Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,16 @@ 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). 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).

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`.

*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.** <a id="cursor-expiry-repair"></a> 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.
Expand Down Expand Up @@ -280,7 +290,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.

Expand Down Expand Up @@ -349,6 +359,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 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 |
| `plan_repair` | `repair::plan`, `Snapshot::stale_keys` | every model's expiry dispatch |
Expand Down Expand Up @@ -525,7 +537,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_*`; 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

Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -117,6 +117,14 @@ 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 = []
# 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
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions src/applied.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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<WatchHealth>,
/// 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 {
Expand All @@ -162,6 +172,7 @@ impl Default for BatchConfig {
max: 100,
channel_capacity: 256,
health: None,
on_foreign: ForeignPolicy::Repair,
}
}
}
Expand Down Expand Up @@ -428,6 +439,7 @@ where
resume,
unanchored,
repair,
config.on_foreign,
tx,
config.health.clone(),
));
Expand Down
5 changes: 4 additions & 1 deletion src/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading