Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-architecture-mv/patches/7ae1837372e8db91 # aien-architecture-mv Canonical architecture for the AIEN ecosystem: flows, boundaries, ADRs, and the map from design to implementation repositories. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-architecture-mv#112 (code only) closed derived `7ae1837372e8db91` #112 Imported from GitHub aien-dev/aien-architecture-mv#112 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `fb41e813747963b95d38b5fb1d98bb0727484c63` · Head `c64b3d92713bff67875d2e32fd61847747090e26` ### Apply it ``` git checkout -b patch-7ae1837372e8db91 fb41e813747963b95d38b5fb1d98bb0727484c63 curl -fsSL https://interplane.io/drakestapleton/aien-architecture-mv/patches/7ae1837372e8db91.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-architecture-mv 112 c64b3d92713bff67875d2e32fd61847747090e26 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-architecture-mv","number":112,"url":"https://github.com/aien-dev/aien-architecture-mv/pull/112","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:42Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/bootstrap/formal-oracles/lean/AienKv.lean b/bootstrap/formal-oracles/lean/AienKv.lean new file mode 100644 index 0000000..0f0c696 --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienKv.lean @@ -0,0 +1,3 @@ +import AienKv.Model +import AienKv.Theorems +import AienKv.Corpus diff --git a/bootstrap/formal-oracles/lean/AienKv/Corpus.lean b/bootstrap/formal-oracles/lean/AienKv/Corpus.lean new file mode 100644 index 0000000..cbb3b9c --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienKv/Corpus.lean @@ -0,0 +1,40 @@ +import AienKv.Theorems +namespace AienKv + +/-- TinyLlama as `KvPoolConfig::for_tinyllama(num_blocks, 16, Fp32)`: 22 layers, 4 KV heads, head dim 64. -/ +def tiny (nb : Nat) : Cfg := + { numBlocks := nb, blockSize := 16, numLayers := 22, numKvHeads := 4, headDim := 64, elemBytes := 4 } + +/-! Ties to the PREFILL-E2E-0 receipt (spark-cpu-5512e3c): kv_block_bytes = 720896, physical_kv_bytes = +10092544 = 14 blocks. Which config the receipt run used is read from transformer_backend.rs (Fp32) and +lib.rs (block_size 16); the receipt itself does not record dtype or block size. -/ +theorem pos_tinyllama_block_bytes : (tiny 1).block = 720896 := by decide +theorem pos_receipt_physical_bytes : 14 * (tiny 1).block = 10092544 := by decide +theorem pos_strides : (tiny 1).head = 256 ∧ (tiny 1).token = 1024 ∧ (tiny 1).plane = 16384 ∧ + (tiny 1).layer = 32768 := by decide + +/-- last element of the last block -/ +theorem pos_last_element_in_pool : + InRange ((tiny 256).off 255 21 1 15 3 63) 4 (tiny 256).total := by decide +theorem pos_last_element_exact : + (tiny 256).off 255 21 1 15 3 63 + 4 = (tiny 256).total := by decide +theorem pos_first_element : (tiny 256).off 0 0 0 0 0 0 = 0 := by decide +theorem pos_v_plane_start : (tiny 256).off 0 0 1 0 0 0 = 16384 := by decide +theorem pos_next_block_start : (tiny 256).off 1 0 0 0 0 0 = 720896 := by decide + +/-- an index just past each limit is NOT inside (the bounds theorem needs validity) -/ +theorem neg_block_past_end : ¬ InRange ((tiny 256).off 256 0 0 0 0 0) 4 (tiny 256).total := by decide +theorem neg_token_overruns_into_next_plane : + (tiny 256).off 0 0 0 16 0 0 = (tiny 256).off 0 0 1 0 0 0 := by decide + +/-- V flag 2 (invalid) aliases the next layer: why the `v < 2` validity matters -/ +theorem neg_v_flag_2_aliases_next_layer : + (tiny 256).off 0 0 2 0 0 0 = (tiny 256).off 0 1 0 0 0 0 := by decide + +/-- concrete wrap: block 720896 B times 2^45 blocks = 25364273101350633472 B >= 2^64; the machine value wraps to +6917529027641081856, as reproduced by `KvPoolConfig{num_blocks: 1<<45,..}.layout()` in a release build. -/ +theorem wrap_witness_real : (tiny (2 ^ 45)).total = 25364273101350633472 := by decide +theorem wrap_witness_machine : wrapTotal (tiny (2 ^ 45)) = 6917529027641081856 := by decide +theorem wrap_witness_over : two64 ≤ (tiny (2 ^ 45)).total := by decide + +end AienKv diff --git a/bootstrap/formal-oracles/lean/AienKv/Model.lean b/bootstrap/formal-oracles/lean/AienKv/Model.lean new file mode 100644 index 0000000..fe43306 --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienKv/Model.lean @@ -0,0 +1,59 @@ +/-! +# Abstract model of the pooled KV tensor layout (DEVELOPMENT_ORACLE) + +Source modelled: aien-dev/sovereign-core `crates/aien-kv-cache/src/lib.rs` at dd1fe32, +`KvLayout::from_config` (stride arithmetic), `element_offset`, `token_plane_offset`, +`block_offset`, and `UnifiedKvTensorPool::{new, block_region}`. + +Invariant: AIEN.INV.KV.LAYOUT_BOUNDS.V1 (formal/invariants/kv-layout-bounds-v1.toml). + +Abstractions (each is an ASSUMPTION, not a proof): +* Arithmetic is on unbounded naturals. The Rust code uses `usize` with NO checked arithmetic. + The theorems in `Theorems.lean` (section "64-bit") state exactly when the natural + result equals the machine result: every product stays below 2^64, equivalently `total < 2^64` + when `numBlocks ≥ 1`. A concrete wrap witness is in `Corpus.lean`, and was reproduced in a release + build of the real crate (see DISCREPANCIES.md). +* Bytes are a half-open range `[start, start + len)`. "Within allocation" means the range lies in + `[0, total)`. +* `elemBytes` is the dtype width in bytes (Fp8 1, Bf16/Fp16 2, Fp32 4). Fp4 is refused by the code + and is not modelled. +* Alignment and the host buffer's own address are not modelled. The pool constructor's check + `buffer.len() >= total_bytes` is modelled as the hypothesis `bufLen ≥ total`. +-/ +namespace AienKv + +structure Cfg where + numBlocks : Nat + blockSize : Nat -- tokens per block + numLayers : Nat + numKvHeads : Nat + headDim : Nat + elemBytes : Nat + +/-- Rust `KvLayout::from_config`, same order of operations. -/ +def Cfg.head (c : Cfg) : Nat := c.headDim * c.elemBytes +def Cfg.token (c : Cfg) : Nat := c.numKvHeads * c.head +def Cfg.plane (c : Cfg) : Nat := c.blockSize * c.token +def Cfg.layer (c : Cfg) : Nat := 2 * c.plane +def Cfg.block (c : Cfg) : Nat := c.numLayers * c.layer +def Cfg.total (c : Cfg) : Nat := c.numBlocks * c.block + +/-- Rust `element_offset` (is_value = 0 for K, 1 for V). -/ +def Cfg.off (c : Cfg) (b l v t h d : Nat) : Nat := + b * c.block + l * c.layer + v * c.plane + t * c.token + h * c.head + d * c.elemBytes + +/-- Rust `token_plane_offset`. -/ +def Cfg.tokOff (c : Cfg) (b l v t : Nat) : Nat := + b * c.block + l * c.layer + v * c.plane + t * c.token + +/-- All indices valid (the Rust asserts, in `element_offset`). -/ +def Cfg.Valid (c : Cfg) (b l v t h d : Nat) : Prop := + b < c.numBlocks ∧ l < c.numLayers ∧ v < 2 ∧ t < c.blockSize ∧ h < c.numKvHeads ∧ d < c.headDim + +/-- A byte range `[s, s+n)` lies inside `[0, total)`. -/ +abbrev InRange (s n total : Nat) : Prop := s + n ≤ total + +/-- Two byte ranges do not overlap. -/ +abbrev Disjoint (s1 n1 s2 n2 : Nat) : Prop := s1 + n1 ≤ s2 ∨ s2 + n2 ≤ s1 + +end AienKv diff --git a/bootstrap/formal-oracles/lean/AienKv/Theorems.lean b/bootstrap/formal-oracles/lean/AienKv/Theorems.lean new file mode 100644 index 0000000..f1ff675 --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienKv/Theorems.lean @@ -0,0 +1,148 @@ +import AienKv.Model +namespace AienKv + +/-! Rules enforced by the code (AIEN.INV.KV.LAYOUT_BOUNDS.V1). Every theorem is for every config. -/ + +/-- scaling a bound: `i < n` gives `i*s + s ≤ n*s` -/ +theorem succ_mul_le {i n s : Nat} (h : i < n) : i * s + s ≤ n * s := by + have := Nat.mul_le_mul_right s (show i + 1 ≤ n from h) + rw [Nat.succ_mul] at this; exact this + +/-! ### Nested bounds, innermost first -/ + +theorem elem_in_head (c : Cfg) {d : Nat} (h : d < c.headDim) : d * c.elemBytes + c.elemBytes ≤ c.head := + succ_mul_le h + +theorem head_in_token (c : Cfg) {h : Nat} (hh : h < c.numKvHeads) : h * c.head + c.head ≤ c.token := + succ_mul_le hh + +theorem token_in_plane (c : Cfg) {t : Nat} (ht : t < c.blockSize) : t * c.token + c.token ≤ c.plane := + succ_mul_le ht + +theorem plane_in_layer (c : Cfg) {v : Nat} (hv : v < 2) : v * c.plane + c.plane ≤ c.layer := by + have := succ_mul_le (s := c.plane) hv + unfold Cfg.layer; exact this + +theorem layer_in_block (c : Cfg) {l : Nat} (hl : l < c.numLayers) : l * c.layer + c.layer ≤ c.block := + succ_mul_le hl + +theorem block_in_total (c : Cfg) {b : Nat} (hb : b < c.numBlocks) : b * c.block + c.block ≤ c.total := + succ_mul_le hb + +/-- THE BOUNDS THEOREM. A valid (block, layer, K/V, token, head, dim) names an element whose bytes +`[off, off + elemBytes)` lie inside the allocation `[0, total)`. -/ +theorem element_in_allocation (c : Cfg) {b l v t h d : Nat} (hv : c.Valid b l v t h d) : + InRange (c.off b l v t h d) c.elemBytes c.total := by + obtain ⟨hb, hl, hv2, ht, hh, hd⟩ := hv + have e1 := elem_in_head c hd + have e2 := head_in_token c hh + have e3 := token_in_plane c ht + have e4 := plane_in_layer c hv2 + have e5 := layer_in_block c hl + have e6 := block_in_total c hb + unfold InRange Cfg.off + omega + +/-- the token-plane address used by `write_token_kv` / `read_token_kv` is also inside, with room for a full +`numKvHeads * headDim` row -/ +theorem token_row_in_allocation (c : Cfg) {b l v t : Nat} (hb : b < c.numBlocks) (hl : l < c.numLayers) + (hv : v < 2) (ht : t < c.blockSize) : InRange (c.tokOff b l v t) c.token c.total := by + have e3 := token_in_plane c ht + have e4 := plane_in_layer c hv + have e5 := layer_in_block c hl + have e6 := block_in_total c hb + unfold InRange Cfg.tokOff + omega + +/-- `block_region`: block b occupies `[b*block, b*block + block)` inside the allocation -/ +theorem block_region_in_allocation (c : Cfg) {b : Nat} (hb : b < c.numBlocks) : + InRange (b * c.block) c.block c.total := block_in_total c hb + +/-! ### Disjointness -/ + +/-- distinct blocks have disjoint regions -/ +theorem block_regions_disjoint (c : Cfg) {b1 b2 : Nat} (h : b1 ≠ b2) : + Disjoint (b1 * c.block) c.block (b2 * c.block) c.block := by + unfold Disjoint + rcases Nat.lt_or_gt_of_ne h with h | h + · left; exact succ_mul_le h + · right; exact succ_mul_le h + +/-- distinct layers of the same block have disjoint, in-block regions -/ +theorem layer_regions_disjoint (c : Cfg) {l1 l2 : Nat} (h : l1 ≠ l2) : + Disjoint (l1 * c.layer) c.layer (l2 * c.layer) c.layer := by + unfold Disjoint + rcases Nat.lt_or_gt_of_ne h with h | h + · left; exact succ_mul_le h + · right; exact succ_mul_le h + +/-- every layer region lies inside its block -/ +theorem layer_region_in_block (c : Cfg) {l : Nat} (hl : l < c.numLayers) : + InRange (l * c.layer) c.layer c.block := layer_in_block c hl + +/-- K and V planes of one layer are disjoint (K ends exactly where V starts) -/ +theorem k_v_planes_disjoint (c : Cfg) (l : Nat) : + Disjoint (l * c.layer + 0 * c.plane) c.plane (l * c.layer + 1 * c.plane) c.plane := by + unfold Disjoint; left; omega + +/-- distinct tokens of one plane have disjoint rows -/ +theorem token_rows_disjoint (c : Cfg) {t1 t2 : Nat} (h : t1 ≠ t2) : + Disjoint (t1 * c.token) c.token (t2 * c.token) c.token := by + unfold Disjoint + rcases Nat.lt_or_gt_of_ne h with h | h + · left; exact succ_mul_le h + · right; exact succ_mul_le h + +/-- the stride chain itself is consistent: block = layers * 2 * planes and plane = tokens * heads * dim * bytes -/ +theorem block_closed_form (c : Cfg) : + c.block = 2 * c.numLayers * c.blockSize * c.numKvHeads * c.headDim * c.elemBytes := by + unfold Cfg.block Cfg.layer Cfg.plane Cfg.token Cfg.head + simp only [Nat.mul_assoc, Nat.mul_left_comm, Nat.mul_comm] + +/-- `bytes_per_block` (2 * layers * block_size * heads * dim * element size) is the same number -/ +theorem block_eq_bytes_per_block (c : Cfg) : + c.block = 2 * c.numLayers * c.blockSize * c.numKvHeads * c.headDim * c.elemBytes := block_closed_form c + +/-! ### Pool constructor: `buffer.len() >= total_bytes` -/ + +/-- if the host buffer is at least `total` bytes (the check in `UnifiedKvTensorPool::new`), every valid +element's bytes lie inside the host buffer -/ +theorem element_in_buffer (c : Cfg) {b l v t h d bufLen : Nat} (hv : c.Valid b l v t h d) + (hbuf : c.total ≤ bufLen) : InRange (c.off b l v t h d) c.elemBytes bufLen := by + have := element_in_allocation c hv + unfold InRange at *; omega + +/-! ### 64-bit (machine) arithmetic: when the natural-number result is the machine result -/ + +def two64 : Nat := 18446744073709551616 + +/-- all six dimensions are nonzero (a zero dimension has no valid element at all) -/ +def Cfg.Pos (c : Cfg) : Prop := + 1 ≤ c.numBlocks ∧ 1 ≤ c.blockSize ∧ 1 ≤ c.numLayers ∧ 1 ≤ c.numKvHeads ∧ 1 ≤ c.headDim ∧ 1 ≤ c.elemBytes + +/-- With nonzero dimensions the strides grow along the chain head <= token <= plane <= layer <= block <= total. +So if `total < 2^64`, no stride product wraps and the unbounded model is exact for the Rust `usize` code. -/ +theorem machine_exact_when_total_fits (c : Cfg) (hp : c.Pos) (ht : c.total < two64) : + c.head < two64 ∧ c.token < two64 ∧ c.plane < two64 ∧ c.layer < two64 ∧ c.block < two64 := by + obtain ⟨hnb, hbs, hnl, hnh, _, _⟩ := hp + have h1 : c.block ≤ c.total := Nat.le_mul_of_pos_left _ hnb + have h2 : c.layer ≤ c.block := Nat.le_mul_of_pos_left _ hnl + have h3 : c.plane ≤ c.layer := by unfold Cfg.layer; omega + have h4 : c.token ≤ c.plane := Nat.le_mul_of_pos_left _ hbs + have h5 : c.head ≤ c.token := Nat.le_mul_of_pos_left _ hnh + omega + +/-- and every valid offset (and each summand of it) is below total, hence below 2^64 -/ +theorem offset_fits_u64 (c : Cfg) {b l v t h d : Nat} (hv : c.Valid b l v t h d) (ht : c.total < two64) : + c.off b l v t h d < two64 := by + have := element_in_allocation c hv + unfold InRange at this; omega + +/-- THE LIMITATION, stated: the unbounded model and the Rust code disagree as soon as `total ≥ 2^64`. +`from_config` does not refuse such a config (no checked arithmetic). -/ +def wrapTotal (c : Cfg) : Nat := c.total % two64 + +theorem wrap_total_smaller (c : Cfg) (h : two64 ≤ c.total) : wrapTotal c < c.total := by + unfold wrapTotal two64 at *; omega + +end AienKv diff --git a/bootstrap/formal-oracles/lean/AienSeq.lean b/bootstrap/formal-oracles/lean/AienSeq.lean new file mode 100644 index 0000000..bde262a --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienSeq.lean @@ -0,0 +1,3 @@ +import AienSeq.Model +import AienSeq.Theorems +import AienSeq.Corpus diff --git a/bootstrap/formal-oracles/lean/AienSeq/Corpus.lean b/bootstrap/formal-oracles/lean/AienSeq/Corpus.lean new file mode 100644 index 0000000..3b1ce13 --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienSeq/Corpus.lean @@ -0,0 +1,49 @@ +import AienSeq.Theorems +namespace AienSeq + +/-! Concrete traces. The theorems in `Theorems.lean` hold for every arena; the corpus shows the rules +fire on concrete records, and fixes the Rust numbers (generation starts at 1, wrap skips 0). -/ + +/-- the id handed out by alloc, if any -/ +def allocId (a : Arena) : Option Id := (a.alloc).map (·.2) +/-- the arena after alloc (unchanged when refused) -/ +def allocArena (a : Arena) : Arena := match a.alloc with | some (a', _) => a' | none => a + +def a2 : Arena := Arena.init 2 + +/-! Positive -/ +theorem pos_first_id : allocId a2 = some ⟨0, 1⟩ := by decide +theorem pos_second_id : allocId (allocArena a2) = some ⟨1, 1⟩ := by decide +theorem pos_live_after_alloc : (allocArena a2).live ⟨0, 1⟩ = true := by decide +theorem pos_free_then_reuse_new_gen : + allocId ((allocArena a2).release ⟨0, 1⟩).1 = some ⟨0, 2⟩ := by decide +theorem pos_free_live_true : ((allocArena a2).release ⟨0, 1⟩).2 = true := by decide +theorem pos_fork_live_parent : ((allocArena a2).fork ⟨0, 1⟩).isSome = true := by decide +theorem pos_wrap_skips_zero : nextGen genMax = 1 := by decide +theorem pos_gen_increments : nextGen 1 = 2 := by decide + +/-! Negative: each is refused / not live. -/ +theorem neg_never_allocated : a2.live ⟨0, 1⟩ = false := by decide +theorem neg_stale_after_free : + (((allocArena a2).release ⟨0, 1⟩).1).live ⟨0, 1⟩ = false := by decide +theorem neg_stale_free_refused : + ((((allocArena a2).release ⟨0, 1⟩).1).release ⟨0, 1⟩).2 = false := by decide +theorem neg_wrong_generation : (allocArena a2).live ⟨0, 2⟩ = false := by decide +theorem neg_generation_zero : (allocArena a2).live ⟨0, 0⟩ = false := by decide +theorem neg_slot_out_of_range : (allocArena a2).live ⟨5, 1⟩ = false := by decide +theorem neg_fork_stale_parent : + ((((allocArena a2).release ⟨0, 1⟩).1).fork ⟨0, 1⟩).isSome = false := by decide +theorem neg_capacity_exhausted : + allocId (allocArena (allocArena a2)) = none := by decide +theorem neg_old_id_vs_new_slot_owner : + ((allocArena ((allocArena a2).release ⟨0, 1⟩).1).live ⟨0, 1⟩) = false := by decide + +/-- an arena whose slot 0 generation sits at u32::MAX: free then reuse yields generation 1, not 0 -/ +def aMax : Arena := { Arena.init 1 with gen := fun _ => genMax, occ := fun _ => true, free := [], active := 1 } +theorem pos_wrap_in_arena : allocId (aMax.release ⟨0, genMax⟩).1 = some ⟨0, 1⟩ := by decide +theorem neg_wrapped_id_differs : (aMax.release ⟨0, genMax⟩).1.live ⟨0, genMax⟩ = false := by decide + +/-- Real Rust numbers: 2^32 - 1 = 4294967295 generations per slot before the wrap limitation applies -/ +theorem generation_period : genMax = 4294967295 := rfl + +end AienSeq diff --git a/bootstrap/formal-oracles/lean/AienSeq/Model.lean b/bootstrap/formal-oracles/lean/AienSeq/Model.lean new file mode 100644 index 0000000..854d3bd --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienSeq/Model.lean @@ -0,0 +1,89 @@ +/-! +# Abstract model of the Rust generational sequence arena (DEVELOPMENT_ORACLE) + +Source modelled: aien-dev/sovereign-core `crates/aien-runtime/src/sequence.rs` at dd1fe32 +(`SequenceArena::{new, allocate, fork, get, free, active_count}`, `SequenceId`). +The scheduler arena `crates/aien-scheduler/src/sequence.rs` differs (it retires a slot instead of +wrapping); its free rule is modelled separately as `retireNext` in this file. + +Invariant: AIEN.INV.SEQUENCE.STALE_ID.V1 (formal/invariants/sequence-stale-id-v1.toml). + +Abstractions (each is an ASSUMPTION, not a proof): +* The arena is a total function from slot number to a slot, plus a capacity `cap`; slots at or + beyond `cap` are never consulted (Rust `slots.get(i)` returns None there). +* Record contents (priority, world id, ...) are not modelled. Only presence (`occ`) matters here. +* `u32` generation arithmetic IS modelled: generations live in [1, 2^32 - 1] (`genMax`). +* `free_slots` is a stack (head = next pop). Rust pops the back of a reversed Vec, the same order. +* Single scheduler thread (the arena has no locks, by its own doc comment). No concurrency model. +-/ +namespace AienSeq + +/-- 2^32 (the generation field is a `u32`). -/ +def two32 : Nat := 4294967296 +/-- Largest generation, u32::MAX. -/ +def genMax : Nat := 4294967295 + +structure Id where + slot : Nat + gen : Nat + deriving DecidableEq, Repr + +/-- Rust: `slot.generation.wrapping_add(1).max(1)` on a `u32`. -/ +def nextGen (g : Nat) : Nat := max ((g + 1) % two32) 1 + +structure Arena where + gen : Nat → Nat -- generation counter per slot + occ : Nat → Bool -- slot holds a record + free : List Nat -- free_slots, head is popped next + active : Nat -- active_count + cap : Nat -- capacity + +def upd {α : Type} (f : Nat → α) (i : Nat) (v : α) : Nat → α := + fun j => if j = i then v else f j + +/-- Rust `SequenceArena::new(capacity)`: every generation 1, nothing occupied, all slots free. -/ +def Arena.init (cap : Nat) : Arena := + { gen := fun _ => 1, occ := fun _ => false, free := List.range cap, active := 0, cap := cap } + +/-- Rust `get`: the record behind an id, if the slot exists, the generation matches and a record is present. -/ +def Arena.live (a : Arena) (id : Id) : Bool := + decide (id.slot < a.cap) && decide (a.gen id.slot = id.gen) && a.occ id.slot + +/-- Rust `allocate`: pop a free slot, hand out (slot, current generation). `none` = capacity exhausted. -/ +def Arena.alloc (a : Arena) : Option (Arena × Id) := + match a.free with + | [] => none + | s :: rest => + some ({ a with occ := upd a.occ s true, free := rest, active := a.active + 1 }, + { slot := s, gen := a.gen s }) + +/-- Rust `fork`: refused when the parent id does not resolve, else allocate. -/ +def Arena.fork (a : Arena) (parent : Id) : Option (Arena × Id) := + if a.live parent then a.alloc else none + +/-- Rust `free`: succeeds only for a live id; bumps the generation, returns the slot to the free stack. -/ +def Arena.release (a : Arena) (id : Id) : Arena × Bool := + if a.live id then + ({ a with occ := upd a.occ id.slot false, gen := upd a.gen id.slot (nextGen (a.gen id.slot)), + free := id.slot :: a.free, active := a.active - 1 }, true) + else (a, false) + +/-! ### Scheduler arena variant: retire the slot at u32::MAX instead of wrapping -/ + +/-- `aien-scheduler` `free_sequence`: at `u32::MAX` the slot is retired (never reused); else generation + 1. -/ +def retireNext (g : Nat) : Option Nat := if g = genMax then none else some (g + 1) + +/-- Number of occupied slots below `n`. -/ +def occCount (occ : Nat → Bool) : Nat → Nat + | 0 => 0 + | n + 1 => occCount occ n + (if occ n then 1 else 0) + +/-- Well-formedness: what `new` establishes and every operation must keep. -/ +structure Arena.WF (a : Arena) : Prop where + freeRange : ∀ i ∈ a.free, i < a.cap + freeNodup : a.free.Nodup + freeIff : ∀ i, i < a.cap → (i ∈ a.free ↔ a.occ i = false) + genRange : ∀ i, 1 ≤ a.gen i ∧ a.gen i < two32 + activeEq : a.active = occCount a.occ a.cap + +end AienSeq diff --git a/bootstrap/formal-oracles/lean/AienSeq/Theorems.lean b/bootstrap/formal-oracles/lean/AienSeq/Theorems.lean new file mode 100644 index 0000000..c550b35 --- /dev/null +++ b/bootstrap/formal-oracles/lean/AienSeq/Theorems.lean @@ -0,0 +1,316 @@ +import AienSeq.Model +namespace AienSeq + +/-! Rules enforced by the code (AIEN.INV.SEQUENCE.STALE_ID.V1). -/ + +/-! ### Generation arithmetic -/ + +theorem nextGen_range {g : Nat} (_h1 : 1 ≤ g) (_h2 : g < two32) : 1 ≤ nextGen g ∧ nextGen g < two32 := by + unfold nextGen two32 at *; omega + +/-- one free always changes the generation (for every valid generation) -/ +theorem nextGen_ne {g : Nat} (_h1 : 1 ≤ g) (_h2 : g < two32) : nextGen g ≠ g := by + unfold nextGen two32 at *; omega + +/-- generation 0 is never produced -/ +theorem nextGen_pos (g : Nat) : 1 ≤ nextGen g := by + unfold nextGen; omega + +/-- iterate `nextGen` k times -/ +def iterGen : Nat → Nat → Nat + | 0, g => g + | k + 1, g => iterGen k (nextGen g) + +/-- Closed form: generations cycle through 1 .. 2^32 - 1, so the period is genMax = 2^32 - 1. -/ +theorem iterGen_closed (k : Nat) : ∀ g, 1 ≤ g → g < two32 → iterGen k g = (g - 1 + k) % genMax + 1 := by + induction k with + | zero => intro g h1 h2; unfold iterGen genMax two32 at *; omega + | succ k ih => + intro g h1 h2 + have hr := nextGen_range h1 h2 + show iterGen k (nextGen g) = _ + rw [ih _ hr.1 hr.2] + unfold nextGen genMax two32 at * + omega + +/-- Slot reuse changes identity: while fewer than 2^32 - 1 frees have hit one slot, its generation +differs from the one an old id carries. -/ +theorem no_aba_before_wrap {g k : Nat} (h1 : 1 ≤ g) (h2 : g < two32) (hk0 : 0 < k) (hk : k < genMax) : + iterGen k g ≠ g := by + rw [iterGen_closed k g h1 h2]; unfold genMax two32 at *; omega + +/-- THE GENERATION-WRAP LIMITATION, stated as a theorem: after exactly 2^32 - 1 frees of the same +slot the generation is back where it started, so a stale id from before the cycle resolves again. -/ +theorem aba_after_exactly_one_cycle {g : Nat} (h1 : 1 ≤ g) (h2 : g < two32) : + iterGen genMax g = g := by + rw [iterGen_closed genMax g h1 h2]; unfold genMax two32 at *; omega + +/-- ...and the wrap skips generation 0 (u32::MAX goes to 1, not 0). -/ +theorem wrap_skips_zero : nextGen genMax = 1 := by decide + +/-! ### Scheduler variant: retire at u32::MAX -/ + +/-- a non-retiring step strictly increases the generation, so ids are never reissued -/ +theorem retire_strictly_increases {g g' : Nat} (h : retireNext g = some g') : g < g' := by + unfold retireNext at h; split at h <;> simp_all <;> omega + +/-- at u32::MAX the slot is retired instead of wrapping, so no id of that slot is ever reissued -/ +theorem retire_at_max : retireNext genMax = none := by decide + +/-! ### Counting -/ + +theorem occCount_le (occ : Nat → Bool) : ∀ n, occCount occ n ≤ n := by + intro n; induction n with + | zero => simp [occCount] + | succ n ih => simp only [occCount]; split <;> omega + +theorem occCount_all (occ : Nat → Bool) : ∀ n, (∀ i, i < n → occ i = true) → occCount occ n = n := by + intro n; induction n with + | zero => intro _; rfl + | succ n ih => + intro h + simp only [occCount, h n (by omega), ih (fun i hi => h i (by omega))]; rfl + +theorem occCount_congr {f g : Nat → Bool} : ∀ n, (∀ j, j < n → f j = g j) → occCount f n = occCount g n := by + intro n; induction n with + | zero => intro _; rfl + | succ n ih => + intro h + simp only [occCount, h n (by omega), ih (fun j hj => h j (by omega))] + +theorem occCount_set_true (occ : Nat → Bool) (i : Nat) : + ∀ n, i < n → occ i = false → occCount (upd occ i true) n = occCount occ n + 1 := by + intro n; induction n with + | zero => intro h; omega + | succ n ih => + intro hi ho + by_cases hn : i = n + · subst hn + have hc : occCount (upd occ i true) i = occCount occ i := + occCount_congr i (fun j hj => by simp [upd]; intro h; omega) + simp [occCount, hc, upd, ho] + · have := ih (by omega) ho + simp [occCount, this, upd, Ne.symm hn]; split <;> omega + +theorem occCount_set_false (occ : Nat → Bool) (i : Nat) : + ∀ n, i < n → occ i = true → occCount occ n = occCount (upd occ i false) n + 1 := by + intro n; induction n with + | zero => intro h; omega + | succ n ih => + intro hi ho + by_cases hn : i = n + · subst hn + have hc : occCount (upd occ i false) i = occCount occ i := + occCount_congr i (fun j hj => by simp [upd]; intro h; omega) + simp [occCount, hc, upd, ho] + · have := ih (by omega) ho + simp [occCount, this, upd, Ne.symm hn]; split <;> omega + +/-! ### Well-formedness -/ + +theorem occCount_none (n : Nat) : occCount (fun _ => false) n = 0 := by + induction n with + | zero => rfl + | succ n ih => simp [occCount, ih] + +theorem init_wf (cap : Nat) : (Arena.init cap).WF where + freeRange := by intro i hi; simpa [Arena.init] using hi + freeNodup := by simpa [Arena.init] using List.nodup_range + freeIff := by intro i hi; simp [Arena.init]; exact hi + genRange := by intro i; simp [Arena.init, two32] + activeEq := by simp [Arena.init, occCount_none] + +/-- allocation preserves well-formedness -/ +theorem alloc_wf {a a' : Arena} {id : Id} (hw : a.WF) (h : a.alloc = some (a', id)) : a'.WF := by + unfold Arena.alloc at h + cases hf : a.free with + | nil => simp [hf] at h + | cons s rest => + simp only [hf, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have hs : s < a.cap := hw.freeRange s (by simp [hf]) + have hso : a.occ s = false := (hw.freeIff s hs).1 (by simp [hf]) + have hnd := hw.freeNodup; rw [hf] at hnd + rw [List.nodup_cons] at hnd + refine ⟨?_, hnd.2, ?_, hw.genRange, ?_⟩ + · intro i hi; exact hw.freeRange i (by simp [hf, hi]) + · intro i hi + by_cases hi' : i = s + · subst hi'; simp [upd, hnd.1] + · have := hw.freeIff i hi + simp only [hf, List.mem_cons, upd, hi', ite_false] at this ⊢ + simp [hi'] at this ⊢; exact this + · simp only + rw [occCount_set_true a.occ s a.cap hs hso, hw.activeEq] + +/-- release preserves well-formedness -/ +theorem release_wf {a a' : Arena} {id : Id} {b : Bool} (hw : a.WF) (h : a.release id = (a', b)) : a'.WF := by + unfold Arena.release at h + by_cases hl : a.live id = true + · simp only [hl, ite_true, Prod.mk.injEq] at h + obtain ⟨rfl, _⟩ := h + simp only [Arena.live, Bool.and_eq_true, decide_eq_true_eq] at hl + obtain ⟨⟨hs, hg⟩, ho⟩ := hl + have hnf : id.slot ∉ a.free := fun hm => by have := (hw.freeIff _ hs).1 hm; simp_all + refine ⟨?_, ?_, ?_, ?_, ?_⟩ + · intro i hi + simp only [List.mem_cons] at hi + rcases hi with rfl | hi + · exact hs + · exact hw.freeRange i hi + · exact List.nodup_cons.2 ⟨hnf, hw.freeNodup⟩ + · intro i hi + by_cases hi' : i = id.slot + · subst hi'; simp [upd] + · have := hw.freeIff i hi + simp [upd, hi', this] + · intro i + by_cases hi' : i = id.slot + · subst hi'; simp only [upd, ite_true] + exact nextGen_range (hw.genRange _).1 (hw.genRange _).2 + · simp only [upd, hi', ite_false]; exact hw.genRange i + · have := occCount_set_false a.occ id.slot a.cap hs ho + simp only + rw [hw.activeEq]; omega + · simp only [hl] at h + simp at h; obtain ⟨rfl, _⟩ := h; exact hw + +theorem fork_wf {a a' : Arena} {p id : Id} (hw : a.WF) (h : a.fork p = some (a', id)) : a'.WF := by + unfold Arena.fork at h + split at h + · exact alloc_wf hw h + · simp at h + +/-! ### The invariant theorems -/ + +/-- a live id has exactly the slot's current generation (generation mismatch never resolves) -/ +theorem live_gen_match {a : Arena} {id : Id} (h : a.live id = true) : + id.slot < a.cap ∧ a.gen id.slot = id.gen ∧ a.occ id.slot = true := by + simpa [Arena.live, Bool.and_eq_true, decide_eq_true_eq, and_assoc] using h + +theorem generation_mismatch_not_live {a : Arena} {id : Id} (h : a.gen id.slot ≠ id.gen) : + a.live id = false := by + unfold Arena.live; simp [h] + +/-- free invalidates the old id: it no longer resolves, and the slot carries a different generation -/ +theorem free_invalidates {a a' : Arena} {id : Id} (hw : a.WF) (h : a.release id = (a', true)) : + a'.live id = false ∧ a'.gen id.slot ≠ id.gen := by + unfold Arena.release at h + by_cases hl : a.live id = true + · simp only [hl, ite_true, Prod.mk.injEq] at h + obtain ⟨rfl, _⟩ := h + obtain ⟨hs, hg, ho⟩ := live_gen_match hl + have hne : nextGen (a.gen id.slot) ≠ id.gen := by + rw [← hg]; exact nextGen_ne (hw.genRange _).1 (hw.genRange _).2 + refine ⟨?_, ?_⟩ + · apply generation_mismatch_not_live; simpa [upd] using hne + · simpa [upd] using hne + · simp only [hl] at h; simp at h + +/-- free of a non-live id (stale, wrong generation, out of range, already freed) changes nothing -/ +theorem free_stale_noop {a : Arena} {id : Id} (h : a.live id = false) : + a.release id = (a, false) := by + unfold Arena.release; simp [h] + +/-- successful free is only possible for a live id -/ +theorem free_true_iff_live {a a' : Arena} {id : Id} (h : a.release id = (a', true)) : a.live id = true := by + unfold Arena.release at h + by_cases hl : a.live id = true + · exact hl + · simp only [hl] at h; simp at h + +/-- allocation hands out a live id at the slot's current generation -/ +theorem alloc_live {a a' : Arena} {id : Id} (hw : a.WF) (h : a.alloc = some (a', id)) : a'.live id = true := by + unfold Arena.alloc at h + cases hf : a.free with + | nil => simp [hf] at h + | cons s rest => + simp only [hf, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + have hs : s < a.cap := hw.freeRange s (by simp [hf]) + simp [Arena.live, upd, hs] + +/-- active count never exceeds capacity -/ +theorem active_le_cap {a : Arena} (hw : a.WF) : a.active ≤ a.cap := by + rw [hw.activeEq]; exact occCount_le _ _ + +/-- capacity cannot be exceeded: allocation is refused exactly when active = cap -/ +theorem alloc_none_iff_full {a : Arena} (hw : a.WF) : a.alloc = none ↔ a.active = a.cap := by + unfold Arena.alloc + cases hf : a.free with + | nil => + simp only [true_iff] + rw [hw.activeEq] + apply occCount_all + intro i hi + have := hw.freeIff i hi + simp only [hf, List.not_mem_nil, false_iff] at this + simpa using this + | cons s rest => + simp only [reduceCtorEq, false_iff] + have hs : s < a.cap := hw.freeRange s (by simp [hf]) + have hso : a.occ s = false := (hw.freeIff s hs).1 (by simp [hf]) + intro hfull + rw [hw.activeEq] at hfull + have := occCount_set_true a.occ s a.cap hs hso + have h2 := occCount_le (upd a.occ s true) a.cap + omega + +/-- successful allocation raises the active count by exactly one and stays within capacity -/ +theorem alloc_active {a a' : Arena} {id : Id} (hw : a.WF) (h : a.alloc = some (a', id)) : + a'.active = a.active + 1 ∧ a'.active ≤ a'.cap ∧ a'.cap = a.cap := by + have hw' := alloc_wf hw h + unfold Arena.alloc at h + cases hf : a.free with + | nil => simp [hf] at h + | cons s rest => + simp only [hf, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact ⟨rfl, active_le_cap hw', rfl⟩ + +/-- successful free lowers the active count by exactly one -/ +theorem release_active {a a' : Arena} {id : Id} (hw : a.WF) (h : a.release id = (a', true)) : + a'.active + 1 = a.active := by + have hl := free_true_iff_live h + obtain ⟨hs, _, ho⟩ := live_gen_match hl + unfold Arena.release at h + simp only [hl, ite_true, Prod.mk.injEq] at h + obtain ⟨rfl, _⟩ := h + have := occCount_set_false a.occ id.slot a.cap hs ho + simp only + rw [hw.activeEq]; omega + +/-- fork from a stale or unknown parent is refused -/ +theorem fork_stale_refused {a : Arena} {p : Id} (h : a.live p = false) : a.fork p = none := by + unfold Arena.fork; simp [h] + +/-- fork success implies the parent id was live -/ +theorem fork_parent_live {a a' : Arena} {p id : Id} (h : a.fork p = some (a', id)) : a.live p = true := by + unfold Arena.fork at h + by_cases hl : a.live p = true + · exact hl + · simp only [hl] at h; simp at h + +/-- allocation reads the slot's current generation and leaves every generation unchanged -/ +theorem alloc_gen {a a' : Arena} {id : Id} (h : a.alloc = some (a', id)) : + id.gen = a.gen id.slot ∧ a'.gen = a.gen := by + unfold Arena.alloc at h + cases hf : a.free with + | nil => simp [hf] at h + | cons s rest => + simp only [hf, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact ⟨rfl, rfl⟩ + +/-- slot reuse changes identity: free an id, allocate again, and if the same slot comes back the id +differs. One-step case; it needs no wrap assumption. -/ +theorem reuse_changes_identity {a a1 a2 : Arena} {id id2 : Id} (hw : a.WF) + (hf : a.release id = (a1, true)) (ha : a1.alloc = some (a2, id2)) (_hslot : id2.slot = id.slot) : + id2 ≠ id := by + intro heq + have hi := (free_invalidates hw hf).2 + have hg := (alloc_gen ha).1 + apply hi + rw [← heq]; exact hg.symm + +end AienSeq diff --git a/bootstrap/formal-oracles/lean/DISCREPANCIES.md b/bootstrap/formal-oracles/lean/DISCREPANCIES.md index ad9f41c..b4f87cf 100644 --- a/bootstrap/formal-oracles/lean/DISCREPANCIES.md +++ b/bootstrap/formal-oracles/lean/DISCREPANCIES.md @@ -35,3 +35,26 @@ As the manifest notes: `Rejected` also forces exit status 0, zero syscalls, zero ## Abstractions (assumptions, not proofs) SHA-256 nonce derivation is an arbitrary function `nf` (every theorem holds for all `nf`). Ed25519 is not modelled (`verify` is out of scope; `validate` does not check signatures). Digests are naturals, zero meaning all zero. Little-endian byte packing is assumed to be a per-field bijection. Integer width overflow is not modelled. Unknown flag bits are unrepresentable in the model; `decode` checks them on the raw word (`flags < 8`, `rflags < 256`). `exit_status` is an `Int`. Opaque digests that no rule reads are kept as one list. + +# Sequence identity and KV layout (FORMAL-6) + +Observed on aien-dev/sovereign-core main dd1fe32 (PREFILL-E2E C8 merged, #154). Read only. Models: `AienSeq/` (runtime `SequenceArena`) and `AienKv/` (`KvLayout`). + +## Finding: two sequence arenas, different wrap policy + +- `crates/aien-runtime/src/sequence.rs` `free` (lines 197 to 209) sets the generation to `wrapping_add(1).max(1)`. After exactly 2^32 - 1 frees of one slot the generation repeats and a stale id resolves again. Lean: `aba_after_exactly_one_cycle`; below the cycle `no_aba_before_wrap`. +- `crates/aien-scheduler/src/sequence.rs` `free_sequence` (512 to 531) retires the slot at `u32::MAX` and never reuses it. Lean: `retire_strictly_increases`, `retire_at_max`. No ABA window, but capacity shrinks by one slot per exhausted slot. +- Not asserted which policy is intended. The invariant states the wrapping limitation explicitly and does not claim eternal ABA freedom. + +## Finding: KV layout arithmetic is unchecked + +- `KvLayout::from_config` (aien-kv-cache/src/lib.rs 169 to 184) multiplies `usize` values with plain operators and does not refuse overflow or zero dimensions. +- Reproduced with a throwaway example run in a release build of the real crate (scratch worktree, deleted afterwards, nothing committed): `KvPoolConfig { num_blocks: 1<<45, block_size: 16, num_layers: 22, num_kv_heads: 4, head_dim: 64, dtype: Fp32 }.layout()` returns `Ok` with `total_bytes = 6917529027641081856`; the true value is `25364273101350633472`. Lean: `wrap_witness_real`, `wrap_witness_machine`, `wrap_total_smaller`. +- The Lean bounds theorems hold for unbounded arithmetic. `machine_exact_when_total_fits` and `offset_fits_u64` say they transfer to the Rust code exactly when `total < 2^64` with nonzero dimensions. +- No current caller can reach this (block counts are small). Latent. Recorded, not fixed. + +## Not covered (stated so nobody reads more into the proofs) + +- Injectivity of the offset map (distinct valid tuples never share a byte) is not proven. Only the bounds and the disjointness listed in the manifest. +- Scheduler `insert_with_id` (explicit caller generation) is not modelled. +- Block table, copy-on-write and PrefillState are not modelled here. PREFILL gating is the PREFILL-GATE campaign's evidence. diff --git a/bootstrap/formal-oracles/lean/MutantKvBlockClaim.lean b/bootstrap/formal-oracles/lean/MutantKvBlockClaim.lean new file mode 100644 index 0000000..569e10c --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantKvBlockClaim.lean @@ -0,0 +1,10 @@ +import MutantKvModels +namespace AienKv +/-- Real-model theorem `block_regions_disjoint` restated for blockStrideM5. MUST FAIL to check. -/ +theorem mutant_block_regions_disjoint (c : Cfg) {b1 b2 : Nat} (h : b1 ≠ b2) : + Disjoint (b1 * c.blockStrideM5) c.block (b2 * c.blockStrideM5) c.block := by + unfold Disjoint + rcases Nat.lt_or_gt_of_ne h with h | h + · left; exact succ_mul_le h + · right; exact succ_mul_le h +end AienKv diff --git a/bootstrap/formal-oracles/lean/MutantKvModels.lean b/bootstrap/formal-oracles/lean/MutantKvModels.lean new file mode 100644 index 0000000..5fb4eb3 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantKvModels.lean @@ -0,0 +1,32 @@ +import AienKv.Corpus +/-! +# Deliberate mutants of the KV layout (each must break one required rule) + +WRONG on purpose. Each mutant model compiles; the matching claim file must not. +-/ +namespace AienKv + +/-- MUTANT 1 (kv_planes_overlap): layer stride is one plane, so the V plane starts inside the next layer. -/ +def Cfg.layerM1 (c : Cfg) : Nat := c.plane + +/-- MUTANT 2 (total_one_block_short): the allocation is one block too small. -/ +def Cfg.totalM2 (c : Cfg) : Nat := c.numBlocks * c.block - c.block + +/-- MUTANT 3 (token_stride_forgets_element_size): token stride = heads * dim, not heads * dim * bytes. -/ +def Cfg.tokenM3 (c : Cfg) : Nat := c.numKvHeads * c.headDim + +/-- MUTANT 4 (validity_off_by_one): the K/V selector is allowed to be 0, 1 or 2. -/ +def Cfg.ValidM4 (c : Cfg) (b l v t h d : Nat) : Prop := + b < c.numBlocks ∧ l < c.numLayers ∧ v < 3 ∧ t < c.blockSize ∧ h < c.numKvHeads ∧ d < c.headDim + +/-- MUTANT 5 (block_stride_short): consecutive blocks are placed one byte too close. -/ +def Cfg.blockStrideM5 (c : Cfg) : Nat := c.block - 1 + +theorem m1_witness : (tiny 4).plane = (tiny 4).layerM1 ∧ (tiny 4).layerM1 < 2 * (tiny 4).plane := by decide +theorem m2_witness : (tiny 4).totalM2 < (tiny 4).block * 4 := by decide +theorem m3_witness : (tiny 4).tokenM3 < (tiny 4).head * 4 := by decide +theorem m4_witness : (tiny 4).off 0 0 2 0 0 0 + 4 ≤ (tiny 4).total ∧ ¬ (tiny 4).Valid 0 0 2 0 0 0 := by + refine ⟨by decide, ?_⟩; unfold Cfg.Valid; decide +theorem m5_witness : 1 * (tiny 4).blockStrideM5 + (tiny 4).block > 1 * (tiny 4).block := by decide + +end AienKv diff --git a/bootstrap/formal-oracles/lean/MutantKvPlanesClaim.lean b/bootstrap/formal-oracles/lean/MutantKvPlanesClaim.lean new file mode 100644 index 0000000..805e3a3 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantKvPlanesClaim.lean @@ -0,0 +1,7 @@ +import MutantKvModels +namespace AienKv +/-- Real-model theorem `plane_in_layer` restated for layerM1. MUST FAIL to check. -/ +theorem mutant_plane_in_layer (c : Cfg) {v : Nat} (hv : v < 2) : v * c.plane + c.plane ≤ c.layerM1 := by + have := succ_mul_le (s := c.plane) hv + unfold Cfg.layerM1; exact this +end AienKv diff --git a/bootstrap/formal-oracles/lean/MutantKvTokenClaim.lean b/bootstrap/formal-oracles/lean/MutantKvTokenClaim.lean new file mode 100644 index 0000000..9f84b32 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantKvTokenClaim.lean @@ -0,0 +1,7 @@ +import MutantKvModels +namespace AienKv +/-- Real-model theorem `head_in_token` restated for tokenM3. MUST FAIL to check. -/ +theorem mutant_head_in_token (c : Cfg) {h : Nat} (hh : h < c.numKvHeads) : h * c.head + c.head ≤ c.tokenM3 := by + have := succ_mul_le (s := c.head) hh + unfold Cfg.tokenM3; exact this +end AienKv diff --git a/bootstrap/formal-oracles/lean/MutantKvTotalClaim.lean b/bootstrap/formal-oracles/lean/MutantKvTotalClaim.lean new file mode 100644 index 0000000..5b4e0f2 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantKvTotalClaim.lean @@ -0,0 +1,7 @@ +import MutantKvModels +namespace AienKv +/-- Real-model theorem `block_in_total` restated for totalM2. MUST FAIL to check. -/ +theorem mutant_block_in_total (c : Cfg) {b : Nat} (hb : b < c.numBlocks) : b * c.block + c.block ≤ c.totalM2 := by + have := succ_mul_le (s := c.block) hb + unfold Cfg.totalM2; exact this +end AienKv diff --git a/bootstrap/formal-oracles/lean/MutantKvValidClaim.lean b/bootstrap/formal-oracles/lean/MutantKvValidClaim.lean new file mode 100644 index 0000000..b07fae8 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantKvValidClaim.lean @@ -0,0 +1,15 @@ +import MutantKvModels +namespace AienKv +/-- Real-model theorem `element_in_allocation` restated for ValidM4. MUST FAIL to check. -/ +theorem mutant_element_in_allocation (c : Cfg) {b l v t h d : Nat} (hv : c.ValidM4 b l v t h d) : + InRange (c.off b l v t h d) c.elemBytes c.total := by + obtain ⟨hb, hl, hv2, ht, hh, hd⟩ := hv + have e1 := elem_in_head c hd + have e2 := head_in_token c hh + have e3 := token_in_plane c ht + have e4 := plane_in_layer c hv2 + have e5 := layer_in_block c hl + have e6 := block_in_total c hb + unfold InRange Cfg.off + omega +end AienKv diff --git a/bootstrap/formal-oracles/lean/MutantSeqActiveClaim.lean b/bootstrap/formal-oracles/lean/MutantSeqActiveClaim.lean new file mode 100644 index 0000000..da3795f --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantSeqActiveClaim.lean @@ -0,0 +1,15 @@ +import MutantSeqModels +namespace AienSeq +/-- Real-model theorem `release_active` restated for releaseM4. MUST FAIL to check. -/ +theorem mutant_release_active {a a' : Arena} {id : Id} (hw : a.WF) (h : a.releaseM4 id = (a', true)) : + a'.active + 1 = a.active := by + unfold Arena.releaseM4 at h + by_cases hl : a.live id = true + · simp only [hl, ite_true, Prod.mk.injEq] at h + obtain ⟨rfl, _⟩ := h + obtain ⟨hs, hg, ho⟩ := live_gen_match hl + have := occCount_set_false a.occ id.slot a.cap hs ho + simp only + rw [hw.activeEq]; omega + · simp only [hl] at h; simp at h +end AienSeq diff --git a/bootstrap/formal-oracles/lean/MutantSeqForkClaim.lean b/bootstrap/formal-oracles/lean/MutantSeqForkClaim.lean new file mode 100644 index 0000000..05ee66a --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantSeqForkClaim.lean @@ -0,0 +1,6 @@ +import MutantSeqModels +namespace AienSeq +/-- Real-model theorem `fork_stale_refused` restated for forkM5. MUST FAIL to check. -/ +theorem mutant_fork_stale {a : Arena} {p : Id} (h : a.live p = false) : a.forkM5 p = none := by + unfold Arena.forkM5; simp [h] +end AienSeq diff --git a/bootstrap/formal-oracles/lean/MutantSeqIgnoreGenClaim.lean b/bootstrap/formal-oracles/lean/MutantSeqIgnoreGenClaim.lean new file mode 100644 index 0000000..ae60e84 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantSeqIgnoreGenClaim.lean @@ -0,0 +1,7 @@ +import MutantSeqModels +namespace AienSeq +/-- Real-model theorem `generation_mismatch_not_live` restated for liveM2. MUST FAIL to check. -/ +theorem mutant_mismatch_not_live {a : Arena} {id : Id} (h : a.gen id.slot ≠ id.gen) : + a.liveM2 id = false := by + unfold Arena.liveM2; simp [h] +end AienSeq diff --git a/bootstrap/formal-oracles/lean/MutantSeqModels.lean b/bootstrap/formal-oracles/lean/MutantSeqModels.lean new file mode 100644 index 0000000..57405e0 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantSeqModels.lean @@ -0,0 +1,43 @@ +import AienSeq.Corpus +/-! +# Deliberate mutants of the sequence arena (each must break one required rule) + +WRONG on purpose. Each mutant model compiles; the matching claim file must not. +-/ +namespace AienSeq + +/-- MUTANT 1 (free_keeps_generation): free does not bump the generation. -/ +def Arena.releaseM1 (a : Arena) (id : Id) : Arena × Bool := + if a.live id then + ({ a with occ := upd a.occ id.slot false, free := id.slot :: a.free, active := a.active - 1 }, true) + else (a, false) + +/-- MUTANT 2 (get_ignores_generation): resolution ignores the generation. -/ +def Arena.liveM2 (a : Arena) (id : Id) : Bool := + decide (id.slot < a.cap) && a.occ id.slot + +/-- MUTANT 3 (wrap_to_zero): the wrap drops the `.max(1)`, so generation 0 can appear. -/ +def nextGenM3 (g : Nat) : Nat := (g + 1) % two32 + +/-- MUTANT 4 (free_keeps_active): free forgets to decrement the active count. -/ +def Arena.releaseM4 (a : Arena) (id : Id) : Arena × Bool := + if a.live id then + ({ a with occ := upd a.occ id.slot false, gen := upd a.gen id.slot (nextGen (a.gen id.slot)), + free := id.slot :: a.free }, true) + else (a, false) + +/-- MUTANT 5 (fork_without_parent_check): fork allocates even when the parent id is stale. -/ +def Arena.forkM5 (a : Arena) (_parent : Id) : Option (Arena × Id) := a.alloc + +/-- witnesses: each mutant accepts what the real model refuses -/ +theorem m1_reuses_generation : + allocId ((allocArena a2).releaseM1 ⟨0, 1⟩).1 = some ⟨0, 1⟩ := by decide +theorem m2_wrong_gen_resolves : (allocArena a2).liveM2 ⟨0, 7⟩ = true := by decide +theorem m3_zero_generation : nextGenM3 genMax = 0 := by decide +theorem m4_active_stuck : (((allocArena a2).releaseM4 ⟨0, 1⟩).1).active = 1 := by decide +theorem m5_stale_fork_allowed : + (((allocArena a2).release ⟨0, 1⟩).1.forkM5 ⟨0, 1⟩).isSome = true := by decide +theorem real_refuses_stale_fork : + (((allocArena a2).release ⟨0, 1⟩).1.fork ⟨0, 1⟩).isSome = false := by decide + +end AienSeq diff --git a/bootstrap/formal-oracles/lean/MutantSeqNoBumpClaim.lean b/bootstrap/formal-oracles/lean/MutantSeqNoBumpClaim.lean new file mode 100644 index 0000000..ddd9b50 --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantSeqNoBumpClaim.lean @@ -0,0 +1,13 @@ +import MutantSeqModels +namespace AienSeq +/-- Real-model theorem `free_invalidates` (generation half) restated for releaseM1. MUST FAIL to check. -/ +theorem mutant_free_changes_gen {a a' : Arena} {id : Id} (h : a.releaseM1 id = (a', true)) : + a'.gen id.slot ≠ id.gen := by + unfold Arena.releaseM1 at h + by_cases hl : a.live id = true + · simp only [hl, ite_true, Prod.mk.injEq] at h + obtain ⟨rfl, _⟩ := h + obtain ⟨hs, hg, ho⟩ := live_gen_match hl + simp [upd, hg] + · simp only [hl] at h; simp at h +end AienSeq diff --git a/bootstrap/formal-oracles/lean/MutantSeqZeroWrapClaim.lean b/bootstrap/formal-oracles/lean/MutantSeqZeroWrapClaim.lean new file mode 100644 index 0000000..67c516a --- /dev/null +++ b/bootstrap/formal-oracles/lean/MutantSeqZeroWrapClaim.lean @@ -0,0 +1,6 @@ +import MutantSeqModels +namespace AienSeq +/-- Real-model theorem `nextGen_pos` restated for nextGenM3. MUST FAIL to check. -/ +theorem mutant_next_pos (g : Nat) : 1 ≤ nextGenM3 g := by + unfold nextGenM3; omega +end AienSeq diff --git a/bootstrap/formal-oracles/lean/lakefile.toml b/bootstrap/formal-oracles/lean/lakefile.toml index a695e71..991a6dd 100644 --- a/bootstrap/formal-oracles/lean/lakefile.toml +++ b/bootstrap/formal-oracles/lean/lakefile.toml @@ -1,5 +1,5 @@ name = "aien_formal_oracle" -defaultTargets = ["AienCap", "AienReceipt"] +defaultTargets = ["AienCap", "AienReceipt", "AienSeq", "AienKv"] # Core Lean only. No Mathlib, no Batteries, no other dependency: builds offline. @@ -52,3 +52,58 @@ globs = ["MutantCanaryClaim"] [[lean_lib]] name = "MutantAbsentFlagClaim" globs = ["MutantAbsentFlagClaim"] + +# FORMAL-6: sequence identity (AIEN.INV.SEQUENCE.STALE_ID.V1) and KV layout bounds (AIEN.INV.KV.LAYOUT_BOUNDS.V1). +[[lean_lib]] +name = "AienSeq" + +[[lean_lib]] +name = "AienKv" + +[[lean_lib]] +name = "MutantSeqModels" +globs = ["MutantSeqModels"] + +[[lean_lib]] +name = "MutantSeqNoBumpClaim" +globs = ["MutantSeqNoBumpClaim"] + +[[lean_lib]] +name = "MutantSeqIgnoreGenClaim" +globs = ["MutantSeqIgnoreGenClaim"] + +[[lean_lib]] +name = "MutantSeqZeroWrapClaim" +globs = ["MutantSeqZeroWrapClaim"] + +[[lean_lib]] +name = "MutantSeqActiveClaim" +globs = ["MutantSeqActiveClaim"] + +[[lean_lib]] +name = "MutantSeqForkClaim" +globs = ["MutantSeqForkClaim"] + +[[lean_lib]] +name = "MutantKvModels" +globs = ["MutantKvModels"] + +[[lean_lib]] +name = "MutantKvPlanesClaim" +globs = ["MutantKvPlanesClaim"] + +[[lean_lib]] +name = "MutantKvTotalClaim" +globs = ["MutantKvTotalClaim"] + +[[lean_lib]] +name = "MutantKvTokenClaim" +globs = ["MutantKvTokenClaim"] + +[[lean_lib]] +name = "MutantKvValidClaim" +globs = ["MutantKvValidClaim"] + +[[lean_lib]] +name = "MutantKvBlockClaim" +globs = ["MutantKvBlockClaim"] diff --git a/bootstrap/formal-oracles/lean/oracle.toml b/bootstrap/formal-oracles/lean/oracle.toml index b8728a3..743bf4e 100644 --- a/bootstrap/formal-oracles/lean/oracle.toml +++ b/bootstrap/formal-oracles/lean/oracle.toml @@ -45,3 +45,21 @@ note = "A PASS is one evidence input bound to a source and model revision. It is script = "run-receipt-formal.sh" result_line = "RECEIPT_FORMAL_BOOTSTRAP: PASS|FAIL|NOT_RUN" note = "FORMAL-4. Same rule: PASS is one evidence input, not authority." + +[[covers]] +invariant = "AIEN.INV.SEQUENCE.STALE_ID.V1" +manifest = "formal/invariants/sequence-stale-id-v1.toml" + +[[covers]] +invariant = "AIEN.INV.KV.LAYOUT_BOUNDS.V1" +manifest = "formal/invariants/kv-layout-bounds-v1.toml" + +[[run_extra]] +script = "run-seq-formal.sh" +result_line = "SEQ_FORMAL_BOOTSTRAP: PASS|FAIL|NOT_RUN" +note = "FORMAL-6. Models aien-dev/sovereign-core dd1fe32 (PREFILL-E2E settled). PASS is one evidence input, not authority." + +[[run_extra]] +script = "run-kv-formal.sh" +result_line = "KV_FORMAL_BOOTSTRAP: PASS|FAIL|NOT_RUN" +note = "FORMAL-6. Same rule: PASS is one evidence input, not authority." diff --git a/bootstrap/formal-oracles/lean/run-kv-formal.sh b/bootstrap/formal-oracles/lean/run-kv-formal.sh new file mode 100755 index 0000000..3cf6268 --- /dev/null +++ b/bootstrap/formal-oracles/lean/run-kv-formal.sh @@ -0,0 +1,56 @@ +#!/bin/sh +# FORMAL-6: KV layout bounds formal bootstrap runner (DEVELOPMENT_ORACLE, not permanent lineage). +# Builds the real model (must PASS) and each deliberate mutant claim (must FAIL for a proof reason). +# Last stdout line: KV_FORMAL_BOOTSTRAP: PASS | FAIL | NOT_RUN +# No network needed after the toolchain is installed (core Lean only, no dependencies). +set -u +here=$(cd "$(dirname "$0")" && pwd) +cd "$here" || exit 2 +PATH="$HOME/.elan/bin:$PATH"; export PATH + +quiet="${AIEN_SPARK_QUIET_FLAG:-$HOME/workspace/.spark-quiet}" +if [ -e "$quiet" ]; then + echo "quiet flag present ($quiet): not building" + echo "KV_FORMAL_BOOTSTRAP: NOT_RUN" + exit 3 +fi +command -v lake >/dev/null 2>&1 || { echo "lake not found (install elan)"; echo "KV_FORMAL_BOOTSTRAP: NOT_RUN"; exit 3; } + +log=$(mktemp); trap 'rm -f "$log"' EXIT +echo "toolchain: $(cat lean-toolchain) / $(lean --version)" +fail=0 + +# Forbidden constructs in the receipt sources (comments excluded by matching code-like uses). +if grep -nE '^[^-]*\b(sorry|admit|native_decide|unsafe)\b|^axiom |^ *axiom ' AienKv/*.lean AienKv.lean >"$log"; then + echo "forbidden_constructs: FAIL"; cat "$log"; fail=1 +else + echo "forbidden_constructs: PASS" +fi + +lake build AienKv >"$log" 2>&1; rc=$? +if [ $rc -eq 0 ] && ! grep -qi "sorry" "$log"; then + echo "real_model: PASS" +else + echo "real_model: FAIL (rc=$rc)"; tail -20 "$log"; fail=1 +fi + +lake build MutantKvModels >"$log" 2>&1; rc=$? +if [ $rc -eq 0 ] && ! grep -qi "sorry" "$log"; then + echo "mutant_models_compile: PASS" +else + echo "mutant_models_compile: FAIL (rc=$rc)"; tail -20 "$log"; fail=1 +fi + +# A mutant is killed only by a proof error in its own claim file, not a syntax or import error. +for m in MutantKvPlanesClaim MutantKvTotalClaim MutantKvTokenClaim MutantKvValidClaim MutantKvBlockClaim; do + lake build "$m" >"$log" 2>&1; rc=$? + if [ $rc -ne 0 ] && grep -qE "^error: $m.lean:[0-9]+:[0-9]+: (unsolved goals|simp_all made no progress|Type mismatch|Application type mismatch|.?simp.? made no progress|omega could not prove|Tactic)" "$log" \ + && ! grep -q "unexpected token" "$log" && ! grep -qE "^error: (MutantKvModels|AienKv)" "$log"; then + echo "$m: FAIL_AS_EXPECTED (mutant killed)" + else + echo "$m: UNEXPECTED_BUILD_SUCCESS_OR_NO_PROOF_ERROR (rc=$rc), mutant survived"; fail=1 + fi +done + +if [ $fail -eq 0 ]; then echo "KV_FORMAL_BOOTSTRAP: PASS"; else echo "KV_FORMAL_BOOTSTRAP: FAIL"; fi +exit $fail diff --git a/bootstrap/formal-oracles/lean/run-seq-formal.sh b/bootstrap/formal-oracles/lean/run-seq-formal.sh new file mode 100755 index 0000000..d07fe64 --- /dev/null +++ b/bootstrap/formal-oracles/lean/run-seq-formal.sh @@ -0,0 +1,56 @@ +#!/bin/sh +# FORMAL-6: sequence identity formal bootstrap runner (DEVELOPMENT_ORACLE, not permanent lineage). +# Builds the real model (must PASS) and each deliberate mutant claim (must FAIL for a proof reason). +# Last stdout line: SEQ_FORMAL_BOOTSTRAP: PASS | FAIL | NOT_RUN +# No network needed after the toolchain is installed (core Lean only, no dependencies). +set -u +here=$(cd "$(dirname "$0")" && pwd) +cd "$here" || exit 2 +PATH="$HOME/.elan/bin:$PATH"; export PATH + +quiet="${AIEN_SPARK_QUIET_FLAG:-$HOME/workspace/.spark-quiet}" +if [ -e "$quiet" ]; then + echo "quiet flag present ($quiet): not building" + echo "SEQ_FORMAL_BOOTSTRAP: NOT_RUN" + exit 3 +fi +command -v lake >/dev/null 2>&1 || { echo "lake not found (install elan)"; echo "SEQ_FORMAL_BOOTSTRAP: NOT_RUN"; exit 3; } + +log=$(mktemp); trap 'rm -f "$log"' EXIT +echo "toolchain: $(cat lean-toolchain) / $(lean --version)" +fail=0 + +# Forbidden constructs in the receipt sources (comments excluded by matching code-like uses). +if grep -nE '^[^-]*\b(sorry|admit|native_decide|unsafe)\b|^axiom |^ *axiom ' AienSeq/*.lean AienSeq.lean >"$log"; then + echo "forbidden_constructs: FAIL"; cat "$log"; fail=1 +else + echo "forbidden_constructs: PASS" +fi + +lake build AienSeq >"$log" 2>&1; rc=$? +if [ $rc -eq 0 ] && ! grep -qi "sorry" "$log"; then + echo "real_model: PASS" +else + echo "real_model: FAIL (rc=$rc)"; tail -20 "$log"; fail=1 +fi + +lake build MutantSeqModels >"$log" 2>&1; rc=$? +if [ $rc -eq 0 ] && ! grep -qi "sorry" "$log"; then + echo "mutant_models_compile: PASS" +else + echo "mutant_models_compile: FAIL (rc=$rc)"; tail -20 "$log"; fail=1 +fi + +# A mutant is killed only by a proof error in its own claim file, not a syntax or import error. +for m in MutantSeqNoBumpClaim MutantSeqIgnoreGenClaim MutantSeqZeroWrapClaim MutantSeqActiveClaim MutantSeqForkClaim; do + lake build "$m" >"$log" 2>&1; rc=$? + if [ $rc -ne 0 ] && grep -qE "^error: $m.lean:[0-9]+:[0-9]+: (unsolved goals|simp_all made no progress|Type mismatch|Application type mismatch|.?simp.? made no progress|omega could not prove|Tactic)" "$log" \ + && ! grep -q "unexpected token" "$log" && ! grep -qE "^error: (MutantSeqModels|AienSeq)" "$log"; then + echo "$m: FAIL_AS_EXPECTED (mutant killed)" + else + echo "$m: UNEXPECTED_BUILD_SUCCESS_OR_NO_PROOF_ERROR (rc=$rc), mutant survived"; fail=1 + fi +done + +if [ $fail -eq 0 ]; then echo "SEQ_FORMAL_BOOTSTRAP: PASS"; else echo "SEQ_FORMAL_BOOTSTRAP: FAIL"; fi +exit $fail diff --git a/formal/invariants/SCHEMA.md b/formal/invariants/SCHEMA.md index 264ba11..e06cea7 100644 --- a/formal/invariants/SCHEMA.md +++ b/formal/invariants/SCHEMA.md @@ -38,3 +38,5 @@ One TOML file per invariant, named `--v.toml`. The invariant ID s - `capability-attenuation-v1.toml`: AIEN.INV.CAP.ATTENUATION.V1 - `capability-revocation-v1.toml`: AIEN.INV.CAP.REVOCATION_CLOSURE.V1 - `artifact-receipt-v1.toml`: AIEN.INV.RECEIPT.REJECTION_CONSISTENCY.V1 +- `sequence-stale-id-v1.toml`: AIEN.INV.SEQUENCE.STALE_ID.V1 +- `kv-layout-bounds-v1.toml`: AIEN.INV.KV.LAYOUT_BOUNDS.V1 diff --git a/formal/invariants/kv-layout-bounds-v1.toml b/formal/invariants/kv-layout-bounds-v1.toml new file mode 100644 index 0000000..38a1b38 --- /dev/null +++ b/formal/invariants/kv-layout-bounds-v1.toml @@ -0,0 +1,105 @@ +schema_version = 0 +id = "AIEN.INV.KV.LAYOUT_BOUNDS.V1" +version = 1 +status = "SEEDED" + +statement = """ +The pooled KV tensor is one allocation of total = numBlocks * block bytes, where block = numLayers * 2 * blockSize * numKvHeads * \ +headDim * elemBytes, laid out block, then layer, then K plane and V plane, then token, then head, then dim. For every valid block, \ +layer, K/V selector (0 or 1), token, head and dim, the element's bytes [offset, offset + elemBytes) lie within [0, total). The same \ +holds for a whole token row and for a whole block region. Regions of different blocks are disjoint, regions of different layers of \ +one block are disjoint and inside the block, the K plane and the V plane of one layer are disjoint, and rows of different tokens \ +of one plane are disjoint. If the host buffer is at least total bytes, every valid element lies inside the host buffer. These \ +statements are about unbounded arithmetic; they equal the machine statements exactly when the config's total is below 2^64.""" + +assumptions = [ + "Arithmetic is unbounded in the model. The Rust code uses usize without checked arithmetic; a config with total >= 2^64 wraps silently and is not covered (stated as a theorem and shown by a witness).", + "Indices are valid. The Rust element_offset and token_plane_offset assert this (assert!, active in release builds).", + "Dtype width elemBytes is Fp8 1, Bf16 or Fp16 2, Fp32 4. Fp4 is refused by the code and is not modelled.", + "Alignment and the buffer's base address are not modelled.", + "Distinct valid element tuples map to distinct offsets (full injectivity) is NOT claimed here; only bounds and the region disjointness listed.", +] + +semantic_types = ["KvPoolConfig", "KvLayout", "BlockRegion", "ElementOffset"] + +oracle_models = ["lean"] + +evidence_requirements = [ + "positive corpus: TinyLlama config, first and last element, block and V plane starts, block bytes equal to the PREFILL-E2E-0 receipt kv_block_bytes", + "negative corpus: block index past the end, invalid K/V selector aliasing the next layer", + "deliberate mutants that must not survive: planes overlap, total one block short, token stride forgets element size, validity off by one, block stride short", + "wrap witness reproduced against the real crate in a release build", + "existing Miri, property and mutation tests of aien-kv-cache keep passing; Lean does not replace them", +] + +required_counterexamples = [ + "kv_planes_overlap", + "total_one_block_short", + "token_stride_forgets_element_size", + "validity_off_by_one", + "block_stride_short", +] + +omega_takeover_condition = """ +Omega expresses the layout rules as native propositions over the stride chain and offset formula, accepts the positive corpus, \ +rejects the negative corpus, kills the required counterexample mutants, carries the 2^64 bound as an explicit hypothesis, and emits a \ +canonical proof/evidence identity that the gates consume, with Lean absent.""" + +[[positive_examples]] +name = "tinyllama_block" +description = "22 layers, 4 KV heads, head dim 64, block size 16, 4 byte elements: block stride 720896 bytes." + +[[positive_examples]] +name = "last_element_exact" +description = "The last element of the last block ends exactly at total." + +[[negative_examples]] +name = "block_past_end" +description = "Block index equal to numBlocks is not inside the allocation." + +[[negative_examples]] +name = "v_selector_2" +description = "K/V selector 2 aliases the first plane of the next layer." + +[[counterexamples]] +name = "kv_planes_overlap" +description = "Layer stride equals one plane, so V overlaps the next layer's K." + +[[counterexamples]] +name = "total_one_block_short" +description = "The allocation is one block smaller than the layout needs." + +[[counterexamples]] +name = "token_stride_forgets_element_size" +description = "Token stride omits the element width, so heads overlap." + +[[counterexamples]] +name = "validity_off_by_one" +description = "The K/V selector check admits 2, which indexes past the layer." + +[[counterexamples]] +name = "block_stride_short" +description = "Blocks are placed one byte too close together and overlap." + +[[implementation_surfaces]] +repo = "aien-dev/sovereign-core" +path = "crates/aien-kv-cache/src/lib.rs" +kind = "production" +observed_at = "dd1fe323d5fc774ff0fe6faaadebfea6450563c0" +note = "KvLayout::from_config (169 to 184), element_offset (203), token_plane_offset (227), block_offset (245), UnifiedKvTensorPool::new buffer check (335 to 337)." + +[[observations]] +surface = "crates/aien-kv-cache/src/lib.rs" +text = """ +from_config multiplies usize values with plain operators (no checked_mul) and never refuses a zero dimension or an oversized config. \ +Reproduced on a release build of the real crate at dd1fe32: num_blocks = 2^45 with the TinyLlama dimensions and Fp32 returns Ok with \ +total_bytes = 6917529027641081856 while the true product is 25364273101350633472 (>= 2^64). The pool constructor then compares the \ +buffer length with the wrapped total. No such config is reachable from current callers (arena capacity and block counts are small); the \ +risk is latent. Recorded, not fixed (formal verification does not edit the PREFILL surfaces).""" + +[[observations]] +surface = "crates/aien-kv-cache/src/lib.rs" +text = """ +bytes_per_block (line 107) is computed separately as ceil(elements * bytes_per_element as f32); for the integer dtypes it equals the \ +layout block stride (theorem block_eq_bytes_per_block). It goes through f32, which is exact only below 2^24 elements per block; larger \ +configs would round. Not modelled.""" diff --git a/formal/invariants/sequence-stale-id-v1.toml b/formal/invariants/sequence-stale-id-v1.toml new file mode 100644 index 0000000..e04e8e1 --- /dev/null +++ b/formal/invariants/sequence-stale-id-v1.toml @@ -0,0 +1,116 @@ +schema_version = 0 +id = "AIEN.INV.SEQUENCE.STALE_ID.V1" +version = 1 +status = "SEEDED" + +statement = """ +A sequence id is a pair (slot, generation). An id resolves to a live record only when its slot exists, the slot's current \ +generation equals the id's generation, and the slot holds a record. Freeing a live id removes the record and changes the \ +slot's generation, so the freed id and every copy of it stop resolving; freeing a stale, unknown or already freed id changes \ +nothing and reports failure. Generation 0 is never issued. Allocation is refused exactly when every slot is occupied, so the \ +active count never exceeds the capacity, rises by one on a successful allocation or fork and falls by one on a successful free. \ +Fork from an id that does not resolve is refused. Re-allocating a just freed slot never returns the freed id. The generation field \ +is finite (u32): after exactly 2^32 - 1 frees of one slot the generation repeats, so a stale id from before the cycle would resolve \ +again. This limitation is part of the invariant and is NOT eternal ABA freedom.""" + +assumptions = [ + "Single scheduler thread owns the arena (no concurrency model; the Rust arena has no locks).", + "Generation arithmetic is the u32 rule next = max((g + 1) mod 2^32, 1); the model carries it exactly.", + "Record contents are not modelled, only whether a record is present.", + "Callers do not keep an id across 2^32 - 1 frees of its slot; the code does not enforce this, and the runtime arena has no retire path (the scheduler arena retires the slot at u32::MAX instead).", +] + +semantic_types = ["SequenceId", "SequenceArena", "SlotGeneration", "ActiveCount", "Capacity"] + +oracle_models = ["lean"] + +evidence_requirements = [ + "positive corpus: first allocation, free then reuse with a new generation, live fork", + "negative corpus: never allocated, stale after free, stale free refused, wrong generation, generation zero, slot out of range, stale fork, capacity exhausted", + "deliberate mutants that must not survive: free keeps generation, resolution ignores generation, wrap yields generation 0, free keeps active count, fork skips the parent check", + "the generation wrap limitation stated as a theorem (iterGen genMax g = g) next to the no-reuse-before-wrap theorem", + "existing implementation unit tests and the PREFILL-E2E runtime tests keep passing", +] + +required_counterexamples = [ + "free_keeps_generation", + "resolution_ignores_generation", + "wrap_to_generation_zero", + "free_keeps_active_count", + "fork_from_stale_parent", +] + +omega_takeover_condition = """ +Omega expresses the arena rules as native propositions over (slot, generation) records, accepts the positive corpus, rejects the \ +negative corpus, kills the required counterexample mutants, states the finite-generation limitation as an explicit assumption, and \ +emits a canonical proof/evidence identity that the gates consume, with Lean absent.""" + +[[positive_examples]] +name = "free_then_reuse" +description = "Allocate (0,1), free it, allocate again: the slot comes back as (0,2). The old id (0,1) does not resolve." + +[[positive_examples]] +name = "live_fork" +description = "Fork from a live parent id succeeds and returns a new live id." + +[[negative_examples]] +name = "stale_id_after_free" +description = "An id used after its record was freed does not resolve, and freeing it again is refused." + +[[negative_examples]] +name = "wrong_generation" +description = "Right slot, generation that is not the slot's current one: does not resolve." + +[[negative_examples]] +name = "capacity_exhausted" +description = "Allocation when every slot is occupied is refused." + +[[counterexamples]] +name = "free_keeps_generation" +description = "Free leaves the generation unchanged, so a reallocated slot reissues the freed id." + +[[counterexamples]] +name = "resolution_ignores_generation" +description = "get resolves any id whose slot holds a record, whatever generation it carries." + +[[counterexamples]] +name = "wrap_to_generation_zero" +description = "The generation wrap produces 0, which the scheduler arena treats as invalid." + +[[counterexamples]] +name = "free_keeps_active_count" +description = "Free forgets to lower the active count, so capacity accounting drifts." + +[[counterexamples]] +name = "fork_from_stale_parent" +description = "Fork allocates a child even though the parent id does not resolve." + +[[implementation_surfaces]] +repo = "aien-dev/sovereign-core" +path = "crates/aien-runtime/src/sequence.rs" +kind = "production" +observed_at = "dd1fe323d5fc774ff0fe6faaadebfea6450563c0" +note = "SequenceArena: new (line 76 onward), allocate (98), fork (131), get (178), free (197, wrapping_add(1).max(1) at 202), active_count." + +[[implementation_surfaces]] +repo = "aien-dev/sovereign-core" +path = "crates/aien-scheduler/src/sequence.rs" +kind = "production" +observed_at = "dd1fe323d5fc774ff0fe6faaadebfea6450563c0" +note = "Second SequenceArena: free_sequence (512) retires the slot at u32::MAX (523) instead of wrapping. Modelled only as the pure rule retireNext." + +[[observations]] +surface = "crates/aien-runtime/src/sequence.rs" +text = """ +free (197 to 209) bumps the generation with wrapping_add(1).max(1), so the runtime arena has no retire path: a slot freed 2^32 - 1 times \ +reissues an old id. get (178) resolves on slot-in-range, equal generation and a present record. allocate and fork pop a free slot and \ +hand out its current generation. active_count is incremented on both and decremented with saturating_sub on free; the model proves the \ +subtraction never saturates for a well formed arena.""" + +[[observations]] +surface = "crates/aien-scheduler/src/sequence.rs" +text = """ +divergence between the two arenas: the scheduler arena retires a slot when its generation reaches u32::MAX (free_sequence, 512 to 523) \ +and never reuses it, so it has no ABA window at the cost of capacity; the runtime arena wraps. Both are in production code in the same \ +workspace. Recorded, not asserted either way. insert_with_id in the scheduler arena also accepts a caller supplied generation and sets the \ +slot generation to it, which the model does not cover.""" ```