From 91559e0e9ed53cdce9f086ea4ccb04890df42d02 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sun, 29 Nov 2026 07:06:12 -0800 Subject: [PATCH 1/5] repair: opt-in ForeignPolicy::Hold keeps a fold on a foreign incarnation; adopt_incarnation re-anchors it A fold that is the only full copy (its consumer is the bucket's only writer) is destroyed by the foreign-cursor repair: the new stream starts empty and the key-listing diff deletes every key it lacks. BatchConfig::on_foreign chooses: Repair (default, unchanged) or Hold, under which the watch ends with the typed KvError::Foreign { old_incarnation, new_incarnation } and never touches the fold. WatchCursor::adopt_incarnation(new) resumes on the new stream afterwards. The decision is protocol::foreign_action, proven in Verus with hold_proofs.rs; mutants mut_hold_repairs, mut_repair_holds, mut_adopt_unrecorded go red. Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 8 +- Cargo.toml | 6 ++ src/applied.rs | 12 +++ src/health.rs | 5 +- src/kernels/hold_proofs.rs | 157 +++++++++++++++++++++++++++++++++ src/kernels/mod.rs | 2 + src/kernels/protocol.rs | 101 +++++++++++++++++++++ src/kv.rs | 35 ++++++++ src/lib.rs | 1 + src/repair.rs | 81 ++++++++++++----- tests/recreated_stream.rs | 175 ++++++++++++++++++++++++++++++++++++- 11 files changed, 554 insertions(+), 29 deletions(-) create mode 100644 src/kernels/hold_proofs.rs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f624557..bf0e112 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -242,6 +242,8 @@ The one exception: an update carrying the **unknown** version (an unparseable AC **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. +**Foreign cursor, held (`ForeignPolicy::Hold`).** The repair above is right for a fold that is a view derived from the bucket, and wrong for one that is the only full copy (a consumer that is the bucket's only writer): it deletes every key the new stream lacks, and the new stream starts empty. `BatchConfig::on_foreign` chooses; `Repair` is the default and the behaviour above, unchanged. Under `Hold` a foreign cursor (at resume, or ended mid-watch by the floor guard), and a fold with data and no cursor that names another incarnation, never reaches the repair: the watch task returns `KvError::Foreign { old_incarnation, new_incarnation }` before sending the main loop any request, so no key is deleted, overwritten or re-anchored and the fold stays complete at its old cursor (health: `ForeignCursorRefused`, sticky). The decision is `protocol::foreign_action(policy, mode)`; `Hold` wins over whatever repair is armed. The caller republishes into the new stream (the fold is its source), then resumes with `resume = Some(WatchCursor::adopt_incarnation(new_incarnation))` (`protocol::adopted_position`: rank 0 of the new incarnation). That watch re-lists the new stream over the fold and follows it, so from then on a key the new stream deletes is deleted like any other. A key the new stream never wrote stays in the fold: removing one is the caller's. The persisted cursor stays the old incarnation's until the first batch commits, so a crash in between is held and adopted again (idempotent). A held fold does not export (`export_allowed` refuses a foreign cursor). Proven in `src/kernels/hold_proofs.rs` (Hold never removes a key; the fleet invariant "complete at the cursor" holds for a held fold until adopted; an adopted fold folds the new stream and deletes what it deletes) and `protocol::an_adopted_position_is_the_new_streams_and_precedes_it` (the retry after the hold is admitted); live in `tests/recreated_stream.rs` (`held_fold_keeps_every_key_*`, `adopting_the_new_stream_folds_it_normally`). + **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. @@ -280,7 +282,7 @@ A watch that is stale, stuck, or refused a repair looks like a healthy one from No allocation per update; the detail mutex is held for a few stores and never across an await, and `snapshot()` copies under it. A handle outlives the watch's runs, so `restarts` and `last_error` accumulate across the caller's restart loop. -**Repair state is sticky where it must be.** A refused or waiting repair ends the watch, and the caller's restart retries the same expired cursor, so `Refused` and `WaitingForArtifact` persist across runs and clear only when a repair succeeds (`Relisting` and `Restoring` never overwrite them). `WaitingForArtifact` means a restore found no usable artifact: none published, none readable, or the newest is not ahead of the fold while covering the scope. `Reseeding` marks a foreign cursor (recreated bucket) with a repair armed, replaced by the repair's own state; `ForeignCursorRefused` is sticky and marks the same event with no repair armed, where the error stands. `Refused` is every other refusal: an artifact outside retention or scope, a key-listing diff on an evicting bucket, or the main loop's authoritative not-ahead check. The split is made at the call site from the artifact's scope and cursor; `check_restore` itself is unchanged. +**Repair state is sticky where it must be.** A refused or waiting repair ends the watch, and the caller's restart retries the same expired cursor, so `Refused` and `WaitingForArtifact` persist across runs and clear only when a repair succeeds (`Relisting` and `Restoring` never overwrite them). `WaitingForArtifact` means a restore found no usable artifact: none published, none readable, or the newest is not ahead of the fold while covering the scope. `Reseeding` marks a foreign cursor (recreated bucket) with a repair armed, replaced by the repair's own state; `ForeignCursorRefused` is sticky and marks the same event with no repair armed, where the error stands, and with `ForeignPolicy::Hold`, where the typed `KvError::Foreign` ends the watch. `Refused` is every other refusal: an artifact outside retention or scope, a key-listing diff on an evicting bucket, or the main loop's authoritative not-ahead check. The split is made at the call site from the artifact's scope and cursor; `check_restore` itself is unchanged. **Lag is `head - applied` at the last sample.** It is exact only for `All` scope. A `Prefix` or `Prefixes` watch's cursor advances only on matching keys, so it reads nonzero lag while idle; read it as a trend. `head_sample_age` says how stale it is. @@ -349,6 +351,8 @@ Every decision the protocol's correctness rests on is a pure function in `src/ke | `payload_prunable` | `transport` prune | `model.rs` | | `resume_window_ok` | `nats` resume paths (`create_resume`), floor guard | every model | | `same_incarnation` | `nats` resume paths (`check_resume_window`), floor guard, `repair::check_restore` | `model_incarnation.rs` | +| `foreign_action` | `repair::run_watch` (foreign cursor, foreign cursor-less fold) | Verus (`hold_proofs.rs`), live `tests/recreated_stream.rs` | +| `adopted_position` | `WatchCursor::adopt_incarnation` | Verus (`an_adopted_position_is_the_new_streams_and_precedes_it`), live `tests/recreated_stream.rs` | | `restore_allowed` / `restore_ahead` | `repair::check_restore`, the main loop's ahead re-check | `model.rs`, `model_live_watch.rs`, `model_repair.rs`, `model_fleet.rs` | | `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 | @@ -525,7 +529,7 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut - **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_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. +`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_hold_repairs` fails `foreign_action`'s contract (a held fold repaired) and the live `held_fold_keeps_every_key_*`; `mut_repair_holds` fails its contract (the default holds) and the live `warm_fold_*` tests; `mut_adopt_unrecorded` fails `adopted_position`'s contract; `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 2247777..3e34b2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -117,6 +117,12 @@ mut_foreign_keeps_memo = [] mut_restore_trusts_foreign = [] # The fold forgets that it saw retention evict current values. mut_no_eviction_memo = [] +# A fold meant to be held on a foreign cursor is repaired like a derived view (its keys the new stream lacks are deleted). +mut_hold_repairs = [] +# The default policy holds: every existing consumer stops repairing a foreign cursor. +mut_repair_holds = [] +# The adopted cursor records no incarnation, so it is admitted by its position alone. +mut_adopt_unrecorded = [] [package.metadata.verus] verify = true diff --git a/src/applied.rs b/src/applied.rs index 49e762e..2d41af6 100644 --- a/src/applied.rs +++ b/src/applied.rs @@ -71,6 +71,7 @@ use crate::kernels::applied::{ step, }; use crate::kv::{KvError, KvUpdate, KvWatcher, Retention, WatchCursor}; +use crate::protocol::ForeignPolicy; use crate::repair::{self, ExpiryRepair}; use crate::snapshot::{SnapshotError, SnapshotStore}; @@ -150,6 +151,15 @@ pub struct BatchConfig { /// and poll [`snapshot`](WatchHealth::snapshot). Use one per watch, and /// the same one across its restarts. `None` records nothing. pub health: Option, + /// What the watch does when the fold's cursor belongs to another incarnation of the stream + /// (the bucket was deleted and recreated). [`ForeignPolicy::Repair`] (the default) repairs + /// the fold against the stream that exists now, which deletes the keys that stream lacks: + /// right for a view derived from the bucket. [`ForeignPolicy::Hold`] never touches the fold: + /// the watch ends with [`KvError::Foreign`] and the fold stays complete at its old cursor. + /// Use it when the fold is the only full copy, for instance when its consumer is the bucket's + /// only writer. Resume with [`WatchCursor::adopt_incarnation`] once the new stream is + /// republished. See `ARCHITECTURE.md`, "Foreign cursor". + pub on_foreign: ForeignPolicy, } impl Default for BatchConfig { @@ -162,6 +172,7 @@ impl Default for BatchConfig { max: 100, channel_capacity: 256, health: None, + on_foreign: ForeignPolicy::Repair, } } } @@ -428,6 +439,7 @@ where resume, unanchored, repair, + config.on_foreign, tx, config.health.clone(), )); diff --git a/src/health.rs b/src/health.rs index 6f947ec..a274395 100644 --- a/src/health.rs +++ b/src/health.rs @@ -95,7 +95,10 @@ pub enum RepairState { /// as in [`Preset::node_slice`](crate::Preset::node_slice)): the watch /// fails with `KvError::ForeignCursor` rather than keep the old stream's /// keys, and its restart fails the same way. Sticky. Needs an operator to - /// discard the fold and cold-boot it. + /// discard the fold and cold-boot it. Also the state of a fold held by + /// [`ForeignPolicy::Hold`](crate::ForeignPolicy::Hold): the watch ends with + /// `KvError::Foreign`, the fold untouched, until the caller adopts the new + /// incarnation ([`WatchCursor::adopt_incarnation`](crate::WatchCursor::adopt_incarnation)). ForeignCursorRefused, /// A restore is needed, but no usable artifact exists yet: none is /// published, the newest is not ahead of the fold, or it could not be diff --git a/src/kernels/hold_proofs.rs b/src/kernels/hold_proofs.rs new file mode 100644 index 0000000..ef05015 --- /dev/null +++ b/src/kernels/hold_proofs.rs @@ -0,0 +1,157 @@ +//! A consumer whose fold is the only full copy (`ForeignPolicy::Hold`), proven with no bound: any number of keys and writes. +//! The unbounded statement for the one thing `fleet_proofs` does not cover: a node that must never be repaired. +//! +//! # What is proven +//! +//! The decision is `protocol::foreign_action` (its `*_spec` table below; the kernel's own `ensures` says the code equals it), called +//! by `repair::run_watch` on every foreign cursor, resume-time or mid-watch, and on a cursor-less fold of another incarnation. +//! Under `Hold` the shell's whole effect is to end the watch with `KvError::Foreign`: it sends the fold no repair request, so +//! no delete, put or cursor commit follows. The proofs below take that effect as the spec of the shell (`foreign_step`). +//! +//! * [`a_held_fold_keeps_every_key_on_a_foreign_cursor`]: whatever repair is armed, whatever the repair would have left, a held +//! fold and its cursor are exactly what they were. +//! * [`a_held_fold_is_complete_at_its_old_cursor_until_adopted`]: the fleet's invariant (`fleet_proofs::complete`), restated +//! for a held consumer: a fold of the old stream, complete at its cursor, stays so over every foreign detection and every +//! restart, for as long as it is not adopted. +//! * [`folding_a_new_stream_over_a_held_fold`], [`a_key_the_new_stream_deletes_is_deleted`]: once adopted +//! (`protocol::adopted_position`: the resume position before the first revision of the new stream), the fold folds the new +//! stream normally: a key the new stream wrote is exactly the truth of the new stream, and a key it later deletes is deleted. +//! A key the new stream never wrote keeps its entry: removing one is the caller's, never the watch's. +//! +//! `protocol::an_adopted_position_is_the_new_streams_and_precedes_it` is the liveness partner of the hold: the resume after an +//! adoption is admitted by the new stream. + +use crate::kernels::fleet_proofs::*; +use crate::kernels::protocol::*; +use vstd::prelude::*; + +verus! { + +/// A consumer's persisted fold and the position of the stream it was folded to. +pub struct Held { + pub fold: Fold, + pub cursor: nat, +} + +/// What the shell leaves of the fold after one foreign cursor: the repair's result (`repaired`: anything) when the kernel says +/// repair, and the fold untouched for a refusal and for a hold (the watch ends before any request reaches the fold). +pub open spec fn foreign_step(policy: ForeignPolicy, mode: RepairMode, n: Held, repaired: Held) -> Held { + match foreign_action_spec(policy, mode) { + ForeignAction::Repair => repaired, + _ => n, + } +} + +/// THEOREM (a hold never removes a key): on a foreign cursor a held fold, under any armed repair and whatever the repair +/// would have done, keeps every entry and its cursor. +pub proof fn a_held_fold_keeps_every_key_on_a_foreign_cursor(mode: RepairMode, n: Held, repaired: Held, k: nat) + ensures + (foreign_step(ForeignPolicy::Hold, mode, n, repaired).fold)(k) == (n.fold)(k), + foreign_step(ForeignPolicy::Hold, mode, n, repaired).cursor == n.cursor, +{ +} + +/// The consumer's steps while held: a foreign cursor under any armed repair, and a restart (the persisted fold is what it was). +pub enum HeldAction { + Foreign { mode: RepairMode }, + Restart, +} + +pub open spec fn held_step(a: HeldAction, n: Held, repaired: Held) -> Held { + match a { + HeldAction::Foreign { mode } => foreign_step(ForeignPolicy::Hold, mode, n, repaired), + HeldAction::Restart => n, + } +} + +/// THEOREM (the fleet invariant, for a held consumer): a fold of the old stream that is real and complete at its cursor stays +/// real and complete at that cursor over every foreign detection and restart, however the repair would have changed it, until +/// the caller adopts. (`fleet_proofs::finv` says the same of a node of the current incarnation; a held consumer's incarnation is +/// the dead one, and the invariant is what makes the fold safe to republish from.) +pub proof fn a_held_fold_is_complete_at_its_old_cursor_until_adopted( + old: Log, + a: HeldAction, + n: Held, + repaired: Held, +) + requires + ok_fold(n.fold, old.ops, n.cursor), + ensures + ok_fold(held_step(a, n, repaired).fold, old.ops, held_step(a, n, repaired).cursor), +{ +} + +/// A key is written within the first `b` revisions of `ops`. +pub open spec fn written_by(ops: Seq, b: nat, k: nat) -> bool { + exists|j: int| 0 <= j && j < b && #[trigger] ops[j].key == k +} + +/// THEOREM (an adopted fold folds the new stream normally): fold the new stream's first `b` writes over a held fold `g`. A key the +/// new stream wrote is exactly the new stream's truth at `b` (a put is the entry, a delete removes it); a key it did not write +/// keeps the held entry. +pub proof fn folding_a_new_stream_over_a_held_fold(g: Fold, ops: Seq, b: nat, k: nat) + requires + b <= ops.len(), + ensures + written_by(ops, b, k) ==> fold_range(g, ops, 0, b)(k) == truth(ops, b, k), + !written_by(ops, b, k) ==> fold_range(g, ops, 0, b)(k) == g(k), + decreases b, +{ + if b > 0 { + let prev = (b - 1) as nat; + folding_a_new_stream_over_a_held_fold(g, ops, prev, k); + if ops[prev as int].key == k { + assert(ops[prev as int].key == k); + assert(written_by(ops, b, k)); + } else { + if written_by(ops, b, k) { + let j = choose|j: int| 0 <= j && j < b && #[trigger] ops[j].key == k; + assert(j < prev as int); + assert(written_by(ops, prev, k)); + } + if written_by(ops, prev, k) { + let j = choose|j: int| 0 <= j && j < prev && #[trigger] ops[j].key == k; + assert(0 <= j && j < b && ops[j].key == k); + assert(written_by(ops, b, k)); + } + } + } +} + +/// No write to `k` in `[c, c2)`: the truth at `c2` is the truth at `c`. +pub proof fn truth_is_stable_without_writes(ops: Seq, c: nat, c2: nat, k: nat) + requires + c <= c2, + c2 <= ops.len(), + forall|j: int| c <= j && j < c2 ==> #[trigger] ops[j].key != k, + ensures + truth(ops, c2, k) == truth(ops, c, k), + decreases c2 - c, +{ + if c2 > c { + let prev = (c2 - 1) as nat; + assert(ops[prev as int].key != k); + truth_is_stable_without_writes(ops, c, prev, k); + } +} + +/// THEOREM (a key the new stream deletes is deleted): if revision `r <= b` of the new stream deletes `k` and nothing writes `k` +/// after it up to `b`, the adopted fold, folded to `b`, holds no entry for `k`, whatever it held before. +pub proof fn a_key_the_new_stream_deletes_is_deleted(g: Fold, ops: Seq, b: nat, r: nat, k: nat) + requires + b <= ops.len(), + 1 <= r, + r <= b, + ops[(r - 1) as int].key == k, + !ops[(r - 1) as int].put, + forall|j: int| r <= j && j < b ==> #[trigger] ops[j].key != k, + ensures + fold_range(g, ops, 0, b)(k) is None, +{ + folding_a_new_stream_over_a_held_fold(g, ops, b, k); + assert(ops[(r - 1) as int].key == k); + assert(written_by(ops, b, k)); + truth_is_stable_without_writes(ops, r, b, k); +} + +} // verus! diff --git a/src/kernels/mod.rs b/src/kernels/mod.rs index acc9936..57a26f7 100644 --- a/src/kernels/mod.rs +++ b/src/kernels/mod.rs @@ -15,4 +15,6 @@ mod applied_proofs; #[cfg(verus_keep_ghost)] mod fleet_proofs; #[cfg(verus_keep_ghost)] +mod hold_proofs; +#[cfg(verus_keep_ghost)] mod transport_proofs; diff --git a/src/kernels/protocol.rs b/src/kernels/protocol.rs index 702da44..6202ed2 100644 --- a/src/kernels/protocol.rs +++ b/src/kernels/protocol.rs @@ -829,6 +829,107 @@ pub fn resume_start_sequence(revision: u64) -> (r: Option) if revision == u64::MAX { None } else { Some(revision + 1) } } +/// What a watch does when the fold's cursor belongs to another incarnation of the stream (the bucket was deleted and recreated). +/// Chosen per watch by [`BatchConfig::on_foreign`](crate::BatchConfig::on_foreign). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForeignPolicy { + /// The fold is a derived view of the bucket: repair it against the stream that exists now (the armed [`RepairMode`]), which + /// deletes the keys the new stream does not hold. The default. + Repair, + /// The fold is the only full copy (its consumer is the bucket's writer): never touch it. The watch ends with + /// [`KvError::Foreign`](crate::KvError::Foreign) and the fold stays complete at its old cursor, until the caller + /// re-anchors it with [`WatchCursor::adopt_incarnation`](crate::WatchCursor::adopt_incarnation). + Hold, +} + +/// What [`foreign_action`] decided for one foreign cursor. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForeignAction { + /// Repair the fold as an unanchored fold against the current stream ([`RepairMode`] decides how). + Repair, + /// No repair armed: the watch fails with `KvError::ForeignCursor`; the fold is untouched. + Refuse, + /// Hold: the watch fails with `KvError::Foreign`; the fold is untouched. + Hold, +} + +/// THE foreign-cursor policy: what a watch does with a cursor of another incarnation. `Hold` wins over whatever repair is armed +/// (it is the explicit statement that the fold is not derived), so a held fold is never repaired, and only `Hold` yields the typed +/// outcome. `Repair` is the behaviour before the policy existed, unchanged: repair when anything is armed, otherwise refuse. +pub fn foreign_action(policy: ForeignPolicy, mode: RepairMode) -> (r: ForeignAction) + ensures + r == foreign_action_spec(policy, mode), + // Never a repair of a held fold: it keeps every key. + policy is Hold ==> r is Hold, + // The default is what it always was. + policy is Repair ==> (r is Repair <==> !(mode is None)), + policy is Repair ==> (r is Refuse <==> mode is None), +{ + // Mutation (model tests only): a fold meant to be held is repaired like a derived view. + let policy = if cfg!(feature = "mut_hold_repairs") { ForeignPolicy::Repair } else { policy }; + // Mutation (model tests only): the default holds, so every existing consumer changes behaviour. + let policy = if cfg!(feature = "mut_repair_holds") { ForeignPolicy::Hold } else { policy }; + match policy { + ForeignPolicy::Hold => ForeignAction::Hold, + ForeignPolicy::Repair => match mode { + RepairMode::None => ForeignAction::Refuse, + _ => ForeignAction::Repair, + }, + } +} + +/// [`foreign_action`]'s table. +pub open spec fn foreign_action_spec(policy: ForeignPolicy, mode: RepairMode) -> ForeignAction { + match policy { + ForeignPolicy::Hold => ForeignAction::Hold, + ForeignPolicy::Repair => match mode { + RepairMode::None => ForeignAction::Refuse, + _ => ForeignAction::Repair, + }, + } +} + +/// THEOREM (the policy alone decides): whatever repair is armed, `Hold` is decided by the policy and by nothing else, and no other +/// policy yields it, so arming a repair never repairs a held fold and a default consumer is never held. +pub proof fn only_hold_holds(policy: ForeignPolicy, mode: RepairMode) + ensures + foreign_action_spec(policy, mode) is Hold <==> policy is Hold, +{ +} + +/// THE adoption position: where a consumer that has re-anchored a held fold on the stream `new` (its `Foreign::new_incarnation`) resumes: +/// before the first revision of that incarnation, so the watch re-lists the stream and then follows it. Its rank is 0, below every +/// revision of the stream; it records the stream's incarnation, so the same stream admits it ([`same_incarnation`]) and the old one +/// never did. +pub fn adopted_position(new: u64) -> (r: Pos) + ensures + r == adopted_position_spec(new), +{ + // Mutation (model tests only): the adopted cursor records no incarnation (an unrecorded cursor is admitted by position alone). + let origin = if cfg!(feature = "mut_adopt_unrecorded") { 0 } else { new }; + Pos { origin, rank: 0 } +} + +/// [`adopted_position`]'s table. +pub open spec fn adopted_position_spec(new: u64) -> Pos { + Pos { origin: new, rank: 0 } +} + +/// THEOREM (liveness of the hold: the retry succeeds): the adopted position is a position of the stream `new` for any +/// `last_sequence`, so the resume that follows an adoption is never refused as foreign by that stream, and it is strictly below every +/// revision of it, so the watch misses nothing of the new stream. The hold is stateless (the policy alone), so it clears exactly +/// when the caller adopts; no timer is involved. +pub proof fn an_adopted_position_is_the_new_streams_and_precedes_it(new: u64, last: u64, rank: u64) + requires + new != 0, + rank >= 1, + ensures + adopted_position_spec(new).origin == new, + same_incarnation_spec(Some(adopted_position_spec(new).origin), adopted_position_spec(new).rank, new, last), + pos_lt(adopted_position_spec(new), Pos { origin: new, rank }), +{ +} + } // verus! /// [`listing_is_truth`] for retention as a watcher reports it: `None` when diff --git a/src/kv.rs b/src/kv.rs index 2d00136..8b9505e 100644 --- a/src/kv.rs +++ b/src/kv.rs @@ -191,6 +191,25 @@ impl WatchCursor { self.as_u64().unwrap_or(0) } + /// The resume cursor that re-anchors a fold held by + /// [`ForeignPolicy::Hold`](crate::protocol::ForeignPolicy::Hold) on the stream that replaced + /// its own: pass it as `resume` to [`watch_applied`](crate::watch_applied) with the + /// [`KvError::Foreign::new_incarnation`] the held watch reported. + /// + /// It is the position before the first revision of that incarnation + /// ([`adopted_position`](crate::protocol::adopted_position)): the watch re-lists the new stream + /// over the fold (puts replace, nothing is deleted by the re-list itself) and then follows it, + /// and from then on a key the new stream deletes is deleted from the fold like any other. A key + /// the new stream never wrote stays in the fold: removing one is the caller's. The fold's + /// persisted cursor stays the old incarnation's until the first batch commits, so a crash + /// before it is held again and adopted again: adoption is idempotent. A `new` of 0 is no + /// incarnation and records nothing. + #[must_use] + pub fn adopt_incarnation(new: u64) -> Self { + let at = crate::protocol::adopted_position(new); + Self::from_version(VersionToken::from_u64(at.rank).with_origin(at.origin)) + } + /// 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. @@ -262,6 +281,22 @@ pub enum KvError { /// must discard the cursor and the fold built on it. #[error("watch cursor belongs to a different incarnation of the stream (bucket recreated)")] ForeignCursor, + /// The fold belongs to another incarnation of the stream (the bucket was deleted and + /// recreated) and the watch was run with + /// [`ForeignPolicy::Hold`](crate::protocol::ForeignPolicy::Hold): nothing was repaired, + /// deleted or overwritten, and the fold is exactly what it was, complete at its old + /// cursor. Republish what the new stream must hold, then resume with + /// [`WatchCursor::adopt_incarnation`] of `new_incarnation`. + #[error( + "the fold belongs to another incarnation of the stream (bucket recreated); held, not repaired" + )] + Foreign { + /// The incarnation (the stream's creation time, Unix ns) the fold's cursor or data records, + /// when it records one. + old_incarnation: Option, + /// The incarnation of the stream that exists now, when the backend can say. + new_incarnation: Option, + }, } /// What a backend's retention can do to the log a watch resumes from. These diff --git a/src/lib.rs b/src/lib.rs index bd08157..21e6e20 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,6 +55,7 @@ pub use health::{ }; pub use kernels::applied as cursor_kernel; pub use kernels::protocol; +pub use kernels::protocol::ForeignPolicy; pub use kv::{ KvEntry, KvError, KvPurge, KvReader, KvTtl, KvUpdate, KvWatcher, KvWriter, Retention, VersionToken, WatchCursor, diff --git a/src/repair.rs b/src/repair.rs index 0035194..d021bca 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -42,9 +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_fold_is_this_stream, - cursorless_start_needs_repair, listing_truth, plan_repair, restore_ahead, restore_allowed, - restore_key, resume_window_ok, same_incarnation, + ForeignAction, ForeignPolicy, KeyRestore, KeyState, RepairMode, RepairPlan, + cursorless_fold_is_this_stream, cursorless_start_needs_repair, foreign_action, listing_truth, + plan_repair, restore_ahead, restore_allowed, restore_key, resume_window_ok, same_incarnation, }; use crate::snapshot::{SnapshotError, SnapshotStore}; @@ -753,6 +753,23 @@ impl EvictionMemo<'_, S> { } } +/// The watch ends with the fold untouched: a [`ForeignPolicy::Hold`] consumer's foreign cursor. +/// Nothing is sent to the fold (no repair request), so no key is deleted, overwritten or +/// re-anchored; the caller republishes and adopts ([`WatchCursor::adopt_incarnation`]). +fn held(health: Option<&WatchHealth>, old: Option, new: Option) -> KvError { + warn!( + old_incarnation = ?old, + new_incarnation = ?new, + "the bucket was deleted and recreated and this fold is held: nothing is repaired or \ + deleted; adopt the new incarnation once the stream is republished" + ); + note(health, RepairState::ForeignCursorRefused); + KvError::Foreign { + old_incarnation: old, + new_incarnation: new, + } +} + /// The watch task: run the underlying watch for `scope`, resuming from /// `resume` when it carries a position, with cursor-expiry repair: an expiry /// (at resume, or mid-watch from the floor guard) runs the planned repair and @@ -765,6 +782,7 @@ impl EvictionMemo<'_, S> { /// or a populated store started without one). A re-list alone never removes /// what it doesn't deliver, so that start is repaired like an expiry at /// revision 0 before watching. +#[allow(clippy::too_many_arguments)] pub(crate) async fn run_watch( watcher: Arc, scope: WatchScope, @@ -774,6 +792,9 @@ pub(crate) async fn run_watch( // [`cursorless_fold_is_this_stream`]). unanchored: Option>, repair: Option>, + // What a cursor (or a fold with data and no cursor) of another incarnation does: repaired, + // or held untouched ([`foreign_action`]). + on_foreign: ForeignPolicy, tx: mpsc::Sender, health: Option, ) -> Result<(), KvError> { @@ -802,13 +823,17 @@ pub(crate) async fn run_watch( let unanchored_data = unanchored.is_some(); if resume.is_none() { if let Some(provenance) = unanchored - && mode != RepairMode::None + && (mode != RepairMode::None || on_foreign == ForeignPolicy::Hold) { 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; } + // A fold with data and no cursor of another incarnation: held like a foreign cursor. + if foreign_start && foreign_action(on_foreign, mode) == ForeignAction::Hold { + return Err(held(health, provenance, stream)); + } if foreign_start { warn!( ?provenance, @@ -875,24 +900,36 @@ pub(crate) async fn run_watch( // it is an unanchored fold — repaired like a cursor-less start // that holds data, against the stream that exists now; with // none, the error stands (a re-list alone would leave the old - // stream's keys in the fold). - Err(KvError::ForeignCursor) if mode != RepairMode::None => { - warn!( - "the bucket was deleted and recreated: the fold's cursor belongs to the \ - old stream. Repairing it against the current one as an unanchored fold" - ); - 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) => { - note(health, RepairState::ForeignCursorRefused); - return Err(KvError::ForeignCursor); - } + // stream's keys in the fold). A `Hold` consumer never repairs: + // the watch ends with `KvError::Foreign` and the fold untouched. + Err(KvError::ForeignCursor) => match foreign_action(on_foreign, mode) { + ForeignAction::Repair => { + warn!( + "the bucket was deleted and recreated: the fold's cursor belongs to the \ + old stream. Repairing it against the current one as an unanchored fold" + ); + 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() + } + ForeignAction::Refuse => { + note(health, RepairState::ForeignCursorRefused); + return Err(KvError::ForeignCursor); + } + ForeignAction::Hold => { + let stream = watcher + .retention() + .await + .ok() + .flatten() + .and_then(|r| r.incarnation); + return Err(held(health, cursor.origin(), stream)); + } + }, other => return other, } }; diff --git a/tests/recreated_stream.rs b/tests/recreated_stream.rs index e75c523..6c828c1 100644 --- a/tests/recreated_stream.rs +++ b/tests/recreated_stream.rs @@ -27,9 +27,9 @@ use std::time::Duration; use common::TestNats; use slipstream::{ - AppendLogSnapshot, BatchConfig, Connection, ExpiryRepair, ExportRequest, KvStore, KvUpdate, - NatsConnection, NatsConnectionConfig, SnapshotStore, StoreConfig, WatchCursor, WatchScope, - watch_applied, + AppendLogSnapshot, BatchConfig, Connection, ExpiryRepair, ExportRequest, ForeignPolicy, + KvError, KvStore, KvUpdate, NatsConnection, NatsConnectionConfig, SnapshotStore, StoreConfig, + WatchCursor, WatchScope, watch_applied, }; use tempfile::TempDir; use tokio::sync::{mpsc, oneshot, watch}; @@ -91,6 +91,16 @@ fn spawn_node( fold: AppendLogSnapshot, resume: Option, repair: ExpiryRepair, +) -> Node { + spawn_node_with(bucket, fold, resume, repair, BatchConfig::default()) +} + +fn spawn_node_with( + bucket: &Arc, + fold: AppendLogSnapshot, + resume: Option, + repair: ExpiryRepair, + config: BatchConfig, ) -> Node { let (ex_tx, ex_rx) = mpsc::channel(1); let (sd_tx, sd_rx) = watch::channel(false); @@ -103,7 +113,7 @@ fn spawn_node( repair, Some(fold), Some(ex_rx), - BatchConfig::default(), + config, |_: &KvUpdate| Some(()), |_: Vec<()>| {}, move |cur: WatchCursor| applied_w.store(cur.as_u64().unwrap_or(0), Ordering::SeqCst), @@ -395,3 +405,160 @@ async fn unrecorded_cursor_beyond_the_head_is_refused() { .expect_err("refused"); assert!(err.to_string().contains("different incarnation"), "{err}"); } + +// --------------------------------------------------------------------------- +// `ForeignPolicy::Hold`: a fold that is the only full copy is never repaired. +// --------------------------------------------------------------------------- + +fn hold() -> BatchConfig { + BatchConfig { + on_foreign: ForeignPolicy::Hold, + ..Default::default() + } +} + +/// The fold's keys, read from its file. +fn fold_keys(path: &Path) -> Vec { + let (_, fold) = AppendLogSnapshot::open(path, u64::MAX).expect("reopen the fold"); + let mut keys: Vec = fold + .range("") + .expect("range") + .into_iter() + .map(|e| e.key) + .collect(); + keys.sort(); + keys +} + +fn keys_of(prefix: &str, range: std::ops::Range) -> Vec { + let mut keys: Vec = range.map(|i| format!("{prefix}.{i}")).collect(); + keys.sort(); + keys +} + +/// The watch of a held fold whose bucket was recreated: it ends with the typed outcome, naming both +/// incarnations, and the fold is exactly what it was, under every armed repair (the default +/// policy repairs the same three, `warm_fold_*_reseeds`). +async fn held_fold_keeps_every_key( + repair: impl Fn(&Arc) -> ExpiryRepair, +) { + let nats = TestNats::start().await; + let (_c, old) = open_bucket(&nats).await; + let dir = TempDir::new().unwrap(); + let (path, _) = fold_the_old_stream(&old, dir.path(), 20).await; + + let (_c, new) = recreate(&nats).await; + put_all(&new, "new", 25).await; + + let (cursor, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let node = spawn_node_with(&new, fold, Some(cursor), repair(&new), hold()); + let err = timeout(Duration::from_secs(10), node.task) + .await + .expect("a held watch ends, it does not run on") + .unwrap() + .expect_err("a foreign cursor is held, not resumed"); + match err { + KvError::Foreign { + old_incarnation: old_seen, + new_incarnation: Some(new_seen), + } => { + assert!(old_seen.is_some(), "it names the fold's incarnation"); + assert_ne!(Some(new_seen), old_seen, "and the stream that replaced it"); + } + other => panic!("expected the typed Foreign outcome, got {other:?}"), + } + // Nothing was repaired, deleted or overwritten, and nothing of the new stream was folded. + assert_eq!( + fold_keys(&path), + keys_of("old", 0..20), + "the fold keeps every key" + ); + let (cursor, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + assert_eq!(cursor.as_u64(), Some(20), "at its old cursor"); + assert_eq!( + fold.get("old.7").unwrap().map(|e| e.value), + Some(b"old-7".to_vec()) + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn held_fold_keeps_every_key_under_a_relist() { + held_fold_keeps_every_key(relist).await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn held_fold_keeps_every_key_with_no_repair_armed() { + held_fold_keeps_every_key(|_| ExpiryRepair::None).await; +} + +/// HOLD, then ADOPT: the held fold is the only full copy; the caller republishes into the new +/// stream and adopts it. From then on the fold folds the new stream: a put is folded, a key the new +/// stream deletes is deleted. A key the caller never republished stays (removing it is the caller's). +#[tokio::test(flavor = "multi_thread")] +async fn adopting_the_new_stream_folds_it_normally() { + let nats = TestNats::start().await; + let (_c, old) = open_bucket(&nats).await; + let dir = TempDir::new().unwrap(); + let (path, _) = fold_the_old_stream(&old, dir.path(), 20).await; + + let (_c, new) = recreate(&nats).await; + + // Held. + let (cursor, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let node = spawn_node_with(&new, fold, Some(cursor), relist(&new), hold()); + let err = timeout(Duration::from_secs(10), node.task) + .await + .expect("held") + .unwrap() + .expect_err("held"); + let KvError::Foreign { + new_incarnation: Some(new_incarnation), + .. + } = err + else { + panic!("expected the typed Foreign outcome, got {err:?}"); + }; + assert_eq!(fold_keys(&path), keys_of("old", 0..20)); + + // The caller republishes what the new stream must hold: 15 of the 20 keys. + put_all(&new, "old", 15).await; + + // Adopt, then follow the new stream. + let (_, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let adopted = WatchCursor::adopt_incarnation(new_incarnation); + let node = spawn_node_with(&new, fold, Some(adopted), relist(&new), hold()); + let writer = new.writer().expect("writer"); + let head = put_all(&new, "later", 1).await; + wait_applied(&node, head).await; + let deleted_at = { + assert!(writer.delete("old.3").await.expect("delete")); + put_all(&new, "tail", 1).await + }; + wait_applied(&node, deleted_at).await; + stop(node) + .await + .expect("an adopted fold runs on, held no more"); + + let mut want: Vec = keys_of("old", 0..20); + want.retain(|k| k != "old.3"); + want.push("later.0".into()); + want.push("tail.0".into()); + want.sort(); + assert_eq!( + fold_keys(&path), + want, + "the new stream's put and delete were folded; the five keys it never wrote stay" + ); + let (cursor, _) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + assert_eq!(cursor.as_u64(), Some(deleted_at)); + + // Restarting from the persisted cursor resumes in the new incarnation: no longer foreign. + let (cursor, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let node = spawn_node_with(&new, fold, Some(cursor), relist(&new), hold()); + let after = put_all(&new, "after", 1).await; + wait_applied(&node, after).await; + stop(node) + .await + .expect("restart after adoption resumes without error"); + assert!(fold_keys(&path).contains(&"after.0".to_string())); +} From 87492fce6ba19c9f353a3e68e69adb28fbab7738 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sun, 29 Nov 2026 07:19:42 -0800 Subject: [PATCH 2/5] hold: adoption repairs the fold to the new stream; Hold's no-write is a structure pin; drop circular proofs - adopt_incarnation is an order: run_watch repairs the fold to the new stream's listing (the repair Hold deferred) before following it, so the fold is the new stream and exports no phantom key. - Delete hold_proofs.rs (its lemmas restated their premise); the no-write half is tests/hold_structure.rs with fixture mutants. - Live tests: export after adoption, second recreate, stale adoption. Document known limits. Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 10 +- src/kernels/hold_proofs.rs | 157 ----------------------------- src/kernels/mod.rs | 2 - src/kv.rs | 20 +++- src/repair.rs | 25 ++++- tests/hold_structure.rs | 92 +++++++++++++++++ tests/recreated_stream.rs | 195 ++++++++++++++++++++++++++++++------- 7 files changed, 298 insertions(+), 203 deletions(-) delete mode 100644 src/kernels/hold_proofs.rs create mode 100644 tests/hold_structure.rs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index bf0e112..13c4c32 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -242,7 +242,11 @@ The one exception: an update carrying the **unknown** version (an unparseable AC **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. -**Foreign cursor, held (`ForeignPolicy::Hold`).** The repair above is right for a fold that is a view derived from the bucket, and wrong for one that is the only full copy (a consumer that is the bucket's only writer): it deletes every key the new stream lacks, and the new stream starts empty. `BatchConfig::on_foreign` chooses; `Repair` is the default and the behaviour above, unchanged. Under `Hold` a foreign cursor (at resume, or ended mid-watch by the floor guard), and a fold with data and no cursor that names another incarnation, never reaches the repair: the watch task returns `KvError::Foreign { old_incarnation, new_incarnation }` before sending the main loop any request, so no key is deleted, overwritten or re-anchored and the fold stays complete at its old cursor (health: `ForeignCursorRefused`, sticky). The decision is `protocol::foreign_action(policy, mode)`; `Hold` wins over whatever repair is armed. The caller republishes into the new stream (the fold is its source), then resumes with `resume = Some(WatchCursor::adopt_incarnation(new_incarnation))` (`protocol::adopted_position`: rank 0 of the new incarnation). That watch re-lists the new stream over the fold and follows it, so from then on a key the new stream deletes is deleted like any other. A key the new stream never wrote stays in the fold: removing one is the caller's. The persisted cursor stays the old incarnation's until the first batch commits, so a crash in between is held and adopted again (idempotent). A held fold does not export (`export_allowed` refuses a foreign cursor). Proven in `src/kernels/hold_proofs.rs` (Hold never removes a key; the fleet invariant "complete at the cursor" holds for a held fold until adopted; an adopted fold folds the new stream and deletes what it deletes) and `protocol::an_adopted_position_is_the_new_streams_and_precedes_it` (the retry after the hold is admitted); live in `tests/recreated_stream.rs` (`held_fold_keeps_every_key_*`, `adopting_the_new_stream_folds_it_normally`). +**Foreign cursor, held (`ForeignPolicy::Hold`).** The repair above is right for a fold that is a view derived from the bucket, and wrong for one that is the only full copy (a consumer that is the bucket's only writer): it deletes every key the new stream lacks, and the new stream starts empty. `BatchConfig::on_foreign` chooses; `Repair` is the default and the behaviour above, unchanged. Under `Hold` a foreign cursor (at resume, or ended mid-watch by the floor guard), and a fold with data and no cursor that names another incarnation, never reaches the repair: the watch task returns `KvError::Foreign { old_incarnation, new_incarnation }` before sending the main loop any request, so no key is deleted, overwritten or re-anchored and the fold stays complete at its old cursor (health: `ForeignCursorRefused`, sticky). The decision is `protocol::foreign_action(policy, mode)`; `Hold` wins over whatever repair is armed. The caller republishes into the new stream (the fold is its source), then resumes with `resume = Some(WatchCursor::adopt_incarnation(new_incarnation))` (`protocol::adopted_position`: rank 0 of the new incarnation). Adoption is an order, not a position: `run_watch` recognises it (`WatchCursor::adopted_origin`) and runs the repair `Hold` deferred, now that the caller says the new stream is the truth: with `Relist`/`Auto` the fold is repaired as a foreign fold stamped with the new incarnation (synthetic deletes for every fold key the stream does not hold, then the re-list), so right after adoption the fold is the new stream, nothing phantom can be exported, and a later `CursorExpired` behaves like any fold's. With `ExpiryRepair::None` there is no reader to list with: the stream is re-listed over the fold and keys it does not hold stay. Adopting an incarnation that is no longer the stream's (recreated again) is held again. The persisted cursor stays the old incarnation's until the first batch commits, so a crash in between is held and adopted again (idempotent). A held fold does not export (`export_allowed` refuses a foreign cursor). + +*What proves it.* Decision: `protocol::foreign_action` (Verus: `Hold ==> ForeignAction::Hold`, `Repair` unchanged; `mut_hold_repairs` and `mut_repair_holds` are red) and `adopted_position` / `an_adopted_position_is_the_new_streams_and_precedes_it` (the retry after the hold is admitted). Effect: the other half, that a Hold arm writes nothing to the fold, is a structure pin over `run_watch` (`tests/hold_structure.rs`): every Hold arm reaches `return Err(held(..))` before the planner, the resync, the restore or any send to the main loop (the fold's only owner), with fixture mutants that must be caught. Live (`tests/recreated_stream.rs`): `held_fold_keeps_every_key_*`, `adopting_the_new_stream_makes_the_fold_the_new_stream`, `export_after_adoption_is_exactly_the_new_stream` (a cold node restoring the artifact holds exactly the new stream's keys), `a_second_recreate_during_an_adopted_watch_holds_again`, `adopting_a_stale_incarnation_is_held_again`. + +*Known limits.* (A) A cursor with no recorded incarnation (a fold last committed by a 0.9.x build) is admitted by position alone (`same_incarnation`), so a recreated bucket whose stream has grown past that position is not detected as foreign, under `Hold` as under `Repair`; it closes as soon as the fold commits a recorded cursor (`tests/model_incarnation.rs`). Refusing unrecorded cursors under `Hold` needs the model's alternative policy and is not done. (B) Deleting a bucket under a live watch often ends it with a plain `WatchError` (the deleted stream's consumer misses its heartbeat) before the floor guard sees the new incarnation; the caller's restart from the fold's cursor is then held (`a_second_recreate_during_an_adopted_watch_holds_again`). **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: @@ -351,7 +355,7 @@ Every decision the protocol's correctness rests on is a pure function in `src/ke | `payload_prunable` | `transport` prune | `model.rs` | | `resume_window_ok` | `nats` resume paths (`create_resume`), floor guard | every model | | `same_incarnation` | `nats` resume paths (`check_resume_window`), floor guard, `repair::check_restore` | `model_incarnation.rs` | -| `foreign_action` | `repair::run_watch` (foreign cursor, foreign cursor-less fold) | Verus (`hold_proofs.rs`), live `tests/recreated_stream.rs` | +| `foreign_action` | `repair::run_watch` (foreign cursor, foreign cursor-less fold) | Verus contract, `tests/hold_structure.rs`, live `tests/recreated_stream.rs` | | `adopted_position` | `WatchCursor::adopt_incarnation` | Verus (`an_adopted_position_is_the_new_streams_and_precedes_it`), live `tests/recreated_stream.rs` | | `restore_allowed` / `restore_ahead` | `repair::check_restore`, the main loop's ahead re-check | `model.rs`, `model_live_watch.rs`, `model_repair.rs`, `model_fleet.rs` | | `listing_is_truth` | `repair` (plan, cursor-less start), `Snapshot::stale_keys` | every model's view of retention | @@ -529,7 +533,7 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut - **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_hold_repairs` fails `foreign_action`'s contract (a held fold repaired) and the live `held_fold_keeps_every_key_*`; `mut_repair_holds` fails its contract (the default holds) and the live `warm_fold_*` tests; `mut_adopt_unrecorded` fails `adopted_position`'s contract; `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. +`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_hold_repairs` fails `foreign_action`'s contract (a held fold repaired) and the live `held_fold_keeps_every_key_*`; a repair put before a Hold arm's return fails `tests/hold_structure.rs`; `mut_repair_holds` fails its contract (the default holds) and the live `warm_fold_*` tests; `mut_adopt_unrecorded` fails `adopted_position`'s contract; `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/src/kernels/hold_proofs.rs b/src/kernels/hold_proofs.rs deleted file mode 100644 index ef05015..0000000 --- a/src/kernels/hold_proofs.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! A consumer whose fold is the only full copy (`ForeignPolicy::Hold`), proven with no bound: any number of keys and writes. -//! The unbounded statement for the one thing `fleet_proofs` does not cover: a node that must never be repaired. -//! -//! # What is proven -//! -//! The decision is `protocol::foreign_action` (its `*_spec` table below; the kernel's own `ensures` says the code equals it), called -//! by `repair::run_watch` on every foreign cursor, resume-time or mid-watch, and on a cursor-less fold of another incarnation. -//! Under `Hold` the shell's whole effect is to end the watch with `KvError::Foreign`: it sends the fold no repair request, so -//! no delete, put or cursor commit follows. The proofs below take that effect as the spec of the shell (`foreign_step`). -//! -//! * [`a_held_fold_keeps_every_key_on_a_foreign_cursor`]: whatever repair is armed, whatever the repair would have left, a held -//! fold and its cursor are exactly what they were. -//! * [`a_held_fold_is_complete_at_its_old_cursor_until_adopted`]: the fleet's invariant (`fleet_proofs::complete`), restated -//! for a held consumer: a fold of the old stream, complete at its cursor, stays so over every foreign detection and every -//! restart, for as long as it is not adopted. -//! * [`folding_a_new_stream_over_a_held_fold`], [`a_key_the_new_stream_deletes_is_deleted`]: once adopted -//! (`protocol::adopted_position`: the resume position before the first revision of the new stream), the fold folds the new -//! stream normally: a key the new stream wrote is exactly the truth of the new stream, and a key it later deletes is deleted. -//! A key the new stream never wrote keeps its entry: removing one is the caller's, never the watch's. -//! -//! `protocol::an_adopted_position_is_the_new_streams_and_precedes_it` is the liveness partner of the hold: the resume after an -//! adoption is admitted by the new stream. - -use crate::kernels::fleet_proofs::*; -use crate::kernels::protocol::*; -use vstd::prelude::*; - -verus! { - -/// A consumer's persisted fold and the position of the stream it was folded to. -pub struct Held { - pub fold: Fold, - pub cursor: nat, -} - -/// What the shell leaves of the fold after one foreign cursor: the repair's result (`repaired`: anything) when the kernel says -/// repair, and the fold untouched for a refusal and for a hold (the watch ends before any request reaches the fold). -pub open spec fn foreign_step(policy: ForeignPolicy, mode: RepairMode, n: Held, repaired: Held) -> Held { - match foreign_action_spec(policy, mode) { - ForeignAction::Repair => repaired, - _ => n, - } -} - -/// THEOREM (a hold never removes a key): on a foreign cursor a held fold, under any armed repair and whatever the repair -/// would have done, keeps every entry and its cursor. -pub proof fn a_held_fold_keeps_every_key_on_a_foreign_cursor(mode: RepairMode, n: Held, repaired: Held, k: nat) - ensures - (foreign_step(ForeignPolicy::Hold, mode, n, repaired).fold)(k) == (n.fold)(k), - foreign_step(ForeignPolicy::Hold, mode, n, repaired).cursor == n.cursor, -{ -} - -/// The consumer's steps while held: a foreign cursor under any armed repair, and a restart (the persisted fold is what it was). -pub enum HeldAction { - Foreign { mode: RepairMode }, - Restart, -} - -pub open spec fn held_step(a: HeldAction, n: Held, repaired: Held) -> Held { - match a { - HeldAction::Foreign { mode } => foreign_step(ForeignPolicy::Hold, mode, n, repaired), - HeldAction::Restart => n, - } -} - -/// THEOREM (the fleet invariant, for a held consumer): a fold of the old stream that is real and complete at its cursor stays -/// real and complete at that cursor over every foreign detection and restart, however the repair would have changed it, until -/// the caller adopts. (`fleet_proofs::finv` says the same of a node of the current incarnation; a held consumer's incarnation is -/// the dead one, and the invariant is what makes the fold safe to republish from.) -pub proof fn a_held_fold_is_complete_at_its_old_cursor_until_adopted( - old: Log, - a: HeldAction, - n: Held, - repaired: Held, -) - requires - ok_fold(n.fold, old.ops, n.cursor), - ensures - ok_fold(held_step(a, n, repaired).fold, old.ops, held_step(a, n, repaired).cursor), -{ -} - -/// A key is written within the first `b` revisions of `ops`. -pub open spec fn written_by(ops: Seq, b: nat, k: nat) -> bool { - exists|j: int| 0 <= j && j < b && #[trigger] ops[j].key == k -} - -/// THEOREM (an adopted fold folds the new stream normally): fold the new stream's first `b` writes over a held fold `g`. A key the -/// new stream wrote is exactly the new stream's truth at `b` (a put is the entry, a delete removes it); a key it did not write -/// keeps the held entry. -pub proof fn folding_a_new_stream_over_a_held_fold(g: Fold, ops: Seq, b: nat, k: nat) - requires - b <= ops.len(), - ensures - written_by(ops, b, k) ==> fold_range(g, ops, 0, b)(k) == truth(ops, b, k), - !written_by(ops, b, k) ==> fold_range(g, ops, 0, b)(k) == g(k), - decreases b, -{ - if b > 0 { - let prev = (b - 1) as nat; - folding_a_new_stream_over_a_held_fold(g, ops, prev, k); - if ops[prev as int].key == k { - assert(ops[prev as int].key == k); - assert(written_by(ops, b, k)); - } else { - if written_by(ops, b, k) { - let j = choose|j: int| 0 <= j && j < b && #[trigger] ops[j].key == k; - assert(j < prev as int); - assert(written_by(ops, prev, k)); - } - if written_by(ops, prev, k) { - let j = choose|j: int| 0 <= j && j < prev && #[trigger] ops[j].key == k; - assert(0 <= j && j < b && ops[j].key == k); - assert(written_by(ops, b, k)); - } - } - } -} - -/// No write to `k` in `[c, c2)`: the truth at `c2` is the truth at `c`. -pub proof fn truth_is_stable_without_writes(ops: Seq, c: nat, c2: nat, k: nat) - requires - c <= c2, - c2 <= ops.len(), - forall|j: int| c <= j && j < c2 ==> #[trigger] ops[j].key != k, - ensures - truth(ops, c2, k) == truth(ops, c, k), - decreases c2 - c, -{ - if c2 > c { - let prev = (c2 - 1) as nat; - assert(ops[prev as int].key != k); - truth_is_stable_without_writes(ops, c, prev, k); - } -} - -/// THEOREM (a key the new stream deletes is deleted): if revision `r <= b` of the new stream deletes `k` and nothing writes `k` -/// after it up to `b`, the adopted fold, folded to `b`, holds no entry for `k`, whatever it held before. -pub proof fn a_key_the_new_stream_deletes_is_deleted(g: Fold, ops: Seq, b: nat, r: nat, k: nat) - requires - b <= ops.len(), - 1 <= r, - r <= b, - ops[(r - 1) as int].key == k, - !ops[(r - 1) as int].put, - forall|j: int| r <= j && j < b ==> #[trigger] ops[j].key != k, - ensures - fold_range(g, ops, 0, b)(k) is None, -{ - folding_a_new_stream_over_a_held_fold(g, ops, b, k); - assert(ops[(r - 1) as int].key == k); - assert(written_by(ops, b, k)); - truth_is_stable_without_writes(ops, r, b, k); -} - -} // verus! diff --git a/src/kernels/mod.rs b/src/kernels/mod.rs index 57a26f7..acc9936 100644 --- a/src/kernels/mod.rs +++ b/src/kernels/mod.rs @@ -15,6 +15,4 @@ mod applied_proofs; #[cfg(verus_keep_ghost)] mod fleet_proofs; #[cfg(verus_keep_ghost)] -mod hold_proofs; -#[cfg(verus_keep_ghost)] mod transport_proofs; diff --git a/src/kv.rs b/src/kv.rs index 8b9505e..d77ee80 100644 --- a/src/kv.rs +++ b/src/kv.rs @@ -197,10 +197,15 @@ impl WatchCursor { /// [`KvError::Foreign::new_incarnation`] the held watch reported. /// /// It is the position before the first revision of that incarnation - /// ([`adopted_position`](crate::protocol::adopted_position)): the watch re-lists the new stream - /// over the fold (puts replace, nothing is deleted by the re-list itself) and then follows it, - /// and from then on a key the new stream deletes is deleted from the fold like any other. A key - /// the new stream never wrote stays in the fold: removing one is the caller's. The fold's + /// ([`adopted_position`](crate::protocol::adopted_position)), and an order: the caller has + /// republished into the new stream, so the watch repairs the fold to that stream's listing + /// first (the repair `Hold` deferred: synthetic deletes for every fold key the stream does not + /// hold, as the armed [`ExpiryRepair`](crate::ExpiryRepair) does for a foreign cursor), then + /// re-lists it and follows it. Right after adoption the fold is the new stream, a key it later + /// deletes is deleted like any other, and a later expiry behaves like any fold's. With + /// `ExpiryRepair::None` there is no reader to list with: the stream is re-listed over the fold + /// and keys it does not hold stay. Adopting an incarnation that is no longer the stream's + /// (recreated again) is held again. The fold's /// persisted cursor stays the old incarnation's until the first batch commits, so a crash /// before it is held again and adopted again: adoption is idempotent. A `new` of 0 is no /// incarnation and records nothing. @@ -210,6 +215,13 @@ impl WatchCursor { Self::from_version(VersionToken::from_u64(at.rank).with_origin(at.origin)) } + /// The incarnation this cursor adopts, when it is [`adopt_incarnation`](Self::adopt_incarnation)'s + /// (rank 0 of a recorded incarnation; no stream's revisions start below 1). + pub(crate) fn adopted_origin(&self) -> Option { + let at = self.position(); + (self.as_u64() == Some(0) && at.origin != 0).then_some(at.origin) + } + /// 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. diff --git a/src/repair.rs b/src/repair.rs index d021bca..9aaadcd 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -810,6 +810,12 @@ pub(crate) async fn run_watch( // resume position" structural — there is no separate bool whose truth a later // edit could let drift from the `Some`. let mut resume = resume.filter(|c| !c.is_none()); + // A held fold re-anchored by the caller ([`WatchCursor::adopt_incarnation`]): not a position + // to resume from, but the order to repair the fold against the new stream, now. + let adopted = resume.as_ref().and_then(WatchCursor::adopted_origin); + if adopted.is_some() { + resume = None; + } // A cursor-less start that must be repaired before it watches // ([`cursorless_start_needs_repair`]). Retention is read only when the @@ -820,9 +826,24 @@ pub(crate) async fn run_watch( // (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(); + let unanchored_data = unanchored.is_some() || adopted.is_some(); if resume.is_none() { - if let Some(provenance) = unanchored + if let Some(origin) = adopted { + // The caller republished into the stream it adopted, so (with a repair armed) that + // stream's listing is the truth and the fold is repaired to it before the watch: the + // repair `Hold` deferred, run when the caller says go. The fold's data is the old + // stream's whatever the adoption says (`foreign`: its revision numbers decide nothing). + let stream = watcher.retention().await?.and_then(|r| r.incarnation); + let stale = stream != Some(origin); + // The adopted stream is not the one that exists now (recreated again): held again. + if stale && foreign_action(on_foreign, mode) == ForeignAction::Hold { + return Err(held(health, Some(origin), stream)); + } + foreign_start = true; + if !stale { + own_stream = stream; + } + } else if let Some(provenance) = unanchored && (mode != RepairMode::None || on_foreign == ForeignPolicy::Hold) { let stream = watcher.retention().await?.and_then(|r| r.incarnation); diff --git a/tests/hold_structure.rs b/tests/hold_structure.rs new file mode 100644 index 0000000..0e9f040 --- /dev/null +++ b/tests/hold_structure.rs @@ -0,0 +1,92 @@ +//! `ForeignPolicy::Hold` never writes the fold: a structure pin over `repair::run_watch`. +//! +//! The decision (`protocol::foreign_action`, proven in Verus: `Hold ==> ForeignAction::Hold`) is +//! only half the property. The other half is that the shell, once it has decided to hold, returns +//! `KvError::Foreign` before it calls anything that can write the fold: the repair planner, the +//! key-listing resync, the artifact restore, or a send to the main loop (the only task that owns +//! the fold). This test reads the source of `run_watch` and pins that every Hold arm reaches +//! `return Err(held(..))` with none of those between it and the decision. It is red on a fixture +//! mutant that puts a repair before the return. + +const SRC: &str = include_str!("../src/repair.rs"); + +/// What may write the fold, or hand the main loop (which owns it) a request. +const WRITERS: &[&str] = &[ + "plan(", + "resync_stale_keys(", + "restore_from_artifact(", + ".send(", + "repairs", + "watching(", + "forget_cursor", +]; + +fn run_watch(src: &str) -> &str { + let start = src + .find("pub(crate) async fn run_watch") + .expect("run_watch exists"); + let rest = &src[start..]; + let end = rest.find("\n}\n").expect("run_watch ends"); + &rest[..end] +} + +/// Every `ForeignAction::Hold` in `body` is followed by `return Err(held(` with no writer between. +fn check(body: &str) -> Result { + let mut arms = 0; + let mut from = 0; + while let Some(at) = body[from..].find("ForeignAction::Hold") { + let at = from + at; + let tail = &body[at..]; + let ret = tail + .find("return Err(held(") + .ok_or("a Hold arm never returns the typed outcome")?; + let between = &tail[..ret]; + for w in WRITERS { + if between.contains(w) { + return Err(format!("a Hold arm reaches `{w}` before it returns")); + } + } + if between.contains("ForeignAction::") && between.matches("ForeignAction::").count() > 1 { + return Err("a Hold arm runs into another arm before it returns".into()); + } + arms += 1; + from = at + 1; + } + Ok(arms) +} + +#[test] +fn every_hold_arm_returns_before_anything_that_writes_the_fold() { + // The foreign cursor, the foreign cursor-less fold, and a stale adoption. + assert_eq!(check(run_watch(SRC)), Ok(3)); +} + +#[test] +fn the_held_outcome_itself_writes_nothing() { + let start = SRC.find("fn held(").expect("held exists"); + let body = &SRC[start..]; + let body = &body[..body.find("\n}\n").unwrap()]; + for w in WRITERS { + assert!(!body.contains(w), "`held` reaches `{w}`"); + } +} + +/// FIXTURE MUTANT: the Hold arm of a foreign cursor runs the key-listing resync before it returns. +#[test] +fn a_repair_before_the_return_is_caught() { + let mutant = run_watch(SRC).replacen( + "return Err(held(health, cursor.origin(), stream));", + "resync_stale_keys(reader, scratch, (true, None), repairs).await?;\n return Err(held(health, cursor.origin(), stream));", + 1, + ); + assert_ne!(mutant, run_watch(SRC), "the fixture matched"); + assert!(check(&mutant).is_err()); +} + +/// FIXTURE MUTANT: a Hold arm that falls through to the repair (no return). +#[test] +fn a_hold_that_falls_through_is_caught() { + let mutant = run_watch(SRC).replacen("return Err(held(health, provenance, stream));", "", 1); + assert_ne!(mutant, run_watch(SRC), "the fixture matched"); + assert!(check(&mutant).is_err()); +} diff --git a/tests/recreated_stream.rs b/tests/recreated_stream.rs index 6c828c1..4fd6125 100644 --- a/tests/recreated_stream.rs +++ b/tests/recreated_stream.rs @@ -152,7 +152,8 @@ fn relist(bucket: &Arc) -> ExpiryRepair { ExpiryRepair::Relist(bucket.reader()) } -/// The fold's keys and values, and the bucket's: they must be the same set. +/// The fold's keys and values, and the bucket's: they must be the same set. Reads the fold from its +/// file, so the watch must be stopped; `assert_fold_is_bucket_now` is for a running one. 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 @@ -491,19 +492,26 @@ async fn held_fold_keeps_every_key_with_no_repair_armed() { held_fold_keeps_every_key(|_| ExpiryRepair::None).await; } -/// HOLD, then ADOPT: the held fold is the only full copy; the caller republishes into the new -/// stream and adopts it. From then on the fold folds the new stream: a put is folded, a key the new -/// stream deletes is deleted. A key the caller never republished stays (removing it is the caller's). -#[tokio::test(flavor = "multi_thread")] -async fn adopting_the_new_stream_folds_it_normally() { - let nats = TestNats::start().await; - let (_c, old) = open_bucket(&nats).await; - let dir = TempDir::new().unwrap(); - let (path, _) = fold_the_old_stream(&old, dir.path(), 20).await; - - let (_c, new) = recreate(&nats).await; +/// The new incarnation a held watch reports. +fn foreign_new(err: KvError) -> u64 { + match err { + KvError::Foreign { + new_incarnation: Some(new), + .. + } => new, + other => panic!("expected the typed Foreign outcome, got {other:?}"), + } +} - // Held. +/// An old stream folded (20 keys), the bucket recreated, the fold held. Returns the fold's path and +/// the new bucket and incarnation. +async fn held_on_a_recreated_bucket( + nats: &TestNats, + dir: &Path, +) -> (std::path::PathBuf, Arc, u64) { + let (_c, old) = open_bucket(nats).await; + let (path, _) = fold_the_old_stream(&old, dir, 20).await; + let (_c, new) = recreate(nats).await; let (cursor, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); let node = spawn_node_with(&new, fold, Some(cursor), relist(&new), hold()); let err = timeout(Duration::from_secs(10), node.task) @@ -511,43 +519,42 @@ async fn adopting_the_new_stream_folds_it_normally() { .expect("held") .unwrap() .expect_err("held"); - let KvError::Foreign { - new_incarnation: Some(new_incarnation), - .. - } = err - else { - panic!("expected the typed Foreign outcome, got {err:?}"); - }; assert_eq!(fold_keys(&path), keys_of("old", 0..20)); + (path, new, foreign_new(err)) +} + +/// HOLD, then ADOPT: the held fold is the only full copy; the caller republishes what it wants into +/// the new stream and adopts it. Adoption repairs the fold to the new stream (the five keys it did +/// not republish are gone), and from then on the fold folds the new stream: a put is folded, a key +/// it deletes is deleted. +#[tokio::test(flavor = "multi_thread")] +async fn adopting_the_new_stream_makes_the_fold_the_new_stream() { + let nats = TestNats::start().await; + let dir = TempDir::new().unwrap(); + let (path, new, new_incarnation) = held_on_a_recreated_bucket(&nats, dir.path()).await; // The caller republishes what the new stream must hold: 15 of the 20 keys. put_all(&new, "old", 15).await; - // Adopt, then follow the new stream. let (_, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); let adopted = WatchCursor::adopt_incarnation(new_incarnation); let node = spawn_node_with(&new, fold, Some(adopted), relist(&new), hold()); let writer = new.writer().expect("writer"); let head = put_all(&new, "later", 1).await; wait_applied(&node, head).await; - let deleted_at = { - assert!(writer.delete("old.3").await.expect("delete")); - put_all(&new, "tail", 1).await - }; + assert!(writer.delete("old.3").await.expect("delete")); + let deleted_at = put_all(&new, "tail", 1).await; wait_applied(&node, deleted_at).await; stop(node) .await .expect("an adopted fold runs on, held no more"); - let mut want: Vec = keys_of("old", 0..20); - want.retain(|k| k != "old.3"); - want.push("later.0".into()); - want.push("tail.0".into()); - want.sort(); - assert_eq!( - fold_keys(&path), - want, - "the new stream's put and delete were folded; the five keys it never wrote stay" + assert_fold_is_bucket(&path, &new).await; + let keys = fold_keys(&path); + assert!(!keys.contains(&"old.3".to_string())); + assert!( + (15..20).all(|i| !keys.contains(&format!("old.{i}"))), + "the five un-republished keys are gone: {keys:?}" ); let (cursor, _) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); assert_eq!(cursor.as_u64(), Some(deleted_at)); @@ -560,5 +567,123 @@ async fn adopting_the_new_stream_folds_it_normally() { stop(node) .await .expect("restart after adoption resumes without error"); - assert!(fold_keys(&path).contains(&"after.0".to_string())); + assert_fold_is_bucket(&path, &new).await; +} + +/// After adoption the fold is the new stream, so what it exports is exactly the new stream's keys: +/// a cold node that restores the artifact holds no phantom key. +#[tokio::test(flavor = "multi_thread")] +async fn export_after_adoption_is_exactly_the_new_stream() { + let nats = TestNats::start().await; + let dir = TempDir::new().unwrap(); + let (path, new, new_incarnation) = held_on_a_recreated_bucket(&nats, dir.path()).await; + put_all(&new, "old", 15).await; + + let (_, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let adopted = WatchCursor::adopt_incarnation(new_incarnation); + let node = spawn_node_with(&new, fold, Some(adopted), relist(&new), hold()); + let head = put_all(&new, "later", 1).await; + wait_applied(&node, head).await; + + let artifact = dir.path().join("artifact"); + let (reply_tx, reply_rx) = oneshot::channel(); + node.exports + .send(ExportRequest { + dest_dir: artifact.clone(), + reply: reply_tx, + }) + .await + .unwrap(); + reply_rx.await.unwrap().expect("an adopted fold exports"); + stop(node).await.expect("clean stop"); + + let dest = dir.path().join("cold"); + let (_, _cold) = AppendLogSnapshot::import(&artifact, &dest, u64::MAX).unwrap(); + drop(_cold); + assert_fold_is_bucket(&dest, &new).await; +} + +/// The bucket is recreated AGAIN under a live adopted watch: the fold is held again, untouched, and +/// adopting the newest incarnation repairs it to that stream. +#[tokio::test(flavor = "multi_thread")] +async fn a_second_recreate_during_an_adopted_watch_holds_again() { + let nats = TestNats::start().await; + let dir = TempDir::new().unwrap(); + let (path, new, new_incarnation) = held_on_a_recreated_bucket(&nats, dir.path()).await; + put_all(&new, "old", 15).await; + + let (_, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let adopted = WatchCursor::adopt_incarnation(new_incarnation); + let node = spawn_node_with(&new, fold, Some(adopted), relist(&new), hold()); + let head = put_all(&new, "later", 1).await; + wait_applied(&node, head).await; + + let (_c, third) = recreate(&nats).await; + put_all(&third, "third", 3).await; + // The live watch ends: with the typed outcome when its consumer reattaches to the new stream + // (the floor guard), or with a plain watch error when the deleted stream's consumer dies first. + // Either way the fold is untouched, and the restart from its cursor is held again. + let end = timeout(Duration::from_secs(30), node.task) + .await + .expect("a recreate under a live adopted watch ends it") + .unwrap() + .expect_err("the watch ends"); + let mut held_keys = keys_of("old", 0..15); + held_keys.push("later.0".into()); + held_keys.sort(); + assert_eq!(fold_keys(&path), held_keys, "untouched"); + let third_incarnation = match end { + KvError::Foreign { + new_incarnation: Some(n), + .. + } => n, + _ => { + let (cursor, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let node = spawn_node_with(&third, fold, Some(cursor), relist(&third), hold()); + let err = timeout(Duration::from_secs(10), node.task) + .await + .expect("held") + .unwrap() + .expect_err("held again"); + foreign_new(err) + } + }; + assert_ne!(third_incarnation, new_incarnation); + assert_eq!(fold_keys(&path), held_keys, "held again, untouched"); + + // Adopt the newest: the fold becomes that stream. + let (_, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let adopted = WatchCursor::adopt_incarnation(third_incarnation); + let node = spawn_node_with(&third, fold, Some(adopted), relist(&third), hold()); + let head = put_all(&third, "more", 1).await; + wait_applied(&node, head).await; + stop(node).await.expect("clean stop"); + assert_fold_is_bucket(&path, &third).await; +} + +/// Adopting an incarnation that is no longer the stream's (it was recreated again before the +/// adoption ran) is held again, untouched. +#[tokio::test(flavor = "multi_thread")] +async fn adopting_a_stale_incarnation_is_held_again() { + let nats = TestNats::start().await; + let dir = TempDir::new().unwrap(); + let (path, _new, stale) = held_on_a_recreated_bucket(&nats, dir.path()).await; + let (_c, third) = recreate(&nats).await; + put_all(&third, "third", 3).await; + + let (_, fold) = AppendLogSnapshot::open(&path, u64::MAX).unwrap(); + let node = spawn_node_with( + &third, + fold, + Some(WatchCursor::adopt_incarnation(stale)), + relist(&third), + hold(), + ); + let err = timeout(Duration::from_secs(10), node.task) + .await + .expect("held") + .unwrap() + .expect_err("held again"); + assert_ne!(foreign_new(err), stale); + assert_eq!(fold_keys(&path), keys_of("old", 0..20)); } From 43b47f483c917ff72e55394268eef8974b4ca3e9 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sun, 29 Nov 2026 07:22:08 -0800 Subject: [PATCH 3/5] hold: mut_adopt_skips_relist; name the source pin a structure pin Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 6 ++++-- Cargo.toml | 2 ++ src/repair.rs | 6 +++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 13c4c32..bf3340b 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -244,7 +244,9 @@ The one exception: an update carrying the **unknown** version (an unparseable AC **Foreign cursor, held (`ForeignPolicy::Hold`).** The repair above is right for a fold that is a view derived from the bucket, and wrong for one that is the only full copy (a consumer that is the bucket's only writer): it deletes every key the new stream lacks, and the new stream starts empty. `BatchConfig::on_foreign` chooses; `Repair` is the default and the behaviour above, unchanged. Under `Hold` a foreign cursor (at resume, or ended mid-watch by the floor guard), and a fold with data and no cursor that names another incarnation, never reaches the repair: the watch task returns `KvError::Foreign { old_incarnation, new_incarnation }` before sending the main loop any request, so no key is deleted, overwritten or re-anchored and the fold stays complete at its old cursor (health: `ForeignCursorRefused`, sticky). The decision is `protocol::foreign_action(policy, mode)`; `Hold` wins over whatever repair is armed. The caller republishes into the new stream (the fold is its source), then resumes with `resume = Some(WatchCursor::adopt_incarnation(new_incarnation))` (`protocol::adopted_position`: rank 0 of the new incarnation). Adoption is an order, not a position: `run_watch` recognises it (`WatchCursor::adopted_origin`) and runs the repair `Hold` deferred, now that the caller says the new stream is the truth: with `Relist`/`Auto` the fold is repaired as a foreign fold stamped with the new incarnation (synthetic deletes for every fold key the stream does not hold, then the re-list), so right after adoption the fold is the new stream, nothing phantom can be exported, and a later `CursorExpired` behaves like any fold's. With `ExpiryRepair::None` there is no reader to list with: the stream is re-listed over the fold and keys it does not hold stay. Adopting an incarnation that is no longer the stream's (recreated again) is held again. The persisted cursor stays the old incarnation's until the first batch commits, so a crash in between is held and adopted again (idempotent). A held fold does not export (`export_allowed` refuses a foreign cursor). -*What proves it.* Decision: `protocol::foreign_action` (Verus: `Hold ==> ForeignAction::Hold`, `Repair` unchanged; `mut_hold_repairs` and `mut_repair_holds` are red) and `adopted_position` / `an_adopted_position_is_the_new_streams_and_precedes_it` (the retry after the hold is admitted). Effect: the other half, that a Hold arm writes nothing to the fold, is a structure pin over `run_watch` (`tests/hold_structure.rs`): every Hold arm reaches `return Err(held(..))` before the planner, the resync, the restore or any send to the main loop (the fold's only owner), with fixture mutants that must be caught. Live (`tests/recreated_stream.rs`): `held_fold_keeps_every_key_*`, `adopting_the_new_stream_makes_the_fold_the_new_stream`, `export_after_adoption_is_exactly_the_new_stream` (a cold node restoring the artifact holds exactly the new stream's keys), `a_second_recreate_during_an_adopted_watch_holds_again`, `adopting_a_stale_incarnation_is_held_again`. +The adopt-time repair is not a new branch: an adopted start feeds the existing `cursorless_start_needs_repair` (as a fold with data) and then `plan`/`plan_repair`/`listing_truth` and `resync_stale_keys`, the path a foreign Relist takes (its Verus lemma is `lemma_relist`). + +*What proves it.* Decision: `protocol::foreign_action` (Verus: `Hold ==> ForeignAction::Hold`, `Repair` unchanged; `mut_hold_repairs` and `mut_repair_holds` are red) and `adopted_position` / `an_adopted_position_is_the_new_streams_and_precedes_it` (the retry after the hold is admitted). Effect: the other half, that a Hold arm writes nothing to the fold, is a capability-style structure pin over `run_watch` (`tests/hold_structure.rs`: a source check with fixture mutants, not a Verus property): every Hold arm reaches `return Err(held(..))` before the planner, the resync, the restore or any send to the main loop (the fold's only owner), with fixture mutants that must be caught. Live (`tests/recreated_stream.rs`): `held_fold_keeps_every_key_*`, `adopting_the_new_stream_makes_the_fold_the_new_stream`, `export_after_adoption_is_exactly_the_new_stream` (a cold node restoring the artifact holds exactly the new stream's keys), `a_second_recreate_during_an_adopted_watch_holds_again`, `adopting_a_stale_incarnation_is_held_again`. *Known limits.* (A) A cursor with no recorded incarnation (a fold last committed by a 0.9.x build) is admitted by position alone (`same_incarnation`), so a recreated bucket whose stream has grown past that position is not detected as foreign, under `Hold` as under `Repair`; it closes as soon as the fold commits a recorded cursor (`tests/model_incarnation.rs`). Refusing unrecorded cursors under `Hold` needs the model's alternative policy and is not done. (B) Deleting a bucket under a live watch often ends it with a plain `WatchError` (the deleted stream's consumer misses its heartbeat) before the floor guard sees the new incarnation; the caller's restart from the fold's cursor is then held (`a_second_recreate_during_an_adopted_watch_holds_again`). @@ -533,7 +535,7 @@ Each `mut_*` feature turns an obligation red (`mise run verify -- --features mut - **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_hold_repairs` fails `foreign_action`'s contract (a held fold repaired) and the live `held_fold_keeps_every_key_*`; a repair put before a Hold arm's return fails `tests/hold_structure.rs`; `mut_repair_holds` fails its contract (the default holds) and the live `warm_fold_*` tests; `mut_adopt_unrecorded` fails `adopted_position`'s contract; `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. +`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_hold_repairs` fails `foreign_action`'s contract (a held fold repaired) and the live `held_fold_keeps_every_key_*`; a repair put before a Hold arm's return fails `tests/hold_structure.rs`; `mut_adopt_skips_relist` (an adopted fold taken as empty, so no truth re-list) fails the live adopt and export tests; `mut_repair_holds` fails its contract (the default holds) and the live `warm_fold_*` tests; `mut_adopt_unrecorded` fails `adopted_position`'s contract; `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 3e34b2b..d8aadfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -123,6 +123,8 @@ mut_hold_repairs = [] mut_repair_holds = [] # The adopted cursor records no incarnation, so it is admitted by its position alone. mut_adopt_unrecorded = [] +# Adoption follows the new stream without the truth re-list: the held fold's phantom keys stay. +mut_adopt_skips_relist = [] [package.metadata.verus] verify = true diff --git a/src/repair.rs b/src/repair.rs index 9aaadcd..3087191 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -870,7 +870,11 @@ pub(crate) async fn run_watch( RepairMode::Restore | RepairMode::Auto if unanchored_data => None, _ => memo.listing_truth(watcher).await?, }; - repair_first = cursorless_start_needs_repair(mode, unanchored_data, truth); + // Mutation (model tests only): an adopted fold is taken as empty, so the truth re-list is + // skipped and its phantom keys stay (the same input forgery as `mut_unanchored_relist`). + let fold_has_data = + unanchored_data && !(adopted.is_some() && cfg!(feature = "mut_adopt_skips_relist")); + repair_first = cursorless_start_needs_repair(mode, fold_has_data, truth); if repair_first && unanchored_data { warn!( "the fold holds data but no cursor; repairing it like an expired cursor \ From 75394cc3c77b7cae8dbe34f73d021e2f487e9024 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sun, 29 Nov 2026 07:26:25 -0800 Subject: [PATCH 4/5] release: 0.11.0 (KvError::Foreign and BatchConfig::on_foreign are breaking; default unchanged) Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 2 ++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index bf3340b..b438867 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -248,6 +248,8 @@ The adopt-time repair is not a new branch: an adopted start feeds the existing ` *What proves it.* Decision: `protocol::foreign_action` (Verus: `Hold ==> ForeignAction::Hold`, `Repair` unchanged; `mut_hold_repairs` and `mut_repair_holds` are red) and `adopted_position` / `an_adopted_position_is_the_new_streams_and_precedes_it` (the retry after the hold is admitted). Effect: the other half, that a Hold arm writes nothing to the fold, is a capability-style structure pin over `run_watch` (`tests/hold_structure.rs`: a source check with fixture mutants, not a Verus property): every Hold arm reaches `return Err(held(..))` before the planner, the resync, the restore or any send to the main loop (the fold's only owner), with fixture mutants that must be caught. Live (`tests/recreated_stream.rs`): `held_fold_keeps_every_key_*`, `adopting_the_new_stream_makes_the_fold_the_new_stream`, `export_after_adoption_is_exactly_the_new_stream` (a cold node restoring the artifact holds exactly the new stream's keys), `a_second_recreate_during_an_adopted_watch_holds_again`, `adopting_a_stale_incarnation_is_held_again`. +*Version 0.11.0 (breaking, default unchanged).* Two additions break source compatibility because neither type is `#[non_exhaustive]`: the `KvError::Foreign { .. }` variant (an exhaustive `match` on `KvError` needs an arm) and the public `BatchConfig::on_foreign` field (a struct literal without `..Default::default()` needs it). `ForeignPolicy::Repair` is the default: a consumer that adds nothing but the arm or field behaves exactly as before. + *Known limits.* (A) A cursor with no recorded incarnation (a fold last committed by a 0.9.x build) is admitted by position alone (`same_incarnation`), so a recreated bucket whose stream has grown past that position is not detected as foreign, under `Hold` as under `Repair`; it closes as soon as the fold commits a recorded cursor (`tests/model_incarnation.rs`). Refusing unrecorded cursors under `Hold` needs the model's alternative policy and is not done. (B) Deleting a bucket under a live watch often ends it with a plain `WatchError` (the deleted stream's consumer misses its heartbeat) before the floor guard sees the new incarnation; the caller's restart from the fold's cursor is then held (`a_second_recreate_during_an_adopted_watch_holds_again`). **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: diff --git a/Cargo.lock b/Cargo.lock index aa202cd..9f22c26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -159,7 +159,7 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "beyond-slipstream" -version = "0.10.4" +version = "0.11.0" dependencies = [ "aho-corasick", "async-nats", diff --git a/Cargo.toml b/Cargo.toml index d8aadfc..694479a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ rust-version = "1.92" [package] name = "beyond-slipstream" -version = "0.10.4" +version = "0.11.0" edition.workspace = true license.workspace = true rust-version.workspace = true From 5175b5c0fa49fba2256a87fcc92dce0b4d1eb7f7 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sun, 29 Nov 2026 07:26:30 -0800 Subject: [PATCH 5/5] docs: README pins 0.11 Co-Authored-By: Claude Sonnet 5.5 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9b7945f..da28b10 100644 --- a/README.md +++ b/README.md @@ -70,15 +70,15 @@ Operating a bucket (sizing, limits, recovery, alerts): [docs/OPERATIONS.md](docs ```toml [dependencies] -beyond-slipstream = "0.10" +beyond-slipstream = "0.11" ``` On-disk snapshot backends are opt-in cargo features: ```toml -beyond-slipstream = { version = "0.10", features = ["fjall"] } # pure-Rust LSM, no C toolchain -beyond-slipstream = { version = "0.10", features = ["rocksdb"] } # RocksDB (requires C++ toolchain + libclang) -beyond-slipstream = { version = "0.10", features = ["transport"] } # export/import via object_store (S3, GCS, local) +beyond-slipstream = { version = "0.11", features = ["fjall"] } # pure-Rust LSM, no C toolchain +beyond-slipstream = { version = "0.11", features = ["rocksdb"] } # RocksDB (requires C++ toolchain + libclang) +beyond-slipstream = { version = "0.11", features = ["transport"] } # export/import via object_store (S3, GCS, local) ``` ## Concepts