From 0363b82c900e6467dfb9fd0fd296e8e999a70990 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 18:25:32 -0800 Subject: [PATCH 1/7] Verus: the fleet induction, the transport protocol and fleet liveness, with no bound fleet_proofs.rs: N nodes running applied::step_spec and the protocol specs over a log spec (writes, deletes, eviction, recreation); finv inductive over every action; progress by a rank. transport_proofs.rs: pointer monotone, prune never deletes the target, fetch-vs-prune, over all interleavings. Findings F1-F4 as Verus-checked concrete states. rlimit raised on one existing lemma. Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 37 + src/kernels/applied_proofs.rs | 13 +- src/kernels/fleet_proofs.rs | 1984 +++++++++++++++++++++++++++++++ src/kernels/mod.rs | 4 + src/kernels/protocol.rs | 25 +- src/kernels/transport_proofs.rs | 347 ++++++ tests/model_fleet.rs | 19 + 7 files changed, 2423 insertions(+), 6 deletions(-) create mode 100644 src/kernels/fleet_proofs.rs create mode 100644 src/kernels/transport_proofs.rs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c63e2cd..e99d59d 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -478,6 +478,43 @@ Proving `step` equal to its spec found that a failure streak above the bound (un Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut_x`): `mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck` (and `mut_no_restore_guard`) fail `step`'s proof of equality with `step_spec`, whose theorems above are the properties those mutations break; `mut_resume_from_memory` fails `resume_from`'s postcondition; the protocol ones fail their `ensures`. +### What is proven about the fleet and the transport (Verus, no bound) + +`tests/model_fleet.rs`, `tests/model.rs` check three nodes and one key (Stateright). `src/kernels/fleet_proofs.rs` and `src/kernels/transport_proofs.rs` are their unbounded twins: any number of nodes, keys, writes, evictions, restarts and stream recreations. The log is a spec (`Log`: writes, deletes, head eviction, incarnation); the nodes run the production cursor kernel (`applied::step_spec`, through `applied_proofs::w_step`, one event at a time) and the production repair decisions through their `*_spec` tables (`restore_allowed_spec`, `plan_repair_spec`, `listing_truth_spec`, `cursorless_spec`, `restore_key_spec`, `same_incarnation`, `publish_allowed_spec`, `prunable_spec`). Nothing restates a decision. A mutation forges a decision's input exactly as the `mut_*` feature forges the code. + +| Theorem | Where | Says | +| --- | --- | --- | +| `a_fresh_fleet_satisfies_the_invariant` | `fleet_proofs.rs:1218` | base case: any number of fresh nodes over an empty log | +| `every_fleet_action_preserves_the_invariant` | `fleet_proofs.rs:1241` | `finv` is inductive over every action of every node: deliver, flush, crash at any point (even mid-restore), floor guard on a foreign cursor, key-listing repair, restore (begin, chunks, commit), publish; and write, delete, head eviction, stream recreation | +| `every_live_nodes_fold_is_the_truth_at_its_cursor` | `fleet_proofs.rs:1440` | a node of the current incarnation holds only real writes, and the truth at its cursor on every key not written since | +| `every_published_artifact_is_the_truth_at_its_cursor` | `fleet_proofs.rs:1455` | the same of the pointer's artifact | +| `a_converged_fold_is_the_truth` / `an_artifact_at_the_head_is_the_truth` | `fleet_proofs.rs:1470`, `:1483` | at the head every key is "not written since": exactly the truth | +| `a_restore_leaves_the_fold_complete_at_both_cursors` | `fleet_proofs.rs:874` | `restore_key` over every key leaves a fold complete at the old cursor (a restore cut short is safe) and at the artifact's | +| `a_restore_never_moves_a_key_backward_or_deletes_a_live_one` | `fleet_proofs.rs:934` | the kernel's per-key guarantees over the whole key space | +| `the_trusted_listing_is_the_truth` | `fleet_proofs.rs:261` | a listing the planner trusts is the truth | +| `folding_the_log_forward_keeps_a_fold_ok` | `fleet_proofs.rs:326` | delivery from `a` to `b` keeps a complete fold complete | +| `a_node_is_converged_or_a_fair_step_lowers_its_rank_or_it_is_blocked` | `fleet_proofs.rs:1679` | liveness: a ranking function (`nrank`) every fair step lowers; a node is converged or blocked | +| `a_converged_node_unblocks_every_blocked_one` | `fleet_proofs.rs:1879` | liveness: a converged node's publish is admitted and gives every blocked node an artifact | +| `a_blocked_node_names_the_write_that_aged_out` | `fleet_proofs.rs:1928` | the one fail-stop is loud and exact: revision `first - 1` was evicted after the node's cursor and no artifact of this stream holds it | +| `every_step_preserves_the_invariant` | `transport_proofs.rs:174` | transport invariant over every interleaving of N exporters, pruners and fetchers with stale reads | +| `the_pointer_never_regresses` | `transport_proofs.rs:261` | the monotone-pointer theorem lifted to the whole protocol | +| `prune_never_deletes_the_pointers_target` | `transport_proofs.rs:287` | whatever a pruner read, what it may delete is not the pointer's current target | +| `a_fetch_gets_its_payload_or_a_detected_miss` | `transport_proofs.rs:305` | a fetch racing a prune gets the object its read named or a miss, never another payload; a miss means the pointer moved strictly past it | +| `a_fresh_read_never_misses_without_a_publish`, `a_lost_cas_means_a_publish_happened` | `transport_proofs.rs:325`, `:337` | liveness: a refused fetch retries; a lost CAS is paid for by a publish | + +**The statement.** `finv`: every node of the current incarnation holds a real fold (every entry a write of the log) that is *complete* at its cursor `c`: equal to the truth at `c` on every key not written after `c`; every published artifact of the current incarnation likewise. Exact equality at `c` is not what the code keeps and is not an invariant (F3): an artifact at `C` is complete together with the log after `C`, and a restore keeps the stale entry of a key the bucket lists live (`restore_key`) because the resume delivers its later write. At the head every key is "not written since", so a converged node holds exactly the truth. The Stateright model (one key, atomic repair) cannot show the difference. + +**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. + +**Findings the proofs surfaced** (each a Verus-checked concrete state of the shipped decisions, in `fleet_proofs.rs`): + +- **F1** (`finding_f1_*`) the pointer guard compares ranks only, never the incarnation. A pointer whose artifact is the old stream's, ranked above the new head, refuses every publish of the new stream until the head passes it, while `same_incarnation` refuses to restore from it: a node that must restore has no artifact though other nodes hold the head. The unblock theorem assumes no such pointer. +- **F2** (`finding_f2_*`) a restore over the fold of a recreated stream keeps old entries that carry a higher revision number than the artifact's (`restore_key` decides by revision number). The fleet's restore step requires the local entries be real writes of the log; a foreign fold is `blocked_by_foreign_fold`. +- **F3** (`finding_f3_*`) the statement above. +- **F4** (`finding_f4_*`) the eviction memo (`seen_evicting`) rides the cursor and survives a recreation, so on the new, un-evicted bucket the exact listing is distrusted and a restore is planned; a fleet whose nodes are all foreign has no node to publish an artifact of the new stream. + +`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. + ### Export Round State Machine ``` diff --git a/src/kernels/applied_proofs.rs b/src/kernels/applied_proofs.rs index bd1c3eb..b0539d1 100644 --- a/src/kernels/applied_proofs.rs +++ b/src/kernels/applied_proofs.rs @@ -96,9 +96,19 @@ pub open spec fn pre(w: World, e: Event) -> bool { } } +/// Where a restart resumes from: the production decision, `resume_from`'s table. `mut_resume_from_memory` forges it exactly as that +/// feature forges the code, so a mutated build fails every proof that rests on a restart (the invariant, the fleet's crash step). +pub open spec fn resume_source(holds_store: bool) -> ResumeFrom { + if cfg!(feature = "mut_resume_from_memory") { + ResumeFrom::Memory + } else { + resume_from_spec(holds_store) + } +} + /// After a crash or a fail-stop: the run restarts from the cursor `resume_from` names; the store keeps what it persisted. pub open spec fn restart(w: World) -> World { - let resume = match resume_from_spec(true) { + let resume = match resume_source(true) { ResumeFrom::Store => w.store_cursor, ResumeFrom::Memory => w.applied, }; @@ -222,6 +232,7 @@ pub proof fn only_a_landed_fold_moves_the_store_cursor(w: World, e: Event, art_n /// THEOREM (restore order): the artifact's cursor is committed only by the answer to the chunk fold, from the `Fold` phase, and /// the reply to the watch task is the very next action. The restore's phases are a chain: `Ahead -> Diff -> (Listing ->) Fold -> /// Idle`, with a refusal returning to `Idle` from `Ahead` or `Listing` only. +#[verifier::rlimit(40)] pub proof fn the_cursor_commits_only_after_the_chunks_fold(s: State, e: Event) ensures step_spec(s, e).1.contains(Action::CommitCursor) ==> (e is RestoreFolded && s.restore is Fold diff --git a/src/kernels/fleet_proofs.rs b/src/kernels/fleet_proofs.rs new file mode 100644 index 0000000..22d1333 --- /dev/null +++ b/src/kernels/fleet_proofs.rs @@ -0,0 +1,1984 @@ +//! The fleet, proven with no bound: any number of nodes, keys, writes, evictions, restarts and stream recreations. +//! `tests/model_fleet.rs` model-checks three nodes and one key (Stateright); this is its unbounded twin. +//! +//! # What is proven +//! +//! A spec of the log ([`Log`]: writes, deletes, retention eviction, incarnation) and a spec of N nodes ([`Node`]), each running +//! the production cursor kernel (`applied::step_spec`, through `applied_proofs::w_step`) and the production repair decisions +//! (`restore_allowed`, `plan_repair`, `listing_truth`, `restore_key`, `cursorless_start_needs_repair`, `same_incarnation`, +//! `pointer_publish_allowed`), through their `*_spec` tables. Nothing here restates a decision: every guard below is one of those +//! specs (the kernel's own `ensures` says the code equals it). The invariant [`finv`] is inductive over every action of every +//! node ([`every_fleet_action_preserves_the_invariant`]) and holds of the initial fleet ([`a_fresh_fleet_satisfies_the_invariant`]): +//! +//! * every node of the current incarnation holds a fold that is the truth at its cursor, and +//! * every published artifact of the current incarnation is the truth at its cursor, +//! +//! where "the truth at its cursor `c` on key `k`" is the last write to `k` at or before `c` (a delete is `None`). +//! +//! # The statement, exactly (FINDING F3) +//! +//! The Stateright header says "equals the truth at its cursor". On one key with an atomic repair that is the invariant; on many +//! keys it is not what the code keeps, by design: an artifact at cursor `C` is complete *together with the log after `C`* (see +//! `restore_key`): a key whose latest write is after `C` may hold an older value in it, and the resume delivers that write. So the +//! invariant is [`complete`]: the fold equals the truth at its cursor on every key that has not been written after the cursor. +//! At the head that is every key, so a converged node's fold is exactly the truth at the head ([`a_converged_fold_is_the_truth`]). +//! [`finding_f3_the_fold_is_not_the_truth_on_a_key_rewritten_after_the_cursor`] is a concrete restore where the fold at cursor `C` +//! is not the truth at `C`, by the kernel's own `restore_key` table. +//! +//! # Findings (each a Verus-checked concrete state of the shipped decisions) +//! +//! * **F1** the pointer guard compares ranks only: a dead incarnation's pointer above the new head refuses every publish of the new +//! stream while `same_incarnation` refuses to restore from it (`finding_f1_*`). The liveness theorems assume it away explicitly. +//! * **F2** a restore over a fold of a recreated stream keeps stale entries by revision number (`finding_f2_*`). The fleet's restore +//! step requires the local entries be real writes of the log (`real`); a foreign fold is `blocked_by_foreign_fold`. +//! * **F3** the invariant is `complete`, not exact equality (above). +//! * **F4** the eviction memo outlives the incarnation: a fleet of foreign nodes blocks on a restore the exact listing could serve +//! (`finding_f4_*`). +//! +//! # What the shell and the environment must supply +//! +//! * the restore's steps (chunks, commit) interleave with crashes (a crash mid-restore leaves a store that is complete at its old +//! cursor: [`rst_ok`]); the relist (the key-listing repair) is one atomic step, as in `tests/model_fleet.rs` (its steps are +//! `tests/model_repair.rs` and `tests/resync.rs`); the restore's diff and listing events run inside [`restore_begin_w`], which +//! needs the ahead check, the window re-check and no eviction in between (a refusal is a stutter: `blocked_by_artifact`); +//! * **A1** retention config is constant inside an incarnation (a toggle is what the `seen_evicting` memo guards, so +//! `mut_no_eviction_memo` is not observable in this world); `seen` is carried and only ever narrows trust; +//! * **A2** positions are `u64`; the stream's revision numbers fit (below `2^63`); +//! * **A3** the pointer object is written only by publishes (`transport_proofs`, O2); +//! * a cursor with no recorded origin (written before cursors recorded one) is excluded: `tests/model_incarnation.rs` owns it; +//! * the liveness fairness axioms below (F-a to F-d). + +use crate::kernels::applied::*; +use crate::kernels::applied_proofs::*; +use crate::kernels::protocol::*; +use vstd::prelude::*; + +verus! { + +// --------------------------------------------------------------------------------------------------------------------- +// The log and the truth. +// --------------------------------------------------------------------------------------------------------------------- + +pub type Fold = spec_fn(nat) -> Option; + +/// One write: revision `r` (1-based) is `ops[r - 1]`. +pub struct Op { + pub key: nat, + pub put: bool, +} + +pub struct Log { + /// The stream incarnation: strictly increases on a recreation. + pub origin: nat, + pub ops: Seq, + /// The first retained revision. + pub first: nat, + /// Retention can evict current values (`max_age`, `discard: old`). + pub evicts: bool, +} + +pub open spec fn head(l: Log) -> nat { + l.ops.len() +} + +pub open spec fn umax() -> nat { + u64::MAX as nat +} + +/// The truth on `k` at cursor `c`: the last write to `k` at or before `c` (a delete is `None`); `Some(revision)`. +pub open spec fn truth(ops: Seq, c: nat, k: nat) -> Option + decreases c, +{ + if c == 0 { + None + } else if c > ops.len() { + truth(ops, ops.len(), k) + } else if ops[(c - 1) as int].key == k { + if ops[(c - 1) as int].put { Some(c) } else { None } + } else { + truth(ops, (c - 1) as nat, k) + } +} + +/// `k` is written after `c`. +pub open spec fn touched(ops: Seq, c: nat, k: nat) -> bool { + exists|j: int| c <= j && j < ops.len() && #[trigger] ops[j].key == k +} + +/// A fold entry `Some(l)` is a real write: revision `l` is a put of `k`. +pub open spec fn real_entry(ops: Seq, k: nat, l: nat) -> bool { + 1 <= l && l <= ops.len() && ops[(l - 1) as int].key == k && ops[(l - 1) as int].put +} + +pub open spec fn real(g: Fold, ops: Seq) -> bool { + forall|k: nat| (#[trigger] g(k)) is Some ==> real_entry(ops, k, g(k)->Some_0) +} + +/// THE statement: the fold is the truth at `c` on every key not written after `c` ("complete together with the log after `c`"). +pub open spec fn complete(g: Fold, ops: Seq, c: nat) -> bool { + forall|k: nat| !touched(ops, c, k) ==> #[trigger] g(k) == truth(ops, c, k) +} + +/// A real fold, complete at `c`, with `c` a position of the log. +pub open spec fn ok_fold(g: Fold, ops: Seq, c: nat) -> bool { + real(g, ops) && complete(g, ops, c) && c <= ops.len() +} + +/// The bucket's key listing (live keys only): what a key-listing repair reads. A value evicted from the log is not listed. +pub open spec fn listed(l: Log, k: nat) -> Option { + match truth(l.ops, l.ops.len(), k) { + Some(r) => if r >= l.first { Some(r) } else { None }, + None => None, + } +} + +pub open spec fn live_rev(l: Log, k: nat) -> Option { + truth(l.ops, l.ops.len(), k) +} + +pub open spec fn log_ok(l: Log) -> bool { + &&& 1 <= l.first + &&& l.first <= l.ops.len() + 1 + &&& l.ops.len() < 0x8000_0000_0000_0000 + // A bucket that keeps current values never evicts one. + &&& (!l.evicts ==> forall|k: nat| (#[trigger] live_rev(l, k)) is Some ==> live_rev(l, k)->Some_0 >= l.first) +} + +// --------------------------------------------------------------------------------------------------------------------- +// Lemmas about the truth. +// --------------------------------------------------------------------------------------------------------------------- + +pub proof fn truth_clamp(ops: Seq, c: nat, k: nat) + requires + c >= ops.len(), + ensures + truth(ops, c, k) == truth(ops, ops.len(), k), +{ +} + +/// The truth only ever names real writes, at or before the cursor. +pub proof fn truth_is_real(ops: Seq, c: nat, k: nat) + ensures + truth(ops, c, k) is Some ==> real_entry(ops, k, truth(ops, c, k)->Some_0) && truth(ops, c, k)->Some_0 <= c, + decreases c, +{ + if c == 0 { + } else if c > ops.len() { + truth_is_real(ops, ops.len(), k); + } else if ops[(c - 1) as int].key == k { + } else { + truth_is_real(ops, (c - 1) as nat, k); + } +} + +/// A key not written after `c` has the same truth at every later cursor. +pub proof fn truth_untouched(ops: Seq, c: nat, c2: nat, k: nat) + requires + c <= c2, + c2 <= ops.len(), + !touched(ops, c, k), + ensures + truth(ops, c2, k) == truth(ops, c, k), + decreases c2 - c, +{ + if c2 > c { + assert(ops[(c2 - 1) as int].key != k) by { + if ops[(c2 - 1) as int].key == k { + assert(touched(ops, c, k)); + } + } + truth_untouched(ops, c, (c2 - 1) as nat, k); + } +} + +/// `touched` shrinks as the cursor rises. +pub proof fn touched_monotone(ops: Seq, c: nat, c2: nat, k: nat) + requires + c <= c2, + touched(ops, c2, k), + ensures + touched(ops, c, k), +{ + let j = choose|j: int| c2 <= j && j < ops.len() && #[trigger] ops[j].key == k; + assert(c <= j && j < ops.len() && ops[j].key == k); +} + +/// A real put at or before `c` is not later than the truth at `c`, when the truth is a put: the truth is the LAST write. +pub proof fn truth_is_the_last_write(ops: Seq, c: nat, k: nat, l: nat) + requires + c <= ops.len(), + real_entry(ops, k, l), + l <= c, + truth(ops, c, k) is Some, + ensures + l <= truth(ops, c, k)->Some_0, + decreases c, +{ + if c == l { + } else if ops[(c - 1) as int].key == k { + } else { + truth_is_the_last_write(ops, (c - 1) as nat, k, l); + } +} + +/// Appending a write changes nothing at or below the old head. +pub proof fn truth_append(ops: Seq, op: Op, c: nat, k: nat) + requires + c <= ops.len(), + ensures + truth(ops.push(op), c, k) == truth(ops, c, k), + decreases c, +{ + let ops2 = ops.push(op); + if c == 0 { + } else if ops[(c - 1) as int].key == k { + assert(ops2[(c - 1) as int] == ops[(c - 1) as int]); + } else { + assert(ops2[(c - 1) as int] == ops[(c - 1) as int]); + truth_append(ops, op, (c - 1) as nat, k); + } +} + +/// A real fold is complete at cursor 0: a key with no write at all has no entry. +pub proof fn a_real_fold_is_complete_at_zero(g: Fold, ops: Seq) + requires + real(g, ops), + ensures + complete(g, ops, 0), +{ + assert forall|k: nat| !touched(ops, 0, k) implies #[trigger] g(k) == truth(ops, 0, k) by { + if g(k) is Some { + let l = g(k)->Some_0; + assert(real_entry(ops, k, l)); + assert(0 <= (l - 1) as int && ((l - 1) as int) < ops.len() && ops[(l - 1) as int].key == k); + assert(touched(ops, 0, k)); + } + } +} + +/// The listing is the truth when the planner trusts it: the production `listing_is_truth` (Verus-proven equal to its spec) on a +/// log whose retention keeps current values, or has evicted nothing. +pub proof fn the_trusted_listing_is_the_truth(l: Log, seen: bool, k: nat) + requires + log_ok(l), + listing_is_truth_spec(l.evicts, l.first as u64, seen), + ensures + listed(l, k) == truth(l.ops, l.ops.len(), k), +{ + truth_is_real(l.ops, l.ops.len(), k); + if !l.evicts { + assert(live_rev(l, k) == truth(l.ops, l.ops.len(), k)); + } else { + assert(l.first <= 1); + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// Folding the log into a fold. +// --------------------------------------------------------------------------------------------------------------------- + +/// Apply write `r` to a fold. +pub open spec fn fold_op(g: Fold, ops: Seq, r: nat) -> Fold { + if 1 <= r && r <= ops.len() { + |k: nat| if k == ops[(r - 1) as int].key { if ops[(r - 1) as int].put { Some(r) } else { None } } else { g(k) } + } else { + g + } +} + +/// Apply writes `a + 1 ..= b` in order. +pub open spec fn fold_range(g: Fold, ops: Seq, a: nat, b: nat) -> Fold + decreases (if b > a { b - a } else { 0int }), +{ + if b > a { fold_op(fold_range(g, ops, a, (b - 1) as nat), ops, b) } else { g } +} + +pub proof fn fold_op_keeps_ok(g: Fold, ops: Seq, c: nat) + requires + ok_fold(g, ops, c), + c < ops.len(), + ensures + ok_fold(fold_op(g, ops, c + 1), ops, c + 1), +{ + let g2 = fold_op(g, ops, c + 1); + let op = ops[c as int]; + assert forall|k: nat| (#[trigger] g2(k)) is Some implies real_entry(ops, k, g2(k)->Some_0) by { + if k == op.key { + assert(real_entry(ops, k, c + 1)); + } else { + } + } + assert forall|k: nat| !touched(ops, c + 1, k) implies #[trigger] g2(k) == truth(ops, c + 1, k) by { + if k != op.key { + assert(!touched(ops, c, k)) by { + if touched(ops, c, k) { + let j = choose|j: int| c <= j && j < ops.len() && #[trigger] ops[j].key == k; + assert(j != c as int); + assert(c + 1 <= j); + assert(touched(ops, c + 1, k)); + } + } + } + } +} + +/// THEOREM (delivery keeps the fold complete): folding the log from `a` to `b` takes a fold complete at `a` to one complete at `b`. +pub proof fn folding_the_log_forward_keeps_a_fold_ok(g: Fold, ops: Seq, a: nat, b: nat) + requires + ok_fold(g, ops, a), + a <= b, + b <= ops.len(), + ensures + ok_fold(fold_range(g, ops, a, b), ops, b), + decreases b - a, +{ + if b > a { + folding_the_log_forward_keeps_a_fold_ok(g, ops, a, (b - 1) as nat); + fold_op_keeps_ok(fold_range(g, ops, a, (b - 1) as nat), ops, (b - 1) as nat); + } +} + +/// A fold stays ok when a write is appended: nothing it claims is changed. +pub proof fn ok_fold_append(g: Fold, ops: Seq, op: Op, c: nat) + requires + ok_fold(g, ops, c), + ensures + ok_fold(g, ops.push(op), c), +{ + let ops2 = ops.push(op); + assert forall|k: nat| (#[trigger] g(k)) is Some implies real_entry(ops2, k, g(k)->Some_0) by { + let l = g(k)->Some_0; + assert(real_entry(ops, k, l)); + assert(ops2[(l - 1) as int] == ops[(l - 1) as int]); + } + assert forall|k: nat| !touched(ops2, c, k) implies #[trigger] g(k) == truth(ops2, c, k) by { + assert(!touched(ops, c, k)) by { + if touched(ops, c, k) { + let j = choose|j: int| c <= j && j < ops.len() && #[trigger] ops[j].key == k; + assert(ops2[j] == ops[j]); + assert(touched(ops2, c, k)); + } + } + truth_append(ops, op, c, k); + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// The production decisions, through their specs. A mutation forges the decision's INPUT exactly as the code's `mut_*` feature +// forges it, so a mutated build fails the induction below. +// --------------------------------------------------------------------------------------------------------------------- + +/// `resume_window_ok` on positions. +pub open spec fn win(c: nat, first: nat) -> bool { + resume_window_spec(c as u64, first as u64) +} + +/// `restore_allowed`. +pub open spec fn restore_ok(artifact: nat, local: nat, first: nat) -> bool { + if cfg!(feature = "mut_no_restore_guard") { + true + } else { + restore_allowed_spec(artifact as u64, local as u64, first as u64) + } +} + +/// `listing_truth` on a backend that reports retention. +pub open spec fn listing_lt(evicts: bool, first: nat, seen: bool) -> Option { + if cfg!(feature = "mut_relist_on_evicting") { + Some(true) + } else { + listing_truth_spec(Some((evicts, first as u64)), seen && !cfg!(feature = "mut_no_eviction_memo")) + } +} + +/// `plan_repair` under the shipped `ExpiryRepair::Auto`. +pub open spec fn plan_of(lt: Option) -> RepairPlan { + plan_repair_spec(RepairMode::Auto, lt) +} + +/// `cursorless_start_needs_repair` under `Auto`. +pub open spec fn needs_repair_first(has_data: bool, lt: Option) -> bool { + cursorless_spec(RepairMode::Auto, has_data && !cfg!(feature = "mut_unanchored_relist"), lt) +} + +pub open spec fn key_state(o: Option) -> KeyState { + match o { + Some(r) => KeyState::At(if cfg!(feature = "mut_restore_ignores_versions") { None } else { Some(r as u64) }), + None => KeyState::Absent, + } +} + +/// `restore_key` for one key: the local entry, the artifact's, and whether the bucket lists the key live. +pub open spec fn key_decision(local: Option, art: Option, listed_live: bool) -> KeyRestore { + restore_key_spec( + key_state(local), + key_state(art), + local == art, + listed_live && !cfg!(feature = "mut_restore_ignores_listing"), + ) +} + +/// What the restore leaves on each key. +pub open spec fn restore_result(l: Log, art: Fold, old: Fold) -> Fold { + |k: nat| match key_decision(old(k), art(k), listed(l, k) is Some) { + KeyRestore::Keep => old(k), + KeyRestore::TakeArtifact => art(k), + KeyRestore::Delete => None, + } +} + +pub open spec fn has_data(g: Fold) -> bool { + exists|k: nat| #[trigger] g(k) is Some +} + +// --------------------------------------------------------------------------------------------------------------------- +// The kernel's side: what each fleet step does to a node's `World` (the production kernel, one event at a time). +// --------------------------------------------------------------------------------------------------------------------- + +/// A revision of the stream is received and queued. +pub open spec fn recv_w(w: World) -> World { + w_step(w, Event::Received { positioned: true, queued: Queued { batch: 1, raw: 1 }, max: 1000 }, 0) +} + +/// A flush asks, the store fold lands. +pub open spec fn flush_w(w: World) -> World { + let w1 = w_step(w, Event::FlushRequested { queued: Queued { batch: 0, raw: 1 }, has_store: true }, 0); + w_step(w1, Event::StoreDone(StoreOutcome::Ok), 0) +} + +/// A restore starts against an artifact at cursor `a` and runs to the chunk fold. +pub open spec fn restore_begin_w(w: World, a: nat, hd: bool) -> World { + let w1 = w_step(w, Event::RepairRequested(RepairKind::Restore), a); + let w2 = w_step(w1, Event::RestoreAhead { ahead: true }, 0); + let w3 = w_step(w2, Event::RestoreDiffed { has_deletes: hd }, 0); + if hd { w_step(w3, Event::RestoreListed { window_ok: true }, 0) } else { w3 } +} + +/// The chunks are folded: the artifact's cursor is committed and flushed. +pub open spec fn restore_commit_w(w: World) -> World { + let w1 = w_step(w, Event::RestoreFolded, 0); + let w2 = w_step(w1, Event::FlushRequested { queued: Queued { batch: 0, raw: 1 }, has_store: true }, 0); + w_step(w2, Event::StoreDone(StoreOutcome::Ok), 0) +} + +pub proof fn a_received_revision_keeps_the_kernel_invariant(w: World) + requires + inv(w), + w.k.flush is Idle, + w.k.restore is Idle, + ensures + inv(recv_w(w)), + recv_w(w).store_cursor == w.store_cursor, + recv_w(w).delivered == w.delivered + 1, + recv_w(w).k.flush is Idle, + recv_w(w).k.restore is Idle, + recv_w(w).k.high, +{ + broadcast use vstd::seq_lib::group_seq_properties; + every_event_preserves_the_invariant( + w, + Event::Received { positioned: true, queued: Queued { batch: 1, raw: 1 }, max: 1000 }, + 0, + ); +} + +pub proof fn a_flush_lands_the_store_at_the_delivered_position(w: World) + requires + inv(w), + w.k.flush is Idle, + w.k.restore is Idle, + w.store_cursor < w.delivered, + ensures + inv(flush_w(w)), + flush_w(w).store_cursor == w.delivered, + flush_w(w).delivered == w.delivered, + flush_w(w).k.flush is Idle, + flush_w(w).k.restore is Idle, + !flush_w(w).k.high, +{ + broadcast use vstd::seq_lib::group_seq_properties; + let q = Queued { batch: 0, raw: 1 }; + a_landed_fold_brings_the_store_to_the_head(w, q); + let w1 = w_step(w, Event::FlushRequested { queued: q, has_store: true }, 0); + every_event_preserves_the_invariant(w, Event::FlushRequested { queued: q, has_store: true }, 0); + every_event_preserves_the_invariant(w1, Event::StoreDone(StoreOutcome::Ok), 0); +} + +pub proof fn a_restore_runs_from_a_settled_node_to_the_chunk_fold(w: World, a: nat, hd: bool) + requires + inv(w), + w.k.flush is Idle, + w.k.restore is Idle, + !w.k.high, + w.store_cursor == w.delivered, + a > w.store_cursor, + ensures + inv(restore_begin_w(w, a, hd)), + restore_begin_w(w, a, hd).k.restore is Fold, + restore_begin_w(w, a, hd).k.flush is Idle, + restore_begin_w(w, a, hd).art == a, + restore_begin_w(w, a, hd).store_cursor == w.store_cursor, + restore_begin_w(w, a, hd).delivered == w.delivered, + !restore_begin_w(w, a, hd).k.high, +{ + broadcast use vstd::seq_lib::group_seq_properties; + let w1 = w_step(w, Event::RepairRequested(RepairKind::Restore), a); + every_event_preserves_the_invariant(w, Event::RepairRequested(RepairKind::Restore), a); + let w2 = w_step(w1, Event::RestoreAhead { ahead: true }, 0); + every_event_preserves_the_invariant(w1, Event::RestoreAhead { ahead: true }, 0); + let w3 = w_step(w2, Event::RestoreDiffed { has_deletes: hd }, 0); + every_event_preserves_the_invariant(w2, Event::RestoreDiffed { has_deletes: hd }, 0); + if hd { + every_event_preserves_the_invariant(w3, Event::RestoreListed { window_ok: true }, 0); + } +} + +pub proof fn a_restore_commit_lands_the_store_at_the_artifacts_cursor(w: World) + requires + inv(w), + w.k.flush is Idle, + w.k.restore is Fold, + ensures + inv(restore_commit_w(w)), + restore_commit_w(w).store_cursor == w.art, + restore_commit_w(w).delivered == w.art, + restore_commit_w(w).k.flush is Idle, + restore_commit_w(w).k.restore is Idle, + !restore_commit_w(w).k.high, +{ + broadcast use vstd::seq_lib::group_seq_properties; + let w1 = w_step(w, Event::RestoreFolded, 0); + every_event_preserves_the_invariant(w, Event::RestoreFolded, 0); + let q = Queued { batch: 0, raw: 1 }; + let w2 = w_step(w1, Event::FlushRequested { queued: q, has_store: true }, 0); + every_event_preserves_the_invariant(w1, Event::FlushRequested { queued: q, has_store: true }, 0); + every_event_preserves_the_invariant(w2, Event::StoreDone(StoreOutcome::Ok), 0); +} + +// --------------------------------------------------------------------------------------------------------------------- +// The fleet. +// --------------------------------------------------------------------------------------------------------------------- + +/// A published artifact: the cursor it holds, the incarnation that cursor belongs to, its content. +pub struct Art { + pub cursor: nat, + pub origin: nat, + pub fold: Fold, +} + +/// A restore in flight: the artifact, the fold it started from, and the fold it ends with (what the diff decided per key). +pub struct Rst { + pub art: Art, + pub old: Fold, + pub result: Fold, +} + +/// One node: the production kernel's world (`w`, whose `store_cursor` is the persisted cursor), the STORE's content, and +/// the incarnation that content belongs to. +pub struct Node { + pub w: World, + pub fold: Fold, + pub origin: nat, + /// A cursor is persisted (else `w.store_cursor == 0` and the start is cursor-less). + pub anchored: bool, + /// The fold has seen retention evict current values (the memo). + pub seen: bool, + pub rst: Option, +} + +pub struct F { + pub log: Log, + pub nodes: Seq, + pub ptr: Option, +} + +pub enum Act { + Put(nat), + Del(nat), + /// Head eviction raises the first retained revision to `.0`. + Evict(nat), + /// The stream is deleted and recreated (new incarnation, retention `.0`). + Recreate(bool), + /// A revision reaches node `.0`'s kernel. + Advance(int), + /// A flush lands node `.0`'s store at what it received. + Flush(int), + /// Node `.0` crashes and restarts. + Crash(int), + /// The floor guard sees the cursor belongs to another incarnation: the fold is repaired as a cursor-less one. + Detect(int), + /// The fold sees retention evict current values. + See(int), + /// The key-listing repair (`ExpiryRepair::Auto` chose it), or the plain start of a cursor-less empty fold. + Relist(int), + /// A restore starts and folds some of its chunks (`.2` picks which keys); `.1`: there are delete candidates. + RestoreBegin(int, bool, spec_fn(nat) -> bool), + /// The rest of the chunks fold. + FoldChunks(int), + /// The restore's cursor commits and flushes. + RestoreEnd(int), + /// Node `.0` exports its store; the publish guard decides. + Publish(int), +} + +pub open spec fn valid(f: F, i: int) -> bool { + 0 <= i < f.nodes.len() +} + +pub open spec fn ptr_state(p: Option) -> PointerState { + match p { + None => PointerState::Absent, + Some(a) => PointerState::Present { rank: Some(a.cursor as u64) }, + } +} + +/// The kernel has nothing in flight: the pre-repair settle has run. +pub open spec fn settled(n: Node) -> bool { + n.w.k.flush is Idle && n.w.k.restore is Idle && !n.w.k.high && n.w.store_cursor == n.w.delivered && n.rst is None +} + +/// The node's cursor is expired (or it has none) and the fold's own stream is the current one. +pub open spec fn repairable(l: Log, n: Node) -> bool { + !n.anchored || (n.origin == l.origin && !win(n.w.store_cursor, l.first)) +} + +pub open spec fn lt_of(l: Log, n: Node) -> Option { + listing_lt(l.evicts, l.first, n.seen) +} + +/// The fold after the key-listing repair: the listing replaces the fold; a plain start of a fold that needs no repair re-lists +/// OVER it (a re-list never removes what it does not deliver). +pub open spec fn relist_result(l: Log, n: Node) -> Fold { + |k: nat| if n.anchored || needs_repair_first(has_data(n.fold), lt_of(l, n)) { + listed(l, k) + } else { + match listed(l, k) { + Some(r) => Some(r), + None => (n.fold)(k), + } + } +} + +pub open spec fn rst_of(n: Node) -> Rst { + n.rst->Some_0 +} + +pub open spec fn node_at(f: F, i: int) -> Node { + f.nodes[i] +} + +pub open spec fn enabled(f: F, a: Act) -> bool { + let l = f.log; + match a { + Act::Put(k) => l.ops.len() + 1 < 0x8000_0000_0000_0000, + Act::Del(k) => l.ops.len() + 1 < 0x8000_0000_0000_0000, + Act::Evict(g) => { + &&& l.first < g + &&& g <= l.ops.len() + 1 + &&& (l.evicts || forall|k: nat| (#[trigger] live_rev(l, k)) is Some ==> live_rev(l, k)->Some_0 >= g) + }, + Act::Recreate(e) => true, + Act::Advance(i) => { + valid(f, i) && ({ + let n = node_at(f, i); + &&& n.anchored + &&& n.origin == l.origin + &&& n.rst is None + &&& n.w.k.restore is Idle + &&& n.w.k.flush is Idle + &&& win(n.w.delivered, l.first) + &&& n.w.delivered < l.ops.len() + }) + }, + Act::Flush(i) => { + valid(f, i) && ({ + let n = node_at(f, i); + n.w.k.flush is Idle && n.w.k.restore is Idle && n.w.store_cursor < n.w.delivered + }) + }, + Act::Crash(i) => valid(f, i), + Act::Detect(i) => valid(f, i) && node_at(f, i).anchored && node_at(f, i).origin != l.origin, + Act::See(i) => valid(f, i) && l.evicts, + Act::Relist(i) => { + valid(f, i) && ({ + let n = node_at(f, i); + repairable(l, n) && n.rst is None && plan_of(lt_of(l, n)) is Relist + }) + }, + Act::RestoreBegin(i, hd, pick) => { + valid(f, i) && ({ + let n = node_at(f, i); + &&& repairable(l, n) + &&& settled(n) + &&& plan_of(lt_of(l, n)) is Restore + &&& f.ptr is Some + // The artifact is of THIS stream (`same_incarnation`) and `restore_allowed` (ahead, inside the window). + &&& f.ptr->Some_0.origin == l.origin + &&& restore_ok(f.ptr->Some_0.cursor, n.w.store_cursor, l.first) + // The local entries are writes of this log (FINDING F2: nothing in the code checks this of a foreign fold). + &&& real(n.fold, l.ops) + }) + }, + Act::FoldChunks(i) => valid(f, i) && node_at(f, i).rst is Some, + Act::RestoreEnd(i) => { + valid(f, i) && node_at(f, i).rst is Some + && forall|k: nat| (#[trigger] (node_at(f, i).fold)(k)) == (rst_of(node_at(f, i)).result)(k) + }, + Act::Publish(i) => { + valid(f, i) && ({ + let n = node_at(f, i); + n.anchored && n.w.store_cursor >= 1 && publish_allowed_spec(ptr_state(f.ptr), n.w.store_cursor as u64) + }) + }, + } +} + +pub open spec fn advance_node(n: Node) -> Node { + Node { w: recv_w(n.w), ..n } +} + +pub open spec fn flush_node(l: Log, n: Node) -> Node { + // The flush folds the raw queue, which is `(raw_from, delivered]`. + Node { w: flush_w(n.w), fold: fold_range(n.fold, l.ops, n.w.raw_from, n.w.delivered), ..n } +} + +pub open spec fn crash_node(n: Node) -> Node { + Node { w: restart(n.w), rst: None, ..n } +} + +pub open spec fn detect_node(n: Node) -> Node { + Node { w: init_world(0, 0), anchored: false, rst: None, ..n } +} + +pub open spec fn relist_node(l: Log, n: Node) -> Node { + Node { + w: init_world(l.ops.len(), l.ops.len()), + fold: relist_result(l, n), + origin: l.origin, + anchored: true, + seen: n.seen, + rst: None, + } +} + +pub open spec fn begin_node(l: Log, n: Node, a: Art, hd: bool, pick: spec_fn(nat) -> bool) -> Node { + let result = restore_result(l, a.fold, n.fold); + Node { + w: restore_begin_w(n.w, a.cursor, hd), + fold: |k: nat| if pick(k) { result(k) } else { (n.fold)(k) }, + origin: l.origin, + rst: Some(Rst { art: a, old: n.fold, result }), + ..n + } +} + +pub open spec fn chunks_node(n: Node) -> Node { + Node { fold: rst_of(n).result, ..n } +} + +pub open spec fn end_node(n: Node) -> Node { + Node { w: restore_commit_w(n.w), origin: rst_of(n).art.origin, anchored: true, rst: None, ..n } +} + +pub open spec fn set_node(f: F, i: int, n: Node) -> F { + F { nodes: f.nodes.update(i, n), ..f } +} + +pub open spec fn step(f: F, a: Act) -> F { + let l = f.log; + match a { + Act::Put(k) => F { log: Log { ops: l.ops.push(Op { key: k, put: true }), ..l }, ..f }, + Act::Del(k) => F { log: Log { ops: l.ops.push(Op { key: k, put: false }), ..l }, ..f }, + Act::Evict(g) => F { log: Log { first: g, ..l }, ..f }, + Act::Recreate(e) => F { log: Log { origin: l.origin + 1, ops: Seq::empty(), first: 1, evicts: e }, ..f }, + Act::Advance(i) => set_node(f, i, advance_node(node_at(f, i))), + Act::Flush(i) => set_node(f, i, flush_node(l, node_at(f, i))), + Act::Crash(i) => set_node(f, i, crash_node(node_at(f, i))), + Act::Detect(i) => set_node(f, i, detect_node(node_at(f, i))), + Act::See(i) => set_node(f, i, Node { seen: true, ..node_at(f, i) }), + Act::Relist(i) => set_node(f, i, relist_node(l, node_at(f, i))), + Act::RestoreBegin(i, hd, pick) => set_node(f, i, begin_node(l, node_at(f, i), f.ptr->Some_0, hd, pick)), + Act::FoldChunks(i) => set_node(f, i, chunks_node(node_at(f, i))), + Act::RestoreEnd(i) => set_node(f, i, end_node(node_at(f, i))), + Act::Publish(i) => { + let n = node_at(f, i); + F { ptr: Some(Art { cursor: n.w.store_cursor, origin: n.origin, fold: n.fold }), ..f } + }, + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// The invariant. +// --------------------------------------------------------------------------------------------------------------------- + +pub open spec fn rst_ok(l: Log, n: Node) -> bool { + match n.rst { + None => true, + Some(r) => { + &&& ok_fold(r.art.fold, l.ops, r.art.cursor) + &&& r.art.cursor > n.w.store_cursor + &&& ok_fold(r.old, l.ops, n.w.store_cursor) + &&& ok_fold(r.result, l.ops, n.w.store_cursor) + &&& ok_fold(r.result, l.ops, r.art.cursor) + // The store holds some chunks of the result and the rest of the old fold. + &&& forall|k: nat| (#[trigger] (n.fold)(k)) == (r.old)(k) || (n.fold)(k) == (r.result)(k) + }, + } +} + +/// What a node of the CURRENT incarnation claims. +pub open spec fn claims(l: Log, n: Node) -> bool { + &&& n.w.delivered <= l.ops.len() + &&& ok_fold(n.fold, l.ops, n.w.store_cursor) + &&& rst_ok(l, n) +} + +pub open spec fn node_ok(l: Log, n: Node) -> bool { + // The cursor authority invariant of the production kernel (`applied_proofs::inv`), per node. + &&& inv(n.w) + &&& n.w.k.flush is Idle + &&& (n.w.k.restore is Idle || n.w.k.restore is Fold) + &&& (n.w.k.restore is Fold <==> n.rst is Some) + &&& (n.rst is Some ==> n.w.art == rst_of(n).art.cursor && rst_of(n).art.origin == n.origin + && rst_of(n).art.cursor <= umax()) + &&& n.w.delivered <= umax() + &&& (!n.anchored ==> n.w.store_cursor == 0 && n.w.delivered == 0) + // A store that holds everything received has no pending position. + &&& (n.w.store_cursor == n.w.delivered ==> !n.w.k.high) + &&& n.origin <= l.origin + &&& (n.origin == l.origin ==> claims(l, n)) +} + +pub open spec fn art_ok(l: Log, a: Art) -> bool { + &&& a.cursor <= umax() + &&& a.origin <= l.origin + &&& (a.origin == l.origin ==> ok_fold(a.fold, l.ops, a.cursor)) +} + +/// THE FLEET INVARIANT: every node of the current incarnation holds a real fold that is the truth at its cursor (on every key not +/// written since), and so does every published artifact of it. +pub open spec fn finv(f: F) -> bool { + &&& log_ok(f.log) + &&& forall|i: int| 0 <= i < f.nodes.len() ==> node_ok(f.log, #[trigger] f.nodes[i]) + &&& (f.ptr is Some ==> art_ok(f.log, f.ptr->Some_0)) +} + +// --------------------------------------------------------------------------------------------------------------------- +// The restore's per-key decision (`restore_key`), over the whole key space. +// --------------------------------------------------------------------------------------------------------------------- + +/// THEOREM (a restore leaves a node complete at BOTH cursors): from a real fold complete at `c0` and an artifact complete at +/// `c1 > c0`, the per-key decisions (`restore_key`: take the artifact, keep the local entry, delete it unless the bucket lists +/// the key live) produce a real fold complete at `c0` (so a restore interrupted after any number of chunks leaves the store +/// complete at its old cursor) and complete at `c1` (so the committed cursor names a fold that is complete there). +pub proof fn a_restore_leaves_the_fold_complete_at_both_cursors(l: Log, old: Fold, art: Fold, c0: nat, c1: nat) + requires + log_ok(l), + ok_fold(old, l.ops, c0), + ok_fold(art, l.ops, c1), + c0 < c1, + ensures + ok_fold(restore_result(l, art, old), l.ops, c0), + ok_fold(restore_result(l, art, old), l.ops, c1), +{ + let ops = l.ops; + let res = restore_result(l, art, old); + assert forall|k: nat| (#[trigger] res(k)) is Some implies real_entry(ops, k, res(k)->Some_0) by { + assert(old(k) is Some ==> real_entry(ops, k, old(k)->Some_0)); + assert(art(k) is Some ==> real_entry(ops, k, art(k)->Some_0)); + } + assert forall|k: nat| !touched(ops, c0, k) implies #[trigger] res(k) == truth(ops, c0, k) by { + if !touched(ops, c0, k) { + assert(!touched(ops, c1, k)) by { + if touched(ops, c1, k) { + touched_monotone(ops, c0, c1, k); + } + } + truth_untouched(ops, c0, c1, k); + assert(old(k) == art(k)); + if old(k) is Some { + assert(real_entry(ops, k, old(k)->Some_0)); + } + } + } + assert forall|k: nat| !touched(ops, c1, k) implies #[trigger] res(k) == truth(ops, c1, k) by { + if !touched(ops, c1, k) { + truth_untouched(ops, c1, ops.len(), k); + truth_clamp(ops, ops.len(), k); + assert(art(k) == truth(ops, c1, k)); + // The bucket lists a key only if its current value is a write; an untouched key's current value is the truth at `c1`. + assert(listed(l, k) is Some ==> truth(ops, c1, k) is Some); + if old(k) is Some { + let lo = old(k)->Some_0; + assert(real_entry(ops, k, lo)); + // A write of `k` after `c1` would touch it: so every real write of `k` is at or before `c1`. + assert(lo <= c1) by { + if lo > c1 { + assert(c1 <= (lo - 1) as int && ((lo - 1) as int) < ops.len() && ops[(lo - 1) as int].key == k); + } + } + if art(k) is Some { + truth_is_the_last_write(ops, c1, k, lo); + let ar = art(k)->Some_0; + assert(lo <= ar); + assert(ar <= umax() && lo <= umax()); + } + } + } + } +} + +/// THEOREM (a restore never moves a key backward, and never deletes a key the bucket lists live): the kernel's `restore_key` +/// guarantees, over every key of the fleet's fold. Every key of the fold: if the local entry survives or is replaced, its +/// revision does not fall; a deleted entry was not listed live. +pub proof fn a_restore_never_moves_a_key_backward_or_deletes_a_live_one(l: Log, old: Fold, art: Fold, k: nat) + requires + log_ok(l), + real(old, l.ops), + real(art, l.ops), + ensures + ({ + let res = restore_result(l, art, old); + &&& (old(k) is Some && res(k) is Some ==> res(k)->Some_0 >= old(k)->Some_0) + &&& (old(k) is Some && res(k) is None ==> listed(l, k) is None) + }), +{ + assert(old(k) is Some ==> real_entry(l.ops, k, old(k)->Some_0)); + assert(art(k) is Some ==> real_entry(l.ops, k, art(k)->Some_0)); +} + +// --------------------------------------------------------------------------------------------------------------------- +// Node-level steps. +// --------------------------------------------------------------------------------------------------------------------- + +proof fn lemma_advance(l: Log, n: Node) + requires + log_ok(l), + node_ok(l, n), + n.anchored, + n.origin == l.origin, + n.rst is None, + n.w.k.restore is Idle, + n.w.k.flush is Idle, + n.w.delivered < l.ops.len(), + ensures + node_ok(l, advance_node(n)), +{ + a_received_revision_keeps_the_kernel_invariant(n.w); +} + +proof fn lemma_flush(l: Log, n: Node) + requires + node_ok(l, n), + n.w.k.flush is Idle && n.w.k.restore is Idle && n.w.store_cursor < n.w.delivered, + ensures + node_ok(l, flush_node(l, n)), +{ + a_flush_lands_the_store_at_the_delivered_position(n.w); + let n2 = flush_node(l, n); + // Nothing between the store and the loop falls on the floor: the queue starts at the store's cursor (the kernel invariant). + assert(n.w.raw_from == n.w.store_cursor); + if n.origin == l.origin { + assert(n.rst is None); + folding_the_log_forward_keeps_a_fold_ok(n.fold, l.ops, n.w.store_cursor, n.w.delivered); + } +} + +proof fn lemma_crash(l: Log, n: Node) + requires + node_ok(l, n), + ensures + node_ok(l, crash_node(n)), +{ + // The kernel invariant survives a restart (`a_restart_preserves_the_invariant`, re-derived here from `restart`, so a forged + // `resume_from` breaks THIS proof and not only that theorem). + assert(inv(restart(n.w))); + let w2 = restart(n.w); + assert(w2.store_cursor == n.w.store_cursor); + assert(w2.k.flush is Idle && w2.k.restore is Idle); +} + +proof fn lemma_detect(l: Log, n: Node) + requires + node_ok(l, n), + n.origin != l.origin, + ensures + node_ok(l, detect_node(n)), +{ + a_fresh_run_satisfies_the_invariant(0, 0); +} + +proof fn lemma_relist(l: Log, n: Node) + requires + log_ok(l), + node_ok(l, n), + repairable(l, n), + n.rst is None, + plan_of(lt_of(l, n)) is Relist, + ensures + node_ok(l, relist_node(l, n)), +{ + let n2 = relist_node(l, n); + a_fresh_run_satisfies_the_invariant(l.ops.len(), l.ops.len()); + let lt = lt_of(l, n); + assert(lt == Some(true)); + let seen2 = n.seen && !cfg!(feature = "mut_no_eviction_memo"); + assert(listing_is_truth_spec(l.evicts, l.first as u64, seen2)); + assert forall|k: nat| (#[trigger] (n2.fold)(k)) is Some implies real_entry(l.ops, k, (n2.fold)(k)->Some_0) by { + the_trusted_listing_is_the_truth(l, seen2, k); + truth_is_real(l.ops, l.ops.len(), k); + } + assert forall|k: nat| !touched(l.ops, l.ops.len(), k) implies #[trigger] (n2.fold)(k) == truth(l.ops, l.ops.len(), k) by { + the_trusted_listing_is_the_truth(l, seen2, k); + if !n.anchored && !needs_repair_first(has_data(n.fold), lt) { + // A cursor-less fold that needs no repair holds no data: the re-list over it is the listing. + assert(!has_data(n.fold)); + assert((n.fold)(k) is None); + } + } +} + +proof fn lemma_begin(l: Log, f_ptr: Art, n: Node, hd: bool, pick: spec_fn(nat) -> bool) + requires + log_ok(l), + node_ok(l, n), + art_ok(l, f_ptr), + repairable(l, n), + settled(n), + f_ptr.origin == l.origin, + restore_ok(f_ptr.cursor, n.w.store_cursor, l.first), + real(n.fold, l.ops), + ensures + node_ok(l, begin_node(l, n, f_ptr, hd, pick)), +{ + let n2 = begin_node(l, n, f_ptr, hd, pick); + let c0 = n.w.store_cursor; + let c1 = f_ptr.cursor; + // Positions are `u64`: the casts in the guard lose nothing. + assert(c0 <= umax() && c1 <= umax()); + assert(c1 > c0) by { + assert(c1 as u64 as nat == c1); + assert(c0 as u64 as nat == c0); + } + a_restore_runs_from_a_settled_node_to_the_chunk_fold(n.w, c1, hd); + // The fold is real, and complete at its cursor: by its claims (anchored), or at cursor 0 (cursor-less). + assert(ok_fold(n.fold, l.ops, c0)) by { + if n.anchored { + assert(n.origin == l.origin); + } else { + a_real_fold_is_complete_at_zero(n.fold, l.ops); + } + } + assert(c1 <= l.ops.len()); + a_restore_leaves_the_fold_complete_at_both_cursors(l, n.fold, f_ptr.fold, c0, c1); + let result = restore_result(l, f_ptr.fold, n.fold); + assert(n.w.delivered <= l.ops.len()); + assert forall|k: nat| (#[trigger] (n2.fold)(k)) is Some implies real_entry(l.ops, k, (n2.fold)(k)->Some_0) by { + assert(result(k) is Some ==> real_entry(l.ops, k, result(k)->Some_0)); + } + assert forall|k: nat| !touched(l.ops, c0, k) implies #[trigger] (n2.fold)(k) == truth(l.ops, c0, k) by { + assert(result(k) == truth(l.ops, c0, k)); + assert((n.fold)(k) == truth(l.ops, c0, k)); + } + assert(rst_ok(l, n2)); +} + +proof fn lemma_chunks(l: Log, n: Node) + requires + node_ok(l, n), + n.rst is Some, + ensures + node_ok(l, chunks_node(n)), +{ +} + +proof fn lemma_end(l: Log, n: Node) + requires + node_ok(l, n), + n.rst is Some, + forall|k: nat| (#[trigger] (n.fold)(k)) == (rst_of(n).result)(k), + ensures + node_ok(l, end_node(n)), +{ + a_restore_commit_lands_the_store_at_the_artifacts_cursor(n.w); + let n2 = end_node(n); + assert(n2.w.store_cursor == n.w.art); + if n.origin == l.origin { + assert(ok_fold(n2.fold, l.ops, rst_of(n).art.cursor)); + } +} + +// --------------------------------------------------------------------------------------------------------------------- +// Log-level steps. +// --------------------------------------------------------------------------------------------------------------------- + +proof fn lemma_append_node(l: Log, op: Op, n: Node) + requires + node_ok(l, n), + ensures + node_ok(Log { ops: l.ops.push(op), ..l }, n), +{ + let l2 = Log { ops: l.ops.push(op), ..l }; + if n.origin == l.origin { + ok_fold_append(n.fold, l.ops, op, n.w.store_cursor); + if n.rst is Some { + let r = rst_of(n); + ok_fold_append(r.art.fold, l.ops, op, r.art.cursor); + ok_fold_append(r.old, l.ops, op, n.w.store_cursor); + ok_fold_append(r.result, l.ops, op, n.w.store_cursor); + ok_fold_append(r.result, l.ops, op, r.art.cursor); + } + assert(claims(l2, n)); + } +} + +proof fn lemma_append_art(l: Log, op: Op, a: Art) + requires + art_ok(l, a), + ensures + art_ok(Log { ops: l.ops.push(op), ..l }, a), +{ + if a.origin == l.origin { + ok_fold_append(a.fold, l.ops, op, a.cursor); + } +} + +proof fn lemma_append_log(l: Log, op: Op) + requires + log_ok(l), + l.ops.len() + 1 < 0x8000_0000_0000_0000, + ensures + log_ok(Log { ops: l.ops.push(op), ..l }), +{ + let l2 = Log { ops: l.ops.push(op), ..l }; + if !l.evicts { + assert forall|k: nat| (#[trigger] live_rev(l2, k)) is Some implies live_rev(l2, k)->Some_0 >= l2.first by { + truth_is_real(l2.ops, l2.ops.len(), k); + assert(l2.ops[l.ops.len() as int] == op); + if op.key == k { + assert(live_rev(l2, k) == truth(l2.ops, l2.ops.len(), k)); + if op.put { + assert(live_rev(l2, k) == Some(l2.ops.len())); + } + } else { + truth_append(l.ops, op, l.ops.len(), k); + assert(live_rev(l2, k) == live_rev(l, k)); + } + } + } +} + +proof fn lemma_evict_log(l: Log, g: nat) + requires + log_ok(l), + l.first < g, + g <= l.ops.len() + 1, + l.evicts || forall|k: nat| (#[trigger] live_rev(l, k)) is Some ==> live_rev(l, k)->Some_0 >= g, + ensures + log_ok(Log { first: g, ..l }), +{ + let l2 = Log { first: g, ..l }; + if !l.evicts { + assert forall|k: nat| (#[trigger] live_rev(l2, k)) is Some implies live_rev(l2, k)->Some_0 >= l2.first by { + assert(live_rev(l2, k) == live_rev(l, k)); + } + } +} + +proof fn update_node_keeps(f: F, i: int, n2: Node) + requires + valid(f, i), + forall|j: int| 0 <= j < f.nodes.len() ==> node_ok(f.log, #[trigger] f.nodes[j]), + node_ok(f.log, n2), + ensures + forall|j: int| 0 <= j < set_node(f, i, n2).nodes.len() ==> node_ok(f.log, #[trigger] set_node(f, i, n2).nodes[j]), +{ + let f2 = set_node(f, i, n2); + assert forall|j: int| 0 <= j < f2.nodes.len() implies node_ok(f.log, #[trigger] f2.nodes[j]) by { + if j != i { + assert(f2.nodes[j] == f.nodes[j]); + } + } +} + +proof fn lemma_recreate_node(l: Log, e: bool, n: Node) + requires + node_ok(l, n), + ensures + node_ok(Log { origin: l.origin + 1, ops: Seq::empty(), first: 1, evicts: e }, n), +{ +} + +// --------------------------------------------------------------------------------------------------------------------- +// THE INDUCTION. +// --------------------------------------------------------------------------------------------------------------------- + +/// THEOREM (base case): the initial fleet satisfies the invariant: an empty log and any number of nodes, each a fresh run over an +/// empty store (anchored at cursor 0 or cursor-less), no artifact. +pub proof fn a_fresh_fleet_satisfies_the_invariant(nodes: Seq, evicts: bool) + requires + forall|i: int| 0 <= i < nodes.len() ==> ( + #[trigger] nodes[i].w == init_world(0, 0) && nodes[i].origin == 1 && nodes[i].rst is None), + forall|i: int, k: nat| 0 <= i < nodes.len() ==> #[trigger] (nodes[i].fold)(k) is None, + ensures + finv(F { log: Log { origin: 1, ops: Seq::empty(), first: 1, evicts }, nodes, ptr: None }), +{ + a_fresh_run_satisfies_the_invariant(0, 0); + let l = Log { origin: 1, ops: Seq::empty(), first: 1, evicts }; + assert forall|i: int| 0 <= i < nodes.len() implies node_ok(l, #[trigger] nodes[i]) by { + let n = nodes[i]; + assert(ok_fold(n.fold, l.ops, 0)) by { + assert forall|k: nat| (#[trigger] (n.fold)(k)) is Some implies real_entry(l.ops, k, (n.fold)(k)->Some_0) by {} + assert forall|k: nat| !touched(l.ops, 0, k) implies #[trigger] (n.fold)(k) == truth(l.ops, 0, k) by {} + } + } +} + +/// THEOREM (THE INDUCTION): from any fleet satisfying the invariant, every action of every node (and of the log) that its guard +/// admits leaves a fleet that satisfies it: a delivery, a flush, a crash and restart at any point (even mid-restore), the floor +/// guard seeing a foreign cursor, a key-listing repair, a restore (its chunks, its commit), a publish; and a write, a delete, +/// head eviction, a recreation of the stream. Any number of nodes, keys and writes. +pub proof fn every_fleet_action_preserves_the_invariant(f: F, a: Act) + requires + finv(f), + enabled(f, a), + ensures + finv(step(f, a)), +{ + match a { + Act::Put(k) => case_write(f, Op { key: k, put: true }), + Act::Del(k) => case_write(f, Op { key: k, put: false }), + Act::Evict(g) => case_evict(f, g), + Act::Recreate(e) => case_recreate(f, e), + Act::Publish(i) => case_publish(f, i), + Act::Advance(i) => case_advance(f, i), + Act::Flush(i) => case_flush(f, i), + Act::Crash(i) => case_crash(f, i), + Act::Detect(i) => case_detect(f, i), + Act::See(i) => case_see(f, i), + Act::Relist(i) => case_relist(f, i), + Act::RestoreBegin(i, hd, pick) => case_begin(f, i, hd, pick), + Act::FoldChunks(i) => case_chunks(f, i), + Act::RestoreEnd(i) => case_end(f, i), + } +} + +proof fn case_advance(f: F, i: int) + requires + finv(f), + enabled(f, Act::Advance(i)), + ensures + finv(step(f, Act::Advance(i))), +{ + lemma_advance(f.log, node_at(f, i)); + node_step_ok(f, i, advance_node(node_at(f, i))); +} + +proof fn case_flush(f: F, i: int) + requires + finv(f), + enabled(f, Act::Flush(i)), + ensures + finv(step(f, Act::Flush(i))), +{ + lemma_flush(f.log, node_at(f, i)); + node_step_ok(f, i, flush_node(f.log, node_at(f, i))); +} + +proof fn case_crash(f: F, i: int) + requires + finv(f), + enabled(f, Act::Crash(i)), + ensures + finv(step(f, Act::Crash(i))), +{ + lemma_crash(f.log, node_at(f, i)); + node_step_ok(f, i, crash_node(node_at(f, i))); +} + +proof fn case_detect(f: F, i: int) + requires + finv(f), + enabled(f, Act::Detect(i)), + ensures + finv(step(f, Act::Detect(i))), +{ + lemma_detect(f.log, node_at(f, i)); + node_step_ok(f, i, detect_node(node_at(f, i))); +} + +proof fn case_see(f: F, i: int) + requires + finv(f), + enabled(f, Act::See(i)), + ensures + finv(step(f, Act::See(i))), +{ + let n = node_at(f, i); + assert(node_ok(f.log, n)); + node_step_ok(f, i, Node { seen: true, ..n }); +} + +proof fn case_relist(f: F, i: int) + requires + finv(f), + enabled(f, Act::Relist(i)), + ensures + finv(step(f, Act::Relist(i))), +{ + lemma_relist(f.log, node_at(f, i)); + node_step_ok(f, i, relist_node(f.log, node_at(f, i))); +} + +proof fn case_begin(f: F, i: int, hd: bool, pick: spec_fn(nat) -> bool) + requires + finv(f), + enabled(f, Act::RestoreBegin(i, hd, pick)), + ensures + finv(step(f, Act::RestoreBegin(i, hd, pick))), +{ + lemma_begin(f.log, f.ptr->Some_0, node_at(f, i), hd, pick); + node_step_ok(f, i, begin_node(f.log, node_at(f, i), f.ptr->Some_0, hd, pick)); +} + +proof fn case_chunks(f: F, i: int) + requires + finv(f), + enabled(f, Act::FoldChunks(i)), + ensures + finv(step(f, Act::FoldChunks(i))), +{ + lemma_chunks(f.log, node_at(f, i)); + node_step_ok(f, i, chunks_node(node_at(f, i))); +} + +proof fn case_end(f: F, i: int) + requires + finv(f), + enabled(f, Act::RestoreEnd(i)), + ensures + finv(step(f, Act::RestoreEnd(i))), +{ + lemma_end(f.log, node_at(f, i)); + node_step_ok(f, i, end_node(node_at(f, i))); +} + +proof fn node_step_ok(f: F, i: int, n2: Node) + requires + finv(f), + valid(f, i), + node_ok(f.log, n2), + ensures + finv(set_node(f, i, n2)), +{ + update_node_keeps(f, i, n2); +} + +proof fn case_write(f: F, op: Op) + requires + finv(f), + f.log.ops.len() + 1 < 0x8000_0000_0000_0000, + ensures + finv(F { log: Log { ops: f.log.ops.push(op), ..f.log }, ..f }), +{ + let l = f.log; + let f2 = F { log: Log { ops: l.ops.push(op), ..l }, ..f }; + lemma_append_log(l, op); + assert forall|i: int| 0 <= i < f2.nodes.len() implies node_ok(f2.log, #[trigger] f2.nodes[i]) by { + lemma_append_node(l, op, f.nodes[i]); + } + if f.ptr is Some { + lemma_append_art(l, op, f.ptr->Some_0); + } +} + +proof fn case_evict(f: F, g: nat) + requires + finv(f), + enabled(f, Act::Evict(g)), + ensures + finv(step(f, Act::Evict(g))), +{ + let l = f.log; + let f2 = step(f, Act::Evict(g)); + lemma_evict_log(l, g); + assert forall|i: int| 0 <= i < f2.nodes.len() implies node_ok(f2.log, #[trigger] f2.nodes[i]) by { + assert(node_ok(l, f.nodes[i])); + } +} + +proof fn case_recreate(f: F, e: bool) + requires + finv(f), + ensures + finv(step(f, Act::Recreate(e))), +{ + let l = f.log; + let f2 = step(f, Act::Recreate(e)); + assert forall|i: int| 0 <= i < f2.nodes.len() implies node_ok(f2.log, #[trigger] f2.nodes[i]) by { + lemma_recreate_node(l, e, f.nodes[i]); + } +} + +proof fn case_publish(f: F, i: int) + requires + finv(f), + enabled(f, Act::Publish(i)), + ensures + finv(step(f, Act::Publish(i))), +{ + let n = node_at(f, i); + assert(node_ok(f.log, n)); +} + +// --------------------------------------------------------------------------------------------------------------------- +// What the invariant says, stated as the two safety properties. +// --------------------------------------------------------------------------------------------------------------------- + +/// THEOREM (every live node's fold is the truth at its cursor): a node of the current incarnation holds, on every key not written +/// since its cursor, the truth at its cursor; and holds only writes of this log. +pub proof fn every_live_nodes_fold_is_the_truth_at_its_cursor(f: F, i: int, k: nat) + requires + finv(f), + valid(f, i), + node_at(f, i).origin == f.log.origin, + ensures + !touched(f.log.ops, node_at(f, i).w.store_cursor, k) + ==> (node_at(f, i).fold)(k) == truth(f.log.ops, node_at(f, i).w.store_cursor, k), + (node_at(f, i).fold)(k) is Some ==> real_entry(f.log.ops, k, (node_at(f, i).fold)(k)->Some_0), +{ + assert(node_ok(f.log, f.nodes[i])); +} + +/// THEOREM (every published artifact is the truth at its cursor): the same of the pointer's artifact, when it is of the current +/// incarnation (an artifact of another incarnation is never restored: `same_incarnation`). +pub proof fn every_published_artifact_is_the_truth_at_its_cursor(f: F, k: nat) + requires + finv(f), + f.ptr is Some, + f.ptr->Some_0.origin == f.log.origin, + ensures + !touched(f.log.ops, f.ptr->Some_0.cursor, k) + ==> (f.ptr->Some_0.fold)(k) == truth(f.log.ops, f.ptr->Some_0.cursor, k), + (f.ptr->Some_0.fold)(k) is Some ==> real_entry(f.log.ops, k, (f.ptr->Some_0.fold)(k)->Some_0), + f.ptr->Some_0.cursor <= f.log.ops.len(), +{ +} + +/// THEOREM (converged means exactly the truth): at the head every key is "not written since", so a node (or artifact) at the head +/// holds exactly the truth at the head, key for key. +pub proof fn a_converged_fold_is_the_truth(f: F, i: int, k: nat) + requires + finv(f), + valid(f, i), + node_at(f, i).origin == f.log.origin, + node_at(f, i).w.store_cursor == f.log.ops.len(), + ensures + (node_at(f, i).fold)(k) == truth(f.log.ops, f.log.ops.len(), k), +{ + assert(node_ok(f.log, f.nodes[i])); + assert(!touched(f.log.ops, f.log.ops.len(), k)); +} + +pub proof fn an_artifact_at_the_head_is_the_truth(f: F, k: nat) + requires + finv(f), + f.ptr is Some, + f.ptr->Some_0.origin == f.log.origin, + f.ptr->Some_0.cursor == f.log.ops.len(), + ensures + (f.ptr->Some_0.fold)(k) == truth(f.log.ops, f.log.ops.len(), k), +{ + assert(!touched(f.log.ops, f.log.ops.len(), k)); +} + +// --------------------------------------------------------------------------------------------------------------------- +// FINDINGS, each a concrete state the shipped decisions reach. +// --------------------------------------------------------------------------------------------------------------------- + +/// FINDING F3 (the statement): `fold == truth at cursor` is not what the code keeps, by design. A restore keeps the stale local +/// entry of a key the bucket lists live (`restore_key`: "never a phantom delete"; the resume delivers the later write). Here +/// key 0 is put (rev 1), deleted (rev 2) and put again (rev 3). A node at cursor 1 restores from an artifact at cursor 2 (key 0 +/// absent): the bucket lists key 0 (rev 3), so the entry `Some(1)` is kept, and the committed cursor 2 names a fold whose key 0 is +/// `Some(1)`, not the truth at 2 (absent). The fold is complete at 2 on every key not written since (key 0 was), and converges +/// when revision 3 is delivered. The invariant is `complete`, and the Stateright model (one key, atomic repair) cannot see this. +pub proof fn finding_f3_the_fold_is_not_the_truth_on_a_key_rewritten_after_the_cursor() + requires + !cfg!(feature = "mut_restore_ignores_listing"), + !cfg!(feature = "mut_restore_ignores_versions"), + ensures + ({ + let ops = seq![Op { key: 0, put: true }, Op { key: 0, put: false }, Op { key: 0, put: true }]; + let l = Log { origin: 1, ops, first: 1, evicts: true }; + let old: Fold = |k: nat| if k == 0 { Some(1nat) } else { None }; + let art: Fold = |k: nat| None; + restore_result(l, art, old)(0) == Some(1nat) && truth(ops, 2, 0) is None && truth(ops, 3, 0) == Some(3nat) + && touched(ops, 2, 0) + }), +{ + let ops = seq![Op { key: 0, put: true }, Op { key: 0, put: false }, Op { key: 0, put: true }]; + let l = Log { origin: 1, ops, first: 1, evicts: true }; + assert(ops[2].key == 0); + assert(touched(ops, 2, 0)); + assert(truth(ops, 3, 0) == Some(3nat)); + assert(truth(ops, 2, 0) is None); +} + +/// FINDING F2 (a restore over a foreign fold): when the stream is deleted and recreated, a node's fold holds the OLD stream's +/// entries and revisions (`Detect`: repaired "like a cursor-less start that holds data"). With the listing untrusted +/// (an evicting bucket) that repair is a restore, and `restore_key` decides by REVISION NUMBER: an old entry numbered above the +/// artifact's is "newer" and kept. Here the new stream has put key 0 seven times (artifact cursor 7, key 0 at rev 7), the old +/// entry is `Some(500)`: the restore keeps it, and the committed fold at cursor 7 holds a value no write of this log made, on a key +/// no write follows. (Nothing in `check_restore` or `restore_diff` rules a foreign fold out.) The fleet proof therefore requires +/// the local entries be real writes of this log (`real`) before a restore, and a foreign fold that is not is not restored: +/// the liveness theorems carry the same premise (`blocked_by_foreign_fold`). +pub proof fn finding_f2_a_restore_over_a_foreign_fold_keeps_a_stale_entry() + requires + !cfg!(feature = "mut_restore_ignores_versions"), + ensures + ({ + let ops = Seq::new(7, |i: int| Op { key: 0, put: true }); + let l = Log { origin: 2, ops, first: 1, evicts: true }; + let old: Fold = |k: nat| if k == 0 { Some(500nat) } else { None }; + let art: Fold = |k: nat| if k == 0 { Some(7nat) } else { None }; + ok_fold(art, ops, 7) && !real(old, ops) && restore_result(l, art, old)(0) == Some(500nat) + && truth(ops, 7, 0) == Some(7nat) && !touched(ops, 7, 0) + }), +{ + let ops = Seq::new(7, |i: int| Op { key: 0, put: true }); + let l = Log { origin: 2, ops, first: 1, evicts: true }; + let old: Fold = |k: nat| if k == 0 { Some(500nat) } else { None }; + let art: Fold = |k: nat| if k == 0 { Some(7nat) } else { None }; + assert(truth(ops, 7, 0) == Some(7nat)); + assert(!real_entry(ops, 0, 500)); + assert(old(0) == Some(500nat)); + assert(!real(old, ops)); + assert forall|k: nat| (#[trigger] art(k)) is Some implies real_entry(ops, k, art(k)->Some_0) by {} + assert forall|k: nat| !touched(ops, 7, k) implies #[trigger] art(k) == truth(ops, 7, k) by { + if k == 0 { + } else { + assert(truth(ops, 7, k) is None) by { + truth_is_real(ops, 7, k); + } + } + } + assert(!touched(ops, 7, 0)); +} + +/// FINDING F1 (a dead incarnation's pointer wedges publishing): the pointer guard compares ranks only +/// (`pointer_publish_allowed`, `transport::swap_pointer`), never the incarnation. After the stream is recreated, a pointer whose +/// artifact is the OLD stream's, ranked above the new stream's head, refuses every publish of the new stream until its head +/// passes that rank, while `same_incarnation` refuses to restore from it. Between the two, the fleet has no usable artifact: a node +/// that must restore (an evicting bucket) cannot, though every other node holds the head. +pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_refuses_every_publish(l: Log, a: Art, c: nat) + requires + a.origin < l.origin, + a.cursor > c, + a.cursor <= umax(), + c <= umax(), + ensures + !publish_allowed_spec(ptr_state(Some(a)), c as u64), + !(a.origin == l.origin), +{ +} + +// --------------------------------------------------------------------------------------------------------------------- +// LIVENESS. Every node converges, or fail-stops loudly exactly where a write aged out before any fold held it. +// +// The progress argument is a ranking function (`nrank`) that every fair step lowers until the goal, under named fairness +// assumptions on the ENVIRONMENT (never on slipstream's own code): +// * F-a NATS delivers: a received revision reaches the kernel (`Advance`) while the window holds; +// * F-b the disk works: a flush lands, the chunks fold, the commit flushes (`Flush`, `FoldChunks`, `RestoreEnd`); +// * F-c the object store answers (`Publish`, the artifact read in `RestoreBegin`); +// * F-d quiescence: from some point on the log takes no more writes, evictions or recreations, and the nodes no more crashes. +// (Every other node action is a node's own decision, and a fair scheduler runs each enabled one.) +// The lemmas below are state-based: from any state satisfying the invariant, for each node. +// --------------------------------------------------------------------------------------------------------------------- + +/// The node is watching the current stream inside its window. +pub open spec fn live(l: Log, n: Node) -> bool { + n.anchored && n.origin == l.origin && win(n.w.delivered, l.first) && n.rst is None +} + +pub open spec fn converged(l: Log, n: Node) -> bool { + live(l, n) && n.w.delivered == l.ops.len() && n.w.store_cursor == n.w.delivered +} + +pub open spec fn folded(n: Node) -> bool { + forall|k: nat| (#[trigger] (n.fold)(k)) == (rst_of(n).result)(k) +} + +/// THE RANK. Zero is converged. A live node's rank is what it still has to receive and flush. A node that must repair ranks +/// above every live one, and a restore's stages rank in the order they run. +pub open spec fn nrank(l: Log, n: Node) -> int { + let len = l.ops.len() as int; + if converged(l, n) { + 0 + } else if live(l, n) { + 2 * (len - n.w.delivered as int) + (n.w.delivered as int - n.w.store_cursor as int) + } else if n.rst is Some { + let fl: int = if folded(n) { 0 } else { 1 }; + if n.origin != l.origin { + 2 * len + 11 + fl + } else if win(rst_of(n).art.cursor, l.first) { + 2 * len + 4 + fl + } else { + 2 * len + 7 + fl + } + } else if n.anchored && n.origin != l.origin { + 2 * len + 10 + } else { + 2 * len + 6 + (n.w.delivered as int - n.w.store_cursor as int) + } +} + +/// The artifact the pointer names can seed this node: of this stream, ahead, inside the window. +pub open spec fn admissible_art(f: F, n: Node) -> bool { + f.ptr is Some && f.ptr->Some_0.origin == f.log.origin && restore_ok(f.ptr->Some_0.cursor, n.w.store_cursor, f.log.first) +} + +/// The node must restore (expired cursor, or none, and the listing is not the truth) and NO artifact can seed it: the loud +/// fail-stop (`check_restore` returns the operator-facing error). This is the one data loss retention can cause. +pub open spec fn blocked_by_artifact(f: F, i: int) -> bool { + let n = node_at(f, i); + repairable(f.log, n) && settled(n) && plan_of(lt_of(f.log, n)) is Restore && !admissible_art(f, n) +} + +/// FINDING F2's liveness face: an artifact could seed the node but its fold holds entries that are no write of this log. +pub open spec fn blocked_by_foreign_fold(f: F, i: int) -> bool { + let n = node_at(f, i); + repairable(f.log, n) && settled(n) && plan_of(lt_of(f.log, n)) is Restore && admissible_art(f, n) + && !real(n.fold, f.log.ops) +} + +pub open spec fn acts_on(a: Act, i: int) -> bool { + match a { + Act::Advance(j) => j == i, + Act::Flush(j) => j == i, + Act::Detect(j) => j == i, + Act::Relist(j) => j == i, + Act::RestoreBegin(j, hd, pick) => j == i, + Act::FoldChunks(j) => j == i, + Act::RestoreEnd(j) => j == i, + _ => false, + } +} + +/// A fair step of node `i` that lowers its rank (and leaves the log as it is). +pub open spec fn lowers(f: F, i: int, a: Act) -> bool { + &&& enabled(f, a) + &&& acts_on(a, i) + &&& step(f, a).log == f.log + &&& valid(step(f, a), i) + &&& nrank(f.log, step(f, a).nodes[i]) < nrank(f.log, f.nodes[i]) +} + +/// THEOREM (progress): from any state satisfying the invariant, every node is converged, or some fair step of its own lowers its +/// rank, or it is blocked (no artifact can seed it, or, FINDING F2, its fold is foreign). The rank is a natural number, so a node +/// that is never blocked reaches the head in finitely many steps. +pub proof fn a_node_is_converged_or_a_fair_step_lowers_its_rank_or_it_is_blocked(f: F, i: int) + requires + finv(f), + valid(f, i), + ensures + converged(f.log, node_at(f, i)) || (exists|a: Act| #[trigger] lowers(f, i, a)) || blocked_by_artifact(f, i) + || blocked_by_foreign_fold(f, i), +{ + let l = f.log; + let n = node_at(f, i); + assert(node_ok(l, n)); + if converged(l, n) { + } else if live(l, n) { + prog_live(f, i); + } else if n.rst is Some { + prog_restore(f, i); + } else if n.anchored && n.origin != l.origin { + let a = Act::Detect(i); + lemma_detect(l, n); + node_step_ok(f, i, detect_node(n)); + assert(lowers(f, i, a)); + } else { + prog_repair(f, i); + } +} + +proof fn lowers_from(f: F, i: int, a: Act, n2: Node) + requires + valid(f, i), + enabled(f, a), + acts_on(a, i), + step(f, a) == set_node(f, i, n2), + nrank(f.log, n2) < nrank(f.log, f.nodes[i]), + ensures + lowers(f, i, a), +{ + assert(step(f, a).nodes[i] == n2); +} + +proof fn prog_live(f: F, i: int) + requires + finv(f), + valid(f, i), + live(f.log, node_at(f, i)), + !converged(f.log, node_at(f, i)), + ensures + exists|a: Act| #[trigger] lowers(f, i, a), +{ + let l = f.log; + let n = node_at(f, i); + assert(node_ok(l, n)); + let len = l.ops.len(); + assert(n.w.delivered <= len); + if n.w.delivered < len { + let a = Act::Advance(i); + lemma_advance(l, n); + let n2 = advance_node(n); + assert(win(n2.w.delivered, l.first)) by { + assert(n.w.delivered <= umax()); + assert(n.w.delivered as u64 as nat == n.w.delivered); + assert(l.first <= l.ops.len() + 1); + } + assert(live(l, n2)); + assert(!converged(l, n2)); + lowers_from(f, i, a, n2); + } else { + assert(n.w.store_cursor < n.w.delivered); + let a = Act::Flush(i); + lemma_flush(l, n); + a_flush_lands_the_store_at_the_delivered_position(n.w); + let n2 = flush_node(l, n); + assert(live(l, n2)); + assert(converged(l, n2)); + lowers_from(f, i, a, n2); + } +} + +proof fn prog_restore(f: F, i: int) + requires + finv(f), + valid(f, i), + node_at(f, i).rst is Some, + ensures + exists|a: Act| #[trigger] lowers(f, i, a), +{ + let l = f.log; + let n = node_at(f, i); + let len = l.ops.len() as int; + assert(node_ok(l, n)); + assert(!live(l, n)); + assert(!converged(l, n)); + if folded(n) { + let a = Act::RestoreEnd(i); + lemma_end(l, n); + a_restore_commit_lands_the_store_at_the_artifacts_cursor(n.w); + let n2 = end_node(n); + let art = rst_of(n).art; + assert(enabled(f, a)); + assert(n2.w.delivered == art.cursor && n2.w.store_cursor == art.cursor); + assert(n2.rst is None && n2.anchored && n2.origin == art.origin); + assert(nrank(l, n) == (if n.origin != l.origin { 2 * len + 11 } else if win(art.cursor, l.first) { + 2 * len + 4 + } else { + 2 * len + 7 + })); + if n.origin == l.origin { + assert(ok_fold(n.fold, l.ops, art.cursor)); + if win(art.cursor, l.first) { + assert(live(l, n2)); + assert(nrank(l, n2) <= 2 * len); + } else { + assert(!live(l, n2)); + assert(nrank(l, n2) == 2 * len + 6); + } + } else { + assert(!live(l, n2)); + assert(nrank(l, n2) == 2 * len + 10); + } + lowers_from(f, i, a, n2); + } else { + let a = Act::FoldChunks(i); + lemma_chunks(l, n); + let n2 = chunks_node(n); + assert(folded(n2)); + assert(!live(l, n2) && !converged(l, n2)); + lowers_from(f, i, a, n2); + } +} + +proof fn prog_repair(f: F, i: int) + requires + finv(f), + valid(f, i), + !live(f.log, node_at(f, i)), + node_at(f, i).rst is None, + !(node_at(f, i).anchored && node_at(f, i).origin != f.log.origin), + ensures + (exists|a: Act| #[trigger] lowers(f, i, a)) || blocked_by_artifact(f, i) || blocked_by_foreign_fold(f, i), +{ + let l = f.log; + let n = node_at(f, i); + let len = l.ops.len() as int; + assert(node_ok(l, n)); + assert(!converged(l, n)); + assert(nrank(l, n) == 2 * len + 6 + (n.w.delivered as int - n.w.store_cursor as int)); + // Unanchored, or anchored on this stream and out of its window: the cursor is expired (or none). + assert(repairable(l, n)) by { + if n.anchored { + assert(!win(n.w.delivered, l.first)); + assert(!win(n.w.store_cursor, l.first)) by { + assert(n.w.store_cursor <= n.w.delivered); + } + } + } + if n.w.store_cursor < n.w.delivered { + let a = Act::Flush(i); + lemma_flush(l, n); + a_flush_lands_the_store_at_the_delivered_position(n.w); + let n2 = flush_node(l, n); + assert(!live(l, n2)); + assert(!(n2.anchored && n2.origin != l.origin)); + assert(nrank(l, n2) == 2 * len + 6); + lowers_from(f, i, a, n2); + } else { + assert(settled(n)); + if plan_of(lt_of(l, n)) is Relist { + let a = Act::Relist(i); + lemma_relist(l, n); + let n2 = relist_node(l, n); + assert(win(n2.w.delivered, l.first)) by { + assert(l.ops.len() < 0x8000_0000_0000_0000); + assert(l.first <= l.ops.len() + 1); + assert(l.ops.len() as u64 as nat == l.ops.len()); + assert(l.first as u64 as nat == l.first); + } + assert(converged(l, n2)); + assert(enabled(f, a)); + lowers_from(f, i, a, n2); + } else if admissible_art(f, n) && real(n.fold, l.ops) { + let pick = |k: nat| true; + let a = Act::RestoreBegin(i, false, pick); + assert(enabled(f, a)); + lemma_begin(l, f.ptr->Some_0, n, false, pick); + let n2 = begin_node(l, n, f.ptr->Some_0, false, pick); + assert(win(f.ptr->Some_0.cursor, l.first)) by { + assert(f.ptr->Some_0.cursor <= umax()); + assert(f.ptr->Some_0.cursor as u64 as nat == f.ptr->Some_0.cursor); + } + assert(folded(n2)); + assert(!live(l, n2) && !converged(l, n2)); + assert(nrank(l, n2) == 2 * len + 4); + lowers_from(f, i, a, n2); + } + } +} + +/// THEOREM (a blocked node unblocks): if some node is converged, a publish by it is admitted by the pointer guard, and afterwards +/// the pointer names an artifact that seeds every blocked node behind the head. The artifact an exporter publishes is its own +/// store at its own cursor; a converged node's cursor is the head. HYPOTHESIS: the pointer is not a dead incarnation's, ranked above +/// the head (FINDING F1 is exactly that state: `finding_f1_a_dead_pointer_ahead_of_the_head_refuses_every_publish`). +pub proof fn a_converged_node_unblocks_every_blocked_one(f: F, j: int, i: int) + requires + finv(f), + valid(f, j), + valid(f, i), + converged(f.log, node_at(f, j)), + blocked_by_artifact(f, i), + node_at(f, i).w.store_cursor < f.log.ops.len(), + // No dead incarnation's pointer sits above the head. + !(f.ptr is Some && f.ptr->Some_0.origin != f.log.origin && f.ptr->Some_0.cursor > f.log.ops.len()), + ensures + enabled(f, Act::Publish(j)), + finv(step(f, Act::Publish(j))), + admissible_art(step(f, Act::Publish(j)), node_at(f, i)), +{ + let l = f.log; + let nj = node_at(f, j); + let ni = node_at(f, i); + assert(node_ok(l, nj)); + assert(node_ok(l, ni)); + let len = l.ops.len(); + assert(len >= 1); + assert(nj.w.store_cursor == len); + assert(len <= umax()); + assert(len as u64 as nat == len); + // The guard: the pointer is absent, or an artifact of this stream (at most the head), or a dead one at most the head. + if f.ptr is Some { + let a = f.ptr->Some_0; + assert(a.cursor <= len); + assert(a.cursor <= umax()); + assert(a.cursor as u64 as nat == a.cursor); + } + assert(publish_allowed_spec(ptr_state(f.ptr), len as u64)); + case_publish(f, j); + let f2 = step(f, Act::Publish(j)); + let a2 = f2.ptr->Some_0; + assert(a2.origin == l.origin); + assert(a2.cursor == len); + assert(restore_ok(len, ni.w.store_cursor, l.first)) by { + assert(ni.w.store_cursor as u64 as nat == ni.w.store_cursor); + assert(l.first as u64 as nat == l.first); + assert(l.first <= len + 1); + } +} + +/// THEOREM (the fail-stop is exactly the aged-out case, and it is loud): a node blocked by the artifact whose cursor is outside +/// the window (every anchored one, and a cursor-less one on a bucket that has evicted) names a write, revision `first - 1`, that +/// was evicted after its cursor, and no artifact of this stream reaches it either: the write was lost before any fold held it. +/// The plan is a restore only where the listing is not the truth. +pub proof fn a_blocked_node_names_the_write_that_aged_out(f: F, i: int) + requires + finv(f), + valid(f, i), + blocked_by_artifact(f, i), + !win(node_at(f, i).w.store_cursor, f.log.first), + ensures + ({ + let n = node_at(f, i); + let r = (f.log.first - 1) as nat; + // The write `r` is evicted, and is past the node's cursor: + &&& r < f.log.first + &&& n.w.store_cursor < r + // no artifact of this stream holds it; + &&& !(f.ptr is Some && f.ptr->Some_0.origin == f.log.origin && f.ptr->Some_0.cursor >= r) + }), +{ + let l = f.log; + let n = node_at(f, i); + assert(node_ok(l, n)); + assert(l.first <= l.ops.len() + 1); + assert(n.w.store_cursor <= umax()); + assert(n.w.store_cursor as u64 as nat == n.w.store_cursor); + assert(l.first as u64 as nat == l.first); + if f.ptr is Some && f.ptr->Some_0.origin == l.origin { + let a = f.ptr->Some_0; + assert(a.cursor as u64 as nat == a.cursor); + assert(!restore_allowed_spec(a.cursor as u64, n.w.store_cursor as u64, l.first as u64)) by { + assert(!admissible_art(f, n)); + } + } +} + +/// FINDING F4 (a stale memo blocks a start the listing could serve): `seen_evicting` rides the cursor, and a node that sees its +/// cursor belong to another incarnation keeps it (`Detect`). On the recreated, un-evicted bucket the listing IS the truth, but the +/// memo distrusts it, so the plan is a restore; with no artifact of the new stream (a fleet that is all foreign has no node to +/// publish one) every such node is blocked for ever, though nothing was lost. +pub proof fn finding_f4_a_stale_eviction_memo_blocks_a_start_the_listing_could_serve(f: F, i: int) + requires + finv(f), + valid(f, i), + !f.log.evicts, + f.log.first == 1, + node_at(f, i).seen, + !cfg!(feature = "mut_no_eviction_memo"), + ensures + plan_of(lt_of(f.log, node_at(f, i))) is Restore, + forall|k: nat| (#[trigger] listed(f.log, k)) == truth(f.log.ops, f.log.ops.len(), k), +{ + let l = f.log; + assert(log_ok(l)); + assert forall|k: nat| (#[trigger] listed(l, k)) == truth(l.ops, l.ops.len(), k) by { + the_trusted_listing_is_the_truth(l, false, k); + } +} + +} // verus! diff --git a/src/kernels/mod.rs b/src/kernels/mod.rs index 12b291e..1e6e06a 100644 --- a/src/kernels/mod.rs +++ b/src/kernels/mod.rs @@ -12,3 +12,7 @@ pub mod protocol; // The invariant and progress proofs over `applied::step`: spec and proof code only, so a normal build has nothing to compile. #[cfg(verus_keep_ghost)] mod applied_proofs; +#[cfg(verus_keep_ghost)] +mod transport_proofs; +#[cfg(verus_keep_ghost)] +mod fleet_proofs; diff --git a/src/kernels/protocol.rs b/src/kernels/protocol.rs index dfad230..f0447a4 100644 --- a/src/kernels/protocol.rs +++ b/src/kernels/protocol.rs @@ -252,10 +252,7 @@ pub fn same_incarnation( last_sequence: u64, ) -> (r: bool) ensures - r == match cursor_origin { - Some(origin) => origin == stream_origin, - None => revision <= last_sequence, - }, + r == same_incarnation_spec(cursor_origin, revision, stream_origin, last_sequence), // A recorded origin decides alone: the position is never consulted, so a recreated stream refuses an old cursor // wherever it falls. cursor_origin is Some ==> (r <==> cursor_origin->Some_0 == stream_origin), @@ -266,6 +263,19 @@ pub fn same_incarnation( } } +/// [`same_incarnation`]'s table. +pub open spec fn same_incarnation_spec( + cursor_origin: Option, + revision: u64, + stream_origin: u64, + last_sequence: u64, +) -> bool { + match cursor_origin { + Some(origin) => origin == stream_origin, + None => revision <= last_sequence, + } +} + /// THE restore guard: may a fold whose cursor (`local_revision`) fell out of /// the log be replaced by an artifact exported at `artifact_revision`? /// @@ -286,7 +296,7 @@ pub fn same_incarnation( /// (`GuardRepair`). pub fn restore_allowed(artifact_revision: u64, local_revision: u64, first_sequence: u64) -> (r: bool) ensures - r == (artifact_revision > local_revision && resume_window_spec(artifact_revision, first_sequence)), + r == restore_allowed_spec(artifact_revision, local_revision, first_sequence), // Never backward, never stale: an admitted restore is strictly ahead of the fold and resumable from its cursor. r ==> artifact_revision > local_revision && first_sequence as int <= artifact_revision as int + 1, { @@ -298,6 +308,11 @@ pub fn restore_allowed(artifact_revision: u64, local_revision: u64, first_sequen && resume_window_ok(artifact_revision, first_sequence) } +/// [`restore_allowed`]: strictly ahead of the fold, and resumable from the artifact's cursor. +pub open spec fn restore_allowed_spec(artifact_revision: u64, local_revision: u64, first_sequence: u64) -> bool { + artifact_revision > local_revision && resume_window_spec(artifact_revision, first_sequence) +} + /// The "ahead" half of [`restore_allowed`], on its own: what the main loop /// re-checks against its own applied cursor (a mid-watch expiry delivered /// past the resume cursor the watch task checked against). diff --git a/src/kernels/transport_proofs.rs b/src/kernels/transport_proofs.rs new file mode 100644 index 0000000..e1ff3a6 --- /dev/null +++ b/src/kernels/transport_proofs.rs @@ -0,0 +1,347 @@ +//! The artifact transport protocol, proven for every interleaving of any number of exporters, pruners and fetchers, with no +//! bound on how many objects, actors or steps there are. `tests/model.rs` checks the same protocol in a bounded world (Stateright); +//! this is its unbounded twin. The decisions are the production kernels, not copies: [`pointer_publish_allowed`]'s spec +//! (`publish_allowed_spec`) decides every publish and [`payload_prunable`]'s spec (`prunable_spec`) decides every delete. +//! +//! # The world +//! +//! The object store holds immutable, content-addressed payload objects (`-`: [`Payload`]) and one +//! pointer object, swapped by compare-and-swap (`transport::swap_pointer`; [`TS::ver`] counts successful swaps, and a CAS only +//! succeeds against the version the publisher read). An exporter runs `Upload`, then reads the pointer and applies the guard +//! (`Observe`), then swaps (`Swap`); a refused guard ends its round, a lost CAS re-reads. A pruner reads the pointer once and +//! then deletes any number of objects against that (possibly stale) read. A fetcher reads the pointer and later gets the object. +//! Every actor's read can be arbitrarily stale: that is what the interleaving quantifies over. +//! +//! # Environment axioms +//! +//! * **O1** a payload path names its content for ever (content addressing; a hash collision is the only way to break it); +//! * **O2** the pointer object is written only by [`Act::Swap`] (nothing else deletes or rewrites it); +//! * **O3** a compare-and-swap succeeds exactly when the object is unchanged since the read (`ver`). + +use crate::kernels::protocol::*; +use vstd::prelude::*; + +verus! { + +/// A payload object's address: the cursor's rank and the digest of the manifest (which commits to the content). +pub struct Payload { + pub rank: u64, + pub digest: nat, +} + +/// One actor of the protocol, with what it has read so far. +pub enum Actor { + Idle, + /// An exporter whose payload is uploaded. + Uploaded { p: Payload }, + /// An exporter that read the pointer (`st`, at swap-version `ver`) and the guard admitted its candidate. + Observed { p: Payload, st: PointerState, ver: nat }, + /// A pruner that read the pointer's rank `pr` (and its target `keep`). + Pruning { pr: u64, keep: Payload }, + /// A fetcher that read the pointer's target `t`. + Fetching { t: Payload }, +} + +pub struct TS { + /// The pointer's target payload, once one is published. Its rank is the target's rank. + pub ptr: Option, + /// Successful swaps so far. + pub ver: nat, + /// The payload objects that exist. + pub objs: Set, + pub actors: Seq, +} + +pub open spec fn pstate(ptr: Option) -> PointerState { + match ptr { + None => PointerState::Absent, + Some(p) => PointerState::Present { rank: Some(p.rank) }, + } +} + +pub enum Act { + /// Actor `i` (idle) uploads payload `p`. + Upload(int, Payload), + /// Actor `i` reads the pointer and applies the publish guard. + Observe(int), + /// Actor `i` swaps the pointer by CAS; it succeeds only if the pointer is as read. + Swap(int), + /// Actor `i`'s CAS lost the race: it re-reads. + Reread(int), + /// Actor `i` (idle) starts a prune: reads the pointer. + PruneRead(int), + /// Pruner `i` deletes object `o` if the prune guard allows. + Delete(int, Payload), + /// Actor `i` (idle) starts a fetch: reads the pointer. + FetchRead(int), + /// Fetcher `i` gets its object (the answer is [`fetched`]). + FetchGet(int), +} + +pub open spec fn actor(s: TS, i: int) -> Actor { + s.actors[i] +} + +pub open spec fn valid(s: TS, i: int) -> bool { + 0 <= i < s.actors.len() +} + +pub open spec fn enabled(s: TS, a: Act) -> bool { + match a { + Act::Upload(i, p) => valid(s, i) && actor(s, i) is Idle, + Act::Observe(i) => valid(s, i) && actor(s, i) is Uploaded, + Act::Swap(i) => valid(s, i) && actor(s, i) is Observed && actor(s, i)->Observed_ver == s.ver, + Act::Reread(i) => valid(s, i) && actor(s, i) is Observed && actor(s, i)->Observed_ver != s.ver, + Act::PruneRead(i) => valid(s, i) && actor(s, i) is Idle && s.ptr is Some, + Act::Delete(i, o) => { + valid(s, i) && actor(s, i) is Pruning && s.objs.contains(o) + && prunable_spec(Some(o.rank), actor(s, i)->Pruning_pr, o == actor(s, i)->Pruning_keep, true) + }, + Act::FetchRead(i) => valid(s, i) && actor(s, i) is Idle && s.ptr is Some, + Act::FetchGet(i) => valid(s, i) && actor(s, i) is Fetching, + } +} + +pub open spec fn step(s: TS, a: Act) -> TS { + match a { + Act::Upload(i, p) => TS { objs: s.objs.insert(p), actors: s.actors.update(i, Actor::Uploaded { p }), ..s }, + Act::Observe(i) => { + let p = actor(s, i)->Uploaded_p; + let st = pstate(s.ptr); + if publish_allowed_spec(st, p.rank) { + TS { actors: s.actors.update(i, Actor::Observed { p, st, ver: s.ver }), ..s } + } else { + // Refused (`SupersededByNewer`): the round ends, nothing changes. + TS { actors: s.actors.update(i, Actor::Idle), ..s } + } + }, + Act::Swap(i) => { + let p = actor(s, i)->Observed_p; + TS { ptr: Some(p), ver: s.ver + 1, actors: s.actors.update(i, Actor::Idle), ..s } + }, + Act::Reread(i) => TS { actors: s.actors.update(i, Actor::Uploaded { p: actor(s, i)->Observed_p }), ..s }, + Act::PruneRead(i) => { + let t = s.ptr->Some_0; + TS { actors: s.actors.update(i, Actor::Pruning { pr: t.rank, keep: t }), ..s } + }, + Act::Delete(i, o) => TS { objs: s.objs.remove(o), ..s }, + Act::FetchRead(i) => TS { actors: s.actors.update(i, Actor::Fetching { t: s.ptr->Some_0 }), ..s }, + Act::FetchGet(i) => TS { actors: s.actors.update(i, Actor::Idle), ..s }, + } +} + +/// What a fetcher's get answers: the object its read named, or a detected miss. +pub open spec fn fetched(s: TS, t: Payload) -> Option { + if s.objs.contains(t) { Some(t) } else { None } +} + +/// An actor's reads are consistent with the store (whatever the interleaving). +pub open spec fn actor_ok(s: TS, a: Actor) -> bool { + match a { + Actor::Idle => true, + // An uploaded payload exists, or was pruned because the pointer is strictly past it. + Actor::Uploaded { p } => s.objs.contains(p) || (s.ptr is Some && p.rank < s.ptr->Some_0.rank), + Actor::Observed { p, st, ver } => { + &&& publish_allowed_spec(st, p.rank) + &&& ver <= s.ver + // Same as `Uploaded`, whatever the version: a lost CAS goes back to `Uploaded`. + &&& (s.objs.contains(p) || (s.ptr is Some && p.rank < s.ptr->Some_0.rank)) + // The read is current while the version is: so the guard's verdict still stands. + &&& (ver == s.ver ==> st == pstate(s.ptr)) + }, + Actor::Pruning { pr, keep } => s.ptr is Some && pr <= s.ptr->Some_0.rank, + Actor::Fetching { t } => s.objs.contains(t) || (s.ptr is Some && t.rank < s.ptr->Some_0.rank), + } +} + +/// THE invariant: the pointer's target exists, and every actor's reads are consistent. +pub open spec fn inv(s: TS) -> bool { + &&& s.ptr is Some ==> s.objs.contains(s.ptr->Some_0) + &&& forall|i: int| 0 <= i < s.actors.len() ==> actor_ok(s, #[trigger] s.actors[i]) +} + +/// THEOREM: the empty store with `n` idle actors satisfies the invariant, for any `n`. +pub proof fn a_fresh_store_satisfies_the_invariant(actors: Seq) + requires + forall|i: int| 0 <= i < actors.len() ==> #[trigger] actors[i] is Idle, + ensures + inv(TS { ptr: None, ver: 0, objs: Set::empty(), actors }), +{ +} + +/// THEOREM (the invariant is inductive over every interleaving): any actor's any step keeps it, so it holds in every reachable +/// state, however many exporters, pruners and fetchers run and however stale their reads are. +pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) + requires + inv(s), + enabled(s, a), + ensures + inv(step(s, a)), +{ + let s1 = step(s, a); + assert forall|j: int| 0 <= j < s1.actors.len() implies actor_ok(s1, #[trigger] s1.actors[j]) by { + assert(s1.actors.len() == s.actors.len()); + assert(actor_ok(s, s.actors[j])); + match a { + Act::Upload(i, p) => { + if j != i { + assert(s1.actors[j] == s.actors[j]); + } + }, + Act::Observe(i) => { + let pp = actor(s, i)->Uploaded_p; + if j != i { + assert(s1.actors[j] == s.actors[j]); + } else if publish_allowed_spec(pstate(s.ptr), pp.rank) { + assert(actor_ok(s, s.actors[i])); + // Admitted: the candidate is not below the pointer, so it was not pruned: it exists. + assert(s.objs.contains(pp)); + } + }, + Act::Swap(i) => { + if j != i { + assert(s1.actors[j] == s.actors[j]); + } + }, + Act::Reread(i) => { + let pp = actor(s, i)->Observed_p; + if j == i { + assert(actor_ok(s, s.actors[i])); + } else { + assert(s1.actors[j] == s.actors[j]); + } + }, + Act::PruneRead(i) => { + if j != i { + assert(s1.actors[j] == s.actors[j]); + } + }, + Act::Delete(i, o) => { + assert(s1.actors[j] == s.actors[j]); + let pr = actor(s, i)->Pruning_pr; + let t = s.ptr->Some_0; + assert(actor_ok(s, s.actors[i])); + // `o` is strictly below the pruner's read of the pointer, which is at most the pointer's rank now. + assert(o.rank < pr); + assert(pr <= t.rank); + }, + Act::FetchRead(i) => { + if j != i { + assert(s1.actors[j] == s.actors[j]); + } + }, + Act::FetchGet(i) => { + if j != i { + assert(s1.actors[j] == s.actors[j]); + } + }, + } + } + if s1.ptr is Some { + match a { + Act::Swap(i) => { + assert(actor_ok(s, s.actors[i])); + }, + Act::Delete(i, o) => { + let pr = actor(s, i)->Pruning_pr; + assert(actor_ok(s, s.actors[i])); + assert(o.rank < pr); + assert(o != s.ptr->Some_0); + }, + _ => {}, + } + } +} + + +/// THEOREM (the pointer never regresses, for every interleaving of N exporters): every step either leaves the pointer alone or +/// moves it to a payload whose rank is at least the old one, and a published pointer is never removed. This is +/// `a_publish_never_regresses_the_pointer` lifted from one decision to the whole protocol: the guard decided on a read, but the +/// swap succeeds only against that read (O3), so the read is the pointer being replaced. +pub proof fn the_pointer_never_regresses(s: TS, a: Act) + requires + inv(s), + enabled(s, a), + ensures + s.ptr is Some ==> step(s, a).ptr is Some && step(s, a).ptr->Some_0.rank >= s.ptr->Some_0.rank, + ({ let ps = pstate(s.ptr); let q = pstate(step(s, a).ptr); + (ps is Present && ps->Present_rank is Some) ==> q is Present && q->Present_rank is Some + && q->Present_rank->Some_0 >= ps->Present_rank->Some_0 }), +{ + match a { + Act::Swap(i) => { + assert(actor_ok(s, s.actors[i])); + let p = actor(s, i)->Observed_p; + if s.ptr is Some { + a_publish_never_regresses_the_pointer(pstate(s.ptr), p.rank); + } + }, + _ => {}, + } +} + +/// THEOREM (prune never deletes the pointer's target): at any moment, whatever a pruner read earlier, the object it is allowed to +/// delete is not the pointer's current target. The pruner's read of the pointer is stale, but the pointer's rank only grows, and +/// the guard deletes only strictly below the pruner's read (`the_target_and_unknown_objects_are_never_pruned` is the guard's own +/// half). +pub proof fn prune_never_deletes_the_pointers_target(s: TS, i: int, o: Payload) + requires + inv(s), + enabled(s, Act::Delete(i, o)), + ensures + s.ptr is Some, + s.ptr->Some_0 != o, + inv(step(s, Act::Delete(i, o))), + step(s, Act::Delete(i, o)).objs.contains(step(s, Act::Delete(i, o)).ptr->Some_0), +{ + assert(actor_ok(s, s.actors[i])); + every_step_preserves_the_invariant(s, Act::Delete(i, o)); +} + +/// THEOREM (a fetch races a prune: the object it named, or a detected miss, never another payload): a get answers the payload +/// its read named (a path names its content, O1) or a miss; and a miss means the pointer has strictly moved on since the read, so +/// a re-read names a payload that exists and, by `prune_never_deletes_the_pointers_target`, stays until the pointer moves again. +/// (A fetch that does not race a prune never misses: the target exists.) +pub proof fn a_fetch_gets_its_payload_or_a_detected_miss(s: TS, i: int) + requires + inv(s), + enabled(s, Act::FetchGet(i)), + ensures + ({ + let t = actor(s, i)->Fetching_t; + match fetched(s, t) { + Some(x) => x == t, + None => s.ptr is Some && t.rank < s.ptr->Some_0.rank && s.objs.contains(s.ptr->Some_0), + } + }), +{ + assert(actor_ok(s, s.actors[i])); +} + +/// THEOREM (liveness: a refused fetch retries): after a miss, a fresh read names the pointer's current target, which exists, so +/// the get answers it. The only way to miss again is for the pointer to move again, strictly upward. Rank: the pointer's rank +/// (monotone), unbounded, but each miss is paid for by one publish, so a fetch retries at most once per publish. Fairness +/// assumption: the publishers do not publish for ever between a read and its get (the environment, not this code). +pub proof fn a_fresh_read_never_misses_without_a_publish(s: TS, i: int) + requires + inv(s), + s.ptr is Some, + ensures + s.objs.contains(s.ptr->Some_0), +{ +} + +/// THEOREM (a publisher's refusal clears): an exporter refused by the guard (the pointer strictly newer) is refused for as long as +/// the pointer stays newer, and the pointer never regresses, so its exit is a fresher export (`a_publish_at_or_above_the_pointer_is_admitted`). +/// A lost CAS is never final: the exporter re-reads, and the version it lost to is a publish that raised the pointer. +pub proof fn a_lost_cas_means_a_publish_happened(s: TS, i: int) + requires + inv(s), + enabled(s, Act::Reread(i)), + ensures + actor(s, i)->Observed_ver < s.ver, +{ + assert(actor_ok(s, s.actors[i])); +} + +} // verus! diff --git a/tests/model_fleet.rs b/tests/model_fleet.rs index 120c889..a84c44d 100644 --- a/tests/model_fleet.rs +++ b/tests/model_fleet.rs @@ -31,6 +31,25 @@ //! Mutations the checker must catch: the key-listing repair on an evicting //! bucket, and a cursor-less start that re-lists an already-evicted bucket — //! each poisons the fleet's artifacts. +//! +//! **This check is bounded; it has an unbounded twin.** `src/kernels/fleet_proofs.rs` +//! proves the same induction in Verus for any number of nodes, keys and writes, with +//! the log's retention eviction and stream recreation, crash/restart at every point +//! (even mid-restore), and the restore's own steps interleaved, over the same shared +//! kernels (`applied::step_spec` through `applied_proofs`, and the `protocol` specs). +//! What it adds, which this model cannot see: +//! +//! - on MANY keys the invariant is "complete together with the log after the cursor", +//! not "equals the truth at the cursor": a restore keeps a stale entry of a key the +//! bucket lists live (`restore_key`), and the resume delivers the later write +//! (`fleet_proofs::finding_f3_*`). With one key that entry is the truth, so the two +//! statements coincide here; +//! - a restore over a fold of a RECREATED stream keeps stale entries by revision +//! number (`finding_f2_*`), and a dead incarnation's pointer refuses every publish +//! of the new stream (`finding_f1_*`); this model has one incarnation; +//! - liveness as a ranking function under named fairness axioms (`nrank`). +//! +//! The proof's mutations are the same `mut_*` features: `mise run verify -- --features mut_x`. use slipstream::protocol::{ PointerState, RepairMode, RepairPlan, cursorless_start_needs_repair, listing_is_truth, From 1ec4fad671e5cf73b9773cc4908edd03ae6ae0b1 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 18:36:59 -0800 Subject: [PATCH 2/7] tests: F1, F2, F4 against a live nats-server (red before the fixes) --- tests/recreated_fleet.rs | 378 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 378 insertions(+) create mode 100644 tests/recreated_fleet.rs diff --git a/tests/recreated_fleet.rs b/tests/recreated_fleet.rs new file mode 100644 index 0000000..a168361 --- /dev/null +++ b/tests/recreated_fleet.rs @@ -0,0 +1,378 @@ +//! A bucket deleted and recreated under the same name, with artifacts in play: +//! the fleet findings F1, F2 and F4 of the Verus fleet proof, each reached +//! against a live nats-server and a real transport (local filesystem object +//! store). `tests/recreated_stream.rs` covers the key-listing repair; these +//! cover what an artifact adds. +//! +//! - **F1**: a dead incarnation's pointer, ranked above the new stream's head, +//! must not refuse the new stream's publishes. +//! - **F2**: a restore over a fold of the old stream must replace it with the +//! artifact's, key for key: the old stream's revision numbers decide nothing +//! in the new one, and the old cursor's rank is no bar to the artifact. +//! - **F4**: the eviction memo is a fact about the stream that was evicting; +//! a recreated stream that keeps its values is served by the exact listing. +#![cfg(feature = "transport")] + +mod common; + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use common::TestNats; +use slipstream::snapshot::SnapshotStore; +use slipstream::{ + AppendLogSnapshot, ArtifactRestore, ArtifactTransport, BatchConfig, Connection, DiscardPolicy, + ExpiryRepair, ExportRequest, KvStore, KvUpdate, NatsConnection, NatsConnectionConfig, + ObjectStoreTransport, PublishOutcome, StoreConfig, WatchCursor, WatchScope, watch_applied, +}; +use tempfile::TempDir; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::time::timeout; + +const BUCKET: &str = "routes"; +const KEY: &str = "routes"; + +fn plain() -> StoreConfig { + StoreConfig { + name: BUCKET.into(), + max_bytes: Some(8 * 1024 * 1024), + ..Default::default() + } +} + +/// `discard: old` under a small `max_bytes`: filler writes evict current values. +fn evicting() -> StoreConfig { + StoreConfig { + name: BUCKET.into(), + max_bytes: Some(4096), + discard: DiscardPolicy::Old, + ..Default::default() + } +} + +async fn open_bucket(nats: &TestNats, config: StoreConfig) -> (NatsConnection, Arc) { + let conn = NatsConnection::new(NatsConnectionConfig { + url: nats.url.clone(), + creds: None, + creds_file: None, + }); + conn.connect().await.expect("connect"); + let store = conn.store_with_config(config).await.expect("open bucket"); + (conn, store) +} + +/// Delete the bucket and create it again under the same name. +async fn recreate(nats: &TestNats, config: StoreConfig) -> (NatsConnection, Arc) { + let client = async_nats::connect(&nats.url).await.expect("connect"); + async_nats::jetstream::new(client) + .delete_key_value(BUCKET) + .await + .expect("delete the bucket"); + open_bucket(nats, config).await +} + +async fn put(bucket: &Arc, key: &str, value: &str) -> u64 { + bucket + .writer() + .expect("writer") + .put(key, value.as_bytes()) + .await + .expect("put") + .as_u64() + .expect("revision") +} + +struct Node { + applied: Arc, + exports: mpsc::Sender, + shutdown: watch::Sender, + task: tokio::task::JoinHandle>, +} + +fn spawn_node( + bucket: &Arc, + fold: AppendLogSnapshot, + resume: Option, + repair: ExpiryRepair, +) -> Node { + let (ex_tx, ex_rx) = mpsc::channel(1); + let (sd_tx, sd_rx) = watch::channel(false); + let applied = Arc::new(AtomicU64::new(0)); + let applied_w = Arc::clone(&applied); + let task = tokio::spawn(watch_applied( + bucket.watcher().expect("watcher"), + WatchScope::All, + resume, + repair, + Some(fold), + Some(ex_rx), + BatchConfig::default(), + |_: &KvUpdate| Some(()), + |_: Vec<()>| {}, + move |cur: WatchCursor| applied_w.store(cur.as_u64().unwrap_or(0), Ordering::SeqCst), + sd_rx, + )); + Node { + applied, + exports: ex_tx, + shutdown: sd_tx, + task, + } +} + +async fn wait_applied(node: &Node, at_least: u64) { + let outcome = timeout(Duration::from_secs(15), async { + while node.applied.load(Ordering::SeqCst) < at_least { + if node.task.is_finished() { + return false; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + true + }) + .await; + assert!( + outcome == Ok(true), + "the fold never applied revision {at_least} (at {}); the watch {}", + node.applied.load(Ordering::SeqCst), + if node.task.is_finished() { + "ended" + } else { + "ran on" + } + ); +} + +async fn stop(node: Node) -> Result { + node.shutdown.send(true).unwrap(); + node.task.await.unwrap() +} + +/// Export a live node's fold to `dest`. +async fn export(node: &Node, dest: &Path) { + let (reply_tx, reply_rx) = oneshot::channel(); + node.exports + .send(ExportRequest { + dest_dir: dest.to_path_buf(), + reply: reply_tx, + }) + .await + .expect("export request"); + reply_rx.await.expect("reply").expect("export"); +} + +struct Fleet { + nats: TestNats, + dir: TempDir, + transport: Arc, +} + +impl Fleet { + async fn new() -> Fleet { + let nats = TestNats::start().await; + let dir = TempDir::new().unwrap(); + std::fs::create_dir(dir.path().join("objects")).unwrap(); + let store = + object_store::local::LocalFileSystem::new_with_prefix(dir.path().join("objects")) + .expect("local object store"); + let transport: Arc = Arc::new( + ObjectStoreTransport::new(Arc::new(store), "artifacts") + .with_non_atomic_pointer_fallback(), + ); + Fleet { + nats, + dir, + transport, + } + } + + fn path(&self, name: &str) -> PathBuf { + self.dir.path().join(name) + } + + fn open(&self, name: &str) -> (WatchCursor, AppendLogSnapshot) { + AppendLogSnapshot::open(&self.path(name), u64::MAX).expect("open fold") + } + + fn auto(&self, bucket: &Arc) -> ExpiryRepair { + ExpiryRepair::Auto { + reader: bucket.reader(), + restore: self.restore(), + } + } + + fn restore_only(&self, bucket: &Arc) -> ExpiryRepair { + ExpiryRepair::Restore { + reader: bucket.reader(), + restore: self.restore(), + } + } + + fn restore(&self) -> Arc> { + Arc::new(ArtifactRestore::new( + Arc::clone(&self.transport), + KEY, + self.dir.path(), + |artifact: &Path, dest: &Path| AppendLogSnapshot::import(artifact, dest, u64::MAX), + )) + } + + /// Export a live node and publish the artifact. + async fn publish(&self, node: &Node, name: &str) -> PublishOutcome { + let dest = self.path(name); + export(node, &dest).await; + self.transport.upload(KEY, &dest).await.expect("upload") + } +} + +/// The fold's keys and values, and the bucket's: the same set. +async fn assert_fold_is_bucket(fold_path: &Path, bucket: &Arc) { + let (_, fold) = AppendLogSnapshot::open(fold_path, u64::MAX).expect("reopen the fold"); + let mut got: Vec<(String, Vec)> = fold + .range("") + .expect("range") + .into_iter() + .map(|e| (e.key, e.value)) + .collect(); + got.sort(); + let mut want: Vec<(String, Vec)> = bucket + .reader() + .scan("") + .await + .expect("scan") + .into_iter() + .map(|e| (e.key, e.value)) + .collect(); + want.sort(); + assert_eq!(got, want, "the fold is exactly the stream that exists now"); +} + +/// F1. The old stream's fleet published an artifact at cursor 20. The bucket +/// is recreated; its head is 5. The new stream's first export must replace the +/// dead incarnation's pointer, or no node of the new stream ever publishes +/// again (and `same_incarnation` refuses to restore from the dead one). +#[tokio::test(flavor = "multi_thread")] +async fn a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish() { + let fleet = Fleet::new().await; + let (_c, old) = open_bucket(&fleet.nats, plain()).await; + let a = spawn_node(&old, fleet.open("a").1, None, ExpiryRepair::None); + for i in 0..20 { + put(&old, &format!("old.{i}"), "o").await; + } + wait_applied(&a, 20).await; + assert_eq!(fleet.publish(&a, "art-a").await, PublishOutcome::Published); + stop(a).await.expect("clean stop"); + assert_eq!(fleet.transport.manifest(KEY).await.unwrap().cursor.as_u64(), Some(20)); + + let (_c, new) = recreate(&fleet.nats, plain()).await; + let mut head = 0; + for i in 0..5 { + head = put(&new, &format!("new.{i}"), "n").await; + } + let b = spawn_node(&new, fleet.open("b").1, None, ExpiryRepair::None); + wait_applied(&b, head).await; + assert_eq!( + fleet.publish(&b, "art-b").await, + PublishOutcome::Published, + "the new stream's artifact replaces the dead incarnation's" + ); + assert_eq!( + fleet.transport.manifest(KEY).await.unwrap().cursor.as_u64(), + Some(head) + ); + stop(b).await.expect("clean stop"); +} + +/// F2. A fold of the old stream, repaired by a restore from an artifact of the +/// new one. The old fold holds `k` at revision 18 ("old"); the new stream wrote +/// `k` at revision 1 ("new"). By revision number the old entry looks newer. +/// `new_head` below the old cursor (20) also checks the old cursor's rank is no +/// bar to the artifact. +async fn restore_over_a_foreign_fold(new_head: u64) { + let fleet = Fleet::new().await; + let (_c, old) = open_bucket(&fleet.nats, plain()).await; + let a = spawn_node(&old, fleet.open("a").1, None, ExpiryRepair::None); + for i in 0..17 { + put(&old, &format!("o.{i}"), "o").await; + } + assert_eq!(put(&old, "k", "old").await, 18); + put(&old, "o.17", "o").await; + put(&old, "o.18", "o").await; + wait_applied(&a, 20).await; + stop(a).await.expect("clean stop"); + let (cursor, _) = fleet.open("a"); + assert_eq!(cursor.as_u64(), Some(20)); + + let (_c, new) = recreate(&fleet.nats, plain()).await; + put(&new, "k", "new").await; + let mut head = 1; + for i in 1..new_head { + head = put(&new, &format!("n.{i}"), "n").await; + } + let exporter = spawn_node(&new, fleet.open("x").1, None, ExpiryRepair::None); + wait_applied(&exporter, head).await; + assert_eq!(fleet.publish(&exporter, "art").await, PublishOutcome::Published); + stop(exporter).await.expect("clean stop"); + + let (cursor, fold) = fleet.open("a"); + let node = spawn_node(&new, fold, Some(cursor), fleet.restore_only(&new)); + wait_applied(&node, head).await; + stop(node).await.expect("clean stop"); + assert_fold_is_bucket(&fleet.path("a"), &new).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_restore_over_a_foreign_fold_replaces_entries_the_old_stream_numbered_higher() { + restore_over_a_foreign_fold(25).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_restore_over_a_foreign_fold_is_not_barred_by_the_old_cursors_rank() { + restore_over_a_foreign_fold(5).await; +} + +/// F4. The fold saw its bucket evict current values (the memo rides its +/// cursor). The bucket is recreated without eviction: the exact listing serves +/// the repair, with no artifact anywhere. The memo is the old stream's. +#[tokio::test(flavor = "multi_thread")] +async fn the_old_streams_eviction_memo_does_not_distrust_the_new_streams_listing() { + let fleet = Fleet::new().await; + let (_c, old) = open_bucket(&fleet.nats, evicting()).await; + put(&old, "route.keep", "v1").await; + let node = spawn_node(&old, fleet.open("n").1, None, fleet.auto(&old)); + let mut last = 0; + for i in 0..200 { + last = put(&old, &format!("filler.{i}"), &"x".repeat(64)).await; + } + wait_applied(&node, last).await; + stop(node).await.expect("clean stop"); + // A restart on the evicting bucket reads retention and commits the memo. + let (c, fold) = fleet.open("n"); + let node = spawn_node(&old, fold, Some(c), fleet.auto(&old)); + let marker = put(&old, "route.marker", "m").await; + wait_applied(&node, marker).await; + stop(node).await.expect("clean stop"); + let (c, _) = fleet.open("n"); + assert!( + format!("{c:?}").contains("seen evicting"), + "the fold remembers the eviction: {c:?}" + ); + + let (_c, new) = recreate(&fleet.nats, plain()).await; + let mut head = 0; + for i in 0..30 { + head = put(&new, &format!("new.{i}"), "n").await; + } + let (c, fold) = fleet.open("n"); + let node = spawn_node(&new, fold, Some(c), fleet.auto(&new)); + wait_applied(&node, head).await; + stop(node).await.expect("clean stop"); + assert_fold_is_bucket(&fleet.path("n"), &new).await; + let (c, _) = fleet.open("n"); + assert!( + !format!("{c:?}").contains("seen evicting"), + "the new stream never evicted: {c:?}" + ); +} From c097773e8c4f2bc7a72eb47e6397d353251e080f Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 18:54:39 -0800 Subject: [PATCH 3/7] Fleet findings F1, F2, F4 fixed; F3 stated exactly; the proofs lose the premises that excluded them (0.10.4) F1: the pointer guard orders by (incarnation, rank); payload names carry the incarnation so prune stays sound. F2: a foreign cursor is forgotten and the restore of a fold of another incarnation is the artifact, key for key. F4: forgetting the foreign cursor forgets its eviction memo. F3: ARCHITECTURE, model_fleet and the theorem names state 'complete', not 'equals the truth at its cursor'. Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 119 ++++++------ Cargo.lock | 2 +- Cargo.toml | 8 +- src/applied.rs | 11 ++ src/kernels/fleet_proofs.rs | 314 +++++++++++++++++++------------- src/kernels/mod.rs | 4 +- src/kernels/protocol.rs | 296 +++++++++++++++++++++--------- src/kernels/transport_proofs.rs | 65 ++++--- src/kv.rs | 10 + src/repair.rs | 86 ++++++--- src/transport.rs | 58 ++++-- tests/model.rs | 19 +- tests/model_fleet.rs | 33 +++- tests/model_repair.rs | 9 +- tests/recreated_fleet.rs | 10 +- 15 files changed, 686 insertions(+), 358 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index e99d59d..99db05e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -56,8 +56,8 @@ CAS tombstone (empty-value Put) is how `delete_with_version` works — it writes ObjectStore (/.manifest.json) ↓ download pointer ExportManifest (cursor, backend, file hashes) - ↓ derive payload key from blake3(manifest)[..8] -ObjectStore (/.payloads/.tar) + ↓ derive payload key from the cursor and blake3(manifest)[..8] +ObjectStore (/.payloads/--.tar) ↓ stream to temp dir (verified: embedded manifest == pointer bytes, every file hash re-checked) Staged artifact dir ↓ rename into place (atomic; bad artifact never becomes the fold) @@ -81,9 +81,9 @@ ExportManifest (cursor, backend, file BLAKE3 hashes) ↓ ObjectStoreTransport::upload(key, artifact_dir) ├─ tar data/ → multipart upload (8 MiB chunks, 8 concurrent) - │ key = /.payloads/.tar + │ key = /.payloads/--.tar └─ swap_pointer() → conditional put at /.manifest.json - ├─ pointer_publish_allowed(current, candidate_rank)? + ├─ pointer_publish_allowed(current, candidate Pos)? (incarnation, then rank) │ true → CAS put (max 8 retries on concurrent swap) │ false → SupersededByNewer (slow exporter gives up cleanly) └─ PublishOutcome::Published | SupersededByNewer @@ -91,7 +91,7 @@ ObjectStoreTransport::upload(key, artifact_dir) LeaseGuard::complete(cursor) ↓ ObjectStoreTransport::prune(key, grace=4×ttl) - └─ delete payloads: payload_prunable(payload_rank, pointer_rank, is_target, aged_out)? + └─ delete payloads: payload_prunable(payload Pos, pointer Pos, is_target, aged_out)? ↓ delete local artifact dir (transience enforced — not hoped for) ``` @@ -147,7 +147,7 @@ Every non-`_from` watch is a **state-sync** stream (NATS `DeliverPolicy::LastPer | `ArtifactTransport` | Trait: `upload(key, dir) → ManifestAndOutcome`, `download(key) → ManifestAndDir`, `pointer(key)`, `prune(key, grace)` | Not an object store; adapts `ObjectStore` for the pointer-swap protocol | | `ObjectStoreTransport` | Concrete `ArtifactTransport` over any `object_store` backend (S3, GCS, Azure, local) | `file://` lacks CAS and FAILS CLOSED unless `with_non_atomic_pointer_fallback()` (dev only) | | `PublishOutcome` | `Published` (pointer advanced) or `SupersededByNewer` (refused — a newer pointer exists) | Not an error; a slow exporter's normal exit under concurrent rounds | -| `PointerState` | What `swap_pointer` observes before deciding: `Absent`, `Present { rank: Some(n) }`, or `Present { rank: None }` (corrupt) | Used only by `pointer_publish_allowed`; never stored independently | +| `PointerState` | What `swap_pointer` observes before deciding: `Absent`, `Present { at: Some(Pos) }`, or `Present { at: None }` (corrupt) | Used only by `pointer_publish_allowed`; never stored independently | ## Layer Architecture @@ -240,12 +240,12 @@ The one exception: an update carrying the **unknown** version (an unparseable AC **Resuming in-process (`watch_applied_owned`).** Closing on every exit makes a watch error fatal to a caller whose readers hold the store (a fold's `FjallReader` keeps its database alive). Such a caller can't re-open the path while those handles live, so its only recovery was a process restart, which a NATS heartbeat miss forced. `watch_applied_owned` is the same loop without the close. Its `WatchEnd` carries the result, the resume cursor, and the store itself, intact on every exit. With a store the resume cursor (`WatchEnd::applied`, and the `Ok` of `result` and of `watch_applied`) is the store's own persisted cursor, read after the last flush, never the in-memory one: a transient store failure leaves the in-memory cursor ahead of the store and drops the re-queued batch with the run, so resuming from the in-memory cursor skipped that batch for good (`in_process_resume_after_failed_final_flush_leaves_no_hole`; the `mut_resume_from_memory` kernel mutation in `tests/model_applied.rs`). Without a store it is the in-memory applied cursor. `on_applied` is a notification, not a resume source with a store. The caller resumes by calling again with the same store and `resume = applied`: nothing is re-applied out of order and nothing is skipped, and cursor expiry and its repair take the same path as a fresh start. A store that comes back `None` was lost (a flush task panicked), and only a fresh open recovers it. `watch_applied` is `watch_applied_owned` followed by `close_off_runtime` (`owned_watch_hands_the_store_back_and_resumes_in_process`). -**Foreign cursor.** A resume that fails with `KvError::ForeignCursor` (or a live All-scope watch the floor guard ends with it, below) is repaired as a fold that holds data but has no cursor — the unanchored start below — against the stream that exists now: the key-listing diff on a bucket that keeps current values, an artifact restore otherwise, whose artifact must itself be this stream's (`repair::check_restore`). With `ExpiryRepair::None` or no store the error stands: a re-list alone would leave the old stream's keys in the fold. Nothing of the new stream is folded under the old cursor. +**Foreign cursor.** A resume that fails with `KvError::ForeignCursor` (or a live All-scope watch the floor guard ends with it, below) is repaired as a fold that holds data but has no cursor — the unanchored start below — against the stream that exists now: the key-listing diff on a bucket that keeps current values, an artifact restore otherwise, whose artifact must itself be this stream's (`repair::check_restore`). The repair first forgets the old cursor with everything it carried (`Fold::forget_cursor`): its position (so an artifact below the old rank is no longer "not ahead"), its incarnation, and the eviction memo (a fact about the stream that was evicting: the new stream's retention is read afresh, so an exact listing serves a recreated bucket that keeps its values). A restore over that fold replaces it with the artifact's, key for key (`restore_key`'s `local_known`), because the old stream's revision numbers decide nothing in the new one (fleet findings F2, F4). With `ExpiryRepair::None` or no store the error stands: a re-list alone would leave the old stream's keys in the fold. Nothing of the new stream is folded under the old cursor. **Cursor-expiry repair.** The cursor expires at resume (`CursorExpired` from the `*_from` watch) or mid-watch (the live floor guard ends an All-scope watch with `CursorExpired` when retention overruns it). Both take one path. Correct means **every write minus every real delete** — not "whatever NATS still lists"; the two agree only when retention never evicts current values. The repair (`ExpiryRepair`, `src/repair.rs`) is chosen accordingly: - **Key-listing diff** (`Relist`; `Auto` on a bucket that keeps current values). The watch task hands the main loop the reader and waits for an ack; the main loop lists the bucket's live keys, sorting them externally (`KeySorter`: 64 MiB runs spilled to the restore source's scratch dir under `Auto`, else `TMPDIR`), merge-joins that against the fold's own key-ordered scan — so neither the listing nor the fold is held in memory, only the stale keys — and runs a synthetic `KvUpdate::Delete` (unknown version — never advances the cursor) through `parse`/`apply`/store for each key that vanished; only then does the full-scope re-list (`watch_all` / `watch_prefix` / `watch_prefixes`) start. That ack ordering is the invariant: a synthetic delete always precedes the re-list put for the same key, so delete-then-recreate during the gap converges. (With the listing taken by the main loop after its drain, `tests/model_repair.rs` shows axiom 6 alone already keeps it correct; the barrier is defense in depth.) **Refused** — the watch fails — when the watcher reports retention that evicts current values (`KvWatcher::retention`, read live from the stream config), or the fold remembers seeing it do so (below): there it deletes valid keys. `tests/eviction.rs` reproduced exactly that against a live server before the fix. -- **Artifact restore** (`Restore`; `Auto` on a bucket that evicts current values or can't say). The watch task peeks the newest artifact's manifest and checks it before downloading: it must cover the watch scope (recorded in the manifest by the exporting `watch_applied`), and pass `protocol::restore_allowed` — strictly ahead of the local fold, cursor still inside retention. It then downloads and imports it into scratch as a temporary fold of the consumer's backend, re-checks what actually arrived, and hands it to the main loop. The main loop re-checks "ahead" against its own applied cursor (a mid-watch expiry delivered past the resume cursor) and diffs the in-scope fold against the artifact in one key-ordered pass: keys the artifact's entry should replace are spilled to a scratch file next to the imported artifact (`RestoredFold::scratch_in`), and local keys the artifact lacks are collected as delete candidates. Only if there are candidates does it stream the bucket's live keys past them (`KvReader::for_each_key`) and then re-read retention: the listing vouches for writes after the artifact's cursor only while the log still holds all of them, so if retention passed that cursor meanwhile the restore is refused before anything is folded (`tests/model_repair.rs`, `NoListingRecheck`). It then folds the difference through `parse`/`apply`/store in `max`-sized chunks, read back from the spill, then advances the cursor to the artifact's in one final commit and replies. Memory is the delete candidates — the keys deleted between the two cursors — never the fold, the artifact, or the bucket's listing, so a billion-key fold (or a fresh node seeding from an artifact) restores in bounded memory. The diff takes an artifact entry only when it is newer than the local one, and deletes a key the artifact lacks only when the bucket does not list it live. An artifact is complete *together with the log after its cursor* — a NATS cursor C means every retained message ≤ C is applied, not "the truth at C": a key whose latest write is after C may be missing or older in an artifact exported mid catch-up — and in both skipped cases the key's latest write is after C, so the resume delivers it. The consumer therefore never sees a key move backward or a live key deleted, not even transiently. The watch resumes from that cursor (which can itself expire later and go round again, each time only for a strictly newer artifact). A failed check fails the watch and logs the reason at `error`: a stale artifact has no safe recovery. +- **Artifact restore** (`Restore`; `Auto` on a bucket that evicts current values or can't say). The watch task peeks the newest artifact's manifest and checks it before downloading: it must cover the watch scope (recorded in the manifest by the exporting `watch_applied`), and pass `protocol::restore_allowed` — strictly ahead of the local fold, cursor still inside retention. It then downloads and imports it into scratch as a temporary fold of the consumer's backend, re-checks what actually arrived, and hands it to the main loop. The main loop re-checks "ahead" against its own applied cursor (a mid-watch expiry delivered past the resume cursor) and diffs the in-scope fold against the artifact in one key-ordered pass: keys the artifact's entry should replace are spilled to a scratch file next to the imported artifact (`RestoredFold::scratch_in`), and local keys the artifact lacks are collected as delete candidates. Only if there are candidates does it stream the bucket's live keys past them (`KvReader::for_each_key`) and then re-read retention: the listing vouches for writes after the artifact's cursor only while the log still holds all of them, so if retention passed that cursor meanwhile the restore is refused before anything is folded (`tests/model_repair.rs`, `NoListingRecheck`). It then folds the difference through `parse`/`apply`/store in `max`-sized chunks, read back from the spill, then advances the cursor to the artifact's in one final commit and replies. Memory is the delete candidates — the keys deleted between the two cursors — never the fold, the artifact, or the bucket's listing, so a billion-key fold (or a fresh node seeding from an artifact) restores in bounded memory. The diff takes an artifact entry only when it is newer than the local one, and deletes a key the artifact lacks only when the bucket does not list it live; over a fold of another incarnation (a foreign cursor: the repair forgets that cursor, its eviction memo and its rank first, so the ahead check is against nothing) it takes the artifact's entries and deletes every other key. An artifact is complete *together with the log after its cursor* — a NATS cursor C means every retained message ≤ C is applied, not "the truth at C": a key whose latest write is after C may be missing or older in an artifact exported mid catch-up — and in both skipped cases the key's latest write is after C, so the resume delivers it. The consumer therefore never sees a key move backward or a live key deleted, not even transiently. The watch resumes from that cursor (which can itself expire later and go round again, each time only for a strictly newer artifact). A failed check fails the watch and logs the reason at `error`: a stale artifact has no safe recovery. - **None** (`None`, or no store): the re-list alone, with a warning that deleted keys may persist. Whichever runs, the main loop first **drains** the watch channel: a mid-watch expiry leaves delivered updates buffered there, and the repair must fold them first — one applied after the repair would resurrect pre-repair state and could move the cursor backward. The watch task is parked on the ack/reply, so the drain takes exactly that backlog. @@ -353,30 +353,32 @@ Every decision the protocol's correctness rests on is a pure function in `src/ke | `listing_is_truth` | `repair` (plan, cursor-less start), `Snapshot::stale_keys` | every model's view of retention | | `plan_repair` | `repair::plan`, `Snapshot::stale_keys` | every model's expiry dispatch | | `cursorless_start_needs_repair` | `repair::run_watch` | `model_repair.rs`, `model_fleet.rs` | -| `restore_key` | `repair::restore_diff` | `model_repair.rs` | +| `restore_key` | `repair::restore_diff` | `model_repair.rs`, `fleet_proofs.rs` | -**The cursor-authority kernel** (`src/kernels/applied.rs`) is the one stateful kernel: `step(state, event) -> (state, actions)`, no I/O, async or clock. `applied::Fold` turns what it observes (a received update, a flush request, a store result, an export or repair request) into an `Event`, calls `step`, and runs the returned `Action`s through its interpreter; it decides nothing itself. The kernel owns what has no other home: whether a batch is open, whether a stream position is pending, the unsynced eviction memo, the store-failure streak, and where an in-flight flush or resync is. It decides which flush steps run and in which order (domain `apply` before the cursor moves), that a failed store fold re-queues its raw batch at the front (and the streak bound that fail-stops), that an export flushes first, that the resync's ack follows the folded deletes, and the artifact restore's order: ahead check, diff, listing with its window re-check (only when there are delete candidates), chunks folded under the old cursor, the cursor commit, then the reply; a refusal (not ahead, window aged) replies with an error before anything is folded. The restore's phase is kernel state, so an event out of phase is ignored and a restart (a fresh state) re-runs the whole repair. The data (updates, cursors, the store) stay in the shell. The three applied models call it too (`tests/model_applied.rs`, `tests/model_resync_order.rs`, `tests/model_repair.rs`, through `slipstream::cursor_kernel`): they keep only environment state (deliveries, store contents, crashes, the bucket) and feed `step` events. Their mutations are cargo features that break the kernel itself (`mut_drop_failed_batch`, `mut_resume_from_memory`, `mut_no_ack_barrier`, and for the repair steps `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_restore_guard`, `mut_no_listing_recheck`; the protocol-kernel ones `mut_relist_on_evicting`, `mut_unanchored_relist`, `mut_restore_ignores_versions`, `mut_restore_ignores_listing`, `mut_no_eviction_memo` break `protocol.rs`); each turns its model red, and they are for model tests only, never production builds. +**The cursor-authority kernel** (`src/kernels/applied.rs`) is the one stateful kernel: `step(state, event) -> (state, actions)`, no I/O, async or clock. `applied::Fold` turns what it observes (a received update, a flush request, a store result, an export or repair request) into an `Event`, calls `step`, and runs the returned `Action`s through its interpreter; it decides nothing itself. The kernel owns what has no other home: whether a batch is open, whether a stream position is pending, the unsynced eviction memo, the store-failure streak, and where an in-flight flush or resync is. It decides which flush steps run and in which order (domain `apply` before the cursor moves), that a failed store fold re-queues its raw batch at the front (and the streak bound that fail-stops), that an export flushes first, that the resync's ack follows the folded deletes, and the artifact restore's order: ahead check, diff, listing with its window re-check (only when there are delete candidates), chunks folded under the old cursor, the cursor commit, then the reply; a refusal (not ahead, window aged) replies with an error before anything is folded. The restore's phase is kernel state, so an event out of phase is ignored and a restart (a fresh state) re-runs the whole repair. The data (updates, cursors, the store) stay in the shell. The three applied models call it too (`tests/model_applied.rs`, `tests/model_resync_order.rs`, `tests/model_repair.rs`, through `slipstream::cursor_kernel`): they keep only environment state (deliveries, store contents, crashes, the bucket) and feed `step` events. Their mutations are cargo features that break the kernel itself (`mut_drop_failed_batch`, `mut_resume_from_memory`, `mut_no_ack_barrier`, and for the repair steps `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_restore_guard`, `mut_no_listing_recheck`; the protocol-kernel ones `mut_relist_on_evicting`, `mut_unanchored_relist`, `mut_restore_ignores_versions`, `mut_restore_ignores_listing`, `mut_restore_trusts_foreign`, `mut_pointer_ignores_incarnation`, `mut_no_eviction_memo` break `protocol.rs` (and `mut_foreign_keeps_memo` the repair's forgetting of a foreign cursor)); each turns its model red, and they are for model tests only, never production builds. -**`pointer_publish_allowed(current: &PointerState, candidate_rank: u64) → bool`** +**`pointer_publish_allowed(current: &PointerState, candidate: Pos) → bool`** -The monotonic pointer guard. Returns `true` for an open slot, a corrupt pointer, or a candidate at or above the existing cursor — and `false` exactly when the existing pointer is parseable and strictly newer. +The monotonic pointer guard. `Pos` is `(origin, rank)`: the stream incarnation a cursor was taken from (its creation time; 0 for a cursor that records none), then its revision, ordered incarnation first. Returns `true` for an open slot, a corrupt pointer, or a candidate at or above the existing cursor — and `false` exactly when the existing pointer is parseable and strictly newer. ``` -Absent → true (open slot) -Present { rank: None } → true (corrupt pointer is replaceable, not a wedge) -Present { rank: Some(n) } - candidate >= n → true - candidate < n → false (stale publish refused) +Absent → true (open slot) +Present { at: None } → true (corrupt pointer is replaceable, not a wedge) +Present { at: Some(p) } + candidate >= p → true ((origin, rank) order) + candidate < p → false (stale publish refused) ``` -Machine-checked as: _"published cursor never regresses."_ +A pointer of a dead incarnation is below every publish of the incarnation that replaced it, whatever its rank, so a recreated bucket's first export replaces it; the guard compared ranks only before, and a dead pointer ranked above the new head refused every publish of the new stream (fleet finding F1). The order across incarnations rests on O4: a recreated stream is created later than the one it replaces. -**`payload_prunable(payload_rank, pointer_rank, is_pointer_target, aged_out) → bool`** +Machine-checked as: _"published cursor never regresses"_ (`tests/model.rs`, one incarnation) and, over any number of incarnations, `transport_proofs::the_pointer_never_regresses` and `protocol::a_newer_incarnation_replaces_any_pointer` (Verus). -The prune guard. A payload is deletable only when all hold: it is not the pointer's target, its rank is parseable AND strictly below the pointer's, and its age has cleared the grace period. +**`payload_prunable(payload, pointer, is_pointer_target, aged_out) → bool`** + +The prune guard. A payload is deletable only when all hold: it is not the pointer's target, its position (`Pos`, parsed from the file name: `--.tar`, or `-.tar` for an unrecorded incarnation) is parseable AND strictly below the pointer's, and its age has cleared the grace period. ``` -!is_pointer_target && aged_out && payload_rank.is_some_and(|r| r < pointer_rank) +!is_pointer_target && aged_out && payload.is_some_and(|p| p < pointer) ``` Strictly-below (not `<=`) is the structural fix that makes dangling pointers impossible: `pointer_publish_allowed` refuses any candidate strictly below the pointer, and the pointer is monotone — so anything this guard deletes can never be successfully published afterward. The model checker found a dangling-pointer counterexample under an earlier age-only rule; this guard is the fix. @@ -423,9 +425,9 @@ Whether "not listed" means "deleted": yes when retention never evicts current va A start with no cursor repairs first when the fold holds data anyway (a re-list never removes what it doesn't deliver), or, with a restore armed, when the listing isn't the truth (a re-list would be incomplete). -**`restore_key(local, artifact, identical, listed_live) → KeyRestore`** +**`restore_key(local, artifact, identical, listed_live, local_known) → KeyRestore`** -The per-key restore decision: take the artifact's entry unless the local one is newer (never a move backward), and delete a key the artifact lacks unless the bucket lists it live (never a phantom delete). `tests/model_repair.rs` catches both pre-fix variants as kernel mutation features (`mut_restore_ignores_versions`, `mut_restore_ignores_listing`). +The per-key restore decision: take the artifact's entry unless the local one is newer (never a move backward), and delete a key the artifact lacks unless the bucket lists it live (never a phantom delete). Both hold for a fold of this stream (`local_known`). A fold whose cursor was another incarnation's (`KvError::ForeignCursor`, repaired as a cursor-less fold) is not: its revision numbers are the dead stream's, so the restore makes it the artifact's key for key (`mut_restore_trusts_foreign` is the pre-fix decision). `tests/model_repair.rs` catches both pre-fix variants as kernel mutation features (`mut_restore_ignores_versions`, `mut_restore_ignores_listing`). ### What is proven (Verus, `mise run verify`) @@ -484,36 +486,39 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut | Theorem | Where | Says | | --- | --- | --- | -| `a_fresh_fleet_satisfies_the_invariant` | `fleet_proofs.rs:1218` | base case: any number of fresh nodes over an empty log | -| `every_fleet_action_preserves_the_invariant` | `fleet_proofs.rs:1241` | `finv` is inductive over every action of every node: deliver, flush, crash at any point (even mid-restore), floor guard on a foreign cursor, key-listing repair, restore (begin, chunks, commit), publish; and write, delete, head eviction, stream recreation | -| `every_live_nodes_fold_is_the_truth_at_its_cursor` | `fleet_proofs.rs:1440` | a node of the current incarnation holds only real writes, and the truth at its cursor on every key not written since | -| `every_published_artifact_is_the_truth_at_its_cursor` | `fleet_proofs.rs:1455` | the same of the pointer's artifact | -| `a_converged_fold_is_the_truth` / `an_artifact_at_the_head_is_the_truth` | `fleet_proofs.rs:1470`, `:1483` | at the head every key is "not written since": exactly the truth | -| `a_restore_leaves_the_fold_complete_at_both_cursors` | `fleet_proofs.rs:874` | `restore_key` over every key leaves a fold complete at the old cursor (a restore cut short is safe) and at the artifact's | -| `a_restore_never_moves_a_key_backward_or_deletes_a_live_one` | `fleet_proofs.rs:934` | the kernel's per-key guarantees over the whole key space | -| `the_trusted_listing_is_the_truth` | `fleet_proofs.rs:261` | a listing the planner trusts is the truth | -| `folding_the_log_forward_keeps_a_fold_ok` | `fleet_proofs.rs:326` | delivery from `a` to `b` keeps a complete fold complete | -| `a_node_is_converged_or_a_fair_step_lowers_its_rank_or_it_is_blocked` | `fleet_proofs.rs:1679` | liveness: a ranking function (`nrank`) every fair step lowers; a node is converged or blocked | -| `a_converged_node_unblocks_every_blocked_one` | `fleet_proofs.rs:1879` | liveness: a converged node's publish is admitted and gives every blocked node an artifact | -| `a_blocked_node_names_the_write_that_aged_out` | `fleet_proofs.rs:1928` | the one fail-stop is loud and exact: revision `first - 1` was evicted after the node's cursor and no artifact of this stream holds it | -| `every_step_preserves_the_invariant` | `transport_proofs.rs:174` | transport invariant over every interleaving of N exporters, pruners and fetchers with stale reads | -| `the_pointer_never_regresses` | `transport_proofs.rs:261` | the monotone-pointer theorem lifted to the whole protocol | -| `prune_never_deletes_the_pointers_target` | `transport_proofs.rs:287` | whatever a pruner read, what it may delete is not the pointer's current target | -| `a_fetch_gets_its_payload_or_a_detected_miss` | `transport_proofs.rs:305` | a fetch racing a prune gets the object its read named or a miss, never another payload; a miss means the pointer moved strictly past it | -| `a_fresh_read_never_misses_without_a_publish`, `a_lost_cas_means_a_publish_happened` | `transport_proofs.rs:325`, `:337` | liveness: a refused fetch retries; a lost CAS is paid for by a publish | - -**The statement.** `finv`: every node of the current incarnation holds a real fold (every entry a write of the log) that is *complete* at its cursor `c`: equal to the truth at `c` on every key not written after `c`; every published artifact of the current incarnation likewise. Exact equality at `c` is not what the code keeps and is not an invariant (F3): an artifact at `C` is complete together with the log after `C`, and a restore keeps the stale entry of a key the bucket lists live (`restore_key`) because the resume delivers its later write. At the head every key is "not written since", so a converged node holds exactly the truth. The Stateright model (one key, atomic repair) cannot show the difference. - -**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. - -**Findings the proofs surfaced** (each a Verus-checked concrete state of the shipped decisions, in `fleet_proofs.rs`): - -- **F1** (`finding_f1_*`) the pointer guard compares ranks only, never the incarnation. A pointer whose artifact is the old stream's, ranked above the new head, refuses every publish of the new stream until the head passes it, while `same_incarnation` refuses to restore from it: a node that must restore has no artifact though other nodes hold the head. The unblock theorem assumes no such pointer. -- **F2** (`finding_f2_*`) a restore over the fold of a recreated stream keeps old entries that carry a higher revision number than the artifact's (`restore_key` decides by revision number). The fleet's restore step requires the local entries be real writes of the log; a foreign fold is `blocked_by_foreign_fold`. -- **F3** (`finding_f3_*`) the statement above. -- **F4** (`finding_f4_*`) the eviction memo (`seen_evicting`) rides the cursor and survives a recreation, so on the new, un-evicted bucket the exact listing is distrusted and a restore is planned; a fleet whose nodes are all foreign has no node to publish an artifact of the new stream. - -`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. +| `a_fresh_fleet_satisfies_the_invariant` | `fleet_proofs.rs:1279` | base case: any number of fresh nodes over an empty log | +| `every_fleet_action_preserves_the_invariant` | `fleet_proofs.rs:1302` | `finv` is inductive over every action of every node: deliver, flush, crash at any point (even mid-restore), floor guard on a foreign cursor, key-listing repair, restore (begin, chunks, commit), publish; and write, delete, head eviction, stream recreation | +| `every_live_nodes_fold_is_complete_at_its_cursor` | `fleet_proofs.rs:1502` | a node of the current incarnation holds only real writes, and the truth at its cursor on every key not written since ("complete", not exact: F3) | +| `every_published_artifact_is_complete_at_its_cursor` | `fleet_proofs.rs:1517` | the same of the pointer's artifact | +| `a_converged_fold_is_the_truth` / `an_artifact_at_the_head_is_the_truth` | `fleet_proofs.rs:1532`, `:1545` | at the head every key is "not written since": exactly the truth | +| `a_restore_leaves_the_fold_complete_at_both_cursors` | `fleet_proofs.rs:896` | `restore_key` over every key leaves a fold complete at the old cursor (a restore cut short is safe) and at the artifact's | +| `a_restore_over_a_foreign_fold_is_the_artifact` | `fleet_proofs.rs:976` | a restore over a fold of another incarnation (any content) is the artifact, key for key: no premise on the old fold (F2) | +| `a_restore_never_moves_a_key_backward_or_deletes_a_live_one` | `fleet_proofs.rs:956` | the kernel's per-key guarantees over the whole key space | +| `the_trusted_listing_is_the_truth` | `fleet_proofs.rs:270` | a listing the planner trusts is the truth | +| `folding_the_log_forward_keeps_a_fold_ok` | `fleet_proofs.rs:335` | delivery from `a` to `b` keeps a complete fold complete | +| `a_node_is_converged_or_a_fair_step_lowers_its_rank_or_it_is_blocked` | `fleet_proofs.rs:1758` | liveness: a ranking function (`nrank`) every fair step lowers; a node is converged or blocked | +| `a_converged_node_unblocks_every_blocked_one` | `fleet_proofs.rs:1958` | liveness: a converged node's publish is admitted over any pointer (a dead incarnation's included: no hypothesis) and gives every blocked node an artifact | +| `finding_f1_*`, `a_newer_incarnation_replaces_any_pointer` | `fleet_proofs.rs:1633`, `protocol.rs` | a dead incarnation's pointer, whatever its rank, never refuses a publish of the current one (F1) | +| `finding_f4_*` | `fleet_proofs.rs:1651` | a node that sees a foreign cursor forgets the eviction memo and plans the exact listing wherever the listing is exact (F4) | +| `a_blocked_node_names_the_write_that_aged_out` | `fleet_proofs.rs:2011` | the one fail-stop is loud and exact: revision `first - 1` was evicted after the node's cursor and no artifact of this stream holds it | +| `every_step_preserves_the_invariant` | `transport_proofs.rs:183` | transport invariant over every interleaving of N exporters, pruners and fetchers with stale reads | +| `the_pointer_never_regresses` | `transport_proofs.rs:270` | the monotone-pointer theorem lifted to the whole protocol | +| `prune_never_deletes_the_pointers_target` | `transport_proofs.rs:296` | whatever a pruner read, what it may delete is not the pointer's current target | +| `a_fetch_gets_its_payload_or_a_detected_miss` | `transport_proofs.rs:314` | a fetch racing a prune gets the object its read named or a miss, never another payload; a miss means the pointer moved strictly past it | +| `a_fresh_read_never_misses_without_a_publish`, `a_lost_cas_means_a_publish_happened` | `transport_proofs.rs:334`, `:346` | liveness: a refused fetch retries; a lost CAS is paid for by a publish | + +**The statement.** `finv`: every node of the current incarnation holds a real fold (every entry a write of the log) that is *complete* at its cursor `c`: equal to the truth at `c` on every key not written after `c`; every published artifact of the current incarnation likewise. Exact equality at `c` is not what the code keeps and is not an invariant (F3): an artifact at `C` is complete together with the log after `C`, and a restore keeps the stale entry of a key the bucket lists live (`restore_key`) because the resume delivers its later write. At the head every key is "not written since", so a converged node holds exactly the truth. The Stateright model (`tests/model_fleet.rs`: one key, atomic repair) states the stronger "equals the truth at its cursor" and passes only because of those bounds; the statement the code keeps is this one. + +**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: **O4** the stream incarnations of one bucket are ordered by creation time (a recreated stream is created later; `protocol::Pos`); the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle; a foreign cursor forgets it); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. + +**Findings the proofs surfaced** (each a Verus-checked concrete state of the shipped decisions, in `fleet_proofs.rs`; F1, F2 and F4 were real bugs, reached against a live nats-server in `tests/recreated_fleet.rs`, and are fixed; the proof no longer carries a premise that excluded them): + +- **F1** (`finding_f1_*`) the pointer guard compared ranks only, never the incarnation. A pointer whose artifact was the old stream's, ranked above the new head, refused every publish of the new stream until the head passed it, while `same_incarnation` refused to restore from it: a node that must restore had no artifact though other nodes held the head. Reachable: `swap_pointer` read only `cursor.rank()`, and the exporter's candidate was whatever its fold held. Fixed: the guard orders by `(incarnation, rank)` (`protocol::Pos`), so a dead incarnation's pointer is replaced by the new stream's first publish and never replaces it back; the payload name carries the incarnation so `prune` stays sound (`payload_prunable`). Test `a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish`. The liveness theorem lost its hypothesis. The order rests on O4 (a recreated stream is created later). +- **F2** (`finding_f2_*`) a restore over the fold of a recreated stream kept old entries that carried a higher revision number than the artifact's (`restore_key` decided by revision number), and refused an artifact below the old cursor's rank as "not ahead" (`restore_request` compared against the foreign cursor the fold still held). Reachable: `ForeignCursor` with a repair armed ran the restore over the old fold (`repair::run_watch`). Fixed: the repair forgets the foreign cursor (`Fold::forget_cursor`) and the restore of a fold of another incarnation takes the artifact key for key (`restore_key`'s `local_known`). Tests `a_restore_over_a_foreign_fold_replaces_entries_the_old_stream_numbered_higher`, `a_restore_over_a_foreign_fold_is_not_barred_by_the_old_cursors_rank`. Not covered, by design: a fold that holds data and NO cursor (a torn first checkpoint, or a store populated elsewhere) carries nothing that names its incarnation; it is taken to be this stream's, because treating it as foreign would let a restore move a key the consumer already saw backward (`tests/model_repair.rs`, "never backward"). +- **F3** (`finding_f3_*`) the statement above: complete, not exact. +- **F4** (`finding_f4_*`) the eviction memo (`seen_evicting`) rode the cursor and survived a recreation (the task's copy, and the fold's, which carried it over every cursor it advanced). On the new, un-evicted bucket the exact listing was distrusted and a restore planned; a fleet whose nodes are all foreign has no node to publish an artifact of the new stream, so none could start. Fixed with F2's `forget_cursor`: the memo goes with the cursor, and the new stream's retention is read afresh. Test `the_old_streams_eviction_memo_does_not_distrust_the_new_streams_listing`. + +`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_restore_trusts_foreign` fails `restore_key`'s contract, `a_restore_over_a_foreign_fold_is_the_artifact` and `finding_f2_*`; `mut_pointer_ignores_incarnation` fails `pointer_publish_allowed`'s contract and `finding_f1_*`; `mut_foreign_keeps_memo` fails `finding_f4_*` (and the live test); `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. ### Export Round State Machine @@ -698,7 +703,7 @@ When the watched bucket is a **bounded** log (size-capped, history evicted), a f **Transport** (feature `transport`): `ObjectStoreTransport` adapts any `object_store` backend (S3, GCS, Azure, local). Object layout: ``` -/.payloads/.tar ← content-addressed payload (write-once) +/.payloads/--.tar ← content-addressed payload (write-once; a cursor with no recorded incarnation omits the origin) /.manifest.json ← monotonic pointer (published last) ``` @@ -802,9 +807,9 @@ Per-message TTLs need a new-enough NATS server, a bucket flag, and a backend tha The legacy layout wrote the payload at `.payload.tar` and the manifest at `.manifest.json` as independent last-write-wins objects. The model checker proved two failure modes under that layout: (1) a cursor regression when a slow exporter's stale manifest overwrites a faster one's, and (2) a dangling pointer when the manifest advances past a payload that an older concurrent publisher still holds. The shipped layout fixes both structurally: -- **Content-addressed payload** — the key is `blake3(manifest)[..8].tar`. Two different artifacts can never share a key. Re-uploading the same artifact is an idempotent overwrite. A slow exporter's payload is valid until pruned; it just can't become the pointer. -- **Monotonic pointer via CAS** — `pointer_publish_allowed` refuses any candidate strictly below the current pointer. Combined with CAS (no torn reads between observe and write), the pointer is monotone non-decreasing. Slow exporters always get `SupersededByNewer`, never succeed at regression. -- **Strictly-below prune rule** — `payload_prunable` only deletes ranks strictly below the pointer. Because the pointer is monotone and `pointer_publish_allowed` refuses `< pointer`, a pruned payload can never become reachable again. The model checker found the dangling counterexample under an earlier age-only rule; this is the structural fix. +- **Content-addressed payload** — the key is `--blake3(manifest)[..8].tar` (the cursor's incarnation and revision in the name let `prune` order a payload against the pointer; the digest is the content address). Two different artifacts can never share a key. Re-uploading the same artifact is an idempotent overwrite. A slow exporter's payload is valid until pruned; it just can't become the pointer. +- **Monotonic pointer via CAS** — `pointer_publish_allowed` refuses any candidate strictly below the current pointer in (incarnation, rank) order: a pointer of a bucket's dead incarnation, whatever its rank, is replaced by the recreated stream's first publish (it used to refuse every publish of the new stream until its head passed the old rank), and never replaces it back. Incarnations are ordered by stream creation time (axiom O4: a recreated stream is created later; a clock that steps back across a recreation leaves the old pointer standing, loudly, never a regression). Combined with CAS (no torn reads between observe and write), the pointer is monotone non-decreasing. Slow exporters always get `SupersededByNewer`, never succeed at regression. +- **Strictly-below prune rule** — `payload_prunable` only deletes positions strictly below the pointer. Because the pointer is monotone and `pointer_publish_allowed` refuses `< pointer`, a pruned payload can never become reachable again. The model checker found the dangling counterexample under an earlier age-only rule; this is the structural fix. Machine-checked as three theorems in `tests/model.rs`: published cursor never regresses, pointer target always fetchable (zero-grace prune), bootstrap never silently diverges. diff --git a/Cargo.lock b/Cargo.lock index 3dcbe33..812cc3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -143,7 +143,7 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "beyond-slipstream" -version = "0.10.3" +version = "0.10.4" dependencies = [ "aho-corasick", "async-nats", diff --git a/Cargo.toml b/Cargo.toml index f1431b5..8a992c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ rust-version = "1.92" [package] name = "beyond-slipstream" -version = "0.10.3" +version = "0.10.4" edition.workspace = true license.workspace = true rust-version.workspace = true @@ -105,6 +105,12 @@ mut_unanchored_relist = [] mut_restore_ignores_versions = [] # The restore deletes keys the bucket lists live. mut_restore_ignores_listing = [] +# The pointer guard compares revisions across incarnations (a dead incarnation's pointer wedges publishing). +mut_pointer_ignores_incarnation = [] +# A foreign cursor keeps its eviction memo (the old stream's) through the repair. +mut_foreign_keeps_memo = [] +# The restore trusts a fold of another incarnation (a recreated bucket's old fold decides keys by its own revision numbers). +mut_restore_trusts_foreign = [] # The fold forgets that it saw retention evict current values. mut_no_eviction_memo = [] diff --git a/src/applied.rs b/src/applied.rs index c03907f..f62b228 100644 --- a/src/applied.rs +++ b/src/applied.rs @@ -869,6 +869,17 @@ where } } + /// The fold's cursor was another incarnation's: its position, its + /// incarnation and its eviction memo are the old stream's, so the fold is + /// a cursor-less one that holds data until a repair commits the new + /// stream's cursor. Run after the repair's settle, so nothing queued under + /// the old cursor is lost. + pub(crate) fn forget_cursor(&mut self) { + // Mutation (model tests only): keep the memo (the pre-fix repair). + let seen = self.applied.seen_evicting() && cfg!(feature = "mut_foreign_keeps_memo"); + self.applied = WatchCursor::none().remembering(seen); + } + /// Remember, durably, that the bucket's retention evicts current values: /// from now on every cursor this fold commits carries the memo, and so /// does every artifact exported from it. Commits at once, even with diff --git a/src/kernels/fleet_proofs.rs b/src/kernels/fleet_proofs.rs index 22d1333..5bf7e56 100644 --- a/src/kernels/fleet_proofs.rs +++ b/src/kernels/fleet_proofs.rs @@ -15,25 +15,29 @@ //! //! where "the truth at its cursor `c` on key `k`" is the last write to `k` at or before `c` (a delete is `None`). //! -//! # The statement, exactly (FINDING F3) +//! # The statement, exactly (F3) //! -//! The Stateright header says "equals the truth at its cursor". On one key with an atomic repair that is the invariant; on many -//! keys it is not what the code keeps, by design: an artifact at cursor `C` is complete *together with the log after `C`* (see -//! `restore_key`): a key whose latest write is after `C` may hold an older value in it, and the resume delivers that write. So the -//! invariant is [`complete`]: the fold equals the truth at its cursor on every key that has not been written after the cursor. -//! At the head that is every key, so a converged node's fold is exactly the truth at the head ([`a_converged_fold_is_the_truth`]). -//! [`finding_f3_the_fold_is_not_the_truth_on_a_key_rewritten_after_the_cursor`] is a concrete restore where the fold at cursor `C` -//! is not the truth at `C`, by the kernel's own `restore_key` table. +//! The Stateright header used to say "equals the truth at its cursor". On one key with an atomic repair that is the invariant; on +//! many keys it is not what the code keeps, by design: an artifact at cursor `C` is complete *together with the log after `C`* +//! (see `restore_key`): a key whose latest write is after `C` may hold an older value in it, and the resume delivers that write. +//! So the invariant is [`complete`]: the fold equals the truth at its cursor on every key that has not been written after the +//! cursor. At the head that is every key, so a converged node's fold is exactly the truth at the head +//! ([`a_converged_fold_is_the_truth`]). [`finding_f3_the_fold_is_not_the_truth_on_a_key_rewritten_after_the_cursor`] is a concrete +//! restore where the fold at cursor `C` is not the truth at `C`, by the kernel's own `restore_key` table. //! -//! # Findings (each a Verus-checked concrete state of the shipped decisions) +//! # Findings, and what each one changed (every one is a Verus-checked concrete state of the shipped decisions) //! -//! * **F1** the pointer guard compares ranks only: a dead incarnation's pointer above the new head refuses every publish of the new -//! stream while `same_incarnation` refuses to restore from it (`finding_f1_*`). The liveness theorems assume it away explicitly. -//! * **F2** a restore over a fold of a recreated stream keeps stale entries by revision number (`finding_f2_*`). The fleet's restore -//! step requires the local entries be real writes of the log (`real`); a foreign fold is `blocked_by_foreign_fold`. +//! * **F1** the pointer guard compared ranks only: a dead incarnation's pointer above the new head refused every publish of the +//! new stream while `same_incarnation` refused to restore from it. FIXED: the guard orders by (incarnation, rank) +//! (`protocol::Pos`), so the new stream's first publish replaces the dead pointer. [`finding_f1_*`] states the fix; the liveness +//! theorem no longer assumes the state away. +//! * **F2** a restore over a fold of a recreated stream kept stale entries by revision number, and refused an artifact below the +//! old cursor's rank. FIXED: a fold whose cursor is no position of this stream (none, or another incarnation's, which the repair +//! forgets) is replaced by the artifact key for key (`restore_key`'s `local_known`). [`finding_f2_*`] states the fix; a restore +//! needs no premise on the local entries. //! * **F3** the invariant is `complete`, not exact equality (above). -//! * **F4** the eviction memo outlives the incarnation: a fleet of foreign nodes blocks on a restore the exact listing could serve -//! (`finding_f4_*`). +//! * **F4** the eviction memo outlived the incarnation: a fleet of foreign nodes blocked on a restore the exact listing could +//! serve. FIXED: the repair forgets the old cursor, memo included (`Detect`). [`finding_f4_*`] states the fix. //! //! # What the shell and the environment must supply //! @@ -42,10 +46,14 @@ //! `tests/model_repair.rs` and `tests/resync.rs`); the restore's diff and listing events run inside [`restore_begin_w`], which //! needs the ahead check, the window re-check and no eviction in between (a refusal is a stutter: `blocked_by_artifact`); //! * **A1** retention config is constant inside an incarnation (a toggle is what the `seen_evicting` memo guards, so -//! `mut_no_eviction_memo` is not observable in this world); `seen` is carried and only ever narrows trust; -//! * **A2** positions are `u64`; the stream's revision numbers fit (below `2^63`); +//! `mut_no_eviction_memo` is not observable in this world); `seen` is carried inside an incarnation and only ever narrows trust; +//! the repair of a foreign cursor forgets it (the memo is a fact about the stream that was evicting); +//! * **A2** positions are `u64`; the stream's revision numbers fit (below `2^63`); incarnations (creation times) fit `u64` and a +//! recreation's is larger than the stream it replaces (O4 of `transport_proofs`); //! * **A3** the pointer object is written only by publishes (`transport_proofs`, O2); //! * a cursor with no recorded origin (written before cursors recorded one) is excluded: `tests/model_incarnation.rs` owns it; +//! * a fold that holds data and NO cursor (a torn first checkpoint) is taken to be of the current stream: nothing in it names an +//! incarnation, so a restore cannot tell it from this stream's, and keeps its newer entries (`model_repair`'s "never backward"); //! * the liveness fairness axioms below (F-a to F-d). use crate::kernels::applied::*; @@ -137,6 +145,7 @@ pub open spec fn live_rev(l: Log, k: nat) -> Option { } pub open spec fn log_ok(l: Log) -> bool { + &&& l.origin <= umax() &&& 1 <= l.first &&& l.first <= l.ops.len() + 1 &&& l.ops.len() < 0x8000_0000_0000_0000 @@ -408,19 +417,22 @@ pub open spec fn key_state(o: Option) -> KeyState { } } -/// `restore_key` for one key: the local entry, the artifact's, and whether the bucket lists the key live. -pub open spec fn key_decision(local: Option, art: Option, listed_live: bool) -> KeyRestore { +/// `restore_key` for one key: the local entry, the artifact's, whether the bucket lists the key live, and whether the local fold +/// is KNOWN to be this stream's (it has a cursor of it). +pub open spec fn key_decision(local: Option, art: Option, listed_live: bool, known: bool) -> KeyRestore { restore_key_spec( key_state(local), key_state(art), local == art, listed_live && !cfg!(feature = "mut_restore_ignores_listing"), + known || cfg!(feature = "mut_restore_trusts_foreign"), ) } -/// What the restore leaves on each key. -pub open spec fn restore_result(l: Log, art: Fold, old: Fold) -> Fold { - |k: nat| match key_decision(old(k), art(k), listed(l, k) is Some) { +/// What the restore leaves on each key. `known`: the local fold is of THIS stream (the repair saw no foreign cursor); a fold of +/// another incarnation is replaced by the artifact key for key. +pub open spec fn restore_result(l: Log, art: Fold, old: Fold, known: bool) -> Fold { + |k: nat| match key_decision(old(k), art(k), listed(l, k) is Some, known) { KeyRestore::Keep => old(k), KeyRestore::TakeArtifact => art(k), KeyRestore::Delete => None, @@ -571,6 +583,8 @@ pub struct Rst { pub art: Art, pub old: Fold, pub result: Fold, + /// The old fold was of this stream (its incarnation is the current one) when the restore began: its entries were trusted. + pub known: bool, } /// One node: the production kernel's world (`w`, whose `store_cursor` is the persisted cursor), the STORE's content, and @@ -625,10 +639,16 @@ pub open spec fn valid(f: F, i: int) -> bool { 0 <= i < f.nodes.len() } +/// A position in the artifact order (`protocol::Pos`): the incarnation, then the cursor. A mutation forges the incarnation away +/// exactly as `mut_pointer_ignores_incarnation` does in the code. +pub open spec fn art_pos(origin: nat, cursor: nat) -> Pos { + Pos { origin: if cfg!(feature = "mut_pointer_ignores_incarnation") { 0 } else { origin as u64 }, rank: cursor as u64 } +} + pub open spec fn ptr_state(p: Option) -> PointerState { match p { None => PointerState::Absent, - Some(a) => PointerState::Present { rank: Some(a.cursor as u64) }, + Some(a) => PointerState::Present { at: Some(art_pos(a.origin, a.cursor)) }, } } @@ -677,7 +697,7 @@ pub open spec fn enabled(f: F, a: Act) -> bool { &&& g <= l.ops.len() + 1 &&& (l.evicts || forall|k: nat| (#[trigger] live_rev(l, k)) is Some ==> live_rev(l, k)->Some_0 >= g) }, - Act::Recreate(e) => true, + Act::Recreate(e) => l.origin + 1 <= umax(), Act::Advance(i) => { valid(f, i) && ({ let n = node_at(f, i); @@ -715,8 +735,6 @@ pub open spec fn enabled(f: F, a: Act) -> bool { // The artifact is of THIS stream (`same_incarnation`) and `restore_allowed` (ahead, inside the window). &&& f.ptr->Some_0.origin == l.origin &&& restore_ok(f.ptr->Some_0.cursor, n.w.store_cursor, l.first) - // The local entries are writes of this log (FINDING F2: nothing in the code checks this of a foreign fold). - &&& real(n.fold, l.ops) }) }, Act::FoldChunks(i) => valid(f, i) && node_at(f, i).rst is Some, @@ -727,7 +745,8 @@ pub open spec fn enabled(f: F, a: Act) -> bool { Act::Publish(i) => { valid(f, i) && ({ let n = node_at(f, i); - n.anchored && n.w.store_cursor >= 1 && publish_allowed_spec(ptr_state(f.ptr), n.w.store_cursor as u64) + n.anchored && n.w.store_cursor >= 1 && n.origin <= umax() + && publish_allowed_spec(ptr_state(f.ptr), art_pos(n.origin, n.w.store_cursor)) }) }, } @@ -747,7 +766,8 @@ pub open spec fn crash_node(n: Node) -> Node { } pub open spec fn detect_node(n: Node) -> Node { - Node { w: init_world(0, 0), anchored: false, rst: None, ..n } + // The cursor is forgotten with its incarnation and its eviction memo: the fold holds data and no cursor. + Node { w: init_world(0, 0), anchored: false, rst: None, seen: n.seen && cfg!(feature = "mut_foreign_keeps_memo"), ..n } } pub open spec fn relist_node(l: Log, n: Node) -> Node { @@ -762,12 +782,11 @@ pub open spec fn relist_node(l: Log, n: Node) -> Node { } pub open spec fn begin_node(l: Log, n: Node, a: Art, hd: bool, pick: spec_fn(nat) -> bool) -> Node { - let result = restore_result(l, a.fold, n.fold); + let result = restore_result(l, a.fold, n.fold, n.origin == l.origin); Node { w: restore_begin_w(n.w, a.cursor, hd), fold: |k: nat| if pick(k) { result(k) } else { (n.fold)(k) }, - origin: l.origin, - rst: Some(Rst { art: a, old: n.fold, result }), + rst: Some(Rst { art: a, old: n.fold, result, known: n.origin == l.origin }), ..n } } @@ -839,8 +858,11 @@ pub open spec fn node_ok(l: Log, n: Node) -> bool { &&& n.w.k.flush is Idle &&& (n.w.k.restore is Idle || n.w.k.restore is Fold) &&& (n.w.k.restore is Fold <==> n.rst is Some) - &&& (n.rst is Some ==> n.w.art == rst_of(n).art.cursor && rst_of(n).art.origin == n.origin - && rst_of(n).art.cursor <= umax()) + &&& (n.rst is Some ==> n.w.art == rst_of(n).art.cursor && rst_of(n).art.cursor <= umax() && art_ok(l, rst_of(n).art)) + // A restore of a fold of this stream is of this stream's artifact; of a foreign fold, the restore IS the artifact. + &&& (n.rst is Some && rst_of(n).known ==> rst_of(n).art.origin == n.origin) + &&& (n.rst is Some && !rst_of(n).known ==> forall|k: nat| (#[trigger] (rst_of(n).result)(k)) == (rst_of(n).art.fold)(k)) + &&& (n.rst is Some && n.origin == l.origin ==> rst_of(n).art.origin == l.origin) &&& n.w.delivered <= umax() &&& (!n.anchored ==> n.w.store_cursor == 0 && n.w.delivered == 0) // A store that holds everything received has no pending position. @@ -878,11 +900,11 @@ pub proof fn a_restore_leaves_the_fold_complete_at_both_cursors(l: Log, old: Fol ok_fold(art, l.ops, c1), c0 < c1, ensures - ok_fold(restore_result(l, art, old), l.ops, c0), - ok_fold(restore_result(l, art, old), l.ops, c1), + ok_fold(restore_result(l, art, old, true), l.ops, c0), + ok_fold(restore_result(l, art, old, true), l.ops, c1), { let ops = l.ops; - let res = restore_result(l, art, old); + let res = restore_result(l, art, old, true); assert forall|k: nat| (#[trigger] res(k)) is Some implies real_entry(ops, k, res(k)->Some_0) by { assert(old(k) is Some ==> real_entry(ops, k, old(k)->Some_0)); assert(art(k) is Some ==> real_entry(ops, k, art(k)->Some_0)); @@ -929,7 +951,7 @@ pub proof fn a_restore_leaves_the_fold_complete_at_both_cursors(l: Log, old: Fol } /// THEOREM (a restore never moves a key backward, and never deletes a key the bucket lists live): the kernel's `restore_key` -/// guarantees, over every key of the fleet's fold. Every key of the fold: if the local entry survives or is replaced, its +/// guarantees for a fold with a cursor, over every key of the fleet's fold. Every key of the fold: if the local entry survives or is replaced, its /// revision does not fall; a deleted entry was not listed live. pub proof fn a_restore_never_moves_a_key_backward_or_deletes_a_live_one(l: Log, old: Fold, art: Fold, k: nat) requires @@ -938,7 +960,7 @@ pub proof fn a_restore_never_moves_a_key_backward_or_deletes_a_live_one(l: Log, real(art, l.ops), ensures ({ - let res = restore_result(l, art, old); + let res = restore_result(l, art, old, true); &&& (old(k) is Some && res(k) is Some ==> res(k)->Some_0 >= old(k)->Some_0) &&& (old(k) is Some && res(k) is None ==> listed(l, k) is None) }), @@ -947,6 +969,16 @@ pub proof fn a_restore_never_moves_a_key_backward_or_deletes_a_live_one(l: Log, assert(art(k) is Some ==> real_entry(l.ops, k, art(k)->Some_0)); } +/// THEOREM (a restore of a foreign fold is the artifact): the old fold may be anything, entries and revision numbers of another +/// stream included. The restore leaves exactly the artifact's fold, key for key, so it is real and complete wherever the +/// artifact is, with no premise on what the old fold held (FINDING F2: the revision-number comparison of `restore_key` is for a +/// fold of this stream). +pub proof fn a_restore_over_a_foreign_fold_is_the_artifact(l: Log, old: Fold, art: Fold, k: nat) + ensures + restore_result(l, art, old, false)(k) == art(k), +{ +} + // --------------------------------------------------------------------------------------------------------------------- // Node-level steps. // --------------------------------------------------------------------------------------------------------------------- @@ -1047,7 +1079,6 @@ proof fn lemma_begin(l: Log, f_ptr: Art, n: Node, hd: bool, pick: spec_fn(nat) - settled(n), f_ptr.origin == l.origin, restore_ok(f_ptr.cursor, n.w.store_cursor, l.first), - real(n.fold, l.ops), ensures node_ok(l, begin_node(l, n, f_ptr, hd, pick)), { @@ -1061,26 +1092,28 @@ proof fn lemma_begin(l: Log, f_ptr: Art, n: Node, hd: bool, pick: spec_fn(nat) - assert(c0 as u64 as nat == c0); } a_restore_runs_from_a_settled_node_to_the_chunk_fold(n.w, c1, hd); - // The fold is real, and complete at its cursor: by its claims (anchored), or at cursor 0 (cursor-less). - assert(ok_fold(n.fold, l.ops, c0)) by { - if n.anchored { - assert(n.origin == l.origin); - } else { - a_real_fold_is_complete_at_zero(n.fold, l.ops); - } - } + assert(ok_fold(f_ptr.fold, l.ops, c1)); assert(c1 <= l.ops.len()); - a_restore_leaves_the_fold_complete_at_both_cursors(l, n.fold, f_ptr.fold, c0, c1); - let result = restore_result(l, f_ptr.fold, n.fold); + let result = restore_result(l, f_ptr.fold, n.fold, n.origin == l.origin); assert(n.w.delivered <= l.ops.len()); - assert forall|k: nat| (#[trigger] (n2.fold)(k)) is Some implies real_entry(l.ops, k, (n2.fold)(k)->Some_0) by { - assert(result(k) is Some ==> real_entry(l.ops, k, result(k)->Some_0)); - } - assert forall|k: nat| !touched(l.ops, c0, k) implies #[trigger] (n2.fold)(k) == truth(l.ops, c0, k) by { - assert(result(k) == truth(l.ops, c0, k)); - assert((n.fold)(k) == truth(l.ops, c0, k)); + if n.origin == l.origin { + // A fold of this stream: real and complete at its cursor by its claims (at 0, when it has none). + assert(ok_fold(n.fold, l.ops, c0)); + a_restore_leaves_the_fold_complete_at_both_cursors(l, n.fold, f_ptr.fold, c0, c1); + assert forall|k: nat| (#[trigger] (n2.fold)(k)) is Some implies real_entry(l.ops, k, (n2.fold)(k)->Some_0) by { + assert(result(k) is Some ==> real_entry(l.ops, k, result(k)->Some_0)); + } + assert forall|k: nat| !touched(l.ops, c0, k) implies #[trigger] (n2.fold)(k) == truth(l.ops, c0, k) by { + assert(result(k) == truth(l.ops, c0, k)); + assert((n.fold)(k) == truth(l.ops, c0, k)); + } + assert(rst_ok(l, n2)); + } else { + // A fold of another incarnation, of any content: the result IS the artifact's fold, so nothing is claimed of the mix. + assert forall|k: nat| (#[trigger] result(k)) == (f_ptr.fold)(k) by { + a_restore_over_a_foreign_fold_is_the_artifact(l, n.fold, f_ptr.fold, k); + } } - assert(rst_ok(l, n2)); } proof fn lemma_chunks(l: Log, n: Node) @@ -1102,9 +1135,33 @@ proof fn lemma_end(l: Log, n: Node) { a_restore_commit_lands_the_store_at_the_artifacts_cursor(n.w); let n2 = end_node(n); + let art = rst_of(n).art; assert(n2.w.store_cursor == n.w.art); - if n.origin == l.origin { - assert(ok_fold(n2.fold, l.ops, rst_of(n).art.cursor)); + assert(art_ok(l, art)); + if art.origin == l.origin { + // The node now holds a fold of this stream at the artifact's cursor: complete there. + if rst_of(n).known { + // Its restore was of a fold of this stream, so its claims hold (the artifact is this stream's): the result is complete + // at the artifact's cursor. + assert(n.origin == l.origin); + assert(ok_fold(n.fold, l.ops, art.cursor)); + } else { + // A foreign fold's restore is the artifact. + assert forall|k: nat| (#[trigger] (n.fold)(k)) == (art.fold)(k) by { + assert((n.fold)(k) == (rst_of(n).result)(k)); + } + assert(ok_fold(n.fold, l.ops, art.cursor)) by { + assert forall|k: nat| (#[trigger] (n.fold)(k)) is Some implies real_entry(l.ops, k, (n.fold)(k)->Some_0) by { + assert((art.fold)(k) == (n.fold)(k)); + } + assert forall|k: nat| !touched(l.ops, art.cursor, k) implies #[trigger] (n.fold)(k) == truth(l.ops, art.cursor, k) by { + assert((art.fold)(k) == (n.fold)(k)); + } + } + } + assert(n2.fold == n.fold); + assert(ok_fold(n2.fold, l.ops, art.cursor)); + assert(claims(l, n2)); } } @@ -1130,6 +1187,9 @@ proof fn lemma_append_node(l: Log, op: Op, n: Node) } assert(claims(l2, n)); } + if n.rst is Some { + lemma_append_art(l, op, rst_of(n).art); + } } proof fn lemma_append_art(l: Log, op: Op, a: Art) @@ -1204,6 +1264,7 @@ proof fn update_node_keeps(f: F, i: int, n2: Node) proof fn lemma_recreate_node(l: Log, e: bool, n: Node) requires node_ok(l, n), + l.origin + 1 <= umax(), ensures node_ok(Log { origin: l.origin + 1, ops: Seq::empty(), first: 1, evicts: e }, n), { @@ -1410,6 +1471,7 @@ proof fn case_evict(f: F, g: nat) proof fn case_recreate(f: F, e: bool) requires finv(f), + enabled(f, Act::Recreate(e)), ensures finv(step(f, Act::Recreate(e))), { @@ -1437,7 +1499,7 @@ proof fn case_publish(f: F, i: int) /// THEOREM (every live node's fold is the truth at its cursor): a node of the current incarnation holds, on every key not written /// since its cursor, the truth at its cursor; and holds only writes of this log. -pub proof fn every_live_nodes_fold_is_the_truth_at_its_cursor(f: F, i: int, k: nat) +pub proof fn every_live_nodes_fold_is_complete_at_its_cursor(f: F, i: int, k: nat) requires finv(f), valid(f, i), @@ -1452,7 +1514,7 @@ pub proof fn every_live_nodes_fold_is_the_truth_at_its_cursor(f: F, i: int, k: n /// THEOREM (every published artifact is the truth at its cursor): the same of the pointer's artifact, when it is of the current /// incarnation (an artifact of another incarnation is never restored: `same_incarnation`). -pub proof fn every_published_artifact_is_the_truth_at_its_cursor(f: F, k: nat) +pub proof fn every_published_artifact_is_complete_at_its_cursor(f: F, k: nat) requires finv(f), f.ptr is Some, @@ -1512,7 +1574,7 @@ pub proof fn finding_f3_the_fold_is_not_the_truth_on_a_key_rewritten_after_the_c let l = Log { origin: 1, ops, first: 1, evicts: true }; let old: Fold = |k: nat| if k == 0 { Some(1nat) } else { None }; let art: Fold = |k: nat| None; - restore_result(l, art, old)(0) == Some(1nat) && truth(ops, 2, 0) is None && truth(ops, 3, 0) == Some(3nat) + restore_result(l, art, old, true)(0) == Some(1nat) && truth(ops, 2, 0) is None && truth(ops, 3, 0) == Some(3nat) && touched(ops, 2, 0) }), { @@ -1524,24 +1586,21 @@ pub proof fn finding_f3_the_fold_is_not_the_truth_on_a_key_rewritten_after_the_c assert(truth(ops, 2, 0) is None); } -/// FINDING F2 (a restore over a foreign fold): when the stream is deleted and recreated, a node's fold holds the OLD stream's -/// entries and revisions (`Detect`: repaired "like a cursor-less start that holds data"). With the listing untrusted -/// (an evicting bucket) that repair is a restore, and `restore_key` decides by REVISION NUMBER: an old entry numbered above the -/// artifact's is "newer" and kept. Here the new stream has put key 0 seven times (artifact cursor 7, key 0 at rev 7), the old -/// entry is `Some(500)`: the restore keeps it, and the committed fold at cursor 7 holds a value no write of this log made, on a key -/// no write follows. (Nothing in `check_restore` or `restore_diff` rules a foreign fold out.) The fleet proof therefore requires -/// the local entries be real writes of this log (`real`) before a restore, and a foreign fold that is not is not restored: -/// the liveness theorems carry the same premise (`blocked_by_foreign_fold`). -pub proof fn finding_f2_a_restore_over_a_foreign_fold_keeps_a_stale_entry() - requires - !cfg!(feature = "mut_restore_ignores_versions"), +/// FINDING F2 (a restore over a foreign fold), FIXED: when the stream is deleted and recreated, a node's fold holds the OLD +/// stream's entries and revisions (`Detect`: the cursor is forgotten and the fold repaired "like a cursor-less start that holds +/// data"). With the listing untrusted (an evicting bucket) that repair is a restore, and `restore_key` used to decide by REVISION +/// NUMBER: an old entry numbered above the artifact's was "newer" and kept. Here the new stream has put key 0 seven times +/// (artifact cursor 7, key 0 at rev 7) and the old entry is `Some(500)`. The restore of a fold with no cursor (`known == false`) +/// takes the artifact's entry: the committed fold at cursor 7 holds the write the log made. The same restore, with the old +/// fold's entries trusted, is the pre-fix state (`mut_restore_trusts_foreign` forges it: this proof goes red). +pub proof fn finding_f2_a_restore_over_a_foreign_fold_takes_the_artifacts_entry() ensures ({ let ops = Seq::new(7, |i: int| Op { key: 0, put: true }); let l = Log { origin: 2, ops, first: 1, evicts: true }; let old: Fold = |k: nat| if k == 0 { Some(500nat) } else { None }; let art: Fold = |k: nat| if k == 0 { Some(7nat) } else { None }; - ok_fold(art, ops, 7) && !real(old, ops) && restore_result(l, art, old)(0) == Some(500nat) + ok_fold(art, ops, 7) && !real(old, ops) && restore_result(l, art, old, false)(0) == Some(7nat) && truth(ops, 7, 0) == Some(7nat) && !touched(ops, 7, 0) }), { @@ -1565,21 +1624,48 @@ pub proof fn finding_f2_a_restore_over_a_foreign_fold_keeps_a_stale_entry() assert(!touched(ops, 7, 0)); } -/// FINDING F1 (a dead incarnation's pointer wedges publishing): the pointer guard compares ranks only +/// FINDING F1 (a dead incarnation's pointer wedged publishing), FIXED: the pointer guard used to compare ranks only /// (`pointer_publish_allowed`, `transport::swap_pointer`), never the incarnation. After the stream is recreated, a pointer whose -/// artifact is the OLD stream's, ranked above the new stream's head, refuses every publish of the new stream until its head -/// passes that rank, while `same_incarnation` refuses to restore from it. Between the two, the fleet has no usable artifact: a node -/// that must restore (an evicting bucket) cannot, though every other node holds the head. -pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_refuses_every_publish(l: Log, a: Art, c: nat) +/// artifact is the OLD stream's, ranked above the new stream's head, refused every publish of the new stream until its head +/// passed that rank, while `same_incarnation` refused to restore from it. Now the guard orders by (incarnation, rank): a publish of +/// the current incarnation is admitted over any pointer of a dead one, whatever its rank (`mut_pointer_ignores_incarnation` +/// forges the old guard: this proof goes red), and a publish of a dead incarnation is refused over the current one's. +pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_does_not_refuse_a_publish(l: Log, a: Art, c: nat) requires + log_ok(l), a.origin < l.origin, a.cursor > c, a.cursor <= umax(), c <= umax(), ensures - !publish_allowed_spec(ptr_state(Some(a)), c as u64), - !(a.origin == l.origin), + publish_allowed_spec(ptr_state(Some(a)), art_pos(l.origin, c)), + !publish_allowed_spec(ptr_state(Some(Art { origin: l.origin, cursor: c, fold: a.fold })), art_pos(a.origin, a.cursor)), +{ +} + +/// FINDING F4 (a stale memo blocked a start the listing could serve), FIXED: `seen_evicting` rides the cursor, and a node that +/// sees its cursor belong to another incarnation used to keep it (`Detect`). On the recreated, un-evicted bucket the listing IS the +/// truth, but the memo distrusted it, so the plan was a restore; with no artifact of the new stream (a fleet that is all foreign +/// has no node to publish one) every such node was blocked for ever, though nothing was lost. Now the detected node forgets the +/// memo with the cursor, and plans the listing wherever the listing is exact. +pub proof fn finding_f4_a_detected_node_forgets_the_old_streams_eviction_memo(f: F, i: int) + requires + finv(f), + valid(f, i), + !f.log.evicts, + f.log.first == 1, + !cfg!(feature = "mut_no_eviction_memo"), + enabled(f, Act::Detect(i)), + ensures + !step(f, Act::Detect(i)).nodes[i].seen, + plan_of(lt_of(f.log, step(f, Act::Detect(i)).nodes[i])) is Relist, + forall|k: nat| (#[trigger] listed(f.log, k)) == truth(f.log.ops, f.log.ops.len(), k), { + let l = f.log; + assert(log_ok(l)); + assert forall|k: nat| (#[trigger] listed(l, k)) == truth(l.ops, l.ops.len(), k) by { + the_trusted_listing_is_the_truth(l, false, k); + } } // --------------------------------------------------------------------------------------------------------------------- @@ -1618,7 +1704,7 @@ pub open spec fn nrank(l: Log, n: Node) -> int { 2 * (len - n.w.delivered as int) + (n.w.delivered as int - n.w.store_cursor as int) } else if n.rst is Some { let fl: int = if folded(n) { 0 } else { 1 }; - if n.origin != l.origin { + if rst_of(n).art.origin != l.origin { 2 * len + 11 + fl } else if win(rst_of(n).art.cursor, l.first) { 2 * len + 4 + fl @@ -1644,13 +1730,6 @@ pub open spec fn blocked_by_artifact(f: F, i: int) -> bool { repairable(f.log, n) && settled(n) && plan_of(lt_of(f.log, n)) is Restore && !admissible_art(f, n) } -/// FINDING F2's liveness face: an artifact could seed the node but its fold holds entries that are no write of this log. -pub open spec fn blocked_by_foreign_fold(f: F, i: int) -> bool { - let n = node_at(f, i); - repairable(f.log, n) && settled(n) && plan_of(lt_of(f.log, n)) is Restore && admissible_art(f, n) - && !real(n.fold, f.log.ops) -} - pub open spec fn acts_on(a: Act, i: int) -> bool { match a { Act::Advance(j) => j == i, @@ -1674,15 +1753,14 @@ pub open spec fn lowers(f: F, i: int, a: Act) -> bool { } /// THEOREM (progress): from any state satisfying the invariant, every node is converged, or some fair step of its own lowers its -/// rank, or it is blocked (no artifact can seed it, or, FINDING F2, its fold is foreign). The rank is a natural number, so a node -/// that is never blocked reaches the head in finitely many steps. +/// rank, or it is blocked: no artifact can seed it (and the listing is not the truth). The rank is a natural number, so a node +/// that is never blocked reaches the head in finitely many steps. A foreign fold needs no case of its own: a restore replaces it. pub proof fn a_node_is_converged_or_a_fair_step_lowers_its_rank_or_it_is_blocked(f: F, i: int) requires finv(f), valid(f, i), ensures - converged(f.log, node_at(f, i)) || (exists|a: Act| #[trigger] lowers(f, i, a)) || blocked_by_artifact(f, i) - || blocked_by_foreign_fold(f, i), + converged(f.log, node_at(f, i)) || (exists|a: Act| #[trigger] lowers(f, i, a)) || blocked_by_artifact(f, i), { let l = f.log; let n = node_at(f, i); @@ -1776,13 +1854,13 @@ proof fn prog_restore(f: F, i: int) assert(enabled(f, a)); assert(n2.w.delivered == art.cursor && n2.w.store_cursor == art.cursor); assert(n2.rst is None && n2.anchored && n2.origin == art.origin); - assert(nrank(l, n) == (if n.origin != l.origin { 2 * len + 11 } else if win(art.cursor, l.first) { + assert(nrank(l, n) == (if art.origin != l.origin { 2 * len + 11 } else if win(art.cursor, l.first) { 2 * len + 4 } else { 2 * len + 7 })); - if n.origin == l.origin { - assert(ok_fold(n.fold, l.ops, art.cursor)); + if art.origin == l.origin { + assert(ok_fold(n2.fold, l.ops, art.cursor)); if win(art.cursor, l.first) { assert(live(l, n2)); assert(nrank(l, n2) <= 2 * len); @@ -1813,7 +1891,7 @@ proof fn prog_repair(f: F, i: int) node_at(f, i).rst is None, !(node_at(f, i).anchored && node_at(f, i).origin != f.log.origin), ensures - (exists|a: Act| #[trigger] lowers(f, i, a)) || blocked_by_artifact(f, i) || blocked_by_foreign_fold(f, i), + (exists|a: Act| #[trigger] lowers(f, i, a)) || blocked_by_artifact(f, i), { let l = f.log; let n = node_at(f, i); @@ -1854,7 +1932,7 @@ proof fn prog_repair(f: F, i: int) assert(converged(l, n2)); assert(enabled(f, a)); lowers_from(f, i, a, n2); - } else if admissible_art(f, n) && real(n.fold, l.ops) { + } else if admissible_art(f, n) { let pick = |k: nat| true; let a = Act::RestoreBegin(i, false, pick); assert(enabled(f, a)); @@ -1874,8 +1952,9 @@ proof fn prog_repair(f: F, i: int) /// THEOREM (a blocked node unblocks): if some node is converged, a publish by it is admitted by the pointer guard, and afterwards /// the pointer names an artifact that seeds every blocked node behind the head. The artifact an exporter publishes is its own -/// store at its own cursor; a converged node's cursor is the head. HYPOTHESIS: the pointer is not a dead incarnation's, ranked above -/// the head (FINDING F1 is exactly that state: `finding_f1_a_dead_pointer_ahead_of_the_head_refuses_every_publish`). +/// store at its own cursor; a converged node's cursor is the head. No hypothesis on the pointer: a dead incarnation's, whatever its +/// rank, is replaced (FINDING F1, fixed: `finding_f1_a_dead_pointer_ahead_of_the_head_does_not_refuse_a_publish`), and an artifact +/// of this stream is at most the head. pub proof fn a_converged_node_unblocks_every_blocked_one(f: F, j: int, i: int) requires finv(f), @@ -1884,8 +1963,6 @@ pub proof fn a_converged_node_unblocks_every_blocked_one(f: F, j: int, i: int) converged(f.log, node_at(f, j)), blocked_by_artifact(f, i), node_at(f, i).w.store_cursor < f.log.ops.len(), - // No dead incarnation's pointer sits above the head. - !(f.ptr is Some && f.ptr->Some_0.origin != f.log.origin && f.ptr->Some_0.cursor > f.log.ops.len()), ensures enabled(f, Act::Publish(j)), finv(step(f, Act::Publish(j))), @@ -1901,14 +1978,20 @@ pub proof fn a_converged_node_unblocks_every_blocked_one(f: F, j: int, i: int) assert(nj.w.store_cursor == len); assert(len <= umax()); assert(len as u64 as nat == len); - // The guard: the pointer is absent, or an artifact of this stream (at most the head), or a dead one at most the head. + // The guard: the pointer is absent, or an artifact of this stream (at most the head), or a dead incarnation's (older). if f.ptr is Some { let a = f.ptr->Some_0; - assert(a.cursor <= len); + assert(a.origin <= l.origin); assert(a.cursor <= umax()); assert(a.cursor as u64 as nat == a.cursor); + assert(a.origin as u64 as nat == a.origin); + assert(nj.origin == l.origin); + assert(l.origin as u64 as nat == l.origin); + if a.origin == l.origin { + assert(a.cursor <= len); + } } - assert(publish_allowed_spec(ptr_state(f.ptr), len as u64)); + assert(publish_allowed_spec(ptr_state(f.ptr), art_pos(nj.origin, len))); case_publish(f, j); let f2 = step(f, Act::Publish(j)); let a2 = f2.ptr->Some_0; @@ -1958,27 +2041,4 @@ pub proof fn a_blocked_node_names_the_write_that_aged_out(f: F, i: int) } } -/// FINDING F4 (a stale memo blocks a start the listing could serve): `seen_evicting` rides the cursor, and a node that sees its -/// cursor belong to another incarnation keeps it (`Detect`). On the recreated, un-evicted bucket the listing IS the truth, but the -/// memo distrusts it, so the plan is a restore; with no artifact of the new stream (a fleet that is all foreign has no node to -/// publish one) every such node is blocked for ever, though nothing was lost. -pub proof fn finding_f4_a_stale_eviction_memo_blocks_a_start_the_listing_could_serve(f: F, i: int) - requires - finv(f), - valid(f, i), - !f.log.evicts, - f.log.first == 1, - node_at(f, i).seen, - !cfg!(feature = "mut_no_eviction_memo"), - ensures - plan_of(lt_of(f.log, node_at(f, i))) is Restore, - forall|k: nat| (#[trigger] listed(f.log, k)) == truth(f.log.ops, f.log.ops.len(), k), -{ - let l = f.log; - assert(log_ok(l)); - assert forall|k: nat| (#[trigger] listed(l, k)) == truth(l.ops, l.ops.len(), k) by { - the_trusted_listing_is_the_truth(l, false, k); - } -} - } // verus! diff --git a/src/kernels/mod.rs b/src/kernels/mod.rs index 1e6e06a..acc9936 100644 --- a/src/kernels/mod.rs +++ b/src/kernels/mod.rs @@ -13,6 +13,6 @@ pub mod protocol; #[cfg(verus_keep_ghost)] mod applied_proofs; #[cfg(verus_keep_ghost)] -mod transport_proofs; -#[cfg(verus_keep_ghost)] mod fleet_proofs; +#[cfg(verus_keep_ghost)] +mod transport_proofs; diff --git a/src/kernels/protocol.rs b/src/kernels/protocol.rs index f0447a4..6ce1ed1 100644 --- a/src/kernels/protocol.rs +++ b/src/kernels/protocol.rs @@ -36,64 +36,111 @@ use vstd::prelude::*; // decides, the lemmas are the safety arguments the doc comments make in prose. A normal build erases all of it. verus! { +/// A position in the artifact order: the stream incarnation a cursor was taken from, then its revision. Incarnations are +/// ordered by the stream's creation time ([`same_incarnation`]'s `origin`; 0 for a cursor that records none, older than +/// every recorded one), revisions within one. Environment axiom **O4**: a bucket recreated under its name is created later +/// than the stream it replaces (NATS stamps `created` from the server's clock); a clock that steps back across a recreation +/// leaves the old pointer standing until the new stream's head passes it: loud as a refused publish, never a regression. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Pos { + /// The stream incarnation (creation time in Unix ns; 0 when the cursor records none). + pub origin: u64, + /// The cursor's revision. + pub rank: u64, +} + +/// `a` is strictly before `b`: an older incarnation, or the same one at a lower revision. +pub open spec fn pos_lt(a: Pos, b: Pos) -> bool { + a.origin < b.origin || (a.origin == b.origin && a.rank < b.rank) +} + /// What the publisher observed at the pointer key before deciding. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PointerState { /// No pointer object exists — the slot is open (create-only publish). Absent, - /// A pointer object exists. `rank` is its cursor's rank, or `None` when + /// A pointer object exists. `at` is its cursor's position, or `None` when /// the object is unparseable — a corrupt pointer MUST be replaceable, or /// one bad write wedges publishing forever (the same rule as the export /// lease's corrupt-steal). Present { - /// Rank of the existing pointer's cursor; `None` if unparseable. - rank: Option, + /// Position of the existing pointer's cursor; `None` if unparseable. + at: Option, }, } -/// THE monotonic pointer guard: may `candidate_rank` be published over the +/// THE monotonic pointer guard: may `candidate` be published over the /// observed `current` pointer? /// /// `true` for an open slot, a corrupt pointer, or a candidate at or above -/// the existing cursor; `false` exactly when the existing pointer is -/// parseable and STRICTLY newer — the refusal that makes a slow exporter's -/// stale publish a no-op instead of a regression. +/// the existing cursor in ([`Pos`]) order; `false` exactly when the existing +/// pointer is parseable and STRICTLY newer — the refusal that makes a slow +/// exporter's stale publish a no-op instead of a regression. The order is the +/// incarnation first: a pointer of a dead incarnation, whatever its revision, +/// is replaced by the first publish of the stream that replaced it, and never +/// replaces it back. (Ranks alone left such a pointer, ranked above the new +/// head, refusing every publish of the new stream.) /// /// Soundness of deciding on a read (before the conditional put): every -/// writer uses this guard with a compare-and-swap, so the pointer's rank is +/// writer uses this guard with a compare-and-swap, so the pointer's position is /// monotone non-decreasing — once "strictly newer" is observed, it can never /// become false, so refusal needs no CAS. Machine-checked as `published /// cursor never regresses` in `tests/model.rs`. -pub fn pointer_publish_allowed(current: &PointerState, candidate_rank: u64) -> (r: bool) +pub fn pointer_publish_allowed(current: &PointerState, candidate: Pos) -> (r: bool) ensures - r == publish_allowed_spec(*current, candidate_rank), + r == publish_allowed_spec(*current, candidate), { + // Mutation (model tests only): compare revisions across incarnations (the pre-fix guard). + let candidate = if cfg!(feature = "mut_pointer_ignores_incarnation") { + Pos { origin: 0, rank: candidate.rank } + } else { + candidate + }; match current { PointerState::Absent => true, - PointerState::Present { rank: None } => true, - PointerState::Present { rank: Some(existing) } => candidate_rank >= *existing, + PointerState::Present { at: None } => true, + PointerState::Present { at: Some(existing) } => { + let existing = if cfg!(feature = "mut_pointer_ignores_incarnation") { + Pos { origin: 0, rank: existing.rank } + } else { + *existing + }; + candidate.origin > existing.origin + || (candidate.origin == existing.origin && candidate.rank >= existing.rank) + }, } } /// [`pointer_publish_allowed`]: refused exactly when the existing pointer is parseable and strictly newer. -pub open spec fn publish_allowed_spec(current: PointerState, candidate_rank: u64) -> bool { - !(current is Present && current->Present_rank is Some - && current->Present_rank->Some_0 > candidate_rank) +pub open spec fn publish_allowed_spec(current: PointerState, candidate: Pos) -> bool { + !(current is Present && current->Present_at is Some && pos_lt(candidate, current->Present_at->Some_0)) } /// The pointer after a publish that [`pointer_publish_allowed`] admitted: the candidate's cursor. -pub open spec fn published(candidate_rank: u64) -> PointerState { - PointerState::Present { rank: Some(candidate_rank) } +pub open spec fn published(candidate: Pos) -> PointerState { + PointerState::Present { at: Some(candidate) } } -/// THEOREM (monotone pointer): an admitted publish never lowers a parseable pointer, so the pointer's rank is monotone -/// non-decreasing under every interleaving of admitted publishes. This is what lets a refusal be decided on a read. -pub proof fn a_publish_never_regresses_the_pointer(current: PointerState, candidate_rank: u64) +/// THEOREM (monotone pointer): an admitted publish never lowers a parseable pointer, so the pointer's position is monotone +/// non-decreasing under every interleaving of admitted publishes: across incarnations by creation time (O4), within one by +/// revision. This is what lets a refusal be decided on a read. +pub proof fn a_publish_never_regresses_the_pointer(current: PointerState, candidate: Pos) requires - publish_allowed_spec(current, candidate_rank), + publish_allowed_spec(current, candidate), ensures - (current is Present && current->Present_rank is Some) - ==> published(candidate_rank)->Present_rank->Some_0 >= current->Present_rank->Some_0, + (current is Present && current->Present_at is Some) + ==> !pos_lt(published(candidate)->Present_at->Some_0, current->Present_at->Some_0), +{ +} + +/// THEOREM (a dead incarnation's pointer never refuses a newer incarnation): whatever revision the pointer holds, a candidate +/// of a later incarnation is admitted. The pointer of a deleted and recreated bucket is replaced by the new stream's first +/// publish, even when ranked above the new head. +pub proof fn a_newer_incarnation_replaces_any_pointer(current: PointerState, candidate: Pos) + requires + current is Present && current->Present_at is Some ==> candidate.origin > current->Present_at->Some_0.origin, + ensures + publish_allowed_spec(current, candidate), { } @@ -101,88 +148,91 @@ pub proof fn a_publish_never_regresses_the_pointer(current: PointerState, candid /// the pointer are always admitted, so an exporter that retries with a cursor at or above the pointer's succeeds. A stale /// publish is refused only while the pointer is strictly newer, and the pointer never regresses, so it stays refused: the /// exporter's exit is a fresher export, never a retry of the stale one. Rank: none needed, the guard is stateless. -pub proof fn a_publish_at_or_above_the_pointer_is_admitted(current: PointerState, candidate_rank: u64) +pub proof fn a_publish_at_or_above_the_pointer_is_admitted(current: PointerState, candidate: Pos) requires - current is Present && current->Present_rank is Some ==> candidate_rank >= current->Present_rank->Some_0, + current is Present && current->Present_at is Some ==> !pos_lt(candidate, current->Present_at->Some_0), ensures - publish_allowed_spec(current, candidate_rank), + publish_allowed_spec(current, candidate), { } /// THE prune guard: may this payload object be deleted, given the current -/// pointer's rank? +/// pointer's position? /// /// A payload is prunable only when ALL hold: /// - it is not the pointer's own target; -/// - its rank is parseable AND **strictly below** the pointer's (an -/// unparseable rank is never deleted — unknown objects are not ours); +/// - its position is parseable AND **strictly below** the pointer's (an +/// unparseable name is never deleted — unknown objects are not ours); /// - its age has cleared the grace period (`aged_out`; the model passes /// `true`, checking the harshest zero-grace timing). /// /// Strictly-below is what makes a dangling pointer impossible regardless of /// timing: [`pointer_publish_allowed`] refuses any candidate below the /// pointer, and the pointer is monotone — so anything this guard deletes -/// (rank < pointer-at-prune ≤ pointer-at-any-later-swap) can never be -/// successfully published afterward. The model checker FOUND the dangling +/// (position < pointer-at-prune ≤ pointer-at-any-later-swap) can never be +/// successfully published afterward. The payload's name carries its +/// incarnation as well as its revision for that reason: a revision alone +/// cannot say whether a payload of another incarnation is below the pointer. +/// The model checker FOUND the dangling /// counterexample under the earlier age-only rule (a same-cursor payload /// collected mid-publish, then published by the `>=` swap guard); this rule /// is the structural fix, machine-checked as `pointer target always /// fetchable` under zero-grace pruning. pub fn payload_prunable( - payload_rank: Option, - pointer_rank: u64, + payload: Option, + pointer: Pos, is_pointer_target: bool, aged_out: bool, ) -> (r: bool) ensures - r == prunable_spec(payload_rank, pointer_rank, is_pointer_target, aged_out), + r == prunable_spec(payload, pointer, is_pointer_target, aged_out), { if is_pointer_target || !aged_out { return false; } - match payload_rank { - Some(rank) => rank < pointer_rank, + match payload { + Some(p) => p.origin < pointer.origin || (p.origin == pointer.origin && p.rank < pointer.rank), None => false, } } /// [`payload_prunable`]: not the target, aged out, and parseable strictly below the pointer. pub open spec fn prunable_spec( - payload_rank: Option, - pointer_rank: u64, + payload: Option, + pointer: Pos, is_pointer_target: bool, aged_out: bool, ) -> bool { - !is_pointer_target && aged_out && payload_rank is Some && payload_rank->Some_0 < pointer_rank + !is_pointer_target && aged_out && payload is Some && pos_lt(payload->Some_0, pointer) } -/// THEOREM (no dangling pointer): a payload the prune guard deletes can never be published afterwards. The pointer's rank is -/// monotone ([`a_publish_never_regresses_the_pointer`]), so at any later swap it is `later >= pointer_rank > payload`, and the -/// publish guard refuses that candidate. Holds for every timing, including zero grace (`aged_out` is a free input). +/// THEOREM (no dangling pointer): a payload the prune guard deletes can never be published afterwards. The pointer's position is +/// monotone ([`a_publish_never_regresses_the_pointer`]), so at any later swap it is `later >= pointer > payload` in [`Pos`] order, +/// and the publish guard refuses that candidate. Holds for every timing, including zero grace (`aged_out` is a free input). pub proof fn a_pruned_payload_is_never_published_after( - payload_rank: u64, - pointer_rank: u64, - later_pointer_rank: u64, + payload: Pos, + pointer: Pos, + later_pointer: Pos, is_pointer_target: bool, aged_out: bool, ) requires - prunable_spec(Some(payload_rank), pointer_rank, is_pointer_target, aged_out), - later_pointer_rank >= pointer_rank, + prunable_spec(Some(payload), pointer, is_pointer_target, aged_out), + !pos_lt(later_pointer, pointer), ensures - !publish_allowed_spec(PointerState::Present { rank: Some(later_pointer_rank) }, payload_rank), + !publish_allowed_spec(PointerState::Present { at: Some(later_pointer) }, payload), { } -/// THEOREM: the pointer's own target and an unparseable payload are never pruned, whatever the ranks and ages. +/// THEOREM: the pointer's own target and an unparseable payload are never pruned, whatever the positions and ages. pub proof fn the_target_and_unknown_objects_are_never_pruned( - payload_rank: Option, - pointer_rank: u64, + payload: Option, + pointer: Pos, aged_out: bool, ) ensures - !prunable_spec(payload_rank, pointer_rank, true, aged_out), - !prunable_spec(None, pointer_rank, false, aged_out), + !prunable_spec(payload, pointer, true, aged_out), + !prunable_spec(None, pointer, false, aged_out), { } @@ -531,6 +581,10 @@ pub enum KeyRestore { /// together with the log after `C`: a key whose latest write is after `C` /// may be missing or older in it, and the resume delivers that write. So: /// +/// - the local fold is not this stream's (`!local_known`: its cursor was another incarnation's, which the repair forgets): its +/// entries and revision numbers say nothing about this log, so the artifact's entry is taken whenever it has one and a +/// local entry it lacks is deleted (the bucket's listing proves nothing about an entry of another stream; the resume +/// delivers every write after the artifact's cursor). What follows is for a known fold; /// - the artifact has the key: take it, unless the local entry is NEWER /// (revisions decide; without both, only `identical` entries are kept) — /// never a move backward; @@ -543,16 +597,21 @@ pub fn restore_key( artifact: KeyState, identical: bool, listed_live: bool, + local_known: bool, ) -> (r: KeyRestore) ensures - r == restore_key_spec(local, artifact, identical, listed_live), - // Never a move backward: a local entry strictly newer than the artifact's is kept. - (local is At && artifact is At && local->At_0 is Some && artifact->At_0 is Some + r == restore_key_spec(local, artifact, identical, listed_live, local_known), + // A fold of another incarnation has entries whose revision numbers mean nothing here: the restore makes it the + // artifact's, key for key. + !local_known ==> (r is TakeArtifact <==> artifact is At), + !local_known ==> (r is Delete <==> (local is At && artifact is Absent)), + // Never a move backward: a known local entry strictly newer than the artifact's is kept. + (local_known && local is At && artifact is At && local->At_0 is Some && artifact->At_0 is Some && local->At_0->Some_0 > artifact->At_0->Some_0) ==> r is Keep, - // Never a phantom delete: a key the bucket lists live is not deleted. - listed_live ==> !(r is Delete), - // A delete needs a local entry the artifact lacks. - r is Delete ==> (local is At && artifact is Absent && !listed_live), + // Never a phantom delete: a key of a known fold that the bucket lists live is not deleted. + (local_known && listed_live) ==> !(r is Delete), + // A delete needs a local entry the artifact lacks (and, of a known fold, the bucket not listing it live). + r is Delete ==> (local is At && artifact is Absent && (!listed_live || !local_known)), // The artifact's entry is taken only if it has one. r is TakeArtifact ==> artifact is At, // Nothing on either side: nothing to do. @@ -566,6 +625,15 @@ pub fn restore_key( (local, artifact) }; let listed_live = listed_live && !cfg!(feature = "mut_restore_ignores_listing"); + // Mutation (model tests only): trust a fold of another incarnation (the pre-fix restore). + let local_known = local_known || cfg!(feature = "mut_restore_trusts_foreign"); + if !local_known { + return match (local, artifact) { + (_, KeyState::At(_)) => KeyRestore::TakeArtifact, + (KeyState::At(_), KeyState::Absent) => KeyRestore::Delete, + (KeyState::Absent, KeyState::Absent) => KeyRestore::Keep, + }; + } match (local, artifact) { (KeyState::At(Some(l)), KeyState::At(Some(a))) if l != a => { if l > a { @@ -602,7 +670,15 @@ pub open spec fn restore_key_spec( artifact: KeyState, identical: bool, listed_live: bool, + local_known: bool, ) -> KeyRestore { + if !local_known { + match (local, artifact) { + (_, KeyState::At(_)) => KeyRestore::TakeArtifact, + (KeyState::At(_), KeyState::Absent) => KeyRestore::Delete, + (KeyState::Absent, KeyState::Absent) => KeyRestore::Keep, + } + } else { match (local, artifact) { (KeyState::At(Some(l)), KeyState::At(Some(a))) if l != a => { if l > a { KeyRestore::Keep } else { KeyRestore::TakeArtifact } @@ -612,6 +688,7 @@ pub open spec fn restore_key_spec( (KeyState::At(_), KeyState::Absent) => if listed_live { KeyRestore::Keep } else { KeyRestore::Delete }, (KeyState::Absent, KeyState::Absent) => KeyRestore::Keep, } + } } /// Can a resume gap that looks expired (the log's first retained revision is @@ -665,27 +742,48 @@ mod tests { #[test] fn publish_guard_boundaries() { let absent = PointerState::Absent; - let corrupt = PointerState::Present { rank: None }; - let at = |r| PointerState::Present { rank: Some(r) }; - assert!(pointer_publish_allowed(&absent, 0)); - assert!(pointer_publish_allowed(&corrupt, 0)); - assert!(pointer_publish_allowed(&at(5), 5), "equal republishes"); - assert!(pointer_publish_allowed(&at(5), 6)); - assert!(!pointer_publish_allowed(&at(5), 4), "stale is refused"); + let corrupt = PointerState::Present { at: None }; + let at = |origin, rank| PointerState::Present { + at: Some(Pos { origin, rank }), + }; + let pos = |origin, rank| Pos { origin, rank }; + assert!(pointer_publish_allowed(&absent, pos(1, 0))); + assert!(pointer_publish_allowed(&corrupt, pos(1, 0))); + assert!( + pointer_publish_allowed(&at(1, 5), pos(1, 5)), + "equal republishes" + ); + assert!(pointer_publish_allowed(&at(1, 5), pos(1, 6))); + assert!( + !pointer_publish_allowed(&at(1, 5), pos(1, 4)), + "stale is refused" + ); + // A dead incarnation's pointer, ranked above the new head, is replaced... + assert!(pointer_publish_allowed(&at(1, 500), pos(2, 3))); + // ...and never replaces the newer incarnation's. + assert!(!pointer_publish_allowed(&at(2, 3), pos(1, 500))); + // A pointer that records no incarnation is older than every recorded one. + assert!(pointer_publish_allowed(&at(0, 500), pos(2, 3))); + assert!(!pointer_publish_allowed(&at(2, 3), pos(0, 500))); } #[test] fn prune_guard_boundaries() { + let pos = |origin, rank| Some(Pos { origin, rank }); + let ptr = Pos { origin: 2, rank: 5 }; // Strictly below, aged, not the target: prunable. - assert!(payload_prunable(Some(4), 5, false, true)); - // Equal rank is NOT prunable — it is still publishable (>= guard). - assert!(!payload_prunable(Some(5), 5, false, true)); - assert!(!payload_prunable(Some(6), 5, false, true)); - // The pointer's own target and unparseable ranks are never prunable. - assert!(!payload_prunable(Some(4), 5, true, true)); - assert!(!payload_prunable(None, 5, false, true)); + assert!(payload_prunable(pos(2, 4), ptr, false, true)); + // Equal position is NOT prunable: it is still publishable (>= guard). + assert!(!payload_prunable(pos(2, 5), ptr, false, true)); + assert!(!payload_prunable(pos(2, 6), ptr, false, true)); + // An older incarnation is below, whatever its revision; a newer one is above. + assert!(payload_prunable(pos(1, 500), ptr, false, true)); + assert!(!payload_prunable(pos(3, 1), ptr, false, true)); + // The pointer's own target and unparseable names are never prunable. + assert!(!payload_prunable(pos(2, 4), ptr, true, true)); + assert!(!payload_prunable(None, ptr, false, true)); // Grace window holds everything. - assert!(!payload_prunable(Some(4), 5, false, false)); + assert!(!payload_prunable(pos(2, 4), ptr, false, false)); } #[test] @@ -792,28 +890,60 @@ mod tests { use KeyRestore::*; use KeyState::*; assert_eq!( - restore_key(At(Some(5)), At(Some(3)), false, false), + restore_key(At(Some(5)), At(Some(3)), false, false, true), Keep, "local newer" ); assert_eq!( - restore_key(At(Some(3)), At(Some(5)), false, false), + restore_key(At(Some(3)), At(Some(5)), false, false, true), TakeArtifact ); assert_eq!( - restore_key(At(Some(3)), At(Some(3)), true, false), + restore_key(At(Some(3)), At(Some(3)), true, false, true), Keep, "identical" ); - assert_eq!(restore_key(At(None), At(None), false, false), TakeArtifact); - assert_eq!(restore_key(Absent, At(Some(1)), false, false), TakeArtifact); assert_eq!( - restore_key(At(Some(1)), Absent, false, true), + restore_key(At(None), At(None), false, false, true), + TakeArtifact + ); + assert_eq!( + restore_key(Absent, At(Some(1)), false, false, true), + TakeArtifact + ); + assert_eq!( + restore_key(At(Some(1)), Absent, false, true, true), Keep, "listed live" ); - assert_eq!(restore_key(At(Some(1)), Absent, false, false), Delete); - assert_eq!(restore_key(Absent, Absent, false, true), Keep); + assert_eq!(restore_key(At(Some(1)), Absent, false, false, true), Delete); + assert_eq!(restore_key(Absent, Absent, false, true, true), Keep); + } + + #[test] + fn restore_key_over_an_unknown_fold_is_the_artifacts() { + use KeyRestore::*; + use KeyState::*; + // A local entry the old stream numbered above the artifact's is not newer. + assert_eq!( + restore_key(At(Some(500)), At(Some(3)), false, false, false), + TakeArtifact + ); + // Even when identical: nothing is kept on a foreign claim. + assert_eq!( + restore_key(At(Some(3)), At(Some(3)), true, false, false), + TakeArtifact + ); + // The bucket listing the key proves nothing about an entry of another stream. + assert_eq!( + restore_key(At(Some(500)), Absent, false, true, false), + Delete + ); + assert_eq!(restore_key(Absent, Absent, false, true, false), Keep); + assert_eq!( + restore_key(Absent, At(Some(1)), false, false, false), + TakeArtifact + ); } #[test] diff --git a/src/kernels/transport_proofs.rs b/src/kernels/transport_proofs.rs index e1ff3a6..0bd15e3 100644 --- a/src/kernels/transport_proofs.rs +++ b/src/kernels/transport_proofs.rs @@ -5,7 +5,7 @@ //! //! # The world //! -//! The object store holds immutable, content-addressed payload objects (`-`: [`Payload`]) and one +//! The object store holds immutable, content-addressed payload objects (`--`: [`Payload`]) and one //! pointer object, swapped by compare-and-swap (`transport::swap_pointer`; [`TS::ver`] counts successful swaps, and a CAS only //! succeeds against the version the publisher read). An exporter runs `Upload`, then reads the pointer and applies the guard //! (`Observe`), then swaps (`Swap`); a refused guard ends its round, a lost CAS re-reads. A pruner reads the pointer once and @@ -16,19 +16,28 @@ //! //! * **O1** a payload path names its content for ever (content addressing; a hash collision is the only way to break it); //! * **O2** the pointer object is written only by [`Act::Swap`] (nothing else deletes or rewrites it); -//! * **O3** a compare-and-swap succeeds exactly when the object is unchanged since the read (`ver`). +//! * **O3** a compare-and-swap succeeds exactly when the object is unchanged since the read (`ver`); +//! * **O4** the stream incarnations of one bucket are ordered by creation time: a recreated stream is created later (the +//! incarnation is the creation time in Unix ns; the order of [`Pos`]). use crate::kernels::protocol::*; use vstd::prelude::*; verus! { -/// A payload object's address: the cursor's rank and the digest of the manifest (which commits to the content). +/// A payload object's address: the cursor's incarnation and rank (the file name records both) and the digest of the manifest +/// (which commits to the content). pub struct Payload { + pub origin: u64, pub rank: u64, pub digest: nat, } +/// The payload's place in the artifact order. +pub open spec fn pos(p: Payload) -> Pos { + Pos { origin: p.origin, rank: p.rank } +} + /// One actor of the protocol, with what it has read so far. pub enum Actor { Idle, @@ -36,14 +45,14 @@ pub enum Actor { Uploaded { p: Payload }, /// An exporter that read the pointer (`st`, at swap-version `ver`) and the guard admitted its candidate. Observed { p: Payload, st: PointerState, ver: nat }, - /// A pruner that read the pointer's rank `pr` (and its target `keep`). - Pruning { pr: u64, keep: Payload }, + /// A pruner that read the pointer's position `pr` (and its target `keep`). + Pruning { pr: Pos, keep: Payload }, /// A fetcher that read the pointer's target `t`. Fetching { t: Payload }, } pub struct TS { - /// The pointer's target payload, once one is published. Its rank is the target's rank. + /// The pointer's target payload, once one is published. Its position is the target's. pub ptr: Option, /// Successful swaps so far. pub ver: nat, @@ -55,7 +64,7 @@ pub struct TS { pub open spec fn pstate(ptr: Option) -> PointerState { match ptr { None => PointerState::Absent, - Some(p) => PointerState::Present { rank: Some(p.rank) }, + Some(p) => PointerState::Present { at: Some(pos(p)) }, } } @@ -95,7 +104,7 @@ pub open spec fn enabled(s: TS, a: Act) -> bool { Act::PruneRead(i) => valid(s, i) && actor(s, i) is Idle && s.ptr is Some, Act::Delete(i, o) => { valid(s, i) && actor(s, i) is Pruning && s.objs.contains(o) - && prunable_spec(Some(o.rank), actor(s, i)->Pruning_pr, o == actor(s, i)->Pruning_keep, true) + && prunable_spec(Some(pos(o)), actor(s, i)->Pruning_pr, o == actor(s, i)->Pruning_keep, true) }, Act::FetchRead(i) => valid(s, i) && actor(s, i) is Idle && s.ptr is Some, Act::FetchGet(i) => valid(s, i) && actor(s, i) is Fetching, @@ -108,7 +117,7 @@ pub open spec fn step(s: TS, a: Act) -> TS { Act::Observe(i) => { let p = actor(s, i)->Uploaded_p; let st = pstate(s.ptr); - if publish_allowed_spec(st, p.rank) { + if publish_allowed_spec(st, pos(p)) { TS { actors: s.actors.update(i, Actor::Observed { p, st, ver: s.ver }), ..s } } else { // Refused (`SupersededByNewer`): the round ends, nothing changes. @@ -122,7 +131,7 @@ pub open spec fn step(s: TS, a: Act) -> TS { Act::Reread(i) => TS { actors: s.actors.update(i, Actor::Uploaded { p: actor(s, i)->Observed_p }), ..s }, Act::PruneRead(i) => { let t = s.ptr->Some_0; - TS { actors: s.actors.update(i, Actor::Pruning { pr: t.rank, keep: t }), ..s } + TS { actors: s.actors.update(i, Actor::Pruning { pr: pos(t), keep: t }), ..s } }, Act::Delete(i, o) => TS { objs: s.objs.remove(o), ..s }, Act::FetchRead(i) => TS { actors: s.actors.update(i, Actor::Fetching { t: s.ptr->Some_0 }), ..s }, @@ -140,17 +149,17 @@ pub open spec fn actor_ok(s: TS, a: Actor) -> bool { match a { Actor::Idle => true, // An uploaded payload exists, or was pruned because the pointer is strictly past it. - Actor::Uploaded { p } => s.objs.contains(p) || (s.ptr is Some && p.rank < s.ptr->Some_0.rank), + Actor::Uploaded { p } => s.objs.contains(p) || (s.ptr is Some && pos_lt(pos(p), pos(s.ptr->Some_0))), Actor::Observed { p, st, ver } => { - &&& publish_allowed_spec(st, p.rank) + &&& publish_allowed_spec(st, pos(p)) &&& ver <= s.ver // Same as `Uploaded`, whatever the version: a lost CAS goes back to `Uploaded`. - &&& (s.objs.contains(p) || (s.ptr is Some && p.rank < s.ptr->Some_0.rank)) + &&& (s.objs.contains(p) || (s.ptr is Some && pos_lt(pos(p), pos(s.ptr->Some_0)))) // The read is current while the version is: so the guard's verdict still stands. &&& (ver == s.ver ==> st == pstate(s.ptr)) }, - Actor::Pruning { pr, keep } => s.ptr is Some && pr <= s.ptr->Some_0.rank, - Actor::Fetching { t } => s.objs.contains(t) || (s.ptr is Some && t.rank < s.ptr->Some_0.rank), + Actor::Pruning { pr, keep } => s.ptr is Some && !pos_lt(pos(s.ptr->Some_0), pr), + Actor::Fetching { t } => s.objs.contains(t) || (s.ptr is Some && pos_lt(pos(t), pos(s.ptr->Some_0))), } } @@ -192,7 +201,7 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) let pp = actor(s, i)->Uploaded_p; if j != i { assert(s1.actors[j] == s.actors[j]); - } else if publish_allowed_spec(pstate(s.ptr), pp.rank) { + } else if publish_allowed_spec(pstate(s.ptr), pos(pp)) { assert(actor_ok(s, s.actors[i])); // Admitted: the candidate is not below the pointer, so it was not pruned: it exists. assert(s.objs.contains(pp)); @@ -221,9 +230,9 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) let pr = actor(s, i)->Pruning_pr; let t = s.ptr->Some_0; assert(actor_ok(s, s.actors[i])); - // `o` is strictly below the pruner's read of the pointer, which is at most the pointer's rank now. - assert(o.rank < pr); - assert(pr <= t.rank); + // `o` is strictly below the pruner's read of the pointer, which is at most the pointer's position now. + assert(pos_lt(pos(o), pr)); + assert(!pos_lt(pos(t), pr)); }, Act::FetchRead(i) => { if j != i { @@ -245,7 +254,7 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) Act::Delete(i, o) => { let pr = actor(s, i)->Pruning_pr; assert(actor_ok(s, s.actors[i])); - assert(o.rank < pr); + assert(pos_lt(pos(o), pr)); assert(o != s.ptr->Some_0); }, _ => {}, @@ -255,7 +264,7 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) /// THEOREM (the pointer never regresses, for every interleaving of N exporters): every step either leaves the pointer alone or -/// moves it to a payload whose rank is at least the old one, and a published pointer is never removed. This is +/// moves it to a payload whose position (incarnation, then revision) is at least the old one, and a published pointer is never removed. This is /// `a_publish_never_regresses_the_pointer` lifted from one decision to the whole protocol: the guard decided on a read, but the /// swap succeeds only against that read (O3), so the read is the pointer being replaced. pub proof fn the_pointer_never_regresses(s: TS, a: Act) @@ -263,17 +272,17 @@ pub proof fn the_pointer_never_regresses(s: TS, a: Act) inv(s), enabled(s, a), ensures - s.ptr is Some ==> step(s, a).ptr is Some && step(s, a).ptr->Some_0.rank >= s.ptr->Some_0.rank, + s.ptr is Some ==> step(s, a).ptr is Some && !pos_lt(pos(step(s, a).ptr->Some_0), pos(s.ptr->Some_0)), ({ let ps = pstate(s.ptr); let q = pstate(step(s, a).ptr); - (ps is Present && ps->Present_rank is Some) ==> q is Present && q->Present_rank is Some - && q->Present_rank->Some_0 >= ps->Present_rank->Some_0 }), + (ps is Present && ps->Present_at is Some) ==> q is Present && q->Present_at is Some + && !pos_lt(q->Present_at->Some_0, ps->Present_at->Some_0) }), { match a { Act::Swap(i) => { assert(actor_ok(s, s.actors[i])); let p = actor(s, i)->Observed_p; if s.ptr is Some { - a_publish_never_regresses_the_pointer(pstate(s.ptr), p.rank); + a_publish_never_regresses_the_pointer(pstate(s.ptr), pos(p)); } }, _ => {}, @@ -281,7 +290,7 @@ pub proof fn the_pointer_never_regresses(s: TS, a: Act) } /// THEOREM (prune never deletes the pointer's target): at any moment, whatever a pruner read earlier, the object it is allowed to -/// delete is not the pointer's current target. The pruner's read of the pointer is stale, but the pointer's rank only grows, and +/// delete is not the pointer's current target. The pruner's read of the pointer is stale, but the pointer's position only grows, and /// the guard deletes only strictly below the pruner's read (`the_target_and_unknown_objects_are_never_pruned` is the guard's own /// half). pub proof fn prune_never_deletes_the_pointers_target(s: TS, i: int, o: Payload) @@ -311,7 +320,7 @@ pub proof fn a_fetch_gets_its_payload_or_a_detected_miss(s: TS, i: int) let t = actor(s, i)->Fetching_t; match fetched(s, t) { Some(x) => x == t, - None => s.ptr is Some && t.rank < s.ptr->Some_0.rank && s.objs.contains(s.ptr->Some_0), + None => s.ptr is Some && pos_lt(pos(t), pos(s.ptr->Some_0)) && s.objs.contains(s.ptr->Some_0), } }), { @@ -319,7 +328,7 @@ pub proof fn a_fetch_gets_its_payload_or_a_detected_miss(s: TS, i: int) } /// THEOREM (liveness: a refused fetch retries): after a miss, a fresh read names the pointer's current target, which exists, so -/// the get answers it. The only way to miss again is for the pointer to move again, strictly upward. Rank: the pointer's rank +/// the get answers it. The only way to miss again is for the pointer to move again, strictly upward. Rank: the pointer's position /// (monotone), unbounded, but each miss is paid for by one publish, so a fetch retries at most once per publish. Fairness /// assumption: the publishers do not publish for ever between a read and its get (the environment, not this code). pub proof fn a_fresh_read_never_misses_without_a_publish(s: TS, i: int) diff --git a/src/kv.rs b/src/kv.rs index 0c1a9ac..8e2e095 100644 --- a/src/kv.rs +++ b/src/kv.rs @@ -190,6 +190,16 @@ impl WatchCursor { pub(crate) fn rank(&self) -> u64 { self.as_u64().unwrap_or(0) } + + /// The cursor's place in the artifact order: its stream incarnation (0 + /// when it records none: older than any recorded one), then its + /// [`rank`](Self::rank). The ONE place a cursor becomes a [`Pos`]. + pub(crate) fn position(&self) -> crate::protocol::Pos { + crate::protocol::Pos { + origin: self.origin().unwrap_or(0), + rank: self.rank(), + } + } } /// Error type for KV operations. diff --git a/src/repair.rs b/src/repair.rs index fced9a6..46a4478 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -292,6 +292,11 @@ pub(crate) fn disjoint(prefixes: &[String]) -> Vec { /// and only these need checking against the listing. Out-of-scope keys are /// untouched on both sides. /// +/// `local_known`: the local fold is of THIS stream, so its entries' revisions +/// are this log's. A fold of another incarnation (its cursor was foreign) is +/// replaced by the artifact's key for key: revision numbers of another stream +/// decide nothing ([`restore_key`]). +/// /// Memory is the returned set, which holds the keys deleted between the local /// fold's cursor and the artifact's: never the fold, the artifact, or the /// bucket's listing. @@ -299,6 +304,7 @@ pub(crate) fn restore_diff( local: &S, artifact: &S, prefixes: &[String], + local_known: bool, mut take: impl FnMut(String) -> Result<(), SnapshotError>, ) -> Result, SnapshotError> { let mut candidates = HashSet::new(); @@ -314,7 +320,7 @@ pub(crate) fn restore_diff( ), None => (KeyState::Absent, false), }; - if restore_key(state, at, identical, false) == KeyRestore::TakeArtifact { + if restore_key(state, at, identical, false, local_known) == KeyRestore::TakeArtifact { take(entry.key)?; } Ok(()) @@ -324,7 +330,7 @@ pub(crate) fn restore_diff( // artifact is read only for keys that could be deleted. local.for_each_in_range(&prefix, |entry| { let state = KeyState::At(entry.version.as_u64()); - if restore_key(state, KeyState::Absent, false, false) == KeyRestore::Delete + if restore_key(state, KeyState::Absent, false, false, local_known) == KeyRestore::Delete && artifact.get(&entry.key)?.is_none() { candidates.insert(entry.key); @@ -570,6 +576,8 @@ pub(crate) enum RepairRequest { Relist { reader: Arc, scratch: Option, + /// The fold's cursor was another incarnation's ([`KvError::ForeignCursor`]). + foreign: bool, ack: oneshot::Sender<()>, }, /// The artifact restore: a verified artifact fold, the reader that lists @@ -581,6 +589,8 @@ pub(crate) enum RepairRequest { restored: RestoredFold, reader: Arc, watcher: Arc, + /// The fold's cursor was another incarnation's ([`KvError::ForeignCursor`]). + foreign: bool, reply: oneshot::Sender>, }, } @@ -842,6 +852,10 @@ pub(crate) async fn run_watch( ); note(health, RepairState::Reseeding); foreign = true; + // The eviction memo is a fact about the stream that was + // evicting: the new one's retention is read afresh. + // Mutation (model tests only): keep it (the pre-fix repair). + memo.seen = memo.seen && cfg!(feature = "mut_foreign_keeps_memo"); WatchCursor::none() } Err(KvError::ForeignCursor) => { @@ -867,7 +881,7 @@ pub(crate) async fn run_watch( "watch cursor expired; resyncing stale keys, then falling back to the full re-list" ); note(health, RepairState::Relisting); - resync_stale_keys(reader, scratch, repairs).await?; + resync_stale_keys(reader, scratch, foreign, repairs).await?; if let Some(h) = health { h.repair_done(); } @@ -878,21 +892,28 @@ pub(crate) async fn run_watch( Plan::Restore(reader, source, repairs) => { warn!("watch cursor expired; restoring the fold from the latest artifact"); note(health, RepairState::Restoring); - let restored = - restore_from_artifact(&shared, scope, reader, source, repairs, &cursor, health) - .await - .map_err(|e| match e { - KvError::WatchError(msg) if cursor.is_none() && !foreign => { - KvError::WatchError(format!( - "{msg}. This node has no cursor, so it can only seed from an \ + let restored = restore_from_artifact( + &shared, + scope, + reader, + source, + repairs, + (&cursor, foreign), + health, + ) + .await + .map_err(|e| match e { + KvError::WatchError(msg) if cursor.is_none() && !foreign => { + KvError::WatchError(format!( + "{msg}. This node has no cursor, so it can only seed from an \ artifact. If none exists yet (first deploy onto a bucket that \ already evicted values), start one node with ExpiryRepair::None \ — accepting that values which already aged out are gone — and \ publish an export from it" - )) - } - other => other, - })?; + )) + } + other => other, + })?; // An artifact from a fold that saw eviction carries the memo // (the fold took it with the artifact's cursor). memo.seen |= restored.seen_evicting(); @@ -995,7 +1016,9 @@ async fn restore_from_artifact( reader: &Arc, source: &Arc>, repairs: &mpsc::Sender>, - local: &WatchCursor, + // The fold's cursor (none when foreign), and whether it was another + // incarnation's. + (local, foreign): (&WatchCursor, bool), health: Option<&WatchHealth>, ) -> Result { let prefixes = scope.prefixes(); @@ -1066,6 +1089,7 @@ async fn restore_from_artifact( restored, reader: Arc::clone(reader), watcher: Arc::clone(watcher), + foreign, reply: reply_tx, }) .await @@ -1107,6 +1131,7 @@ fn note(health: Option<&WatchHealth>, state: RepairState) { async fn resync_stale_keys( reader: &Arc, scratch: Option, + foreign: bool, repairs: &mpsc::Sender>, ) -> Result<(), KvError> { let (ack_tx, ack_rx) = oneshot::channel(); @@ -1114,6 +1139,7 @@ async fn resync_stale_keys( .send(RepairRequest::Relist { reader: Arc::clone(reader), scratch, + foreign, ack: ack_tx, }) .await @@ -1184,11 +1210,15 @@ where let Some(RepairRequest::Relist { reader, scratch, + foreign, ack, }) = req.take() else { unreachable!("RunRelist follows a Relist request") }; + if foreign { + fold.forget_cursor(); + } relist(fold, &*reader, scratch, prefixes).await?; // Ack AFTER the deletes are applied: the watch task is holding // the fallback watch until it hears back, which is what orders @@ -1215,12 +1245,17 @@ where restored, reader, watcher, + foreign, reply, }) = req.take() else { unreachable!("CheckAhead follows a Restore request") }; - return restore_request(fold, restored, reader, watcher, reply, prefixes).await; + if foreign { + fold.forget_cursor(); + } + return restore_request(fold, restored, reader, watcher, foreign, reply, prefixes) + .await; } other => unreachable!("fold_in: {other:?}"), } @@ -1238,6 +1273,7 @@ async fn restore_request( restored: RestoredFold, reader: Arc, watcher: Arc, + foreign: bool, reply: oneshot::Sender>, prefixes: &[String], ) -> Result<(), KvError> @@ -1249,6 +1285,10 @@ where O: FnMut(WatchCursor) + Send, { let target = restored.manifest().cursor.clone(); + // A fold of another incarnation (its cursor was foreign, and forgotten): + // the restore replaces it with the artifact's, key for key + // ([`restore_key`]). + let local_known = !foreign; let prefixes = disjoint(prefixes); let max = fold.batch_cap(); let mut restored = Some(restored); @@ -1296,7 +1336,7 @@ where let Some(r) = restored.take() else { unreachable!("the artifact is held until the reply") }; - let (r, spill, deletes) = run_diff(fold, r, &prefixes).await?; + let (r, spill, deletes) = run_diff(fold, r, &prefixes, local_known).await?; restored = Some(r); let has_deletes = !deletes.is_empty(); diff = Some((spill, deletes)); @@ -1310,8 +1350,9 @@ where // current value is a write after the artifact's cursor, which // the resume delivers (`restore_key`'s `listed_live`). A // failed listing fails the watch, like the key-listing - // repair's. - for prefix in &prefixes { + // repair's. A fold that is no position of this stream has no + // such entries to keep: every candidate is deleted. + for prefix in prefixes.iter().filter(|_| local_known) { reader .for_each_key(prefix, &mut |key| { deletes.remove(&key); @@ -1384,6 +1425,7 @@ async fn run_diff( fold: &mut Fold, restored: RestoredFold, prefixes: &[String], + local_known: bool, ) -> Result<(RestoredFold, KeySpill, HashSet), KvError> where U: Send, @@ -1402,7 +1444,7 @@ where let (st, owned, diff) = tokio::task::spawn_blocking(move || { let diff = (|| { let mut spill = KeySpill::new(owned.scratch.as_deref())?; - let candidates = restore_diff(&st, owned.fold(), &scope, |key| { + let candidates = restore_diff(&st, owned.fold(), &scope, local_known, |key| { spill.push(&key).map_err(SnapshotError::from) })?; Ok::<_, SnapshotError>((spill, candidates)) @@ -1728,7 +1770,7 @@ mod tests { live: &HashSet, ) -> Vec { let mut spill = KeySpill::new(None).unwrap(); - let candidates = restore_diff(local, artifact, prefixes, |k| { + let candidates = restore_diff(local, artifact, prefixes, true, |k| { spill.push(&k).map_err(SnapshotError::from) }) .unwrap(); @@ -1779,7 +1821,7 @@ mod tests { 9, ); let mut rewritten = Vec::new(); - let candidates = restore_diff(&local, &artifact, &["node.".to_string()], |k| { + let candidates = restore_diff(&local, &artifact, &["node.".to_string()], true, |k| { rewritten.push(k); Ok(()) }) diff --git a/src/transport.rs b/src/transport.rs index bdefcef..8198d0e 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -5,7 +5,7 @@ //! //! The payload is a **plain tar** of the artifact directory (`MANIFEST.json` //! plus `data/…`) at a **content-addressed** key — -//! `/.payloads/.tar` — so payload +//! `/.payloads/--.tar` — so payload //! objects are write-once: two different artifacts can never collide on a //! key, and re-uploading the same artifact is an idempotent overwrite. No //! compression layer: fjall/RocksDB payload files are already lz4/zstd @@ -68,7 +68,7 @@ use crate::artifact::{ }; use crate::export_lease::ExportLease; use crate::kv::WatchCursor; -use crate::protocol::{PointerState, payload_prunable, pointer_publish_allowed}; +use crate::protocol::{PointerState, Pos, payload_prunable, pointer_publish_allowed}; use crate::repair::{RestoreSource, RestoredFold}; use crate::snapshot::SnapshotError; @@ -255,11 +255,14 @@ impl ObjectStoreTransport { fn payload_path(&self, key: &str, cursor: &WatchCursor, pointer_bytes: &[u8]) -> ObjPath { let digest = blake3::hash(pointer_bytes); let hex = hex_encode(&digest.as_bytes()[..8]); - ObjPath::from(format!( - "{}/{key}.payloads/{:016x}-{hex}.tar", - self.prefix, - cursor.rank() - )) + // The name carries the cursor's incarnation (when it records one) as + // well as its revision, so the prune guard can order a payload against + // the pointer ([`payload_position`]). + let name = match cursor.origin() { + Some(origin) => format!("{origin:016x}-{:016x}-{hex}.tar", cursor.rank()), + None => format!("{:016x}-{hex}.tar", cursor.rank()), + }; + ObjPath::from(format!("{}/{key}.payloads/{name}", self.prefix)) } fn manifest_path(&self, key: &str) -> ObjPath { @@ -329,9 +332,9 @@ impl ObjectStoreTransport { // rank-less and replaced. let existing = manifest_from_slice(&bytes).ok(); let observed = PointerState::Present { - rank: existing.as_ref().map(|m| m.cursor.rank()), + at: existing.as_ref().map(|m| m.cursor.position()), }; - if !pointer_publish_allowed(&observed, new_cursor.rank()) { + if !pointer_publish_allowed(&observed, new_cursor.position()) { let existing = existing.expect("refusal implies a parseable, newer pointer"); return Ok(PublishOutcome::SupersededByNewer { @@ -625,7 +628,7 @@ impl ArtifactTransport for ObjectStoreTransport { return Ok(0); }; let keep = self.payload_path(key, ¤t.cursor, &pointer); - let pointer_rank = current.cursor.rank(); + let pointer = current.cursor.position(); let cutoff_millis = std::time::SystemTime::now() .checked_sub(grace) .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) @@ -645,14 +648,10 @@ impl ArtifactTransport for ObjectStoreTransport { // impossibility argument live). The grace period remains as // defense in depth for in-flight downloads holding stale // pointer reads. - let payload_rank = meta - .location - .filename() - .and_then(|f| f.split('-').next()) - .and_then(|h| u64::from_str_radix(h, 16).ok()); + let payload = meta.location.filename().and_then(payload_position); if payload_prunable( - payload_rank, - pointer_rank, + payload, + pointer, meta.location == keep, meta.last_modified.timestamp_millis() <= cutoff_millis, ) { @@ -666,6 +665,31 @@ impl ArtifactTransport for ObjectStoreTransport { } } +/// The position a payload's file name records ([`ObjectStoreTransport::payload_path`]): +/// `--.tar`, or `-.tar` for a cursor that +/// recorded no incarnation (origin 0). Anything else is not ours: `None`, and +/// never pruned. +fn payload_position(name: &str) -> Option { + let hex = |h: &str| { + (h.len() == 16) + .then(|| u64::from_str_radix(h, 16).ok()) + .flatten() + }; + let mut parts = name.split('-'); + let (first, second, third) = (parts.next()?, parts.next()?, parts.next()); + match third { + None => Some(Pos { + origin: 0, + rank: hex(first)?, + }), + Some(_) if parts.next().is_none() => Some(Pos { + origin: hex(first)?, + rank: hex(second)?, + }), + Some(_) => None, + } +} + fn map_obj(e: object_store::Error) -> SnapshotError { match e { object_store::Error::NotFound { path, .. } => { diff --git a/tests/model.rs b/tests/model.rs index d6a1998..48a6758 100644 --- a/tests/model.rs +++ b/tests/model.rs @@ -488,6 +488,14 @@ impl SnapshotProtocol { } } +/// A cursor in the artifact order: this model has one incarnation. +fn pos(cursor: u8) -> slipstream::protocol::Pos { + slipstream::protocol::Pos { + origin: 1, + rank: u64::from(cursor), + } +} + impl Model for SnapshotProtocol { type State = St; type Action = Act; @@ -649,14 +657,11 @@ impl Model for SnapshotProtocol { let observed = match s.manifest { None => slipstream::protocol::PointerState::Absent, Some(m) => slipstream::protocol::PointerState::Present { - rank: Some(m.cursor as u64), + at: Some(pos(m.cursor)), }, }; let allowed = self.mutation == Mutation::LwwPointer - || slipstream::protocol::pointer_publish_allowed( - &observed, - a.cursor as u64, - ); + || slipstream::protocol::pointer_publish_allowed(&observed, pos(a.cursor)); if allowed { if let Some(m) = s.manifest && m.cursor > a.cursor @@ -731,8 +736,8 @@ impl Model for SnapshotProtocol { } else { s.uploaded.retain(|a| { !slipstream::protocol::payload_prunable( - Some(a.cursor as u64), - keep.cursor as u64, + Some(pos(a.cursor)), + pos(keep.cursor), *a == keep, true, ) diff --git a/tests/model_fleet.rs b/tests/model_fleet.rs index a84c44d..a2d4a10 100644 --- a/tests/model_fleet.rs +++ b/tests/model_fleet.rs @@ -10,8 +10,10 @@ //! propagate through artifacts to every node that restores. Here the nodes //! ARE the exporters, and the checker proves the induction: //! -//! - **Every published artifact is the truth at its cursor.** -//! - **Every live node's fold is the truth at its cursor.** +//! - **Every published artifact is the truth at its cursor** (on this model's +//! one key: see the bounds below; what the code keeps on many keys is the +//! weaker "complete" statement). +//! - **Every live node's fold is the truth at its cursor** (same). //! - **Every maximal run ends with every live node converged** to every //! write minus every real delete. A node may instead be fail-stopped — and //! then only because a write aged out before ANY node folded it: no fold @@ -42,17 +44,22 @@ //! - on MANY keys the invariant is "complete together with the log after the cursor", //! not "equals the truth at the cursor": a restore keeps a stale entry of a key the //! bucket lists live (`restore_key`), and the resume delivers the later write -//! (`fleet_proofs::finding_f3_*`). With one key that entry is the truth, so the two -//! statements coincide here; -//! - a restore over a fold of a RECREATED stream keeps stale entries by revision -//! number (`finding_f2_*`), and a dead incarnation's pointer refuses every publish -//! of the new stream (`finding_f1_*`); this model has one incarnation; +//! (`fleet_proofs::finding_f3_*`). The two `always` properties below state the +//! stronger "equals the truth at its cursor" and PASS ONLY BECAUSE of this model's +//! bounds: one key, and an atomic repair. With a second key the stronger statement +//! is false of the shipped code (F3), so this model proves the one-key instance, and +//! `fleet_proofs::every_live_nodes_fold_is_complete_at_its_cursor` (despite its +//! name: complete, exact at the head) proves the statement the code keeps; +//! - recreated streams, which this model does not have (one incarnation): a restore +//! over a fold of another incarnation takes the artifact key for key (`finding_f2_*`), +//! a dead incarnation's pointer is replaced by the new stream's first publish +//! (`finding_f1_*`), and a foreign cursor forgets the eviction memo (`finding_f4_*`); //! - liveness as a ranking function under named fairness axioms (`nrank`). //! //! The proof's mutations are the same `mut_*` features: `mise run verify -- --features mut_x`. use slipstream::protocol::{ - PointerState, RepairMode, RepairPlan, cursorless_start_needs_repair, listing_is_truth, + PointerState, Pos, RepairMode, RepairPlan, cursorless_start_needs_repair, listing_is_truth, plan_repair, pointer_publish_allowed, restore_allowed, resume_window_ok, }; use stateright::{Checker, Model, Property}; @@ -222,13 +229,19 @@ impl Model for Fleet { acts.push(Act::Expire(i)); } let current = s.pointer.map(|(c, _)| PointerState::Present { - rank: Some(c as u64), + at: Some(Pos { + origin: 1, + rank: c as u64, + }), }); if n.cursor >= 1 && s.pointer.is_none_or(|(c, _)| c < n.cursor) && pointer_publish_allowed( ¤t.unwrap_or(PointerState::Absent), - n.cursor as u64, + Pos { + origin: 1, + rank: n.cursor as u64, + }, ) { acts.push(Act::Publish(i)); diff --git a/tests/model_repair.rs b/tests/model_repair.rs index 21ce75f..29f89e1 100644 --- a/tests/model_repair.rs +++ b/tests/model_repair.rs @@ -425,7 +425,14 @@ impl RepairModel { None => KeyState::Absent, }; let identical = s.store_val.is_some() && s.store_val == want; - restore_key(state(s.store_val), state(want), identical, listed_live) + // One incarnation here: the fold is this stream's (`tests/model_incarnation.rs`, `tests/recreated_fleet.rs`). + restore_key( + state(s.store_val), + state(want), + identical, + listed_live, + true, + ) } fn upd(target: u8, s: &St, r: KeyRestore) -> Option { diff --git a/tests/recreated_fleet.rs b/tests/recreated_fleet.rs index a168361..bf692e6 100644 --- a/tests/recreated_fleet.rs +++ b/tests/recreated_fleet.rs @@ -264,7 +264,10 @@ async fn a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish() { wait_applied(&a, 20).await; assert_eq!(fleet.publish(&a, "art-a").await, PublishOutcome::Published); stop(a).await.expect("clean stop"); - assert_eq!(fleet.transport.manifest(KEY).await.unwrap().cursor.as_u64(), Some(20)); + assert_eq!( + fleet.transport.manifest(KEY).await.unwrap().cursor.as_u64(), + Some(20) + ); let (_c, new) = recreate(&fleet.nats, plain()).await; let mut head = 0; @@ -313,7 +316,10 @@ async fn restore_over_a_foreign_fold(new_head: u64) { } let exporter = spawn_node(&new, fleet.open("x").1, None, ExpiryRepair::None); wait_applied(&exporter, head).await; - assert_eq!(fleet.publish(&exporter, "art").await, PublishOutcome::Published); + assert_eq!( + fleet.publish(&exporter, "art").await, + PublishOutcome::Published + ); stop(exporter).await.expect("clean stop"); let (cursor, fold) = fleet.open("a"); From 35440e079f69686547e2b10f6d5229c5f9d1b8fd Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 19:07:07 -0800 Subject: [PATCH 4/7] tests: a torn first checkpoint across a recreation (red before provenance) --- tests/recreated_fleet.rs | 82 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/tests/recreated_fleet.rs b/tests/recreated_fleet.rs index bf692e6..96bcac2 100644 --- a/tests/recreated_fleet.rs +++ b/tests/recreated_fleet.rs @@ -382,3 +382,85 @@ async fn the_old_streams_eviction_memo_does_not_distrust_the_new_streams_listing "the new stream never evicted: {c:?}" ); } + +/// A fold of the old stream whose FIRST checkpoint tore: its data is on disk, +/// its final cursor record is not. Nothing but the fold's own record can say +/// which stream that data is of. +fn tear_the_cursor(fleet: &Fleet, name: &str) { + let (cursor, _) = fleet.open(name); + let record = 4 + 1 + 1 + cursor.to_bytes().len() as u64; + let path = fleet.path(name); + let file = std::fs::OpenOptions::new().write(true).open(&path).unwrap(); + let len = file.metadata().unwrap().len(); + file.set_len(len - record).unwrap(); + let (torn, _) = fleet.open(name); + assert!(torn.is_none(), "the cursor is torn off: {torn:?}"); +} + +/// The torn fold of the old stream: `k` at revision 18 ("old"), cursor 20. +async fn torn_old_fold(fleet: &Fleet) -> Arc { + let (_c, old) = open_bucket(&fleet.nats, plain()).await; + let a = spawn_node(&old, fleet.open("a").1, None, ExpiryRepair::None); + for i in 0..17 { + put(&old, &format!("o.{i}"), "o").await; + } + assert_eq!(put(&old, "k", "old").await, 18); + put(&old, "o.17", "o").await; + put(&old, "o.18", "o").await; + wait_applied(&a, 20).await; + stop(a).await.expect("clean stop"); + tear_the_cursor(fleet, "a"); + old +} + +/// Data and no cursor, across a recreation: the fold's own record of its +/// stream says it is another's, so a restore replaces it key for key. Without +/// the record the data's provenance is unknown, and the restore kept `k` at +/// the old stream's higher revision. +#[tokio::test(flavor = "multi_thread")] +async fn a_torn_first_checkpoint_of_the_old_stream_is_foreign_to_the_recreated_one() { + let fleet = Fleet::new().await; + let _old = torn_old_fold(&fleet).await; + let (_c, new) = recreate(&fleet.nats, plain()).await; + put(&new, "k", "new").await; + let mut head = 1; + for i in 1..25 { + head = put(&new, &format!("n.{i}"), "n").await; + } + let exporter = spawn_node(&new, fleet.open("x").1, None, ExpiryRepair::None); + wait_applied(&exporter, head).await; + assert_eq!( + fleet.publish(&exporter, "art").await, + PublishOutcome::Published + ); + stop(exporter).await.expect("clean stop"); + + let (cursor, fold) = fleet.open("a"); + let node = spawn_node(&new, fold, Some(cursor), fleet.restore_only(&new)); + wait_applied(&node, head).await; + stop(node).await.expect("clean stop"); + assert_fold_is_bucket(&fleet.path("a"), &new).await; +} + +/// The same torn fold on the SAME stream is its own: its newer entries are +/// kept (a restore never moves a key backward), and the fold ends exactly the +/// bucket. +#[tokio::test(flavor = "multi_thread")] +async fn a_torn_first_checkpoint_of_this_stream_is_trusted() { + let fleet = Fleet::new().await; + let old = torn_old_fold(&fleet).await; + put(&old, "late", "l").await; + let head = put(&old, "k2", "x").await; + let exporter = spawn_node(&old, fleet.open("x").1, None, ExpiryRepair::None); + wait_applied(&exporter, head).await; + assert_eq!( + fleet.publish(&exporter, "art").await, + PublishOutcome::Published + ); + stop(exporter).await.expect("clean stop"); + let (cursor, fold) = fleet.open("a"); + let node = spawn_node(&old, fold, Some(cursor), fleet.restore_only(&old)); + wait_applied(&node, head).await; + stop(node).await.expect("clean stop"); + assert_fold_is_bucket(&fleet.path("a"), &old).await; +} From 2336268db7534f462509475740b9210d08a90fbf Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 19:44:17 -0800 Subject: [PATCH 5/7] F1 without a clock axiom (a pointer of another incarnation is replaceable; F1b reported); folds record their stream before data, so a torn first checkpoint is judged, not trusted Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 25 +++--- Cargo.toml | 2 + src/applied.rs | 16 +++- src/kernels/fleet_proofs.rs | 38 +++++++-- src/kernels/protocol.rs | 140 +++++++++++++++++++------------- src/kernels/transport_proofs.rs | 34 ++++---- src/kv.rs | 7 ++ src/repair.rs | 58 +++++++++++-- src/snapshot.rs | 62 ++++++++++++++ tests/repair_dst.rs | 33 ++++++-- tests/snapshot_store.rs | 55 +++++++++++++ 11 files changed, 364 insertions(+), 106 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 99db05e..71b101f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -354,24 +354,26 @@ Every decision the protocol's correctness rests on is a pure function in `src/ke | `plan_repair` | `repair::plan`, `Snapshot::stale_keys` | every model's expiry dispatch | | `cursorless_start_needs_repair` | `repair::run_watch` | `model_repair.rs`, `model_fleet.rs` | | `restore_key` | `repair::restore_diff` | `model_repair.rs`, `fleet_proofs.rs` | +| `cursorless_fold_is_this_stream` | `repair::run_watch` (a fold with data and no cursor) | `tests/recreated_fleet.rs` (live), Verus | **The cursor-authority kernel** (`src/kernels/applied.rs`) is the one stateful kernel: `step(state, event) -> (state, actions)`, no I/O, async or clock. `applied::Fold` turns what it observes (a received update, a flush request, a store result, an export or repair request) into an `Event`, calls `step`, and runs the returned `Action`s through its interpreter; it decides nothing itself. The kernel owns what has no other home: whether a batch is open, whether a stream position is pending, the unsynced eviction memo, the store-failure streak, and where an in-flight flush or resync is. It decides which flush steps run and in which order (domain `apply` before the cursor moves), that a failed store fold re-queues its raw batch at the front (and the streak bound that fail-stops), that an export flushes first, that the resync's ack follows the folded deletes, and the artifact restore's order: ahead check, diff, listing with its window re-check (only when there are delete candidates), chunks folded under the old cursor, the cursor commit, then the reply; a refusal (not ahead, window aged) replies with an error before anything is folded. The restore's phase is kernel state, so an event out of phase is ignored and a restart (a fresh state) re-runs the whole repair. The data (updates, cursors, the store) stay in the shell. The three applied models call it too (`tests/model_applied.rs`, `tests/model_resync_order.rs`, `tests/model_repair.rs`, through `slipstream::cursor_kernel`): they keep only environment state (deliveries, store contents, crashes, the bucket) and feed `step` events. Their mutations are cargo features that break the kernel itself (`mut_drop_failed_batch`, `mut_resume_from_memory`, `mut_no_ack_barrier`, and for the repair steps `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_restore_guard`, `mut_no_listing_recheck`; the protocol-kernel ones `mut_relist_on_evicting`, `mut_unanchored_relist`, `mut_restore_ignores_versions`, `mut_restore_ignores_listing`, `mut_restore_trusts_foreign`, `mut_pointer_ignores_incarnation`, `mut_no_eviction_memo` break `protocol.rs` (and `mut_foreign_keeps_memo` the repair's forgetting of a foreign cursor)); each turns its model red, and they are for model tests only, never production builds. **`pointer_publish_allowed(current: &PointerState, candidate: Pos) → bool`** -The monotonic pointer guard. `Pos` is `(origin, rank)`: the stream incarnation a cursor was taken from (its creation time; 0 for a cursor that records none), then its revision, ordered incarnation first. Returns `true` for an open slot, a corrupt pointer, or a candidate at or above the existing cursor — and `false` exactly when the existing pointer is parseable and strictly newer. +The monotonic pointer guard. `Pos` is `(origin, rank)`: the stream incarnation a cursor was taken from (its creation time; 0 for a cursor that records none) and its revision. Ranks are ordered only within an incarnation; nothing orders two incarnations, and no clock is assumed. Returns `true` for an open slot, a corrupt pointer, a pointer of another incarnation than the candidate's, or a candidate at or above the existing cursor in its own incarnation — and `false` exactly when the existing pointer is parseable, of the candidate's incarnation, and higher. ``` Absent → true (open slot) Present { at: None } → true (corrupt pointer is replaceable, not a wedge) Present { at: Some(p) } - candidate >= p → true ((origin, rank) order) - candidate < p → false (stale publish refused) + other origin → true (a dead incarnation's pointer is replaceable) + same origin, rank >= p → true + same origin, rank < p → false (stale publish refused) ``` -A pointer of a dead incarnation is below every publish of the incarnation that replaced it, whatever its rank, so a recreated bucket's first export replaces it; the guard compared ranks only before, and a dead pointer ranked above the new head refused every publish of the new stream (fleet finding F1). The order across incarnations rests on O4: a recreated stream is created later than the one it replaces. +A pointer of a dead incarnation never refuses a publish of the incarnation that replaced it, whatever its rank, so a recreated bucket's first export replaces it; the guard compared ranks only before, and a dead pointer ranked above the new head refused every publish of the new stream (fleet finding F1). Only one incarnation is live at a time: a slow exporter of the dead stream can replace the live pointer once, the next live publish replaces it, and restorers refuse it meanwhile (`same_incarnation`). The cost (a stale live exporter publishing a payload a prune deleted) is finding F1b below. -Machine-checked as: _"published cursor never regresses"_ (`tests/model.rs`, one incarnation) and, over any number of incarnations, `transport_proofs::the_pointer_never_regresses` and `protocol::a_newer_incarnation_replaces_any_pointer` (Verus). +Machine-checked as: _"published cursor never regresses"_ (`tests/model.rs`, one incarnation) and, within an incarnation `transport_proofs::the_pointer_never_regresses`, and `protocol::a_pointer_of_another_incarnation_never_refuses_a_publish` (liveness, no time axiom; Verus). **`payload_prunable(payload, pointer, is_pointer_target, aged_out) → bool`** @@ -509,16 +511,17 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut **The statement.** `finv`: every node of the current incarnation holds a real fold (every entry a write of the log) that is *complete* at its cursor `c`: equal to the truth at `c` on every key not written after `c`; every published artifact of the current incarnation likewise. Exact equality at `c` is not what the code keeps and is not an invariant (F3): an artifact at `C` is complete together with the log after `C`, and a restore keeps the stale entry of a key the bucket lists live (`restore_key`) because the resume delivers its later write. At the head every key is "not written since", so a converged node holds exactly the truth. The Stateright model (`tests/model_fleet.rs`: one key, atomic repair) states the stronger "equals the truth at its cursor" and passes only because of those bounds; the statement the code keeps is this one. -**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: **O4** the stream incarnations of one bucket are ordered by creation time (a recreated stream is created later; `protocol::Pos`); the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle; a foreign cursor forgets it); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. +**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: **O4** (scope of the transport proofs) the pointer stays in one incarnation: nothing orders two incarnations and no clock is assumed (a pointer of another incarnation is replaceable; F1b is the cost); the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle; a foreign cursor forgets it); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. **Findings the proofs surfaced** (each a Verus-checked concrete state of the shipped decisions, in `fleet_proofs.rs`; F1, F2 and F4 were real bugs, reached against a live nats-server in `tests/recreated_fleet.rs`, and are fixed; the proof no longer carries a premise that excluded them): -- **F1** (`finding_f1_*`) the pointer guard compared ranks only, never the incarnation. A pointer whose artifact was the old stream's, ranked above the new head, refused every publish of the new stream until the head passed it, while `same_incarnation` refused to restore from it: a node that must restore had no artifact though other nodes held the head. Reachable: `swap_pointer` read only `cursor.rank()`, and the exporter's candidate was whatever its fold held. Fixed: the guard orders by `(incarnation, rank)` (`protocol::Pos`), so a dead incarnation's pointer is replaced by the new stream's first publish and never replaces it back; the payload name carries the incarnation so `prune` stays sound (`payload_prunable`). Test `a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish`. The liveness theorem lost its hypothesis. The order rests on O4 (a recreated stream is created later). -- **F2** (`finding_f2_*`) a restore over the fold of a recreated stream kept old entries that carried a higher revision number than the artifact's (`restore_key` decided by revision number), and refused an artifact below the old cursor's rank as "not ahead" (`restore_request` compared against the foreign cursor the fold still held). Reachable: `ForeignCursor` with a repair armed ran the restore over the old fold (`repair::run_watch`). Fixed: the repair forgets the foreign cursor (`Fold::forget_cursor`) and the restore of a fold of another incarnation takes the artifact key for key (`restore_key`'s `local_known`). Tests `a_restore_over_a_foreign_fold_replaces_entries_the_old_stream_numbered_higher`, `a_restore_over_a_foreign_fold_is_not_barred_by_the_old_cursors_rank`. Not covered, by design: a fold that holds data and NO cursor (a torn first checkpoint, or a store populated elsewhere) carries nothing that names its incarnation; it is taken to be this stream's, because treating it as foreign would let a restore move a key the consumer already saw backward (`tests/model_repair.rs`, "never backward"). +- **F1** (`finding_f1_*`) the pointer guard compared ranks only, never the incarnation. A pointer whose artifact was the old stream's, ranked above the new head, refused every publish of the new stream until the head passed it, while `same_incarnation` refused to restore from it: a node that must restore had no artifact though other nodes held the head. Reachable: `swap_pointer` read only `cursor.rank()`, and the exporter's candidate was whatever its fold held. Fixed: ranks are ordered only within an incarnation (`protocol::Pos`) and a pointer of another incarnation is replaceable, like a corrupt one, so the new stream's first publish replaces a dead incarnation's pointer; no clock and no order between incarnations is assumed. The payload name carries the incarnation so `prune` only judges payloads of the pointer's own incarnation (`payload_prunable`). Test `a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish`. The liveness theorem lost its hypothesis. +- **F1b** (`finding_f1b_*`) the price of F1's fix, reported rather than assumed away: with no order between incarnations a slow exporter of a dead incarnation can move the live pointer out of its incarnation, and a stale live exporter can then publish a payload the prune guard had already deleted (it was below the live pointer). The pointer then names a missing payload until the next live publish replaces it; restorers see a loud miss, never wrong data. `transport_proofs` proves the protocol within one incarnation (monotone rank, no dangling pointer, fetch and prune races). Closing F1b needs the swap to check its payload still exists, or an order between incarnations. +- **F2** (`finding_f2_*`) a restore over the fold of a recreated stream kept old entries that carried a higher revision number than the artifact's (`restore_key` decided by revision number), and refused an artifact below the old cursor's rank as "not ahead" (`restore_request` compared against the foreign cursor the fold still held). Reachable: `ForeignCursor` with a repair armed ran the restore over the old fold (`repair::run_watch`). Fixed: the repair forgets the foreign cursor (`Fold::forget_cursor`) and the restore of a fold of another incarnation takes the artifact key for key (`restore_key`'s `local_known`). Tests `a_restore_over_a_foreign_fold_replaces_entries_the_old_stream_numbered_higher`, `a_restore_over_a_foreign_fold_is_not_barred_by_the_old_cursors_rank`. A fold that holds data and no cursor (a torn first checkpoint) is judged by its own record: a fold persists the incarnation of its stream before its first data record (`AppendLogSnapshot::apply` writes an origin-only cursor record first, and `compact_to_file` keeps it ahead of the data; fjall and RocksDB commit data and cursor in one atomic batch, so the cursor's origin is the record). On start, `cursorless_fold_is_this_stream` compares it with the stream's incarnation: a match is this stream's (trusted, so "never backward" holds), another incarnation is foreign (the F2 path), and no record is foreign too (fail closed). The commits a repair makes under a cursor-less fold of this stream keep recording its incarnation (`Fold::stamp_incarnation`); a restore over a foreign fold commits under no cursor, so a crash part-way leaves a fold that names no stream and the whole repair runs again. The last case is only files written before folds recorded an incarnation: a one-time re-seed on upgrade. Test `a_torn_first_checkpoint_of_the_old_stream_is_foreign_to_the_recreated_one`. - **F3** (`finding_f3_*`) the statement above: complete, not exact. - **F4** (`finding_f4_*`) the eviction memo (`seen_evicting`) rode the cursor and survived a recreation (the task's copy, and the fold's, which carried it over every cursor it advanced). On the new, un-evicted bucket the exact listing was distrusted and a restore planned; a fleet whose nodes are all foreign has no node to publish an artifact of the new stream, so none could start. Fixed with F2's `forget_cursor`: the memo goes with the cursor, and the new stream's retention is read afresh. Test `the_old_streams_eviction_memo_does_not_distrust_the_new_streams_listing`. -`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_restore_trusts_foreign` fails `restore_key`'s contract, `a_restore_over_a_foreign_fold_is_the_artifact` and `finding_f2_*`; `mut_pointer_ignores_incarnation` fails `pointer_publish_allowed`'s contract and `finding_f1_*`; `mut_foreign_keeps_memo` fails `finding_f4_*` (and the live test); `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. +`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_restore_trusts_foreign` fails `restore_key`'s contract, `a_restore_over_a_foreign_fold_is_the_artifact` and `finding_f2_*`; `mut_pointer_ignores_incarnation` fails `pointer_publish_allowed`'s contract and `finding_f1_*`; `mut_foreign_keeps_memo` fails `finding_f4_*` (and the live test); `mut_cursorless_fold_trusted` fails `cursorless_fold_is_this_stream`'s contract; `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. ### Export Round State Machine @@ -808,8 +811,8 @@ Per-message TTLs need a new-enough NATS server, a bucket flag, and a backend tha The legacy layout wrote the payload at `.payload.tar` and the manifest at `.manifest.json` as independent last-write-wins objects. The model checker proved two failure modes under that layout: (1) a cursor regression when a slow exporter's stale manifest overwrites a faster one's, and (2) a dangling pointer when the manifest advances past a payload that an older concurrent publisher still holds. The shipped layout fixes both structurally: - **Content-addressed payload** — the key is `--blake3(manifest)[..8].tar` (the cursor's incarnation and revision in the name let `prune` order a payload against the pointer; the digest is the content address). Two different artifacts can never share a key. Re-uploading the same artifact is an idempotent overwrite. A slow exporter's payload is valid until pruned; it just can't become the pointer. -- **Monotonic pointer via CAS** — `pointer_publish_allowed` refuses any candidate strictly below the current pointer in (incarnation, rank) order: a pointer of a bucket's dead incarnation, whatever its rank, is replaced by the recreated stream's first publish (it used to refuse every publish of the new stream until its head passed the old rank), and never replaces it back. Incarnations are ordered by stream creation time (axiom O4: a recreated stream is created later; a clock that steps back across a recreation leaves the old pointer standing, loudly, never a regression). Combined with CAS (no torn reads between observe and write), the pointer is monotone non-decreasing. Slow exporters always get `SupersededByNewer`, never succeed at regression. -- **Strictly-below prune rule** — `payload_prunable` only deletes positions strictly below the pointer. Because the pointer is monotone and `pointer_publish_allowed` refuses `< pointer`, a pruned payload can never become reachable again. The model checker found the dangling counterexample under an earlier age-only rule; this is the structural fix. +- **Monotonic pointer via CAS** — `pointer_publish_allowed` refuses any candidate strictly below the current pointer in its own incarnation: a pointer of a bucket's dead incarnation, whatever its rank, is replaced by the recreated stream's first publish (it used to refuse every publish of the new stream until its head passed the old rank); no order between incarnations is assumed. Combined with CAS (no torn reads between observe and write), the pointer's rank is monotone non-decreasing within an incarnation. Slow exporters always get `SupersededByNewer`, never succeed at regression. +- **Strictly-below prune rule** — `payload_prunable` only deletes payloads of the pointer's incarnation strictly below it. Because the pointer is monotone and `pointer_publish_allowed` refuses `< pointer`, a pruned payload can never become reachable again. The model checker found the dangling counterexample under an earlier age-only rule; this is the structural fix. Machine-checked as three theorems in `tests/model.rs`: published cursor never regresses, pointer target always fetchable (zero-grace prune), bootstrap never silently diverges. diff --git a/Cargo.toml b/Cargo.toml index 8a992c3..eb9566b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -107,6 +107,8 @@ mut_restore_ignores_versions = [] mut_restore_ignores_listing = [] # The pointer guard compares revisions across incarnations (a dead incarnation's pointer wedges publishing). mut_pointer_ignores_incarnation = [] +# A fold with data and no cursor is trusted whatever stream it records. +mut_cursorless_fold_trusted = [] # A foreign cursor keeps its eviction memo (the old stream's) through the repair. mut_foreign_keeps_memo = [] # The restore trusts a fold of another incarnation (a recreated bucket's old fold decides keys by its own revision numbers). diff --git a/src/applied.rs b/src/applied.rs index f62b228..038cad6 100644 --- a/src/applied.rs +++ b/src/applied.rs @@ -378,13 +378,15 @@ where // `repair::run_watch`). let unanchored = match &store { Some(st) if resume.as_ref().is_none_or(WatchCursor::is_none) => match st.has_entries() { - Ok(has) => has, + // The incarnation the store's data records as its own: what a fold + // with data and no cursor is judged by (`repair::run_watch`). + Ok(has) => has.then(|| st.cursor().origin()), Err(e) => { let e = KvError::WatchError(format!("reading the fold at start failed: {e}")); return early(e, store); } }, - _ => false, + _ => None, }; // The cursor we'll return. Initialized from the resume position so that a @@ -880,6 +882,16 @@ where self.applied = WatchCursor::none().remembering(seen); } + /// A fold of this stream that has no cursor records the stream's incarnation + /// on the commits a repair makes under it, so they do not erase the record + /// that says whose its data is (a position-less, origin-only cursor). + pub(crate) fn stamp_incarnation(&mut self, origin: Option) { + if let (true, Some(o)) = (self.applied.is_none(), origin) { + let seen = self.applied.seen_evicting(); + self.applied = WatchCursor::origin_only(o).remembering(seen); + } + } + /// Remember, durably, that the bucket's retention evicts current values: /// from now on every cursor this fold commits carries the memo, and so /// does every artifact exported from it. Commits at once, even with diff --git a/src/kernels/fleet_proofs.rs b/src/kernels/fleet_proofs.rs index 5bf7e56..648abaf 100644 --- a/src/kernels/fleet_proofs.rs +++ b/src/kernels/fleet_proofs.rs @@ -28,8 +28,9 @@ //! # Findings, and what each one changed (every one is a Verus-checked concrete state of the shipped decisions) //! //! * **F1** the pointer guard compared ranks only: a dead incarnation's pointer above the new head refused every publish of the -//! new stream while `same_incarnation` refused to restore from it. FIXED: the guard orders by (incarnation, rank) -//! (`protocol::Pos`), so the new stream's first publish replaces the dead pointer. [`finding_f1_*`] states the fix; the liveness +//! new stream while `same_incarnation` refused to restore from it. FIXED: a pointer of another incarnation is replaceable +//! (`protocol::Pos`: ranks are ordered only within an incarnation, no clock is assumed), so the new stream's first publish +//! replaces the dead pointer; the price is F1b below. [`finding_f1_*`] states the fix; the liveness //! theorem no longer assumes the state away. //! * **F2** a restore over a fold of a recreated stream kept stale entries by revision number, and refused an artifact below the //! old cursor's rank. FIXED: a fold whose cursor is no position of this stream (none, or another incarnation's, which the repair @@ -48,12 +49,15 @@ //! * **A1** retention config is constant inside an incarnation (a toggle is what the `seen_evicting` memo guards, so //! `mut_no_eviction_memo` is not observable in this world); `seen` is carried inside an incarnation and only ever narrows trust; //! the repair of a foreign cursor forgets it (the memo is a fact about the stream that was evicting); -//! * **A2** positions are `u64`; the stream's revision numbers fit (below `2^63`); incarnations (creation times) fit `u64` and a -//! recreation's is larger than the stream it replaces (O4 of `transport_proofs`); +//! * **A2** positions are `u64`; the stream's revision numbers fit (below `2^63`); incarnations (creation times) fit `u64` (no +//! order between incarnations is assumed); //! * **A3** the pointer object is written only by publishes (`transport_proofs`, O2); //! * a cursor with no recorded origin (written before cursors recorded one) is excluded: `tests/model_incarnation.rs` owns it; -//! * a fold that holds data and NO cursor (a torn first checkpoint) is taken to be of the current stream: nothing in it names an -//! incarnation, so a restore cannot tell it from this stream's, and keeps its newer entries (`model_repair`'s "never backward"); +//! * a fold that holds data and NO cursor (a torn first checkpoint) names its stream: `Node::origin` is the fold's durable record +//! of its incarnation (written before its first data record: `AppendLogSnapshot::apply`; with the data in one atomic batch in +//! the other backends), and the shell judges it against the stream that exists now (`cursorless_fold_is_this_stream`, proven +//! in `protocol.rs`: an exact match is this stream's; another incarnation, or no record, is foreign: one origin is +//! `Node::origin != l.origin`, the foreign path of every theorem below); //! * the liveness fairness axioms below (F-a to F-d). use crate::kernels::applied::*; @@ -1627,9 +1631,9 @@ pub proof fn finding_f2_a_restore_over_a_foreign_fold_takes_the_artifacts_entry( /// FINDING F1 (a dead incarnation's pointer wedged publishing), FIXED: the pointer guard used to compare ranks only /// (`pointer_publish_allowed`, `transport::swap_pointer`), never the incarnation. After the stream is recreated, a pointer whose /// artifact is the OLD stream's, ranked above the new stream's head, refused every publish of the new stream until its head -/// passed that rank, while `same_incarnation` refused to restore from it. Now the guard orders by (incarnation, rank): a publish of +/// passed that rank, while `same_incarnation` refused to restore from it. Now a pointer of another incarnation is replaceable (ranks are ordered only within one; no clock is assumed): a publish of /// the current incarnation is admitted over any pointer of a dead one, whatever its rank (`mut_pointer_ignores_incarnation` -/// forges the old guard: this proof goes red), and a publish of a dead incarnation is refused over the current one's. +/// forges the old guard: this proof goes red). pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_does_not_refuse_a_publish(l: Log, a: Art, c: nat) requires log_ok(l), @@ -1639,7 +1643,23 @@ pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_does_not_refuse_a_publi c <= umax(), ensures publish_allowed_spec(ptr_state(Some(a)), art_pos(l.origin, c)), - !publish_allowed_spec(ptr_state(Some(Art { origin: l.origin, cursor: c, fold: a.fold })), art_pos(a.origin, a.cursor)), +{ +} + +/// FINDING F1b (the price of F1's fix, reported, not assumed away): with no order between incarnations, a slow exporter of a dead +/// incarnation `b` may replace the live pointer (admitted: another incarnation's), and a STALE live exporter may then replace +/// that (admitted likewise) with a payload the prune guard has already deleted (it was strictly below the live pointer `(a, R)` +/// when pruned). Every step is a guard verdict below: the pointer then names a payload that does not exist, until the next live +/// publish replaces it. `transport_proofs` proves the protocol within one incarnation, where this cannot happen. Closing it +/// needs either an order between incarnations (the creation-time axiom, refused) or the swap to check its payload still exists. +pub proof fn finding_f1b_a_dead_exporter_lets_a_pruned_payload_be_published(a: u64, b: u64, r: u64, big: u64) + requires + a != b, + r < big, + ensures + prunable_spec(Some(Pos { origin: a, rank: r }), Pos { origin: a, rank: big }, false, true), + publish_allowed_spec(PointerState::Present { at: Some(Pos { origin: a, rank: big }) }, Pos { origin: b, rank: 1 }), + publish_allowed_spec(PointerState::Present { at: Some(Pos { origin: b, rank: 1 }) }, Pos { origin: a, rank: r }), { } diff --git a/src/kernels/protocol.rs b/src/kernels/protocol.rs index 6ce1ed1..5b1ccf3 100644 --- a/src/kernels/protocol.rs +++ b/src/kernels/protocol.rs @@ -14,6 +14,7 @@ //! | [`listing_is_truth`] / [`listing_truth`] | `repair` (plan, cursor-less start), `Snapshot::stale_keys` | every model's view of retention; repair-steps `ConfigForgot` | //! | [`plan_repair`] | `repair::plan`, `Snapshot::stale_keys` | expiry dispatch in every model | //! | [`cursorless_start_needs_repair`] | `repair::run_watch` | repair-steps `WStart`, fleet `Start` | +//! | [`cursorless_fold_is_this_stream`] | `repair::run_watch` (a fold with data and no cursor) | `tests/recreated_fleet.rs` (live) | //! | [`restore_key`] | `repair::restore_diff` | repair-steps restore op | //! | [`gap_holds_no_eviction`] | `nats` resume (`NatsKvWatcher::resume_point`) | — (unit-tested; `tests/eviction.rs` live) | //! @@ -36,22 +37,20 @@ use vstd::prelude::*; // decides, the lemmas are the safety arguments the doc comments make in prose. A normal build erases all of it. verus! { -/// A position in the artifact order: the stream incarnation a cursor was taken from, then its revision. Incarnations are -/// ordered by the stream's creation time ([`same_incarnation`]'s `origin`; 0 for a cursor that records none, older than -/// every recorded one), revisions within one. Environment axiom **O4**: a bucket recreated under its name is created later -/// than the stream it replaces (NATS stamps `created` from the server's clock); a clock that steps back across a recreation -/// leaves the old pointer standing until the new stream's head passes it: loud as a refused publish, never a regression. +/// A position in the artifact order: the stream incarnation a cursor was taken from (its creation time in Unix ns; 0 for a cursor +/// that records none) and its revision. Revisions are ordered only WITHIN an incarnation: nothing orders two incarnations (no +/// clock is assumed), and only one is live at a time. A position of another incarnation is replaceable, not older or newer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Pos { - /// The stream incarnation (creation time in Unix ns; 0 when the cursor records none). + /// The stream incarnation (0 when the cursor records none). pub origin: u64, /// The cursor's revision. pub rank: u64, } -/// `a` is strictly before `b`: an older incarnation, or the same one at a lower revision. +/// `a` is strictly below `b`: the same incarnation at a lower revision. Positions of different incarnations are incomparable. pub open spec fn pos_lt(a: Pos, b: Pos) -> bool { - a.origin < b.origin || (a.origin == b.origin && a.rank < b.rank) + a.origin == b.origin && a.rank < b.rank } /// What the publisher observed at the pointer key before deciding. @@ -72,20 +71,18 @@ pub enum PointerState { /// THE monotonic pointer guard: may `candidate` be published over the /// observed `current` pointer? /// -/// `true` for an open slot, a corrupt pointer, or a candidate at or above -/// the existing cursor in ([`Pos`]) order; `false` exactly when the existing -/// pointer is parseable and STRICTLY newer — the refusal that makes a slow -/// exporter's stale publish a no-op instead of a regression. The order is the -/// incarnation first: a pointer of a dead incarnation, whatever its revision, -/// is replaced by the first publish of the stream that replaced it, and never -/// replaces it back. (Ranks alone left such a pointer, ranked above the new -/// head, refusing every publish of the new stream.) +/// `true` for an open slot, a corrupt pointer, a pointer of ANOTHER incarnation than the candidate's, or a candidate at or above +/// the existing cursor in its own incarnation; `false` exactly when the existing pointer is parseable, of the candidate's +/// incarnation, and STRICTLY higher — the refusal that makes a slow exporter's stale publish a no-op instead of a regression. +/// A pointer of a dead incarnation, whatever its revision, never refuses a publish of the incarnation that replaced it (ranks +/// alone left such a pointer, ranked above the new head, refusing every publish of the new stream): it is foreign, like a corrupt +/// one, and replaceable. A slow exporter of the dead stream can replace the live pointer once; the next live publish replaces it +/// (restorers refuse it meanwhile: `same_incarnation`). /// -/// Soundness of deciding on a read (before the conditional put): every -/// writer uses this guard with a compare-and-swap, so the pointer's position is -/// monotone non-decreasing — once "strictly newer" is observed, it can never -/// become false, so refusal needs no CAS. Machine-checked as `published -/// cursor never regresses` in `tests/model.rs`. +/// Soundness of deciding on a read (before the conditional put): every writer uses this guard with a compare-and-swap, so while +/// the pointer stays in one incarnation its rank is monotone non-decreasing — once "strictly higher" is observed, it stays so +/// until the pointer leaves that incarnation, so refusal needs no CAS. Machine-checked as `published cursor never regresses` in +/// `tests/model.rs` (one incarnation). pub fn pointer_publish_allowed(current: &PointerState, candidate: Pos) -> (r: bool) ensures r == publish_allowed_spec(*current, candidate), @@ -105,13 +102,12 @@ pub fn pointer_publish_allowed(current: &PointerState, candidate: Pos) -> (r: bo } else { *existing }; - candidate.origin > existing.origin - || (candidate.origin == existing.origin && candidate.rank >= existing.rank) + candidate.origin != existing.origin || candidate.rank >= existing.rank }, } } -/// [`pointer_publish_allowed`]: refused exactly when the existing pointer is parseable and strictly newer. +/// [`pointer_publish_allowed`]: refused exactly when the existing pointer is parseable, of the candidate's incarnation, and higher. pub open spec fn publish_allowed_spec(current: PointerState, candidate: Pos) -> bool { !(current is Present && current->Present_at is Some && pos_lt(candidate, current->Present_at->Some_0)) } @@ -121,31 +117,31 @@ pub open spec fn published(candidate: Pos) -> PointerState { PointerState::Present { at: Some(candidate) } } -/// THEOREM (monotone pointer): an admitted publish never lowers a parseable pointer, so the pointer's position is monotone -/// non-decreasing under every interleaving of admitted publishes: across incarnations by creation time (O4), within one by -/// revision. This is what lets a refusal be decided on a read. -pub proof fn a_publish_never_regresses_the_pointer(current: PointerState, candidate: Pos) +/// THEOREM (monotone within an incarnation): an admitted publish over a parseable pointer of its own incarnation never lowers it, +/// so while the pointer stays in an incarnation its rank is monotone non-decreasing under every interleaving of admitted +/// publishes. This is what lets a refusal be decided on a read. +pub proof fn a_publish_never_regresses_the_pointer_within_an_incarnation(current: PointerState, candidate: Pos) requires publish_allowed_spec(current, candidate), + current is Present && current->Present_at is Some && current->Present_at->Some_0.origin == candidate.origin, ensures - (current is Present && current->Present_at is Some) - ==> !pos_lt(published(candidate)->Present_at->Some_0, current->Present_at->Some_0), + candidate.rank >= current->Present_at->Some_0.rank, { } -/// THEOREM (a dead incarnation's pointer never refuses a newer incarnation): whatever revision the pointer holds, a candidate -/// of a later incarnation is admitted. The pointer of a deleted and recreated bucket is replaced by the new stream's first -/// publish, even when ranked above the new head. -pub proof fn a_newer_incarnation_replaces_any_pointer(current: PointerState, candidate: Pos) +/// THEOREM (liveness: a dead incarnation's pointer never refuses a live exporter): whatever revision the pointer holds, a candidate +/// of another incarnation is admitted, with no assumption about time or about which incarnation is newer. The pointer of a deleted +/// and recreated bucket is replaced by the new stream's first publish, even when ranked above the new head. +pub proof fn a_pointer_of_another_incarnation_never_refuses_a_publish(current: PointerState, candidate: Pos) requires - current is Present && current->Present_at is Some ==> candidate.origin > current->Present_at->Some_0.origin, + current is Present && current->Present_at is Some ==> candidate.origin != current->Present_at->Some_0.origin, ensures publish_allowed_spec(current, candidate), { } -/// THEOREM (liveness of the publish guard): the refusal clears. An open slot, a corrupt pointer, and any candidate at or above -/// the pointer are always admitted, so an exporter that retries with a cursor at or above the pointer's succeeds. A stale +/// THEOREM (liveness of the publish guard): the refusal clears. An open slot, a corrupt pointer, a pointer of another +/// incarnation, and any candidate at or above the pointer in its incarnation are always admitted, so an exporter that retries with a cursor at or above the pointer's succeeds. A stale /// publish is refused only while the pointer is strictly newer, and the pointer never regresses, so it stays refused: the /// exporter's exit is a fresher export, never a retry of the stale one. Rank: none needed, the guard is stateless. pub proof fn a_publish_at_or_above_the_pointer_is_admitted(current: PointerState, candidate: Pos) @@ -166,13 +162,18 @@ pub proof fn a_publish_at_or_above_the_pointer_is_admitted(current: PointerState /// - its age has cleared the grace period (`aged_out`; the model passes /// `true`, checking the harshest zero-grace timing). /// -/// Strictly-below is what makes a dangling pointer impossible regardless of -/// timing: [`pointer_publish_allowed`] refuses any candidate below the -/// pointer, and the pointer is monotone — so anything this guard deletes -/// (position < pointer-at-prune ≤ pointer-at-any-later-swap) can never be -/// successfully published afterward. The payload's name carries its -/// incarnation as well as its revision for that reason: a revision alone -/// cannot say whether a payload of another incarnation is below the pointer. +/// Strictly-below, in the pointer's own incarnation, is what makes a dangling +/// pointer impossible regardless of timing, WHILE THE POINTER STAYS IN THAT +/// INCARNATION: [`pointer_publish_allowed`] refuses any candidate below the +/// pointer in its incarnation, and the pointer's rank is monotone there — so +/// anything this guard deletes (rank < pointer-at-prune ≤ pointer-at-any-later +/// -swap) can never be successfully published afterward. The payload's name +/// carries its incarnation as well as its revision so that a payload of another +/// incarnation is never judged by a revision that means nothing to it (it is +/// never pruned here). The bound is real: a slow exporter of a dead +/// incarnation can move the pointer out of the live one, and a stale live +/// exporter can then publish a payload this guard already deleted (fleet +/// finding F1b, `fleet_proofs`); the next live publish replaces that pointer. /// The model checker FOUND the dangling /// counterexample under the earlier age-only rule (a same-cursor payload /// collected mid-publish, then published by the `>=` swap guard); this rule @@ -191,7 +192,7 @@ pub fn payload_prunable( return false; } match payload { - Some(p) => p.origin < pointer.origin || (p.origin == pointer.origin && p.rank < pointer.rank), + Some(p) => p.origin == pointer.origin && p.rank < pointer.rank, None => false, } } @@ -206,9 +207,10 @@ pub open spec fn prunable_spec( !is_pointer_target && aged_out && payload is Some && pos_lt(payload->Some_0, pointer) } -/// THEOREM (no dangling pointer): a payload the prune guard deletes can never be published afterwards. The pointer's position is -/// monotone ([`a_publish_never_regresses_the_pointer`]), so at any later swap it is `later >= pointer > payload` in [`Pos`] order, -/// and the publish guard refuses that candidate. Holds for every timing, including zero grace (`aged_out` is a free input). +/// THEOREM (no dangling pointer, within an incarnation): a payload the prune guard deletes can never be published afterwards while +/// the pointer stays in its incarnation. The rank is monotone there ([`a_publish_never_regresses_the_pointer_within_an_incarnation`]), +/// so at any later swap it is `later >= pointer > payload`, and the publish guard refuses that candidate. Holds for every timing, +/// including zero grace (`aged_out` is a free input). Across incarnations it does not hold: see F1b. pub proof fn a_pruned_payload_is_never_published_after( payload: Pos, pointer: Pos, @@ -218,7 +220,8 @@ pub proof fn a_pruned_payload_is_never_published_after( ) requires prunable_spec(Some(payload), pointer, is_pointer_target, aged_out), - !pos_lt(later_pointer, pointer), + later_pointer.origin == pointer.origin, + later_pointer.rank >= pointer.rank, ensures !publish_allowed_spec(PointerState::Present { at: Some(later_pointer) }, payload), { @@ -326,6 +329,33 @@ pub open spec fn same_incarnation_spec( } } +/// THE provenance guard for a fold that holds data and NO cursor (a torn first checkpoint, or a restore cut short): is its data of +/// the stream that exists now? The fold persists its stream's incarnation (`recorded`) before any data; the stream's own is +/// `stream` (`Retention::incarnation`). Only an exact match is this stream's. A fold that names another incarnation is foreign, and +/// so is one that names none (a file written before folds recorded one: a one-time re-seed on upgrade) or a stream that cannot say: +/// what cannot be proven to be this stream's is treated as foreign, and the repair replaces it key for key. +pub fn cursorless_fold_is_this_stream(recorded: Option, stream: Option) -> (r: bool) + ensures + r == cursorless_fold_spec(recorded, stream), + recorded is None ==> !r, + stream is None ==> !r, + (recorded is Some && stream is Some && recorded->Some_0 != stream->Some_0) ==> !r, +{ + // Mutation (model tests only): trust any fold with data and no cursor (the pre-provenance restore). + if cfg!(feature = "mut_cursorless_fold_trusted") { + return true; + } + match (recorded, stream) { + (Some(r), Some(s)) => r == s, + _ => false, + } +} + +/// [`cursorless_fold_is_this_stream`]'s table. +pub open spec fn cursorless_fold_spec(recorded: Option, stream: Option) -> bool { + recorded is Some && stream is Some && recorded->Some_0 == stream->Some_0 +} + /// THE restore guard: may a fold whose cursor (`local_revision`) fell out of /// the log be replaced by an artifact exported at `artifact_revision`? /// @@ -760,11 +790,11 @@ mod tests { ); // A dead incarnation's pointer, ranked above the new head, is replaced... assert!(pointer_publish_allowed(&at(1, 500), pos(2, 3))); - // ...and never replaces the newer incarnation's. - assert!(!pointer_publish_allowed(&at(2, 3), pos(1, 500))); - // A pointer that records no incarnation is older than every recorded one. + // ...and nothing orders incarnations: no clock is assumed, a pointer of another incarnation is replaceable either way. + assert!(pointer_publish_allowed(&at(2, 3), pos(1, 500))); + // A pointer that records no incarnation is another incarnation to every recorded one. assert!(pointer_publish_allowed(&at(0, 500), pos(2, 3))); - assert!(!pointer_publish_allowed(&at(2, 3), pos(0, 500))); + assert!(pointer_publish_allowed(&at(2, 3), pos(0, 500))); } #[test] @@ -776,8 +806,8 @@ mod tests { // Equal position is NOT prunable: it is still publishable (>= guard). assert!(!payload_prunable(pos(2, 5), ptr, false, true)); assert!(!payload_prunable(pos(2, 6), ptr, false, true)); - // An older incarnation is below, whatever its revision; a newer one is above. - assert!(payload_prunable(pos(1, 500), ptr, false, true)); + // A payload of another incarnation is never judged by a revision that means nothing to it. + assert!(!payload_prunable(pos(1, 4), ptr, false, true)); assert!(!payload_prunable(pos(3, 1), ptr, false, true)); // The pointer's own target and unparseable names are never prunable. assert!(!payload_prunable(pos(2, 4), ptr, true, true)); diff --git a/src/kernels/transport_proofs.rs b/src/kernels/transport_proofs.rs index 0bd15e3..0b47e72 100644 --- a/src/kernels/transport_proofs.rs +++ b/src/kernels/transport_proofs.rs @@ -17,8 +17,11 @@ //! * **O1** a payload path names its content for ever (content addressing; a hash collision is the only way to break it); //! * **O2** the pointer object is written only by [`Act::Swap`] (nothing else deletes or rewrites it); //! * **O3** a compare-and-swap succeeds exactly when the object is unchanged since the read (`ver`); -//! * **O4** the stream incarnations of one bucket are ordered by creation time: a recreated stream is created later (the -//! incarnation is the creation time in Unix ns; the order of [`Pos`]). +//! * **O4** (scope) the pointer stays in one incarnation: every payload and the pointer are of [`TS::inc`]. Across incarnations +//! nothing orders them (no clock is assumed): a pointer of another incarnation is replaceable (`a_pointer_of_another_incarnation_ +//! never_refuses_a_publish`, proven on the guard), and what that costs is FINDING F1b in `fleet_proofs`: a slow exporter of a dead +//! incarnation moves the pointer out, and a stale live exporter can then publish a payload a prune already deleted. The +//! invariants below are therefore the within-incarnation protocol, which is what every pointer swap of a live fleet runs. use crate::kernels::protocol::*; use vstd::prelude::*; @@ -52,6 +55,8 @@ pub enum Actor { } pub struct TS { + /// The incarnation every payload and the pointer belong to (the scope of this proof). + pub inc: u64, /// The pointer's target payload, once one is published. Its position is the target's. pub ptr: Option, /// Successful swaps so far. @@ -97,7 +102,7 @@ pub open spec fn valid(s: TS, i: int) -> bool { pub open spec fn enabled(s: TS, a: Act) -> bool { match a { - Act::Upload(i, p) => valid(s, i) && actor(s, i) is Idle, + Act::Upload(i, p) => valid(s, i) && actor(s, i) is Idle && p.origin == s.inc, Act::Observe(i) => valid(s, i) && actor(s, i) is Uploaded, Act::Swap(i) => valid(s, i) && actor(s, i) is Observed && actor(s, i)->Observed_ver == s.ver, Act::Reread(i) => valid(s, i) && actor(s, i) is Observed && actor(s, i)->Observed_ver != s.ver, @@ -149,8 +154,9 @@ pub open spec fn actor_ok(s: TS, a: Actor) -> bool { match a { Actor::Idle => true, // An uploaded payload exists, or was pruned because the pointer is strictly past it. - Actor::Uploaded { p } => s.objs.contains(p) || (s.ptr is Some && pos_lt(pos(p), pos(s.ptr->Some_0))), + Actor::Uploaded { p } => p.origin == s.inc && (s.objs.contains(p) || (s.ptr is Some && pos_lt(pos(p), pos(s.ptr->Some_0)))), Actor::Observed { p, st, ver } => { + &&& p.origin == s.inc &&& publish_allowed_spec(st, pos(p)) &&& ver <= s.ver // Same as `Uploaded`, whatever the version: a lost CAS goes back to `Uploaded`. @@ -158,23 +164,23 @@ pub open spec fn actor_ok(s: TS, a: Actor) -> bool { // The read is current while the version is: so the guard's verdict still stands. &&& (ver == s.ver ==> st == pstate(s.ptr)) }, - Actor::Pruning { pr, keep } => s.ptr is Some && !pos_lt(pos(s.ptr->Some_0), pr), - Actor::Fetching { t } => s.objs.contains(t) || (s.ptr is Some && pos_lt(pos(t), pos(s.ptr->Some_0))), + Actor::Pruning { pr, keep } => s.ptr is Some && pr.origin == s.inc && pr.rank <= s.ptr->Some_0.rank, + Actor::Fetching { t } => t.origin == s.inc && (s.objs.contains(t) || (s.ptr is Some && pos_lt(pos(t), pos(s.ptr->Some_0)))), } } /// THE invariant: the pointer's target exists, and every actor's reads are consistent. pub open spec fn inv(s: TS) -> bool { - &&& s.ptr is Some ==> s.objs.contains(s.ptr->Some_0) + &&& s.ptr is Some ==> s.objs.contains(s.ptr->Some_0) && s.ptr->Some_0.origin == s.inc &&& forall|i: int| 0 <= i < s.actors.len() ==> actor_ok(s, #[trigger] s.actors[i]) } /// THEOREM: the empty store with `n` idle actors satisfies the invariant, for any `n`. -pub proof fn a_fresh_store_satisfies_the_invariant(actors: Seq) +pub proof fn a_fresh_store_satisfies_the_invariant(inc: u64, actors: Seq) requires forall|i: int| 0 <= i < actors.len() ==> #[trigger] actors[i] is Idle, ensures - inv(TS { ptr: None, ver: 0, objs: Set::empty(), actors }), + inv(TS { inc, ptr: None, ver: 0, objs: Set::empty(), actors }), { } @@ -232,7 +238,7 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) assert(actor_ok(s, s.actors[i])); // `o` is strictly below the pruner's read of the pointer, which is at most the pointer's position now. assert(pos_lt(pos(o), pr)); - assert(!pos_lt(pos(t), pr)); + assert(pr.rank <= t.rank); }, Act::FetchRead(i) => { if j != i { @@ -272,17 +278,15 @@ pub proof fn the_pointer_never_regresses(s: TS, a: Act) inv(s), enabled(s, a), ensures - s.ptr is Some ==> step(s, a).ptr is Some && !pos_lt(pos(step(s, a).ptr->Some_0), pos(s.ptr->Some_0)), - ({ let ps = pstate(s.ptr); let q = pstate(step(s, a).ptr); - (ps is Present && ps->Present_at is Some) ==> q is Present && q->Present_at is Some - && !pos_lt(q->Present_at->Some_0, ps->Present_at->Some_0) }), + s.ptr is Some ==> step(s, a).ptr is Some && step(s, a).ptr->Some_0.rank >= s.ptr->Some_0.rank + && step(s, a).ptr->Some_0.origin == s.inc, { match a { Act::Swap(i) => { assert(actor_ok(s, s.actors[i])); let p = actor(s, i)->Observed_p; if s.ptr is Some { - a_publish_never_regresses_the_pointer(pstate(s.ptr), pos(p)); + a_publish_never_regresses_the_pointer_within_an_incarnation(pstate(s.ptr), pos(p)); } }, _ => {}, diff --git a/src/kv.rs b/src/kv.rs index 8e2e095..2d00136 100644 --- a/src/kv.rs +++ b/src/kv.rs @@ -191,6 +191,13 @@ impl WatchCursor { self.as_u64().unwrap_or(0) } + /// A cursor with no position that records only which stream incarnation a + /// fold's data is of: what a fold persists BEFORE its first data, so a + /// first checkpoint that tears still names its stream. + pub(crate) fn origin_only(origin: u64) -> Self { + Self::from_version(VersionToken::unknown().with_origin(origin)) + } + /// The cursor's place in the artifact order: its stream incarnation (0 /// when it records none: older than any recorded one), then its /// [`rank`](Self::rank). The ONE place a cursor becomes a [`Pos`]. diff --git a/src/repair.rs b/src/repair.rs index 46a4478..0035194 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -42,8 +42,9 @@ use crate::health::{RepairState, WatchHealth}; use crate::kernels::applied::{Action, Event, Refusal, RepairKind}; use crate::kv::{KvError, KvReader, KvUpdate, KvWatcher, Retention, VersionToken, WatchCursor}; use crate::protocol::{ - KeyRestore, KeyState, RepairMode, RepairPlan, cursorless_start_needs_repair, listing_truth, - plan_repair, restore_ahead, restore_allowed, restore_key, resume_window_ok, same_incarnation, + KeyRestore, KeyState, RepairMode, RepairPlan, cursorless_fold_is_this_stream, + cursorless_start_needs_repair, listing_truth, plan_repair, restore_ahead, restore_allowed, + restore_key, resume_window_ok, same_incarnation, }; use crate::snapshot::{SnapshotError, SnapshotStore}; @@ -578,6 +579,9 @@ pub(crate) enum RepairRequest { scratch: Option, /// The fold's cursor was another incarnation's ([`KvError::ForeignCursor`]). foreign: bool, + /// A fold with data and no cursor that is this stream's: the incarnation + /// its commits keep recording, so the repair's own commits don't erase it. + stamp: Option, ack: oneshot::Sender<()>, }, /// The artifact restore: a verified artifact fold, the reader that lists @@ -765,7 +769,10 @@ pub(crate) async fn run_watch( watcher: Arc, scope: WatchScope, resume: Option, - unanchored: bool, + // `Some(recorded)`: the fold holds data but no cursor, and `recorded` is + // the incarnation it records as its data's (see + // [`cursorless_fold_is_this_stream`]). + unanchored: Option>, repair: Option>, tx: mpsc::Sender, health: Option, @@ -788,14 +795,37 @@ pub(crate) async fn run_watch( // decision, or the warning, depends on it. let mode = repair.as_ref().map_or(RepairMode::None, |h| h.mode.mode()); let mut repair_first = false; + // Data and no cursor whose recorded stream is not the one that exists now + // (or records none): foreign, repaired like a foreign cursor's fold. + let mut foreign_start = false; + let mut own_stream = None; + let unanchored_data = unanchored.is_some(); if resume.is_none() { + if let Some(provenance) = unanchored + && mode != RepairMode::None + { + let stream = watcher.retention().await?.and_then(|r| r.incarnation); + foreign_start = !cursorless_fold_is_this_stream(provenance, stream); + if !foreign_start { + own_stream = stream; + } + if foreign_start { + warn!( + ?provenance, + ?stream, + "the fold holds data and no cursor, and its recorded stream is not the \ + one that exists now (or it records none): treating it as another \ + incarnation's" + ); + } + } let truth = match mode { RepairMode::Relist => None, - RepairMode::Restore | RepairMode::Auto if unanchored => None, + RepairMode::Restore | RepairMode::Auto if unanchored_data => None, _ => memo.listing_truth(watcher).await?, }; - repair_first = cursorless_start_needs_repair(mode, unanchored, truth); - if repair_first && unanchored { + repair_first = cursorless_start_needs_repair(mode, unanchored_data, truth); + if repair_first && unanchored_data { warn!( "the fold holds data but no cursor; repairing it like an expired cursor \ before watching (a re-list alone never removes what it doesn't deliver)" @@ -822,7 +852,8 @@ pub(crate) async fn run_watch( loop { // The cursor belongs to another incarnation of the stream. - let mut foreign = false; + let mut foreign = std::mem::take(&mut foreign_start); + let stamp = std::mem::take(&mut own_stream); let cursor = if std::mem::take(&mut repair_first) { WatchCursor::none() } else { @@ -881,7 +912,7 @@ pub(crate) async fn run_watch( "watch cursor expired; resyncing stale keys, then falling back to the full re-list" ); note(health, RepairState::Relisting); - resync_stale_keys(reader, scratch, foreign, repairs).await?; + resync_stale_keys(reader, scratch, (foreign, stamp), repairs).await?; if let Some(h) = health { h.repair_done(); } @@ -1131,7 +1162,7 @@ fn note(health: Option<&WatchHealth>, state: RepairState) { async fn resync_stale_keys( reader: &Arc, scratch: Option, - foreign: bool, + (foreign, stamp): (bool, Option), repairs: &mpsc::Sender>, ) -> Result<(), KvError> { let (ack_tx, ack_rx) = oneshot::channel(); @@ -1140,6 +1171,7 @@ async fn resync_stale_keys( reader: Arc::clone(reader), scratch, foreign, + stamp, ack: ack_tx, }) .await @@ -1211,6 +1243,7 @@ where reader, scratch, foreign, + stamp, ack, }) = req.take() else { @@ -1219,6 +1252,7 @@ where if foreign { fold.forget_cursor(); } + fold.stamp_incarnation(stamp); relist(fold, &*reader, scratch, prefixes).await?; // Ack AFTER the deletes are applied: the watch task is holding // the fallback watch until it hears back, which is what orders @@ -1389,6 +1423,12 @@ where let Some(r) = restored.take() else { unreachable!("the artifact is held until the reply") }; + // A fold of this stream with no cursor keeps recording the + // stream its chunks are of (the artifact's), so a crash between + // chunks leaves data that still names it. + if local_known { + fold.stamp_incarnation(target.origin()); + } restored = Some(fold_chunks(fold, r, spill, deletes, max).await?); fold.decide(Event::RestoreFolded) } diff --git a/src/snapshot.rs b/src/snapshot.rs index 9d54fe3..1ec956d 100644 --- a/src/snapshot.rs +++ b/src/snapshot.rs @@ -600,6 +600,19 @@ impl SnapshotStore for AppendLogSnapshot { } fn apply(&mut self, batch: &[KvUpdate], cursor: &WatchCursor) -> Result<(), SnapshotError> { + // A fresh fold records which stream incarnation it is of BEFORE its first + // data record (a checkpoint, flushed), so a first checkpoint that tears + // still names its stream: data plus a recorded incarnation is judged + // against the stream on open, and data with none is foreign. + if self.entries.is_empty() + && self.cursor.origin().is_none() + && !batch.is_empty() + && let Some(origin) = cursor.origin() + { + let origin_only = WatchCursor::origin_only(origin); + let _ = self.writer.checkpoint(&origin_only)?; + self.cursor = origin_only; + } // Stream the raw records, then the cursor checkpoint — data-then-cursor, // so a torn write leaves data ahead of the cursor (re-folded on resume), // never a cursor ahead of its data. The in-RAM fold mirrors the same @@ -1212,6 +1225,11 @@ fn compact_to_file( 0 } else { 4 + 1 + 1 + cursor.to_bytes().len() + } + + if cursor.origin().is_some() { + 4 + 1 + 1 + 20 + } else { + 0 }; let capacity = estimated.clamp(8 * 1024, 1024 * 1024); let mut buf = io::BufWriter::with_capacity(capacity, tempfile::NamedTempFile::new_in(dir)?); @@ -1219,6 +1237,12 @@ fn compact_to_file( buf.write_all(MAGIC)?; buf.write_all(&FORMAT_VERSION.to_le_bytes())?; + // The fold's incarnation BEFORE its data, as `apply` writes it: a log cut + // anywhere after this record still names the stream its entries are of. + if let Some(origin) = cursor.origin() { + write_cursor_record(&mut buf, &WatchCursor::origin_only(origin))?; + } + for entry in sorted { write_put_record(&mut buf, &entry.key, &entry.value, &entry.version)?; } @@ -1861,6 +1885,44 @@ mod tests { /// the file (missing those records), rewrote it, and the old buffer then /// flushed into the renamed-away inode — silently dropping the writes. With /// the leading flush, an un-checkpointed write survives compaction. + /// A fresh fold records its stream's incarnation before its first data + /// record, so a first checkpoint that tears (data on disk, the cursor + /// record not) still names its stream. A fold with no recorded + /// incarnation (a file from before folds recorded one) names none. + #[test] + fn a_torn_first_checkpoint_still_names_its_stream() { + let torn = |origin: Option| { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("fold"); + let (_, mut s) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let mut v = VersionToken::from_u64(5); + if let Some(o) = origin { + v = v.with_origin(o); + } + let c = WatchCursor::from_version(v); + s.apply(&[put("a", b"1", 5)], &c).unwrap(); + drop(s); + let len = fs::metadata(&path).unwrap().len(); + let record = (4 + 1 + 1 + c.to_bytes().len()) as u64; + OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_len(len - record) + .unwrap(); + let (cursor, s) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + assert!(cursor.is_none(), "the cursor record is torn off"); + assert!(s.get("a").unwrap().is_some(), "the data is there"); + // And it survives a compaction on the next open. + drop(s); + let (again, _) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + assert_eq!(again.origin(), cursor.origin()); + cursor.origin() + }; + assert_eq!(torn(Some(77)), Some(77)); + assert_eq!(torn(None), None, "no recorded incarnation: foreign"); + } + #[test] fn compact_preserves_uncheckpointed_writes() { let dir = TempDir::new().unwrap(); diff --git a/tests/repair_dst.rs b/tests/repair_dst.rs index accfdb7..5c9ec6b 100644 --- a/tests/repair_dst.rs +++ b/tests/repair_dst.rs @@ -345,7 +345,7 @@ impl KvWatcher for SimLog { evicts_current_values: st.evicts_current, first_revision: st.first_revision(), last_revision: u64::MAX, - incarnation: None, + incarnation: Some(SIM_INCARNATION), })) } } @@ -477,7 +477,7 @@ impl SimRestore { schema_version: ARTIFACT_SCHEMA_VERSION, backend: "sim".into(), backend_version: "0".into(), - cursor: WatchCursor::from_u64(self.cursor), + cursor: sim_cursor(self.cursor), created_at_unix: 0, files: vec![], scope: Some(vec![String::new()]), @@ -528,7 +528,7 @@ impl RestoreSource> for SimRestore { }) }) .collect(); - fold.apply(&updates, &WatchCursor::from_u64(self.cursor))?; + fold.apply(&updates, &sim_cursor(self.cursor))?; Ok(RestoredFold::new( self.manifest(), FaultStore { @@ -861,9 +861,10 @@ fn world(sc: &Scenario, yield_between: bool) -> World { .map(to_update) .collect(); let cursor = if sc.unanchored { - WatchCursor::none() + // Data and no cursor: a torn first checkpoint, which still names its stream. + sim_origin_only() } else { - WatchCursor::from_u64(at) + sim_cursor(at) }; fold.apply(&seed, &cursor).unwrap(); } @@ -1132,6 +1133,28 @@ struct Cfg { export: bool, } +/// The one stream incarnation the simulated log is, and a cursor of it (the encoding of a cursor that records its stream: the +/// version padded to 10 bytes, its length, the origin flag, the origin u64 LE). The folds record it, so a fold with data and no +/// cursor is judged this stream's, as a real watch's would be. +const SIM_INCARNATION: u64 = 7; + +/// What a torn first checkpoint leaves: no position, the stream recorded. +fn sim_origin_only() -> WatchCursor { + let mut bytes = vec![0u8; 12]; + bytes[11] = 0b100; + bytes.extend_from_slice(&SIM_INCARNATION.to_le_bytes()); + WatchCursor::from_bytes(&bytes).expect("an origin-only cursor") +} + +fn sim_cursor(rev: u64) -> WatchCursor { + let mut bytes = vec![0u8; 12]; + bytes[..8].copy_from_slice(&rev.to_be_bytes()); + bytes[10] = 8; + bytes[11] = 0b100; + bytes.extend_from_slice(&SIM_INCARNATION.to_le_bytes()); + WatchCursor::from_bytes(&bytes).expect("a cursor with an origin") +} + /// Drive a schedule (faults per run) to convergence and check the outcome. /// Returns the number of store-apply calls the first run made. async fn check_schedule(sc: &Scenario, cfg: Cfg, schedule: &[RunFaults]) -> usize { diff --git a/tests/snapshot_store.rs b/tests/snapshot_store.rs index 13a59c2..ba2b028 100644 --- a/tests/snapshot_store.rs +++ b/tests/snapshot_store.rs @@ -218,6 +218,46 @@ fn check_has_entries(open: impl Fn(&Path) -> (WatchCursor, S)) /// Cursor-resume after a reconnect: fold a first segment, reopen (cursor reflects /// it), fold the post-cursor delta, reopen again (cursor advanced). Models a /// service restarting and resuming the watch from the persisted position. +/// A cursor at `rev` that records the stream incarnation `origin` it was taken +/// from (the cursor encoding: the version padded to 10 bytes, its length, the +/// origin flag, then the origin, u64 LE). +fn cursor_of(rev: u64, origin: u64) -> WatchCursor { + let mut bytes = vec![0u8; 12]; + bytes[..8].copy_from_slice(&rev.to_be_bytes()); + bytes[10] = 8; + bytes[11] = 0b100; + bytes.extend_from_slice(&origin.to_le_bytes()); + WatchCursor::from_bytes(&bytes).expect("a cursor with an origin") +} + +/// A fold's data and the incarnation it is of are persisted together: a fold +/// reopened holds the cursor it committed, incarnation included, and data +/// committed under no cursor (a restore's chunks, which mix streams) names no +/// incarnation. A fold whose data names none is foreign to every stream. +fn check_incarnation_is_persisted_with_the_data( + open: impl Fn(&Path) -> (WatchCursor, S), +) { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("store"); + let c = cursor_of(1, 77); + { + let (_r, mut s) = open(&path); + s.apply(&[put("a", b"1", 1)], &c).unwrap(); + } + { + let (r, mut s) = open(&path); + assert_eq!(r.to_bytes(), c.to_bytes(), "the incarnation is persisted"); + assert_eq!(r.as_u64(), Some(1)); + s.apply(&[put("b", b"2", 2)], &WatchCursor::none()).unwrap(); + } + let (r, s) = open(&path); + assert!( + r.to_bytes().is_empty(), + "data under no cursor names no stream" + ); + assert!(s.get("b").unwrap().is_some()); +} + fn check_cursor_resume(open: impl Fn(&Path) -> (WatchCursor, S)) { let dir = TempDir::new().unwrap(); let path = dir.path().join("store"); @@ -746,6 +786,11 @@ fn append_log_cursor_resume() { check_cursor_resume(open_append_log); } +#[test] +fn append_log_incarnation_is_persisted_with_the_data() { + check_incarnation_is_persisted_with_the_data(open_append_log); +} + #[test] fn append_log_pure_fold_property() { check_property_pure_fold(open_append_log); @@ -905,6 +950,11 @@ mod fjall_backend { check_cursor_resume(open_no_sync); } + #[test] + fn fjall_incarnation_is_persisted_with_the_data() { + check_incarnation_is_persisted_with_the_data(open_no_sync); + } + #[test] fn fjall_pure_fold_property() { check_property_pure_fold(open_no_sync); @@ -1128,6 +1178,11 @@ mod rocksdb_backend { check_cursor_resume(open_no_sync); } + #[test] + fn rocksdb_incarnation_is_persisted_with_the_data() { + check_incarnation_is_persisted_with_the_data(open_no_sync); + } + #[test] fn rocksdb_pure_fold_property() { check_property_pure_fold(open_no_sync); From b5c8962e02fd4521a406ab118b9e3446b6ff9bca Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 19:51:27 -0800 Subject: [PATCH 6/7] F1b: the transport proofs cover all incarnations; a dangling pointer is a detected miss (a) ended by the live exporter's round (b) Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 16 +- src/kernels/fleet_proofs.rs | 47 +--- src/kernels/protocol.rs | 2 +- src/kernels/transport_proofs.rs | 409 ++++++++++++++++++++++++-------- 4 files changed, 326 insertions(+), 148 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 71b101f..b10a5a2 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -503,20 +503,22 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut | `finding_f1_*`, `a_newer_incarnation_replaces_any_pointer` | `fleet_proofs.rs:1633`, `protocol.rs` | a dead incarnation's pointer, whatever its rank, never refuses a publish of the current one (F1) | | `finding_f4_*` | `fleet_proofs.rs:1651` | a node that sees a foreign cursor forgets the eviction memo and plans the exact listing wherever the listing is exact (F4) | | `a_blocked_node_names_the_write_that_aged_out` | `fleet_proofs.rs:2011` | the one fail-stop is loud and exact: revision `first - 1` was evicted after the node's cursor and no artifact of this stream holds it | -| `every_step_preserves_the_invariant` | `transport_proofs.rs:183` | transport invariant over every interleaving of N exporters, pruners and fetchers with stale reads | -| `the_pointer_never_regresses` | `transport_proofs.rs:270` | the monotone-pointer theorem lifted to the whole protocol | -| `prune_never_deletes_the_pointers_target` | `transport_proofs.rs:296` | whatever a pruner read, what it may delete is not the pointer's current target | -| `a_fetch_gets_its_payload_or_a_detected_miss` | `transport_proofs.rs:314` | a fetch racing a prune gets the object its read named or a miss, never another payload; a miss means the pointer moved strictly past it | -| `a_fresh_read_never_misses_without_a_publish`, `a_lost_cas_means_a_publish_happened` | `transport_proofs.rs:334`, `:346` | liveness: a refused fetch retries; a lost CAS is paid for by a publish | +| `every_step_preserves_the_invariant` | `transport_proofs.rs:199` | transport invariant over every interleaving of N exporters, pruners and fetchers with stale reads, over all incarnations | +| `the_pointer_never_regresses` | `transport_proofs.rs:265` | the monotone-pointer theorem lifted to the whole protocol: a swap never moves the pointer strictly below the old one in its incarnation | +| `a_prune_deletes_only_below_what_it_read` | `transport_proofs.rs:283` | whatever a pruner read, what it may delete is strictly below that read in its incarnation (that it is not the CURRENT target holds within an incarnation only: F1b) | +| `a_fetch_gets_its_payload_or_a_detected_miss`, `finding_f1b_a_dangling_pointer_is_a_detected_miss` | `transport_proofs.rs:296`, `:349` | (a) a fetch gets the object its read named or a miss, never another payload: in every state, a dangling pointer's included | +| `a_lost_cas_means_a_publish_happened` | `transport_proofs.rs:313` | liveness: a lost CAS is paid for by a publish | +| `a_live_round_ends_the_dangling_window` | `transport_proofs.rs:469` | (b) liveness, ranking function `rho` (four per dead round in flight plus the live exporter's phase): the live exporter's round replaces a dangling pointer with a payload that exists; its payload is never pruned, its read is admitted, a lost CAS is paid by a dead round's swap | +| `a_restore_never_takes_a_foreign_artifact` | `fleet_proofs.rs:1654` | a restore begins only from an artifact of the current incarnation | **The statement.** `finv`: every node of the current incarnation holds a real fold (every entry a write of the log) that is *complete* at its cursor `c`: equal to the truth at `c` on every key not written after `c`; every published artifact of the current incarnation likewise. Exact equality at `c` is not what the code keeps and is not an invariant (F3): an artifact at `C` is complete together with the log after `C`, and a restore keeps the stale entry of a key the bucket lists live (`restore_key`) because the resume delivers its later write. At the head every key is "not written since", so a converged node holds exactly the truth. The Stateright model (`tests/model_fleet.rs`: one key, atomic repair) states the stronger "equals the truth at its cursor" and passes only because of those bounds; the statement the code keeps is this one. -**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: **O4** (scope of the transport proofs) the pointer stays in one incarnation: nothing orders two incarnations and no clock is assumed (a pointer of another incarnation is replaceable; F1b is the cost); the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle; a foreign cursor forgets it); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. +**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *F-e* (the transport liveness) while the live exporter's round runs no round starts: the export lease admits one live round and a dead stream's nodes start none after the recreation; *F-h* it exports at the live head; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: **O4** (scope of the transport proofs) the pointer stays in one incarnation: nothing orders two incarnations and no clock is assumed (a pointer of another incarnation is replaceable; F1b is the cost); the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle; a foreign cursor forgets it); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. **Findings the proofs surfaced** (each a Verus-checked concrete state of the shipped decisions, in `fleet_proofs.rs`; F1, F2 and F4 were real bugs, reached against a live nats-server in `tests/recreated_fleet.rs`, and are fixed; the proof no longer carries a premise that excluded them): - **F1** (`finding_f1_*`) the pointer guard compared ranks only, never the incarnation. A pointer whose artifact was the old stream's, ranked above the new head, refused every publish of the new stream until the head passed it, while `same_incarnation` refused to restore from it: a node that must restore had no artifact though other nodes held the head. Reachable: `swap_pointer` read only `cursor.rank()`, and the exporter's candidate was whatever its fold held. Fixed: ranks are ordered only within an incarnation (`protocol::Pos`) and a pointer of another incarnation is replaceable, like a corrupt one, so the new stream's first publish replaces a dead incarnation's pointer; no clock and no order between incarnations is assumed. The payload name carries the incarnation so `prune` only judges payloads of the pointer's own incarnation (`payload_prunable`). Test `a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish`. The liveness theorem lost its hypothesis. -- **F1b** (`finding_f1b_*`) the price of F1's fix, reported rather than assumed away: with no order between incarnations a slow exporter of a dead incarnation can move the live pointer out of its incarnation, and a stale live exporter can then publish a payload the prune guard had already deleted (it was below the live pointer). The pointer then names a missing payload until the next live publish replaces it; restorers see a loud miss, never wrong data. `transport_proofs` proves the protocol within one incarnation (monotone rank, no dangling pointer, fetch and prune races). Closing F1b needs the swap to check its payload still exists, or an order between incarnations. +- **F1b** (`finding_f1b_*`, `a_live_round_ends_the_dangling_window`) the price of F1's fix, bounded and proven, not assumed away: after a bucket recreation, a fetch can miss until the next live export round. With no order between incarnations a slow exporter of a dead incarnation can move the live pointer out of its incarnation, and a stale live exporter can then publish a payload the prune guard had already deleted (it was below the live pointer): the pointer dangles, so "the pointer's target exists" is not an invariant over all incarnations and is not claimed. (a) Safety, in every state: a fetch gets the payload its read named or a detected miss, never another payload, and a restore never takes a foreign artifact. (b) Liveness: the live exporter's round (the lease admits one at a time; a dead stream's nodes start no new round after the recreation) replaces the dangling pointer with a payload that exists, in at most one round plus one re-read per dead round still in flight: its read is admitted because it exports at the live head, its payload cannot be pruned (every live read is at most its rank), and a lost CAS is paid by a dead round's swap (ranking function `rho`). So the window is bounded, loud (a detected miss) and never serves wrong data. The proof's hypotheses are named axioms (F-e: no round starts during the window; F-h: the live exporter exports at the live head); without F-h it is red. - **F2** (`finding_f2_*`) a restore over the fold of a recreated stream kept old entries that carried a higher revision number than the artifact's (`restore_key` decided by revision number), and refused an artifact below the old cursor's rank as "not ahead" (`restore_request` compared against the foreign cursor the fold still held). Reachable: `ForeignCursor` with a repair armed ran the restore over the old fold (`repair::run_watch`). Fixed: the repair forgets the foreign cursor (`Fold::forget_cursor`) and the restore of a fold of another incarnation takes the artifact key for key (`restore_key`'s `local_known`). Tests `a_restore_over_a_foreign_fold_replaces_entries_the_old_stream_numbered_higher`, `a_restore_over_a_foreign_fold_is_not_barred_by_the_old_cursors_rank`. A fold that holds data and no cursor (a torn first checkpoint) is judged by its own record: a fold persists the incarnation of its stream before its first data record (`AppendLogSnapshot::apply` writes an origin-only cursor record first, and `compact_to_file` keeps it ahead of the data; fjall and RocksDB commit data and cursor in one atomic batch, so the cursor's origin is the record). On start, `cursorless_fold_is_this_stream` compares it with the stream's incarnation: a match is this stream's (trusted, so "never backward" holds), another incarnation is foreign (the F2 path), and no record is foreign too (fail closed). The commits a repair makes under a cursor-less fold of this stream keep recording its incarnation (`Fold::stamp_incarnation`); a restore over a foreign fold commits under no cursor, so a crash part-way leaves a fold that names no stream and the whole repair runs again. The last case is only files written before folds recorded an incarnation: a one-time re-seed on upgrade. Test `a_torn_first_checkpoint_of_the_old_stream_is_foreign_to_the_recreated_one`. - **F3** (`finding_f3_*`) the statement above: complete, not exact. - **F4** (`finding_f4_*`) the eviction memo (`seen_evicting`) rode the cursor and survived a recreation (the task's copy, and the fold's, which carried it over every cursor it advanced). On the new, un-evicted bucket the exact listing was distrusted and a restore planned; a fleet whose nodes are all foreign has no node to publish an artifact of the new stream, so none could start. Fixed with F2's `forget_cursor`: the memo goes with the cursor, and the new stream's retention is read afresh. Test `the_old_streams_eviction_memo_does_not_distrust_the_new_streams_listing`. diff --git a/src/kernels/fleet_proofs.rs b/src/kernels/fleet_proofs.rs index 648abaf..184358e 100644 --- a/src/kernels/fleet_proofs.rs +++ b/src/kernels/fleet_proofs.rs @@ -30,7 +30,8 @@ //! * **F1** the pointer guard compared ranks only: a dead incarnation's pointer above the new head refused every publish of the //! new stream while `same_incarnation` refused to restore from it. FIXED: a pointer of another incarnation is replaceable //! (`protocol::Pos`: ranks are ordered only within an incarnation, no clock is assumed), so the new stream's first publish -//! replaces the dead pointer; the price is F1b below. [`finding_f1_*`] states the fix; the liveness +//! replaces the dead pointer; the price is F1b: a window in which the pointer can dangle, a detected miss ended by the live +//! exporter's round (`transport_proofs`). [`finding_f1_*`] states the fix; the liveness //! theorem no longer assumes the state away. //! * **F2** a restore over a fold of a recreated stream kept stale entries by revision number, and refused an artifact below the //! old cursor's rank. FIXED: a fold whose cursor is no position of this stream (none, or another incarnation's, which the repair @@ -1646,46 +1647,16 @@ pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_does_not_refuse_a_publi { } -/// FINDING F1b (the price of F1's fix, reported, not assumed away): with no order between incarnations, a slow exporter of a dead -/// incarnation `b` may replace the live pointer (admitted: another incarnation's), and a STALE live exporter may then replace -/// that (admitted likewise) with a payload the prune guard has already deleted (it was strictly below the live pointer `(a, R)` -/// when pruned). Every step is a guard verdict below: the pointer then names a payload that does not exist, until the next live -/// publish replaces it. `transport_proofs` proves the protocol within one incarnation, where this cannot happen. Closing it -/// needs either an order between incarnations (the creation-time axiom, refused) or the swap to check its payload still exists. -pub proof fn finding_f1b_a_dead_exporter_lets_a_pruned_payload_be_published(a: u64, b: u64, r: u64, big: u64) +/// FINDING F1b (the price of F1's fix) lives in `transport_proofs`, where the pointer and the prune are: a dead exporter can leave +/// the pointer dangling; (a) a fetch of it is a detected miss, never another payload, and (b) the live exporter's round replaces it +/// (`a_live_round_ends_the_dangling_window`). What the FLEET adds: a restore never takes a foreign artifact, so a dangling or dead +/// pointer is never restored from, whatever it names. +pub proof fn a_restore_never_takes_a_foreign_artifact(f: F, i: int, hd: bool, pick: spec_fn(nat) -> bool) requires - a != b, - r < big, - ensures - prunable_spec(Some(Pos { origin: a, rank: r }), Pos { origin: a, rank: big }, false, true), - publish_allowed_spec(PointerState::Present { at: Some(Pos { origin: a, rank: big }) }, Pos { origin: b, rank: 1 }), - publish_allowed_spec(PointerState::Present { at: Some(Pos { origin: b, rank: 1 }) }, Pos { origin: a, rank: r }), -{ -} - -/// FINDING F4 (a stale memo blocked a start the listing could serve), FIXED: `seen_evicting` rides the cursor, and a node that -/// sees its cursor belong to another incarnation used to keep it (`Detect`). On the recreated, un-evicted bucket the listing IS the -/// truth, but the memo distrusted it, so the plan was a restore; with no artifact of the new stream (a fleet that is all foreign -/// has no node to publish one) every such node was blocked for ever, though nothing was lost. Now the detected node forgets the -/// memo with the cursor, and plans the listing wherever the listing is exact. -pub proof fn finding_f4_a_detected_node_forgets_the_old_streams_eviction_memo(f: F, i: int) - requires - finv(f), - valid(f, i), - !f.log.evicts, - f.log.first == 1, - !cfg!(feature = "mut_no_eviction_memo"), - enabled(f, Act::Detect(i)), + enabled(f, Act::RestoreBegin(i, hd, pick)), ensures - !step(f, Act::Detect(i)).nodes[i].seen, - plan_of(lt_of(f.log, step(f, Act::Detect(i)).nodes[i])) is Relist, - forall|k: nat| (#[trigger] listed(f.log, k)) == truth(f.log.ops, f.log.ops.len(), k), + f.ptr is Some && f.ptr->Some_0.origin == f.log.origin, { - let l = f.log; - assert(log_ok(l)); - assert forall|k: nat| (#[trigger] listed(l, k)) == truth(l.ops, l.ops.len(), k) by { - the_trusted_listing_is_the_truth(l, false, k); - } } // --------------------------------------------------------------------------------------------------------------------- diff --git a/src/kernels/protocol.rs b/src/kernels/protocol.rs index 5b1ccf3..7c18749 100644 --- a/src/kernels/protocol.rs +++ b/src/kernels/protocol.rs @@ -173,7 +173,7 @@ pub proof fn a_publish_at_or_above_the_pointer_is_admitted(current: PointerState /// never pruned here). The bound is real: a slow exporter of a dead /// incarnation can move the pointer out of the live one, and a stale live /// exporter can then publish a payload this guard already deleted (fleet -/// finding F1b, `fleet_proofs`); the next live publish replaces that pointer. +/// finding F1b, `transport_proofs`: a detected miss, ended by the live exporter's next round). /// The model checker FOUND the dangling /// counterexample under the earlier age-only rule (a same-cursor payload /// collected mid-publish, then published by the `>=` swap guard); this rule diff --git a/src/kernels/transport_proofs.rs b/src/kernels/transport_proofs.rs index 0b47e72..d6ea7aa 100644 --- a/src/kernels/transport_proofs.rs +++ b/src/kernels/transport_proofs.rs @@ -1,27 +1,44 @@ -//! The artifact transport protocol, proven for every interleaving of any number of exporters, pruners and fetchers, with no -//! bound on how many objects, actors or steps there are. `tests/model.rs` checks the same protocol in a bounded world (Stateright); -//! this is its unbounded twin. The decisions are the production kernels, not copies: [`pointer_publish_allowed`]'s spec -//! (`publish_allowed_spec`) decides every publish and [`payload_prunable`]'s spec (`prunable_spec`) decides every delete. +//! The artifact transport protocol, proven for every interleaving of any number of exporters, pruners and fetchers, over ALL stream +//! incarnations, with no bound on how many objects, actors or steps there are. `tests/model.rs` checks the same protocol in a +//! bounded world (Stateright); this is its unbounded twin. The decisions are the production kernels, not copies: +//! [`pointer_publish_allowed`]'s spec (`publish_allowed_spec`) decides every publish and [`payload_prunable`]'s spec +//! (`prunable_spec`) decides every delete. //! //! # The world //! -//! The object store holds immutable, content-addressed payload objects (`--`: [`Payload`]) and one -//! pointer object, swapped by compare-and-swap (`transport::swap_pointer`; [`TS::ver`] counts successful swaps, and a CAS only -//! succeeds against the version the publisher read). An exporter runs `Upload`, then reads the pointer and applies the guard -//! (`Observe`), then swaps (`Swap`); a refused guard ends its round, a lost CAS re-reads. A pruner reads the pointer once and -//! then deletes any number of objects against that (possibly stale) read. A fetcher reads the pointer and later gets the object. -//! Every actor's read can be arbitrarily stale: that is what the interleaving quantifies over. +//! The object store holds immutable, content-addressed payload objects (`--`: +//! [`Payload`]) and one pointer object, swapped by compare-and-swap (`transport::swap_pointer`; [`TS::ver`] counts successful +//! swaps, and a CAS only succeeds against the version the publisher read). An exporter runs `Upload`, then reads the pointer and +//! applies the guard (`Observe`), then swaps (`Swap`); a refused guard ends its round, a lost CAS re-reads. A pruner reads the +//! pointer once and then deletes any number of objects against that (possibly stale) read. A fetcher reads the pointer and later +//! gets the object. Every actor's read can be arbitrarily stale: that is what the interleaving quantifies over. +//! +//! # What is proven, and what the pointer of another incarnation costs (FINDING F1b) +//! +//! No order between incarnations is assumed (no clock), so a pointer of another incarnation is replaceable: a slow exporter of a +//! dead incarnation can replace the live pointer, and a stale live exporter can then replace THAT with a payload a prune already +//! deleted. The pointer then DANGLES: it names a payload that does not exist. So "the pointer's target exists" is not an +//! invariant of this world, and is not claimed. What holds, for every incarnation: +//! +//! * **(a) safety**: a fetch gets the payload its read named or a detected miss, never another payload +//! ([`a_fetch_gets_its_payload_or_a_detected_miss`]), also in the state where the pointer dangles +//! ([`finding_f1b_a_dangling_pointer_is_a_detected_miss`]); the pointer never regresses within an incarnation +//! ([`the_pointer_never_regresses`]); a restore never takes a foreign artifact (`fleet_proofs`); +//! * **(b) liveness**: the window of a dangling pointer is bounded by the live exporter's round +//! ([`a_live_round_ends_the_dangling_window`], ranking function [`rho`]): its round replaces the pointer with a payload that +//! exists, in at most one round plus one re-read per dead round still in flight. //! //! # Environment axioms //! //! * **O1** a payload path names its content for ever (content addressing; a hash collision is the only way to break it); //! * **O2** the pointer object is written only by [`Act::Swap`] (nothing else deletes or rewrites it); //! * **O3** a compare-and-swap succeeds exactly when the object is unchanged since the read (`ver`); -//! * **O4** (scope) the pointer stays in one incarnation: every payload and the pointer are of [`TS::inc`]. Across incarnations -//! nothing orders them (no clock is assumed): a pointer of another incarnation is replaceable (`a_pointer_of_another_incarnation_ -//! never_refuses_a_publish`, proven on the guard), and what that costs is FINDING F1b in `fleet_proofs`: a slow exporter of a dead -//! incarnation moves the pointer out, and a stale live exporter can then publish a payload a prune already deleted. The -//! invariants below are therefore the within-incarnation protocol, which is what every pointer swap of a live fleet runs. +//! * **F-e** (liveness only) while the live exporter's round runs, no round starts: the export lease admits one live round at a +//! time, and a node of a dead stream starts no new round after the recreation (it re-seeds as a live one first), so the dead +//! rounds in flight are finitely many ([`credits`]); +//! * **F-h** (liveness only) the live exporter exports at the live head, which is at least every live rank the pointer or a pruner's +//! read holds (nothing of the live incarnation is published above the head), and its own payload exists when the round starts; +//! * **F-c** the object store answers (the existing fairness axiom: a round's steps run). use crate::kernels::protocol::*; use vstd::prelude::*; @@ -55,8 +72,8 @@ pub enum Actor { } pub struct TS { - /// The incarnation every payload and the pointer belong to (the scope of this proof). - pub inc: u64, + /// The live stream incarnation (what the liveness theorem calls live; no safety statement mentions it). + pub live: u64, /// The pointer's target payload, once one is published. Its position is the target's. pub ptr: Option, /// Successful swaps so far. @@ -102,7 +119,7 @@ pub open spec fn valid(s: TS, i: int) -> bool { pub open spec fn enabled(s: TS, a: Act) -> bool { match a { - Act::Upload(i, p) => valid(s, i) && actor(s, i) is Idle && p.origin == s.inc, + Act::Upload(i, p) => valid(s, i) && actor(s, i) is Idle, Act::Observe(i) => valid(s, i) && actor(s, i) is Uploaded, Act::Swap(i) => valid(s, i) && actor(s, i) is Observed && actor(s, i)->Observed_ver == s.ver, Act::Reread(i) => valid(s, i) && actor(s, i) is Observed && actor(s, i)->Observed_ver != s.ver, @@ -149,38 +166,31 @@ pub open spec fn fetched(s: TS, t: Payload) -> Option { if s.objs.contains(t) { Some(t) } else { None } } -/// An actor's reads are consistent with the store (whatever the interleaving). +/// An actor's reads are consistent with the store (whatever the interleaving): an exporter that read the pointer holds the guard's +/// verdict, at a version no later than the pointer's, and still current while the version is. pub open spec fn actor_ok(s: TS, a: Actor) -> bool { match a { - Actor::Idle => true, - // An uploaded payload exists, or was pruned because the pointer is strictly past it. - Actor::Uploaded { p } => p.origin == s.inc && (s.objs.contains(p) || (s.ptr is Some && pos_lt(pos(p), pos(s.ptr->Some_0)))), Actor::Observed { p, st, ver } => { - &&& p.origin == s.inc &&& publish_allowed_spec(st, pos(p)) &&& ver <= s.ver - // Same as `Uploaded`, whatever the version: a lost CAS goes back to `Uploaded`. - &&& (s.objs.contains(p) || (s.ptr is Some && pos_lt(pos(p), pos(s.ptr->Some_0)))) - // The read is current while the version is: so the guard's verdict still stands. &&& (ver == s.ver ==> st == pstate(s.ptr)) }, - Actor::Pruning { pr, keep } => s.ptr is Some && pr.origin == s.inc && pr.rank <= s.ptr->Some_0.rank, - Actor::Fetching { t } => t.origin == s.inc && (s.objs.contains(t) || (s.ptr is Some && pos_lt(pos(t), pos(s.ptr->Some_0)))), + _ => true, } } -/// THE invariant: the pointer's target exists, and every actor's reads are consistent. +/// THE invariant, over every incarnation: every actor's reads are consistent. (That the pointer's target exists is NOT part of it: +/// see FINDING F1b.) pub open spec fn inv(s: TS) -> bool { - &&& s.ptr is Some ==> s.objs.contains(s.ptr->Some_0) && s.ptr->Some_0.origin == s.inc - &&& forall|i: int| 0 <= i < s.actors.len() ==> actor_ok(s, #[trigger] s.actors[i]) + forall|i: int| 0 <= i < s.actors.len() ==> actor_ok(s, #[trigger] s.actors[i]) } /// THEOREM: the empty store with `n` idle actors satisfies the invariant, for any `n`. -pub proof fn a_fresh_store_satisfies_the_invariant(inc: u64, actors: Seq) +pub proof fn a_fresh_store_satisfies_the_invariant(live: u64, actors: Seq) requires forall|i: int| 0 <= i < actors.len() ==> #[trigger] actors[i] is Idle, ensures - inv(TS { inc, ptr: None, ver: 0, objs: Set::empty(), actors }), + inv(TS { live, ptr: None, ver: 0, objs: Set::empty(), actors }), { } @@ -208,21 +218,20 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) if j != i { assert(s1.actors[j] == s.actors[j]); } else if publish_allowed_spec(pstate(s.ptr), pos(pp)) { - assert(actor_ok(s, s.actors[i])); - // Admitted: the candidate is not below the pointer, so it was not pruned: it exists. - assert(s.objs.contains(pp)); + assert(s1.actors[j] == (Actor::Observed { p: pp, st: pstate(s.ptr), ver: s.ver })); + } else { + assert(s1.actors[j] == Actor::Idle); } }, Act::Swap(i) => { if j != i { assert(s1.actors[j] == s.actors[j]); + } else { + assert(s1.actors[j] == Actor::Idle); } }, Act::Reread(i) => { - let pp = actor(s, i)->Observed_p; - if j == i { - assert(actor_ok(s, s.actors[i])); - } else { + if j != i { assert(s1.actors[j] == s.actors[j]); } }, @@ -233,12 +242,6 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) }, Act::Delete(i, o) => { assert(s1.actors[j] == s.actors[j]); - let pr = actor(s, i)->Pruning_pr; - let t = s.ptr->Some_0; - assert(actor_ok(s, s.actors[i])); - // `o` is strictly below the pruner's read of the pointer, which is at most the pointer's position now. - assert(pos_lt(pos(o), pr)); - assert(pr.rank <= t.rank); }, Act::FetchRead(i) => { if j != i { @@ -252,69 +255,44 @@ pub proof fn every_step_preserves_the_invariant(s: TS, a: Act) }, } } - if s1.ptr is Some { - match a { - Act::Swap(i) => { - assert(actor_ok(s, s.actors[i])); - }, - Act::Delete(i, o) => { - let pr = actor(s, i)->Pruning_pr; - assert(actor_ok(s, s.actors[i])); - assert(pos_lt(pos(o), pr)); - assert(o != s.ptr->Some_0); - }, - _ => {}, - } - } } - -/// THEOREM (the pointer never regresses, for every interleaving of N exporters): every step either leaves the pointer alone or -/// moves it to a payload whose position (incarnation, then revision) is at least the old one, and a published pointer is never removed. This is -/// `a_publish_never_regresses_the_pointer` lifted from one decision to the whole protocol: the guard decided on a read, but the -/// swap succeeds only against that read (O3), so the read is the pointer being replaced. +/// THEOREM (the pointer never regresses within an incarnation, for every interleaving of N exporters): every step either leaves the +/// pointer alone or moves it to a payload that is not strictly below the old one in its incarnation ([`pos_lt`]: a pointer of +/// another incarnation is replaceable, so nothing orders it), and a published pointer is never removed. This is +/// `a_publish_never_regresses_the_pointer_within_an_incarnation` lifted from one decision to the whole protocol: the guard decided +/// on a read, but the swap succeeds only against that read (O3), so the read is the pointer being replaced. pub proof fn the_pointer_never_regresses(s: TS, a: Act) requires inv(s), enabled(s, a), ensures - s.ptr is Some ==> step(s, a).ptr is Some && step(s, a).ptr->Some_0.rank >= s.ptr->Some_0.rank - && step(s, a).ptr->Some_0.origin == s.inc, + s.ptr is Some ==> step(s, a).ptr is Some && !pos_lt(pos(step(s, a).ptr->Some_0), pos(s.ptr->Some_0)), { match a { Act::Swap(i) => { assert(actor_ok(s, s.actors[i])); - let p = actor(s, i)->Observed_p; - if s.ptr is Some { - a_publish_never_regresses_the_pointer_within_an_incarnation(pstate(s.ptr), pos(p)); - } }, _ => {}, } } -/// THEOREM (prune never deletes the pointer's target): at any moment, whatever a pruner read earlier, the object it is allowed to -/// delete is not the pointer's current target. The pruner's read of the pointer is stale, but the pointer's position only grows, and -/// the guard deletes only strictly below the pruner's read (`the_target_and_unknown_objects_are_never_pruned` is the guard's own -/// half). -pub proof fn prune_never_deletes_the_pointers_target(s: TS, i: int, o: Payload) +/// THEOREM (a prune deletes only below its own read): whatever the pruner read, and however long ago, what it may delete is +/// strictly below that read in the read pointer's incarnation. (That the object is not the pointer's CURRENT target is true within +/// an incarnation and not across them: FINDING F1b.) +pub proof fn a_prune_deletes_only_below_what_it_read(s: TS, i: int, o: Payload) requires inv(s), enabled(s, Act::Delete(i, o)), ensures - s.ptr is Some, - s.ptr->Some_0 != o, - inv(step(s, Act::Delete(i, o))), - step(s, Act::Delete(i, o)).objs.contains(step(s, Act::Delete(i, o)).ptr->Some_0), + pos_lt(pos(o), actor(s, i)->Pruning_pr), + o != actor(s, i)->Pruning_keep, { - assert(actor_ok(s, s.actors[i])); - every_step_preserves_the_invariant(s, Act::Delete(i, o)); } -/// THEOREM (a fetch races a prune: the object it named, or a detected miss, never another payload): a get answers the payload -/// its read named (a path names its content, O1) or a miss; and a miss means the pointer has strictly moved on since the read, so -/// a re-read names a payload that exists and, by `prune_never_deletes_the_pointers_target`, stays until the pointer moves again. -/// (A fetch that does not race a prune never misses: the target exists.) +/// THEOREM (a) (a fetch gets its payload or a detected miss, never another payload): a get answers the payload its read named (a +/// path names its content, O1) or a miss. A miss means the object is gone: it was pruned. This holds in every state, the one where +/// the pointer dangles included. pub proof fn a_fetch_gets_its_payload_or_a_detected_miss(s: TS, i: int) requires inv(s), @@ -324,37 +302,264 @@ pub proof fn a_fetch_gets_its_payload_or_a_detected_miss(s: TS, i: int) let t = actor(s, i)->Fetching_t; match fetched(s, t) { Some(x) => x == t, - None => s.ptr is Some && pos_lt(pos(t), pos(s.ptr->Some_0)) && s.objs.contains(s.ptr->Some_0), + None => !s.objs.contains(t), } }), { - assert(actor_ok(s, s.actors[i])); } -/// THEOREM (liveness: a refused fetch retries): after a miss, a fresh read names the pointer's current target, which exists, so -/// the get answers it. The only way to miss again is for the pointer to move again, strictly upward. Rank: the pointer's position -/// (monotone), unbounded, but each miss is paid for by one publish, so a fetch retries at most once per publish. Fairness -/// assumption: the publishers do not publish for ever between a read and its get (the environment, not this code). -pub proof fn a_fresh_read_never_misses_without_a_publish(s: TS, i: int) +/// THEOREM (a publisher's refusal clears): a lost CAS is never final: the exporter re-reads, and the version it lost to is a +/// publish that moved the pointer. +pub proof fn a_lost_cas_means_a_publish_happened(s: TS, i: int) requires inv(s), - s.ptr is Some, + enabled(s, Act::Reread(i)), ensures - s.objs.contains(s.ptr->Some_0), + actor(s, i)->Observed_ver < s.ver, { + assert(actor_ok(s, s.actors[i])); } -/// THEOREM (a publisher's refusal clears): an exporter refused by the guard (the pointer strictly newer) is refused for as long as -/// the pointer stays newer, and the pointer never regresses, so its exit is a fresher export (`a_publish_at_or_above_the_pointer_is_admitted`). -/// A lost CAS is never final: the exporter re-reads, and the version it lost to is a publish that raised the pointer. -pub proof fn a_lost_cas_means_a_publish_happened(s: TS, i: int) +// --------------------------------------------------------------------------------------------------------------------- +// FINDING F1b: the pointer can dangle. (a) holds there; (b) is the theorem below. +// --------------------------------------------------------------------------------------------------------------------- + +/// The pointer names a payload that does not exist. +pub open spec fn dangling(s: TS) -> bool { + s.ptr is Some && !s.objs.contains(s.ptr->Some_0) +} + +/// FINDING F1b, the state: with no order between incarnations, a slow exporter of a dead incarnation `b` may replace the live +/// pointer `(a, big)` (admitted: another incarnation's), and a STALE live exporter may then replace that (admitted likewise) with a +/// payload `(a, r)` the prune guard had already deleted (it was strictly below the live pointer when pruned). Every step is a guard +/// verdict below. +pub proof fn finding_f1b_a_dead_exporter_lets_a_pruned_payload_be_published(a: u64, b: u64, r: u64, big: u64) + requires + a != b, + r < big, + ensures + prunable_spec(Some(Pos { origin: a, rank: r }), Pos { origin: a, rank: big }, false, true), + publish_allowed_spec(PointerState::Present { at: Some(Pos { origin: a, rank: big }) }, Pos { origin: b, rank: 1 }), + publish_allowed_spec(PointerState::Present { at: Some(Pos { origin: b, rank: 1 }) }, Pos { origin: a, rank: r }), +{ +} + +/// THEOREM (a) in the F1b state: when the pointer dangles, a fetch of its target is a DETECTED miss (the object is gone), never +/// another payload: the window is loud, and a restore of it is refused by `same_incarnation` or fails to fetch, never takes wrong data. +pub proof fn finding_f1b_a_dangling_pointer_is_a_detected_miss(s: TS) + requires + dangling(s), + ensures + fetched(s, s.ptr->Some_0) is None, +{ +} + +// --------------------------------------------------------------------------------------------------------------------- +// (b) LIVENESS: the window of a dangling pointer ends with the live exporter's round. +// --------------------------------------------------------------------------------------------------------------------- + +/// An exporter mid-round whose payload is of another incarnation than the live one. +pub open spec fn dead_flight(live: u64, a: Actor) -> bool { + match a { + Actor::Uploaded { p } => p.origin != live, + Actor::Observed { p, st, ver } => p.origin != live, + _ => false, + } +} + +/// An exporter mid-round whose payload is of the live incarnation. +pub open spec fn live_flight(live: u64, a: Actor) -> bool { + match a { + Actor::Uploaded { p } => p.origin == live, + Actor::Observed { p, st, ver } => p.origin == live, + _ => false, + } +} + +pub open spec fn flight(live: u64, a: Actor) -> nat { + if dead_flight(live, a) { 1 } else { 0 } +} + +/// The dead rounds in flight among the first `n` actors. +pub open spec fn credits_upto(actors: Seq, live: u64, n: nat) -> nat + decreases n, +{ + if n == 0 { + 0 + } else if n > actors.len() { + credits_upto(actors, live, actors.len()) + } else { + credits_upto(actors, live, (n - 1) as nat) + flight(live, actors[(n - 1) as int]) + } +} + +/// The dead rounds in flight: finitely many (F-e), and each ends with a swap or a refused guard. +pub open spec fn credits(s: TS) -> nat { + credits_upto(s.actors, s.live, s.actors.len()) +} + +/// The live exporter `i`'s distance to the end of its round: Uploaded 2, Observed 1, Observed on a stale read (it lost its CAS) 3, +/// otherwise 0. +pub open spec fn phase(s: TS, a: Actor) -> int { + match a { + Actor::Uploaded { p } => 2, + Actor::Observed { p, st, ver } => if ver == s.ver { 1 } else { 3 }, + _ => 0, + } +} + +/// THE RANK of the live exporter `i`'s round: four per dead round still in flight, plus its own phase. A dead round's swap or +/// refusal lowers it by four and can make `i`'s read stale (up by two); `i`'s own steps lower it. +pub open spec fn rho(s: TS, i: int) -> int { + 4 * credits(s) + phase(s, actor(s, i)) +} + +pub open spec fn payload_of(a: Actor) -> Payload { + match a { + Actor::Uploaded { p } => p, + Actor::Observed { p, st, ver } => p, + _ => Payload { origin: 0, rank: 0, digest: 0 }, + } +} + +/// The live exporter `i` is mid-round (F-e: the lease admits one live round, so no other actor is in a live round), its payload +/// exists, and it exports at the live head (F-h): no live rank in the pointer or in a pruner's read exceeds its own. +pub open spec fn round_ok(s: TS, i: int) -> bool { + &&& valid(s, i) + &&& live_flight(s.live, actor(s, i)) + &&& s.objs.contains(payload_of(actor(s, i))) + &&& (s.ptr is Some && s.ptr->Some_0.origin == s.live ==> s.ptr->Some_0.rank <= payload_of(actor(s, i)).rank) + &&& forall|j: int| 0 <= j < s.actors.len() && j != i ==> !live_flight(s.live, #[trigger] s.actors[j]) + &&& forall|j: int| + 0 <= j < s.actors.len() && #[trigger] s.actors[j] is Pruning && s.actors[j]->Pruning_pr.origin == s.live + ==> s.actors[j]->Pruning_pr.rank <= payload_of(actor(s, i)).rank +} + +/// Updating one actor changes the credits by the difference of the two actors' flights. +proof fn credits_update(actors: Seq, live: u64, i: int, a2: Actor, n: nat) + requires + 0 <= i < actors.len(), + ensures + credits_upto(actors.update(i, a2), live, n) as int == credits_upto(actors, live, n) as int + + (if i < n { flight(live, a2) as int - flight(live, actors[i]) as int } else { 0int }), + decreases n, +{ + broadcast use vstd::seq_lib::group_seq_properties; + if n == 0 { + } else if n > actors.len() { + credits_update(actors, live, i, a2, actors.len()); + } else { + credits_update(actors, live, i, a2, (n - 1) as nat); + assert(actors.update(i, a2).len() == actors.len()); + if (n - 1) as int == i { + assert(actors.update(i, a2)[(n - 1) as int] == a2); + } else { + assert(actors.update(i, a2)[(n - 1) as int] == actors[(n - 1) as int]); + } + } +} + +/// THEOREM (b) (the dangling window ends with the live exporter's round): while the live exporter `i` runs its round (no round +/// starts meanwhile: F-e), every step of the world either leaves its rank [`rho`] where it was or lowers it, and every step of `i` +/// itself lowers it: its read of the pointer is admitted (the pointer is not above its payload, so the guard cannot refuse it: +/// the refusal clears), its swap succeeds against a fresh read, a lost CAS (a dead round's swap, which lowered the credits) takes +/// it back to a re-read. Its payload exists throughout (a prune never deletes it: every live read is at most its rank), so the +/// swap that ends the round leaves a pointer whose target EXISTS: the pointer no longer dangles. The window is therefore at most +/// one round plus one re-read per dead round in flight, and in it a fetch is a detected miss (a), never wrong data. +pub proof fn a_live_round_ends_the_dangling_window(s: TS, i: int, a: Act) requires inv(s), - enabled(s, Act::Reread(i)), + round_ok(s, i), + enabled(s, a), + !(a is Upload), ensures - actor(s, i)->Observed_ver < s.ver, + inv(step(s, a)), + // `i`'s own steps lower the rank; every other step does not raise it. + (a is Observe && a->Observe_0 == i) ==> actor(step(s, a), i) is Observed && rho(step(s, a), i) < rho(s, i), + (a is Reread && a->Reread_0 == i) ==> live_flight(s.live, actor(step(s, a), i)) && rho(step(s, a), i) < rho(s, i), + (a is Swap && a->Swap_0 == i) ==> !dangling(step(s, a)) && step(s, a).ptr == Some(payload_of(actor(s, i))), + !(a is Observe && a->Observe_0 == i) && !(a is Reread && a->Reread_0 == i) && !(a is Swap && a->Swap_0 == i) + ==> round_ok(step(s, a), i) && rho(step(s, a), i) <= rho(s, i), { - assert(actor_ok(s, s.actors[i])); + broadcast use vstd::seq_lib::group_seq_properties; + every_step_preserves_the_invariant(s, a); + let ai = actor(s, i); + let p = payload_of(ai); + let s1 = step(s, a); + assert(actor_ok(s, ai)); + match a { + Act::Observe(j) => { + let pj = actor(s, j)->Uploaded_p; + if j == i { + // The pointer is not above `p` in its own incarnation, so the guard admits the candidate. + assert(publish_allowed_spec(pstate(s.ptr), pos(p))); + assert(s1.actors[i] == (Actor::Observed { p, st: pstate(s.ptr), ver: s.ver })); + credits_update(s.actors, s.live, i, s1.actors[i], s.actors.len()); + } else { + // A dead exporter reads the pointer: it stays in flight or ends its round. + assert(!live_flight(s.live, actor(s, j))); + assert(s1.actors[i] == s.actors[i]); + let a2 = s1.actors[j]; + credits_update(s.actors, s.live, j, a2, s.actors.len()); + assert(flight(s.live, a2) <= flight(s.live, actor(s, j))); + assert(s1.ptr == s.ptr && s1.objs == s.objs && s1.ver == s.ver); + } + }, + Act::Swap(j) => { + if j == i { + assert(s1.ptr == Some(p)); + assert(s1.objs == s.objs); + } else { + // A dead round ends: the pointer is dead, the credits fall by one, `i`'s read goes stale. + assert(!live_flight(s.live, actor(s, j))); + let pj = payload_of(actor(s, j)); + assert(pj.origin != s.live); + assert(dead_flight(s.live, actor(s, j))); + assert(s1.actors[j] == Actor::Idle); + credits_update(s.actors, s.live, j, Actor::Idle, s.actors.len()); + assert(s1.actors[i] == s.actors[i]); + assert(s1.ver == s.ver + 1); + assert(s1.objs == s.objs); + assert(s1.ptr == Some(pj)); + } + }, + Act::Reread(j) => { + if j == i { + assert(ai is Observed); + assert(actor(s1, i) == (Actor::Uploaded { p })); + credits_update(s.actors, s.live, i, s1.actors[i], s.actors.len()); + } else { + assert(s1.actors[i] == s.actors[i]); + credits_update(s.actors, s.live, j, s1.actors[j], s.actors.len()); + } + }, + Act::PruneRead(j) => { + assert(s1.actors[i] == s.actors[i]); + credits_update(s.actors, s.live, j, s1.actors[j], s.actors.len()); + if s.ptr->Some_0.origin == s.live { + assert(s.ptr->Some_0.rank <= p.rank); + } + }, + Act::Delete(j, o) => { + assert(actor_ok(s, s.actors[j])); + // `o` is strictly below the pruner's read in its incarnation; every live read is at most `p`'s rank, so `o` is not `p`. + assert(s.actors[j] is Pruning); + if o == p { + assert(pos_lt(pos(o), s.actors[j]->Pruning_pr)); + assert(p.origin == s.live); + } + assert(s1.actors == s.actors); + }, + Act::FetchRead(j) => { + assert(s1.actors[i] == s.actors[i]); + credits_update(s.actors, s.live, j, s1.actors[j], s.actors.len()); + }, + Act::FetchGet(j) => { + assert(s1.actors[i] == s.actors[i]); + credits_update(s.actors, s.live, j, s1.actors[j], s.actors.len()); + }, + Act::Upload(j, q) => {}, + } } } // verus! From b73937cbbb320210843d5194c7261f4b1ea946c6 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 20:04:27 -0800 Subject: [PATCH 7/7] F1b premises are theorems: export guard, lease takeover guard, converged exporter at the head; the axiom list is the environment only Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 8 +- Cargo.toml | 2 + src/applied.rs | 126 +++++++++++++++++++++++++++++++- src/export_lease.rs | 7 +- src/kernels/fleet_proofs.rs | 20 ++++- src/kernels/protocol.rs | 107 +++++++++++++++++++++++++++ src/kernels/transport_proofs.rs | 29 +++++--- 7 files changed, 279 insertions(+), 20 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b10a5a2..f7c1275 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -354,6 +354,8 @@ Every decision the protocol's correctness rests on is a pure function in `src/ke | `plan_repair` | `repair::plan`, `Snapshot::stale_keys` | every model's expiry dispatch | | `cursorless_start_needs_repair` | `repair::run_watch` | `model_repair.rs`, `model_fleet.rs` | | `restore_key` | `repair::restore_diff` | `model_repair.rs`, `fleet_proofs.rs` | +| `export_allowed` | `applied::Fold::export` (every export round) | `tests/recreated_fleet.rs`, `applied::tests::a_fold_of_a_dead_stream_exports_nothing`, Verus | +| `lease_takeover_allowed` | `export_lease::try_acquire` | Verus (`a_held_lease_is_never_taken`) | | `cursorless_fold_is_this_stream` | `repair::run_watch` (a fold with data and no cursor) | `tests/recreated_fleet.rs` (live), Verus | **The cursor-authority kernel** (`src/kernels/applied.rs`) is the one stateful kernel: `step(state, event) -> (state, actions)`, no I/O, async or clock. `applied::Fold` turns what it observes (a received update, a flush request, a store result, an export or repair request) into an `Event`, calls `step`, and runs the returned `Action`s through its interpreter; it decides nothing itself. The kernel owns what has no other home: whether a batch is open, whether a stream position is pending, the unsynced eviction memo, the store-failure streak, and where an in-flight flush or resync is. It decides which flush steps run and in which order (domain `apply` before the cursor moves), that a failed store fold re-queues its raw batch at the front (and the streak bound that fail-stops), that an export flushes first, that the resync's ack follows the folded deletes, and the artifact restore's order: ahead check, diff, listing with its window re-check (only when there are delete candidates), chunks folded under the old cursor, the cursor commit, then the reply; a refusal (not ahead, window aged) replies with an error before anything is folded. The restore's phase is kernel state, so an event out of phase is ignored and a restart (a fresh state) re-runs the whole repair. The data (updates, cursors, the store) stay in the shell. The three applied models call it too (`tests/model_applied.rs`, `tests/model_resync_order.rs`, `tests/model_repair.rs`, through `slipstream::cursor_kernel`): they keep only environment state (deliveries, store contents, crashes, the bucket) and feed `step` events. Their mutations are cargo features that break the kernel itself (`mut_drop_failed_batch`, `mut_resume_from_memory`, `mut_no_ack_barrier`, and for the repair steps `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_restore_guard`, `mut_no_listing_recheck`; the protocol-kernel ones `mut_relist_on_evicting`, `mut_unanchored_relist`, `mut_restore_ignores_versions`, `mut_restore_ignores_listing`, `mut_restore_trusts_foreign`, `mut_pointer_ignores_incarnation`, `mut_no_eviction_memo` break `protocol.rs` (and `mut_foreign_keeps_memo` the repair's forgetting of a foreign cursor)); each turns its model red, and they are for model tests only, never production builds. @@ -513,17 +515,17 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut **The statement.** `finv`: every node of the current incarnation holds a real fold (every entry a write of the log) that is *complete* at its cursor `c`: equal to the truth at `c` on every key not written after `c`; every published artifact of the current incarnation likewise. Exact equality at `c` is not what the code keeps and is not an invariant (F3): an artifact at `C` is complete together with the log after `C`, and a restore keeps the stale entry of a key the bucket lists live (`restore_key`) because the resume delivers its later write. At the head every key is "not written since", so a converged node holds exactly the truth. The Stateright model (`tests/model_fleet.rs`: one key, atomic repair) states the stronger "equals the truth at its cursor" and passes only because of those bounds; the statement the code keeps is this one. -**Environment axioms (the liveness rests on these and on nothing in slipstream).** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes. For the transport: *O1* a payload path names its content for ever; *F-e* (the transport liveness) while the live exporter's round runs no round starts: the export lease admits one live round and a dead stream's nodes start none after the recreation; *F-h* it exports at the live head; *O2* the pointer is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read. Also: **O4** (scope of the transport proofs) the pointer stays in one incarnation: nothing orders two incarnations and no clock is assumed (a pointer of another incarnation is replaceable; F1b is the cost); the retention config is constant inside an incarnation (the `seen_evicting` memo guards a toggle; a foreign cursor forgets it); positions are `u64`; the relist (key-listing repair) is one atomic step (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. +**Environment axioms: the environment (NATS, the disk, the object store, clocks) and nothing of slipstream's.** *F-a* NATS delivers a received revision while its window holds; *F-b* the disk works (a flush lands, chunks fold, the commit flushes); *F-c* the object store answers (publish, the artifact read); *F-d* quiescence: from some point the log takes no more writes, evictions or recreations and nodes no more crashes; *O1* a payload path names its content for ever; *O2* the pointer object is written only by a publish; *O3* a compare-and-swap succeeds exactly when the object is unchanged since the read (the object store, and the KV store under the lease); *T* a round finishes before its lease lapses (the clock, and an object store that answers within the round period); *I* a recreated stream has a different creation time than the one it replaces (equality only: no order between incarnations, no clock order); *R* the retention config is constant inside an incarnation, and the retention read reports the stream as it is; *A2* positions and creation times fit `u64`. Everything else the proofs use is a theorem of slipstream's code: the lease's takeover guard (`a_held_lease_is_never_taken`), the export guard (`export_allowed`: a fold exports only a cursor of the stream that exists now), the pointer and prune guards, the restore guards, the foreign-cursor repair. Scope, not axioms: the relist (key-listing repair) is one atomic step here (its steps are `tests/model_repair.rs`, `tests/resync.rs`); a cursor with no recorded origin is `tests/model_incarnation.rs`'s. **Findings the proofs surfaced** (each a Verus-checked concrete state of the shipped decisions, in `fleet_proofs.rs`; F1, F2 and F4 were real bugs, reached against a live nats-server in `tests/recreated_fleet.rs`, and are fixed; the proof no longer carries a premise that excluded them): - **F1** (`finding_f1_*`) the pointer guard compared ranks only, never the incarnation. A pointer whose artifact was the old stream's, ranked above the new head, refused every publish of the new stream until the head passed it, while `same_incarnation` refused to restore from it: a node that must restore had no artifact though other nodes held the head. Reachable: `swap_pointer` read only `cursor.rank()`, and the exporter's candidate was whatever its fold held. Fixed: ranks are ordered only within an incarnation (`protocol::Pos`) and a pointer of another incarnation is replaceable, like a corrupt one, so the new stream's first publish replaces a dead incarnation's pointer; no clock and no order between incarnations is assumed. The payload name carries the incarnation so `prune` only judges payloads of the pointer's own incarnation (`payload_prunable`). Test `a_dead_incarnations_pointer_does_not_refuse_the_new_streams_publish`. The liveness theorem lost its hypothesis. -- **F1b** (`finding_f1b_*`, `a_live_round_ends_the_dangling_window`) the price of F1's fix, bounded and proven, not assumed away: after a bucket recreation, a fetch can miss until the next live export round. With no order between incarnations a slow exporter of a dead incarnation can move the live pointer out of its incarnation, and a stale live exporter can then publish a payload the prune guard had already deleted (it was below the live pointer): the pointer dangles, so "the pointer's target exists" is not an invariant over all incarnations and is not claimed. (a) Safety, in every state: a fetch gets the payload its read named or a detected miss, never another payload, and a restore never takes a foreign artifact. (b) Liveness: the live exporter's round (the lease admits one at a time; a dead stream's nodes start no new round after the recreation) replaces the dangling pointer with a payload that exists, in at most one round plus one re-read per dead round still in flight: its read is admitted because it exports at the live head, its payload cannot be pruned (every live read is at most its rank), and a lost CAS is paid by a dead round's swap (ranking function `rho`). So the window is bounded, loud (a detected miss) and never serves wrong data. The proof's hypotheses are named axioms (F-e: no round starts during the window; F-h: the live exporter exports at the live head); without F-h it is red. +- **F1b** (`finding_f1b_*`, `a_live_round_ends_the_dangling_window`) the price of F1's fix, bounded and proven, not assumed away: after a bucket recreation, a fetch can miss until the next live export round. With no order between incarnations a slow exporter of a dead incarnation can move the live pointer out of its incarnation, and a stale live exporter can then publish a payload the prune guard had already deleted (it was below the live pointer): the pointer dangles, so "the pointer's target exists" is not an invariant over all incarnations and is not claimed. (a) Safety, in every state: a fetch gets the payload its read named or a detected miss, never another payload, and a restore never takes a foreign artifact. (b) Liveness: the live exporter's round (the lease admits one at a time; a dead stream's nodes start no new round after the recreation) replaces the dangling pointer with a payload that exists, in at most one round plus one re-read per dead round still in flight: its read is admitted because it exports at the live head, its payload cannot be pruned (every live read is at most its rank), and a lost CAS is paid by a dead round's swap (ranking function `rho`). So the window is bounded, loud (a detected miss) and never serves wrong data. The proof's hypotheses are named premises (each a theorem of slipstream's code, not an axiom: the live round runs alone (`a_held_lease_is_never_taken`, with the clock axiom T); no round starts after the recreation (`export_allowed` refuses a dead stream's export); the exporter is at the live head once its fold converges (`a_converged_exporter_is_at_the_live_head`)); without the head premise it is red. - **F2** (`finding_f2_*`) a restore over the fold of a recreated stream kept old entries that carried a higher revision number than the artifact's (`restore_key` decided by revision number), and refused an artifact below the old cursor's rank as "not ahead" (`restore_request` compared against the foreign cursor the fold still held). Reachable: `ForeignCursor` with a repair armed ran the restore over the old fold (`repair::run_watch`). Fixed: the repair forgets the foreign cursor (`Fold::forget_cursor`) and the restore of a fold of another incarnation takes the artifact key for key (`restore_key`'s `local_known`). Tests `a_restore_over_a_foreign_fold_replaces_entries_the_old_stream_numbered_higher`, `a_restore_over_a_foreign_fold_is_not_barred_by_the_old_cursors_rank`. A fold that holds data and no cursor (a torn first checkpoint) is judged by its own record: a fold persists the incarnation of its stream before its first data record (`AppendLogSnapshot::apply` writes an origin-only cursor record first, and `compact_to_file` keeps it ahead of the data; fjall and RocksDB commit data and cursor in one atomic batch, so the cursor's origin is the record). On start, `cursorless_fold_is_this_stream` compares it with the stream's incarnation: a match is this stream's (trusted, so "never backward" holds), another incarnation is foreign (the F2 path), and no record is foreign too (fail closed). The commits a repair makes under a cursor-less fold of this stream keep recording its incarnation (`Fold::stamp_incarnation`); a restore over a foreign fold commits under no cursor, so a crash part-way leaves a fold that names no stream and the whole repair runs again. The last case is only files written before folds recorded an incarnation: a one-time re-seed on upgrade. Test `a_torn_first_checkpoint_of_the_old_stream_is_foreign_to_the_recreated_one`. - **F3** (`finding_f3_*`) the statement above: complete, not exact. - **F4** (`finding_f4_*`) the eviction memo (`seen_evicting`) rode the cursor and survived a recreation (the task's copy, and the fold's, which carried it over every cursor it advanced). On the new, un-evicted bucket the exact listing was distrusted and a restore planned; a fleet whose nodes are all foreign has no node to publish an artifact of the new stream, so none could start. Fixed with F2's `forget_cursor`: the memo goes with the cursor, and the new stream's retention is read afresh. Test `the_old_streams_eviction_memo_does_not_distrust_the_new_streams_listing`. -`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_restore_trusts_foreign` fails `restore_key`'s contract, `a_restore_over_a_foreign_fold_is_the_artifact` and `finding_f2_*`; `mut_pointer_ignores_incarnation` fails `pointer_publish_allowed`'s contract and `finding_f1_*`; `mut_foreign_keeps_memo` fails `finding_f4_*` (and the live test); `mut_cursorless_fold_trusted` fails `cursorless_fold_is_this_stream`'s contract; `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. +`mise run verify` runs both files. Mutations (`--features mut_x`) turn these red: `mut_no_restore_guard` fails `lemma_begin` (the artifact is ahead of the cursor) and `prog_repair` (the artifact is inside the window); `mut_relist_on_evicting` and `mut_unanchored_relist` fail `lemma_relist` (the re-listed fold is the truth); `mut_restore_ignores_versions` and `mut_restore_ignores_listing` fail `a_restore_never_moves_a_key_backward_or_deletes_a_live_one`; `mut_restore_trusts_foreign` fails `restore_key`'s contract, `a_restore_over_a_foreign_fold_is_the_artifact` and `finding_f2_*`; `mut_pointer_ignores_incarnation` fails `pointer_publish_allowed`'s contract and `finding_f1_*`; `mut_foreign_keeps_memo` fails `finding_f4_*` (and the live test); `mut_cursorless_fold_trusted` fails `cursorless_fold_is_this_stream`'s contract; `mut_export_ignores_stream` fails `export_allowed`'s contract and `a_fold_of_a_dead_stream_exports_nothing`; `mut_resume_from_memory` fails `lemma_crash` and `a_restart_preserves_the_invariant`. `mut_no_eviction_memo` guards a retention toggle, which the closed world excludes; it fails `listing_is_truth`'s contract only. The `applied` ones (`mut_drop_failed_batch`, `mut_no_ack_barrier`, `mut_no_drain`, `mut_no_settle_retry`, `mut_cursor_before_diff`, `mut_no_listing_recheck`) fail `step`'s equality with `step_spec`, which every fleet node runs. ### Export Round State Machine diff --git a/Cargo.toml b/Cargo.toml index eb9566b..7a4d3b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -107,6 +107,8 @@ mut_restore_ignores_versions = [] mut_restore_ignores_listing = [] # The pointer guard compares revisions across incarnations (a dead incarnation's pointer wedges publishing). mut_pointer_ignores_incarnation = [] +# A fold exports itself whatever its cursor says (a foreign or cursor-less fold publishes). +mut_export_ignores_stream = [] # A fold with data and no cursor is trusted whatever stream it records. mut_cursorless_fold_trusted = [] # A foreign cursor keeps its eviction memo (the old stream's) through the repair. diff --git a/src/applied.rs b/src/applied.rs index 038cad6..49e762e 100644 --- a/src/applied.rs +++ b/src/applied.rs @@ -70,7 +70,7 @@ use crate::kernels::applied::{ Action, Actions, Event, Fatal, Queued, ResumeFrom, State as KState, StoreOutcome, resume_from, step, }; -use crate::kv::{KvError, KvUpdate, KvWatcher, WatchCursor}; +use crate::kv::{KvError, KvUpdate, KvWatcher, Retention, WatchCursor}; use crate::repair::{self, ExpiryRepair}; use crate::snapshot::{SnapshotError, SnapshotStore}; @@ -421,6 +421,7 @@ where // Spawn the watch task. It owns the cursor-expiry handling so the main loop // only ever sees a clean ordered stream of updates on `rx`, plus repairs. let (tx, mut rx) = mpsc::channel::(config.channel_capacity.max(1)); + let export_watcher = Arc::clone(&watcher); let handle = tokio::spawn(repair::run_watch( watcher, scope, @@ -498,7 +499,12 @@ where req = async { exports.as_mut().expect("arm guarded by is_some").recv().await }, if exports.is_some() => { match req { - Some(req) => fold.export(req, &prefixes).await.map_err(stop)?, + Some(req) => { + // The stream as it is now: an export is refused + // unless the fold's cursor is this stream's. + let retention = export_watcher.retention().await; + fold.export(req, &prefixes, retention).await.map_err(stop)? + } // Sender dropped: disarm the arm for the rest of the run. None => exports = None, } @@ -945,6 +951,7 @@ where &mut self, ExportRequest { dest_dir, reply }: ExportRequest, scope: &[String], + retention: Result, KvError>, ) -> Result<(), KvError> { let acts = self.decide(Event::ExportRequested { has_store: self.store.is_some(), @@ -963,6 +970,30 @@ where } } let mut st = self.store.take().expect("ExportStore implies a store"); + // THE export guard: the store's cursor must be a position of the stream + // that exists now (`protocol::export_allowed`). A node of a dead stream, + // a fold whose foreign cursor was forgotten, and a cursor-less fold + // start no round: the lease is given back, nothing is published. A + // stream that cannot be read fails closed. + let cursor = st.cursor(); + let allowed = match &retention { + Ok(r) => crate::protocol::export_allowed( + cursor.as_u64().is_some(), + cursor.origin(), + cursor.rank(), + r.and_then(|r| r.incarnation), + r.map_or(0, |r| r.last_revision), + ), + Err(_) => false, + }; + if !allowed { + self.store = Some(st); + let _ = reply.send(Err(SnapshotError::Backend(format!( + "export refused: the fold's cursor ({cursor:?}) is not a position of the stream \ + that exists now (a foreign cursor, no cursor, or the stream could not be read)" + )))); + return Ok(()); + } let scope = scope.to_vec(); match tokio::task::spawn_blocking(move || { let res = st @@ -2282,6 +2313,97 @@ mod tests { task.await.unwrap().unwrap(); } + /// A watcher over a stream of incarnation `.1` that delivers `.0`'s script. + struct OfStream(MockWatcher, u64); + + #[async_trait] + impl KvWatcher for OfStream { + async fn watch_all(&self, tx: Sender) -> Result<(), KvError> { + self.0.watch_all(tx).await + } + + async fn watch_prefix(&self, prefix: &str, tx: Sender) -> Result<(), KvError> { + self.0.watch_prefix(prefix, tx).await + } + + async fn watch_prefixes( + &self, + prefixes: &[&str], + tx: Sender, + ) -> Result<(), KvError> { + self.0.watch_prefixes(prefixes, tx).await + } + + async fn retention(&self) -> Result, KvError> { + Ok(Some(Retention { + evicts_current_values: false, + first_revision: 1, + last_revision: 1_000, + incarnation: Some(self.1), + })) + } + } + + /// THE export guard, end to end: a fold exports only a cursor that is a + /// position of the stream that exists now. A fold folded on incarnation 7 + /// exports while the stream is 7, and is refused (its lease given back, + /// nothing published) once the stream is 9: a node of a dead stream starts + /// no export round. A fold with no cursor never exports. + #[tokio::test(start_paused = true)] + async fn a_fold_of_a_dead_stream_exports_nothing() { + let versioned = |rev: u64| { + KvUpdate::Put(KvEntry { + key: format!("k{rev}"), + value: b"v".to_vec(), + version: VersionToken::from_u64(rev).with_origin(7), + }) + }; + for (stream, updates, expect_export) in [ + (7, vec![versioned(1), versioned(2)], true), + (9, vec![versioned(1), versioned(2)], false), + (7, vec![], false), + ] { + let dir = tempfile::TempDir::new().unwrap(); + let (_r, store) = AppendLogSnapshot::open(&dir.path().join("fold"), u64::MAX).unwrap(); + let watcher = Arc::new(OfStream(MockWatcher::new(updates, true), stream)); + let (sd_tx, sd_rx) = watch::channel(false); + let (ex_tx, ex_rx) = mpsc::channel(1); + let task = tokio::spawn(watch_applied( + watcher, + WatchScope::All, + None, + None, + Some(store), + Some(ex_rx), + BatchConfig { + window: Duration::from_secs(3600), + max: 100, + ..BatchConfig::default() + }, + parse_put, + move |_batch: Vec>| {}, + move |_| {}, + sd_rx, + )); + tokio::time::sleep(Duration::from_millis(1)).await; + let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); + ex_tx + .send(ExportRequest { + dest_dir: dir.path().join("artifact"), + reply: reply_tx, + }) + .await + .unwrap(); + let reply = reply_rx.await.unwrap(); + assert_eq!(reply.is_ok(), expect_export, "stream {stream}: {reply:?}"); + if !expect_export { + assert!(!dir.path().join("artifact").exists(), "nothing was staged"); + } + sd_tx.send(true).unwrap(); + task.await.unwrap().unwrap(); + } + } + /// An [`ExportRequest`] that arrives with NOTHING pending (the window /// already flushed everything) still produces a valid artifact whose /// cursor is the applied cursor. The flush-before-export step must be a diff --git a/src/export_lease.rs b/src/export_lease.rs index d9db933..e029b66 100644 --- a/src/export_lease.rs +++ b/src/export_lease.rs @@ -156,9 +156,10 @@ impl ExportLease { // A live, parseable, unexpired lease wins; anything else (expired, // tombstone, unparseable garbage) is taken over. Unparseable leases // MUST be stealable or one corrupt write wedges exports fleet-wide. - if let Ok(existing) = serde_json::from_slice::(&entry.value) - && existing.expires_at_unix > now - { + let held_until = serde_json::from_slice::(&entry.value) + .ok() + .map(|r| r.expires_at_unix); + if !crate::protocol::lease_takeover_allowed(held_until, now) { return Ok(None); } diff --git a/src/kernels/fleet_proofs.rs b/src/kernels/fleet_proofs.rs index 184358e..d3bda4e 100644 --- a/src/kernels/fleet_proofs.rs +++ b/src/kernels/fleet_proofs.rs @@ -1649,7 +1649,8 @@ pub proof fn finding_f1_a_dead_pointer_ahead_of_the_head_does_not_refuse_a_publi /// FINDING F1b (the price of F1's fix) lives in `transport_proofs`, where the pointer and the prune are: a dead exporter can leave /// the pointer dangling; (a) a fetch of it is a detected miss, never another payload, and (b) the live exporter's round replaces it -/// (`a_live_round_ends_the_dangling_window`). What the FLEET adds: a restore never takes a foreign artifact, so a dangling or dead +/// (`a_live_round_ends_the_dangling_window`, whose premises are theorems: `protocol::export_allowed`, +/// `protocol::a_held_lease_is_never_taken`, `a_converged_exporter_is_at_the_live_head`). What the FLEET adds: a restore never takes a foreign artifact, so a dangling or dead /// pointer is never restored from, whatever it names. pub proof fn a_restore_never_takes_a_foreign_artifact(f: F, i: int, hd: bool, pick: spec_fn(nat) -> bool) requires @@ -1681,6 +1682,23 @@ pub open spec fn converged(l: Log, n: Node) -> bool { live(l, n) && n.w.delivered == l.ops.len() && n.w.store_cursor == n.w.delivered } +/// THEOREM (a converged exporter is at the live head): every artifact of the current incarnation has a cursor at most the log's +/// head, and a converged node's cursor IS the head. So the exporter of a converged node is at least every live rank the pointer +/// holds, and a pruner's read (a past pointer) holds: the head premise of the transport liveness +/// (`transport_proofs::a_live_round_ends_the_dangling_window`), once the fleet liveness has brought a live node to the head. +pub proof fn a_converged_exporter_is_at_the_live_head(f: F, j: int, a: Art) + requires + valid(f, j), + node_ok(f.log, node_at(f, j)), + converged(f.log, node_at(f, j)), + art_ok(f.log, a), + a.origin == f.log.origin, + ensures + a.cursor <= node_at(f, j).w.store_cursor, +{ + assert(ok_fold(a.fold, f.log.ops, a.cursor)); +} + pub open spec fn folded(n: Node) -> bool { forall|k: nat| (#[trigger] (n.fold)(k)) == (rst_of(n).result)(k) } diff --git a/src/kernels/protocol.rs b/src/kernels/protocol.rs index 7c18749..702da44 100644 --- a/src/kernels/protocol.rs +++ b/src/kernels/protocol.rs @@ -14,6 +14,8 @@ //! | [`listing_is_truth`] / [`listing_truth`] | `repair` (plan, cursor-less start), `Snapshot::stale_keys` | every model's view of retention; repair-steps `ConfigForgot` | //! | [`plan_repair`] | `repair::plan`, `Snapshot::stale_keys` | expiry dispatch in every model | //! | [`cursorless_start_needs_repair`] | `repair::run_watch` | repair-steps `WStart`, fleet `Start` | +//! | [`export_allowed`] | `applied::Fold::export` (every export round) | `tests/recreated_fleet.rs` (live) | +//! | [`lease_takeover_allowed`] | `export_lease::ExportLease::try_acquire` | Verus (`a_held_lease_is_never_taken`) | //! | [`cursorless_fold_is_this_stream`] | `repair::run_watch` (a fold with data and no cursor) | `tests/recreated_fleet.rs` (live) | //! | [`restore_key`] | `repair::restore_diff` | repair-steps restore op | //! | [`gap_holds_no_eviction`] | `nats` resume (`NatsKvWatcher::resume_point`) | — (unit-tested; `tests/eviction.rs` live) | @@ -356,6 +358,81 @@ pub open spec fn cursorless_fold_spec(recorded: Option, stream: Option recorded is Some && stream is Some && recorded->Some_0 == stream->Some_0 } +/// THE export guard: may a fold export itself now? An artifact is the fold at its store's cursor, so the cursor must be a position of +/// THE STREAM THAT EXISTS NOW: it has a position (a cursor-less fold would publish a rank-0 artifact over any pointer of another +/// incarnation), and, when the log can say which incarnation it is (`stream`), the cursor is that one's ([`same_incarnation`]: a +/// foreign cursor, one forgotten by the repair, never exports). A node of a dead stream therefore starts no export round after the +/// recreation: its first export is refused, and its lease is given back. +pub fn export_allowed( + has_position: bool, + cursor_origin: Option, + revision: u64, + stream: Option, + last_sequence: u64, +) -> (r: bool) + ensures + r == export_allowed_spec(has_position, cursor_origin, revision, stream, last_sequence), + !has_position ==> !r, + (has_position && stream is Some && cursor_origin is Some && cursor_origin->Some_0 != stream->Some_0) ==> !r, +{ + // Mutation (model tests only): export whatever the fold holds (the pre-guard behaviour). + if cfg!(feature = "mut_export_ignores_stream") { + return true; + } + if !has_position { + return false; + } + match stream { + Some(s) => same_incarnation(cursor_origin, revision, s, last_sequence), + None => true, + } +} + +/// [`export_allowed`]'s table. +pub open spec fn export_allowed_spec( + has_position: bool, + cursor_origin: Option, + revision: u64, + stream: Option, + last_sequence: u64, +) -> bool { + has_position && match stream { + Some(s) => same_incarnation_spec(cursor_origin, revision, s, last_sequence), + None => true, + } +} + +/// THE lease takeover guard: may a round be won over the lease record found? A record that parses and has not expired is held; an +/// expired one, or one that does not parse (`None`: one corrupt write must not wedge exports), is taken over. The takeover is a +/// compare-and-swap against the version read (O3-style, NATS KV), so of racing takers exactly one wins. +pub fn lease_takeover_allowed(held_until: Option, now: u64) -> (r: bool) + ensures + r == lease_takeover_spec(held_until, now), +{ + match held_until { + Some(until) => until <= now, + None => true, + } +} + +/// [`lease_takeover_allowed`]'s table. +pub open spec fn lease_takeover_spec(held_until: Option, now: u64) -> bool { + match held_until { + Some(until) => until <= now, + None => true, + } +} + +/// THEOREM (a held lease is never taken): while a round's lease has not expired (`now < until`), no other round can take it. So two +/// rounds overlap only if the first outlives its lease: the one clock assumption is that a round finishes within its ttl. +pub proof fn a_held_lease_is_never_taken(until: u64, now: u64) + requires + now < until, + ensures + !lease_takeover_spec(Some(until), now), +{ +} + /// THE restore guard: may a fold whose cursor (`local_revision`) fell out of /// the log be replaced by an artifact exported at `artifact_revision`? /// @@ -816,6 +893,36 @@ mod tests { assert!(!payload_prunable(pos(2, 4), ptr, false, false)); } + #[test] + fn export_and_lease_guards() { + // A cursor of this stream exports; of another, or none, does not. + assert!(export_allowed(true, Some(7), 5, Some(7), 10)); + assert!( + !export_allowed(true, Some(6), 5, Some(7), 10), + "dead stream" + ); + assert!( + !export_allowed(false, Some(7), 0, Some(7), 10), + "no position" + ); + assert!( + export_allowed(true, None, 5, Some(7), 10), + "unrecorded, possible here" + ); + assert!( + !export_allowed(true, None, 50, Some(7), 10), + "unrecorded, beyond the head" + ); + assert!( + export_allowed(true, None, 5, None, 0), + "a log that cannot say" + ); + // A held lease is not taken; an expired or unparseable one is. + assert!(!lease_takeover_allowed(Some(100), 99)); + assert!(lease_takeover_allowed(Some(100), 100)); + assert!(lease_takeover_allowed(None, 0)); + } + #[test] fn incarnation_guard_boundaries() { assert!( diff --git a/src/kernels/transport_proofs.rs b/src/kernels/transport_proofs.rs index d6ea7aa..8337842 100644 --- a/src/kernels/transport_proofs.rs +++ b/src/kernels/transport_proofs.rs @@ -28,17 +28,23 @@ //! ([`a_live_round_ends_the_dangling_window`], ranking function [`rho`]): its round replaces the pointer with a payload that //! exists, in at most one round plus one re-read per dead round still in flight. //! -//! # Environment axioms +//! # Environment axioms (the object store, NATS, clocks: nothing of slipstream's) //! //! * **O1** a payload path names its content for ever (content addressing; a hash collision is the only way to break it); //! * **O2** the pointer object is written only by [`Act::Swap`] (nothing else deletes or rewrites it); //! * **O3** a compare-and-swap succeeds exactly when the object is unchanged since the read (`ver`); -//! * **F-e** (liveness only) while the live exporter's round runs, no round starts: the export lease admits one live round at a -//! time, and a node of a dead stream starts no new round after the recreation (it re-seeds as a live one first), so the dead -//! rounds in flight are finitely many ([`credits`]); -//! * **F-h** (liveness only) the live exporter exports at the live head, which is at least every live rank the pointer or a pruner's -//! read holds (nothing of the live incarnation is published above the head), and its own payload exists when the round starts; -//! * **F-c** the object store answers (the existing fairness axiom: a round's steps run). +//! * **T** a round finishes before its lease lapses (the clock, and an object store that answers within the round period). +//! +//! The liveness lemma's premises ([`round_ok`]) are claims about slipstream's own code, so each is a THEOREM, not an axiom: +//! +//! * the live round runs alone: `protocol::a_held_lease_is_never_taken` (the takeover guard `ExportLease` runs) with **T**; +//! * no dead round starts after the recreation: `protocol::export_allowed` refuses the export of a fold whose cursor is not the +//! stream's (`Fold::export`), so a node of a dead stream gives its lease back and publishes nothing; only the dead rounds +//! already in flight at the recreation remain, finitely many ([`credits`]); +//! * the exporter is at the live head: the window ends once a live exporter's fold REACHES the head, which the fleet liveness +//! theorem delivers (`fleet_proofs::a_converged_exporter_is_at_the_live_head`: a converged node's cursor is at least every live +//! artifact's); +//! * its payload exists when its round starts: `Act::Upload` inserts it. use crate::kernels::protocol::*; use vstd::prelude::*; @@ -393,7 +399,7 @@ pub open spec fn credits_upto(actors: Seq, live: u64, n: nat) -> nat } } -/// The dead rounds in flight: finitely many (F-e), and each ends with a swap or a refused guard. +/// The dead rounds in flight: finitely many (no round starts after the recreation: `export_allowed`), and each ends with a swap or a refused guard. pub open spec fn credits(s: TS) -> nat { credits_upto(s.actors, s.live, s.actors.len()) } @@ -422,8 +428,9 @@ pub open spec fn payload_of(a: Actor) -> Payload { } } -/// The live exporter `i` is mid-round (F-e: the lease admits one live round, so no other actor is in a live round), its payload -/// exists, and it exports at the live head (F-h): no live rank in the pointer or in a pruner's read exceeds its own. +/// The live exporter `i` is mid-round and alone in a live round (the lease with **T**), its payload exists (`Act::Upload`), and it is +/// at the live head (its fold is converged): no live rank in the pointer or in a pruner's read exceeds its own (each is a +/// published artifact's cursor, at most the head). The header says why each holds. pub open spec fn round_ok(s: TS, i: int) -> bool { &&& valid(s, i) &&& live_flight(s.live, actor(s, i)) @@ -460,7 +467,7 @@ proof fn credits_update(actors: Seq, live: u64, i: int, a2: Actor, n: nat } /// THEOREM (b) (the dangling window ends with the live exporter's round): while the live exporter `i` runs its round (no round -/// starts meanwhile: F-e), every step of the world either leaves its rank [`rho`] where it was or lowers it, and every step of `i` +/// starts meanwhile: the header), every step of the world either leaves its rank [`rho`] where it was or lowers it, and every step of `i` /// itself lowers it: its read of the pointer is admitted (the pointer is not above its payload, so the guard cannot refuse it: /// the refusal clears), its swap succeeds against a fresh read, a lost CAS (a dead round's swap, which lowered the credits) takes /// it back to a re-read. Its payload exists throughout (a prune never deletes it: every live read is at most its rank), so the