Skip to main content

rushdb_storage/
lib.rs

1//! Ordered KV substrate shared by every node: buffered transactions over a
2//! committed B-tree view, atomic redb publication of expanded op sets, a
3//! serialized command log, multi-version snapshot reads, and
4//! serializable-optimistic dependency validation.
5
6// The storage boundary deliberately exposes byte-oriented iterator and callback
7// signatures. Naming each nested trait-object form would obscure that API.
8#![allow(clippy::type_complexity)]
9
10mod adapter_budgets;
11pub mod backend;
12pub mod cache;
13mod health;
14pub mod read_accounting;
15mod transaction_view;
16pub use transaction_view::Txn;
17use transaction_view::TxnBase;
18mod commit;
19mod copy_on_write;
20pub use copy_on_write::CopyOnWrite;
21mod conflict_window;
22mod derive;
23mod fair_gate;
24pub mod history_v2;
25mod layout;
26mod log_export;
27pub mod log_store;
28mod maintenance;
29mod memory_backend;
30mod observability;
31mod overlay_view;
32pub mod owner_sets;
33mod persist;
34pub mod planner_stats;
35mod publish;
36mod read_view;
37mod receipt;
38mod redb_backend;
39pub mod resources;
40mod temp_path;
41pub mod tenant_dir;
42mod usage;
43pub use temp_path::TempPath;
44pub use usage::is_usage_bytes_key;
45pub mod wal;
46mod wal_replay;
47use backend::StorageBackend;
48pub use derive::{DeriveRead, Deriver};
49pub use maintenance::CompactOutcome;
50pub use observability::{
51    BackendLockTimes, CommitObserver, CommitPhase, WriterHolder, WriterHolds, WRITER_HOLD_BOUNDS,
52};
53pub use overlay_view::OverlayView;
54pub use planner_stats::PlannerStats;
55pub use read_view::{
56    ReadCancellation, ReadLimits, ReadPin, ReadView, ScanBatch, ScanBounds, ScanCursor,
57    ScanProjection, ScanRow,
58};
59
60#[cfg(test)]
61mod derive_tests;
62#[cfg(test)]
63mod read_view_tests;
64#[cfg(test)]
65mod receipt_tests;
66#[cfg(test)]
67mod regression_tests;
68#[cfg(test)]
69mod sequencer_tests;
70#[cfg(test)]
71mod writer_tests;
72
73/// Remove the materialization file at `path`. The WAL directory and layout
74/// manifest are left alone.
75///
76/// # Errors
77/// Returns the I/O error of the removal.
78pub fn remove_store(path: &std::path::Path) -> std::io::Result<()> {
79    std::fs::remove_file(path)
80}
81
82use rushdb_types::command::CommitBatch;
83use rushdb_types::ids::TenantId;
84use serde::de::DeserializeOwned;
85use serde::Serialize;
86use std::cell::RefCell;
87use std::collections::{BTreeMap, BTreeSet};
88use std::ops::Bound::{Included, Unbounded};
89use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
90use std::sync::mpsc;
91use std::sync::{Arc, Condvar, Mutex, RwLock};
92use thiserror::Error;
93use uuid::Uuid;
94
95/// Per-tenant outer admission shards, retained for replication call ordering.
96/// Local expansion additionally takes the single logical writer mutex.
97const N_SHARDS: usize = 64;
98
99/// A fully-admitted op-set awaiting batched durable publication, keyed by
100/// its reserved commit index. The publisher drains the contiguous prefix from
101/// the published watermark in one redb write transaction.
102struct PendingCommit {
103    ci: u64,
104    /// Physical shard this commit belongs to (tenant routing). The publisher
105    /// fans out durability across shard backends so different tenants persist
106    /// in parallel once `shard_count > 1`.
107    shard: usize,
108    ops: Vec<Op>,
109    prepared: PreparedCommand,
110    /// The originating `CommitBatch`, pre-serialized: paired with
111    /// `ops` in the WAL record so the command journal is derivable from the
112    /// WAL alone, without a separate `__log__` redb row.
113    command_payload: Vec<u8>,
114    ack: mpsc::Sender<Result<(), StorageError>>,
115}
116
117/// Pending-overlay state for the commit sequencer.
118///
119/// A committed `base` plus the net key effect of every assigned-but-unpublished
120/// commit, so an expansion can read through `Txn`'s overlay instead of waiting
121/// for the predecessor to be published. It is guarded by the writer
122/// `admission_lock`, so every writer that can assign a commit index observes
123/// one consistent overlay.
124///
125/// `buffer` is this state's *own* copy (never the publisher's `pending` map), so
126/// it cannot race the publisher removing a drained entry. Rebase only needs the
127/// generation (commit index) at which each key was last written, so the buffer
128/// stays O(distinct in-flight keys), not O(in-flight ops).
129#[derive(Default)]
130struct SequencerState {
131    /// `key -> (commit index that last wrote it, value or tombstone)` for
132    /// assigned-but-unpublished commits. The committed base is opened fresh
133    /// (and dropped) per critical section, so this state holds no read pin
134    /// between commits and cannot stall GC.
135    buffer: BTreeMap<Vec<u8>, (u64, Option<Vec<u8>>)>,
136}
137
138impl std::fmt::Debug for SequencerState {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        f.debug_struct("SequencerState")
141            .field("in_flight_keys", &self.buffer.len())
142            .finish()
143    }
144}
145
146impl SequencerState {
147    /// Fold an assigned commit's expanded ops into the pending buffer.
148    fn record(&mut self, ci: u64, ops: &[Op]) {
149        for op in ops {
150            match op {
151                Op::Put(key, value) | Op::Set(key, value) => {
152                    self.buffer.insert(key.clone(), (ci, Some(value.clone())));
153                }
154                Op::Del(key) | Op::Purge(key) => {
155                    self.buffer.insert(key.clone(), (ci, None));
156                }
157            }
158        }
159    }
160}
161
162pub(crate) const LOG_PREFIX: &[u8] = b"__log__/";
163const LAST_APPLIED_KEY: &[u8] = b"meta/last-applied";
164/// Durable watermark: the highest LSN retention has retired.
165/// Bounds `Store::truncate_log`, so the retention floor (hard caps and
166/// consumer protection) decides which WAL segments may go.
167pub(crate) const RETENTION_CURSOR_KEY: &[u8] = b"meta/retention-cursor";
168
169/// Durable byte accounting by key family, for growth diagnosis and operator
170/// metrics. All values are exact sums of stored key+value lengths for the
171/// family, taken from one read view; they exclude redb's copy-on-write slack
172/// (compare against [`Store::storage_file_bytes`]).
173#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
174pub struct StorageStatistics {
175    /// Canonical data rows (records, occurrences, postings, catalogs, …).
176    pub data_keys: u64,
177    /// Total key+value bytes of canonical data rows.
178    pub data_bytes: u64,
179    /// Retained MVCC history rows.
180    pub history_keys: u64,
181    /// Total key+encoded-history bytes.
182    pub history_bytes: u64,
183    /// Retained command-log rows (`__log__/<lsn>`).
184    pub log_keys: u64,
185    /// Total command-log bytes.
186    pub log_bytes: u64,
187    /// Retry-receipt rows (receipts plus their expiry index).
188    pub receipt_keys: u64,
189    /// Total retry-receipt bytes.
190    pub receipt_bytes: u64,
191    /// Number of bounded admission-lock waits (including timed-out waits).
192    pub admission_waits: u64,
193    /// Milliseconds spent waiting for admission-lock ownership.
194    pub admission_wait_ms: u64,
195    /// Number of explicit durability checkpoints.
196    pub checkpoints: u64,
197    /// Milliseconds spent in explicit durability checkpoints.
198    pub checkpoint_wait_ms: u64,
199}
200
201/// Errors returned by the storage layer: failed preconditions, corrupt or
202/// unsupported durable state, resource exhaustion, and invalid read requests.
203#[derive(Debug, Clone, Error)]
204pub enum StorageError {
205    /// A poisoned storage lock fenced the store; reopen is required.
206    #[error("storage unhealthy after lock poisoning; reopen required")]
207    Unhealthy,
208    /// A transaction precondition was violated; `path` is the offending key.
209    #[error("precondition failed on {path}")]
210    Precondition {
211        /// Key whose precondition failed.
212        path: String,
213    },
214    /// The deterministic expander failed while building a commit.
215    #[error("builder error: {0}")]
216    Builder(String),
217    /// A durable record could not be decoded or verified.
218    #[error("corrupt log entry")]
219    CorruptLog,
220    /// A log record carries a command version this build does not support.
221    #[error("unsupported command version {0}")]
222    UnsupportedCommandVersion(u32),
223    /// The stored outcome payload is missing or cannot be deserialized.
224    #[error("committed outcome payload is unavailable or incompatible")]
225    OutcomePayload,
226    /// The physical backend failed while applying or reading durable state.
227    #[error("durable storage failure: {0}")]
228    Durability(String),
229    /// The requested snapshot predates the oldest retained commit.
230    #[error("snapshot {requested} expired; oldest supported commit is {oldest}")]
231    SnapshotExpired {
232        /// Snapshot commit index that was requested.
233        requested: u64,
234        /// Oldest commit index still readable.
235        oldest: u64,
236    },
237    /// The requested snapshot is newer than the visible commit index.
238    #[error("snapshot {requested} is newer than visible commit {visible}")]
239    FutureSnapshot {
240        /// Snapshot commit index that was requested.
241        requested: u64,
242        /// Commit index currently visible.
243        visible: u64,
244    },
245    /// A managed byte budget refused the request.
246    #[error("storage resource exhausted: {0}")]
247    ResourceExhausted(String),
248    /// The supplied storage configuration is not valid.
249    #[error("invalid storage configuration: {0}")]
250    InvalidConfiguration(String),
251    /// A pinned read was cancelled by its caller.
252    #[error("storage read cancelled")]
253    Cancelled,
254    /// Scan bounds or batch limits are invalid.
255    #[error("invalid scan bounds or limits: {0}")]
256    InvalidRead(String),
257    /// Physical compaction was requested while protected read views are open.
258    #[error("physical compaction requires all protected read views to close")]
259    ReadersActive,
260    /// No conflict summary is retained for a commit that must be probed.
261    #[error(
262        "actual write summary unavailable for commit {commit_index}; retry with a fresh snapshot"
263    )]
264    ConflictHistoryUnavailable {
265        /// Commit index whose conflict summary is missing.
266        commit_index: u64,
267    },
268}
269
270/// Operation emitted into the atomic publish set.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub enum Op {
273    /// Insert or overwrite a key, retaining the superseded value as history.
274    Put(Vec<u8>, Vec<u8>),
275    /// Remove a key, retaining the removed value as history.
276    Del(Vec<u8>),
277    /// Overwrite a key **without** retaining a superseded version (and drop
278    /// any history already accumulated for it). Used for internal bookkeeping
279    /// keys whose values are not part of user-visible time travel: counters,
280    /// allocation watermarks, degree counters, the label catalog and the
281    /// commit watermark. Without this, every overwrite of a hot counter
282    /// rewrites its whole history vector, which is quadratic in the number of
283    /// writes.
284    Set(Vec<u8>, Vec<u8>),
285    /// Erase a key together with its current-value MVCC metadata and retained
286    /// history, without appending a new version. Destructive by design: used
287    /// by tenant purge, where the values are intentionally destroyed and
288    /// keeping versions for them would bloat storage without bound.
289    Purge(Vec<u8>),
290}
291
292impl Op {
293    /// Approximate encoded size (key + value bytes) for group-commit byte
294    /// accounting (P04 bounded writer).
295    #[must_use]
296    pub fn encoded_len(&self) -> usize {
297        match self {
298            Op::Put(k, v) | Op::Set(k, v) => k.len() + v.len(),
299            Op::Del(k) | Op::Purge(k) => k.len(),
300        }
301    }
302}
303
304/// Reason prefix of a [`CommitOutcome::Conflicted`] caused by a read
305/// dependency that a later commit wrote (first-committer-wins).
306pub const SERIALIZABLE_CONFLICT: &str = "serializable_conflict";
307
308/// Serializable-mode read dependencies recorded against a transaction.
309/// Zero-width entries are point reads; otherwise half-open [start,end).
310#[derive(Default, Clone, Debug)]
311pub struct DependencySet {
312    /// Recorded read ranges as `(start, end)` pairs; a zero-width pair is a
313    /// point dependency.
314    pub ranges: Vec<(Vec<u8>, Vec<u8>)>,
315    whole_keyspace: bool,
316}
317
318impl DependencySet {
319    /// Whether no point, range, or whole-keyspace dependency was recorded.
320    #[must_use]
321    pub fn is_empty(&self) -> bool {
322        self.ranges.is_empty() && !self.whole_keyspace
323    }
324
325    /// Record a half-open `[start, end)` range dependency.
326    pub fn record(&mut self, start: Vec<u8>, end: Vec<u8>) {
327        self.ranges.push((start, end));
328    }
329
330    /// Prefix tracking is explicit so an empty prefix (all keys) is distinct
331    /// from a point dependency on the empty key.
332    pub fn record_prefix(&mut self, prefix: &[u8]) {
333        if prefix.is_empty() {
334            self.whole_keyspace = true;
335        } else {
336            let (start, end) = prefix_range(prefix);
337            self.record(start, end);
338        }
339    }
340
341    /// Merge dependencies captured by another preparation phase.
342    pub fn extend(&mut self, other: Self) {
343        self.ranges.extend(other.ranges);
344        self.whole_keyspace |= other.whole_keyspace;
345    }
346
347    fn intersects(&self, key: &[u8]) -> bool {
348        self.whole_keyspace
349            || self.ranges.iter().any(|(s, e)| {
350                if s == e {
351                    key == s.as_slice()
352                } else {
353                    key >= s.as_slice() && (e.is_empty() || key < e.as_slice())
354                }
355            })
356    }
357
358    /// Whether `key` falls in any recorded read range (serializable conflict
359    /// probe for transaction commit).
360    #[must_use]
361    pub fn intersects_key(&self, key: &[u8]) -> bool {
362        self.intersects(key)
363    }
364}
365
366/// Prepared metadata for one admitted command. The publisher keeps this
367/// alongside expanded operations so an admission overlay can validate
368/// read/write conflicts without re-expanding the command.
369#[derive(Clone, Debug, Default)]
370pub struct PreparedCommand {
371    /// Reserved commit index, preserving command-log order.
372    pub commit_index: u64,
373    /// Canonical keys written by the expanded operation set.
374    pub writes: BTreeSet<Vec<u8>>,
375    /// Keys/ranges read while preparing the command.
376    pub reads: DependencySet,
377    /// Expanded under writer admission against the sequencer overlay, so its
378    /// reads already observed every lower-index commit (published or
379    /// pending). Such a command can share a publish group with the commits
380    /// it read from: the group applies in commit-index order.
381    pub sequenced: bool,
382}
383
384impl PreparedCommand {
385    /// Build prepared metadata from an expanded operation set.
386    #[must_use]
387    pub fn from_ops(commit_index: u64, ops: &[Op]) -> Self {
388        let writes = ops
389            .iter()
390            .map(|op| match op {
391                Op::Put(key, _) | Op::Set(key, _) | Op::Del(key) | Op::Purge(key) => key,
392            })
393            .cloned()
394            .collect();
395        Self {
396            commit_index,
397            writes,
398            reads: DependencySet::default(),
399            sequenced: false,
400        }
401    }
402
403    /// Whether this command's reads overlap writes from `other`, or vice
404    /// versa. The check is symmetric and suitable for optimistic admission.
405    ///
406    /// The write-write check (large-transaction support, Part F) uses
407    /// `writes` being a `BTreeSet` directly — `other.writes.contains(key)`
408    /// is O(log n), not the nested linear scan this used to be. Filtering
409    /// only `self`'s side is still exactly equivalent to filtering both:
410    /// `is_coordination_write` is a pure function of the key's own bytes, so
411    /// if `key` already passed the filter, an identical byte sequence in
412    /// `other.writes` has the same classification — there is no case where
413    /// filtering the other side too would change the answer.
414    ///
415    /// Read sets are probed **against** the ordered write set — one range
416    /// query per recorded read — rather than testing every written key
417    /// against a linear list of read ranges. The old form was
418    /// O(writes × reads) per pair and, applied pairwise inside every publish
419    /// group, starved bulk ingest for minutes (cloud-capacity F4 follow-up).
420    #[must_use]
421    pub fn conflicts_with(&self, other: &Self) -> bool {
422        reads_hit_writes(&other.reads, &self.writes)
423            || reads_hit_writes(&self.reads, &other.writes)
424            || {
425                let (small, large) = if self.writes.len() <= other.writes.len() {
426                    (&self.writes, &other.writes)
427                } else {
428                    (&other.writes, &self.writes)
429                };
430                small
431                    .iter()
432                    .filter(|key| !is_coordination_write(key))
433                    .any(|key| large.contains(key))
434            }
435    }
436}
437
438/// Whether any recorded read (point, range, or whole keyspace) covers a
439/// non-coordination key of `writes`. O(reads × log writes).
440fn reads_hit_writes(reads: &DependencySet, writes: &BTreeSet<Vec<u8>>) -> bool {
441    use std::ops::Bound::Excluded;
442    let application = |key: &&Vec<u8>| !is_coordination_write(key);
443    if reads.whole_keyspace {
444        return writes.iter().any(|key| application(&key));
445    }
446    reads.ranges.iter().any(|(start, end)| {
447        if start == end {
448            writes.contains(start) && !is_coordination_write(start)
449        } else if end.is_empty() {
450            writes
451                .range::<[u8], _>((Included(start.as_slice()), Unbounded))
452                .any(|key| application(&key))
453        } else if start < end {
454            writes
455                .range::<[u8], _>((Included(start.as_slice()), Excluded(end.as_slice())))
456                .any(|key| application(&key))
457        } else {
458            false
459        }
460    })
461}
462
463/// Ordered publication owns these metadata rows; they are rewritten by every
464/// commit as part of the command log and do not represent application-level
465/// read/write overlap for group admission.
466fn is_coordination_write(key: &[u8]) -> bool {
467    key == LAST_APPLIED_KEY
468        || key.starts_with(LOG_PREFIX)
469        || key.starts_with(receipt::RECEIPT_PREFIX)
470        || key.starts_with(receipt::RECEIPT_EXP_PREFIX)
471}
472
473/// Inclusive start / exclusive end range covering all keys under a prefix.
474/// An empty end bound means unbounded above.
475#[must_use]
476pub fn prefix_range(prefix: &[u8]) -> (Vec<u8>, Vec<u8>) {
477    let mut end = prefix.to_vec();
478    loop {
479        match end.last_mut() {
480            Some(last) if *last != 0xFF => {
481                *last += 1;
482                return (prefix.to_vec(), end);
483            }
484            Some(_) => {
485                end.pop();
486            }
487            None => return (prefix.to_vec(), Vec::new()),
488        }
489    }
490}
491
492fn log_key(seq: u64) -> Vec<u8> {
493    let mut k = LOG_PREFIX.to_vec();
494    k.extend_from_slice(format!("{seq:020}").as_bytes());
495    k
496}
497
498/// Terminal status of a commit key, as stored durably.
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub enum OutcomeKind {
501    /// The commit succeeded at the given commit index.
502    Committed(u64),
503    /// The commit was terminally aborted and must not be retried under the
504    /// same commit key.
505    Aborted,
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
509enum OutcomeStatus {
510    Committed,
511    Aborted,
512}
513
514/// Result of a commit attempt: either the durable commit index plus the
515/// caller payload, or a conflict reason.
516#[derive(Debug)]
517pub enum CommitOutcome<Payload> {
518    /// The commit was published at `commit_index` with the caller's `payload`.
519    Committed {
520        /// Durable commit index assigned to this commit.
521        commit_index: u64,
522        /// Caller-supplied response payload persisted with the outcome.
523        payload: Payload,
524    },
525    /// The commit was rejected; the string explains the conflict.
526    Conflicted(String),
527}
528
529/// Deterministic state-machine expansion callback: derives every canonical
530/// and derived key implied by one committed batch (document 07).
531pub type ExpandFn = Box<dyn Fn(u64, &CommitBatch, &mut Txn) -> Result<(), String> + Send + Sync>;
532
533/// Accumulated state of one in-flight cross-service transaction. The buffer is
534/// the transaction's uncommitted write overlay (read-buffer-first like `Txn`);
535/// `deps` records the public reads performed inside the transaction;
536/// `mutations`/`preconditions` replay the writes atomically at commit.
537#[derive(Clone)]
538pub struct TxAccumulator {
539    /// Commit index the transaction's snapshot reads are based on.
540    pub base_ci: u64,
541    /// Tenant that owns the transaction.
542    pub tenant: TenantId,
543    /// Uncommitted write overlay, keyed by storage key.
544    pub buffer: BTreeMap<Vec<u8>, Option<Vec<u8>>>,
545    /// Public read dependencies recorded inside the transaction.
546    pub deps: DependencySet,
547    /// Mutations accumulated across statements, replayed at commit.
548    pub mutations: Vec<rushdb_types::command::Mutation>,
549    /// Preconditions accumulated across statements, checked at commit.
550    pub preconditions: Vec<rushdb_types::command::Precondition>,
551    /// Pinned snapshot all transaction reads resolve at. Cross-request
552    /// coordinators set this at BEGIN so statements and expansion observe the
553    /// transaction's snapshot rather than current committed state. `None`
554    /// keeps current-state reads for embedded/short-lived callers.
555    pub base_view: Option<std::sync::Arc<ReadView>>,
556}
557
558impl TxAccumulator {
559    /// Create an empty accumulator for `tenant` whose snapshot is `base_ci`.
560    #[must_use]
561    pub fn new(tenant: TenantId, base_ci: u64) -> Self {
562        TxAccumulator {
563            base_ci,
564            tenant,
565            buffer: BTreeMap::new(),
566            deps: DependencySet::default(),
567            mutations: Vec::new(),
568            preconditions: Vec::new(),
569            base_view: None,
570        }
571    }
572}
573
574/// Replication seam: when installed on a `Store`, local commits build the
575/// canonical `CommitBatch` and route it through the leader. The leader
576/// replicates to the quorum and every node (leader included) applies it
577/// through `Store::apply_replicated_batch`, which returns after the batch is
578/// durably applied locally. Serialized `payload` is stored with the outcome so
579/// idempotent retries can reproduce the caller's response.
580pub trait Replicator: Send + Sync {
581    /// Replicate `batch` with its serialized `payload` to the quorum.
582    ///
583    /// # Errors
584    /// Returns a human-readable reason if replication fails.
585    fn replicate(&self, batch: &CommitBatch, payload: &[u8]) -> Result<(), String>;
586
587    /// Highest commit index durably acknowledged by the replication quorum.
588    ///
589    /// Implementations that cannot expose a watermark return `None`; the
590    /// retention worker then leaves the replica consumer unregistered rather
591    /// than guessing that a lagging replica is caught up.
592    fn acknowledged_commit_index(&self) -> Option<u64> {
593        None
594    }
595}
596
597/// One superseded value of a key, covering the half-open range [from,to).
598#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
599pub struct VersionEntry {
600    /// Commit index at which this version became current.
601    pub from_ci: u64,
602    /// Commit index that superseded this version; `0` means still current.
603    pub to_ci: u64,
604    /// Stored value; `None` represents a deletion.
605    pub value: Option<Vec<u8>>,
606}
607
608/// Ordered key/value store shared by every node: admission, deterministic
609/// expansion, group-commit publication, multi-version reads, and retention.
610pub struct Store {
611    health: Arc<health::StoreHealth>,
612    resources: resources::ByteBudget,
613    transaction_resources: resources::ByteBudget,
614    /// Persistent shared budget for retained logical caches.
615    logical_cache_resources: Option<resources::ByteBudget>,
616    /// Shared reservation pool for in-flight query/adapter phases.
617    phase_resources: Option<resources::ByteBudget>,
618    /// Per-adapter attribution children of the two budgets above.
619    adapter_budgets: adapter_budgets::AdapterBudgets,
620    planner_stats: Arc<planner_stats::PlannerStats>,
621    owner_sets: Arc<owner_sets::OwnerSets>,
622    resource_config: resources::StorageResources,
623    data: Arc<RwLock<BTreeMap<Vec<u8>, Vec<u8>>>>,
624    /// creation commit index per live key (multi-version reads).
625    created: Arc<RwLock<BTreeMap<Vec<u8>, u64>>>,
626    /// superseded values per key for time-travel reads.
627    history: Arc<RwLock<BTreeMap<Vec<u8>, Vec<VersionEntry>>>>,
628    /// lowest commit index that must remain readable (GC watermark).
629    gc_watermark: AtomicU64,
630    /// Logical retention leases (held under `publish_lock` so a successful
631    /// view cannot race GC). Each entry maps a pinned CI to its [`ReadPin`]
632    /// (count, last-lease-ms, generation) so an abandoned reader can be
633    /// expired by age (P06 safe cancellation-before-release).
634    read_pins: Arc<Mutex<BTreeMap<u64, ReadPin>>>,
635    /// Cancellation handles corresponding to each retained read lease. GC
636    /// cancels a lease before removing its retention pin, so an expired view
637    /// cannot continue reading after history is reclaimed.
638    read_cancellations: Arc<Mutex<BTreeMap<u64, Vec<ReadCancellation>>>>,
639    /// Transitional single logical writer. Planning and expansion see the
640    /// fully published predecessor, including global metadata shared by tenants.
641    /// Also owns the sequencer's pending overlay (`SequencerState`).
642    admission_lock: Mutex<SequencerState>,
643    /// A failed fsync can have an uncertain durable outcome. Fence all later
644    /// writes until reopen; never retry publication under another CI in-process.
645    publisher_failure: Mutex<Option<StorageError>>,
646    #[cfg(test)]
647    fail_next_persist: std::sync::atomic::AtomicBool,
648    /// Per-tenant outer admission shards (replication planning order).
649    shards: Vec<Mutex<()>>,
650    /// Serializes durable persist + in-memory publish in commit-index order.
651    publish_lock: Mutex<()>,
652    /// FIFO gate in front of `admission_lock` (see `fair_gate`).
653    admission_queue: fair_gate::FairGate,
654    /// Write sets of recently published commits for optimistic conflict
655    /// validation (in memory only; see `conflict_window`).
656    conflicts: Mutex<conflict_window::ConflictWindow>,
657    /// Fully-admitted op-sets awaiting batched publication, keyed by their
658    /// reserved commit index (drained from `published+1`).
659    pending: Mutex<BTreeMap<u64, PendingCommit>>,
660    pending_cv: Condvar,
661    /// Commit-index reservation counter (1-based). Reservation happens at
662    /// admission; only successful commits consume a slot so the log stays
663    /// dense and replay stays position-indexed.
664    next_commit_index: AtomicU64,
665    /// Last durably persisted + applied index. `committed_version()` reads
666    /// this watermark (a reservation may run ahead of publication).
667    published: AtomicU64,
668    expander: RwLock<Option<Arc<ExpandFn>>>,
669    /// Called with each durable commit's latency in seconds (metrics hook).
670    commit_observer: RwLock<Option<Arc<CommitObserver>>>,
671    /// Apply-time deriver; `None` applies base ops unchanged.
672    deriver: RwLock<Option<Arc<dyn Deriver>>>,
673    /// Bounded tenant-directory resolution cache.
674    tenant_cache: Mutex<tenant_dir::TenantCache>,
675    /// Set when WAL recovery applied records with no deriver installed, so a
676    /// later `set_deriver` fences the store instead of serving missing
677    /// derived rows.
678    underived_replay: std::sync::atomic::AtomicBool,
679    /// One durable backend per physical shard. `shard_count == 1` (default)
680    /// keeps a single element, preserving today's single-file layout. A future
681    /// per-shard commit-index split (W4 phase 2b) routes each tenant's commits
682    /// to its shard's backend for parallel writers.
683    durable: RwLock<Box<[Option<Arc<dyn StorageBackend>>]>>,
684    /// Log-first segmented WAL: when present, the durable truth — a
685    /// commit acks after its op-set is appended+fsynced here, and redb is a
686    /// checkpointed materialization replayed from it. `None` for in-memory.
687    log: Mutex<Option<log_store::LogStore>>,
688    /// Optional replication seam (`OpenRaft` leader): when set, local commits
689    /// route through the leader instead of publishing locally; every node
690    /// (including this one) applies the result via `apply_replicated_batch`.
691    replicator: RwLock<Option<Arc<dyn Replicator>>>,
692    /// Resumable GC cursor: the last history key the background worker
693    /// processed. `None` means no sweep is in progress.
694    gc_cursor: Mutex<Option<Vec<u8>>>,
695    /// Primary durable file path (shard 0), set by `attach_redb`. Used only
696    /// for operator-facing size metrics.
697    data_path: Mutex<Option<std::path::PathBuf>>,
698    /// Copy-on-write state of the data files, recorded at open.
699    copy_on_write: Mutex<Option<CopyOnWrite>>,
700    /// Set at shutdown so long maintenance scans stop promptly and the store
701    /// closes cleanly instead of waiting for a full keyspace scan.
702    maintenance_abort: Arc<AtomicBool>,
703    /// Operator counters for retention/compaction sweeps.
704    log_rows_pruned: AtomicU64,
705    receipts_swept: AtomicU64,
706    /// Clock of retry receipts (unix ms); injectable so tests can age them.
707    receipt_clock: RwLock<Arc<dyn Fn() -> u64 + Send + Sync>>,
708    compactions: AtomicU64,
709    /// Number of group-commit redb write transactions persisted (one fsync
710    /// each under `Local`); the coalescing metric for the linger knob.
711    group_commits: AtomicU64,
712    admission_waits: AtomicU64,
713    admission_wait_ms: AtomicU64,
714    checkpoints: AtomicU64,
715    checkpoint_wait_ms: AtomicU64,
716    /// Wall-clock ms of the last published commit; compaction quiescence gate.
717    last_commit_ms: AtomicU64,
718    /// File bytes immediately after the last compaction; growth-ratio gate.
719    last_compacted_file_bytes: AtomicU64,
720    /// Keys erased by purges (tenant purge) since the last compaction: a
721    /// purge frees pages without growing the file, so it triggers idle
722    /// compaction on its own.
723    purged_since_compaction: AtomicU64,
724}
725
726impl Default for Store {
727    fn default() -> Self {
728        Self::new_in_memory()
729    }
730}
731
732impl Store {
733    /// Create an in-memory store with default resource budgets.
734    ///
735    /// # Panics
736    /// Panics if the default storage resources are invalid, which is a
737    /// compile-time constant and cannot happen at runtime.
738    #[must_use]
739    pub fn new_in_memory() -> Self {
740        Self::new_with_resources(resources::StorageResources::default())
741            .expect("valid default storage resources")
742    }
743
744    /// Create an in-memory store with an explicit resource configuration.
745    ///
746    /// # Errors
747    /// Returns [`StorageError::InvalidConfiguration`] when `config` fails
748    /// validation, or [`StorageError::ResourceExhausted`] when a byte budget
749    /// cannot be created.
750    pub fn new_with_resources(config: resources::StorageResources) -> Result<Self, StorageError> {
751        config
752            .validate()
753            .map_err(|e| StorageError::InvalidConfiguration(e.to_string()))?;
754        let resources = resources::ByteBudget::new("store", config.managed_limit_bytes)
755            .map_err(|e| StorageError::ResourceExhausted(e.to_string()))?;
756        let transaction_resources = resources
757            .child("transaction-staging", config.transaction_pool_bytes)
758            .map_err(|e| StorageError::InvalidConfiguration(e.to_string()))?;
759        // A zero-sized pool is disabled; otherwise it is capped by the root.
760        let optional_child = |name: &'static str, bytes: usize| {
761            (bytes > 0)
762                .then(|| resources.child(name, bytes.min(config.managed_limit_bytes)))
763                .transpose()
764                .map_err(|e| StorageError::InvalidConfiguration(e.to_string()))
765        };
766        let phase_resources = optional_child("query-phases", config.phase_budget_bytes)?;
767        let logical_cache_resources = optional_child("logical-cache", config.logical_cache_bytes)?;
768        let adapter_budgets = adapter_budgets::AdapterBudgets::new(
769            optional_child("vector-cache", config.vector_cache_bytes)?,
770            phase_resources.as_ref(),
771        )?;
772        let owner_sets = Arc::new(owner_sets::OwnerSets::new(
773            logical_cache_resources.as_ref(),
774        )?);
775        let planner_stats = Arc::new(planner_stats::PlannerStats::new(
776            &config,
777            logical_cache_resources.as_ref(),
778            Arc::new(std::time::Instant::now),
779        )?);
780        // The in-memory store is a real `StorageBackend`. `Store` keeps
781        // shared handles to the same maps for diagnostics/replay; the backend
782        // owns the read view and the write path.
783        let health = Arc::new(health::StoreHealth::default());
784        let maintenance_abort = Arc::new(AtomicBool::new(false));
785        let maps = memory_backend::MemoryMaps::new();
786        let memory_backends: Box<[Option<Arc<dyn StorageBackend>>]> = (0..config.shard_count)
787            .map(|_| {
788                Some(Arc::new(memory_backend::MemoryBackend::new(
789                    Arc::clone(&health),
790                    memory_backend::MemoryMaps {
791                        data: Arc::clone(&maps.data),
792                        created: Arc::clone(&maps.created),
793                        history: Arc::clone(&maps.history),
794                    },
795                    Arc::clone(&maintenance_abort),
796                )) as Arc<dyn StorageBackend>)
797            })
798            .collect();
799        let conflicts = conflict_window::ConflictWindow::charged_to(&resources);
800        Ok(Store {
801            resources,
802            transaction_resources,
803            logical_cache_resources,
804            phase_resources,
805            adapter_budgets,
806            planner_stats,
807            owner_sets,
808            resource_config: config,
809            data: Arc::clone(&maps.data),
810            created: Arc::clone(&maps.created),
811            history: Arc::clone(&maps.history),
812            gc_watermark: AtomicU64::new(0),
813            read_pins: Arc::new(Mutex::new(BTreeMap::new())),
814            read_cancellations: Arc::new(Mutex::new(BTreeMap::new())),
815            admission_lock: Mutex::new(SequencerState::default()),
816            health,
817            publisher_failure: Mutex::new(None),
818            #[cfg(test)]
819            fail_next_persist: std::sync::atomic::AtomicBool::new(false),
820            shards: (0..N_SHARDS).map(|_| Mutex::new(())).collect(),
821            publish_lock: Mutex::new(()),
822            admission_queue: fair_gate::FairGate::default(),
823            conflicts: Mutex::new(conflicts),
824            pending: Mutex::new(BTreeMap::new()),
825            pending_cv: Condvar::new(),
826            next_commit_index: AtomicU64::new(1),
827            published: AtomicU64::new(0),
828            expander: RwLock::new(None),
829            commit_observer: RwLock::new(None),
830            deriver: RwLock::new(None),
831            tenant_cache: Mutex::new(tenant_dir::TenantCache::default()),
832            underived_replay: std::sync::atomic::AtomicBool::new(false),
833            durable: RwLock::new(memory_backends),
834            log: Mutex::new(None),
835            replicator: RwLock::new(None),
836            gc_cursor: Mutex::new(None),
837            data_path: Mutex::new(None),
838            copy_on_write: Mutex::new(None),
839            maintenance_abort,
840            log_rows_pruned: AtomicU64::new(0),
841            receipts_swept: AtomicU64::new(0),
842            receipt_clock: RwLock::new(Arc::new(wal::now_ms)),
843            compactions: AtomicU64::new(0),
844            group_commits: AtomicU64::new(0),
845            admission_waits: AtomicU64::new(0),
846            admission_wait_ms: AtomicU64::new(0),
847            checkpoints: AtomicU64::new(0),
848            checkpoint_wait_ms: AtomicU64::new(0),
849            last_commit_ms: AtomicU64::new(0),
850            last_compacted_file_bytes: AtomicU64::new(0),
851            purged_since_compaction: AtomicU64::new(0),
852        })
853    }
854
855    /// The store's managed-byte budget.
856    pub fn resource_budget(&self) -> resources::ByteBudget {
857        self.resources.clone()
858    }
859
860    /// The configuration this store was opened with.
861    pub fn resource_config(&self) -> resources::StorageResources {
862        self.resource_config
863    }
864
865    /// The byte budget charged for transaction staging.
866    pub fn transaction_budget(&self) -> resources::ByteBudget {
867        self.transaction_resources.clone()
868    }
869
870    /// Approximate bytes resident in the writer's current-value and history
871    /// maps. This is the transitional RAM mirror P04 removes; the baseline
872    /// harness records it so the "no full RAM mirror" milestone is
873    /// measurable and comparable across revisions.
874    ///
875    /// Lock poisoning fences the store until reopen.
876    pub fn approximate_map_bytes(&self) -> (u64, u64) {
877        let data = self.health.cleanup(self.data.read());
878        let current: u64 = data.iter().map(|(k, v)| (k.len() + v.len()) as u64).sum();
879        drop(data);
880        let history = self.health.cleanup(self.history.read());
881        let hist: u64 = history
882            .iter()
883            .map(|(k, v)| {
884                k.len() as u64
885                    + v.iter()
886                        .map(|e| e.value.as_ref().map_or(0, std::vec::Vec::len) as u64)
887                        .sum::<u64>()
888            })
889            .sum();
890        (current, hist)
891    }
892
893    /// Shard index for a tenant; commits without a tenant use shard 0.
894    #[expect(
895        clippy::cast_possible_truncation,
896        reason = "the hash is immediately reduced modulo N_SHARDS, so truncating its high bits cannot change routing correctness"
897    )]
898    fn shard_for(tenant: Option<&TenantId>) -> usize {
899        match tenant {
900            Some(t) => {
901                let mut h = 2_166_136_261u64;
902                for b in &t.to_be_bytes() {
903                    h ^= u64::from(*b);
904                    h = h.wrapping_mul(16_777_619);
905                }
906                (h as usize) % N_SHARDS
907            }
908            None => 0,
909        }
910    }
911
912    /// Open a crash-safe redb-backed store. The materialized keyspace and
913    /// MVCC metadata are restored before the store is returned.
914    ///
915    /// # Errors
916    /// Returns [`StorageError`] if the resource configuration is invalid, the
917    /// backend cannot be opened, or its durable watermark cannot be read.
918    pub fn open(path: &std::path::Path) -> Result<Self, StorageError> {
919        Self::open_with_resources(path, resources::StorageResources::default())
920    }
921
922    /// Open a redb-backed store with an explicit resource configuration.
923    ///
924    /// # Errors
925    /// Returns [`StorageError`] if `config` is invalid, the shard backends
926    /// cannot be opened, or their durable watermarks cannot be read.
927    pub fn open_with_resources(
928        path: &std::path::Path,
929        config: resources::StorageResources,
930    ) -> Result<Self, StorageError> {
931        Self::open_with_deriver(path, config, None)
932    }
933
934    /// Open a redb-backed store with the apply-time deriver installed
935    /// *before* WAL recovery, so replayed commits derive the same rows live
936    /// publication would have.
937    ///
938    /// # Errors
939    /// Returns [`StorageError`] if `config` is invalid, the shard backends
940    /// cannot be opened, their watermarks cannot be read, or replay fails.
941    pub fn open_with_deriver(
942        path: &std::path::Path,
943        config: resources::StorageResources,
944        deriver: Option<Arc<dyn Deriver>>,
945    ) -> Result<Self, StorageError> {
946        let store = Self::new_with_resources(config)?;
947        if let Some(deriver) = deriver {
948            store.set_deriver(deriver);
949        }
950        store.attach_redb(path)?;
951        Ok(store)
952    }
953
954    fn attach_redb(&self, path: &std::path::Path) -> Result<(), StorageError> {
955        self.check_health()?;
956        let shard_count = self.resource_config.shard_count;
957        let layout_info =
958            layout::validate_layout(path, shard_count).map_err(StorageError::Durability)?;
959        // Before any file is created, so the shard files and the WAL inherit
960        // it (SCALE-2: checkpoint fsyncs on copy-on-write stall every tenant).
961        if let Some(parent) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) {
962            std::fs::create_dir_all(parent)
963                .map_err(|error| StorageError::Durability(error.to_string()))?;
964        }
965        copy_on_write::opt_out(path);
966        let cache_pool = self
967            .resources
968            .child("redb-cache", self.resource_config.page_cache_bytes)
969            .map_err(|e| StorageError::ResourceExhausted(e.to_string()))?;
970        let mut backends: Vec<Option<Arc<dyn StorageBackend>>> = Vec::with_capacity(shard_count);
971        for shard in 0..shard_count {
972            // Shard 0 keeps the historical single-file name; shard N uses a
973            // suffixed file. With shard_count == 1 the layout is unchanged.
974            let shard_path = if shard == 0 {
975                path.to_path_buf()
976            } else {
977                let mut os = path.as_os_str().to_os_string();
978                os.push(format!("-{shard}"));
979                std::path::PathBuf::from(os)
980            };
981            // Split the configured page cache across physical shards.
982            let shard_cache_bytes = self.resource_config.page_cache_bytes / shard_count;
983            let cache = cache_pool
984                .child("shard", shard_cache_bytes)
985                .and_then(|pool| pool.try_reserve(shard_cache_bytes))
986                .map_err(|e| StorageError::ResourceExhausted(e.to_string()))?;
987            let backend =
988                backend::open_backend(&shard_path, cache).map_err(StorageError::Durability)?;
989            backends.push(Some(backend));
990        }
991        // Each shard file holds its tenants' data plus the global
992        // log/outcome/last-applied rows for commits routed to it. The durable
993        // LSN and GC floor are read for the watermark; the data/created/history
994        // maps are NOT materialized: a redb-backed store reads natively
995        // and stays memory-bounded regardless of dataset size.
996        let mut gc_watermark = 0u64;
997        let mut commit_index = 0u64;
998        let mut materialization: Vec<u64> = Vec::with_capacity(shard_count);
999        for backend in backends.iter().flatten() {
1000            let (lsn, floor) = backend.load_watermark().map_err(StorageError::Durability)?;
1001            materialization.push(lsn);
1002            gc_watermark = gc_watermark.max(floor);
1003            commit_index = commit_index.max(lsn);
1004        }
1005        // Log-first: open the segmented WAL (the durable truth) and replay any
1006        // tail beyond each shard's materialization.
1007        let (log, recovered) = self.open_log_and_replay(path, &backends, &materialization)?;
1008        commit_index = commit_index.max(recovered);
1009        self.gc_watermark.store(gc_watermark, Ordering::SeqCst);
1010        self.next_commit_index
1011            .store(commit_index + 1, Ordering::SeqCst);
1012        self.published.store(commit_index, Ordering::SeqCst);
1013        *self.health.guard(self.log.lock())? = Some(log);
1014        *self.health.guard(self.durable.write())? = backends.into_boxed_slice();
1015        *self.health.guard(self.data_path.lock())? = Some(path.to_path_buf());
1016        *self.health.guard(self.copy_on_write.lock())? = Some(copy_on_write::opt_out(path));
1017        // Idle compaction measures growth from the file as opened, not from
1018        // zero: with a zero baseline every boot compacted the whole file
1019        // under the publish lock (27 min at 10M records, SCALE-1).
1020        self.last_compacted_file_bytes
1021            .store(self.storage_file_bytes().unwrap_or(0), Ordering::Relaxed);
1022        if layout_info.is_none() {
1023            layout::create_manifest(path, shard_count).map_err(StorageError::Durability)?;
1024        }
1025        Ok(())
1026    }
1027
1028    /// The durable backend for a physical shard, if this store has one.
1029    fn backend(&self, shard: usize) -> Option<Arc<dyn StorageBackend>> {
1030        self.health
1031            .cleanup(self.durable.read())
1032            .get(shard)
1033            .and_then(std::clone::Clone::clone)
1034    }
1035
1036    /// Shard 0 backend (the global single-file layout).
1037    fn primary_backend(&self) -> Option<Arc<dyn StorageBackend>> {
1038        self.backend(0)
1039    }
1040
1041    /// The planner-statistics cache: idle eviction and metrics.
1042    #[must_use]
1043    pub fn planner_stats(&self) -> &PlannerStats {
1044        &self.planner_stats
1045    }
1046
1047    /// The persistent shared byte budget for logical caches, or `None`
1048    /// when `resources.logical-cache-bytes` is 0. Every retained cache/cursor
1049    /// reservation from this store contends on this same child.
1050    #[must_use]
1051    pub fn cache_budget(&self) -> Option<resources::ByteBudget> {
1052        self.logical_cache_resources.clone()
1053    }
1054
1055    /// Shared byte budget for active query/adapter phases: one persistent
1056    /// child of the resource tree, so concurrent requests share one cap.
1057    #[must_use]
1058    pub fn phase_budget(&self) -> Option<resources::ByteBudget> {
1059        self.phase_resources.clone()
1060    }
1061
1062    /// All open shard backends, in shard order.
1063    fn all_backends(&self) -> Vec<Arc<dyn StorageBackend>> {
1064        self.health
1065            .cleanup(self.durable.read())
1066            .iter()
1067            .flatten()
1068            .cloned()
1069            .collect()
1070    }
1071
1072    /// Run `op` on every shard backend and collect the results in shard order,
1073    /// with the first error (in shard order) winning. Shards are independent
1074    /// files, so with more than one shard the work runs concurrently — this is
1075    /// what makes multi-shard GC/compaction scale instead of serializing.
1076    fn for_each_backend_parallel<T, F>(&self, op: F) -> Result<Vec<T>, StorageError>
1077    where
1078        T: Send,
1079        F: Fn(&dyn StorageBackend) -> Result<T, String> + Sync,
1080    {
1081        self.check_health()?;
1082        let backends = self.all_backends();
1083        if backends.len() <= 1 {
1084            let mut out = Vec::with_capacity(backends.len());
1085            for backend in &backends {
1086                out.push(op(backend.as_ref()).map_err(StorageError::Durability)?);
1087            }
1088            return Ok(out);
1089        }
1090        std::thread::scope(|scope| {
1091            let handles: Vec<_> = backends
1092                .iter()
1093                .map(|backend| scope.spawn(|| op(backend.as_ref())))
1094                .collect();
1095            let mut out = Vec::with_capacity(handles.len());
1096            let mut first_err: Option<String> = None;
1097            for handle in handles {
1098                match handle.join() {
1099                    Ok(Ok(value)) => out.push(value),
1100                    Ok(Err(error)) => {
1101                        if first_err.is_none() {
1102                            first_err = Some(error);
1103                        }
1104                    }
1105                    Err(_) => {
1106                        if first_err.is_none() {
1107                            first_err = Some("backend worker panicked".to_string());
1108                        }
1109                    }
1110                }
1111            }
1112            match first_err {
1113                Some(error) => Err(StorageError::Durability(error)),
1114                None => Ok(out),
1115            }
1116        })
1117    }
1118
1119    /// Acquire the admission lock, honoring the configured acquisition timeout.
1120    /// A bounded wait turns unbounded writer queueing into a retryable
1121    /// `resource exhausted` instead of an unbounded stall (config #4).
1122    fn acquire_admission(&self) -> Result<std::sync::MutexGuard<'_, SequencerState>, StorageError> {
1123        self.check_health()?;
1124        let timeout_ms = self.resource_config().lock_acquisition_timeout_ms;
1125        if timeout_ms == 0 {
1126            // FIFO: the turn is held until the mutex is acquired, so waiting
1127            // writers acquire admission in arrival order (no starvation).
1128            let _turn = self.admission_queue.enter();
1129            return self.health.guard(self.admission_lock.lock());
1130        }
1131        let started = std::time::Instant::now();
1132        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
1133        loop {
1134            match self.admission_lock.try_lock() {
1135                Ok(guard) => {
1136                    let waited = started.elapsed();
1137                    if waited > std::time::Duration::ZERO {
1138                        self.admission_waits.fetch_add(1, Ordering::Relaxed);
1139                        self.admission_wait_ms.fetch_add(
1140                            u64::try_from(waited.as_millis()).unwrap_or(u64::MAX),
1141                            Ordering::Relaxed,
1142                        );
1143                    }
1144                    return Ok(guard);
1145                }
1146                Err(std::sync::TryLockError::Poisoned(poisoned)) => {
1147                    drop(poisoned);
1148                    self.health.fence();
1149                    return Err(StorageError::Unhealthy);
1150                }
1151                Err(std::sync::TryLockError::WouldBlock) => {
1152                    if std::time::Instant::now() >= deadline {
1153                        let waited = started.elapsed();
1154                        self.admission_waits.fetch_add(1, Ordering::Relaxed);
1155                        self.admission_wait_ms.fetch_add(
1156                            u64::try_from(waited.as_millis()).unwrap_or(u64::MAX),
1157                            Ordering::Relaxed,
1158                        );
1159                        return Err(StorageError::ResourceExhausted(
1160                            "admission lock acquisition timed out".into(),
1161                        ));
1162                    }
1163                    std::thread::sleep(std::time::Duration::from_millis(1));
1164                }
1165            }
1166        }
1167    }
1168
1169    /// Drop the in-flight prefix the published base now subsumes. Called at the
1170    /// top of every writer's admission critical section. It reads `published`
1171    /// once; if the publisher advances in between, the overlay just carries an
1172    /// already-published op redundantly until the next trim, which is harmless
1173    /// (the base holds the same value).
1174    fn trim_sequencer(&self, state: &mut SequencerState) {
1175        let published = self.published.load(Ordering::SeqCst);
1176        state.buffer.retain(|_, (ci, _)| *ci > published);
1177    }
1178
1179    /// Assemble the pending overlay (current committed base + in-flight writes)
1180    /// used to expand a command without waiting for its predecessors to
1181    /// publish. The base is the live committed view, opened here and dropped
1182    /// with the overlay, so no read pin outlives the commit. The caller must
1183    /// hold the admission guard that owns `state`.
1184    fn sequencer_overlay(&self, state: &SequencerState) -> Result<Arc<OverlayView>, StorageError> {
1185        let base = Arc::new(self.read_view()?);
1186        let mut buffer: BTreeMap<Vec<u8>, Option<Vec<u8>>> = BTreeMap::new();
1187        for (key, (_, value)) in &state.buffer {
1188            buffer.insert(key.clone(), value.clone());
1189        }
1190        Ok(Arc::new(OverlayView::with_buffer(base, buffer)))
1191    }
1192
1193    fn check_health(&self) -> Result<(), StorageError> {
1194        if self.data.is_poisoned()
1195            || self.created.is_poisoned()
1196            || self.history.is_poisoned()
1197            || self.publish_lock.is_poisoned()
1198            || self.admission_lock.is_poisoned()
1199            || self.pending.is_poisoned()
1200            || self.publisher_failure.is_poisoned()
1201            || self.read_pins.is_poisoned()
1202            || self.read_cancellations.is_poisoned()
1203            || self.expander.is_poisoned()
1204            || self.durable.is_poisoned()
1205            || self.log.is_poisoned()
1206            || self.replicator.is_poisoned()
1207            || self.gc_cursor.is_poisoned()
1208            || self.data_path.is_poisoned()
1209            || self.shards.iter().any(Mutex::is_poisoned)
1210        {
1211            self.health.fence();
1212        }
1213        self.health.check()
1214    }
1215
1216    fn check_publisher(&self) -> Result<(), StorageError> {
1217        self.check_health()?;
1218        match self.health.guard(self.publisher_failure.lock())?.clone() {
1219            Some(error) => Err(error),
1220            None => Ok(()),
1221        }
1222    }
1223
1224    /// Return the terminal publisher failure, if durable publication has been
1225    /// fenced. Readiness callers use this to avoid routing traffic to a store
1226    /// whose later commits cannot become durable.
1227    ///
1228    /// Lock poisoning fences the store until reopen.
1229    #[must_use]
1230    pub fn publisher_failure(&self) -> Option<String> {
1231        if let Err(error) = self.check_health() {
1232            return Some(error.to_string());
1233        }
1234        self.health
1235            .cleanup(self.publisher_failure.lock())
1236            .as_ref()
1237            .map(ToString::to_string)
1238    }
1239
1240    fn native_transaction_view(&self) -> Result<Option<redb_backend::MergedViews>, StorageError> {
1241        self.check_health()?;
1242        let backends = self.all_backends();
1243        if backends.is_empty() {
1244            return Ok(None);
1245        }
1246        let mut views: Vec<Box<dyn crate::backend::StorageReadView>> =
1247            Vec::with_capacity(backends.len());
1248        for backend in &backends {
1249            views.push(backend.read_view()?);
1250        }
1251        Ok(Some(redb_backend::MergedViews::new(views)))
1252    }
1253
1254    /// Install the deterministic expander used to derive canonical and
1255    /// derived keys for every committed batch.
1256    ///
1257    /// Lock poisoning fences the store until reopen.
1258    pub fn set_expander(&self, expander: Arc<ExpandFn>) {
1259        *self.health.cleanup(self.expander.write()) = Some(expander);
1260    }
1261
1262    /// Whether this store persists to a durable backend. A construction
1263    /// property (was a file opened?), not a property of the map contents.
1264    #[must_use]
1265    pub fn is_durable(&self) -> bool {
1266        self.health.cleanup(self.data_path.lock()).is_some()
1267    }
1268
1269    /// Install a replication seam (e.g. an `OpenRaft` leader). When set, local
1270    /// commits route through the leader instead of publishing locally.
1271    ///
1272    /// Lock poisoning fences the store until reopen.
1273    pub fn set_replicator(&self, replicator: Option<Arc<dyn Replicator>>) {
1274        *self.health.cleanup(self.replicator.write()) = replicator;
1275    }
1276
1277    fn replicator(&self) -> Option<Arc<dyn Replicator>> {
1278        self.health.cleanup(self.replicator.read()).clone()
1279    }
1280
1281    /// Return the replication watermark when the configured replicator can
1282    /// expose one. A missing watermark is deliberately fail-closed for
1283    /// retention: history is retained until coverage is observable.
1284    #[must_use]
1285    pub fn replication_acknowledged_commit(&self) -> Option<u64> {
1286        self.replicator()
1287            .and_then(|replicator| replicator.acknowledged_commit_index())
1288    }
1289
1290    /// Last durably persisted and applied commit index.
1291    pub fn committed_version(&self) -> u64 {
1292        self.published.load(Ordering::SeqCst)
1293    }
1294
1295    /// Public idempotency probe: durable commit index for a commit key.
1296    pub fn committed_index_for(&self, commit_key: Uuid) -> Option<u64> {
1297        self.lookup_outcome(commit_key)
1298            .filter(|(st, _)| matches!(st, OutcomeStatus::Committed))
1299            .map(|(_, ci)| ci)
1300    }
1301
1302    /// Public outcome probe for transaction coordinators: distinguishes a
1303    /// durable committed index from a durable aborted outcome.
1304    pub fn outcome_for(&self, commit_key: Uuid) -> Option<OutcomeKind> {
1305        self.lookup_outcome(commit_key).map(|(st, ci)| match st {
1306            OutcomeStatus::Committed => OutcomeKind::Committed(ci),
1307            OutcomeStatus::Aborted => OutcomeKind::Aborted,
1308        })
1309    }
1310
1311    /// Durably record an aborted outcome under a commit key (used by
1312    /// rollback so a later commit attempt discovers `aborted`, never false
1313    /// success). No data is published.
1314    ///
1315    /// # Errors
1316    /// Returns [`StorageError`] if the durable outcome write fails.
1317    ///
1318    /// Lock poisoning fences the store until reopen.
1319    pub fn record_aborted_outcome(&self, commit_key: Uuid) -> Result<(), StorageError> {
1320        self.check_health()?;
1321        let _admission = self.acquire_admission()?;
1322        self.record_aborted_outcome_admitted(commit_key)
1323    }
1324
1325    fn record_aborted_outcome_admitted(&self, commit_key: Uuid) -> Result<(), StorageError> {
1326        self.check_health()?;
1327        let _guard = self.health.guard(self.publish_lock.lock())?;
1328        if self.lookup_outcome_checked(commit_key)?.is_some() {
1329            return Ok(());
1330        }
1331        // An aborted tx consumes no commit index: the terminal aborted outcome
1332        // is keyed by the commit key and does not occupy a sequence slot, so
1333        // the contiguous publisher never has to fill a hole for it.
1334        self.record_outcome_locked(commit_key, OutcomeStatus::Aborted, 0)?;
1335        Ok(())
1336    }
1337
1338    /// Fallible latest-state point probe. Multi-read consumers must instead
1339    /// hold a `ReadView`. Write admission uses this under the logical writer.
1340    ///
1341    /// # Errors
1342    /// Returns [`StorageError`] if the publisher has failed or the native
1343    /// backend read fails.
1344    ///
1345    /// Lock poisoning fences the store until reopen.
1346    pub fn try_get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, StorageError> {
1347        self.check_health()?;
1348        self.check_publisher()?;
1349        let native = self
1350            .native_transaction_view()?
1351            .ok_or(StorageError::Unhealthy)?;
1352        native.get_current(key, ReadLimits::default(), ScanProjection::KeyValue)
1353    }
1354
1355    /// Fallible outcome probe that distinguishes committed from aborted and
1356    /// surfaces corrupt durable state.
1357    ///
1358    /// # Errors
1359    /// Returns [`StorageError::CorruptLog`] if the stored outcome row is
1360    /// malformed, or a backend error if the read fails.
1361    pub fn try_outcome_for(&self, commit_key: Uuid) -> Result<Option<OutcomeKind>, StorageError> {
1362        self.check_health()?;
1363        Ok(self
1364            .lookup_outcome_checked(commit_key)?
1365            .map(|(status, ci)| match status {
1366                OutcomeStatus::Committed => OutcomeKind::Committed(ci),
1367                OutcomeStatus::Aborted => OutcomeKind::Aborted,
1368            }))
1369    }
1370
1371    /// Fallible exact-width `u64` read for engine callers.
1372    ///
1373    /// # Errors
1374    /// Returns [`StorageError::CorruptLog`] when a present value is not exactly
1375    /// eight bytes, or when the durable read fails.
1376    ///
1377    /// Lock poisoning fences the store until reopen.
1378    pub fn try_get_u64(&self, k: &[u8]) -> Result<Option<u64>, StorageError> {
1379        self.check_health()?;
1380        let bytes = self
1381            .native_transaction_view()?
1382            .ok_or(StorageError::Unhealthy)?
1383            .get_current(k, ReadLimits::default(), ScanProjection::KeyValue)?;
1384        let Some(bytes) = bytes else {
1385            return Ok(None);
1386        };
1387        let raw: [u8; 8] = bytes
1388            .as_slice()
1389            .try_into()
1390            .map_err(|_| StorageError::CorruptLog)?;
1391        Ok(Some(u64::from_be_bytes(raw)))
1392    }
1393
1394    /// Fallible historical prefix scan for engine callers.
1395    ///
1396    /// # Errors
1397    /// Returns backend or read-limit failures.
1398    ///
1399    /// Lock poisoning fences the store until reopen.
1400    pub fn try_range_prefix(&self, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>, StorageError> {
1401        self.check_health()?;
1402        let view = self
1403            .native_transaction_view()?
1404            .ok_or(StorageError::Unhealthy)?;
1405        let (s, e) = prefix_range(prefix);
1406        let rows: Result<Vec<(Vec<u8>, Vec<u8>)>, StorageError> = view
1407            .current_range(&s, &e, ReadLimits::default(), ScanProjection::KeyValue)?
1408            .collect();
1409        rows
1410    }
1411
1412    /// Fallible historical point read for engine callers.
1413    ///
1414    /// # Errors
1415    /// Returns backend or read-limit failures.
1416    ///
1417    /// Lock poisoning fences the store until reopen.
1418    pub fn try_get_at(&self, k: &[u8], snap: u64) -> Result<Option<Vec<u8>>, StorageError> {
1419        self.check_health()?;
1420        self.native_transaction_view()?
1421            .ok_or(StorageError::Unhealthy)?
1422            .get_at(k, snap, ReadLimits::default(), ScanProjection::KeyValue)
1423    }
1424
1425    /// Fallible historical prefix scan for engine callers.
1426    ///
1427    /// # Errors
1428    /// Returns backend or read-limit failures.
1429    ///
1430    /// Lock poisoning fences the store until reopen.
1431    pub fn try_range_prefix_at(
1432        &self,
1433        prefix: &[u8],
1434        snap: u64,
1435    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, StorageError> {
1436        self.check_health()?;
1437        // Read directly through the backend view at `snap` (like `try_get_at`):
1438        // this is a fallible legacy probe, not the pinned `ReadView` path. It
1439        // therefore does not require the store's published watermark to have
1440        // caught up, which raw-apply test/recovery callers rely on.
1441        let view = self
1442            .native_transaction_view()?
1443            .ok_or(StorageError::Unhealthy)?;
1444        let limits = ReadLimits::default();
1445        let (s, e) = prefix_range(prefix);
1446        let mut lower = Included(s);
1447        let upper = if e.is_empty() {
1448            Unbounded
1449        } else {
1450            std::ops::Bound::Excluded(e)
1451        };
1452        let mut out: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
1453        let mut bytes = 0usize;
1454        while let Some(key) = view.next_key(&lower, &upper, limits, true)? {
1455            if let Some(value) = view.get_at(&key, snap, limits, ScanProjection::KeyValue)? {
1456                bytes = bytes.saturating_add(key.len() + value.len());
1457                if bytes > 64 * 1024 * 1024 {
1458                    return Err(StorageError::ResourceExhausted(
1459                        "materialized read exceeds configured limit; use a cursor".into(),
1460                    ));
1461                }
1462                out.push((key.clone(), value));
1463            }
1464            lower = std::ops::Bound::Excluded(key);
1465        }
1466        Ok(out)
1467    }
1468
1469    /// Advances retention: superseded versions covered before the watermark
1470    /// are reclaimed; versions still needed by any newer snapshot stay.
1471    ///
1472    /// # Errors
1473    /// Returns [`StorageError`] if the durable reclamation fails.
1474    ///
1475    /// Lock poisoning fences the store until reopen.
1476    pub fn retire_before(&self, watermark: u64) -> Result<usize, StorageError> {
1477        self.check_health()?;
1478        let _publisher = self.health.guard(self.publish_lock.lock())?;
1479        self.retire_before_locked(watermark)
1480    }
1481
1482    /// Bounded, resumable GC: reclaim history superseded before `watermark`
1483    /// for at most `max_keys` per shard in this call. Returns the next key to
1484    /// resume from (or `None` when every shard finished the walk). A
1485    /// background driver calls this repeatedly; it never performs one
1486    /// monolithic redb txn.
1487    ///
1488    /// # Errors
1489    /// Returns [`StorageError`] if the publisher has failed or a shard's
1490    /// durable reclamation fails.
1491    ///
1492    /// # Panics
1493    /// Panics if the read-pin mutex or history `RwLock` is poisoned by a
1494    /// previous panic.
1495    #[expect(
1496        clippy::needless_pass_by_value,
1497        reason = "public signature is a compatibility contract; the cursor is cloned per shard so taking it by value cannot change behavior"
1498    )]
1499    pub fn retire_before_batch(
1500        &self,
1501        watermark: u64,
1502        cursor: Option<Vec<u8>>,
1503        max_keys: usize,
1504    ) -> Result<Option<Vec<u8>>, StorageError> {
1505        self.check_health()?;
1506        self.check_publisher()?;
1507        // Clamp identically to the monolithic path: never reclaim a version a
1508        // pinned read may still need, never advance the floor past the
1509        // committed version, and never move the floor backwards. The clamp is
1510        // taken under `read_pins`, the same lock reads use for their floor
1511        // check and pin insert, so no read can admit a snapshot below the new
1512        // floor.
1513        let watermark = {
1514            let pins = self.health.guard(self.read_pins.lock())?;
1515            let watermark = watermark.min(self.committed_version());
1516            let watermark = pins
1517                .first_key_value()
1518                .map_or(watermark, |(ci, _)| watermark.min(*ci));
1519            let watermark = watermark.max(self.gc_watermark());
1520            // Publish the floor *while holding* `read_pins`. A reader that
1521            // acquires the lock after this sees the new floor and is rejected;
1522            // a reader that acquired it before this is already reflected in
1523            // `pins`, so the clamp cannot be below its snapshot. Storing after
1524            // unlocking would let a reader admit a below-floor snapshot that
1525            // GC is about to reclaim.
1526            self.gc_watermark
1527                .store(watermark, std::sync::atomic::Ordering::SeqCst);
1528            watermark
1529        };
1530        // Reclaim holds no read lock, so readers are never blocked behind a GC
1531        // write transaction.
1532        // A single cursor is shared across shards. Resume from the smallest
1533        // per-shard cursor so no shard skips keys, and treat the sweep as
1534        // complete only when every shard reports no further work.
1535        let mut last: Option<Vec<u8>> = None;
1536        let mut all_done = true;
1537        for backend in self.all_backends() {
1538            if let Some(k) = backend
1539                .retire_before_batch(watermark, cursor.clone(), max_keys)
1540                .map_err(StorageError::Durability)?
1541            {
1542                all_done = false;
1543                last = Some(match last {
1544                    Some(prev) if prev <= k => prev,
1545                    _ => k,
1546                });
1547            }
1548        }
1549        if all_done {
1550            // Full walk completed on every shard: apply the same in-memory
1551            // retention the monolithic path applies after durable reclamation.
1552            let mut hist = self.health.guard(self.history.write())?;
1553            for entries in hist.values_mut() {
1554                entries.retain(|e| e.to_ci > watermark || e.to_ci == 0);
1555            }
1556            hist.retain(|_, v| !v.is_empty());
1557        }
1558        Ok(last)
1559    }
1560
1561    /// One tick of the background GC loop: reclaim a bounded batch toward
1562    /// the current committed watermark. Returns `true` when the whole history
1563    /// table was swept this tick (a full GC pass completed and a checkpoint
1564    /// was published per shard), `false` when the sweep is mid-walk and the
1565    /// caller should tick again. Safe to call concurrently: each tick is a
1566    /// small redb write transaction.
1567    ///
1568    /// # Errors
1569    /// Returns [`StorageError`] if the publisher has failed or a shard's
1570    /// durable reclamation fails.
1571    ///
1572    /// Lock poisoning fences the store until reopen.
1573    pub fn gc_tick(&self, max_keys: usize) -> Result<bool, StorageError> {
1574        self.check_health()?;
1575        let watermark = self.committed_version();
1576        let cursor = self.health.guard(self.gc_cursor.lock())?.clone();
1577        let next = self.retire_before_batch(watermark, cursor, max_keys)?;
1578        if let Some(k) = next {
1579            *self.health.guard(self.gc_cursor.lock())? = Some(k);
1580            Ok(false)
1581        } else {
1582            // Sweep complete: reset the cursor so the next pass starts
1583            // from the beginning (new histories are reclaimed too).
1584            *self.health.guard(self.gc_cursor.lock())? = None;
1585            Ok(true)
1586        }
1587    }
1588
1589    /// [`Self::gc_tick`] in batches of `max_keys` until the history sweep
1590    /// completes or `budget` has elapsed, so reclamation keeps up with the
1591    /// write rate instead of retiring a fixed number of keys per maintenance
1592    /// tick (SOAK-1: 512 keys per 5 s fell behind ~750 rewrites/s and history
1593    /// grew without bound). Returns whether the sweep completed.
1594    ///
1595    /// # Errors
1596    /// See [`Self::gc_tick`].
1597    pub fn gc_tick_for(
1598        &self,
1599        max_keys: usize,
1600        budget: std::time::Duration,
1601    ) -> Result<bool, StorageError> {
1602        let started = std::time::Instant::now();
1603        loop {
1604            if self.gc_tick(max_keys)? {
1605                return Ok(true);
1606            }
1607            if started.elapsed() >= budget {
1608                return Ok(false);
1609            }
1610        }
1611    }
1612
1613    fn retire_before_locked(&self, watermark: u64) -> Result<usize, StorageError> {
1614        self.check_health()?;
1615        self.check_publisher()?;
1616        let watermark = {
1617            let pins = self.health.guard(self.read_pins.lock())?;
1618            let watermark = watermark.min(self.committed_version());
1619            let watermark = pins
1620                .first_key_value()
1621                .map_or(watermark, |(ci, _)| watermark.min(*ci));
1622            let watermark = watermark.max(self.gc_watermark());
1623            // Fence reads below the new floor while still holding `read_pins`
1624            // (see `retire_before_batch`). A failed durable reclamation leaves
1625            // the floor advanced — a conservative, fail-closed state — never
1626            // the reverse.
1627            self.gc_watermark
1628                .store(watermark, std::sync::atomic::Ordering::SeqCst);
1629            watermark
1630        };
1631        // Prune the in-memory maps first so the reclaimed-version count is
1632        // observable (the durable maps are empty; the backend does its own
1633        // reclamation below). `MemoryBackend::retire_before` then re-prunes the
1634        // same maps idempotently.
1635        let mut removed = 0usize;
1636        {
1637            let mut hist = self.health.guard(self.history.write())?;
1638            for entries in hist.values_mut() {
1639                let before = entries.len();
1640                entries.retain(|e| e.to_ci > watermark || e.to_ci == 0);
1641                removed += before - entries.len();
1642            }
1643            hist.retain(|_, v| !v.is_empty());
1644        }
1645        self.for_each_backend_parallel(|backend| backend.retire_before(watermark))?;
1646        Ok(removed)
1647    }
1648
1649    /// Oldest supported logical commit index, inclusive. New historical views
1650    /// below this floor fail, even if an individual key still has older bytes.
1651    pub fn gc_watermark(&self) -> u64 {
1652        self.gc_watermark.load(std::sync::atomic::Ordering::SeqCst)
1653    }
1654
1655    /// Expire retained read leases older than `max_age_ms` (P06: reader age
1656    /// limits with safe cancellation-before-release). An abandoned reader that
1657    /// never drops its view cannot block history advancement forever; the GC
1658    /// worker calls this so the floor can move. Returns the count of leases
1659    /// released (CI entries whose remaining pin count reached zero).
1660    ///
1661    /// Lock poisoning fences the store until reopen.
1662    pub fn expire_read_pins(&self, max_age_ms: u64) -> usize {
1663        if self.check_health().is_err() {
1664            return 0;
1665        }
1666        let now = wal::now_ms();
1667        let mut pins = self.health.cleanup(self.read_pins.lock());
1668        let mut cancellations = self.health.cleanup(self.read_cancellations.lock());
1669        let mut released = 0usize;
1670        pins.retain(|ci, pin| {
1671            if now.saturating_sub(pin.lease_ms) > max_age_ms {
1672                if let Some(handles) = cancellations.remove(ci) {
1673                    for handle in handles {
1674                        handle.cancel();
1675                    }
1676                }
1677                released += 1;
1678                false
1679            } else {
1680                true
1681            }
1682        });
1683        released
1684    }
1685
1686    /// Observability: the oldest active pin (inclusive CI floor) and how
1687    /// many distinct CIs are retained. Lets operators see long-reader retention
1688    /// and confirm it releases after handles close.
1689    ///
1690    /// Lock poisoning fences the store until reopen.
1691    pub fn retention_summary(&self) -> (Option<u64>, usize) {
1692        let pins = self.health.cleanup(self.read_pins.lock());
1693        (pins.first_key_value().map(|(ci, _)| *ci), pins.len())
1694    }
1695
1696    /// Number of keys in the sequencer's assigned-but-unpublished overlay.
1697    /// Observability for the single-writer in-flight window; returns 0
1698    /// when the admission lock is poisoned rather than panicking a scrape.
1699    #[must_use]
1700    pub fn sequencer_inflight_keys(&self) -> usize {
1701        self.admission_lock
1702            .lock()
1703            .map_or(0, |state| state.buffer.len())
1704    }
1705
1706    /// Reclaim versions superseded at or before the requested watermark,
1707    /// clamped by protected read views and the committed CI. Legacy unpinned
1708    /// readers must still coordinate their own retention. Returns reclaimed
1709    /// version count; canonical current data and command logs are unchanged.
1710    ///
1711    /// # Errors
1712    /// Returns [`StorageError`] if the durable reclamation fails.
1713    pub fn gc(&self, watermark: u64) -> Result<usize, StorageError> {
1714        self.check_health()?;
1715        self.retire_before(watermark)
1716    }
1717
1718    fn record_outcome_locked(
1719        &self,
1720        commit_key: Uuid,
1721        status: OutcomeStatus,
1722        ci: u64,
1723    ) -> Result<(), StorageError> {
1724        self.check_health()?;
1725        let ops: Vec<Op> = receipt::rows(commit_key, status, ci, self.receipt_now(), None)
1726            .into_iter()
1727            .map(|(key, value)| Op::Put(key, value))
1728            .collect();
1729        // Aborted-outcome idempotency markers are local metadata, not part of
1730        // the committed log sequence (they carry no commit index), so they are
1731        // written to the materialization directly rather than the WAL.
1732        self.persist_ops_local(&ops, ci)
1733    }
1734
1735    /// Current time of the receipt clock (unix ms).
1736    fn receipt_now(&self) -> u64 {
1737        (self.health.cleanup(self.receipt_clock.read()).clone())()
1738    }
1739
1740    /// Replace the receipt clock (tests age receipts with a mock clock).
1741    #[doc(hidden)]
1742    pub fn set_receipt_clock(&self, clock: Arc<dyn Fn() -> u64 + Send + Sync>) {
1743        *self.health.cleanup(self.receipt_clock.write()) = clock;
1744    }
1745
1746    /// Stage the receipt of `commit_key` in `txn`.
1747    fn put_receipt(
1748        &self,
1749        txn: &mut Txn<'_>,
1750        commit_key: Uuid,
1751        status: OutcomeStatus,
1752        ci: u64,
1753        payload: Option<&[u8]>,
1754    ) {
1755        for (key, value) in receipt::rows(commit_key, status, ci, self.receipt_now(), payload) {
1756            txn.put(key, value);
1757        }
1758    }
1759
1760    /// The live receipt of `commit_key`: `None` when there is none or it is
1761    /// past the idempotency window (a retry then executes as a new commit).
1762    fn live_receipt(&self, commit_key: Uuid) -> Result<Option<receipt::Receipt>, StorageError> {
1763        let Some(raw) = self.try_get(&receipt::receipt_key(commit_key))? else {
1764            return Ok(None);
1765        };
1766        let receipt = receipt::decode(&raw)?;
1767        let window_ms = self
1768            .resource_config
1769            .idempotency_window_seconds
1770            .saturating_mul(1000);
1771        Ok((!receipt.expired(self.receipt_now(), window_ms)).then_some(receipt))
1772    }
1773
1774    /// Apply an op-set to the materialization without a WAL record. Used only
1775    /// for local idempotency metadata that is not part of the commit log.
1776    fn persist_ops_local(&self, ops: &[Op], commit_index: u64) -> Result<(), StorageError> {
1777        self.check_health()?;
1778        self.check_publisher()?;
1779        if let Some(backend) = self.primary_backend() {
1780            backend
1781                .apply(ops, commit_index)
1782                .map_err(StorageError::Durability)?;
1783        }
1784        Ok(())
1785    }
1786
1787    fn lookup_outcome(&self, commit_key: Uuid) -> Option<(OutcomeStatus, u64)> {
1788        self.lookup_outcome_checked(commit_key).ok().flatten()
1789    }
1790
1791    fn lookup_outcome_checked(
1792        &self,
1793        commit_key: Uuid,
1794    ) -> Result<Option<(OutcomeStatus, u64)>, StorageError> {
1795        self.check_health()?;
1796        Ok(self
1797            .live_receipt(commit_key)?
1798            .map(|receipt| (receipt.status, receipt.commit_index)))
1799    }
1800
1801    /// The stored response of a committed `commit_key` (its retry answer).
1802    fn committed_payload<P: serde::de::DeserializeOwned>(
1803        &self,
1804        commit_key: Uuid,
1805    ) -> Result<P, StorageError> {
1806        let payload = self
1807            .live_receipt(commit_key)?
1808            .and_then(|receipt| receipt.payload)
1809            .ok_or(StorageError::OutcomePayload)?;
1810        serde_json::from_slice(&payload).map_err(|_| StorageError::OutcomePayload)
1811    }
1812
1813    /// Rebuilds state by replaying the full serialized command log through
1814    /// the registered deterministic expander.
1815    ///
1816    /// # Errors
1817    /// Returns [`StorageError::CorruptLog`] for malformed input or missing
1818    /// expansion support, and [`StorageError::Builder`] when deterministic
1819    /// expansion rejects an entry. No replayed state is published on decode or
1820    /// expansion failure.
1821    ///
1822    /// # Panics
1823    /// Panics only if an internal lock is poisoned by a previous panic.
1824    pub fn try_replay(&self, log: &[Vec<u8>]) -> Result<(), StorageError> {
1825        self.check_health()?;
1826        // A replay input is a committed command log, so silently dropping a
1827        // malformed entry would renumber every later commit and produce a
1828        // state that looks valid while diverging from the durable history.
1829        // Recovery callers that intentionally trim a torn tail must do so
1830        // before invoking replay (as the WAL reader does).
1831        let entries: Vec<CommitBatch> = log
1832            .iter()
1833            .map(|raw| {
1834                rushdb_types::command_codec::decode(raw).map_err(|_| StorageError::CorruptLog)
1835            })
1836            .collect::<Result<_, _>>()?;
1837        let expander = self.health.guard(self.expander.read())?.clone();
1838        let mut prepared = Vec::with_capacity(entries.len());
1839        // Expansion of a later command may legitimately depend on canonical
1840        // state produced by an earlier command (for example, a text
1841        // watermark refers to a profile created in the preceding commit).
1842        // Build a private shadow map while preparing the complete replay so
1843        // those dependencies are visible without publishing partial state.
1844        let mut shadow = self.health.guard(self.data.read())?.clone();
1845
1846        for (i, batch) in entries.iter().enumerate() {
1847            let ci = i as u64 + 1;
1848            let Some(expand) = expander.as_ref() else {
1849                return Err(StorageError::CorruptLog);
1850            };
1851            let ops;
1852            {
1853                // Full command replay still builds the reference state, so
1854                // the base is always the live shadow map, never native.
1855                let mut txn = Txn {
1856                    base: TxnBase::Live(&shadow),
1857                    buffer: BTreeMap::new(),
1858                    purge_keys: BTreeSet::default(),
1859                    set_keys: BTreeSet::default(),
1860                    deps: None,
1861                };
1862                expand(ci, batch, &mut txn).map_err(StorageError::Builder)?;
1863                self.put_receipt(
1864                    &mut txn,
1865                    batch.commit_key,
1866                    OutcomeStatus::Committed,
1867                    ci,
1868                    None,
1869                );
1870                txn.set(LAST_APPLIED_KEY.to_vec(), wal::encode_last_applied(0, ci));
1871                ops = txn.drain();
1872            }
1873            // Command replay expands against a base-only shadow; fold the
1874            // derived rows in too, so an expander that reads derived counters
1875            // (DeleteFamily) sees what a live expansion would.
1876            let derived =
1877                Self::derive_ops(self.deriver().as_ref(), ci, &ops, &derive::MapRead(&shadow))?;
1878            for op in derived.as_deref().unwrap_or(&ops) {
1879                match op {
1880                    Op::Put(key, value) | Op::Set(key, value) => {
1881                        shadow.insert(key.clone(), value.clone());
1882                    }
1883                    Op::Del(key) | Op::Purge(key) => {
1884                        shadow.remove(key);
1885                    }
1886                }
1887            }
1888            prepared.push((ci, ops, rushdb_types::command_codec::encode(batch)));
1889        }
1890        for (ci, ops, command_payload) in prepared {
1891            // Apply through the backend: one write path for memory and
1892            // durable replay; `persist_ops` derives the same derived rows the
1893            // live publisher would, never shipped over the wire.
1894            self.persist_ops(&ops, ci, Some(&command_payload))?;
1895            self.health.guard(self.conflicts.lock())?.record(ci, &ops);
1896        }
1897        {
1898            let applied = entries.len() as u64;
1899            self.next_commit_index.store(applied + 1, Ordering::SeqCst);
1900            self.published.store(applied, Ordering::SeqCst);
1901            self.last_commit_ms.store(wal::now_ms(), Ordering::Relaxed);
1902            self.persist_ops(
1903                &[Op::Set(
1904                    LAST_APPLIED_KEY.to_vec(),
1905                    wal::encode_last_applied(0, applied),
1906                )],
1907                applied,
1908                None,
1909            )?;
1910        }
1911        Ok(())
1912    }
1913
1914    /// Apply a command batch already committed by `OpenRaft`. This bypasses
1915    /// admission-time planning but uses exactly the same deterministic
1916    /// expander and durable publication path as a local commit.
1917    ///
1918    /// # Errors
1919    /// Returns [`StorageError`] if the publisher has failed, the batch has a
1920    /// terminal aborted outcome, or expansion/publication fails.
1921    pub fn apply_replicated_batch(&self, batch: &CommitBatch) -> Result<u64, StorageError> {
1922        self.check_health()?;
1923        self.apply_replicated_batch_with_payload(batch, None)
1924    }
1925
1926    /// Apply a replicated batch and durably store its serialized payload with
1927    /// the outcome so idempotent retries on the leader reproduce the original
1928    /// caller response.
1929    ///
1930    /// # Errors
1931    /// Returns [`StorageError`] if the publisher has failed, no expander is
1932    /// installed, the batch has a terminal aborted outcome, or publication
1933    /// fails.
1934    ///
1935    /// # Panics
1936    /// Panics only if `batch` fails to serialize (never, for a well-formed
1937    /// `CommitBatch`). Lock poisoning fences the store until reopen.
1938    pub fn apply_replicated_batch_with_payload(
1939        &self,
1940        batch: &CommitBatch,
1941        payload: Option<&[u8]>,
1942    ) -> Result<u64, StorageError> {
1943        self.check_health()?;
1944        let _admission = self.acquire_admission()?;
1945        self.check_publisher()?;
1946        if let Some((OutcomeStatus::Committed, commit_index)) =
1947            self.lookup_outcome_checked(batch.commit_key)?
1948        {
1949            return Ok(commit_index);
1950        }
1951
1952        if matches!(
1953            self.try_outcome_for(batch.commit_key)?,
1954            Some(OutcomeKind::Aborted)
1955        ) {
1956            return Err(StorageError::Builder(
1957                "commit key has a terminal aborted outcome".into(),
1958            ));
1959        }
1960        let commit_index = self.next_commit_index.load(Ordering::SeqCst);
1961        let ops = {
1962            let guard = self.health.guard(self.data.read())?;
1963            let native = self.native_transaction_view()?;
1964            let base = TxnBase::resolve(None, None, native, Some(&guard));
1965            let mut txn = Txn {
1966                base,
1967                buffer: BTreeMap::new(),
1968                purge_keys: BTreeSet::default(),
1969                set_keys: BTreeSet::default(),
1970                deps: None,
1971            };
1972            let expander = self.health.guard(self.expander.read())?.clone();
1973            let Some(expand) = expander.as_ref() else {
1974                return Err(StorageError::CorruptLog);
1975            };
1976            expand(commit_index, batch, &mut txn).map_err(StorageError::Builder)?;
1977            self.put_receipt(
1978                &mut txn,
1979                batch.commit_key,
1980                OutcomeStatus::Committed,
1981                commit_index,
1982                payload,
1983            );
1984            txn.set(
1985                LAST_APPLIED_KEY.to_vec(),
1986                wal::encode_last_applied(0, commit_index),
1987            );
1988            txn.drain()
1989        };
1990        // Large transactions: the same ceiling `commit_sharded`
1991        // enforces before its own CAS reservation (see `commit.rs`) applies
1992        // here too, before `next_commit_index` advances — this path has its
1993        // own, separate reservation (no CAS loop; a replicated batch's index
1994        // is assigned directly from the leader's already-ordered stream).
1995        // Operationally this means a follower configured with a *smaller*
1996        // ceiling than the leader will stall (loudly, retried forever by
1997        // `replication.rs`'s follower loop) on a commit the leader already
1998        // accepted, rather than silently diverging or truncating it —
1999        // deliberately: this is a config-mismatch to fix, not a case to
2000        // paper over. Chaining itself doesn't need this check to write a
2001        // large commit correctly; it's policy consistency, not correctness.
2002        let command_payload = rushdb_types::command_codec::encode(batch);
2003        let expanded_bytes = wal::op_set_encoded_len(&ops).saturating_add(command_payload.len());
2004        if expanded_bytes > self.resource_config.max_expanded_commit_bytes {
2005            return Err(StorageError::ResourceExhausted(format!(
2006                "expanded mutation batch exceeds {} bytes (got {expanded_bytes})",
2007                self.resource_config.max_expanded_commit_bytes
2008            )));
2009        }
2010        self.next_commit_index
2011            .store(commit_index + 1, Ordering::SeqCst);
2012        let shard =
2013            resources::physical_shard_for(Some(&batch.tenant), self.resource_config.shard_count);
2014        self.enqueue_and_publish(commit_index, shard, ops, command_payload)?;
2015        Ok(commit_index)
2016    }
2017}