diff --git a/.changes/kv-rollback-map-acquisition.fixed.md b/.changes/kv-rollback-map-acquisition.fixed.md new file mode 100644 index 000000000000..7e0e21f020a6 --- /dev/null +++ b/.changes/kv-rollback-map-acquisition.fixed.md @@ -0,0 +1,2 @@ +Prevent C++ KV transactions from acquiring map views invalidated since their read version was selected, while permitting acquisition of unaffected maps. +See [transaction semantics](doc/build_apps/kv/kv_how_to.rst#transaction-semantics). diff --git a/lean/kv/Kv.lean b/lean/kv/Kv.lean index 910a1be0d81e..1174dbb19c75 100644 --- a/lean/kv/Kv.lean +++ b/lean/kv/Kv.lean @@ -4,6 +4,7 @@ public import Kv.Model public import Kv.Model.Transitions public import Kv.Model.Types public import Kv.Proofs.Deadlock +public import Kv.Proofs.Identity public import Kv.Proofs.Reachable public import Kv.Proofs.Replay public import Kv.Proofs.Witnesses diff --git a/lean/kv/Kv/Model/Transitions.lean b/lean/kv/Kv/Model/Transitions.lean index 0d96d2d085cb..7ad0a58d7ff9 100644 --- a/lean/kv/Kv/Model/Transitions.lean +++ b/lean/kv/Kv/Model/Transitions.lean @@ -31,9 +31,13 @@ def captureLocal (s : Store) (snap : Snapshot) (m : String) : Frame := else {} -/-- Whether a new map handle can still acquire its local snapshot. -/ +/-- Retention and birth/revision identities must agree with the original snapshot. -/ def available (s : Store) (snap : Snapshot) (m : String) : Bool := - mapAvailable s (captureLocal s snap m) m + let current := captureLocal s snap m + decide + (find current.births m = find snap.current.births m + ∧ revision current m = revision snap.current m) + && mapAvailable s current m /-- Computes independent local and global frames for one acquired map. -/ def captureGlobal (s : Store) (snap : Snapshot) (m : String) : GlobalView := @@ -228,6 +232,14 @@ def executeOperation (t : Tx) (op : Operation) : Tx × Output := (fun a b => decide (a.1 ≤ b.1))) ) +/-- Records rollback crossing without changing an attempt's captured views. -/ +def markRollback (sid : Nat) (truncates : Bool) (t : Tx) : Tx := + { + t with + crossedRollback := + t.crossedRollback || (truncates && t.store == sid && t.snapshot.isSome) + } + /-- Environment and transaction inputs. -/ inductive Action where /-- Create a live store with an explicit initial term. -/ @@ -242,8 +254,8 @@ inductive Action where | setTerm (store term : Nat) /-- Freeze read metadata. -/ | snapshot (store tx : Nat) - /-- Lazily acquire a map or record its unavailability. -/ - | acquire (store tx : Nat) (map : String) + /-- Acquire a retained map, optionally refusing conservatively after rollback crossing. -/ + | acquire (store tx : Nat) (map : String) (refuse : Bool := false) /-- Execute a KV operation. -/ | operation (store tx : Nat) (op : Operation) /-- Begin a commit. -/ @@ -301,14 +313,15 @@ def execute (w : State) (action : Action) : Option (State × Output) := do let next := { t with snapshot := some { current := s.head, term := s.term } } some ({ w with txs := set w.txs tid next }, .snapshot s.head.version s.global s.term) - | .acquire sid tid m => + | .acquire sid tid m refuse => let (s, t) ← lookupTx w sid tid let snap ← t.snapshot if t.phase != .active || (find t.globalViews m).isSome - || !t.normal.log.all (fun op => op.map != m) then + || !t.normal.log.all (fun op => op.map != m) + || (refuse && available s snap m && !t.crossedRollback) then none - else if available s snap m then + else if !refuse && available s snap m then let view := captureGlobal s snap m let next := { @@ -381,7 +394,11 @@ def execute (w : State) (action : Action) : Option (State × Output) := do none else let next := rollbackStore s requested term - some ({ w with stores := set w.stores sid next }, .rolledBack next.head.version) + let txs := + w.txs.map + fun (tid, t) => + (tid, markRollback sid (decide (next.head.version < s.head.version)) t) + some ({ stores := set w.stores sid next, txs }, .rolledBack next.head.version) /-- State projection of model execution. -/ def step (w : State) (action : Action) : Option State := diff --git a/lean/kv/Kv/Model/Types.lean b/lean/kv/Kv/Model/Types.lean index 17f71206d1b2..d0ab1f3f0782 100644 --- a/lean/kv/Kv/Model/Types.lean +++ b/lean/kv/Kv/Model/Types.lean @@ -257,6 +257,8 @@ structure Tx where normal : Normal String String String := {} /-- A required lazy acquisition could not retain its snapshot. -/ unavailable : Bool := false + /-- A truncating rollback of this store occurred after snapshot capture. -/ + crossedRollback : Bool := false /-- The commit lifecycle. -/ phase : Phase := .active deriving Repr, DecidableEq diff --git a/lean/kv/Kv/Proofs/Identity.lean b/lean/kv/Kv/Proofs/Identity.lean new file mode 100644 index 000000000000..0ca76e877155 --- /dev/null +++ b/lean/kv/Kv/Proofs/Identity.lean @@ -0,0 +1,595 @@ +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +module + +public import Kv.Model +public import CCF.Execution + +@[expose] public section + +namespace Kv.Proofs.Identity + +open Kv.Model + +private theorem find_set_cases {K V : Type} [DecidableEq K] + (xs : Assoc K V) (key other : K) (value : V) + : find (set xs key value) other + = if key = other then some value else find xs other := by + have erase_find (ys : Assoc K V) + : find (erase ys key) other = if key = other then none else find ys other := by + induction ys with + | nil => simp [erase, find] + | cons entry ys ih => + obtain ⟨k, v⟩ := entry + by_cases h : key = other <;> by_cases hk : k = key <;> + by_cases ho : k = other <;> simp_all [erase, find] + by_cases same : key = other <;> simp [Model.set, find, erase_find, same] + +private theorem find_image (db : Data) (m key : String) + : find (image db m) key = find db (m, key) := by + induction db with + | nil => rfl + | cons entry db ih => + rcases entry with ⟨⟨name, k⟩, cell⟩ + by_cases hm : name = m <;> by_cases hk : k = key <;> + simp_all [image, find, Prod.mk.injEq] + +private theorem image_erase (db : Data) (a : String × String) (m : String) + (absent : a.1 = m → find db a = none) + : image (erase db a) m = image db m := by + induction db with + | nil => rfl + | cons entry db ih => + obtain ⟨⟨name, key⟩, cell⟩ := entry + obtain ⟨am, ak⟩ := a + by_cases hm : name = am <;> by_cases hk : key = ak <;> + by_cases hn : name = m <;> simp_all [erase, image, find, Prod.mk.injEq] + +private theorem image_publish_unchanged (db : Data) (v : Nat) (ws : Pending) (m : String) + (unchanged : ∀ a value, (a, value) ∈ ws → a.1 = m → value = none ∧ find db a = none) + : image (publish db v ws) m = image db m := by + induction ws with + | nil => rfl + | cons entry ws ih => + obtain ⟨a, value⟩ := entry + have tail := ih (fun b value member => unchanged b value (by simp [member])) + cases value with + | none => + change image (erase (publish db v ws) a) m = image db m + rw [image_erase, tail] + intro same + have hf := congrArg (fun entries => find entries a.2) tail + rw [find_image, find_image, ← same] at hf + exact hf.trans (unchanged a none (by simp) same).2 + | some value => + have other : a.1 ≠ m := by + intro same + have impossible := (unchanged a (some value) (by simp) same).1 + cases impossible + have image_set (xs : Data) : image (set xs a { value, version := v }) m = image xs m := by + obtain ⟨name, key⟩ := a + simp only [Model.set, image, List.filterMap_cons, other, ↓reduceIte] + change image (erase xs (name, key)) m = image xs m + exact image_erase xs (name, key) m (by simp_all) + exact (image_set _).trans tail + +/-- A publication either gives a map a fresh revision or leaves its image and revision alone. -/ +private theorem advance_map (s : Store) (ws : Pending) (m : String) + : (revision (advance s ws).head m).identity = s.nextIdentity + ∨ (revision (advance s ws).head m = revision s.head m + ∧ image (advance s ws).head.data m = image s.head.data m) := by + let effective := fun (entry : (String × String) × Option String) => + entry.1.1 == m && (entry.2.isSome || (find s.head.data entry.1).isSome) + have revisions (xs : Pending) (rs : Assoc String Stamp) + : find (xs.foldl + (fun rs (a, value) => + if value.isSome || (find s.head.data a).isSome then + set rs a.1 { version := s.head.version + 1, identity := s.nextIdentity } + else rs) rs) m + = if xs.any effective then + some { version := s.head.version + 1, identity := s.nextIdentity } + else find rs m := by + induction xs generalizing rs with + | nil => rfl + | cons entry xs ih => + obtain ⟨a, value⟩ := entry + simp only [List.foldl_cons, List.any_cons] + rw [ih] + by_cases ht : value.isSome || (find s.head.data a).isSome + · by_cases hm : a.1 = m + · simp only [ht, ↓reduceIte, find_set_cases, hm, beq_self_eq_true, + effective, Bool.true_and, Bool.true_or] + split <;> rfl + · have he : effective (a, value) = false := by + dsimp only [effective] + have hb : (a.1 == m) = false := beq_eq_false_iff_ne.mpr hm + rw [hb] + rfl + simp only [ht, ↓reduceIte, find_set_cases, hm, he, Bool.false_or] + · have hf : (value.isSome || (find s.head.data a).isSome) = false := + Bool.eq_false_iff.mpr ht + have he : effective (a, value) = false := by + dsimp only [effective] + rw [hf] + exact Bool.and_false _ + simp only [hf, Bool.false_eq_true, ite_false, he, Bool.false_or] + have hr := revisions ws s.head.revisions + change find (advance s ws).head.revisions m = _ at hr + by_cases changed : ws.any effective + · left + rw [ite_eq_left changed] at hr + unfold revision + rw [hr] + rfl + · right + constructor + · rw [ite_eq_right changed] at hr + exact congrArg (fun x => x.getD {}) hr + · apply image_publish_unchanged + intro a value member same + have h := List.any_eq_false.mp (Bool.eq_false_iff.mpr changed) (a, value) member + simp only [effective, same, beq_self_eq_true, Bool.true_and] at h + cases value <;> cases hf : find s.head.data a <;> simp_all + +/-- Proof-only retained frames, including snapshots from discarded branches. -/ +private structure Archive (frames : List Frame) (next : Nat) : Prop where + /-- All retained revision identities precede the next publication. -/ + bounded : ∀ f ∈ frames, ∀ m, (revision f m).identity < next + /-- Equal map revisions identify equal map images throughout this store lifetime. -/ + coherent + : ∀ f ∈ frames, + ∀ g ∈ frames, + ∀ m, + (revision f m).identity = (revision g m).identity + → image f.data m = image g.data m + +/-- Adding a fresh publication preserves old-branch and new-branch map coherence. -/ +private theorem Archive.advance (s : Store) (ws : Pending) (frames : List Frame) + (valid : Archive frames s.nextIdentity) (head : s.head ∈ frames) + : Archive ((advance s ws).head :: frames) (s.nextIdentity + 1) := by + have compare (g : Frame) (member : g ∈ frames) (m : String) + (same : (revision (Model.advance s ws).head m).identity = (revision g m).identity) + : image (Model.advance s ws).head.data m = image g.data m := by + rcases advance_map s ws m with fresh | ⟨unchanged, data⟩ + · have bounded := valid.bounded g member m + rw [← same, fresh] at bounded + exact False.elim (Nat.lt_irrefl _ bounded) + · exact data.trans (valid.coherent s.head head g member m + ((congrArg Stamp.identity unchanged).symm.trans same)) + constructor + · intro f member m + rcases List.mem_cons.mp member with rfl | old + · rcases advance_map s ws m with fresh | ⟨unchanged, _⟩ + · rw [fresh]; exact Nat.lt_succ_self _ + · rw [unchanged] + exact Nat.lt_trans (valid.bounded s.head head m) (Nat.lt_succ_self _) + · exact Nat.lt_trans (valid.bounded f old m) (Nat.lt_succ_self _) + · intro f hf g hg m same + rcases List.mem_cons.mp hf with rfl | hf + · rcases List.mem_cons.mp hg with rfl | hg + · rfl + · exact compare g hg m same + · rcases List.mem_cons.mp hg with rfl | hg + · exact (compare f hf m same.symm).symm + · exact valid.coherent f hf g hg m same + +/-- Store histories and snapshots use one archive within each live store incarnation. -/ +private structure StoreIdentity (s : Store) (frames : List Frame) : Prop where + /-- The head belongs to the archive. -/ + head : s.head ∈ frames + /-- Every retained history frame belongs to the archive. -/ + history : ∀ f ∈ s.history, f ∈ frames + /-- The archive includes the empty placeholder and has fresh identities. -/ + empty : ({} : Frame) ∈ frames + /-- Revision identities determine data. -/ + valid : Archive frames s.nextIdentity + +/-- A new store begins a new identity scope. -/ +private theorem initial (term : Nat) : StoreIdentity { term } [{}] := by + refine ⟨by simp, ?_, by simp, ?_⟩ + · intro f member + exact member + · constructor + · intro f member m + have same : f = {} := List.mem_singleton.mp member + subst f + exact Nat.zero_lt_one + · intro f hf g hg m _ + have hfg : f = g := (List.mem_singleton.mp hf).trans (List.mem_singleton.mp hg).symm + rw [hfg] + +/-- Publication archives the new head without losing discarded snapshots. -/ +private theorem StoreIdentity.advance (s : Store) (frames : List Frame) + (valid : StoreIdentity s frames) (ws : Pending) + : StoreIdentity (advance s ws) ((advance s ws).head :: frames) := by + refine ⟨by simp, ?_, by simp [valid.empty], valid.valid.advance s ws frames valid.head⟩ + intro f member + rcases List.mem_cons.mp member with rfl | old + · exact List.mem_cons_self + · exact List.mem_cons_of_mem _ (valid.history f old) + +/-- A history cut either selects an archived frame or the archived empty placeholder. -/ +private theorem StoreIdentity.cut (s : Store) (frames : List Frame) + (valid : StoreIdentity s frames) (v : Nat) + : atCut s v ∈ frames := by + unfold atCut + cases found : s.history.find? (fun f => f.version ≤ v) with + | none => exact valid.empty + | some f => + exact valid.history f (List.mem_of_find?_eq_some found) + +/-- Rollback retains the archive and never recycles its publication counter. -/ +private theorem StoreIdentity.rollback (s : Store) (frames : List Frame) + (valid : StoreIdentity s frames) (v term : Nat) + : StoreIdentity (rollbackStore s v term) frames := by + refine ⟨valid.cut s frames (rollbackCut s v), ?_, valid.empty, valid.valid⟩ + intro f member + exact valid.history f (List.mem_filter.mp member).1 + +/-- Compaction does not affect the identity archive. -/ +private theorem StoreIdentity.compact (s : Store) (frames : List Frame) + (valid : StoreIdentity s frames) (v : Nat) + : StoreIdentity (compactStore s v) frames := by + unfold compactStore + split + · exact ⟨valid.head, valid.history, valid.empty, valid.valid⟩ + · exact valid + +/-- An available acquisition agrees with any archived original snapshot on that map. -/ +private theorem available_image (s : Store) (frames : List Frame) + (valid : StoreIdentity s frames) (snap : Snapshot) (captured : snap.current ∈ frames) + (m : String) (accepted : available s snap m = true) + : image (captureGlobal s snap m).current.data m = image snap.current.data m := by + have localMember : captureLocal s snap m ∈ frames := by + unfold captureLocal + split + · exact valid.cut s frames snap.current.version + · exact valid.empty + have same : revision (captureLocal s snap m) m = revision snap.current m := by + have h : decide + (find (captureLocal s snap m).births m = find snap.current.births m + ∧ revision (captureLocal s snap m) m = revision snap.current m) = true + ∧ mapAvailable s (captureLocal s snap m) m = true := by + simpa only [available, Bool.and_eq_true] using accepted + exact (of_decide_eq_true h.1).2 + have data := valid.valid.coherent _ localMember _ captured m (congrArg Stamp.identity same) + dsimp only [captureGlobal] + split <;> exact data + +private def Archives := Nat → List Frame + +private def AttemptIdentity (w : State) (archives : Archives) (t : Tx) : Prop := + (∃ s, find w.stores t.store = some s) + ∧ ∀ snap, t.snapshot = some snap → snap.current ∈ archives t.store + +private structure StateIdentity (w : State) (archives : Archives) : Prop where + stores : ∀ sid s, find w.stores sid = some s → StoreIdentity s (archives sid) + txs : ∀ tid t, find w.txs tid = some t → AttemptIdentity w archives t + +private theorem bind_ok {α β : Type} {x : Option α} {f : α → Option β} {b : β} + (h : x.bind f = some b) + : ∃ a, x = some a ∧ f a = some b := by + cases x with + | none => cases h + | some a => exact ⟨a, rfl, h⟩ + +private theorem find_mem {K V : Type} [DecidableEq K] (xs : Assoc K V) (k : K) (v : V) + (found : find xs k = some v) + : (k, v) ∈ xs := by + induction xs with + | nil => cases found + | cons p xs ih => + obtain ⟨a, value⟩ := p + by_cases same : a = k + · simp only [find, same, ↓reduceIte, Option.some.injEq] at found + subst a; subst value + exact List.mem_cons_self + · exact List.mem_cons_of_mem _ (ih (by simpa only [find, same, ↓reduceIte] using found)) + +private theorem find_erase_cases {K V : Type} [DecidableEq K] + (xs : Assoc K V) (id key : K) + : find (erase xs id) key = if id = key then none else find xs key := by + induction xs with + | nil => simp [erase, find] + | cons p xs ih => + obtain ⟨k, value⟩ := p + by_cases h : id = key <;> by_cases hk : k = id <;> + by_cases he : k = key <;> simp_all [erase, find] + +private theorem lookup (w : State) (archives : Archives) + (_valid : StateIdentity w archives) (sid tid : Nat) (s : Store) (t : Tx) + (found : lookupTx w sid tid = some (s, t)) + : find w.stores sid = some s ∧ find w.txs tid = some t ∧ t.store = sid := by + obtain ⟨s', hs, rest⟩ := bind_ok found + obtain ⟨t', ht, rest⟩ := bind_ok rest + split at rest + next same => + cases rest + exact ⟨hs, ht, by simpa using same⟩ + next => cases rest + +private theorem update_tx (w : State) (archives : Archives) + (valid : StateIdentity w archives) (tid : Nat) (t : Tx) + (holds : AttemptIdentity w archives t) + : StateIdentity { w with txs := set w.txs tid t } archives := by + refine ⟨valid.stores, ?_⟩ + intro key next found + rw [find_set_cases] at found + split at found + · cases found; exact holds + · exact valid.txs key next found + +private theorem fields (w : State) (archives : Archives) (t next : Tx) + (valid : AttemptIdentity w archives t) + (store : next.store = t.store) (snapshot : next.snapshot = t.snapshot) + : AttemptIdentity w archives next := by + simpa only [AttemptIdentity, store, snapshot] using valid + +private def replace (archives : Archives) (sid : Nat) (frames : List Frame) : Archives := + fun other => if other = sid then frames else archives other + +private theorem update_store (w : State) (archives : Archives) + (valid : StateIdentity w archives) (sid : Nat) (s : Store) (frames : List Frame) + (holds : StoreIdentity s frames) + (keep + : ∀ tid t, + find w.txs tid = some t + → ∀ snap, + t.snapshot = some snap → snap.current ∈ replace archives sid frames t.store) + : StateIdentity { w with stores := set w.stores sid s } + (replace archives sid frames) := by + constructor + · intro key next found + rw [find_set_cases] at found + split at found + next same => + cases found + simpa only [replace, same, ↓reduceIte] using holds + next different => + simpa only [replace, Ne.symm different, ↓reduceIte] using valid.stores key next found + · intro tid t found + refine ⟨?_, keep tid t found⟩ + obtain ⟨before, live⟩ := (valid.txs tid t found).1 + by_cases same : sid = t.store + · exact ⟨s, by simp only [find_set_cases, same, ↓reduceIte]⟩ + · exact ⟨before, by simpa only [find_set_cases, same, ↓reduceIte] using live⟩ + +private theorem keep_extended (w : State) (archives : Archives) + (valid : StateIdentity w archives) (sid : Nat) (frames : List Frame) + (extension : ∀ f ∈ archives sid, f ∈ frames) + : ∀ tid t, + find w.txs tid = some t + → ∀ snap, + t.snapshot = some snap + → snap.current ∈ replace archives sid frames t.store := by + intro tid t found snap captured + have member := (valid.txs tid t found).2 snap captured + by_cases same : t.store = sid + · simp only [replace, same, ↓reduceIte] + exact extension _ (by simpa only [same] using member) + · simpa only [replace, same, ↓reduceIte] using member + +private theorem operation_fields (t : Tx) (op : Operation) + : (executeOperation t op).1.store = t.store + ∧ (executeOperation t op).1.snapshot = t.snapshot := by + have clear (entries : Assoc String String) (m : String) (tx : Tx) + : (entries.foldl + (fun acc (k, _) => + { acc with normal := recordOp acc.data acc.normal (.write (m, k) none) }) + tx).store = tx.store + ∧ (entries.foldl + (fun acc (k, _) => + { acc with normal := recordOp acc.data acc.normal (.write (m, k) none) }) + tx).snapshot = tx.snapshot := by + induction entries generalizing tx with + | nil => exact ⟨rfl, rfl⟩ + | cons entry _entries ih => exact ih _ + cases op <;> try exact ⟨rfl, rfl⟩ + case get m k global => cases global <;> exact ⟨rfl, rfl⟩ + case has m k global => cases global <;> exact ⟨rfl, rfl⟩ + case range m lower upper => + dsimp only [executeOperation] + split <;> exact ⟨rfl, rfl⟩ + case clear m => exact clear _ m _ + +private theorem execute_identity (w next : State) (archives : Archives) + (valid : StateIdentity w archives) (a : Action) (output : Output) + (accepted : execute w a = some (next, output)) + : ∃ nextArchives, StateIdentity next nextArchives := by + cases a with + | storeCreate sid term => + dsimp only [execute] at accepted + split at accepted + · cases accepted + next absent => + cases accepted + refine ⟨_, update_store w archives valid sid _ [{}] (initial term) ?_⟩ + intro tid t live snap captured + have identity := valid.txs tid t live + have different : t.store ≠ sid := by + intro same + obtain ⟨s, hs⟩ := identity.1 + have hs' : find w.stores sid = some s := same ▸ hs + simp only [hs', Option.isSome_some] at absent + exact absent True.intro + simpa only [replace, different, ↓reduceIte] using identity.2 snap captured + | storeEnd sid => + obtain ⟨_, _, rest⟩ := bind_ok accepted + try dsimp only at rest + split at rest + · cases rest + next noTx => + cases rest + refine ⟨archives, ?_, ?_⟩ + · intro key s found + rw [find_erase_cases] at found + split at found + · cases found + · exact valid.stores key s found + · intro tid t found + have identity := valid.txs tid t found + refine ⟨?_, identity.2⟩ + have different : t.store ≠ sid := by + intro same + have member := find_mem w.txs tid t found + have yes : w.txs.any (fun (_, tx) => tx.store == sid) = true := + List.any_eq_true.mpr ⟨(tid, t), member, by simp only [same, beq_self_eq_true]⟩ + exact noTx yes + obtain ⟨s, hs⟩ := identity.1 + refine ⟨s, ?_⟩ + simpa only [find_erase_cases, Ne.symm different, ↓reduceIte] using hs + | txCreate sid tid => + obtain ⟨s, found, rest⟩ := bind_ok accepted + try dsimp only at rest + split at rest + · cases rest + · cases rest + exact ⟨archives, update_tx w archives valid tid _ ⟨⟨s, found⟩, by simp⟩⟩ + | txEnd sid tid => + obtain ⟨_, _, rest⟩ := bind_ok accepted + try dsimp only at rest + cases rest + refine ⟨archives, valid.stores, ?_⟩ + intro key t found + rw [find_erase_cases] at found + split at found + · cases found + · exact valid.txs key t found + | setTerm sid term => + obtain ⟨s, found, rest⟩ := bind_ok accepted + try dsimp only at rest + split at rest + · cases rest + · cases rest + have inv := valid.stores sid s found + exact ⟨_, update_store w archives valid sid _ _ + ⟨inv.head, inv.history, inv.empty, inv.valid⟩ + (keep_extended w archives valid sid _ (fun _ h => h))⟩ + | snapshot sid tid => + obtain ⟨⟨s, t⟩, found, rest⟩ := bind_ok accepted + try dsimp only at rest + obtain ⟨hs, ht, owner⟩ := lookup w archives valid sid tid s t found + split at rest + · cases rest + · cases rest + refine ⟨archives, update_tx w archives valid tid _ ⟨(valid.txs tid t ht).1, ?_⟩⟩ + intro snap captured + cases captured + simpa only [owner] using (valid.stores sid s hs).head + | acquire sid tid m refuse => + obtain ⟨⟨s, t⟩, found, rest⟩ := bind_ok accepted + try dsimp only at rest + obtain ⟨_, ht, _⟩ := lookup w archives valid sid tid s t found + obtain ⟨snap, _, rest⟩ := bind_ok rest + try dsimp only at rest + split at rest + · cases rest + · split at rest <;> cases rest <;> + exact ⟨archives, update_tx w archives valid tid _ + (fields w archives t _ (valid.txs tid t ht) rfl rfl)⟩ + | operation sid tid op => + obtain ⟨⟨s, t⟩, found, rest⟩ := bind_ok accepted + try dsimp only at rest + obtain ⟨_, ht, _⟩ := lookup w archives valid sid tid s t found + split at rest + · cases rest + · cases rest + exact ⟨archives, update_tx w archives valid tid _ + (fields w archives t _ (valid.txs tid t ht) + (operation_fields t op).1 (operation_fields t op).2)⟩ + | commitBegin sid tid => + obtain ⟨⟨s, t⟩, found, rest⟩ := bind_ok accepted + try dsimp only at rest + obtain ⟨_, ht, _⟩ := lookup w archives valid sid tid s t found + split at rest + · cases rest + · cases rest + exact ⟨archives, update_tx w archives valid tid _ + (fields w archives t _ (valid.txs tid t ht) rfl rfl)⟩ + | apply sid tid => + obtain ⟨⟨s, t⟩, found, rest⟩ := bind_ok accepted + try dsimp only at rest + obtain ⟨hs, ht, _⟩ := lookup w archives valid sid tid s t found + split at rest + · cases rest + · obtain ⟨store, applied, rest⟩ := bind_ok rest + unfold tryApply at applied + split at applied + · cases applied + try dsimp only at rest + cases rest + have inv := valid.stores sid s hs + have updated := update_store w archives valid sid _ _ + (inv.advance s (archives sid) t.normal.writes) + (keep_extended w archives valid sid _ (fun _ h => List.mem_cons_of_mem _ h)) + refine ⟨_, update_tx _ _ updated tid _ ?_⟩ + exact fields _ _ t _ (updated.txs tid t ht) rfl rfl + · cases applied + | commitResult sid tid result => + obtain ⟨⟨s, t⟩, found, rest⟩ := bind_ok accepted + try dsimp only at rest + obtain ⟨_, ht, _⟩ := lookup w archives valid sid tid s t found + cases phase : t.phase <;> simp only [phase] at rest + all_goals try split at rest + all_goals try dsimp only at rest + all_goals cases rest + all_goals exact ⟨archives, update_tx w archives valid tid _ + (fields w archives t _ (valid.txs tid t ht) rfl rfl)⟩ + | compact sid requested => + obtain ⟨s, found, rest⟩ := bind_ok accepted + try dsimp only at rest + cases rest + exact ⟨_, update_store w archives valid sid _ _ + ((valid.stores sid s found).compact s _ requested) + (keep_extended w archives valid sid _ (fun _ h => h))⟩ + | rollback sid requested term => + obtain ⟨s, found, rest⟩ := bind_ok accepted + try dsimp only at rest + split at rest + · cases rest; exact ⟨archives, valid⟩ + · split at rest + · cases rest + · cases rest + have updated := update_store w archives valid sid _ _ + ((valid.stores sid s found).rollback s _ requested term) + (keep_extended w archives valid sid _ (fun _ h => h)) + refine ⟨_, updated.stores, ?_⟩ + intro tid t live + have find_map {V : Type} (xs : Assoc Nat V) (f : V → V) (key : Nat) + : find (xs.map fun (k, v) => (k, f v)) key = (find xs key).map f := by + induction xs with + | nil => rfl + | cons p xs ih => + obtain ⟨k, value⟩ := p + by_cases same : k = key <;> simp [find, same, ih] + rw [find_map] at live + obtain ⟨before, source, same⟩ := Option.map_eq_some_iff.mp live + subst t + exact fields _ _ before _ (updated.txs tid before source) rfl rfl + +private theorem reachable_identity (w : State) (reachable : transitionSystem.Reachable w) + : ∃ archives, StateIdentity w archives := by + induction reachable using @CCF.TransitionSystem.Reachable.rec transitionSystem with + | initial initialized => + cases initialized + exact ⟨fun _ => [], ⟨by simp [find], by simp [find]⟩⟩ + | @step w next action _ transition ih => + obtain ⟨archives, valid⟩ := ih + obtain ⟨⟨state, output⟩, executed, same⟩ := Option.map_eq_some_iff.mp transition + cases same + exact execute_identity w state archives valid action output executed + +/-- Every reachable acquisition's revision identity identifies the original snapshot image. -/ +theorem reachable_available_image (w : State) (sid tid : Nat) (s : Store) (t : Tx) + (snap : Snapshot) (m : String) (reachable : transitionSystem.Reachable w) + (found : lookupTx w sid tid = some (s, t)) (captured : t.snapshot = some snap) + (accepted : available s snap m = true) + : image (captureGlobal s snap m).current.data m = image snap.current.data m := by + obtain ⟨archives, valid⟩ := reachable_identity w reachable + obtain ⟨hs, ht, owner⟩ := lookup w archives valid sid tid s t found + have member := (valid.txs tid t ht).2 snap captured + rw [owner] at member + exact available_image s (archives sid) (valid.stores sid s hs) snap member m accepted + +end Kv.Proofs.Identity diff --git a/lean/kv/Kv/Proofs/Reachable.lean b/lean/kv/Kv/Proofs/Reachable.lean index a4ffc1677fe2..e13af9471789 100644 --- a/lean/kv/Kv/Proofs/Reachable.lean +++ b/lean/kv/Kv/Proofs/Reachable.lean @@ -6,6 +6,8 @@ module public import Kv.Properties.Invariants public import CCF.Execution +import Kv.Proofs.Identity + @[expose] public section namespace Kv.Proofs.Reachable @@ -14,6 +16,15 @@ open Kv.Model Kv.Properties variable {M K V : Type} +/-- Mapping association-list values commutes with first-match lookup. -/ +theorem find_map_values [DecidableEq K] (xs : Assoc K V) (key : K) (f : V → V) + : find (xs.map fun (k, v) => (k, f v)) key = (find xs key).map f := by + induction xs with + | nil => rfl + | cons entry xs ih => + obtain ⟨k, v⟩ := entry + by_cases same : k = key <;> simp [find, same, ih] + /-- The reports agree with the computed local operation. -/ private def observes {M K V : Type} [DecidableEq M] [DecidableEq K] [DecidableEq V] (db : DB M K V) (ws : Writes M K V) @@ -63,6 +74,16 @@ private structure TxInvariant (t : Tx) : Prop where t.snapshot = some snap → ∃ s : Store, StoreInvariant s ∧ snap.current = s.head /-- Each acquired global view has valid provenance. -/ globals : ∀ map view, find t.globalViews map = some view → GlobalInvariant view + /-- The original snapshot reproduces the normal view, before and after lazy acquisitions. -/ + original + : ∀ snap, + t.snapshot = some snap + → normalRun snap.current.data {} t.normal.log = some t.normal + /-- Every acquired map agrees with the attempt's original snapshot. -/ + maps + : ∀ m view, + find t.globalViews m = some view + → ∃ snap, t.snapshot = some snap ∧ image t.data m = image snap.current.data m /-- Internal consistency of every live store and attempt. -/ private structure StateInvariant (w : State) : Prop where @@ -244,6 +265,23 @@ private theorem find_image (db : Data) (m key : String) by_cases hm : name = m <;> by_cases hk : k = key <;> simp_all [image, find, Prod.mk.injEq] +private theorem normalStep_images (db original : Data) + (n : Normal String String String) (op : NormalOp String String String) + (same : image db op.map = image original op.map) + : normalStep db n op = normalStep original n op := by + cases op with + | read a v | previous a v => + have hf := congrArg (fun entries => find entries a.2) same + simp only [NormalOp.map, find_image] at hf + change find db a = find original a at hf + simp only [normalStep, recordOp, observes, valueAt, previousAt, needs, hf] + rfl + | scan m entries => + simp only [NormalOp.map] at same + simp only [normalStep, recordOp, observes, scanAt, needs, same] + rfl + | write => rfl + private theorem normalStep_pinData (db acquired : Data) (m : String) (n : Normal String String String) (op : NormalOp String String String) (h : op.map ≠ m) @@ -345,7 +383,7 @@ private theorem rollback_invariant (s : Store) (valid : StoreInvariant s) (v ter cut_global_bound s valid _ within (Nat.le_max_left _ _)⟩ private theorem tx_initial (sid : Nat) : TxInvariant { store := sid } := by - refine ⟨rfl, ?_, ?_⟩ <;> simp [find] + refine ⟨rfl, ?_, ?_, ?_, ?_⟩ <;> simp [find] private theorem captureGlobal_invariant (s : Store) (valid : StoreInvariant s) (snap : Snapshot) (map : String) @@ -358,20 +396,29 @@ private theorem captureGlobal_invariant (s : Store) (valid : StoreInvariant s) private theorem snapshot_invariant (s : Store) (store : StoreInvariant s) (term : Nat) (t : Tx) (valid : TxInvariant t) (fresh : t.snapshot = none) : TxInvariant { t with snapshot := some { current := s.head, term } } := by - refine ⟨snapshot_normal t valid.normal t.data fresh, ?_, valid.globals⟩ - intro snap captured - cases captured - exact ⟨s, store, rfl⟩ + refine ⟨snapshot_normal t valid.normal t.data fresh, ?_, valid.globals, ?_, ?_⟩ + · intro snap captured + cases captured + exact ⟨s, store, rfl⟩ + · intro snap captured + cases captured + exact snapshot_normal t valid.normal s.head.data fresh + · intro m view found + obtain ⟨snap, captured, _⟩ := valid.maps m view found + rw [fresh] at captured + cases captured private theorem tx_fields_invariant (t next : Tx) (valid : TxInvariant t) (snapshot : next.snapshot = t.snapshot) (data : next.data = t.data) (normal : next.normal = t.normal) (globals : next.globalViews = t.globalViews) : TxInvariant next := by - rcases valid with ⟨hn, hs, hg⟩ + rcases valid with ⟨hn, hs, hg, ho, hm⟩ constructor · simpa [NormalInvariant, snapshot, data, normal] using hn · simpa [snapshot] using hs · simpa [globals] using hg + · simpa only [snapshot, normal] using ho + · simpa only [snapshot, data, globals] using hm private theorem lookup_set_invariant [DecidableEq K] (P : V → Prop) (xs : Assoc K V) (valid : ∀ key value, find xs key = some value → P value) @@ -622,11 +669,9 @@ private theorem durable_cut_survives_rollback (s : Store) (v term cut : Nat) (Nat.le_trans hcut valid.globalBound)] private theorem transaction_snapshot_serial (t : Tx) (snap : Snapshot) - (valid : NormalInvariant t) (hs : t.snapshot = some snap) - : serialRun t.data [] t.normal.log = some t.normal.writes := by - have hc : normalRun t.data {} t.normal.log = some t.normal := by - simpa [NormalInvariant, hs] using valid - exact readonly_snapshot_serial t.data t.normal.log t.normal hc + (valid : TxInvariant t) (hs : t.snapshot = some snap) + : serialRun snap.current.data [] t.normal.log = some t.normal.writes := by + exact readonly_snapshot_serial snap.current.data t.normal.log t.normal (valid.original snap hs) /-- A valid attempt that passes OCC agrees with serial execution on the current head. -/ private theorem transaction_application_serial (s : Store) (t : Tx) (snap : Snapshot) @@ -681,10 +726,17 @@ private theorem executable_branch_serializability (s final : Store) (ts : List T private theorem record_invariant (t : Tx) (valid : TxInvariant t) (snap : Snapshot) (captured : t.snapshot = some snap) (op : NormalOp String String String) (observed : observes t.data t.normal.writes op = true) + (agreement : normalStep snap.current.data t.normal op = normalStep t.data t.normal op) : TxInvariant { t with normal := recordOp t.data t.normal op } := by - refine ⟨?_, valid.snapshot, valid.globals⟩ - exact operation_normal t valid.normal snap _ op captured - (by simp [normalStep, observed]) + have step : normalStep t.data t.normal op = some (recordOp t.data t.normal op) := by + simp [normalStep, observed] + refine ⟨operation_normal t valid.normal snap _ op captured step, + valid.snapshot, valid.globals, ?_, valid.maps⟩ + intro original same + have equal : original = snap := Option.some.inj (same.symm.trans captured) + subst original + exact normalRun_extend snap.current.data _ _ op (valid.original snap captured) + (agreement.trans step) private theorem clear_invariant (t : Tx) (valid : TxInvariant t) (snap : Snapshot) (captured : t.snapshot = some snap) (m : String) (entries : Assoc String String) @@ -696,35 +748,47 @@ private theorem clear_invariant (t : Tx) (valid : TxInvariant t) (snap : Snapsho induction entries generalizing t with | nil => exact valid | cons entry _rest ih => - exact ih _ (record_invariant t valid snap captured (.write (m, entry.1) none) rfl) + exact ih _ (record_invariant t valid snap captured (.write (m, entry.1) none) rfl rfl) captured private theorem operation_invariant (t : Tx) (valid : TxInvariant t) (snap : Snapshot) (captured : t.snapshot = some snap) (op : Operation) + (acquired : (find t.globalViews op.map).isSome = true) : TxInvariant (executeOperation t op).1 := by + obtain ⟨view, found⟩ := Option.isSome_iff_exists.mp acquired + obtain ⟨original, same, data⟩ := valid.maps op.map view found + have equal : original = snap := Option.some.inj (same.symm.trans captured) + subst original + have agreement (normalOp : NormalOp String String String) (map : normalOp.map = op.map) + : normalStep snap.current.data t.normal normalOp = normalStep t.data t.normal normalOp := + normalStep_images _ _ _ _ (by simpa only [map] using data.symm) cases op with | get m k global => cases global - · exact record_invariant t valid snap captured _ (by simp [observes]) + · exact record_invariant t valid snap captured _ (by simp [observes]) (agreement _ rfl) · exact valid | has m k global => cases global - · exact record_invariant t valid snap captured _ (by simp [observes]) + · exact record_invariant t valid snap captured _ (by simp [observes]) (agreement _ rfl) · exact valid - | previous m k => exact record_invariant t valid snap captured _ (by simp [observes]) - | write m k v => exact record_invariant t valid snap captured _ rfl + | previous m k => + exact record_invariant t valid snap captured _ (by simp [observes]) + (agreement _ rfl) + | write m k v => exact record_invariant t valid snap captured _ rfl rfl | size m => exact record_invariant t valid snap captured _ (by simp [observes]) + (agreement _ rfl) | scan m => exact record_invariant t valid snap captured _ (by simp [observes]) + (agreement _ rfl) | range m lower upper => dsimp only [executeOperation, Operation.map] split · exact valid - · exact record_invariant t valid snap captured _ (by simp [observes]) + · exact record_invariant t valid snap captured _ (by simp [observes]) (agreement _ rfl) | clear m => exact clear_invariant _ - (record_invariant t valid snap captured _ (by simp [observes])) + (record_invariant t valid snap captured _ (by simp [observes]) (agreement _ rfl)) snap captured m _ private theorem option_bind_ok {α β : Type} {x : Option α} {f : α → Option β} {b : β} @@ -755,19 +819,36 @@ private theorem update_store (w : State) (valid : StateInvariant w) (sid : Nat) ⟨lookup_set_invariant StoreInvariant w.stores valid.stores sid s holds, valid.txs⟩ private theorem acquired_invariant (s : Store) (store : StoreInvariant s) (t : Tx) - (valid : TxInvariant t) (snap : Snapshot) (_captured : t.snapshot = some snap) + (valid : TxInvariant t) (snap : Snapshot) (captured : t.snapshot = some snap) (m : String) (unused : t.normal.log.all (fun op => op.map != m) = true) + (agreement + : image (captureGlobal s snap m).current.data m = image snap.current.data m) : TxInvariant { t with globalViews := set t.globalViews m (captureGlobal s snap m) data := pinData t.data m (captureGlobal s snap m).current.data } := by - refine ⟨acquisition_normal t valid.normal m _ unused, valid.snapshot, ?_⟩ - exact lookup_set_invariant GlobalInvariant t.globalViews valid.globals m _ - (captureGlobal_invariant s store snap m) + refine ⟨acquisition_normal t valid.normal m _ unused, valid.snapshot, ?_, + valid.original, ?_⟩ + · exact lookup_set_invariant GlobalInvariant t.globalViews valid.globals m _ + (captureGlobal_invariant s store snap m) + · intro name view found + rw [find_set_cases] at found + split at found + next same => + subst name + refine ⟨snap, captured, ?_⟩ + rw [pinData, image_append, image_filter t.data m (fun name => name != m), + image_filter _ m (fun name => name == m)] + simpa only [beq_self_eq_true, bne_self_eq_false, Bool.false_eq_true, + ite_false, ite_true, List.nil_append] using agreement + next different => + obtain ⟨original, hs, data⟩ := valid.maps name view found + exact ⟨original, hs, (pinData_other _ _ _ _ (Ne.symm different)).trans data⟩ private theorem execute_invariant (w next : State) (valid : StateInvariant w) + (reachable : Model.transitionSystem.Reachable w) (a : Action) (output : Output) (accepted : execute w a = some (next, output)) : StateInvariant next := by cases a with @@ -819,7 +900,7 @@ private theorem execute_invariant (w next : State) (valid : StateInvariant w) · simp [captured] at condition cases rest exact update_tx w valid tid _ (snapshot_invariant s inv.1 s.term t inv.2 fresh) - | acquire sid tid m => + | acquire sid tid m refuse => obtain ⟨⟨s, t⟩, found, rest⟩ := option_bind_ok accepted try dsimp only at rest have inv := lookup_invariant w valid sid tid s t found @@ -829,14 +910,23 @@ private theorem execute_invariant (w next : State) (valid : StateInvariant w) · cases rest · have unused : t.normal.log.all (fun op => op.map != m) = true := by have condition : (t.phase != .active || (find t.globalViews m).isSome - || !t.normal.log.all (fun op => op.map != m)) = false := by + || !t.normal.log.all (fun op => op.map != m) + || (refuse && available s snap m && !t.crossedRollback)) = false := by apply Bool.eq_false_iff.mpr assumption cases used : t.normal.log.all (fun op => op.map != m) <;> simp [used] at condition ⊢ split at rest - · cases rest - exact update_tx w valid tid _ (acquired_invariant s inv.1 t inv.2 snap captured m unused) + · have available' : available s snap m = true := by + have condition : (!refuse && available s snap m) = true := by assumption + have pair : (!refuse) = true ∧ available s snap m = true := by + simpa only [Bool.and_eq_true] using condition + exact pair.2 + cases rest + exact update_tx w valid tid _ + (acquired_invariant s inv.1 t inv.2 snap captured m unused + (Identity.reachable_available_image w sid tid s t snap m reachable found + captured available')) · cases rest exact update_tx w valid tid _ (tx_fields_invariant t _ inv.2 rfl rfl rfl rfl) | operation sid tid op => @@ -850,8 +940,11 @@ private theorem execute_invariant (w next : State) (valid : StateInvariant w) | none => simp [captured] at * | some snap => exact ⟨snap, rfl⟩ obtain ⟨snap, captured⟩ := captured + have acquired : (find t.globalViews op.map).isSome = true := by + cases h : find t.globalViews op.map <;> simp_all cases rest - exact update_tx w valid tid _ (operation_invariant t inv.2 snap captured op) + exact update_tx w valid tid _ + (operation_invariant t inv.2 snap captured op acquired) | commitBegin sid tid => obtain ⟨⟨s, t⟩, found, rest⟩ := option_bind_ok accepted try dsimp only at rest @@ -895,7 +988,13 @@ private theorem execute_invariant (w next : State) (valid : StateInvariant w) · split at rest · cases rest · cases rest - exact update_store w valid sid _ (rollback_invariant s (valid.stores sid s found) requested term) + refine ⟨(update_store w valid sid _ (rollback_invariant s + (valid.stores sid s found) requested term)).stores, ?_⟩ + intro tid t live + rw [find_map_values] at live + obtain ⟨before, source, same⟩ := Option.map_eq_some_iff.mp live + subst t + exact tx_fields_invariant before _ (valid.txs tid before source) rfl rfl rfl rfl private theorem reachable_invariant (w : State) (reachable : Model.transitionSystem.Reachable w) @@ -909,7 +1008,7 @@ private theorem reachable_invariant (w : State) obtain ⟨pair, executed, state⟩ := Option.map_eq_some_iff.mp transition obtain ⟨nextState, output⟩ := pair cases state - exact execute_invariant _ _ ih action output executed + exact execute_invariant _ _ ih ‹Model.transitionSystem.Reachable w› action output executed private theorem History.head_cells_bounded (fs : List Frame) (n : Nat) (shape : History fs n) @@ -999,16 +1098,16 @@ theorem reachable_store_data_invariants using History.head_cells_bounded s.history s.head.version inv.historyShape ⟩ -/-- Every model-reachable captured normal program reproduces its staged writes on pinned data. -/ +/-- Every model-reachable normal program reproduces its staged writes on its original snapshot. -/ theorem reachable_transaction_snapshot_serial : ∀ (w : State) (tid : Nat) (t : Tx) (snap : Snapshot), Model.transitionSystem.Reachable w → find w.txs tid = some t → t.snapshot = some snap - → serialRun t.data [] t.normal.log = some t.normal.writes := by + → serialRun snap.current.data [] t.normal.log = some t.normal.writes := by intro w tid t snap reachable found captured exact transaction_snapshot_serial t snap - ((reachable_invariant w reachable).txs tid t found).normal captured + ((reachable_invariant w reachable).txs tid t found) captured /-- OCC-valid model-reachable programs have an independent serial witness at application. -/ theorem reachable_transaction_application_serial diff --git a/lean/kv/Kv/Proofs/Replay.lean b/lean/kv/Kv/Proofs/Replay.lean index 2e96fd7fb0d8..701ba42313d5 100644 --- a/lean/kv/Kv/Proofs/Replay.lean +++ b/lean/kv/Kv/Proofs/Replay.lean @@ -243,7 +243,7 @@ theorem execute_retains (w next : Model.State) (tid : Nat) (before : Model.Tx) refine ⟨rfl, ?_, fun _ _ h => ⟨h, rfl⟩⟩ intro snap captured simp [captured] at enabled - | acquire sid actual m => + | acquire sid actual m refuse => dsimp only [execute] at accepted obtain ⟨⟨s, t⟩, lookup, accepted⟩ := option_bind_ok accepted dsimp only at accepted @@ -303,14 +303,18 @@ theorem execute_retains (w next : Model.State) (tid : Nat) (before : Model.Tx) exact unchanged w _ tid before live rfl | rollback sid requested term => dsimp only [execute] at accepted - obtain ⟨_, _, accepted⟩ := option_bind_ok accepted + obtain ⟨s, _, accepted⟩ := option_bind_ok accepted split at accepted · cases accepted exact unchanged w _ tid before live rfl · split at accepted · cases accepted · cases accepted - exact unchanged w _ tid before live rfl + refine ⟨markRollback sid (decide + ((rollbackStore s requested term).head.version < s.head.version)) before, ?_, ?_⟩ + · rw [Reachable.find_map_values, live] + rfl + · exact ⟨rfl, fun _ h => h, fun _ _ h => ⟨h, rfl⟩⟩ /-- Captured-view preservation holds throughout every actual model run in an attempt segment. -/ theorem run_retains (w final : Model.State) (tid : Nat) (before : Model.Tx) @@ -391,16 +395,18 @@ theorem step_capture_cut_values /-- Map acquisition installs its selected local/global frames and computes their revisions. -/ theorem step_map_capture : ∀ (w next : State) (sid tid localVersion globalVersion : Nat) (map : String) - (s : Store) (before after : Tx) (snap : Snapshot), + (s : Store) (before after : Tx) (snap : Snapshot) (refuse : Bool), lookupTx w sid tid = some (s, before) → before.snapshot = some snap - → execute w (.acquire sid tid map) + → execute w (.acquire sid tid map refuse) = some (next, .acquired localVersion globalVersion) → find next.txs tid = some after → find after.globalViews map = some (captureGlobal s snap map) ∧ localVersion = (revision (captureLocal s snap map) map).version - ∧ globalVersion = (revision (captureGlobal s snap map).frame map).version := by - intro w next sid tid localVersion globalVersion map s before after snap source captured accepted live + ∧ globalVersion = (revision (captureGlobal s snap map).frame map).version + ∧ find (captureLocal s snap map).births map = find snap.current.births map + ∧ revision (captureLocal s snap map) map = revision snap.current map := by + intro w next sid tid localVersion globalVersion map s before after snap refuse source captured accepted live dsimp only [execute] at accepted rw [source] at accepted obtain ⟨_, selected, accepted⟩ := option_bind_ok accepted @@ -412,14 +418,71 @@ theorem step_map_capture split at accepted · cases accepted · split at accepted - · cases accepted + · rename_i permitted + simp only [available, Bool.and_eq_true, decide_eq_true_eq] at permitted + cases accepted simp only [find_set_same, Option.some.injEq] at live subst after have current : (captureGlobal s snap map).current = captureLocal s snap map := by dsimp only [captureGlobal] split <;> rfl - exact ⟨find_set_same _ _ _, congrArg (fun f => (revision f map).version) current, rfl⟩ + exact ⟨find_set_same _ _ _, congrArg (fun f => (revision f map).version) current, + rfl, permitted.2.1.1, permitted.2.1.2⟩ + · cases accepted + +/-- Refusing a semantically available view requires a rollback-crossing attempt. -/ +theorem step_unavailable_requires_rollback + : ∀ (w next : State) (sid tid : Nat) (map : String) (s : Store) + (t : Tx) (snap : Snapshot) (refuse : Bool), + lookupTx w sid tid = some (s, t) + → t.snapshot = some snap + → available s snap map = true + → execute w (.acquire sid tid map refuse) = some (next, .unavailable) + → t.crossedRollback = true := by + intro w next sid tid map s t snap refuse source captured retained accepted + dsimp only [execute] at accepted + rw [source] at accepted + obtain ⟨_, selected, accepted⟩ := option_bind_ok accepted + cases selected + dsimp only at accepted + obtain ⟨_, snapshot, accepted⟩ := option_bind_ok accepted + cases captured.symm.trans snapshot + try dsimp only at accepted + split at accepted + · cases accepted + · rename_i enabled + split at accepted · cases accepted + · rename_i refused + cases crossed : t.crossedRollback + · cases refuse <;> simp_all + · rfl + +/-- A rollback-crossing attempt can conservatively refuse a retained empty view. -/ +theorem step_unavailable_requires_rollback_witness + : ∃ (w next : State) (sid tid : Nat) (map : String) (s : Store) + (t : Tx) (snap : Snapshot) (refuse : Bool), + lookupTx w sid tid = some (s, t) + ∧ t.snapshot = some snap + ∧ available s snap map = true + ∧ execute w (.acquire sid tid map refuse) = some (next, .unavailable) := by + let t : Tx := + { store := 1, snapshot := some { current := {}, term := 0 }, crossedRollback := true } + exact ⟨ + { stores := [(1, {})], txs := [(1, t)] }, + { stores := [(1, {})], txs := [(1, { t with unavailable := true })] }, + 1, + 1, + "a", + {}, + t, + { current := {}, term := 0 }, + true, + by decide +kernel, + rfl, + by decide +kernel, + by decide +kernel + ⟩ /-- Every attempt-preserving model execution keeps an existing current snapshot fixed. -/ theorem replay_snapshot_fixed @@ -486,10 +549,10 @@ theorem capture_replay_preserves_metadata theorem capture_replay_preserves_map : ∀ (w captured final : State) (sid tid localVersion globalVersion : Nat) (map : String) (s : Store) (before acquired : Tx) (snap : Snapshot) - (inputs : List Action), + (inputs : List Action) (refuse : Bool), lookupTx w sid tid = some (s, before) → before.snapshot = some snap - → execute w (.acquire sid tid map) + → execute w (.acquire sid tid map refuse) = some (captured, .acquired localVersion globalVersion) → find captured.txs tid = some acquired → (∀ a ∈ inputs, AttemptAction tid a) @@ -500,10 +563,10 @@ theorem capture_replay_preserves_map ∧ localVersion = (revision (captureLocal s snap map) map).version ∧ globalVersion = (revision (captureGlobal s snap map).frame map).version := by - intro w captured final sid tid localVersion globalVersion map s before acquired snap inputs + intro w captured final sid tid localVersion globalVersion map s before acquired snap inputs refuse source pinned capture live segment run - obtain ⟨view, localCut, globalCut⟩ := - step_map_capture w captured sid tid localVersion globalVersion map s before acquired snap source pinned capture live + obtain ⟨view, localCut, globalCut, _⟩ := + step_map_capture w captured sid tid localVersion globalVersion map s before acquired snap refuse source pinned capture live obtain ⟨after, finalLive, same⟩ := replay_map_global_fixed captured final tid acquired map _ inputs live view segment run exact ⟨after, finalLive, same, localCut, globalCut⟩ diff --git a/lean/kv/Kv/Proofs/Segment.lean b/lean/kv/Kv/Proofs/Segment.lean index e4e4a519ded9..4320c7b31615 100644 --- a/lean/kv/Kv/Proofs/Segment.lean +++ b/lean/kv/Kv/Proofs/Segment.lean @@ -103,7 +103,7 @@ private theorem execute_head (w next : Model.State) (sid : Nat) (before : Model. · cases accepted · cases accepted exact unchanged w _ sid before live rfl - | acquire actual tid map => + | acquire actual tid map refuse => dsimp only [Model.execute] at accepted obtain ⟨⟨s, t⟩, _, accepted⟩ := option_bind_ok accepted dsimp only at accepted diff --git a/lean/kv/Kv/Properties.lean b/lean/kv/Kv/Properties.lean index 44ab15bc9a3c..54b89b747474 100644 --- a/lean/kv/Kv/Properties.lean +++ b/lean/kv/Kv/Properties.lean @@ -154,13 +154,14 @@ theorem apply_atomic_witness /-! ## Serial snapshot runs and normal-view serializability -/ -/-- An attempt's operation log runs serially on its pinned local views to its staged writes. -/ +/-- Every attempt's normal-operation prefix is consistent with its original snapshot +across all maps, including its own preceding writes. -/ theorem transaction_snapshot_serial : ∀ (w : Model.State) (tid : Nat) (t : Model.Tx) (snap : Snapshot), Model.transitionSystem.Reachable w → find w.txs tid = some t → t.snapshot = some snap - → serialRun t.data [] t.normal.log = some t.normal.writes := by + → serialRun snap.current.data [] t.normal.log = some t.normal.writes := by exact Proofs.Reachable.reachable_transaction_snapshot_serial /-- Witness: an attempt with a snapshot can have a nonempty log. -/ @@ -362,18 +363,20 @@ theorem replay_snapshot_fixed_witness /-! ## Per-map globally committed views -/ -/-- Acquiring a map records its global view and returns the revision versions. -/ +/-- Successful acquisition records its views and preserves the snapshot's map identities. -/ theorem step_map_capture : ∀ (w next : State) (sid tid localVersion globalVersion : Nat) (map : String) - (s : Store) (before after : Tx) (snap : Snapshot), + (s : Store) (before after : Tx) (snap : Snapshot) (refuse : Bool), lookupTx w sid tid = some (s, before) → before.snapshot = some snap - → execute w (.acquire sid tid map) + → execute w (.acquire sid tid map refuse) = some (next, .acquired localVersion globalVersion) → find next.txs tid = some after → find after.globalViews map = some (captureGlobal s snap map) ∧ localVersion = (revision (captureLocal s snap map) map).version - ∧ globalVersion = (revision (captureGlobal s snap map).frame map).version := by + ∧ globalVersion = (revision (captureGlobal s snap map).frame map).version + ∧ find (captureLocal s snap map).births map = find snap.current.births map + ∧ revision (captureLocal s snap map) map = revision snap.current map := by exact Proofs.Safety.step_map_capture /-- Witness: a map acquisition can be accepted. -/ @@ -387,6 +390,27 @@ theorem step_map_capture_witness ∧ find next.txs tid = some after := by exact Proofs.Witnesses.step_map_capture_witness +/-- Refusal of a semantically available view requires crossing a truncating rollback. -/ +theorem step_unavailable_requires_rollback + : ∀ (w next : State) (sid tid : Nat) (map : String) (s : Store) + (t : Tx) (snap : Snapshot) (refuse : Bool), + lookupTx w sid tid = some (s, t) + → t.snapshot = some snap + → available s snap map = true + → execute w (.acquire sid tid map refuse) = some (next, .unavailable) + → t.crossedRollback = true := by + exact Proofs.Safety.step_unavailable_requires_rollback + +/-- Witness: an available view can be refused by a rollback-crossing attempt. -/ +theorem step_unavailable_requires_rollback_witness + : ∃ (w next : State) (sid tid : Nat) (map : String) (s : Store) + (t : Tx) (snap : Snapshot) (refuse : Bool), + lookupTx w sid tid = some (s, t) + ∧ t.snapshot = some snap + ∧ available s snap map = true + ∧ execute w (.acquire sid tid map refuse) = some (next, .unavailable) := by + exact Proofs.Safety.step_unavailable_requires_rollback_witness + /-- A map's captured local and global views are unchanged by later actions that do not end the attempt. -/ theorem replay_map_global_fixed : ∀ (w final : State) (tid : Nat) (before : Tx) (map : String) (view : GlobalView) @@ -439,10 +463,10 @@ not end the attempt. -/ theorem capture_replay_preserves_map : ∀ (w captured final : State) (sid tid localVersion globalVersion : Nat) (map : String) (s : Store) (before acquired : Tx) (snap : Snapshot) - (inputs : List Action), + (inputs : List Action) (refuse : Bool), lookupTx w sid tid = some (s, before) → before.snapshot = some snap - → execute w (.acquire sid tid map) + → execute w (.acquire sid tid map refuse) = some (captured, .acquired localVersion globalVersion) → find captured.txs tid = some acquired → (∀ a ∈ inputs, AttemptAction tid a) diff --git a/lean/kv/Kv/Tests/Replay.lean b/lean/kv/Kv/Tests/Replay.lean index 42136938f5eb..d015f5642db4 100644 --- a/lean/kv/Kv/Tests/Replay.lean +++ b/lean/kv/Kv/Tests/Replay.lean @@ -146,6 +146,109 @@ private def modelRejection (path : System.FilePath) : IO (Option Nat) := do w := { model := next, recording := metadata w.recording record.event output } return none +private def acquisition (s : Model.Store) (snap : Snapshot) (map : String) + : Option (Model.State × Output) := + Model.execute + { + stores := [(1, s)] + txs := [(1, { store := 1, snapshot := some snap })] + } + (.acquire 1 1 map) + +private def assertAcquisition : IO Unit := do + let base := Model.advance {} [(("a", "00"), some "11")] + let changed := Model.advance base [(("a", "00"), some "22")] + let snap : Snapshot := { current := changed.head, term := 0 } + let rolled := Model.rollbackStore changed 1 0 + let replacement := Model.advance rolled [(("a", "00"), some "22")] + for s in [rolled, replacement] do + if (acquisition s snap "a").map Prod.snd != some .unavailable then + throw + (IO.userError "rollback or same-value replacement restored discarded identity") + let newBirth := + Model.advance (Model.rollbackStore changed 0 0) [(("b", "00"), some "33")] + if (acquisition newBirth snap "b").map Prod.snd != some .unavailable then + throw + (IO.userError "replacement branch exposed a map absent at the original snapshot") + let unrelated := Model.advance base [(("b", "00"), some "22")] + let unchanged : Snapshot := { current := unrelated.head, term := 0 } + if (acquisition (Model.rollbackStore unrelated 1 0) unchanged "a").map Prod.snd + != some (.acquired 1 0) then + throw (IO.userError "unrelated rollback blocked an unchanged map") + let absent : Snapshot := { current := {}, term := 0 } + let bornLater := { base with global := 1 } + let some (placeholder, .acquired 0 0) := acquisition bornLater absent "a" + | throw (IO.userError "later map creation blocked an original empty placeholder") + let some placeholderTx := find placeholder.txs 1 + | throw (IO.userError "placeholder acquisition lost attempt") + if !placeholderTx.data.isEmpty + || (find placeholderTx.globalViews "a").map (fun v => v.frame.data) != some [] then + throw (IO.userError "originally absent map exposed newer local or global data") + let empty := Model.advance {} [(("a", "00"), none)] + let recreated := Model.advance (Model.rollbackStore empty 0 0) [(("a", "00"), none)] + if (acquisition recreated { current := empty.head, term := 0 } "a").map Prod.snd + != some .unavailable then + throw (IO.userError "empty-map recreation restored discarded birth identity") + let initial : Model.State := + { + stores := [(1, changed), (2, changed)] + txs := + [ + (1, { store := 1, snapshot := some { current := base.head, term := 0 } }), + (2, { store := 1 }) + ] + } + for inputs + in [ + [], + [.rollback 1 2 0], + [.rollback 1 9 0], + [.rollback 2 1 0], + [.compact 1 1, .rollback 1 0 0] + ] do + let some (unchanged, _) := executeActions initial inputs + | throw (IO.userError "rollback boundary setup was disabled") + let world : World := { model := unchanged } + if (Model.execute unchanged (.acquire 1 1 "a" true)).isSome + || (guardEvent world (.unavailable 1 1 "a")).isOk then + throw (IO.userError "refusal enabled without this attempt crossing a truncation") + let some (crossed, _) := Model.execute initial (.rollback 1 1 0) + | throw (IO.userError "truncating rollback was disabled") + let some (lateSnapshot, _) := Model.execute crossed (.snapshot 1 2) + | throw (IO.userError "post-rollback snapshot was disabled") + if (Model.execute lateSnapshot (.acquire 1 2 "a" true)).isSome then + throw (IO.userError "snapshot captured after rollback inherited refusal permission") + let world : World := { model := crossed } + let some (refused, .unavailable) := + executeActions crossed (actions world (.unavailable 1 1 "a")) + | throw + (IO.userError "rollback crossing did not permit conservative acquisition failure") + if !(guardEvent world (.unavailable 1 1 "a")).isOk then + throw (IO.userError "diagnostics forbade permitted rollback refusal") + let some refusedTx := find refused.txs 1 + | throw (IO.userError "refused acquisition lost attempt") + if !refusedTx.unavailable + || !refusedTx.globalViews.isEmpty + || Model.canApply base refusedTx then + throw (IO.userError "refusal pinned a handle or allowed application") + let some (committing, _) := Model.execute refused (.commitBegin 1 1) + | throw (IO.userError "refused attempt could not begin commit") + if (Model.execute committing (.commitResult 1 1 .success)).isSome then + throw (IO.userError "refused acquisition allowed successful commit") + let some (pinnedState, _) := + executeActions initial [.acquire 1 1 "a", .rollback 1 1 0] + | throw (IO.userError "rollback of an attempt with a pinned handle was disabled") + let some (_, .committed .success 0) := + executeActions pinnedState + [.operation 1 1 (.get "a" "00" false), .commitBegin 1 1, .commitResult 1 1 .success] + | throw (IO.userError "rollback crossing invalidated a pinned read-only attempt") + let missing : World := { model := { crossed with txs := [(1, { store := 1 })] } } + let pinned : World := { model := pinnedState } + for w in [missing, pinned] do + if (guardEvent w (.unavailable 1 1 "a")).isOk + || (executeActions w.model (actions w (.unavailable 1 1 "a"))).isSome then + throw (IO.userError "refusal bypassed missing-snapshot or pinned-handle checks") + /-- Checks rejected fixtures without `guardEvent`; callback visitation remains adapter-only. -/ def checkModelFixtures (directory : System.FilePath) : IO Unit := do let mut modelFailures := 0 @@ -176,6 +279,7 @@ def checkModelFixtures (directory : System.FilePath) : IO Unit := do private def run : IO Unit := do assertProjection + assertAcquisition let _ ← assertStutters {} [ diff --git a/lean/kv/Kv/TraceValidation/Adapter.lean b/lean/kv/Kv/TraceValidation/Adapter.lean index 7157516e930b..cc50a08216aa 100644 --- a/lean/kv/Kv/TraceValidation/Adapter.lean +++ b/lean/kv/Kv/TraceValidation/Adapter.lean @@ -11,8 +11,9 @@ namespace Kv.TraceValidation open Kv.Model -/-- Translates inputs, not reported outputs, into model actions. +/-- Translates inputs and environment choices, not reported outputs, into model actions. The omitted initial term is supplied as an environment input before the first snapshot. +Unavailability selects a refusal input whose rollback cause is checked by the model. Trace scopes and individual callback reports stutter; freezing entries is a model scan. -/ def actions (w : World) : Event → List Model.Action | .storeCreate sid => [.storeCreate sid 0] @@ -25,7 +26,8 @@ def actions (w : World) : Event → List Model.Action else []) ++ [.snapshot sid tid] - | .acquire sid tid m _ _ | .unavailable sid tid m => [.acquire sid tid m] + | .acquire sid tid m _ _ => [.acquire sid tid m] + | .unavailable sid tid m => [.acquire sid tid m true] | .get sid tid m k _ global => [.operation sid tid (.get m k global)] | .has sid tid m k _ global => [.operation sid tid (.has m k global)] | .previous sid tid m k _ => [.operation sid tid (.previous m k)] diff --git a/lean/kv/Kv/TraceValidation/Transitions.lean b/lean/kv/Kv/TraceValidation/Transitions.lean index 8bc071420615..c99542e09ede 100644 --- a/lean/kv/Kv/TraceValidation/Transitions.lean +++ b/lean/kv/Kv/TraceValidation/Transitions.lean @@ -181,7 +181,8 @@ def guardEvent (w : World) (event : Event) : Except Failure Unit := do operationPosition (attemptRecording w tid) let snap ← snapOf t require ((find t.globalViews m).isNone) "pinned handle reported unavailable" - expect (!(available s snap m)) "available snapshot reported unavailable" + expect (!available s snap m || t.crossedRollback) + "available snapshot reported unavailable without crossing a truncating rollback" | .get sid tid m k value global => let t ← txOf w sid tid let _ ← handleOf t (attemptRecording w tid) m diff --git a/lean/kv/README.md b/lean/kv/README.md index b41e5f51d70f..59b017160087 100644 --- a/lean/kv/README.md +++ b/lean/kv/README.md @@ -61,7 +61,11 @@ Store and transaction terms drive stale-term rejection. Per-map revision and birth stamps carry application identities, so reuse of a rolled-back version cannot restore discarded lineage, including for empty maps. Maps are acquired lazily, as in C++. -The first acquisition of a map selects the newest surviving frame at or below the snapshot's read version, or an empty placeholder if the map is absent there, so it may observe a rollback that occurred after the snapshot. +The first acquisition of a map selects the newest surviving frame at or below the snapshot's read version, or an empty placeholder if the map is absent there. +Acquisition checks retention and the original snapshot's map birth/revision identities; see `step_map_capture` in [`Properties.lean`](Kv/Properties.lean). +`Tx.crossedRollback` records a truncating rollback of the attempt's store after snapshot capture. +After such a rollback, `Action.acquire` permits conservative refusal through `refuse := true`, even when the map's original view survives; see `step_unavailable_requires_rollback` in [`Properties.lean`](Kv/Properties.lean). +Acquisition failure pins no view and marks the attempt unavailable for successful commit. `Tx.globalViews` stores one `GlobalView` per acquired map: the pinned local frame and the globally committed frame. Once acquired, neither frame changes for the rest of the attempt, and `Tx.data` combines the pinned local data used by normal observations. @@ -92,7 +96,7 @@ The five claims without premises (`read_your_write`, `read_your_deletion`, `prev | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `read_your_write`, `read_your_deletion`, `absent_read`, `staged_noninterference`, `previous_ignores_pending` | Point-read and overlay semantics | | `publish_lookup`, `publication_noninterference`, `publish_unique`, `apply_atomic` | Entire finite multi-map publication and unrelated-key preservation | -| `transaction_snapshot_serial` | Every live attempt's normal log runs serially on its pinned local data, including read-only completions | +| `transaction_snapshot_serial` | Every live attempt's normal log runs serially on its original snapshot across all maps, including its own preceding writes and read-only completions | | `transaction_application_serial` | The same executable application primitive used by replay has an independent sequential transaction witness | | `executable_branch_serializability` | Every finite branch of executable applications, with compaction interleavings, admits application order as a serial witness, including locally applied `no_replicate` attempts | | `replay_segment_serializability` | Actual model execution projects to a selected live store's application-order serial witness; the attempts come from pre-application `Model.lookupTx` | @@ -130,6 +134,7 @@ Snapshot preservation requires no creation/end of the selected attempt during it The model guarantees are proved for actual `Model.execute` transitions and arbitrary reachable model runs, without trace preconditions or a sequential acceptance oracle. The trace decoder, event translation, report comparisons, and recording checks are part of the validation trust boundary, rather than a separately proved trace transition system. +The adapter translates `map_acquire` using the default acquisition action and `map_unavailable` using `refuse := true`; the model checks refusal eligibility and computes the resulting output and state. The canonical model theorems cover normal-view serial projection, history safety, frozen read metadata, and per-map local/global provenance and immutability. They do not prove that arbitrary C++ executions refine this model or that the instrumentation is complete; iteration protocol and acquisition-availability checks are not claimed as independently verified C++ algorithms. @@ -236,5 +241,5 @@ The build runs the trace-validation self-tests in `Tests/Replay.lean`, and `chec The shared `lake exe check-imports` checks import coverage and layering, as described in the [common package](../common/README.md#architecture-checks). To check C++ traces against the model, build the replayer and pass it to CMake as described in [Reproducing a run](../../doc/build_apps/kv/semantics.rst). -In the Lean CI workflow, the `KV trace captures` job builds the instrumented C++ tests and captures traces in Azure Linux 3, while the model job runs these checks and the fixtures in parallel and then replays the captured traces. +In the Lean CI workflow, the `KV trace captures` job builds the instrumented C++ tests and captures traces in Azure Linux 4, while the model job runs these checks and the fixtures in parallel and then replays the captured traces. See the disaster-recovery [Formatting](../disaster-recovery/README.md#formatting) section for the formatting check, and pass `lean/kv` to restrict it to this package. diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-advance-global.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-advance-global.diff index b8ec00c4cc36..51cfe2d4c57b 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-advance-global.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-advance-global.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -216 +216 @@ --{"requested":2,"seq":216,"store":7,"type":"compact","version":0} -+{"requested":2,"seq":216,"store":7,"type":"compact","version":2} +@@ -196 +196 @@ +-{"requested":2,"seq":196,"store":7,"type":"compact","version":0} ++{"requested":2,"seq":196,"store":7,"type":"compact","version":2} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-replace-established-global.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-replace-established-global.diff index b39dc349335a..907f167a446d 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-replace-established-global.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.above-head-compaction-cannot-replace-established-global.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -218 +218 @@ --{"requested":9,"seq":218,"store":7,"type":"compact","version":1} -+{"requested":9,"seq":218,"store":7,"type":"compact","version":2} +@@ -198 +198 @@ +-{"requested":9,"seq":198,"store":7,"type":"compact","version":1} ++{"requested":9,"seq":198,"store":7,"type":"compact","version":2} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.empty-map-recreation-does-not-restore-birth-lineage.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.empty-map-recreation-does-not-restore-birth-lineage.diff index 44f74c4223a3..d3ee8f544d48 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.empty-map-recreation-does-not-restore-birth-lineage.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.empty-map-recreation-does-not-restore-birth-lineage.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -200 +200 @@ --{"result":"conflict","seq":200,"store":6,"tx":52,"type":"commit_result","version":0} -+{"seq":200,"store":6,"term":0,"tx":52,"type":"apply","version":2,"writes":[{"key":"00","map":"b","value":"11"}]} +@@ -180 +180 @@ +-{"result":"conflict","seq":180,"store":6,"tx":52,"type":"commit_result","version":0} ++{"seq":180,"store":6,"term":0,"tx":52,"type":"apply","version":2,"writes":[{"key":"00","map":"b","value":"11"}]} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.illegal-rollback.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.illegal-rollback.diff index 63f08f71c36e..6ac3a631387f 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.illegal-rollback.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.illegal-rollback.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -219 +219 @@ --{"requested":0,"seq":219,"store":7,"term":1,"type":"rollback_rejected"} -+{"requested":0,"seq":219,"store":7,"term":1,"type":"rollback","version":0} +@@ -199 +199 @@ +-{"requested":0,"seq":199,"store":7,"term":1,"type":"rollback_rejected"} ++{"requested":0,"seq":199,"store":7,"term":1,"type":"rollback","version":0} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-claim-the-discarded-snapshot-revision.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-claim-the-discarded-snapshot-revision.diff index 9b9d22a6eee7..44b3d3806d63 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-claim-the-discarded-snapshot-revision.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-claim-the-discarded-snapshot-revision.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson @@ -22 +22 @@ --{"global":0,"map":"a","seq":22,"store":1,"tx":2,"type":"map_acquire","version":0} +-{"map":"a","seq":22,"store":1,"tx":2,"type":"map_unavailable"} +{"global":0,"map":"a","seq":22,"store":1,"tx":2,"type":"map_acquire","version":1} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-read-discarded-data.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-read-discarded-data.diff deleted file mode 100644 index ca32b2188245..000000000000 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.late-acquisition-cannot-read-discarded-data.diff +++ /dev/null @@ -1,5 +0,0 @@ ---- a/trace.ndjson -+++ b/trace.ndjson -@@ -23 +23 @@ --{"key":"00","map":"a","seq":23,"store":1,"tx":2,"type":"get","value":null} -+{"key":"00","map":"a","seq":23,"store":1,"tx":2,"type":"get","value":"11"} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.pinned-map-cannot-refresh-its-local-data-after-rollback.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.pinned-map-cannot-refresh-its-local-data-after-rollback.diff index b8a3928ac710..ad80cf1f6d6d 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.pinned-map-cannot-refresh-its-local-data-after-rollback.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.pinned-map-cannot-refresh-its-local-data-after-rollback.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -28 +28 @@ --{"key":"00","map":"a","seq":28,"store":1,"tx":3,"type":"get","value":"11"} -+{"key":"00","map":"a","seq":28,"store":1,"tx":3,"type":"get","value":null} +@@ -23 +23 @@ +-{"key":"00","map":"a","seq":23,"store":1,"tx":3,"type":"get","value":"11"} ++{"key":"00","map":"a","seq":23,"store":1,"tx":3,"type":"get","value":null} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.reused-version-does-not-restore-lineage.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.reused-version-does-not-restore-lineage.diff index 09ed7c9ea5d6..1d6b83b0601d 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.reused-version-does-not-restore-lineage.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.reused-version-does-not-restore-lineage.diff @@ -1,5 +1,5 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -172 +172 @@ --{"result":"conflict","seq":172,"store":5,"tx":42,"type":"commit_result","version":0} -+{"seq":172,"store":5,"term":0,"tx":42,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} +@@ -152 +152 @@ +-{"result":"conflict","seq":152,"store":5,"tx":42,"type":"commit_result","version":0} ++{"seq":152,"store":5,"term":0,"tx":42,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.surviving-late-acquisition-cannot-use-the-original-snapshot-data.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.surviving-late-acquisition-cannot-use-the-original-snapshot-data.diff deleted file mode 100644 index 9f8465b64bb8..000000000000 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.surviving-late-acquisition-cannot-use-the-original-snapshot-data.diff +++ /dev/null @@ -1,5 +0,0 @@ ---- a/trace.ndjson -+++ b/trace.ndjson -@@ -62 +62 @@ --{"key":"00","map":"a","seq":62,"store":2,"tx":13,"type":"get","value":"11"} -+{"key":"00","map":"a","seq":62,"store":2,"tx":13,"type":"get","value":"22"} diff --git a/lean/kv/replayer/fixtures/rollback/invalid/rejected.term-only-stale-attempt.diff b/lean/kv/replayer/fixtures/rollback/invalid/rejected.term-only-stale-attempt.diff index de9d8c04c1cf..9c2e87c46bba 100644 --- a/lean/kv/replayer/fixtures/rollback/invalid/rejected.term-only-stale-attempt.diff +++ b/lean/kv/replayer/fixtures/rollback/invalid/rejected.term-only-stale-attempt.diff @@ -1,8 +1,8 @@ --- a/trace.ndjson +++ b/trace.ndjson -@@ -136 +136 @@ --{"requested":1,"seq":136,"store":4,"term":0,"type":"rollback","version":1} -+{"requested":1,"seq":136,"store":4,"term":1,"type":"rollback","version":1} -@@ -139 +139 @@ --{"seq":139,"store":4,"term":0,"tx":32,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} -+{"seq":139,"store":4,"term":1,"tx":32,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} +@@ -116 +116 @@ +-{"requested":1,"seq":116,"store":4,"term":0,"type":"rollback","version":1} ++{"requested":1,"seq":116,"store":4,"term":1,"type":"rollback","version":1} +@@ -119 +119 @@ +-{"seq":119,"store":4,"term":0,"tx":32,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} ++{"seq":119,"store":4,"term":1,"tx":32,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} diff --git a/lean/kv/replayer/fixtures/rollback/trace.ndjson b/lean/kv/replayer/fixtures/rollback/trace.ndjson index 1743a3f3b31d..a9fb1cccdc95 100644 --- a/lean/kv/replayer/fixtures/rollback/trace.ndjson +++ b/lean/kv/replayer/fixtures/rollback/trace.ndjson @@ -1,5 +1,5 @@ {"schema":1,"seq":1,"type":"trace_start"} -{"name":"first acquisition after rollback uses a placeholder; pinned maps retain their data","seq":2,"type":"case_begin"} +{"name":"first acquisition after rollback is unavailable; pinned maps retain their data","seq":2,"type":"case_begin"} {"seq":3,"store":1,"type":"store_create"} {"seq":4,"store":1,"tx":1,"type":"tx_create"} {"global":0,"seq":5,"store":1,"term":0,"tx":1,"type":"snapshot","version":0} @@ -19,204 +19,184 @@ {"global":0,"seq":19,"store":1,"term":0,"tx":3,"type":"snapshot","version":1} {"global":0,"map":"a","seq":20,"store":1,"tx":3,"type":"map_acquire","version":1} {"requested":0,"seq":21,"store":1,"term":0,"type":"rollback","version":0} -{"global":0,"map":"a","seq":22,"store":1,"tx":2,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":23,"store":1,"tx":2,"type":"get","value":null} -{"key":"00","map":"a","seq":24,"store":1,"tx":2,"type":"get_global","value":null} -{"key":"00","map":"a","seq":25,"store":1,"tx":2,"type":"previous_write","value":null} -{"map":"a","seq":26,"store":1,"tx":2,"type":"size","value":0} -{"key":"00","map":"b","seq":27,"store":1,"tx":2,"type":"get","value":"11"} -{"key":"00","map":"a","seq":28,"store":1,"tx":3,"type":"get","value":"11"} -{"key":"00","map":"a","seq":29,"store":1,"tx":2,"type":"put","value":"22"} -{"key":"00","map":"a","seq":30,"store":1,"tx":2,"type":"has","value":true} -{"map":"a","seq":31,"store":1,"tx":2,"type":"clear"} -{"map":"a","seq":32,"store":1,"tx":2,"type":"size","value":0} -{"seq":33,"store":1,"tx":3,"type":"tx_end"} -{"seq":34,"store":1,"tx":2,"type":"tx_end"} -{"seq":35,"store":1,"type":"store_end"} -{"failed":false,"name":"first acquisition after rollback uses a placeholder; pinned maps retain their data","seq":36,"type":"case_end"} -{"name":"late acquisition selects a surviving revision and can apply on the current branch","seq":37,"type":"case_begin"} -{"seq":38,"store":2,"type":"store_create"} -{"seq":39,"store":2,"tx":11,"type":"tx_create"} -{"global":0,"seq":40,"store":2,"term":0,"tx":11,"type":"snapshot","version":0} -{"global":0,"map":"a","seq":41,"store":2,"tx":11,"type":"map_acquire","version":0} -{"global":0,"map":"b","seq":42,"store":2,"tx":11,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":43,"store":2,"tx":11,"type":"put","value":"11"} -{"key":"00","map":"b","seq":44,"store":2,"tx":11,"type":"put","value":"11"} -{"seq":45,"store":2,"tx":11,"type":"commit_begin"} -{"seq":46,"store":2,"term":0,"tx":11,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} -{"result":"success","seq":47,"store":2,"tx":11,"type":"commit_result","version":1} -{"seq":48,"store":2,"tx":11,"type":"tx_end"} -{"seq":49,"store":2,"tx":12,"type":"tx_create"} -{"global":0,"seq":50,"store":2,"term":0,"tx":12,"type":"snapshot","version":1} -{"global":0,"map":"a","seq":51,"store":2,"tx":12,"type":"map_acquire","version":1} -{"key":"00","map":"a","seq":52,"store":2,"tx":12,"type":"put","value":"22"} -{"seq":53,"store":2,"tx":12,"type":"commit_begin"} -{"seq":54,"store":2,"term":0,"tx":12,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"22"}]} -{"result":"success","seq":55,"store":2,"tx":12,"type":"commit_result","version":2} -{"seq":56,"store":2,"tx":12,"type":"tx_end"} -{"seq":57,"store":2,"tx":13,"type":"tx_create"} -{"global":0,"seq":58,"store":2,"term":0,"tx":13,"type":"snapshot","version":2} -{"global":0,"map":"b","seq":59,"store":2,"tx":13,"type":"map_acquire","version":1} -{"requested":1,"seq":60,"store":2,"term":0,"type":"rollback","version":1} -{"global":0,"map":"a","seq":61,"store":2,"tx":13,"type":"map_acquire","version":1} -{"key":"00","map":"a","seq":62,"store":2,"tx":13,"type":"get","value":"11"} -{"key":"00","map":"a","seq":63,"store":2,"tx":13,"type":"put","value":"33"} -{"seq":64,"store":2,"tx":13,"type":"commit_begin"} -{"seq":65,"store":2,"term":0,"tx":13,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} -{"result":"success","seq":66,"store":2,"tx":13,"type":"commit_result","version":2} -{"seq":67,"store":2,"tx":13,"type":"tx_end"} -{"seq":68,"store":2,"type":"store_end"} -{"failed":false,"name":"late acquisition selects a surviving revision and can apply on the current branch","seq":69,"type":"case_end"} -{"name":"late acquisition selects a replacement branch with the same version","seq":70,"type":"case_begin"} -{"seq":71,"store":3,"type":"store_create"} -{"seq":72,"store":3,"tx":21,"type":"tx_create"} -{"global":0,"seq":73,"store":3,"term":0,"tx":21,"type":"snapshot","version":0} -{"global":0,"map":"a","seq":74,"store":3,"tx":21,"type":"map_acquire","version":0} -{"global":0,"map":"b","seq":75,"store":3,"tx":21,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":76,"store":3,"tx":21,"type":"put","value":"11"} -{"key":"00","map":"b","seq":77,"store":3,"tx":21,"type":"put","value":"11"} -{"seq":78,"store":3,"tx":21,"type":"commit_begin"} -{"seq":79,"store":3,"term":0,"tx":21,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} -{"result":"success","seq":80,"store":3,"tx":21,"type":"commit_result","version":1} -{"seq":81,"store":3,"tx":21,"type":"tx_end"} -{"seq":82,"store":3,"tx":22,"type":"tx_create"} -{"global":0,"seq":83,"store":3,"term":0,"tx":22,"type":"snapshot","version":1} -{"global":0,"map":"a","seq":84,"store":3,"tx":22,"type":"map_acquire","version":1} -{"key":"00","map":"a","seq":85,"store":3,"tx":22,"type":"put","value":"22"} -{"seq":86,"store":3,"tx":22,"type":"commit_begin"} -{"seq":87,"store":3,"term":0,"tx":22,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"22"}]} -{"result":"success","seq":88,"store":3,"tx":22,"type":"commit_result","version":2} -{"seq":89,"store":3,"tx":22,"type":"tx_end"} -{"seq":90,"store":3,"tx":23,"type":"tx_create"} -{"global":0,"seq":91,"store":3,"term":0,"tx":23,"type":"snapshot","version":2} -{"global":0,"map":"b","seq":92,"store":3,"tx":23,"type":"map_acquire","version":1} -{"requested":1,"seq":93,"store":3,"term":0,"type":"rollback","version":1} -{"seq":94,"store":3,"tx":24,"type":"tx_create"} -{"global":0,"seq":95,"store":3,"term":0,"tx":24,"type":"snapshot","version":1} -{"global":0,"map":"a","seq":96,"store":3,"tx":24,"type":"map_acquire","version":1} -{"key":"00","map":"a","seq":97,"store":3,"tx":24,"type":"put","value":"44"} -{"seq":98,"store":3,"tx":24,"type":"commit_begin"} -{"seq":99,"store":3,"term":0,"tx":24,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"44"}]} -{"result":"success","seq":100,"store":3,"tx":24,"type":"commit_result","version":2} -{"seq":101,"store":3,"tx":24,"type":"tx_end"} -{"requested":2,"seq":102,"store":3,"type":"compact","version":2} -{"global":2,"map":"a","seq":103,"store":3,"tx":23,"type":"map_acquire","version":2} -{"key":"00","map":"a","seq":104,"store":3,"tx":23,"type":"get","value":"44"} -{"key":"00","map":"a","seq":105,"store":3,"tx":23,"type":"get_global","value":"44"} -{"key":"00","map":"a","seq":106,"store":3,"tx":23,"type":"put","value":"55"} -{"seq":107,"store":3,"tx":23,"type":"commit_begin"} -{"seq":108,"store":3,"term":0,"tx":23,"type":"apply","version":3,"writes":[{"key":"00","map":"a","value":"55"}]} -{"result":"success","seq":109,"store":3,"tx":23,"type":"commit_result","version":3} -{"seq":110,"store":3,"tx":23,"type":"tx_end"} -{"seq":111,"store":3,"type":"store_end"} -{"failed":false,"name":"late acquisition selects a replacement branch with the same version","seq":112,"type":"case_end"} -{"name":"unrelated same-term rollback keeps attempt valid","seq":113,"type":"case_begin"} -{"seq":114,"store":4,"type":"store_create"} -{"seq":115,"store":4,"tx":31,"type":"tx_create"} -{"global":0,"seq":116,"store":4,"term":0,"tx":31,"type":"snapshot","version":0} -{"global":0,"map":"a","seq":117,"store":4,"tx":31,"type":"map_acquire","version":0} -{"global":0,"map":"b","seq":118,"store":4,"tx":31,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":119,"store":4,"tx":31,"type":"put","value":"11"} -{"key":"00","map":"b","seq":120,"store":4,"tx":31,"type":"put","value":"11"} -{"seq":121,"store":4,"tx":31,"type":"commit_begin"} -{"seq":122,"store":4,"term":0,"tx":31,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} -{"result":"success","seq":123,"store":4,"tx":31,"type":"commit_result","version":1} -{"seq":124,"store":4,"tx":31,"type":"tx_end"} -{"seq":125,"store":4,"tx":32,"type":"tx_create"} -{"global":0,"seq":126,"store":4,"term":0,"tx":32,"type":"snapshot","version":1} -{"global":0,"map":"a","seq":127,"store":4,"tx":32,"type":"map_acquire","version":1} -{"seq":128,"store":4,"tx":33,"type":"tx_create"} -{"global":0,"seq":129,"store":4,"term":0,"tx":33,"type":"snapshot","version":1} -{"global":0,"map":"b","seq":130,"store":4,"tx":33,"type":"map_acquire","version":1} -{"key":"00","map":"b","seq":131,"store":4,"tx":33,"type":"put","value":"22"} -{"seq":132,"store":4,"tx":33,"type":"commit_begin"} -{"seq":133,"store":4,"term":0,"tx":33,"type":"apply","version":2,"writes":[{"key":"00","map":"b","value":"22"}]} -{"result":"success","seq":134,"store":4,"tx":33,"type":"commit_result","version":2} -{"seq":135,"store":4,"tx":33,"type":"tx_end"} -{"requested":1,"seq":136,"store":4,"term":0,"type":"rollback","version":1} -{"key":"00","map":"a","seq":137,"store":4,"tx":32,"type":"put","value":"33"} -{"seq":138,"store":4,"tx":32,"type":"commit_begin"} -{"seq":139,"store":4,"term":0,"tx":32,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} -{"result":"success","seq":140,"store":4,"tx":32,"type":"commit_result","version":2} -{"seq":141,"store":4,"tx":32,"type":"tx_end"} -{"seq":142,"store":4,"type":"store_end"} -{"failed":false,"name":"unrelated same-term rollback keeps attempt valid","seq":143,"type":"case_end"} -{"name":"reused version does not restore lineage","seq":144,"type":"case_begin"} -{"seq":145,"store":5,"type":"store_create"} -{"seq":146,"store":5,"tx":41,"type":"tx_create"} -{"global":0,"seq":147,"store":5,"term":0,"tx":41,"type":"snapshot","version":0} -{"global":0,"map":"a","seq":148,"store":5,"tx":41,"type":"map_acquire","version":0} -{"global":0,"map":"b","seq":149,"store":5,"tx":41,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":150,"store":5,"tx":41,"type":"put","value":"11"} -{"key":"00","map":"b","seq":151,"store":5,"tx":41,"type":"put","value":"11"} -{"seq":152,"store":5,"tx":41,"type":"commit_begin"} -{"seq":153,"store":5,"term":0,"tx":41,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} -{"result":"success","seq":154,"store":5,"tx":41,"type":"commit_result","version":1} -{"seq":155,"store":5,"tx":41,"type":"tx_end"} -{"seq":156,"store":5,"tx":42,"type":"tx_create"} -{"global":0,"seq":157,"store":5,"term":0,"tx":42,"type":"snapshot","version":1} -{"global":0,"map":"a","seq":158,"store":5,"tx":42,"type":"map_acquire","version":1} -{"requested":0,"seq":159,"store":5,"term":0,"type":"rollback","version":0} -{"seq":160,"store":5,"tx":43,"type":"tx_create"} -{"global":0,"seq":161,"store":5,"term":0,"tx":43,"type":"snapshot","version":0} -{"global":0,"map":"a","seq":162,"store":5,"tx":43,"type":"map_acquire","version":0} -{"global":0,"map":"b","seq":163,"store":5,"tx":43,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":164,"store":5,"tx":43,"type":"put","value":"22"} -{"key":"00","map":"b","seq":165,"store":5,"tx":43,"type":"put","value":"22"} -{"seq":166,"store":5,"tx":43,"type":"commit_begin"} -{"seq":167,"store":5,"term":0,"tx":43,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"22"},{"key":"00","map":"b","value":"22"}]} -{"result":"success","seq":168,"store":5,"tx":43,"type":"commit_result","version":1} -{"seq":169,"store":5,"tx":43,"type":"tx_end"} -{"key":"00","map":"a","seq":170,"store":5,"tx":42,"type":"put","value":"33"} -{"seq":171,"store":5,"tx":42,"type":"commit_begin"} -{"result":"conflict","seq":172,"store":5,"tx":42,"type":"commit_result","version":0} -{"seq":173,"store":5,"tx":42,"type":"tx_end"} -{"seq":174,"store":5,"type":"store_end"} -{"failed":false,"name":"reused version does not restore lineage","seq":175,"type":"case_end"} -{"name":"empty map rollback and recreation does not restore birth lineage","seq":176,"type":"case_begin"} -{"seq":177,"store":6,"type":"store_create"} -{"seq":178,"store":6,"tx":51,"type":"tx_create"} -{"global":0,"seq":179,"store":6,"term":0,"tx":51,"type":"snapshot","version":0} -{"global":0,"map":"b","seq":180,"store":6,"tx":51,"type":"map_acquire","version":0} -{"key":"00","map":"b","seq":181,"store":6,"tx":51,"type":"remove"} -{"seq":182,"store":6,"tx":51,"type":"commit_begin"} -{"seq":183,"store":6,"term":0,"tx":51,"type":"apply","version":1,"writes":[{"key":"00","map":"b","value":null}]} -{"result":"success","seq":184,"store":6,"tx":51,"type":"commit_result","version":1} -{"seq":185,"store":6,"tx":51,"type":"tx_end"} -{"seq":186,"store":6,"tx":52,"type":"tx_create"} -{"global":0,"seq":187,"store":6,"term":0,"tx":52,"type":"snapshot","version":1} -{"global":0,"map":"b","seq":188,"store":6,"tx":52,"type":"map_acquire","version":0} -{"requested":0,"seq":189,"store":6,"term":0,"type":"rollback","version":0} -{"seq":190,"store":6,"tx":53,"type":"tx_create"} -{"global":0,"seq":191,"store":6,"term":0,"tx":53,"type":"snapshot","version":0} -{"global":0,"map":"b","seq":192,"store":6,"tx":53,"type":"map_acquire","version":0} -{"key":"00","map":"b","seq":193,"store":6,"tx":53,"type":"remove"} -{"seq":194,"store":6,"tx":53,"type":"commit_begin"} -{"seq":195,"store":6,"term":0,"tx":53,"type":"apply","version":1,"writes":[{"key":"00","map":"b","value":null}]} -{"result":"success","seq":196,"store":6,"tx":53,"type":"commit_result","version":1} -{"seq":197,"store":6,"tx":53,"type":"tx_end"} -{"key":"00","map":"b","seq":198,"store":6,"tx":52,"type":"put","value":"11"} -{"seq":199,"store":6,"tx":52,"type":"commit_begin"} -{"result":"conflict","seq":200,"store":6,"tx":52,"type":"commit_result","version":0} -{"seq":201,"store":6,"tx":52,"type":"tx_end"} -{"seq":202,"store":6,"type":"store_end"} -{"failed":false,"name":"empty map rollback and recreation does not restore birth lineage","seq":203,"type":"case_end"} -{"name":"compaction and rollback respect the irrevocable prefix","seq":204,"type":"case_begin"} -{"seq":205,"store":7,"type":"store_create"} -{"seq":206,"store":7,"tx":61,"type":"tx_create"} -{"global":0,"seq":207,"store":7,"term":0,"tx":61,"type":"snapshot","version":0} -{"global":0,"map":"a","seq":208,"store":7,"tx":61,"type":"map_acquire","version":0} -{"global":0,"map":"b","seq":209,"store":7,"tx":61,"type":"map_acquire","version":0} -{"key":"00","map":"a","seq":210,"store":7,"tx":61,"type":"put","value":"11"} -{"key":"00","map":"b","seq":211,"store":7,"tx":61,"type":"put","value":"11"} -{"seq":212,"store":7,"tx":61,"type":"commit_begin"} -{"seq":213,"store":7,"term":0,"tx":61,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} -{"result":"success","seq":214,"store":7,"tx":61,"type":"commit_result","version":1} -{"seq":215,"store":7,"tx":61,"type":"tx_end"} -{"requested":2,"seq":216,"store":7,"type":"compact","version":0} -{"requested":1,"seq":217,"store":7,"type":"compact","version":1} -{"requested":9,"seq":218,"store":7,"type":"compact","version":1} -{"requested":0,"seq":219,"store":7,"term":1,"type":"rollback_rejected"} -{"seq":220,"store":7,"type":"store_end"} -{"failed":false,"name":"compaction and rollback respect the irrevocable prefix","seq":221,"type":"case_end"} -{"events":221,"seq":222,"type":"trace_end"} +{"map":"a","seq":22,"store":1,"tx":2,"type":"map_unavailable"} +{"key":"00","map":"a","seq":23,"store":1,"tx":3,"type":"get","value":"11"} +{"seq":24,"store":1,"tx":3,"type":"tx_end"} +{"seq":25,"store":1,"tx":2,"type":"tx_end"} +{"seq":26,"store":1,"type":"store_end"} +{"failed":false,"name":"first acquisition after rollback is unavailable; pinned maps retain their data","seq":27,"type":"case_end"} +{"name":"late acquisition cannot replace a discarded revision with an older surviving revision","seq":28,"type":"case_begin"} +{"seq":29,"store":2,"type":"store_create"} +{"seq":30,"store":2,"tx":11,"type":"tx_create"} +{"global":0,"seq":31,"store":2,"term":0,"tx":11,"type":"snapshot","version":0} +{"global":0,"map":"a","seq":32,"store":2,"tx":11,"type":"map_acquire","version":0} +{"global":0,"map":"b","seq":33,"store":2,"tx":11,"type":"map_acquire","version":0} +{"key":"00","map":"a","seq":34,"store":2,"tx":11,"type":"put","value":"11"} +{"key":"00","map":"b","seq":35,"store":2,"tx":11,"type":"put","value":"11"} +{"seq":36,"store":2,"tx":11,"type":"commit_begin"} +{"seq":37,"store":2,"term":0,"tx":11,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} +{"result":"success","seq":38,"store":2,"tx":11,"type":"commit_result","version":1} +{"seq":39,"store":2,"tx":11,"type":"tx_end"} +{"seq":40,"store":2,"tx":12,"type":"tx_create"} +{"global":0,"seq":41,"store":2,"term":0,"tx":12,"type":"snapshot","version":1} +{"global":0,"map":"a","seq":42,"store":2,"tx":12,"type":"map_acquire","version":1} +{"key":"00","map":"a","seq":43,"store":2,"tx":12,"type":"put","value":"22"} +{"seq":44,"store":2,"tx":12,"type":"commit_begin"} +{"seq":45,"store":2,"term":0,"tx":12,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"22"}]} +{"result":"success","seq":46,"store":2,"tx":12,"type":"commit_result","version":2} +{"seq":47,"store":2,"tx":12,"type":"tx_end"} +{"seq":48,"store":2,"tx":13,"type":"tx_create"} +{"global":0,"seq":49,"store":2,"term":0,"tx":13,"type":"snapshot","version":2} +{"global":0,"map":"b","seq":50,"store":2,"tx":13,"type":"map_acquire","version":1} +{"requested":1,"seq":51,"store":2,"term":0,"type":"rollback","version":1} +{"map":"a","seq":52,"store":2,"tx":13,"type":"map_unavailable"} +{"seq":53,"store":2,"tx":13,"type":"tx_end"} +{"seq":54,"store":2,"type":"store_end"} +{"failed":false,"name":"late acquisition cannot replace a discarded revision with an older surviving revision","seq":55,"type":"case_end"} +{"name":"late acquisition after rollback cannot select a replacement branch with the same version","seq":56,"type":"case_begin"} +{"seq":57,"store":3,"type":"store_create"} +{"seq":58,"store":3,"tx":21,"type":"tx_create"} +{"global":0,"seq":59,"store":3,"term":0,"tx":21,"type":"snapshot","version":0} +{"global":0,"map":"a","seq":60,"store":3,"tx":21,"type":"map_acquire","version":0} +{"global":0,"map":"b","seq":61,"store":3,"tx":21,"type":"map_acquire","version":0} +{"key":"00","map":"a","seq":62,"store":3,"tx":21,"type":"put","value":"11"} +{"key":"00","map":"b","seq":63,"store":3,"tx":21,"type":"put","value":"11"} +{"seq":64,"store":3,"tx":21,"type":"commit_begin"} +{"seq":65,"store":3,"term":0,"tx":21,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} +{"result":"success","seq":66,"store":3,"tx":21,"type":"commit_result","version":1} +{"seq":67,"store":3,"tx":21,"type":"tx_end"} +{"seq":68,"store":3,"tx":22,"type":"tx_create"} +{"global":0,"seq":69,"store":3,"term":0,"tx":22,"type":"snapshot","version":1} +{"global":0,"map":"a","seq":70,"store":3,"tx":22,"type":"map_acquire","version":1} +{"key":"00","map":"a","seq":71,"store":3,"tx":22,"type":"put","value":"22"} +{"seq":72,"store":3,"tx":22,"type":"commit_begin"} +{"seq":73,"store":3,"term":0,"tx":22,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"22"}]} +{"result":"success","seq":74,"store":3,"tx":22,"type":"commit_result","version":2} +{"seq":75,"store":3,"tx":22,"type":"tx_end"} +{"seq":76,"store":3,"tx":23,"type":"tx_create"} +{"global":0,"seq":77,"store":3,"term":0,"tx":23,"type":"snapshot","version":2} +{"global":0,"map":"b","seq":78,"store":3,"tx":23,"type":"map_acquire","version":1} +{"requested":1,"seq":79,"store":3,"term":0,"type":"rollback","version":1} +{"seq":80,"store":3,"tx":24,"type":"tx_create"} +{"global":0,"seq":81,"store":3,"term":0,"tx":24,"type":"snapshot","version":1} +{"global":0,"map":"a","seq":82,"store":3,"tx":24,"type":"map_acquire","version":1} +{"key":"00","map":"a","seq":83,"store":3,"tx":24,"type":"put","value":"44"} +{"seq":84,"store":3,"tx":24,"type":"commit_begin"} +{"seq":85,"store":3,"term":0,"tx":24,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"44"}]} +{"result":"success","seq":86,"store":3,"tx":24,"type":"commit_result","version":2} +{"seq":87,"store":3,"tx":24,"type":"tx_end"} +{"requested":2,"seq":88,"store":3,"type":"compact","version":2} +{"map":"a","seq":89,"store":3,"tx":23,"type":"map_unavailable"} +{"seq":90,"store":3,"tx":23,"type":"tx_end"} +{"seq":91,"store":3,"type":"store_end"} +{"failed":false,"name":"late acquisition after rollback cannot select a replacement branch with the same version","seq":92,"type":"case_end"} +{"name":"unrelated same-term rollback keeps attempt valid","seq":93,"type":"case_begin"} +{"seq":94,"store":4,"type":"store_create"} +{"seq":95,"store":4,"tx":31,"type":"tx_create"} +{"global":0,"seq":96,"store":4,"term":0,"tx":31,"type":"snapshot","version":0} +{"global":0,"map":"a","seq":97,"store":4,"tx":31,"type":"map_acquire","version":0} +{"global":0,"map":"b","seq":98,"store":4,"tx":31,"type":"map_acquire","version":0} +{"key":"00","map":"a","seq":99,"store":4,"tx":31,"type":"put","value":"11"} +{"key":"00","map":"b","seq":100,"store":4,"tx":31,"type":"put","value":"11"} +{"seq":101,"store":4,"tx":31,"type":"commit_begin"} +{"seq":102,"store":4,"term":0,"tx":31,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} +{"result":"success","seq":103,"store":4,"tx":31,"type":"commit_result","version":1} +{"seq":104,"store":4,"tx":31,"type":"tx_end"} +{"seq":105,"store":4,"tx":32,"type":"tx_create"} +{"global":0,"seq":106,"store":4,"term":0,"tx":32,"type":"snapshot","version":1} +{"global":0,"map":"a","seq":107,"store":4,"tx":32,"type":"map_acquire","version":1} +{"seq":108,"store":4,"tx":33,"type":"tx_create"} +{"global":0,"seq":109,"store":4,"term":0,"tx":33,"type":"snapshot","version":1} +{"global":0,"map":"b","seq":110,"store":4,"tx":33,"type":"map_acquire","version":1} +{"key":"00","map":"b","seq":111,"store":4,"tx":33,"type":"put","value":"22"} +{"seq":112,"store":4,"tx":33,"type":"commit_begin"} +{"seq":113,"store":4,"term":0,"tx":33,"type":"apply","version":2,"writes":[{"key":"00","map":"b","value":"22"}]} +{"result":"success","seq":114,"store":4,"tx":33,"type":"commit_result","version":2} +{"seq":115,"store":4,"tx":33,"type":"tx_end"} +{"requested":1,"seq":116,"store":4,"term":0,"type":"rollback","version":1} +{"key":"00","map":"a","seq":117,"store":4,"tx":32,"type":"put","value":"33"} +{"seq":118,"store":4,"tx":32,"type":"commit_begin"} +{"seq":119,"store":4,"term":0,"tx":32,"type":"apply","version":2,"writes":[{"key":"00","map":"a","value":"33"}]} +{"result":"success","seq":120,"store":4,"tx":32,"type":"commit_result","version":2} +{"seq":121,"store":4,"tx":32,"type":"tx_end"} +{"seq":122,"store":4,"type":"store_end"} +{"failed":false,"name":"unrelated same-term rollback keeps attempt valid","seq":123,"type":"case_end"} +{"name":"reused version does not restore lineage","seq":124,"type":"case_begin"} +{"seq":125,"store":5,"type":"store_create"} +{"seq":126,"store":5,"tx":41,"type":"tx_create"} +{"global":0,"seq":127,"store":5,"term":0,"tx":41,"type":"snapshot","version":0} +{"global":0,"map":"a","seq":128,"store":5,"tx":41,"type":"map_acquire","version":0} +{"global":0,"map":"b","seq":129,"store":5,"tx":41,"type":"map_acquire","version":0} +{"key":"00","map":"a","seq":130,"store":5,"tx":41,"type":"put","value":"11"} +{"key":"00","map":"b","seq":131,"store":5,"tx":41,"type":"put","value":"11"} +{"seq":132,"store":5,"tx":41,"type":"commit_begin"} +{"seq":133,"store":5,"term":0,"tx":41,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} +{"result":"success","seq":134,"store":5,"tx":41,"type":"commit_result","version":1} +{"seq":135,"store":5,"tx":41,"type":"tx_end"} +{"seq":136,"store":5,"tx":42,"type":"tx_create"} +{"global":0,"seq":137,"store":5,"term":0,"tx":42,"type":"snapshot","version":1} +{"global":0,"map":"a","seq":138,"store":5,"tx":42,"type":"map_acquire","version":1} +{"requested":0,"seq":139,"store":5,"term":0,"type":"rollback","version":0} +{"seq":140,"store":5,"tx":43,"type":"tx_create"} +{"global":0,"seq":141,"store":5,"term":0,"tx":43,"type":"snapshot","version":0} +{"global":0,"map":"a","seq":142,"store":5,"tx":43,"type":"map_acquire","version":0} +{"global":0,"map":"b","seq":143,"store":5,"tx":43,"type":"map_acquire","version":0} +{"key":"00","map":"a","seq":144,"store":5,"tx":43,"type":"put","value":"22"} +{"key":"00","map":"b","seq":145,"store":5,"tx":43,"type":"put","value":"22"} +{"seq":146,"store":5,"tx":43,"type":"commit_begin"} +{"seq":147,"store":5,"term":0,"tx":43,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"22"},{"key":"00","map":"b","value":"22"}]} +{"result":"success","seq":148,"store":5,"tx":43,"type":"commit_result","version":1} +{"seq":149,"store":5,"tx":43,"type":"tx_end"} +{"key":"00","map":"a","seq":150,"store":5,"tx":42,"type":"put","value":"33"} +{"seq":151,"store":5,"tx":42,"type":"commit_begin"} +{"result":"conflict","seq":152,"store":5,"tx":42,"type":"commit_result","version":0} +{"seq":153,"store":5,"tx":42,"type":"tx_end"} +{"seq":154,"store":5,"type":"store_end"} +{"failed":false,"name":"reused version does not restore lineage","seq":155,"type":"case_end"} +{"name":"empty map rollback and recreation does not restore birth lineage","seq":156,"type":"case_begin"} +{"seq":157,"store":6,"type":"store_create"} +{"seq":158,"store":6,"tx":51,"type":"tx_create"} +{"global":0,"seq":159,"store":6,"term":0,"tx":51,"type":"snapshot","version":0} +{"global":0,"map":"b","seq":160,"store":6,"tx":51,"type":"map_acquire","version":0} +{"key":"00","map":"b","seq":161,"store":6,"tx":51,"type":"remove"} +{"seq":162,"store":6,"tx":51,"type":"commit_begin"} +{"seq":163,"store":6,"term":0,"tx":51,"type":"apply","version":1,"writes":[{"key":"00","map":"b","value":null}]} +{"result":"success","seq":164,"store":6,"tx":51,"type":"commit_result","version":1} +{"seq":165,"store":6,"tx":51,"type":"tx_end"} +{"seq":166,"store":6,"tx":52,"type":"tx_create"} +{"global":0,"seq":167,"store":6,"term":0,"tx":52,"type":"snapshot","version":1} +{"global":0,"map":"b","seq":168,"store":6,"tx":52,"type":"map_acquire","version":0} +{"requested":0,"seq":169,"store":6,"term":0,"type":"rollback","version":0} +{"seq":170,"store":6,"tx":53,"type":"tx_create"} +{"global":0,"seq":171,"store":6,"term":0,"tx":53,"type":"snapshot","version":0} +{"global":0,"map":"b","seq":172,"store":6,"tx":53,"type":"map_acquire","version":0} +{"key":"00","map":"b","seq":173,"store":6,"tx":53,"type":"remove"} +{"seq":174,"store":6,"tx":53,"type":"commit_begin"} +{"seq":175,"store":6,"term":0,"tx":53,"type":"apply","version":1,"writes":[{"key":"00","map":"b","value":null}]} +{"result":"success","seq":176,"store":6,"tx":53,"type":"commit_result","version":1} +{"seq":177,"store":6,"tx":53,"type":"tx_end"} +{"key":"00","map":"b","seq":178,"store":6,"tx":52,"type":"put","value":"11"} +{"seq":179,"store":6,"tx":52,"type":"commit_begin"} +{"result":"conflict","seq":180,"store":6,"tx":52,"type":"commit_result","version":0} +{"seq":181,"store":6,"tx":52,"type":"tx_end"} +{"seq":182,"store":6,"type":"store_end"} +{"failed":false,"name":"empty map rollback and recreation does not restore birth lineage","seq":183,"type":"case_end"} +{"name":"compaction and rollback respect the irrevocable prefix","seq":184,"type":"case_begin"} +{"seq":185,"store":7,"type":"store_create"} +{"seq":186,"store":7,"tx":61,"type":"tx_create"} +{"global":0,"seq":187,"store":7,"term":0,"tx":61,"type":"snapshot","version":0} +{"global":0,"map":"a","seq":188,"store":7,"tx":61,"type":"map_acquire","version":0} +{"global":0,"map":"b","seq":189,"store":7,"tx":61,"type":"map_acquire","version":0} +{"key":"00","map":"a","seq":190,"store":7,"tx":61,"type":"put","value":"11"} +{"key":"00","map":"b","seq":191,"store":7,"tx":61,"type":"put","value":"11"} +{"seq":192,"store":7,"tx":61,"type":"commit_begin"} +{"seq":193,"store":7,"term":0,"tx":61,"type":"apply","version":1,"writes":[{"key":"00","map":"a","value":"11"},{"key":"00","map":"b","value":"11"}]} +{"result":"success","seq":194,"store":7,"tx":61,"type":"commit_result","version":1} +{"seq":195,"store":7,"tx":61,"type":"tx_end"} +{"requested":2,"seq":196,"store":7,"type":"compact","version":0} +{"requested":1,"seq":197,"store":7,"type":"compact","version":1} +{"requested":9,"seq":198,"store":7,"type":"compact","version":1} +{"requested":0,"seq":199,"store":7,"term":1,"type":"rollback_rejected"} +{"seq":200,"store":7,"type":"store_end"} +{"failed":false,"name":"compaction and rollback respect the irrevocable prefix","seq":201,"type":"case_end"} +{"events":201,"seq":202,"type":"trace_end"} diff --git a/src/kv/apply_changes.h b/src/kv/apply_changes.h index 4761b3dd0e6f..1b26dec357ad 100644 --- a/src/kv/apply_changes.h +++ b/src/kv/apply_changes.h @@ -28,7 +28,7 @@ namespace ccf::kv const MapCollection& new_maps, const std::optional& new_maps_conflict_version, bool track_deletes_on_missing_keys, - const std::optional& expected_rollback_count = std::nullopt) + const std::optional& expected_validity_epoch = std::nullopt) { // All maps with pending writes are locked, transactions are prepared // and possibly committed, and then all maps with pending writes are @@ -51,9 +51,9 @@ namespace ccf::kv bool ok = true; - if (expected_rollback_count.has_value() && !changes.empty()) + if (expected_validity_epoch.has_value() && !changes.empty()) { - // expected_rollback_count is only set on signature transactions + // expected_validity_epoch is only set on signature transactions // which always contain some writes, and on which all the maps // point to the same store. auto* store = changes.begin()->second.map->get_store(); @@ -66,7 +66,7 @@ namespace ccf::kv // maps at once to truncate their roll. The net result is that the // transaction becomes a noop if a rollback occurred between it being // committed, and the side effects being applied. - ok = store->check_rollback_count(expected_rollback_count.value()); + ok = store->check_validity_epoch(expected_validity_epoch.value()); } } diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index ae43aa9901ff..16419a23bda7 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -248,7 +248,7 @@ namespace ccf::kv bool track_deletes_on_missing_keys = false; bool commit_term_changed = false; std::optional c; - std::optional expected_rollback_count; + std::optional expected_validity_epoch; #ifdef CCF_KV_TRACING trace::Json trace_writes; if (trace::enabled()) @@ -310,8 +310,8 @@ namespace ccf::kv return std::optional{}; } - const auto [resolved_version, rollback_count] = resolution.value(); - expected_rollback_count = rollback_count; + const auto [resolved_version, validity_epoch] = resolution.value(); + expected_validity_epoch = validity_epoch; return std::optional(resolved_version); }, hooks, @@ -361,16 +361,16 @@ namespace ccf::kv // applied if a concurrent rollback has already discarded its writes. if (force_ledger_chunk || snapshot_at_next_signature) { - if (!expected_rollback_count.has_value()) + if (!expected_validity_epoch.has_value()) { throw std::logic_error( - "Transaction was allocated a version without a rollback count"); + "Transaction was allocated a version without a validity epoch"); } if (!pimpl->store->apply_tx_flags( version, pimpl->commit_view, - expected_rollback_count.value(), + expected_validity_epoch.value(), force_ledger_chunk, snapshot_at_next_signature)) { @@ -508,7 +508,8 @@ namespace ccf::kv return TxID(pimpl->commit_view, version); } - void set_read_txid(const TxID& tx_id, Term commit_view_) + void set_read_txid( + const TxID& tx_id, Term commit_view_, Version read_validity_epoch) { KV_TRACE( trace::unsupported(pimpl->store, "explicit read transaction ID")); @@ -518,6 +519,7 @@ namespace ccf::kv } pimpl->read_txid = tx_id; pimpl->commit_view = commit_view_; + pimpl->read_validity_epoch = read_validity_epoch; } void set_root_at_read_version(const ccf::crypto::Sha256Hash& r) @@ -552,16 +554,16 @@ namespace ccf::kv class ReservedTx : public CommittableTx { private: - Version rollback_count = 0; + Version validity_epoch = 0; public: ReservedTx( AbstractStore* _store, Term read_term, const TxID& reserved_tx_id, - Version rollback_count_) : + Version validity_epoch_) : CommittableTx(_store), - rollback_count(rollback_count_) + validity_epoch(validity_epoch_) { version = reserved_tx_id.seqno; pimpl->role = PrivateImpl::Role::Reserved; @@ -631,14 +633,14 @@ namespace ccf::kv pimpl->created_maps, version, track_deletes_on_missing_keys, - rollback_count); + validity_epoch); } success = c.has_value(); if (!success) { - if (pimpl->store->check_rollback_count(rollback_count)) + if (pimpl->store->check_validity_epoch(validity_epoch)) { throw std::logic_error("Failed to commit reserved transaction"); } @@ -658,7 +660,7 @@ namespace ccf::kv // behind. const auto should_create_chunk = pimpl->store->should_create_ledger_chunk_for_reserved_tx( - version, pimpl->commit_view, rollback_count); + version, pimpl->commit_view, validity_epoch); if (!should_create_chunk.has_value()) { committed = true; diff --git a/src/kv/compacted_version_conflict.h b/src/kv/compacted_version_conflict.h index 1fb49ca5cc78..ab7238333dcc 100644 --- a/src/kv/compacted_version_conflict.h +++ b/src/kv/compacted_version_conflict.h @@ -7,6 +7,8 @@ namespace ccf::kv { + // Also thrown when a map was invalidated after the transaction selected its + // read snapshot. Both conditions require retrying the entire transaction. class CompactedVersionConflict { private: diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index d26cdf1f5638..a2dad95f7bad 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -893,7 +893,7 @@ namespace ccf::kv virtual void compact(Version v) = 0; virtual std::unique_ptr snapshot(Version v) = 0; virtual void post_compact() = 0; - virtual void rollback(Version v) = 0; + virtual void rollback(Version v, Version validity_epoch) = 0; virtual void lock() = 0; virtual void unlock() = 0; virtual SecurityDomain get_security_domain() = 0; @@ -949,7 +949,9 @@ namespace ccf::kv virtual Version current_version() = 0; virtual ccf::TxID current_txid() = 0; - virtual std::pair current_txid_and_commit_term() = 0; + virtual std::tuple + current_txid_commit_term_and_validity_epoch() = 0; + virtual Version current_validity_epoch() = 0; virtual std::pair materialised_read_state() = 0; virtual Version compacted_version() = 0; @@ -978,15 +980,16 @@ namespace ccf::kv const ccf::TxID& txid, std::unique_ptr pending_tx, bool globally_committable) = 0; + virtual bool check_validity_epoch(Version expected_epoch) = 0; virtual bool check_rollback_count(Version count) = 0; virtual bool apply_tx_flags( Version version, Term expected_term, - Version expected_rollback_count, + Version expected_validity_epoch, bool force_ledger_chunk, bool snapshot_at_next_signature) = 0; virtual std::optional should_create_ledger_chunk_for_reserved_tx( - Version version, Term expected_term, Version expected_rollback_count) = 0; + Version version, Term expected_term, Version expected_validity_epoch) = 0; virtual std::unique_ptr snapshot_unsafe_maps( Version v) = 0; diff --git a/src/kv/store.h b/src/kv/store.h index 41399ce409ab..a2fdeec1da89 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -66,6 +66,10 @@ namespace ccf::kv // Always <= version: rollback() clamps it. Version last_committable = 0; + // Advances when map history is invalidated by rollback, installation, or + // replacement. Each map records the last store epoch observed by its + // history, including subsequent writes. + Version validity_epoch CCF_GUARDED_BY(version_lock) = 0; // Written only under version_lock; atomic so check_rollback_count() can // read it without contending on version_lock. std::atomic rollback_count = 0; @@ -78,8 +82,8 @@ namespace ccf::kv { // StoreState is only a base of the store, so it cannot name it. KV_TRACE(trace::unsupported(nullptr, "store clear")); - std::scoped_lock mguard( - maps_lock, version_lock); + ccf::ds::MutexGuard mguard(maps_lock); + ccf::ds::MutexGuard vguard(version_lock); maps.clear(); pending_txs.clear(); @@ -91,6 +95,7 @@ namespace ccf::kv last_replicated = 0; last_committable = 0; + validity_epoch = 0; rollback_count = 0; } }; @@ -647,6 +652,8 @@ namespace ccf::kv { std::lock_guard mguard(maps_lock); + // maps_lock serialises epoch allocation; publish it only on apply. + const auto snapshot_epoch = current_validity_epoch() + 1; OrderedChanges changes; MapCollection new_maps; @@ -724,7 +731,7 @@ namespace ccf::kv } deserialised_snapshot_changes = ccf::kv::untyped::Map::make_snapshot_changes( - captured_it->second.state, map_version); + captured_it->second.state, map_version, snapshot_epoch); ++reused_count; } else @@ -737,13 +744,13 @@ namespace ccf::kv map_version, state, serialised_digest}); deserialised_snapshot_changes = ccf::kv::untyped::Map::make_snapshot_changes( - std::move(state), map_version); + std::move(state), map_version, snapshot_epoch); } } else { deserialised_snapshot_changes = - map->deserialise_snapshot_changes(d); + map->deserialise_snapshot_changes(d, snapshot_epoch); } // Take ownership of the produced change set, store it to be @@ -777,7 +784,11 @@ namespace ccf::kv bool track_deletes_on_missing_keys = false; auto r = apply_changes( changes, - []() { return NoVersion; }, + [&]() { + ccf::ds::MutexGuard vguard(version_lock); + validity_epoch = snapshot_epoch; + return NoVersion; + }, hooks, new_maps, std::nullopt, @@ -913,8 +924,9 @@ namespace ccf::kv #ifdef CCF_KV_TRACING trace::Rollback trace_rollback(this); #endif + Version rollback_epoch = 0; { - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); if (tx_id.seqno < compacted) { KV_TRACE(trace_rollback.rejected(tx_id.seqno, term_of_next_version_)); @@ -963,7 +975,8 @@ namespace ccf::kv // underflow. last_committable = std::min(last_committable, tx_id.seqno); unset_flag_unsafe(StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE); - rollback_count++; + rollback_epoch = ++validity_epoch; + ++rollback_count; pending_txs.clear(); if (snapshotter) { @@ -994,7 +1007,7 @@ namespace ccf::kv auto& [map_creation_version, map] = it->second; // Rollback this map whether we're forgetting about it or not. Anyone // else still holding it should see it has rolled back - map->rollback(tx_id.seqno); + map->rollback(tx_id.seqno, rollback_epoch); if (map_creation_version > tx_id.seqno) { // Map was created more recently; its creation is being forgotten. @@ -1167,12 +1180,23 @@ namespace ccf::kv return current_txid_unsafe(); } - std::pair current_txid_and_commit_term() override + std::tuple + current_txid_commit_term_and_validity_epoch() override { // Must lock in case the version or commit term is being incremented. - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); KV_TRACE(trace::snapshot(this, version, term_of_next_version)); - return {current_txid_unsafe(), term_of_next_version}; + return {current_txid_unsafe(), term_of_next_version, validity_epoch}; + } + + std::tuple + get_replicated_state_txid_and_root() + { + // Rollback takes the store version lock before the history state lock. + // Hold both while pairing the history snapshot with the store epoch. + ccf::ds::MutexGuard vguard(version_lock); + auto [txid, root, term] = history->get_replicated_state_txid_and_root(); + return {txid, root, term, validity_epoch}; } Version compacted_version() override @@ -1220,7 +1244,7 @@ namespace ccf::kv BatchVector batch; Version previous_last_replicated = 0; Version next_last_replicated = 0; - Version previous_rollback_count = 0; + Version previous_validity_epoch = 0; ccf::View replication_view = 0; std::vector, bool>> @@ -1228,7 +1252,7 @@ namespace ccf::kv auto h = get_history(); { - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); if (txid.view != term_of_next_version) { // This can happen when a transaction started before a view change, @@ -1273,7 +1297,7 @@ namespace ccf::kv pending_txs.erase(search); } - previous_rollback_count = rollback_count; + previous_validity_epoch = validity_epoch; previous_last_replicated = last_replicated; next_last_replicated = last_replicated + contiguous_pending_txs.size(); @@ -1322,16 +1346,16 @@ namespace ccf::kv std::nullopt; { - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); // A rollback can only discard this batch's writes by truncating, // which requires its target to be below `version` and therefore - // increments rollback_count. A rollback that does not truncate + // increments validity_epoch. A rollback that does not truncate // leaves the writes intact, but may still move the term on, which // consensus will reject - so both are checked here. Consensus does // not roll back while local writes are accepted, so this only // happens when the Store is rolled back directly. if ( - previous_rollback_count != rollback_count || + previous_validity_epoch != validity_epoch || replication_view != term_of_next_version) { LOG_DEBUG_FMT( @@ -1380,10 +1404,10 @@ namespace ccf::kv if (c->replicate(batch, replication_view)) { - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); if ( last_replicated == previous_last_replicated && - previous_rollback_count == rollback_count) + previous_validity_epoch == validity_epoch) { last_replicated = next_last_replicated; } @@ -1407,12 +1431,12 @@ namespace ccf::kv std::optional should_create_ledger_chunk_for_reserved_tx( Version version, Term expected_term, - Version expected_rollback_count) override + Version expected_validity_epoch) override { - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); if ( term_of_next_version != expected_term || - rollback_count != expected_rollback_count) + validity_epoch != expected_validity_epoch) { return std::nullopt; } @@ -1468,6 +1492,18 @@ namespace ccf::kv maps_lock.unlock(); } + bool check_validity_epoch(Version expected_epoch) override + { + ccf::ds::MutexGuard vguard(version_lock); + return validity_epoch == expected_epoch; + } + + Version current_validity_epoch() override + { + ccf::ds::MutexGuard vguard(version_lock); + return validity_epoch; + } + bool check_rollback_count(Version count) override { return rollback_count.load() == count; @@ -1485,7 +1521,7 @@ namespace ccf::kv return std::nullopt; } - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); // If rollback updates the term before this lock is acquired, reject the // transaction before map writes are applied. If version allocation wins // the race, rollback observes the new version and truncates those writes. @@ -1503,7 +1539,7 @@ namespace ccf::kv Version v = next_version_unsafe(); KV_TRACE(trace::apply(this, v, term_of_next_version)); - return std::make_tuple(v, rollback_count.load()); + return std::make_tuple(v, validity_epoch); } std::optional next_txid() override @@ -1602,9 +1638,21 @@ namespace ccf::kv my_map->lock(); } - for (auto& [my_map, their_map] : entries) + if (!entries.empty()) { - my_map->swap(*their_map); + // Epochs from different stores are not comparable. Allocate a fresh + // epoch in each store for the incoming history, invalidating pre-swap + // change sets and preventing old transactions from acquiring it. + ccf::ds::MutexGuard guard_my_version(version_lock); + ++validity_epoch; + + ccf::ds::MutexGuard guard_their_version(store.version_lock); + ++store.validity_epoch; + + for (auto& [my_map, their_map] : entries) + { + my_map->swap(*their_map, validity_epoch, store.validity_epoch); + } } for (auto& [my_map, their_map] : entries) @@ -1715,21 +1763,21 @@ namespace ccf::kv ReservedTx create_reserved_tx(const TxID& tx_id) { - std::lock_guard vguard(version_lock); - return {this, term_of_last_version, tx_id, rollback_count.load()}; + ccf::ds::MutexGuard vguard(version_lock); + return {this, term_of_last_version, tx_id, validity_epoch}; } bool apply_tx_flags( Version tx_version, Term expected_term, - Version expected_rollback_count, + Version expected_validity_epoch, bool force_ledger_chunk, bool snapshot_at_next_signature) override { - std::lock_guard vguard(version_lock); + ccf::ds::MutexGuard vguard(version_lock); if ( term_of_next_version != expected_term || - rollback_count != expected_rollback_count) + validity_epoch != expected_validity_epoch) { return false; } diff --git a/src/kv/test/kv_contention.cpp b/src/kv/test/kv_contention.cpp index 86d2e9905673..9df48f5d00fc 100644 --- a/src/kv/test/kv_contention.cpp +++ b/src/kv/test/kv_contention.cpp @@ -391,7 +391,10 @@ DOCTEST_TEST_CASE( for (size_t read_at = 1; read_at < last_write_version; ++read_at) { auto tx = kv_store.create_tx(); - tx.set_read_txid({store_commit_term, read_at}, store_commit_term); + tx.set_read_txid( + {store_commit_term, read_at}, + store_commit_term, + kv_store.current_validity_epoch()); auto h = tx.ro(map); auto v = h->get(k); diff --git a/src/kv/test/kv_snapshot.cpp b/src/kv/test/kv_snapshot.cpp index 2b8e0edbf8a9..13899e050428 100644 --- a/src/kv/test/kv_snapshot.cpp +++ b/src/kv/test/kv_snapshot.cpp @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. +#include "kv/compacted_version_conflict.h" #include "kv/kv_serialiser.h" #include "kv/null_encryptor.h" #include "kv/store.h" @@ -834,17 +835,22 @@ TEST_CASE( REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); new_store.rollback(txid_before, new_store.commit_view()); - REQUIRE(new_store.check_rollback_count(1)); + REQUIRE(new_store.check_validity_epoch(1)); } INFO("Apply snapshot to the rolled back target store"); { + auto waiting = new_store.create_read_only_tx(); + waiting.ro(num_map); ccf::kv::ConsensusHookPtrs hooks; REQUIRE_EQ( new_store.deserialise_snapshot( serialised_snapshot.data(), serialised_snapshot.size(), hooks), ccf::kv::ApplyResult::PASS); REQUIRE_EQ(new_store.current_version(), snapshot_version); + REQUIRE(new_store.check_validity_epoch(2)); + REQUIRE_THROWS_AS( + waiting.ro(string_map), ccf::kv::CompactedVersionConflict); auto tx = new_store.create_read_only_tx(); const auto v = tx.ro(string_map)->get("foo"); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index d7df96818af5..49e9382d0932 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -3448,7 +3448,7 @@ namespace void post_compact() override {} - void rollback(ccf::kv::Version) override {} + void rollback(ccf::kv::Version, ccf::kv::Version) override {} void lock() override {} @@ -4376,12 +4376,20 @@ TEST_CASE("CommittableTx guards") const auto baseline_txid = kv_store.current_txid(); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({42}); - - // Roll the store back, invalidating the rollback_count that `reserved` - // captured when it was created. - kv_store.rollback(baseline_txid, 3); + SUBCASE("Handle acquired before rollback") + { + reserved + .wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); + kv_store.rollback(baseline_txid, 3); + } + SUBCASE("Handle acquired after rollback") + { + kv_store.rollback(baseline_txid, 3); + reserved + .wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); + } const auto info = reserved.commit_reserved(); REQUIRE(info.success == ccf::kv::CommitResult::FAIL_NO_REPLICATE); @@ -5364,14 +5372,14 @@ TEST_CASE("Rollback-sensitive transaction flags are not restored") } const auto discarded = store.current_txid(); - REQUIRE(store.check_rollback_count(0)); + REQUIRE(store.check_validity_epoch(0)); INFO("Flags from a transaction a rollback discarded are dropped"); { // A view change truncates the transaction's write away, then the // transaction reaches the point where it would apply its flags. store.rollback({initial_term, discarded.seqno - 1}, initial_term + 1); - REQUIRE(store.check_rollback_count(1)); + REQUIRE(store.check_validity_epoch(1)); CHECK_FALSE(store.apply_tx_flags( discarded.seqno, @@ -5438,7 +5446,7 @@ TEST_CASE("Reserved signature side effects are not applied after a rollback") } const auto reserved = store.current_txid(); - REQUIRE(store.check_rollback_count(0)); + REQUIRE(store.check_validity_epoch(0)); INFO("A signature a rollback discarded records no chunk end"); { @@ -5447,7 +5455,7 @@ TEST_CASE("Reserved signature side effects are not applied after a rollback") store.set_flag( ccf::kv::AbstractStore::StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE); store.rollback({initial_term, reserved.seqno - 1}, initial_term + 1); - REQUIRE(store.check_rollback_count(1)); + REQUIRE(store.check_validity_epoch(1)); CHECK_FALSE(store .should_create_ledger_chunk_for_reserved_tx( @@ -5469,7 +5477,7 @@ TEST_CASE("Reserved signature side effects are not applied after a rollback") // consensus will refuse to replicate this signature. The snapshot flag // survives, so without the view check the chunk end would be recorded. store.rollback(superseded, superseded.view + 1); - REQUIRE(store.check_rollback_count(1)); + REQUIRE(store.check_validity_epoch(1)); REQUIRE(store.flag_enabled( ccf::kv::AbstractStore::StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE)); diff --git a/src/kv/test/kv_trace.cpp b/src/kv/test/kv_trace.cpp index 8ea494471c29..54d1d351742d 100644 --- a/src/kv/test/kv_trace.cpp +++ b/src/kv/test/kv_trace.cpp @@ -253,6 +253,45 @@ TEST_CASE("KV trace iteration") } } +TEST_CASE("KV trace rollback map acquisition") +{ + TraceStore store; + store.initialise_term(1); + Map a("trace.a"); + Map b("trace.b"); + Map c("trace.c"); + for (const auto* value : {"old", "new"}) + { + auto writer = store.create_tx(); + writer.rw(a)->put("key", value); + writer.rw(b)->put("key", value); + if (store.current_version() == 0) + { + writer.rw(c)->put("key", "unaffected"); + } + REQUIRE(writer.commit() == Result::SUCCESS); + } + REQUIRE(store.current_version() == 2); + + auto reader = store.create_tx(); + REQUIRE(reader.ro(a)->get("key") == "new"); + store.rollback({1, 1}, 2); + REQUIRE(store.current_version() == 1); + SUBCASE("Unchanged map") + { + CHECK(reader.ro(c)->get("key") == "unaffected"); + CHECK_THROWS_AS(reader.ro(b), ccf::kv::CompactedVersionConflict); + } + SUBCASE("Replacement write to untruncated map") + { + auto writer = store.create_tx(); + writer.rw(c)->put("key", "unaffected"); + REQUIRE(writer.commit() == Result::SUCCESS); + CHECK_THROWS_AS(reader.ro(c), ccf::kv::CompactedVersionConflict); + } + CHECK(reader.ro(a)->get("key") == "new"); +} + TEST_CASE("KV trace compaction rollback") { TraceStore store; @@ -318,15 +357,7 @@ TEST_CASE("KV trace compaction rollback") CHECK(retained->get("key") == "rolled back"); rolled_back_store.rollback({0, 0}, 1); CHECK(retained->get("key") == "rolled back"); - auto late = waiting.rw(a); - CHECK_FALSE(late->get("key").has_value()); - CHECK_FALSE(late->get_globally_committed("key").has_value()); - CHECK_FALSE(late->get_version_of_previous_write("key").has_value()); - CHECK_FALSE(late->has("key")); - CHECK(late->size() == 0); - late->put("key", "staged"); - CHECK(late->get("key") == "staged"); - CHECK(waiting.ro(a) == late); + CHECK_THROWS_AS(waiting.rw(a), ccf::kv::CompactedVersionConflict); } for (const bool replace : {false, true}) @@ -356,17 +387,9 @@ TEST_CASE("KV trace compaction rollback") REQUIRE(writer.commit() == Result::SUCCESS); surviving_store.compact(2); } - auto late = waiting.rw(a); - CHECK(late->get("key") == (replace ? "replacement" : "survives")); - CHECK( - late->get_globally_committed("key") == - (replace ? std::make_optional("replacement") : - std::nullopt)); - CHECK(late->get_version_of_previous_write("key") == (replace ? 2 : 1)); + CHECK_THROWS_AS(waiting.rw(a), ccf::kv::CompactedVersionConflict); CHECK(retained->get("key") == "discarded"); CHECK(waiting.ro(b)->get("key") == "unchanged"); - late->put("key", "new branch"); - CHECK(waiting.commit() == Result::SUCCESS); retained->put("key", "stale branch"); CHECK(before_rollback.commit() == Result::FAIL_CONFLICT); } diff --git a/src/kv/tx.cpp b/src/kv/tx.cpp index 7bf5a60eecc4..8b7dc6f6cd6a 100644 --- a/src/kv/tx.cpp +++ b/src/kv/tx.cpp @@ -113,9 +113,11 @@ namespace ccf::kv // rather than earlier, at Tx construction. This is to minimise the // window during which concurrent transactions can write to the same map // and cause this transaction to conflict on commit. - auto p = pimpl->store->current_txid_and_commit_term(); - read_txid = p.first; - pimpl->commit_view = p.second; + const auto [txid, commit_term, validity_epoch] = + pimpl->store->current_txid_commit_term_and_validity_epoch(); + read_txid = txid; + pimpl->commit_view = commit_term; + pimpl->read_validity_epoch = validity_epoch; } auto abstract_map = pimpl->store->get_map(read_txid->seqno, map_name); @@ -148,7 +150,9 @@ namespace ccf::kv } auto change_set = untyped_map->create_change_set( - read_txid->seqno, track_deletes_on_missing_keys); + read_txid->seqno, + track_deletes_on_missing_keys, + pimpl->read_validity_epoch); // Rollback can replace a map between the access check and snapshot capture. if ( pimpl->role == PrivateImpl::Role::MaterialisedReadOnly && diff --git a/src/kv/tx_pimpl.h b/src/kv/tx_pimpl.h index 9598f14b6aee..a29db076b5d6 100644 --- a/src/kv/tx_pimpl.h +++ b/src/kv/tx_pimpl.h @@ -35,6 +35,9 @@ namespace ccf::kv std::optional read_txid = std::nullopt; Version read_rollback_count = 0; ccf::View commit_view = ccf::VIEW_UNKNOWN; + // Reserved transactions are write-only and validate their reservation on + // commit instead of selecting a read snapshot. + std::optional read_validity_epoch = std::nullopt; std::map> created_maps; }; diff --git a/src/kv/untyped_change_set.h b/src/kv/untyped_change_set.h index 9d9afd35d10e..0b383d107db6 100644 --- a/src/kv/untyped_change_set.h +++ b/src/kv/untyped_change_set.h @@ -34,13 +34,15 @@ namespace ccf::kv::untyped struct ChangeSet : public AbstractChangeSet { protected: - ChangeSet() = default; + explicit ChangeSet(Version validity_epoch_) : + validity_epoch(validity_epoch_) + {} public: #ifdef CCF_KV_TRACING trace::MapMetadata trace_metadata; #endif - const size_t rollback_counter = {}; + const Version validity_epoch = {}; const ccf::kv::untyped::State state; const ccf::kv::untyped::State committed; const Version start_version = {}; @@ -51,12 +53,12 @@ namespace ccf::kv::untyped ccf::kv::untyped::Write writes; ChangeSet( - size_t rollbacks, + Version validity_epoch_, ccf::kv::untyped::State& current_state, ccf::kv::untyped::State& committed_state, ccf::kv::untyped::Write changed_writes, Version current_version) : - rollback_counter(rollbacks), + validity_epoch(validity_epoch_), state(current_state), committed(committed_state), start_version(current_version), @@ -81,7 +83,10 @@ namespace ccf::kv::untyped const Version version; SnapshotChangeSet( - ccf::kv::untyped::State&& snapshot_state, Version version_) : + ccf::kv::untyped::State&& snapshot_state, + Version version_, + Version validity_epoch_) : + ChangeSet(validity_epoch_), state(std::move(snapshot_state)), version(version_) {} diff --git a/src/kv/untyped_map.h b/src/kv/untyped_map.h index 949fc998d8af..8308fb28ad7e 100644 --- a/src/kv/untyped_map.h +++ b/src/kv/untyped_map.h @@ -40,7 +40,9 @@ namespace ccf::kv::untyped struct Roll { std::unique_ptr commits; - size_t rollback_counter{0}; + // History replacement and writes in a later store epoch both prevent an + // older transaction from acquiring this map on the replacement branch. + Version last_observed_validity_epoch{0}; LocalCommits empty_commits; @@ -149,9 +151,8 @@ namespace ccf::kv::untyped { auto& map_roll = map.get_roll(); - // If the parent map has rolled back since this transaction began, this - // transaction must fail. - if (change_set.rollback_counter != map_roll.rollback_counter) + // A change in the map's validity epoch invalidates this change set. + if (change_set.validity_epoch != map_roll.last_observed_validity_epoch) { return false; } @@ -246,6 +247,8 @@ namespace ccf::kv::untyped { map.roll.commits->insert_back(map.roll.create_new_local_commit( v, std::move(state), change_set.writes)); + map.roll.last_observed_validity_epoch = + map.get_store()->current_validity_epoch(); } } @@ -306,7 +309,8 @@ namespace ccf::kv::untyped Map(AbstractStore* store_, const std::string& name_) : AbstractMap(name_), store(store_), - roll{std::make_unique(), 0, {}}, + roll{ + std::make_unique(), store_->current_validity_epoch(), {}}, security_domain(ccf::kv::get_security_domain(name_)) { roll.reset_commits(); @@ -401,7 +405,7 @@ namespace ccf::kv::untyped // snapshot is applied depends on the version of the map at which the // snapshot was taken. map.roll.reset_commits(); - map.roll.rollback_counter++; + map.roll.last_observed_validity_epoch = change_set.validity_epoch; auto* r = map.roll.commits->get_head(); @@ -444,12 +448,15 @@ namespace ccf::kv::untyped return {version, d.deserialise_raw_span()}; } - ChangeSetPtr deserialise_snapshot_changes(KvStoreDeserialiser& d) + ChangeSetPtr deserialise_snapshot_changes( + KvStoreDeserialiser& d, Version validity_epoch) { // Create a new empty change set, deserialising d's contents into it. const auto entry = read_snapshot_entry(d); return make_snapshot_changes( - deserialise_snapshot_state(entry.serialised_state), entry.version); + deserialise_snapshot_state(entry.serialised_state), + entry.version, + validity_epoch); } static State deserialise_snapshot_state( @@ -460,9 +467,11 @@ namespace ccf::kv::untyped // Change set replacing a map's state with state, at version, as when the // map is deserialised from a snapshot - static ChangeSetPtr make_snapshot_changes(State state, Version version) + static ChangeSetPtr make_snapshot_changes( + State state, Version version, Version validity_epoch) { - return std::make_unique(std::move(state), version); + return std::make_unique( + std::move(state), version, validity_epoch); } ChangeSetPtr deserialise_changes(KvStoreDeserialiser& d, Version version) @@ -671,7 +680,7 @@ namespace ccf::kv::untyped commit_deltas.clear(); } - void rollback(Version v) override + void rollback(Version v, Version validity_epoch) override { KV_TRACE(if (!trace::in_environment()) { trace::unsupported(get_store(), "map rollback outside store"); @@ -698,7 +707,7 @@ namespace ccf::kv::untyped if (advance) { - roll.rollback_counter++; + roll.last_observed_validity_epoch = validity_epoch; } } @@ -706,10 +715,10 @@ namespace ccf::kv::untyped { KV_TRACE( trace::unsupported(get_store(), "map clear outside transaction")); - // This discards all entries in the roll and resets the rollback - // counter. The Map expects to be locked before clearing it. + // This discards all entries in the roll. The Map expects to be locked + // before clearing it. roll.reset_commits(); - roll.rollback_counter = 0; + roll.last_observed_validity_epoch = store->current_validity_epoch(); } // Clang cannot track capabilities selected and held across map collection @@ -725,14 +734,20 @@ namespace ccf::kv::untyped } // Exchanges the entire state of this map with that of other. The caller - // must hold the locks of both maps. - void swap(Map& other) noexcept + // must hold the locks of both maps. Epochs belong to each store, so the + // imported histories are restamped rather than keeping the swapped epochs. + void swap( + Map& other, Version validity_epoch, Version other_validity_epoch) noexcept { std::swap(roll, other.roll); + roll.last_observed_validity_epoch = validity_epoch; + other.roll.last_observed_validity_epoch = other_validity_epoch; } ChangeSetPtr create_change_set( - Version version, bool track_deletes_on_missing_keys) + Version version, + bool track_deletes_on_missing_keys, + std::optional read_validity_epoch = std::nullopt) { lock(); @@ -742,6 +757,12 @@ namespace ccf::kv::untyped for (auto* current = roll.commits->get_tail(); current != nullptr; current = current->prev) { + if ( + read_validity_epoch.has_value() && + roll.last_observed_validity_epoch > read_validity_epoch.value()) + { + break; + } if (current->version <= version) { // Only deletes are copied: MapDiff reconstructs puts from the state @@ -758,7 +779,7 @@ namespace ccf::kv::untyped } } changes = std::make_unique( - roll.rollback_counter, + roll.last_observed_validity_epoch, current->state, roll.commits->get_head()->state, std::move(writes), @@ -775,8 +796,8 @@ namespace ccf::kv::untyped } // Returning nullptr is allowed, and indicates that we have no suitable - // version - the version requested is _earlier_ than anything in the - // roll + // version, either because it predates retained history or because the + // map was invalidated after the transaction selected its read version. KV_TRACE(if (changes == nullptr) { trace::operation(trace::context(), "map_unavailable", get_name()); diff --git a/src/node/rpc/frontend.h b/src/node/rpc/frontend.h index 7f7737c4bb35..65b3dd29f86f 100644 --- a/src/node/rpc/frontend.h +++ b/src/node/rpc/frontend.h @@ -1214,9 +1214,9 @@ namespace ccf // should only ever be used for the proposal creation endpoint and // nothing else. Many bad things could happen otherwise (e.g. breaking // session consistency). - const auto& [txid, root, term_of_next_version] = - current_history->get_replicated_state_txid_and_root(); - tx.set_read_txid(txid, term_of_next_version); + const auto& [txid, root, term_of_next_version, validity_epoch] = + tables.get_replicated_state_txid_and_root(); + tx.set_read_txid(txid, term_of_next_version, validity_epoch); tx.set_root_at_read_version(root); } } diff --git a/src/node/test/retry_on_compacted_version_conflict.cpp b/src/node/test/retry_on_compacted_version_conflict.cpp index 5a3a744bcb71..05b97dcc69a4 100644 --- a/src/node/test/retry_on_compacted_version_conflict.cpp +++ b/src/node/test/retry_on_compacted_version_conflict.cpp @@ -103,9 +103,10 @@ TEST_CASE("Read-only transaction retries a conflict on its first handle") { bool compact_on_read = false; - std::pair current_txid_and_commit_term() override + std::tuple + current_txid_commit_term_and_validity_epoch() override { - auto result = Store::current_txid_and_commit_term(); + auto result = Store::current_txid_commit_term_and_validity_epoch(); if (compact_on_read) { compact_on_read = false; diff --git a/tests/kv_trace_validation.py b/tests/kv_trace_validation.py index a5c9ee2c80bf..f317b70ec7cb 100755 --- a/tests/kv_trace_validation.py +++ b/tests/kv_trace_validation.py @@ -22,6 +22,7 @@ "KV trace per-map global snapshots", "KV trace disjoint concurrent commits", "KV trace replication failure after apply", + "KV trace rollback map acquisition", "KV trace rollback during replicate", } REQUIRED_FUZZ_COVERAGE = {