From 377c32e1191f8f83aa59c6212b05efe514909ceb Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 19:11:30 -0500 Subject: [PATCH 01/30] feat(formal): a retire with no seal, and the fresh identity The owner decided on 2026-11-11 that a retire is the shallow removal: the item leaves the present, its history stays readable at the cuts where it existed, no seal is applied, and a note written later at the same path takes a fresh identity. The library proved the two seals; this adds what the decision rests on, over the same model. With no seal the history of a key at a cut is its landings inside the cut (landingsAt): append invariant, a prefix of the history at a later cut, every landing at the head, and holding as its end everything the stricter seal serves. With a fresh identity at a retired path (lives: the path with the number of its retires before the event) the identity a landing takes is a function of the events before it, the history of the identity a path holds at a cut is the path's landings since its last retire, and a retired identity keeps the life it had at every cut that holds its retire. Two controls: an identity used again after its retire inherits the retired item's versions, and under the seal a later retire empties a history that was served. Eighteen theorems, two of them controls. The seals' theorems stay. Co-Authored-By: Claude Fable 5.2 --- formal/Palace/Snapshot.lean | 204 ++++++++++++++++++++++++++++++- formal/Palace/Snapshot/Defs.lean | 25 +++- 2 files changed, 226 insertions(+), 3 deletions(-) diff --git a/formal/Palace/Snapshot.lean b/formal/Palace/Snapshot.lean index 85ef1b2f..55e25999 100644 --- a/formal/Palace/Snapshot.lean +++ b/formal/Palace/Snapshot.lean @@ -59,8 +59,19 @@ a cut a prefix length for each. Cited from the note, not from the ledger. `Witness.servedNow_restores`). The seal covers the key's versions as it covers its value: the history served at a cut ends at the value served there, and at every cut after a retire, the head included, it holds only versions landed after that retire (`getLast?_historyAt`, - `historyAt_append_of_retire`, `historyAt_of_retire_inside`, `sinceRetire_append_retire`). The - control is the erasure that deletes rows (`Witness.compact_moves`). For a keyed chain whose + `historyAt_append_of_retire`, `historyAt_of_retire_inside`, `sinceRetire_append_retire`). A + retire with no seal: the history of a key at a cut is its landings inside the cut, a derived + view of the prefix that holds everything the seal serves (`landingsAt_append`, + `landingsAt_mono`, `landingsAt_length`, `historyAt_suffix_landingsAt`). When a landing at a + retired path takes a fresh identity, the identity is a function of the events before the + landing, the history of the identity a path holds at a cut is the path's landings since its + last retire, and a retired identity keeps the life it had at every later cut and gains + nothing (`lives_take`, + `landingsAt_lives_present`, `landingsAt_lives_of_retire`, `landingsAt_lives_append`). The + controls: an identity used again after its retire, whose history holds the retired item's + versions, and the seal, under which a later retire empties a history that was served + (`Witness.reused_identity_inherits`, `Witness.seal_empties_history`). The control for the + erasure is the one that deletes rows (`Witness.compact_moves`). For a keyed chain whose holes keep their keys, the read of a key at a cut is its last write at or under the cut, a hole when that write is erased, and the three reads agree on it (`stateAt_holes`, `stateAt_holes_of_erased`, `not_erased_of_stateAt_holes`, `genRead_gens_holes`, @@ -807,6 +818,176 @@ theorem historyAt_length (l : List (κ × Option β)) (x : κ) : historyAt l l.length x = sinceRetire l x := by simp [historyAt, sealedAt] +/-! ### A retire with no seal, and the fresh identity -/ + +/-- SNP-1 With no seal the history of a key at a cut is append invariant: growth of the chain, a +retire of the key included, changes nothing in it. -/ +theorem landingsAt_append {l : List (κ × Option β)} (t : List (κ × Option β)) {c : ℕ} + (hc : c ≤ l.length) (x : κ) : landingsAt (l ++ t) c x = landingsAt l c x := by + unfold landingsAt + rw [List.take_append_of_le_length hc] + +/-- SNP-4 At the head cut the history with no seal is every landing of the key. -/ +theorem landingsAt_length (l : List (κ × Option β)) (x : κ) : + landingsAt l l.length x = l.filterMap fun e ↦ if e.1 = x then e.2 else none := by + simp [landingsAt] + +/-- SNP-2 With no seal the history at an earlier cut is a prefix of the history at a later +one. -/ +theorem landingsAt_mono (l : List (κ × Option β)) {a b : ℕ} (h : a ≤ b) (x : κ) : + landingsAt l a x <+: landingsAt l b x := + (List.take_prefix_take_left h).filterMap _ + +theorem sinceRetire_suffix_filterMap (m : List (κ × Option β)) (x : κ) : + sinceRetire m x <:+ m.filterMap fun e ↦ if e.1 = x then e.2 else none := by + induction m using List.reverseRecOn with + | nil => exact List.suffix_refl _ + | append_singleton m e ih => + rw [sinceRetire_append_singleton, List.filterMap_append] + by_cases hx : e.1 = x + · cases he : e.2 with + | none => simp [hx] + | some v => + obtain ⟨p, hp⟩ := ih + refine ⟨p, ?_⟩ + simp [hx, he, ← hp] + · simpa [hx] using ih + +/-- SNP-7 The history with no seal holds everything the stricter seal serves, as its end: the +seal only withholds, and what it withholds are the landings before a retire. -/ +theorem historyAt_suffix_landingsAt (l : List (κ × Option β)) (c : ℕ) (x : κ) : + historyAt l c x <:+ landingsAt l c x := by + unfold historyAt landingsAt + split_ifs + · exact List.nil_suffix + · exact sinceRetire_suffix_filterMap _ x + +theorem retiresOf_append (l t : List (κ × Option β)) (x : κ) : + retiresOf (l ++ t) x = retiresOf l x + retiresOf t x := by + simp [retiresOf, List.filter_append] + +theorem retiresOf_reverse (l : List (κ × Option β)) (x : κ) : + retiresOf l.reverse x = retiresOf l x := by + simp [retiresOf, List.filter_reverse] + +theorem lives_append_singleton (l : List (κ × Option β)) (e : κ × Option β) : + lives (l ++ [e]) = lives l ++ [((e.1, retiresOf l e.1), e.2)] := by + simp [lives, livesRev, retiresOf_reverse] + +theorem length_lives (l : List (κ × Option β)) : (lives l).length = l.length := by + induction l using List.reverseRecOn with + | nil => rfl + | append_singleton l e ih => simp [lives_append_singleton, ih] + +/-- The identity a landing takes is a function of the events before it: the chain of lives of a +prefix is the prefix of the chain of lives. So a landing run again takes the identity it took. -/ +theorem lives_take (l : List (κ × Option β)) (c : ℕ) : (lives l).take c = lives (l.take c) := by + induction l using List.reverseRecOn with + | nil => simp [lives, livesRev] + | append_singleton l e ih => + rw [lives_append_singleton] + by_cases hc : c ≤ l.length + · rw [List.take_append_of_le_length (by rw [length_lives]; exact hc), + List.take_append_of_le_length hc, ih] + · rw [List.take_of_length_le (by simp [length_lives]; omega), + List.take_of_length_le (by simp; omega), lives_append_singleton] + +/-- No event of a path is keyed by a life the path has not reached. -/ +theorem le_retiresOf_of_mem_lives {l : List (κ × Option β)} {x : κ} {n : ℕ} {v : Option β} + (h : ((x, n), v) ∈ lives l) : n ≤ retiresOf l x := by + induction l using List.reverseRecOn with + | nil => simp [lives, livesRev] at h + | append_singleton l e ih => + rw [lives_append_singleton, List.mem_append, List.mem_singleton] at h + rw [retiresOf_append] + rcases h with h | h + · exact (ih h).trans (Nat.le_add_right _ _) + · simp only [Prod.mk.injEq] at h + obtain ⟨⟨rfl, rfl⟩, -⟩ := h + exact Nat.le_add_right _ _ + +theorem filterMap_lives_of_lt (l : List (κ × Option β)) (x : κ) {n : ℕ} + (h : retiresOf l x < n) : + (lives l).filterMap (fun e ↦ if e.1 = (x, n) then e.2 else none) = [] := by + rw [List.filterMap_eq_nil_iff] + rintro ⟨⟨y, m⟩, v⟩ hmem + by_cases hk : (y, m) = (x, n) + · simp only [Prod.mk.injEq] at hk + obtain ⟨rfl, rfl⟩ := hk + exact absurd (le_retiresOf_of_mem_lives hmem) (by omega) + · simp [hk] + +/-- The landings of a path's present identity are the path's landings since its last retire. -/ +theorem filterMap_lives_retiresOf (l : List (κ × Option β)) (x : κ) : + (lives l).filterMap (fun e ↦ if e.1 = (x, retiresOf l x) then e.2 else none) + = sinceRetire l x := by + induction l using List.reverseRecOn with + | nil => rfl + | append_singleton l e ih => + rw [lives_append_singleton, List.filterMap_append, sinceRetire_append_singleton, + retiresOf_append] + by_cases hx : e.1 = x + · subst hx + cases he : e.2 with + | none => + have h1 : retiresOf [e] e.1 = 1 := by simp [retiresOf, he] + rw [h1, filterMap_lives_of_lt l e.1 (Nat.lt_succ_self _)] + simp + | some v => + have h0 : retiresOf [e] e.1 = 0 := by simp [retiresOf, he] + rw [h0, Nat.add_zero, ih] + simp + · have h0 : retiresOf [e] x = 0 := by simp [retiresOf, hx] + rw [h0, Nat.add_zero, ih] + simp [hx] + +/-- SNP-7 With a fresh identity at a retired path and no seal, the history of the identity a +path holds at a cut is the path's landings since its last retire inside the cut: no version of +an identity retired at the path is in it, at the head or at any cut. -/ +theorem landingsAt_lives_present (l : List (κ × Option β)) (c : ℕ) (x : κ) : + landingsAt (lives l) c (x, retiresOf (l.take c) x) = sinceRetire (l.take c) x := by + unfold landingsAt + rw [lives_take, filterMap_lives_retiresOf] + +/-- SNP-7 A retired identity keeps its history and gains nothing: at every cut that holds the +retire, however the chain grows after it, the history of the identity retired there is the life +it had. Under the stricter seal the same growth empties it (`historyAt_append_of_retire`). -/ +theorem landingsAt_lives_of_retire (l t : List (κ × Option β)) (x : κ) {c : ℕ} + (hc : l.length + 1 ≤ c) : + landingsAt (lives (l ++ (x, none) :: t)) c (x, retiresOf l x) = sinceRetire l x := by + unfold landingsAt + have h1 : (l ++ (x, none) :: t).take c + = l ++ (x, none) :: t.take (c - (l.length + 1)) := by + rw [List.take_append, List.take_of_length_le (by omega), + show c - l.length = (c - (l.length + 1)) + 1 by omega, List.take_succ_cons] + rw [lives_take, h1] + generalize t.take (c - (l.length + 1)) = b + induction b using List.reverseRecOn with + | nil => + rw [lives_append_singleton, List.filterMap_append, filterMap_lives_retiresOf] + simp + | append_singleton b e ih => + rw [show l ++ (x, none) :: (b ++ [e]) = (l ++ (x, none) :: b) ++ [e] by simp, + lives_append_singleton, List.filterMap_append, ih] + have hne : (e.1, retiresOf (l ++ (x, none) :: b) e.1) ≠ (x, retiresOf l x) := by + intro h + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, h2⟩ := h + have : retiresOf ((e.1, none) :: b) e.1 = 1 + retiresOf b e.1 := by + rw [show (e.1, (none : Option β)) :: b = [(e.1, none)] ++ b by rfl, retiresOf_append] + simp [retiresOf] + rw [retiresOf_append, this] at h2 + omega + simp [hne] + +/-- SNP-1 The history of an identity at a cut inside the chain is unchanged by any growth of the +chain: a later retire or a later landing at its path closes nothing and adds nothing. -/ +theorem landingsAt_lives_append {l : List (κ × Option β)} (t : List (κ × Option β)) {c : ℕ} + (hc : c ≤ l.length) (y : κ × ℕ) : + landingsAt (lives (l ++ t)) c y = landingsAt (lives l) c y := by + unfold landingsAt + rw [lives_take, lives_take, List.take_append_of_le_length hc] + omit [DecidableEq κ] in theorem holes_append (E : κ × β → Bool) (l t : List (κ × β)) : holes E (l ++ t) = holes E l ++ holes E t := @@ -1701,6 +1882,25 @@ theorem servedNow_restores : refine ⟨[((), some 0), ((), none)], [((), some 1)], 1, by decide, ?_, ?_⟩ <;> simp [servedNow, stateAt, stateOf] +/-- The control for the retire with no seal: an identity used again after its retire inherits. +One path lands version 1, is retired, and lands version 2. Keyed by the path, the history at the +head holds the retired item's version; keyed by lives, the new identity's holds version 2 alone +and the retired identity's still holds version 1. -/ +theorem reused_identity_inherits : + ∃ l : List (Unit × Option ℕ), + landingsAt l l.length () = [1, 2] ∧ + landingsAt (lives l) l.length ((), 1) = [2] ∧ + landingsAt (lives l) l.length ((), 0) = [1] := + ⟨[((), some 1), ((), none), ((), some 2)], by decide, by decide, by decide⟩ + +/-- The control for the retire with no seal: what the stricter seal costs. A retire written +after a cut empties the history the seal serves there, and leaves the history with no seal as +it was. -/ +theorem seal_empties_history : + ∃ (l t : List (Unit × Option ℕ)) (c : ℕ), c ≤ l.length ∧ + historyAt l c () = [5] ∧ historyAt (l ++ t) c () = [] ∧ landingsAt (l ++ t) c () = [5] := + ⟨[((), some 5)], [((), none)], 1, by decide, by decide, by decide, by decide⟩ + /-- The control for SNP-10: under the horizon the pruned store reads a key as absent where it held a value. So the horizon is recorded, and a cut under it is not served. -/ theorem prune_forgets : diff --git a/formal/Palace/Snapshot/Defs.lean b/formal/Palace/Snapshot/Defs.lean index 34247ef7..0670097f 100644 --- a/formal/Palace/Snapshot/Defs.lean +++ b/formal/Palace/Snapshot/Defs.lean @@ -30,7 +30,9 @@ the asker's **grant** (`snapshot`: the chains it names and the events it may see position kept; `holes`: the same for a keyed chain, the hole keeping its key; `shown`: the grant and the erasure applied to one read; `servedAt`: a key retired after the cut is served at no earlier cut, with `servedNow` the looser seal that a later landing lifts, and `historyAt` the -versions the stricter seal serves). The control for the erasure is `compact`, an erasure that +versions the stricter seal serves). A retire with no seal is `landingsAt`, every landing of a key +inside the cut, read on `lives`, the chain keyed by the identity a landing takes when a landing at +a retired path takes a fresh one. The control for the erasure is `compact`, an erasure that deletes rows and lets the later ones move up. Events may read from events of other chains (`R k i k' j`: the `i`-th event of chain `k` reads @@ -202,6 +204,27 @@ follows. A version landed before a retire of its key is in no history, at any cu def historyAt [DecidableEq κ] (l : List (κ × Option β)) (c : ℕ) (x : κ) : List β := if sealedAt l c x then [] else sinceRetire (l.take c) x +/-- The history of a key at a cut with no seal: every landing of the key inside the cut, oldest +first. A retire closes nothing here, at this cut or at an earlier one, so it is a derived view of +the prefix. -/ +def landingsAt [DecidableEq κ] (l : List (κ × Option β)) (c : ℕ) (x : κ) : List β := + (l.take c).filterMap fun e ↦ if e.1 = x then e.2 else none + +/-- How many times a chain of landings and retires retires a key. -/ +def retiresOf [DecidableEq κ] (l : List (κ × Option β)) (x : κ) : ℕ := + (l.filter fun e ↦ decide (e.1 = x) && e.2.isNone).length + +/-- The chain of `lives`, given newest first. -/ +def livesRev [DecidableEq κ] : List (κ × Option β) → List ((κ × ℕ) × Option β) + | [] => [] + | e :: older => ((e.1, retiresOf older e.1), e.2) :: livesRev older + +/-- A chain of landings and retires at paths, keyed again by the identity each event belongs to +when a landing at a retired path takes a fresh identity: the path with the number of the path's +retires before the event. The identity is a function of the events before it. -/ +def lives [DecidableEq κ] (l : List (κ × Option β)) : List ((κ × ℕ) × Option β) := + (livesRev l.reverse).reverse + /-- A keyed chain with a hole at each erased write: the hole keeps the write's key and its position and loses its value, so it still shadows the key's earlier writes. The alternative, a hole that loses its key too, is the control (`Witness.keyless_hole`). -/ From 9ce5ac55c2a044abc1239d880976e6bbb7406f41 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 19:11:30 -0500 Subject: [PATCH 02/30] test(formal): attack the retire with no seal, with its controls Seeds 521 to 528 on the model's own definitions. Five attacks survive all 500 instances: the history with no seal is unchanged by growth, a retire included; it ends with what the stricter seal serves and grows by prefix; under fresh identities the history of the identity a path holds is the path's landings since its last retire; a retired identity keeps its life at every later cut; the identity a landing takes is a function of the events before it. Three controls are refuted: the sealed history taken for append invariant, a path's identity used again after its retire, and a retired identity's history taken for empty. Co-Authored-By: Claude Fable 5.2 --- formal/PalaceTest/Snapshot.lean | 62 ++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 5 deletions(-) diff --git a/formal/PalaceTest/Snapshot.lean b/formal/PalaceTest/Snapshot.lean index 256bab1a..1ebc1521 100644 --- a/formal/PalaceTest/Snapshot.lean +++ b/formal/PalaceTest/Snapshot.lean @@ -21,7 +21,8 @@ the horizon, the positions a chain serves from ten bits, with the greatest consi them found by enumeration. The controls are the readings a build must not take: a read at a cut past the head, the store rewritten in place, generations without their closing stamp, a key's state taken for unchanged whatever the delta writes, an event filter before the cut, an erasure -that deletes rows, a state served without the seal, the looser seal taken for a monotone one, +that deletes rows, the state at a cut taken for what the stricter seal serves, the looser seal +taken for a monotone one, kept rows served without their sources, a frontier taken for a cut, an additive digest, a digest over contents, the pruned store read under its horizon, a frontier lowered to the served positions without the descent, the floor and the descent each run once in either order, a hole @@ -31,8 +32,10 @@ executable here too: the floor and the descent alternated until nothing moves, t the enumeration. So is the row filter: the rows no chain of sources leads outside the cut, tested against every set of rows of the two chains that lies inside the cut and holds its own sources; its controls are the filter without its closure, the prefix taken for the filtered -read, and a chain that follows a lowered chain read as asked. They run when this module builds -(`lake test`). +read, and a chain that follows a lowered chain read as asked. For the retire with no seal +(seeds 521 to 528) the controls are the sealed history taken for append invariant, a path's +identity used again after its retire, and a retired identity's history taken for empty. They run +when this module builds (`lake test`). -/ @[expose] public section @@ -361,7 +364,8 @@ is the same: positions count what an event filter hides. -/ || servedAt (l.map ev ++ t.map ev) (min c l.length) x == servedAt (l.map ev) (min c l.length) x) = true) 457 -/- Control: the state at the cut, without the seal, serves a key retired since. -/ +/- Control: the state at the cut, without the seal, serves a key retired since. The two readings +differ; the note's §6.2 says which a retire takes. -/ #eval refuted (∀ (l t : List (Fin 9)) (c : ℕ) (x : Fin 3), ((stateAt (l.map ev ++ t.map ev) (min c l.length) x).join == servedAt (l.map ev ++ t.map ev) (min c l.length) x) = true) 458 @@ -586,7 +590,7 @@ retire of the key it holds no version landed before the retire. -/ else sinceRetire ((t.map ev).take c) x) = true) 512 /- Control: the versions of a key inside the cut, without the seal, hold versions landed -before a retire. -/ +before a retire. That is the inheritance a fresh identity removes (524, 526). -/ #eval refuted (∀ (l : List (Fin 9)) (c : ℕ) (x : Fin 3), (((l.map ev).take c).filterMap (fun e ↦ if e.1 = x then e.2 else none) == historyAt (l.map ev) c x) = true) 513 @@ -712,4 +716,52 @@ that position. -/ == (resolve (foll es) x.val y.val 0, floorSv (sv1 m) 1 (resolve (foll es) x.val y.val 1))) = true) 520 +/- SNP-1: with no seal the history of a key at a cut inside the chain is unchanged by growth, a +retire of the key included. -/ +#eval survives (∀ (l t : List (Fin 9)) (c : ℕ) (x : Fin 3), + (landingsAt (l.map ev ++ t.map ev) (min c l.length) x + == landingsAt (l.map ev) (min c l.length) x) = true) 521 + +/- Control: the history the stricter seal serves is not: a retire after the cut empties it. -/ +#eval refuted (∀ (l t : List (Fin 9)) (c : ℕ) (x : Fin 3), + (historyAt (l.map ev ++ t.map ev) (min c l.length) x + == historyAt (l.map ev) (min c l.length) x) = true) 522 + +/- SNP-7: the history with no seal ends with what the stricter seal serves, and the history at +an earlier cut is a prefix of the history at a later one. -/ +#eval survives (∀ (l : List (Fin 9)) (c d : ℕ) (x : Fin 3), + ((historyAt (l.map ev) c x).isSuffixOf (landingsAt (l.map ev) c x) + && (landingsAt (l.map ev) (min c d) x).isPrefixOf (landingsAt (l.map ev) d x)) = true) 523 + +/- SNP-7: with a fresh identity at a retired path, the history of the identity a path holds at +a cut is the path's landings since its last retire inside the cut. -/ +#eval survives (∀ (l : List (Fin 9)) (c : ℕ) (x : Fin 3), + (landingsAt (lives (l.map ev)) c (x, retiresOf ((l.map ev).take c) x) + == sinceRetire ((l.map ev).take c) x) = true) 524 + +/- SNP-7: a retired identity keeps the life it had at every cut that holds its retire, whatever +lands after. -/ +#eval survives (∀ (l t : List (Fin 9)) (c : ℕ) (x : Fin 3), + (landingsAt (lives (l.map ev ++ (x, none) :: t.map ev)) (l.length + 1 + c) + (x, retiresOf (l.map ev) x) + == sinceRetire (l.map ev) x) = true) 525 + +/- Control: an identity used again after its retire inherits. Keyed by the path, the history +with no seal holds versions landed before a retire. -/ +#eval refuted (∀ (l : List (Fin 9)) (c : ℕ) (x : Fin 3), + (landingsAt (l.map ev) c x == sinceRetire ((l.map ev).take c) x) = true) 526 + +/- SNP-1: the identity a landing takes is a function of the events before it, and the history +of an identity at a cut inside the chain is unchanged by growth. -/ +#eval survives (∀ (l t : List (Fin 9)) (c : ℕ) (x : Fin 3) (n : Fin 4), + ((lives (l.map ev)).take c == lives ((l.map ev).take c) + && landingsAt (lives (l.map ev ++ t.map ev)) (min c l.length) (x, n.val) + == landingsAt (lives (l.map ev)) (min c l.length) (x, n.val)) = true) 527 + +/- Control: a retired identity's history is not empty at the cuts that hold its retire, as the +history of a sealed key is. -/ +#eval refuted (∀ (l t : List (Fin 9)) (c : ℕ) (x : Fin 3), + (landingsAt (lives (l.map ev ++ (x, none) :: t.map ev)) (l.length + 1 + c) + (x, retiresOf (l.map ev) x)).isEmpty = true) 528 + end Palace.Snapshot.Attack From 10ecf11341a89e37111fb9426f4e32ba6be06636 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 19:18:31 -0500 Subject: [PATCH 03/30] docs(design): a retire is the shallow removal, and six findings closed The owner decided D3 on 2026-11-11, against the note's recommendation: removal has two forms. A retire is the shallow one: the item leaves the present, its history stays readable at the cuts where it existed, no seal is applied, and a note written later at the same path takes a fresh identity. The purge of section 6.1 is the deep one. The note carries the decision wherever the design rested on the seal: decisions 4 and 6 of 1.2, the log's kinds and columns (no unseal, one horizon column), 3.6, the reads of 4.1 and 7, section 6.2 rewritten with what the decision costs and why the fresh identity removes the failure the stricter seal was recommended for, the laws of section 10, D3 recorded as decided, and the build order: the seal and the unseal leave SN-3, which becomes the two forms of removal and owns the fresh identity, since that changes what the writer admits, needs the log's positions and must be in force before SN-4 reads a history. The two seals stay as proved facts of the model. The six findings the review of the design left open: - an authored supersession reads the landings of its two notes: listed in 3.5 and filtered by two recorded log positions; - a second declaration of a pair rewrites its note: decl gets a chain-table row a declaration under a salted commitment, and 5.4 says the store is keyed by the pair; - the resolver's bound is the bound of the three resolved references and no position recorded for the filter; - the dispositions are read at a position on a verdicts chain, added to 3.1, and the filter's stores are named; - the CI witness's attestation of a commit is listed and filtered, and the one row the filtered read withholds at the head is stated; - the article's sentence on model output is the article's commit. Section 2.3's item 8 gains a second case, checked on the catalog: a new note at a path a rename left takes the identity that moved. Co-Authored-By: Claude Fable 5.2 --- docs/design-notes/dn-temporal-snapshot.md | 735 ++++++++++++++-------- 1 file changed, 477 insertions(+), 258 deletions(-) diff --git a/docs/design-notes/dn-temporal-snapshot.md b/docs/design-notes/dn-temporal-snapshot.md index bba4177e..3ea47972 100644 --- a/docs/design-notes/dn-temporal-snapshot.md +++ b/docs/design-notes/dn-temporal-snapshot.md @@ -38,6 +38,12 @@ warrant: null > checks, with what would check it named. Code claims were read on > `origin/main` at `e3e3ee47`. The article `papers/2026-11-10-temporal-snapshot/paper.tex` > states the same theorems with proof sketches and the references. +> +> Two things were added on 2026-11-11, after the design was merged, and each is marked where it +> stands. The owner decided what a retire does to the past (D3, §6.2), against the +> recommendation this note had made, and the note now carries the decision wherever the design +> rested on the seal. And six findings the review of the design left open are closed (§3.1, +> §3.5, §5.1, §5.4). The code cited for both was read at `f969904e`. ## 1. Purpose and scope @@ -75,23 +81,26 @@ as of a cut (dn-utility-field, open question 1). that no other chain reads (§3.3, §3.6).** A certificate verifies on every later state of the store and, under a collision-free digest, pins the prefix it digests. For the landing log that prefix is the commitments, so under a binding commitment it pins the events. It attests no - erasure, no seal and no grant: those are the present's, and an answer at a certified cut is the - same on two stores for one erasure, one grant and one set of seals. `[THEOREM: SNP-9]` + erasure and no grant: those are the present's, and an answer at a certified cut is the same + on two stores for one erasure and one grant. `[THEOREM: SNP-9]` 5. **Derived data is a function of the prefixes, held store by store in the cheapest of the equal ways (§5):** version-keyed rows selected by the log for vectors and lexical units, recomputation for the causal fiber and for the relations a note declares, kept generations for model output. `[THEOREM: SNP-5; INFERENCE per store]` -6. **The grant and the erasure are the present's (§6).** A narrower grant's snapshot is the - restriction of a wider one's; nothing erased is visible at any cut, and a read by path returns - a hole where the version at the cut is erased; a retired identity is sealed at every earlier - cut, its versions with its value. `[THEOREM: SNP-6, SNP-7]` -7. **A read under `as of` holds no event from after the cut it names (§7).** Where a store - cannot serve the cut asked, the cut read is the greatest consistent cut among the positions - the stores serve, and the answer names it chain by chain. A chain that no other chain reads is - lowered alone; a chain that others read takes its readers down with it, which is why a - recorded cut is kept off the chains that content reads, and why a row that reads a landing - without being a landing's own record, a pass attestation or a row of model output, is - withheld by a filter of the read and lowers no position (§3.5). `[THEOREM: SNP-8, SNP-10; +6. **The grant and the erasure are the present's (§6), and removal has two forms.** A narrower + grant's snapshot is the restriction of a wider one's; nothing erased is visible at any cut, + and a read by path returns a hole where the version at the cut is erased. A purge is the deep + removal: a hole at every cut. A retire is the shallow one: the item leaves the present, its + history stays readable at the cuts where it existed, no seal is applied, and a note written + later at its path takes a fresh identity. `[THEOREM: SNP-6, SNP-7; the owner's decision of + 2026-11-11 for the retire, D3]` +7. **A read under `as of` holds no event from after the cut it names (§7).** Where a store cannot + serve the cut asked, the cut read is the greatest consistent cut among the positions the stores + serve, and the answer names it chain by chain. A chain that no other chain reads is lowered + alone; a chain that others read takes its readers down with it, which is why a recorded cut is + kept off the chains that content reads, and why a row that reads a landing without being a + landing's own record, as a pass attestation, a row of model output and an authored supersession + do, is withheld by a filter of the read and lowers no position (§3.5). `[THEOREM: SNP-8, SNP-10; INFERENCE for the surface, falsifier SNF-4]` 8. **History is exact from the horizon, and the horizon is an event of the chain (§8).** A store that drops old generations reads every cut from its horizon on exactly, and a cut under @@ -134,9 +143,9 @@ cut. One of them keeps text, the rejected requests, and §6.1 names it for the p ### 1.4 What is proved, what is measured, what is open Proved, in `formal/Palace/Snapshot.lean` over `formal/Palace/Snapshot/Defs.lean`: SNP-1 to SNP-10 -as §10 states them, 175 theorems, eighteen of them the controls; attacked in -`formal/PalaceTest/Snapshot.lean` (seeds 430 to 520: forty-nine attacks, every one surviving -all 500 instances, and forty-two negative controls, each refuted). They are design theorems: no +as §10 states them, 193 theorems, twenty of them the controls; attacked in +`formal/PalaceTest/Snapshot.lean` (seeds 430 to 528: fifty-four attacks, every one surviving +all 500 instances, and forty-five negative controls, each refuted). They are design theorems: no code relies on them, so they have no row in `docs/LAWS.md` and no statement in `formal/Spec/`; §12 says when they enter the ledger. Some of what §6 and §7 require holds by the construction of the model and not by a theorem about the code: §10 says which, law by law. @@ -307,7 +316,12 @@ in §2.2 unless given]` an existing path keeps the stored identity, and a tombstoned row stays in the catalog (`catalog.py:103-121`, `:160-172`), so the version chain of the identity appends (`core/stores/versions.py:109-119`): a new note written at a deleted note's path has the - deleted note's versions under it. §6.2 seals them. + deleted note's versions under it. The same holds after a rename. The old path's row is + tombstoned with the identity that moved, the writer asks for an identity only where the path + has no row (`core/ingest/writer.py:372`, `:409`), and so a new note written at the old path + takes the identity that now lives at the new one: two active paths under one identity, which + the writer's rule R6 otherwise refuses. `[MEASURED §11 on the catalog]` §6.2 gives a note + written at a path with a past an identity of its own. ## 3. The cut @@ -326,6 +340,7 @@ prefix length of it. `[DERIVED from global-event-clock §2.2, generator g1]` | `decl` | authored supersessions | a sequence number a declaration | not built | | `staging` | the staging store | its generation | recorded | | `runs` | the run ledger, with the structural snapshot of a pass | a sequence number | recorded as insertion order | +| `verdicts` | the verdict ledger (`core/stores/verdicts.py:42-51`), which the dispositions are read by (§5.1) | its `seq`: signed with the verdict, strictly increasing, never given twice (`verdicts.py:135-139`) | recorded; a dropped verdict is a gap the store reports (`verdicts.py:171-181`), and a position is the rows at or under it | | `use` | the utility field's use log (dn-utility-field §3.1) | the tick | not built | | `cuts` | the recorded cuts (§3.3) | `seq` | not built; it reads every chain it certifies, and no other chain reads it | @@ -391,7 +406,7 @@ CREATE TABLE landing_chains ( CREATE TABLE landings ( chain INTEGER NOT NULL, -- landing_chains.chain seq INTEGER NOT NULL, -- the position in the chain, from 1, never given twice - kind TEXT NOT NULL, -- genesis | store | retire | move | unseal | horizon + kind TEXT NOT NULL, -- genesis | store | retire | move | horizon path_key BLOB, -- hmac-sha256(secret, source_path): the key a hole keeps source_path TEXT, -- NULL once purged doc_id TEXT, -- the identity the event belongs to; NULL once purged @@ -399,8 +414,7 @@ CREATE TABLE landings ( digest TEXT, -- NULL for a retire, and once purged title TEXT, -- NULL once purged att_head INTEGER, -- the head of att when the row was written; NULL before SN-2 - ref_lo INTEGER, -- a horizon: the horizon; an unseal: the first retire it lifts - ref_hi INTEGER, -- an unseal: the last retire it lifts + horizon INTEGER, -- a horizon row: the position it declares; NULL otherwise salt BLOB, -- 16 random bytes; NULL once purged commitment BLOB NOT NULL, -- sha256(salt, the row's fields): what the chain digests hash BLOB NOT NULL, -- sha256(the previous row's hash, commitment) @@ -414,16 +428,16 @@ CREATE INDEX landings_doc ON landings (chain, doc_id, seq) CREATE INDEX landings_closed ON landings (chain, closed_at) WHERE closed_at IS NOT NULL; ``` -**The kinds** are the catalog's writes. `store` is a landing (`record`). `retire` is the -tombstone of an identity no other active path holds. `move` is a tombstone that leaves the -identity at another path (the second half of a rename, which the writer tells from a delete by -the catalog, `writer.py:409-413`), the owner-gated re-key of an identity (`catalog.py:210-241`), -and the row that closes a path in one chain when a `record` gives it another class, its `store` -then landing in a chain of the new class. `genesis`, `unseal` and `horizon` are below, §6.2 and -§8. A purge is not a kind: it empties rows (§6.1). A `record` that changes nothing, the same -path, digest, title, class and identity as the path's open row, appends nothing: the log is of -the changes of the map, and the catalog's `updated_at` is a bookmark (the curated lane re-lands -an unchanged digest after a plane reset, `core/ingest/curated.py:66-82`). +**The kinds** are the catalog's writes. `store` is a landing (`record`). `retire` is the tombstone +of an identity no other active path holds. `move` is a tombstone that leaves the identity at another +path (the second half of a rename, which the writer tells from a delete by the catalog, +`writer.py:409-413`), the owner-gated re-key of an identity (`catalog.py:210-241`), and the row that +closes a path in one chain when a `record` gives it another class, its `store` then landing in a +chain of the new class. `genesis` and `horizon` are below and in §8. There is no kind that lifts a +retire: a retire seals nothing (§6.2). A purge is not a kind: it empties rows (§6.1). A `record` +that changes nothing, the same path, digest, title, class and identity as the path's open row, +appends nothing: the log is of the changes of the map, and the catalog's `updated_at` is a bookmark +(the curated lane re-lands an unchanged digest after a plane reset, `core/ingest/curated.py:66-82`). **Which chain a landing goes to.** The chain that holds the path's last event; for a path with no event, the newest chain of its class, opened if the class has none. So a relabel moves no row @@ -432,7 +446,7 @@ holds. **The commitment and the hash.** `commitment` is SHA-256 over the salt followed by the canonical JSON (keys sorted, no white space, UTF-8) of the object with the fields `chain`, `seq`, `kind`, -`source_path`, `doc_id`, `version`, `digest`, `title`, `att_head`, `ref_lo`, `ref_hi` and `at`. +`source_path`, `doc_id`, `version`, `digest`, `title`, `att_head`, `horizon` and `at`. `closed_at` is out, since it is written later, and so is `path_key`, which is an index key. `hash` is SHA-256 over the previous row's `hash` followed by the commitment; the first row's previous hash is 32 zero bytes. No row is ever deleted, by a purge or by a history window: both @@ -454,7 +468,7 @@ ledger, which reads as the end of the ledger's genesis (§8). **The genesis.** At the first open after the migration that fills `doc_id` (`catalog.py:77-92`), each class the catalog holds gets a chain: a `genesis` row, then the catalog's rows of the class in path order, an active path as one `store` and a tombstoned path -as a `store` of the digest it held followed by a `retire`, then a `horizon` row whose `ref_lo` +as a `store` of the digest it held followed by a `retire`, then a `horizon` row whose `horizon` is its own position. The order inside the block is not history, so the positions before the `horizon` are under it (§8). A class that first appears later opens its chain at its first landing, with a `genesis` and a `horizon` and nothing between. @@ -579,7 +593,10 @@ read. `[INFERENCE, falsifier SNF-3]` An event of one chain may read from an event of another: `R k i k' j` says the `i`-th event of chain `k` reads from the `j`-th of chain `k'` (the event clock's generators g2 and g3). The -references between the chains of §3.1 are these. `[ESTABLISHED: read off the writers]` +references between the chains of §3.1 are these. `[ESTABLISHED: read off the writers]` The +list is what a reading of the writers found, and the review of this note found two it had +missed, the witness's attestation and the supersession, which are in it now; SNF-16 is the +falsifier for the next one. - a landing reads from its attestation and, where the place keeps chains, its version row, by the order the writer lands them in (`core/ingest/writer.py:397-436`: the version, the @@ -589,6 +606,12 @@ references between the chains of §3.1 are these. `[ESTABLISHED: read off the wr - a citation edge reads from its commit and from the projection that wrote it; - a recorded cut reads from the prefix of every chain it certifies and from the record before it, and no row of another chain reads a recorded cut; +- the attestation of a verdict on a commit reads from the commit, and the sensor did not write + it. The CI witness appends to the ledger every landing reads an attestation whose input is a + commit's sha (`ops/ci_witness.py:112-121`, through `build_attestor`, + `core/attestation/attestor.py:94`); a deploy runs it for the head of main + (`ops/lifecycle/launcher.py:757-761`), and the code sensor reads the commits of main inside a + job of its own (`ops/code_sensor.py:404-418`), which may not have run yet; - the attestation of a pass reads from the landings of the notes the pass read. The dreamer's and the curator's attestations sit on the ledger the landings' attestations sit on, name the notes' digests as their inputs (`core/dreaming/dreamer.py:144-148`, `:223-227`; @@ -602,13 +625,17 @@ references between the chains of §3.1 are these. `[ESTABLISHED: read off the wr two endpoint digests; - a claim op reads from the note or the artifact its `claim_id` names, and a supersede from the conclusion artifact the same call wrote, its `related_id` (`core/stores/claim_ops.py:45`, - `:161-163`); a verdict's disposition reads from the claim or artifact it is about - (`core/verdict/dispositions.py:59-64`). + `:161-163`); a verdict's disposition reads from the verdict and from the claim or artifact it + is about (`core/verdict/dispositions.py:59-64`); +- an authored supersession reads from the landings of the two notes it names. Both are + authored content digests (`core/stores/authored_supersession.py:106-107`), resolved among + the catalog's active paths when the owner declares it (`ops/supersede.py:42-50`) or taken + from the two items a founding sequence has just landed (`core/ingest/founding.py:118-131`). The first four are **resolved**: the resolver follows them, and the cut read is consistent for them. Three of them join chains of §3.1. A citation edge is a row of no chain: it is read by its stamps, which are positions on `repo` and `att` (§5.1), so a cut that holds its stamps holds its -sources. The last four are **filtered**: the resolver does not follow them, and a row that has one +sources. The last six are **filtered**: the resolver does not follow them, and a row that has one is served at a cut only when its sources are. Both are taken up below, after the definition. A causal edge reads from the turn that witnessed it and, when it ends at a commit, from the @@ -637,15 +664,16 @@ fact whose sources lie after the cut, every cross-chain reference closed. `[THEO So ING-7's invariant, that a key implies its rows, holds at every consistent cut and not only at the head: a cut that holds a landing holds its attestation and its version. `[DERIVED]` -**Where the resolved references are recorded.** The resolver has to know, for an event, where -its sources lie. A landing records the head of `att` at its writing (`att_head`); an attestation -of a commit names the commit; a recorded cut carries its whole frontier. With one writer a row's -sources were all written before it, so the head at its writing bounds them, the bound rises -along the chain, and it is sound: a cut consistent for the recorded bounds is consistent for the -true references they bound (`Consistent.of_bound`). It can only make fewer cuts consistent. The -theorem's hypothesis is a recorded bound at or above every true reference, so it speaks of the -resolved references and of no other. `[THEOREM: SNP-8; DERIVED from the one-writer rule, -dn-ingress D3, for the bound]` +**Where the resolved references are recorded.** The resolver has to know, for an event, where its +sources lie. A landing records the head of `att` at its writing (`att_head`); the sensor's +attestation of a commit names the commit; a recorded cut carries its whole frontier. These three are +the bounds of the resolved references, and the resolver reads no other. With one writer a row's +sources were all written before it, so the head at its writing bounds them, the bound rises along +the chain, and it is sound: a cut consistent for the recorded bounds is consistent for the true +references they bound (`Consistent.of_bound`). It can only make fewer cuts consistent. The theorem's +hypothesis is a recorded bound at or above every true reference, so it speaks of the resolved +references and of no other. `[THEOREM: SNP-8; DERIVED from the one-writer rule, dn-ingress D3, for +the bound]` **Rows that are filtered, not resolved.** The other references must not be given to the resolver. A pass attestation sits on `att`, which every landing reads, and it reads landings. @@ -653,7 +681,11 @@ Resolved, that reference would put `att` below the first pass that read a landin cut, and every landing chain attested after that pass would fall with it: a landing chain read low behind a history window would take the other landing chains to the positions they had when that pass ran, which is the cascade of a record kept on the ledger, through a pass -(`Witness.pass_drags`). So the closure of these references is kept row by row. A row is +(`Witness.pass_drags`). A witness's attestation of a commit is the same case from the other +side: it sits on `att` and reads a commit the ledger may not hold yet, so resolved it would make +a record taken at a trough between a deploy and the sensor's job inconsistent, and the resolver +would put `att` under the witness's row and every landing chain attested after it with it. So +the closure of these references is kept row by row. A row is **withheld** at a cut when it fails a test of its own, when a source of it lies outside the cut, or when a source of it is withheld (`Withheld`); the read at a cut is the rows inside the cut that are not withheld (`Kept`). `[THEOREM: SNP-8 for the control; INFERENCE for the choice, @@ -666,13 +698,27 @@ falsifier SNF-16]` What a row's sources and its own test are, store by store: or under it, so the bound can only withhold more; it is a position and names no digest, so a purge or a history window, which empty rows and move no position, change nothing in what is withheld. The ledger is read by sequence number with those rows left out. +- **A witness's attestation of a commit:** an attestation whose input is a commit's sha and + whose writer is not the sensor, which today is the CI witness's. Its chain-table row records + the commit. It is withheld when the commit is not inside the cut on `repo`, which is one + ancestry test, or one lookup of the commit ledger on a history that is a line (§3.1). - **A row of the run ledger.** A run's chain-table row records the same pairs, and a dream claim is served when its run is. - **An interpreted artifact and an interpreted relation edge.** §5.4: the attestation the row names is kept at the cut, and every digest its sources reach is a head at the cut and is not - erased or sealed. + erased. - **A claim op and a disposition.** The note or the artifact it names is served at the cut, - and for a supersede the conclusion artifact as well. + and for a supersede the conclusion artifact as well. A disposition is read at the cut's + position on `verdicts` (§3.1, §5.1). +- **An authored supersession.** Its chain-table row records, at the declaration, the position + in the log of each of the two notes' open rows, a chain and a `seq` each, found through the + catalog's index by digest (`core/stores/catalog.py:45`). It is served when the cut read holds + both positions and neither row is a hole. The positions name no digest, so a history window + changes nothing in what is withheld, and a purge of either note empties the supersession's + own row (§6.1). A row the store holds when the columns are added is given the positions of + the earliest `store` rows of its two digests that the log holds, and for a digest the log + does not hold, the head of the newest chain of the note's class at the migration: a bound + that can only withhold more. What is proved of the filtered read, for any reads-from relation and any test. `[THEOREM: SNP-8, with SNP-1 and SNP-2 for the last item]` @@ -685,21 +731,27 @@ SNP-8, with SNP-1 and SNP-2 for the last item]` - It never withholds a row all of whose references are resolved. The landings, the attestations of landings and of commits, and the commits read only one another, by resolved references, so at a cut consistent for those references every one of them inside the cut is kept - (`kept_of_resolved`). The filter takes rows out of `att`, `runs` and the `interp` chains and - takes no landing. + (`kept_of_resolved`). The filter takes rows out of `att`, `runs`, the `interp` chains, `decl` + and the dispositions, and takes no landing. - At a cut consistent for every reference, where every row passes its test, it withholds - nothing and the read is the prefix (`kept_iff_of_consistent`). For the attestations and the - runs, whose test is empty, that is the case at the head, since a store holds the sources of - its own rows, and at a recorded cut every position of which is served. + nothing and the read is the prefix (`kept_iff_of_consistent`). For the pass attestations and + the runs, whose test is empty, that is the case at the head, since a pass is written after + the landings it read, and at a recorded cut every position of which is served. It is not the + case at the head for one row: a witness's attestation of a commit the sensor has not read + yet, whose commit is not in the ledger until the sensor's next job. Until then the filtered + read at the head cut withholds it and the present read returns it. No answer shows the + difference, since `as of "head"` is the present read (§3.4); a test that compares the two + reads at the head leaves that row out (§10, SNP-8). - For a test that does not depend on the cut it is monotone, a row kept at a cut being kept at every later one, and it is append invariant (`Kept.mono`, `kept_grown_iff`). -So the cut read is consistent for the resolved references, and the read at it is filtered for -the rest. That read is a derived view of the prefixes (SNP-5), and on `att`, `runs` and the -`interp` chains it is not the prefix. The control is the store of `Witness.pass_drags` with the -pass's reference filtered: the landing chain behind its window is lowered alone, the prefix at -that cut holds a pass whose landing is outside it, and the filtered read withholds the pass and -keeps the attestation after it and the other class's landing (`Witness.pass_withheld`). +So the cut read is consistent for the resolved references, and the read at it is filtered for the +rest. That read is a derived view of the prefixes (SNP-5), and on `att`, `runs`, the `interp` +chains, `decl` and the dispositions it is not the prefix. The control is the store of +`Witness.pass_drags` with the pass's reference filtered: the landing chain behind its window is +lowered alone, the prefix at that cut holds a pass whose landing is outside it, and the filtered +read withholds the pass and keeps the attestation after it and the other class's landing +(`Witness.pass_withheld`). **The resolver.** A name that selects a recorded cut needs none while every chain serves the record's positions: the record is consistent. Otherwise it is two steps alternated until @@ -708,7 +760,14 @@ nothing moves: 1. the floor: each chain's position is lowered to the greatest position at or under it that the chain serves (§7.1); 2. one pass of the descent: each chain's position is lowered to the first event inside the cut - whose recorded bound lies outside it. + whose recorded bound, for a resolved reference, lies outside it. + +The bound the descent reads is one of three and no other: `att_head` on a landing, the commit +on the sensor's attestation of a commit, the frontier on a record. A chain-table row also +records positions for the filter: the landing heads on a pass attestation and on a run, the +commit on a witness's attestation, the two landing positions on a supersession. The descent +never reads those. Followed, they are the cascade the filter exists to prevent +(`Witness.pass_drags`). A round that moves anything lowers a position, so there are at most as many rounds as the frontier has positions. Neither step alone is enough, in either order: the descent leaves the @@ -728,9 +787,13 @@ The certificate of a cut is, for each chain, the digest of its prefix under the **Which chains have a hash.** A landing chain from SN-1, as the `hash` of the row at the position. `repo` always: the commit's sha is git's own chain. `chat`, `att`, `staging` and `runs` from SN-2, as the running hash of the chain table added beside each. The `interp` chains, -the claim ops among them, and `decl` from SN-6, which gives each a sequence number and a -running hash over its rows' content, the wall bookmark left out; and `use` with the stage that -builds the field. A record carries a digest +the claim ops among them, `decl` and `verdicts` from SN-6. An `interp` chain gets a sequence +number and a running hash over its rows' content, the wall bookmark left out. `decl` gets a +chain-table row at every declaration, a second declaration of a pair included, and its hash +runs over a salted commitment to each row as the landing log's does, so no row a hash covers is +rewritten when a note is declared again (§5.4) and a purge can empty one (§6.1). `verdicts` has +its position already and gets the running hash. And `use` with the stage that builds the +field. A record carries a digest for each chain that has a hash when it is taken and a null for the others, and `verify` says which chains it checked. Until a chain is hashed, a recorded cut fixes its position and nothing about its rows, and the two conclusions below do not reach a view that reads it. `[INFERENCE]` @@ -749,12 +812,14 @@ about its rows, and the two conclusions below do not reach a view that reads it. - **What it does not attest.** An erasure: a store verifies a certificate after a purge exactly when it did before (`verifies_purge_iff`), so a backup taken before a purge and restored later verifies every certificate and still holds what was purged. A restore therefore has to apply - again the purges recorded since, which §6.1's attestation of a purge makes listable. A seal: a - retire written after a certified cut changes what is served at it, and the certificate still - verifies (`Witness.seal_not_certified`). The grant, and the identity of the embedder and the - tokenizer (D5). So an answer at a recorded cut is the same on two stores that verify it for - one erasure, one set of seals, one grant and one derivation identity, and not otherwise; for - the grant and the erasure together that is `Verifies.shown_eq`. + again the purges recorded since, which §6.1's attestation of a purge makes listable. The + grant, and the identity of the embedder and the tokenizer (D5). So an answer at a recorded cut + is the same on two stores that verify it for one erasure, one grant and one derivation + identity, and not otherwise; for the grant and the erasure together that is + `Verifies.shown_eq`. A seal would be a third thing a certificate does not attest, since a + retire written after a certified cut would change what is served at it + (`Witness.seal_not_certified`); the design applies none (§6.2), so a retire after a cut + changes nothing read at it. - **Cheap.** A certificate extends over the events since an earlier one (`certify_digest_readBetween`), and the meet and the join of two certified cuts are certified from the two certificates alone, chain by chain the earlier or the later digest (`certify_inf`, @@ -783,7 +848,7 @@ measured: | ledger | `read_at(c)` | `read_between(a, b)` | index | cost | |---|---|---|---|---| | landing log, a chain | the rows with `seq ≤ c`; `state_at` of one path: its last event at or under `c`, by its key; every head of a class: the `store` rows with `seq ≤ c` not closed at or under `c`, over the class's chains | the rows with `a < seq ≤ b` | the primary key, `landings_path`, `landings_closed` | one path 3 µs through `landings_path`, and 1.4 µs for its keyed hash; 1,000 positions 0.64 to 0.69 ms; every head §4.2 `[MEASURED §11]` | -| a document's version chain | the log's rows of the identity at or under `c`, after its last retire (§6.2) | the same rows in the range | `landings_path` where the identity is the path, `landings_doc` where it is not | 9 µs for seven versions through the index, and 49 to 57 ms when the planner takes the primary key, so the statement names the index `[MEASURED §11]` | +| a document's version chain | the log's `store` rows of the identity at or under `c` (§6.2) | the same rows in the range | `landings_path` where the identity is the path, `landings_doc` where it is not | 9 µs for seven versions through the index, and 49 to 57 ms when the planner takes the primary key, so the statement names the index `[MEASURED §11]` | | raw objects | the object of the digest the log names at `c` | the objects the delta names | none: content-addressed | one file read, the object's bytes | | chat log | a session's turns whose chain number is at or under `c` | the turns numbered in the range | the chain table's key and its `(session, turn)` | a range of an integer key: of the order of the log's 0.7 ms a thousand rows | | attestations | by id, as today; in order, the chain table at or under `c` | a range of the chain table | the chain table | the same order, where `all()` sorts the ledger by wall time and `producers_of` decodes every record today (`core/attestation/store.py:127-132`, `:159-165`) | @@ -847,8 +912,9 @@ table is built that way, and §5.2 says why its versions are not the snapshot. | chat events, causal edges | the transcript as retained at the cut, and the commits inside the cut | recomputed at the cut, the present rows a cache of the head | 6 ms a session of 2,000 records `[MEASURED §11]`; no bytes | a sentence that walks the causal fiber at a past cut over a second on a real instance (SNF-5): then generations, written with a diff | | interpreted artifacts with their hyperedges, interpreted relation edges | a model's output: of nothing that can be computed again | generations, the replaced row archived with its interval | one archived row a replacement, which is thrown away today; how often a row is replaced is not measured | a measured churn so low that declaring them outside the snapshot loses nothing | | the relations a note declares | the note's text at a version, and the titles the catalog resolves at the cut | recomputed from the heads at the cut | one parse of a note's properties a head that has any, kept in a memo by digest; no bytes | nothing | -| claim ops, authored supersessions | nothing: they are appended, keyed by their content | a position a first insert; the read at a cut is the rows at or under it, a claim op served with what it names (§3.5) | one integer a row | nothing | -| verdict dispositions | nothing: one row a verdict, appended (§2.2) | the key is the position: the read at a cut is the rows whose `verdict_seq` is at or under the cut on the verdicts' own sequence, each served with the claim it is about (§3.5) | nothing new | nothing | +| claim ops | nothing: they are appended, keyed by their whole content | a position a first insert; the read at a cut is the rows at or under it, each served with what it names (§3.5) | one integer a row | nothing | +| authored supersessions | nothing: the owner's declarations, keyed by the pair, with a note a second declaration of the pair replaces | a chain-table row a declaration, with the note and the log positions of the two notes; the read at a cut is each pair's last declaration at or under it, served when the cut read holds both positions and neither is a hole (§3.5, §5.4) | one chain-table row a declaration: an integer, the pair, the note, two positions, a salt and two hashes | nothing | +| verdict dispositions | nothing: one row a verdict, appended (§2.2) | the key is the position: the read at a cut is the rows whose `verdict_seq` is at or under the cut's position on `verdicts` (§3.1), each served with the claim it is about (§3.5) | nothing new | nothing | | the similarity backbone | the vectors of the support | recomputed, as today | nothing | nothing | | citation readings | the tree at the commit and the extractor that projected it | append-only rows, as built, each stamped with the extractor's version and the position on `att` of the projection that wrote it; the reading of a commit at a cut is its rows stamped at or under the cut | one integer and a short string a row, on 3,029,562 rows over 1,487 commits at 567 bytes a row in the repository's records | the store's size: then a row valid over a range of commits (SN-b) | | code memberships | git's blob at the path | version-keyed by blob; git's tree selects the version | nothing new | nothing | @@ -931,18 +997,26 @@ the catalog. At a cut it is recomputed: for each head at the cut that has such a property parsed from the raw object the log names, the title resolved among the heads at the cut. Nothing is stored and the edge has its note's class. `[DERIVED from SNP-5]` -**Claim ops and authored supersessions** are not rewritten in place. Each row is keyed by its -whole content (§2.2), so a second write stamps a bookmark and changes nothing else. The +**Claim ops and authored supersessions** are appended sets that lack a position, and they differ in +their key. A claim op is keyed by its whole content (§2.2), so a second write stamps a bookmark and +changes nothing else. An authored supersession is keyed by the pair, and its note is a column +outside the key, so a second declaration of a pair replaces the note with the bookmark +(`core/stores/authored_supersession.py:113-119`, `:159-161`; §2.2 says what that loses today). The supersessions are the owner's declarations. The claim ops are appended by a store that calls no model (`core/stores/claim_ops.py:14-15`), and what it appends is by design a model's proposal: -extracting the operations from a dialogue is a model task behind an analyzer whose default -proposes none (`core/kernel/recursion_ops.py:44-46`), and at `e3e3ee47` no caller outside the -tests applies one. So the claim ops are rows of the class `interpreted` (§3.1). The storage -choice does not depend on who proposes them: both stores are append-only sets that lack a -position, each gets a sequence number at a row's first insert, and the read at a cut is the -rows at or under it. A claim op is further filtered by what it names, the claim it acts on and, -for a supersede, the conclusion artifact the same call wrote (`claim_ops.py:45`, `:161-163`): -it is served when those are (§3.5). `[DERIVED]` +extracting the operations from a dialogue is a model task behind an analyzer whose default proposes +none (`core/kernel/recursion_ops.py:44-46`), and at `e3e3ee47` no caller outside the tests applies +one. So the claim ops are rows of the class `interpreted` (§3.1). The storage choice does not depend +on who proposes them. A claim op gets a sequence number at its first insert, and the read at a cut +is the rows at or under it. A supersession gets a row of its chain table at every declaration: the +sequence number, the pair, the note and the positions §3.5 gives, under a salted commitment the +chain's hash runs over. The store's own row stays the pair's latest declaration, the head's cache; +the read at a cut is each pair's last declaration at or under it. So no row that a running hash +covers is rewritten, in either store. Both are further filtered by what they name. A claim op is +served when the claim it acts on is and, for a supersede, the conclusion artifact the same call +wrote (`claim_ops.py:45`, `:161-163`). A supersession is served when the cut read holds the landings +of both its notes (§3.5), so a read of the active projection at a cut marks no note historical by a +note the cut does not hold. `[DERIVED]` **Interpreted artifacts and interpreted relation edges** are model output: written by a pass that calls a model or by a `link` request (`core/relations.py:192-210`, @@ -976,8 +1050,9 @@ on its own chain; the attestation it names, if any, is kept at the cut on `att`, pass attestation is more than lying under the cut (§3.5); every digest its sources reach is some path's head at the cut, where an artifact's sources are followed through the artifacts it names, each as it stood at the cut, down to digests (the -store refuses a cycle, `derived.py:186-189`); and none of those digests is erased or sealed -(`mem_serve_iff`). `[THEOREM: SNP-7 for the erasure, SNP-8 for the closure; DERIVED for the +store refuses a cycle, `derived.py:186-189`); and none of those digests is erased +(`mem_serve_iff`). A source retired since the cut withholds nothing: the retire is shallow +(§6.2). `[THEOREM: SNP-7 for the erasure, SNP-8 for the closure; DERIVED for the rest]` This is the row filter of §3.5: it withholds a row and lowers no position. Until SN-6 builds it the `interp` chains serve two positions, the empty prefix and the head (§7.1). Lowering them moves no chain outside them but the chain of records, which follows (§7.1): the @@ -1098,6 +1173,7 @@ reaches today: | dream claims of the run ledger | keep the digests a claim rests on and its surface text (`core/stores/runledger.py:90-97`) | the claim's support and text nulled, the row kept | | staging rows | keep the content digest and the payload (`core/stores/staging.py:130-131`) | the digest and the payload nulled, the row and its generation kept | | claim ops | keep the warrant's text (`core/stores/claim_ops.py:40-48`) | the ops on a removed artifact removed | +| authored supersessions | keep both digests and the note (`core/stores/authored_supersession.py:112-120`) | the store's rows that name the digest removed; in the chain table the pair, the note and the salt nulled, the commitment and the hash kept | | rejected requests of the ingress spools | keep the request's text (`core/ingest/ingress.py:20-27`, `:505-517`) | the files that hold the purged text removed | | the attestation ledger | still names the digest `[MEASURED §11]` | decision D9 | | a deletion attestation | none is written (`core/attestation/store.py:3-6` says one is) | one, of action `purge`, naming the positions emptied and no digest | @@ -1108,55 +1184,125 @@ is stage SN-3, and it lands before any of those stores is read at a past cut (§ attestation of a purge lists the positions it emptied, which is what lets a backup restored from before it be purged again (§3.6). -### 6.2 A retire seals +### 6.2 A retire is the shallow removal A vault delete is a tombstone: the catalog's row goes inactive and the raw object stays -(`catalog.py:160-172`). The requirement is that a tombstoned item does not come back through a -snapshot either. Two rules do that for the value served at a cut, both proved, and they are -ordered. - -- **The stricter seal** (`servedAt`). A retire among the events past the cut closes the cut for - that identity. Once the chain retires an identity, no cut before the retire serves it - (`servedAt_append_of_retire`); growth that does not retire it changes nothing - (`servedAt_append_of_no_retire`); so growth changes a served value only by removing it - (`servedAt_of_append`). -- **The looser seal** (`servedNow`). An identity is withheld at every cut exactly while it is not - live at the head. It serves everything the stricter one serves (`servedNow_of_servedAt`), keeps - an identity that is retired now out of every cut (`servedNow_of_not_live`), and is lifted by a - later landing, which brings the past back (`Witness.servedNow_restores`). `[THEOREM: SNP-7]` - -This note takes the stricter seal, keyed by identity, with an `unseal` event that only the owner -writes. `[INFERENCE, falsifier SNF-10]` The reason is in the code: a new row's identity is its -path unless it declares one, and a re-record of a path keeps the identity it has -(`catalog.py:103-121`), so a different note written later at a deleted note's path has the -deleted note's identity, and under the looser seal it would bring the deleted note's versions -back at the earlier cuts. - -**The seal covers the versions, at every cut.** Sealing the value is not enough. The new note's -identity is the deleted note's, so its chain of versions holds the deleted note's versions -(§2.3, item 8), and a read of the history would return them at the head and at every cut after -the new note landed, where no value is sealed. So the history served of an identity at a cut is -defined with the seal (`historyAt`): nothing where the identity is sealed, else its landings -inside the cut that no retire follows. It ends at the value served there -(`getLast?_historyAt`); a retire after the cut empties it (`historyAt_append_of_retire`); and at -every cut after a retire, the head included, it holds only versions landed after that retire -(`historyAt_of_retire_inside`, `sinceRetire_append_retire`). `[THEOREM: SNP-7]` This changes a -read at the head too: `trace` of a note written at a deleted note's path stops at the delete. -The versions store keeps its rows; the read withholds them. - -The seal is by identity and not by path so that a rename seals nothing: the old path's tombstone -is a `move` (§3.2). The cost of the stricter seal is also in the code. The sync retires every -stored path its source no longer lists (`ingress/sync_vault.palace:7-15`, -`core/ingest/writer.py:499-519`), and a source whose directory is missing lists no file -(`core/ingest/readers.py:126-137`), so a vault that is missing at a sync seals every note's -past. The owner lifts it with one `unseal` row, whose `ref_lo` and `ref_hi` name the range of -positions of the retires it lifts; an `unseal` of one identity carries the identity and the -position of its retire in both. - -The seal is read off the whole chain, the present, and off no prefix of it: one more seek, the -position of the identity's last retire that no later `unseal` names. At the head no value is -sealed (`servedAt_length`), and the history served is the identity's landings since that retire -(`historyAt_length`). +(`catalog.py:160-172`). What that does to the past was decision D3. This note recommended a +seal; the owner decided otherwise on 2026-11-11, after the design was merged, and this section +states the decision and what follows from it. Removal has two forms. + +- **A retire is the shallow form.** The item leaves the present: from the retire on, no read + returns it as live. Its history stays readable at the cuts where it existed. No seal is + applied to a retire, and a note written later at the same path takes a fresh identity, so + that it does not inherit the retired note's versions. +- **A purge is the deep form** (§6.1): a hole at every cut. Every derived answer at a past cut + becomes what it is on a store that never held the item's content: a kept row that rests on it + is not served, the statistics of a mask are computed without it, and what is recomputed is + recomputed without it (`erased_invisible`, `mem_serve_iff`). So the answers about the item's + neighbourhood at past cuts change with a purge, and that is intended. What survives is the + record that a purge happened, its attestation and the positions it emptied, and not the + content. + +**What a read at a cut returns of a retired item.** The value of an identity at a cut is the +one it held there: its last event at or under the cut, a `store` or nothing (`stateAt`). The +history of an identity at a cut is its landings inside the cut (`landingsAt`). Both are derived +views of the prefix, so a retire written after a cut changes neither (`stateAt_append`, +`landingsAt_append`), the history at an earlier cut is a prefix of the history at a later one +(`landingsAt_mono`), and at the head the history is every landing of the identity +(`landingsAt_length`). `[THEOREM: SNP-1, SNP-2, SNP-4]` Two things the seal cost are gone with +it. A read at a cut no longer consults the present for a later retire, which was one more seek +a keyed read. And a certificate now pins what is served of a retired item: with a seal, a +retire after a certified cut changed the answer at it and the certificate could not show that +(§3.6). + +**The two seals remain proved, and the design applies neither.** They are facts of the model +and stay in the library as what a seal would do. + +- The stricter seal (`servedAt`, `historyAt`). A retire among the events past the cut closes + the cut for that identity: no cut before the retire serves it or any version of it + (`servedAt_append_of_retire`, `historyAt_append_of_retire`), and growth changes what is + served only by removing it (`servedAt_of_append`). +- The looser seal (`servedNow`). An identity is withheld at every cut exactly while it is not + live at the head; a later landing lifts it and brings the past back + (`servedNow_of_servedAt`, `Witness.servedNow_restores`). + +The history with no seal holds everything the stricter seal serves, as its end +(`historyAt_suffix_landingsAt`): the seal only withheld. The control for the choice is the +retire that empties a served history under the seal and leaves the unsealed one as it was +(`Witness.seal_empties_history`). `[THEOREM: SNP-7]` + +**The fresh identity.** The stricter seal was recommended for one failure, and the fresh +identity removes that failure at its source. A new row's identity is its path unless it +declares one, and a re-record of a path keeps the identity the path has (`catalog.py:103-121`), +a tombstoned row included. So a different note written later at a deleted note's path has the +deleted note's identity, and its chain of versions holds the deleted note's versions (§2.3, +item 8). With one identity used again, the history with no seal returns the deleted note's +versions under the new note, at the head and at every cut after it landed +(`Witness.reused_identity_inherits`); the looser seal brought them back at the earlier cuts as +well; and the stricter seal hid them by sealing the whole past of the identity. The decision +takes the fourth way: the new note is another identity. + +The rule is on the first bind. A `store` at a path that has an open row lands under that row's +identity, as today. A `store` at a path with no open row is a first bind, whether the path has +no row, a tombstoned one or only emptied ones: the identity is the one the item declares, or +the one held at a vanished path with the same bytes (the writer's rule R6, +`core/ingest/writer.py:438-481`), and otherwise the path's own when the log holds no event of +the path, and a fresh one when it does. The fresh identity is named by the path and the +position of the path's last event in the log, `#.`: the retire, the `move` or +the hole that closed it. A position is given once, so the name is new. It is a function of the +rows already written, so a landing repeated after a crash before its key takes the identity +the first attempt took and appends no second version (ING-7). It differs from its path, so +`landings_doc` indexes it (§3.2), and R6's refusal of an identity that another active path +holds applies to it as to a declared one. + +On the model a chain of landings and retires at paths is keyed again by identity (`lives`): the +path with the number of the path's retires before the event. `[THEOREM: SNP-1, SNP-7]` + +- The identity a landing takes is a function of the events before it (`lives_take`). +- The history of the identity a path holds at a cut is the path's landings since its last + retire inside the cut: no version of an identity retired at the path is in it, at the head or + at any cut (`landingsAt_lives_present`). This is what the stricter seal's history gave where + it served anything (`historyAt_of_retire_inside`), with nothing sealed. +- A retired identity keeps the life it had and gains nothing: at every cut that holds its + retire, whatever lands at the path afterwards, its history is the landings of that life + (`landingsAt_lives_of_retire`), and at a cut inside the chain it is unchanged by any growth + (`landingsAt_lives_append`). Under the stricter seal the same retire emptied it. + +What the model leaves to the code: the name of an identity, an identity a note declares, and a +rename, which moves an identity between paths. The retire is by identity and not by path, so a +rename retires nothing: the old path's tombstone is a `move` (§3.2). A new note written at a +path a rename left is a first bind like any other, which closes the second case of §2.3's item +8, where today it takes the identity that moved. + +**What the decision costs.** + +- **A note that goes and comes back is two identities.** The sync retires every stored path + its source no longer lists (`ingress/sync_vault.palace:7-15`, + `core/ingest/writer.py:499-519`), and a source whose directory is missing lists no file + (`core/ingest/readers.py:126-137`), so a vault that is missing at a sync retires every note, + and the next sync lands each again under a fresh identity. Nothing is sealed and nothing is + lost: at every cut before the retire the old identity reads as it did, and the log's rows of + a path, read by its key, run across both lives. What is lost is continuity at the head: + `trace` of a returned note starts at its return. Under the stricter seal the same event + sealed every note's past until the owner lifted it. A note that declares its identity is the + exception by its own statement: it binds that identity again when it returns, and its + history at a cut is all its landings inside the cut, on both sides of the retire. Joining + two identities of one path is not designed here: the owner-gated re-key + (`catalog.py:210-241`, `core/stores/versions.py:132`) refuses to merge two chains. It is + parked as SN-l, with SNF-10 as its re-entry. +- **A delete withdraws nothing from the past.** A retired note is read at the cuts where it + existed by any asker whose grant reads its class. An item that must not be read at a past cut + is purged; that is what the deep form is for. +- **The rule is not retroactive.** An identity bound before the rule keeps the versions it has, + the ones it inherited included: the log's commitments cover the identity of every row, and + the versions store has no write that splits a chain. From the stage that builds the rule on, + no chain continues across a retire unless the note declares it. The stage's migration counts + the identities that have a `store` after a `retire` in the log, so the owner knows how many + histories at the head still run across a delete. + +**At the head.** `trace` of a note written at a path with a past starts at that note's first +landing, where today it runs back through the deleted note's versions. This is the one change +to a read at the head, and it was owed under every alternative (D3). ### 6.3 The grant is the asker's now @@ -1258,7 +1404,8 @@ position it serves whose events read the lowered chains inside their new positio The design is arranged so that, among the references the resolver follows, the second and the third case are the only ones that occur at a recorded cut. Those references are a landing's to -`att`, an attestation's to `repo` and a record's to every chain it certifies (§3.5). Neither +`att`, the sensor's attestation's to `repo` and a record's to every chain it certifies (§3.5). +Neither `att` nor `repo` has a horizon that moves: the attestation ledger is never pruned (§9.2) and `repo` is git's. Every chain that can fail to serve a recorded position, a landing chain behind a history window, a chain that keeps no past yet, the use log behind its horizon, is read @@ -1268,14 +1415,14 @@ position it serves; the chain of records is lowered with them, to its last recor position of which the cut read holds (`Witness.record_follows`); and every other chain is read as recorded. `[DERIVED]` -That is a statement about positions, and it holds for the resolved references only. A row that -reads a lowered chain through a filtered reference, a pass attestation, a dream claim, an -interpreted row or a claim op, leaves the read by the filter of §3.5 and moves no position: at -a cut where a landing chain is read at its empty prefix, every pass attestation that read a -landing of that chain is withheld, with the artifacts that name it, and `att` keeps its -position. Resolving those references instead would bring the cascade back through `att` -(`Witness.pass_drags`, against `Witness.pass_withheld`). `[THEOREM: SNP-8 for the two -controls]` +That is a statement about positions, and it holds for the resolved references only. A row that reads +a lowered chain through a filtered reference, a pass attestation, a dream claim, an interpreted row, +a claim op or an authored supersession, leaves the read by the filter of §3.5 and moves no position: +at a cut where a landing chain is read at its empty prefix, every pass attestation that read a +landing of that chain is withheld, with the artifacts that name it and the supersessions between +notes of that chain, and `att` keeps its position. Resolving those references instead would bring +the cascade back through `att` (`Witness.pass_drags`, against `Witness.pass_withheld`). `[THEOREM: +SNP-8 for the two controls]` **When the cut read falls.** The monotonicity needs the served positions to grow. They do not always. A store that keeps no past serves its empty prefix and its head, and loses its old head @@ -1319,7 +1466,7 @@ The mode of a clause follows from its scope (`core/query.py:273-281`). |---|---|---|---| | semantic | `near`, `diffuse S`, `reach S`, `relate` | the heads of the clause's classes, from the log; their vectors by content address and the lexical index for the pending ones (§5.2, §5.3); the backbone recomputed among them | SN-4; `relate` SN-6 | | structural | `reach F`, `diffuse F`, `walk` over `F` | the citation reading of the cut's commit, as projected at or under the cut (§5.1) | today for a commit projected once; SN-4 for one projected again | -| temporal | `trace`, `reach D`, `walk` over `D`, `changed` (§7.4) | the history served of the identity at the cut (§6.2): the log's rows of the identity at or under the cut, after its last retire | SN-4; `changed` SN-8 | +| temporal | `trace`, `reach D`, `walk` over `D`, `changed` (§7.4) | the history of the identity at the cut (§6.2): the log's `store` rows of the identity at or under the cut | SN-4; `changed` SN-8 | | causal | `reach C`, `walk` over `C`, `witness` | the causal fiber recomputed at the cut (§5.5); an attestation kept at the cut on `att` (§3.5) | SN-5 | | species | at a cut | @@ -1343,7 +1490,8 @@ The mode of a clause follows from its scope (`core/query.py:273-281`). returns `HEAD`'s blob (§2.1). A note or a dialogue turn: the raw object of the digest the log names for the path at the cut, never the vault file, which is the present and can be newer than the catalog (§2.1). A path whose event at the cut is a hole reads as erased, and not as - the version before it (`stateAt_holes_of_erased`); a sealed identity reads as nothing (§6). A + the version before it (`stateAt_holes_of_erased`); a path whose last event at the cut is a + retire reads as retired there, and at an earlier cut as what it held (§6.2). A transcript turn: the chat log's row when its number is at or under the cut. A curated row: what landed through the catalog as a note is; a row with no landing is not read (§5.6). - **`witness`.** The record when it lies inside the cut: an attestation by its number on `att`, @@ -1356,8 +1504,9 @@ The mode of a clause follows from its scope (`core/query.py:273-281`). **`as of "head"` is no `as of`.** At the head cut the read is the store (`readAt_head`), every derived view is the derivation of the present (`view_head`), the generational store reads the store rewritten in place (`genRead_gens_length`), a snapshot is the grant's restriction of the -store (`snapshot_head`), nothing is sealed (`servedAt_length`) and what is visible is the store -without the erased events (`visible_head`). `[THEOREM: SNP-4]` On the code this is the first test +store (`snapshot_head`), the history of an identity is every landing of it +(`landingsAt_length`) and what is visible is the store without the erased events +(`visible_head`). `[THEOREM: SNP-4]` On the code this is the first test of every stage: the same sentence with and without `as of "head"` returns the same hits. **Refusals.** An ambiguous prefix, as today (`universe.py:471-475`). A name that selects nothing: @@ -1435,8 +1584,9 @@ So the horizon is recorded, and a cut under it is not served. above a recorded position is read by the chain of records alone, so each such chain is lowered alone and the chain of records with them, to its last record that the cut read holds (§7.1, `resolvesIn_of_followed`). What else follows a lowered landing chain is the rows about - it, by the filter and not by position: a pass attestation, a dream claim, an interpreted row - or a claim op whose sources are not inside the cut read is withheld (§3.5, §5.4). A sentence + it, by the filter and not by position: a pass attestation, a dream claim, an interpreted + row, a claim op or an authored supersession whose sources are not inside the cut read is + withheld (§3.5, §5.4). A sentence all of whose chains are under their horizons returns the note and no hit. - **What that means today.** A commit read before the log exists resolves, on every chain but `repo`, under the horizon: `as of` such a commit reads the citation graph and the repository's @@ -1539,7 +1689,8 @@ landings a day. An instance that must bound its disk declares the first window, those derived rows and moves no horizon. The second frees, beyond that, only the raw objects and about three quarters of the bytes of the log's rows of the closed versions, and it is declared only by the owner (D8). At the cuts a chain no longer serves it also withholds every -pass attestation, dream claim and interpreted row that read a landing of that chain (§7.1). +pass attestation, dream claim, interpreted row and authored supersession that read a landing of +that chain (§7.1). ### 9.3 Lazy landing, in time @@ -1589,17 +1740,21 @@ passes to the code only as an obligation of the stage that transcribes it. - **SNP-1 append invariance.** A read at a cut inside the store, a read between two such cuts and every derived view are unchanged by any growth of the store (`readAt_grow`, `readAt_of_extends`, `readBetween_grow`, `appendInvariant_view`), also under an erasure and a grant (`visible_grow`, - `snapshot_grow`, `shown_grow`), for the keyed forms (`stateAt_append`, `genRead_gens_append`) and - for the filtered read of SNP-8 (`kept_grown_iff`). By construction: a store is a family of lists, - so growth is append and nothing else. That the code's stores only append below a cut is what the - stage's test checks. Controls: the reader that ignores the cut - (`Witness.present_not_appendInvariant`); a read at a cut past the head (431, 487, 488). Attacks - 430, 432, 446. The test, at SN-1: over random sequences of catalog writes, `read_at(chain, c)` and - `state_at` of every path at `c`, taken after every further write, equal the ones taken when `c` - was the head. + `snapshot_grow`, `shown_grow`), for the keyed forms (`stateAt_append`, `genRead_gens_append`), for + the history of an identity, a retire of it among the growth included (`landingsAt_append`, + `landingsAt_lives_append`), and for the filtered read of SNP-8 (`kept_grown_iff`). By + construction: a store is a family of lists, so growth is append and nothing else. That the code's + stores only append below a cut is what the stage's test checks. Controls: the reader that ignores + the cut (`Witness.present_not_appendInvariant`); a read at a cut past the head (431, 487, 488); + the history a seal serves, which a later retire empties (`Witness.seal_empties_history`, 522). + Attacks 430, 432, 446, 521, 527. The test, at SN-1: over random sequences of catalog writes, + `read_at(chain, c)` and `state_at` of every path at `c`, taken after every further write, equal + the ones taken when `c` was the head. - **SNP-2 monotonicity.** The read at an earlier cut is a prefix, chain by chain, of the read at a later one, and a cut of a cut is the meet (`readAt_mono`, `mem_readAt_of_le`, `readAt_readAt`, - `head_readAt`, `visible_mono`), and the filtered read of SNP-8 grows with the cut (`Kept.mono`). + `head_readAt`, `visible_mono`), the history of an identity at an earlier cut is a prefix of its + history at a later one (`landingsAt_mono`), and the filtered read of SNP-8 grows with the cut + (`Kept.mono`). Controls: the read at one cut taken for a prefix of the read at any other (434); a cut of a cut taken for the join (500). Attacks 433, 435, 515. The test, at SN-1: for `a ≤ b`, `read_at(chain, a)` is a prefix of `read_at(chain, b)`. @@ -1615,10 +1770,10 @@ passes to the code only as an obligation of the stage that transcribes it. a checkpoint and the delta equals the catalog; at SN-8: the region of §7.4. - **SNP-4 idempotence.** The read at the head cut is the store, and every reading at it is the present's (`readAt_head`, `readAt_of_head_le`, `view_head`, `genRead_gens_length`, - `snapshot_head`, `shown_head`, `servedAt_length`, `servedNow_length`, `historyAt_length`, - `visible_head`). Control: the read at a cut that is not the head taken for the store (501). - Attack 440. The test, at every stage: a sentence under `as of "head"` returns what it returns - without. + `snapshot_head`, `shown_head`, `landingsAt_length`, `visible_head`, and for the two seals + `servedAt_length`, `servedNow_length`, `historyAt_length`). Control: the read at a cut that is not + the head taken for the store (501). Attack 440. The test, at every stage: a sentence under `as of + "head"` returns what it returns without. - **SNP-5 a derived view depends only on the prefixes.** A reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view (`prefixOnly_view`, `view_congr`, `appendInvariant_iff_prefixOnly`, `appendInvariant_iff_exists_view`). For keyed @@ -1644,32 +1799,45 @@ passes to the code only as an obligation of the stage that transcribes it. (§6.3); and landings of a class the grant does not name change neither the rows shown at a recorded cut nor the cut shown. - **SNP-7 erasure dominance.** No erased event is visible at any cut; a larger erasure shows a - sublist; the store with holes keeps every position; stores that differ only in erased events - read the same at every cut; a kept row is served only when none of its sources is erased + sublist; the store with holes keeps every position; stores that differ only in erased events read + the same at every cut; a kept row is served only when none of its sources is erased (`not_erased_of_mem_visible`, `not_erased_of_mem_shown`, `visible_sublist`, `head_redact`, - `redact_readAt`, `visible_eq_reduceOption`, `visible_congr`, `erased_invisible`, - `mem_serve_iff`, `serve_sublist`). A read by key on a chain whose holes keep their keys is the - key's last write at or under the cut, a hole when that write is erased, on all three reads - (`stateAt_holes`, `stateAt_holes_of_erased`, `not_erased_of_stateAt_holes`, - `genRead_gens_holes`, `lastWrite_holes`). A key retired after a cut is served at no earlier - cut, growth changes a served value only by removing it, and the looser seal serves what the - stricter one serves (`stateAt_of_servedAt`, `servedAt_append_of_retire`, + `redact_readAt`, `visible_eq_reduceOption`, `visible_congr`, `erased_invisible`, `mem_serve_iff`, + `serve_sublist`). A read by key on a chain whose holes keep their keys is the key's last write at + or under the cut, a hole when that write is erased, on all three reads (`stateAt_holes`, + `stateAt_holes_of_erased`, `not_erased_of_stateAt_holes`, `genRead_gens_holes`, + `lastWrite_holes`). Of a retire the library proves both readings, and the design takes the first + (§6.2, the decision of 2026-11-11). With no seal: the history of an identity at a cut is its + landings inside the cut, and it holds as its end everything a seal serves + (`historyAt_suffix_landingsAt`); where a landing at a retired path takes a fresh identity, the + identity is a function of the events before the landing, the history of the identity a path holds + at a cut is the path's landings since its last retire, and a retired identity keeps the life it + had at every cut that holds its retire (`lives_take`, `landingsAt_lives_present`, + `landingsAt_lives_of_retire`). With a seal, which the design does not apply: a key retired after a + cut is served at no earlier cut, growth changes a served value only by removing it, and the looser + seal serves what the stricter one serves (`stateAt_of_servedAt`, `servedAt_append_of_retire`, `servedAt_append_of_no_retire`, `servedAt_of_append`, `servedNow_of_servedAt`, - `servedNow_of_not_live`). The seal covers the key's versions: the history served ends at the - value served, a retire after the cut empties it, and after a retire it holds only versions - landed since, at every cut (`getLast?_historyAt`, `historyAt_append_of_retire`, - `historyAt_of_retire_inside`, `sinceRetire_append_retire`). By construction: these are laws of - a reader that reads `visible`, `holes` or `historyAt`. That every reader of every store in the - code does is the reach of SN-3, checked by its scan, and no theorem. Controls: the erasure - that deletes rows (`Witness.compact_moves`, 455); the hole that loses its key - (`Witness.keyless_hole`, 496, 497); the state served without the seal (458); the looser seal - taken for a monotone one (`Witness.servedNow_restores`, 474); the history without the seal - (513); kept rows served without their sources (460). Attacks 452, 453, 454, 456, 457, 459, - 473, 495, 511, 512. The test, at SN-3: after a purge no read at any cut and no scan of the - instance's files finds the purged words; after a purge of an old version of a live path, the - read of the path at a cut where that version was the head is a hole, by all three reads; after - a retire no cut before it serves the identity, and after a new note lands at the path no read - of its history, at the head or at any cut, returns a version from before the retire. + `servedNow_of_not_live`); the seal covers the key's versions: the history served ends at the value + served, a retire after the cut empties it, and after a retire it holds only versions landed since, + at every cut (`getLast?_historyAt`, `historyAt_append_of_retire`, `historyAt_of_retire_inside`, + `sinceRetire_append_retire`). By construction: these are laws of a reader that reads `visible`, + `holes` or `landingsAt`, on a chain keyed as `lives` keys it. That every reader of every store in + the code does, and that the writer names identities so, is SN-3's to transcribe, checked by its + scan and its tests, and no theorem. Controls: the erasure that deletes rows + (`Witness.compact_moves`, 455); the hole that loses its key (`Witness.keyless_hole`, 496, 497); an + identity used again after its retire, whose history holds the retired item's versions + (`Witness.reused_identity_inherits`, 526, and 513 for the same reading against the seal); a + retired identity's history taken for empty (528); the state at a cut taken for what the stricter + seal serves (458); the looser seal taken for a monotone one (`Witness.servedNow_restores`, 474); + kept rows served without their sources (460). Attacks 452, 453, 454, 456, 457, 459, 473, 495, 511, + 512, 523, 524, 525. The test, at SN-3: after a purge no read at any cut and no scan of the + instance's files finds the purged words; after a purge of an old version of a live path, the read + of the path at a cut where that version was the head is a hole, by all three reads; after a retire + every read at a cut before it, of the identity's value and of its history, returns what it + returned before the retire; a new note landed at the path has an identity no earlier row carries, + no read of its history, at the head or at any cut, returns a version from before the retire, and + the retired identity's history at every cut is what it was; a landing at a retired path repeated + after a crash before its key takes the identity the first attempt took. - **SNP-8 resolution.** Every frontier resolves to exactly one greatest consistent cut under it, monotonically; a consistent cut stays consistent as the store grows; a cut consistent for a recorded bound on the references is consistent for the true ones (`exists_resolves`, @@ -1685,8 +1853,9 @@ passes to the code only as an obligation of the stage that transcribes it. withholds a row whose references are all resolved (`Kept.source`, `Kept.passes`, `kept_of_closed`, `kept_iff_of_consistent`, `kept_of_resolved`, on `Withheld.anti` and `Withheld.of_grown`). By construction: which references are resolved and which filtered is - the design's reading of the writers (§3.5), and that every reader of `att`, `runs` and the - `interp` chains at a cut goes through the filter is the stages' to transcribe. Controls: a + the design's reading of the writers (§3.5), and that every reader of `att`, `runs`, the + `interp` chains, `decl` and the dispositions at a cut goes through the filter is the stages' + to transcribe. Controls: a frontier taken for a cut (462); a consistent cut advanced by one position (464); resolution taken to fall as the frontier rises (490); a pass attestation's reference resolved, which lowers a landing chain that serves its position (`Witness.pass_drags`); the prefix read where @@ -1694,7 +1863,8 @@ passes to the code only as an obligation of the stage that transcribes it. without its closure (517). Attacks 461, 463, 465, 514, 516. The test, at SN-2: the resolver against enumeration on small stores, and no recorded cut with a resolved reference crossing it; at SN-5 and SN-6: at every cut, no row served whose source, by any reference of §3.5, is - outside the cut or withheld, and at the head no row withheld that the present read returns. + outside the cut or withheld, and at the head no row withheld that the present read returns, + but a witness's attestation of a commit the sensor has not read yet (§3.5). - **SNP-9 certified cuts.** A certificate verifies on every extension of the store; under a collision-free digest two stores that verify one certificate have the same prefix of every digested chain at its cut and the same derived views of it; a certificate extends over the @@ -1741,17 +1911,19 @@ What the model leaves out, said plainly. A chain is a list and a store a family is assumed, and nothing is said of two. Events are opaque, and so is the stores' SQL. The set of chain keys is fixed: a relabel is not in the model, which is why a chain has an id that a relabel does not change (§3.1). The hash's collision freedom and the commitment's binding are hypotheses of -SNP-9 (`CollisionFree`, an injective `commit`), not theorems about SHA-256. The `unseal` and -`horizon` events are not in the model of the seal, and the owner's gate on them is the code's. There -is no single reader in the model that applies the cut's resolution, the grant, the erasure and the -seal together: `shown` composes the grant and the erasure over one read, the seal is stated on a -keyed chain, and the resolution on cuts; the sentence's reader applies the resolution first, then -`shown`, then the seal to each keyed read, and that order is the code's to transcribe. The row -filter of §3.5 is in the model as `Kept`, with the reads-from relation and each row's own test as -parameters; what the code's rows read is §3.5's reading of the writers and no theorem, and the bound -a pass attestation records is argued there, not proved. The filtered read is a derived view, not a -prefix. A repository history with merges is covered by CLK-2's down-sets and not by the chain model -(§3.1). The resolver, the descent and its alternation with the floor, is attacked, not proved. +SNP-9 (`CollisionFree`, an injective `commit`), not theorems about SHA-256. The `horizon` event is +not in the model of a keyed chain, and the owner's gate on a history window is the code's. The fresh +identity is in the model as a count of a path's retires (`lives`); the name the code gives it, an +identity a note declares and a rename are not (§6.2). There is no single reader in the model that +applies the cut's resolution, the grant, the erasure and the history of an identity together: +`shown` composes the grant and the erasure over one read, the history is stated on a keyed chain, +and the resolution on cuts; the sentence's reader applies the resolution first, then `shown`, and no +seal (§6.2), and that order is the code's to transcribe. The row filter of §3.5 is in the model as +`Kept`, with the reads-from relation and each row's own test as parameters; what the code's rows +read is §3.5's reading of the writers and no theorem, and the bound a pass attestation records is +argued there, not proved. The filtered read is a derived view, not a prefix. A repository history +with merges is covered by CLK-2's down-sets and not by the chain model (§3.1). The resolver, the +descent and its alternation with the floor, is attacked, not proved. ## 11. Measurements @@ -1790,6 +1962,7 @@ the runs is given where they differed. `[MEASURED]` | what `as of` accepts | the unit tests' store fakes, with two readings in the reference store and with none; the real reference store on an empty temporary file; git read-only on the checkout | with readings held: `as of "HEAD"` and `as of "2026-11-01"` refused, a sha prefix accepted. With none held (`latest_commit()` is `None` on the empty store): `as of "HEAD"`, the date and an unknown name all answered, the universe's cut the string asked | | `read` under `as of` | the same fakes, one reading at a commit of the checkout fourteen back and one at a sha of forty `d`s that git does not hold | at the commit git holds: that commit's blob and not the head's, under a note saying that `read` read the present, the hit carrying no commit; at the sha git does not hold: `HEAD`'s blob, the same note, the same hit | | row numbering | a table keyed by text, five rows, in a temporary file | after the last row was deleted the next insert was numbered 5 again; a vacuum after a delete in the middle kept the numbers | +| an identity after a rename | an in-memory `VaultCatalog` at `f969904e`: a path recorded, a second path recorded with the first one's identity, the first tombstoned, then the first recorded again with no identity given, as the writer records a path that has a row (`core/ingest/writer.py:372`, `:409`) | the identity then has two active paths, the old one and the new one; added on 2026-11-11 for §2.3's item 8 | Not measured: anything on an instance's own stores; the size of a recorded cut, of a chain table's row and of a row of the log that a window emptied, which are arithmetic; how often a row of model @@ -1847,27 +2020,47 @@ property-testing the transcription against the Lean statements; the laws a stage that stops writing them and resumes later appends a `horizon`. - **SN-2 cuts.** The chain tables, each with its running hash and its genesis followed by a horizon, for `chat`, `att`, `staging` and `runs`; `att_head` filled from then on; on the chain-table row of - a pass attestation and of a run, the landing chains that held its inputs and the head of each - (§3.5); the extractor's version and the projection's position on `att` stamped on new citation - edges, the edges already held stamped with the genesis; the `cuts` table of §3.3, a record at a - trough that moved and on command, and an attestor method that builds and signs an attestation - without appending it; the four names, with every name that resolves to nothing refused; the - resolver of §3.5, the floor and the descent alternated; a command, `mind-palace cut` with - `record`, `list` and `verify`. Tests: SNP-8 and SNP-9 as stated; the served resolver against - enumeration; a record refused inside a job, and refused with jobs queued and no daemon; a cut read - below a record on one chain reading the chain of records at its last record under it. SNP-8 enters - the ledger as resolution, with its closure cited to CLK-2's row, and SNP-9 with it. Rollback: - additive tables and columns; the names fall back to today's. -- **SN-3 the erasure's reach and the seal.** A purge removes the lexical units, nulls the - version rows' digests, removes the relation edges and artifacts that name the digest, opens - the curated store, nulls the support and text of the dream claims and the digest and payload - of the staging rows, removes the claim ops on a removed artifact and the rejected requests - that hold the text, compacts both vector tables and writes its attestation, which names the - positions it emptied (§6.1); decision D9's form for the attestation ledger; the seal by - identity over the value and the history, and the owner's `unseal`. It lands before SN-4, since - SN-4 is the first stage that reads a superseded version. Tests: SNP-7 as stated, with the - purge probe of §11 turned into a test that must find nothing. Rollback: a purge has none by - its nature; the rest is additive. + a pass attestation and of a run, the landing chains that held its inputs and the head of each, and + on the row of a witness's attestation of a commit, the commit (§3.5); `verdicts` among the chains + a record names, by the position it has; the extractor's version and the projection's position on + `att` stamped on new citation edges, the edges already held stamped with the genesis; the `cuts` + table of §3.3, a record at a trough that moved and on command, and an attestor method that builds + and signs an attestation without appending it; the four names, with every name that resolves to + nothing refused; the resolver of §3.5, the floor and the descent alternated, the descent reading + the three bounds of the resolved references and no position recorded for the filter; a command, + `mind-palace cut` with `record`, `list` and `verify`. Tests: SNP-8 and SNP-9 as stated; the served + resolver against enumeration; a record refused inside a job, and refused with jobs queued and no + daemon; a cut read below a record on one chain reading the chain of records at its last record + under it; a record taken after a witness attested a commit the sensor has not read is consistent, + and lowers no chain. SNP-8 enters the ledger as resolution, with its closure cited to CLK-2's row, + and SNP-9 with it. Rollback: additive tables and columns; the names fall back to today's. +- **SN-3 the two forms of removal.** The deep form's reach: a purge removes the lexical units, + nulls the version rows' digests, removes the relation edges and artifacts that name the + digest, opens the curated store, nulls the support and text of the dream claims and the + digest and payload of the staging rows, removes the claim ops on a removed artifact, the + authored supersessions that name the digest and the rejected requests that hold the text, + compacts both vector tables and writes its attestation, which names the positions it emptied + (§6.1); decision D9's form for the attestation ledger. The shallow form's identity: a `store` + at a path with no open row is a first bind, and where it neither declares an identity nor + carries one from a vanished path, and the log holds an event of the path, it takes the fresh + identity `#.` of §6.2, in both lanes that bind one + (`core/ingest/writer.py:372`, `:409`; `core/ingest/sync.py:140-201`); the migration's count of + the identities that already run across a retire. No seal and no `unseal` are built. + + The fresh identity is this stage's for three reasons. It changes what the writer admits and + what `trace` returns at the head, and D12 licenses a change of behaviour with its own pull + request, where SN-1 adds tables and changes no behaviour. It needs the log: the name is the + position of the path's last event, which exists from SN-1. And it has to be in force before + any history is read at a cut, which is SN-4, so that no reader of a history is built on + identities that inherit; SN-3 is the stage already ordered before SN-4 for removal, and with + it the stage holds both forms the owner's decision names. + + It lands before SN-4, since SN-4 is the first stage that reads a superseded version. Tests: + SNP-7 as stated, with the purge probe of §11 turned into a test that must find nothing; the + two-paths probe of §11 turned into a test that finds one path an identity. Rollback: a purge + has none by its nature; the identity rule is one branch of the first bind, and with it off a + landing at a retired path continues the path's identity as today, the identities already + given staying as they are. - **SN-4 the notes at a cut.** The universe's nodes from `heads_at`, with kept heads for a chain over the size §4.2 gives; `read` from the raw object the log names, and refused for a repository path whose commit git lacks; the vectors and the lexical units joined to the heads; @@ -1881,20 +2074,29 @@ property-testing the transcription against the Lean statements; the laws a stage chain of records. Rollback: one configuration switch under `[query]`, off being today's behaviour. - **SN-5 the causal fiber at a cut.** The recomputation of §5.5 with its memo; edges named by session, order and endpoint; the transcript integrator's checkpoint a cut on `chat` and `repo`; - `witness` at a cut, the ledger read by sequence number with the pass attestations filtered (§3.5). + `witness` at a cut, the ledger read by sequence number with the pass attestations and the + witness's attestations of a commit filtered (§3.5). Tests: the two job orders giving one result; the prefix that ends before a result; the stored rows at the head equal to the recomputation; a pass attestation withheld at a cut that lacks a landing - it read, the attestations after it served, and none withheld at the head. Rollback: the stored - rows stay the head's cache. + it read, the attestations after it served, and none withheld at the head; a witness's attestation + withheld at a cut whose commit is an ancestor of its own, and served from its commit on. + Rollback: the stored rows stay the head's cache. - **SN-6 model output by generation.** A sequence number, a running hash and a history table for the interpreted artifacts and the interpreted relation edges, a chain each; a sequence - number and a running hash for the claim ops and the authored supersessions, which need no - history table since no row of theirs is replaced; the authored relations recomputed at a cut; - `relate` at a cut; a kept row served only with its sources inside the cut and its attestation - kept there, a claim op only with the artifacts it names, a dream claim only with its run + number and a running hash for the claim ops, which need no history table since a row is + keyed by its whole content and none is replaced; for the authored supersessions a chain-table + row at every declaration, with the note, the log positions of the two notes and a salted + commitment the hash runs over, since a second declaration of a pair replaces the store's row + (§5.4); the running hash of `verdicts`; the authored relations recomputed at a cut; `relate` + at a cut; a kept row served only with its sources inside the cut and its attestation kept + there, a claim op only with the artifacts it names, a dream claim only with its run, a + supersession only with both its notes, a disposition at the cut's position on `verdicts` (§3.5, §5.4). Tests: SNP-5 on random sequences of writes and replacements; `mem_serve_iff`'s test; SNP-8's filter as §10 states it; an artifact replaced over the same titles served with - the sources each generation had. Rollback: additive columns and tables. + the sources each generation had; a pair declared twice read at a cut between the two + declarations with the first note, the chain verifying after the second; a supersession + withheld at a cut that holds one of its notes and not the other, so that the active + projection at that cut marks nothing historical by it. Rollback: additive columns and tables. - **SN-7 retention.** The two windows a chain in the instance's configuration; the pass of §9.2; the `horizon` row; the horizon in the answers. Tests: SNP-10 as stated; a pass killed at each step leaving no served position incomplete; a derived row dropped under the first window @@ -1946,13 +2148,24 @@ give, and what each alternative costs is the answers it changes, which the entry to every place, is ten million pairs a cut at the scale the corpus records plan for; or one landing chain for every class, which saves a few integers a cut and tells a narrower reader, by its positions, how many landings the classes it cannot read made. -3. **D3, what a retire does to the past.** Recommended: the stricter seal, by identity, over the - value and the versions, lifted only by the owner's `unseal` (§6.2). The alternative, the - looser seal, brings a deleted note's versions back at earlier cuts when another note is - written at its path, and lets a past answer grow; it needs no unseal when a vault is missing - at a sync, where the stricter one needs one row. Neither is free at the head: under both, - the history of a note written at a deleted note's path has to stop at the delete, which - today it does not (§2.3, item 8). +3. **D3, what a retire does to the past. Decided by the owner on 2026-11-11, against the + recommendation.** The decision: removal has two forms. A retire is the shallow one: the item + leaves the present, its history stays readable at the cuts where it existed, no seal is + applied, and a note written later at the same path takes a fresh identity so that it does + not inherit the retired note's versions. The purge of §6.1 is the deep one: a hole at every + cut, with every derived answer at a past cut becoming what it is without the item; the + change that makes to the past answers of the item's neighbourhood is intended, and what + survives is the record that a purge happened, not the content (§6.2). What had been + recommended: the stricter seal, by identity, over the value and the versions, lifted only by + an owner's `unseal`; its alternative was the looser seal, which brings a deleted note's + versions back at earlier cuts when another note is written at its path. What the decision + costs: a note that is retired and returns has two identities unless it declares its own, so + its history at the head starts at its return (SN-l, SNF-10); a delete withdraws nothing + from the past, and only a purge does; and the identities bound before the rule keep what + they inherited. What it saves: the `unseal` event and its gate, a read of the present in + every keyed read at a cut, and the one thing about a retire that a certificate did not pin + (§3.6). The failure the seal was recommended for, a deleted note's versions standing under + a new note, is removed by the fresh identity at the first bind, at the head as at a cut. 4. **D4, a store that cannot serve the cut asked.** Recommended: read at the greatest consistent cut among the positions the stores serve, and name it (§7.1). With the recorded cuts on a chain of their own (D13), and the rows that read a landing without being its record filtered @@ -1975,17 +2188,17 @@ give, and what each alternative costs is the answers it changes, which the entry question about change is a hand-written read; or a general two-cut adjective, which is a second universe a sentence and a pair sort, and which dn-graph-dynamics designs already as GD-4. Neither alternative is sized here. -8. **D8, retention.** Recommended: no window on the default instance; where the disk is bounded, - a window for derived rows, which moves no horizon and frees what a superseded version mostly - costs, about 29 kilobytes of derived rows for a note of four chunks by §9.1's arithmetic; and - a window for the history only when the owner declares one, since it drops raw objects - (§9.2), and at the cuts under the new horizon withholds every pass attestation, dream claim - and interpreted row that read a landing of the chain. The alternatives: a horizon - everywhere, which over the first window frees only a closed version's raw bytes and about - 0.3 of its 0.4 kilobytes of log, by arithmetic, and loses the default instance's history for - it; that trade is worth making only where raw objects are large, as a transcript - retained whole at each growth is (0.79 MB a growth on the fixture). Or the last `n` versions - an identity, which leaves no horizon to name. +8. **D8, retention.** Recommended: no window on the default instance; where the disk is bounded, a + window for derived rows, which moves no horizon and frees what a superseded version mostly costs, + about 29 kilobytes of derived rows for a note of four chunks by §9.1's arithmetic; and a window + for the history only when the owner declares one, since it drops raw objects (§9.2), and at the + cuts under the new horizon withholds every pass attestation, dream claim, interpreted row and + authored supersession that read a landing of the chain. The alternatives: a horizon everywhere, + which over the first window frees only a closed version's raw bytes and about 0.3 of its 0.4 + kilobytes of log, by arithmetic, and loses the default instance's history for it; that trade is + worth making only where raw objects are large, as a transcript retained whole at each growth is + (0.79 MB a growth on the fixture). Or the last `n` versions an identity, which leaves no horizon + to name. 9. **D9, the attestation ledger under a purge.** It still names a purged digest (§6.1), against the plane's rule that no content hash of purged text is kept. Recommended: from SN-3 on, an attestation names a content digest by a salted commitment, the salt held in a side table of @@ -2015,12 +2228,12 @@ give, and what each alternative costs is the answers it changes, which the entry edges inside the cut (§6.4). The alternative, the list taken at the cut's tree, shows at a past cut a file that was tracked then and is not now, which the head withholds, and makes the grant a function of the cut. -12. **D12, what the merge licenses.** Recommended: SN-1 and SN-2. SN-1 adds tables and changes - no reader. SN-2 adds tables, columns and names; the one behaviour it changes is that a name - which resolves to nothing is refused on an instance whose reference store is empty, where - today it is answered (§2.1). SN-3 to SN-8 change an erasure, the universe and what an - instance keeps, and each is licensed with its own pull request. The alternative, all eight - at once, saves the owner seven decisions and reviews the purge, the universe and retention +12. **D12, what the merge licenses.** Recommended: SN-1 and SN-2. SN-1 adds tables and changes no + reader. SN-2 adds tables, columns and names; the one behaviour it changes is that a name which + resolves to nothing is refused on an instance whose reference store is empty, where today it is + answered (§2.1). SN-3 to SN-8 change an erasure, the identity a landing takes, the universe and + what an instance keeps, and each is licensed with its own pull request. The alternative, all + eight at once, saves the owner seven decisions and reviews the purge, the universe and retention together. 13. **D13, where a recorded cut is kept.** Recommended: a chain of its own that no other chain reads, its attestation in its own row (§3.3). That chain is read at its last record under @@ -2050,6 +2263,7 @@ give, and what each alternative costs is the answers it changes, which the entry | SN-i | the curated rows written outside the catalog | outside the snapshot, counted in the answer's note (§5.6) | the script routed through the writer | | SN-j | a date asked under a narrower grant | resolved over every record, the answer showing the record's id and its positions on the grant's chains only | a use that must hide when the instance was quiescent | | SN-k | the genesis of a class seeded from the plane's supersession log | not seeded: the genesis is the catalog as it stands | a need for a path's order before the log existed, on an instance that has a plane | +| SN-l | joining the identities a path had on the two sides of a retire | none: a note that returns takes a fresh identity unless it declares its own (§6.2) | SNF-10 | ## Falsifiers @@ -2080,14 +2294,16 @@ give, and what each alternative costs is the answers it changes, which the entry - **SNF-9 (retention drops what is asked for):** cuts asked for under a declared horizon, or a pass ordered by the field that drops rows later asked for more often than a pass ordered by age. Then the window grows, or the order stays age. -- **SNF-10 (the stricter seal is the wrong default):** unseals become routine, as an instance - whose vault goes missing at syncs would show. Then D3 takes the looser seal, with its cost. +- **SNF-10 (the fresh identity splits what is one item):** returns after a retire become + routine, as an instance whose vault goes missing at syncs would show: notes that declare no + identity whose history at the head starts at a return. Then SN-l, a join the owner runs. The + retire stays unsealed: that is the owner's decision and no falsifier of this note reopens it. - **SNF-11 (a transcription lies):** a built stage whose property test against a Lean statement fails. A transcription defect; the stage does not land until it agrees. - **SNF-12 (an erasure leaks):** after a purge, a read at any cut or a scan of the instance's files finds the purged words. Then SN-3's reach is incomplete and no stage after it is on. - **SNF-13 (append invariance fails on the code):** a sentence at a recorded cut that answers - differently after unrelated landings or a re-projection, the erasure, the seals and the grant + differently after unrelated landings, a retire or a re-projection, the erasure and the grant unchanged; or `as of "head"` that differs from no `as of`. Then some reader is not a function of the prefixes, and SNP-5 says which kind of store to look for. - **SNF-14 (the region is not what is asked):** questions about change that need the two @@ -2099,8 +2315,9 @@ give, and what each alternative costs is the answers it changes, which the entry premise of §7.1 is false for it, and that reference is found and moved to the filter of §3.5 or the chain is kept whole. - **SNF-16 (a filtered row is served without its source):** at some cut, a pass attestation, a - dream claim, an interpreted row or a claim op served while a row it reads, by a reference of - §3.5 or one that list missed, is outside the cut or withheld. Then the list of §3.5 is + witness's attestation, a dream claim, an interpreted row, a claim op, a disposition or an + authored supersession served while a row it reads, by a reference of §3.5 or one that list + missed, is outside the cut or withheld. Then the list of §3.5 is incomplete or a reader goes around the filter, and the stage that reads that store at a cut does not land until it is closed. @@ -2129,8 +2346,9 @@ Each with the default the stages build on until it is decided. `compact`, `serve`, `committed`, `purge`, `commitments`, `contents`, `Consistent`, `generator`, `reached`, `Resolves`, `reachedIn`, `ResolvesIn`, `Withheld`, `Kept`, `chainDigest`, `CollisionFree`, `Certificate`, `certify`, `Verifies`, and `sinceRetire`, `historyAt`, `holes`, -`shown`); `formal/Palace/Snapshot.lean` (the declarations §10 names, by law, and the eighteen -`Witness` controls); `formal/PalaceTest/Snapshot.lean` (seeds 430 to 520); the families cited: +`shown`, `landingsAt`, `retiresOf`, `lives`); `formal/Palace/Snapshot.lean` (the declarations +§10 names, by law, and the twenty `Witness` controls); `formal/PalaceTest/Snapshot.lean` (seeds +430 to 528); the families cited: `Palace/Clock.lean` (CLK-2: `IsCut`, `frontierCut`, `isCut_iff_not_crossed`, `IsCut.inter`, `IsCut.union`, `IsCut.frontier_inf`, `IsCut.frontier_sup`), `Palace/Ingress.lean` (ING-7), `Palace/Script.lean` (ING-17), `Palace/Derived.lean` (ING-19 to ING-21), `Palace/Plane.lean` @@ -2151,6 +2369,7 @@ Each with the default the stages build on until it is decided. `core/integrator.py`; `ingress/sync_vault.palace`, `ingress/sync_corpus.palace`; `scripts/purge_raw.py`, `scripts/curate_local.py`, `scripts/migrate_provenance_split.py`; `ops/code_sensor.py`, `ops/self_sensor.py`, `ops/code_snapshot.py`, `ops/chat_sensor.py`, +`ops/ci_witness.py`, `ops/supersede.py`, `core/ingest/founding.py`, `ops/heartbeat.py`, `ops/ledger.py`, `ops/effect_ledger.py`, `ops/lifecycle/launcher.py`, `ops/lifecycle/runs.py`; `eval/harness/store.py`, `eval/predictions/ledger.py`. From 906b885e8e9747718e3276ffc69e9e1449bf6c28 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 19:18:31 -0500 Subject: [PATCH 04/30] docs(paper): the pass alone cascades, and the resolver's bounds Two sentences the review found wrong. Resolving a pass attestation's reference lowers the attestation ledger; a row of model output sits on a chain no landing reads, so the article now gives the cascade for the pass alone and says the filter takes model output with it. Algorithm 1's bound is the bound recorded for the resolved references only, so the landing heads a pass or a run records for the filter are not followed. The article also states the decision on a retire, taken after it was written: no seal, a fresh identity at a deleted note's path. The counts are this tree's: 193 theorems, twenty controls, seeds 430 to 528, 5,250 declarations audited and 56,231 replayed. Ten pages, as before. Co-Authored-By: Claude Fable 5.2 --- papers/2026-11-10-temporal-snapshot/paper.tex | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/papers/2026-11-10-temporal-snapshot/paper.tex b/papers/2026-11-10-temporal-snapshot/paper.tex index 53aa204a..b7444265 100644 --- a/papers/2026-11-10-temporal-snapshot/paper.tex +++ b/papers/2026-11-10-temporal-snapshot/paper.tex @@ -44,8 +44,8 @@ recomputation reads, with at most one generation of a key alive at a cut. A narrower grant's snapshot is the restriction of a wider one's, and positions on a shared chain count what a filter hides. Nothing erased is visible at any cut when an erasure leaves holes; a hole must keep its -key, or a read by key returns a superseded version; and a seal keeps a retired identity, with -its versions, out of earlier cuts. Every frontier resolves to one greatest consistent cut. The +key, or a read by key returns a superseded version; and a seal, where one is applied, keeps a +retired identity out of earlier cuts. Every frontier resolves to one greatest consistent cut. The digest of each prefix certifies a cut, survives an erasure that keeps commitments, and attests no erasure. A store that drops old generations is exact from its horizon on, never wrong under it, and unable to tell what it lost. The last law gives the rule for an incomplete history: a @@ -77,7 +77,7 @@ \section{Introduction} \begin{enumerate} \item A model (\Cref{sec:model}) of a multi-store as a family of append chains with cuts, reads at and between cuts, derived views, a grant, an erasure and certificates. -\item Ten laws (\Cref{sec:laws}), SNP-1 to SNP-10, machine-checked as 175 theorems, with eighteen +\item Ten laws (\Cref{sec:laws}), SNP-1 to SNP-10, machine-checked as 193 theorems, with twenty failure modes as theorems too, among them the reader that ignores the cut, the store rewritten in place, a filter applied before the cut, an erasure that deletes rows, a hole that loses its key, a digest with collisions, a pruned store read under its horizon, and a record of a cut @@ -305,7 +305,7 @@ \section{The laws}\label{sec:laws} \end{proof} A certificate thus pins what it digests and nothing else. It attests no erasure, so a copy taken before an erasure verifies it and still holds what was erased; no seal, since a retire written -after the cut changes what is served at it (\lean{Witness.seal_not_certified}); and no grant. +after the cut changes what a seal serves (\lean{Witness.seal_not_certified}); and no grant. Its chains are named, and a renamed chain no longer verifies (\lean{Witness.rename_breaks_certificate}). @@ -371,15 +371,15 @@ \section{The design}\label{sec:design} date, which selects the last record whose wall bookmark is not later. Wall time is a lookup key there and orders nothing. The resolver follows three references, each through a recorded bound that is sound because there is one writer (\Cref{thm:lattice}): a landing's to the attestation -ledger, an attestation's to its commit, a record's to its frontier. A pass's attestation and a -row of model output read landings too; resolved, they would lower the ledger, and that can take -another landing chain down (\lean{Witness.pass_drags}), so the filter of \Cref{thm:lattice} withholds them -from the read instead. +ledger, an attestation's to its commit, a record's to its frontier. A pass's attestation reads +landings too; resolved, it would lower the ledger and can take another landing chain down +(\lean{Witness.pass_drags}), so the filter of \Cref{thm:lattice} withholds it from the read, +and with it the rows of model output. \begin{algorithm}[t] \caption{The cut a read under \texttt{as of} is taken at. $S_k$: the positions chain $k$ serves. -$\beta_k(i)$: for the $i$-th event of chain $k$, the heads of the chains it reads, as recorded at -its writing; they rise with $i$.}\label{alg:resolve} +$\beta_k(i)$: for the $i$-th event of chain $k$, the bounds recorded at its writing for its +resolved references only; they rise with $i$.}\label{alg:resolve} \begin{algorithmic}[1] \Require a frontier $f$ from the name \Ensure the greatest consistent cut under $f$ every position of which is served @@ -420,10 +420,10 @@ \section{The design}\label{sec:design} Both are parameters of a read, not functions of the cut. A purge empties the log's row and keeps its position, its commitment, its hash and the keyed hash of its path, so that a read by path finds the hole (\Cref{thm:erase,thm:cert}); the salt goes with the content, so the commitment -cannot be tested against a guess. A retire seals the identity's earlier cuts under the stricter -seal, lifted only by an owner's act. A new note written at a deleted note's path inherits its -identity by default; the looser seal would bring the deleted versions back at earlier cuts, and -without the seal on the history they would stand under the new note at every later one. The grant is the asker's now, an event filter is applied after the read, +cannot be tested against a guess. A retire, by a decision taken after this article was written, +seals nothing: the item leaves the present and its history stays readable at the cuts where it +existed. A new note at a deleted note's path would inherit its identity and its versions, so it +takes a fresh identity. The grant is the asker's now, an event filter is applied after the read, and an answer names the cut only on the chains the grant names (\Cref{thm:grant}). \paragraph{What an answer says.} @@ -452,23 +452,23 @@ \section{Evaluation}\label{sec:eval} \paragraph{What is proved.} \Cref{thm:append,thm:compose,thm:forms,thm:grant,thm:erase,thm:lattice,thm:cert,thm:horizon} are machine-checked in \lean{formal/Palace/Snapshot.lean} over \lean{formal/Palace/Snapshot/Defs.lean} -on Lean~4 \cite{moura2021lean4}, v4.36.0-rc2, and the Mathlib \cite{mathlib2020} it pins: 175 -theorems, eighteen of them the controls, no -\lean{sorry}, and the axioms of all 5{,}213 library declarations audited (\lean{propext}, -\lean{Classical.choice}, \lean{Quot.sound} only). The library's export, 56{,}188 declarations +on Lean~4 \cite{moura2021lean4}, v4.36.0-rc2, and the Mathlib \cite{mathlib2020} it pins: 193 +theorems, twenty of them the controls, no +\lean{sorry}, and the axioms of all 5{,}250 library declarations audited (\lean{propext}, +\lean{Classical.choice}, \lean{Quot.sound} only). The library's export, 56{,}231 declarations from \lean{Init} up, is replayed by Lean's kernel and five independent checkers. These are design theorems: no code relies on them yet, so they are not among the 328 statements the library restates separately and judges against its ledger of laws. \paragraph{The attacks.} The definitions compute, so they are attacked as they are with property-based testing -(\lean{formal/PalaceTest/Snapshot.lean}, seeds 430 to 520, 500 draws each): stores of two chains +(\lean{formal/PalaceTest/Snapshot.lean}, seeds 430 to 528, 500 draws each): stores of two chains over three events, keyed chains over three keys, chains of landings and retires, grants and erasures from bit masks, reads-from relations as edge lists, a base-four digest, served positions -from ten bits. Forty-nine attacks survive every draw. \Cref{alg:resolve}, which the library +from ten bits. Fifty-four attacks survive every draw. \Cref{alg:resolve}, which the library does not define, is run as an equivalent alternation, every chain floored and then one pass of the descent, and agrees on every draw with the pointwise maximum of every consistent served cut -under the frontier. Forty-two controls are refuted within 61 draws: among them a read at a cut past the head, generations +under the frontier. Forty-five controls are refuted within 61 draws: among them a read at a cut past the head, generations without the closing stamp, an event filter before the cut, an erasure that deletes rows, a seek over rows that lost their key, an additive digest, the pruned store read under its horizon, a chain that others read lowered alone, and the floor and the descent each run once, in either order. @@ -520,7 +520,7 @@ \section{Limitations} function. \Cref{alg:resolve} is attacked, not proved; the library proves the cut it must return exists and is unique. The laws of the grant and the erasure are laws of a reader that reads through them; that every reader in the code does is an obligation of the build, and no single -reader in the model applies the resolution, the grant, the erasure and the seal together. A +reader in the model applies the resolution, the grant and the erasure together. A repository history with merges is a partial order, which the clock's down-set laws cover and the chain model does not. Every measurement is on a synthetic fixture and cannot yet be repeated from the repository: the cost of the lexical statistics from a mask at a corpus's size, of a vector @@ -531,7 +531,7 @@ \section{Limitations} \section{Future work} The build is eight stages, each with its tests and its rollback: the landing log; -recorded cuts, names and the resolver; the erasure's reach and the seal; the notes, vectors and +recorded cuts, names and the resolver; the two forms of removal; the notes, vectors and lexical index at a cut; the causal edges at a cut; model output by generation; retention; and the delta between two cuts. Each stage property-tests its transcription against the Lean statements, and its laws then enter the ledger. From 4e2566b7119a768dcb380ebd55a0f6d732feaffc Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 19:18:31 -0500 Subject: [PATCH 05/30] docs(readme): the Lean counts from this tree's check.sh run The Snapshot library grew by 18 theorems, 5 attacks and 3 controls for the retire with no seal: 1,538 theorems, 232 attacks and 206 controls, 25,649 lines of models and proofs, 5,757 of attacks, and 56,231 declarations replayed. formal/README.md names the new theorems, the two controls and the seeds. The tests badge is not touched: no Python changed. Co-Authored-By: Claude Fable 5.2 --- README.md | 10 +++++----- formal/README.md | 30 +++++++++++++++++++++--------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 863c0d21..4552cb54 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![Lean statements](https://img.shields.io/badge/Lean-328_statements_judged-blue)](formal/README.md) [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) -[![attacks](https://img.shields.io/badge/attacks-227_with_controls-blue)](formal/PalaceTest) +[![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) [![tests](https://img.shields.io/badge/tests-3651-brightgreen)](docs/runbook.md) [![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) @@ -121,12 +121,12 @@ A law has one row in [`docs/LAWS.md`](docs/LAWS.md): its statement, the structur | | | |---|---| | toolchain | Lean `v4.36.0-rc2`, Mathlib; Plausible for the attacks | -| the library | 38 proof modules, 37 models, 26 statement files; 25,426 lines of models and proofs, 3,460 of statements, 5,705 of attacks | -| theorems | 1,520 proved in `formal/Palace`; 328 statements in `formal/Spec` judged identical by the comparator | +| the library | 38 proof modules, 37 models, 26 statement files; 25,649 lines of models and proofs, 3,460 of statements, 5,757 of attacks | +| theorems | 1,538 proved in `formal/Palace`; 328 statements in `formal/Spec` judged identical by the comparator | | the ledger | 100 rows in 15 families, 334 cited declarations, 87 law markers checked against the rows | -| attacks | 227 Plausible attacks and 203 negative controls over 33 modules, fixed seeds | +| attacks | 232 Plausible attacks and 206 negative controls over 33 modules, fixed seeds | | axioms | `propext`, `Classical.choice`, `Quot.sound`; `sorry` 0 | -| the replay | 56,188 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | +| the replay | 56,231 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | | families | memberships · Laplacian, balance and spectral · cut and conductance · curvature · the global event clock · the shared prose plane · capability scopes · the abstraction ultrametric σ* · bridges · the retrieval curve · the query sentence algebra · the ingress · stored vectors · the growth readout · the utility field | ## The mathematics diff --git a/formal/README.md b/formal/README.md index 620cf516..559efe38 100644 --- a/formal/README.md +++ b/formal/README.md @@ -327,7 +327,12 @@ Roundoff and FloatModel, so it has no statements of its own): value only by removing it, where the looser seal that withholds a key only while it is not live serves everything the stricter one serves and is lifted by a later landing; the seal covers a key's versions as it covers its value, so after a retire the history served holds - only versions landed since, at every cut; and on a keyed chain whose holes keep their keys + only versions landed since, at every cut; with no seal, which the design takes for a retire, + the history of a key at a cut is its landings inside the cut, append invariant and ending + with what the stricter seal serves, and where a landing at a retired path takes a fresh + identity (`lives`) the identity is a function of the events before it, the history of the + identity a path holds is the path's landings since its last retire, and a retired identity + keeps the life it had at every later cut; and on a keyed chain whose holes keep their keys the read of a key at a cut is its last write at or under the cut, a hole when that write is erased; SNP-8 resolution: the consistent cuts (every source of an event inside is inside) are CLK-2's cuts among the frontier cuts, so their closure under meet and join is CLK-2's, derived @@ -355,15 +360,17 @@ Roundoff and FloatModel, so it has no statements of its own): alone, every other chain read as asked, and a chain that reads the lowered chains and that nothing but itself reads, as a chain of records does, follows them and takes nothing with it. The grant and the erasure applied to one read - (`shown`) keep the laws of each. The eighteen controls as theorems, in `Witness`: the reader + (`shown`) keep the laws of each. The twenty controls as theorems, in `Witness`: the reader that ignores the cut (`present_not_appendInvariant`), the store rewritten in place (`stateOf_forgets`), an event filter applied before the cut (`filter_before_cut`), positions that count hidden events (`position_channel`), the erasure that deletes rows (`compact_moves`), the looser seal lifted by a later landing (`servedNow_restores`), the pruned store read under its horizon and unable to tell a lost key from one never written (`prune_forgets`, `prune_indistinct`), a digest with collisions (`digest_collides`), a hole - that loses its key (`keyless_hole`), a seal written after a certified cut - (`seal_not_certified`), a renamed chain (`rename_breaks_certificate`), a record on a chain + that loses its key (`keyless_hole`), an identity used again after its retire, which + inherits the retired item's versions (`reused_identity_inherits`), a served history that a + later retire empties under the seal (`seal_empties_history`), a seal written after a + certified cut (`seal_not_certified`), a renamed chain (`rename_breaks_certificate`), a record on a chain that content reads (`record_drags`), a chain of records lowered with a chain it certifies (`record_follows`), a pass attestation whose reference to a landing is resolved, and the same reference filtered, where the prefix is not closed and the filtered read is @@ -901,12 +908,12 @@ at a gain above the rate the ceiling is fixed, on the first instance; at exponen not constant, on the first instance; and the greedy walk's empirical measure is not within `1/8` of the structural stationary distribution, on the first instance. -The snapshot is attacked on the model's own definitions (seeds 430 to 520): stores of two +The snapshot is attacked on the model's own definitions (seeds 430 to 528): stores of two chains over three events, cuts from two naturals, keyed chains over three keys, chains of landings and retires from codes, grants from two bits and event filters and erasures from three, reads-from relations as lists of edges between the two chains at positions under four, a digest that reads a chain as a numeral in base four, which is collision free, and the positions -a chain serves from ten bits. Forty-nine attacks survived, every one all 500 instances: the read +a chain serves from ten bits. Fifty-four attacks survived, every one all 500 instances: the read at a cut and between two cuts under growth; the prefix order and the meet; the two compositions and the journal; the head cut; the generational store against the recomputed state and the last write, one generation alive at most, the same under growth, and the keyed journal; an event of @@ -915,7 +922,10 @@ narrower grant, the chains a snapshot reads, and the grant and the erasure toget (nothing erased visible or shown, positions kept, the holes dropped), the keyed read on a chain whose holes keep their keys, the retire that seals every earlier cut, growth that only removes, the two seals in their order, the history served under the seal, and the kept rows with their -sources; the resolver, the meet and the join of consistent cuts, and the monotone resolution; +sources; the history with no seal under growth, ending with what the seal serves and growing by +prefix, the history of the identity a path holds under fresh identities, a retired identity's +history at every later cut, and the identity a landing takes as a function of the events before +it; the resolver, the meet and the join of consistent cuts, and the monotone resolution; the certificate under growth, the digest of a reversed chain, the certificate over the delta, at the meet and the join, and across an erasure on a committed store; the pruned generational store at and past its horizon, never wrong under it, and two horizons as the later one; and, @@ -930,7 +940,7 @@ lowers a frontier until no event inside it has a source outside, checked against consistent cut by enumerating the thirty-six cuts of the grid (461), and its alternation with the floor to the served positions, checked against the greatest consistent served cut (492). -The forty-two controls, each refuted, with the instances it took. A read at a cut past the +The forty-five controls, each refuted, with the instances it took. A read at a cut past the head changes with growth, for the prefix, the read between two cuts and the generational store (11, 11, 7). The read at one cut is a prefix of the read at any other (6); a cut of a cut is the join (5); the read at a cut that is not the head is the store (8). The composition with @@ -941,7 +951,9 @@ applied before the cut (26); a hidden event more before the cut (7); a narrower smaller erasure (45). An erasure that deletes rows (29); a seek over the rows that kept their key, and over the chain with its holes deleted (35, 17); the state served without the seal (53); the looser seal as one under which growth only removes (48); the history without the -seal (33); the kept rows served without their sources (11). The frontier taken for a +seal (33); the sealed history taken for append invariant (30); a path's identity used again +after its retire (30); a retired identity's history taken for empty (18); the kept rows served +without their sources (11). The frontier taken for a consistent cut (11); a consistent cut advanced by one position (12); resolution falling as the frontier rises (6). The additive digest (11); a digest over the contents (14); the certificate of a cut past the head (6); the meet certified from the later digest (5). The pruned store read From d618d249cd6e9b5eba798a5687805ce8b1ed41e7 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:01:34 -0500 Subject: [PATCH 06/30] feat(stores): the catalog keeps its past in a landing log (SN-1) The catalog is rewritten in place, so it held no record of which digest a path held when. Stage SN-1 of dn-temporal-snapshot adds that record in the catalog's own file: two tables, landing_chains and landings, with the three indexes of section 3.2, appended to by the catalog's six writing methods in the transaction of the row each writes, so a deferred() batch carries its log rows and the catalog is the fold of the log. The migration that fills doc_id also creates the tables and, on a catalog that has rows and no log, writes the genesis of each class followed by a horizon. remove and remove_digest empty the rows of the path or of the digest and keep their keys, positions, commitments and hashes; relabel_provenance rewrites the label of a chain and no row; record takes the version the writer appended or found (writer.py's two key writes, sync.py's one) and appends nothing when nothing changes. The reads are on VaultCatalog: chains, head, read_at, state_at, history_at, heads_at, read_between and verify. Nothing reads them yet. The keyed hash of a path needs a secret, read as the repository reads an instance's secrets: get_secret, from the environment, the instance's own item. Without it the genesis and every write raise LandingLogKeyMissing and write nothing; another value is refused by the chain's key check. A read needs no secret. Two departures from the note's section 3.2, both for the fold: a path that changes class leaves its chain with a sixth kind, leave, since the move that a rename's tombstone writes must fold to the catalog's tombstoned row; and the genesis writes a tombstoned path's tombstone as a move where another active path holds its identity, as tombstone does. tests/property/test_landing_log.py checks SNP-1 to SNP-5 over random catalog writes with retires, renames, relabels, re-keys and purges, and the stage's cases; the suite's fixture gives every test a fixed secret. Co-Authored-By: Claude Opus 5.5 --- core/ingest/sync.py | 11 +- core/ingest/writer.py | 7 +- core/stores/catalog.py | 246 +++++++++--- core/stores/landings.py | 585 ++++++++++++++++++++++++++++ tests/conftest.py | 16 + tests/property/test_landing_log.py | 592 +++++++++++++++++++++++++++++ 6 files changed, 1403 insertions(+), 54 deletions(-) create mode 100644 core/stores/landings.py create mode 100644 tests/property/test_landing_log.py diff --git a/core/ingest/sync.py b/core/ingest/sync.py index fb41af28..e4bd4274 100644 --- a/core/ingest/sync.py +++ b/core/ingest/sync.py @@ -177,6 +177,7 @@ def sync_path(self, path: Path, # resolved above, else the path (what the catalog will default to when the key lands), so a # rename carries the chain forward instead of forking it. appended = False + version = None # the version this landing is, carried by the landing log if self.version_store is not None: doc_id = (self.catalog.doc_id_for(source_path) if prev is not None else resolved_doc_id if resolved_doc_id is not None else source_path) @@ -188,17 +189,21 @@ def sync_path(self, path: Path, rename = prev is None and any( other != source_path for other in self.catalog.paths_for(doc_id)) if rename: - self.version_store.record(doc_id, digest) + version = self.version_store.record(doc_id, digest).version_seq appended = True else: - appended = record_version_if_new(self.version_store, doc_id, digest) is not None + added = record_version_if_new(self.version_store, doc_id, digest) + appended = added is not None + head = added if added is not None else self.version_store.current(doc_id) + version = head.version_seq if head is not None else None # input == output == the content digest: for AUTHORED content the bytes read and the # content-addressed object written share one address. This is the chain's leaf. A landing # that appended a version is an event of its own (a revert to bytes attested before); # one that did not attests only when nothing names its digest (a re-run after a crash) attest_once(self.attestor, agent_role="vault_watcher", action="ingest_note", digest=digest, event=appended) - self.catalog.record(source_path, digest, record.title, doc_id=resolved_doc_id) # the key + self.catalog.record(source_path, digest, record.title, doc_id=resolved_doc_id, + version=version) # the key return SyncOutcome.INDEXED def sync_one(self, path: Path) -> SyncOutcome: diff --git a/core/ingest/writer.py b/core/ingest/writer.py index ddb0045b..8d01a98f 100644 --- a/core/ingest/writer.py +++ b/core/ingest/writer.py @@ -434,6 +434,7 @@ def finish(self, e: StoreEff, adm: _Admitted, record: IngestRecord, *, path, label = e.path, e.content.label catalog = self.stores.catalog appended = False + version = None # the version this landing is, where one is kept versions = self.stores.versions if place.versions and versions is not None: doc = catalog.doc_id_for(path) if prev is not None else (doc_id or path) @@ -443,11 +444,13 @@ def finish(self, e: StoreEff, adm: _Admitted, record: IngestRecord, *, appended = True else: appended = record_version_if_new(versions, doc, record.digest) is not None + head = versions.current(doc) # the version just appended, or found at the head + version = head.version_seq if head is not None else None if producers is None: attest_once(self.stores.attestor, agent_role=self.role, action=place.action, digest=record.digest, event=appended) catalog.record(path, record.digest, e.title, provenance=Provenance(label), - doc_id=doc_id) # the key, last + doc_id=doc_id, version=version) # the key, last return Outcome("store", path, "landed", digest=record.digest, attestations=tuple(attested_by(self.stores.attestor, place.action, record.digest))) @@ -461,7 +464,7 @@ def finish(self, e: StoreEff, adm: _Admitted, record: IngestRecord, *, made.append((place.action, att.id)) mine.append(att.id) catalog.record(path, record.digest, e.title, provenance=Provenance(label), - doc_id=doc_id) # the key, last + doc_id=doc_id, version=version) # the key, last return Outcome("store", path, "landed", digest=record.digest, attestations=tuple(sorted(mine))) diff --git a/core/stores/catalog.py b/core/stores/catalog.py index b2705ddc..2da53617 100644 --- a/core/stores/catalog.py +++ b/core/stores/catalog.py @@ -17,19 +17,37 @@ now realized, so `Provenance.AUTHORED_SOLO` is the concrete tag (was the single `authored`). Dialogue capture records `authored-dialogue` and curated ingest records `curated` through the same catalog, by passing `provenance=` to `record`. + +The catalog keeps its own past (dn-temporal-snapshot §3.2, stage SN-1): the landing log of +`core/stores/landings.py`, two tables in this file that the six writing methods below append to +in the transaction of the row each writes, so a `deferred()` batch carries its log rows and the +catalog is the fold of the log. The migration that fills `doc_id` also creates the log and, on a +catalog that has rows and no log yet, writes its genesis. The log's keyed hash of a path needs the +instance's landing-log secret, which is read from the environment and never stored here: without +it the genesis and every write refuse, loudly, and nothing is written unkeyed. The reads of the +log (`chains`, `head`, `read_at`, `state_at`, `history_at`, `heads_at`, `read_between`, +`verify`) have no reader yet. """ from __future__ import annotations import sqlite3 -from collections.abc import Iterator +from collections.abc import Iterator, Mapping from contextlib import contextmanager -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path from core.kernel.provenance import Provenance from core.stores.authored_supersession import OwnerDeclaration, verify_owner_declaration +from core.stores.landings import ( + ChainCheck, + Landing, + LandingLog, + Prior, + landing_log_key, + parse_key, +) from core.stores.versions import RekeyRefusedError _DDL = """ @@ -62,6 +80,9 @@ class CatalogEntry: @dataclass class VaultCatalog: path: Path + # The landing log's secret, 32 bytes or more. None, the usual case: read from the environment + # when the log first needs it (`core.stores.landings.landing_log_key`), and never stored. + key: bytes | None = field(default=None, repr=False) def __post_init__(self) -> None: if str(self.path) != ":memory:": @@ -69,10 +90,18 @@ def __post_init__(self) -> None: self._defer = False self._conn = sqlite3.connect(str(self.path)) self._conn.row_factory = sqlite3.Row - self._conn.execute("PRAGMA journal_mode=WAL") - self._conn.executescript(_DDL) - self._migrate() - self._conn.commit() + self._log = LandingLog(self._conn, self._landing_key) + try: + self._conn.execute("PRAGMA journal_mode=WAL") + self._conn.executescript(_DDL) + self._migrate() + self._conn.commit() + except BaseException: + self._conn.close() + raise + + def _landing_key(self) -> bytes: + return parse_key(self.key.hex()) if self.key is not None else landing_log_key() def _migrate(self) -> None: """Bring a pre-`doc_id` catalog forward, idempotently (bp-031 Item 1). `CREATE TABLE IF NOT @@ -80,7 +109,12 @@ def _migrate(self) -> None: an explicit `ALTER … ADD COLUMN` + a one-time backfill `doc_id := source_path` for every legacy row. Behavior-preserving: identity stays equal to the path until a mechanism (Item 2) diverges it. A second run matches no `doc_id IS NULL` rows — same shape as - `relabel_provenance`.""" + `relabel_provenance`. + + Then the landing log (dn-temporal-snapshot §3.2): its two tables and their indexes, and, + on the first open of a catalog that has rows and no log, the genesis, in one transaction. + The genesis keys every row it writes, so it needs the landing-log secret: absent, it raises + `LandingLogKeyMissing` and writes no row of the log.""" cols = {r["name"] for r in self._conn.execute("PRAGMA table_info(vault_files)").fetchall()} if "doc_id" not in cols: self._conn.execute("ALTER TABLE vault_files ADD COLUMN doc_id TEXT") @@ -90,6 +124,42 @@ def _migrate(self) -> None: self._conn.execute("CREATE INDEX IF NOT EXISTS vault_files_doc_id ON vault_files (doc_id)") self._conn.execute("UPDATE vault_files SET doc_id = source_path WHERE doc_id IS NULL") self._conn.commit() + self._log.create() + if self._log.has_chains() or self._empty(): + return # a log already, or nothing to begin from yet + with self._writing(): # asked again under the write lock: one genesis only + if not self._log.has_chains() and not self._empty(): + self._log.genesis() + + def _empty(self) -> bool: + return self._conn.execute("SELECT 1 FROM vault_files LIMIT 1").fetchone() is None + + @contextmanager + def _writing(self) -> Iterator[None]: + """The transaction of one write: the catalog's row and its log rows commit together, or + neither does. Inside `deferred()` the batch's transaction is the one, and it commits at + the end of the batch.""" + if not self._conn.in_transaction: + self._conn.execute("BEGIN IMMEDIATE") + if self._defer: + yield + return + try: + yield + except BaseException: + self._conn.rollback() + raise + self._conn.commit() + + def _prior(self, source_path: str) -> Prior | None: + r = self._conn.execute( + "SELECT digest, title, provenance, active, doc_id FROM vault_files " + "WHERE source_path = ?", [source_path]).fetchone() + if r is None: + return None + return Prior(digest=r["digest"], title=r["title"], provenance=r["provenance"], + active=bool(r["active"]), + doc_id=r["doc_id"] if r["doc_id"] is not None else source_path) def get(self, source_path: str) -> CatalogEntry | None: r = self._conn.execute( @@ -99,34 +169,46 @@ def get(self, source_path: str) -> CatalogEntry | None: def record(self, source_path: str, digest: str, title: str, *, provenance: Provenance = Provenance.AUTHORED_SOLO, - doc_id: str | None = None) -> None: + doc_id: str | None = None, version: int | None = None) -> None: """Upsert a file as active at `digest` (re-adding a tombstoned file reactivates it). `doc_id` binds the note's stable identity (bp-031 Item 2): pass an explicit id (an existing `id::`, or a renamed predecessor's carried id) to bind it; omit it and a NEW row defaults `doc_id := source_path` (identity == path) while a re-record PRESERVES the stored `doc_id`. An explicit `doc_id` DOES overwrite on conflict — but sync only passes one at first bind, - never to switch a historied note's identity (the re-key is owner-run bp-034).""" + never to switch a historied note's identity (the re-key is owner-run bp-034). + + The landing log takes a `store` in the same transaction, carrying `version`, the number of + the version this landing is where the place keeps a version chain (`None` elsewhere). A + record that changes nothing, the same digest, title, class and identity as the path's + active row, appends nothing: the log is of the changes of the map.""" insert_doc_id = doc_id if doc_id is not None else source_path # Preserve the stored doc_id on a re-record; overwrite only when an explicit id is given. set_doc = ", doc_id=excluded.doc_id" if doc_id is not None else "" - self._conn.execute( - "INSERT INTO vault_files" - " (source_path, digest, title, provenance, active, updated_at, doc_id)" - " VALUES (?, ?, ?, ?, 1, ?, ?)" - " ON CONFLICT(source_path) DO UPDATE SET" - " digest=excluded.digest, title=excluded.title," - " provenance=excluded.provenance, active=1, updated_at=excluded.updated_at" + set_doc, - [source_path, digest, title, str(provenance), _utcnow(), insert_doc_id], - ) - if not self._defer: - self._conn.commit() + with self._writing(): + prior = self._prior(source_path) + doc = doc_id if doc_id is not None else (prior.doc_id if prior else source_path) + self._conn.execute( + "INSERT INTO vault_files" + " (source_path, digest, title, provenance, active, updated_at, doc_id)" + " VALUES (?, ?, ?, ?, 1, ?, ?)" + " ON CONFLICT(source_path) DO UPDATE SET" + " digest=excluded.digest, title=excluded.title," + " provenance=excluded.provenance, active=1, updated_at=excluded.updated_at" + + set_doc, + [source_path, digest, title, str(provenance), _utcnow(), insert_doc_id], + ) + if prior is None or not (prior.active and prior.digest == digest + and prior.title == title + and prior.provenance == str(provenance) + and prior.doc_id == doc): + self._log.store(source_path, str(provenance), doc, version, digest, title, prior) @contextmanager def deferred(self) -> Iterator[None]: """The records made inside commit once, at the end, in one transaction (a batch's keys, - the last writes of its landing); an exception inside rolls them back, so none of them is - written.""" + the last writes of its landing, and their rows of the landing log); an exception inside + rolls them back, so none of them is written.""" self._defer = True try: yield @@ -160,16 +242,25 @@ def doc_id_for(self, source_path: str) -> str: def tombstone(self, source_path: str) -> str | None: """Mark a file inactive (deleted from the vault). Returns the digest it held, or None if it was unknown. The raw blob is intentionally NOT touched — raw is sacred; true - deletion is the separate, owner-gated purge (core/ingest/purge.py).""" - entry = self.get(source_path) - if entry is None: - return None - self._conn.execute( - "UPDATE vault_files SET active = 0, updated_at = ? WHERE source_path = ?", - [_utcnow(), source_path], - ) - self._conn.commit() - return entry.digest + deletion is the separate, owner-gated purge (core/ingest/purge.py). + + The landing log takes the tombstone of an active path in the same transaction: a `move` + when another active path holds its identity (the second half of a rename), a `retire` + otherwise. A tombstone of a path already inactive changes nothing and appends nothing.""" + with self._writing(): + prior = self._prior(source_path) + if prior is None: + return None + self._conn.execute( + "UPDATE vault_files SET active = 0, updated_at = ? WHERE source_path = ?", + [_utcnow(), source_path], + ) + if prior.active: + moved = self._conn.execute( + "SELECT 1 FROM vault_files WHERE doc_id = ? AND active = 1 " + "AND source_path <> ? LIMIT 1", [prior.doc_id, source_path]).fetchone() + self._log.tombstone(source_path, prior, "move" if moved else "retire") + return prior.digest def active_refs(self, digest: str) -> int: """How many ACTIVE files currently hold this content. Derived rows for a digest may be @@ -197,14 +288,17 @@ def relabel_provenance(self, old: str, new: str) -> int: The catalog-side half of the §1 spectrum-split migration (relabel legacy `'authored'` → `'authored-solo'`). Same-trust-tier relabel, idempotent (a second run matches no - `old` rows).""" + `old` rows). In the landing log it rewrites the label of the class's chains and no row, + so no position moves and every chain still verifies; after a relabel into a class that + has rows, the class has two chains.""" if old == new: return 0 - cur = self._conn.execute( - "UPDATE vault_files SET provenance = ?, updated_at = ? WHERE provenance = ?", - [new, _utcnow(), old], - ) - self._conn.commit() + with self._writing(): + cur = self._conn.execute( + "UPDATE vault_files SET provenance = ?, updated_at = ? WHERE provenance = ?", + [new, _utcnow(), old], + ) + self._log.relabel(old, new) return cur.rowcount def migrate_rekey_doc_id(self, source_path: str, new_doc_id: str, *, @@ -234,16 +328,24 @@ def migrate_rekey_doc_id(self, source_path: str, new_doc_id: str, *, f"catalog re-key refused: doc_id {new_doc_id!r} is already resolved by another " "note — rebinding this path onto it would MERGE two identities at resolution." ) - self._conn.execute( - "UPDATE vault_files SET doc_id = ?, updated_at = ? WHERE source_path = ?", - [new_doc_id, _utcnow(), source_path], - ) - self._conn.commit() + with self._writing(): + prior = self._prior(source_path) + self._conn.execute( + "UPDATE vault_files SET doc_id = ?, updated_at = ? WHERE source_path = ?", + [new_doc_id, _utcnow(), source_path], + ) + if prior is not None: # the log: a `move` of the old identity, then the new + self._log.rekey(source_path, prior, new_doc_id) def remove(self, source_path: str) -> None: - """Delete the catalog row entirely (used by the gated purge after raw removal).""" - self._conn.execute("DELETE FROM vault_files WHERE source_path = ?", [source_path]) - self._conn.commit() + """Delete the catalog row entirely (used by the gated purge after raw removal). Every row + of the path in the landing log is emptied in the same transaction: the path, the + identity, the digest, the title, the salt and the bookmark go; the position, the key, + the commitment and the hash stay (dn-temporal-snapshot §6.1), so the chain still + verifies and the hole still shadows the path's earlier versions.""" + with self._writing(): + self._conn.execute("DELETE FROM vault_files WHERE source_path = ?", [source_path]) + self._log.empty_path(source_path) def paths_for_digest(self, digest: str) -> list[str]: rows = self._conn.execute( @@ -253,11 +355,57 @@ def paths_for_digest(self, digest: str) -> list[str]: def remove_digest(self, digest: str) -> int: """Delete every catalog row for a digest (the gated purge removes only tombstoned - content — callers must verify `active_refs(digest) == 0` first). Returns rows removed.""" - cur = self._conn.execute("DELETE FROM vault_files WHERE digest = ?", [digest]) - self._conn.commit() + content — callers must verify `active_refs(digest) == 0` first). Returns rows removed. + + Every row of the digest in the landing log is emptied in the same transaction, as + `remove` empties a path's, including a version a live path held before: the log then + returns a hole at a cut where that version was the head, never the version before it.""" + with self._writing(): + cur = self._conn.execute("DELETE FROM vault_files WHERE digest = ?", [digest]) + self._log.empty_digest(digest) return cur.rowcount + # the landing log's reads (dn-temporal-snapshot §4.1; SNP-1 to SNP-5). A cut over a class is + # one position a chain, `{chain: seq}`; a bare integer is taken for a class with one chain. + + def chains(self, provenance: Provenance | str) -> list[int]: + """The ids of the landing chains that hold a class now, oldest first.""" + return self._log.chains(str(provenance)) + + def head(self, chain: int) -> int: + """A chain's last position: its head.""" + return self._log.head(chain) + + def read_at(self, chain: int, c: int) -> list[Landing]: + """The prefix of a chain at `c`: its rows with `seq ≤ c`, in order.""" + return self._log.read_at(chain, c) + + def read_between(self, chain: int, a: int, b: int) -> list[Landing]: + """A chain's rows after `a` and up to `b`, in order.""" + return self._log.read_between(chain, a, b) + + def state_at(self, provenance: Provenance | str, source_path: str, + c: Mapping[int, int] | int) -> Landing | None: + """A path's last event at or under the cut, over the class's chains: a `store`, a + `retire`, a `move` or a `leave`, a hole, or nothing. One seek on the key index a chain.""" + return self._log.state_at(str(provenance), source_path, c) + + def history_at(self, provenance: Provenance | str, source_path: str, + c: Mapping[int, int] | int) -> list[Landing]: + """A path's `store` rows at or under the cut, over the class's chains, oldest first; a + purged version is a hole in place.""" + return self._log.history_at(str(provenance), source_path, c) + + def heads_at(self, provenance: Provenance | str, c: Mapping[int, int] | int) -> list[Landing]: + """Every head of a class at the cut: the `store` rows alive there, through the closing + stamp, a hole returned as a hole with its position and no name.""" + return self._log.heads_at(str(provenance), c) + + def verify(self, chain: int) -> ChainCheck: + """A chain's hashes recomputed from its first row, and every commitment that still has + its salt: the first position where one fails, or none.""" + return self._log.verify(chain) + def close(self) -> None: self._conn.close() diff --git a/core/stores/landings.py b/core/stores/landings.py new file mode 100644 index 00000000..3b4987ea --- /dev/null +++ b/core/stores/landings.py @@ -0,0 +1,585 @@ +"""The landing log: the catalog's past (dn-temporal-snapshot §3.2, stage SN-1). + +The catalog is rewritten in place, so on its own it holds no past: which digest a path held +when, and whether it was active. This log is that past. It lives in the catalog's own file, and +only the catalog's writing methods append to it, in the transaction of the row each writes, so the +key and its log rows land together and no caller can write one without the other (ING-7's order +is unchanged: the key last, now two rows of one transaction). The catalog is the fold of the log, +and the state of a path at a past position is the same fold of a prefix (SNP-5). + +**Chains.** A chain is an append order with an integer id that is never reused or changed, and +it holds one provenance class, which is its label in `landing_chains`. A relabel of a class +rewrites that label and no row of the log, so it moves no position and breaks no hash; after a +merge a class has two chains and the read of a class is the union of its chains' reads. A path's +events stay in the chain that holds its last event; a path that changes class leaves its chain +with a `leave` row and lands in a chain of its new class. + +**Rows.** `genesis` and `horizon` open a chain (§8: the positions before a horizon are under +it); `store` is a landing; `retire` the tombstone of an identity no other active path holds; +`move` a tombstone that leaves the identity at another path (the second half of a rename), or +the identity a re-key takes off a path; `leave` the row that closes a path in a chain when the +path takes another class. A row's `commitment` is SHA-256 over a random salt and the canonical +JSON of its fields, and its `hash` is SHA-256 over the previous row's hash and the commitment, so +a purge can empty a row and keep the chain (SNP-9). `closed_at` is the position of the path's +next event in the chain, written after the row and a function of the rows (SNP-5). + +**The key of a path.** A row names its path also by `path_key`, a keyed hash, which is what a +read by path seeks on and the one name a purged row keeps, so a hole still shadows the path's +earlier versions (§6.1). Its key is derived from two halves: the chain's 32 random bytes in the +file, and the instance's landing-log secret, which is never in the file: it is read from the +environment (`get_secret`, Keychain-backed in the owner's setup, the instance's own item under a +named instance). A missing or malformed secret refuses the write, or the migration, loudly; no +row is ever written unkeyed. A secret that is not the one a chain was written with is refused as +well, by the chain's `key_check`, so a chain is never keyed two ways. + +Nothing reads the log yet: the reads below are the ones the later stages build on. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import secrets +import sqlite3 +from collections.abc import Callable, Iterator, Mapping, Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Any + +# The Keychain/env item the instance's landing-log secret is read from (a named instance reads +# `.landing-log-key`, `InstanceConfig.secret`): 32 random bytes or more, as hex digits. +LANDING_LOG_KEY = "landing-log-key" + +KINDS = ("genesis", "store", "retire", "move", "leave", "horizon") + +DDL = """ +CREATE TABLE IF NOT EXISTS landing_chains ( + chain INTEGER PRIMARY KEY, -- the chain's id: never reused, never changed + class TEXT NOT NULL, -- the provenance class it holds now; a relabel rewrites this + secret BLOB NOT NULL, -- 32 random bytes: the chain's half of the key of path_key + key_check BLOB NOT NULL -- hmac-sha256(the chain's key, 'key check') +); +CREATE TABLE IF NOT EXISTS landings ( + chain INTEGER NOT NULL, -- landing_chains.chain + seq INTEGER NOT NULL, -- the position in the chain, from 1, never given twice + kind TEXT NOT NULL, -- genesis | store | retire | move | leave | horizon + path_key BLOB, -- hmac-sha256(the chain's key, source_path): kept by a hole + source_path TEXT, -- NULL once purged + doc_id TEXT, -- the identity the event belongs to; NULL once purged + version INTEGER, -- the version number, where the place keeps a chain + digest TEXT, -- a store's digest; NULL for every other kind, and once purged + title TEXT, -- a store's title; NULL once purged + att_head INTEGER, -- the head of att when the row was written; NULL before SN-2 + horizon INTEGER, -- a horizon row: the position it declares; NULL otherwise + salt BLOB, -- 16 random bytes; NULL once purged + commitment BLOB NOT NULL, -- sha256(salt, the row's fields): what the chain digests + hash BLOB NOT NULL, -- sha256(the previous row's hash, commitment) + closed_at INTEGER, -- the seq of the path's next event; NULL while it is the last + at TEXT, -- wall bookmark: lookup only, never an order; NULL once purged + PRIMARY KEY (chain, seq) +) WITHOUT ROWID; +CREATE INDEX IF NOT EXISTS landings_path ON landings (chain, path_key, seq) + WHERE path_key IS NOT NULL; +CREATE INDEX IF NOT EXISTS landings_doc ON landings (chain, doc_id, seq) + WHERE doc_id IS NOT NULL AND doc_id <> source_path; +CREATE INDEX IF NOT EXISTS landings_closed ON landings (chain, closed_at) + WHERE closed_at IS NOT NULL; +""" + +_ZERO = bytes(32) +_COLUMNS = ("chain, seq, kind, path_key, source_path, doc_id, version, digest, title, att_head, " + "horizon, salt, commitment, hash, closed_at, at") +_INSERT = f"INSERT INTO landings ({_COLUMNS}) VALUES ({', '.join('?' * 16)})" +# What a purge empties in a row (§6.1): the path, the identity, the digest, the title, the salt +# and the bookmark. The position, the kind, the key, the version, the closing stamp, the +# commitment and the hash stay. +_EMPTY = "source_path = NULL, doc_id = NULL, digest = NULL, title = NULL, salt = NULL, at = NULL" +_BATCH = 5000 # genesis rows written a statement + + +class LandingLogKeyMissing(RuntimeError): + """The landing log's secret is not in the environment, or is not 32 bytes of hex. Raised before + anything is written: the log is never keyed without it.""" + + +class LandingLogKeyMismatch(RuntimeError): + """The secret in the environment is not the one a chain was written with. Raised before + anything is written: a chain is never keyed two ways.""" + + +def _now() -> str: + return datetime.now(UTC).replace(tzinfo=None).isoformat(timespec="seconds") + + +def _mac(key: bytes, message: bytes) -> bytes: + return hmac.new(key, message, hashlib.sha256).digest() + + +def parse_key(value: str, name: str = LANDING_LOG_KEY) -> bytes: + """The secret as bytes: at least 32 of them, written as hex digits. The value is never put + in a message.""" + try: + raw = bytes.fromhex(value.strip()) + except ValueError: + raise LandingLogKeyMissing(f"get_secret({name!r}) is not hex digits; the landing log " + "takes 32 random bytes as 64 hex digits") from None + if len(raw) < 32: + raise LandingLogKeyMissing(f"get_secret({name!r}) is {len(raw)} bytes; the landing log " + "takes 32 random bytes or more") + return raw + + +def landing_log_key() -> bytes: + """The instance's landing-log secret, from the environment (`get_secret`, the instance's own + item: `landing-log-key`, or `.landing-log-key` for a named instance). Raises + `LandingLogKeyMissing` when it is absent: place it before the catalog is written.""" + from core.kernel.config import get_config, get_secret + + name = get_config().instance.secret(LANDING_LOG_KEY) + value = get_secret(name) + if not value: + raise LandingLogKeyMissing( + f"the landing log needs its secret at get_secret({name!r}): 32 random bytes as 64 " + "hex digits (`openssl rand -hex 32`), placed in the Keychain and the environment " + "(scripts/run_with_secrets.sh); nothing was written") + return parse_key(value, name) + + +def commitment(salt: bytes, fields: Mapping[str, object]) -> bytes: + """SHA-256 over the salt followed by the canonical JSON of the row's fields: keys sorted, no + white space, UTF-8 (§3.2).""" + canonical = json.dumps(fields, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(salt + canonical.encode("utf-8")).digest() + + +def chain_hash(previous: bytes, commit: bytes) -> bytes: + """SHA-256 over the previous row's hash followed by this row's commitment; the first row's + previous hash is 32 zero bytes.""" + return hashlib.sha256(previous + commit).digest() + + +@dataclass(frozen=True) +class Landing: + """One row of the log. A row a purge emptied keeps its position, its kind, its key, its + version, its closing stamp, its commitment and its hash, and nothing else: it is a hole.""" + + chain: int + seq: int + kind: str + path_key: bytes | None + source_path: str | None + doc_id: str | None + version: int | None + digest: str | None + title: str | None + att_head: int | None + horizon: int | None + salt: bytes | None + commitment: bytes + hash: bytes + closed_at: int | None + at: str | None + + @property + def hole(self) -> bool: + """The row was emptied by a purge: its content is gone, its position stays.""" + return self.salt is None + + def fields(self) -> dict[str, object]: + """The fields the commitment covers (§3.2): every column but the key, the salt, the + commitment, the hash and the closing stamp.""" + return {"chain": self.chain, "seq": self.seq, "kind": self.kind, + "source_path": self.source_path, "doc_id": self.doc_id, + "version": self.version, "digest": self.digest, "title": self.title, + "att_head": self.att_head, "horizon": self.horizon, "at": self.at} + + +@dataclass(frozen=True) +class ChainCheck: + """What `verify` found on one chain: the rows it read, the commitments it recomputed (the + rows that still have their salt), and the first position at which a commitment or a hash + does not hold, with what failed there, or `None`.""" + + chain: int + rows: int + commitments: int + failed_at: int | None = None + why: str = "" + + @property + def ok(self) -> bool: + return self.failed_at is None and self.rows > 0 + + +@dataclass(frozen=True) +class Prior: + """A path's catalog row before a write: what the log compares against and carries.""" + + digest: str + title: str + provenance: str + active: bool + doc_id: str + + +def _landing(r: Sequence[Any]) -> Landing: + return Landing(*r) + + +class _Block: + """One chain's genesis block: its rows committed to and hashed in order, and written a batch + at a time, so a catalog of any size is read once and held in memory a batch at most.""" + + def __init__(self, conn: sqlite3.Connection, chain: int, key: bytes) -> None: + self.conn, self.chain, self.key, self.at = conn, chain, key, _now() + self.seq = self.written = 0 + self.previous = _ZERO + self.rows: list[tuple[Any, ...]] = [] + + def add(self, kind: str, path: str | None = None, doc_id: str | None = None, + digest: str | None = None, title: str | None = None, *, + horizon: int | None = None, closed_at: int | None = None) -> None: + self.seq += 1 + salt = secrets.token_bytes(16) + commit = commitment(salt, {"chain": self.chain, "seq": self.seq, "kind": kind, + "source_path": path, "doc_id": doc_id, "version": None, + "digest": digest, "title": title, "att_head": None, + "horizon": horizon, "at": self.at}) + self.previous = chain_hash(self.previous, commit) + path_key = None if path is None else _mac(self.key, path.encode("utf-8")) + self.rows.append((self.chain, self.seq, kind, path_key, path, doc_id, None, digest, title, + None, horizon, salt, commit, self.previous, closed_at, self.at)) + if len(self.rows) >= _BATCH: + self.flush() + + def flush(self) -> int: + """Write the rows held; returns every row the block has written.""" + self.conn.executemany(_INSERT, self.rows) + self.written += len(self.rows) + self.rows.clear() + return self.written + + +def cut_position(cut: Mapping[int, int] | int, chain: int, chains: Sequence[int]) -> int: + """A chain's position in a cut over a class. A cut is one position a chain; a bare integer is + accepted for a class with one chain. A chain the cut does not name is read at its empty + prefix.""" + if isinstance(cut, int): + if len(chains) != 1: + raise ValueError(f"a cut over {len(chains)} chains is one position a chain") + return cut + return int(cut.get(chain, 0)) + + +class LandingLog: + """The log's rows in the catalog's connection. The catalog calls the writing half inside the + transaction of its own row; nothing here commits.""" + + def __init__(self, conn: sqlite3.Connection, key: Callable[[], bytes]) -> None: + self._conn = conn + self._key_source = key + self._key: bytes | None = None + self._chain_keys: dict[int, bytes] = {} + + # the schema and the genesis --------------------------------------------------------------- + + def create(self) -> None: + self._conn.executescript(DDL) + + def has_chains(self) -> bool: + return self._conn.execute("SELECT 1 FROM landing_chains LIMIT 1").fetchone() is not None + + def genesis(self) -> int: + """Each class the catalog holds gets a chain: a `genesis` row, then the catalog's rows of + the class in path order, an active path as one `store` and a tombstoned path as a `store` + of the digest it held followed by its tombstone (a `move` where another active path holds + its identity, a `retire` otherwise), then a `horizon` row whose horizon is its own + position. The order inside the block is not history, so the positions before the horizon + are under it (§8). Returns the rows written.""" + written = 0 + classes = [str(r[0]) for r in self._conn.execute( + "SELECT DISTINCT provenance FROM vault_files ORDER BY provenance")] + held = {str(r[0]) for r in self._conn.execute( + "SELECT DISTINCT doc_id FROM vault_files WHERE active = 1 AND doc_id IS NOT NULL")} + for cls in classes: + block = _Block(self._conn, *self._new_chain(cls)) + block.add("genesis") + for path, digest, title, active, doc_id in self._conn.execute( + "SELECT source_path, digest, title, active, doc_id FROM vault_files " + "WHERE provenance = ? ORDER BY source_path", [cls]).fetchall(): + doc = str(doc_id) if doc_id is not None else str(path) + if active: + block.add("store", path, doc, digest, title) + else: + block.add("store", path, doc, digest, title, closed_at=block.seq + 2) + block.add("move" if doc in held else "retire", path, doc) + block.add("horizon", horizon=block.seq + 1) + written += block.flush() + return written + + # keys ----------------------------------------------------------------------------------- + + def _instance_key(self) -> bytes: + if self._key is None: + self._key = self._key_source() + return self._key + + def _chain_key(self, chain: int) -> bytes: + key = self._chain_keys.get(chain) + if key is None: + row = self._conn.execute( + "SELECT secret, key_check FROM landing_chains WHERE chain = ?", [chain]).fetchone() + if row is None: + raise KeyError(f"no landing chain {chain}") + key = _mac(self._instance_key(), b"landing chain\x00" + bytes(row[0])) + if not hmac.compare_digest(_mac(key, b"key check"), bytes(row[1])): + raise LandingLogKeyMismatch( + f"the landing-log secret is not the one chain {chain} was written with; " + "nothing was written") + self._chain_keys[chain] = key + return key + + def path_key(self, chain: int, path: str) -> bytes: + """The key a row of `path` carries in `chain`.""" + return _mac(self._chain_key(chain), path.encode("utf-8")) + + def _new_chain(self, cls: str) -> tuple[int, bytes]: + secret = secrets.token_bytes(32) + key = _mac(self._instance_key(), b"landing chain\x00" + secret) + chain = int(self._conn.execute( + "SELECT coalesce(max(chain), 0) + 1 FROM landing_chains").fetchone()[0]) + self._conn.execute( + "INSERT INTO landing_chains (chain, class, secret, key_check) VALUES (?, ?, ?, ?)", + [chain, cls, secret, _mac(key, b"key check")]) + self._chain_keys[chain] = key + return chain, key + + def _open_chain(self, cls: str) -> int: + """A class that first appears after the genesis opens its chain at its first landing: a + `genesis` and a `horizon`, and nothing between.""" + chain, _ = self._new_chain(cls) + self._append(chain, "genesis") + self._append(chain, "horizon", horizon=2) + return chain + + # appending ------------------------------------------------------------------------------ + + def _append(self, chain: int, kind: str, *, path: str | None = None, + doc_id: str | None = None, version: int | None = None, + digest: str | None = None, title: str | None = None, + horizon: int | None = None) -> int: + last = self._conn.execute( + "SELECT seq, hash FROM landings WHERE chain = ? ORDER BY seq DESC LIMIT 1", + [chain]).fetchone() + seq = 1 if last is None else int(last[0]) + 1 + previous = _ZERO if last is None else bytes(last[1]) + at = _now() + salt = secrets.token_bytes(16) + commit = commitment(salt, {"chain": chain, "seq": seq, "kind": kind, "source_path": path, + "doc_id": doc_id, "version": version, "digest": digest, + "title": title, "att_head": None, "horizon": horizon, + "at": at}) + path_key = None + if path is not None: + path_key = self.path_key(chain, path) + # the path's previous event in the chain is closed at this one (§3.2) + self._conn.execute( + "UPDATE landings SET closed_at = ? WHERE chain = ? AND path_key = ? " + "AND closed_at IS NULL", [seq, chain, path_key]) + self._conn.execute(_INSERT, [chain, seq, kind, path_key, path, doc_id, version, digest, + title, None, horizon, salt, commit, + chain_hash(previous, commit), None, at]) + return seq + + def _class_of(self, chain: int) -> str: + return str(self._conn.execute( + "SELECT class FROM landing_chains WHERE chain = ?", [chain]).fetchone()[0]) + + def _locate(self, path: str, cls: str | None) -> tuple[Landing | None, list[int]]: + """The path's last event in the chain that holds its present, the one chain where the + path's last event is not a `leave`, with the chains seen to hold only a `leave` of it. The + chains of `cls`, the class the catalog gives the path, are asked first; a path the + catalog does not hold is looked for in every chain.""" + first = self.chains(cls) if cls is not None else [] + left: list[int] = [] + for chain in [*first, *(c for c in self.all_chains() if c not in first)]: + row = self._seek(chain, path) + if row is None: + continue + if row.kind != "leave": + return row, left + left.append(chain) + return None, left + + def _target(self, cls: str, left: Sequence[int]) -> int: + """The chain a landing goes to when the path's present is in no chain of its class: a + chain of the class the path left, else the newest chain of the class, opened if the class + has none (§3.2).""" + chains = self.chains(cls) + back = [c for c in chains if c in left] + if back: + return back[-1] + return chains[-1] if chains else self._open_chain(cls) + + def store(self, path: str, cls: str, doc_id: str, version: int | None, digest: str, + title: str, prior: Prior | None) -> None: + """A landing of `path` (`record`): a `store` in the chain that holds the path's last event, + after a `move` when the landing changes the identity the path holds, or after a `leave` + of the path's chain when it changes the path's class.""" + current, left = self._locate(path, prior.provenance if prior is not None else None) + if current is not None and self._class_of(current.chain) == cls: + target = current.chain + if current.kind == "store" and not current.hole and current.doc_id != doc_id: + self._append(target, "move", path=path, doc_id=current.doc_id) + else: + target = self._target(cls, left) + if current is not None: + self._append(current.chain, "leave", path=path, + doc_id=current.doc_id or (prior.doc_id if prior else None)) + self._append(target, "store", path=path, doc_id=doc_id, version=version, digest=digest, + title=title) + + def tombstone(self, path: str, prior: Prior, kind: str) -> None: + """A tombstone of an active path (`tombstone`): a `retire`, or a `move` when another + active path holds the identity.""" + current, left = self._locate(path, prior.provenance) + chain = current.chain if current is not None else self._target(prior.provenance, left) + self._append(chain, kind, path=path, doc_id=prior.doc_id) + + def rekey(self, path: str, prior: Prior, doc_id: str) -> None: + """The owner-gated re-key of a path's identity (`migrate_rekey_doc_id`): a `move` of the + identity it held, then the path under the new one, a `store` of what it holds when it is + active and a `retire` when it is tombstoned.""" + current, left = self._locate(path, prior.provenance) + chain = current.chain if current is not None else self._target(prior.provenance, left) + self._append(chain, "move", path=path, doc_id=prior.doc_id) + if prior.active: + version = current.version if current is not None and current.kind == "store" else None + self._append(chain, "store", path=path, doc_id=doc_id, version=version, + digest=prior.digest, title=prior.title) + else: + self._append(chain, "retire", path=path, doc_id=doc_id) + + def relabel(self, old: str, new: str) -> None: + """A whole-class relabel rewrites the label of the class's chains and no row (§3.1).""" + self._conn.execute("UPDATE landing_chains SET class = ? WHERE class = ?", [new, old]) + + def empty_path(self, path: str) -> int: + """`remove`: every row of the path emptied as §6.1 says, its key and position kept.""" + n = 0 + for chain in self.all_chains(): + n += self._conn.execute( + f"UPDATE landings SET {_EMPTY} WHERE chain = ? AND path_key = ? " + "AND salt IS NOT NULL", [chain, self.path_key(chain, path)]).rowcount + return n + + def empty_digest(self, digest: str) -> int: + """`remove_digest`: every row of the digest emptied as §6.1 says, its key and position + kept. Another version of the same path is not touched.""" + return self._conn.execute( + f"UPDATE landings SET {_EMPTY} WHERE digest = ?", [digest]).rowcount + + # reads ---------------------------------------------------------------------------------- + + def all_chains(self) -> list[int]: + return [int(r[0]) for r in self._conn.execute( + "SELECT chain FROM landing_chains ORDER BY chain")] + + def chains(self, cls: str) -> list[int]: + """The chains that hold `cls` now, oldest first.""" + return [int(r[0]) for r in self._conn.execute( + "SELECT chain FROM landing_chains WHERE class = ? ORDER BY chain", [str(cls)])] + + def head(self, chain: int) -> int: + """The chain's last position: the head cut on it.""" + row = self._conn.execute("SELECT max(seq) FROM landings WHERE chain = ?", + [chain]).fetchone() + return int(row[0]) if row is not None and row[0] is not None else 0 + + def read_at(self, chain: int, c: int) -> list[Landing]: + """The prefix of the chain at `c`: the rows with `seq ≤ c`, in order.""" + return [_landing(r) for r in self._conn.execute( + f"SELECT {_COLUMNS} FROM landings WHERE chain = ? AND seq <= ? ORDER BY seq", + [chain, c])] + + def read_between(self, chain: int, a: int, b: int) -> list[Landing]: + """The rows after `a` and up to `b`, in order.""" + return [_landing(r) for r in self._conn.execute( + f"SELECT {_COLUMNS} FROM landings WHERE chain = ? AND seq > ? AND seq <= ? " + "ORDER BY seq", [chain, a, b])] + + def _seek(self, chain: int, path: str, c: int | None = None) -> Landing | None: + """The path's last event in the chain at or under `c` (the head when `None`): one seek on + `landings_path`, which the statement names.""" + row = self._conn.execute( + f"SELECT {_COLUMNS} FROM landings INDEXED BY landings_path " + "WHERE chain = ? AND path_key = ? AND seq <= ? ORDER BY seq DESC LIMIT 1", + [chain, self.path_key(chain, path), (1 << 62) if c is None else c]).fetchone() + return _landing(row) if row is not None else None + + def state_at(self, cls: str, path: str, c: Mapping[int, int] | int) -> Landing | None: + """The path's last event at or under the cut over the class's chains: a `store`, a + `retire`, a `move`, a `leave`, a hole (a row a purge emptied, with its position and no + name), or nothing. A path has events in two chains of one class only after it changed + class and the two classes were merged; then the event that is not a `leave` is the + path's at the cut, and among two such the later chain's, a rule of the prefix alone.""" + chains = self.chains(cls) + found = [r for chain in chains + if (r := self._seek(chain, path, cut_position(c, chain, chains))) is not None] + staying = [r for r in found if r.kind != "leave"] or found + return staying[-1] if staying else None + + def history_at(self, cls: str, path: str, c: Mapping[int, int] | int) -> list[Landing]: + """The path's `store` rows at or under the cut over the class's chains, oldest first, a + hole where a version was purged. Where the path has events in two chains of the class, + the chains it had left at the cut come first: a rule of the prefix alone.""" + chains = self.chains(cls) + parts: list[tuple[bool, int, list[Landing]]] = [] + for chain in chains: + rows = [_landing(r) for r in self._conn.execute( + f"SELECT {_COLUMNS} FROM landings INDEXED BY landings_path " + "WHERE chain = ? AND path_key = ? AND seq <= ? ORDER BY seq", + [chain, self.path_key(chain, path), cut_position(c, chain, chains)])] + if rows: + parts.append((rows[-1].kind != "leave", chain, + [r for r in rows if r.kind == "store"])) + return [r for _, _, stores in sorted(parts, key=lambda p: (p[0], p[1])) for r in stores] + + def heads_at(self, cls: str, c: Mapping[int, int] | int) -> list[Landing]: + """Every head of the class at the cut: the `store` rows with `seq ≤ c` whose closing + stamp is absent or above `c`, over the class's chains (§4.2), a hole returned as a hole + with its position and no name.""" + chains = self.chains(cls) + out: list[Landing] = [] + for chain in chains: + pos = cut_position(c, chain, chains) + out.extend(_landing(r) for r in self._conn.execute( + f"SELECT {_COLUMNS} FROM landings WHERE chain = ? AND seq <= ? " + "AND kind = 'store' AND (closed_at IS NULL OR closed_at > ?) ORDER BY seq", + [chain, pos, pos])) + return out + + def rows(self, chain: int) -> Iterator[Landing]: + """Every row of the chain, in order.""" + for r in self._conn.execute( + f"SELECT {_COLUMNS} FROM landings WHERE chain = ? ORDER BY seq", [chain]): + yield _landing(r) + + def verify(self, chain: int) -> ChainCheck: + """The chain's hashes recomputed from its first row, and the commitment of every row that + still has its salt (SNP-9): the first position where either fails, or none.""" + previous = _ZERO + n = checked = 0 + for row in self.rows(chain): + n += 1 + if row.seq != n: + return ChainCheck(chain, n, checked, n, "a position is missing") + if row.salt is not None: + checked += 1 + if not hmac.compare_digest(commitment(row.salt, row.fields()), row.commitment): + return ChainCheck(chain, n, checked, row.seq, "the commitment") + if not hmac.compare_digest(chain_hash(previous, row.commitment), row.hash): + return ChainCheck(chain, n, checked, row.seq, "the hash") + previous = row.hash + return ChainCheck(chain, n, checked) diff --git a/tests/conftest.py b/tests/conftest.py index 3714f65e..611b1558 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -80,3 +80,19 @@ def _isolate_from_the_instance_overlay(monkeypatch: pytest.MonkeyPatch, loader.get_config.cache_clear() yield loader.get_config.cache_clear() + + +# The landing log's secret for the suite: fixed, so a run is reproducible, and no instance's. +LANDING_LOG_TEST_KEY = bytes(range(32)).hex() + + +@pytest.fixture(autouse=True) +def _landing_log_test_key() -> Iterator[None]: + """Every catalog a test writes keys its landing log (dn-temporal-snapshot §3.2) with the + suite's fixed secret, read from the environment as an instance reads its own. A test of the + refusal without one deletes it. Its own patch, so a test's `monkeypatch.undo()` keeps it.""" + from core.stores.landings import LANDING_LOG_KEY + + with pytest.MonkeyPatch.context() as mp: + mp.setenv(LANDING_LOG_KEY, LANDING_LOG_TEST_KEY) + yield diff --git a/tests/property/test_landing_log.py b/tests/property/test_landing_log.py new file mode 100644 index 00000000..7b3b4e03 --- /dev/null +++ b/tests/property/test_landing_log.py @@ -0,0 +1,592 @@ +"""The landing log's laws on the code (dn-temporal-snapshot §3.2, §10; stage SN-1). + +The log is the catalog's past: the six writing methods of `VaultCatalog` append to it in the +transaction of the row each writes, and the catalog is its fold. Hypothesis draws sequences of +catalog writes over a few paths, digests, titles and classes, with retires, renames, relabels, +re-keys and both purges among them, and after every write checks that the catalog is the fold +of the log and that every chain verifies. The laws, as §10 states them for this stage: + +* SNP-1, append invariance: the read of a chain at a cut, and the state of every path at it, + taken after every later write, are the ones taken when the cut was the head, up to the holes a + later purge leaves (a purge empties rows and keeps their positions, SNP-7). +* SNP-2, monotonicity: the read at an earlier cut is a prefix of the read at a later one. +* SNP-3, composition: the catalog rebuilt from the state at a checkpoint and the delta since is + the catalog. +* SNP-4, idempotence: the read at the head is the chain, and the state at the head the catalog. +* SNP-5, three reads: at every position of every chain the seek by key, the closing-stamp read + and the fold of the prefix give each path the same row, before and after rows are emptied, and + no path has two rows alive. + +Then the stage's own cases: a record that changes nothing, and a store the UNCHANGED check +skips, append nothing; a transaction killed between the catalog's row and the log's leaves +neither; the genesis is the catalog, tombstoned paths included, and ends at a horizon; a relabel +into a class that has rows changes no row of the log and every chain verifies; a purge of an old +version of a live path leaves a hole that all three reads return at a cut where it was the head; +`verify` fails on an edited row; the secret is required, and another one is refused. +""" + +from __future__ import annotations + +import os +import sqlite3 +import subprocess +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from core.kernel.provenance import Provenance +from core.stores.authored_supersession import owner_declaration +from core.stores.catalog import VaultCatalog +from core.stores.landings import ( + LANDING_LOG_KEY, + Landing, + LandingLogKeyMismatch, + LandingLogKeyMissing, +) +from core.stores.versions import RekeyRefusedError +from tests.conftest import LANDING_LOG_TEST_KEY +from tests.fixtures.ingress import palace_at, write_file + +PATHS = [f"notes/n{i}.md" for i in range(5)] +DIGESTS = [f"d{i}" for i in range(6)] +TITLES = ["one", "two"] +CLASSES = [Provenance.AUTHORED_SOLO, Provenance.CURATED, Provenance.OBSERVED] +IDS = ["id-a", "id-b"] + +Row = tuple[str, str, str, bool, str] # digest, title, class, active, identity + + +# --- the fold of the log, from its rows alone --------------------------------------------------- + +@dataclass +class Fold: + """Each path's last row and last `store` row, chain by chain, keyed by its key in the chain, + and the name each key carries on its rows that still have one.""" + + last: dict[tuple[int, bytes], Landing] = field(default_factory=dict) + store: dict[tuple[int, bytes], Landing] = field(default_factory=dict) + names: dict[tuple[int, bytes], str] = field(default_factory=dict) + + def step(self, row: Landing) -> None: + if row.path_key is None: + return + k = (row.chain, row.path_key) + self.last[k] = row + if row.kind == "store": + self.store[k] = row + if row.source_path is not None: + self.names[k] = row.source_path + + def catalog(self, classes: dict[int, str]) -> dict[str, Row]: + """The catalog this fold gives (§3.2): each path's last event in the chain that holds its + present (the one where its last event is not a `leave`), an active row for a `store`, a + tombstoned row for a `retire` or a `move` with the digest and title of the path's last + `store`, and no row when that `store` is a hole.""" + keys: dict[str, list[tuple[int, bytes]]] = {} + for k, name in self.names.items(): + keys.setdefault(name, []).append(k) + out: dict[str, Row] = {} + for name, ks in keys.items(): + present = [k for k in ks if self.last[k].kind != "leave"] + assert len(present) <= 1, f"{name} has its present in {len(present)} chains" + if not present: + continue + k = present[0] + last, store = self.last[k], self.store.get(k) + if last.kind == "store": + if not last.hole: + out[name] = (str(last.digest), str(last.title), classes[k[0]], True, + str(last.doc_id)) + elif store is not None and not store.hole: + out[name] = (str(store.digest), str(store.title), classes[k[0]], False, + str(last.doc_id)) + return out + + +def chains(cat: VaultCatalog) -> list[int]: + return cat._log.all_chains() + + +def classes(cat: VaultCatalog) -> dict[int, str]: + return {int(r[0]): str(r[1]) for r in cat._conn.execute( + "SELECT chain, class FROM landing_chains")} + + +def heads(cat: VaultCatalog) -> dict[int, int]: + return {ch: cat.head(ch) for ch in chains(cat)} + + +def fold(cat: VaultCatalog, cut: dict[int, int] | None = None) -> Fold: + f = Fold() + for ch in chains(cat): + for row in cat.read_at(ch, cut.get(ch, 0) if cut is not None else cat.head(ch)): + f.step(row) + return f + + +def rows_of(conn: sqlite3.Connection) -> dict[str, Row]: + return {str(r[0]): (str(r[1]), str(r[2]), str(r[3]), bool(r[4]), str(r[5])) + for r in conn.execute( + "SELECT source_path, digest, title, provenance, active, doc_id FROM vault_files")} + + +def catalog_rows(cat: VaultCatalog) -> dict[str, Row]: + return rows_of(cat._conn) + + +def all_rows(cat: VaultCatalog) -> list[tuple[Any, ...]]: + return [tuple(r) for r in cat._conn.execute("SELECT * FROM landings ORDER BY chain, seq")] + + +def alive(row: Landing, c: int) -> bool: + return row.seq <= c and (row.closed_at is None or row.closed_at > c) + + +def same_up_to_holes(now: Landing, then: Landing, c: int) -> bool: + """A row read again after later writes: the same position, kind, key, commitment and hash; the + same content unless a purge has emptied it since; alive at `c` exactly when it was.""" + if (now.seq, now.kind, now.path_key, now.commitment, now.hash) != \ + (then.seq, then.kind, then.path_key, then.commitment, then.hash): + return False + if alive(now, c) != alive(then, c): + return False + return now.hole or now == Landing(**{**then.__dict__, "closed_at": now.closed_at}) + + +def assert_consistent(cat: VaultCatalog) -> None: + """After every write: the catalog is the fold of the log, and every chain verifies.""" + assert fold(cat).catalog(classes(cat)) == catalog_rows(cat) + for ch in chains(cat): + check = cat.verify(ch) + assert check.ok, check + + +# --- the writes ----------------------------------------------------------------------------------- + +record_op = st.tuples(st.just("record"), st.sampled_from(PATHS), st.sampled_from(DIGESTS), + st.sampled_from(TITLES), st.sampled_from(CLASSES), + st.one_of(st.none(), st.sampled_from(IDS)), + st.one_of(st.none(), st.integers(1, 9))) +ops = st.lists(st.one_of( + record_op, record_op, record_op, + st.tuples(st.just("tombstone"), st.sampled_from(PATHS)), + st.tuples(st.just("rename"), st.sampled_from(PATHS), st.sampled_from(PATHS)), + st.tuples(st.just("relabel"), st.sampled_from(CLASSES), st.sampled_from(CLASSES)), + st.tuples(st.just("purge"), st.sampled_from(DIGESTS)), + st.tuples(st.just("remove"), st.sampled_from(PATHS)), + st.tuples(st.just("rekey"), st.sampled_from(PATHS), st.sampled_from(["id-x", "id-y"])), +), min_size=3, max_size=40) + + +def apply(cat: VaultCatalog, op: tuple[Any, ...]) -> None: + """One write, as the code's callers make it: a rename lands the new path with the old one's + identity and then tombstones the old one (the writer and the sync); a purge removes only a + digest no active path holds (`purge_raw`'s gate).""" + match op: + case ("record", path, digest, title, cls, doc_id, version): + cat.record(path, digest, title, provenance=cls, doc_id=doc_id, version=version) + case ("tombstone", path): + cat.tombstone(path) + case ("rename", old, new): + held = cat.get(old) + if old != new and held is not None and held.active and cat.get(new) is None: + cat.record(new, held.digest, held.title, provenance=Provenance(held.provenance), + doc_id=cat.doc_id_for(old)) + cat.tombstone(old) + case ("relabel", old, new): + cat.relabel_provenance(str(old), str(new)) + case ("purge", digest): + if cat.active_refs(digest) == 0: + cat.remove_digest(digest) + case ("remove", path): + cat.remove(path) + case ("rekey", path, new): + try: + cat.migrate_rekey_doc_id(path, new, declaration=owner_declaration()) + except RekeyRefusedError: + pass + + +@dataclass +class Taken: + """A cut taken at the head, with what was read at it then.""" + + cut: dict[int, int] + reads: dict[int, list[Landing]] + states: dict[tuple[str, str], Landing | None] + class_chains: dict[str, list[int]] + + +def take(cat: VaultCatalog) -> Taken: + cut = heads(cat) + names = sorted({*PATHS, *catalog_rows(cat)}) + class_chains = {str(c): cat.chains(c) for c in CLASSES} + return Taken(cut, {ch: cat.read_at(ch, c) for ch, c in cut.items()}, + {(cls, p): cat.state_at(cls, p, cut) for cls in class_chains + for p in names if class_chains[cls]}, + class_chains) + + +def assert_unchanged(cat: VaultCatalog, taken: Taken) -> None: + """SNP-1: a cut taken earlier reads what it read then, up to the holes a purge left.""" + for ch, c in taken.cut.items(): + now = cat.read_at(ch, c) + assert len(now) == len(taken.reads[ch]) + assert all(same_up_to_holes(a, b, c) for a, b in zip(now, taken.reads[ch], strict=True)) + for (cls, path), then in taken.states.items(): + if cat.chains(cls) != taken.class_chains[cls]: + continue # a relabel gave the class another chain since + now_state = cat.state_at(cls, path, taken.cut) + if then is None: + assert now_state is None + else: + assert now_state is not None + assert same_up_to_holes(now_state, then, taken.cut[then.chain]) + + +def assert_three_reads(cat: VaultCatalog) -> None: + """SNP-5: at every position of every chain, for every path, the seek by key, the closing-stamp + read and the fold of the prefix agree, and no path has two rows alive. The heads of the class + at the position are the rows of the fold that are `store`s, and the history of a path is its + `store` rows in the prefix.""" + names = sorted({*PATHS, "id-x", "id-y", *catalog_rows(cat)}) + cls_of = classes(cat) + for ch in chains(cat): + rows = cat.read_at(ch, cat.head(ch)) + cls = cls_of[ch] + for c in range(cat.head(ch) + 1): + prefix = rows[:c] + f = Fold() + for row in prefix: + f.step(row) + living: dict[bytes, list[Landing]] = {} + for row in prefix: + if row.path_key is not None and alive(row, c): + living.setdefault(row.path_key, []).append(row) + assert all(len(rs) == 1 for rs in living.values()) + assert {k: rs[0] for k, rs in living.items()} == \ + {k[1]: r for k, r in f.last.items()} + cut = {ch: c} + assert cat.heads_at(cls, cut) == [r for r in prefix if r.kind == "store" + and alive(r, c)] + for name in names: + key = cat._log.path_key(ch, name) + assert cat.state_at(cls, name, cut) == f.last.get((ch, key)) + assert cat.history_at(cls, name, cut) == \ + [r for r in prefix if r.path_key == key and r.kind == "store"] + + +@settings(max_examples=200, deadline=None, suppress_health_check=[HealthCheck.too_slow]) +@given(ops) +def test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold( + writes: list[tuple[Any, ...]]) -> None: + """SNP-1 to SNP-5 over random catalog writes, retires, renames, relabels, re-keys and purges + among them: the catalog is the fold of the log after every write and every chain verifies; + every cut taken reads after every later write what it read then (SNP-1); at the end the + reads are prefixes of each other (SNP-2), the catalog is the state at any checkpoint + continued over the delta (SNP-3), the read at the head is the chain and the state at the + head the catalog (SNP-4), and the three reads agree at every position (SNP-5).""" + cat = VaultCatalog(Path(":memory:")) + taken: list[Taken] = [] + for op in writes: + apply(cat, op) + assert_consistent(cat) + taken.append(take(cat)) + for t in taken: + assert_unchanged(cat, t) + # SNP-2: every read of a chain is a prefix of the read at its head; SNP-4: a cut at or past + # the head reads the whole chain + for ch in chains(cat): + whole = list(cat._log.rows(ch)) + assert cat.read_at(ch, cat.head(ch)) == cat.read_at(ch, cat.head(ch) + 5) == whole + for c in range(len(whole) + 1): + assert cat.read_at(ch, c) == whole[:c] + assert cat.read_between(ch, c, len(whole)) == whole[c:] + # SNP-3: the state at each cut taken, continued over the delta since, is the catalog + for t in taken: + f = fold(cat, t.cut) + for ch in chains(cat): + for row in cat.read_between(ch, t.cut.get(ch, 0), cat.head(ch)): + f.step(row) + assert f.catalog(classes(cat)) == catalog_rows(cat) + # SNP-4: at the head the state of a path over its class's chains is the catalog's row + present = catalog_rows(cat) + for cls in {str(c) for c in CLASSES}: + if not cat.chains(cls): + continue + for path in PATHS: + state = cat.state_at(cls, path, heads(cat)) + entry = present.get(path) + if entry is not None and entry[2] == cls: + assert state is not None and not state.hole + assert (state.kind == "store") == entry[3] + if entry[3]: + assert (state.digest, state.title, state.doc_id) == \ + (entry[0], entry[1], entry[4]) + assert_three_reads(cat) + cat.close() + + +# --- the stage's cases ---------------------------------------------------------------------------- + +def test_a_record_that_changes_nothing_appends_nothing() -> None: + cat = VaultCatalog(Path(":memory:")) + cat.record("a.md", "d1", "A") + head = heads(cat) + cat.record("a.md", "d1", "A") + cat.record("a.md", "d1", "A", version=7) # the version alone is no change + assert heads(cat) == head + cat.record("a.md", "d1", "B") # a title is + assert cat.head(cat.chains(Provenance.AUTHORED_SOLO)[0]) == head[1] + 1 + cat.tombstone("a.md") + head = heads(cat) + cat.tombstone("a.md") # already tombstoned: nothing changes + cat.tombstone("nowhere.md") + assert heads(cat) == head + assert_consistent(cat) + + +def test_a_store_the_unchanged_check_skips_appends_nothing(tmp_path: Path) -> None: + """Through the writer, as the daemon lands a vault: the second sync of the same notes is + UNCHANGED and the log does not move. The store rows carry the version each landing is, the + version chain's own number; an edit appends the next; a delete is a `retire` and a rename's + tombstone a `move`.""" + p = palace_at(tmp_path) + cat = p.stores.catalog + a = write_file(p.vault, "a.md", "alpha\n") + write_file(p.vault, "b.md", "beta\n") + assert p.run("do sync_vault")["effects"] == {"landed": 2} + head = heads(cat) + assert p.run("do sync_vault")["effects"] == {"unchanged": 2} + assert heads(cat) == head + a.write_text("alpha, edited\n", encoding="utf-8") + assert p.run("do sync_vault")["effects"] == {"landed": 1, "unchanged": 1} + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + stores = [r for r in cat.read_at(chain, cat.head(chain)) + if r.kind == "store" and r.source_path == str(a)] + assert p.stores.versions is not None + assert [r.version for r in stores] == \ + [v.version_seq for v in p.stores.versions.history(cat.doc_id_for(str(a)))] == [1, 2] + a.rename(p.vault / "c.md") # the same bytes at a new path + (p.vault / "b.md").unlink() + p.run("do sync_vault") + tail = cat.read_between(chain, head[chain], cat.head(chain)) + kinds = {(r.kind, Path(str(r.source_path)).name) for r in tail} + assert {("move", "a.md"), ("retire", "b.md"), ("store", "c.md")} <= kinds + assert_consistent(cat) + + +_KILL = """ +import os, sys +from pathlib import Path +from core.stores import landings +from core.stores.catalog import VaultCatalog + +cat = VaultCatalog(Path(sys.argv[1])) +real = landings.LandingLog._append + +def die(self, chain, kind, **kw): + if kind == "store": + os._exit(9) # killed: no handler, no rollback + return real(self, chain, kind, **kw) + +landings.LandingLog._append = die +cat.record("killed.md", "dk", "K") +""" + + +def test_a_transaction_killed_between_the_two_rows_leaves_neither( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + db = tmp_path / "catalog.sqlite" + cat = VaultCatalog(db) + cat.record("kept.md", "d0", "K") + head = heads(cat) + cat.close() + env = {**os.environ, LANDING_LOG_KEY: LANDING_LOG_TEST_KEY} + done = subprocess.run([sys.executable, "-c", _KILL, str(db)], env=env, + cwd=Path(__file__).resolve().parents[2], check=False) + assert done.returncode == 9 + cat = VaultCatalog(db) + assert cat.get("killed.md") is None + assert heads(cat) == head + assert_consistent(cat) + # and in process: the write that raises after the catalog's row rolls the row back + def boom(*args: Any, **kwargs: Any) -> None: + raise RuntimeError("between the two rows") + + monkeypatch.setattr(cat._log, "store", boom) + with pytest.raises(RuntimeError): + cat.record("raised.md", "dr", "R") + assert cat.get("raised.md") is None + assert heads(cat) == head + cat.close() + + +def test_a_deferred_batch_carries_its_log_rows(tmp_path: Path) -> None: + cat = VaultCatalog(tmp_path / "catalog.sqlite") + with cat.deferred(): + cat.record("a.md", "d1", "A") + cat.record("b.md", "d2", "B") + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + head = cat.head(chain) + with pytest.raises(RuntimeError), cat.deferred(): + cat.record("c.md", "d3", "C") + cat.tombstone("a.md") + raise RuntimeError("the batch dies before its end") + assert cat.get("c.md") is None and cat.get("a.md") is not None + assert cat.head(chain) == head + assert_consistent(cat) + + +def _legacy_catalog(db: Path, rows: list[tuple[str, str, str, str, int, str]]) -> None: + """A catalog as a build before the log left it: its rows and no log.""" + with sqlite3.connect(db) as conn: + conn.execute("CREATE TABLE vault_files (source_path TEXT PRIMARY KEY, digest TEXT NOT " + "NULL, title TEXT NOT NULL, provenance TEXT NOT NULL DEFAULT " + "'authored-solo', active INTEGER NOT NULL DEFAULT 1, updated_at TEXT NOT " + "NULL, doc_id TEXT)") + conn.executemany("INSERT INTO vault_files VALUES (?, ?, ?, ?, ?, '2026-11-01', ?)", rows) + + +def test_the_genesis_is_the_catalog_and_ends_at_a_horizon(tmp_path: Path) -> None: + db = tmp_path / "catalog.sqlite" + _legacy_catalog(db, [ + ("v/a.md", "da", "A", "authored-solo", 1, "v/a.md"), + ("v/b.md", "db", "B", "authored-solo", 0, "v/b.md"), # deleted: a retire + ("v/c.md", "dc", "C", "authored-solo", 0, "v/d.md"), # renamed away: a move + ("v/d.md", "dc", "C", "authored-solo", 1, "v/d.md"), + ("dialogue/x/1", "dx", "X", "authored-dialogue", 1, "dialogue/x/1"), + ("docs/r.md", "dr", "R", "curated", 0, "docs/r.md"), + ]) + with sqlite3.connect(db) as conn: + before = rows_of(conn) + cat = VaultCatalog(db) + assert catalog_rows(cat) == before + assert fold(cat).catalog(classes(cat)) == before + assert sorted(classes(cat).values()) == ["authored-dialogue", "authored-solo", "curated"] + for ch in chains(cat): + rows = cat.read_at(ch, cat.head(ch)) + assert rows[0].kind == "genesis" and rows[-1].kind == "horizon" + assert rows[-1].horizon == rows[-1].seq == len(rows) + assert {r.kind for r in rows[1:-1]} <= {"store", "retire", "move"} + assert cat.verify(ch).ok + (solo,) = cat.chains(Provenance.AUTHORED_SOLO) + kinds = [(r.kind, r.source_path) for r in cat.read_at(solo, cat.head(solo))[1:-1]] + assert kinds == [("store", "v/a.md"), ("store", "v/b.md"), ("retire", "v/b.md"), + ("store", "v/c.md"), ("move", "v/c.md"), ("store", "v/d.md")] + head = heads(cat) + cat.close() + assert heads(VaultCatalog(db)) == head # one genesis: a reopen adds nothing + + +def test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies() -> None: + cat = VaultCatalog(Path(":memory:")) + cat.record("a.md", "d1", "A", provenance=Provenance.AUTHORED_SOLO) + cat.record("b.md", "d2", "B", provenance=Provenance.CURATED) + cat.record("c.md", "d3", "C", provenance=Provenance.CURATED) + rows = all_rows(cat) + assert cat.relabel_provenance("curated", "authored-solo") == 2 + assert all_rows(cat) == rows + assert len(cat.chains(Provenance.AUTHORED_SOLO)) == 2 and cat.chains("curated") == [] + assert_consistent(cat) + cat.record("b.md", "d4", "B", provenance=Provenance.AUTHORED_SOLO) # stays in its chain + state = cat.state_at(Provenance.AUTHORED_SOLO, "b.md", heads(cat)) + assert state is not None and state.chain == 2 and state.digest == "d4" + assert_consistent(cat) + + +def test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads() -> None: + cat = VaultCatalog(Path(":memory:")) + for d in ("d1", "d2", "d3"): + cat.record("live.md", d, "L") + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + at_d2 = next(r.seq for r in cat.read_at(chain, cat.head(chain)) if r.digest == "d2") + assert cat.active_refs("d2") == 0 # purge_raw's gate lets it through + assert cat.remove_digest("d2") == 0 # no catalog row held it + cut = {chain: at_d2} + state = cat.state_at(Provenance.AUTHORED_SOLO, "live.md", cut) + assert state is not None and state.hole and state.seq == at_d2 and state.kind == "store" + assert state.path_key == cat._log.path_key(chain, "live.md") + (head_row,) = cat.heads_at(Provenance.AUTHORED_SOLO, cut) + assert head_row.hole and head_row.seq == at_d2 and head_row.source_path is None + history = cat.history_at(Provenance.AUTHORED_SOLO, "live.md", cut) + assert [r.digest for r in history] == ["d1", None] and history[-1].hole + assert fold(cat, cut).last[(chain, state.path_key)] == state + assert catalog_rows(cat)["live.md"][0] == "d3" + assert_consistent(cat) + assert_three_reads(cat) + + +def test_verify_fails_on_an_edited_row() -> None: + cat = VaultCatalog(Path(":memory:")) + for d in ("d1", "d2", "d3"): + cat.record("a.md", d, "A") + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + assert cat.verify(chain).ok + edits = [ + ("UPDATE landings SET digest = 'forged' WHERE chain = ? AND seq = 4", 4, "the commitment"), + ("UPDATE landings SET title = 'forged' WHERE chain = ? AND seq = 3", 3, "the commitment"), + ("UPDATE landings SET commitment = zeroblob(32) WHERE chain = ? AND seq = 5", 5, + "the commitment"), + ("UPDATE landings SET hash = zeroblob(32) WHERE chain = ? AND seq = 2", 2, "the hash"), + ] + for edit, seq, why in edits: + cat._conn.execute("SAVEPOINT edit") + cat._conn.execute(edit, [chain]) + check = cat.verify(chain) + assert not check.ok and check.failed_at == seq and check.why == why + cat._conn.execute("ROLLBACK TO edit") + cat._conn.execute("RELEASE edit") + assert cat.verify(chain).ok + cat._conn.execute("UPDATE landings SET salt = NULL WHERE chain = ? AND seq = 4", [chain]) + assert cat.verify(chain).ok # an emptied row: the hash still holds + cat._conn.execute("DELETE FROM landings WHERE chain = ? AND seq = 3", [chain]) + check = cat.verify(chain) + assert not check.ok and check.failed_at == 3 + + +def test_without_the_secret_the_genesis_and_every_write_refuse(tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + db = tmp_path / "catalog.sqlite" + _legacy_catalog(db, [("a.md", "d1", "A", "authored-solo", 1, "a.md")]) + monkeypatch.delenv(LANDING_LOG_KEY) + with pytest.raises(LandingLogKeyMissing, match="landing-log-key"): + VaultCatalog(db) # the migration's genesis refuses + with sqlite3.connect(db) as conn: + assert conn.execute("SELECT count(*) FROM landings").fetchone() == (0,) + monkeypatch.setenv(LANDING_LOG_KEY, "00" * 31) # too short + with pytest.raises(LandingLogKeyMissing, match="31 bytes"): + VaultCatalog(db) + monkeypatch.setenv(LANDING_LOG_KEY, LANDING_LOG_TEST_KEY) + cat = VaultCatalog(db) + head = heads(cat) + cat.close() + monkeypatch.delenv(LANDING_LOG_KEY) + cat = VaultCatalog(db) # a read needs no key + assert cat.read_at(1, 2) == cat.read_at(1, cat.head(1))[:2] + for write in (lambda: cat.record("b.md", "d2", "B"), lambda: cat.tombstone("a.md"), + lambda: cat.remove("a.md")): + with pytest.raises(LandingLogKeyMissing): + write() + kept = cat.get("a.md") + assert heads(cat) == head and cat.get("b.md") is None and kept is not None and kept.active + + +def test_another_secret_is_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + db = tmp_path / "catalog.sqlite" + cat = VaultCatalog(db) + cat.record("a.md", "d1", "A") + head = heads(cat) + cat.close() + monkeypatch.setenv(LANDING_LOG_KEY, "ab" * 32) + cat = VaultCatalog(db) + with pytest.raises(LandingLogKeyMismatch): + cat.record("a.md", "d2", "A") + kept = cat.get("a.md") + assert heads(cat) == head and kept is not None and kept.digest == "d1" From 5365e21a786b560c55e8615befc198d599718428 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:01:41 -0500 Subject: [PATCH 07/30] ops(secrets): the landing log's secret in the wrapper and the runbook The catalog's landing log keys its hash of a path with landing-log-key, which has no switch: the first open of a catalog that has rows writes the genesis and every catalog write appends, so a process that writes the catalog refuses to without it. The wrapper now carries the item from the Keychain, and the runbook's section 0 says how to place it, that the daemon must run under the wrapper before the build is deployed, what a named instance reads, that a lost secret leaves the log unwritable, and that a rollback drops the two tables. The secrets map gains its row. Co-Authored-By: Claude Opus 5.5 --- docs/runbook.md | 21 +++++++++++++++++++++ scripts/run_with_secrets.sh | 4 +++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/runbook.md b/docs/runbook.md index 0f72fed3..a0f65156 100644 --- a/docs/runbook.md +++ b/docs/runbook.md @@ -434,6 +434,26 @@ exec env \ A secret that isn't placed yet just resolves to `None` — the corresponding layer stays off, fail-closed where it matters (see §1). Place only the ones whose layer you're turning on. +**One secret has no switch: the landing log's** (`landing-log-key`; dn-temporal-snapshot §3.2, +stage SN-1). The catalog keeps its past in two tables of its own file, and every row names its path +by a keyed hash whose key is this secret, so the file alone cannot be tested against a guess of a +purged path. The first open of a catalog that has rows writes the log's genesis, and every write of +the catalog appends to the log, so a process that writes the catalog refuses to, loudly, without +the secret (`LandingLogKeyMissing`), and writes nothing; a read needs no secret once the genesis is +written. Place it before deploying the build that brings the log, and run the daemon under the +wrapper above (it carries the item), or the daemon stops at its first open: + +```sh +openssl rand -hex 32 # 32 random bytes, as hex +security add-generic-password -U -a mind-palace -s landing-log-key -w # prompts; paste them +``` + +A named instance reads `.landing-log-key`, and the wrapper refuses a named instance, so that +instance's process must be given the item under its own name. The secret is not recoverable from +the log: a lost one leaves the log unwritable (`LandingLogKeyMismatch` for any other value), so +keep it with the attestation keys. A rollback to a build without the log drops the two tables +(`landing_chains`, `landings`); the next open of a build with the log writes a new genesis. + ### 1. Attestation signing keys — turn on the signed runtime-proof layer Activates Ed25519 signing inside `StoreAttestor.emit` (records become tamper-evident). The @@ -607,6 +627,7 @@ is Phase 5 (the bridge holding its own identity). On a single-user Mac with SSO | `attestation-signing-key` | Keychain | `build_attestor` (supervisor signer) | signs all non-gate attestations | | `attestation-owner-key` | Keychain | `build_attestor` (owner signer) | signs **gate decisions only** | | `vault-supervisor-token` | Keychain | `build_secrets_backend` | mints scoped child tokens; reads no role secret | +| `landing-log-key` | Keychain | `VaultCatalog` (`core/stores/landings.py::landing_log_key`) | keys the landing log's hash of a path; every catalog write needs it | | `vault-unseal-key` / `vault-root-token` | Keychain | the unseal LaunchAgent / you | bootstrap Vault itself | | `kv/oura-daily-aggregates` | Vault kv-v2 | `dreamer`, `correlator` tokens | biometric aggregates | | `kv/oura-api-token` | Vault kv-v2 | `bridge`, `advisor` tokens | Oura API | diff --git a/scripts/run_with_secrets.sh b/scripts/run_with_secrets.sh index 2184ba39..816b2e91 100755 --- a/scripts/run_with_secrets.sh +++ b/scripts/run_with_secrets.sh @@ -9,7 +9,8 @@ # # A secret you haven't provisioned yet resolves to empty — which is falsy, so the layer that needs # it stays fail-closed (e.g. [attestation] enabled = true with no key is a hard error). Place only -# the ones whose layer you've turned on. +# the ones whose layer you've turned on. The landing log's secret is the exception: the catalog's +# log has no switch, so a process that writes the catalog refuses to without it (runbook §0). set -eu # These are Ouroboros's items. A named instance (MIND_PALACE_OVERLAY, DI-2) reads its own, @@ -26,4 +27,5 @@ exec env \ "attestation-signing-key=$(kc attestation-signing-key)" \ "attestation-owner-key=$(kc attestation-owner-key)" \ "vault-supervisor-token=$(kc vault-supervisor-token)" \ + "landing-log-key=$(kc landing-log-key)" \ "$@" From 0d5da81e70223a9bb9fae112df71ac0ad72a51a9 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:05:25 -0500 Subject: [PATCH 08/30] feat(formal): SNP-1 to SNP-5 enter the ledger as family XVI The landing log is the first code that relies on the snapshot's laws, so the five it transcribes enter docs/LAWS.md as the temporal snapshot, family XVI: append invariance, monotonicity, composition, idempotence, and a derived view as a function of the prefixes. Each row cites the declarations section 10 of dn-temporal-snapshot lists for it, the controls among them, anchors to the catalog's reads, and names the property tests of tests/property/test_landing_log.py as its falsifiers. The 47 cited declarations carry their law in bold at the head of their docstrings (head_readAt gains the docstring it lacked, and snapshot_grow, cited under SNP-1, is marked so), are restated with their proofs left out in formal/Spec/Snapshot.lean over the model, and are judged by the comparator. SNP-6 to SNP-10 stay design theorems; the module docstring and formal/README.md say which are which. check.sh is green: 375 statements judged identical, 105 rows, 381 cited declarations, 92 law markers, 5,250 declarations audited and 56,231 replayed by the six checkers. Co-Authored-By: Claude Opus 5.5 --- docs/LAWS.md | 24 +++ formal/Palace/Snapshot.lean | 101 ++++++----- formal/README.md | 11 +- formal/Spec.lean | 1 + formal/Spec/Snapshot.lean | 349 ++++++++++++++++++++++++++++++++++++ formal/comparator.json | 47 +++++ 6 files changed, 482 insertions(+), 51 deletions(-) create mode 100644 formal/Spec/Snapshot.lean diff --git a/docs/LAWS.md b/docs/LAWS.md index 84662313..abebfc9d 100644 --- a/docs/LAWS.md +++ b/docs/LAWS.md @@ -301,3 +301,27 @@ greedy walk's localization) are design theorems of the same file. The family was | UTL-4 | the field is the fold of the tick over the use log, so appending uses continues the fold and two stores with one log have one field; at the baseline the effective weights are the structural ones, so the field is a source that an ablation switches off and the structural order is recovered (exact over any linearly ordered field; float64 exact in the simulator) | a left fold; the identity perturbation | `eval/utility_field.py::evolve`, `eval/utility_field.py::nudge` | Proposition + Claim | `tests/unit/test_utility_field.py::test_the_field_is_a_fold_over_the_log_and_switches_off_at_baseline` | `Utility.lean::evolve_append`, `Utility.lean::nudge_baseline` | | UTL-5 | the field moves the Laplacian's quadratic form by at most `θ` times the structural form, `\|xᵀ (L' − L) x\| ≤ θ xᵀ L x`, so with every degree at most `d` the nudged Laplacian is within `2θd` of the structural one as a form and, by Weyl's inequality counted (SPC-3), an eigenvalue at most `t − 2θd` stays at most `t` and one at most `t` was at most `t + 2θd`; two weights whose ratio exceeds `(1 + θ)/(1 − θ)` keep their order (exact over ℝ; float64 to `1e-9` in the simulator) | a relative perturbation of a Dirichlet form; Weyl's inequality through Courant and Fischer's dimension count | `eval/utility_field.py::laplacian`, `eval/utility_field.py::margin` | Proposition + Claim | `tests/unit/test_utility_field.py::test_the_laplacian_eigenvalues_move_within_the_bound`, `tests/unit/test_utility_field.py::test_order_is_kept_beyond_the_margin`; the control: `tests/unit/test_utility_field.py::test_control_outside_the_box_the_eigenvalues_move_past_the_bound` | `Utility.lean::abs_dotProduct_lap_sub_le`, `Utility.lean::near_lap_nudge`, `Utility.lean::count_lap_nudge_sub_le`, `Utility.lean::count_lap_nudge_le_add`, `Utility.lean::nudge_lt_nudge_of_margin` | | UTL-6 | when the tick's use is a `K`-Lipschitz function of the field with `K < lam`, the closed loop contracts the sup metric by `1 − lam + K` a tick and has exactly one stationary field; at `K ≥ lam` the loop `use = K (u − b)` holds the ceiling fixed beside the baseline, the control (exact over ℝ; float64 to `1e-12` in the simulator) | Banach's fixed point for a contraction of the sup metric | `eval/utility_field.py::closed_loop` | Proposition + Claim | `tests/unit/test_utility_field.py::test_the_closed_loop_contracts_below_the_rate`; the control: `tests/unit/test_utility_field.py::test_control_at_the_rate_the_ceiling_is_a_second_fixed_point` | `Utility.lean::loop_dist_le`, `Utility.lean::loop_existsUnique_fixedPoint` | + +## XVI. The temporal snapshot + +`core/stores/landings.py`, `core/stores/catalog.py`: the landing log of dn-temporal-snapshot (§3.2, +stage SN-1), the catalog's past as one append-only, hash-chained log a provenance class, in the +catalog's own file and written by its six writing methods in the transaction of the row each +writes, so that the catalog is the fold of the log. A chain's position is a cut of it, the read at a +cut its prefix, and a path's state at a cut its last event there. Each law here is the statement +`formal/Palace/Snapshot.lean` proves over the model `formal/Palace/Snapshot/Defs.lean`, a store as a +family of append chains and a cut as a prefix length for each, stated in `formal/Spec/Snapshot.lean` +and judged by the comparator; `tests/property/test_landing_log.py` checks the code's reads against +it over random sequences of catalog writes with retires, renames, relabels, re-keys and both purges +among them. The same file checks what no row states yet: `verify` failing on an edited row (SNP-9, +which enters with stage SN-2) and the secret the keyed hash of a path needs. SNP-6 to SNP-10 stay +design theorems of `Snapshot.lean`, cited from the note until the stage that relies on each is +built (dn-temporal-snapshot §12). Nothing reads the log yet. The family was opened on 2026-11-11. + +| law | statement | structure | anchor | label | falsifier | formal | +|---|---|---|---|---|---|---| +| SNP-1 | append invariance: the read of a chain at a cut inside the store, the read between two such cuts and every derived view of them are unchanged by any growth of the store; so are the read under an erasure and under a grant, the state of a chain of keyed writes and its generations, the history of a key with no seal and of an identity keyed by its lives, a retire among the growth included, and the filtered read of the references a resolver does not follow; the controls: a reader that ignores the cut is not append invariant, and a later retire empties the history a seal serves (exact: finite lists; on the code, every cut taken during a sequence of catalog writes reads after every later write the rows and the state of every path it read then, up to the holes a later purge leaves, which keep their positions, keys, commitments and hashes) | the prefix of an append-only sequence, a function of the prefix | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_grow`, `Snapshot.lean::readAt_of_extends`, `Snapshot.lean::readBetween_grow`, `Snapshot.lean::appendInvariant_view`, `Snapshot.lean::visible_grow`, `Snapshot.lean::snapshot_grow`, `Snapshot.lean::shown_grow`, `Snapshot.lean::stateAt_append`, `Snapshot.lean::genRead_gens_append`, `Snapshot.lean::landingsAt_append`, `Snapshot.lean::landingsAt_lives_append`, `Snapshot.lean::kept_grown_iff`; the controls: `Snapshot.lean::Witness.present_not_appendInvariant`, `Snapshot.lean::Witness.seal_empties_history` | +| SNP-2 | monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a later one, an event read at a cut is read at every later cut, a cut of a cut is the meet of the two, and the head of the read at a cut is the meet of the cut and the head; so are the read under an erasure, the history of a key with no seal, and the filtered read (exact: finite lists; on the code, every read of a chain is a prefix of the read at its head, and the rows between a cut and the head are the rest) | the prefix order on lists; cuts as a lattice | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.read_between` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_mono`, `Snapshot.lean::mem_readAt_of_le`, `Snapshot.lean::readAt_readAt`, `Snapshot.lean::head_readAt`, `Snapshot.lean::visible_mono`, `Snapshot.lean::landingsAt_mono`, `Snapshot.lean::Kept.mono` | +| SNP-3 | composition: the read at `a` followed by the read between `a` and `b` is the read at `b`, and two adjacent reads-between compose, so a fold continued from a checkpoint over the delta is the fold of the prefix, for a store and for a chain of keyed writes; an event, or a pair of events, read at the later cut was read at the earlier one or lies in the delta, and a key the delta does not write has one state at both cuts (exact: finite lists; on the code, the catalog folded from every cut taken and continued over the rows since is the catalog) | a left fold over a concatenation | `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_append_readBetween`, `Snapshot.lean::readBetween_append`, `Snapshot.lean::foldAt_readBetween`, `Snapshot.lean::stateAt_eq_foldl`, `Snapshot.lean::mem_readAt_iff`, `Snapshot.lean::pair_readAt`, `Snapshot.lean::stateAt_eq_of_not_written` | +| SNP-4 | idempotence: a cut at or past the head reads the store, so the read at the head is the store and every derived view at it is the present's: the generations read the store rewritten in place, a grant's snapshot and what an asker is shown are the grant's restriction of the store, what is visible is the store without the erased events, the history of a key with no seal is its every landing, and each seal serves at the head what the key holds live (exact: finite lists; on the code, a cut at or past a chain's head reads the whole chain, and the state of a path at the head is its catalog row; the genesis is the catalog, tombstoned paths included, and ends at a horizon) | the identity read: `as of` the head is no `as of` | `core/stores/catalog.py::VaultCatalog.head`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.genesis` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_the_genesis_is_the_catalog_and_ends_at_a_horizon` | `Snapshot.lean::readAt_head`, `Snapshot.lean::readAt_of_head_le`, `Snapshot.lean::view_head`, `Snapshot.lean::genRead_gens_length`, `Snapshot.lean::snapshot_head`, `Snapshot.lean::shown_head`, `Snapshot.lean::landingsAt_length`, `Snapshot.lean::visible_head`, `Snapshot.lean::servedAt_length`, `Snapshot.lean::servedNow_length`, `Snapshot.lean::historyAt_length` | +| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, a write killed between the catalog's row and the log's leaving neither, a batch carrying its log rows, and a record that changes nothing and a store the UNCHANGED check skips appending nothing; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place, and no path has two rows alive; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/catalog.py::VaultCatalog.heads_at`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_a_transaction_killed_between_the_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | diff --git a/formal/Palace/Snapshot.lean b/formal/Palace/Snapshot.lean index 55e25999..f635efb1 100644 --- a/formal/Palace/Snapshot.lean +++ b/formal/Palace/Snapshot.lean @@ -13,7 +13,9 @@ public import Mathlib.Order.Sublattice Design theorems of `docs/design-notes/dn-temporal-snapshot.md`, proved before any code reads a store at a cut, on the model of `Palace/Snapshot/Defs.lean`: a store is a family of append chains, -a cut a prefix length for each. Cited from the note, not from the ledger. +a cut a prefix length for each. SNP-1 to SNP-5 are the ledger's (`docs/LAWS.md`, XVI) since stage +SN-1 built the landing log: each declaration a row cites carries its law in bold and is stated in +`formal/Spec/Snapshot.lean`. SNP-6 to SNP-10 are cited from the note. * SNP-1, append invariance: a read at a cut inside the store, a read between two such cuts and every derived view of them are the same after any growth of the store (`readAt_grow`, @@ -144,47 +146,48 @@ theorem Extends.exists_grow {s s' : Store K α} (h : Extends s s') : ∃ t, s' = theorem Extends.head_le {s s' : Store K α} (h : Extends s s') : head s ≤ head s' := fun k ↦ (h k).length_le -/-- SNP-1 Append invariance: the read at a cut inside the store does not change when the store +/-- **SNP-1** Append invariance: the read at a cut inside the store does not change when the store grows. -/ theorem readAt_grow {s : Store K α} (t : Store K α) {c : Cut K} (h : c ≤ head s) : readAt (grow s t) c = readAt s c := funext fun k ↦ List.take_append_of_le_length (h k) -/-- SNP-1 The same over every extension: a later state of an append-only store reads, at a cut +/-- **SNP-1** The same over every extension: a later state of an append-only store reads, at a cut of an earlier state, what the earlier state read. -/ theorem readAt_of_extends {s s' : Store K α} {c : Cut K} (h : Extends s s') (hc : c ≤ head s) : readAt s' c = readAt s c := by obtain ⟨t, rfl⟩ := h.exists_grow exact readAt_grow t hc -/-- SNP-1 The read between two cuts inside the store does not change when the store grows. -/ +/-- **SNP-1** The read between two cuts inside the store does not change when the store grows. -/ theorem readBetween_grow {s : Store K α} (t : Store K α) (a : Cut K) {b : Cut K} (h : b ≤ head s) : readBetween (grow s t) a b = readBetween s a b := funext fun k ↦ congrArg (List.drop (a k)) (List.take_append_of_le_length (h k)) -/-- SNP-1 Every derived view is append invariant. -/ +/-- **SNP-1** Every derived view is append invariant. -/ theorem appendInvariant_view (D : Store K α → β) : AppendInvariant (view D) := fun _ t _ h ↦ congrArg D (readAt_grow t h) theorem readAt_extends (s : Store K α) (c : Cut K) : Extends (readAt s c) s := fun k ↦ List.take_prefix (c k) (s k) -/-- SNP-2 Monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a +/-- **SNP-2** Monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a later one. -/ theorem readAt_mono (s : Store K α) {c d : Cut K} (h : c ≤ d) : Extends (readAt s c) (readAt s d) := fun k ↦ List.take_prefix_take_left (h k) -/-- SNP-2 An event read at a cut is read at every later cut. -/ +/-- **SNP-2** An event read at a cut is read at every later cut. -/ theorem mem_readAt_of_le {s : Store K α} {c d : Cut K} (h : c ≤ d) {k : K} {a : α} (ha : a ∈ readAt s c k) : a ∈ readAt s d k := (readAt_mono s h k).subset ha -/-- SNP-2 A cut of a cut is the meet of the two. -/ +/-- **SNP-2** A cut of a cut is the meet of the two. -/ theorem readAt_readAt (s : Store K α) (c d : Cut K) : readAt (readAt s c) d = readAt s (d ⊓ c) := funext fun _ ↦ List.take_take +/-- **SNP-2** The head of the read at a cut is the meet of the cut and the store's head. -/ theorem head_readAt (s : Store K α) (c : Cut K) : head (readAt s c) = c ⊓ head s := funext fun _ ↦ List.length_take @@ -192,14 +195,14 @@ theorem head_readAt_of_le {s : Store K α} {c : Cut K} (h : c ≤ head s) : head (readAt s c) = c := by rw [head_readAt, inf_of_le_left h] -/-- SNP-4 A cut at or past the head reads the store. -/ +/-- **SNP-4** A cut at or past the head reads the store. -/ theorem readAt_of_head_le {s : Store K α} {c : Cut K} (h : head s ≤ c) : readAt s c = s := funext fun k ↦ List.take_of_length_le (h k) -/-- SNP-4 Idempotence: the read at the head cut is the store. -/ +/-- **SNP-4** Idempotence: the read at the head cut is the store. -/ theorem readAt_head (s : Store K α) : readAt s (head s) = s := readAt_of_head_le le_rfl -/-- SNP-4 Every derived view at the head cut is the derivation of the present: `as of` the +/-- **SNP-4** Every derived view at the head cut is the derivation of the present: `as of` the current cut is no `as of`. -/ theorem view_head (D : Store K α → β) (s : Store K α) : view D s (head s) = D s := congrArg D (readAt_head s) @@ -212,7 +215,7 @@ theorem drop_take_append_drop (l : List α) {a b : ℕ} (h : a ≤ b) : · rw [List.length_take, Nat.min_eq_left hb, Nat.sub_eq_zero_of_le h, List.drop_zero] · rw [List.drop_of_length_le hb, List.drop_nil] -/-- SNP-3 Composition: the read at `a` followed by the read between `a` and `b` is the read at +/-- **SNP-3** Composition: the read at `a` followed by the read between `a` and `b` is the read at `b`. -/ theorem readAt_append_readBetween (s : Store K α) {a b : Cut K} (h : a ≤ b) : grow (readAt s a) (readBetween s a b) = readAt s b := by @@ -222,7 +225,7 @@ theorem readAt_append_readBetween (s : Store K α) {a b : Cut K} (h : a ≤ b) : change (s k).take (a k) ++ ((s k).take (b k)).drop (a k) = (s k).take (b k) rw [h1, List.take_append_drop] -/-- SNP-3 Two adjacent reads-between compose. -/ +/-- **SNP-3** Two adjacent reads-between compose. -/ theorem readBetween_append (s : Store K α) {a b c : Cut K} (hab : a ≤ b) (hbc : b ≤ c) : grow (readBetween s a b) (readBetween s b c) = readBetween s a c := by funext k @@ -251,7 +254,7 @@ theorem readBetween_head (s : Store K α) (a : Cut K) : change ((s k).take (s k).length).drop (a k) = (s k).drop (a k) rw [List.take_length] -/-- SNP-3 The journal: a fold of the prefixes at a later cut is the fold at an earlier cut +/-- **SNP-3** The journal: a fold of the prefixes at a later cut is the fold at an earlier cut continued over the events between the two. A job that keeps its state and the cut it stopped at reads only the delta. -/ theorem foldAt_readBetween (f : β → α → β) (init : K → β) (s : Store K α) {a b : Cut K} @@ -262,13 +265,13 @@ theorem foldAt_readBetween (f : β → α → β) (init : K → β) (s : Store K congrArg (fun l ↦ l.foldl f (init k)) (congrFun (readAt_append_readBetween s h) k).symm _ = _ := List.foldl_append -/-- SNP-3 An event read at the later cut was read at the earlier cut or lies in the delta. -/ +/-- **SNP-3** An event read at the later cut was read at the earlier cut or lies in the delta. -/ theorem mem_readAt_iff {s : Store K α} {a b : Cut K} (h : a ≤ b) {k : K} {x : α} : x ∈ readAt s b k ↔ x ∈ readAt s a k ∨ x ∈ readBetween s a b k := by rw [← readAt_append_readBetween s h] exact List.mem_append -/-- SNP-3 The delta rule for a job that joins two chains: a pair of events read at the later +/-- **SNP-3** The delta rule for a job that joins two chains: a pair of events read at the later cut was read at the earlier cut, or one of the two lies in the delta. So a job that kept the pairs of its checkpoint has only the pairs with a new member left to visit. -/ theorem pair_readAt {s : Store K α} {a b : Cut K} (h : a ≤ b) {k k' : K} {x y : α} @@ -281,17 +284,17 @@ theorem pair_readAt {s : Store K α} {a b : Cut K} (h : a ≤ b) {k k' : K} {x y · exact Or.inr (Or.inr hy) · exact Or.inr (Or.inl hx) -/-- SNP-5 A derived view reads only the prefixes. -/ +/-- **SNP-5** A derived view reads only the prefixes. -/ theorem prefixOnly_view (D : Store K α → β) : PrefixOnly (view D) := fun s c _ ↦ by change D (readAt s c) = D (readAt (readAt s c) c) rw [readAt_readAt, inf_idem] -/-- SNP-5 Two stores with the same prefixes at a cut give every derived view the same +/-- **SNP-5** Two stores with the same prefixes at a cut give every derived view the same reading. -/ theorem view_congr (D : Store K α → β) {s s' : Store K α} {c : Cut K} (h : readAt s c = readAt s' c) : view D s c = view D s' c := congrArg D h -/-- SNP-5 A reader is append invariant exactly when it reads only the prefixes. -/ +/-- **SNP-5** A reader is append invariant exactly when it reads only the prefixes. -/ theorem appendInvariant_iff_prefixOnly (F : Store K α → Cut K → β) : AppendInvariant F ↔ PrefixOnly F := by constructor @@ -303,7 +306,7 @@ theorem appendInvariant_iff_prefixOnly (F : Store K α → Cut K → β) : · intro h s t c hc rw [h (grow s t) c (hc.trans (extends_grow s t).head_le), readAt_grow t hc, ← h s c hc] -/-- SNP-5 A reader is append invariant exactly when it is a derived view: on cuts inside the +/-- **SNP-5** A reader is append invariant exactly when it is a derived view: on cuts inside the store, a function of the prefixes alone. -/ theorem appendInvariant_iff_exists_view (F : Store K α → Cut K → β) : AppendInvariant F ↔ ∃ D : Store K α → β, ∀ s c, c ≤ head s → F s c = view D s c := by @@ -340,13 +343,13 @@ theorem stateAt_of_length_le {l : List (κ × β)} {c : ℕ} (h : l.length ≤ c unfold stateAt rw [List.take_of_length_le h] -/-- SNP-1 The state at a cut inside the chain does not change when the chain grows. -/ +/-- **SNP-1** The state at a cut inside the chain does not change when the chain grows. -/ theorem stateAt_append {l : List (κ × β)} (t : List (κ × β)) {c : ℕ} (h : c ≤ l.length) : stateAt (l ++ t) c = stateAt l c := by unfold stateAt rw [List.take_append_of_le_length h] -/-- SNP-3 The journal of the keyed state: the state at a later cut is the state at an earlier +/-- **SNP-3** The journal of the keyed state: the state at a later cut is the state at an earlier cut with the writes between the two applied in order. -/ theorem stateAt_eq_foldl (l : List (κ × β)) {a b : ℕ} (h : a ≤ b) : stateAt l b = ((l.take b).drop a).foldl @@ -365,7 +368,7 @@ theorem foldl_update_of_ne {t : List (κ × β)} {m : κ → Option β} {x : κ} rw [List.foldl_cons, ih fun e' he' ↦ ht e' (List.mem_cons_of_mem _ he')] exact Function.update_of_ne (Ne.symm (ht e List.mem_cons_self)) _ _ -/-- SNP-3 The delta bounds the change: a key the writes between two cuts do not name has the +/-- **SNP-3** The delta bounds the change: a key the writes between two cuts do not name has the same state at both. What changed between two cuts is found among the keys of the delta. -/ theorem stateAt_eq_of_not_written (l : List (κ × β)) {a b : ℕ} (h : a ≤ b) {x : κ} (hx : ∀ e ∈ (l.take b).drop a, e.1 ≠ x) : stateAt l b x = stateAt l a x := by @@ -384,7 +387,7 @@ theorem stateOf_eq_find? (l : List (κ × β)) (x : κ) : · simp [hx] · simp [hx, Function.update_of_ne (Ne.symm hx), ih] -/-- SNP-5 The state at a cut is the last write of the key inside the prefix: one seek on an +/-- **SNP-5** The state at a cut is the last write of the key inside the prefix: one seek on an index of (key, position). -/ theorem stateAt_eq_lastWrite (l : List (κ × β)) (c : ℕ) (x : κ) : stateAt l c x = lastWrite l c x := @@ -476,7 +479,7 @@ theorem find?_landGen_of_new {rs : List (Gen κ β)} {p : ℕ} {e : κ × β} {q simp only [landGen, List.find?_append, hnone, Option.none_or, List.find?_singleton, hnew, ↓reduceIte] -/-- SNP-5 Generations are recomputation: the generational store read at a cut is the state +/-- **SNP-5** Generations are recomputation: the generational store read at a cut is the state recomputed from the chain's prefix, at every cut. -/ theorem genRead_gens (l : List (κ × β)) (c : ℕ) (x : κ) : genRead (gens l) c x = stateAt l c x := by @@ -503,12 +506,12 @@ theorem genRead_gens (l : List (κ × β)) (c : ℕ) (x : κ) : (by simp [selects, Ne.symm hx]), ih, Function.update_of_ne hx, stateAt_of_length_le (Nat.le_of_succ_le hc)] -/-- SNP-4 At the head cut the generational store reads the store rewritten in place. -/ +/-- **SNP-4** At the head cut the generational store reads the store rewritten in place. -/ theorem genRead_gens_length (l : List (κ × β)) (x : κ) : genRead (gens l) l.length x = stateOf l x := by rw [genRead_gens, stateAt_length] -/-- SNP-1 The generational store read at a cut inside the chain does not change when the chain +/-- **SNP-1** The generational store read at a cut inside the chain does not change when the chain grows, though the growth writes closing stamps into it. -/ theorem genRead_gens_append {l : List (κ × β)} (t : List (κ × β)) {c : ℕ} (h : c ≤ l.length) (x : κ) : genRead (gens (l ++ t)) c x = genRead (gens l) c x := by @@ -535,7 +538,7 @@ theorem length_filter_landGen_of_new {rs : List (Gen κ β)} {p : ℕ} {e : κ rw [List.filter_append, hnil] simp [hnew] -/-- SNP-5 At most one generation of a key is alive at a cut: the snapshot of a keyed store is a +/-- **SNP-5** At most one generation of a key is alive at a cut: the snapshot of a keyed store is a transversal of its chains. -/ theorem length_filter_selects_le_one (l : List (κ × β)) (c : ℕ) (x : κ) : ((gens l).filter (selects c x)).length ≤ 1 := by @@ -643,7 +646,7 @@ theorem prune_landGen {h p : ℕ} (hp : h < p) (rs : List (Gen κ β)) (e : κ rw [List.filter_append, List.filter_map, hq] simp -/-- SNP-4 At the head cut nothing is sealed: a chain of landings and retires serves what the +/-- **SNP-4** At the head cut nothing is sealed: a chain of landings and retires serves what the store rewritten in place holds live. -/ theorem servedAt_length (l : List (κ × Option β)) (x : κ) : servedAt l l.length x = (stateOf l x).join := by @@ -715,7 +718,7 @@ theorem servedNow_of_not_live {l : List (κ × Option β)} {x : κ} (h : (stateOf l x).join = none) (c : ℕ) : servedNow l c x = none := by simp [servedNow, h] -/-- SNP-4 At the head cut the looser seal serves what the store rewritten in place holds +/-- **SNP-4** At the head cut the looser seal serves what the store rewritten in place holds live. -/ theorem servedNow_length (l : List (κ × Option β)) (x : κ) : servedNow l l.length x = (stateOf l x).join := by @@ -813,26 +816,26 @@ theorem historyAt_of_retire_inside (l t : List (κ × Option β)) (x : κ) {c : show c - l.length = (c - (l.length + 1)) + 1 by omega, List.take_succ_cons] rw [h1, sinceRetire_append_retire] -/-- SNP-4 At the head cut the history served is the key's present life. -/ +/-- **SNP-4** At the head cut the history served is the key's present life. -/ theorem historyAt_length (l : List (κ × Option β)) (x : κ) : historyAt l l.length x = sinceRetire l x := by simp [historyAt, sealedAt] /-! ### A retire with no seal, and the fresh identity -/ -/-- SNP-1 With no seal the history of a key at a cut is append invariant: growth of the chain, a +/-- **SNP-1** With no seal the history of a key at a cut is append invariant: growth of the chain, a retire of the key included, changes nothing in it. -/ theorem landingsAt_append {l : List (κ × Option β)} (t : List (κ × Option β)) {c : ℕ} (hc : c ≤ l.length) (x : κ) : landingsAt (l ++ t) c x = landingsAt l c x := by unfold landingsAt rw [List.take_append_of_le_length hc] -/-- SNP-4 At the head cut the history with no seal is every landing of the key. -/ +/-- **SNP-4** At the head cut the history with no seal is every landing of the key. -/ theorem landingsAt_length (l : List (κ × Option β)) (x : κ) : landingsAt l l.length x = l.filterMap fun e ↦ if e.1 = x then e.2 else none := by simp [landingsAt] -/-- SNP-2 With no seal the history at an earlier cut is a prefix of the history at a later +/-- **SNP-2** With no seal the history at an earlier cut is a prefix of the history at a later one. -/ theorem landingsAt_mono (l : List (κ × Option β)) {a b : ℕ} (h : a ≤ b) (x : κ) : landingsAt l a x <+: landingsAt l b x := @@ -980,7 +983,7 @@ theorem landingsAt_lives_of_retire (l t : List (κ × Option β)) (x : κ) {c : omega simp [hne] -/-- SNP-1 The history of an identity at a cut inside the chain is unchanged by any growth of the +/-- **SNP-1** The history of an identity at a cut inside the chain is unchanged by any growth of the chain: a later retire or a later landing at its path closes nothing and adds nothing. -/ theorem landingsAt_lives_append {l : List (κ × Option β)} (t : List (κ × Option β)) {c : ℕ} (hc : c ≤ l.length) (y : κ × ℕ) : @@ -1062,7 +1065,7 @@ section Grant variable {K α : Type*} -/-- SNP-6 A snapshot under a grant is append invariant. -/ +/-- **SNP-1** A snapshot under a grant (SNP-6) is append invariant. -/ theorem snapshot_grow (G : K → Prop) [DecidablePred G] (p : α → Bool) {s : Store K α} (t : Store K α) {c : Cut K} (h : c ≤ head s) : snapshot G p (grow s t) c = snapshot G p s c := by @@ -1104,7 +1107,7 @@ theorem snapshot_congr (G : K → Prop) [DecidablePred G] (p : α → Bool) {s s · simp [snapshot, restrict, readAt, h, hs k h, hc k h] · simp [snapshot, restrict, h] -/-- SNP-4 At the head cut a snapshot is the grant's restriction of the store. -/ +/-- **SNP-4** At the head cut a snapshot is the grant's restriction of the store. -/ theorem snapshot_head (G : K → Prop) [DecidablePred G] (p : α → Bool) (s : Store K α) : snapshot G p s (head s) = restrict G p s := by unfold snapshot @@ -1117,7 +1120,7 @@ theorem restrict_readAt (G : K → Prop) [DecidablePred G] (s : Store K α) (c : funext k by_cases h : G k <;> simp [restrict, readAt, h] -/-- SNP-1 for the composite reader: what an asker is shown at a cut inside the store is the +/-- **SNP-1** for the composite reader: what an asker is shown at a cut inside the store is the same after any growth. -/ theorem shown_grow (G : K → Prop) [DecidablePred G] (p E : α → Bool) {s : Store K α} (t : Store K α) {c : Cut K} (h : c ≤ head s) : @@ -1146,7 +1149,7 @@ theorem shown_narrow {G G' : K → Prop} [DecidablePred G] [DecidablePred G'] · have := hE a h simp [this] at ha) s c -/-- SNP-4 for the composite reader: at the head cut it is the grant's restriction of the store +/-- **SNP-4** for the composite reader: at the head cut it is the grant's restriction of the store without the erased events. -/ theorem shown_head (G : K → Prop) [DecidablePred G] (p E : α → Bool) (s : Store K α) : shown G p E s (head s) = restrict G (fun a ↦ p a && !E a) s := @@ -1198,18 +1201,18 @@ theorem visible_sublist {E E' : α → Bool} (h : ∀ a, E a = true → E' a = t · rfl · simp [h a hE] at ha -/-- SNP-2 under an erasure: what is visible at an earlier cut is a prefix of what is visible +/-- **SNP-2** under an erasure: what is visible at an earlier cut is a prefix of what is visible at a later one. -/ theorem visible_mono (E : α → Bool) (s : Store K α) {c d : Cut K} (h : c ≤ d) (k : K) : visible E s c k <+: visible E s d k := (List.take_prefix_take_left (h k)).filter _ -/-- SNP-4 under an erasure: at the head cut what is visible is the store without the erased +/-- **SNP-4** under an erasure: at the head cut what is visible is the store without the erased events. -/ theorem visible_head (E : α → Bool) (s : Store K α) : visible E s (head s) = compact E s := funext fun _ ↦ congrArg (List.filter fun a ↦ !E a) List.take_length -/-- SNP-1 under an erasure: growth of the store changes nothing visible at a cut inside it. -/ +/-- **SNP-1** under an erasure: growth of the store changes nothing visible at a cut inside it. -/ theorem visible_grow (E : α → Bool) {s : Store K α} (t : Store K α) {c : Cut K} (h : c ≤ head s) : visible E (grow s t) c = visible E s c := funext fun k ↦ congrArg (List.filter fun a ↦ !E a) (List.take_append_of_le_length (h k)) @@ -1649,7 +1652,7 @@ theorem Withheld.anti {c d : Cut K} (hcd : c ≤ d) {k : K} {i : ℕ} (h : Withh | outside hr hle => exact .outside hr ((hcd _).trans hle) | through hr _ ih => exact .through hr ih -/-- SNP-2 The filtered read is monotone in the cut, for a test that does not depend on the cut: +/-- **SNP-2** The filtered read is monotone in the cut, for a test that does not depend on the cut: a row kept at a cut is kept at every later one. -/ theorem Kept.mono {c d : Cut K} (hcd : c ≤ d) {k : K} {i : ℕ} (h : Kept R ok c k i) : Kept R ok d k i := @@ -1668,7 +1671,7 @@ theorem Withheld.of_grown {R' : K → ℕ → K → ℕ → Prop} {h : Cut K} · exact .through (hR _ _ _ _ hi hr) (ih hj) · exact .outside (hR _ _ _ _ hi hr) ((hc k').trans (not_lt.1 hj)) -/-- SNP-1 The filtered read is append invariant: when the rows inside the old head keep the +/-- **SNP-1** The filtered read is append invariant: when the rows inside the old head keep the references they had, the rows kept at a cut inside the old head are the same after the store grows. -/ theorem kept_grown_iff {R' : K → ℕ → K → ℕ → Prop} {h : Cut K} @@ -1825,7 +1828,7 @@ end Certified namespace Witness -/-- The control for SNP-1: the reader that ignores the cut, which is what a verb reads of a +/-- **SNP-1** The control: the reader that ignores the cut, which is what a verb reads of a store rewritten in place, is not append invariant. -/ theorem present_not_appendInvariant : ¬AppendInvariant (present fun s : Store Unit ℕ ↦ (s ()).length) := by @@ -1833,7 +1836,7 @@ theorem present_not_appendInvariant : have h1 := h (fun _ ↦ []) (fun _ ↦ [0]) (fun _ ↦ 0) (fun _ ↦ le_rfl) simp [present, grow] at h1 -/-- The control for SNP-5: the store rewritten in place determines no read at a past cut. Two +/-- **SNP-5** The control: the store rewritten in place determines no read at a past cut. Two chains leave one head state and had different states at the first cut. -/ theorem stateOf_forgets : ¬∃ G : (Unit → Option ℕ) → ℕ → Unit → Option ℕ, @@ -1893,9 +1896,9 @@ theorem reused_identity_inherits : landingsAt (lives l) l.length ((), 0) = [1] := ⟨[((), some 1), ((), none), ((), some 2)], by decide, by decide, by decide⟩ -/-- The control for the retire with no seal: what the stricter seal costs. A retire written -after a cut empties the history the seal serves there, and leaves the history with no seal as -it was. -/ +/-- **SNP-1** The control for the retire with no seal: what the stricter seal costs. A retire +written after a cut empties the history the seal serves there, and leaves the history with no +seal as it was. -/ theorem seal_empties_history : ∃ (l t : List (Unit × Option ℕ)) (c : ℕ), c ≤ l.length ∧ historyAt l c () = [5] ∧ historyAt (l ++ t) c () = [] ∧ landingsAt (l ++ t) c () = [5] := diff --git a/formal/README.md b/formal/README.md index 559efe38..aec16330 100644 --- a/formal/README.md +++ b/formal/README.md @@ -27,7 +27,7 @@ Each family comes in three parts: `Spec/` is proved in `Palace` with exactly the same statement, from the standard axioms, and everything the statements reach passes Lean's kernel and five independent checkers. A proof file therefore cannot change what the ledger's laws state: only `Spec/` and the model can. The design -theorems (Sever, Frustration, Leak, Transport, Superconnection, Lineage, Dynamics, Scale, Snapshot, and the parts of Magnetic and +theorems (Sever, Frustration, Leak, Transport, Superconnection, Lineage, Dynamics, Scale, and the parts of Snapshot, Magnetic and NegativeType no row cites) have no `Spec/` statements yet: the kernel replays their proofs, but their statements live in the proof files, which can change them, until code relies on them and a row cites them. Whether a statement says what its row says stays a reader's judgment, and the reading is now confined to those two places; @@ -298,7 +298,9 @@ Roundoff and FloatModel, so it has no statements of its own): falsifiers, so the six laws are the ledger's family XV (`Spec/Utility.lean`, 20 statements); the controls and the gap stay design theorems. - `Snapshot`: a read of the stores at a cut (`docs/design-notes/dn-temporal-snapshot.md`), proved - before any code reads a store at a cut, on a model of a store as a family of append chains (a + before any code reads a store at a cut; SNP-1 to SNP-5 entered the ledger with stage SN-1, the + landing log (`core/stores/landings.py`), and are stated in `Spec/Snapshot.lean`, the rest stay + design theorems. On a model of a store as a family of append chains (a document's versions, a session's turns, a class's landing log), a cut as a prefix length for each chain (the frontier of the event clock's §2.4), the read at a cut and between two cuts, a derived view as a derivation of the prefixes, a store of keyed writes held three ways (rewritten @@ -506,6 +508,11 @@ Roundoff and FloatModel, so it has no statements of its own): | UTL-5 | `\|xᵀ (L' − L) x\| ≤ θ xᵀ L x`, so the nudged Laplacian is within `2θ d_max` of the structural one and Weyl's counts bound every eigenvalue's move; order beyond the margin is kept | proved; the form bound survived 500, the degree bound 500 | | UTL-6 | with the use `K`-Lipschitz in the field and `K < lam`, the loop contracts the sup metric by `1 − lam + K` and has one stationary field; at `K ≥ lam` the ceiling is a second fixed point | proved; the contraction survived 500 | | the regimes | the two-site mean field's ratio moves apart at exponent 2, holds at 1, moves to one at 0; the greedy walk never leaves two nodes of the three-node path | proved; the three exponents survived 500 as one attack, the greedy walk 500 | +| SNP-1 | a read at a cut inside the store, a read between two such cuts and every derived view are unchanged by any growth; so are the reads under an erasure and a grant, the keyed state and its generations, the history of a key with no seal and of an identity by its lives, and the filtered read | proved; attacks survived 500 each (seeds 430, 432, 446, 521, 527); the controls refuted, the reader that ignores the cut and the seal's history also as theorems | +| SNP-2 | the read at an earlier cut is a prefix of the read at a later one, and a cut of a cut is the meet; so for the visible read, the history with no seal and the filtered read | proved; attacks survived 500 each (seeds 433, 435, 515); the controls refuted | +| SNP-3 | the read at `a` and the read between `a` and `b` compose to the read at `b`, so a fold continued over the delta is the fold of the prefix; a key the delta does not write keeps its state | proved; attacks survived 500 each (seeds 436, 438, 439, 447, 475, 476); the controls refuted | +| SNP-4 | a cut at or past the head reads the store, so every reading at the head is the present's | proved; the attack survived 500 (seed 440); the control refuted | +| SNP-5 | a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; the generational read is the recomputed state and the last write, with at most one generation alive | proved; attacks survived 500 each (seeds 441, 442, 443); the controls refuted, the store rewritten in place also as a theorem | The binarized forms (0/1 adjacency) reduce to Mathlib's `SimpleGraph.posSemidef_lapMatrix` and `card_connectedComponent_eq_finrank_ker_toLin'_lapMatrix` in one line each. diff --git a/formal/Spec.lean b/formal/Spec.lean index ae90bead..6c45fa55 100644 --- a/formal/Spec.lean +++ b/formal/Spec.lean @@ -24,5 +24,6 @@ public import Spec.Scope public import Spec.Script public import Spec.Sentence public import Spec.SigmaStar +public import Spec.Snapshot public import Spec.Spectral public import Spec.Utility diff --git a/formal/Spec/Snapshot.lean b/formal/Spec/Snapshot.lean new file mode 100644 index 00000000..4f215931 --- /dev/null +++ b/formal/Spec/Snapshot.lean @@ -0,0 +1,349 @@ +module + +public import Palace.Snapshot.Defs +public import Mathlib.Data.List.Induction +public import Mathlib.Data.List.ReduceOption +public import Mathlib.Order.Lattice +public import Mathlib.Order.Lattice.Nat +public import Mathlib.Order.Sublattice + +/-! +# The temporal snapshot: the statements + +SNP-1 to SNP-5 (`docs/LAWS.md`, XVI): append invariance, monotonicity, composition, idempotence, +and a derived view as a function of the prefixes, over the model of `Palace/Snapshot/Defs.lean`: a +store as a family of append chains, a cut as a prefix length for each chain, the read at a cut and +between two cuts, a derived view as a derivation of the prefixes, a chain of keyed writes held +three ways (rewritten in place, recomputed from the prefix, kept by generation with a closing +stamp), the grant and the erasure applied to one read, the history of a key with and without a +seal, the identity a landing at a retired path takes (`lives`), and the filtered read of the +references a resolver does not follow (`Kept`). Each law's controls are among its statements. What +they leave out: the stores' SQL, the hash and the commitment of a row (SNP-9's, not stated here), +the class a chain holds and the relabel that rewrites it, and the identity's name in the code; +`core/stores/landings.py` is the transcription these laws are tested against +(`tests/property/test_landing_log.py`). + +SNP-6 to SNP-10 are not stated here: they are design theorems of `Palace/Snapshot.lean`, cited from +the note until a stage of dn-temporal-snapshot §12 builds what relies on them. + +These are the laws of `Palace/Snapshot.lean` as the ledger cites them, each with its proof left as +`sorry`. `lake comparator` checks that the `Palace` library proves each one exactly as stated +here, from the standard axioms alone. +-/ + +@[expose] public section + +namespace Palace.Snapshot + +section Reads + +variable {K α β : Type*} + +/-- **SNP-1** Append invariance: the read at a cut inside the store does not change when the store +grows. -/ +theorem readAt_grow {s : Store K α} (t : Store K α) {c : Cut K} (h : c ≤ head s) : + readAt (grow s t) c = readAt s c := + sorry + +/-- **SNP-1** The same over every extension: a later state of an append-only store reads, at a cut +of an earlier state, what the earlier state read. -/ +theorem readAt_of_extends {s s' : Store K α} {c : Cut K} (h : Extends s s') (hc : c ≤ head s) : + readAt s' c = readAt s c := + sorry + +/-- **SNP-1** The read between two cuts inside the store does not change when the store grows. -/ +theorem readBetween_grow {s : Store K α} (t : Store K α) (a : Cut K) {b : Cut K} + (h : b ≤ head s) : readBetween (grow s t) a b = readBetween s a b := + sorry + +/-- **SNP-1** Every derived view is append invariant. -/ +theorem appendInvariant_view (D : Store K α → β) : AppendInvariant (view D) := + sorry + +/-- **SNP-2** Monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a +later one. -/ +theorem readAt_mono (s : Store K α) {c d : Cut K} (h : c ≤ d) : + Extends (readAt s c) (readAt s d) := + sorry + +/-- **SNP-2** An event read at a cut is read at every later cut. -/ +theorem mem_readAt_of_le {s : Store K α} {c d : Cut K} (h : c ≤ d) {k : K} {a : α} + (ha : a ∈ readAt s c k) : a ∈ readAt s d k := + sorry + +/-- **SNP-2** A cut of a cut is the meet of the two. -/ +theorem readAt_readAt (s : Store K α) (c d : Cut K) : + readAt (readAt s c) d = readAt s (d ⊓ c) := + sorry + +/-- **SNP-2** The head of the read at a cut is the meet of the cut and the store's head. -/ +theorem head_readAt (s : Store K α) (c : Cut K) : head (readAt s c) = c ⊓ head s := + sorry + +/-- **SNP-4** A cut at or past the head reads the store. -/ +theorem readAt_of_head_le {s : Store K α} {c : Cut K} (h : head s ≤ c) : readAt s c = s := + sorry + +/-- **SNP-4** Idempotence: the read at the head cut is the store. -/ +theorem readAt_head (s : Store K α) : readAt s (head s) = s := + sorry + +/-- **SNP-4** Every derived view at the head cut is the derivation of the present: `as of` the +current cut is no `as of`. -/ +theorem view_head (D : Store K α → β) (s : Store K α) : view D s (head s) = D s := + sorry + +/-- **SNP-3** Composition: the read at `a` followed by the read between `a` and `b` is the read at +`b`. -/ +theorem readAt_append_readBetween (s : Store K α) {a b : Cut K} (h : a ≤ b) : + grow (readAt s a) (readBetween s a b) = readAt s b := + sorry + +/-- **SNP-3** Two adjacent reads-between compose. -/ +theorem readBetween_append (s : Store K α) {a b c : Cut K} (hab : a ≤ b) (hbc : b ≤ c) : + grow (readBetween s a b) (readBetween s b c) = readBetween s a c := + sorry + +/-- **SNP-3** The journal: a fold of the prefixes at a later cut is the fold at an earlier cut +continued over the events between the two. A job that keeps its state and the cut it stopped at +reads only the delta. -/ +theorem foldAt_readBetween (f : β → α → β) (init : K → β) (s : Store K α) {a b : Cut K} + (h : a ≤ b) (k : K) : + foldAt f init s b k = (readBetween s a b k).foldl f (foldAt f init s a k) := + sorry + +/-- **SNP-3** An event read at the later cut was read at the earlier cut or lies in the delta. -/ +theorem mem_readAt_iff {s : Store K α} {a b : Cut K} (h : a ≤ b) {k : K} {x : α} : + x ∈ readAt s b k ↔ x ∈ readAt s a k ∨ x ∈ readBetween s a b k := + sorry + +/-- **SNP-3** The delta rule for a job that joins two chains: a pair of events read at the later +cut was read at the earlier cut, or one of the two lies in the delta. So a job that kept the +pairs of its checkpoint has only the pairs with a new member left to visit. -/ +theorem pair_readAt {s : Store K α} {a b : Cut K} (h : a ≤ b) {k k' : K} {x y : α} + (hx : x ∈ readAt s b k) (hy : y ∈ readAt s b k') : + (x ∈ readAt s a k ∧ y ∈ readAt s a k') ∨ x ∈ readBetween s a b k ∨ + y ∈ readBetween s a b k' := + sorry + +/-- **SNP-5** A derived view reads only the prefixes. -/ +theorem prefixOnly_view (D : Store K α → β) : PrefixOnly (view D) := + sorry + +/-- **SNP-5** Two stores with the same prefixes at a cut give every derived view the same +reading. -/ +theorem view_congr (D : Store K α → β) {s s' : Store K α} {c : Cut K} + (h : readAt s c = readAt s' c) : view D s c = view D s' c := + sorry + +/-- **SNP-5** A reader is append invariant exactly when it reads only the prefixes. -/ +theorem appendInvariant_iff_prefixOnly (F : Store K α → Cut K → β) : + AppendInvariant F ↔ PrefixOnly F := + sorry + +/-- **SNP-5** A reader is append invariant exactly when it is a derived view: on cuts inside the +store, a function of the prefixes alone. -/ +theorem appendInvariant_iff_exists_view (F : Store K α → Cut K → β) : + AppendInvariant F ↔ ∃ D : Store K α → β, ∀ s c, c ≤ head s → F s c = view D s c := + sorry + +end Reads + +section Generations + +variable {κ β : Type*} [DecidableEq κ] + +/-- **SNP-1** The state at a cut inside the chain does not change when the chain grows. -/ +theorem stateAt_append {l : List (κ × β)} (t : List (κ × β)) {c : ℕ} (h : c ≤ l.length) : + stateAt (l ++ t) c = stateAt l c := + sorry + +/-- **SNP-3** The journal of the keyed state: the state at a later cut is the state at an earlier +cut with the writes between the two applied in order. -/ +theorem stateAt_eq_foldl (l : List (κ × β)) {a b : ℕ} (h : a ≤ b) : + stateAt l b = ((l.take b).drop a).foldl + (fun (m : κ → Option β) (e : κ × β) ↦ Function.update m e.1 (some e.2)) (stateAt l a) := + sorry + +/-- **SNP-3** The delta bounds the change: a key the writes between two cuts do not name has the +same state at both. What changed between two cuts is found among the keys of the delta. -/ +theorem stateAt_eq_of_not_written (l : List (κ × β)) {a b : ℕ} (h : a ≤ b) {x : κ} + (hx : ∀ e ∈ (l.take b).drop a, e.1 ≠ x) : stateAt l b x = stateAt l a x := + sorry + +/-- **SNP-5** The state at a cut is the last write of the key inside the prefix: one seek on an +index of (key, position). -/ +theorem stateAt_eq_lastWrite (l : List (κ × β)) (c : ℕ) (x : κ) : + stateAt l c x = lastWrite l c x := + sorry + +/-- **SNP-5** Generations are recomputation: the generational store read at a cut is the state +recomputed from the chain's prefix, at every cut. -/ +theorem genRead_gens (l : List (κ × β)) (c : ℕ) (x : κ) : + genRead (gens l) c x = stateAt l c x := + sorry + +/-- **SNP-4** At the head cut the generational store reads the store rewritten in place. -/ +theorem genRead_gens_length (l : List (κ × β)) (x : κ) : + genRead (gens l) l.length x = stateOf l x := + sorry + +/-- **SNP-1** The generational store read at a cut inside the chain does not change when the chain +grows, though the growth writes closing stamps into it. -/ +theorem genRead_gens_append {l : List (κ × β)} (t : List (κ × β)) {c : ℕ} (h : c ≤ l.length) + (x : κ) : genRead (gens (l ++ t)) c x = genRead (gens l) c x := + sorry + +/-- **SNP-5** At most one generation of a key is alive at a cut: the snapshot of a keyed store is a +transversal of its chains. -/ +theorem length_filter_selects_le_one (l : List (κ × β)) (c : ℕ) (x : κ) : + ((gens l).filter (selects c x)).length ≤ 1 := + sorry + +/-- **SNP-4** At the head cut nothing is sealed: a chain of landings and retires serves what the +store rewritten in place holds live. -/ +theorem servedAt_length (l : List (κ × Option β)) (x : κ) : + servedAt l l.length x = (stateOf l x).join := + sorry + +/-- **SNP-4** At the head cut the looser seal serves what the store rewritten in place holds +live. -/ +theorem servedNow_length (l : List (κ × Option β)) (x : κ) : + servedNow l l.length x = (stateOf l x).join := + sorry + +/-- **SNP-4** At the head cut the history served is the key's present life. -/ +theorem historyAt_length (l : List (κ × Option β)) (x : κ) : + historyAt l l.length x = sinceRetire l x := + sorry + +/-- **SNP-1** With no seal the history of a key at a cut is append invariant: growth of the chain, a +retire of the key included, changes nothing in it. -/ +theorem landingsAt_append {l : List (κ × Option β)} (t : List (κ × Option β)) {c : ℕ} + (hc : c ≤ l.length) (x : κ) : landingsAt (l ++ t) c x = landingsAt l c x := + sorry + +/-- **SNP-4** At the head cut the history with no seal is every landing of the key. -/ +theorem landingsAt_length (l : List (κ × Option β)) (x : κ) : + landingsAt l l.length x = l.filterMap fun e ↦ if e.1 = x then e.2 else none := + sorry + +/-- **SNP-2** With no seal the history at an earlier cut is a prefix of the history at a later +one. -/ +theorem landingsAt_mono (l : List (κ × Option β)) {a b : ℕ} (h : a ≤ b) (x : κ) : + landingsAt l a x <+: landingsAt l b x := + sorry + +/-- **SNP-1** The history of an identity at a cut inside the chain is unchanged by any growth of the +chain: a later retire or a later landing at its path closes nothing and adds nothing. -/ +theorem landingsAt_lives_append {l : List (κ × Option β)} (t : List (κ × Option β)) {c : ℕ} + (hc : c ≤ l.length) (y : κ × ℕ) : + landingsAt (lives (l ++ t)) c y = landingsAt (lives l) c y := + sorry + +end Generations + +section Grant + +variable {K α : Type*} + +/-- **SNP-1** A snapshot under a grant (SNP-6) is append invariant. -/ +theorem snapshot_grow (G : K → Prop) [DecidablePred G] (p : α → Bool) {s : Store K α} + (t : Store K α) {c : Cut K} (h : c ≤ head s) : + snapshot G p (grow s t) c = snapshot G p s c := + sorry + +/-- **SNP-4** At the head cut a snapshot is the grant's restriction of the store. -/ +theorem snapshot_head (G : K → Prop) [DecidablePred G] (p : α → Bool) (s : Store K α) : + snapshot G p s (head s) = restrict G p s := + sorry + +/-- **SNP-1** for the composite reader: what an asker is shown at a cut inside the store is the +same after any growth. -/ +theorem shown_grow (G : K → Prop) [DecidablePred G] (p E : α → Bool) {s : Store K α} + (t : Store K α) {c : Cut K} (h : c ≤ head s) : + shown G p E (grow s t) c = shown G p E s c := + sorry + +/-- **SNP-4** for the composite reader: at the head cut it is the grant's restriction of the store +without the erased events. -/ +theorem shown_head (G : K → Prop) [DecidablePred G] (p E : α → Bool) (s : Store K α) : + shown G p E s (head s) = restrict G (fun a ↦ p a && !E a) s := + sorry + +end Grant + +section Erasure + +variable {K α β C : Type*} + +/-- **SNP-2** under an erasure: what is visible at an earlier cut is a prefix of what is visible +at a later one. -/ +theorem visible_mono (E : α → Bool) (s : Store K α) {c d : Cut K} (h : c ≤ d) (k : K) : + visible E s c k <+: visible E s d k := + sorry + +/-- **SNP-4** under an erasure: at the head cut what is visible is the store without the erased +events. -/ +theorem visible_head (E : α → Bool) (s : Store K α) : visible E s (head s) = compact E s := + sorry + +/-- **SNP-1** under an erasure: growth of the store changes nothing visible at a cut inside it. -/ +theorem visible_grow (E : α → Bool) {s : Store K α} (t : Store K α) {c : Cut K} + (h : c ≤ head s) : visible E (grow s t) c = visible E s c := + sorry + +end Erasure + +section Consistency + +variable {K : Type*} {R : K → ℕ → K → ℕ → Prop} + +section Filter + +variable {ok : K → ℕ → Prop} {c : Cut K} + +/-- **SNP-2** The filtered read is monotone in the cut, for a test that does not depend on the cut: +a row kept at a cut is kept at every later one. -/ +theorem Kept.mono {c d : Cut K} (hcd : c ≤ d) {k : K} {i : ℕ} (h : Kept R ok c k i) : + Kept R ok d k i := + sorry + +/-- **SNP-1** The filtered read is append invariant: when the rows inside the old head keep the +references they had, the rows kept at a cut inside the old head are the same after the store +grows. -/ +theorem kept_grown_iff {R' : K → ℕ → K → ℕ → Prop} {h : Cut K} + (hR : ∀ k i k' j, i < h k → (R' k i k' j ↔ R k i k' j)) (hc : c ≤ h) {k : K} {i : ℕ} : + Kept R' ok c k i ↔ Kept R ok c k i := + sorry + +end Filter + +end Consistency + +namespace Witness + +/-- **SNP-1** The control: the reader that ignores the cut, which is what a verb reads of a +store rewritten in place, is not append invariant. -/ +theorem present_not_appendInvariant : + ¬AppendInvariant (present fun s : Store Unit ℕ ↦ (s ()).length) := + sorry + +/-- **SNP-5** The control: the store rewritten in place determines no read at a past cut. Two +chains leave one head state and had different states at the first cut. -/ +theorem stateOf_forgets : + ¬∃ G : (Unit → Option ℕ) → ℕ → Unit → Option ℕ, + ∀ (l : List (Unit × ℕ)) (c : ℕ), stateAt l c = G (stateOf l) c := + sorry + +/-- **SNP-1** The control for the retire with no seal: what the stricter seal costs. A retire +written after a cut empties the history the seal serves there, and leaves the history with no +seal as it was. -/ +theorem seal_empties_history : + ∃ (l t : List (Unit × Option ℕ)) (c : ℕ), c ≤ l.length ∧ + historyAt l c () = [5] ∧ historyAt (l ++ t) c () = [] ∧ landingsAt (l ++ t) c () = [5] := + sorry + +end Witness + +end Palace.Snapshot diff --git a/formal/comparator.json b/formal/comparator.json index 7f260ac9..aff69491 100644 --- a/formal/comparator.json +++ b/formal/comparator.json @@ -266,6 +266,53 @@ "Palace.SigmaStar.sigmaStar_eq_none_iff", "Palace.SigmaStar.sigmaStar_symm", "Palace.SigmaStar.sigmaStar_ultra", + "Palace.Snapshot.Kept.mono", + "Palace.Snapshot.Witness.present_not_appendInvariant", + "Palace.Snapshot.Witness.seal_empties_history", + "Palace.Snapshot.Witness.stateOf_forgets", + "Palace.Snapshot.appendInvariant_iff_exists_view", + "Palace.Snapshot.appendInvariant_iff_prefixOnly", + "Palace.Snapshot.appendInvariant_view", + "Palace.Snapshot.foldAt_readBetween", + "Palace.Snapshot.genRead_gens", + "Palace.Snapshot.genRead_gens_append", + "Palace.Snapshot.genRead_gens_length", + "Palace.Snapshot.head_readAt", + "Palace.Snapshot.historyAt_length", + "Palace.Snapshot.kept_grown_iff", + "Palace.Snapshot.landingsAt_append", + "Palace.Snapshot.landingsAt_length", + "Palace.Snapshot.landingsAt_lives_append", + "Palace.Snapshot.landingsAt_mono", + "Palace.Snapshot.length_filter_selects_le_one", + "Palace.Snapshot.mem_readAt_iff", + "Palace.Snapshot.mem_readAt_of_le", + "Palace.Snapshot.pair_readAt", + "Palace.Snapshot.prefixOnly_view", + "Palace.Snapshot.readAt_append_readBetween", + "Palace.Snapshot.readAt_grow", + "Palace.Snapshot.readAt_head", + "Palace.Snapshot.readAt_mono", + "Palace.Snapshot.readAt_of_extends", + "Palace.Snapshot.readAt_of_head_le", + "Palace.Snapshot.readAt_readAt", + "Palace.Snapshot.readBetween_append", + "Palace.Snapshot.readBetween_grow", + "Palace.Snapshot.servedAt_length", + "Palace.Snapshot.servedNow_length", + "Palace.Snapshot.shown_grow", + "Palace.Snapshot.shown_head", + "Palace.Snapshot.snapshot_grow", + "Palace.Snapshot.snapshot_head", + "Palace.Snapshot.stateAt_append", + "Palace.Snapshot.stateAt_eq_foldl", + "Palace.Snapshot.stateAt_eq_lastWrite", + "Palace.Snapshot.stateAt_eq_of_not_written", + "Palace.Snapshot.view_congr", + "Palace.Snapshot.view_head", + "Palace.Snapshot.visible_grow", + "Palace.Snapshot.visible_head", + "Palace.Snapshot.visible_mono", "Palace.Utility.abs_dotProduct_lap_sub_le", "Palace.Utility.count_lap_nudge_le_add", "Palace.Utility.count_lap_nudge_sub_le", From f18223e77e74ead845f3c3c5bba2e1d52b094214 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:21:52 -0500 Subject: [PATCH 09/30] perf(stores): the log's writes by path seek the key index On a copy of the corpus instance's catalog, 400,274 rows in one chain, a landing took about 40 ms: the update that writes the closing stamp of the path's previous row took the primary key, (chain, seq), and walked the whole chain to find the path's rows, though the statement names the path's key. The reads already named landings_path for this reason (dn-temporal-snapshot section 4.1, where the planner's choice cost 49 to 57 ms on the fixture). The closing update and remove's emptying now name the index too, and a record takes tens of microseconds again. A test traces every statement the log runs for one path, a record, a tombstone, a re-key, the two reads and a remove, and asks SQLite's plan of each to name landings_path; without the named index it fails. Co-Authored-By: Claude Opus 5.5 --- core/stores/landings.py | 12 +++++++----- tests/property/test_landing_log.py | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/core/stores/landings.py b/core/stores/landings.py index 3b4987ea..e6fc7af2 100644 --- a/core/stores/landings.py +++ b/core/stores/landings.py @@ -383,10 +383,11 @@ def _append(self, chain: int, kind: str, *, path: str | None = None, path_key = None if path is not None: path_key = self.path_key(chain, path) - # the path's previous event in the chain is closed at this one (§3.2) + # the path's previous event in the chain is closed at this one (§3.2); the statement + # names the key index, since the planner takes the primary key and walks the chain self._conn.execute( - "UPDATE landings SET closed_at = ? WHERE chain = ? AND path_key = ? " - "AND closed_at IS NULL", [seq, chain, path_key]) + "UPDATE landings INDEXED BY landings_path SET closed_at = ? " + "WHERE chain = ? AND path_key = ? AND closed_at IS NULL", [seq, chain, path_key]) self._conn.execute(_INSERT, [chain, seq, kind, path_key, path, doc_id, version, digest, title, None, horizon, salt, commit, chain_hash(previous, commit), None, at]) @@ -470,8 +471,9 @@ def empty_path(self, path: str) -> int: n = 0 for chain in self.all_chains(): n += self._conn.execute( - f"UPDATE landings SET {_EMPTY} WHERE chain = ? AND path_key = ? " - "AND salt IS NOT NULL", [chain, self.path_key(chain, path)]).rowcount + f"UPDATE landings INDEXED BY landings_path SET {_EMPTY} " + "WHERE chain = ? AND path_key = ? AND salt IS NOT NULL", + [chain, self.path_key(chain, path)]).rowcount return n def empty_digest(self, digest: str) -> int: diff --git a/tests/property/test_landing_log.py b/tests/property/test_landing_log.py index 7b3b4e03..8d51bfff 100644 --- a/tests/property/test_landing_log.py +++ b/tests/property/test_landing_log.py @@ -590,3 +590,27 @@ def test_another_secret_is_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPat cat.record("a.md", "d2", "A") kept = cat.get("a.md") assert heads(cat) == head and kept is not None and kept.digest == "d1" + + +def test_every_statement_by_path_seeks_the_key_index() -> None: + """A write or a read of one path touches that path's rows through `landings_path`, never by + walking the chain: on the corpus's 400,274 rows the planner took the primary key for the + closing stamp's update, and a landing took 40 ms where it takes tens of microseconds.""" + cat = VaultCatalog(Path(":memory:")) + for i in range(50): + cat.record(f"p{i}.md", f"d{i}", "t") + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + seen: list[str] = [] + cat._conn.set_trace_callback(seen.append) + cat.record("p1.md", "new", "t") + cat.tombstone("p2.md") + cat.record("p4.md", "d4", "t", doc_id="another") + cat.state_at(Provenance.AUTHORED_SOLO, "p1.md", {chain: 30}) + cat.history_at(Provenance.AUTHORED_SOLO, "p1.md", {chain: cat.head(chain)}) + cat.remove("p3.md") + cat._conn.set_trace_callback(None) + by_path = [q for q in seen if "path_key = " in q] + assert len(by_path) >= 6 + for q in by_path: + plan = " ".join(str(tuple(r)[-1]) for r in cat._conn.execute("EXPLAIN QUERY PLAN " + q)) + assert "landings_path" in plan, (q, plan) From 5a08779af16b6d3eee0f25593227b060e253e6e3 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:23:35 -0500 Subject: [PATCH 10/30] feat(eval): the landing log bench and its record on the corpus's catalog eval/landing_log_bench.py measures stage SN-1 on a copy of a catalog file, migrated in place under a secret made for the run: the migration and its genesis, the bytes a row takes in the table and each index, the chain's verify and the fold of the log against the catalog, a key's write in a batch of 10,000 with the log and without it, and every read. It refuses the configured instance's own catalog. Two runs on copy-on-write clones of the corpus instance's catalog, 400,274 rows: the migration 6.2 to 6.3 s, 429 bytes a row (the table 381, the key index 47), the fold equal to the catalog, verify 3.1 s; one path at a cut 14 to 15 us; every head at the head 1.6 s, of which the walk in SQL is 54 to 57 ms; a key's write 42 us more for a new path and 65 to 69 us more for a new version, 0.1 to 0.2 percent of a lazy landing. docs/experiments/landing-log-2026-11-11.md reads them; the first run is what found the closing update walking the chain. Co-Authored-By: Claude Opus 5.5 --- docs/experiments/landing-log-2026-11-11.json | 413 +++++++++++++++++++ docs/experiments/landing-log-2026-11-11.md | 112 +++++ eval/landing_log_bench.py | 277 +++++++++++++ 3 files changed, 802 insertions(+) create mode 100644 docs/experiments/landing-log-2026-11-11.json create mode 100644 docs/experiments/landing-log-2026-11-11.md create mode 100644 eval/landing_log_bench.py diff --git a/docs/experiments/landing-log-2026-11-11.json b/docs/experiments/landing-log-2026-11-11.json new file mode 100644 index 00000000..3df01d67 --- /dev/null +++ b/docs/experiments/landing-log-2026-11-11.json @@ -0,0 +1,413 @@ +{ + "note": "eval/landing_log_bench.py on two copy-on-write clones of the corpus instance's catalog, 2026-11-11; default arguments (--batch 10000 --rounds 5 --repeat 200 --seed 11)", + "run1": { + "catalog_copy": "vault_catalog.sqlite", + "load_start": [ + 2.26123046875, + 2.5947265625, + 2.93701171875 + ], + "python": "3.15.2", + "sqlite": "3.54.1", + "machine": "arm64", + "batch": 10000, + "rounds": 5, + "repeat": 200, + "seed": 11, + "catalog_rows": { + "observed active": 400274 + }, + "has_log_before": false, + "files_before": { + "vault_catalog.sqlite": 162652160, + "vault_catalog.sqlite-wal": 0, + "vault_catalog.sqlite-shm": 32768 + }, + "objects_before": { + "sqlite_autoindex_vault_files_1": 16924672, + "sqlite_schema": 4096, + "vault_files": 94765056, + "vault_files_digest": 34033664, + "vault_files_doc_id": 16924672 + }, + "migration_s": 6.220551250036806, + "chains": { + "1": { + "class": "observed", + "rows": 400276 + } + }, + "log_rows": 400276, + "files_after": { + "vault_catalog.sqlite": 334131200, + "vault_catalog.sqlite-wal": 0, + "vault_catalog.sqlite-shm": 360448 + }, + "objects_after": { + "landing_chains": 4096, + "landings": 152621056, + "landings_closed": 4096, + "landings_doc": 4096, + "landings_path": 18845696, + "sqlite_autoindex_vault_files_1": 16924672, + "sqlite_schema": 4096, + "vault_files": 94765056, + "vault_files_digest": 34033664, + "vault_files_doc_id": 16924672 + }, + "growth_bytes": 171806720, + "growth_bytes_a_row": 429.22063775994565, + "bytes_a_row": { + "landings": 381.28955021035483, + "landings_path": 47.081753590022885, + "landings_doc": 0.010232939271902388, + "landings_closed": 0.010232939271902388, + "landing_chains": 0.010232939271902388 + }, + "verify": { + "1": { + "ok": true, + "rows": 400276, + "commitments": 400276, + "seconds": 3.0703140411060303 + } + }, + "fold_equals_catalog": true, + "fold_seconds": 2.8317980838473886, + "reads": { + "chain": 1, + "class": "observed", + "head": { + "median_us": 2.4170149117708206, + "low_us": 2.3329630494117737, + "high_us": 18.124934285879135, + "runs": 200 + }, + "path_key": { + "median_us": 1.5830155462026596, + "low_us": 1.4998950064182281, + "high_us": 26.665860787034035, + "runs": 200 + }, + "state_at_mid": { + "median_us": 14.25005029886961, + "low_us": 8.167000487446785, + "high_us": 160.33300198614597, + "runs": 200 + }, + "history_at_head": { + "median_us": 15.708035789430141, + "low_us": 13.417098671197891, + "high_us": 66.83287210762501, + "runs": 200 + }, + "read_between_1000": { + "median_us": 3442.95846298337, + "low_us": 3368.9169213175774, + "high_us": 3593.666944652796, + "runs": 200 + }, + "read_at_1000": { + "median_us": 3280.0829503685236, + "low_us": 3207.0830930024385, + "high_us": 3584.667108952999, + "runs": 200 + }, + "heads_at_tenth": { + "median_us": 151410.75011342764, + "low_us": 150872.8750050068, + "high_us": 169505.79197145998, + "runs": 5, + "rows": 40026 + }, + "heads_walk_tenth": { + "median_us": 5558.416014537215, + "low_us": 5286.04188002646, + "high_us": 6100.333062931895, + "runs": 5 + }, + "heads_at_mid": { + "median_us": 789987.4169379473, + "low_us": 759208.207949996, + "high_us": 810563.457896933, + "runs": 5, + "rows": 200137 + }, + "heads_walk_mid": { + "median_us": 26317.6248408854, + "low_us": 26199.499843642116, + "high_us": 27383.832959458232, + "runs": 5 + }, + "heads_at_head": { + "median_us": 1617782.6661150903, + "low_us": 1572967.833140865, + "high_us": 1625654.5409560204, + "runs": 5, + "rows": 400274 + }, + "heads_walk_head": { + "median_us": 56461.54098212719, + "low_us": 55988.00000734627, + "high_us": 60100.20803660154, + "runs": 5 + } + }, + "writes_us_a_record": { + "new": { + "with": [ + 48.001220799051225, + 48.92591249663383, + 48.21360409259796, + 49.26652500871569, + 50.32935000490397 + ], + "without": [ + 6.799195799976587, + 6.8319084122776985, + 6.65885410271585, + 6.896770792081952, + 6.805129209533334 + ], + "with_median_us": 48.92591249663383, + "without_median_us": 6.805129209533334, + "overhead_us": 42.120783287100494 + }, + "changed": { + "with": [ + 105.88544998317957, + 109.1484708013013, + 105.0655041821301, + 106.46303340326995, + 107.13723751250654 + ], + "without": [ + 40.69942079950124, + 40.631037508137524, + 37.9464291036129, + 37.86343338433653, + 37.41974588483572 + ], + "with_median_us": 106.46303340326995, + "without_median_us": 37.9464291036129, + "overhead_us": 68.51660429965705 + } + }, + "verify_after_writes": true, + "files_end": { + "vault_catalog.sqlite": 389640192, + "vault_catalog.sqlite-wal": 0, + "vault_catalog.sqlite-shm": 360448 + }, + "load_end": [ + 8.271484375, + 4.3427734375, + 3.572265625 + ] + }, + "run2": { + "catalog_copy": "vault_catalog.sqlite", + "load_start": [ + 8.271484375, + 4.3427734375, + 3.572265625 + ], + "python": "3.15.2", + "sqlite": "3.54.1", + "machine": "arm64", + "batch": 10000, + "rounds": 5, + "repeat": 200, + "seed": 11, + "catalog_rows": { + "observed active": 400274 + }, + "has_log_before": false, + "files_before": { + "vault_catalog.sqlite": 162652160, + "vault_catalog.sqlite-wal": 0, + "vault_catalog.sqlite-shm": 32768 + }, + "objects_before": { + "sqlite_autoindex_vault_files_1": 16924672, + "sqlite_schema": 4096, + "vault_files": 94765056, + "vault_files_digest": 34033664, + "vault_files_doc_id": 16924672 + }, + "migration_s": 6.325798250036314, + "chains": { + "1": { + "class": "observed", + "rows": 400276 + } + }, + "log_rows": 400276, + "files_after": { + "vault_catalog.sqlite": 334127104, + "vault_catalog.sqlite-wal": 0, + "vault_catalog.sqlite-shm": 360448 + }, + "objects_after": { + "landing_chains": 4096, + "landings": 152621056, + "landings_closed": 4096, + "landings_doc": 4096, + "landings_path": 18841600, + "sqlite_autoindex_vault_files_1": 16924672, + "sqlite_schema": 4096, + "vault_files": 94765056, + "vault_files_digest": 34033664, + "vault_files_doc_id": 16924672 + }, + "growth_bytes": 171802624, + "growth_bytes_a_row": 429.2104048206737, + "bytes_a_row": { + "landings": 381.28955021035483, + "landings_path": 47.07152065075098, + "landings_doc": 0.010232939271902388, + "landings_closed": 0.010232939271902388, + "landing_chains": 0.010232939271902388 + }, + "verify": { + "1": { + "ok": true, + "rows": 400276, + "commitments": 400276, + "seconds": 3.051000916864723 + } + }, + "fold_equals_catalog": true, + "fold_seconds": 2.848458959022537, + "reads": { + "chain": 1, + "class": "observed", + "head": { + "median_us": 2.459157258272171, + "low_us": 2.37487256526947, + "high_us": 24.124979972839355, + "runs": 200 + }, + "path_key": { + "median_us": 1.5830155462026596, + "low_us": 1.4998950064182281, + "high_us": 22.999942302703857, + "runs": 200 + }, + "state_at_mid": { + "median_us": 14.832941815257072, + "low_us": 8.542090654373169, + "high_us": 133.2079991698265, + "runs": 200 + }, + "history_at_head": { + "median_us": 14.666467905044556, + "low_us": 13.249926269054413, + "high_us": 63.04099224507809, + "runs": 200 + }, + "read_between_1000": { + "median_us": 3424.0210661664605, + "low_us": 3286.0420178622007, + "high_us": 3612.959058955312, + "runs": 200 + }, + "read_at_1000": { + "median_us": 3255.7500526309013, + "low_us": 3225.250169634819, + "high_us": 3565.666964277625, + "runs": 200 + }, + "heads_at_tenth": { + "median_us": 151474.91707466543, + "low_us": 150040.70801660419, + "high_us": 160787.37494535744, + "runs": 5, + "rows": 40026 + }, + "heads_walk_tenth": { + "median_us": 5932.959029451013, + "low_us": 5322.749959304929, + "high_us": 6092.166993767023, + "runs": 5 + }, + "heads_at_mid": { + "median_us": 798841.6668958962, + "low_us": 764181.62509799, + "high_us": 805269.2501805723, + "runs": 5, + "rows": 200137 + }, + "heads_walk_mid": { + "median_us": 26318.04207339883, + "low_us": 25891.083059832454, + "high_us": 27076.20896399021, + "runs": 5 + }, + "heads_at_head": { + "median_us": 1613144.7500083596, + "low_us": 1580234.7920835018, + "high_us": 1634123.8748282194, + "runs": 5, + "rows": 400274 + }, + "heads_walk_head": { + "median_us": 54320.41618041694, + "low_us": 52884.4587970525, + "high_us": 57886.87500171363, + "runs": 5 + } + }, + "writes_us_a_record": { + "new": { + "with": [ + 48.21380840148777, + 48.990112519823015, + 48.84648330044001, + 49.588733399286866, + 49.51973750721663 + ], + "without": [ + 6.882070912979543, + 6.796324998140335, + 6.684429198503494, + 6.795345805585384, + 6.710762483999133 + ], + "with_median_us": 48.990112519823015, + "without_median_us": 6.795345805585384, + "overhead_us": 42.19476671423763 + }, + "changed": { + "with": [ + 110.63325421418995, + 106.03663329966366, + 104.65863330755383, + 106.02083748672158, + 105.65141250845045 + ], + "without": [ + 43.35534158162773, + 41.16715001873672, + 41.45721250679344, + 37.74790000170469, + 39.11720409523696 + ], + "with_median_us": 106.02083748672158, + "without_median_us": 41.16715001873672, + "overhead_us": 64.85368746798486 + } + }, + "verify_after_writes": true, + "files_end": { + "vault_catalog.sqlite": 389656576, + "vault_catalog.sqlite-wal": 0, + "vault_catalog.sqlite-shm": 360448 + }, + "load_end": [ + 7.1728515625, + 4.68798828125, + 3.74462890625 + ] + } +} diff --git a/docs/experiments/landing-log-2026-11-11.md b/docs/experiments/landing-log-2026-11-11.md new file mode 100644 index 00000000..b1a6bfd8 --- /dev/null +++ b/docs/experiments/landing-log-2026-11-11.md @@ -0,0 +1,112 @@ +--- +type: experiment-report +experiment: landing-log +runs: 2 +status: complete +started: 2026-11-11 +links: + - docs/design-notes/dn-temporal-snapshot.md # the design these figures test (§3.2, §4, §11; stage SN-1) + - docs/experiments/landing-log-2026-11-11.json # both runs, every figure below + - eval/landing_log_bench.py # the harness + - core/stores/landings.py # what is measured + - docs/experiments/two-phase-ingestion-2026-11-07.md # a lazy landing's cost, the overhead's scale +--- + +# The landing log, measured on the corpus instance's catalog (2026-11-11) + +**Question.** What does stage SN-1's landing log cost at a corpus's size: the migration that +writes its genesis, the bytes a row takes, the time it adds to a key's write, and the time each of +its reads takes? And does the genesis hold the catalog exactly? The design note measured the log +on a synthetic fixture only (§11); these are the figures of the code as built, on a copy of a real +catalog. + +## Method + +Two runs of `eval/landing_log_bench.py` with its defaults (`--batch 10000 --rounds 5 +--repeat 200 --seed 11`), each on its own copy-on-write clone (`cp -c`) of the corpus instance's +catalog file with its `-wal` and `-shm`, made in a scratch directory; the original was never +opened. The harness migrates the clone in place under a random secret made for the run and +dropped with it. + +- **The catalog.** 400,274 rows, every one `observed` and active, so the genesis is one chain of + 400,276 rows: the `genesis`, a `store` a path in path order, the `horizon`. No identity differs + from its path and no path is tombstoned, so the identity index and the closing index stay empty. + A path is 28.6 characters on average and a title 63.8. +- **The migration.** The first open with the log, timed whole: the tables, their indexes and the + genesis in one transaction. The bytes are the file's, with the write-ahead log checkpointed into + it, before and after, and each table's and index's from SQLite's `dbstat`. +- **The check.** The chain verified from its first row, every commitment and every hash + recomputed; the fold of the log compared with the catalog row by row. +- **The writes.** Batches of 10,000 catalog writes, each batch one transaction, as a landing + batch writes its keys (`deferred()`): first new paths, then new versions of paths the catalog + holds. Each batch runs with the log and with the log's appending switched off on the same file + (a patch of `LandingLog.store`), the order alternated over five rounds; the figure is the + median over the rounds of the time a write takes. +- **The reads.** On the chain: `state_at` of one path at the middle cut and `history_at` at the + head, the 200 paths drawn from the catalog; `read_at` of the first 1,000 positions and + `read_between` of 1,000 positions from 200 random starts; `head`; the keyed hash of a path + alone; and `heads_at` at a tenth of the chain, at its middle and at its head, five times each, + with the same predicate counted in SQL, the walk without the rows built. +- **The machine.** Apple M2 Pro, 12 cores, 32 GB, macOS 27.0.1, Python 3.15.2, SQLite 3.54.1, with + other work running: the one-minute load average was 2.3 at the first run's start, 8.3 between + the two runs, which another process raised, and 7.2 at the second's end. Medians with their + ranges over the repetitions; the two runs are given side by side. + +## Results + +| measurement | run 1 | run 2 | +|---|---|---| +| the migration, 400,276 rows of genesis | 6.22 s | 6.33 s | +| the file, before and after | 162.7 MB, 334.1 MB | 162.7 MB, 334.1 MB | +| bytes a row of the log, from the file's growth | 429.2 | 429.2 | +| of which the table, the key index | 381.3, 47.1 | 381.3, 47.1 | +| `verify`: every commitment and hash of the chain | 3.07 s | 3.05 s | +| the fold of the log against the catalog | equal, 2.83 s | equal, 2.85 s | +| `head` | 2.4 µs | 2.5 µs | +| the keyed hash of a path | 1.6 µs | 1.6 µs | +| `state_at`, one path at the middle cut | 14.3 µs (8.2 to 160) | 14.8 µs (8.5 to 133) | +| `history_at`, one path at the head | 15.7 µs | 14.7 µs | +| `read_at`, 1,000 positions | 3.28 ms | 3.26 ms | +| `read_between`, 1,000 positions | 3.44 ms | 3.42 ms | +| `heads_at` at a tenth (40,026 rows) | 151 ms | 152 ms | +| `heads_at` at the middle (200,137 rows) | 790 ms | 799 ms | +| `heads_at` at the head (400,274 rows) | 1.62 s | 1.61 s | +| the same three walks counted in SQL | 5.6, 26.3, 56.5 ms | 5.9, 26.3, 54.3 ms | +| a write of a new path: with the log, without | 48.9, 6.8 µs | 49.0, 6.8 µs | +| a write of a new version of a held path: with, without | 106.5, 37.9 µs | 106.0, 41.2 µs | +| every chain verifies after the 200,000 writes | yes | yes | + +## Reading + +- **The genesis holds the catalog.** The fold of the 400,276 rows equals the catalog's 400,274 + rows in both runs, and the chain verifies. The migration takes six seconds once, on the first + open of the build with the log. +- **A row is 429 bytes,** against the fixture's 434 where the identity is the path (§4.3): the + table's row is 381 bytes against 374, its titles far longer (63.8 characters against under + twelve) and its paths shorter (28.6 against 37), and the key index is the same 47 bytes. The + fixture's closing index, 13 bytes, is empty here, since a genesis of active paths closes no row. + The log doubles the catalog's file, 162.7 MB to 334.1 MB; it holds paths, digests and titles, + which the catalog holds already. +- **The log adds 42 µs to a new path's write and 65 to 69 µs to a new version's,** the second + writing a closing stamp as well. A lazy landing took 31 ms an item on the two-phase record (32.0 + items a second, `docs/experiments/two-phase-ingestion-2026-11-07.md`), so the log is between + 0.1 and 0.2 percent of a landing. +- **A read of one path is 14 to 16 µs** through the key index, of which the keyed hash is 1.6. +- **Every head at the head is 1.6 s,** past the tenth of a second §4.2 allows. The walk itself is + 54 to 57 ms in SQL, 0.14 µs an event, under the fixture's quarter of a microsecond; the rest is + building 400,274 rows in Python. A corpus chain is over §4.2's 250,000 events from the start, + which is why SN-4 keeps heads at recorded cuts for such a chain (SN-c); nothing reads every head + yet. +- **A planner's choice, found here.** The first run of the harness took about 40 ms a landing: + the update that writes the previous row's closing stamp took the primary key and walked the + chain, as the fixture's seek did when the planner took the primary key (§4.1). The statement + now names the key index, as the reads did already, and a test asks the plan of every statement + by path to name it (`tests/property/test_landing_log.py`). The figures above are after the fix. + +## Not measured + +A whole landing batch through the writer with the log against without it (the overhead above is +the catalog's writes alone, and nothing else in a landing changed); a purge on the corpus's size, +whose emptying of a digest's rows reads the whole log, since the log has no index by digest; a +catalog of several classes, or one whose identities differ from their paths; and every read at a +cut that SN-2 and later stages build. diff --git a/eval/landing_log_bench.py b/eval/landing_log_bench.py new file mode 100644 index 00000000..c04ae6df --- /dev/null +++ b/eval/landing_log_bench.py @@ -0,0 +1,277 @@ +"""The landing log, measured (dn-temporal-snapshot §11; stage SN-1). + + uv run python -m eval.landing_log_bench --catalog COPY [--batch 10000] [--rounds 5] + [--repeat 200] [--out PATH] + +COPY is a copy of an instance's catalog file, never a live one: a copy-on-write clone of the file +with its `-wal` and `-shm` beside it (`cp -c`), which the harness migrates in place. It refuses the +catalog the configuration names. The landing log's secret is a random one made for the run and +dropped with it, so nothing written here can be read by path afterwards, and nothing needs to be. + +Four measurements, each on the copy's own size: + +1. **The migration.** The first open of the catalog with the log: the tables, their indexes and + the genesis of every class the catalog holds, timed whole; the file's bytes before and after + (the write-ahead log checkpointed into the file), and the bytes a row of the log takes in the + table and in each index, from SQLite's `dbstat` table when it is compiled in. +2. **Its check.** Each chain verified from its first row, every commitment recomputed and every + hash, timed; and the fold of the log compared with the catalog row by row. +3. **The write overhead.** Batches of catalog writes in one transaction each, as a landing batch + writes its keys (`deferred()`): new paths, and new versions of paths the catalog holds, timed + with the log and with the log's appending switched off on the same file, alternated over + `--rounds`, so the difference is what the log adds to a key's write. +4. **The reads.** `state_at` and `history_at` of one path, the paths drawn from the catalog; + `heads_at` at a tenth of the chain, at its middle and at its head, and the same predicate + counted in SQL, the walk without the rows built; `read_at` and + `read_between` of a thousand positions; `head`; and the keyed hash of a path alone. Medians + with their ranges over `--repeat` (a whole-class read over five). + +Timings are wall time on whatever else the machine is doing, so the load average is recorded at +the start and the end, with the versions of Python and SQLite. +""" + +from __future__ import annotations + +import argparse +import contextlib +import functools +import json +import os +import platform +import random +import sqlite3 +import statistics +import sys +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # repo root on path + +from core.kernel.provenance import Provenance # noqa: E402 +from core.stores.catalog import VaultCatalog # noqa: E402 + + +def _files(db: Path) -> dict[str, int]: + out = {} + for suffix in ("", "-wal", "-shm"): + f = Path(f"{db}{suffix}") + out[f.name] = f.stat().st_size if f.exists() else 0 + return out + + +def _checkpoint(conn: sqlite3.Connection) -> None: + conn.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchall() + + +def _objects(conn: sqlite3.Connection) -> dict[str, int] | None: + """The bytes each table and index takes, from `dbstat`, or None when SQLite lacks it.""" + try: + rows = conn.execute("SELECT name, sum(pgsize) FROM dbstat GROUP BY name").fetchall() + except sqlite3.OperationalError: + return None + return {str(name): int(size) for name, size in rows} + + +def _timed(fn: Callable[[], Any], n: int) -> dict[str, float]: + """Median, low and high of `n` runs of `fn`, in microseconds.""" + times = [] + for _ in range(n): + t0 = time.perf_counter() + fn() + times.append((time.perf_counter() - t0) * 1e6) + return {"median_us": statistics.median(times), "low_us": min(times), "high_us": max(times), + "runs": n} + + +def _count(conn: sqlite3.Connection, sql: str, args: list[int]) -> int: + return int(conn.execute(sql, args).fetchone()[0]) + + +def _fold(cat: VaultCatalog) -> dict[str, tuple[str, str, str, bool, str]]: + """The catalog the log gives: each path's last event in the chain where it is not a `leave`, + an active row for a `store`, a tombstoned one with its last `store`'s digest and title for a + `retire` or a `move` (dn-temporal-snapshot §3.2).""" + classes = {int(c): str(k) for c, k in cat._conn.execute( + "SELECT chain, class FROM landing_chains")} + last: dict[tuple[int, bytes], Any] = {} + store: dict[tuple[int, bytes], Any] = {} + names: dict[tuple[int, bytes], str] = {} + for chain in classes: + for row in cat._log.rows(chain): + if row.path_key is None: + continue + k = (chain, row.path_key) + last[k] = row + if row.kind == "store": + store[k] = row + if row.source_path is not None: + names[k] = row.source_path + out: dict[str, tuple[str, str, str, bool, str]] = {} + for k, name in names.items(): + row, kept = last[k], store.get(k) + if row.kind == "leave": + continue + if row.kind == "store" and not row.hole: + out[name] = (row.digest, row.title, classes[k[0]], True, row.doc_id) + elif row.kind in ("retire", "move") and kept is not None and not kept.hole: + out[name] = (kept.digest, kept.title, classes[k[0]], False, row.doc_id) + return out + + +def _catalog(cat: VaultCatalog) -> dict[str, tuple[str, str, str, bool, str]]: + return {str(r[0]): (str(r[1]), str(r[2]), str(r[3]), bool(r[4]), str(r[5])) + for r in cat._conn.execute( + "SELECT source_path, digest, title, provenance, active, doc_id FROM vault_files")} + + +def _batch(cat: VaultCatalog, records: list[tuple[str, str, str, Provenance]], + log: bool) -> float: + """One batch of records in one transaction, as a landing batch writes its keys; with the + log's appending switched off when `log` is false. Seconds.""" + switch = (contextlib.nullcontext() if log # the control: no log row appended + else mock.patch.object(cat._log, "store", lambda *a, **k: None)) + with switch: + t0 = time.perf_counter() + with cat.deferred(): + for path, digest, title, cls in records: + cat.record(path, digest, title, provenance=cls) + return time.perf_counter() - t0 + + +def measure(db: Path, batch: int, rounds: int, repeat: int, seed: int) -> dict[str, Any]: + from core.kernel.config import get_config + + if db.resolve() == Path(get_config().paths.vault_catalog).resolve(): + raise SystemExit("refusing the configured instance's own catalog: give a copy") + rng = random.Random(seed) + key = os.urandom(32) + out: dict[str, Any] = {"catalog_copy": db.name, "load_start": os.getloadavg(), + "python": platform.python_version(), + "sqlite": sqlite3.sqlite_version, "machine": platform.machine(), + "batch": batch, "rounds": rounds, "repeat": repeat, "seed": seed} + with sqlite3.connect(db) as conn: + out["catalog_rows"] = {f"{cls} {'active' if a else 'tombstoned'}": n for cls, a, n in + conn.execute("SELECT provenance, active, count(*) FROM vault_files " + "GROUP BY provenance, active")} + out["has_log_before"] = conn.execute( + "SELECT 1 FROM sqlite_master WHERE name = 'landings'").fetchone() is not None + _checkpoint(conn) + out["files_before"] = _files(db) + out["objects_before"] = _objects(conn) + + t0 = time.perf_counter() + cat = VaultCatalog(db, key=key) + out["migration_s"] = time.perf_counter() - t0 + chains = {int(c): str(k) for c, k in cat._conn.execute( + "SELECT chain, class FROM landing_chains ORDER BY chain")} + out["chains"] = {str(c): {"class": k, "rows": cat.head(c)} for c, k in chains.items()} + out["log_rows"] = sum(cat.head(c) for c in chains) + _checkpoint(cat._conn) + out["files_after"] = _files(db) + out["objects_after"] = _objects(cat._conn) + grown = sum(out["files_after"].values()) - sum(out["files_before"].values()) + out["growth_bytes"] = grown + out["growth_bytes_a_row"] = grown / out["log_rows"] if out["log_rows"] else None + objects = out["objects_after"] + if objects is not None: + names = ("landings", "landings_path", "landings_doc", "landings_closed", "landing_chains") + out["bytes_a_row"] = {n: objects.get(n, 0) / out["log_rows"] for n in names} + + # the check: every chain verified, and the fold of the log against the catalog + out["verify"] = {} + for chain in chains: + t0 = time.perf_counter() + check = cat.verify(chain) + out["verify"][str(chain)] = {"ok": check.ok, "rows": check.rows, + "commitments": check.commitments, + "seconds": time.perf_counter() - t0} + t0 = time.perf_counter() + out["fold_equals_catalog"] = _fold(cat) == _catalog(cat) + out["fold_seconds"] = time.perf_counter() - t0 + + # the reads, on the largest chain + big = max(chains, key=lambda c: cat.head(c)) + cls = chains[big] + head = cat.head(big) + paths = [str(r[0]) for r in cat._conn.execute( + "SELECT source_path FROM vault_files WHERE provenance = ?", [cls])] + sample = rng.sample(paths, min(repeat, len(paths))) + mid = head // 2 + reads: dict[str, Any] = {"chain": big, "class": cls, "head": head} + it = iter(sample * 2) + reads["path_key"] = _timed(lambda: cat._log.path_key(big, next(it)), len(sample)) + it = iter(sample * 2) + reads["state_at_mid"] = _timed(lambda: cat.state_at(cls, next(it), {big: mid}), len(sample)) + it = iter(sample * 2) + reads["history_at_head"] = _timed(lambda: cat.history_at(cls, next(it), {big: head}), + len(sample)) + starts = [rng.randrange(0, max(1, head - 1000)) for _ in range(repeat)] + its = iter(starts * 2) + reads["read_between_1000"] = _timed(lambda: cat.read_between(big, (a := next(its)), a + 1000), + repeat) + reads["read_at_1000"] = _timed(lambda: cat.read_at(big, 1000), repeat) + reads["head"] = _timed(lambda: cat.head(big), repeat) + walk = ("SELECT count(*) FROM landings WHERE chain = ? AND seq <= ? AND kind = 'store' " + "AND (closed_at IS NULL OR closed_at > ?)") + for name, c in (("heads_at_tenth", head // 10), ("heads_at_mid", mid), ("heads_at_head", head)): + cut = {big: c} + reads[name] = {**_timed(functools.partial(cat.heads_at, cls, cut), 5), + "rows": len(cat.heads_at(cls, cut))} + # the same predicate counted in SQL: the walk alone, without building the rows + reads[name.replace("heads_at", "heads_walk")] = _timed( + functools.partial(_count, cat._conn, walk, [big, c, c]), 5) + out["reads"] = reads + + # the write overhead: new paths, then new versions of held paths, with and without the log + writes: dict[str, Any] = {"new": {"with": [], "without": []}, + "changed": {"with": [], "without": []}} + held = rng.sample(paths, min(batch * rounds * 2, len(paths))) + n = 0 + for r in range(rounds): + for log in ((True, False) if r % 2 == 0 else (False, True)): + fresh = [(f"bench/r{r}/{'w' if log else 'o'}/{i:06}.md", f"bench-{r}-{log}-{i}", + f"bench {i}", Provenance(cls)) for i in range(batch)] + secs = _batch(cat, fresh, log) + writes["new"]["with" if log else "without"].append(secs / batch * 1e6) + changed = [(p, f"changed-{r}-{log}-{i}", f"changed {i}", Provenance(cls)) + for i, p in enumerate(held[n:n + batch])] + n += batch + secs = _batch(cat, changed, log) + writes["changed"]["with" if log else "without"].append(secs / len(changed) * 1e6) + for kind in ("new", "changed"): + w = writes[kind] + w["with_median_us"] = statistics.median(w["with"]) + w["without_median_us"] = statistics.median(w["without"]) + w["overhead_us"] = w["with_median_us"] - w["without_median_us"] + out["writes_us_a_record"] = writes + out["verify_after_writes"] = all(cat.verify(c).ok for c in cat._log.all_chains()) + _checkpoint(cat._conn) + out["files_end"] = _files(db) + out["load_end"] = os.getloadavg() + cat.close() + return out + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("--catalog", type=Path, required=True, + help="a copy of a catalog file, migrated in place") + ap.add_argument("--batch", type=int, default=10_000) + ap.add_argument("--rounds", type=int, default=5) + ap.add_argument("--repeat", type=int, default=200) + ap.add_argument("--seed", type=int, default=11) + ap.add_argument("--out", type=Path) + args = ap.parse_args(argv) + out = measure(args.catalog, args.batch, args.rounds, args.repeat, args.seed) + text = json.dumps(out, indent=2, default=str) + if args.out: + args.out.write_text(text + "\n", encoding="utf-8") + print(text) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From d2faafaec6ef2314e8f4489073d6c61d19e6f514 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:24:02 -0500 Subject: [PATCH 11/30] docs(design): the snapshot note carries stage SN-1 as built Stage SN-1, the landing log, is built, so the note says so where it matters: the front matter and the header, section 1.4 (SNP-1 to SNP-5 in the ledger, the rest design theorems), section 11 (the measurements on a copy of the corpus instance's catalog, with the two findings the first run made: the closing update walking the chain, and every head of a 400,274-event chain at 1.6 s, the chain section 4.2 keeps heads for), and section 12 (SN-1 built, its rollback as built). Section 3.2 marks the three places the build departed from the design: the key of a path takes half its key from the instance's secret, which is not in the file, so the file alone cannot test a guess of a purged path (and section 6.1's purged row says so); a path that changes class leaves its chain by a sixth kind, leave, since a rename's move must fold to the catalog's tombstoned row and one kind cannot fold both; and the genesis writes a renamed path's tombstone as a move, as tombstone does. The fold is stated as the catalog keeps it. Co-Authored-By: Claude Opus 5.5 --- docs/design-notes/dn-temporal-snapshot.md | 165 +++++++++++++++------- 1 file changed, 113 insertions(+), 52 deletions(-) diff --git a/docs/design-notes/dn-temporal-snapshot.md b/docs/design-notes/dn-temporal-snapshot.md index 3ea47972..9292d4ec 100644 --- a/docs/design-notes/dn-temporal-snapshot.md +++ b/docs/design-notes/dn-temporal-snapshot.md @@ -3,7 +3,7 @@ type: design-note id: dn-temporal-snapshot track: query-language status: draft # provenance description, never a gate; the merge is ratification -implementation: design-only # nothing built in the store; the laws are machine-checked in formal/Palace/Snapshot.lean +implementation: partial # SN-1 built (the landing log, core/stores/landings.py; SNP-1 to SNP-5 in docs/LAWS.md); SN-2 to SN-8 design created: 2026-11-10 updated: 2026-11-11 links: @@ -18,6 +18,9 @@ links: - docs/design-notes/dn-graph-dynamics.md # GD-4: velocity over a window of cuts, which waits on the snapshot - docs/design-notes/dn-mathematical-foundations.md # the ladder; design theorems before code - formal/Palace/Snapshot.lean # the theorems (Snapshot/Defs.lean the model; PalaceTest/Snapshot.lean the attacks) + - core/stores/landings.py # SN-1 as built: the landing log, in the catalog's file + - docs/experiments/landing-log-2026-11-11.md # SN-1 measured on a copy of the corpus instance's catalog + - papers/2026-11-11-landing-log/paper.tex # the article of SN-1 supersedes: null superseded_by: null warrant: null @@ -44,6 +47,13 @@ warrant: null > recommendation this note had made, and the note now carries the decision wherever the design > rested on the seal. And six findings the review of the design left open are closed (§3.1, > §3.5, §5.1, §5.4). The code cited for both was read at `f969904e`. +> +> Stage SN-1, the landing log, was built the same day (§12), with its tests, its ledger rows +> (SNP-1 to SNP-5, `docs/LAWS.md` family XVI) and its measurements on a copy of the corpus +> instance's catalog (§11, `docs/experiments/landing-log-2026-11-11.md`). Where the build +> departed from §3.2 the section says so where it stands: the key of a path takes half of its +> key from the instance's secret, outside the file; a path that changes class leaves its chain +> by a sixth kind, `leave`; and the genesis writes a renamed path's tombstone as a `move`. ## 1. Purpose and scope @@ -145,16 +155,20 @@ cut. One of them keeps text, the rejected requests, and §6.1 names it for the p Proved, in `formal/Palace/Snapshot.lean` over `formal/Palace/Snapshot/Defs.lean`: SNP-1 to SNP-10 as §10 states them, 193 theorems, twenty of them the controls; attacked in `formal/PalaceTest/Snapshot.lean` (seeds 430 to 528: fifty-four attacks, every one surviving -all 500 instances, and forty-five negative controls, each refuted). They are design theorems: no -code relies on them, so they have no row in `docs/LAWS.md` and no statement in `formal/Spec/`; -§12 says when they enter the ledger. Some of what §6 and §7 require holds by the construction of +all 500 instances, and forty-five negative controls, each refuted). SNP-1 to SNP-5 entered the +ledger with SN-1, the landing log: they are family XVI of `docs/LAWS.md`, and the 47 declarations +§10 lists for them are restated in `formal/Spec/Snapshot.lean` and judged by the comparator. SNP-6 +to SNP-10 are design theorems: no code relies on them yet, so they have no row and no statement; +§12 says when each enters. Some of what §6 and §7 require holds by the construction of the model and not by a theorem about the code: §10 says which, law by law. -Measured, on synthetic fixtures only (§11): the landing log's size and the cost of its reads; what +Measured, on synthetic fixtures (§11): the landing log's size and the cost of its reads; what a kept version costs in the lexical index; what a purge leaves behind today; that the causal store depends on the order of two jobs; that the events of a transcript's prefix are not always the prefix of its events, and what re-deriving a session costs; what `as of` accepts and when; that a -position taken from a store's row numbering is given again after a delete. +position taken from a store's row numbering is given again after a delete. And, at SN-1, the log as +built, on a copy of the corpus instance's catalog: its migration, its bytes, its writes and its +reads (§11, as built). Open, stated where it bites: the attestation ledger's own content hashes under an erasure (decision D9); the cadence of recorded cuts (§3.3); a repository history that is not one line @@ -395,23 +409,26 @@ INFERENCE for the line, parked as SN-f]` Two tables in the catalog's file, written by the catalog's own methods in the transaction that writes the catalog's row, so the key and its log entry land together, no caller can write one without the other, and ING-7's order is unchanged (the key last, now two rows of one -transaction): +transaction). Stage SN-1 built them on 2026-11-11 (`core/stores/landings.py`), and three things +changed from the design as it was merged, each marked where it stands: where the key of a path +comes from, a sixth kind, and the tombstone the genesis writes. ```sql CREATE TABLE landing_chains ( - chain INTEGER PRIMARY KEY, -- the chain's id: never reused, never changed - class TEXT NOT NULL, -- the provenance class it holds now; a relabel rewrites this only - secret BLOB NOT NULL -- 32 random bytes: the key of path_key + chain INTEGER PRIMARY KEY, -- the chain's id: never reused, never changed + class TEXT NOT NULL, -- the provenance class it holds now; a relabel rewrites it + secret BLOB NOT NULL, -- 32 random bytes: the chain's half of the key of path_key + key_check BLOB NOT NULL -- hmac-sha256(the chain's key, 'key check') ); CREATE TABLE landings ( chain INTEGER NOT NULL, -- landing_chains.chain seq INTEGER NOT NULL, -- the position in the chain, from 1, never given twice - kind TEXT NOT NULL, -- genesis | store | retire | move | horizon - path_key BLOB, -- hmac-sha256(secret, source_path): the key a hole keeps + kind TEXT NOT NULL, -- genesis | store | retire | move | leave | horizon + path_key BLOB, -- hmac-sha256(the chain's key, source_path): kept by a hole source_path TEXT, -- NULL once purged doc_id TEXT, -- the identity the event belongs to; NULL once purged version INTEGER, -- the version number, where the place keeps a chain - digest TEXT, -- NULL for a retire, and once purged + digest TEXT, -- a store's digest; NULL for every other kind, and once purged title TEXT, -- NULL once purged att_head INTEGER, -- the head of att when the row was written; NULL before SN-2 horizon INTEGER, -- a horizon row: the position it declares; NULL otherwise @@ -431,13 +448,19 @@ CREATE INDEX landings_closed ON landings (chain, closed_at) WHERE closed_at IS N **The kinds** are the catalog's writes. `store` is a landing (`record`). `retire` is the tombstone of an identity no other active path holds. `move` is a tombstone that leaves the identity at another path (the second half of a rename, which the writer tells from a delete by the catalog, -`writer.py:409-413`), the owner-gated re-key of an identity (`catalog.py:210-241`), and the row that -closes a path in one chain when a `record` gives it another class, its `store` then landing in a -chain of the new class. `genesis` and `horizon` are below and in §8. There is no kind that lifts a -retire: a retire seals nothing (§6.2). A purge is not a kind: it empties rows (§6.1). A `record` -that changes nothing, the same path, digest, title, class and identity as the path's open row, -appends nothing: the log is of the changes of the map, and the catalog's `updated_at` is a bookmark -(the curated lane re-lands an unchanged digest after a plane reset, `core/ingest/curated.py:66-82`). +`writer.py:409-413`), and the owner-gated re-key of an identity (`catalog.py:210-241`), which writes +the path's `store` under the new identity after it, or its `retire` when the path is tombstoned. +`leave` is the row that closes a path in one chain when a `record` gives it another class, its +`store` then landing in a chain of the new class. The design had a `move` for this too; SN-1 made it +a kind of its own, because the two fold differently. The catalog keeps a renamed path's row, +tombstoned, so the old path's `move` folds to that row; a path that changed class has its row from +the chain it went to, so its `leave` folds to nothing; and a path that changed class and was then +renamed has an open `move` in two chains, which one kind cannot tell apart. `genesis` and `horizon` +are below and in §8. There is no kind that lifts a retire: a retire seals nothing (§6.2). A purge is +not a kind: it empties rows (§6.1). A `record` that changes nothing, the same path, digest, title, +class and identity as the path's open row, appends nothing: the log is of the changes of the map, +and the catalog's `updated_at` is a bookmark (the curated lane re-lands an unchanged digest after a +plane reset, `core/ingest/curated.py:66-82`). **Which chain a landing goes to.** The chain that holds the path's last event; for a path with no event, the newest chain of its class, opened if the class has none. So a relabel moves no row @@ -456,35 +479,46 @@ first row for as long as it lives. The chain is hashed like the prediction ledge commitment to the row and not the row, so a purge can empty the row and keep the chain (`commitments_purge`, `verifies_purge`). `[THEOREM: SNP-9]` -**The key of a hole.** `path_key` is a keyed hash of the path under the chain's secret. It is -what a read by path seeks on, and it is the one name a purged row keeps, so a hole still shadows -the path's earlier versions (§6.1). `version` and `att_head` are the two fields a caller -supplies: `record` gains a `version` argument, passed by the writer's last step from the version -it just appended or found (`writer.py:408-419`, `:433`; `sync.py:201`) and left out where the -place keeps no chain; `att_head` is the attestation ledger's head read inside the key's -transaction, after the landing's own attestation, and stays `NULL` until SN-2 numbers that -ledger, which reads as the end of the ledger's genesis (§8). - -**The genesis.** At the first open after the migration that fills `doc_id` -(`catalog.py:77-92`), each class the catalog holds gets a chain: a `genesis` row, then the -catalog's rows of the class in path order, an active path as one `store` and a tombstoned path -as a `store` of the digest it held followed by a `retire`, then a `horizon` row whose `horizon` -is its own position. The order inside the block is not history, so the positions before the -`horizon` are under it (§8). A class that first appears later opens its chain at its first -landing, with a `genesis` and a `horizon` and nothing between. - -The catalog is then the fold of the log: each path's last event (`stateOf`), an active row for a -`store`, a tombstoned row for a `retire` with the digest of the path's last `store`, and no row -when that `store` is a hole or the path's last event is a `move`. The state at a position is the -same fold of the prefix (`stateAt`), read by one seek as the path's last event at or under the -position (`stateAt_eq_lastWrite`), or for every path at once through the closing stamp: the rows -with `seq ≤ c` and `closed_at` absent or above `c` (`genRead_gens`). The stamp is the one field -written after a row is appended, and it is a function of the rows, the position of the path's +**The key of a hole.** `path_key` is a keyed hash of the path. It is what a read by path seeks on, +and it is the one name a purged row keeps, so a hole still shadows the path's earlier versions +(§6.1). Its key has two halves: the chain's 32 random bytes, in the file, and the instance's +landing-log secret, which is never in the file. The design had the chain's bytes alone; SN-1 takes +the secret as the repository takes every instance's secret, from the environment through +`get_secret`, Keychain-backed in the owner's setup and the instance's own item under a named +instance (`landing-log-key`, `.landing-log-key`), so the file alone cannot test a guess of a +purged path. Without the secret the genesis and every write refuse, loudly, and write nothing; a +secret that is not the one a chain was written with is refused by the chain's `key_check`; a read +needs it only to seek by path. `version` and `att_head` are the two fields a caller supplies: +`record` gains a `version` argument, passed by the writer's last step from the version it just +appended or found (`writer.py:408-419`, `:433`; `sync.py:201`) and left out where the place keeps no +chain; `att_head` is the attestation ledger's head read inside the key's transaction, after the +landing's own attestation, and stays `NULL` until SN-2 numbers that ledger, which reads as the end +of the ledger's genesis (§8). + +**The genesis.** At the first open after the migration that fills `doc_id` (`catalog.py:77-92`), +each class the catalog holds gets a chain: a `genesis` row, then the catalog's rows of the class in +path order, an active path as one `store` and a tombstoned path as a `store` of the digest it held +followed by its tombstone, then a `horizon` row whose `horizon` is its own position. The tombstone +is the one `tombstone` would write: a `move` where another active path holds the identity, a +`retire` otherwise (the design said `retire` for every one, which would count a renamed path among +the identities that run across a retire, §6.2). The order inside the block is not history, so the +positions before the `horizon` are under it (§8). A class that first appears later opens its chain +at its first landing, with a `genesis` and a `horizon` and nothing between. + +The catalog is then the fold of the log: each path's last event (`stateOf`) in the chain that holds +its present, the one where its last event is not a `leave`; an active row for a `store`; a +tombstoned row for a `retire` or a `move`, with the digest and title of the path's last `store` and +the identity the tombstone names; and no row when that `store` is a hole. (The design read a `move` +as no row, which the catalog contradicts: it keeps a renamed path's row, tombstoned.) The state at a +position is the same fold of the prefix (`stateAt`), read by one seek as the path's last event at or +under the position (`stateAt_eq_lastWrite`), or for every path at once through the closing stamp: +the rows with `seq ≤ c` and `closed_at` absent or above `c` (`genRead_gens`). The stamp is the one +field written after a row is appended, and it is a function of the rows, the position of the path's next event (`gens_append_singleton`), so it can be rebuilt and it changes no read at a cut inside the chain (`genRead_gens_append`). At most one row of a path is alive at a cut -(`length_filter_selects_le_one`), which is L7's falsifier turned into a theorem. `[THEOREM: -SNP-5]` The store's own precedent is the staging store: a generation clock, an admission stamp -and a tombstone stamp on each row, and `read_at(g)` as exactly this predicate +(`length_filter_selects_le_one`), which is L7's falsifier turned into a theorem. `[THEOREM: SNP-5]` +The store's own precedent is the staging store: a generation clock, an admission stamp and a +tombstone stamp on each row, and `read_at(g)` as exactly this predicate (`core/stores/staging.py:232-244`). `[ESTABLISHED]` ### 3.3 The cut and its record @@ -1147,7 +1181,7 @@ content. `[THEOREM: SNP-9 for the chain; DERIVED for the salt]` What stays, and - `chain`, `seq` and `kind`: the position, which the erasure must keep. - `path_key`: so that the hole shadows. It can be tested against a guess of the path only with - the chain's secret, which is in the same file as the rows. + the instance's landing-log secret, which is not in the file (§3.2, as built at SN-1). - `closed_at` and `version`: positions and a count, no content. `closed_at` is a function of the rows that keep their keys, so nulling it would hide nothing. - `att_head`: a position on another chain. @@ -1939,8 +1973,9 @@ given as arithmetic are marked so where they stand. The probes are short scripts and are not in the repository: this pull request changes no Python, and the newest notes keep a harness under `eval/` with a record under `docs/experiments/`. So these figures cannot be repeated from the tree as it stands. Each stage -of §12 commits the harness of what it builds with its record: SN-1 the log's size and reads, -SN-3 the purge probe as a test, SN-5 the causal probes. The table gives each fixture closely +of §12 commits the harness of what it builds with its record: SN-1 the log's size and reads +(done: `eval/landing_log_bench.py`, measured on the corpus's catalog, below the table), SN-3 the +purge probe as a test, SN-5 the causal probes. The table gives each fixture closely enough to be built again. One machine (Apple M2 Pro, 12 cores, 32 GB, macOS 27.0) with other work running, the load @@ -1971,6 +2006,25 @@ recomputed over a real instance's sessions, cold or warm; a vector search with s joined to the heads at a cut; the reads of the chat log and the attestation ledger through their chain tables; a retention pass. Each is the measurement of the stage that builds it. +**Measured at SN-1, on a copy of the corpus instance's catalog (added 2026-11-11).** The log as +built, by its committed harness (`eval/landing_log_bench.py`), on two copy-on-write clones of the +corpus instance's catalog, 400,274 rows all `observed` and active; the record is +`docs/experiments/landing-log-2026-11-11.md`, every figure in its JSON. The same machine, with +Python 3.15.2 and SQLite 3.54.1 and other work running. `[MEASURED]` + +| probe | result | +|---|---| +| the migration: the tables, their indexes and the genesis, one chain of 400,276 rows | 6.22 to 6.33 s; the file 162.7 MB before and 334.1 MB after, 429 bytes a row (the table 381, the key index 47, the other two empty); the fold of the log equal to the catalog row by row | +| `verify`, every commitment and hash from the first row | 3.05 to 3.07 s | +| the reads | `state_at` of one path at the middle cut 14.3 to 14.8 µs, 1.6 of them the keyed hash; `history_at` at the head 14.7 to 15.7 µs; `read_at` and `read_between` of 1,000 positions 3.3 to 3.4 ms, the rows built in Python; `heads_at` 0.15 s at a tenth, 0.79 to 0.80 s at the middle and 1.6 s at the head, of which the walk in SQL is 6 ms, 26 ms and 54 to 57 ms | +| a key's write in a batch of 10,000, with the log and without | a new path 48.9 to 49.0 µs against 6.8; a new version of a held path 106.0 to 106.5 against 37.9 to 41.2: 42 and 65 to 69 µs added, 0.1 to 0.2 percent of a lazy landing's 31 ms (`docs/experiments/two-phase-ingestion-2026-11-07.md`) | + +Two findings came out of it. The update that writes a row's closing stamp took the primary key and +walked the chain, about 40 ms a landing at this size, until it named the key index as the seeks do +(§4.1); a test now asks the plan of every statement by path to name it. And every head at the head +of a chain of 400,274 events is 1.6 s, past §4.2's tenth of a second, the walk itself at 0.14 µs an +event: the corpus's chain is the one §4.2 says keeps heads at recorded cuts from SN-4 on (SN-c). + ## 12. The build order Nothing is built by this note. What the merge licenses is decision D12. The stages, each a pull @@ -1978,7 +2032,11 @@ request against main with its tests and its rollback, each transcribing its laws property-testing the transcription against the Lean statements; the laws a stage relies on enter `docs/LAWS.md` and `formal/Spec/` with it, as design theorems do when code comes to rely on them. -- **SN-1 the landing log.** What is built: +- **SN-1 the landing log.** Built on 2026-11-11: `core/stores/landings.py` and the catalog's six + methods, `tests/property/test_landing_log.py`, family XVI of `docs/LAWS.md` with + `formal/Spec/Snapshot.lean`, and the measurements of §11; the three departures from §3.2 are + marked there, and the landing-log secret is a deploy's precondition (`docs/runbook.md` §0). + What is built: - The tables `landing_chains` and `landings` of §3.2 with their three indexes, in the catalog's file, created by the catalog's own migration after it fills `doc_id` (`core/stores/catalog.py:77-92`), and the genesis of §3.2 for each class the catalog holds. @@ -2017,7 +2075,10 @@ property-testing the transcription against the Lean statements; the laws a stage `formal/comparator.json` gains their names, as the last family added did. Rollback: the tables are additive and unread, so dropping them restores the file; a build - that stops writing them and resumes later appends a `horizon`. + that stops writing them and resumes later appends a `horizon`. As built, the resumption is a + new genesis on the dropped tables, which ends at its `horizon`: a build without the log that + wrote the catalog while the tables stayed would leave the log behind the catalog, and nothing + detects that yet, so the rollback drops them (`docs/runbook.md` §0). - **SN-2 cuts.** The chain tables, each with its running hash and its genesis followed by a horizon, for `chat`, `att`, `staging` and `runs`; `att_head` filled from then on; on the chain-table row of a pass attestation and of a run, the landing chains that held its inputs and the head of each, and From c51f7e9e7dbf0578db4e4aa7e2b1242c62ff2244 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:26:39 -0500 Subject: [PATCH 12/30] docs(paper): the landing log, the article of stage SN-1 Eight pages in the format of the existing articles: the catalog's missing past, the decision of the design on the two forms of removal, the five laws as the model states them with their Lean declarations, the log as built (its tables and kinds, the fold, commitments, holes that keep their keys and the key's half outside the file, the genesis, the write in pseudocode, the reads), and the evaluation: what the gate proves and judges, what the property test checks, and the measurements on a copy of the corpus instance's catalog, with the query plan the first run found walking the chain. Limitations and the next stages close it. Every reference was looked up on Crossref by its DOI or its title. scripts/build_papers.sh builds it clean, with no undefined reference and no overfull box. Co-Authored-By: Claude Opus 5.5 --- papers/2026-11-11-landing-log/paper.tex | 398 ++++++++++++++++++++++++ papers/2026-11-11-landing-log/refs.bib | 198 ++++++++++++ 2 files changed, 596 insertions(+) create mode 100644 papers/2026-11-11-landing-log/paper.tex create mode 100644 papers/2026-11-11-landing-log/refs.bib diff --git a/papers/2026-11-11-landing-log/paper.tex b/papers/2026-11-11-landing-log/paper.tex new file mode 100644 index 00000000..8760d19f --- /dev/null +++ b/papers/2026-11-11-landing-log/paper.tex @@ -0,0 +1,398 @@ +\documentclass[11pt]{article} +\usepackage[T1]{fontenc} +\usepackage{lmodern} +\usepackage{microtype} +\usepackage[margin=1in]{geometry} +\usepackage{amsmath,amssymb,amsthm,mathtools} +\usepackage{algorithm} +\usepackage{algpseudocode} +\usepackage{booktabs} +\usepackage[numbers,sort&compress]{natbib} +\usepackage[hidelinks]{hyperref} +\usepackage[capitalise,noabbrev]{cleveref} +\setlength{\emergencystretch}{3em} + +\theoremstyle{plain} +\newtheorem{theorem}{Theorem}[section] +\theoremstyle{definition} +\newtheorem{definition}[theorem]{Definition} + +\newcommand{\lean}[1]{\path{#1}} +\newcommand{\N}{\mathbb{N}} +\newcommand{\at}[2]{#1|_{#2}} +\newcommand{\btw}[3]{#1|_{(#2,\,#3]}} +\newcommand{\hd}[1]{\lvert #1 \rvert} +\newcommand{\pre}{\preceq} +\newcommand{\cat}{\mathbin{+\!\!+}} + +\title{The Landing Log:\\ +A Catalog's Past in Its Own File, with Holes That Keep Their Keys} +\author{Alberto Serrano-Calva} +\date{November 11, 2026} + +\begin{document} +\maketitle + +\begin{abstract} +The catalog of a knowledge store maps each path to the content it holds now and is rewritten in +place, so it has no past: nothing records which content a path held before, or whether it was +deleted. A design for reading the store as of a past cut found this the one missing ledger, and +this paper builds it as the design's first stage. The landing log is two tables in the catalog's +own file, appended to by the catalog's six writing methods in the transaction of the row each +writes, so the catalog is the fold of the log and no caller can write one without the other. A +row carries a salted commitment that a hash chain covers, so a purge empties a row and the chain +still verifies; a row names its path by a keyed hash whose key is split between the file and a +secret outside it, so a hole still shadows the path's earlier versions, and the file alone cannot +test a guess of a purged path. The design takes two forms of removal: a retire leaves the item's +history readable at the cuts where it existed, and a purge leaves a hole at every cut. Five laws +of the design (append invariance, monotonicity, composition, idempotence, and a derived view as a +function of the prefixes) enter the store's ledger of laws as 47 statements machine-checked in +Lean~4, and a property test checks the code's reads against them over random sequences of writes. +On a copy of a catalog of 400{,}274 items the migration that writes the log takes 6.3~s and +429~bytes a row, the log adds 42 to 69~$\mu$s to a key's write, and a read of one path at a cut +takes 15~$\mu$s. Measuring at that size also found a query plan that walked the whole chain on +every write. +\end{abstract} + +\section{Introduction} + +The system is a personal knowledge store \cite{serranocalva2026palace}: notes, dialogue, papers and +code land through one writer into a dozen stores, and a sentence of a query algebra reads them. +Among the stores is a catalog, a table from each source path to the digest of the content it +holds, its title, its provenance class, an identity, and whether it is active. The writer reads it +to decide that content is unchanged, writes it last as the idempotence key of a landing, and +flips a row inactive when its source deletes the item. It is rewritten in place. A design for +reading the store as of a past cut \cite{serranocalva2026palace} found that this is the one store +whose past nothing else holds: the version chains record the past of one place only, and the +attestation ledger names digests and no paths. So no read at a past cut can say which version of +a note a cut holds. + +This paper builds the first stage of that design, the landing log, and reports what it costs. +The contributions: +\begin{enumerate} +\item The log (\Cref{sec:log}): an append-only, hash-chained record of the catalog's changes, one + chain a provenance class, written by the catalog's own methods in the transaction of the row + each writes, with the reads a later stage needs (the state of a path at a cut, its history, every + head at a cut, a range between cuts) and a verifier. +\item The rules that keep an erasure compatible with the chain and with reads by path: a purge + empties a row and keeps its position, its commitment and its hash, and the row keeps a keyed + hash of its path, whose key is half in the file and half in a secret outside it. +\item Five laws (\Cref{sec:laws}), proved in Lean over the design's model, now stated in the + store's ledger and judged by a comparator, with a property test of the code against each + (\Cref{sec:eval}). +\item Measurements on a copy of a 400{,}274-item catalog (\Cref{sec:eval}), and three places where + building the design changed it. +\end{enumerate} + +\paragraph{A decision of the design: two forms of removal.} +A retire, the tombstone a deletion in the source writes, is the shallow form: the item leaves the +present, and its history stays readable at the cuts where it existed; no seal withholds it there, +and a note written later at the same path takes a fresh identity, so that it does not inherit the +retired note's versions. A purge is the deep form: a hole at every cut, and every derived answer +at a past cut becomes what it would have been had the item never landed; what survives is the +record that a purge happened, not the content. The design's owner took this decision on 11 +November 2026, after the design was reviewed. The log holds both: a retire is a row like any +other, and a purge empties rows. The fresh identity is a later stage's. + +\section{Background and related work} + +\paragraph{Hash chains and audit logs.} +Linking each record to the hash of its predecessor makes an append history tamper-evident +\cite{haber1991timestamp,merkle1988signature}, and secure audit logs add keys so that an attacker +who later holds the log cannot rewrite or read what came before \cite{schneier1999audit}. Here the +chain covers a salted commitment to each row and not the row \cite{halevi1996commitment}, so a row +can be emptied and the chain kept; once the salt is gone the commitment cannot be tested against a +guess of the content. A plain digest of guessable data is such a test, the reason salts were +added to stored passwords \cite{morris1979password}. The key of a path is an HMAC +\cite{bellare1996keying,rfc2104}. + +\paragraph{Erasure in append-only records.} +A right to erasure meets append-only records in many systems \cite{politou2018forgetting}, and one +answer for a hash-chained ledger is to make blocks redactable \cite{ateniese2017redactable}. The +log needs less: one writer, and a chain over commitments that an erasure leaves in place. + +\paragraph{Temporal data.} +Temporal databases keep rows valid over periods \cite{snodgrass1985taxonomy}, and SQL:2011's +system-versioned tables answer a query as of a system time \cite{kulkarni2012sql2011}; multiversion +concurrency control keeps versions so a reader sees a past state \cite{bernstein1983mvcc}. The log +counts periods in positions of an append chain, never in wall time, since the store's stores share +no clock; a cut is a position a chain, after the consistent cuts of distributed systems +\cite{lamport1978time,chandy1985snapshots}. + +\paragraph{Checking a transcription.} +The laws are proved in Lean~4 \cite{moura2021lean4} over Mathlib \cite{mathlib2020}, on a model, and +the code is checked against them by property-based testing \cite{claessen2000quickcheck} with +Hypothesis \cite{maciver2019hypothesis}. + +\section{The model and the laws}\label{sec:laws} + +\begin{definition}[Stores, cuts, reads] +A \emph{store} is a family of append chains $s : K \to \mathrm{List}\,\alpha$, its \emph{head} +$\hd{s}(k)$ the length of chain $k$; $s \cat t$ appends chain by chain, and $s \pre s'$ when +every chain of $s$ is a prefix of its chain in $s'$. A \emph{cut} is $c : K \to \N$, ordered +pointwise. The \emph{read at} $c$ is $\at{s}{c}(k) = \mathrm{take}\,(c\,k)\,(s\,k)$, the +\emph{read between} $a$ and $b$ is $\btw{s}{a}{b}(k) = \mathrm{drop}\,(a\,k)\,(\at{s}{b}\,k)$, and +a \emph{derived view} at $c$ is $D(\at{s}{c})$. A reader $F(s,c)$ is \emph{append invariant} when +$F(s \cat t, c) = F(s, c)$ for every $t$ and every $c \le \hd{s}$. +\end{definition} + +\begin{definition}[A keyed chain, three ways] +For a chain $l$ of keyed writes $(x, v)$: $\mathrm{stateAt}\,l\,c$ maps each key to its last value +in $\mathrm{take}\,c\,l$; $\mathrm{lastWrite}\,l\,c\,x$ is the value of the last write of $x$ in +that prefix, one seek; and $\mathrm{gens}\,l$ is one row a write, valid from the first cut that +holds it up to the first cut that holds the key's next write, its \emph{closing stamp}, read at a +cut by $\mathrm{genRead}$. +\end{definition} + +\begin{theorem}[SNP-1, append invariance]\label{thm:snp1} +For $c \le \hd{s}$: $\at{(s \cat t)}{c} = \at{s}{c}$, a read between two cuts inside the store is +unchanged likewise, and every derived view is append invariant. So are the read under an erasure +and under a grant, the keyed state and the generations (whose closing stamps growth writes), the +history of a key with no seal, and the filtered read of the references a resolver does not +follow. The controls: a reader that ignores the cut is not append invariant, and a retire written +after a cut empties the history a seal serves there. +(\lean{readAt_grow}, \lean{readBetween_grow}, \lean{appendInvariant_view}, +\lean{stateAt_append}, \lean{genRead_gens_append}, \lean{landingsAt_append}, +\lean{kept_grown_iff}; \lean{Witness.present_not_appendInvariant}, +\lean{Witness.seal_empties_history}.) +\end{theorem} + +\begin{theorem}[SNP-2, monotonicity]\label{thm:snp2} +If $c \le d$ then $\at{s}{c} \pre \at{s}{d}$; $\at{(\at{s}{c})}{d} = \at{s}{(d \sqcap c)}$ and +$\hd{\at{s}{c}} = c \sqcap \hd{s}$. The history of a key with no seal and the filtered read grow +with the cut. (\lean{readAt_mono}, \lean{readAt_readAt}, \lean{head_readAt}, +\lean{landingsAt_mono}, \lean{Kept.mono}.) +\end{theorem} + +\begin{theorem}[SNP-3, composition]\label{thm:snp3} +If $a \le b$ then $\at{s}{a} \cat \btw{s}{a}{b} = \at{s}{b}$, and two adjacent reads-between +compose. So a fold continued from a checkpoint over the delta is the fold of the prefix, for a +store and for a keyed chain, and a key the delta does not write has one state at both cuts. +(\lean{readAt_append_readBetween}, \lean{readBetween_append}, \lean{foldAt_readBetween}, +\lean{stateAt_eq_foldl}, \lean{stateAt_eq_of_not_written}.) +\end{theorem} + +\begin{theorem}[SNP-4, idempotence]\label{thm:snp4} +If $\hd{s} \le c$ then $\at{s}{c} = s$; every derived view at the head is the derivation of the +store, and the generations at the head read the store rewritten in place. +(\lean{readAt_of_head_le}, \lean{readAt_head}, \lean{view_head}, \lean{genRead_gens_length}.) +\end{theorem} + +\begin{theorem}[SNP-5, a derived view is a function of the prefixes]\label{thm:snp5} +A reader is append invariant if and only if it reads only the prefixes, if and only if it agrees +with a derived view on every cut inside the store. For a keyed chain, +$\mathrm{genRead}\,(\mathrm{gens}\,l)\,c\,x = \mathrm{stateAt}\,l\,c\,x = +\mathrm{lastWrite}\,l\,c\,x$, and at most one generation of a key is alive at a cut. The control: +the store rewritten in place determines no read at a past cut. +(\lean{appendInvariant_iff_prefixOnly}, \lean{appendInvariant_iff_exists_view}, +\lean{genRead_gens}, \lean{stateAt_eq_lastWrite}, \lean{length_filter_selects_le_one}; +\lean{Witness.stateOf_forgets}.) +\end{theorem} + +The proofs are short inductions on lists; the substance is in the choice of statements. SNP-5 is +what lets the log be read three ways that must agree: by a seek on a path's key, by the closing +stamp for every path at once, and by folding the prefix. The log's \lean{closed_at} column is the +closing stamp, and it is the one field written after a row is appended; SNP-1 for the generations +says that writing it changes no read at a cut inside the chain. The design's other five laws +(the grant, the erasure, resolution, certificates, the horizon) stay design theorems until the +stage that relies on each is built; SNP-7's holes and SNP-9's commitments shape the log below, and +the tests of \Cref{sec:eval} check what of them the log already does. + +\section{The log as built}\label{sec:log} + +\paragraph{Tables.} +\lean{landing_chains} has one row a chain: an integer id never reused, the class it holds now, the +chain's 32 random bytes, and a key check. \lean{landings} has one row an event, keyed by +\lean{(chain, seq)}: its kind, the path's key, the path, the identity, the version number where +the place keeps version chains, the digest and title of a landing, a horizon's position, a 16-byte +salt, the commitment, the hash, the closing stamp, and a wall-clock bookmark that orders nothing. +Three partial indexes serve the reads: by path key, by identity where it differs from the path, and +by closing stamp. + +\paragraph{Kinds.} +A \lean{store} is a landing; a \lean{retire} the tombstone of an identity no other active path +holds; a \lean{move} a tombstone that leaves the identity at another path (the second half of a +rename), or an identity taken off a path by an owner's re-key; a \lean{leave} the row that closes +a path in its chain when the path changes class, its \lean{store} then landing in a chain of the +new class; \lean{genesis} and \lean{horizon} open a chain. A write that changes nothing appends +nothing. A relabel of a whole class rewrites the class of its chains and no row, so no position +moves and no hash breaks. + +\paragraph{The fold.} +The catalog is the fold of the log. A path's present is its last event in the one chain where that +event is not a \lean{leave}; a \lean{store} there is an active row, a \lean{retire} or a +\lean{move} a tombstoned row with the digest and title of the path's last \lean{store}, and a +\lean{store} emptied by a purge no row. The design had a \lean{move} for a change of class as +well, and read every \lean{move} as no row. The catalog contradicts that reading: it keeps a renamed +path's row, tombstoned. With one kind, a path that changed class and was then renamed has an open +\lean{move} in two chains and no way to tell which is its present; with \lean{leave} the present is +unique, also after a purge, since a purge keeps a row's kind. + +\paragraph{Commitments, holes and keys.} +The commitment is SHA-256 over the salt and the canonical JSON of the row's fields; the hash is +SHA-256 over the previous row's hash and the commitment. A purge (\lean{remove} of a path, +\lean{remove_digest} of a digest) empties a row: the path, the identity, the digest, the title, +the salt and the bookmark go, and the position, the kind, the key, the closing stamp, the +commitment and the hash stay. The chain then verifies from its first row as before, and the +commitment, its salt gone, tests no guess. The row keeps its path's key because a purge is by +digest and may take an old version of a path that is still live: a hole that lost its key would +let a read by path return the version before it at a cut where the purged one was the head. The +key is $\mathrm{HMAC}(k_c, \text{path})$ with $k_c = \mathrm{HMAC}(K, \text{chain's bytes})$, +where $K$ is the instance's landing-log secret, read from the environment as the store reads its +other secrets and never written to the file. The design had the chain's bytes alone as the key, +in the same file as the rows; with $K$ outside it, a copy of the file cannot test whether a hole +was a given path. A missing secret refuses the migration and every write before anything is +written, and a chain's key check refuses a secret it was not written with. + +\begin{algorithm}[t] +\caption{A landing of \texttt{path} in class \texttt{cls}, inside the catalog's transaction.} +\label{alg:record} +\begin{algorithmic}[1] +\State $p \gets$ the catalog's row of \texttt{path}, read before it is rewritten +\State upsert the catalog's row (the key, as before) +\If{$p$ is active with the same digest, title, class and identity} + \State \Return \Comment{a write that changes nothing appends nothing} +\EndIf +\State $e \gets$ the path's last event in the one chain where it is not a \texttt{leave} +\If{$e$ exists and its chain holds \texttt{cls}} + \State $T \gets e$'s chain; \textbf{if} $e$ is a \texttt{store} of another identity \textbf{then} + append a \texttt{move} to $T$ +\Else + \State $T \gets$ a chain of \texttt{cls} the path left, else the newest chain of \texttt{cls}, + else a new chain (\texttt{genesis}, \texttt{horizon}) + \State \textbf{if} $e$ exists \textbf{then} append a \texttt{leave} to $e$'s chain +\EndIf +\State append a \texttt{store} to $T$: set the path's open row's closing stamp to the new + position, then insert the row with its salt, commitment and hash +\end{algorithmic} +\end{algorithm} + +\paragraph{The genesis.} +On the first open of a catalog that has rows and no log, each class gets a chain: a +\lean{genesis}, the catalog's rows of the class in path order, an active path as a \lean{store} +and a tombstoned one as a \lean{store} followed by its tombstone, then a \lean{horizon} whose +position is its own. The order inside the block is not history, so the positions under the horizon +are not served at a cut. The design wrote every such tombstone as a \lean{retire}; the build writes +the \lean{move} that \lean{tombstone} would, where another active path holds the identity, so that +a renamed path is not counted among the identities whose history runs across a retire. + +\paragraph{Reads.} +\Cref{alg:record} is the write. The reads are \lean{chains(class)}, \lean{head(chain)}, +\lean{read_at} and \lean{read_between} (the rows of a range of positions), \lean{state_at} (a +path's last event at or under a cut over its class's chains, one seek on the key index a chain), +\lean{history_at} (its \lean{store} rows there, a hole where a version was purged), +\lean{heads_at} (the \lean{store} rows whose closing stamp is absent or past the cut), and +\lean{verify}, which recomputes the hashes from the first row and the commitment of every row that +still has its salt. A cut over a class is one position a chain. Nothing reads the log yet; the +stage that reads the notes at a cut does. + +\section{Evaluation}\label{sec:eval} + +\paragraph{What is proved.} +The 47 declarations the design lists for SNP-1 to SNP-5 are restated, their proofs left out, in a +statement file over the model, and a comparator checks that the library proves each exactly as +stated, from the standard axioms; the store's gate also audits the axioms of all 5{,}250 library +declarations and replays the export, 56{,}231 declarations from \lean{Init} up, through Lean's +kernel and five independent checkers. The ledger now has 105 rows in 16 families, and a +cross-reference holds its rows, the statements and the docstring markers to one another. The +attacks on these laws, property tests of the model's computable definitions run before the proofs, +survive 500 draws each. + +\paragraph{What is tested.} +The transcription is checked against the laws by a property test: Hypothesis draws sequences of 3 to +40 catalog writes over five paths, six digests, two titles, three classes and two identities, with +retires, renames, relabels, re-keys and both purges among them, 200 sequences a run. After every +write the catalog must equal the fold of the log and every chain must verify; every cut taken during +the sequence must read, after every later write, the rows and the state of every path it read +then, up to the holes a later purge leaves (SNP-1); every read of a chain must be a prefix of the +read at its head (SNP-2); the fold of every cut taken, continued over the rows since, must be the +catalog (SNP-3); the state of a path at the head must be its catalog row (SNP-4); and at every +position of every chain the seek, the closing-stamp read and the fold of the prefix must give every +path the same row, with no path alive twice (SNP-5). Eleven more tests take the stage's cases: a +write that changes nothing, and a landing the writer's unchanged check skips, append nothing; a +process killed between the catalog's row and the log's leaves neither; a failed batch leaves no +log row; the genesis is the catalog, tombstoned paths included, and ends at a horizon; a relabel +into a class that has rows changes no row; a purge of an old version of a live path is a hole by +all three reads at a cut where it was the head; an edited row fails \lean{verify}; the secret is +required, and another is refused; and every statement by path is planned on the key index. Seeding +two bugs, a log that writes no closing stamp and one that writes no \lean{leave}, fails the suite. + +\paragraph{What is measured.} +\Cref{tab:measure} gives two runs of the committed harness on two copy-on-write clones of the +catalog of the store's corpus instance, 400{,}274 rows of one class, all active, on an Apple M2 +Pro with SQLite 3.54.1 and other work running; the original was never opened. The genesis is one +chain of 400{,}276 rows, and its fold equals the catalog. + +\begin{table}[t] +\centering +\small +\begin{tabular}{@{}p{0.50\linewidth}p{0.44\linewidth}@{}} +\toprule +measurement & result \\ +\midrule +the migration: tables, indexes, genesis & 6.22 to 6.33 s \\ +bytes a row of the log (table, key index) & 429 (381, 47); the file from 162.7 to 334.1 MB \\ +\lean{verify}, every commitment and hash & 3.05 to 3.07 s \\ +\lean{state_at} of one path; its keyed hash & 14.3 to 14.8 $\mu$s; 1.6 $\mu$s \\ +\lean{history_at} of one path & 14.7 to 15.7 $\mu$s \\ +\lean{read_at}, \lean{read_between}, 1{,}000 positions & 3.3 to 3.4 ms \\ +\lean{heads_at} at a tenth, the middle, the head & 0.15, 0.79 to 0.80, 1.6 s \\ +the same walks counted in SQL & 6, 26, 54 to 57 ms \\ +a new path's write, with the log and without & 49.0 and 6.8 $\mu$s \\ +a new version's write, with the log and without & 106.0 to 106.5 and 37.9 to 41.2 $\mu$s \\ +\bottomrule +\end{tabular} +\caption{The landing log on a copy of a 400{,}274-item catalog: two runs, medians, ranges across +the runs. Writes are in batches of 10{,}000, one transaction each, as a landing batch writes its +keys.}\label{tab:measure} +\end{table} + +The log doubles the catalog's file, with paths, digests and titles the catalog holds already. It +adds 42~$\mu$s to a new path's write and 65 to 69~$\mu$s to a new version's, which also writes a +closing stamp; a landing without its vector took 31~ms an item on the store's earlier measurement +of two-phase ingestion, so the log is 0.1 to 0.2 percent of a landing. Reading every head at the +head of this chain takes 1.6~s, almost all of it building 400{,}274 rows in Python; the walk alone +is 0.14~$\mu$s an event. That is past the tenth of a second the design allows a read from the log +alone, and the design already keeps heads at recorded cuts for a chain over 250{,}000 events; this +chain is one. + +\paragraph{What measuring found.} +The first run took about 40~ms a landing. The update that writes the closing stamp of a path's +previous row took the primary key, \lean{(chain, seq)}, and walked the chain for the path's rows, +though the statement names the path's key: the planner's choice the design had already met for a +seek on its fixture. The statement now names the key index, and a test asks the plan of every +statement by path to name it. Nothing at the test suite's sizes showed the walk. + +\section{Limitations} + +One writer is assumed, as by the model. A build that wrote the catalog without the log, while the +log's tables stayed, would leave the log behind the catalog, and nothing detects that yet; the +rollback drops the tables, and the next open writes a new genesis. The genesis knows no version +numbers, since the version chains are another file. A purge of a digest reads the whole log, which +has no index by digest. A path with events in two chains of one class, possible only after a +change of class and a merge of the two classes, is read by a rule of the prefix alone that can +order its earlier segments otherwise than they happened. The secret is an operational dependency: +a process that writes the catalog stops without it, and a lost secret leaves the log unwritable. +The measurements are of one instance, one class and no deletions; a catalog of several classes, +with identities apart from paths, is tested and not measured. + +\section{Future work} + +The next stages of the design number the chat log and the attestation ledger, record cuts and +resolve names to them; then take the two forms of removal into every store (the deep form's reach +and the fresh identity), then read the notes, vectors and lexical index at a cut from this log. +Each property-tests its transcription against the Lean statements, and its laws then enter the +ledger. + +\section{Conclusion} + +A catalog rewritten in place loses its past at every write. Two tables in its own file, written in +the same transactions, keep it at about 430 bytes and 50~$\mu$s a landing, with the catalog their +fold. Holes keep their positions and their keys, so the chain survives an erasure and a read by +path never steps over one; the key's other half stays outside the file, so the holes reveal +nothing to whoever copies it. The five laws a reader at a cut relies on are now statements the +library is judged against, and the code is tested against them. + +\bibliographystyle{plainnat} +\bibliography{refs} +\end{document} diff --git a/papers/2026-11-11-landing-log/refs.bib b/papers/2026-11-11-landing-log/refs.bib new file mode 100644 index 00000000..e08e67ef --- /dev/null +++ b/papers/2026-11-11-landing-log/refs.bib @@ -0,0 +1,198 @@ +@article{haber1991timestamp, + author = {Haber, Stuart and Stornetta, W. Scott}, + title = {How to Time-Stamp a Digital Document}, + journal = {Journal of Cryptology}, + volume = {3}, + number = {2}, + pages = {99--111}, + year = {1991}, + doi = {10.1007/BF00196791} +} + +@inproceedings{merkle1988signature, + author = {Merkle, Ralph C.}, + title = {A Digital Signature Based on a Conventional Encryption Function}, + booktitle = {Advances in Cryptology --- CRYPTO '87}, + series = {Lecture Notes in Computer Science}, + volume = {293}, + pages = {369--378}, + publisher = {Springer}, + year = {1988}, + doi = {10.1007/3-540-48184-2_32} +} + +@article{schneier1999audit, + author = {Schneier, Bruce and Kelsey, John}, + title = {Secure Audit Logs to Support Computer Forensics}, + journal = {ACM Transactions on Information and System Security}, + volume = {2}, + number = {2}, + pages = {159--176}, + year = {1999}, + doi = {10.1145/317087.317089} +} + +@inproceedings{halevi1996commitment, + author = {Halevi, Shai and Micali, Silvio}, + title = {Practical and Provably-Secure Commitment Schemes from Collision-Free Hashing}, + booktitle = {Advances in Cryptology --- CRYPTO '96}, + series = {Lecture Notes in Computer Science}, + pages = {201--215}, + publisher = {Springer}, + year = {1996}, + doi = {10.1007/3-540-68697-5_16} +} + +@inproceedings{bellare1996keying, + author = {Bellare, Mihir and Canetti, Ran and Krawczyk, Hugo}, + title = {Keying Hash Functions for Message Authentication}, + booktitle = {Advances in Cryptology --- CRYPTO '96}, + series = {Lecture Notes in Computer Science}, + pages = {1--15}, + publisher = {Springer}, + year = {1996}, + doi = {10.1007/3-540-68697-5_1} +} + +@techreport{rfc2104, + author = {Krawczyk, H. and Bellare, M. and Canetti, R.}, + title = {{HMAC}: Keyed-Hashing for Message Authentication}, + institution = {RFC Editor}, + type = {RFC}, + number = {2104}, + year = {1997}, + doi = {10.17487/RFC2104} +} + +@article{morris1979password, + author = {Morris, Robert and Thompson, Ken}, + title = {Password Security: A Case History}, + journal = {Communications of the ACM}, + volume = {22}, + number = {11}, + pages = {594--597}, + year = {1979}, + doi = {10.1145/359168.359172} +} + +@inproceedings{snodgrass1985taxonomy, + author = {Snodgrass, Richard and Ahn, Ilsoo}, + title = {A Taxonomy of Time in Databases}, + booktitle = {Proceedings of the 1985 ACM SIGMOD International Conference on Management of Data}, + pages = {236--246}, + year = {1985}, + doi = {10.1145/318898.318921} +} + +@article{kulkarni2012sql2011, + author = {Kulkarni, Krishna and Michels, Jan-Eike}, + title = {Temporal Features in {SQL}:2011}, + journal = {ACM SIGMOD Record}, + volume = {41}, + number = {3}, + pages = {34--43}, + year = {2012}, + doi = {10.1145/2380776.2380786} +} + +@article{bernstein1983mvcc, + author = {Bernstein, Philip A. and Goodman, Nathan}, + title = {Multiversion Concurrency Control---Theory and Algorithms}, + journal = {ACM Transactions on Database Systems}, + volume = {8}, + number = {4}, + pages = {465--483}, + year = {1983}, + doi = {10.1145/319996.319998} +} + +@article{lamport1978time, + author = {Lamport, Leslie}, + title = {Time, Clocks, and the Ordering of Events in a Distributed System}, + journal = {Communications of the ACM}, + volume = {21}, + number = {7}, + pages = {558--565}, + year = {1978}, + doi = {10.1145/359545.359563} +} + +@article{chandy1985snapshots, + author = {Chandy, K. Mani and Lamport, Leslie}, + title = {Distributed Snapshots: Determining Global States of Distributed Systems}, + journal = {ACM Transactions on Computer Systems}, + volume = {3}, + number = {1}, + pages = {63--75}, + year = {1985}, + doi = {10.1145/214451.214456} +} + +@article{politou2018forgetting, + author = {Politou, Eugenia and Alepis, Efthimios and Patsakis, Constantinos}, + title = {Forgetting Personal Data and Revoking Consent under the {GDPR}: Challenges and Proposed + Solutions}, + journal = {Journal of Cybersecurity}, + volume = {4}, + number = {1}, + year = {2018}, + doi = {10.1093/cybsec/tyy001} +} + +@inproceedings{ateniese2017redactable, + author = {Ateniese, Giuseppe and Magri, Bernardo and Venturi, Daniele and Andrade, Ewerton}, + title = {Redactable Blockchain, or Rewriting History in Bitcoin and Friends}, + booktitle = {2017 IEEE European Symposium on Security and Privacy (EuroS\&P)}, + pages = {111--126}, + year = {2017}, + doi = {10.1109/EuroSP.2017.37} +} + +@inproceedings{claessen2000quickcheck, + author = {Claessen, Koen and Hughes, John}, + title = {{QuickCheck}: A Lightweight Tool for Random Testing of {Haskell} Programs}, + booktitle = {Proceedings of the Fifth ACM SIGPLAN International Conference on Functional + Programming}, + pages = {268--279}, + year = {2000}, + doi = {10.1145/351240.351266} +} + +@article{maciver2019hypothesis, + author = {MacIver, David and Hatfield-Dodds, Zac and {Many Contributors}}, + title = {Hypothesis: A New Approach to Property-Based Testing}, + journal = {Journal of Open Source Software}, + volume = {4}, + number = {43}, + pages = {1891}, + year = {2019}, + doi = {10.21105/joss.01891} +} + +@inproceedings{moura2021lean4, + author = {de Moura, Leonardo and Ullrich, Sebastian}, + title = {The {Lean} 4 Theorem Prover and Programming Language}, + booktitle = {Automated Deduction -- {CADE} 28}, + series = {Lecture Notes in Computer Science}, + pages = {625--635}, + publisher = {Springer}, + year = {2021}, + doi = {10.1007/978-3-030-79876-5_37} +} + +@inproceedings{mathlib2020, + author = {{The mathlib Community}}, + title = {The {Lean} Mathematical Library}, + booktitle = {Proceedings of the 9th ACM SIGPLAN International Conference on Certified Programs + and Proofs}, + pages = {367--381}, + year = {2020}, + doi = {10.1145/3372885.3373824} +} + +@misc{serranocalva2026palace, + author = {Serrano-Calva, Alberto}, + title = {mind-palace}, + howpublished = {\url{https://github.com/ascalva/mind-palace}}, + year = {2026} +} From 0916c5b276b81d5c8e2e2f53097d919a287eaa98 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:30:59 -0500 Subject: [PATCH 13/30] fix(stores): an open before the log's genesis waits for another's lock The genesis of the corpus instance's catalog holds the write lock for six seconds, and every open of the catalog takes the lock briefly for its doc_id backfill, so a second process that opened the catalog while the first wrote the genesis gave up after the connection's five seconds with "database is locked". Until the file holds the log with a chain, the migration now waits up to two minutes for the lock; once the log exists an open waits five seconds as it always did, so a hung writer still fails a new open quickly. Checked by hand: an open while another connection held the write lock for 6.5 s waited and then wrote the genesis. Co-Authored-By: Claude Opus 5.5 --- core/stores/catalog.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/stores/catalog.py b/core/stores/catalog.py index 2da53617..cdd3728e 100644 --- a/core/stores/catalog.py +++ b/core/stores/catalog.py @@ -64,6 +64,10 @@ """ +_BUSY_MS = 5000 # sqlite3.connect's own timeout, five seconds +_GENESIS_WAIT_MS = 120_000 # how long an open before the genesis waits for another's lock + + def _utcnow() -> str: return datetime.now(UTC).replace(tzinfo=None).isoformat(timespec="seconds") @@ -92,14 +96,27 @@ def __post_init__(self) -> None: self._conn.row_factory = sqlite3.Row self._log = LandingLog(self._conn, self._landing_key) try: + # Until the log's genesis is written another process may be writing it, six seconds + # on a catalog of 400,274 rows: the migration then waits for its lock longer than the + # connection's five seconds. Once the log has chains an open waits as it always did. + if not self._logged(): + self._conn.execute(f"PRAGMA busy_timeout = {_GENESIS_WAIT_MS}") self._conn.execute("PRAGMA journal_mode=WAL") self._conn.executescript(_DDL) self._migrate() self._conn.commit() + self._conn.execute(f"PRAGMA busy_timeout = {_BUSY_MS}") except BaseException: self._conn.close() raise + def _logged(self) -> bool: + """Whether the file holds the landing log with a chain: read only, no lock taken.""" + if self._conn.execute("SELECT 1 FROM sqlite_master WHERE type = 'table' " + "AND name = 'landing_chains'").fetchone() is None: + return False + return self._log.has_chains() + def _landing_key(self) -> bytes: return parse_key(self.key.hex()) if self.key is not None else landing_log_key() From 76723f7305f38162d1a3cf2b0efc6d4919500ebe Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 20:35:24 -0500 Subject: [PATCH 14/30] docs(readme): the counts from this branch's runs The ledger gains family XVI, the temporal snapshot: 105 rows in 16 families, 381 cited declarations and 92 law markers, and 375 statements judged by the comparator, from the check.sh run of the ledger's commit (5,250 declarations audited, 56,231 replayed, the attacks and controls unchanged at 232 and 206). The library has 27 statement files, 25,652 lines of models and proofs and 3,809 of statements. The deterministic tier is 3,645 tests at 77% coverage, the twelve new ones the landing log's. formal/README.md's count of the judged theorems follows. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 ++++++++-------- formal/README.md | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 4552cb54..19819ea7 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,12 @@ [![CI](https://github.com/ascalva/mind-palace/actions/workflows/ci.yml/badge.svg)](https://github.com/ascalva/mind-palace/actions/workflows/ci.yml) [![Lean](https://github.com/ascalva/mind-palace/actions/workflows/lean.yml/badge.svg)](https://github.com/ascalva/mind-palace/actions/workflows/lean.yml) -[![laws](https://img.shields.io/badge/laws-100_rows_in_15_families-blue)](docs/LAWS.md) -[![Lean statements](https://img.shields.io/badge/Lean-328_statements_judged-blue)](formal/README.md) +[![laws](https://img.shields.io/badge/laws-105_rows_in_16_families-blue)](docs/LAWS.md) +[![Lean statements](https://img.shields.io/badge/Lean-375_statements_judged-blue)](formal/README.md) [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) [![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3651-brightgreen)](docs/runbook.md) +[![tests](https://img.shields.io/badge/tests-3663-brightgreen)](docs/runbook.md) [![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) [![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py) @@ -121,13 +121,13 @@ A law has one row in [`docs/LAWS.md`](docs/LAWS.md): its statement, the structur | | | |---|---| | toolchain | Lean `v4.36.0-rc2`, Mathlib; Plausible for the attacks | -| the library | 38 proof modules, 37 models, 26 statement files; 25,649 lines of models and proofs, 3,460 of statements, 5,757 of attacks | -| theorems | 1,538 proved in `formal/Palace`; 328 statements in `formal/Spec` judged identical by the comparator | -| the ledger | 100 rows in 15 families, 334 cited declarations, 87 law markers checked against the rows | +| the library | 38 proof modules, 37 models, 27 statement files; 25,652 lines of models and proofs, 3,809 of statements, 5,757 of attacks | +| theorems | 1,538 proved in `formal/Palace`; 375 statements in `formal/Spec` judged identical by the comparator | +| the ledger | 105 rows in 16 families, 381 cited declarations, 92 law markers checked against the rows | | attacks | 232 Plausible attacks and 206 negative controls over 33 modules, fixed seeds | | axioms | `propext`, `Classical.choice`, `Quot.sound`; `sorry` 0 | | the replay | 56,231 declarations accepted by all six checkers on the run of `formal/check.sh` this commit was built with | -| families | memberships · Laplacian, balance and spectral · cut and conductance · curvature · the global event clock · the shared prose plane · capability scopes · the abstraction ultrametric σ* · bridges · the retrieval curve · the query sentence algebra · the ingress · stored vectors · the growth readout · the utility field | +| families | memberships · Laplacian, balance and spectral · cut and conductance · curvature · the global event clock · the shared prose plane · capability scopes · the abstraction ultrametric σ* · bridges · the retrieval curve · the query sentence algebra · the ingress · stored vectors · the growth readout · the utility field · the temporal snapshot | ## The mathematics @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in ```sh uv sync --extra dev -uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,651 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,663 tests uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned) uv run python scripts/check_imports.py # the sealed core names no network module uv run python -m ops.type_gate # every core-reaching package is type-checked diff --git a/formal/README.md b/formal/README.md index aec16330..b8a0924b 100644 --- a/formal/README.md +++ b/formal/README.md @@ -386,7 +386,7 @@ Roundoff and FloatModel, so it has no statements of its own): delegation's noninterference through the plane, and BRG-6 Forman's curvature as the Weitzenböck term of `L₁`. - `comparator.json`: what `lake comparator` judges: `Spec` against `Palace`, the cited theorems - (328 theorems), and the three standard axioms. + (375 theorems), and the three standard axioms. - `Compare.lean`: the comparator's comparison step, run in-process where its sandbox is unavailable (macOS has no `bwrap`); CI runs the comparator itself. It is weaker than the comparator: it compares the statements' types and the definitions' values, not constructors, recursor rules or From 73467eff8a0029995cc13116936cc9a31c4abda8 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 22:53:11 -0500 Subject: [PATCH 15/30] fix(stores): what a purge leaves, what a hole is, and a batch's failed write Review of SN-1 found three places where the landing log did less than dn-temporal-snapshot says, and tests that would not have noticed. A purge by digest emptied the rows of the digest and nothing else, so a note deleted and then purged, purge_raw's usual case, kept its retire: its path, its identity and the date of its delete stayed in the file, against D14. remove_digest now also empties a path's other rows, its retire, move and leave in every chain, once none of its versions keeps its content; while one does, the hole stays tied to the path as section 6.1 intends. It finds those rows by the names they carry and the keys the emptied rows keep, so a purge still needs no secret. verify took any row without its salt for a hole, so a row whose salt was nulled while its content stayed, or was rewritten, verified. It now fails a row without its salt that keeps any of the content a purge empties. Inside a deferred() batch a write whose log row failed after its catalog row left the catalog row in the batch when the caller caught the error and went on. Each write in a batch is now a savepoint, rolled back on its error. The docstrings of history_at say the order it gives across two chains of a class is a rule of the prefixes, and the module docstrings say which writes and reads need the secret. The tests: the property test starts from a random catalog's genesis and checks, after every write, that no row carries att_head, that a hole keeps no content, that every name the log carries is carried by a version that keeps its content, and that a change of identity follows a move; across a relabel it compares a path's last event chain by chain. Each of the six writes is killed, and failed, between its two rows, in a batch too. New cases pin the sync's versions, a re-key's version, the genesis's closing stamps by the three reads, a relabel over closed rows and holes, a history over two chains, a purge of every version of a deleted note (no row, and after a vacuum no byte, names it), a hole that keeps content, and the secret over every write and read. Of 58 seeded bugs, the reviewers' 50 (one rewritten for the new batch code) and 8 for these fixes, every one fails the suite on hypothesis seed 1 but one that changes nothing (it nulls a column already null). The ledger's rows SNP-1, SNP-2 and SNP-5 say what the tests check, the relabel's exception among it, and cite the renamed and new tests. Co-Authored-By: Claude Opus 5.5 --- core/stores/catalog.py | 44 ++- core/stores/landings.py | 75 ++++- docs/LAWS.md | 11 +- tests/fixtures/landing_writes.py | 32 ++ tests/property/test_landing_log.py | 456 ++++++++++++++++++++++++----- 5 files changed, 511 insertions(+), 107 deletions(-) create mode 100644 tests/fixtures/landing_writes.py diff --git a/core/stores/catalog.py b/core/stores/catalog.py index cdd3728e..784da3cc 100644 --- a/core/stores/catalog.py +++ b/core/stores/catalog.py @@ -22,11 +22,14 @@ `core/stores/landings.py`, two tables in this file that the six writing methods below append to in the transaction of the row each writes, so a `deferred()` batch carries its log rows and the catalog is the fold of the log. The migration that fills `doc_id` also creates the log and, on a -catalog that has rows and no log yet, writes its genesis. The log's keyed hash of a path needs the -instance's landing-log secret, which is read from the environment and never stored here: without -it the genesis and every write refuse, loudly, and nothing is written unkeyed. The reads of the -log (`chains`, `head`, `read_at`, `state_at`, `history_at`, `heads_at`, `read_between`, -`verify`) have no reader yet. +catalog that has rows and no log yet, writes its genesis: every process's first open of such a +catalog runs it, a reader's included. The log's keyed hash of a path needs the instance's +landing-log secret, which is read from the environment and never stored here: without it the +genesis, every write that appends a row (`record` and `tombstone` when they change the map, the +re-key) and `remove` refuse, loudly, and nothing is written unkeyed; `relabel_provenance` and +`remove_digest` append no row and need none. The reads of the log (`chains`, `head`, `read_at`, +`state_at`, `history_at`, `heads_at`, `read_between`, `verify`) have no reader yet; the two by +path, `state_at` and `history_at`, need the secret. """ from __future__ import annotations @@ -155,11 +158,20 @@ def _empty(self) -> bool: def _writing(self) -> Iterator[None]: """The transaction of one write: the catalog's row and its log rows commit together, or neither does. Inside `deferred()` the batch's transaction is the one, and it commits at - the end of the batch.""" + the end of the batch; each write in it is a savepoint, so a write that fails leaves + neither of its rows, even when the batch's caller catches the error and goes on.""" if not self._conn.in_transaction: self._conn.execute("BEGIN IMMEDIATE") if self._defer: - yield + self._conn.execute("SAVEPOINT catalog_write") + try: + yield + except BaseException: + if self._conn.in_transaction: # an error SQLite rolled back whole has no savepoint + self._conn.execute("ROLLBACK TO catalog_write") + self._conn.execute("RELEASE catalog_write") + raise + self._conn.execute("RELEASE catalog_write") return try: yield @@ -225,7 +237,9 @@ def record(self, source_path: str, digest: str, title: str, *, def deferred(self) -> Iterator[None]: """The records made inside commit once, at the end, in one transaction (a batch's keys, the last writes of its landing, and their rows of the landing log); an exception inside - rolls them back, so none of them is written.""" + rolls them back, so none of them is written. A write inside that fails is undone, its + catalog row with its log rows, before its error reaches the caller, so a caller that + catches it and goes on commits neither.""" self._defer = True try: yield @@ -359,7 +373,8 @@ def remove(self, source_path: str) -> None: of the path in the landing log is emptied in the same transaction: the path, the identity, the digest, the title, the salt and the bookmark go; the position, the key, the commitment and the hash stay (dn-temporal-snapshot §6.1), so the chain still - verifies and the hole still shadows the path's earlier versions.""" + verifies and the hole still shadows the path's earlier versions. It seeks the path's + rows by their key, so it needs the landing log's secret.""" with self._writing(): self._conn.execute("DELETE FROM vault_files WHERE source_path = ?", [source_path]) self._log.empty_path(source_path) @@ -376,7 +391,9 @@ def remove_digest(self, digest: str) -> int: Every row of the digest in the landing log is emptied in the same transaction, as `remove` empties a path's, including a version a live path held before: the log then - returns a hole at a cut where that version was the head, never the version before it.""" + returns a hole at a cut where that version was the head, never the version before it. A + path none of whose versions keeps its content afterwards has its tombstones emptied too, + so no row of the log names it (`LandingLog.empty_digest`). It needs no secret.""" with self._writing(): cur = self._conn.execute("DELETE FROM vault_files WHERE digest = ?", [digest]) self._log.empty_digest(digest) @@ -409,8 +426,11 @@ def state_at(self, provenance: Provenance | str, source_path: str, def history_at(self, provenance: Provenance | str, source_path: str, c: Mapping[int, int] | int) -> list[Landing]: - """A path's `store` rows at or under the cut, over the class's chains, oldest first; a - purged version is a hole in place.""" + """A path's `store` rows at or under the cut, over the class's chains; a purged version + is a hole in place. Oldest first in each chain; across two chains of one class, which a + path has only after a change of class and a relabel that merged the two, the chains it + left come first and the one that holds its present last, a rule of the prefixes and not + the order the versions landed in (`LandingLog.history_at`).""" return self._log.history_at(str(provenance), source_path, c) def heads_at(self, provenance: Provenance | str, c: Mapping[int, int] | int) -> list[Landing]: diff --git a/core/stores/landings.py b/core/stores/landings.py index e6fc7af2..6436d8e6 100644 --- a/core/stores/landings.py +++ b/core/stores/landings.py @@ -28,9 +28,13 @@ earlier versions (§6.1). Its key is derived from two halves: the chain's 32 random bytes in the file, and the instance's landing-log secret, which is never in the file: it is read from the environment (`get_secret`, Keychain-backed in the owner's setup, the instance's own item under a -named instance). A missing or malformed secret refuses the write, or the migration, loudly; no -row is ever written unkeyed. A secret that is not the one a chain was written with is refused as -well, by the chain's `key_check`, so a chain is never keyed two ways. +named instance). Whatever appends a row, or seeks a path's rows by their key, needs the secret: +the genesis, a `record` or a `tombstone` that changes the map, a re-key, `remove`, and the two +reads by path. Without it they refuse, loudly, before anything is written; no row is ever +written unkeyed. A relabel and a purge by digest need none: they append no row, and the purge +finds its rows by the digest, by the names they carry and by the keys the emptied rows keep. A +secret that is not the one a chain was written with is refused as well, by the chain's +`key_check`, so a chain is never keyed two ways. Nothing reads the log yet: the reads below are the ones the later stages build on. """ @@ -183,9 +187,17 @@ class Landing: @property def hole(self) -> bool: - """The row was emptied by a purge: its content is gone, its position stays.""" + """The row was emptied by a purge: its content is gone, its position stays. A row is + told a hole by its salt; `verify` fails a row without its salt that keeps any of the + content a purge empties (`content`).""" return self.salt is None + def content(self) -> dict[str, object]: + """The fields a purge empties beside the salt (§6.1): the path, the identity, the digest, + the title and the bookmark.""" + return {"source_path": self.source_path, "doc_id": self.doc_id, "digest": self.digest, + "title": self.title, "at": self.at} + def fields(self) -> dict[str, object]: """The fields the commitment covers (§3.2): every column but the key, the salt, the commitment, the hash and the closing stamp.""" @@ -478,9 +490,40 @@ def empty_path(self, path: str) -> int: def empty_digest(self, digest: str) -> int: """`remove_digest`: every row of the digest emptied as §6.1 says, its key and position - kept. Another version of the same path is not touched.""" - return self._conn.execute( + kept. Another version of the same path is not touched, so while a `store` of the path + keeps its content the path's other rows keep its name, and the hole stays tied to it. A + path whose every `store`, in every chain, is then a hole has its other rows emptied as + well, its `retire`, `move` and `leave`: no row then names it, or the identity and the + date its tombstone carried. A path's rows are found by the names they carry and by the + keys the emptied rows keep, so the purge needs no secret; the rows of the digest and the + names are read by a walk of the log, which has no index by digest or by name. Returns + the rows emptied.""" + hit = [(int(c), bytes(k), str(p)) for c, k, p in self._conn.execute( + "SELECT chain, path_key, source_path FROM landings WHERE digest = ? " + "AND path_key IS NOT NULL AND source_path IS NOT NULL", [digest])] + n = self._conn.execute( f"UPDATE landings SET {_EMPTY} WHERE digest = ?", [digest]).rowcount + paths = sorted({p for _, _, p in hit}) + if not paths: + return n + keys: dict[str, set[tuple[int, bytes]]] = {p: set() for p in paths} + for c, k, p in hit: + keys[p].add((c, k)) + for c, k, p in self._conn.execute( + "SELECT DISTINCT chain, path_key, source_path FROM landings WHERE path_key IS NOT " + f"NULL AND source_path IN ({', '.join('?' * len(paths))})", paths): + keys[str(p)].add((int(c), bytes(k))) + for path in paths: + if any(self._conn.execute( + "SELECT 1 FROM landings INDEXED BY landings_path WHERE chain = ? AND " + "path_key = ? AND kind = 'store' AND salt IS NOT NULL LIMIT 1", + [c, k]).fetchone() for c, k in keys[path]): + continue # a version of the path keeps its content + for c, k in sorted(keys[path]): + n += self._conn.execute( + f"UPDATE landings INDEXED BY landings_path SET {_EMPTY} " + "WHERE chain = ? AND path_key = ? AND salt IS NOT NULL", [c, k]).rowcount + return n # reads ---------------------------------------------------------------------------------- @@ -533,9 +576,14 @@ class and the two classes were merged; then the event that is not a `leave` is t return staying[-1] if staying else None def history_at(self, cls: str, path: str, c: Mapping[int, int] | int) -> list[Landing]: - """The path's `store` rows at or under the cut over the class's chains, oldest first, a - hole where a version was purged. Where the path has events in two chains of the class, - the chains it had left at the cut come first: a rule of the prefix alone.""" + """The path's `store` rows at or under the cut over the class's chains, a hole where a + version was purged. In one chain they are oldest first. A path has events in two chains + of one class only after it changed class and the two classes were merged by a relabel; + then the chains it had left at the cut come first, by chain id, and the chain that holds + its present last. That is a rule of the prefixes alone, not the order the versions + landed in, which no position across two chains records: the order can differ from it, + and across the chains the read at an earlier cut need not be a prefix of the read at a + later one. Chain by chain it is (SNP-2).""" chains = self.chains(cls) parts: list[tuple[bool, int, list[Landing]]] = [] for chain in chains: @@ -570,14 +618,19 @@ def rows(self, chain: int) -> Iterator[Landing]: def verify(self, chain: int) -> ChainCheck: """The chain's hashes recomputed from its first row, and the commitment of every row that - still has its salt (SNP-9): the first position where either fails, or none.""" + still has its salt (SNP-9); a row without its salt is a hole, and it must keep none of + the content a purge empties (§6.1), since nothing else can be checked of it. The first + position where one of these fails, or none.""" previous = _ZERO n = checked = 0 for row in self.rows(chain): n += 1 if row.seq != n: return ChainCheck(chain, n, checked, n, "a position is missing") - if row.salt is not None: + if row.salt is None: + if any(v is not None for v in row.content().values()): + return ChainCheck(chain, n, checked, row.seq, "a hole keeps content") + else: checked += 1 if not hmac.compare_digest(commitment(row.salt, row.fields()), row.commitment): return ChainCheck(chain, n, checked, row.seq, "the commitment") diff --git a/docs/LAWS.md b/docs/LAWS.md index abebfc9d..f30cee38 100644 --- a/docs/LAWS.md +++ b/docs/LAWS.md @@ -313,15 +313,16 @@ cut its prefix, and a path's state at a cut its last event there. Each law here family of append chains and a cut as a prefix length for each, stated in `formal/Spec/Snapshot.lean` and judged by the comparator; `tests/property/test_landing_log.py` checks the code's reads against it over random sequences of catalog writes with retires, renames, relabels, re-keys and both purges -among them. The same file checks what no row states yet: `verify` failing on an edited row (SNP-9, -which enters with stage SN-2) and the secret the keyed hash of a path needs. SNP-6 to SNP-10 stay +among them. The same file checks what no row states yet: `verify` failing on an edited row and on a +row without its salt that keeps content (SNP-9, which enters with stage SN-2), what a purge empties, +and the secret the keyed hash of a path needs. SNP-6 to SNP-10 stay design theorems of `Snapshot.lean`, cited from the note until the stage that relies on each is built (dn-temporal-snapshot §12). Nothing reads the log yet. The family was opened on 2026-11-11. | law | statement | structure | anchor | label | falsifier | formal | |---|---|---|---|---|---|---| -| SNP-1 | append invariance: the read of a chain at a cut inside the store, the read between two such cuts and every derived view of them are unchanged by any growth of the store; so are the read under an erasure and under a grant, the state of a chain of keyed writes and its generations, the history of a key with no seal and of an identity keyed by its lives, a retire among the growth included, and the filtered read of the references a resolver does not follow; the controls: a reader that ignores the cut is not append invariant, and a later retire empties the history a seal serves (exact: finite lists; on the code, every cut taken during a sequence of catalog writes reads after every later write the rows and the state of every path it read then, up to the holes a later purge leaves, which keep their positions, keys, commitments and hashes) | the prefix of an append-only sequence, a function of the prefix | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_grow`, `Snapshot.lean::readAt_of_extends`, `Snapshot.lean::readBetween_grow`, `Snapshot.lean::appendInvariant_view`, `Snapshot.lean::visible_grow`, `Snapshot.lean::snapshot_grow`, `Snapshot.lean::shown_grow`, `Snapshot.lean::stateAt_append`, `Snapshot.lean::genRead_gens_append`, `Snapshot.lean::landingsAt_append`, `Snapshot.lean::landingsAt_lives_append`, `Snapshot.lean::kept_grown_iff`; the controls: `Snapshot.lean::Witness.present_not_appendInvariant`, `Snapshot.lean::Witness.seal_empties_history` | -| SNP-2 | monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a later one, an event read at a cut is read at every later cut, a cut of a cut is the meet of the two, and the head of the read at a cut is the meet of the cut and the head; so are the read under an erasure, the history of a key with no seal, and the filtered read (exact: finite lists; on the code, every read of a chain is a prefix of the read at its head, and the rows between a cut and the head are the rest) | the prefix order on lists; cuts as a lattice | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.read_between` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_mono`, `Snapshot.lean::mem_readAt_of_le`, `Snapshot.lean::readAt_readAt`, `Snapshot.lean::head_readAt`, `Snapshot.lean::visible_mono`, `Snapshot.lean::landingsAt_mono`, `Snapshot.lean::Kept.mono` | +| SNP-1 | append invariance: the read of a chain at a cut inside the store, the read between two such cuts and every derived view of them are unchanged by any growth of the store; so are the read under an erasure and under a grant, the state of a chain of keyed writes and its generations, the history of a key with no seal and of an identity keyed by its lives, a retire among the growth included, and the filtered read of the references a resolver does not follow; the controls: a reader that ignores the cut is not append invariant, and a later retire empties the history a seal serves (exact: finite lists; on the code, every cut taken during a sequence of catalog writes, from a random catalog's genesis, reads after every later write the rows of every chain and each path's last event in each chain that it read then, up to the holes a later purge leaves, which keep their positions, keys, commitments and hashes; and the state of every path over a class while the class's chains are the ones it had: a relabel is not in the model, and it moves a whole chain to another class, so a read by class at a past cut follows the chain's class now, dn-temporal-snapshot §6.3, while a read by chain does not change) | the prefix of an append-only sequence, a function of the prefix | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_grow`, `Snapshot.lean::readAt_of_extends`, `Snapshot.lean::readBetween_grow`, `Snapshot.lean::appendInvariant_view`, `Snapshot.lean::visible_grow`, `Snapshot.lean::snapshot_grow`, `Snapshot.lean::shown_grow`, `Snapshot.lean::stateAt_append`, `Snapshot.lean::genRead_gens_append`, `Snapshot.lean::landingsAt_append`, `Snapshot.lean::landingsAt_lives_append`, `Snapshot.lean::kept_grown_iff`; the controls: `Snapshot.lean::Witness.present_not_appendInvariant`, `Snapshot.lean::Witness.seal_empties_history` | +| SNP-2 | monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a later one, an event read at a cut is read at every later cut, a cut of a cut is the meet of the two, and the head of the read at a cut is the meet of the cut and the head; so are the read under an erasure, the history of a key with no seal, and the filtered read (exact: finite lists; on the code, every read of a chain is a prefix of the read at its head, and the rows between a cut and the head are the rest; a path's history is a prefix chain by chain, and across two chains of one class, which only a change of class and a relabel make, it is ordered by a rule of the prefixes and need not be) | the prefix order on lists; cuts as a lattice | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.history_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_history_over_two_chains_of_a_class_follows_a_rule_of_the_prefixes` | `Snapshot.lean::readAt_mono`, `Snapshot.lean::mem_readAt_of_le`, `Snapshot.lean::readAt_readAt`, `Snapshot.lean::head_readAt`, `Snapshot.lean::visible_mono`, `Snapshot.lean::landingsAt_mono`, `Snapshot.lean::Kept.mono` | | SNP-3 | composition: the read at `a` followed by the read between `a` and `b` is the read at `b`, and two adjacent reads-between compose, so a fold continued from a checkpoint over the delta is the fold of the prefix, for a store and for a chain of keyed writes; an event, or a pair of events, read at the later cut was read at the earlier one or lies in the delta, and a key the delta does not write has one state at both cuts (exact: finite lists; on the code, the catalog folded from every cut taken and continued over the rows since is the catalog) | a left fold over a concatenation | `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_append_readBetween`, `Snapshot.lean::readBetween_append`, `Snapshot.lean::foldAt_readBetween`, `Snapshot.lean::stateAt_eq_foldl`, `Snapshot.lean::mem_readAt_iff`, `Snapshot.lean::pair_readAt`, `Snapshot.lean::stateAt_eq_of_not_written` | | SNP-4 | idempotence: a cut at or past the head reads the store, so the read at the head is the store and every derived view at it is the present's: the generations read the store rewritten in place, a grant's snapshot and what an asker is shown are the grant's restriction of the store, what is visible is the store without the erased events, the history of a key with no seal is its every landing, and each seal serves at the head what the key holds live (exact: finite lists; on the code, a cut at or past a chain's head reads the whole chain, and the state of a path at the head is its catalog row; the genesis is the catalog, tombstoned paths included, and ends at a horizon) | the identity read: `as of` the head is no `as of` | `core/stores/catalog.py::VaultCatalog.head`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.genesis` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_the_genesis_is_the_catalog_and_ends_at_a_horizon` | `Snapshot.lean::readAt_head`, `Snapshot.lean::readAt_of_head_le`, `Snapshot.lean::view_head`, `Snapshot.lean::genRead_gens_length`, `Snapshot.lean::snapshot_head`, `Snapshot.lean::shown_head`, `Snapshot.lean::landingsAt_length`, `Snapshot.lean::visible_head`, `Snapshot.lean::servedAt_length`, `Snapshot.lean::servedNow_length`, `Snapshot.lean::historyAt_length` | -| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, a write killed between the catalog's row and the log's leaving neither, a batch carrying its log rows, and a record that changes nothing and a store the UNCHANGED check skips appending nothing; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place, and no path has two rows alive; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/catalog.py::VaultCatalog.heads_at`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_a_transaction_killed_between_the_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | +| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, each of the six writes killed or failed between the catalog's row and the log's leaving neither, in a batch too when its caller goes on, a batch carrying its log rows, a record that changes nothing and a store the UNCHANGED check skips appending nothing, the writer and the sync carrying each landing's version, and a change of identity landing after a `move`; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place that keeps none of its content, and no path has two rows alive; a path none of whose versions keeps its content is named by no row; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/catalog.py::VaultCatalog.heads_at`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_the_sync_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version`, `tests/property/test_landing_log.py::test_each_write_killed_or_failed_between_its_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads`, `tests/property/test_landing_log.py::test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | diff --git a/tests/fixtures/landing_writes.py b/tests/fixtures/landing_writes.py new file mode 100644 index 00000000..cc3c6af8 --- /dev/null +++ b/tests/fixtures/landing_writes.py @@ -0,0 +1,32 @@ +"""The catalog's six writing methods, each as one write on the catalog `ready` leaves, with the +method of the landing log it calls after the catalog's own statement. The landing log's tests kill +the process, or fail the write, between the two (tests/property/test_landing_log.py); a killed +process imports this module, so it stays small.""" + +from __future__ import annotations + +from collections.abc import Callable + +from core.kernel.provenance import Provenance +from core.stores.authored_supersession import owner_declaration +from core.stores.catalog import VaultCatalog + + +def ready(cat: VaultCatalog) -> None: + """A catalog on which each write below changes a row of the catalog and the log with it.""" + cat.record("a.md", "d1", "A") + cat.record("b.md", "d2", "B", provenance=Provenance.CURATED) + cat.record("gone.md", "dg", "G") + cat.tombstone("gone.md") + + +# name: (the landing log's method the write calls after its catalog statement, the write) +WRITES: dict[str, tuple[str, Callable[[VaultCatalog], object]]] = { + "record": ("store", lambda cat: cat.record("a.md", "d9", "A")), + "tombstone": ("tombstone", lambda cat: cat.tombstone("a.md")), + "relabel_provenance": ("relabel", lambda cat: cat.relabel_provenance("curated", "observed")), + "migrate_rekey_doc_id": ("rekey", lambda cat: cat.migrate_rekey_doc_id( + "a.md", "id-new", declaration=owner_declaration())), + "remove": ("empty_path", lambda cat: cat.remove("gone.md")), + "remove_digest": ("empty_digest", lambda cat: cat.remove_digest("dg")), +} diff --git a/tests/property/test_landing_log.py b/tests/property/test_landing_log.py index 8d51bfff..8e85f5d0 100644 --- a/tests/property/test_landing_log.py +++ b/tests/property/test_landing_log.py @@ -1,28 +1,40 @@ """The landing log's laws on the code (dn-temporal-snapshot §3.2, §10; stage SN-1). The log is the catalog's past: the six writing methods of `VaultCatalog` append to it in the -transaction of the row each writes, and the catalog is its fold. Hypothesis draws sequences of -catalog writes over a few paths, digests, titles and classes, with retires, renames, relabels, -re-keys and both purges among them, and after every write checks that the catalog is the fold -of the log and that every chain verifies. The laws, as §10 states them for this stage: - -* SNP-1, append invariance: the read of a chain at a cut, and the state of every path at it, - taken after every later write, are the ones taken when the cut was the head, up to the holes a - later purge leaves (a purge empties rows and keeps their positions, SNP-7). +transaction of the row each writes, and the catalog is its fold. Hypothesis draws a catalog as a +build before the log left it, whose first open writes the genesis, and then sequences of catalog +writes over a few paths, digests, titles and classes, with retires, renames, relabels, re-keys +and both purges among them, and after every write checks that the catalog is the fold of the log, +that every chain verifies, that no row carries `att_head` before SN-2, that a hole keeps none of +the content a purge empties, that every name the log carries is carried by a version that keeps +its content, and that a landing that changes a path's identity is preceded by a `move`. The laws, +as §10 states them for this stage: + +* SNP-1, append invariance: the read of a chain at a cut, and each path's last event in it, taken + after every later write, are the ones taken when the cut was the head, up to the holes a later + purge leaves (a purge empties rows and keeps their positions, SNP-7); so is the state of a path + over a class while the class's chains are the ones it had. A relabel moves a chain to another + class, so a read by class at a past cut follows the chain's class now (§6.3), and across one the + test compares the path's last event chain by chain. * SNP-2, monotonicity: the read at an earlier cut is a prefix of the read at a later one. * SNP-3, composition: the catalog rebuilt from the state at a checkpoint and the delta since is the catalog. * SNP-4, idempotence: the read at the head is the chain, and the state at the head the catalog. -* SNP-5, three reads: at every position of every chain the seek by key, the closing-stamp read - and the fold of the prefix give each path the same row, before and after rows are emptied, and - no path has two rows alive. - -Then the stage's own cases: a record that changes nothing, and a store the UNCHANGED check -skips, append nothing; a transaction killed between the catalog's row and the log's leaves -neither; the genesis is the catalog, tombstoned paths included, and ends at a horizon; a relabel -into a class that has rows changes no row of the log and every chain verifies; a purge of an old -version of a live path leaves a hole that all three reads return at a cut where it was the head; -`verify` fails on an edited row; the secret is required, and another one is refused. +* SNP-5, three reads: at every position of every chain, the genesis's included, the seek by key, + the closing-stamp read and the fold of the prefix give each path the same row, before and after + rows are emptied, and no path has two rows alive. + +Then the stage's own cases: a record that changes nothing, and a store the UNCHANGED check skips, +append nothing; the writer and the sync carry the version each landing is; a change of identity +lands after a `move`, and a re-key carries the version; each of the six writes, killed or failed +between the catalog's row and the log's, leaves neither, in a batch too when its caller goes on; +the genesis is the catalog, tombstoned paths included, closes each tombstoned path's `store` and +ends at a horizon; a relabel into a class that has rows changes no row of the log, closed rows and +holes included, and every chain verifies; a history over two chains of a class follows a rule of +the prefixes; a purge of an old version of a live path leaves a hole that all three reads return at +a cut where it was the head, and a purge of every version of a deleted note leaves no row that +names it; `verify` fails on an edited row and on a hole that keeps content; the secret is required +by what appends or seeks a path by its key and by nothing else, and another one is refused. """ from __future__ import annotations @@ -51,6 +63,7 @@ from core.stores.versions import RekeyRefusedError from tests.conftest import LANDING_LOG_TEST_KEY from tests.fixtures.ingress import palace_at, write_file +from tests.fixtures.landing_writes import WRITES, ready PATHS = [f"notes/n{i}.md" for i in range(5)] DIGESTS = [f"d{i}" for i in range(6)] @@ -60,6 +73,9 @@ Row = tuple[str, str, str, bool, str] # digest, title, class, active, identity +# What a purge empties in a row, as §6.1 lists it (the code's own list is `landings._EMPTY`). +EMPTY = "source_path = NULL, doc_id = NULL, digest = NULL, title = NULL, salt = NULL, at = NULL" + # --- the fold of the log, from its rows alone --------------------------------------------------- @@ -143,27 +159,65 @@ def all_rows(cat: VaultCatalog) -> list[tuple[Any, ...]]: return [tuple(r) for r in cat._conn.execute("SELECT * FROM landings ORDER BY chain, seq")] +def chain_rows(cat: VaultCatalog) -> list[tuple[Any, ...]]: + return [tuple(r) for r in cat._conn.execute( + "SELECT chain, class, secret, key_check FROM landing_chains ORDER BY chain")] + + +def log_rows(cat: VaultCatalog) -> list[Landing]: + """Every row of every chain, chain by chain, in order.""" + return [r for ch in chains(cat) for r in cat.read_at(ch, cat.head(ch))] + + def alive(row: Landing, c: int) -> bool: return row.seq <= c and (row.closed_at is None or row.closed_at > c) +def emptied(row: Landing) -> bool: + """A hole as a purge leaves it (§6.1): no salt, and none of the path, the identity, the + digest, the title or the bookmark.""" + return row.hole and all(v is None for v in row.content().values()) + + def same_up_to_holes(now: Landing, then: Landing, c: int) -> bool: """A row read again after later writes: the same position, kind, key, commitment and hash; the - same content unless a purge has emptied it since; alive at `c` exactly when it was.""" + same content unless a purge has emptied it since, and then the same version, `att_head` and + horizon, which a purge keeps; alive at `c` exactly when it was.""" if (now.seq, now.kind, now.path_key, now.commitment, now.hash) != \ (then.seq, then.kind, then.path_key, then.commitment, then.hash): return False if alive(now, c) != alive(then, c): return False - return now.hole or now == Landing(**{**then.__dict__, "closed_at": now.closed_at}) + if emptied(now): + return (now.version, now.att_head, now.horizon) == \ + (then.version, then.att_head, then.horizon) + return now == Landing(**{**then.__dict__, "closed_at": now.closed_at}) def assert_consistent(cat: VaultCatalog) -> None: - """After every write: the catalog is the fold of the log, and every chain verifies.""" + """After every write: the catalog is the fold of the log; every chain verifies; no row + carries `att_head` (SN-2 fills it); every row without its salt is a hole as a purge leaves + it; every name the log carries is carried by a `store` that keeps its content, so a path + none of whose versions keeps its content is named by no row; and a `store` that follows a + `store` of its path in the chain, both with their content, keeps that one's identity, since + a landing that changes it appends a `move` first.""" assert fold(cat).catalog(classes(cat)) == catalog_rows(cat) for ch in chains(cat): check = cat.verify(ch) assert check.ok, check + rows = log_rows(cat) + assert all(r.att_head is None for r in rows) + assert all(emptied(r) for r in rows if r.hole) + kept = {r.source_path for r in rows if r.kind == "store" and not r.hole} + assert {r.source_path for r in rows if r.source_path is not None} <= kept + before: dict[tuple[int, bytes], Landing] = {} + for r in rows: + if r.path_key is None: + continue + prev = before.get((r.chain, r.path_key)) + if prev is not None and prev.kind == r.kind == "store" and not (prev.hole or r.hole): + assert r.doc_id == prev.doc_id, (prev, r) + before[(r.chain, r.path_key)] = r # --- the writes ----------------------------------------------------------------------------------- @@ -181,6 +235,12 @@ def assert_consistent(cat: VaultCatalog) -> None: st.tuples(st.just("remove"), st.sampled_from(PATHS)), st.tuples(st.just("rekey"), st.sampled_from(PATHS), st.sampled_from(["id-x", "id-y"])), ), min_size=3, max_size=40) +# A catalog as a build before the log left it: a row a path, active or tombstoned, with its class +# and its identity, the path or a declared one (two paths may hold one, as §2.3's item 8 shows). +legacy = st.lists(st.tuples(st.sampled_from(PATHS), st.sampled_from(DIGESTS), + st.sampled_from(TITLES), st.sampled_from(CLASSES), st.booleans(), + st.one_of(st.none(), st.sampled_from(IDS))), + max_size=5, unique_by=lambda r: r[0]) def apply(cat: VaultCatalog, op: tuple[Any, ...]) -> None: @@ -212,6 +272,22 @@ def apply(cat: VaultCatalog, op: tuple[Any, ...]) -> None: pass +def from_legacy(rows: list[tuple[str, str, str, Provenance, bool, str | None]]) -> VaultCatalog: + """A catalog holding `rows` and no log, then migrated: the genesis, as the first open of a + catalog a build before the log wrote writes it.""" + cat = VaultCatalog(Path(":memory:")) + if rows: + cat._conn.executemany( + "INSERT INTO vault_files (source_path, digest, title, provenance, active, updated_at, " + "doc_id) VALUES (?, ?, ?, ?, ?, '2026-11-01', ?)", + [(p, d, t, str(c), int(a), doc if doc is not None else p) + for p, d, t, c, a, doc in rows]) + cat._migrate() + cat._conn.commit() + assert chains(cat) + return cat + + @dataclass class Taken: """A cut taken at the head, with what was read at it then.""" @@ -233,20 +309,29 @@ def take(cat: VaultCatalog) -> Taken: def assert_unchanged(cat: VaultCatalog, taken: Taken) -> None: - """SNP-1: a cut taken earlier reads what it read then, up to the holes a purge left.""" + """SNP-1: a cut taken earlier reads what it read then, up to the holes a purge left: each + chain's rows; the state of each path over a class while the class's chains are the ones it + had; and, for a class a relabel has given other chains since, the path's last event in each + chain the class had, by its key (a read by class follows the chains' classes now, §6.3).""" for ch, c in taken.cut.items(): now = cat.read_at(ch, c) assert len(now) == len(taken.reads[ch]) assert all(same_up_to_holes(a, b, c) for a, b in zip(now, taken.reads[ch], strict=True)) for (cls, path), then in taken.states.items(): - if cat.chains(cls) != taken.class_chains[cls]: - continue # a relabel gave the class another chain since - now_state = cat.state_at(cls, path, taken.cut) - if then is None: - assert now_state is None - else: - assert now_state is not None - assert same_up_to_holes(now_state, then, taken.cut[then.chain]) + if cat.chains(cls) == taken.class_chains[cls]: + now_state = cat.state_at(cls, path, taken.cut) + if then is None: + assert now_state is None + else: + assert now_state is not None + assert same_up_to_holes(now_state, then, taken.cut[then.chain]) + continue + for ch in taken.class_chains[cls]: # a relabel gave the class other chains since + key = cat._log.path_key(ch, path) + last = next((r for r in reversed(taken.reads[ch]) if r.path_key == key), None) + seek = cat._log._seek(ch, path, taken.cut[ch]) + assert (seek is None) == (last is None) + assert seek is None or last is None or same_up_to_holes(seek, last, taken.cut[ch]) def assert_three_reads(cat: VaultCatalog) -> None: @@ -282,20 +367,27 @@ def assert_three_reads(cat: VaultCatalog) -> None: @settings(max_examples=200, deadline=None, suppress_health_check=[HealthCheck.too_slow]) -@given(ops) +@given(legacy, ops) def test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold( + before: list[tuple[str, str, str, Provenance, bool, str | None]], writes: list[tuple[Any, ...]]) -> None: - """SNP-1 to SNP-5 over random catalog writes, retires, renames, relabels, re-keys and purges - among them: the catalog is the fold of the log after every write and every chain verifies; - every cut taken reads after every later write what it read then (SNP-1); at the end the - reads are prefixes of each other (SNP-2), the catalog is the state at any checkpoint - continued over the delta (SNP-3), the read at the head is the chain and the state at the - head the catalog (SNP-4), and the three reads agree at every position (SNP-5).""" - cat = VaultCatalog(Path(":memory:")) - taken: list[Taken] = [] + """SNP-1 to SNP-5 from a random catalog's genesis over random catalog writes, retires, + renames, relabels, re-keys and purges among them: the catalog is the fold of the log after + every write and every chain verifies; a `remove` leaves no row naming its path and a purge + no row carrying its digest; every cut taken reads after every later write what it read then + (SNP-1); at the end the reads are prefixes of each other (SNP-2), the catalog is the state at + any checkpoint continued over the delta (SNP-3), the read at the head is the chain and the + state at the head the catalog (SNP-4), and the three reads agree at every position (SNP-5).""" + cat = from_legacy(before) + assert_consistent(cat) + taken: list[Taken] = [take(cat)] for op in writes: apply(cat, op) assert_consistent(cat) + if op[0] == "remove": + assert all(r.source_path != op[1] for r in log_rows(cat)) + if op[0] == "purge" and cat.active_refs(op[1]) == 0: + assert all(r.digest != op[1] for r in log_rows(cat)) taken.append(take(cat)) for t in taken: assert_unchanged(cat, t) @@ -381,49 +473,126 @@ def test_a_store_the_unchanged_check_skips_appends_nothing(tmp_path: Path) -> No assert_consistent(cat) +def test_the_sync_carries_the_version_each_landing_is(tmp_path: Path) -> None: + """`VaultSync.sync_path`, the other lane that keeps version chains: a landing, an edit and a + revert append versions 1 to 3, and a rename appends version 4 at the same bytes; the log's + `store` of each carries that number, and the rename's tombstone is a `move`.""" + from typing import cast + + from core.ingest.embed import Embedder + from core.ingest.sync import VaultSync + from core.kernel.stores.rawstore import RawStore + from core.stores.vectorstore import VectorStore + from core.stores.versions import VersionStore + from tests.fixtures.embedding import DIM, FakeEmbedder + + vault = tmp_path / "vault" + vault.mkdir() + versions = VersionStore(tmp_path / "versions.sqlite") + cat = VaultCatalog(tmp_path / "catalog.sqlite") + sync = VaultSync(vault=vault, raw=RawStore(tmp_path / "raw"), + store=VectorStore(tmp_path / "v.lance", dim=DIM), catalog=cat, + embedder=cast(Embedder, FakeEmbedder()), version_store=versions) + note = vault / "n.md" + for text in ("alpha content", "beta content", "alpha content"): + note.write_text(text, encoding="utf-8") + sync.rescan() + note.rename(vault / "m.md") + sync.rescan() + (entry,) = cat.active_entries() + doc = cat.doc_id_for(entry.source_path) + assert [v.version_seq for v in versions.history(doc)] == [1, 2, 3, 4] + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + rows = cat.read_at(chain, cat.head(chain)) + assert [(Path(str(r.source_path)).name, r.version) for r in rows if r.kind == "store"] == \ + [("n.md", 1), ("n.md", 2), ("n.md", 3), ("m.md", 4)] + assert [(r.kind, Path(str(r.source_path)).name) for r in rows][-2:] == \ + [("store", "m.md"), ("move", "n.md")] + assert_consistent(cat) + cat.close() + + +def test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version() -> None: + """A `record` that gives an active path another identity writes a `move` of the one it held + before the `store`; the owner's re-key writes a `move` and then the path's `store` under the + new identity with the version it had, or its `retire` when the path is tombstoned.""" + cat = VaultCatalog(Path(":memory:")) + cat.record("a.md", "d1", "A", version=3) + cat.record("a.md", "d1", "A", doc_id="id-b", version=3) + cat.migrate_rekey_doc_id("a.md", "id-c", declaration=owner_declaration()) + cat.tombstone("a.md") + cat.migrate_rekey_doc_id("a.md", "id-d", declaration=owner_declaration()) + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + rows = cat.read_at(chain, cat.head(chain))[2:] # after the genesis and the horizon + assert [(r.kind, r.doc_id, r.version, r.digest) for r in rows] == [ + ("store", "a.md", 3, "d1"), ("move", "a.md", None, None), ("store", "id-b", 3, "d1"), + ("move", "id-b", None, None), ("store", "id-c", 3, "d1"), + ("retire", "id-c", None, None), ("move", "id-c", None, None), + ("retire", "id-d", None, None)] + assert catalog_rows(cat)["a.md"] == ("d1", "A", "authored-solo", False, "id-d") + assert_consistent(cat) + assert_three_reads(cat) + + _KILL = """ import os, sys from pathlib import Path from core.stores import landings from core.stores.catalog import VaultCatalog +from tests.fixtures.landing_writes import WRITES +method, write = WRITES[sys.argv[2]] cat = VaultCatalog(Path(sys.argv[1])) -real = landings.LandingLog._append - -def die(self, chain, kind, **kw): - if kind == "store": - os._exit(9) # killed: no handler, no rollback - return real(self, chain, kind, **kw) - -landings.LandingLog._append = die -cat.record("killed.md", "dk", "K") +setattr(landings.LandingLog, method, lambda *args, **kwargs: os._exit(9)) # no handler, no rollback +write(cat) """ -def test_a_transaction_killed_between_the_two_rows_leaves_neither( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +@pytest.mark.parametrize("name", sorted(WRITES)) +def test_each_write_killed_or_failed_between_its_two_rows_leaves_neither( + name: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Each of the six writing methods, its process killed after the catalog's statement and + before the log's, and then the same write failing there in process: the catalog's rows and the + log's are what they were, both times. Inside a batch, a failed write whose caller catches the + error and goes on leaves neither row either, and the batch commits the rest.""" + method, write = WRITES[name] db = tmp_path / "catalog.sqlite" cat = VaultCatalog(db) - cat.record("kept.md", "d0", "K") - head = heads(cat) + ready(cat) + catalog, log, log_chains = catalog_rows(cat), all_rows(cat), chain_rows(cat) cat.close() + + def unchanged(cat: VaultCatalog) -> None: + assert (catalog_rows(cat), all_rows(cat), chain_rows(cat)) == (catalog, log, log_chains) + assert_consistent(cat) + env = {**os.environ, LANDING_LOG_KEY: LANDING_LOG_TEST_KEY} - done = subprocess.run([sys.executable, "-c", _KILL, str(db)], env=env, + done = subprocess.run([sys.executable, "-c", _KILL, str(db), name], env=env, cwd=Path(__file__).resolve().parents[2], check=False) assert done.returncode == 9 cat = VaultCatalog(db) - assert cat.get("killed.md") is None - assert heads(cat) == head - assert_consistent(cat) - # and in process: the write that raises after the catalog's row rolls the row back + unchanged(cat) + def boom(*args: Any, **kwargs: Any) -> None: raise RuntimeError("between the two rows") - monkeypatch.setattr(cat._log, "store", boom) + monkeypatch.setattr(cat._log, method, boom) with pytest.raises(RuntimeError): - cat.record("raised.md", "dr", "R") - assert cat.get("raised.md") is None - assert heads(cat) == head + write(cat) + unchanged(cat) + with cat.deferred(): + with pytest.raises(RuntimeError): + write(cat) # failed, and the caller goes on + monkeypatch.undo() + cat.record("c.md", "dc", "C") + assert {k: v for k, v in catalog_rows(cat).items() if k != "c.md"} == catalog + assert catalog_rows(cat)["c.md"][:2] == ("dc", "C") + now = {(r[0], r[1]): r for r in all_rows(cat)} + then = {(r[0], r[1]): r for r in log} + assert {k: now[k] for k in then} == then + assert [now[k][4] for k in sorted(now.keys() - then.keys())] == ["c.md"] # c.md's store + assert chain_rows(cat) == log_chains + assert_consistent(cat) cat.close() @@ -476,34 +645,85 @@ def test_the_genesis_is_the_catalog_and_ends_at_a_horizon(tmp_path: Path) -> Non assert {r.kind for r in rows[1:-1]} <= {"store", "retire", "move"} assert cat.verify(ch).ok (solo,) = cat.chains(Provenance.AUTHORED_SOLO) - kinds = [(r.kind, r.source_path) for r in cat.read_at(solo, cat.head(solo))[1:-1]] + block = cat.read_at(solo, cat.head(solo))[1:-1] + kinds = [(r.kind, r.source_path) for r in block] assert kinds == [("store", "v/a.md"), ("store", "v/b.md"), ("retire", "v/b.md"), ("store", "v/c.md"), ("move", "v/c.md"), ("store", "v/d.md")] + # a tombstoned path's store is closed at its tombstone, and an active path's is open, so the + # closing-stamp read at the head serves the active paths alone + assert [r.closed_at for r in block] == [None, block[2].seq, None, block[4].seq, None, None] + assert [r.source_path for r in cat.heads_at(Provenance.AUTHORED_SOLO, heads(cat))] == \ + ["v/a.md", "v/d.md"] + assert [r.source_path for r in cat.heads_at(Provenance.CURATED, heads(cat))] == [] + state = cat.state_at(Provenance.AUTHORED_SOLO, "v/b.md", heads(cat)) + assert state is not None and state.kind == "retire" + assert_consistent(cat) + assert_three_reads(cat) head = heads(cat) cat.close() assert heads(VaultCatalog(db)) == head # one genesis: a reopen adds nothing def test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies() -> None: + """The relabel rewrites the label of the class's chains and nothing else: no row of the log, + a closed row and a hole among them, and no chain's id, secret or key check.""" cat = VaultCatalog(Path(":memory:")) cat.record("a.md", "d1", "A", provenance=Provenance.AUTHORED_SOLO) cat.record("b.md", "d2", "B", provenance=Provenance.CURATED) + cat.record("b.md", "d5", "B", provenance=Provenance.CURATED) # b's first store closed cat.record("c.md", "d3", "C", provenance=Provenance.CURATED) - rows = all_rows(cat) + cat.record("c.md", "d6", "C", provenance=Provenance.CURATED) + assert cat.remove_digest("d3") == 0 # c's first store a hole + rows, before = all_rows(cat), chain_rows(cat) + log = log_rows(cat) + assert any(r.closed_at is not None and not r.hole for r in log) + assert any(r.hole for r in log) assert cat.relabel_provenance("curated", "authored-solo") == 2 assert all_rows(cat) == rows + assert [(c, s, k) for c, _, s, k in chain_rows(cat)] == [(c, s, k) for c, _, s, k in before] assert len(cat.chains(Provenance.AUTHORED_SOLO)) == 2 and cat.chains("curated") == [] assert_consistent(cat) cat.record("b.md", "d4", "B", provenance=Provenance.AUTHORED_SOLO) # stays in its chain state = cat.state_at(Provenance.AUTHORED_SOLO, "b.md", heads(cat)) assert state is not None and state.chain == 2 and state.digest == "d4" assert_consistent(cat) + assert_three_reads(cat) + + +def test_a_history_over_two_chains_of_a_class_follows_a_rule_of_the_prefixes() -> None: + """A path has events in two chains of one class only after it changed class and a relabel + merged the two classes. Its history over the class is oldest first in each chain, with the + chains it left first and the one that holds its present last: a rule of the prefixes, not the + order the versions landed in (d1, d2, d3 here), so across the chains the read at an earlier + cut is not a prefix of the read at a later one. Chain by chain it is, and the state at the + head is the path's present.""" + solo = Provenance.AUTHORED_SOLO + cat = VaultCatalog(Path(":memory:")) + cat.record("p.md", "d1", "t", provenance=solo) # chain 1 + cat.record("p.md", "d2", "t", provenance=Provenance.CURATED) # leaves 1 for chain 2 + early = heads(cat) + cat.record("p.md", "d3", "t", provenance=solo) # leaves 2, back in 1 + cat.relabel_provenance("curated", "authored-solo") + assert cat.chains(solo) == [1, 2] + then = cat.history_at(solo, "p.md", early) + now = cat.history_at(solo, "p.md", heads(cat)) + assert [r.digest for r in then] == ["d1", "d2"] + assert [r.digest for r in now] == ["d2", "d1", "d3"] + assert now[:len(then)] != then + for ch in (1, 2): + mine = [r for r in now if r.chain == ch] + assert [r.seq for r in mine] == sorted(r.seq for r in mine) + assert mine[:len([r for r in then if r.chain == ch])] == [r for r in then if r.chain == ch] + state = cat.state_at(solo, "p.md", heads(cat)) + assert state is not None and (state.chain, state.digest) == (1, "d3") + assert_consistent(cat) + assert_three_reads(cat) def test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads() -> None: cat = VaultCatalog(Path(":memory:")) for d in ("d1", "d2", "d3"): - cat.record("live.md", d, "L") + cat.record("live.md", d, "L", version=int(d[1])) (chain,) = cat.chains(Provenance.AUTHORED_SOLO) at_d2 = next(r.seq for r in cat.read_at(chain, cat.head(chain)) if r.digest == "d2") assert cat.active_refs("d2") == 0 # purge_raw's gate lets it through @@ -511,6 +731,7 @@ def test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads() -> N cut = {chain: at_d2} state = cat.state_at(Provenance.AUTHORED_SOLO, "live.md", cut) assert state is not None and state.hole and state.seq == at_d2 and state.kind == "store" + assert emptied(state) and state.version == 2 # §6.1: the content goes, the count stays assert state.path_key == cat._log.path_key(chain, "live.md") (head_row,) = cat.heads_at(Provenance.AUTHORED_SOLO, cut) assert head_row.hole and head_row.seq == at_d2 and head_row.source_path is None @@ -518,8 +739,47 @@ def test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads() -> N assert [r.digest for r in history] == ["d1", None] and history[-1].hole assert fold(cat, cut).last[(chain, state.path_key)] == state assert catalog_rows(cat)["live.md"][0] == "d3" + # the live path keeps its name on its other rows, so the hole stays tied to it + assert [r.seq for r in log_rows(cat) if r.hole] == [at_d2] + assert_consistent(cat) + assert_three_reads(cat) + + +def test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it( + tmp_path: Path) -> None: + """`purge_raw`'s case: a note that declared its identity and changed class, deleted from the + vault, then each of its digests purged by `remove_digest`. While one of its versions keeps its + content the path's other rows keep its name; once none does, its `leave` and its `retire` are + emptied too, so no row names the path or the identity, or carries the date of its delete; the + holes keep their keys and positions. After a vacuum no byte of the file holds either name.""" + db = tmp_path / "catalog.sqlite" + cat = VaultCatalog(db) + cat.record("keep.md", "dk", "K") + note = "notes/private-topic.md" + cat.record(note, "dp1", "Private", doc_id="id-private") + cat.record(note, "dp2", "Private", provenance=Provenance.CURATED) # a `leave` in chain 1 + cat.tombstone(note) + assert cat.active_refs("dp1") == cat.active_refs("dp2") == 0 + cat.remove_digest("dp2") + assert {r.kind for r in log_rows(cat) if r.source_path == note} == {"store", "leave", "retire"} + assert_consistent(cat) + cat.remove_digest("dp1") + rows = log_rows(cat) + assert all(note not in (r.source_path, r.doc_id) and r.doc_id != "id-private" for r in rows) + holes = [r for r in rows if r.hole] + assert sorted(r.kind for r in holes) == ["leave", "retire", "store", "store"] + assert all(emptied(r) and r.path_key is not None for r in holes) + assert cat.get(note) is None and cat.get("keep.md") is not None assert_consistent(cat) assert_three_reads(cat) + cat.close() + with sqlite3.connect(db) as conn: + conn.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchall() + conn.execute("VACUUM") + conn.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchall() + data = b"".join(f.read_bytes() for f in tmp_path.glob("catalog.sqlite*")) + assert b"keep.md" in data + assert b"private-topic" not in data and b"id-private" not in data def test_verify_fails_on_an_edited_row() -> None: @@ -534,6 +794,13 @@ def test_verify_fails_on_an_edited_row() -> None: ("UPDATE landings SET commitment = zeroblob(32) WHERE chain = ? AND seq = 5", 5, "the commitment"), ("UPDATE landings SET hash = zeroblob(32) WHERE chain = ? AND seq = 2", 2, "the hash"), + # a salt nulled with the content kept, or the content then rewritten: a row that no + # purge leaves, so it is not taken for a hole + ("UPDATE landings SET salt = NULL WHERE chain = ? AND seq = 4", 4, "a hole keeps content"), + ("UPDATE landings SET salt = NULL, digest = 'forged', title = 'forged' " + "WHERE chain = ? AND seq = 3", 3, "a hole keeps content"), + (f"UPDATE landings SET {EMPTY}, at = '2000-01-01T00:00:00' WHERE chain = ? AND seq = 5", + 5, "a hole keeps content"), ] for edit, seq, why in edits: cat._conn.execute("SAVEPOINT edit") @@ -543,16 +810,20 @@ def test_verify_fails_on_an_edited_row() -> None: cat._conn.execute("ROLLBACK TO edit") cat._conn.execute("RELEASE edit") assert cat.verify(chain).ok - cat._conn.execute("UPDATE landings SET salt = NULL WHERE chain = ? AND seq = 4", [chain]) - assert cat.verify(chain).ok # an emptied row: the hash still holds + cat._conn.execute(f"UPDATE landings SET {EMPTY} WHERE chain = ? AND seq = 4", [chain]) + assert cat.verify(chain).ok # a hole as a purge leaves it verifies cat._conn.execute("DELETE FROM landings WHERE chain = ? AND seq = 3", [chain]) check = cat.verify(chain) assert not check.ok and check.failed_at == 3 -def test_without_the_secret_the_genesis_and_every_write_refuse(tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - ) -> None: +def test_without_the_secret_what_appends_or_seeks_a_path_by_its_key_refuses( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The secret keys a path: the genesis, every write that appends a row (a `record` or a + `tombstone` that changes the map, the re-key), `remove`, which seeks the path's rows by their + key, and the two reads by path refuse without it and write nothing. A relabel and a purge by + digest append no row and find their rows without the key, a write that changes nothing + appends nothing, and the other reads read the rows as they are: none of these needs it.""" db = tmp_path / "catalog.sqlite" _legacy_catalog(db, [("a.md", "d1", "A", "authored-solo", 1, "a.md")]) monkeypatch.delenv(LANDING_LOG_KEY) @@ -565,17 +836,39 @@ def test_without_the_secret_the_genesis_and_every_write_refuse(tmp_path: Path, VaultCatalog(db) monkeypatch.setenv(LANDING_LOG_KEY, LANDING_LOG_TEST_KEY) cat = VaultCatalog(db) - head = heads(cat) + cat.record("old.md", "d0", "O") + cat.tombstone("old.md") + cat.record("c.md", "d3", "C", provenance=Provenance.CURATED) + head, log, catalog = heads(cat), all_rows(cat), catalog_rows(cat) cat.close() monkeypatch.delenv(LANDING_LOG_KEY) - cat = VaultCatalog(db) # a read needs no key - assert cat.read_at(1, 2) == cat.read_at(1, cat.head(1))[:2] - for write in (lambda: cat.record("b.md", "d2", "B"), lambda: cat.tombstone("a.md"), - lambda: cat.remove("a.md")): + cat = VaultCatalog(db) # an open after the genesis needs none + (solo,) = cat.chains(Provenance.AUTHORED_SOLO) + refused = [ + lambda: cat.record("b.md", "d2", "B"), + lambda: cat.record("a.md", "d9", "A"), + lambda: cat.tombstone("a.md"), + lambda: cat.migrate_rekey_doc_id("a.md", "id-new", declaration=owner_declaration()), + lambda: cat.remove("a.md"), + lambda: cat.state_at(Provenance.AUTHORED_SOLO, "a.md", head), + lambda: cat.history_at(Provenance.AUTHORED_SOLO, "a.md", head), + ] + for call in refused: with pytest.raises(LandingLogKeyMissing): - write() - kept = cat.get("a.md") - assert heads(cat) == head and cat.get("b.md") is None and kept is not None and kept.active + call() + assert (heads(cat), all_rows(cat), catalog_rows(cat)) == (head, log, catalog) + cat.record("a.md", "d1", "A") # changes nothing: appends nothing + cat.tombstone("nowhere.md") + assert cat.relabel_provenance("curated", "observed") == 1 + assert cat.remove_digest("d0") == 1 # old.md: its store and its retire + assert heads(cat) == head and cat.get("old.md") is None + assert all(r.source_path != "old.md" for r in log_rows(cat)) + assert cat.read_at(solo, 2) == cat.read_at(solo, cat.head(solo))[:2] + assert cat.read_between(solo, 1, 3) == cat.read_at(solo, 3)[1:] + assert [r.source_path for r in cat.heads_at(Provenance.AUTHORED_SOLO, head)] == ["a.md"] + assert cat.chains(Provenance.OBSERVED) and all(cat.verify(c).ok for c in chains(cat)) + assert_consistent(cat) + cat.close() def test_another_secret_is_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -595,11 +888,14 @@ def test_another_secret_is_refused(tmp_path: Path, monkeypatch: pytest.MonkeyPat def test_every_statement_by_path_seeks_the_key_index() -> None: """A write or a read of one path touches that path's rows through `landings_path`, never by walking the chain: on the corpus's 400,274 rows the planner took the primary key for the - closing stamp's update, and a landing took 40 ms where it takes tens of microseconds.""" + closing stamp's update, and a landing took 40 ms where it takes tens of microseconds. A + purge by digest walks the log for the digest and the names, which have no index, and then + reaches each path's rows by their key.""" cat = VaultCatalog(Path(":memory:")) for i in range(50): cat.record(f"p{i}.md", f"d{i}", "t") (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + cat.tombstone("p5.md") seen: list[str] = [] cat._conn.set_trace_callback(seen.append) cat.record("p1.md", "new", "t") @@ -608,9 +904,11 @@ def test_every_statement_by_path_seeks_the_key_index() -> None: cat.state_at(Provenance.AUTHORED_SOLO, "p1.md", {chain: 30}) cat.history_at(Provenance.AUTHORED_SOLO, "p1.md", {chain: cat.head(chain)}) cat.remove("p3.md") + cat.remove_digest("d5") # p5's only version: its retire as well cat._conn.set_trace_callback(None) by_path = [q for q in seen if "path_key = " in q] - assert len(by_path) >= 6 + assert len(by_path) >= 8 for q in by_path: plan = " ".join(str(tuple(r)[-1]) for r in cat._conn.execute("EXPLAIN QUERY PLAN " + q)) assert "landings_path" in plan, (q, plan) + assert all(r.source_path != "p5.md" for r in log_rows(cat)) From 9d847edc74ca2fc5c56ffe54b35e1a80904c024c Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 22:55:46 -0500 Subject: [PATCH 16/30] feat(eval): the landing log bench's control is the write before SN-1 The bench's control patched out LandingLog.store and so kept the read of the path's row before each write and the explicit transaction that SN-1 added to record: what it measured was what the log's rows add, not what SN-1 adds to a key's write. A key's write is now timed three ways on the same file, the order turned each round: record as built; the same with the log's appending switched off, named for what it keeps; and the write as record made it before SN-1 (f969904e), the upsert alone. The first against the third is SN-1's cost, the first against the second the log rows'. With --fresh, it also lands new one-class catalogs of the given sizes, paths and titles of the corpus's lengths, and times every head at the head against the same walk counted in SQL, so the cost a head returned is read apart from the walk on chains under section 4.2's threshold. Co-Authored-By: Claude Opus 5.5 --- eval/landing_log_bench.py | 126 +++++++++++++++++++++++++++++--------- 1 file changed, 98 insertions(+), 28 deletions(-) diff --git a/eval/landing_log_bench.py b/eval/landing_log_bench.py index c04ae6df..fa6036ed 100644 --- a/eval/landing_log_bench.py +++ b/eval/landing_log_bench.py @@ -1,14 +1,14 @@ """The landing log, measured (dn-temporal-snapshot §11; stage SN-1). uv run python -m eval.landing_log_bench --catalog COPY [--batch 10000] [--rounds 5] - [--repeat 200] [--out PATH] + [--repeat 200] [--fresh 30000,100000] [--out PATH] COPY is a copy of an instance's catalog file, never a live one: a copy-on-write clone of the file with its `-wal` and `-shm` beside it (`cp -c`), which the harness migrates in place. It refuses the catalog the configuration names. The landing log's secret is a random one made for the run and dropped with it, so nothing written here can be read by path afterwards, and nothing needs to be. -Four measurements, each on the copy's own size: +Five measurements, the first four on the copy's own size: 1. **The migration.** The first open of the catalog with the log: the tables, their indexes and the genesis of every class the catalog holds, timed whole; the file's bytes before and after @@ -17,17 +17,25 @@ 2. **Its check.** Each chain verified from its first row, every commitment recomputed and every hash, timed; and the fold of the log compared with the catalog row by row. 3. **The write overhead.** Batches of catalog writes in one transaction each, as a landing batch - writes its keys (`deferred()`): new paths, and new versions of paths the catalog holds, timed - with the log and with the log's appending switched off on the same file, alternated over - `--rounds`, so the difference is what the log adds to a key's write. + writes its keys (`deferred()`): new paths, and new versions of paths the catalog holds, each + timed three ways on the same file, the order turned over `--rounds`: `record` as built; the + same with the log's appending switched off (a patch of `LandingLog.store`), which keeps the + read of the path's row before the write, the explicit transaction and each write's savepoint + that SN-1 added; and the write as `record` made it before SN-1 (`f969904e`), the upsert + alone. The first against the third is what SN-1 adds to a key's write, and the first against + the second what the log's rows add. 4. **The reads.** `state_at` and `history_at` of one path, the paths drawn from the catalog; `heads_at` at a tenth of the chain, at its middle and at its head, and the same predicate counted in SQL, the walk without the rows built; `read_at` and `read_between` of a thousand positions; `head`; and the keyed hash of a path alone. Medians with their ranges over `--repeat` (a whole-class read over five). +5. **Every head of a smaller chain.** With `--fresh`, for each size a new catalog beside the copy + with that many paths of one class, landed through `record` in batches, its paths and titles of + the corpus's lengths: `heads_at` at its head and the walk counted in SQL, five times each, so + the cost a head returned can be read apart from the walk. The file is removed after. Timings are wall time on whatever else the machine is doing, so the load average is recorded at -the start and the end, with the versions of Python and SQLite. +the start and the end, and before each fresh chain, with the versions of Python and SQLite. """ from __future__ import annotations @@ -51,7 +59,17 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # repo root on path from core.kernel.provenance import Provenance # noqa: E402 -from core.stores.catalog import VaultCatalog # noqa: E402 +from core.stores.catalog import VaultCatalog, _utcnow # noqa: E402 + +# The key's write as `record` made it before SN-1 (`core/stores/catalog.py` at `f969904e`): this +# upsert alone, in the batch's transaction, with no read of the row before it and no log. +_UPSERT_BEFORE = ( + "INSERT INTO vault_files (source_path, digest, title, provenance, active, updated_at, doc_id)" + " VALUES (?, ?, ?, ?, 1, ?, ?)" + " ON CONFLICT(source_path) DO UPDATE SET" + " digest=excluded.digest, title=excluded.title," + " provenance=excluded.provenance, active=1, updated_at=excluded.updated_at") +ARMS = ("with", "without", "before") # record as built; its log rows off; the write before SN-1 def _files(db: Path) -> dict[str, int]: @@ -128,10 +146,23 @@ def _catalog(cat: VaultCatalog) -> dict[str, tuple[str, str, str, bool, str]]: def _batch(cat: VaultCatalog, records: list[tuple[str, str, str, Provenance]], - log: bool) -> float: - """One batch of records in one transaction, as a landing batch writes its keys; with the - log's appending switched off when `log` is false. Seconds.""" - switch = (contextlib.nullcontext() if log # the control: no log row appended + arm: str) -> float: + """One batch of records in one transaction, as a landing batch writes its keys, by one arm: + `with`, `record` as built; `without`, the same with the log's appending switched off (the + read of the row before, the explicit transaction and the savepoints kept); `before`, the + upsert `record` ran before SN-1, alone. Seconds.""" + if arm == "before": + conn = cat._conn + t0 = time.perf_counter() + try: + for path, digest, title, cls in records: + conn.execute(_UPSERT_BEFORE, [path, digest, title, str(cls), _utcnow(), path]) + conn.commit() + except BaseException: + conn.rollback() + raise + return time.perf_counter() - t0 + switch = (contextlib.nullcontext() if arm == "with" # the control: no log row appended else mock.patch.object(cat._log, "store", lambda *a, **k: None)) with switch: t0 = time.perf_counter() @@ -141,7 +172,42 @@ def _batch(cat: VaultCatalog, records: list[tuple[str, str, str, Provenance]], return time.perf_counter() - t0 -def measure(db: Path, batch: int, rounds: int, repeat: int, seed: int) -> dict[str, Any]: +def _fresh_heads(where: Path, n: int, key: bytes, batch: int) -> dict[str, Any]: + """A new catalog of `n` paths of one class, landed through `record` in batches, its paths and + titles about the corpus's lengths (28.6 and 63.8 characters): every head at its head, and the + walk counted in SQL, five times each. The file is removed after.""" + db = where / f"fresh-{n}.sqlite" + for suffix in ("", "-wal", "-shm"): + Path(f"{db}{suffix}").unlink(missing_ok=True) + out: dict[str, Any] = {"paths": n, "load_start": os.getloadavg()} + cat = VaultCatalog(db, key=key) + try: + for start in range(0, n, batch): + with cat.deferred(): + for i in range(start, min(n, start + batch)): + cat.record(f"corpus/item-{i:08}-{'p' * 6}.md", f"{i:064x}", + f"{'t' * 56} {i:07}", provenance=Provenance.OBSERVED) + (chain,) = cat.chains(Provenance.OBSERVED) + head = cat.head(chain) + cut = {chain: head} + out["chain_rows"] = head + out["heads_at"] = {**_timed(functools.partial(cat.heads_at, Provenance.OBSERVED, cut), 5), + "rows": len(cat.heads_at(Provenance.OBSERVED, cut))} + out["heads_walk"] = _timed(functools.partial( + _count, cat._conn, "SELECT count(*) FROM landings WHERE chain = ? AND seq <= ? AND " + "kind = 'store' AND (closed_at IS NULL OR closed_at > ?)", [chain, head, head]), 5) + past = out["heads_at"]["median_us"] - out["heads_walk"]["median_us"] + out["us_a_head_past_the_walk"] = past / out["heads_at"]["rows"] + finally: + cat.close() + for suffix in ("", "-wal", "-shm"): + Path(f"{db}{suffix}").unlink(missing_ok=True) + out["load_end"] = os.getloadavg() + return out + + +def measure(db: Path, batch: int, rounds: int, repeat: int, seed: int, + fresh: tuple[int, ...] = ()) -> dict[str, Any]: from core.kernel.config import get_config if db.resolve() == Path(get_config().paths.vault_catalog).resolve(): @@ -225,33 +291,34 @@ def measure(db: Path, batch: int, rounds: int, repeat: int, seed: int) -> dict[s functools.partial(_count, cat._conn, walk, [big, c, c]), 5) out["reads"] = reads - # the write overhead: new paths, then new versions of held paths, with and without the log - writes: dict[str, Any] = {"new": {"with": [], "without": []}, - "changed": {"with": [], "without": []}} - held = rng.sample(paths, min(batch * rounds * 2, len(paths))) + # the write overhead: new paths, then new versions of held paths, by each arm in turn + writes: dict[str, Any] = {kind: {arm: [] for arm in ARMS} for kind in ("new", "changed")} + held = rng.sample(paths, min(batch * rounds * len(ARMS), len(paths))) n = 0 for r in range(rounds): - for log in ((True, False) if r % 2 == 0 else (False, True)): - fresh = [(f"bench/r{r}/{'w' if log else 'o'}/{i:06}.md", f"bench-{r}-{log}-{i}", - f"bench {i}", Provenance(cls)) for i in range(batch)] - secs = _batch(cat, fresh, log) - writes["new"]["with" if log else "without"].append(secs / batch * 1e6) - changed = [(p, f"changed-{r}-{log}-{i}", f"changed {i}", Provenance(cls)) + for arm in ARMS[r % len(ARMS):] + ARMS[:r % len(ARMS)]: + new = [(f"bench/r{r}/{arm}/{i:06}.md", f"bench-{r}-{arm}-{i}", f"bench {i}", + Provenance(cls)) for i in range(batch)] + secs = _batch(cat, new, arm) + writes["new"][arm].append(secs / batch * 1e6) + changed = [(p, f"changed-{r}-{arm}-{i}", f"changed {i}", Provenance(cls)) for i, p in enumerate(held[n:n + batch])] n += batch - secs = _batch(cat, changed, log) - writes["changed"]["with" if log else "without"].append(secs / len(changed) * 1e6) + secs = _batch(cat, changed, arm) + writes["changed"][arm].append(secs / len(changed) * 1e6) for kind in ("new", "changed"): w = writes[kind] - w["with_median_us"] = statistics.median(w["with"]) - w["without_median_us"] = statistics.median(w["without"]) - w["overhead_us"] = w["with_median_us"] - w["without_median_us"] + for arm in ARMS: + w[f"{arm}_median_us"] = statistics.median(w[arm]) + w["sn1_adds_us"] = w["with_median_us"] - w["before_median_us"] + w["log_rows_add_us"] = w["with_median_us"] - w["without_median_us"] out["writes_us_a_record"] = writes out["verify_after_writes"] = all(cat.verify(c).ok for c in cat._log.all_chains()) _checkpoint(cat._conn) out["files_end"] = _files(db) out["load_end"] = os.getloadavg() cat.close() + out["fresh_chains"] = [_fresh_heads(db.parent, n, key, batch) for n in fresh] return out @@ -263,9 +330,12 @@ def main(argv: list[str] | None = None) -> int: ap.add_argument("--rounds", type=int, default=5) ap.add_argument("--repeat", type=int, default=200) ap.add_argument("--seed", type=int, default=11) + ap.add_argument("--fresh", default="", + help="sizes of fresh one-class chains to read every head of, comma separated") ap.add_argument("--out", type=Path) args = ap.parse_args(argv) - out = measure(args.catalog, args.batch, args.rounds, args.repeat, args.seed) + fresh = tuple(int(n) for n in args.fresh.split(",") if n.strip()) + out = measure(args.catalog, args.batch, args.rounds, args.repeat, args.seed, fresh) text = json.dumps(out, indent=2, default=str) if args.out: args.out.write_text(text + "\n", encoding="utf-8") From 03b20b2bb266d2ccf45da087f6279038618e4b18 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:00:16 -0500 Subject: [PATCH 17/30] perf(stores): a batch's savepoints keep their journal in memory The savepoint each write in a deferred() batch now takes keeps its journal in a temporary file unless the connection says otherwise, and on a copy of the corpus instance's catalog that doubled the cost of a key's write in a batch (a new path 105 us with the log against 49 before the savepoint). The catalog's connection now keeps its temporary store in memory: on a catalog of 100,000 rows the savepoint costs 6 us a write there, against 38 to 50 us in a file (two runs, batches of 10,000, load 3.9 to 4.2). No query of the catalog sorts or groups more than a few rows in the temporary store, by their plans, so nothing else of size is held there. Co-Authored-By: Claude Opus 5.5 --- core/stores/catalog.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/stores/catalog.py b/core/stores/catalog.py index 784da3cc..d9b4a4f9 100644 --- a/core/stores/catalog.py +++ b/core/stores/catalog.py @@ -97,6 +97,11 @@ def __post_init__(self) -> None: self._defer = False self._conn = sqlite3.connect(str(self.path)) self._conn.row_factory = sqlite3.Row + # Each write in a batch is a savepoint (`_writing`), and SQLite keeps a savepoint's + # journal in a temporary file unless told otherwise: 46 to 50 µs a write, against 6 in + # memory, on a catalog of 100,000 rows. No query of the catalog's sorts or groups more + # than a few rows in the temporary store, so nothing else of size is held there. + self._conn.execute("PRAGMA temp_store = MEMORY") self._log = LandingLog(self._conn, self._landing_key) try: # Until the log's genesis is written another process may be writing it, six seconds From daf24e260a72711ed56fa4d1bfd6638b074cd966 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:07:08 -0500 Subject: [PATCH 18/30] docs(experiments): the landing log's record from runs against the write before it The record first gave the log's cost as the write with the log against the write with its rows switched off, which left out the read of the row before the write and the transaction SN-1 added around them, and it said nothing else in a landing changed, which leaves out the vault's one more read of its version chain. Two new runs of the harness, on fresh copy-on-write clones of the corpus instance's catalog at the code after review, time the write three ways: SN-1 adds 51 to 53 us to a new path's write and 84 to 86 us to a new version's against the write before it (4.6 to 4.7 and 34.5 to 34.7 us), 0.16 to 0.28 percent of a lazy landing; the log's rows are 45 to 47 and 74 of them. Every head costs what building the answer costs: the walk is 0.14 to 0.15 us an event, each head returned 3.5 to 3.9 us more, on the corpus's chain and on new chains of 30,000 and 100,000 paths alike, so a chain of 30,002 events reads its heads in 0.11 s. That meets SNF-6's first condition, which the record had read as the corpus's chain being over section 4.2's threshold; kept heads would not lower it. The two earlier runs that found each savepoint's journal in a temporary file are kept in the JSON. The migration took 6.7 s, a row 429 bytes, at a load average of 2.7 to 3.9. Co-Authored-By: Claude Opus 5.5 --- docs/experiments/landing-log-2026-11-11.json | 601 ++++++++++++++----- docs/experiments/landing-log-2026-11-11.md | 131 ++-- 2 files changed, 529 insertions(+), 203 deletions(-) diff --git a/docs/experiments/landing-log-2026-11-11.json b/docs/experiments/landing-log-2026-11-11.json index 3df01d67..2b4a2305 100644 --- a/docs/experiments/landing-log-2026-11-11.json +++ b/docs/experiments/landing-log-2026-11-11.json @@ -1,11 +1,11 @@ { - "note": "eval/landing_log_bench.py on two copy-on-write clones of the corpus instance's catalog, 2026-11-11; default arguments (--batch 10000 --rounds 5 --repeat 200 --seed 11)", + "note": "eval/landing_log_bench.py at 08d4d506, the code at 88ef0781, on two copy-on-write clones of the corpus instance's catalog, 2026-11-11; default arguments (--batch 10000 --rounds 5 --repeat 200 --seed 11) and --fresh 30000,100000. The writes are timed three ways: 'with' is record as built, 'without' the same with LandingLog.store patched out (the read of the row before, the explicit transaction and the savepoint kept), 'before' the upsert record ran at f969904e, alone.", "run1": { "catalog_copy": "vault_catalog.sqlite", "load_start": [ - 2.26123046875, - 2.5947265625, - 2.93701171875 + 3.86474609375, + 3.90380859375, + 3.43603515625 ], "python": "3.15.2", "sqlite": "3.54.1", @@ -30,7 +30,7 @@ "vault_files_digest": 34033664, "vault_files_doc_id": 16924672 }, - "migration_s": 6.220551250036806, + "migration_s": 6.729614624986425, "chains": { "1": { "class": "observed", @@ -39,7 +39,7 @@ }, "log_rows": 400276, "files_after": { - "vault_catalog.sqlite": 334131200, + "vault_catalog.sqlite": 334127104, "vault_catalog.sqlite-wal": 0, "vault_catalog.sqlite-shm": 360448 }, @@ -48,18 +48,18 @@ "landings": 152621056, "landings_closed": 4096, "landings_doc": 4096, - "landings_path": 18845696, + "landings_path": 18841600, "sqlite_autoindex_vault_files_1": 16924672, "sqlite_schema": 4096, "vault_files": 94765056, "vault_files_digest": 34033664, "vault_files_doc_id": 16924672 }, - "growth_bytes": 171806720, - "growth_bytes_a_row": 429.22063775994565, + "growth_bytes": 171802624, + "growth_bytes_a_row": 429.2104048206737, "bytes_a_row": { "landings": 381.28955021035483, - "landings_path": 47.081753590022885, + "landings_path": 47.07152065075098, "landings_doc": 0.010232939271902388, "landings_closed": 0.010232939271902388, "landing_chains": 0.010232939271902388 @@ -69,148 +69,224 @@ "ok": true, "rows": 400276, "commitments": 400276, - "seconds": 3.0703140411060303 + "seconds": 3.0797554578166455 } }, "fold_equals_catalog": true, - "fold_seconds": 2.8317980838473886, + "fold_seconds": 2.901144874980673, "reads": { "chain": 1, "class": "observed", "head": { - "median_us": 2.4170149117708206, - "low_us": 2.3329630494117737, - "high_us": 18.124934285879135, + "median_us": 2.499902620911598, + "low_us": 2.37487256526947, + "high_us": 26.499852538108826, "runs": 200 }, "path_key": { - "median_us": 1.5830155462026596, + "median_us": 1.6249250620603561, "low_us": 1.4998950064182281, - "high_us": 26.665860787034035, + "high_us": 21.3750172406435, "runs": 200 }, "state_at_mid": { - "median_us": 14.25005029886961, - "low_us": 8.167000487446785, - "high_us": 160.33300198614597, + "median_us": 13.72897531837225, + "low_us": 8.58306884765625, + "high_us": 130.3341705352068, "runs": 200 }, "history_at_head": { - "median_us": 15.708035789430141, - "low_us": 13.417098671197891, - "high_us": 66.83287210762501, + "median_us": 15.457975678145885, + "low_us": 13.124896213412285, + "high_us": 69.29109804332256, "runs": 200 }, "read_between_1000": { - "median_us": 3442.95846298337, - "low_us": 3368.9169213175774, - "high_us": 3593.666944652796, + "median_us": 3351.478953845799, + "low_us": 3183.4589317440987, + "high_us": 3686.541924253106, "runs": 200 }, "read_at_1000": { - "median_us": 3280.0829503685236, - "low_us": 3207.0830930024385, - "high_us": 3584.667108952999, + "median_us": 3179.7916162759066, + "low_us": 3080.999944359064, + "high_us": 3473.334014415741, "runs": 200 }, "heads_at_tenth": { - "median_us": 151410.75011342764, - "low_us": 150872.8750050068, - "high_us": 169505.79197145998, + "median_us": 151287.6250781119, + "low_us": 148509.37481969595, + "high_us": 161804.45812642574, "runs": 5, "rows": 40026 }, "heads_walk_tenth": { - "median_us": 5558.416014537215, - "low_us": 5286.04188002646, - "high_us": 6100.333062931895, + "median_us": 5649.625090882182, + "low_us": 5616.624839603901, + "high_us": 6420.0409688055515, "runs": 5 }, "heads_at_mid": { - "median_us": 789987.4169379473, - "low_us": 759208.207949996, - "high_us": 810563.457896933, + "median_us": 790489.915991202, + "low_us": 752933.2500416785, + "high_us": 809762.9579715431, "runs": 5, "rows": 200137 }, "heads_walk_mid": { - "median_us": 26317.6248408854, - "low_us": 26199.499843642116, - "high_us": 27383.832959458232, + "median_us": 28980.624862015247, + "low_us": 28823.250206187367, + "high_us": 30172.500060871243, "runs": 5 }, "heads_at_head": { - "median_us": 1617782.6661150903, - "low_us": 1572967.833140865, - "high_us": 1625654.5409560204, + "median_us": 1619828.0828539282, + "low_us": 1561983.7080594152, + "high_us": 1626085.9169997275, "runs": 5, "rows": 400274 }, "heads_walk_head": { - "median_us": 56461.54098212719, - "low_us": 55988.00000734627, - "high_us": 60100.20803660154, + "median_us": 59528.332902118564, + "low_us": 58484.707958996296, + "high_us": 61096.3748767972, "runs": 5 } }, "writes_us_a_record": { "new": { "with": [ - 48.001220799051225, - 48.92591249663383, - 48.21360409259796, - 49.26652500871569, - 50.32935000490397 + 55.10822921060026, + 55.28729159850627, + 55.70070000831038, + 56.571758282370865, + 57.32883329037577 ], "without": [ - 6.799195799976587, - 6.8319084122776985, - 6.65885410271585, - 6.896770792081952, - 6.805129209533334 + 10.584408300928771, + 10.540708410553634, + 10.540254204533994, + 10.614020796492696, + 10.518579185009003 + ], + "before": [ + 4.659308400005102, + 4.703449993394315, + 4.651125008240342, + 4.6134083066135645, + 4.631524998694658 ], - "with_median_us": 48.92591249663383, - "without_median_us": 6.805129209533334, - "overhead_us": 42.120783287100494 + "with_median_us": 55.70070000831038, + "without_median_us": 10.540708410553634, + "before_median_us": 4.651125008240342, + "sn1_adds_us": 51.049575000070035, + "log_rows_add_us": 45.15999159775674 }, "changed": { "with": [ - 105.88544998317957, - 109.1484708013013, - 105.0655041821301, - 106.46303340326995, - 107.13723751250654 + 119.69202079344541, + 119.57683339715004, + 122.25654169451444, + 120.29862918425351, + 120.3234083019197 ], "without": [ - 40.69942079950124, - 40.631037508137524, - 37.9464291036129, - 37.86343338433653, - 37.41974588483572 + 47.33577910810709, + 46.588333416730165, + 46.02282920386642, + 43.616541707888246, + 44.30537910666317 + ], + "before": [ + 35.367579106241465, + 36.521849990822375, + 34.526974987238646, + 33.05701659992337, + 33.809708314947784 ], - "with_median_us": 106.46303340326995, - "without_median_us": 37.9464291036129, - "overhead_us": 68.51660429965705 + "with_median_us": 120.29862918425351, + "without_median_us": 46.02282920386642, + "before_median_us": 34.526974987238646, + "sn1_adds_us": 85.77165419701487, + "log_rows_add_us": 74.27579998038709 } }, "verify_after_writes": true, "files_end": { - "vault_catalog.sqlite": 389640192, + "vault_catalog.sqlite": 404824064, "vault_catalog.sqlite-wal": 0, "vault_catalog.sqlite-shm": 360448 }, "load_end": [ - 8.271484375, - 4.3427734375, - 3.572265625 + 3.7021484375, + 3.8291015625, + 3.43212890625 + ], + "fresh_chains": [ + { + "paths": 30000, + "load_start": [ + 3.7021484375, + 3.8291015625, + 3.43212890625 + ], + "chain_rows": 30002, + "heads_at": { + "median_us": 111838.91608379781, + "low_us": 109059.91704203188, + "high_us": 124618.75006556511, + "runs": 5, + "rows": 30000 + }, + "heads_walk": { + "median_us": 4092.208109796047, + "low_us": 3992.582904174924, + "high_us": 4969.167057424784, + "runs": 5 + }, + "us_a_head_past_the_walk": 3.5915569324667254, + "load_end": [ + 3.7021484375, + 3.8291015625, + 3.43212890625 + ] + }, + { + "paths": 100000, + "load_start": [ + 3.7021484375, + 3.8291015625, + 3.43212890625 + ], + "chain_rows": 100002, + "heads_at": { + "median_us": 374241.6659370065, + "low_us": 372616.66590347886, + "high_us": 400077.1250575781, + "runs": 5, + "rows": 100000 + }, + "heads_walk": { + "median_us": 15067.29214452207, + "low_us": 14669.333817437291, + "high_us": 15617.999946698546, + "runs": 5 + }, + "us_a_head_past_the_walk": 3.591743737924844, + "load_end": [ + 3.5654296875, + 3.79833984375, + 3.42333984375 + ] + } ] }, "run2": { "catalog_copy": "vault_catalog.sqlite", "load_start": [ - 8.271484375, - 4.3427734375, - 3.572265625 + 3.5654296875, + 3.79833984375, + 3.42333984375 ], "python": "3.15.2", "sqlite": "3.54.1", @@ -235,7 +311,7 @@ "vault_files_digest": 34033664, "vault_files_doc_id": 16924672 }, - "migration_s": 6.325798250036314, + "migration_s": 6.70507474988699, "chains": { "1": { "class": "observed", @@ -244,7 +320,7 @@ }, "log_rows": 400276, "files_after": { - "vault_catalog.sqlite": 334127104, + "vault_catalog.sqlite": 334131200, "vault_catalog.sqlite-wal": 0, "vault_catalog.sqlite-shm": 360448 }, @@ -253,18 +329,18 @@ "landings": 152621056, "landings_closed": 4096, "landings_doc": 4096, - "landings_path": 18841600, + "landings_path": 18845696, "sqlite_autoindex_vault_files_1": 16924672, "sqlite_schema": 4096, "vault_files": 94765056, "vault_files_digest": 34033664, "vault_files_doc_id": 16924672 }, - "growth_bytes": 171802624, - "growth_bytes_a_row": 429.2104048206737, + "growth_bytes": 171806720, + "growth_bytes_a_row": 429.22063775994565, "bytes_a_row": { "landings": 381.28955021035483, - "landings_path": 47.07152065075098, + "landings_path": 47.081753590022885, "landings_doc": 0.010232939271902388, "landings_closed": 0.010232939271902388, "landing_chains": 0.010232939271902388 @@ -274,140 +350,359 @@ "ok": true, "rows": 400276, "commitments": 400276, - "seconds": 3.051000916864723 + "seconds": 3.065702833002433 } }, "fold_equals_catalog": true, - "fold_seconds": 2.848458959022537, + "fold_seconds": 2.934743707999587, "reads": { "chain": 1, "class": "observed", "head": { - "median_us": 2.459157258272171, + "median_us": 2.499902620911598, "low_us": 2.37487256526947, - "high_us": 24.124979972839355, + "high_us": 21.0409052670002, "runs": 200 }, "path_key": { - "median_us": 1.5830155462026596, - "low_us": 1.4998950064182281, - "high_us": 22.999942302703857, + "median_us": 1.7499551177024841, + "low_us": 1.5830155462026596, + "high_us": 31.83400258421898, "runs": 200 }, "state_at_mid": { - "median_us": 14.832941815257072, - "low_us": 8.542090654373169, - "high_us": 133.2079991698265, + "median_us": 16.54098741710186, + "low_us": 8.457805961370468, + "high_us": 165.9998670220375, "runs": 200 }, "history_at_head": { - "median_us": 14.666467905044556, - "low_us": 13.249926269054413, - "high_us": 63.04099224507809, + "median_us": 18.895952962338924, + "low_us": 13.916054740548134, + "high_us": 102.91696526110172, "runs": 200 }, "read_between_1000": { - "median_us": 3424.0210661664605, - "low_us": 3286.0420178622007, - "high_us": 3612.959058955312, + "median_us": 3372.354549355805, + "low_us": 3172.1252016723156, + "high_us": 3723.874920979142, "runs": 200 }, "read_at_1000": { - "median_us": 3255.7500526309013, - "low_us": 3225.250169634819, - "high_us": 3565.666964277625, + "median_us": 3192.270523868501, + "low_us": 3032.9590663313866, + "high_us": 3557.500196620822, "runs": 200 }, "heads_at_tenth": { - "median_us": 151474.91707466543, - "low_us": 150040.70801660419, - "high_us": 160787.37494535744, + "median_us": 149837.87504024804, + "low_us": 145627.5419332087, + "high_us": 159029.042115435, "runs": 5, "rows": 40026 }, "heads_walk_tenth": { - "median_us": 5932.959029451013, - "low_us": 5322.749959304929, - "high_us": 6092.166993767023, + "median_us": 5779.791856184602, + "low_us": 5585.665814578533, + "high_us": 6089.084083214402, "runs": 5 }, "heads_at_mid": { - "median_us": 798841.6668958962, - "low_us": 764181.62509799, - "high_us": 805269.2501805723, + "median_us": 789410.9999760985, + "low_us": 754632.7088493854, + "high_us": 811964.7921994328, "runs": 5, "rows": 200137 }, "heads_walk_mid": { - "median_us": 26318.04207339883, - "low_us": 25891.083059832454, - "high_us": 27076.20896399021, + "median_us": 30065.417056903243, + "low_us": 28939.95912745595, + "high_us": 30304.33296225965, "runs": 5 }, "heads_at_head": { - "median_us": 1613144.7500083596, - "low_us": 1580234.7920835018, - "high_us": 1634123.8748282194, + "median_us": 1617219.0001234412, + "low_us": 1563315.707957372, + "high_us": 1622686.7500226945, "runs": 5, "rows": 400274 }, "heads_walk_head": { - "median_us": 54320.41618041694, - "low_us": 52884.4587970525, - "high_us": 57886.87500171363, + "median_us": 59110.08291877806, + "low_us": 58275.99996700883, + "high_us": 62306.66604824364, "runs": 5 } }, "writes_us_a_record": { "new": { "with": [ - 48.21380840148777, - 48.990112519823015, - 48.84648330044001, - 49.588733399286866, - 49.51973750721663 + 54.36905410606414, + 55.64371659420431, + 57.90479579009116, + 57.44836248923093, + 57.93580422177911 ], "without": [ - 6.882070912979543, - 6.796324998140335, - 6.684429198503494, - 6.795345805585384, - 6.710762483999133 + 10.374437482096255, + 10.359825007617474, + 10.390820796601474, + 10.337000014260411, + 10.406262497417629 + ], + "before": [ + 4.5640458120033145, + 4.662716598249972, + 4.525408404879272, + 4.5750708086416125, + 4.493379103951156 ], - "with_median_us": 48.990112519823015, - "without_median_us": 6.795345805585384, - "overhead_us": 42.19476671423763 + "with_median_us": 57.44836248923093, + "without_median_us": 10.374437482096255, + "before_median_us": 4.5640458120033145, + "sn1_adds_us": 52.884316677227616, + "log_rows_add_us": 47.073925007134676 }, "changed": { "with": [ - 110.63325421418995, - 106.03663329966366, - 104.65863330755383, - 106.02083748672158, - 105.65141250845045 + 122.07017501350492, + 118.36712919175625, + 120.04747919272631, + 117.80861250590533, + 119.09208749420941 ], "without": [ - 43.35534158162773, - 41.16715001873672, - 41.45721250679344, - 37.74790000170469, - 39.11720409523696 + 51.869129203259945, + 45.72556249331683, + 42.81076251063496, + 43.757937499322, + 45.044100005179644 ], - "with_median_us": 106.02083748672158, - "without_median_us": 41.16715001873672, - "overhead_us": 64.85368746798486 + "before": [ + 36.119758314453065, + 36.37074159923941, + 33.456237497739494, + 33.571337489411235, + 34.735108306631446 + ], + "with_median_us": 119.09208749420941, + "without_median_us": 45.044100005179644, + "before_median_us": 34.735108306631446, + "sn1_adds_us": 84.35697918757796, + "log_rows_add_us": 74.04798748902977 } }, "verify_after_writes": true, "files_end": { - "vault_catalog.sqlite": 389656576, + "vault_catalog.sqlite": 404795392, "vault_catalog.sqlite-wal": 0, "vault_catalog.sqlite-shm": 360448 }, "load_end": [ - 7.1728515625, - 4.68798828125, - 3.74462890625 + 2.8154296875, + 3.5634765625, + 3.357421875 + ], + "fresh_chains": [ + { + "paths": 30000, + "load_start": [ + 2.8154296875, + 3.5634765625, + 3.357421875 + ], + "chain_rows": 30002, + "heads_at": { + "median_us": 110653.37480977178, + "low_us": 109369.91707421839, + "high_us": 124239.5001463592, + "runs": 5, + "rows": 30000 + }, + "heads_walk": { + "median_us": 4666.124936193228, + "low_us": 3926.1248894035816, + "high_us": 5359.542090445757, + "runs": 5 + }, + "us_a_head_past_the_walk": 3.532908329119285, + "load_end": [ + 2.8154296875, + 3.5634765625, + 3.357421875 + ] + }, + { + "paths": 100000, + "load_start": [ + 2.8154296875, + 3.5634765625, + 3.357421875 + ], + "chain_rows": 100002, + "heads_at": { + "median_us": 375836.709048599, + "low_us": 370909.4999358058, + "high_us": 406000.7082298398, + "runs": 5, + "rows": 100000 + }, + "heads_walk": { + "median_us": 15437.291003763676, + "low_us": 15316.500095650554, + "high_us": 17928.87505143881, + "runs": 5 + }, + "us_a_head_past_the_walk": 3.6039941804483533, + "load_end": [ + 2.68994140625, + 3.51123046875, + 3.3408203125 + ] + } ] + }, + "savepoint_journal_in_a_file": { + "note": "the same harness on two earlier clones, at 2d106dd0, before the catalog's connection kept its temporary store in memory: each write in a batch took a savepoint whose journal SQLite kept in a temporary file; the writes only", + "run1": { + "load_start": [ + 3.88623046875, + 3.7333984375, + 3.216796875 + ], + "load_end": [ + 3.830078125, + 3.74853515625, + 3.255859375 + ], + "writes_us_a_record": { + "new": { + "with": [ + 104.19153750408441, + 105.10614160448313, + 105.80063331872225, + 104.23267919104546, + 107.40759999025613 + ], + "without": [ + 35.8013833174482, + 34.651629091240466, + 36.060837493278086, + 36.28457081504166, + 38.067224994301796 + ], + "before": [ + 4.716416588053107, + 4.740945901721716, + 4.919600021094084, + 4.730145796202123, + 4.913333291187882 + ], + "with_median_us": 105.10614160448313, + "without_median_us": 36.060837493278086, + "before_median_us": 4.740945901721716, + "sn1_adds_us": 100.36519570276141, + "log_rows_add_us": 69.04530411120504 + }, + "changed": { + "with": [ + 213.28370838891715, + 191.467983298935, + 196.34440001100302, + 197.77144158724695, + 199.3030291981995 + ], + "without": [ + 58.519500005058944, + 52.49663342256099, + 49.9285584082827, + 57.20237500499934, + 58.86454579886049 + ], + "before": [ + 42.90297920815647, + 41.671029198914766, + 40.235729212872684, + 41.73753750510514, + 42.11257079150528 + ], + "with_median_us": 197.77144158724695, + "without_median_us": 57.20237500499934, + "before_median_us": 41.73753750510514, + "sn1_adds_us": 156.03390408214182, + "log_rows_add_us": 140.56906658224761 + } + } + }, + "run2": { + "load_start": [ + 4.390625, + 3.8876953125, + 3.314453125 + ], + "load_end": [ + 4.51171875, + 3.98486328125, + 3.38232421875 + ], + "writes_us_a_record": { + "new": { + "with": [ + 98.89293750748038, + 107.52870829310268, + 109.82248748186976, + 105.70167500991374, + 111.048962501809 + ], + "without": [ + 30.30264580156654, + 31.740979081951085, + 31.109712505713105, + 33.568929112516344, + 35.236116708256304 + ], + "before": [ + 4.894129186868668, + 4.725395794957876, + 4.881912493146956, + 4.704041685909033, + 4.885404207743704 + ], + "with_median_us": 107.52870829310268, + "without_median_us": 31.740979081951085, + "before_median_us": 4.881912493146956, + "sn1_adds_us": 102.64679579995573, + "log_rows_add_us": 75.7877292111516 + }, + "changed": { + "with": [ + 193.7144417082891, + 192.2450999962166, + 199.66615831945091, + 193.41460408177227, + 199.17669580318034 + ], + "without": [ + 63.67000420577824, + 52.5426333071664, + 51.143874996341765, + 54.282879200764, + 57.24806669168174 + ], + "before": [ + 41.37748330831528, + 40.36920410580933, + 39.85576250124723, + 40.51143329124898, + 40.28654999565333 + ], + "with_median_us": 193.7144417082891, + "without_median_us": 54.282879200764, + "before_median_us": 40.36920410580933, + "sn1_adds_us": 153.34523760247976, + "log_rows_add_us": 139.4315625075251 + } + } + } } } diff --git a/docs/experiments/landing-log-2026-11-11.md b/docs/experiments/landing-log-2026-11-11.md index b1a6bfd8..82d9b748 100644 --- a/docs/experiments/landing-log-2026-11-11.md +++ b/docs/experiments/landing-log-2026-11-11.md @@ -15,18 +15,18 @@ links: # The landing log, measured on the corpus instance's catalog (2026-11-11) **Question.** What does stage SN-1's landing log cost at a corpus's size: the migration that -writes its genesis, the bytes a row takes, the time it adds to a key's write, and the time each of -its reads takes? And does the genesis hold the catalog exactly? The design note measured the log -on a synthetic fixture only (§11); these are the figures of the code as built, on a copy of a real -catalog. +writes its genesis, the bytes a row takes, the time SN-1 adds to a key's write against the write +before it, and the time each of its reads takes? And does the genesis hold the catalog exactly? +The design note measured the log on a synthetic fixture only (§11); these are the figures of the +code as built, on a copy of a real catalog. ## Method -Two runs of `eval/landing_log_bench.py` with its defaults (`--batch 10000 --rounds 5 ---repeat 200 --seed 11`), each on its own copy-on-write clone (`cp -c`) of the corpus instance's -catalog file with its `-wal` and `-shm`, made in a scratch directory; the original was never -opened. The harness migrates the clone in place under a random secret made for the run and -dropped with it. +Two runs of `eval/landing_log_bench.py` (at `08d4d506`, the code at `88ef0781`) with its defaults +(`--batch 10000 --rounds 5 --repeat 200 --seed 11`) and `--fresh 30000,100000`, each on its own +copy-on-write clone (`cp -c`) of the corpus instance's catalog file with its `-wal` and `-shm`, +made in a scratch directory; the original was never opened. The harness migrates the clone in +place under a random secret made for the run and dropped with it. - **The catalog.** 400,274 rows, every one `observed` and active, so the genesis is one chain of 400,276 rows: the `genesis`, a `store` a path in path order, the `horizon`. No identity differs @@ -37,76 +37,107 @@ dropped with it. it, before and after, and each table's and index's from SQLite's `dbstat`. - **The check.** The chain verified from its first row, every commitment and every hash recomputed; the fold of the log compared with the catalog row by row. -- **The writes.** Batches of 10,000 catalog writes, each batch one transaction, as a landing - batch writes its keys (`deferred()`): first new paths, then new versions of paths the catalog - holds. Each batch runs with the log and with the log's appending switched off on the same file - (a patch of `LandingLog.store`), the order alternated over five rounds; the figure is the - median over the rounds of the time a write takes. +- **The writes.** Batches of 10,000 catalog writes, each batch one transaction, as a landing batch + writes its keys (`deferred()`): first new paths, then new versions of paths the catalog holds. + Each batch is timed three ways on the same file, the order turned each round over five rounds: + `record` as built; the same with the log's appending switched off (a patch of + `LandingLog.store`), which keeps what SN-1 added around the log, the read of the path's row + before the write, the explicit transaction and each write's savepoint; and the write as + `record` made it before SN-1 (`f969904e`), the upsert alone. The figure is the median over the + rounds of the time a write takes. The third is what SN-1 is measured against, and it runs on + the migrated file, whose `vault_files` table and indexes are the ones an unmigrated file has. - **The reads.** On the chain: `state_at` of one path at the middle cut and `history_at` at the head, the 200 paths drawn from the catalog; `read_at` of the first 1,000 positions and `read_between` of 1,000 positions from 200 random starts; `head`; the keyed hash of a path alone; and `heads_at` at a tenth of the chain, at its middle and at its head, five times each, with the same predicate counted in SQL, the walk without the rows built. +- **Every head of a smaller chain.** After the copy, a new catalog of 30,000 paths and then one of + 100,000, one class, landed through `record` in batches, with paths and titles of the corpus's + lengths: `heads_at` at the head and the walk counted in SQL, five times each. - **The machine.** Apple M2 Pro, 12 cores, 32 GB, macOS 27.0.1, Python 3.15.2, SQLite 3.54.1, with - other work running: the one-minute load average was 2.3 at the first run's start, 8.3 between - the two runs, which another process raised, and 7.2 at the second's end. Medians with their - ranges over the repetitions; the two runs are given side by side. + other work running: the one-minute load average was 3.9 at the first run's start, 3.6 between + the runs and 2.7 at the second's end, and the second run's smaller chains were read at 2.8. The + harness peaked at 688 and 692 MB resident. Medians with their ranges over the repetitions; the + two runs are given side by side. ## Results | measurement | run 1 | run 2 | |---|---|---| -| the migration, 400,276 rows of genesis | 6.22 s | 6.33 s | +| the migration, 400,276 rows of genesis | 6.73 s | 6.71 s | | the file, before and after | 162.7 MB, 334.1 MB | 162.7 MB, 334.1 MB | | bytes a row of the log, from the file's growth | 429.2 | 429.2 | | of which the table, the key index | 381.3, 47.1 | 381.3, 47.1 | -| `verify`: every commitment and hash of the chain | 3.07 s | 3.05 s | -| the fold of the log against the catalog | equal, 2.83 s | equal, 2.85 s | -| `head` | 2.4 µs | 2.5 µs | -| the keyed hash of a path | 1.6 µs | 1.6 µs | -| `state_at`, one path at the middle cut | 14.3 µs (8.2 to 160) | 14.8 µs (8.5 to 133) | -| `history_at`, one path at the head | 15.7 µs | 14.7 µs | -| `read_at`, 1,000 positions | 3.28 ms | 3.26 ms | -| `read_between`, 1,000 positions | 3.44 ms | 3.42 ms | -| `heads_at` at a tenth (40,026 rows) | 151 ms | 152 ms | -| `heads_at` at the middle (200,137 rows) | 790 ms | 799 ms | -| `heads_at` at the head (400,274 rows) | 1.62 s | 1.61 s | -| the same three walks counted in SQL | 5.6, 26.3, 56.5 ms | 5.9, 26.3, 54.3 ms | -| a write of a new path: with the log, without | 48.9, 6.8 µs | 49.0, 6.8 µs | -| a write of a new version of a held path: with, without | 106.5, 37.9 µs | 106.0, 41.2 µs | -| every chain verifies after the 200,000 writes | yes | yes | +| `verify`: every commitment and hash of the chain | 3.08 s | 3.07 s | +| the fold of the log against the catalog | equal, 2.90 s | equal, 2.93 s | +| `head` | 2.5 µs | 2.5 µs | +| the keyed hash of a path | 1.6 µs | 1.7 µs | +| `state_at`, one path at the middle cut | 13.7 µs (8.6 to 130) | 16.5 µs (8.5 to 166) | +| `history_at`, one path at the head | 15.5 µs | 18.9 µs | +| `read_at`, 1,000 positions | 3.18 ms | 3.19 ms | +| `read_between`, 1,000 positions | 3.35 ms | 3.37 ms | +| `heads_at` at a tenth (40,026 rows) | 151 ms | 150 ms | +| `heads_at` at the middle (200,137 rows) | 790 ms | 789 ms | +| `heads_at` at the head (400,274 rows) | 1.62 s | 1.62 s | +| the same three walks counted in SQL | 5.6, 29.0, 59.5 ms | 5.8, 30.1, 59.1 ms | +| `heads_at`, a chain of 30,000 paths, at its head | 112 ms (walk 4.1 ms) | 111 ms (walk 4.7 ms) | +| `heads_at`, a chain of 100,000 paths, at its head | 374 ms (walk 15.1 ms) | 376 ms (walk 15.4 ms) | +| a write of a new path: as built, the log's rows off, before SN-1 | 55.7, 10.5, 4.7 µs | 57.4, 10.4, 4.6 µs | +| a write of a new version of a held path: the same | 120.3, 46.0, 34.5 µs | 119.1, 45.0, 34.7 µs | +| every chain verifies after the 300,000 writes | yes | yes | ## Reading - **The genesis holds the catalog.** The fold of the 400,276 rows equals the catalog's 400,274 - rows in both runs, and the chain verifies. The migration takes six seconds once, on the first - open of the build with the log. + rows in both runs, and the chain verifies. The migration takes under seven seconds once, on the + first open of the build with the log. - **A row is 429 bytes,** against the fixture's 434 where the identity is the path (§4.3): the table's row is 381 bytes against 374, its titles far longer (63.8 characters against under twelve) and its paths shorter (28.6 against 37), and the key index is the same 47 bytes. The fixture's closing index, 13 bytes, is empty here, since a genesis of active paths closes no row. The log doubles the catalog's file, 162.7 MB to 334.1 MB; it holds paths, digests and titles, which the catalog holds already. -- **The log adds 42 µs to a new path's write and 65 to 69 µs to a new version's,** the second - writing a closing stamp as well. A lazy landing took 31 ms an item on the two-phase record (32.0 - items a second, `docs/experiments/two-phase-ingestion-2026-11-07.md`), so the log is between - 0.1 and 0.2 percent of a landing. -- **A read of one path is 14 to 16 µs** through the key index, of which the keyed hash is 1.6. -- **Every head at the head is 1.6 s,** past the tenth of a second §4.2 allows. The walk itself is - 54 to 57 ms in SQL, 0.14 µs an event, under the fixture's quarter of a microsecond; the rest is - building 400,274 rows in Python. A corpus chain is over §4.2's 250,000 events from the start, - which is why SN-4 keeps heads at recorded cuts for such a chain (SN-c); nothing reads every head - yet. +- **SN-1 adds 51 to 53 µs to a new path's write and 84 to 86 µs to a new version's,** against the + write before it (4.6 to 4.7 and 34.5 to 34.7 µs). The log's rows are 45 to 47 and 74 of them, a + new version's writing the previous row's closing stamp as well; the rest, about 6 and 11 µs, is + the read of the path's row before the write, the explicit transaction and the write's + savepoint. A lazy landing took 31 ms an item on the two-phase record (32.0 items a second, + `docs/experiments/two-phase-ingestion-2026-11-07.md`), so SN-1 is between 0.16 and 0.28 percent + of a landing. A landing in the vault's place also reads its version chain's current version once + more, to pass it to the key (`core/ingest/writer.py:417-418`); the corpus's place keeps no + version chain, and that read was not measured. +- **A read of one path is 14 to 19 µs** through the key index, of which the keyed hash is 1.6. +- **Every head costs what building the answer costs.** The walk is 0.14 to 0.15 µs an event in + SQL; building the rows in Python is 3.5 to 3.9 µs a head returned beyond it, on the corpus's + chain at a tenth, the middle and the head and on the smaller chains alike. So the read from the + log alone passes §4.2's tenth of a second near 27,000 heads: a chain of 30,002 events takes 0.11 + s, far under the 250,000 events §4.2 set as the threshold for kept heads, which is the first + condition of SNF-6, met. Kept heads at a recorded cut shorten the walk and not the building, so + they do not remove this cost. Nothing reads every head yet; before SN-4 builds on it, SN-c + re-enters, and whether the threshold moves or the read changes is open (dn-temporal-snapshot + §4.2, §11). - **A planner's choice, found here.** The first run of the harness took about 40 ms a landing: the update that writes the previous row's closing stamp took the primary key and walked the chain, as the fixture's seek did when the planner took the primary key (§4.1). The statement now names the key index, as the reads did already, and a test asks the plan of every statement by path to name it (`tests/property/test_landing_log.py`). The figures above are after the fix. +- **A savepoint's journal, found here.** Each write in a batch is a savepoint since review, so + that a write that fails leaves neither of its rows when the batch's caller goes on. Two earlier + runs of the same harness, at load 3.9 and 4.4, measured a new path's write at 105 and 108 µs + with the log and 36 and 32 µs with its rows off: SQLite kept each savepoint's journal in a + temporary file. The catalog's connection now keeps its temporary store in memory, and the + savepoint costs about 6 µs a write. Those runs are in the JSON, under + `savepoint_journal_in_a_file`. +- **The control.** The record first gave the log's cost as the write with the log against the + write with its rows switched off, 42 µs and 65 to 69 µs: that is what the log's rows add, and it + left out the read of the row before the write and the transaction SN-1 added around them. The + third arm, the write before SN-1, is the control for SN-1's cost. ## Not measured -A whole landing batch through the writer with the log against without it (the overhead above is -the catalog's writes alone, and nothing else in a landing changed); a purge on the corpus's size, -whose emptying of a digest's rows reads the whole log, since the log has no index by digest; a -catalog of several classes, or one whose identities differ from their paths; and every read at a -cut that SN-2 and later stages build. +A whole landing batch through the writer with the log against without it (the writes above are +the catalog's alone, and a vault landing also reads its version chain once more); a purge on the +corpus's size, whose emptying of a digest's rows walks the whole log twice, for the digest and for +the names of the paths it empties, since the log has no index by either; a catalog of several +classes, or one whose identities differ from their paths; and every read at a cut that SN-2 and +later stages build. From 6fc1a7e2b84248c21eeb1961b0081410a2fba2af Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:07:22 -0500 Subject: [PATCH 19/30] docs(design): the snapshot note after SN-1's review What review of the built stage found, stated where the design stands, each marked as built: - Section 6.1 and D14: a purge by digest empties a path's tombstones with its last version, so no row names a purged note; while a version keeps its content the hole stays tied to the path. SQLite keeps the bytes it frees until a vacuum, which is SN-3's reach. - Section 3.2 and 12 (SN-1): which writes and reads need the secret, and that every process's first open of a catalog without a log writes the genesis, a reader's included. That and "no reader's behaviour changes" cannot both hold; which gives way is left to the owner before SN-1 is deployed. D12 and SN-3's reason say what SN-1 changes. - Section 4.2, 11, SN-c and SNF-6: every head costs 3.5 to 3.9 us a head returned, so a chain of 30,002 events reads its heads in 0.11 s; SNF-6 is met, kept heads would not lower that cost, and the threshold or the read's shape is open before SN-4. Section 11 gives the runs against the write before SN-1 and the savepoint's journal found in a file. - Sections 3.1, 6.2 and 12: the rollback numbers chain ids and positions from 1 again, which SN-3's fresh identity must not rest on; how it is kept from repeating is SN-3's to decide. - Section 6.2: the migration's count sees only what the log recorded since its genesis, and not a note landed at a path a rename left; the exception for a note that declares its identity is graded as the design's reading of the decision, with a falsifier, SNF-17; a life a purge closes with a hole is named among what the model leaves out. - Section 10: SNP-1's test compares a read by class while the class's chains are the ones it had, and chain by chain across a relabel; SNP-2's attacks include 523; SN-3's test is for notes that declare no identity. - The header, section 6.3, section 11's opening and SN-1's list of results no longer speak of a design with nothing built, and name leave where a path changes chains. Co-Authored-By: Claude Opus 5.5 --- docs/design-notes/dn-temporal-snapshot.md | 264 ++++++++++++++++------ 1 file changed, 191 insertions(+), 73 deletions(-) diff --git a/docs/design-notes/dn-temporal-snapshot.md b/docs/design-notes/dn-temporal-snapshot.md index 9292d4ec..805c6b55 100644 --- a/docs/design-notes/dn-temporal-snapshot.md +++ b/docs/design-notes/dn-temporal-snapshot.md @@ -30,17 +30,19 @@ warrant: null > Composed on the snapshot session (Fable 5.2, 2026-11-10 and 2026-11-11), on the standing > direction that the design and its proofs come first and the build follows a licence given at -> the merge. Agent-drafted, filed `draft` on a branch; the merge is ratification. Nothing is -> built: `core/` is untouched and no store of any instance was read. Every nontrivial claim -> carries a grade: `[THEOREM]` is machine-checked in `formal/Palace/Snapshot.lean` and names its -> declaration; `[ESTABLISHED]` is a ratified note's, a fact of the code read at the line cited, -> or a figure of the repository's own experiment records, cited by file and line; `[DERIVED]` is -> argued here from those; `[MEASURED]` is a figure taken for this note on a synthetic fixture, by -> a probe that is not in the repository (§11 says how, and which stage commits its harness); -> `[INFERENCE]` is a design call with a named falsifier; `[HYPOTHESIS]` is a claim nothing here -> checks, with what would check it named. Code claims were read on -> `origin/main` at `e3e3ee47`. The article `papers/2026-11-10-temporal-snapshot/paper.tex` -> states the same theorems with proof sketches and the references. +> the merge. Agent-drafted, filed `draft` on a branch; the merge is ratification. When the design +> was merged nothing was built: `core/` was untouched and no store of any instance was read. +> Every nontrivial claim carries a grade: `[THEOREM]` is machine-checked in +> `formal/Palace/Snapshot.lean` and names its declaration; `[ESTABLISHED]` is a ratified note's, a +> fact of the code read at the line cited, or a figure of the repository's own experiment records, +> cited by file and line; `[DERIVED]` is argued here from those; `[MEASURED]` is a figure taken +> for this note, for the design on a synthetic fixture by a probe that is not in the repository +> (§11 says how, and which stage commits its harness), and from SN-1 on by a stage's committed +> harness, on a copy of an instance's store where its record says so; `[INFERENCE]` is a design +> call with a named falsifier; `[HYPOTHESIS]` is a claim nothing here checks, with what would +> check it named. Code claims were read on `origin/main` at `e3e3ee47`. The article +> `papers/2026-11-10-temporal-snapshot/paper.tex` states the same theorems with proof sketches +> and the references. > > Two things were added on 2026-11-11, after the design was merged, and each is marked where it > stands. The owner decided what a retire does to the past (D3, §6.2), against the @@ -53,7 +55,11 @@ warrant: null > instance's catalog (§11, `docs/experiments/landing-log-2026-11-11.md`). Where the build > departed from §3.2 the section says so where it stands: the key of a path takes half of its > key from the instance's secret, outside the file; a path that changes class leaves its chain -> by a sixth kind, `leave`; and the genesis writes a renamed path's tombstone as a `move`. +> by a sixth kind, `leave`; and the genesis writes a renamed path's tombstone as a `move`. The +> review of the build added three things, each marked where it stands: a purge by digest empties +> the tombstones of a path none of whose versions keeps its content (§6.1); the first open writes +> the genesis for a reader too, which is open for the owner (§12, SN-1); and every head costs +> what building the answer costs, which meets SNF-6 (§4.2, §11). ## 1. Purpose and scope @@ -387,7 +393,9 @@ into another that already has rows (`scripts/migrate_provenance_split.py:58-61`) chain has an integer id that is never reused or changed, and a row of a `landing_chains` table gives the class it holds now. A relabel rewrites that label and no row of the log; after a merge a class has two chains, and the read of a class is the union of its chains' reads. `[THEOREM -for the control; INFERENCE for the id]` +for the control; INFERENCE for the id]` As built at SN-1 the ids are given once while the log's +tables stand: the rollback drops them, and the genesis after it numbers its chains from 1 again +(§12, SN-1), which SN-3's fresh identity must not rest on (§6.2). **A position is a number the store keeps, never the row numbering it happens to have.** The chat log and the attestation ledger are keyed by text, and SQLite numbers their rows as the largest @@ -485,10 +493,15 @@ and it is the one name a purged row keeps, so a hole still shadows the path's ea landing-log secret, which is never in the file. The design had the chain's bytes alone; SN-1 takes the secret as the repository takes every instance's secret, from the environment through `get_secret`, Keychain-backed in the owner's setup and the instance's own item under a named -instance (`landing-log-key`, `.landing-log-key`), so the file alone cannot test a guess of a -purged path. Without the secret the genesis and every write refuse, loudly, and write nothing; a -secret that is not the one a chain was written with is refused by the chain's `key_check`; a read -needs it only to seek by path. `version` and `att_head` are the two fields a caller supplies: +instance (`landing-log-key`, `.landing-log-key`), so the key a hole keeps cannot be tested +against a guess of the path without the secret. Whatever appends a row or seeks a path's rows by +their key needs it: without it the genesis, a `record` or a `tombstone` that changes the map, the +re-key and `remove` refuse, loudly, and write nothing, and so do the two reads by path, +`state_at` and `history_at`. A relabel and a purge by digest need none, since they append no row +and find their rows by the label, the digest, the names they carry and the keys the emptied rows +keep; nor does a write that changes nothing, or a read of positions. A secret that is not the one +a chain was written with is refused by the chain's `key_check`. `version` and `att_head` are the +two fields a caller supplies: `record` gains a `version` argument, passed by the writer's last step from the version it just appended or found (`writer.py:408-419`, `:433`; `sync.py:201`) and left out where the place keeps no chain; `att_head` is the attestation ledger's head read inside the key's transaction, after the @@ -503,7 +516,10 @@ is the one `tombstone` would write: a `move` where another active path holds the `retire` otherwise (the design said `retire` for every one, which would count a renamed path among the identities that run across a retire, §6.2). The order inside the block is not history, so the positions before the `horizon` are under it (§8). A class that first appears later opens its chain -at its first landing, with a `genesis` and a `horizon` and nothing between. +at its first landing, with a `genesis` and a `horizon` and nothing between. As built, the genesis +is written by whichever process opens the catalog first, a reader's included, so that open needs +the secret and holds the write lock while it writes (§12, SN-1, where what this changes is +stated and left to the owner). The catalog is then the fold of the log: each path's last event (`stateOf`) in the chain that holds its present, the one where its last event is not a `leave`; an active row for a `store`; a @@ -913,6 +929,15 @@ corpus instance has one from the start: ten million items are ten million events An instance of a few thousand notes never needs it. `[THEOREM for the journal; INFERENCE for the threshold, falsifier SNF-6]` +As built at SN-1 the cost is the other way round (§11). `heads_at` builds a row in Python for +each head it returns, 3.5 to 3.9 µs a head, against a walk of 0.14 to 0.15 µs an event, so the +size of the answer and not the part of the log walked is the cost, and the read from the log +alone passes a tenth of a second near 27,000 heads: a chain of 30,002 events takes 0.11 s. That +meets SNF-6's first condition. Kept heads at a recorded cut shorten the walk and leave the +building, so they do not answer it. Before SN-4 builds the universe's nodes on this read, either +the threshold moves or the read changes so that it builds less than a row a head, and which is +open (SN-c). `[MEASURED §11; the decision open]` + ### 4.3 What the reads cost in bytes On the fixture a landing is 434 bytes in the log with its indexes when the identity is the path @@ -1186,10 +1211,21 @@ content. `[THEOREM: SNP-9 for the chain; DERIVED for the salt]` What stays, and the rows that keep their keys, so nulling it would hide nothing. - `att_head`: a position on another chain. -The hole is thus still tied to its path while another row of the path keeps the name, which is -the intent: the purge is of a digest, and the path with its other versions is not erased. When -every row of a path is emptied no row names the path. The bookmark goes because nothing looks a -landing up by its date, and a date on a hole says when the erased content arrived. +The hole is thus still tied to its path while another version of the path keeps its content, which +is the intent: the purge is of a digest, and the path with its other versions is not erased. When +no version of the path keeps its content, its other rows, its `retire`, its `move` and its `leave`, +name nothing that is not erased, so they are emptied with the last version, and no row names the +path, its identity or the date of its delete (D14). As built at SN-1, after review: `remove` +empties every row of the path; `remove_digest` empties the rows of the digest and then, for each +path they named, the path's other rows in every chain when none of its `store` rows keeps its +content, finding them by the names they carry and the keys the emptied rows keep, so a purge needs +no secret. That is `purge_raw`'s usual case, a note deleted and then purged, whose `retire` had +kept its path, its identity and its date before. The bookmark goes because nothing looks a +landing up by its date, and a date on a hole says when the erased content arrived. The bytes +SQLite frees when a row is emptied stay in the file until it is vacuumed, as the catalog's deleted +row's do (§11); a file copied before then holds them, and clearing them is SN-3's reach. +`[MEASURED for the bytes, by a probe of the build: the purged path in the freed pages after the +purge and a checkpoint, and in none after a vacuum, which the stage's test checks]` That is a rule the record already has: no tombstone keeps a content hash of purged private text, and for prose privacy outranks lineage (`docs/design-notes/vector-membership-store.md:810-813`). @@ -1287,7 +1323,13 @@ the hole that closed it. A position is given once, so the name is new. It is a f rows already written, so a landing repeated after a crash before its key takes the identity the first attempt took and appends no second version (ING-7). It differs from its path, so `landings_doc` indexes it (§3.2), and R6's refusal of an identity that another active path -holds applies to it as to a declared one. +holds applies to it as to a declared one. As built at SN-1, a position is given once only while +the log's tables stand: the rollback drops them and the next genesis numbers chains and positions +from 1 again (§12, SN-1), while the version chains, in their own file, keep their rows. A name +made after a rollback could then be one made before it, and its version chain would already hold +the earlier note's versions. SN-3 decides, before it names any identity, what closes that: a +high-water mark of chain ids kept outside the tables a rollback drops, or a name a rollback cannot +repeat. On the model a chain of landings and retires at paths is keyed again by identity (`lives`): the path with the number of the path's retires before the event. `[THEOREM: SNP-1, SNP-7]` @@ -1302,8 +1344,10 @@ path with the number of the path's retires before the event. `[THEOREM: SNP-1, S (`landingsAt_lives_of_retire`), and at a cut inside the chain it is unchanged by any growth (`landingsAt_lives_append`). Under the stricter seal the same retire emptied it. -What the model leaves to the code: the name of an identity, an identity a note declares, and a -rename, which moves an identity between paths. The retire is by identity and not by path, so a +What the model leaves to the code: the name of an identity, an identity a note declares, a +rename, which moves an identity between paths, and a life closed by a hole: the rule above takes a +path whose rows a purge emptied as closed (§6.1), and `lives` counts retires only, so that case is +an obligation of SN-3's tests and no theorem. The retire is by identity and not by path, so a rename retires nothing: the old path's tombstone is a `move` (§3.2). A new note written at a path a rename left is a first bind like any other, which closes the second case of §2.3's item 8, where today it takes the identity that moved. @@ -1320,7 +1364,11 @@ path a rename left is a first bind like any other, which closes the second case `trace` of a returned note starts at its return. Under the stricter seal the same event sealed every note's past until the owner lifted it. A note that declares its identity is the exception by its own statement: it binds that identity again when it returns, and its - history at a cut is all its landings inside the cut, on both sides of the retire. Joining + history at a cut is all its landings inside the cut, on both sides of the retire. The + decision as the owner stated it names no exception; this one is the design's reading of it, + for the owner to confirm, and it holds for any note that declares the retired identity, since + R6 binds a declared identity that no active path holds (`core/ingest/writer.py:448-462`). + `[INFERENCE, falsifier SNF-17]` Joining two identities of one path is not designed here: the owner-gated re-key (`catalog.py:210-241`, `core/stores/versions.py:132`) refuses to merge two chains. It is parked as SN-l, with SNF-10 as its re-entry. @@ -1331,8 +1379,15 @@ path a rename left is a first bind like any other, which closes the second case the ones it inherited included: the log's commitments cover the identity of every row, and the versions store has no write that splits a chain. From the stage that builds the rule on, no chain continues across a retire unless the note declares it. The stage's migration counts - the identities that have a `store` after a `retire` in the log, so the owner knows how many - histories at the head still run across a delete. + the identities that have a `store` at a path after that path's `retire` in the log, which is + what the log has recorded since its genesis, and no more. The genesis writes a path's present + as one `store`, so an identity that inherited before the log is not counted; where such an + inheritance could be found, if anywhere, is the version chains read against the catalog's rows, + and this note has not established that any store marks a delete before the log. Nor does the + count see §2.3's second case: a note landed at a path a rename left is a `store` after a + `move`, and the identity it inherits is then held by two active paths, which the catalog shows + at the head. So the count tells the owner how many histories run across a delete the log + recorded, not how many inherit. **At the head.** `trace` of a note written at a path with a past starts at that note's first landing, where today it runs back through the deleted note's versions. This is the one change @@ -1387,8 +1442,10 @@ Two consequences for the surface. An answer names the cut it read on the chains names and on no other, and the bounds a row records (§3.5) are never shown: `att` mixes every class, so its positions count other classes' landings. And a class is a row's class now: a whole-class relabel changes the label of a chain, and a row moves between chains only by a -`move` and a `store` (§3.2), after which its earlier events stay under the class they had -(ING-17). `[DERIVED]` +`leave` and a `store` (§3.2; the design had a `move`, and SN-1 made it a kind of its own), after +which its earlier events stay under the class they had (ING-17). A relabel itself moves a whole +chain to another class, so a read by class at a past cut follows the chain's class now, while a +read by chain is unchanged (§10, SNP-1's test). `[DERIVED]` ### 6.4 A reader that is shown only named endpoints @@ -1782,16 +1839,23 @@ passes to the code only as an obligation of the stage that transcribes it. the cut (`Witness.present_not_appendInvariant`); a read at a cut past the head (431, 487, 488); the history a seal serves, which a later retire empties (`Witness.seal_empties_history`, 522). Attacks 430, 432, 446, 521, 527. The test, at SN-1: over random sequences of catalog writes, - `read_at(chain, c)` and `state_at` of every path at `c`, taken after every further write, equal - the ones taken when `c` was the head. + `read_at(chain, c)` and each path's last event in each chain at `c`, taken after every further + write, equal the ones taken when `c` was the head, up to the holes a later purge leaves; so does + `state_at` of every path over a class while the class's chains are the ones it had. A relabel is + not in the model (below): it moves a whole chain to another class, so a read by class at a past + cut follows the chain's class now (§6.3), and across one the test compares chain by chain. - **SNP-2 monotonicity.** The read at an earlier cut is a prefix, chain by chain, of the read at a later one, and a cut of a cut is the meet (`readAt_mono`, `mem_readAt_of_le`, `readAt_readAt`, `head_readAt`, `visible_mono`), the history of an identity at an earlier cut is a prefix of its history at a later one (`landingsAt_mono`), and the filtered read of SNP-8 grows with the cut (`Kept.mono`). Controls: the read at one cut taken for a prefix of the read at any other (434); a cut of a cut - taken for the join (500). Attacks 433, 435, 515. The test, at SN-1: for `a ≤ b`, - `read_at(chain, a)` is a prefix of `read_at(chain, b)`. + taken for the join (500). Attacks 433, 435, 515, and 523, whose second half is + `landingsAt_mono`'s (its first is SNP-7's). The test, at SN-1: for `a ≤ b`, + `read_at(chain, a)` is a prefix of `read_at(chain, b)`, and a path's history, chain by chain. + Across two chains of one class, which only a change of class and a relabel make, `history_at` + orders the chains by a rule of the prefixes, the ones the path left first, and the read at an + earlier cut need not be a prefix of the later one; the stage's test pins that rule. - **SNP-3 composition.** The read at `a` followed by the read between `a` and `b` is the read at `b`, and two adjacent reads-between compose (`readAt_append_readBetween`, `readBetween_append`); a fold continued from a checkpoint over the delta is the fold of the prefix @@ -1868,10 +1932,12 @@ passes to the code only as an obligation of the stage that transcribes it. instance's files finds the purged words; after a purge of an old version of a live path, the read of the path at a cut where that version was the head is a hole, by all three reads; after a retire every read at a cut before it, of the identity's value and of its history, returns what it - returned before the retire; a new note landed at the path has an identity no earlier row carries, - no read of its history, at the head or at any cut, returns a version from before the retire, and - the retired identity's history at every cut is what it was; a landing at a retired path repeated - after a crash before its key takes the identity the first attempt took. + returned before the retire; a new note that declares no identity, landed at the path, has an + identity no earlier row carries, no read of its history, at the head or at any cut, returns a + version from before the retire, and the retired identity's history at every cut is what it was + (a note that declares the retired identity takes it back, §6.2, SNF-17); a landing at a path a + purge emptied takes a fresh identity as well, which `lives` does not model; a landing at a + retired path repeated after a crash before its key takes the identity the first attempt took. - **SNP-8 resolution.** Every frontier resolves to exactly one greatest consistent cut under it, monotonically; a consistent cut stays consistent as the store grows; a cut consistent for a recorded bound on the references is consistent for the true ones (`exists_resolves`, @@ -1948,8 +2014,9 @@ does not change (§3.1). The hash's collision freedom and the commitment's bindi SNP-9 (`CollisionFree`, an injective `commit`), not theorems about SHA-256. The `horizon` event is not in the model of a keyed chain, and the owner's gate on a history window is the code's. The fresh identity is in the model as a count of a path's retires (`lives`); the name the code gives it, an -identity a note declares and a rename are not (§6.2). There is no single reader in the model that -applies the cut's resolution, the grant, the erasure and the history of an identity together: +identity a note declares, a rename and a life closed by a purge's hole are not (§6.2). There is no +single reader in the model that applies the cut's resolution, the grant, the erasure and the +history of an identity together: `shown` composes the grant and the erasure over one read, the history is stated on a keyed chain, and the resolution on cuts; the sentence's reader applies the resolution first, then `shown`, and no seal (§6.2), and that order is the code's to transcribe. The row filter of §3.5 is in the model as @@ -1961,17 +2028,19 @@ descent and its alternation with the floor, is attacked, not proved. ## 11. Measurements -Every figure measured for this note is from a synthetic fixture: a temporary directory or -in-memory stores built by the probe, the test suite's throwaway palace for the purge, and -nothing of any instance. The other figures the note uses are the repository's own records of an -instance, cited where they stand and graded `[ESTABLISHED]`: the attestation ledger's bytes a -row, the job rate, the citation store's rows and bytes, the plane's bytes an occupancy and the -curated table's bytes an atom (`docs/experiments/corpus-measurements-2026-11-07.md:94-107`, +Every figure measured for the design, before SN-1 was built, is from a synthetic fixture: a +temporary directory or in-memory stores built by the probe, the test suite's throwaway palace for +the purge, and nothing of any instance; SN-1's figures, below the table, are of the build on a +copy of the corpus instance's catalog. The other figures the note uses are the repository's own +records of an instance, cited where they stand and graded `[ESTABLISHED]`: the attestation +ledger's bytes a row, the job rate, the citation store's rows and bytes, the plane's bytes an +occupancy and the curated table's bytes an atom +(`docs/experiments/corpus-measurements-2026-11-07.md:94-107`, `docs/experiments/corpus-stage1-2026-11-07.md:416`, `core/reference_view.py:15-16`). Figures given as arithmetic are marked so where they stand. -The probes are short scripts and are not in the repository: this pull request changes no -Python, and the newest notes keep a harness under `eval/` with a record under +The probes are short scripts and are not in the repository: the design's pull request changed +no Python, and the newest notes keep a harness under `eval/` with a record under `docs/experiments/`. So these figures cannot be repeated from the tree as it stands. Each stage of §12 commits the harness of what it builds with its record: SN-1 the log's size and reads (done: `eval/landing_log_bench.py`, measured on the corpus's catalog, below the table), SN-3 the @@ -1999,12 +2068,13 @@ the runs is given where they differed. `[MEASURED]` | row numbering | a table keyed by text, five rows, in a temporary file | after the last row was deleted the next insert was numbered 5 again; a vacuum after a delete in the middle kept the numbers | | an identity after a rename | an in-memory `VaultCatalog` at `f969904e`: a path recorded, a second path recorded with the first one's identity, the first tombstoned, then the first recorded again with no identity given, as the writer records a path that has a row (`core/ingest/writer.py:372`, `:409`) | the identity then has two active paths, the old one and the new one; added on 2026-11-11 for §2.3's item 8 | -Not measured: anything on an instance's own stores; the size of a recorded cut, of a chain table's -row and of a row of the log that a window emptied, which are arithmetic; how often a row of model -output is replaced; the lexical statistics computed from a mask at a corpus's size; the causal fiber -recomputed over a real instance's sessions, cold or warm; a vector search with superseded rows -joined to the heads at a cut; the reads of the chat log and the attestation ledger through their -chain tables; a retention pass. Each is the measurement of the stage that builds it. +Not measured for the design: anything on an instance's own stores, which SN-1 measured for the +log alone (below); the size of a recorded cut, of a chain table's row and of a row of the log that +a window emptied, which are arithmetic; how often a row of model output is replaced; the lexical +statistics computed from a mask at a corpus's size; the causal fiber recomputed over a real +instance's sessions, cold or warm; a vector search with superseded rows joined to the heads at a +cut; the reads of the chat log and the attestation ledger through their chain tables; a retention +pass. Each is the measurement of the stage that builds it. **Measured at SN-1, on a copy of the corpus instance's catalog (added 2026-11-11).** The log as built, by its committed harness (`eval/landing_log_bench.py`), on two copy-on-write clones of the @@ -2014,16 +2084,24 @@ Python 3.15.2 and SQLite 3.54.1 and other work running. `[MEASURED]` | probe | result | |---|---| -| the migration: the tables, their indexes and the genesis, one chain of 400,276 rows | 6.22 to 6.33 s; the file 162.7 MB before and 334.1 MB after, 429 bytes a row (the table 381, the key index 47, the other two empty); the fold of the log equal to the catalog row by row | -| `verify`, every commitment and hash from the first row | 3.05 to 3.07 s | -| the reads | `state_at` of one path at the middle cut 14.3 to 14.8 µs, 1.6 of them the keyed hash; `history_at` at the head 14.7 to 15.7 µs; `read_at` and `read_between` of 1,000 positions 3.3 to 3.4 ms, the rows built in Python; `heads_at` 0.15 s at a tenth, 0.79 to 0.80 s at the middle and 1.6 s at the head, of which the walk in SQL is 6 ms, 26 ms and 54 to 57 ms | -| a key's write in a batch of 10,000, with the log and without | a new path 48.9 to 49.0 µs against 6.8; a new version of a held path 106.0 to 106.5 against 37.9 to 41.2: 42 and 65 to 69 µs added, 0.1 to 0.2 percent of a lazy landing's 31 ms (`docs/experiments/two-phase-ingestion-2026-11-07.md`) | - -Two findings came out of it. The update that writes a row's closing stamp took the primary key and -walked the chain, about 40 ms a landing at this size, until it named the key index as the seeks do -(§4.1); a test now asks the plan of every statement by path to name it. And every head at the head -of a chain of 400,274 events is 1.6 s, past §4.2's tenth of a second, the walk itself at 0.14 µs an -event: the corpus's chain is the one §4.2 says keeps heads at recorded cuts from SN-4 on (SN-c). +| the migration: the tables, their indexes and the genesis, one chain of 400,276 rows | 6.71 to 6.73 s; the file 162.7 MB before and 334.1 MB after, 429 bytes a row (the table 381, the key index 47, the other two empty); the fold of the log equal to the catalog row by row | +| `verify`, every commitment and hash from the first row | 3.07 to 3.08 s | +| the reads | `state_at` of one path at the middle cut 13.7 to 16.5 µs, 1.6 to 1.7 of them the keyed hash; `history_at` at the head 15.5 to 18.9 µs; `read_at` and `read_between` of 1,000 positions 3.2 to 3.4 ms, the rows built in Python; `heads_at` 0.15 s at a tenth, 0.79 s at the middle and 1.62 s at the head, of which the walk in SQL is 6 ms, 29 to 30 ms and 59 to 60 ms | +| every head of a smaller chain, one class, landed through `record` | 30,000 paths 111 to 112 ms (the walk 4 to 5 ms); 100,000 paths 374 to 376 ms (the walk 15 ms): 3.5 to 3.6 µs a head returned beyond the walk | +| a key's write in a batch of 10,000: as built, with the log's rows switched off, and as `record` made it before SN-1 | a new path 55.7 to 57.4 µs, 10.4 to 10.5 and 4.6 to 4.7; a new version of a held path 119.1 to 120.3, 45.0 to 46.0 and 34.5 to 34.7: SN-1 adds 51 to 53 and 84 to 86 µs, the log's rows 45 to 47 and 74 of them, 0.16 to 0.28 percent of a lazy landing's 31 ms (`docs/experiments/two-phase-ingestion-2026-11-07.md`) | + +The load average was between 2.7 and 3.9. Three findings came out of it. The update that writes a +row's closing stamp took the primary key and walked the chain, about 40 ms a landing at this size, +until it named the key index as the seeks do (§4.1); a test now asks the plan of every statement +by path to name it. The savepoint each write in a batch takes, added after review so that a failed +write leaves neither of its rows (§12, SN-1), kept its journal in a temporary file and doubled a +key's write, 105 to 108 µs for a new path in two runs; the catalog's connection now keeps its +temporary store in memory, where the savepoint costs about 6 µs. And every head costs what +building the answer costs: the walk is 0.14 to 0.15 µs an event, against §4.2's quarter of a +microsecond on the fixture, but each head returned costs 3.5 to 3.9 µs more, in Python, so the read +from the log alone passes a tenth of a second near 27,000 heads, a chain of 30,002 events taking +0.11 s. That is SNF-6's first condition, met at SN-1, and kept heads do not remove it: a kept head +at a recorded cut shortens the walk, not the building of the answer (§4.2). ## 12. The build order @@ -2047,18 +2125,42 @@ property-testing the transcription against the Lean statements; the laws a stage `writer.py:419`, `:433` and `sync.py:201`. `att_head` is `NULL` at this stage. `relabel_provenance` rewrites the label in `landing_chains` and no row of `landings`. `remove` and `remove_digest` empty the log's rows of the path or of the digest as §6.1 - says, the key kept, so the purge's effect on the log is this stage's and not SN-3's. + says, the key kept, so the purge's effect on the log is this stage's and not SN-3's. As + built, after review: `remove_digest` also empties the other rows of a path none of whose + versions keeps its content (§6.1), and each write in a batch is a savepoint, so a write that + fails leaves neither of its rows when the batch's caller catches the error and goes on. - The reads, on `VaultCatalog`: `chains(class)`; `head(chain)`; `read_at(chain, c)`, the rows with `seq ≤ c` in order; `state_at(class, path, c)`, the path's last event at or under the - cut over the class's chains, which is a `store`, a `retire` or `move`, a hole, or nothing; + cut over the class's chains, which is a `store`, a `retire` or `move`, a hole, or nothing (as + built, a `leave` too, when the path's present is in a chain of another class at the cut); `history_at(class, path, c)`, its `store` rows at or under the cut; `heads_at(class, c)`, the `store` rows alive at the cut over the class's chains, a hole returned as a hole with its position and no name; `read_between(chain, a, b)`; and `verify(chain)`, which recomputes - the hashes from the first row and the commitment of every row that still has its salt. The + the hashes from the first row and the commitment of every row that still has its salt (as + built, it also fails a row without its salt that keeps any content a purge empties). The statements of `state_at` and `history_at` name `landings_path`. Here `c` is a position of a chain, or for a class one position a chain. - Nothing reads them yet, and no reader's behaviour changes. + As built, that last line holds once the log has its genesis and not before it. The genesis is + written by the migration, at the first open of a catalog that has rows and no log, and every + process that opens the catalog runs the migration, a reader's included (the MCP server, the + sentence's executor, the spine, the query modes and the launcher open it: + `agents/ambassador/mcp.py:74`, `core/sentence/execute.py:342`, `core/temporal/spine.py:373`, + `core/query.py:428`, `ops/lifecycle/launcher.py:1625`). So the first process to open the catalog + after the deploy writes the genesis: it needs the secret, raising `LandingLogKeyMissing` without + it, and it holds the write lock for the genesis, about six seconds on the corpus's catalog, while + any other opener waits up to two minutes. After the genesis a reader needs no secret and opens + as fast as before; a writer needs it for every write that appends a row (§3.2). So §3.2's rule, + that the genesis refuses loudly without the secret, and the line above, that no reader's + behaviour changes, cannot both hold while every open runs the migration, and which gives way is + the owner's to decide before SN-1 is deployed: + the genesis written by a writer's first write, or by an owner-run migration, with an open that + lacks the secret skipping it; or SN-1 stated as changing what the first open needs, with every + process, the daemon's plists included (`ops/lifecycle/com.mind-palace.palace.plist`, its daemon + twin), run with the secret in its environment. Until then the runbook's §0 makes the secret a + precondition of the deploy. + Tests, in `tests/property/test_landing_log.py`: SNP-1 to SNP-5 as §10 states them, over random sequences of catalog writes that include retires, renames, relabels and purges; the catalog equals the fold of the log after every write, a purge included; a `record` that @@ -2078,7 +2180,10 @@ property-testing the transcription against the Lean statements; the laws a stage that stops writing them and resumes later appends a `horizon`. As built, the resumption is a new genesis on the dropped tables, which ends at its `horizon`: a build without the log that wrote the catalog while the tables stayed would leave the log behind the catalog, and nothing - detects that yet, so the rollback drops them (`docs/runbook.md` §0). + detects that yet, so the rollback drops them (`docs/runbook.md` §0). The new genesis numbers + its chains and positions from 1 again, so a chain id and a position are given once only while + the tables stand; nothing at SN-1 relies on more, and SN-3's fresh identity, which is named by + a position, must (§6.2). - **SN-2 cuts.** The chain tables, each with its running hash and its genesis followed by a horizon, for `chat`, `att`, `staging` and `runs`; `att_head` filled from then on; on the chain-table row of a pass attestation and of a run, the landing chains that held its inputs and the head of each, and @@ -2110,7 +2215,9 @@ property-testing the transcription against the Lean statements; the laws a stage The fresh identity is this stage's for three reasons. It changes what the writer admits and what `trace` returns at the head, and D12 licenses a change of behaviour with its own pull - request, where SN-1 adds tables and changes no behaviour. It needs the log: the name is the + request, where SN-1 adds tables and changes no answer any read gives (what it does change, + what a process needs at the first open and to write, is SN-1's item as built). It needs the + log: the name is the position of the path's last event, which exists from SN-1. And it has to be in force before any history is read at a cut, which is SN-4, so that no reader of a history is built on identities that inherit; SN-3 is the stage already ordered before SN-4 for removal, and with @@ -2290,7 +2397,9 @@ give, and what each alternative costs is the answers it changes, which the entry past cut a file that was tracked then and is not now, which the head withholds, and makes the grant a function of the cut. 12. **D12, what the merge licenses.** Recommended: SN-1 and SN-2. SN-1 adds tables and changes no - reader. SN-2 adds tables, columns and names; the one behaviour it changes is that a name which + reader's answer; as built it changes what a process needs at the first open of a catalog and + to write it, the secret, which §12 states and leaves to the owner. SN-2 adds tables, columns + and names; the one behaviour it changes is that a name which resolves to nothing is refused on an instance whose reference store is empty, where today it is answered (§2.1). SN-3 to SN-8 change an erasure, the identity a landing takes, the universe and what an instance keeps, and each is licensed with its own pull request. The alternative, all @@ -2307,7 +2416,9 @@ give, and what each alternative costs is the answers it changes, which the entry its position (§6.1), 47 bytes a row of index on the fixture. The alternatives: keep the path, which saves the hash and leaves a purged note's name readable in the log when every version of it is purged; or keep no key, after which a read by path at a cut returns the - version before the purged one (`Witness.keyless_hole`). + version before the purged one (`Witness.keyless_hole`). As built at SN-1, the purge empties + a path's tombstones with its last version, which the recommendation needs: a `retire` that + kept its path would leave the name readable as the first alternative does (§6.1). ## Parked decisions @@ -2315,7 +2426,7 @@ give, and what each alternative costs is the answers it changes, which the entry |---|---|---|---| | SN-a | the cadence of recorded cuts | a trough that moved, the owner's command | a date that resolves to a cut farther from it than a declared tolerance | | SN-b | the citation readings as rows valid over a range of commits | append-only rows a commit, stamped with their projection | the store's size on an instance | -| SN-c | the heads kept at some recorded cuts | none for a chain under 250,000 events; kept, from SN-4, for a chain over it (§4.2) | `heads_at` past a tenth of a second on a chain under the threshold, or under it by a wide margin on one over | +| SN-c | the heads kept at some recorded cuts | none for a chain under 250,000 events; kept, from SN-4, for a chain over it (§4.2) | `heads_at` past a tenth of a second on a chain under the threshold, or under it by a wide margin on one over; met at SN-1, 0.11 s on a chain of 30,002 events, the cost the building of the answer (§4.2, §11), so this re-enters before SN-4 | | SN-d | a second embedder identity's vectors kept beside the first | none: the present's identity | dn-two-phase-ingestion's open question 4 | | SN-e | lexical statistics stored per class and per recorded cut | computed from the mask | a lexical query at a past cut over its budget | | SN-f | `repo` as a graph of commits, and a chain a repository | the line of the branch the sensor reads, one repository | an instance whose history has merges or that reads several repositories | @@ -2345,7 +2456,10 @@ give, and what each alternative costs is the answers it changes, which the entry - **SNF-6 (the threshold for kept heads is wrong):** `heads_at` past a tenth of a second on a chain under 250,000 events, or the kept heads costing more than the read they save on one over. Then the threshold moves; on the fixture the read from the log alone passes a tenth of - a second between 100,000 and 500,000 events (§4.2). + a second between 100,000 and 500,000 events (§4.2). Met at SN-1: as built every head costs 3.5 + to 3.9 µs a head returned, and a chain of 30,002 events reads them in 0.11 s (§4.2, §11). Since + kept heads leave that cost, moving the threshold alone does not answer it; the read's shape is + open with SN-c. - **SNF-7 (the mask is too slow for the lexical statistics):** a lexical query at a past cut over its budget at the instance's size. Then SN-e; the rule that the statistics are the mask's does not change. @@ -2381,6 +2495,10 @@ give, and what each alternative costs is the answers it changes, which the entry missed, is outside the cut or withheld. Then the list of §3.5 is incomplete or a reader goes around the filter, and the stage that reads that store at a cut does not land until it is closed. +- **SNF-17 (a declared identity is taken back by another note):** after a retire, a note that is + not the retired one declares the retired identity, as a copied front matter would, and its + history at the head holds the retired note's versions. Then the exception of §6.2 for a note + that declares its identity is reopened with the owner (D3); the retire stays unsealed. ## Open questions From 204cee087f76ec38ffe6449dc036664b1fba0a2f Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:07:35 -0500 Subject: [PATCH 20/30] docs(runbook): what the landing log's secret is needed for Section 0 said a process that writes the catalog refuses without the secret and a read needs none once the genesis is written. As built, the first open of a catalog that has no log writes the genesis whichever process opens it, a reader included, and holds the write lock for it; after that, the writes that append to the log and remove need the secret, while a relabel, a purge by digest, a write that changes nothing and every read but the log's two reads of one path do not. The section and the secrets table say so, with every process that opens the catalog under the wrapper, the daemon first, and the open question of moving the genesis off the first open. It also says that a rollback's new genesis numbers chains from 1 again, and that SQLite keeps the bytes a purge frees until a vacuum. The wrapper's comment follows. Co-Authored-By: Claude Opus 5.5 --- docs/runbook.md | 26 ++++++++++++++++++-------- scripts/run_with_secrets.sh | 3 ++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/docs/runbook.md b/docs/runbook.md index a0f65156..8d5bbc87 100644 --- a/docs/runbook.md +++ b/docs/runbook.md @@ -436,12 +436,19 @@ fail-closed where it matters (see §1). Place only the ones whose layer you're t **One secret has no switch: the landing log's** (`landing-log-key`; dn-temporal-snapshot §3.2, stage SN-1). The catalog keeps its past in two tables of its own file, and every row names its path -by a keyed hash whose key is this secret, so the file alone cannot be tested against a guess of a -purged path. The first open of a catalog that has rows writes the log's genesis, and every write of -the catalog appends to the log, so a process that writes the catalog refuses to, loudly, without -the secret (`LandingLogKeyMissing`), and writes nothing; a read needs no secret once the genesis is -written. Place it before deploying the build that brings the log, and run the daemon under the -wrapper above (it carries the item), or the daemon stops at its first open: +by a keyed hash whose key is half in the file and half this secret, so the key a purged row keeps +cannot be tested against a guess of the path without it. The first open of a catalog that has rows +and no log writes the log's genesis, whichever process opens it, a reader included, so that open +needs the secret and holds the catalog's write lock for the genesis (six seconds on a catalog of +400,000 items) while other openers wait. After that, every write that appends to the log needs the +secret: a `record` or a `tombstone` that changes the catalog, the owner's re-key, and `remove`, +which finds a path's rows by their key. Without it they refuse, loudly +(`LandingLogKeyMissing`), and write nothing. A relabel, a purge by digest and a write that changes +nothing need no secret, and nor does a read, except the log's two reads of one path +(`state_at`, `history_at`), which nothing calls yet. Place it before deploying the build that +brings the log, and run every process that opens the catalog under the wrapper above (it carries +the item), the daemon first, or the first of them to open the catalog stops there. Whether the +genesis should move off the first open is open with the owner (dn-temporal-snapshot §12, SN-1): ```sh openssl rand -hex 32 # 32 random bytes, as hex @@ -452,7 +459,10 @@ A named instance reads `.landing-log-key`, and the wrapper refuses a named i instance's process must be given the item under its own name. The secret is not recoverable from the log: a lost one leaves the log unwritable (`LandingLogKeyMismatch` for any other value), so keep it with the attestation keys. A rollback to a build without the log drops the two tables -(`landing_chains`, `landings`); the next open of a build with the log writes a new genesis. +(`landing_chains`, `landings`); the next open of a build with the log writes a new genesis, its +chains numbered from 1 again. A purge empties the log's rows of what it removes, but SQLite keeps +the bytes it frees in the file until a `VACUUM`, so a copy of the file taken before one still holds +them. ### 1. Attestation signing keys — turn on the signed runtime-proof layer @@ -627,7 +637,7 @@ is Phase 5 (the bridge holding its own identity). On a single-user Mac with SSO | `attestation-signing-key` | Keychain | `build_attestor` (supervisor signer) | signs all non-gate attestations | | `attestation-owner-key` | Keychain | `build_attestor` (owner signer) | signs **gate decisions only** | | `vault-supervisor-token` | Keychain | `build_secrets_backend` | mints scoped child tokens; reads no role secret | -| `landing-log-key` | Keychain | `VaultCatalog` (`core/stores/landings.py::landing_log_key`) | keys the landing log's hash of a path; every catalog write needs it | +| `landing-log-key` | Keychain | `VaultCatalog` (`core/stores/landings.py::landing_log_key`) | keys the landing log's hash of a path; the log's genesis at the first open and every catalog write that appends to the log need it | | `vault-unseal-key` / `vault-root-token` | Keychain | the unseal LaunchAgent / you | bootstrap Vault itself | | `kv/oura-daily-aggregates` | Vault kv-v2 | `dreamer`, `correlator` tokens | biometric aggregates | | `kv/oura-api-token` | Vault kv-v2 | `bridge`, `advisor` tokens | Oura API | diff --git a/scripts/run_with_secrets.sh b/scripts/run_with_secrets.sh index 816b2e91..dc47a533 100755 --- a/scripts/run_with_secrets.sh +++ b/scripts/run_with_secrets.sh @@ -10,7 +10,8 @@ # A secret you haven't provisioned yet resolves to empty — which is falsy, so the layer that needs # it stays fail-closed (e.g. [attestation] enabled = true with no key is a hard error). Place only # the ones whose layer you've turned on. The landing log's secret is the exception: the catalog's -# log has no switch, so a process that writes the catalog refuses to without it (runbook §0). +# log has no switch, so the first process to open a catalog that has no log yet, and any process +# that writes the catalog, refuses to without it (runbook §0). set -eu # These are Ouroboros's items. A named instance (MIND_PALACE_OVERLAY, DI-2) reads its own, From bf191d1fb07f04f4bbe32bfc89d1e042cd36528d Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:09:20 -0500 Subject: [PATCH 21/30] docs(formal): which controls are statements, and seed 523 under SNP-2 The statements' module docstring said each law's controls are among its statements; only SNP-1's two and SNP-5's one are theorems there, and the other controls of the five laws are refuted attacks in PalaceTest/Snapshot.lean. It now says so. Seed 523's second half attacks landingsAt_mono, which SNP-2's row cites, but its comment filed the whole attack under SNP-7: the comment names both laws, and formal/README.md's SNP-2 row lists the seed. No declaration or statement changed. Checked under the 4 GB cap: the source check, the Palace and Spec builds, lake test (seed 523 among the attacks that survive 500), the mk_all checks, the sorry budget, the escape grep and the ledger cross-reference (105 rows, 381 cited, 92 markers, 375 statements). Co-Authored-By: Claude Opus 5.5 --- formal/PalaceTest/Snapshot.lean | 4 ++-- formal/README.md | 2 +- formal/Spec/Snapshot.lean | 11 ++++++----- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/formal/PalaceTest/Snapshot.lean b/formal/PalaceTest/Snapshot.lean index 1ebc1521..a1680399 100644 --- a/formal/PalaceTest/Snapshot.lean +++ b/formal/PalaceTest/Snapshot.lean @@ -727,8 +727,8 @@ retire of the key included. -/ (historyAt (l.map ev ++ t.map ev) (min c l.length) x == historyAt (l.map ev) (min c l.length) x) = true) 522 -/- SNP-7: the history with no seal ends with what the stricter seal serves, and the history at -an earlier cut is a prefix of the history at a later one. -/ +/- SNP-7 and SNP-2: the history with no seal ends with what the stricter seal serves (SNP-7), +and the history at an earlier cut is a prefix of the history at a later one (SNP-2). -/ #eval survives (∀ (l : List (Fin 9)) (c d : ℕ) (x : Fin 3), ((historyAt (l.map ev) c x).isSuffixOf (landingsAt (l.map ev) c x) && (landingsAt (l.map ev) (min c d) x).isPrefixOf (landingsAt (l.map ev) d x)) = true) 523 diff --git a/formal/README.md b/formal/README.md index b8a0924b..3fd1b08f 100644 --- a/formal/README.md +++ b/formal/README.md @@ -509,7 +509,7 @@ Roundoff and FloatModel, so it has no statements of its own): | UTL-6 | with the use `K`-Lipschitz in the field and `K < lam`, the loop contracts the sup metric by `1 − lam + K` and has one stationary field; at `K ≥ lam` the ceiling is a second fixed point | proved; the contraction survived 500 | | the regimes | the two-site mean field's ratio moves apart at exponent 2, holds at 1, moves to one at 0; the greedy walk never leaves two nodes of the three-node path | proved; the three exponents survived 500 as one attack, the greedy walk 500 | | SNP-1 | a read at a cut inside the store, a read between two such cuts and every derived view are unchanged by any growth; so are the reads under an erasure and a grant, the keyed state and its generations, the history of a key with no seal and of an identity by its lives, and the filtered read | proved; attacks survived 500 each (seeds 430, 432, 446, 521, 527); the controls refuted, the reader that ignores the cut and the seal's history also as theorems | -| SNP-2 | the read at an earlier cut is a prefix of the read at a later one, and a cut of a cut is the meet; so for the visible read, the history with no seal and the filtered read | proved; attacks survived 500 each (seeds 433, 435, 515); the controls refuted | +| SNP-2 | the read at an earlier cut is a prefix of the read at a later one, and a cut of a cut is the meet; so for the visible read, the history with no seal and the filtered read | proved; attacks survived 500 each (seeds 433, 435, 515, and 523, whose second half is SNP-2's); the controls refuted | | SNP-3 | the read at `a` and the read between `a` and `b` compose to the read at `b`, so a fold continued over the delta is the fold of the prefix; a key the delta does not write keeps its state | proved; attacks survived 500 each (seeds 436, 438, 439, 447, 475, 476); the controls refuted | | SNP-4 | a cut at or past the head reads the store, so every reading at the head is the present's | proved; the attack survived 500 (seed 440); the control refuted | | SNP-5 | a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; the generational read is the recomputed state and the last write, with at most one generation alive | proved; attacks survived 500 each (seeds 441, 442, 443); the controls refuted, the store rewritten in place also as a theorem | diff --git a/formal/Spec/Snapshot.lean b/formal/Spec/Snapshot.lean index 4f215931..b1416adb 100644 --- a/formal/Spec/Snapshot.lean +++ b/formal/Spec/Snapshot.lean @@ -17,11 +17,12 @@ between two cuts, a derived view as a derivation of the prefixes, a chain of key three ways (rewritten in place, recomputed from the prefix, kept by generation with a closing stamp), the grant and the erasure applied to one read, the history of a key with and without a seal, the identity a landing at a retired path takes (`lives`), and the filtered read of the -references a resolver does not follow (`Kept`). Each law's controls are among its statements. What -they leave out: the stores' SQL, the hash and the commitment of a row (SNP-9's, not stated here), -the class a chain holds and the relabel that rewrites it, and the identity's name in the code; -`core/stores/landings.py` is the transcription these laws are tested against -(`tests/property/test_landing_log.py`). +references a resolver does not follow (`Kept`). The controls that are theorems are among the +statements, SNP-1's two and SNP-5's one; the other controls of the five laws are refuted attacks +in `PalaceTest/Snapshot.lean`. What they leave out: the stores' SQL, the hash and the commitment +of a row (SNP-9's, not stated here), the class a chain holds and the relabel that rewrites it, and +the identity's name in the code; `core/stores/landings.py` is the transcription these laws are +tested against (`tests/property/test_landing_log.py`). SNP-6 to SNP-10 are not stated here: they are design theorems of `Palace/Snapshot.lean`, cited from the note until a stage of dn-temporal-snapshot §12 builds what relies on them. From 92888e424b2450775c1fb5a0128cbabd02aa7baa Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:09:46 -0500 Subject: [PATCH 22/30] docs(paper): the landing log's article after review, and the design's The landing log's article said a copy of the file cannot test whether a hole was a given path and that the holes reveal nothing to whoever copies it; as built, a purged note's retire kept its path until review changed the purge, and SQLite keeps the bytes a purge frees until a vacuum. It now says what a purge empties, what the key a hole keeps tells without the secret, and where the freed bytes go. It says which writes and reads need the secret and that the first open writes the genesis for a reader too, left to the design's owner. Its measurements are the new runs: the stage adds 51 to 86 us to a key's write against the write before it, and every head costs 3.5 to 3.9 us a head returned, which meets the design's falsifier for kept heads; the savepoint's journal found in a file is among what measuring found. Its account of the tests follows the suite (a relabel moves a chain to another class, so a read by class at a past cut follows it), with the seeded bugs. Nine pages, built clean. The design's article said the snapshot's theorems are not among the judged statements; SNP-1 to SNP-5 are, 47 of the 375, since the first stage. Its resolver resolves the repository sensor's attestation of a commit and filters a continuous-integration witness's, as the note's repair of the review's sixth finding has it. Co-Authored-By: Claude Opus 5.5 --- papers/2026-11-10-temporal-snapshot/paper.tex | 18 +- papers/2026-11-11-landing-log/paper.tex | 196 +++++++++++------- 2 files changed, 134 insertions(+), 80 deletions(-) diff --git a/papers/2026-11-10-temporal-snapshot/paper.tex b/papers/2026-11-10-temporal-snapshot/paper.tex index b7444265..84730cdf 100644 --- a/papers/2026-11-10-temporal-snapshot/paper.tex +++ b/papers/2026-11-10-temporal-snapshot/paper.tex @@ -371,10 +371,12 @@ \section{The design}\label{sec:design} date, which selects the last record whose wall bookmark is not later. Wall time is a lookup key there and orders nothing. The resolver follows three references, each through a recorded bound that is sound because there is one writer (\Cref{thm:lattice}): a landing's to the attestation -ledger, an attestation's to its commit, a record's to its frontier. A pass's attestation reads -landings too; resolved, it would lower the ledger and can take another landing chain down -(\lean{Witness.pass_drags}), so the filter of \Cref{thm:lattice} withholds it from the read, -and with it the rows of model output. +ledger, the repository sensor's attestation of a commit to that commit, a record's to its +frontier. A pass's attestation reads landings too; resolved, it would lower the ledger and can +take another landing chain down (\lean{Witness.pass_drags}), so the filter of \Cref{thm:lattice} +withholds it from the read, and with it the rows of model output. A continuous-integration +witness's attestation of a commit, which the commit ledger may not hold yet, is filtered the same +way and not resolved. \begin{algorithm}[t] \caption{The cut a read under \texttt{as of} is taken at. $S_k$: the positions chain $k$ serves. @@ -456,9 +458,11 @@ \section{Evaluation}\label{sec:eval} theorems, twenty of them the controls, no \lean{sorry}, and the axioms of all 5{,}250 library declarations audited (\lean{propext}, \lean{Classical.choice}, \lean{Quot.sound} only). The library's export, 56{,}231 declarations -from \lean{Init} up, is replayed by Lean's kernel and five independent checkers. These are -design theorems: no code relies on them yet, so they are not among the 328 statements the -library restates separately and judges against its ledger of laws. +from \lean{Init} up, is replayed by Lean's kernel and five independent checkers. The laws of +\Cref{thm:append,thm:compose,thm:forms}, SNP-1 to SNP-5, entered the ledger with the design's +first stage, the landing log: their 47 declarations are among the 375 statements the library +restates separately and judges against its ledger of laws. SNP-6 to SNP-10 remain design +theorems, which no code relies on yet. \paragraph{The attacks.} The definitions compute, so they are attacked as they are with property-based testing diff --git a/papers/2026-11-11-landing-log/paper.tex b/papers/2026-11-11-landing-log/paper.tex index 8760d19f..5a174be5 100644 --- a/papers/2026-11-11-landing-log/paper.tex +++ b/papers/2026-11-11-landing-log/paper.tex @@ -42,16 +42,17 @@ writes, so the catalog is the fold of the log and no caller can write one without the other. A row carries a salted commitment that a hash chain covers, so a purge empties a row and the chain still verifies; a row names its path by a keyed hash whose key is split between the file and a -secret outside it, so a hole still shadows the path's earlier versions, and the file alone cannot -test a guess of a purged path. The design takes two forms of removal: a retire leaves the item's +secret outside it, so a hole still shadows the path's earlier versions, the key it keeps cannot be +tested against a guess of the path without the secret, and once no version of a path keeps its +content no row names it. The design takes two forms of removal: a retire leaves the item's history readable at the cuts where it existed, and a purge leaves a hole at every cut. Five laws of the design (append invariance, monotonicity, composition, idempotence, and a derived view as a function of the prefixes) enter the store's ledger of laws as 47 statements machine-checked in Lean~4, and a property test checks the code's reads against them over random sequences of writes. -On a copy of a catalog of 400{,}274 items the migration that writes the log takes 6.3~s and -429~bytes a row, the log adds 42 to 69~$\mu$s to a key's write, and a read of one path at a cut -takes 15~$\mu$s. Measuring at that size also found a query plan that walked the whole chain on -every write. +On a copy of a catalog of 400{,}274 items the migration that writes the log takes 6.7~s and +429~bytes a row, the stage adds 51 to 86~$\mu$s to a key's write, and a read of one path at a cut +takes 14 to 19~$\mu$s. Measuring at that size also found a query plan that walked the whole chain +on every write, and that reading every head costs what building the answer costs. \end{abstract} \section{Introduction} @@ -201,8 +202,8 @@ \section{The model and the laws}\label{sec:laws} \section{The log as built}\label{sec:log} \paragraph{Tables.} -\lean{landing_chains} has one row a chain: an integer id never reused, the class it holds now, the -chain's 32 random bytes, and a key check. \lean{landings} has one row an event, keyed by +\lean{landing_chains} has one row a chain: an integer id given once while the tables stand, the +class it holds now, the chain's 32 random bytes, and a key check. \lean{landings} has one row an event, keyed by \lean{(chain, seq)}: its kind, the path's key, the path, the identity, the version number where the place keeps version chains, the digest and title of a landing, a horizon's position, a 16-byte salt, the commitment, the hash, the closing stamp, and a wall-clock bookmark that orders nothing. @@ -230,19 +231,28 @@ \section{The log as built}\label{sec:log} \paragraph{Commitments, holes and keys.} The commitment is SHA-256 over the salt and the canonical JSON of the row's fields; the hash is -SHA-256 over the previous row's hash and the commitment. A purge (\lean{remove} of a path, -\lean{remove_digest} of a digest) empties a row: the path, the identity, the digest, the title, -the salt and the bookmark go, and the position, the kind, the key, the closing stamp, the -commitment and the hash stay. The chain then verifies from its first row as before, and the -commitment, its salt gone, tests no guess. The row keeps its path's key because a purge is by -digest and may take an old version of a path that is still live: a hole that lost its key would -let a read by path return the version before it at a cut where the purged one was the head. The -key is $\mathrm{HMAC}(k_c, \text{path})$ with $k_c = \mathrm{HMAC}(K, \text{chain's bytes})$, -where $K$ is the instance's landing-log secret, read from the environment as the store reads its -other secrets and never written to the file. The design had the chain's bytes alone as the key, -in the same file as the rows; with $K$ outside it, a copy of the file cannot test whether a hole -was a given path. A missing secret refuses the migration and every write before anything is -written, and a chain's key check refuses a secret it was not written with. +SHA-256 over the previous row's hash and the commitment. A purge empties a row: the path, the +identity, the digest, the title, the salt and the bookmark go, and the position, the kind, the +key, the version, the closing stamp, the commitment and the hash stay. \lean{remove} empties every +row of a path; \lean{remove_digest} empties the rows of a digest, and then, for each path they +named, the path's other rows when none of its versions keeps its content, so no row names a path, +its identity or the date of its delete once its last version is purged. The chain then verifies +from its first row as before, and the commitment, its salt gone, tests no guess; a row without its +salt that keeps any of that content fails \lean{verify}. The row keeps its path's key because a +purge is by digest and may take an old version of a path that is still live: a hole that lost its +key would let a read by path return the version before it at a cut where the purged one was the +head. The key is $\mathrm{HMAC}(k_c, \text{path})$ with $k_c = \mathrm{HMAC}(K, \text{chain's +bytes})$, where $K$ is the instance's landing-log secret, read from the environment as the store +reads its other secrets and never written to the file. The design had the chain's bytes alone as +the key, in the same file as the rows; with $K$ outside it, the key a hole keeps cannot be tested +against a guess of the path from the file alone. The bytes SQLite frees when it empties a row stay +in the file until it is vacuumed, as a deleted row's do, so a copy taken before then holds them; +clearing them is the deep form's reach in a later stage. Whatever appends a row or seeks a path's +rows by their key needs $K$: without it the migration's genesis, a write that changes the map, a +re-key, \lean{remove} and the two reads by path refuse before anything is written. A relabel and a +purge by digest need none, since they append no row and find their rows by the label, the digest, +the names and the keys the emptied rows keep. A chain's key check refuses a secret it was not +written with. \begin{algorithm}[t] \caption{A landing of \texttt{path} in class \texttt{cls}, inside the catalog's transaction.} @@ -268,7 +278,8 @@ \section{The log as built}\label{sec:log} \end{algorithm} \paragraph{The genesis.} -On the first open of a catalog that has rows and no log, each class gets a chain: a +On the first open of a catalog that has rows and no log, by whichever process opens it first, a +reader's included, each class gets a chain: a \lean{genesis}, the catalog's rows of the class in path order, an active path as a \lean{store} and a tombstoned one as a \lean{store} followed by its tombstone, then a \lean{horizon} whose position is its own. The order inside the block is not history, so the positions under the horizon @@ -280,7 +291,8 @@ \section{The log as built}\label{sec:log} \Cref{alg:record} is the write. The reads are \lean{chains(class)}, \lean{head(chain)}, \lean{read_at} and \lean{read_between} (the rows of a range of positions), \lean{state_at} (a path's last event at or under a cut over its class's chains, one seek on the key index a chain), -\lean{history_at} (its \lean{store} rows there, a hole where a version was purged), +\lean{history_at} (its \lean{store} rows there, oldest first in a chain, a hole where a version +was purged), \lean{heads_at} (the \lean{store} rows whose closing stamp is absent or past the cut), and \lean{verify}, which recomputes the hashes from the first row and the commitment of every row that still has its salt. A cut over a class is one position a chain. Nothing reads the log yet; the @@ -299,29 +311,47 @@ \section{Evaluation}\label{sec:eval} survive 500 draws each. \paragraph{What is tested.} -The transcription is checked against the laws by a property test: Hypothesis draws sequences of 3 to -40 catalog writes over five paths, six digests, two titles, three classes and two identities, with -retires, renames, relabels, re-keys and both purges among them, 200 sequences a run. After every -write the catalog must equal the fold of the log and every chain must verify; every cut taken during -the sequence must read, after every later write, the rows and the state of every path it read -then, up to the holes a later purge leaves (SNP-1); every read of a chain must be a prefix of the -read at its head (SNP-2); the fold of every cut taken, continued over the rows since, must be the -catalog (SNP-3); the state of a path at the head must be its catalog row (SNP-4); and at every -position of every chain the seek, the closing-stamp read and the fold of the prefix must give every -path the same row, with no path alive twice (SNP-5). Eleven more tests take the stage's cases: a -write that changes nothing, and a landing the writer's unchanged check skips, append nothing; a -process killed between the catalog's row and the log's leaves neither; a failed batch leaves no -log row; the genesis is the catalog, tombstoned paths included, and ends at a horizon; a relabel -into a class that has rows changes no row; a purge of an old version of a live path is a hole by -all three reads at a cut where it was the head; an edited row fails \lean{verify}; the secret is -required, and another is refused; and every statement by path is planned on the key index. Seeding -two bugs, a log that writes no closing stamp and one that writes no \lean{leave}, fails the suite. +The transcription is checked against the laws by a property test: Hypothesis draws a catalog of up +to five rows as a build before the log left it, whose first open writes the genesis, then a +sequence of 3 to 40 catalog writes over five paths, six digests, two titles, three classes and two +identities, with retires, renames, relabels, re-keys and both purges among them, 200 draws a run. +After every write the catalog must equal the fold of the log, every chain must verify, a hole must +keep none of the content a purge empties, every name the log carries must be carried by a version +that keeps its content, and a landing that changes a path's identity must follow a \lean{move}. +Every cut taken must read, after every later write, the rows of every chain and each path's last +event in each, up to the holes a later purge leaves, and the state of every path over a class +while the class's chains are the ones it had (SNP-1): a relabel, which the model leaves out, moves +a whole chain to another class, so a read by class at a past cut follows the chain's class now. +Every read of a chain must be a prefix of the read at its head (SNP-2); the fold of every cut +taken, continued over the rows since, must be the catalog (SNP-3); the state of a path at the head +must be its catalog row (SNP-4); and at every position of every chain, the genesis's included, the +seek, the closing-stamp read and the fold of the prefix must give every path the same row, with no +path alive twice (SNP-5). Twenty more tests take the stage's cases: a write that changes nothing, +and a landing the writer's unchanged check skips, append nothing; the writer and the sync carry +each landing's version; a change of identity follows a \lean{move}, and a re-key carries the +version; each of the six writes, its process killed or the write failed between the catalog's row +and the log's, leaves neither, in a batch too when its caller catches the error and goes on; a +failed batch leaves no log row; the genesis is the catalog, closes each tombstoned path's +\lean{store} and ends at a horizon; a relabel into a class that has rows changes no row, closed +rows and holes included; a history over two chains of a class follows its rule; a purge of an old +version of a live path is a hole by all three reads at a cut where it was the head, and a purge of +every version of a deleted note leaves no row that names it, nor, after a vacuum, any byte of the +file; an edited row, and a hole that keeps content, fail \lean{verify}; the secret is needed by +what appends a row or seeks a path by its key and by nothing else, and another is refused; and +every statement by path is planned on the key index. Of 58 bugs seeded one at a time, from a +write that skips its log row to a purge that keeps a title, every one fails the suite on a fixed +seed but one that changes nothing, a write of a null over a null; the two that only the property +test catches fail it on four seeds more. \paragraph{What is measured.} \Cref{tab:measure} gives two runs of the committed harness on two copy-on-write clones of the catalog of the store's corpus instance, 400{,}274 rows of one class, all active, on an Apple M2 -Pro with SQLite 3.54.1 and other work running; the original was never opened. The genesis is one -chain of 400{,}276 rows, and its fold equals the catalog. +Pro with SQLite 3.54.1 and other work running, the load average between 2.7 and 3.9; the original +was never opened. The genesis is one chain of 400{,}276 rows, and its fold equals the catalog. A +key's write is timed three ways on the same file: as built; with the log's rows switched off, +which keeps the read of the row before the write, the transaction and the write's savepoint that +the stage added; and as the catalog made it before the stage, the upsert alone. After the copy, +two new catalogs of 30{,}000 and 100{,}000 paths are landed and every head of each is read. \begin{table}[t] \centering @@ -330,16 +360,18 @@ \section{Evaluation}\label{sec:eval} \toprule measurement & result \\ \midrule -the migration: tables, indexes, genesis & 6.22 to 6.33 s \\ +the migration: tables, indexes, genesis & 6.71 to 6.73 s \\ bytes a row of the log (table, key index) & 429 (381, 47); the file from 162.7 to 334.1 MB \\ -\lean{verify}, every commitment and hash & 3.05 to 3.07 s \\ -\lean{state_at} of one path; its keyed hash & 14.3 to 14.8 $\mu$s; 1.6 $\mu$s \\ -\lean{history_at} of one path & 14.7 to 15.7 $\mu$s \\ -\lean{read_at}, \lean{read_between}, 1{,}000 positions & 3.3 to 3.4 ms \\ -\lean{heads_at} at a tenth, the middle, the head & 0.15, 0.79 to 0.80, 1.6 s \\ -the same walks counted in SQL & 6, 26, 54 to 57 ms \\ -a new path's write, with the log and without & 49.0 and 6.8 $\mu$s \\ -a new version's write, with the log and without & 106.0 to 106.5 and 37.9 to 41.2 $\mu$s \\ +\lean{verify}, every commitment and hash & 3.07 to 3.08 s \\ +\lean{state_at} of one path; its keyed hash & 13.7 to 16.5 $\mu$s; 1.6 to 1.7 $\mu$s \\ +\lean{history_at} of one path & 15.5 to 18.9 $\mu$s \\ +\lean{read_at}, \lean{read_between}, 1{,}000 positions & 3.2 to 3.4 ms \\ +\lean{heads_at} at a tenth, the middle, the head & 0.15, 0.79, 1.62 s \\ +the same walks counted in SQL & 6, 29 to 30, 59 to 60 ms \\ +\lean{heads_at} of a chain of 30{,}000, of 100{,}000 & 111 to 112 ms, 374 to 376 ms \\ +a new path's write: as built, the log's rows off, before & 55.7 to 57.4, 10.4 to 10.5, 4.6 to +4.7 $\mu$s \\ +a new version's write: the same & 119.1 to 120.3, 45.0 to 46.0, 34.5 to 34.7 $\mu$s \\ \bottomrule \end{tabular} \caption{The landing log on a copy of a 400{,}274-item catalog: two runs, medians, ranges across @@ -347,34 +379,51 @@ \section{Evaluation}\label{sec:eval} keys.}\label{tab:measure} \end{table} -The log doubles the catalog's file, with paths, digests and titles the catalog holds already. It -adds 42~$\mu$s to a new path's write and 65 to 69~$\mu$s to a new version's, which also writes a -closing stamp; a landing without its vector took 31~ms an item on the store's earlier measurement -of two-phase ingestion, so the log is 0.1 to 0.2 percent of a landing. Reading every head at the -head of this chain takes 1.6~s, almost all of it building 400{,}274 rows in Python; the walk alone -is 0.14~$\mu$s an event. That is past the tenth of a second the design allows a read from the log -alone, and the design already keeps heads at recorded cuts for a chain over 250{,}000 events; this -chain is one. +The log doubles the catalog's file, with paths, digests and titles the catalog holds already. The +stage adds 51 to 53~$\mu$s to a new path's write and 84 to 86~$\mu$s to a new version's, against +the write before it; the log's rows are 45 to 47 and 74 of them, a new version's writing a +closing stamp as well. A landing without its vector took 31~ms an item on the store's earlier +measurement of two-phase ingestion, so the stage is 0.16 to 0.28 percent of a landing. Reading +every head costs what building the answer costs: the walk is 0.14 to 0.15~$\mu$s an event in +SQL, and each head returned costs 3.5 to 3.9~$\mu$s more, building its row in Python, on the +corpus's chain and on the smaller ones alike. So the read from the log alone passes the tenth of a +second the design allows near 27{,}000 heads, the chain of 30{,}000 paths taking 0.11~s, while the +design kept heads at recorded cuts only for a chain over 250{,}000 events. Kept heads shorten the +walk and not the building, so they do not answer it: the design's falsifier for that threshold is +met, and the threshold or the read's shape is to be decided before the stage that reads the notes +at a cut builds on it. \paragraph{What measuring found.} The first run took about 40~ms a landing. The update that writes the closing stamp of a path's previous row took the primary key, \lean{(chain, seq)}, and walked the chain for the path's rows, though the statement names the path's key: the planner's choice the design had already met for a seek on its fixture. The statement now names the key index, and a test asks the plan of every -statement by path to name it. Nothing at the test suite's sizes showed the walk. +statement by path to name it. Nothing at the test suite's sizes showed the walk. Later, each write +in a batch became a savepoint, so that a write that fails leaves neither of its rows when the +batch's caller catches the error and goes on; SQLite kept each savepoint's journal in a temporary +file, and a new path's write took 105 to 108~$\mu$s. The catalog's connection now keeps its +temporary store in memory, where the savepoint costs about 6~$\mu$s. \section{Limitations} One writer is assumed, as by the model. A build that wrote the catalog without the log, while the log's tables stayed, would leave the log behind the catalog, and nothing detects that yet; the -rollback drops the tables, and the next open writes a new genesis. The genesis knows no version -numbers, since the version chains are another file. A purge of a digest reads the whole log, which -has no index by digest. A path with events in two chains of one class, possible only after a -change of class and a merge of the two classes, is read by a rule of the prefix alone that can -order its earlier segments otherwise than they happened. The secret is an operational dependency: -a process that writes the catalog stops without it, and a lost secret leaves the log unwritable. -The measurements are of one instance, one class and no deletions; a catalog of several classes, -with identities apart from paths, is tested and not measured. +rollback drops the tables, and the next open writes a new genesis, numbering chains and positions +from one again, which a later stage's name for a fresh identity must not rest on. The genesis +knows no version numbers, since the version chains are another file. A purge of a digest walks +the whole log twice, for the digest and for the names of the paths it empties, since the log has +no index by either, and SQLite keeps the bytes it frees until the file is vacuumed. A path with +events in two chains of one class, possible only after a change of class and a merge of the two +classes, is read by a rule of the prefixes alone that can order its earlier segments otherwise +than they happened, and across the two chains its history at an earlier cut need not be a prefix +of the later one. The secret is an operational dependency: the first open of a catalog that has no +log writes the genesis, whichever process opens it, a reader's included, so that open needs the +secret, as does every write that appends a row, and a lost secret leaves the log unwritable. +Whether the genesis should move to a writer's first write, so that no reader needs the secret, is +left to the design's owner. Every head of a class is read at 3.5 to 3.9~$\mu$s a head returned, +which the stage that reads the notes at a cut must lower or bound first. The measurements are of +one instance, one class and no deletions; a catalog of several classes, with identities apart from +paths, is tested and not measured. \section{Future work} @@ -387,11 +436,12 @@ \section{Future work} \section{Conclusion} A catalog rewritten in place loses its past at every write. Two tables in its own file, written in -the same transactions, keep it at about 430 bytes and 50~$\mu$s a landing, with the catalog their -fold. Holes keep their positions and their keys, so the chain survives an erasure and a read by -path never steps over one; the key's other half stays outside the file, so the holes reveal -nothing to whoever copies it. The five laws a reader at a cut relies on are now statements the -library is judged against, and the code is tested against them. +the same transactions, keep it at about 430 bytes and 50 to 90~$\mu$s a landing, with the +catalog their fold. Holes keep their positions and their keys, so the chain survives an erasure +and a read by path never steps over one; the key's other half stays outside the file, so a hole's +key tells nothing to whoever copies the file without the secret, and once no version of a path +keeps its content no row names it. The five laws a reader at a cut relies on are now statements +the library is judged against, and the code is tested against them. \bibliographystyle{plainnat} \bibliography{refs} From 098301ab06d647a760906713e3ff3a2c1af2f2b5 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:13:46 -0500 Subject: [PATCH 23/30] docs(readme): the counts from the review's runs The deterministic tier is 3,654 tests at 77% coverage, the landing log's now 21 (3,645 before review, with 12). The statements' module docstring grew by a line, so the statement files are 3,810 lines; the models and proofs (25,652 lines), the attacks (5,757 lines, 232 attacks and 206 controls), the 375 judged statements and the ledger's 105 rows are as they were. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 19819ea7..a7e32947 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) [![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3663-brightgreen)](docs/runbook.md) +[![tests](https://img.shields.io/badge/tests-3672-brightgreen)](docs/runbook.md) [![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) [![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py) @@ -121,7 +121,7 @@ A law has one row in [`docs/LAWS.md`](docs/LAWS.md): its statement, the structur | | | |---|---| | toolchain | Lean `v4.36.0-rc2`, Mathlib; Plausible for the attacks | -| the library | 38 proof modules, 37 models, 27 statement files; 25,652 lines of models and proofs, 3,809 of statements, 5,757 of attacks | +| the library | 38 proof modules, 37 models, 27 statement files; 25,652 lines of models and proofs, 3,810 of statements, 5,757 of attacks | | theorems | 1,538 proved in `formal/Palace`; 375 statements in `formal/Spec` judged identical by the comparator | | the ledger | 105 rows in 16 families, 381 cited declarations, 92 law markers checked against the rows | | attacks | 232 Plausible attacks and 206 negative controls over 33 modules, fixed seeds | @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in ```sh uv sync --extra dev -uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,663 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,672 tests uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned) uv run python scripts/check_imports.py # the sealed core names no network module uv run python -m ops.type_gate # every core-reaching package is type-checked From fb5535e5a25f776c320986663edb2dc9b0b614c9 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Wed, 11 Nov 2026 23:16:22 -0500 Subject: [PATCH 24/30] docs(stores): a chain's id is given once while the log's tables stand The landing log's module docstring said a chain's id is never reused. The rollback drops the log's tables and the next genesis numbers its chains from 1 again, so an id is given once only while the tables stand, as dn-temporal-snapshot's sections 3.1 and 12 now say; SN-3's fresh identity must not rest on more. Co-Authored-By: Claude Opus 5.5 --- core/stores/landings.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/core/stores/landings.py b/core/stores/landings.py index 6436d8e6..2c353e05 100644 --- a/core/stores/landings.py +++ b/core/stores/landings.py @@ -7,12 +7,13 @@ is unchanged: the key last, now two rows of one transaction). The catalog is the fold of the log, and the state of a path at a past position is the same fold of a prefix (SNP-5). -**Chains.** A chain is an append order with an integer id that is never reused or changed, and -it holds one provenance class, which is its label in `landing_chains`. A relabel of a class -rewrites that label and no row of the log, so it moves no position and breaks no hash; after a -merge a class has two chains and the read of a class is the union of its chains' reads. A path's -events stay in the chain that holds its last event; a path that changes class leaves its chain -with a `leave` row and lands in a chain of its new class. +**Chains.** A chain is an append order with an integer id that is never changed and is given +once while the log's tables stand (a rollback that drops them begins the ids again, +dn-temporal-snapshot §12), and it holds one provenance class, which is its label in +`landing_chains`. A relabel of a class rewrites that label and no row of the log, so it moves no +position and breaks no hash; after a merge a class has two chains and the read of a class is the +union of its chains' reads. A path's events stay in the chain that holds its last event; a path +that changes class leaves its chain with a `leave` row and lands in a chain of its new class. **Rows.** `genesis` and `horizon` open a chain (§8: the positions before a horizon are under it); `store` is a landing; `retire` the tombstone of an identity no other active path holds; From c8c8f6a63d935727d2983278c089332e4320eb3d Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Thu, 12 Nov 2026 00:02:49 -0500 Subject: [PATCH 25/30] docs(stores): a chain's id and a position are given once while the tables stand The landing log's DDL comments, in the code and in the note's section 3.2, said a chain's id is never reused and a position never given twice, and the note's table of chains said the same of `seq`. A rollback drops the two tables, and the genesis after it numbers both from 1 again (section 12, SN-1), as the module's docstring already says. The comments now say given once while the tables stand, and the note's DDL and its table point at section 12's rollback. Co-Authored-By: Claude Opus 5.5 --- core/stores/landings.py | 4 ++-- docs/design-notes/dn-temporal-snapshot.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core/stores/landings.py b/core/stores/landings.py index 2c353e05..c250c8c4 100644 --- a/core/stores/landings.py +++ b/core/stores/landings.py @@ -60,14 +60,14 @@ DDL = """ CREATE TABLE IF NOT EXISTS landing_chains ( - chain INTEGER PRIMARY KEY, -- the chain's id: never reused, never changed + chain INTEGER PRIMARY KEY, -- the id: never changed, given once while the tables stand class TEXT NOT NULL, -- the provenance class it holds now; a relabel rewrites this secret BLOB NOT NULL, -- 32 random bytes: the chain's half of the key of path_key key_check BLOB NOT NULL -- hmac-sha256(the chain's key, 'key check') ); CREATE TABLE IF NOT EXISTS landings ( chain INTEGER NOT NULL, -- landing_chains.chain - seq INTEGER NOT NULL, -- the position in the chain, from 1, never given twice + seq INTEGER NOT NULL, -- the position, from 1, given once while the tables stand kind TEXT NOT NULL, -- genesis | store | retire | move | leave | horizon path_key BLOB, -- hmac-sha256(the chain's key, source_path): kept by a hole source_path TEXT, -- NULL once purged diff --git a/docs/design-notes/dn-temporal-snapshot.md b/docs/design-notes/dn-temporal-snapshot.md index 805c6b55..f37ac446 100644 --- a/docs/design-notes/dn-temporal-snapshot.md +++ b/docs/design-notes/dn-temporal-snapshot.md @@ -352,7 +352,7 @@ prefix length of it. `[DERIVED from global-event-clock §2.2, generator g1]` | chain | store | position | today | |---|---|---|---| -| `land`, one or more a provenance class | the landing log (§3.2), in the catalog's file | `seq`, from 1, never given twice | not built | +| `land`, one or more a provenance class | the landing log (§3.2), in the catalog's file | `seq`, from 1, given once while the log's tables stand (§12, SN-1's rollback) | not built | | `chat` | the chat log | a sequence number beside each row; within a session it is the turn order | the order is recorded, the number is not | | `att` | the attestation ledger | a sequence number beside each row | the order is recorded, the number is not; the ledger is read in wall-time order | | `repo` | git, mirrored by the commit ledger and the per-commit readings | a commit, standing for its ancestors | recorded | @@ -423,14 +423,14 @@ comes from, a sixth kind, and the tombstone the genesis writes. ```sql CREATE TABLE landing_chains ( - chain INTEGER PRIMARY KEY, -- the chain's id: never reused, never changed + chain INTEGER PRIMARY KEY, -- never changed, and given once while the tables stand (§12) class TEXT NOT NULL, -- the provenance class it holds now; a relabel rewrites it secret BLOB NOT NULL, -- 32 random bytes: the chain's half of the key of path_key key_check BLOB NOT NULL -- hmac-sha256(the chain's key, 'key check') ); CREATE TABLE landings ( chain INTEGER NOT NULL, -- landing_chains.chain - seq INTEGER NOT NULL, -- the position in the chain, from 1, never given twice + seq INTEGER NOT NULL, -- the position, from 1, given once while the tables stand (§12) kind TEXT NOT NULL, -- genesis | store | retire | move | leave | horizon path_key BLOB, -- hmac-sha256(the chain's key, source_path): kept by a hole source_path TEXT, -- NULL once purged From 7216f2cac6286a5f99080d27f756c2c5b6be32ca Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Thu, 12 Nov 2026 00:10:30 -0500 Subject: [PATCH 26/30] perf(stores): a purge by digest walks the log twice `empty_digest` read the digest's rows by a walk of the log, emptied them by a second (`UPDATE ... WHERE digest = ?`) and read the names of their paths by a third, where the article and the record say a purge walks the log twice. It now empties the rows it read by their positions, on the primary key, so its walks are the read of the digest's rows and the read of the names; every other statement seeks. The rows it empties are the same. The plan test counts the purge's walks of `landings`, two, and the test of a deleted note's purge gives one of its digests to another note's earlier version, so a purge that emptied only some of a digest's rows fails it on any seed (the property test alone caught it on seeds 1 and 3, not on 2). Co-Authored-By: Claude Opus 5.5 --- core/stores/landings.py | 17 ++++++++++------- tests/property/test_landing_log.py | 23 +++++++++++++++++------ 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/core/stores/landings.py b/core/stores/landings.py index c250c8c4..d2946ebc 100644 --- a/core/stores/landings.py +++ b/core/stores/landings.py @@ -496,14 +496,17 @@ def empty_digest(self, digest: str) -> int: path whose every `store`, in every chain, is then a hole has its other rows emptied as well, its `retire`, `move` and `leave`: no row then names it, or the identity and the date its tombstone carried. A path's rows are found by the names they carry and by the - keys the emptied rows keep, so the purge needs no secret; the rows of the digest and the - names are read by a walk of the log, which has no index by digest or by name. Returns + keys the emptied rows keep, so the purge needs no secret. The log has no index by digest + or by name, so the purge walks it twice, once for the rows of the digest, which it then + empties by their positions, and once for the names; every other statement seeks. Returns the rows emptied.""" - hit = [(int(c), bytes(k), str(p)) for c, k, p in self._conn.execute( - "SELECT chain, path_key, source_path FROM landings WHERE digest = ? " - "AND path_key IS NOT NULL AND source_path IS NOT NULL", [digest])] - n = self._conn.execute( - f"UPDATE landings SET {_EMPTY} WHERE digest = ?", [digest]).rowcount + rows = self._conn.execute( + "SELECT chain, seq, path_key, source_path FROM landings WHERE digest = ?", + [digest]).fetchall() + n = self._conn.executemany(f"UPDATE landings SET {_EMPTY} WHERE chain = ? AND seq = ?", + [(c, s) for c, s, _, _ in rows]).rowcount + hit = [(int(c), bytes(k), str(p)) for c, _, k, p in rows + if k is not None and p is not None] paths = sorted({p for _, _, p in hit}) if not paths: return n diff --git a/tests/property/test_landing_log.py b/tests/property/test_landing_log.py index 8e85f5d0..0e1d04ac 100644 --- a/tests/property/test_landing_log.py +++ b/tests/property/test_landing_log.py @@ -751,9 +751,12 @@ def test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it( vault, then each of its digests purged by `remove_digest`. While one of its versions keeps its content the path's other rows keep its name; once none does, its `leave` and its `retire` are emptied too, so no row names the path or the identity, or carries the date of its delete; the - holes keep their keys and positions. After a vacuum no byte of the file holds either name.""" + holes keep their keys and positions. Another note held one of the digests before: its row of + that digest is emptied too, as every row of a digest is, and its later version keeps its name + on its other rows. After a vacuum no byte of the file holds either name of the purged note.""" db = tmp_path / "catalog.sqlite" cat = VaultCatalog(db) + cat.record("keep.md", "dp1", "K") # an earlier version, the bytes of dp1 cat.record("keep.md", "dk", "K") note = "notes/private-topic.md" cat.record(note, "dp1", "Private", doc_id="id-private") @@ -766,8 +769,9 @@ def test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it( cat.remove_digest("dp1") rows = log_rows(cat) assert all(note not in (r.source_path, r.doc_id) and r.doc_id != "id-private" for r in rows) + assert all(r.digest != "dp1" for r in rows) # keep.md's row of it as well holes = [r for r in rows if r.hole] - assert sorted(r.kind for r in holes) == ["leave", "retire", "store", "store"] + assert sorted(r.kind for r in holes) == ["leave", "retire", "store", "store", "store"] assert all(emptied(r) and r.path_key is not None for r in holes) assert cat.get(note) is None and cat.get("keep.md") is not None assert_consistent(cat) @@ -889,8 +893,8 @@ def test_every_statement_by_path_seeks_the_key_index() -> None: """A write or a read of one path touches that path's rows through `landings_path`, never by walking the chain: on the corpus's 400,274 rows the planner took the primary key for the closing stamp's update, and a landing took 40 ms where it takes tens of microseconds. A - purge by digest walks the log for the digest and the names, which have no index, and then - reaches each path's rows by their key.""" + purge by digest walks the log twice, for the digest and for the names, which have no index; + it empties the digest's rows by their positions and reaches each path's rows by their key.""" cat = VaultCatalog(Path(":memory:")) for i in range(50): cat.record(f"p{i}.md", f"d{i}", "t") @@ -904,11 +908,18 @@ def test_every_statement_by_path_seeks_the_key_index() -> None: cat.state_at(Provenance.AUTHORED_SOLO, "p1.md", {chain: 30}) cat.history_at(Provenance.AUTHORED_SOLO, "p1.md", {chain: cat.head(chain)}) cat.remove("p3.md") + purge = len(seen) cat.remove_digest("d5") # p5's only version: its retire as well cat._conn.set_trace_callback(None) + + def plan(q: str) -> str: + return " ".join(str(tuple(r)[-1]) for r in cat._conn.execute("EXPLAIN QUERY PLAN " + q)) + by_path = [q for q in seen if "path_key = " in q] assert len(by_path) >= 8 for q in by_path: - plan = " ".join(str(tuple(r)[-1]) for r in cat._conn.execute("EXPLAIN QUERY PLAN " + q)) - assert "landings_path" in plan, (q, plan) + assert "landings_path" in plan(q), (q, plan(q)) + walks = [q for q in seen[purge:] if q.split(None, 1)[0] in ("SELECT", "UPDATE", "DELETE") + and "SCAN landings" in plan(q)] + assert len(walks) == 2, walks assert all(r.source_path != "p5.md" for r in log_rows(cat)) From c6eda44d286dede10f6c60c984bb52faec9a5d75 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Thu, 12 Nov 2026 00:10:51 -0500 Subject: [PATCH 27/30] test(stores): a batch's earlier write, the batched landing's version, each column of a hole Three gaps the review found by seeding bugs the suite let pass. - A batch whose failed write rolled back the whole transaction, in place of its savepoint, passed: no write of the batch preceded the failing one. The batch now records a note before it, and the test asks that note's catalog row and log row to commit with the note recorded after. - The writer's batched key write (`Writer.finish` with producers, under `Writer.land_batch`) passing no version passed every test. A new test lands two notes, then an edit of one, through a plan of fresh stores with `batch=True`, and asks each `store` row of the log to carry the version chain's number; SNP-5's row cites it. - `verify`'s check of a hole and the test's oracle both read `Landing.content`, so a `content` that left out a column weakened both together. The oracle reads the test's own list of what a purge empties, and `verify` is asked to fail a hole that keeps any one column of it. Each of the four seeded bugs now fails the suite on hypothesis seeds 1 and 2, and so do the review's 25 others on seed 1. Co-Authored-By: Claude Opus 5.5 --- docs/LAWS.md | 2 +- tests/property/test_landing_log.py | 98 +++++++++++++++++++++++++----- 2 files changed, 83 insertions(+), 17 deletions(-) diff --git a/docs/LAWS.md b/docs/LAWS.md index f30cee38..4f011d2f 100644 --- a/docs/LAWS.md +++ b/docs/LAWS.md @@ -325,4 +325,4 @@ built (dn-temporal-snapshot §12). Nothing reads the log yet. The family was ope | SNP-2 | monotonicity: the read at an earlier cut is a prefix, chain by chain, of the read at a later one, an event read at a cut is read at every later cut, a cut of a cut is the meet of the two, and the head of the read at a cut is the meet of the cut and the head; so are the read under an erasure, the history of a key with no seal, and the filtered read (exact: finite lists; on the code, every read of a chain is a prefix of the read at its head, and the rows between a cut and the head are the rest; a path's history is a prefix chain by chain, and across two chains of one class, which only a change of class and a relabel make, it is ordered by a rule of the prefixes and need not be) | the prefix order on lists; cuts as a lattice | `core/stores/catalog.py::VaultCatalog.read_at`; `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.history_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_history_over_two_chains_of_a_class_follows_a_rule_of_the_prefixes` | `Snapshot.lean::readAt_mono`, `Snapshot.lean::mem_readAt_of_le`, `Snapshot.lean::readAt_readAt`, `Snapshot.lean::head_readAt`, `Snapshot.lean::visible_mono`, `Snapshot.lean::landingsAt_mono`, `Snapshot.lean::Kept.mono` | | SNP-3 | composition: the read at `a` followed by the read between `a` and `b` is the read at `b`, and two adjacent reads-between compose, so a fold continued from a checkpoint over the delta is the fold of the prefix, for a store and for a chain of keyed writes; an event, or a pair of events, read at the later cut was read at the earlier one or lies in the delta, and a key the delta does not write has one state at both cuts (exact: finite lists; on the code, the catalog folded from every cut taken and continued over the rows since is the catalog) | a left fold over a concatenation | `core/stores/catalog.py::VaultCatalog.read_between`; `core/stores/catalog.py::VaultCatalog.read_at` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold` | `Snapshot.lean::readAt_append_readBetween`, `Snapshot.lean::readBetween_append`, `Snapshot.lean::foldAt_readBetween`, `Snapshot.lean::stateAt_eq_foldl`, `Snapshot.lean::mem_readAt_iff`, `Snapshot.lean::pair_readAt`, `Snapshot.lean::stateAt_eq_of_not_written` | | SNP-4 | idempotence: a cut at or past the head reads the store, so the read at the head is the store and every derived view at it is the present's: the generations read the store rewritten in place, a grant's snapshot and what an asker is shown are the grant's restriction of the store, what is visible is the store without the erased events, the history of a key with no seal is its every landing, and each seal serves at the head what the key holds live (exact: finite lists; on the code, a cut at or past a chain's head reads the whole chain, and the state of a path at the head is its catalog row; the genesis is the catalog, tombstoned paths included, and ends at a horizon) | the identity read: `as of` the head is no `as of` | `core/stores/catalog.py::VaultCatalog.head`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/landings.py::LandingLog.genesis` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_the_genesis_is_the_catalog_and_ends_at_a_horizon` | `Snapshot.lean::readAt_head`, `Snapshot.lean::readAt_of_head_le`, `Snapshot.lean::view_head`, `Snapshot.lean::genRead_gens_length`, `Snapshot.lean::snapshot_head`, `Snapshot.lean::shown_head`, `Snapshot.lean::landingsAt_length`, `Snapshot.lean::visible_head`, `Snapshot.lean::servedAt_length`, `Snapshot.lean::servedNow_length`, `Snapshot.lean::historyAt_length` | -| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, each of the six writes killed or failed between the catalog's row and the log's leaving neither, in a batch too when its caller goes on, a batch carrying its log rows, a record that changes nothing and a store the UNCHANGED check skips appending nothing, the writer and the sync carrying each landing's version, and a change of identity landing after a `move`; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place that keeps none of its content, and no path has two rows alive; a path none of whose versions keeps its content is named by no row; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/catalog.py::VaultCatalog.heads_at`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_the_sync_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version`, `tests/property/test_landing_log.py::test_each_write_killed_or_failed_between_its_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads`, `tests/property/test_landing_log.py::test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | +| SNP-5 | a derived view is a function of the prefixes: a reader is append invariant exactly when it reads only the prefixes, exactly when it is a derived view; for a chain of keyed writes the generational store read at a cut is the state recomputed from the prefix, which is the key's last write inside it, and at most one generation of a key is alive at a cut; the control: the store rewritten in place determines no read at a past cut (exact: finite lists; on the code, the catalog is the fold of the log after every write, each of the six writes killed or failed between the catalog's row and the log's leaving neither, in a batch too when its caller goes on while the batch's other writes commit, a batch carrying its log rows, a record that changes nothing and a store the UNCHANGED check skips appending nothing, the writer, its batched landing too, and the sync carrying each landing's version, and a change of identity landing after a `move`; at every position of every chain the seek on the key index, the closing-stamp read and the fold of the prefix give each path the same row, a purged version a hole in its place that keeps none of its content, and no path has two rows alive; a path none of whose versions keeps its content is named by no row; a relabel into a class that has rows changes no row) | three ways of holding a derived view, recomputed, journaled and kept by generation, that agree | `core/stores/catalog.py::VaultCatalog.record`; `core/stores/catalog.py::VaultCatalog.state_at`; `core/stores/catalog.py::VaultCatalog.heads_at`; `core/stores/catalog.py::VaultCatalog.history_at`; `core/stores/landings.py::LandingLog.store` | Claim | `tests/property/test_landing_log.py::test_the_catalog_is_the_fold_of_the_log_and_the_laws_hold`, `tests/property/test_landing_log.py::test_a_record_that_changes_nothing_appends_nothing`, `tests/property/test_landing_log.py::test_a_store_the_unchanged_check_skips_appends_nothing`, `tests/property/test_landing_log.py::test_the_sync_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_batched_landing_carries_the_version_each_landing_is`, `tests/property/test_landing_log.py::test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version`, `tests/property/test_landing_log.py::test_each_write_killed_or_failed_between_its_two_rows_leaves_neither`, `tests/property/test_landing_log.py::test_a_deferred_batch_carries_its_log_rows`, `tests/property/test_landing_log.py::test_a_relabel_into_a_class_with_rows_changes_no_row_and_every_chain_verifies`, `tests/property/test_landing_log.py::test_a_purged_old_version_of_a_live_path_is_a_hole_by_the_three_reads`, `tests/property/test_landing_log.py::test_a_purge_of_every_version_of_a_deleted_note_leaves_no_row_that_names_it` | `Snapshot.lean::prefixOnly_view`, `Snapshot.lean::view_congr`, `Snapshot.lean::appendInvariant_iff_prefixOnly`, `Snapshot.lean::appendInvariant_iff_exists_view`, `Snapshot.lean::genRead_gens`, `Snapshot.lean::stateAt_eq_lastWrite`, `Snapshot.lean::length_filter_selects_le_one`; the control: `Snapshot.lean::Witness.stateOf_forgets` | diff --git a/tests/property/test_landing_log.py b/tests/property/test_landing_log.py index 0e1d04ac..8ef9a2c7 100644 --- a/tests/property/test_landing_log.py +++ b/tests/property/test_landing_log.py @@ -25,16 +25,18 @@ rows are emptied, and no path has two rows alive. Then the stage's own cases: a record that changes nothing, and a store the UNCHANGED check skips, -append nothing; the writer and the sync carry the version each landing is; a change of identity -lands after a `move`, and a re-key carries the version; each of the six writes, killed or failed -between the catalog's row and the log's, leaves neither, in a batch too when its caller goes on; -the genesis is the catalog, tombstoned paths included, closes each tombstoned path's `store` and -ends at a horizon; a relabel into a class that has rows changes no row of the log, closed rows and -holes included, and every chain verifies; a history over two chains of a class follows a rule of -the prefixes; a purge of an old version of a live path leaves a hole that all three reads return at -a cut where it was the head, and a purge of every version of a deleted note leaves no row that -names it; `verify` fails on an edited row and on a hole that keeps content; the secret is required -by what appends or seeks a path by its key and by nothing else, and another one is refused. +append nothing; the writer, its batched landing too, and the sync carry the version each landing +is; a change of identity lands after a `move`, and a re-key carries the version; each of the six +writes, killed or failed between the catalog's row and the log's, leaves neither, in a batch too +when its caller goes on, and the batch's other writes commit; the genesis is the catalog, +tombstoned paths included, closes each tombstoned path's `store` and ends at a horizon; a relabel +into a class that has rows changes no row of the log, closed rows and holes included, and every +chain verifies; a history over two chains of a class follows a rule of the prefixes; a purge of an +old version of a live path leaves a hole that all three reads return at a cut where it was the +head, and a purge of every version of a deleted note leaves no row that names it; `verify` fails +on an edited row and on a hole that keeps any one column of its content; the secret is required +by what appends or seeks a path by its key and by nothing else, and another one is refused; a +statement by path seeks the key index, and a purge by digest walks the log twice. """ from __future__ import annotations @@ -75,6 +77,10 @@ # What a purge empties in a row, as §6.1 lists it (the code's own list is `landings._EMPTY`). EMPTY = "source_path = NULL, doc_id = NULL, digest = NULL, title = NULL, salt = NULL, at = NULL" +# The columns it empties beside the salt, read off the list above and not off `Landing.content`, +# which `verify` reads: a `content` that left one out would weaken the check and this oracle +# together. +CONTENT = [part.split(" = ")[0] for part in EMPTY.split(", ") if not part.startswith("salt ")] # --- the fold of the log, from its rows alone --------------------------------------------------- @@ -175,8 +181,8 @@ def alive(row: Landing, c: int) -> bool: def emptied(row: Landing) -> bool: """A hole as a purge leaves it (§6.1): no salt, and none of the path, the identity, the - digest, the title or the bookmark.""" - return row.hole and all(v is None for v in row.content().values()) + digest, the title or the bookmark (`CONTENT`).""" + return row.salt is None and all(getattr(row, column) is None for column in CONTENT) def same_up_to_holes(now: Landing, then: Landing, c: int) -> bool: @@ -512,6 +518,54 @@ def test_the_sync_carries_the_version_each_landing_is(tmp_path: Path) -> None: cat.close() +def test_a_batched_landing_carries_the_version_each_landing_is( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """The writer's other key write: a plan of fresh stores on distinct paths, each naming its own + identity, landed a stage at a time (`Writer.land_batch`), its keys written in one `deferred()` + batch. Two notes land, one is edited and the plan lands again; each `store` row of the log + carries the version the version chain gives that landing.""" + from core.ingest import ingress + from core.ingest.readers import PalaceView + from core.ingest.table import build_table + from core.ingest.writer import Writer + from core.sentence import ast + from core.sentence.plan import compile_sentence + + p = palace_at(tmp_path) + batches: list[int] = [] + land_batch = Writer.land_batch + + def counted(self: Writer, plan: Any) -> Any: + batches.append(len(plan)) + return land_batch(self, plan) + + monkeypatch.setattr(Writer, "land_batch", counted) + plan = compile_sentence('do { for n in files(source("vault")) ' + '{ store n.content in "mirror_authored" } }', + ingress.grant_for("cli"), role="cli") + assert isinstance(plan.term, ast.Do) + term: ast.Do = plan.term + + def land() -> dict[str, Any]: + view = PalaceView(build_table(p.cfg), "cli", p.stores.catalog, refresh=False) + return ingress.perform(term, p.cfg, "cli", stores=p.stores, view=view, batch=True) + + a = write_file(p.vault, "a.md", "alpha\n") + b = write_file(p.vault, "b.md", "beta\n") + assert land()["effects"] == {"landed": 2} + a.write_text("alpha, edited\n", encoding="utf-8") + assert land()["effects"] == {"landed": 1, "unchanged": 1} + assert batches == [2, 2] # both plans took the batched path + cat, versions = p.stores.catalog, p.stores.versions + assert versions is not None + (chain,) = cat.chains(Provenance.AUTHORED_SOLO) + rows = cat.read_at(chain, cat.head(chain)) + for note, numbers in ((str(a), [1, 2]), (str(b), [1])): + assert [r.version for r in rows if r.kind == "store" and r.source_path == note] == \ + [v.version_seq for v in versions.history(cat.doc_id_for(note))] == numbers + assert_consistent(cat) + + def test_a_change_of_identity_moves_first_and_a_rekey_carries_the_version() -> None: """A `record` that gives an active path another identity writes a `move` of the one it held before the `store`; the owner's re-key writes a `move` and then the path's `store` under the @@ -554,7 +608,8 @@ def test_each_write_killed_or_failed_between_its_two_rows_leaves_neither( """Each of the six writing methods, its process killed after the catalog's statement and before the log's, and then the same write failing there in process: the catalog's rows and the log's are what they were, both times. Inside a batch, a failed write whose caller catches the - error and goes on leaves neither row either, and the batch commits the rest.""" + error and goes on leaves neither row either, and the batch commits the rest, the write made + before the failed one and the write made after it, each with its log row.""" method, write = WRITES[name] db = tmp_path / "catalog.sqlite" cat = VaultCatalog(db) @@ -580,17 +635,21 @@ def boom(*args: Any, **kwargs: Any) -> None: with pytest.raises(RuntimeError): write(cat) unchanged(cat) + monkeypatch.undo() with cat.deferred(): + cat.record("e.md", "de", "E") # the batch's write before the failed one + monkeypatch.setattr(cat._log, method, boom) with pytest.raises(RuntimeError): write(cat) # failed, and the caller goes on monkeypatch.undo() cat.record("c.md", "dc", "C") - assert {k: v for k, v in catalog_rows(cat).items() if k != "c.md"} == catalog - assert catalog_rows(cat)["c.md"][:2] == ("dc", "C") + rows = catalog_rows(cat) + assert {k: v for k, v in rows.items() if k not in ("c.md", "e.md")} == catalog + assert (rows["e.md"][:2], rows["c.md"][:2]) == (("de", "E"), ("dc", "C")) now = {(r[0], r[1]): r for r in all_rows(cat)} then = {(r[0], r[1]): r for r in log} assert {k: now[k] for k in then} == then - assert [now[k][4] for k in sorted(now.keys() - then.keys())] == ["c.md"] # c.md's store + assert [now[k][4] for k in sorted(now.keys() - then.keys())] == ["e.md", "c.md"] # the stores assert chain_rows(cat) == log_chains assert_consistent(cat) cat.close() @@ -806,6 +865,13 @@ def test_verify_fails_on_an_edited_row() -> None: (f"UPDATE landings SET {EMPTY}, at = '2000-01-01T00:00:00' WHERE chain = ? AND seq = 5", 5, "a hole keeps content"), ] + # a row emptied as a purge empties it but for one column of the content, which it keeps: + # each column alone is content a hole must not keep + assert CONTENT == ["source_path", "doc_id", "digest", "title", "at"] + for kept in CONTENT: + others = ", ".join(f"{column} = NULL" for column in CONTENT if column != kept) + edits.append((f"UPDATE landings SET salt = NULL, {others} WHERE chain = ? AND seq = 4", + 4, "a hole keeps content")) for edit, seq, why in edits: cat._conn.execute("SAVEPOINT edit") cat._conn.execute(edit, [chain]) From a14d501c0b2624ccd7b6d3fdc986ad2b0a2177b8 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Thu, 12 Nov 2026 00:11:03 -0500 Subject: [PATCH 28/30] ops(lifecycle): the daemon's plists run under the secrets wrapper The daemon writes the catalog, and every write that appends a row to its landing log, the genesis included, needs the landing-log secret, so the daemon needs it wherever the owner places the genesis. `palace deploy` installs a committed plist that changed (`launcher.py:1071-1078`), so an installed plist edited by hand would be overwritten: the committed ones must carry the secret. Both now run `uv run scripts/palace.py start` under `scripts/run_with_secrets.sh`, which reads the item from the Keychain and execs the rest. The daemon twin runs as `ouroboros` and reads that account's keychain; the plane migration's section 7 copies the item there with the unseal key, the same value, and the twin's preconditions name it. The runbook's section 0 says so, and its wrapper block, which the landing-log paragraph called the wrapper that carries the item, now carries it. The note's section 12 says that every writer needs the secret under either placement of the genesis, which stays the owner's choice. Co-Authored-By: Claude Opus 5.5 --- docs/design-notes/dn-temporal-snapshot.md | 9 ++++++--- docs/runbook.md | 13 ++++++++++--- docs/runbooks/plane-migration.md | 7 ++++++- ops/lifecycle/com.mind-palace.palace-daemon.plist | 8 ++++++++ ops/lifecycle/com.mind-palace.palace.plist | 5 +++++ 5 files changed, 35 insertions(+), 7 deletions(-) diff --git a/docs/design-notes/dn-temporal-snapshot.md b/docs/design-notes/dn-temporal-snapshot.md index f37ac446..dc1dac9d 100644 --- a/docs/design-notes/dn-temporal-snapshot.md +++ b/docs/design-notes/dn-temporal-snapshot.md @@ -2157,9 +2157,12 @@ property-testing the transcription against the Lean statements; the laws a stage the owner's to decide before SN-1 is deployed: the genesis written by a writer's first write, or by an owner-run migration, with an open that lacks the secret skipping it; or SN-1 stated as changing what the first open needs, with every - process, the daemon's plists included (`ops/lifecycle/com.mind-palace.palace.plist`, its daemon - twin), run with the secret in its environment. Until then the runbook's §0 makes the secret a - precondition of the deploy. + process that may open the catalog first run with the secret in its environment. Under either, + every writer needs the secret, the daemon first, and a deploy installs a committed plist that + changed (`ops/lifecycle/launcher.py:1071-1078`); so the two plists + (`ops/lifecycle/com.mind-palace.palace.plist`, its daemon twin) run the daemon under + `scripts/run_with_secrets.sh`, which carries the item, the twin, run as `ouroboros`, reading + it from that account's keychain. The runbook's §0 makes the item a precondition of the deploy. Tests, in `tests/property/test_landing_log.py`: SNP-1 to SNP-5 as §10 states them, over random sequences of catalog writes that include retires, renames, relabels and purges; the diff --git a/docs/runbook.md b/docs/runbook.md index 8d5bbc87..23d579be 100644 --- a/docs/runbook.md +++ b/docs/runbook.md @@ -427,6 +427,7 @@ exec env \ "attestation-signing-key=$(kc attestation-signing-key)" \ "attestation-owner-key=$(kc attestation-owner-key)" \ "vault-supervisor-token=$(kc vault-supervisor-token)" \ + "landing-log-key=$(kc landing-log-key)" \ "$@" # plist ProgramArguments: [ .../scripts/run_with_secrets.sh, .../uv, run, .../scripts/watch.py ] ``` @@ -446,9 +447,15 @@ which finds a path's rows by their key. Without it they refuse, loudly (`LandingLogKeyMissing`), and write nothing. A relabel, a purge by digest and a write that changes nothing need no secret, and nor does a read, except the log's two reads of one path (`state_at`, `history_at`), which nothing calls yet. Place it before deploying the build that -brings the log, and run every process that opens the catalog under the wrapper above (it carries -the item), the daemon first, or the first of them to open the catalog stops there. Whether the -genesis should move off the first open is open with the owner (dn-temporal-snapshot §12, SN-1): +brings the log. The daemon writes the catalog, so it needs the item however the genesis is +placed: the committed plists (`ops/lifecycle/com.mind-palace.palace.plist`, its daemon twin) run it +under `scripts/run_with_secrets.sh`, which carries the item, and a deploy installs a plist that +changed. The daemon twin runs as `ouroboros`, so its wrapper reads `ouroboros`'s keychain: place +the item there as well, with the same value, the way `docs/runbooks/plane-migration.md` §7 places +the unseal key. Any other process that opens the catalog before the daemon has written the genesis +needs the item too, so run it under the wrapper or start the daemon first. Whether the genesis +should move off the first open, so that a reader without the secret can open a catalog that has +no log yet, is open with the owner (dn-temporal-snapshot §12, SN-1): ```sh openssl rand -hex 32 # 32 random bytes, as hex diff --git a/docs/runbooks/plane-migration.md b/docs/runbooks/plane-migration.md index aeab7d49..a324cc46 100644 --- a/docs/runbooks/plane-migration.md +++ b/docs/runbooks/plane-migration.md @@ -287,13 +287,18 @@ mind-palace stop # drain the current (asc # --- Unseal key: copy the item into ouroboros's keychain (the daemon, as ouroboros, will read it). sudo -u ouroboros -H security add-generic-password -U -a mind-palace -s vault-unseal-key -w \ "$(security find-generic-password -a mind-palace -s vault-unseal-key -w)" +# --- Landing-log secret: the daemon plist runs under scripts/run_with_secrets.sh, which reads it +# as ouroboros. The same value: the catalog's landing log refuses another (runbook §0). +sudo -u ouroboros -H security add-generic-password -U -a mind-palace -s landing-log-key -w \ + "$(security find-generic-password -a mind-palace -s landing-log-key -w)" ``` - **Verify (no secret printed):** `sudo -u ouroboros -H security find-generic-password -a mind-palace -s vault-unseal-key >/dev/null && echo 'unseal item present for ouroboros'`. (`verify_planes.py` → "unseal key under ouroboros" is a manual SKIP — this IS that check.) + The same with `-s landing-log-key` for the landing log's item. - **Rollback:** `sudo -u ouroboros -H security delete-generic-password -a mind-palace -s - vault-unseal-key`; restart the ascalva Syncthing instance. + vault-unseal-key`, and the same for `landing-log-key`; restart the ascalva Syncthing instance. --- diff --git a/ops/lifecycle/com.mind-palace.palace-daemon.plist b/ops/lifecycle/com.mind-palace.palace-daemon.plist index f630131c..e428525f 100644 --- a/ops/lifecycle/com.mind-palace.palace-daemon.plist +++ b/ops/lifecycle/com.mind-palace.palace-daemon.plist @@ -25,6 +25,8 @@ - the `ouroboros` role account exists and owns the vault + data/ (data/logs must be ouroboros-writable — StandardOut/Err sink there); - the unseal keychain item + Syncthing have migrated to `ouroboros`; + - the landing-log-key item is in `ouroboros`'s keychain, with the value the catalog's log was + written with (the log refuses another; docs/runbooks/plane-migration.md §7); - `/Users/ascalva` is traversable by `ouroboros` so it can reach the repo + ~/.mind-palace. ExitTimeOut gives the drain time to finish before launchd escalates to SIGKILL. Adjust the absolute paths if your checkout is elsewhere. @@ -42,6 +44,12 @@ ProgramArguments + + /Users/ascalva/mind-palace/scripts/run_with_secrets.sh /opt/homebrew/bin/uv run diff --git a/ops/lifecycle/com.mind-palace.palace.plist b/ops/lifecycle/com.mind-palace.palace.plist index efef6bf7..4fa4c9bd 100644 --- a/ops/lifecycle/com.mind-palace.palace.plist +++ b/ops/lifecycle/com.mind-palace.palace.plist @@ -25,6 +25,11 @@ ProgramArguments + + /Users/ascalva/mind-palace/scripts/run_with_secrets.sh /opt/homebrew/bin/uv run From 7720134d606a4be5c82f5c8eb7386df9904cca59 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Thu, 12 Nov 2026 00:18:01 -0500 Subject: [PATCH 29/30] docs(paper): the landing log's article after the second review Twenty-one tests beside the property test: the writer's batched landing carries the version too, and a batch's other writes commit around a failed one. A writer needs the secret under either placement of the genesis. The second review seeded 29 bugs, four of which passed; with the tests it asked for, those 29 and three seeded in the purge's emptying by position all fail the suite on hypothesis seed 1. Nine pages, a clean build. Co-Authored-By: Claude Opus 5.5 --- papers/2026-11-11-landing-log/paper.tex | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/papers/2026-11-11-landing-log/paper.tex b/papers/2026-11-11-landing-log/paper.tex index 5a174be5..aafbdab4 100644 --- a/papers/2026-11-11-landing-log/paper.tex +++ b/papers/2026-11-11-landing-log/paper.tex @@ -326,12 +326,13 @@ \section{Evaluation}\label{sec:eval} taken, continued over the rows since, must be the catalog (SNP-3); the state of a path at the head must be its catalog row (SNP-4); and at every position of every chain, the genesis's included, the seek, the closing-stamp read and the fold of the prefix must give every path the same row, with no -path alive twice (SNP-5). Twenty more tests take the stage's cases: a write that changes nothing, -and a landing the writer's unchanged check skips, append nothing; the writer and the sync carry -each landing's version; a change of identity follows a \lean{move}, and a re-key carries the -version; each of the six writes, its process killed or the write failed between the catalog's row -and the log's, leaves neither, in a batch too when its caller catches the error and goes on; a -failed batch leaves no log row; the genesis is the catalog, closes each tombstoned path's +path alive twice (SNP-5). Twenty-one more tests take the stage's cases: a write that changes +nothing, and a landing the writer's unchanged check skips, append nothing; the writer, in a +batched landing too, and the sync carry each landing's version; a change of identity follows a +\lean{move}, and a re-key carries the version; each of the six writes, its process killed or the +write failed between the catalog's row and the log's, leaves neither, in a batch too when its +caller catches the error and goes on, while the batch's other writes commit; a failed batch leaves +no log row; the genesis is the catalog, closes each tombstoned path's \lean{store} and ends at a horizon; a relabel into a class that has rows changes no row, closed rows and holes included; a history over two chains of a class follows its rule; a purge of an old version of a live path is a hole by all three reads at a cut where it was the head, and a purge of @@ -341,7 +342,10 @@ \section{Evaluation}\label{sec:eval} every statement by path is planned on the key index. Of 58 bugs seeded one at a time, from a write that skips its log row to a purge that keeps a title, every one fails the suite on a fixed seed but one that changes nothing, a write of a null over a null; the two that only the property -test catches fail it on four seeds more. +test catches fail it on four seeds more. A second review seeded 29 more, four of which passed (a +batch rolled back whole, a batched landing's version dropped, and a check of holes that left out a +column, twice); with the tests it asked for, those 29 and three seeded in the purge's emptying by +position all fail it on that seed. \paragraph{What is measured.} \Cref{tab:measure} gives two runs of the committed harness on two copy-on-write clones of the @@ -420,7 +424,7 @@ \section{Limitations} log writes the genesis, whichever process opens it, a reader's included, so that open needs the secret, as does every write that appends a row, and a lost secret leaves the log unwritable. Whether the genesis should move to a writer's first write, so that no reader needs the secret, is -left to the design's owner. Every head of a class is read at 3.5 to 3.9~$\mu$s a head returned, +left to the design's owner; a writer needs it under either choice. Every head of a class is read at 3.5 to 3.9~$\mu$s a head returned, which the stage that reads the notes at a cut must lower or bound first. The measurements are of one instance, one class and no deletions; a catalog of several classes, with identities apart from paths, is tested and not measured. From 245f938d88502d792c236ef1a2ca57d6691e9e51 Mon Sep 17 00:00:00 2001 From: Alberto Serrano-Calva Date: Thu, 12 Nov 2026 00:25:00 -0500 Subject: [PATCH 30/30] docs(readme): the counts from the second review's runs The deterministic tier is 3,655 tests at 77% coverage, the landing log's now 22 (3,654 before, with 21). No Lean file changed: the 375 judged statements, the ledger's 105 rows and the library's lines and attacks are as they were. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a7e32947..cf71bc5d 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![sorry](https://img.shields.io/badge/sorry-0-brightgreen)](formal/sorry-budget) [![kernels](https://img.shields.io/badge/kernel_replay-6_checkers-6f42c1)](formal/check.sh) [![attacks](https://img.shields.io/badge/attacks-232_with_controls-blue)](formal/PalaceTest) -[![tests](https://img.shields.io/badge/tests-3672-brightgreen)](docs/runbook.md) +[![tests](https://img.shields.io/badge/tests-3673-brightgreen)](docs/runbook.md) [![coverage](https://img.shields.io/badge/coverage-77%25-green)](pyproject.toml) [![mypy](https://img.shields.io/badge/mypy-0_errors_in_core-brightgreen)](pyproject.toml) [![sealed core](https://img.shields.io/badge/sealed_core-zero_egress-6f42c1)](scripts/check_imports.py) @@ -177,7 +177,7 @@ The build's own history is a dataset. Every commit's structure is snapshotted in ```sh uv sync --extra dev -uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,672 tests +uv run pytest -q -m 'not live and not podman and not needs_vault and not needs_restic' # the deterministic tier: 3,673 tests uv run mypy # strict core: 0 errors (the 67 in tests/ are pinned) uv run python scripts/check_imports.py # the sealed core names no network module uv run python -m ops.type_gate # every core-reaching package is type-checked