From 2eb86ffff47df96714bd3508c50ed8cdb43cf891 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 16:09:01 -0800 Subject: [PATCH 1/2] repair: the cursor-expiry restore runs through the cursor-authority kernel The restore's step order (ahead check, diff, listing and its window re-check, chunks, cursor commit, reply) and its refusals were control flow in repair.rs, re-described by hand in tests/model_repair.rs. They are now applied::step events and actions (Restore phase in kernel state); the shell runs the actions only. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 --- ARCHITECTURE.md | 4 +- src/kernels/applied.rs | 183 +++++++++++++++++- src/repair.rs | 407 ++++++++++++++++++++++++----------------- 3 files changed, 417 insertions(+), 177 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ef685d4..bf45df8 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -355,7 +355,7 @@ Every decision the protocol's correctness rests on is a pure function in `src/ke | `cursorless_start_needs_repair` | `repair::run_watch` | `model_repair.rs`, `model_fleet.rs` | | `restore_key` | `repair::restore_diff` | `model_repair.rs` | -**The cursor-authority kernel** (`src/kernels/applied.rs`) is the one stateful kernel: `step(state, event) -> (state, actions)`, no I/O, async or clock. `applied::Fold` turns what it observes (a received update, a flush request, a store result, an export or repair request) into an `Event`, calls `step`, and runs the returned `Action`s through its interpreter; it decides nothing itself. The kernel owns what has no other home: whether a batch is open, whether a stream position is pending, the unsynced eviction memo, the store-failure streak, and where an in-flight flush or resync is. It decides which flush steps run and in which order (domain `apply` before the cursor moves), that a failed store fold re-queues its raw batch at the front (and the streak bound that fail-stops), that an export flushes first, and that the resync's ack follows the folded deletes. The data (updates, cursors, the store) stay in the shell. The two applied models call it too (`tests/model_applied.rs`, `tests/model_resync_order.rs`, through `slipstream::cursor_kernel`): they keep only environment state (deliveries, store contents, crashes, the bucket) and feed `step` events. Their mutations are cargo features that break the kernel itself (`mut_drop_failed_batch`, `mut_resume_from_memory`, `mut_no_ack_barrier`); each turns its model red, and they are for model tests only, never production builds. +**The cursor-authority kernel** (`src/kernels/applied.rs`) is the one stateful kernel: `step(state, event) -> (state, actions)`, no I/O, async or clock. `applied::Fold` turns what it observes (a received update, a flush request, a store result, an export or repair request) into an `Event`, calls `step`, and runs the returned `Action`s through its interpreter; it decides nothing itself. The kernel owns what has no other home: whether a batch is open, whether a stream position is pending, the unsynced eviction memo, the store-failure streak, and where an in-flight flush or resync is. It decides which flush steps run and in which order (domain `apply` before the cursor moves), that a failed store fold re-queues its raw batch at the front (and the streak bound that fail-stops), that an export flushes first, that the resync's ack follows the folded deletes, and the artifact restore's order: ahead check, diff, listing with its window re-check (only when there are delete candidates), chunks folded under the old cursor, the cursor commit, then the reply; a refusal (not ahead, window aged) replies with an error before anything is folded. The restore's phase is kernel state, so an event out of phase is ignored and a restart (a fresh state) re-runs the whole repair. The data (updates, cursors, the store) stay in the shell. The two applied models call it too (`tests/model_applied.rs`, `tests/model_resync_order.rs`, through `slipstream::cursor_kernel`): they keep only environment state (deliveries, store contents, crashes, the bucket) and feed `step` events. Their mutations are cargo features that break the kernel itself (`mut_drop_failed_batch`, `mut_resume_from_memory`, `mut_no_ack_barrier`); each turns its model red, and they are for model tests only, never production builds. **`pointer_publish_allowed(current: &PointerState, candidate_rank: u64) → bool`** @@ -837,7 +837,7 @@ Production code and an exhaustive model checker running the same logic closes th | `src/applied.rs` | `watch_applied` cursor-after-apply combinator, generic over `SnapshotStore`: `WatchScope`, `BatchConfig`, the select loop, and `Fold` — the batch, applied cursor, and store every change goes through (ingest, repair corrections, flush, `ExportRequest` handling, which stamps the scope) | | `src/health.rs` | `WatchHealth`, `HealthSnapshot`, `RepairState`: the observation handle and the head sampler. Writes only; no decision reads it | | `src/preset.rs` | `Preset::full_replica` / `node_slice`: fixes scope and repair per use case, then calls `watch_applied_owned` | -| `src/repair.rs` | Cursor-expiry repair, both halves: `ExpiryRepair`, `RestoreSource`, `RestoredFold`; the watch task (`run_watch`: plan, key listing, artifact checks and fetch) and the main loop's side (`fold_in`: drain, settle, key-listing diff, artifact restore into the `Fold`); scope coverage, restore checks, the in-scope restore diff | +| `src/repair.rs` | Cursor-expiry repair, both halves: `ExpiryRepair`, `RestoreSource`, `RestoredFold`; the watch task (`run_watch`: plan, key listing, artifact checks and fetch) and the main loop's side (`fold_in`: runs the kernel's repair actions: drain, settle, key-listing diff, artifact restore into the `Fold`); scope coverage, restore checks, the in-scope restore diff | | `src/lib.rs` | Re-exports all public types; no logic | | `benches/` | Criterion benchmarks: snapshot write/checkpoint/load throughput, batch throughput, ACK subject parsing | | `tests/integration.rs` | NATS JetStream backend integration suite: each test boots its own `nats-server` on a free port; covers bucket create, CAS, watch semantics, cursor resume, and delete reconciliation | diff --git a/src/kernels/applied.rs b/src/kernels/applied.rs index c240a52..0f7d16f 100644 --- a/src/kernels/applied.rs +++ b/src/kernels/applied.rs @@ -49,6 +49,36 @@ pub struct State { pub flush: Flush, /// A resync's synthetic deletes are being folded; the ack is owed after. pub relisting: bool, + /// Where an artifact restore is. + pub restore: Restore, +} + +/// Where an artifact restore is. Every step waits on a fact the shell +/// observes, so an event that arrives out of phase is ignored (a restart +/// builds a fresh `State`: a crash part-way leaves the whole repair to re-run). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Restore { + #[default] + Idle, + /// Settled; waiting for the authoritative ahead check. + Ahead, + /// Diffing the fold against the artifact. + Diff, + /// Listing live keys for the delete candidates. + Listing, + /// Folding the difference under the old cursor. + Fold, +} + +/// Why a restore changed nothing and replied with an error. The watch fails +/// with it; the main loop carries on. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Refusal { + /// The artifact is not ahead of the fold: a restore never moves it back. + NotAhead, + /// The log evicted writes after the artifact's cursor while the live keys + /// were listed, so the listing cannot vouch for them. + WindowAged, } /// What the shell's queues hold, as facts. @@ -104,6 +134,17 @@ pub enum Event { RepairRequested(RepairKind), /// The resync's synthetic deletes are folded. RelistFolded, + /// The authoritative ahead check ran: `ahead` is + /// `protocol::restore_ahead(artifact cursor, applied cursor)`. + RestoreAhead { ahead: bool }, + /// The fold was diffed against the artifact: `has_deletes`, some key the + /// artifact lacks is a delete candidate. + RestoreDiffed { has_deletes: bool }, + /// The live keys were listed and retention re-read after: `window_ok` is + /// `protocol::resume_window_ok(artifact cursor, first retained revision)`. + RestoreListed { window_ok: bool }, + /// The difference is folded and flushed. + RestoreFolded, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -152,8 +193,22 @@ pub enum Action { DrainBacklog, /// Run the resync's listing diff. RunRelist, - /// Run the artifact restore. - RunRestore, + /// The authoritative ahead check; answer with `RestoreAhead`. + CheckAhead, + /// Diff the fold against the artifact; answer with `RestoreDiffed`. + RunDiff, + /// List the live keys, then re-read retention; answer with `RestoreListed`. + ListLive, + /// Fold the difference in chunks, each flushed, under the OLD cursor; + /// answer with `RestoreFolded`. + FoldChunks, + /// Take the artifact's cursor and flush it, with the final chunk's + /// re-queued remainder if any. + CommitCursor, + /// Reply to the watch task with the artifact's cursor. + ReplyRestored, + /// Reply to the watch task with an error: nothing was changed. + Refuse(Refusal), /// Remember the eviction memo durably. RememberEvicting, /// Release the watch task parked on the resync: the deletes are folded. @@ -355,10 +410,59 @@ pub fn step(mut s: State, e: Event) -> (State, Actions) { a.push(Action::AckResync); a.push(Action::RunRelist); } else { - a.push(Action::RunRestore); + s.restore = Restore::Ahead; + a.push(Action::CheckAhead); } } }, + Event::RestoreAhead { ahead } => { + if s.restore == Restore::Ahead { + // A restore never moves the fold backward. + if ahead { + s.restore = Restore::Diff; + a.push(Action::RunDiff); + } else { + s.restore = Restore::Idle; + a.push(Action::Refuse(Refusal::NotAhead)); + } + } + } + Event::RestoreDiffed { has_deletes } => { + if s.restore == Restore::Diff { + // Nothing to delete: no listing to vouch for, so nothing to + // re-check. + if has_deletes { + s.restore = Restore::Listing; + a.push(Action::ListLive); + } else { + s.restore = Restore::Fold; + a.push(Action::FoldChunks); + } + } + } + Event::RestoreListed { window_ok } => { + if s.restore == Restore::Listing { + // The listing vouches for every write after the artifact's + // cursor only while the log still holds all of them. + if window_ok { + s.restore = Restore::Fold; + a.push(Action::FoldChunks); + } else { + s.restore = Restore::Idle; + a.push(Action::Refuse(Refusal::WindowAged)); + } + } + } + Event::RestoreFolded => { + if s.restore == Restore::Fold { + s.restore = Restore::Idle; + // Now the fold IS the artifact's (in scope): its cursor + // commits with the final chunk's re-queued remainder, and only + // then does the watch task hear of it. + a.push(Action::CommitCursor); + a.push(Action::ReplyRestored); + } + } Event::RelistFolded => { // The ack barrier: the fallback watch starts only after the // synthetic deletes are folded, so a delete-then-recreate during @@ -461,6 +565,79 @@ mod tests { assert!(a.as_slice().is_empty(), "one ack per resync"); } + /// Drive a restore through the kernel: the facts each step reports. + fn restore(ahead: bool, has_deletes: bool, window_ok: bool) -> Vec { + let mut seen = Vec::new(); + let (mut s, a) = step(State::default(), Event::RepairRequested(RepairKind::Restore)); + assert_eq!( + a.as_slice(), + [Action::DrainBacklog, Action::Settle, Action::CheckAhead] + ); + seen.extend(a.as_slice()); + let events = [ + Event::RestoreAhead { ahead }, + Event::RestoreDiffed { has_deletes }, + Event::RestoreListed { window_ok }, + Event::RestoreFolded, + ]; + for e in events { + let (next, a) = step(s, e); + s = next; + seen.extend(a.as_slice()); + } + assert_eq!(s.restore, Restore::Idle, "a restore ends idle"); + seen + } + + #[test] + fn a_restore_commits_the_cursor_after_the_diff_and_replies_last() { + let seen = restore(true, true, true); + assert_eq!( + &seen[3..], + [ + Action::RunDiff, + Action::ListLive, + Action::FoldChunks, + Action::CommitCursor, + Action::ReplyRestored, + ] + ); + // No delete candidate: no listing, so no window re-check. + let seen = restore(true, false, true); + assert_eq!( + &seen[3..], + [ + Action::RunDiff, + Action::FoldChunks, + Action::CommitCursor, + Action::ReplyRestored, + ] + ); + } + + #[test] + fn a_restore_refuses_before_it_changes_anything() { + assert_eq!( + &restore(false, true, true)[3..], + [Action::Refuse(Refusal::NotAhead)] + ); + assert_eq!( + &restore(true, true, false)[3..], + [ + Action::RunDiff, + Action::ListLive, + Action::Refuse(Refusal::WindowAged) + ] + ); + } + + #[test] + fn a_restore_event_out_of_phase_is_ignored() { + let (s, a) = step(State::default(), Event::RestoreFolded); + assert!(a.as_slice().is_empty()); + assert_eq!(s, State::default()); + } + #[test] fn an_export_flushes_first() { let (_, a) = step(State::default(), Event::ExportRequested { has_store: true }); diff --git a/src/repair.rs b/src/repair.rs index 09a2a74..b087b4f 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -25,7 +25,7 @@ //! a fold (here or in an artifact) holds the former. use std::any::Any; -use std::collections::HashSet; +use std::collections::{HashSet, VecDeque}; use std::fs::File; use std::io::{BufReader, BufWriter, Read, Seek, Write}; use std::path::{Path, PathBuf}; @@ -39,7 +39,7 @@ use tracing::{error, info, warn}; use crate::applied::{Fold, WatchScope}; use crate::artifact::ExportManifest; use crate::health::{RepairState, WatchHealth}; -use crate::kernels::applied::{Action, Event, RepairKind}; +use crate::kernels::applied::{Action, Event, RepairKind, Refusal}; use crate::kv::{KvError, KvReader, KvUpdate, KvWatcher, Retention, VersionToken, WatchCursor}; use crate::protocol::{ KeyRestore, KeyState, RepairMode, RepairPlan, cursorless_start_needs_repair, listing_truth, @@ -1210,7 +1210,7 @@ where } } } - Action::RunRestore => { + Action::CheckAhead => { let Some(RepairRequest::Restore { restored, reader, @@ -1218,7 +1218,7 @@ where reply, }) = req.take() else { - unreachable!("RunRestore follows a Restore request") + unreachable!("CheckAhead follows a Restore request") }; return restore_request(fold, restored, reader, watcher, reply, prefixes).await; } @@ -1228,8 +1228,11 @@ where Ok(()) } -/// The restore repair, main-loop half: refuse an artifact that is not ahead of -/// the fold, otherwise fold it in and reply with its cursor. +/// The restore repair, main-loop half: the kernel orders the steps (the ahead +/// check, the diff, the listing and its window re-check, the chunks, the +/// cursor commit, the reply); this runs them. A refusal replies with an error +/// and changes nothing; the watch task fails with it and the main loop +/// carries on. async fn restore_request( fold: &mut Fold, restored: RestoredFold, @@ -1246,33 +1249,237 @@ where O: FnMut(WatchCursor) + Send, { let target = restored.manifest().cursor.clone(); - // The authoritative ahead check (the watch task's ran against its - // resume cursor; a mid-watch expiry delivered past that). A - // restore never moves the fold backward. - if !restore_ahead(target.rank(), fold.applied().rank()) { - let msg = format!( - "cursor-expired restore: the latest artifact (cursor {target:?}) is not \ - ahead of the fold (cursor {:?}); nothing newer to restore from", - fold.applied() - ); - error!(%msg, "cursor-expiry repair refused"); - // The watch task fails with this; its channel closing ends the - // loop. - let _ = reply.send(Err(KvError::WatchError(msg))); - return Ok(()); - } - match restore(fold, restored, &*reader, &*watcher, prefixes).await? { - Ok(()) => { - let _ = reply.send(Ok(target)); - } - Err(msg) => { - error!(%msg, "cursor-expiry repair refused"); - let _ = reply.send(Err(KvError::WatchError(msg))); + let prefixes = disjoint(prefixes); + let max = fold.batch_cap(); + let mut restored = Some(restored); + let mut reply = Some(reply); + // What the diff left: the keys to rewrite (spilled) and the delete + // candidates, until the chunks fold them. + let mut diff: Option<(KeySpill, HashSet)> = None; + // The first retained revision when the listing's window re-check failed. + let mut aged: Option = None; + + let ahead = restore_ahead(target.rank(), fold.applied().rank()); + let mut todo: VecDeque = fold + .decide(Event::RestoreAhead { ahead }) + .into_iter() + .copied() + .collect(); + while let Some(act) = todo.pop_front() { + let next = match act { + Action::Refuse(why) => { + let msg = match why { + // The watch task's check ran against its resume cursor; a + // mid-watch expiry delivered past that. + Refusal::NotAhead => format!( + "cursor-expired restore: the latest artifact (cursor {target:?}) is not \ + ahead of the fold (cursor {:?}); nothing newer to restore from", + fold.applied() + ), + Refusal::WindowAged => format!( + "cursor-expired restore: the log evicted writes after the artifact's \ + cursor ({target:?}, first retained revision {}) while the restore was \ + listing live keys, so the listing can't vouch for them; nothing was \ + changed. Exports must run well inside the bucket's max_age / discard \ + turnover", + aged.map_or_else(|| "?".to_string(), |f| f.to_string()) + ), + }; + error!(%msg, "cursor-expiry repair refused"); + if let Some(reply) = reply.take() { + let _ = reply.send(Err(KvError::WatchError(msg))); + } + let _ = tokio::task::spawn_blocking(move || drop((restored, diff))).await; + return Ok(()); + } + Action::RunDiff => { + let Some(r) = restored.take() else { + unreachable!("the artifact is held until the reply") + }; + let (r, spill, deletes) = run_diff(fold, r, &prefixes).await?; + restored = Some(r); + let has_deletes = !deletes.is_empty(); + diff = Some((spill, deletes)); + fold.decide(Event::RestoreDiffed { has_deletes }) + } + Action::ListLive => { + let Some((_, deletes)) = diff.as_mut() else { + unreachable!("ListLive follows the diff") + }; + // A delete candidate the bucket lists live is kept: its + // current value is a write after the artifact's cursor, which + // the resume delivers (`restore_key`'s `listed_live`). A + // failed listing fails the watch, like the key-listing + // repair's. + for prefix in &prefixes { + reader + .for_each_key(prefix, &mut |key| { + deletes.remove(&key); + }) + .await + .map_err(|e| { + repair_fatal(format!( + "cursor-expired restore: listing live keys under {prefix:?} \ + failed: {e}" + )) + })?; + } + // Retention only moves forward, so a check after the listing + // covers every write before it (`tests/model_repair.rs`). + // Nothing is folded yet. + let first = watcher.retention().await?.map(|r| r.first_revision); + let window_ok = first.is_none_or(|f| resume_window_ok(target.rank(), f)); + if !window_ok { + aged = first; + } + fold.decide(Event::RestoreListed { window_ok }) + } + Action::FoldChunks => { + let Some((spill, deletes)) = diff.take() else { + unreachable!("FoldChunks follows the diff") + }; + info!( + from = ?fold.applied(), + to = ?target, + rewritten = spill.len(), + deleted = deletes.len(), + "cursor-expired restore: replacing the in-scope fold with the artifact's" + ); + let Some(r) = restored.take() else { + unreachable!("the artifact is held until the reply") + }; + restored = Some(fold_chunks(fold, r, spill, deletes, max).await?); + fold.decide(Event::RestoreFolded) + } + Action::CommitCursor => { + // The fold IS the artifact's (in scope): take its cursor, + // committed to the store with the final chunk's re-queued + // remainder, if any. + fold.advance_to(target.clone()); + fold.flush().await?; + continue; + } + Action::ReplyRestored => { + // Closing an LSM can block; drop the temporary fold and its + // scratch dir off the async thread. + let _ = tokio::task::spawn_blocking(move || drop(restored)).await; + if let Some(reply) = reply.take() { + let _ = reply.send(Ok(target)); + } + return Ok(()); + } + other => unreachable!("restore_request: {other:?}"), + }; + for a in &next { + todo.push_back(*a); } } Ok(()) } +/// Diff the fold against the artifact ([`restore_diff`]): the keys to rewrite +/// are spilled to scratch, and only the keys the restore would delete are +/// held, so memory stays bounded at any fold size. +async fn run_diff( + fold: &mut Fold, + restored: RestoredFold, + prefixes: &[String], +) -> Result<(RestoredFold, KeySpill, HashSet), KvError> +where + U: Send, + S: SnapshotStore + Send + 'static, + P: FnMut(&KvUpdate) -> Option + Send, + A: FnMut(Vec) + Send, + O: FnMut(WatchCursor) + Send, +{ + let Some(st) = fold.take_store() else { + unreachable!("repairs are armed only with a store") + }; + let scope = prefixes.to_vec(); + // The artifact fold moves into the blocking task and comes back with the + // store. + let owned = restored; + let (st, owned, diff) = tokio::task::spawn_blocking(move || { + let diff = (|| { + let mut spill = KeySpill::new(owned.scratch.as_deref())?; + let candidates = restore_diff(&st, owned.fold(), &scope, |key| { + spill.push(&key).map_err(SnapshotError::from) + })?; + Ok::<_, SnapshotError>((spill, candidates)) + })(); + (st, owned, diff) + }) + .await + .map_err(|e| repair_fatal(format!("cursor-expired restore: diff task panicked: {e}")))?; + fold.put_store(st); + let (spill, deletes) = diff.map_err(|e| { + repair_fatal(format!( + "cursor-expired restore: diffing the fold against the artifact failed: {e}" + )) + })?; + Ok((owned, spill, deletes)) +} + +/// Fold the difference through parse/apply/store in `max`-sized chunks, values +/// read back per chunk. These carry no stream position: every chunk commits +/// under the old cursor, so a crash part-way re-runs the (idempotent) restore +/// on restart. +async fn fold_chunks( + fold: &mut Fold, + mut restored: RestoredFold, + spill: KeySpill, + deletes: HashSet, + max: usize, +) -> Result, KvError> +where + U: Send, + S: SnapshotStore + Send + 'static, + P: FnMut(&KvUpdate) -> Option + Send, + A: FnMut(Vec) + Send, + O: FnMut(WatchCursor) + Send, +{ + let mut spill = spill + .into_reader() + .map_err(|e| repair_fatal(format!("cursor-expired restore: reading scratch: {e}")))?; + loop { + let (r, sp, updates) = tokio::task::spawn_blocking(move || { + let updates = spill + .take(max) + .map_err(SnapshotError::from) + .and_then(|keys| materialize(restored.fold(), keys)); + (restored, spill, updates) + }) + .await + .map_err(|e| repair_fatal(format!("cursor-expired restore: read task panicked: {e}")))?; + restored = r; + spill = sp; + let updates = updates.map_err(|e| { + repair_fatal(format!( + "cursor-expired restore: reading the artifact failed: {e}" + )) + })?; + if updates.is_empty() { + break; + } + for u in updates { + fold.correct(u); + } + fold.flush().await?; + } + let mut deletes = deletes.into_iter(); + loop { + let chunk: Vec<_> = deletes.by_ref().take(max).collect(); + if chunk.is_empty() { + break; + } + for key in chunk { + fold.correct(restore_delete(key)); + } + fold.flush().await?; + } + Ok(restored) +} + /// The key-listing diff, main-loop half: synthetic deletes for in-scope keys /// the fold holds and the bucket no longer lists — they vanished during the /// gap (their delete markers evicted with the cursor), and the re-list can't @@ -1388,150 +1595,6 @@ where fold.flush().await } -/// The artifact restore, main-loop half: replace the in-scope fold with the -/// artifact's ([`restore_diff`]), then take its cursor. -/// -/// Memory stays bounded at any fold size. The keys to rewrite are spilled to -/// scratch and read back a chunk at a time; only the keys the restore would -/// delete are held, and the bucket's listing is streamed past them rather -/// than collected. With no delete candidates the listing is skipped. -async fn restore( - fold: &mut Fold, - mut restored: RestoredFold, - reader: &dyn KvReader, - watcher: &dyn KvWatcher, - prefixes: &[String], -) -> Result, KvError> -where - U: Send, - S: SnapshotStore + Send + 'static, - P: FnMut(&KvUpdate) -> Option + Send, - A: FnMut(Vec) + Send, - O: FnMut(WatchCursor) + Send, -{ - let target = restored.manifest().cursor.clone(); - let Some(st) = fold.take_store() else { - unreachable!("repairs are armed only with a store") - }; - let prefixes = disjoint(prefixes); - let max = fold.batch_cap(); - let scope = prefixes.clone(); - let (st, r, diff) = tokio::task::spawn_blocking(move || { - let diff = (|| { - let mut spill = KeySpill::new(restored.scratch.as_deref())?; - let candidates = restore_diff(&st, restored.fold(), &scope, |key| { - spill.push(&key).map_err(SnapshotError::from) - })?; - Ok::<_, SnapshotError>((spill, candidates)) - })(); - (st, restored, diff) - }) - .await - .map_err(|e| repair_fatal(format!("cursor-expired restore: diff task panicked: {e}")))?; - fold.put_store(st); - restored = r; - let (spill, mut deletes) = diff.map_err(|e| { - repair_fatal(format!( - "cursor-expired restore: diffing the fold against the artifact failed: {e}" - )) - })?; - - // A delete candidate the bucket lists live is kept: its current value is a - // write after the artifact's cursor, which the resume delivers - // (`restore_key`'s `listed_live`). A failed listing fails the watch, like - // the key-listing repair's. - if !deletes.is_empty() { - for prefix in &prefixes { - reader - .for_each_key(prefix, &mut |key| { - deletes.remove(&key); - }) - .await - .map_err(|e| { - repair_fatal(format!( - "cursor-expired restore: listing live keys under {prefix:?} failed: {e}" - )) - })?; - } - // The listing vouches for every write after the artifact's cursor only - // while the log still holds all of them: one that aged out before the - // listing is unlisted, and would be deleted. Retention only moves - // forward, so a check after the listing covers it - // (`tests/model_repair.rs`, `NoListingRecheck`). Nothing is folded yet. - if let Some(first) = watcher.retention().await?.map(|r| r.first_revision) - && !resume_window_ok(target.rank(), first) - { - let _ = tokio::task::spawn_blocking(move || drop(restored)).await; - return Ok(Err(format!( - "cursor-expired restore: the log evicted writes after the artifact's cursor \ - ({:?}, first retained revision {first}) while the restore was listing live \ - keys, so the listing can't vouch for them; nothing was changed. Exports must \ - run well inside the bucket's max_age / discard turnover", - target - ))); - } - } - info!( - from = ?fold.applied(), - to = ?target, - rewritten = spill.len(), - deleted = deletes.len(), - "cursor-expired restore: replacing the in-scope fold with the artifact's" - ); - - // Fold the difference through parse/apply/store in `max`-sized chunks, - // values read back per chunk. These carry no stream position: every chunk - // commits under the old cursor, so a crash part-way re-runs the - // (idempotent) restore on restart. - let mut spill = spill - .into_reader() - .map_err(|e| repair_fatal(format!("cursor-expired restore: reading scratch: {e}")))?; - loop { - let (r, sp, updates) = tokio::task::spawn_blocking(move || { - let updates = spill - .take(max) - .map_err(SnapshotError::from) - .and_then(|keys| materialize(restored.fold(), keys)); - (restored, spill, updates) - }) - .await - .map_err(|e| repair_fatal(format!("cursor-expired restore: read task panicked: {e}")))?; - restored = r; - spill = sp; - let updates = updates.map_err(|e| { - repair_fatal(format!( - "cursor-expired restore: reading the artifact failed: {e}" - )) - })?; - if updates.is_empty() { - break; - } - for u in updates { - fold.correct(u); - } - fold.flush().await?; - } - let mut deletes = deletes.into_iter(); - loop { - let chunk: Vec<_> = deletes.by_ref().take(max).collect(); - if chunk.is_empty() { - break; - } - for key in chunk { - fold.correct(restore_delete(key)); - } - fold.flush().await?; - } - // Now the fold IS the artifact's (in scope): take its cursor, committed to - // the store with the final chunk's re-queued remainder, if any. - fold.advance_to(target); - fold.flush().await?; - // Closing an LSM can block; drop the temporary fold and its scratch dir - // off the async thread. - let _ = tokio::task::spawn_blocking(move || drop(restored)).await; - Ok(Ok(())) -} - #[cfg(test)] mod tests { use super::*; From 35bc5828677ab58b5dad3427b7d0ebcbdcaf5605 Mon Sep 17 00:00:00 2001 From: Jared Lunde Date: Sat, 21 Nov 2026 16:15:15 -0800 Subject: [PATCH 2/2] fmt --- src/kernels/applied.rs | 5 ++++- src/repair.rs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/kernels/applied.rs b/src/kernels/applied.rs index 0f7d16f..2169f15 100644 --- a/src/kernels/applied.rs +++ b/src/kernels/applied.rs @@ -568,7 +568,10 @@ mod tests { /// Drive a restore through the kernel: the facts each step reports. fn restore(ahead: bool, has_deletes: bool, window_ok: bool) -> Vec { let mut seen = Vec::new(); - let (mut s, a) = step(State::default(), Event::RepairRequested(RepairKind::Restore)); + let (mut s, a) = step( + State::default(), + Event::RepairRequested(RepairKind::Restore), + ); assert_eq!( a.as_slice(), [Action::DrainBacklog, Action::Settle, Action::CheckAhead] diff --git a/src/repair.rs b/src/repair.rs index b087b4f..fced9a6 100644 --- a/src/repair.rs +++ b/src/repair.rs @@ -39,7 +39,7 @@ use tracing::{error, info, warn}; use crate::applied::{Fold, WatchScope}; use crate::artifact::ExportManifest; use crate::health::{RepairState, WatchHealth}; -use crate::kernels::applied::{Action, Event, RepairKind, Refusal}; +use crate::kernels::applied::{Action, Event, Refusal, RepairKind}; use crate::kv::{KvError, KvReader, KvUpdate, KvWatcher, Retention, VersionToken, WatchCursor}; use crate::protocol::{ KeyRestore, KeyState, RepairMode, RepairPlan, cursorless_start_needs_repair, listing_truth,