Skip to main content

reddb_server/storage/unified/store/
commit.rs

1use super::*;
2use crate::api::DurabilityMode;
3use crate::storage::wal::{WalReader, WalRecord, WalWriter};
4use reddb_engine::storage::resident_file::EMBEDDED_WAL_HEADROOM_LIMIT;
5use std::cell::RefCell;
6use std::io;
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
9use std::sync::{Arc, Condvar, Mutex};
10
11#[path = "checkpoint_undo.rs"]
12mod checkpoint_undo;
13
14fn validate_incomplete_wal_tail(
15    records: &mut crate::storage::wal::reader::WalIterator,
16    ownership_journal: &[u8],
17) -> io::Result<()> {
18    if ownership_journal.is_empty() {
19        return Ok(());
20    }
21    // A complete Finish closes the pager's obligations. A later torn SQL
22    // batch has no replayable actions and cannot contain a physical intent.
23    if reddb_file::page_ownership_journal::pending_epoch(ownership_journal)?.is_none()
24        && records.incomplete_frame_is_commit_batch()?
25    {
26        return Ok(());
27    }
28    Err(io::Error::new(
29        io::ErrorKind::InvalidData,
30        "incomplete WAL prevents ownership recovery",
31    ))
32}
33
34struct NativeReplayTarget<'a> {
35    store: &'a UnifiedStore,
36    update_btrees: bool,
37}
38
39impl reddb_engine::storage::store_wal::StoreReplayTarget for NativeReplayTarget<'_> {
40    fn set_aux_metadata(&self, bytes: &[u8]) -> Result<(), StoreError> {
41        let bytes = reddb_engine::catalog::codec::canonicalize_collection_contract_blob(bytes)
42            .map_err(|err| StoreError::Serialization(err.to_string()))?;
43        self.store.resident.set_aux_metadata(bytes);
44        Ok(())
45    }
46    fn has_collection(&self, name: &str) -> bool {
47        self.store.get_collection(name).is_some()
48    }
49    fn create_collection(&self, name: &str) -> Result<(), StoreError> {
50        self.store.create_collection_in_memory(name)
51    }
52    fn drop_collection(&self, name: &str) -> Result<(), StoreError> {
53        self.store.drop_collection_in_memory(name)
54    }
55    fn upsert(&self, collection: &str, record: &[u8]) -> Result<(), StoreError> {
56        self.store
57            .apply_replayed_upsert(collection, record, self.update_btrees)
58    }
59    fn delete(&self, collection: &str, id: EntityId) -> Result<(), StoreError> {
60        self.store
61            .apply_replayed_delete(collection, id, self.update_btrees)
62    }
63    fn refresh(&self, collection: &str, records: &[Vec<u8>]) -> Result<(), StoreError> {
64        self.store
65            .apply_replayed_refresh_collection(collection, records, self.update_btrees)
66    }
67}
68
69/// Adaptive group-commit window applied when the configured
70/// `GroupCommitOptions::window_ms` is 0 (the historical default).
71///
72/// Sub-millisecond so individual single-writer commits don't see a
73/// visible latency penalty (a 200 µs floor sits below typical NVMe
74/// fsync latency of 50–150 µs by ~one fsync), while still giving a
75/// pipelined writer a chance to drop a second statement into the
76/// same drain cycle. A lone synchronous `insert_one` still pays one
77/// fsync per row in the worst case, but two back-to-back inserts on
78/// the same connection now coalesce into one drain. See P1 in
79/// `docs/perf/insert_sequential-2026-05-05.md`.
80///
81/// Override via `REDDB_GROUP_COMMIT_WINDOW_US` (microseconds). Set
82/// to `0` to disable the floor entirely (legacy behaviour). Set
83/// `REDDB_GROUP_COMMIT_WINDOW_MS` to any non-zero value to bypass
84/// this floor — explicit ms config wins.
85const DEFAULT_ADAPTIVE_WINDOW_US: u64 = 200;
86
87/// Shorthand — `Arc<parking_lot::Mutex<WalWriter>>` avoids poisoning
88/// (one writer panicking mid-append used to taint every subsequent
89/// lock acquisition) and shaves a few syscalls off the fast path.
90/// The group-commit coordinator + writer threads all acquire this
91/// mutex in the hot insert path, so the unpoison/fast-park win
92/// compounds under 16-way concurrency.
93type WalMutex = parking_lot::Mutex<WalWriter>;
94
95/// Shorthand for the group-commit coordinator's state pair. Same
96/// non-poisoning + lighter-park motivation as `WalMutex`; writer
97/// threads `wait` on this condvar until the coordinator publishes a
98/// new `durable_lsn`, so the park cost shows up on every
99/// WalDurableGrouped transaction.
100type CommitStateMutex = parking_lot::Mutex<CommitState>;
101type CommitStateCondvar = parking_lot::Condvar;
102use std::time::{Duration, Instant};
103
104static NEXT_STORE_TX_ID: AtomicU64 = AtomicU64::new(1);
105
106pub(crate) use reddb_engine::storage::store_wal::StoreWalAction;
107
108#[derive(Debug, Default)]
109pub(crate) struct DeferredStoreWalActions {
110    pub(super) actions: Vec<StoreWalAction>,
111}
112
113pub(crate) struct StoreWalCaptureGuard<'a> {
114    active: bool,
115    session: Option<&'a crate::storage::embedded::EmbeddedCommitSession>,
116}
117
118impl<'a> StoreWalCaptureGuard<'a> {
119    pub(crate) fn begin(
120        session: Option<&'a crate::storage::embedded::EmbeddedCommitSession>,
121    ) -> Self {
122        assert!(
123            !deferred_store_wal_capture_active(),
124            "store WAL captures cannot nest"
125        );
126        begin_deferred_store_wal_capture();
127        Self {
128            active: true,
129            session,
130        }
131    }
132
133    pub(crate) fn finish(mut self) -> DeferredStoreWalActions {
134        let actions = take_deferred_store_wal_capture();
135        self.active = false;
136        actions
137    }
138}
139
140impl Drop for StoreWalCaptureGuard<'_> {
141    fn drop(&mut self) {
142        if self.active {
143            if let Some(session) = self.session {
144                session.fence_interrupted_write();
145            }
146            let _ = take_deferred_store_wal_capture();
147        }
148    }
149}
150
151impl DeferredStoreWalActions {
152    pub(crate) fn push(&mut self, action: StoreWalAction) {
153        self.actions.push(action);
154    }
155
156    pub(crate) fn is_empty(&self) -> bool {
157        self.actions.is_empty()
158    }
159
160    pub(crate) fn extend(&mut self, other: Self) {
161        self.actions.extend(other.actions);
162    }
163}
164
165thread_local! {
166    static DEFERRED_STORE_WAL_ACTIONS: RefCell<Option<Vec<StoreWalAction>>> =
167        const { RefCell::new(None) };
168}
169
170fn begin_deferred_store_wal_capture() {
171    DEFERRED_STORE_WAL_ACTIONS.with(|cell| {
172        let mut guard = cell.borrow_mut();
173        debug_assert!(guard.is_none());
174        *guard = Some(Vec::new());
175    });
176}
177
178fn capture_deferred_store_wal_actions(actions: Vec<StoreWalAction>) -> bool {
179    DEFERRED_STORE_WAL_ACTIONS.with(|cell| {
180        let mut guard = cell.borrow_mut();
181        if let Some(pending) = guard.as_mut() {
182            pending.extend(actions);
183            true
184        } else {
185            false
186        }
187    })
188}
189
190fn deferred_store_wal_capture_active() -> bool {
191    DEFERRED_STORE_WAL_ACTIONS.with(|cell| cell.borrow().is_some())
192}
193
194fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
195    DEFERRED_STORE_WAL_ACTIONS.with(|cell| DeferredStoreWalActions {
196        actions: cell.borrow_mut().take().unwrap_or_default(),
197    })
198}
199
200#[derive(Debug)]
201struct CommitState {
202    durable_lsn: u64,
203    pending_target_lsn: u64,
204    pending_statements: usize,
205    pending_wal_bytes: u64,
206    first_pending_at: Option<Instant>,
207    shutdown: bool,
208    last_error: Option<String>,
209}
210
211impl CommitState {
212    fn new(initial_durable_lsn: u64) -> Self {
213        Self {
214            durable_lsn: initial_durable_lsn,
215            pending_target_lsn: initial_durable_lsn,
216            pending_statements: 0,
217            pending_wal_bytes: 0,
218            first_pending_at: None,
219            shutdown: false,
220            last_error: None,
221        }
222    }
223}
224
225/// Lock-free append queue sitting in front of `WalWriter`.
226///
227/// Writers atomically reserve a byte range via `next_lsn.fetch_add`
228/// and push their encoded bytes into a parking_lot-guarded vector.
229/// The group-commit coordinator is the sole drainer: it sorts the
230/// pending entries by LSN (so the file bytes land at the offsets
231/// each writer reserved) and hands them to `WalWriter::append_bytes`.
232///
233/// This replaces the old `wal.lock() ... append ... append ... drop`
234/// hot path where 16 concurrent writers serialised on the WAL
235/// mutex for ~13µs each. Hold time on the queue's parking_lot
236/// mutex is ~200ns (just a Vec::push) — 65× shorter, so the mutex
237/// convoy on concurrent inserts disappears.
238pub(crate) struct WalAppendQueue {
239    /// Keep reserved offsets valid until their callers observe durability.
240    /// Reset also excludes an old flusher publishing state into the new WAL.
241    epoch: parking_lot::RwLock<()>,
242    /// Tuple of (monotonically-increasing LSN, pending-bytes vec)
243    /// protected by one mutex. Keeping the LSN reservation AND the
244    /// push under the same lock guarantees that every queue entry
245    /// is visible the moment its LSN is assigned — no gap between
246    /// `fetch_add` and `push` for the leader to spin on.
247    ///
248    /// Earlier versions reserved LSN with an `AtomicU64::fetch_add`
249    /// outside the lock; the leader drain observed reordered
250    /// `(lsn, bytes)` tuples whose pushes happened in a different
251    /// order than their fetch_add, creating "holes" in the LSN
252    /// sequence that the drain loop interpreted as "wait for the
253    /// missing enqueuer" — under tokio scheduling pressure the
254    /// missing enqueuer was preempted indefinitely and the
255    /// drain loop busy-waited forever (WAL stayed at 8 bytes).
256    pending: parking_lot::Mutex<WalQueueState>,
257    /// Bytes of encoded records sitting in `pending.entries` (ADR 0073 §2,
258    /// the `wal_buffers` pool). A relaxed atomic rather than a field inside
259    /// `WalQueueState` so a reader sampling the accounting never contends
260    /// with an enqueuer for the queue mutex.
261    queued_bytes: AtomicU64,
262}
263
264struct WalQueueState {
265    next_lsn: u64,
266    entries: Vec<(u64, Vec<u8>)>,
267}
268
269impl WalAppendQueue {
270    fn new(initial_lsn: u64) -> Self {
271        Self {
272            epoch: parking_lot::RwLock::new(()),
273            pending: parking_lot::Mutex::new(WalQueueState {
274                next_lsn: initial_lsn,
275                entries: Vec::with_capacity(64),
276            }),
277            queued_bytes: AtomicU64::new(0),
278        }
279    }
280
281    /// Reserve an LSN range of `bytes.len()` bytes and push onto the
282    /// queue. Returns the commit LSN (end of reserved range), which
283    /// the caller passes to `wait_until_durable`. LSN assignment and
284    /// push happen under the same mutex — no gap for the drain loop
285    /// to busy-spin on.
286    fn enqueue(&self, bytes: Vec<u8>) -> u64 {
287        let len = bytes.len() as u64;
288        let mut state = self.pending.lock();
289        let start_lsn = state.next_lsn;
290        state.next_lsn = start_lsn + len;
291        state.entries.push((start_lsn, bytes));
292        self.queued_bytes.fetch_add(len, Ordering::Relaxed);
293        start_lsn + len
294    }
295
296    /// Drain all queued entries in LSN order. Caller holds the WAL
297    /// file mutex while writing the drained bytes so the on-disk
298    /// layout matches the reserved LSN offsets.
299    fn drain_sorted(&self) -> Vec<(u64, Vec<u8>)> {
300        let mut state = self.pending.lock();
301        let mut v = std::mem::take(&mut state.entries);
302        let drained: u64 = v.iter().map(|(_, bytes)| bytes.len() as u64).sum();
303        drop(state);
304        // Saturating: the drain is the only consumer, so `queued_bytes` can
305        // never sit below what this call took, but an accounting counter that
306        // wraps would poison `red.stats` far past the bug that caused it.
307        let _ = self
308            .queued_bytes
309            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |queued| {
310                Some(queued.saturating_sub(drained))
311            });
312        v.sort_by_key(|(lsn, _)| *lsn);
313        v
314    }
315
316    /// Whether any entry is queued. Leader uses this to decide
317    /// whether to spin once more or go back to the condvar.
318    fn has_pending(&self) -> bool {
319        !self.pending.lock().entries.is_empty()
320    }
321
322    /// Encoded record bytes currently buffered in memory.
323    fn queued_bytes(&self) -> u64 {
324        self.queued_bytes.load(Ordering::Relaxed)
325    }
326
327    /// Reset the LSN cursor and discard any queued entries. Used
328    /// after `wal.truncate()` — the wal-side byte counter goes back
329    /// to the header size, so the queue (which tracks LSNs in the
330    /// same byte space) must follow or every subsequent enqueue
331    /// returns a target the drain loop can never reach.
332    fn reset(&self, next_lsn: u64) {
333        let mut state = self.pending.lock();
334        state.next_lsn = next_lsn;
335        state.entries.clear();
336        drop(state);
337        self.queued_bytes.store(0, Ordering::Relaxed);
338    }
339}
340
341/// An end-of-frame position captured while the checkpoint owns publication.
342pub(super) struct CheckpointWalBoundary {
343    generation: u64,
344    end: u64,
345    ownership_bytes: u64,
346}
347
348pub(crate) struct StoreCommitCoordinator {
349    mode: DurabilityMode,
350    config: crate::api::GroupCommitOptions,
351    wal_path: PathBuf,
352    wal: Arc<WalMutex>,
353    /// Lock-free front door for writers. Populated alongside
354    /// `WalDurableGrouped` / `Async` modes so concurrent inserts
355    /// never contend on `wal` for the append step. Strict mode
356    /// bypasses the queue and calls `WalWriter::append` directly
357    /// to preserve the one-fsync-per-commit semantic.
358    queue: Arc<WalAppendQueue>,
359    state: Arc<(CommitStateMutex, CommitStateCondvar)>,
360    /// Number of `wal.sync()` calls issued by the group-commit
361    /// drain loop. Used by tests to observe coalescing — a burst
362    /// of N concurrent commits should bump this by far less than N
363    /// when the adaptive window is doing its job. Strict-mode
364    /// commits go through `force_sync` which also bumps this.
365    fsync_count: Arc<AtomicU64>,
366    wal_generation: AtomicU64,
367    /// WAL generation and end LSN of reservations and page images queued
368    /// without waiting for durability. The pager flushes them before any page
369    /// or allocator state reaches the file.
370    deferred_ownership: parking_lot::Mutex<Option<(u64, u64)>>,
371    /// Bytes admitted by the ownership recorder. Lets a quiet checkpoint
372    /// truncate directly even though it appended its own page journal.
373    ownership_bytes: AtomicU64,
374    /// Includes recovered epochs that were never published in the catalog.
375    ownership_last_epoch: AtomicU64,
376    // 0: existing WAL not scanned; 1: no ownership records; 2: protected.
377    ownership_wal_state: AtomicU8,
378    // 0: existing WAL not scanned; 1: no runtime records; 2: retained.
379    runtime_wal_state: AtomicU8,
380}
381
382/// Connects a fenced pager ownership epoch to the store's durable WAL.
383#[allow(dead_code)] // Installed once recovery and format fencing are active.
384struct StoreOwnershipRecorder {
385    coordinator: Arc<StoreCommitCoordinator>,
386    epoch: u64,
387    images: parking_lot::Mutex<CheckpointPageImages>,
388    /// The manifest reference of this epoch's generation has been, or is
389    /// being, written: recovery now acts on the epoch's retirements.
390    published: std::sync::atomic::AtomicBool,
391}
392
393#[derive(Default)]
394struct CheckpointPageImages {
395    reserved: roaring::RoaringBitmap,
396    captured: roaring::RoaringBitmap,
397}
398
399impl StoreOwnershipRecorder {
400    #[allow(dead_code)]
401    fn begin(coordinator: Arc<StoreCommitCoordinator>, epoch: u64) -> io::Result<Self> {
402        coordinator.append_durable_page_ownership(
403            reddb_file::page_ownership_journal::PageOwnershipRecord::Begin { epoch },
404        )?;
405        Ok(Self {
406            coordinator,
407            epoch,
408            images: parking_lot::Mutex::new(CheckpointPageImages::default()),
409            published: std::sync::atomic::AtomicBool::new(false),
410        })
411    }
412
413    fn append_pages(
414        &self,
415        pages: &[u32],
416        make_record: impl Fn(u64, u32) -> reddb_file::page_ownership_journal::PageOwnershipRecord,
417    ) -> io::Result<()> {
418        for chunk in pages.chunks(256) {
419            let records: Vec<_> = chunk
420                .iter()
421                .map(|&id| make_record(self.epoch, id))
422                .collect();
423            self.coordinator
424                .append_durable_page_ownership_batch(&records)?;
425        }
426        Ok(())
427    }
428}
429
430impl crate::storage::engine::pager::PageOwnershipRecorder for StoreOwnershipRecorder {
431    fn needs_page_image(&self, page_id: u32) -> io::Result<bool> {
432        // The manifest is the commit boundary, never an undo target. Its
433        // private overflow replacement is already covered by reservations.
434        if page_id < reddb_engine::storage::pager_io::FIRST_ALLOCATABLE_PAGE {
435            return Ok(false);
436        }
437        let images = self.images.lock();
438        Ok(!images.reserved.contains(page_id) && !images.captured.contains(page_id))
439    }
440
441    fn capture_page_image(&self, page: &crate::storage::engine::Page) -> io::Result<()> {
442        let mut images = self.images.lock();
443        let page_id = page.page_id();
444        if images.reserved.contains(page_id) || images.captured.contains(page_id) {
445            return Ok(());
446        }
447        let mut bytes = Vec::new();
448        reddb_file::encode_main_wal_record_frame_into(
449            reddb_file::MainWalRecordFrameRef::FullPageImage {
450                tx_id: 0,
451                page_id,
452                ckpt_epoch: self.epoch,
453                data: page.as_bytes(),
454            },
455            crate::storage::wal::record::WAL_DEFAULT_TERM,
456            &mut bytes,
457        )?;
458        // The old image only has to be durable before the page is overwritten
459        // in the file, and `flush_page_ownership` precedes every such write.
460        // Waiting here cost one sync per page a checkpoint touched.
461        self.coordinator.append_deferred_ownership_bytes(bytes)?;
462        images.captured.insert(page_id);
463        Ok(())
464    }
465
466    fn reserve_pages(&self, start: u32, count: u32) -> io::Result<()> {
467        use reddb_file::page_ownership_journal::PageOwnershipRecord;
468        let end = start.checked_add(count).ok_or_else(|| {
469            io::Error::new(io::ErrorKind::InvalidInput, "ownership range overflow")
470        })?;
471        let mut next = start;
472        while next < end {
473            let chunk_end = next.saturating_add(256).min(end);
474            let records: Vec<_> = (next..chunk_end)
475                .map(|page_id| PageOwnershipRecord::Reserve {
476                    epoch: self.epoch,
477                    page_id,
478                })
479                .collect();
480            // Queued, not awaited: a tree build reserves a page per leaf and
481            // waiting for each one made the reservation the cost of the build.
482            // `flush_page_ownership` is the durability point.
483            self.coordinator
484                .append_deferred_page_ownership_batch(&records)?;
485            self.images.lock().reserved.insert_range(next..chunk_end);
486            next = chunk_end;
487        }
488        Ok(())
489    }
490
491    fn flush_page_ownership(&self) -> io::Result<()> {
492        self.coordinator.flush_deferred_page_ownership()
493    }
494
495    fn detach_free_pages(&self, pages: &[u32]) -> io::Result<()> {
496        self.append_pages(pages, |epoch, page_id| {
497            reddb_file::page_ownership_journal::PageOwnershipRecord::DetachFree { epoch, page_id }
498        })
499    }
500
501    fn retire_pages(&self, pages: &[u32]) -> io::Result<()> {
502        self.append_pages(pages, |epoch, page_id| {
503            reddb_file::page_ownership_journal::PageOwnershipRecord::Retire { epoch, page_id }
504        })
505    }
506
507    fn retire_deferred_page(&self, page_id: u32) -> io::Result<()> {
508        if self.published.load(Ordering::Acquire) {
509            // A crash from here on finds the generation published and frees
510            // exactly the retirements it can read.
511            return self.retire_pages(&[page_id]);
512        }
513        // An unpublished generation's retirements are not acted on, and the
514        // manifest is not written before `flush_page_ownership`. A checkpoint
515        // frees a page for every node it replaces; waiting for each record
516        // was 284 of the 407 syncs of one that changed 20 small tables.
517        self.coordinator.append_deferred_page_ownership_batch(&[
518            reddb_file::page_ownership_journal::PageOwnershipRecord::Retire {
519                epoch: self.epoch,
520                page_id,
521            },
522        ])
523    }
524
525    fn generation_published(&self) {
526        self.published.store(true, Ordering::Release);
527    }
528
529    fn unpublished_reservation(&self, page_id: u32) -> bool {
530        !self.published.load(Ordering::Acquire) && self.images.lock().reserved.contains(page_id)
531    }
532}
533
534impl StoreCommitCoordinator {
535    pub(crate) fn open(
536        wal_path: impl Into<PathBuf>,
537        mode: DurabilityMode,
538        config: crate::api::GroupCommitOptions,
539    ) -> io::Result<Self> {
540        let wal_path = wal_path.into();
541        let wal = WalWriter::open(&wal_path)?;
542        let initial_durable_lsn = wal.durable_lsn();
543        let initial_current_lsn = wal.current_lsn();
544        let wal = Arc::new(WalMutex::new(wal));
545        let queue = Arc::new(WalAppendQueue::new(initial_current_lsn));
546        let state = Arc::new((
547            CommitStateMutex::new(CommitState::new(initial_durable_lsn)),
548            CommitStateCondvar::new(),
549        ));
550        let fsync_count = Arc::new(AtomicU64::new(0));
551
552        if matches!(
553            mode,
554            DurabilityMode::WalDurableGrouped | DurabilityMode::Async
555        ) {
556            let wal_bg = Arc::clone(&wal);
557            let queue_bg = Arc::clone(&queue);
558            let state_bg = Arc::clone(&state);
559            let fsync_bg = Arc::clone(&fsync_count);
560            // P1: adaptive group-commit window. Historical default is
561            // `window_ms = 0` ("no wait"), which under single-writer
562            // OLTP means one fsync per autocommit row — the throughput
563            // floor. When window_ms is 0 we fall back to a small
564            // microsecond floor (`DEFAULT_ADAPTIVE_WINDOW_US`, override
565            // via `REDDB_GROUP_COMMIT_WINDOW_US`) so a pipelined writer
566            // can drop a second statement into the same drain cycle.
567            // Explicit non-zero `window_ms` config takes precedence.
568            //
569            // The loop already short-circuits on
570            // `pending_statements >= max_statements` /
571            // `pending_wal_bytes >= max_wal_bytes`, so the window only
572            // delays the leader when the queue is otherwise empty —
573            // exactly the case we want to coalesce.
574            let window = Self::resolve_window(&config);
575            let max_statements = config.max_statements.max(1);
576            let max_wal_bytes = config.max_wal_bytes.max(1);
577            std::thread::spawn(move || {
578                Self::run_group_commit_loop(
579                    wal_bg,
580                    queue_bg,
581                    state_bg,
582                    fsync_bg,
583                    window,
584                    max_statements,
585                    max_wal_bytes,
586                );
587            });
588        }
589
590        Ok(Self {
591            mode,
592            config,
593            wal_path,
594            wal,
595            queue,
596            state,
597            fsync_count,
598            wal_generation: AtomicU64::new(0),
599            deferred_ownership: parking_lot::Mutex::new(None),
600            ownership_bytes: AtomicU64::new(0),
601            ownership_last_epoch: AtomicU64::new(0),
602            ownership_wal_state: AtomicU8::new(0),
603            runtime_wal_state: AtomicU8::new(0),
604        })
605    }
606
607    /// Resolve the effective group-commit window from the configured
608    /// options + the `REDDB_GROUP_COMMIT_WINDOW_US` env override.
609    ///
610    /// Precedence (highest first):
611    ///   1. `REDDB_GROUP_COMMIT_WINDOW_US=N` — N µs (0 disables).
612    ///   2. `config.window_ms != 0` — explicit ms config wins.
613    ///   3. `DEFAULT_ADAPTIVE_WINDOW_US` — adaptive floor for the
614    ///      historical zero-default. Set the env var to 0 to opt out.
615    pub(super) fn resolve_window(config: &crate::api::GroupCommitOptions) -> Duration {
616        if let Ok(raw) = std::env::var("REDDB_GROUP_COMMIT_WINDOW_US") {
617            if let Ok(parsed) = raw.parse::<u64>() {
618                return Duration::from_micros(parsed);
619            }
620        }
621        if config.window_ms != 0 {
622            return Duration::from_millis(config.window_ms);
623        }
624        Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
625    }
626
627    /// Total `wal.sync()` calls issued since this coordinator opened.
628    /// Public for tests that want to observe fsync coalescing under
629    /// concurrent autocommits.
630    #[cfg(test)]
631    pub(crate) fn fsync_count(&self) -> u64 {
632        self.fsync_count.load(Ordering::Relaxed)
633    }
634
635    /// WAL buffer memory held right now: encoded records waiting in the
636    /// group-commit queue plus the writer's fixed append buffer, which exists
637    /// for the coordinator's whole life (ADR 0073 §2, the `wal_buffers` pool).
638    pub(crate) fn buffered_bytes(&self) -> u64 {
639        self.queue.queued_bytes() + crate::storage::wal::WAL_BUFFER_BYTES as u64
640    }
641
642    pub(crate) fn append_actions(&self, actions: &[StoreWalAction]) -> io::Result<()> {
643        self.append_actions_impl(actions, false, false).map(|_| ())
644    }
645
646    pub(super) fn append_checkpoint_actions(
647        &self,
648        actions: &[StoreWalAction],
649    ) -> io::Result<super::checkpoint_wal::CheckpointWalBatch> {
650        self.append_actions_impl(actions, true, false)
651    }
652
653    /// A publication already gathered callers before taking the store fence.
654    /// Flush it without charging a second group-formation window.
655    pub(super) fn append_ready_actions(
656        &self,
657        actions: &[StoreWalAction],
658        retain: bool,
659    ) -> io::Result<super::checkpoint_wal::CheckpointWalBatch> {
660        self.append_actions_impl(actions, retain, true)
661    }
662
663    fn append_actions_impl(
664        &self,
665        actions: &[StoreWalAction],
666        retain: bool,
667        ready: bool,
668    ) -> io::Result<super::checkpoint_wal::CheckpointWalBatch> {
669        use super::checkpoint_wal::CheckpointWalBatch;
670        self.check_write_error()?;
671        if actions.is_empty() {
672            return Ok(CheckpointWalBatch::default());
673        }
674        let _epoch = self.queue.epoch.read();
675        let tx_id = NEXT_STORE_TX_ID.fetch_add(1, Ordering::SeqCst);
676        let encoded: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
677        let wal_bytes = encoded.iter().fold(0u64, |total, action| {
678            total.saturating_add(action.len() as u64)
679        });
680        let (blob, mut references) = if retain {
681            CheckpointWalBatch::encode(
682                tx_id,
683                &encoded,
684                self.wal_generation.load(Ordering::Acquire),
685            )?
686        } else {
687            (
688                WalRecord::TxCommitBatch {
689                    tx_id,
690                    actions: encoded,
691                }
692                .encode(),
693                CheckpointWalBatch::default(),
694            )
695        };
696        let start_lsn = if matches!(self.mode, DurabilityMode::Strict) {
697            let start = self.wal.lock().append_bytes(&blob)?;
698            self.sync_wal(Some(start + blob.len() as u64))?;
699            start
700        } else {
701            let length = blob.len() as u64;
702            let end = self.queue.enqueue(blob);
703            self.wait_until_durable_batch(end, wal_bytes, ready)?;
704            end.checked_sub(length).ok_or_else(|| {
705                io::Error::new(io::ErrorKind::InvalidData, "invalid WAL batch offset")
706            })?
707        };
708        references.relocate(start_lsn)?;
709        Ok(references)
710    }
711
712    /// Compare exact durable bytes in bounded chunks. A proof from an older
713    /// truncated WAL generation cannot prove a row in the current file.
714    pub(super) fn checkpoint_row_matches(
715        &self,
716        reference: super::checkpoint_wal::WalRowReference,
717        expected: &[u8],
718    ) -> io::Result<bool> {
719        if expected.len() != reference.length as usize {
720            return Ok(false);
721        }
722        let mut position = 0;
723        let mut matches = true;
724        let present = self.visit_checkpoint_row(reference, |chunk| {
725            matches &= chunk == &expected[position..position + chunk.len()];
726            position += chunk.len();
727        })?;
728        Ok(present && matches)
729    }
730
731    /// Materialize only one already-validated durable row for a projection batch.
732    pub(super) fn checkpoint_row_bytes(
733        &self,
734        reference: super::checkpoint_wal::WalRowReference,
735    ) -> io::Result<Vec<u8>> {
736        let mut bytes = Vec::new();
737        let present = self.visit_checkpoint_row(reference, |chunk| {
738            if bytes.is_empty() {
739                bytes.reserve_exact(reference.length as usize);
740            }
741            bytes.extend_from_slice(chunk);
742        })?;
743        if !present {
744            return Err(io::Error::new(
745                io::ErrorKind::InvalidData,
746                "checkpoint WAL reference changed during projection",
747            ));
748        }
749        Ok(bytes)
750    }
751
752    fn visit_checkpoint_row(
753        &self,
754        reference: super::checkpoint_wal::WalRowReference,
755        mut visit: impl FnMut(&[u8]),
756    ) -> io::Result<bool> {
757        use std::io::{Read, Seek, SeekFrom};
758        let _epoch = self.queue.epoch.read_recursive();
759        if reference.generation != self.wal_generation.load(Ordering::Acquire) {
760            return Ok(false);
761        }
762        let end = reference
763            .offset
764            .checked_add(u64::from(reference.length))
765            .ok_or_else(|| {
766                io::Error::new(io::ErrorKind::InvalidData, "WAL proof offset overflow")
767            })?;
768        let (state_lock, _) = &*self.state;
769        if end > state_lock.lock().durable_lsn {
770            return Ok(false);
771        }
772        let mut file = std::fs::File::open(&self.wal_path)?;
773        file.seek(SeekFrom::Start(reference.offset))?;
774        let mut buffer = [0u8; 16 * 1024];
775        let mut checksum = crc32fast::Hasher::new();
776        let mut remaining = reference.length as usize;
777        while remaining != 0 {
778            let length = remaining.min(buffer.len());
779            let chunk = &mut buffer[..length];
780            file.read_exact(chunk)?;
781            checksum.update(chunk);
782            visit(chunk);
783            remaining -= length;
784        }
785        if checksum.finalize() != reference.checksum {
786            return Err(io::Error::new(
787                io::ErrorKind::InvalidData,
788                "checkpoint WAL proof checksum mismatch",
789            ));
790        }
791        Ok(true)
792    }
793
794    /// Encode + enqueue a single, non-batched [`WalRecord`] (issue
795    /// #693). Honours the same Strict / Grouped / Async branching as
796    /// [`Self::append_actions`] so durability semantics are uniform
797    /// across record kinds.
798    pub(crate) fn append_single_record(&self, record: WalRecord) -> io::Result<()> {
799        self.check_write_error()?;
800        if matches!(
801            record,
802            WalRecord::PageOwnership { .. } | WalRecord::FullPageImage { .. }
803        ) {
804            return Err(io::Error::new(
805                io::ErrorKind::InvalidInput,
806                "page ownership requires a durable append",
807            ));
808        }
809        let _epoch = self.queue.epoch.read();
810        if matches!(
811            record,
812            WalRecord::ProbabilisticDelta { .. } | WalRecord::VectorInsert { .. }
813        ) {
814            self.runtime_wal_state.store(2, Ordering::Release);
815        }
816        let blob = record.encode();
817        let wal_bytes = blob.len() as u64;
818        if matches!(self.mode, DurabilityMode::Strict) {
819            let start = self.wal.lock().append_bytes(&blob)?;
820            self.sync_wal(Some(start + wal_bytes))?;
821            return Ok(());
822        }
823        let commit_lsn = self.queue.enqueue(blob);
824        self.wait_until_durable(commit_lsn, wal_bytes)?;
825        Ok(())
826    }
827
828    /// Ownership intents must reach stable storage before the pager consumes
829    /// or changes a page, even when user transactions use async durability.
830    #[allow(dead_code)] // Activated with the pager recovery and format fence.
831    pub(super) fn append_durable_page_ownership(
832        &self,
833        record: reddb_file::page_ownership_journal::PageOwnershipRecord,
834    ) -> io::Result<()> {
835        self.append_durable_page_ownership_batch(&[record])
836    }
837
838    /// Append a bounded set of ownership intents behind one durability fence.
839    #[allow(dead_code)] // Activated with the pager recovery and format fence.
840    pub(super) fn append_durable_page_ownership_batch(
841        &self,
842        records: &[reddb_file::page_ownership_journal::PageOwnershipRecord],
843    ) -> io::Result<()> {
844        if records.is_empty() {
845            return Ok(());
846        }
847        let mut bytes = Vec::new();
848        for &record in records {
849            // Validate before WalRecord::encode, which expects a valid frame.
850            reddb_file::page_ownership_journal::encode(record)?;
851            WalRecord::PageOwnership { record }.encode_into(&mut bytes);
852        }
853        for record in records {
854            self.ownership_last_epoch
855                .fetch_max(record.epoch(), Ordering::AcqRel);
856        }
857        self.append_durable_ownership_bytes(bytes)
858    }
859
860    /// Queue reservations behind the same ordered log without waiting for
861    /// them. Anything that is appended durably afterwards, and
862    /// `flush_deferred_page_ownership`, makes them durable first.
863    pub(super) fn append_deferred_page_ownership_batch(
864        &self,
865        records: &[reddb_file::page_ownership_journal::PageOwnershipRecord],
866    ) -> io::Result<()> {
867        if records.is_empty() {
868            return Ok(());
869        }
870        let mut bytes = Vec::new();
871        for &record in records {
872            reddb_file::page_ownership_journal::encode(record)?;
873            WalRecord::PageOwnership { record }.encode_into(&mut bytes);
874        }
875        for record in records {
876            self.ownership_last_epoch
877                .fetch_max(record.epoch(), Ordering::AcqRel);
878        }
879        self.append_deferred_ownership_bytes(bytes)
880    }
881
882    /// Queue ownership bytes, in log order, without waiting for them.
883    fn append_deferred_ownership_bytes(&self, bytes: Vec<u8>) -> io::Result<()> {
884        self.check_write_error()?;
885        let _epoch = self.queue.epoch.read();
886        self.ownership_wal_state.store(2, Ordering::Release);
887        let length = bytes.len() as u64;
888        let target = if matches!(self.mode, DurabilityMode::Strict) {
889            self.wal.lock().append_bytes(&bytes)? + length
890        } else {
891            let target = self.queue.enqueue(bytes);
892            let (state_lock, cond) = &*self.state;
893            let mut state = state_lock.lock();
894            state.pending_target_lsn = state.pending_target_lsn.max(target);
895            state.pending_statements = state.pending_statements.saturating_add(1);
896            state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(length);
897            state.first_pending_at.get_or_insert_with(Instant::now);
898            cond.notify_all();
899            target
900        };
901        self.ownership_bytes.fetch_add(length, Ordering::Relaxed);
902        let generation = self.wal_generation.load(Ordering::Acquire);
903        let mut deferred = self.deferred_ownership.lock();
904        *deferred = Some(match *deferred {
905            Some((queued, lsn)) if queued == generation => (generation, lsn.max(target)),
906            _ => (generation, target),
907        });
908        Ok(())
909    }
910
911    /// Make every queued reservation and page image durable. A WAL that was
912    /// reset since they were queued had already made them durable: an epoch is
913    /// finished, durably, before its log can be released.
914    pub(super) fn flush_deferred_page_ownership(&self) -> io::Result<()> {
915        let Some((generation, target)) = *self.deferred_ownership.lock() else {
916            return Ok(());
917        };
918        if generation == self.wal_generation.load(Ordering::Acquire) {
919            if matches!(self.mode, DurabilityMode::Strict) {
920                self.sync_wal(Some(target))?;
921            } else {
922                self.check_write_error()?;
923                let _epoch = self.queue.epoch.read_recursive();
924                let (state_lock, cond) = &*self.state;
925                let mut state = state_lock.lock();
926                while state.durable_lsn < target
927                    && generation == self.wal_generation.load(Ordering::Acquire)
928                {
929                    if let Some(error) = state.last_error.clone() {
930                        return Err(io::Error::other(error));
931                    }
932                    cond.wait(&mut state);
933                }
934            }
935        }
936        let mut deferred = self.deferred_ownership.lock();
937        if *deferred == Some((generation, target)) {
938            *deferred = None;
939        }
940        Ok(())
941    }
942
943    fn append_durable_ownership_bytes(&self, bytes: Vec<u8>) -> io::Result<()> {
944        self.check_write_error()?;
945        let _epoch = self.queue.epoch.read();
946        // Set before writing: a failed or uncertain append must never allow
947        // checkpoint truncation to discard the ownership journal.
948        self.ownership_wal_state.store(2, Ordering::Release);
949        let length = bytes.len() as u64;
950        if matches!(self.mode, DurabilityMode::Strict) {
951            let start = self.wal.lock().append_bytes(&bytes)?;
952            self.ownership_bytes.fetch_add(length, Ordering::Relaxed);
953            return self.sync_wal(Some(start + length));
954        }
955
956        let target = self.queue.enqueue(bytes);
957        self.ownership_bytes.fetch_add(length, Ordering::Relaxed);
958        let (state_lock, cond) = &*self.state;
959        let mut state = state_lock.lock();
960        state.pending_target_lsn = state.pending_target_lsn.max(target);
961        state.pending_statements = state.pending_statements.saturating_add(1);
962        state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(length);
963        state.first_pending_at.get_or_insert_with(Instant::now);
964        cond.notify_all();
965        loop {
966            if let Some(error) = state.last_error.clone() {
967                return Err(io::Error::other(error));
968            }
969            if state.durable_lsn >= target {
970                return Ok(());
971            }
972            cond.wait(&mut state);
973        }
974    }
975
976    pub(crate) fn force_sync(&self) -> io::Result<()> {
977        self.sync_wal(None)
978    }
979
980    // A target belongs to an append whose caller still holds its epoch lease.
981    // A forced barrier also covers file metadata and must always reach the OS.
982    fn sync_wal(&self, end_lsn: Option<u64>) -> io::Result<()> {
983        self.check_write_error()?;
984        // Strict append already owns a read lease. Do not wait behind a
985        // checkpoint that needs that append to finish before resetting.
986        let _epoch = self.queue.epoch.read_recursive();
987        {
988            let mut wal = self.wal.lock();
989            let synced = if let Some(end) = end_lsn {
990                let needs_sync = wal.durable_lsn() < end;
991                wal.flush_until(end)?;
992                needs_sync
993            } else {
994                wal.sync()?;
995                true
996            };
997            if synced {
998                self.fsync_count.fetch_add(1, Ordering::Relaxed);
999            }
1000            let durable = wal.durable_lsn();
1001            drop(wal);
1002            let (state_lock, cond) = &*self.state;
1003            let mut state = state_lock.lock();
1004            // Concurrent writers may publish their completed syncs out of order.
1005            state.durable_lsn = state.durable_lsn.max(durable);
1006            state.pending_target_lsn = durable.max(state.pending_target_lsn);
1007            state.pending_statements = 0;
1008            state.pending_wal_bytes = 0;
1009            state.first_pending_at = None;
1010            state.last_error = None;
1011            cond.notify_all();
1012        }
1013        Ok(())
1014    }
1015
1016    fn truncate_incomplete_tail(&self, valid_lsn: u64) -> io::Result<()> {
1017        let _epoch = self.queue.epoch.write();
1018        if self.queue.has_pending() {
1019            return Err(io::Error::other(
1020                "WAL append raced incomplete-tail recovery",
1021            ));
1022        }
1023        let mut wal = self.wal.lock();
1024        self.wal_generation.fetch_add(1, Ordering::AcqRel);
1025        wal.truncate_incomplete_tail(valid_lsn)?;
1026        let durable = wal.durable_lsn();
1027        drop(wal);
1028        self.queue.reset(valid_lsn);
1029
1030        let (state_lock, cond) = &*self.state;
1031        let mut state = state_lock.lock();
1032        state.durable_lsn = durable;
1033        state.pending_target_lsn = durable;
1034        state.pending_statements = 0;
1035        state.pending_wal_bytes = 0;
1036        state.first_pending_at = None;
1037        state.last_error = None;
1038        cond.notify_all();
1039        Ok(())
1040    }
1041
1042    /// Control records need a durable boundary even when user DML is async.
1043    /// Observe the queue's end under the epoch lease: syncing only WalWriter
1044    /// would miss records that have been accepted but not drained yet.
1045    fn sync_pending(&self) -> io::Result<()> {
1046        if matches!(self.mode, DurabilityMode::Strict) {
1047            return self.force_sync();
1048        }
1049        let _epoch = self.queue.epoch.read();
1050        let target = self.queue.pending.lock().next_lsn;
1051        let (state_lock, cond) = &*self.state;
1052        let mut state = state_lock.lock();
1053        state.pending_target_lsn = state.pending_target_lsn.max(target);
1054        state.pending_statements = state.pending_statements.saturating_add(1);
1055        state.first_pending_at.get_or_insert_with(Instant::now);
1056        cond.notify_all();
1057        loop {
1058            if let Some(error) = &state.last_error {
1059                return Err(io::Error::other(error.clone()));
1060            }
1061            if state.durable_lsn >= target {
1062                return Ok(());
1063            }
1064            cond.wait(&mut state);
1065        }
1066    }
1067
1068    pub(super) fn checkpoint_boundary(&self) -> CheckpointWalBoundary {
1069        let _epoch = self.queue.epoch.write();
1070        let end = if matches!(self.mode, DurabilityMode::Strict) {
1071            self.wal.lock().current_lsn()
1072        } else {
1073            self.queue.pending.lock().next_lsn
1074        };
1075        CheckpointWalBoundary {
1076            generation: self.wal_generation.load(Ordering::Acquire),
1077            end,
1078            ownership_bytes: self.ownership_bytes.load(Ordering::Relaxed),
1079        }
1080    }
1081
1082    #[cfg(test)]
1083    pub(crate) fn truncate(&self) -> io::Result<()> {
1084        self.truncate_through(self.checkpoint_boundary(), false)
1085    }
1086
1087    pub(super) fn truncate_through(
1088        &self,
1089        boundary: CheckpointWalBoundary,
1090        runtime_snapshots_durable: bool,
1091    ) -> io::Result<()> {
1092        self.check_write_error()?;
1093        let _epoch = self.queue.epoch.write();
1094        if self.wal_generation.load(Ordering::Acquire) != boundary.generation {
1095            return Err(io::Error::other(
1096                "checkpoint belongs to a previous WAL generation",
1097            ));
1098        }
1099        // Async appenders may have returned while their entries remain queued.
1100        // Drain them before deciding what the checkpoint may discard.
1101        {
1102            let mut wal = self.wal.lock();
1103            for (offset, bytes) in self.queue.drain_sorted() {
1104                if offset != wal.current_lsn() {
1105                    return Err(io::Error::other("WAL queue offset differs from writer"));
1106                }
1107                wal.append_bytes(&bytes)?;
1108            }
1109            wal.sync()?;
1110        }
1111        if self.ownership_wal_state.load(Ordering::Acquire) == 0 {
1112            let reader = WalReader::open(&self.wal_path)?;
1113            let mut protected = false;
1114            for item in reader.iter() {
1115                match item {
1116                    Ok((_, WalRecord::PageOwnership { .. } | WalRecord::FullPageImage { .. })) => {
1117                        protected = true;
1118                        break;
1119                    }
1120                    Ok(_) => {}
1121                    Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
1122                    Err(error) => return Err(error),
1123                }
1124            }
1125            self.ownership_wal_state
1126                .store(if protected { 2 } else { 1 }, Ordering::Release);
1127        }
1128        if self.ownership_wal_state.load(Ordering::Acquire) == 2 {
1129            // A Finish record alone cannot prove that both superblock copies
1130            // are fenced; only recovery may eventually authorize truncation.
1131            return Err(io::Error::other(
1132                "cannot truncate WAL while page ownership records require recovery",
1133            ));
1134        }
1135        if self.runtime_wal_state.load(Ordering::Acquire) == 0 {
1136            let mut protected = false;
1137            for item in WalReader::open(&self.wal_path)?.iter() {
1138                if matches!(
1139                    item?.1,
1140                    WalRecord::ProbabilisticDelta { .. } | WalRecord::VectorInsert { .. }
1141                ) {
1142                    protected = true;
1143                }
1144            }
1145            self.runtime_wal_state
1146                .store(if protected { 2 } else { 1 }, Ordering::Release);
1147        }
1148        self.wal_generation.fetch_add(1, Ordering::AcqRel);
1149        let mut wal = self.wal.lock();
1150        let retain_runtime =
1151            !runtime_snapshots_durable && self.runtime_wal_state.load(Ordering::Acquire) == 2;
1152        // Only completed ownership records can be discarded past the boundary.
1153        // They were validated above. Every other frame belongs to a later write.
1154        let ownership_end = self
1155            .ownership_bytes
1156            .load(Ordering::Relaxed)
1157            .checked_sub(boundary.ownership_bytes)
1158            .and_then(|bytes| boundary.end.checked_add(bytes));
1159        let rewrite = retain_runtime || ownership_end != Some(wal.current_lsn());
1160        if rewrite {
1161            let has_runtime = self.retain_checkpoint_wal(&mut wal, boundary.end, retain_runtime)?;
1162            self.runtime_wal_state
1163                .store(if has_runtime { 2 } else { 1 }, Ordering::Release);
1164        } else {
1165            wal.truncate()?;
1166            self.runtime_wal_state.store(1, Ordering::Release);
1167        }
1168        let durable = wal.durable_lsn();
1169        let current = wal.current_lsn();
1170        drop(wal);
1171
1172        // Queue's next_lsn tracks byte offsets in the same space as
1173        // wal.current_lsn. After truncate both must be reset together
1174        // — otherwise enqueue returns a target_lsn in the old range
1175        // that drain can never reach, and wait_until_durable hangs.
1176        self.queue.reset(current);
1177
1178        let (state_lock, cond) = &*self.state;
1179        let mut state = state_lock.lock();
1180        state.durable_lsn = durable;
1181        state.pending_target_lsn = durable;
1182        state.pending_statements = 0;
1183        state.pending_wal_bytes = 0;
1184        state.first_pending_at = None;
1185        state.last_error = None;
1186        cond.notify_all();
1187        drop(state);
1188        if rewrite {
1189            use reddb_file::Vfs;
1190            let parent = self
1191                .wal_path
1192                .parent()
1193                .filter(|p| !p.as_os_str().is_empty())
1194                .unwrap_or_else(|| Path::new("."));
1195            reddb_file::StdVfs.sync_dir(parent)?;
1196        }
1197        Ok(())
1198    }
1199
1200    /// Keep later logical writes and any runtime frames absent from the snapshot. The
1201    /// temporary file is synced before atomic publication, so interruption
1202    /// leaves either the original WAL or a complete retained journal.
1203    fn retain_checkpoint_wal(
1204        &self,
1205        wal: &mut WalWriter,
1206        boundary: u64,
1207        retain_runtime: bool,
1208    ) -> io::Result<bool> {
1209        use std::io::{Read, Seek, SeekFrom, Write};
1210        static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
1211        let mut name = self
1212            .wal_path
1213            .file_name()
1214            .ok_or_else(|| io::Error::other("WAL filename missing"))?
1215            .to_os_string();
1216        name.push(format!(
1217            ".{}.{}.runtime.tmp",
1218            std::process::id(),
1219            NEXT_TEMP.fetch_add(1, Ordering::Relaxed)
1220        ));
1221        let temporary = self.wal_path.with_file_name(name);
1222        let mut options = std::fs::OpenOptions::new();
1223        options.write(true).create_new(true);
1224        #[cfg(unix)]
1225        {
1226            use std::os::unix::fs::OpenOptionsExt;
1227            options.mode(0o600);
1228        }
1229        let mut temp_file = options.open(&temporary)?;
1230        let result = (|| -> io::Result<bool> {
1231            let mut has_runtime = false;
1232            let mut source = std::fs::File::open(&self.wal_path)?;
1233            let mut header = [0u8; reddb_file::WAL_FILE_HEADER_BYTES];
1234            source.read_exact(&mut header)?;
1235            reddb_file::decode_wal_file_header(&header)
1236                .map_err(|error| io::Error::other(error.to_string()))?;
1237            temp_file.write_all(&header)?;
1238            temp_file.sync_all()?;
1239            drop(temp_file);
1240            let mut retained = WalWriter::open(&temporary)?;
1241            let mut previous = None;
1242            let end = wal.current_lsn();
1243            let mut buffer = [0u8; 64 * 1024];
1244            let mut copy_frame = |start: u64, end: u64| -> io::Result<()> {
1245                source.seek(SeekFrom::Start(start))?;
1246                let mut remaining = end
1247                    .checked_sub(start)
1248                    .ok_or_else(|| io::Error::other("invalid WAL frame boundary"))?;
1249                while remaining > 0 {
1250                    let length = usize::try_from(remaining.min(buffer.len() as u64))
1251                        .map_err(|_| io::Error::other("invalid WAL frame length"))?;
1252                    source.read_exact(&mut buffer[..length])?;
1253                    retained.append_bytes(&buffer[..length])?;
1254                    remaining -= length as u64;
1255                }
1256                Ok(())
1257            };
1258            for item in WalReader::open(&self.wal_path)?.iter() {
1259                let (offset, record) = item?;
1260                if let Some((start, true)) = previous.take() {
1261                    copy_frame(start, offset)?;
1262                }
1263                let runtime = matches!(
1264                    record,
1265                    WalRecord::ProbabilisticDelta { .. } | WalRecord::VectorInsert { .. }
1266                );
1267                let keep = (runtime && retain_runtime)
1268                    || (offset >= boundary
1269                        && !matches!(
1270                            record,
1271                            WalRecord::PageOwnership { .. } | WalRecord::FullPageImage { .. }
1272                        ));
1273                has_runtime |= runtime && keep;
1274                previous = Some((offset, keep));
1275            }
1276            if let Some((start, true)) = previous {
1277                copy_frame(start, end)?;
1278            }
1279            drop(source);
1280            retained.sync()?;
1281            #[cfg(test)]
1282            if std::env::var_os("REDDB_TEST_EXIT_BEFORE_RUNTIME_WAL_RENAME").is_some() {
1283                std::process::exit(211);
1284            }
1285            std::fs::rename(&temporary, &self.wal_path)?;
1286            #[cfg(test)]
1287            if std::env::var_os("REDDB_TEST_EXIT_AFTER_RUNTIME_WAL_RENAME").is_some() {
1288                std::process::exit(212);
1289            }
1290            *wal = retained;
1291            Ok(has_runtime)
1292        })();
1293        if result.is_err() {
1294            let _ = std::fs::remove_file(&temporary);
1295        }
1296        result
1297    }
1298
1299    fn release_completed_ownership_wal(&self) -> io::Result<()> {
1300        use reddb_file::page_ownership_journal::{encode, pending_epoch, PageOwnershipRecord};
1301        let _epoch = self.queue.epoch.write();
1302        let mut journal = Vec::new();
1303        let mut last = None;
1304        for item in WalReader::open(&self.wal_path)?.iter() {
1305            match item {
1306                Ok((_, WalRecord::PageOwnership { record })) => {
1307                    journal.extend_from_slice(&encode(record)?);
1308                    last = Some(record);
1309                }
1310                Ok(_) => {}
1311                Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => {
1312                    return Err(io::Error::new(
1313                        io::ErrorKind::InvalidData,
1314                        "incomplete WAL before ownership completion",
1315                    ));
1316                }
1317                Err(error) => return Err(error),
1318            }
1319        }
1320        if pending_epoch(&journal)?.is_some()
1321            || !matches!(last, Some(PageOwnershipRecord::Finish { .. }))
1322        {
1323            return Err(io::Error::other("page ownership WAL is not complete"));
1324        }
1325        self.ownership_wal_state.store(1, Ordering::Release);
1326        Ok(())
1327    }
1328
1329    fn recover_page_ownership(
1330        coordinator: Option<&Self>,
1331        store: &UnifiedStore,
1332        journal: &[u8],
1333    ) -> io::Result<()> {
1334        use reddb_file::page_ownership_journal::{
1335            pending_epoch, recovery_plan, PageOwnershipRecord,
1336        };
1337        if journal.is_empty() {
1338            return Ok(());
1339        }
1340        let pager = store
1341            .pager
1342            .as_ref()
1343            .ok_or_else(|| io::Error::other("ownership WAL requires a pager"))?;
1344        let header = pager
1345            .header()
1346            .map_err(|error| io::Error::other(error.to_string()))?;
1347        if header.version < reddb_file::file_format::PAGE_OWNERSHIP_FILE_VERSION {
1348            return Err(io::Error::other(
1349                "page ownership journal requires recovery with a fenced file version",
1350            ));
1351        }
1352        let pending = pending_epoch(journal).map_err(|error| {
1353            io::Error::other(format!("page ownership journal requires recovery: {error}"))
1354        })?;
1355        if let Some(mut pending) = pending {
1356            let catalog_epoch = store.ownership_catalog_epoch.load(Ordering::Acquire);
1357            let (_, retained_pages) = pager
1358                .deferred_reclamation_pages()
1359                .map_err(|error| io::Error::other(error.to_string()))?;
1360            // A retirement intent precedes the catalog's deferred-free ledger.
1361            // Publication does not release pages that this ledger still owns,
1362            // including pages allocated and retired within the same epoch.
1363            if catalog_epoch == pending.epoch {
1364                for page in &retained_pages {
1365                    pending.retired_pages.remove(page);
1366                }
1367            }
1368            let mut plan = recovery_plan(
1369                &pending,
1370                catalog_epoch,
1371                reddb_engine::storage::pager_io::FIRST_ALLOCATABLE_PAGE,
1372                header.page_count,
1373            )?;
1374            if retained_pages
1375                .iter()
1376                .any(|page| plan.release.binary_search(page).is_ok())
1377            {
1378                return Err(io::Error::other(
1379                    "ownership recovery would release a catalog-retained page",
1380                ));
1381            }
1382            plan.preserve.extend(retained_pages);
1383            plan.preserve.sort_unstable();
1384            plan.preserve.dedup();
1385            pager
1386                .validate_owned_pages(&plan.preserve)
1387                .map_err(|error| io::Error::other(error.to_string()))?;
1388            let Some(coordinator) = coordinator else {
1389                // Readers validate ownership but never reclaim or finish an epoch.
1390                return Ok(());
1391            };
1392            let manifest_reference = pager
1393                .manifest_reference()
1394                .map_err(|error| io::Error::other(error.to_string()))?;
1395            if !plan.release.is_empty() && manifest_reference.page_id != 0 {
1396                // A crash can leave only one header naming the selected catalog.
1397                // Retiring its predecessor must first fence that same authority
1398                // into both fallback copies, before any allocator writeback.
1399                pager
1400                    .publish_manifest_reference(manifest_reference)
1401                    .map_err(|error| io::Error::other(error.to_string()))?;
1402            }
1403            pager
1404                .recover_unowned_pages(&plan.release)
1405                .map_err(|error| io::Error::other(error.to_string()))?;
1406            #[cfg(test)]
1407            if std::env::var_os("REDDB_EXPERIMENTAL_EXIT_DURING_OWNERSHIP_RECOVERY").is_some() {
1408                std::process::exit(187);
1409            }
1410            pager
1411                .sync_recovered_allocator()
1412                .map_err(|error| io::Error::other(error.to_string()))?;
1413            #[cfg(test)]
1414            if std::env::var_os("REDDB_EXPERIMENTAL_EXIT_AFTER_OWNERSHIP_SYNC").is_some() {
1415                std::process::exit(188);
1416            }
1417            coordinator.append_durable_page_ownership(PageOwnershipRecord::Finish {
1418                epoch: pending.epoch,
1419            })?;
1420            #[cfg(test)]
1421            if std::env::var_os("REDDB_EXPERIMENTAL_EXIT_AFTER_OWNERSHIP_FINISH").is_some() {
1422                std::process::exit(189);
1423            }
1424        }
1425        coordinator.map_or(Ok(()), Self::release_completed_ownership_wal)
1426    }
1427
1428    pub(super) fn next_page_ownership_epoch(&self, store: &UnifiedStore) -> io::Result<u64> {
1429        self.ownership_last_epoch
1430            .load(Ordering::Acquire)
1431            .max(store.ownership_catalog_epoch.load(Ordering::Acquire))
1432            .checked_add(1)
1433            .ok_or_else(|| io::Error::other("page ownership epoch exhausted"))
1434    }
1435
1436    /// Begin an epoch only when the caller has excluded all other pager mutators.
1437    pub(super) fn begin_page_ownership_epoch(
1438        &self,
1439        store: &UnifiedStore,
1440        epoch: u64,
1441    ) -> io::Result<()> {
1442        if store.ownership_active_epoch.load(Ordering::Acquire) != 0
1443            || epoch <= store.ownership_catalog_epoch.load(Ordering::Acquire)
1444            || epoch <= self.ownership_last_epoch.load(Ordering::Acquire)
1445        {
1446            return Err(io::Error::other("invalid page ownership epoch"));
1447        }
1448        let pager = store
1449            .pager
1450            .as_ref()
1451            .ok_or_else(|| io::Error::other("ownership epoch requires a pager"))?;
1452        let format_version = if !store.secondary_index_specs.read().is_empty() {
1453            reddb_file::file_format::PAGE_SECONDARY_INDEX_FILE_VERSION
1454        } else if store.config.resident_memory_bytes_max.is_some() {
1455            reddb_file::file_format::PAGE_DISK_RESIDENCY_FILE_VERSION
1456        } else {
1457            reddb_file::file_format::PAGE_CHECKPOINT_UNDO_FILE_VERSION
1458        };
1459        // Dropping the final secondary tree never permits an old writer to
1460        // reopen the file; its retired pages may still be reader-pinned.
1461        let format_version = format_version.max(
1462            pager
1463                .header()
1464                .map_err(|error| io::Error::other(error.to_string()))?
1465                .version,
1466        );
1467        pager
1468            .fence_file_format_version(format_version)
1469            .map_err(|error| io::Error::other(error.to_string()))?;
1470        let coordinator = Arc::clone(
1471            store
1472                .commit
1473                .as_ref()
1474                .ok_or_else(|| io::Error::other("ownership epoch requires a WAL coordinator"))?,
1475        );
1476        let recorder = Arc::new(StoreOwnershipRecorder::begin(coordinator, epoch)?);
1477        pager.install_ownership_recorder(recorder)?;
1478        store.ownership_active_epoch.store(epoch, Ordering::Release);
1479        Ok(())
1480    }
1481
1482    /// Complete the epoch only while the same exclusion remains in force.
1483    pub(super) fn finish_page_ownership_epoch(
1484        &self,
1485        store: &UnifiedStore,
1486        epoch: u64,
1487    ) -> io::Result<()> {
1488        self.finish_page_ownership_epoch_inner(store, epoch, true)
1489    }
1490
1491    /// A batch may leave completed ownership records protected in the WAL.
1492    /// The next ordinary checkpoint (or recovery) validates the complete
1493    /// journal before truncation; no user WAL is discarded here.
1494    pub(super) fn finish_count_batch_ownership_epoch(
1495        &self,
1496        store: &UnifiedStore,
1497        epoch: u64,
1498    ) -> io::Result<()> {
1499        self.finish_page_ownership_epoch_inner(store, epoch, false)
1500    }
1501
1502    fn finish_page_ownership_epoch_inner(
1503        &self,
1504        store: &UnifiedStore,
1505        epoch: u64,
1506        validate_for_truncation: bool,
1507    ) -> io::Result<()> {
1508        if epoch == 0 || store.ownership_active_epoch.load(Ordering::Acquire) != epoch {
1509            return Err(io::Error::other("page ownership epoch is not active"));
1510        }
1511        if store.ownership_catalog_epoch.load(Ordering::Acquire) != epoch {
1512            return Err(io::Error::other("page ownership epoch is not published"));
1513        }
1514        let pager = store
1515            .pager
1516            .as_ref()
1517            .ok_or_else(|| io::Error::other("ownership epoch requires a pager"))?;
1518        pager
1519            .sync_recovered_allocator()
1520            .map_err(|error| io::Error::other(error.to_string()))?;
1521        self.append_durable_page_ownership(
1522            reddb_file::page_ownership_journal::PageOwnershipRecord::Finish { epoch },
1523        )?;
1524        pager.clear_ownership_recorder()?;
1525        store.ownership_active_epoch.store(0, Ordering::Release);
1526        if validate_for_truncation {
1527            self.release_completed_ownership_wal()
1528        } else {
1529            Ok(())
1530        }
1531    }
1532
1533    pub(crate) fn replay_into(
1534        &self,
1535        store: &UnifiedStore,
1536        boot_wal: Option<&crate::storage::compact::boot_system_wal::BootSystemWalPlan>,
1537    ) -> io::Result<()> {
1538        Self::replay_from_wal(store, &self.wal_path, Some(self), boot_wal)
1539    }
1540
1541    pub(crate) fn replay_read_only(store: &UnifiedStore, wal_path: &Path) -> io::Result<()> {
1542        Self::replay_from_wal(store, wal_path, None, None)
1543    }
1544
1545    fn replay_from_wal(
1546        store: &UnifiedStore,
1547        wal_path: &Path,
1548        coordinator: Option<&Self>,
1549        boot_wal: Option<&crate::storage::compact::boot_system_wal::BootSystemWalPlan>,
1550    ) -> io::Result<()> {
1551        if !wal_path.exists() {
1552            return Ok(());
1553        }
1554
1555        let reader = match WalReader::open(wal_path) {
1556            Ok(reader) => reader,
1557            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
1558            Err(err) => return Err(err),
1559        };
1560
1561        let mut tx_states = std::collections::HashMap::<u64, bool>::new();
1562        let mut has_page_writes = false;
1563        let mut ownership_journal = Vec::new();
1564        let mut latest_ownership_epoch = 0;
1565        let mut incomplete_wal_tail = None;
1566        let mut applied = false;
1567
1568        let mut records = reader.iter();
1569        while let Some(record) = records.next() {
1570            let (lsn, record) = match record {
1571                Ok(record) => record,
1572                Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => {
1573                    validate_incomplete_wal_tail(&mut records, &ownership_journal)?;
1574                    incomplete_wal_tail = Some(records.next_record_lsn());
1575                    break;
1576                }
1577                Err(err) => return Err(err),
1578            };
1579            match record {
1580                WalRecord::PageOwnership { record } => {
1581                    latest_ownership_epoch = latest_ownership_epoch.max(record.epoch());
1582                    if let Some(coordinator) = coordinator {
1583                        coordinator
1584                            .ownership_last_epoch
1585                            .fetch_max(record.epoch(), Ordering::AcqRel);
1586                    }
1587                    ownership_journal
1588                        .extend_from_slice(&reddb_file::page_ownership_journal::encode(record)?);
1589                }
1590                WalRecord::TxCommitBatch { actions, .. } => {
1591                    for (index, payload) in actions.into_iter().enumerate() {
1592                        if boot_wal.is_some_and(|proof| proof.skips_action(lsn, index)) {
1593                            continue;
1594                        }
1595                        let action = StoreWalAction::decode(&payload)?;
1596                        applied = true;
1597                        store.apply_replayed_action(&action, false).map_err(|err| {
1598                            io::Error::other(format!("failed to replay store wal action: {err}"))
1599                        })?;
1600                        // Retain only the existing bounded exact-row proof.
1601                        // These images came from a complete committed WAL batch;
1602                        // replay need not rebuild a whole tree for a sparse edit.
1603                        store.remember_checkpoint_rows(vec![action], Default::default());
1604                    }
1605                }
1606                WalRecord::Begin { tx_id } => {
1607                    tx_states.insert(tx_id, false);
1608                }
1609                WalRecord::Commit { tx_id } => {
1610                    tx_states.insert(tx_id, true);
1611                }
1612                WalRecord::Rollback { tx_id } => {
1613                    tx_states.remove(&tx_id);
1614                }
1615                WalRecord::PageWrite { .. } => has_page_writes = true,
1616                WalRecord::Checkpoint { .. } => {}
1617                WalRecord::VectorInsert {
1618                    collection,
1619                    entity_id,
1620                    vector,
1621                } => {
1622                    if let Some(coordinator) = coordinator {
1623                        coordinator.runtime_wal_state.store(2, Ordering::Release);
1624                    }
1625                    // Issue #694 — capture `vector.turbo` WAL inserts so the
1626                    // boot-time TurboQuant index rebuild can drain them in
1627                    // WAL order (deterministic against the pre-restart
1628                    // state under a fixed codec seed). The legacy `vector`
1629                    // path doesn't read this map.
1630                    let mut map = store.replayed_turbo_inserts.lock();
1631                    map.entry(
1632                        reddb_engine::storage::system_collection_names::canonical_owned(collection),
1633                    )
1634                    .or_default()
1635                    .push((entity_id, vector));
1636                }
1637                WalRecord::ProbabilisticDelta {
1638                    kind,
1639                    operation,
1640                    name,
1641                    operands,
1642                } => {
1643                    if let Some(coordinator) = coordinator {
1644                        coordinator.runtime_wal_state.store(2, Ordering::Release);
1645                    }
1646                    let mut deltas = store.replayed_probabilistic_deltas.lock();
1647                    deltas.push((kind, operation, name, operands));
1648                }
1649                WalRecord::FullPageImage { .. } => {
1650                    // Pager-level FPI (gh-478); store replay ignores.
1651                }
1652            }
1653        }
1654
1655        if let (Some(coordinator), Some(valid_lsn)) = (coordinator, incomplete_wal_tail) {
1656            coordinator.truncate_incomplete_tail(valid_lsn)?;
1657        }
1658        Self::recover_page_ownership(coordinator, store, &ownership_journal)?;
1659
1660        if has_page_writes {
1661            // Do not retain every transaction's page payload while scanning a
1662            // large WAL. The writer remains open and ownership recovery may
1663            // append a Finish record, but it does not truncate the journal.
1664            for item in WalReader::open(wal_path)?.iter() {
1665                let record = match item {
1666                    Ok((_, record)) => record,
1667                    Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break,
1668                    Err(err) => return Err(err),
1669                };
1670                let WalRecord::PageWrite { tx_id, data, .. } = record else {
1671                    continue;
1672                };
1673                if !tx_states.get(&tx_id).copied().unwrap_or(false) {
1674                    continue;
1675                }
1676                let action = StoreWalAction::decode(&data)?;
1677                applied = true;
1678                store.apply_replayed_action(&action, false).map_err(|err| {
1679                    io::Error::other(format!("failed to replay store wal action: {err}"))
1680                })?;
1681                store.remember_checkpoint_rows(vec![action], Default::default());
1682            }
1683        }
1684
1685        let Some(coordinator) = coordinator else {
1686            return Ok(());
1687        };
1688        if applied && store.config.resident_memory_bytes_max.is_some() {
1689            // The immutable base plus committed WAL overlay is authoritative.
1690            // Keep the WAL until a paced checkpoint publishes the replacement;
1691            // boot must not copy every cold payload for a few replayed rows.
1692            return Ok(());
1693        }
1694        if applied {
1695            // Opening is exclusive: no client can mutate published trees
1696            // while replay constructs replacement generations.
1697            #[cfg(test)]
1698            if let Ok(fault) = std::env::var("REDDB_TEST_PAGE_REPLAY_IO") {
1699                use crate::storage::engine::pager;
1700                match fault.as_str() {
1701                    "empty" => pager::test_fail_next_pager_write(None, 0),
1702                    "partial" => pager::test_fail_next_pager_write(None, 17),
1703                    "sync" => pager::test_fail_pager_sync_after(0),
1704                    _ => panic!("unknown replay publication I/O fault {fault}"),
1705                }
1706            }
1707            let epoch = latest_ownership_epoch
1708                .max(store.ownership_catalog_epoch.load(Ordering::Acquire))
1709                .checked_add(1)
1710                .ok_or_else(|| io::Error::other("page ownership epoch exhausted"))?;
1711            coordinator.begin_page_ownership_epoch(store, epoch)?;
1712            // Even when the replayed actions leave all B-trees unchanged, the
1713            // epoch must be in the catalog before its journal can finish.
1714            store.mark_paged_registry_dirty();
1715            store
1716                .reconcile_replayed_btrees()
1717                .map_err(|err| io::Error::other(err.to_string()))?;
1718            coordinator.finish_page_ownership_epoch(store, epoch)?;
1719        }
1720        Ok(())
1721    }
1722
1723    fn wait_until_durable(&self, target_lsn: u64, wal_bytes: u64) -> io::Result<()> {
1724        self.wait_until_durable_batch(target_lsn, wal_bytes, false)
1725    }
1726
1727    fn check_write_error(&self) -> io::Result<()> {
1728        if let Some(error) = &self.state.0.lock().last_error {
1729            return Err(io::Error::other(error.clone()));
1730        }
1731        Ok(())
1732    }
1733
1734    fn wait_until_durable_batch(
1735        &self,
1736        target_lsn: u64,
1737        wal_bytes: u64,
1738        ready: bool,
1739    ) -> io::Result<()> {
1740        match self.mode {
1741            DurabilityMode::Strict => self.force_sync(),
1742            // Async: record the pending target so the background
1743            // flusher eventually covers it, but don't block the
1744            // caller. Matches PG `synchronous_commit=off` semantics —
1745            // crash inside the flush window loses unflushed commits.
1746            DurabilityMode::Async => {
1747                let (state_lock, cond) = &*self.state;
1748                let mut state = state_lock.lock();
1749                if let Some(error) = &state.last_error {
1750                    return Err(io::Error::other(error.clone()));
1751                }
1752                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
1753                state.pending_statements = state.pending_statements.saturating_add(1);
1754                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
1755                state.first_pending_at.get_or_insert_with(Instant::now);
1756                cond.notify_all();
1757                Ok(())
1758            }
1759            DurabilityMode::WalDurableGrouped => {
1760                let (state_lock, cond) = &*self.state;
1761                let mut state = state_lock.lock();
1762                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
1763                state.pending_statements = state.pending_statements.saturating_add(1);
1764                if ready {
1765                    state.pending_statements = state
1766                        .pending_statements
1767                        .max(self.config.max_statements.max(1));
1768                }
1769                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
1770                state.first_pending_at.get_or_insert_with(Instant::now);
1771                cond.notify_all();
1772
1773                loop {
1774                    if let Some(err) = state.last_error.clone() {
1775                        return Err(io::Error::other(err));
1776                    }
1777                    if state.durable_lsn >= target_lsn {
1778                        return Ok(());
1779                    }
1780                    // parking_lot::Condvar mutates the guard in place —
1781                    // no LockResult to unwrap, no poisoning to fold.
1782                    cond.wait(&mut state);
1783                }
1784            }
1785        }
1786    }
1787
1788    fn run_group_commit_loop(
1789        wal: Arc<WalMutex>,
1790        queue: Arc<WalAppendQueue>,
1791        state: Arc<(CommitStateMutex, CommitStateCondvar)>,
1792        fsync_count: Arc<AtomicU64>,
1793        window: Duration,
1794        max_statements: usize,
1795        max_wal_bytes: u64,
1796    ) {
1797        let (state_lock, cond) = &*state;
1798        loop {
1799            let target_lsn = {
1800                let mut guard = state_lock.lock();
1801
1802                while !guard.shutdown && guard.pending_target_lsn <= guard.durable_lsn {
1803                    cond.wait(&mut guard);
1804                }
1805
1806                if guard.shutdown {
1807                    return;
1808                }
1809
1810                let immediate = window.is_zero()
1811                    || guard.pending_statements >= max_statements
1812                    || guard.pending_wal_bytes >= max_wal_bytes;
1813
1814                if !immediate {
1815                    let deadline = guard.first_pending_at.unwrap_or_else(Instant::now) + window;
1816                    let now = Instant::now();
1817                    if now < deadline {
1818                        let timeout = deadline.saturating_duration_since(now);
1819                        let _ = cond.wait_for(&mut guard, timeout);
1820                        if guard.shutdown {
1821                            return;
1822                        }
1823                        if guard.pending_target_lsn <= guard.durable_lsn {
1824                            continue;
1825                        }
1826                        let should_wait_again = guard.pending_statements < max_statements
1827                            && guard.pending_wal_bytes < max_wal_bytes
1828                            && guard
1829                                .first_pending_at
1830                                .map(|first| first.elapsed() < window)
1831                                .unwrap_or(false);
1832                        if should_wait_again {
1833                            continue;
1834                        }
1835                    }
1836                }
1837
1838                guard.pending_target_lsn
1839            };
1840
1841            // Drain the current epoch even when reset is waiting: outstanding
1842            // append leases cannot finish until this flusher acknowledges them.
1843            // Retain the lease through state publication to exclude stale ACKs
1844            // after a checkpoint resets offsets back to the WAL header.
1845            let _epoch = queue.epoch.read_recursive();
1846
1847            // Drain all queued entries. Since `WalAppendQueue::enqueue`
1848            // assigns LSN and pushes under a single mutex, the drained
1849            // tuples are guaranteed to form a contiguous byte range
1850            // starting at `wal.current_lsn()` — no gaps, no leftover
1851            // handling.
1852            let batches = queue.drain_sorted();
1853
1854            let sync_result = {
1855                let mut wal = wal.lock();
1856                let mut write_err: Option<io::Error> = None;
1857                for (_lsn, bytes) in batches {
1858                    if let Err(e) = wal.append_bytes(&bytes) {
1859                        write_err = Some(e);
1860                        break;
1861                    }
1862                }
1863                match write_err {
1864                    Some(e) => Err(e),
1865                    None => wal.sync().map(|_| {
1866                        // Count the fsync exactly once per drain
1867                        // cycle so tests can compare it against the
1868                        // number of `append_actions` callers that
1869                        // entered the queue.
1870                        fsync_count.fetch_add(1, Ordering::Relaxed);
1871                        wal.durable_lsn()
1872                    }),
1873                }
1874            };
1875
1876            // Late enqueuers that arrived after our drain stay in the
1877            // queue — don't clear the `pending_*` counters yet and
1878            // don't claim we reached `target_lsn` unless the fsync
1879            // actually covers it.
1880            let more_pending = queue.has_pending();
1881
1882            let mut guard = state_lock.lock();
1883            match sync_result {
1884                Ok(durable_lsn) => {
1885                    guard.durable_lsn = durable_lsn;
1886                    if !more_pending {
1887                        guard.pending_statements = 0;
1888                        guard.pending_wal_bytes = 0;
1889                        guard.first_pending_at = None;
1890                    }
1891                    guard.last_error = None;
1892                    let _ = target_lsn;
1893                }
1894                Err(err) => {
1895                    guard.last_error = Some(format!("WAL failed; reopen required: {err}"));
1896                    // A failed write may have left a partial batch. Do not
1897                    // retry it in a busy loop or later acknowledge its LSN.
1898                    cond.notify_all();
1899                    return;
1900                }
1901            }
1902            cond.notify_all();
1903        }
1904    }
1905}
1906
1907impl Drop for StoreCommitCoordinator {
1908    fn drop(&mut self) {
1909        let (state_lock, cond) = &*self.state;
1910        // parking_lot::Mutex::lock is infallible (no poisoning).
1911        let mut state = state_lock.lock();
1912        state.shutdown = true;
1913        cond.notify_all();
1914    }
1915}
1916
1917pub(super) struct PendingResultCacheAppend {
1918    pending: crate::storage::embedded::PendingEmbeddedAppend,
1919    epoch_guard: Option<super::result_cache_epoch::ResultCacheEpochGuard>,
1920}
1921
1922impl UnifiedStore {
1923    #[cfg(test)]
1924    pub(crate) fn test_fail_wal_flush_after(&self, bytes: usize) {
1925        self.commit
1926            .as_ref()
1927            .expect("fixture requires an external WAL")
1928            .wal
1929            .lock()
1930            .test_fail_flush_after(bytes);
1931    }
1932
1933    pub(crate) fn sync_control_metadata(&self) -> Result<(), StoreError> {
1934        if let Some(commit) = &self.commit {
1935            commit.sync_pending().map_err(StoreError::Io)?;
1936        }
1937        // Embedded appends wait for their own group-commit completion.
1938        Ok(())
1939    }
1940
1941    pub(crate) fn deferred_store_wal_capture_active() -> bool {
1942        deferred_store_wal_capture_active()
1943    }
1944
1945    pub(crate) fn begin_deferred_store_wal_capture() {
1946        begin_deferred_store_wal_capture();
1947    }
1948
1949    pub(crate) fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
1950        take_deferred_store_wal_capture()
1951    }
1952
1953    pub(crate) fn append_deferred_store_wal_actions(
1954        &self,
1955        actions: DeferredStoreWalActions,
1956    ) -> Result<(), StoreError> {
1957        if actions.actions.is_empty() {
1958            return Ok(());
1959        }
1960        self.ensure_pager_writeback_available()?;
1961        #[cfg(test)]
1962        if self
1963            .test_require_deferred_publication_fence
1964            .swap(false, Ordering::AcqRel)
1965            && !self.vault_publication_lock.is_owned_by_current_thread()
1966        {
1967            return Err(StoreError::Io(io::Error::other(
1968                "deferred WAL missing checkpoint publication fence",
1969            )));
1970        }
1971        #[cfg(test)]
1972        if self
1973            .test_fail_deferred_wal_append
1974            .swap(false, Ordering::AcqRel)
1975        {
1976            return Err(StoreError::Io(io::Error::other(
1977                "injected deferred WAL append failure",
1978            )));
1979        }
1980        if self.config.embedded_wal_path.is_some() {
1981            return self.append_embedded_store_wal_actions(&actions.actions);
1982        }
1983        let _publication = self.vault_publication_lock.lock();
1984        let mut actions = actions.actions;
1985        let epoch_guard = self.append_result_cache_epoch_action(&mut actions)?;
1986        // Deferred transactions need a committed WAL batch even in Strict
1987        // mode. WAL-only versions have no pager pages to flush yet.
1988        if let Some(commit) = &self.commit {
1989            let references = commit
1990                .append_checkpoint_actions(&actions)
1991                .map_err(StoreError::Io)?;
1992            self.remember_checkpoint_rows(actions, references);
1993        } else {
1994            self.flush_paged_state()?;
1995        }
1996        if let Some(guard) = epoch_guard {
1997            guard.commit();
1998        }
1999        Ok(())
2000    }
2001
2002    /// Emit a [`WalRecord::VectorInsert`] for a `vector.turbo`
2003    /// collection (issue #693). Returns `Ok(())` when no commit
2004    /// coordinator is configured (in-memory mode) so callers don't
2005    /// have to special-case the missing WAL — the in-memory index
2006    /// update remains durable enough for in-memory runtimes by
2007    /// construction.
2008    pub(crate) fn append_vector_insert_record(
2009        &self,
2010        collection: &str,
2011        entity_id: u64,
2012        vector: &[f32],
2013    ) -> std::io::Result<()> {
2014        let Some(commit) = &self.commit else {
2015            return Ok(());
2016        };
2017        let record = WalRecord::VectorInsert {
2018            collection: collection.to_string(),
2019            entity_id,
2020            vector: vector.to_vec(),
2021        };
2022        commit.append_single_record(record)
2023    }
2024
2025    pub(crate) fn append_probabilistic_delta_record(
2026        &self,
2027        kind: u8,
2028        operation: u8,
2029        name: &str,
2030        operands: Vec<Vec<u8>>,
2031    ) -> std::io::Result<()> {
2032        let Some(commit) = &self.commit else {
2033            return Ok(());
2034        };
2035        let record = WalRecord::ProbabilisticDelta {
2036            kind,
2037            operation,
2038            name: name.to_string(),
2039            operands,
2040        };
2041        commit.append_single_record(record)
2042    }
2043
2044    pub(crate) fn finish_paged_write(
2045        &self,
2046        actions: impl IntoIterator<Item = StoreWalAction>,
2047    ) -> Result<(), StoreError> {
2048        self.finish_paged_write_for_projection(
2049            actions,
2050            self.config.resident_memory_bytes_max.is_some(),
2051        )
2052    }
2053
2054    pub(crate) fn finish_paged_write_for_projection(
2055        &self,
2056        actions: impl IntoIterator<Item = StoreWalAction>,
2057        track: bool,
2058    ) -> Result<(), StoreError> {
2059        if self.is_read_only() {
2060            return Ok(());
2061        }
2062        self.ensure_pager_writeback_available()?;
2063        let actions: Vec<StoreWalAction> = actions.into_iter().collect();
2064        if deferred_store_wal_capture_active() {
2065            let captured = capture_deferred_store_wal_actions(actions);
2066            debug_assert!(captured);
2067            return Ok(());
2068        }
2069        if self.config.embedded_wal_path.is_some() {
2070            return self.append_embedded_store_wal_actions(&actions);
2071        }
2072        let _publication = self.vault_publication_lock.lock();
2073        let mut actions = actions;
2074        let epoch_guard = self.append_result_cache_epoch_action(&mut actions)?;
2075        let mut references = super::checkpoint_wal::CheckpointWalBatch::default();
2076        let result = match self.config.durability_mode {
2077            DurabilityMode::Strict => {
2078                if let Some(commit) = &self.commit {
2079                    if track {
2080                        references = commit
2081                            .append_checkpoint_actions(&actions)
2082                            .map_err(StoreError::Io)?;
2083                    } else {
2084                        commit.append_actions(&actions).map_err(StoreError::Io)?;
2085                    }
2086                }
2087                self.flush_paged_state()
2088            }
2089            DurabilityMode::WalDurableGrouped | DurabilityMode::Async => {
2090                if let Some(commit) = &self.commit {
2091                    if track {
2092                        references = commit
2093                            .append_checkpoint_actions(&actions)
2094                            .map_err(StoreError::Io)?;
2095                    } else {
2096                        commit.append_actions(&actions).map_err(StoreError::Io)?;
2097                    }
2098                    Ok(())
2099                } else {
2100                    self.flush_paged_state()
2101                }
2102            }
2103        };
2104        result?;
2105        if track {
2106            self.remember_checkpoint_rows(actions, references);
2107        }
2108        if let Some(guard) = epoch_guard {
2109            guard.commit();
2110        }
2111        Ok(())
2112    }
2113
2114    pub(crate) fn apply_encoded_store_wal_action(&self, payload: &[u8]) -> Result<(), StoreError> {
2115        let action = StoreWalAction::decode(payload).map_err(StoreError::Io)?;
2116        self.apply_replayed_action(&action, true)
2117    }
2118
2119    fn append_embedded_store_wal_actions(
2120        &self,
2121        actions: &[StoreWalAction],
2122    ) -> Result<(), StoreError> {
2123        let Some(path) = self.config.embedded_wal_path.as_deref() else {
2124            return Ok(());
2125        };
2126        if actions.is_empty() {
2127            return Ok(());
2128        }
2129        let _publication = self.vault_publication_lock.lock();
2130        let mut actions = actions.to_vec();
2131        let epoch_guard = self.append_result_cache_epoch_action(&mut actions)?;
2132        let payloads: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
2133        let encoded_len = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
2134            .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
2135        let result = match self.append_embedded_payloads(path, &payloads) {
2136            Ok(_) => Ok(()),
2137            Err(crate::api::RedDBError::InvalidOperation(msg))
2138                if msg.contains("embedded wal region full") =>
2139            {
2140                self.recover_full_embedded_wal(path, &payloads, encoded_len)
2141            }
2142            Err(err) => Err(StoreError::Io(std::io::Error::other(err.to_string()))),
2143        };
2144        if result.is_ok() {
2145            if let Some(guard) = epoch_guard {
2146                guard.commit();
2147            }
2148        }
2149        result
2150    }
2151
2152    fn recover_full_embedded_wal(
2153        &self,
2154        path: &Path,
2155        payloads: &[Vec<u8>],
2156        encoded_len: u64,
2157    ) -> Result<(), StoreError> {
2158        let _vault_guard = self.vault_publication_lock.lock();
2159        // The failed append preceded this lock: another writer may already
2160        // have reclaimed space. Retry through the same FIFO coordinator so
2161        // stale full results cannot each serialize another complete snapshot.
2162        match self.append_embedded_payloads(path, payloads) {
2163            Ok(_) => return Ok(()),
2164            Err(crate::api::RedDBError::InvalidOperation(message))
2165                if message.contains("embedded wal region full") => {}
2166            Err(error) => return Err(StoreError::Io(std::io::Error::other(error.to_string()))),
2167        }
2168        // A checkpoint can fail after publishing its image. Preserve the
2169        // session failure fence through errors and unwinding, just as append's
2170        // FlushBatch guard does; in-memory rollback alone cannot resolve disk.
2171        struct CheckpointFence<'a>(Option<&'a crate::storage::embedded::EmbeddedCommitSession>);
2172        impl Drop for CheckpointFence<'_> {
2173            fn drop(&mut self) {
2174                if let Some(session) = self.0 {
2175                    session.fence_interrupted_write();
2176                }
2177            }
2178        }
2179        let mut fence = CheckpointFence(Some(
2180            self.embedded_commit_session
2181                .get()
2182                .expect("WAL-full recovery follows an append attempt"),
2183        ));
2184        let started = Instant::now();
2185        let snapshot = self.to_binary_dump_bytes();
2186        let capacity = encoded_len.max((snapshot.len() as u64).min(EMBEDDED_WAL_HEADROOM_LIMIT));
2187        let checkpoint = crate::storage::EmbeddedRdbArtifact::write_snapshot_with_wal_capacity(
2188            path, &snapshot, capacity,
2189        )
2190        .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
2191        fence.0 = None;
2192        tracing::debug!(
2193            target: "reddb::embedded_checkpoint",
2194            snapshot_bytes = snapshot.len(),
2195            wal_region_bytes = checkpoint.manifest.wal_region_bytes,
2196            elapsed_us = started.elapsed().as_micros() as u64,
2197            "embedded WAL overflow checkpoint"
2198        );
2199        self.append_embedded_payloads(path, payloads)
2200            .map(|_| ())
2201            .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))
2202    }
2203
2204    fn append_embedded_payloads(
2205        &self,
2206        path: &Path,
2207        payloads: &[Vec<u8>],
2208    ) -> crate::RedDBResult<crate::storage::EmbeddedRdbOpen> {
2209        let session = self
2210            .embedded_commit_session
2211            .get_or_init(|| crate::storage::EmbeddedRdbArtifact::group_commit_session(path));
2212        let options = self.config.group_commit;
2213        let grouped = self.config.durability_mode == DurabilityMode::WalDurableGrouped;
2214        let window = if grouped {
2215            StoreCommitCoordinator::resolve_window(&options)
2216        } else {
2217            Duration::ZERO
2218        };
2219        session.append(
2220            payloads,
2221            reddb_file::embedded::EmbeddedGroupCommitOptions {
2222                window,
2223                max_statements: if grouped { options.max_statements } else { 1 },
2224                max_wal_bytes: options.max_wal_bytes,
2225            },
2226        )
2227    }
2228
2229    pub(super) fn enqueue_grouped_actions(
2230        &self,
2231        actions: &[StoreWalAction],
2232    ) -> Result<Option<PendingResultCacheAppend>, StoreError> {
2233        if self.config.durability_mode != DurabilityMode::WalDurableGrouped
2234            || deferred_store_wal_capture_active()
2235        {
2236            return Ok(None);
2237        }
2238        let Some(path) = self.config.embedded_wal_path.as_deref() else {
2239            return Ok(None);
2240        };
2241        let session = self
2242            .embedded_commit_session
2243            .get_or_init(|| crate::storage::EmbeddedRdbArtifact::group_commit_session(path));
2244        let _publication = self.vault_publication_lock.lock();
2245        let mut actions = actions.to_vec();
2246        let epoch_guard = self.append_result_cache_epoch_action(&mut actions)?;
2247        let payloads: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
2248        let options = self.config.group_commit;
2249        session
2250            .enqueue(
2251                &payloads,
2252                reddb_file::embedded::EmbeddedGroupCommitOptions {
2253                    window: StoreCommitCoordinator::resolve_window(&options),
2254                    max_statements: options.max_statements,
2255                    max_wal_bytes: options.max_wal_bytes,
2256                },
2257            )
2258            .map(|pending| {
2259                Some(PendingResultCacheAppend {
2260                    pending,
2261                    epoch_guard,
2262                })
2263            })
2264            .map_err(|error| StoreError::Io(io::Error::other(error.to_string())))
2265    }
2266
2267    pub(super) fn complete_grouped_actions(
2268        &self,
2269        pending: &mut PendingResultCacheAppend,
2270        actions: &[StoreWalAction],
2271    ) -> Result<(), StoreError> {
2272        let result = match pending.pending.wait() {
2273            Ok(_) => Ok(()),
2274            Err(crate::RedDBError::InvalidOperation(message))
2275                if message.contains("embedded wal region full") =>
2276            {
2277                self.append_embedded_store_wal_actions(actions)
2278            }
2279            Err(error) => Err(StoreError::Io(io::Error::other(error.to_string()))),
2280        };
2281        if result.is_ok() {
2282            if let Some(guard) = pending.epoch_guard.take() {
2283                guard.commit();
2284            }
2285        }
2286        result
2287    }
2288
2289    pub(crate) fn apply_replayed_action(
2290        &self,
2291        action: &StoreWalAction,
2292        update_btrees: bool,
2293    ) -> Result<(), StoreError> {
2294        reddb_engine::storage::store_wal::apply_replayed_action(
2295            &NativeReplayTarget {
2296                store: self,
2297                update_btrees,
2298            },
2299            action,
2300        )
2301    }
2302
2303    /// Atomic full-collection replace — issue #595 slice 9c.
2304    ///
2305    /// Builds a fresh `SegmentManager` populated with `entities`,
2306    /// atomically swaps it into the collections map, rebuilds the
2307    /// paged B-tree from the same records, and emits a single
2308    /// `RefreshCollection` WAL action.
2309    ///
2310    /// Concurrent readers that resolved an `Arc<SegmentManager>` for
2311    /// this collection before the swap continue reading the prior
2312    /// contents; readers after the swap see the new contents. The
2313    /// transition is single-pointer so partial state is unobservable.
2314    ///
2315    /// A crash between in-memory mutation and WAL fsync leaves the
2316    /// previous WAL stream intact — on recovery the prior
2317    /// `RefreshCollection` (or whatever last bulk-applied to the
2318    /// collection) is replayed, so the prior contents are observed.
2319    pub fn refresh_collection(
2320        &self,
2321        name: &str,
2322        entities: Vec<UnifiedEntity>,
2323    ) -> Result<Vec<Vec<u8>>, StoreError> {
2324        let name = Self::canonical_collection(name);
2325        let fv = self.format_version();
2326
2327        // Build a fresh manager. Done outside the collections lock so
2328        // the critical section is just the pointer swap below.
2329        let new_manager = Arc::new(SegmentManager::with_config(
2330            name,
2331            self.config.manager_config.clone(),
2332        ));
2333
2334        let mut prepared = entities;
2335        for entity in &mut prepared {
2336            entity.canonicalize_system_collection_names();
2337            if entity.id.raw() == 0 {
2338                entity.id = self.next_entity_id();
2339            } else {
2340                self.register_entity_id(entity.id);
2341            }
2342            if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
2343                if *row_id == 0 {
2344                    *row_id = new_manager.next_row_id();
2345                } else {
2346                    new_manager.register_row_id(*row_id);
2347                }
2348            }
2349            entity.ensure_table_logical_id();
2350        }
2351
2352        let serialized: Vec<Vec<u8>> = prepared
2353            .iter()
2354            .map(|e| Self::serialize_entity_record(e, None, fv))
2355            .collect();
2356
2357        new_manager.bulk_insert(prepared.clone()).map_err(|e| {
2358            StoreError::Io(std::io::Error::other(format!(
2359                "refresh_collection: bulk_insert into new manager failed: {e}"
2360            )))
2361        })?;
2362
2363        self.swap_collection_state(name, new_manager, &prepared, &serialized, true)?;
2364
2365        self.finish_paged_write([StoreWalAction::RefreshCollection {
2366            collection: name.to_string(),
2367            records: serialized.clone(),
2368        }])?;
2369
2370        Ok(serialized)
2371    }
2372
2373    /// Atomic swap of the in-memory collection state. Used by both
2374    /// the live `refresh_collection` path and WAL replay. The new
2375    /// manager is already populated; this fn replaces the live Arc,
2376    /// purges side-state pointing at the previous contents, and
2377    /// rebuilds the paged B-tree from the supplied records.
2378    fn swap_collection_state(
2379        &self,
2380        name: &str,
2381        new_manager: Arc<SegmentManager>,
2382        prepared: &[UnifiedEntity],
2383        serialized: &[Vec<u8>],
2384        update_btrees: bool,
2385    ) -> Result<(), StoreError> {
2386        self.resident
2387            .swap_collection_state(name, new_manager, prepared);
2388
2389        let immutable = self.immutable_paged_base()?;
2390        if let Some(pager) = self.pager.as_ref().filter(|_| update_btrees && !immutable) {
2391            let new_btree = Arc::new(BTree::new(Arc::clone(pager)));
2392            let mut sorted: Vec<(Vec<u8>, Vec<u8>)> = prepared
2393                .iter()
2394                .zip(serialized.iter())
2395                .map(|(e, r)| (e.id.raw().to_be_bytes().to_vec(), r.clone()))
2396                .collect();
2397            sorted.sort_by(|a, b| a.0.cmp(&b.0));
2398            if !sorted.is_empty() {
2399                new_btree
2400                    .bulk_insert_sorted(&sorted)
2401                    .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
2402            }
2403            self.btree_indices
2404                .write()
2405                .insert(name.to_string(), new_btree);
2406            self.mark_paged_registry_dirty();
2407        }
2408        Ok(())
2409    }
2410
2411    fn apply_replayed_refresh_collection(
2412        &self,
2413        collection: &str,
2414        records: &[Vec<u8>],
2415        update_btrees: bool,
2416    ) -> Result<(), StoreError> {
2417        let collection = Self::canonical_collection(collection);
2418        let (new_manager, prepared) = self.resident.prepare_replayed_refresh_collection(
2419            collection,
2420            records,
2421            self.format_version(),
2422            &self.config.manager_config,
2423        )?;
2424        self.swap_collection_state(collection, new_manager, &prepared, records, update_btrees)?;
2425        Ok(())
2426    }
2427
2428    /// Replica-side analogue of [`Self::refresh_collection`] — issue
2429    /// #596 slice 9d. Takes pre-serialized record bytes from the
2430    /// primary's CDC stream (the same bytes the primary wrote into the
2431    /// `RefreshCollection` WAL action), applies the atomic swap, and
2432    /// emits the same `RefreshCollection` WAL action against the
2433    /// replica's local store WAL so the post-swap state survives a
2434    /// replica restart through the normal recovery path.
2435    ///
2436    /// Idempotency: re-applying the same records bytes is a full
2437    /// rebuild from the same payload, so the resulting backing-
2438    /// collection contents are equal to the prior call's result.
2439    /// The primary-side `LogicalChangeApplier` short-circuits exact
2440    /// duplicate LSN+payload combinations before reaching here.
2441    pub fn refresh_collection_from_records(
2442        &self,
2443        name: &str,
2444        records: Vec<Vec<u8>>,
2445    ) -> Result<(), StoreError> {
2446        let name = Self::canonical_collection(name);
2447        self.apply_replayed_refresh_collection(name, &records, true)?;
2448        self.finish_paged_write([StoreWalAction::RefreshCollection {
2449            collection: name.to_string(),
2450            records,
2451        }])?;
2452        Ok(())
2453    }
2454
2455    pub(crate) fn create_collection_in_memory(&self, name: &str) -> Result<(), StoreError> {
2456        let name = Self::canonical_collection(name);
2457        self.resident
2458            .create_collection_in_memory(name, &self.config.manager_config)
2459    }
2460
2461    pub(super) fn drop_collection_in_memory(&self, name: &str) -> Result<(), StoreError> {
2462        let name = Self::canonical_collection(name);
2463        self.resident.drop_collection_in_memory(name, || {
2464            if let Some(tree) = self.btree_indices.write().remove(name) {
2465                self.retire_btree(tree);
2466            }
2467        })
2468    }
2469
2470    fn apply_replayed_upsert(
2471        &self,
2472        collection: &str,
2473        record: &[u8],
2474        update_btrees: bool,
2475    ) -> Result<(), StoreError> {
2476        let collection = Self::canonical_collection(collection);
2477        let id = self.resident.apply_replayed_upsert(
2478            collection,
2479            record,
2480            self.format_version(),
2481            &self.config.manager_config,
2482        )?;
2483
2484        let immutable = self.immutable_paged_base()?;
2485        if let Some(pager) = self.pager.as_ref().filter(|_| update_btrees && !immutable) {
2486            let mut btree_indices = self.btree_indices.write();
2487            let btree = btree_indices
2488                .entry(collection.to_string())
2489                .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
2490            let root_before = btree.root_page_id();
2491            let key = id.raw().to_be_bytes();
2492            match btree.insert(&key, record) {
2493                Ok(_) => {}
2494                Err(BTreeError::DuplicateKey) => {
2495                    let _ = btree.delete(&key);
2496                    let _ = btree.insert(&key, record);
2497                }
2498                Err(err) => {
2499                    return Err(StoreError::Io(io::Error::other(format!(
2500                        "replay upsert btree error: {err}"
2501                    ))));
2502                }
2503            }
2504            if root_before != btree.root_page_id() {
2505                self.mark_paged_registry_dirty();
2506            }
2507        }
2508
2509        Ok(())
2510    }
2511
2512    fn apply_replayed_delete(
2513        &self,
2514        collection: &str,
2515        id: EntityId,
2516        update_btrees: bool,
2517    ) -> Result<(), StoreError> {
2518        let collection = Self::canonical_collection(collection);
2519        let immutable = self.immutable_paged_base()?;
2520        self.resident.apply_replayed_delete(collection, id, || {
2521            if self.pager.is_some() && update_btrees && !immutable {
2522                let btree_indices = self.btree_indices.read();
2523                if let Some(btree) = btree_indices.get(collection) {
2524                    let root_before = btree.root_page_id();
2525                    let key = id.raw().to_be_bytes();
2526                    let _ = btree.delete(&key);
2527                    if root_before != btree.root_page_id() {
2528                        self.mark_paged_registry_dirty();
2529                    }
2530                }
2531            }
2532        })
2533    }
2534}
2535
2536#[cfg(all(test, target_os = "linux"))]
2537#[path = "storage_apocalypse.rs"]
2538mod storage_apocalypse;
2539
2540#[cfg(test)]
2541mod tests {
2542    use super::*;
2543    use crate::api::{DurabilityMode, GroupCommitOptions};
2544    use std::sync::{Barrier, Mutex as StdMutex, OnceLock};
2545    use std::time::SystemTime;
2546
2547    #[test]
2548    fn strict_flush_covers_only_appends_within_the_durable_end() {
2549        let directory = tempfile::tempdir().expect("temporary WAL directory");
2550        let path = directory.path().join("strict.wal");
2551        let coordinator = StoreCommitCoordinator::open(
2552            &path,
2553            DurabilityMode::Strict,
2554            GroupCommitOptions::default(),
2555        )
2556        .expect("open strict WAL");
2557        let _epoch = coordinator.queue.epoch.read();
2558        let append = |tx_id| {
2559            let mut wal = coordinator.wal.lock();
2560            wal.append(&WalRecord::Commit { tx_id }).expect("append");
2561            wal.current_lsn()
2562        };
2563
2564        // Both callers append before either gets the writer lock back to sync.
2565        let first = append(1);
2566        let second = append(2);
2567        coordinator.sync_wal(Some(first)).expect("first sync");
2568        assert_eq!(coordinator.state.0.lock().durable_lsn, second);
2569        coordinator.sync_wal(Some(second)).expect("already synced");
2570        assert_eq!(coordinator.fsync_count(), 1);
2571
2572        drop(_epoch);
2573        coordinator
2574            .append_single_record(WalRecord::Commit { tx_id: 3 })
2575            .expect("next record needs a new sync");
2576        let third = coordinator.wal.lock().current_lsn();
2577        assert_eq!(coordinator.fsync_count(), 2);
2578        coordinator.force_sync().expect("explicit barrier");
2579        assert_eq!(coordinator.fsync_count(), 3);
2580        let records = WalReader::open(&path)
2581            .expect("read strict WAL")
2582            .iter()
2583            .map(|item| item.map(|(_, record)| record))
2584            .collect::<io::Result<Vec<_>>>()
2585            .expect("decode commits");
2586        assert_eq!(
2587            records,
2588            (1..=3)
2589                .map(|tx_id| WalRecord::Commit { tx_id })
2590                .collect::<Vec<_>>()
2591        );
2592
2593        let _epoch = coordinator.queue.epoch.read();
2594        let fourth = append(4);
2595        coordinator.wal.lock().test_fail_flush_after(1);
2596        assert!(coordinator.sync_wal(Some(fourth)).is_err());
2597        assert!(coordinator.sync_wal(Some(third)).is_err());
2598        assert_eq!(coordinator.state.0.lock().durable_lsn, third);
2599        assert_eq!(coordinator.fsync_count(), 3);
2600    }
2601
2602    #[test]
2603    fn runtime_wal_retention_serializes_concurrent_appends() {
2604        let directory = tempfile::tempdir().expect("temporary WAL directory");
2605        let path = directory.path().join("data.wal");
2606        let coordinator = Arc::new(
2607            StoreCommitCoordinator::open(
2608                &path,
2609                DurabilityMode::WalDurableGrouped,
2610                GroupCommitOptions::default(),
2611            )
2612            .expect("coordinator"),
2613        );
2614        let barrier = Arc::new(Barrier::new(5));
2615        let mut workers = Vec::new();
2616        for worker in 0..4u8 {
2617            let coordinator = Arc::clone(&coordinator);
2618            let barrier = Arc::clone(&barrier);
2619            workers.push(std::thread::spawn(move || {
2620                barrier.wait();
2621                for index in 0..20u8 {
2622                    coordinator
2623                        .append_single_record(WalRecord::ProbabilisticDelta {
2624                            kind: 1,
2625                            operation: 1,
2626                            name: "visitors".into(),
2627                            operands: vec![vec![worker, index]],
2628                        })
2629                        .expect("append delta");
2630                }
2631            }));
2632        }
2633        barrier.wait();
2634        for _ in 0..5 {
2635            coordinator.truncate().expect("retain while appending");
2636        }
2637        for worker in workers {
2638            worker.join().expect("worker");
2639        }
2640        coordinator.truncate().expect("final retention");
2641        let entries: std::collections::HashSet<_> = WalReader::open(&path)
2642            .expect("reader")
2643            .iter()
2644            .map(|entry| match entry.expect("record").1 {
2645                WalRecord::ProbabilisticDelta { operands, .. } => operands[0].clone(),
2646                _ => panic!("unexpected retained record"),
2647            })
2648            .collect();
2649        assert_eq!(entries.len(), 80);
2650    }
2651
2652    #[test]
2653    fn checkpoint_boundary_preserves_later_transactions_and_runtime_frames() {
2654        use reddb_file::page_ownership_journal::PageOwnershipRecord;
2655        for mode in [
2656            DurabilityMode::Strict,
2657            DurabilityMode::WalDurableGrouped,
2658            DurabilityMode::Async,
2659        ] {
2660            for snapshot_durable in [false, true] {
2661                let directory = tempfile::tempdir().unwrap();
2662                let path = directory.path().join("data.wal");
2663                let coordinator =
2664                    StoreCommitCoordinator::open(&path, mode, GroupCommitOptions::default())
2665                        .unwrap();
2666                let delta = |value: u8| WalRecord::ProbabilisticDelta {
2667                    kind: 1,
2668                    operation: 1,
2669                    name: "visitors".into(),
2670                    operands: vec![vec![value]],
2671                };
2672                let create = |name: &str| StoreWalAction::CreateCollection { name: name.into() };
2673                coordinator.append_actions(&[create("before")]).unwrap();
2674                coordinator.append_single_record(delta(1)).unwrap();
2675                let boundary = coordinator.checkpoint_boundary();
2676                let stale = coordinator.checkpoint_boundary();
2677                coordinator
2678                    .append_durable_page_ownership(PageOwnershipRecord::Begin { epoch: 1 })
2679                    .unwrap();
2680                let mut page = crate::storage::engine::Page::new(
2681                    crate::storage::engine::PageType::BTreeLeaf,
2682                    100,
2683                );
2684                page.update_checksum();
2685                coordinator
2686                    .append_durable_ownership_bytes(
2687                        WalRecord::FullPageImage {
2688                            tx_id: 0,
2689                            page_id: 100,
2690                            ckpt_epoch: 1,
2691                            data: page.as_bytes().to_vec(),
2692                        }
2693                        .encode(),
2694                    )
2695                    .unwrap();
2696                let actions = [create("a"), create("b")];
2697                coordinator.append_actions(&actions).unwrap();
2698                coordinator.append_single_record(delta(2)).unwrap();
2699                coordinator
2700                    .append_durable_page_ownership(PageOwnershipRecord::Finish { epoch: 1 })
2701                    .unwrap();
2702                coordinator.release_completed_ownership_wal().unwrap();
2703                coordinator
2704                    .truncate_through(boundary, snapshot_durable)
2705                    .unwrap();
2706
2707                let bytes = std::fs::read(&path).unwrap();
2708                assert!(coordinator.truncate_through(stale, true).is_err());
2709                assert_eq!(std::fs::read(&path).unwrap(), bytes);
2710                let mut records = WalReader::open(&path)
2711                    .unwrap()
2712                    .iter()
2713                    .map(|entry| entry.unwrap().1);
2714                if !snapshot_durable {
2715                    assert_eq!(records.next(), Some(delta(1)));
2716                }
2717                let Some(WalRecord::TxCommitBatch {
2718                    actions: retained, ..
2719                }) = records.next()
2720                else {
2721                    panic!("later transaction missing");
2722                };
2723                assert_eq!(retained, actions.map(|action| action.encode()));
2724                assert_eq!(records.next(), Some(delta(2)));
2725                assert_eq!(records.next(), None);
2726
2727                coordinator.append_actions(&[create("after_trim")]).unwrap();
2728                let next = coordinator.checkpoint_boundary();
2729                coordinator.truncate_through(next, true).unwrap();
2730                assert_eq!(
2731                    std::fs::read(&path).unwrap(),
2732                    reddb_file::encode_wal_file_header()
2733                );
2734            }
2735        }
2736    }
2737
2738    #[test]
2739    fn checkpoint_boundary_recovers_later_batch_on_either_side_of_wal_replacement() {
2740        const CHILD: &str = "REDDB_TEST_WAL_BOUNDARY_DATABASE";
2741        if let Some(path) = std::env::var_os(CHILD) {
2742            let store = UnifiedStore::open(Path::new(&path)).unwrap();
2743            let commit = store.commit.as_ref().unwrap();
2744            let boundary = commit.checkpoint_boundary();
2745            let rows = [101, 102].map(|id| {
2746                let entity = UnifiedEntity::table_row(EntityId::new(id), "rows", id, vec![]);
2747                StoreWalAction::UpsertEntityRecord {
2748                    collection: "rows".into(),
2749                    record: UnifiedStore::serialize_entity_record(
2750                        &entity,
2751                        None,
2752                        store.format_version(),
2753                    ),
2754                }
2755            });
2756            commit.append_actions(&rows).unwrap();
2757            commit.truncate_through(boundary, true).unwrap();
2758            panic!("WAL publication interruption was not reached");
2759        }
2760        for (hook, code) in [
2761            ("REDDB_TEST_EXIT_BEFORE_RUNTIME_WAL_RENAME", 211),
2762            ("REDDB_TEST_EXIT_AFTER_RUNTIME_WAL_RENAME", 212),
2763        ] {
2764            let directory = tempfile::tempdir().unwrap();
2765            let path = directory.path().join("checkpoint.rdb");
2766            {
2767                let store = UnifiedStore::open(&path).unwrap();
2768                store.create_collection("rows").unwrap();
2769                store.persist().unwrap();
2770            }
2771            let child = std::process::Command::new(std::env::current_exe().unwrap())
2772                .args(["--exact", "storage::unified::store::commit::tests::checkpoint_boundary_recovers_later_batch_on_either_side_of_wal_replacement"])
2773                .env(CHILD, &path)
2774                .env(hook, "1")
2775                .output().unwrap();
2776            assert_eq!(
2777                child.status.code(),
2778                Some(code),
2779                "{}",
2780                String::from_utf8_lossy(&child.stderr)
2781            );
2782            let recovered = UnifiedStore::open(&path).unwrap();
2783            for id in [101, 102] {
2784                assert_eq!(
2785                    recovered.get("rows", EntityId::new(id)).unwrap().id.raw(),
2786                    id
2787                );
2788            }
2789        }
2790    }
2791
2792    #[test]
2793    fn runtime_wal_retention_preserves_exact_frames_and_append_order() {
2794        use crate::storage::wal::record::WalRecordAuthority;
2795        for mode in [
2796            DurabilityMode::Strict,
2797            DurabilityMode::WalDurableGrouped,
2798            DurabilityMode::Async,
2799        ] {
2800            let directory = tempfile::tempdir().expect("temporary WAL directory");
2801            let path = directory.path().join("data.wal");
2802            let record = WalRecord::ProbabilisticDelta {
2803                kind: 1,
2804                operation: 1,
2805                name: "visitors".into(),
2806                operands: vec![b"alice".to_vec()],
2807            };
2808            let mut frame = Vec::new();
2809            record.encode_with_authority_into(
2810                &mut frame,
2811                WalRecordAuthority {
2812                    term: 42,
2813                    ownership_epoch: Some(9),
2814                },
2815            );
2816            {
2817                let mut writer = WalWriter::open(&path).expect("WAL writer");
2818                writer
2819                    .append(&WalRecord::Begin { tx_id: 1 })
2820                    .expect("logical begin");
2821                writer.append_bytes(&frame).expect("runtime record");
2822                writer
2823                    .append(&WalRecord::Commit { tx_id: 1 })
2824                    .expect("logical commit");
2825                writer.sync().expect("sync");
2826            }
2827            let coordinator =
2828                StoreCommitCoordinator::open(&path, mode, GroupCommitOptions::default())
2829                    .expect("coordinator");
2830            coordinator.truncate().expect("retain runtime records");
2831            let mut expected = reddb_file::encode_wal_file_header().to_vec();
2832            expected.extend_from_slice(&frame);
2833            assert_eq!(std::fs::read(&path).expect("retained WAL"), expected);
2834            let later = WalRecord::ProbabilisticDelta {
2835                kind: 1,
2836                operation: 1,
2837                name: "visitors".into(),
2838                operands: vec![b"bob".to_vec()],
2839            };
2840            coordinator
2841                .append_single_record(later.clone())
2842                .expect("append after rewrite");
2843            coordinator.truncate().expect("retain queued record");
2844            let records: Vec<_> = WalReader::open(&path)
2845                .expect("reader")
2846                .iter()
2847                .map(|entry| entry.expect("record").1)
2848                .collect();
2849            assert_eq!(records, vec![record, later]);
2850            coordinator
2851                .truncate_through(coordinator.checkpoint_boundary(), true)
2852                .expect("runtime snapshot permits truncation");
2853            assert_eq!(
2854                std::fs::read(&path).expect("checkpointed WAL"),
2855                reddb_file::encode_wal_file_header()
2856            );
2857        }
2858    }
2859
2860    #[test]
2861    fn runtime_wal_rewrite_survives_interruption() {
2862        const TEST: &str =
2863            "storage::unified::store::commit::tests::runtime_wal_rewrite_survives_interruption";
2864        const CHILD: &str = "REDDB_TEST_RUNTIME_WAL_REWRITE_PATH";
2865        if let Some(path) = std::env::var_os(CHILD) {
2866            let coordinator = StoreCommitCoordinator::open(
2867                path,
2868                DurabilityMode::Strict,
2869                GroupCommitOptions::default(),
2870            )
2871            .expect("child coordinator");
2872            coordinator.truncate().expect("fault injection");
2873            panic!("interruption point was not reached");
2874        }
2875        for (hook, code, replaced) in [
2876            ("REDDB_TEST_EXIT_BEFORE_RUNTIME_WAL_RENAME", 211, false),
2877            ("REDDB_TEST_EXIT_AFTER_RUNTIME_WAL_RENAME", 212, true),
2878        ] {
2879            let directory = tempfile::tempdir().expect("temporary WAL directory");
2880            let path = directory.path().join("data.wal");
2881            let record = WalRecord::ProbabilisticDelta {
2882                kind: 1,
2883                operation: 1,
2884                name: "visitors".into(),
2885                operands: vec![b"alice".to_vec()],
2886            };
2887            {
2888                let mut writer = WalWriter::open(&path).expect("WAL writer");
2889                writer
2890                    .append(&WalRecord::Begin { tx_id: 1 })
2891                    .expect("begin");
2892                writer.append(&record).expect("runtime record");
2893                writer
2894                    .append(&WalRecord::Commit { tx_id: 1 })
2895                    .expect("commit");
2896                writer.sync().expect("sync");
2897            }
2898            let original = std::fs::read(&path).expect("original WAL");
2899            let child =
2900                std::process::Command::new(std::env::current_exe().expect("test executable"))
2901                    .args(["--exact", TEST, "--nocapture"])
2902                    .env(CHILD, &path)
2903                    .env(hook, "1")
2904                    .output()
2905                    .expect("child");
2906            assert_eq!(
2907                child.status.code(),
2908                Some(code),
2909                "{}",
2910                String::from_utf8_lossy(&child.stderr)
2911            );
2912            let after = std::fs::read(&path).expect("WAL after interruption");
2913            if replaced {
2914                let mut expected = reddb_file::encode_wal_file_header().to_vec();
2915                expected.extend_from_slice(&record.encode());
2916                assert_eq!(after, expected);
2917            } else {
2918                assert_eq!(after, original);
2919            }
2920            let coordinator = StoreCommitCoordinator::open(
2921                &path,
2922                DurabilityMode::Strict,
2923                GroupCommitOptions::default(),
2924            )
2925            .expect("reopen");
2926            coordinator.truncate().expect("retry rewrite");
2927            let records: Vec<_> = WalReader::open(&path)
2928                .expect("reader")
2929                .iter()
2930                .map(|entry| entry.expect("record").1)
2931                .collect();
2932            assert_eq!(records, vec![record]);
2933        }
2934    }
2935
2936    #[test]
2937    fn ownership_epoch_rejects_nested_begin_and_wrong_finish() {
2938        let directory = tempfile::tempdir().expect("temporary store");
2939        let store = UnifiedStore::open(directory.path().join("data.rdb")).expect("store");
2940        store.create_collection("rows").expect("collection");
2941        store.persist().expect("baseline");
2942        let coordinator = store.commit.as_ref().expect("WAL coordinator");
2943        assert!(coordinator.begin_page_ownership_epoch(&store, 0).is_err());
2944        assert!(coordinator.finish_page_ownership_epoch(&store, 1).is_err());
2945        coordinator
2946            .begin_page_ownership_epoch(&store, 2)
2947            .expect("begin epoch");
2948        assert!(coordinator.begin_page_ownership_epoch(&store, 3).is_err());
2949        assert!(coordinator.finish_page_ownership_epoch(&store, 3).is_err());
2950        assert!(coordinator.finish_page_ownership_epoch(&store, 2).is_err());
2951        store.flush_paged_registry().expect("publish epoch");
2952        coordinator
2953            .finish_page_ownership_epoch(&store, 2)
2954            .expect("finish epoch");
2955        assert_eq!(store.ownership_active_epoch.load(Ordering::Acquire), 0);
2956    }
2957
2958    /// A checkpoint frees a page for every node it replaces. Recovery acts on
2959    /// a retirement only once its generation is published, so until then the
2960    /// record is queued; after that it is awaited again.
2961    #[test]
2962    fn a_deferred_retirement_waits_only_once_the_generation_is_published() {
2963        use crate::storage::engine::pager::PageOwnershipRecorder;
2964        use reddb_file::page_ownership_journal::PageOwnershipRecord;
2965
2966        let directory = tempfile::tempdir().expect("temporary store");
2967        let wal_path = directory.path().join("ownership.wal");
2968        let coordinator = Arc::new(
2969            StoreCommitCoordinator::open(
2970                &wal_path,
2971                DurabilityMode::Strict,
2972                GroupCommitOptions::default(),
2973            )
2974            .expect("open WAL"),
2975        );
2976        let recorder =
2977            StoreOwnershipRecorder::begin(Arc::clone(&coordinator), 7).expect("begin epoch");
2978        // A page reserved for the unpublished generation is nobody's to read:
2979        // its home write needs no double-write frame.
2980        recorder.reserve_pages(90, 2).expect("reserve");
2981        recorder.flush_page_ownership().expect("flush reservations");
2982        assert!(recorder.unpublished_reservation(90));
2983        assert!(recorder.unpublished_reservation(91));
2984        assert!(!recorder.unpublished_reservation(92), "never reserved");
2985        let begun = coordinator.fsync_count();
2986
2987        recorder.retire_deferred_page(70).expect("queue");
2988        recorder.retire_deferred_page(71).expect("queue");
2989        assert_eq!(
2990            coordinator.fsync_count(),
2991            begun,
2992            "a retirement of an unpublished generation was awaited"
2993        );
2994        recorder.flush_page_ownership().expect("flush");
2995        assert_eq!(
2996            coordinator.fsync_count(),
2997            begun + 1,
2998            "one sync makes both durable"
2999        );
3000
3001        recorder.generation_published();
3002        assert!(
3003            !recorder.unpublished_reservation(90),
3004            "a published page is double-written again"
3005        );
3006        recorder.retire_deferred_page(72).expect("durable");
3007        assert_eq!(
3008            coordinator.fsync_count(),
3009            begun + 2,
3010            "a retirement of a published generation was not awaited"
3011        );
3012
3013        let records: Vec<_> = WalReader::open(&wal_path)
3014            .expect("read WAL")
3015            .iter()
3016            .map(|item| item.expect("WAL record").1)
3017            .collect();
3018        let retire = |page_id| WalRecord::PageOwnership {
3019            record: PageOwnershipRecord::Retire { epoch: 7, page_id },
3020        };
3021        let reserve = |page_id| WalRecord::PageOwnership {
3022            record: PageOwnershipRecord::Reserve { epoch: 7, page_id },
3023        };
3024        assert_eq!(
3025            records,
3026            vec![
3027                WalRecord::PageOwnership {
3028                    record: PageOwnershipRecord::Begin { epoch: 7 }
3029                },
3030                reserve(90),
3031                reserve(91),
3032                retire(70),
3033                retire(71),
3034                retire(72),
3035            ]
3036        );
3037    }
3038
3039    #[test]
3040    fn native_pager_records_page_ownership_in_durable_wal() {
3041        use reddb_file::page_ownership_journal::PageOwnershipRecord;
3042
3043        let directory = tempfile::tempdir().expect("temporary store");
3044        let path = directory.path().join("data.rdb");
3045        let wal_path = reddb_file::layout::unified_wal_path(&path);
3046        let pager = crate::storage::engine::Pager::open(&path, Default::default())
3047            .expect("open native pager");
3048        let coordinator = Arc::new(
3049            StoreCommitCoordinator::open(
3050                &wal_path,
3051                DurabilityMode::Async,
3052                GroupCommitOptions::default(),
3053            )
3054            .expect("open WAL"),
3055        );
3056        let recorder = Arc::new(
3057            StoreOwnershipRecorder::begin(Arc::clone(&coordinator), 7).expect("begin epoch"),
3058        );
3059        pager
3060            .install_ownership_recorder(recorder)
3061            .expect("install recorder");
3062        let page = pager
3063            .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3064            .expect("allocate")
3065            .page_id();
3066        pager
3067            .record_retirement_intent(&[page])
3068            .expect("record retirement");
3069        pager.free_retired_pages(&[page]).expect("retire");
3070        let records: Vec<_> = WalReader::open(&wal_path)
3071            .expect("read WAL")
3072            .iter()
3073            .map(|item| item.expect("WAL record").1)
3074            .collect();
3075        assert_eq!(
3076            records,
3077            vec![
3078                WalRecord::PageOwnership {
3079                    record: PageOwnershipRecord::Begin { epoch: 7 }
3080                },
3081                WalRecord::PageOwnership {
3082                    record: PageOwnershipRecord::Reserve {
3083                        epoch: 7,
3084                        page_id: page
3085                    }
3086                },
3087                WalRecord::PageOwnership {
3088                    record: PageOwnershipRecord::Retire {
3089                        epoch: 7,
3090                        page_id: page
3091                    }
3092                },
3093                WalRecord::PageOwnership {
3094                    record: PageOwnershipRecord::Retire {
3095                        epoch: 7,
3096                        page_id: page
3097                    }
3098                },
3099            ]
3100        );
3101        assert!(
3102            coordinator.fsync_count() >= 3,
3103            "async ownership writes must sync"
3104        );
3105        assert!(
3106            coordinator.truncate().is_err(),
3107            "ownership WAL remains protected"
3108        );
3109    }
3110
3111    #[test]
3112    fn reservations_and_page_images_are_queued_and_durable_before_a_page_reaches_the_file() {
3113        use reddb_file::page_ownership_journal::PageOwnershipRecord;
3114
3115        for mode in [DurabilityMode::Strict, DurabilityMode::WalDurableGrouped] {
3116            let directory = tempfile::tempdir().expect("temporary store");
3117            let path = directory.path().join("data.rdb");
3118            let wal_path = reddb_file::layout::unified_wal_path(&path);
3119            let pager = crate::storage::engine::Pager::open(&path, Default::default())
3120                .expect("open native pager");
3121            let coordinator = Arc::new(
3122                StoreCommitCoordinator::open(&wal_path, mode, GroupCommitOptions::default())
3123                    .expect("open WAL"),
3124            );
3125            // Pages of an earlier generation: overwriting one needs its image.
3126            let published: Vec<_> = (0..8)
3127                .map(|_| {
3128                    pager
3129                        .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3130                        .expect("allocate")
3131                })
3132                .collect();
3133            pager.flush().expect("publish earlier pages");
3134            let recorder = Arc::new(
3135                StoreOwnershipRecorder::begin(Arc::clone(&coordinator), 7).expect("begin epoch"),
3136            );
3137            pager
3138                .install_ownership_recorder(recorder)
3139                .expect("install recorder");
3140            let syncs = coordinator.fsync_count();
3141            for page in &published {
3142                pager
3143                    .write_page(page.page_id(), page.clone())
3144                    .expect("overwrite");
3145            }
3146            let pages: Vec<u32> = (0..48)
3147                .map(|_| {
3148                    pager
3149                        .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3150                        .expect("allocate")
3151                        .page_id()
3152                })
3153                .collect();
3154            assert!(
3155                coordinator.deferred_ownership.lock().is_some(),
3156                "{mode:?}: reservations were not queued"
3157            );
3158            if mode == DurabilityMode::Strict {
3159                assert_eq!(
3160                    coordinator.fsync_count(),
3161                    syncs,
3162                    "a reservation or a page image waited for its own sync"
3163                );
3164            }
3165
3166            // The first page to reach the file takes every reservation with it.
3167            pager.flush().expect("flush");
3168            assert!(
3169                coordinator.deferred_ownership.lock().is_none(),
3170                "{mode:?}: a page reached the file ahead of its reservation"
3171            );
3172            let mut images = Vec::new();
3173            let reserved: Vec<u32> = WalReader::open(&wal_path)
3174                .expect("read WAL")
3175                .iter()
3176                .filter_map(|item| match item.expect("WAL record").1 {
3177                    WalRecord::PageOwnership {
3178                        record: PageOwnershipRecord::Reserve { epoch: 7, page_id },
3179                    } => Some(page_id),
3180                    WalRecord::FullPageImage { page_id, .. } => {
3181                        images.push(page_id);
3182                        None
3183                    }
3184                    _ => None,
3185                })
3186                .collect();
3187            assert_eq!(reserved, pages, "{mode:?}");
3188            assert_eq!(
3189                images,
3190                published
3191                    .iter()
3192                    .map(|page| page.page_id())
3193                    .collect::<Vec<_>>(),
3194                "{mode:?}"
3195            );
3196            if mode == DurabilityMode::Strict {
3197                assert!(
3198                    coordinator.fsync_count() - syncs < pages.len() as u64 / 4,
3199                    "the reservations and images were not flushed together"
3200                );
3201            }
3202        }
3203    }
3204
3205    #[test]
3206    fn replay_reclaims_unpublished_ownership_reservations() {
3207        use reddb_file::page_ownership_journal::PageOwnershipRecord;
3208
3209        let directory = tempfile::tempdir().expect("temporary store");
3210        let path = directory.path().join("data.rdb");
3211        {
3212            let store = UnifiedStore::open(&path).expect("create store");
3213            store.create_collection("rows").expect("collection");
3214            store.persist().expect("persist baseline");
3215        }
3216        let wal_path = reddb_file::layout::unified_wal_path(&path);
3217        let ids;
3218        {
3219            let pager =
3220                crate::storage::engine::Pager::open(&path, Default::default()).expect("pager");
3221            let first = pager.page_count().expect("page count");
3222            let coordinator = StoreCommitCoordinator::open(
3223                &wal_path,
3224                DurabilityMode::Strict,
3225                GroupCommitOptions::default(),
3226            )
3227            .expect("WAL");
3228            coordinator
3229                .append_durable_page_ownership_batch(&[
3230                    PageOwnershipRecord::Begin { epoch: 2 },
3231                    PageOwnershipRecord::Reserve {
3232                        epoch: 2,
3233                        page_id: first,
3234                    },
3235                    PageOwnershipRecord::Reserve {
3236                        epoch: 2,
3237                        page_id: first + 1,
3238                    },
3239                ])
3240                .expect("reserve pages durably");
3241            ids = [
3242                pager
3243                    .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3244                    .expect("allocate")
3245                    .page_id(),
3246                pager
3247                    .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3248                    .expect("allocate")
3249                    .page_id(),
3250            ];
3251            assert_eq!(ids, [first, first + 1]);
3252            pager.sync().expect("persist abandoned pages");
3253        }
3254        let reopened = UnifiedStore::open(&path).expect("recover ownership");
3255        let pager = reopened.pager.as_ref().expect("pager");
3256        let a = pager
3257            .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3258            .expect("reuse")
3259            .page_id();
3260        let b = pager
3261            .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3262            .expect("reuse")
3263            .page_id();
3264        assert_ne!(a, b);
3265        assert!(ids.contains(&a) && ids.contains(&b));
3266        let records: Vec<_> = WalReader::open(&wal_path)
3267            .expect("read WAL")
3268            .iter()
3269            .collect::<io::Result<Vec<_>>>()
3270            .expect("records");
3271        assert!(matches!(
3272            records.last(),
3273            Some((
3274                _,
3275                WalRecord::PageOwnership {
3276                    record: PageOwnershipRecord::Finish { epoch: 2 }
3277                }
3278            ))
3279        ));
3280        reopened
3281            .commit
3282            .as_ref()
3283            .expect("coordinator")
3284            .truncate()
3285            .expect("completed ownership can be truncated");
3286    }
3287
3288    #[cfg(target_os = "linux")]
3289    #[test]
3290    fn ownership_recovery_survives_interruption_and_retry() {
3291        use reddb_file::page_ownership_journal::PageOwnershipRecord;
3292
3293        const CHILD: &str = "REDDB_EXPERIMENTAL_OWNERSHIP_RECOVERY_PATH";
3294        if let Some(path) = std::env::var_os(CHILD) {
3295            let _store = UnifiedStore::open(path).expect("recover store");
3296            panic!("recovery interruption hook was not reached");
3297        }
3298        for (published, hook, exit_code) in [
3299            (
3300                false,
3301                "REDDB_EXPERIMENTAL_EXIT_DURING_OWNERSHIP_RECOVERY",
3302                187,
3303            ),
3304            (false, "REDDB_EXPERIMENTAL_EXIT_AFTER_OWNERSHIP_SYNC", 188),
3305            (false, "REDDB_EXPERIMENTAL_EXIT_AFTER_OWNERSHIP_FINISH", 189),
3306            (
3307                true,
3308                "REDDB_EXPERIMENTAL_EXIT_DURING_OWNERSHIP_RECOVERY",
3309                187,
3310            ),
3311            (true, "REDDB_EXPERIMENTAL_EXIT_AFTER_OWNERSHIP_SYNC", 188),
3312            (true, "REDDB_EXPERIMENTAL_EXIT_AFTER_OWNERSHIP_FINISH", 189),
3313        ] {
3314            let directory = tempfile::tempdir().expect("temporary store");
3315            let path = directory.path().join("data.rdb");
3316            {
3317                let store = UnifiedStore::open(&path).expect("create store");
3318                store.create_collection("rows").expect("collection");
3319                store.persist().expect("baseline");
3320                if published {
3321                    store.ownership_active_epoch.store(2, Ordering::Release);
3322                    store.flush_paged_registry().expect("publish epoch");
3323                    store.ownership_active_epoch.store(0, Ordering::Release);
3324                }
3325            }
3326            let wal_path = reddb_file::layout::unified_wal_path(&path);
3327            let ids;
3328            {
3329                let pager =
3330                    crate::storage::engine::Pager::open(&path, Default::default()).expect("pager");
3331                let first = pager.page_count().expect("page count");
3332                let coordinator = StoreCommitCoordinator::open(
3333                    &wal_path,
3334                    DurabilityMode::Strict,
3335                    GroupCommitOptions::default(),
3336                )
3337                .expect("WAL");
3338                let intent = |page_id| {
3339                    if published {
3340                        PageOwnershipRecord::Retire { epoch: 2, page_id }
3341                    } else {
3342                        PageOwnershipRecord::Reserve { epoch: 2, page_id }
3343                    }
3344                };
3345                coordinator
3346                    .append_durable_page_ownership_batch(&[
3347                        PageOwnershipRecord::Begin { epoch: 2 },
3348                        intent(first),
3349                        intent(first + 1),
3350                    ])
3351                    .expect("reserve");
3352                ids = [
3353                    pager
3354                        .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3355                        .expect("allocate")
3356                        .page_id(),
3357                    pager
3358                        .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3359                        .expect("allocate")
3360                        .page_id(),
3361                ];
3362                pager.sync().expect("persist abandoned pages");
3363            }
3364            for _ in 0..if exit_code == 189 { 1 } else { 2 } {
3365                let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
3366                    .args(["--exact", "storage::unified::store::commit::tests::ownership_recovery_survives_interruption_and_retry", "--nocapture"])
3367                    .env(CHILD, &path)
3368                    .env(hook, "1")
3369                    .output().expect("run interrupted recovery");
3370                assert_eq!(
3371                    output.status.code(),
3372                    Some(exit_code),
3373                    "published={published} {hook}: {}",
3374                    String::from_utf8_lossy(&output.stderr)
3375                );
3376            }
3377            let reopened = UnifiedStore::open(&path).expect("recover after interruptions");
3378            let pager = reopened.pager.as_ref().expect("pager");
3379            let a = pager
3380                .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3381                .expect("reuse")
3382                .page_id();
3383            let b = pager
3384                .allocate_page(crate::storage::engine::PageType::BTreeLeaf)
3385                .expect("reuse")
3386                .page_id();
3387            assert_ne!(a, b, "published={published} {hook}: duplicate page");
3388            assert!(
3389                ids.contains(&a) && ids.contains(&b),
3390                "published={published} {hook}: lost recovered page"
3391            );
3392        }
3393    }
3394
3395    #[test]
3396    fn ownership_intents_are_durable_in_every_mode() {
3397        use reddb_file::page_ownership_journal::PageOwnershipRecord;
3398
3399        for mode in [
3400            DurabilityMode::Strict,
3401            DurabilityMode::WalDurableGrouped,
3402            DurabilityMode::Async,
3403        ] {
3404            let directory = tempfile::tempdir().expect("temporary WAL");
3405            let path = directory.path().join("ownership");
3406            let coordinator =
3407                StoreCommitCoordinator::open(&path, mode, GroupCommitOptions::default())
3408                    .expect("open coordinator");
3409            let intent = PageOwnershipRecord::Reserve {
3410                epoch: 1,
3411                page_id: 67,
3412            };
3413            let detach = PageOwnershipRecord::DetachFree {
3414                epoch: 1,
3415                page_id: 68,
3416            };
3417            coordinator
3418                .append_durable_page_ownership_batch(&[intent, detach])
3419                .expect("durable intent");
3420            assert!(
3421                coordinator.fsync_count() > 0,
3422                "ownership intent must be synced in {mode:?}"
3423            );
3424            let records: Vec<_> = WalReader::open(&path)
3425                .expect("open WAL")
3426                .iter()
3427                .collect::<io::Result<Vec<_>>>()
3428                .expect("read records");
3429            assert!(
3430                matches!(records.as_slice(), [(_, WalRecord::PageOwnership { record: first }), (_, WalRecord::PageOwnership { record: second })] if *first == intent && *second == detach)
3431            );
3432            assert!(coordinator
3433                .append_single_record(WalRecord::PageOwnership { record: intent })
3434                .is_err());
3435            assert!(coordinator
3436                .append_durable_page_ownership(PageOwnershipRecord::Begin { epoch: 0 })
3437                .is_err());
3438            assert!(
3439                coordinator.truncate().is_err(),
3440                "active ownership must prevent truncation"
3441            );
3442            let before = std::fs::read(&path).expect("ownership WAL");
3443            drop(coordinator);
3444            let reopened = StoreCommitCoordinator::open(&path, mode, GroupCommitOptions::default())
3445                .expect("reopen coordinator");
3446            assert!(
3447                reopened.truncate().is_err(),
3448                "reopen must rediscover ownership records"
3449            );
3450            assert_eq!(std::fs::read(&path).expect("preserved WAL"), before);
3451        }
3452    }
3453
3454    #[test]
3455    fn unresolved_ownership_intent_blocks_store_replay() {
3456        for truncated in [false, true] {
3457            let directory = tempfile::tempdir().expect("temporary store");
3458            let path = directory.path().join("data.rdb");
3459            {
3460                let store = UnifiedStore::open(&path).expect("create store");
3461                store.create_collection("rows").expect("create collection");
3462                store.persist().expect("persist baseline");
3463            }
3464            let wal_path = reddb_file::layout::unified_wal_path(&path);
3465            {
3466                let mut writer = WalWriter::open(&wal_path).expect("open WAL");
3467                writer
3468                    .append(&WalRecord::PageOwnership {
3469                        record: reddb_file::page_ownership_journal::PageOwnershipRecord::Reserve {
3470                            epoch: 1,
3471                            page_id: 67,
3472                        },
3473                    })
3474                    .expect("append ownership intent");
3475                writer.sync().expect("sync ownership intent");
3476            }
3477            if truncated {
3478                let wal = std::fs::OpenOptions::new()
3479                    .write(true)
3480                    .open(&wal_path)
3481                    .expect("WAL");
3482                let length = wal.metadata().expect("length").len();
3483                wal.set_len(length - 1).expect("truncate last byte");
3484                wal.sync_all().expect("sync truncation");
3485            }
3486            let before = std::fs::read(&path).expect("baseline data");
3487            let error = match UnifiedStore::open(&path) {
3488                Ok(_) => panic!("unresolved ownership must prevent opening"),
3489                Err(error) => error,
3490            };
3491            let expected = if truncated {
3492                "incomplete page ownership WAL record"
3493            } else {
3494                "page ownership journal requires recovery"
3495            };
3496            assert!(error.to_string().contains(expected), "{error}");
3497            assert_eq!(std::fs::read(&path).expect("preserved data"), before);
3498        }
3499    }
3500
3501    #[test]
3502    fn logical_wal_replay_restores_a_deleted_physical_identity() {
3503        for flat in [false, true] {
3504            let store = UnifiedStore::new();
3505            store.create_collection("replay").expect("collection");
3506            let id = EntityId::new(42);
3507            let entity = UnifiedEntity::table_row(id, "replay", 42, vec![Value::Integer(1)]);
3508            if flat {
3509                store
3510                    .bulk_insert("replay", vec![entity])
3511                    .expect("flat seed");
3512            } else {
3513                store.insert_auto("replay", entity).expect("hash seed");
3514            }
3515            let metadata = Metadata::with_fields(HashMap::from([(
3516                "source".into(),
3517                MetadataValue::String("wal".into()),
3518            )]));
3519            for sequence in 100..104 {
3520                let delete = StoreWalAction::DeleteEntityRecord {
3521                    collection: "replay".into(),
3522                    entity_id: id.raw(),
3523                };
3524                store
3525                    .apply_encoded_store_wal_action(&delete.encode())
3526                    .expect("replay delete");
3527                let mut restored =
3528                    UnifiedEntity::table_row(id, "replay", 42, vec![Value::Integer(2)]);
3529                restored.ensure_table_logical_id();
3530                restored.sequence_id = sequence;
3531                let upsert = StoreWalAction::upsert_entity(
3532                    "replay",
3533                    &restored,
3534                    Some(&metadata),
3535                    store.format_version(),
3536                );
3537                store
3538                    .apply_encoded_store_wal_action(&upsert.encode())
3539                    .expect("replay upsert");
3540                let manager = store.get_collection("replay").expect("restored collection");
3541                let stored = manager.get(id).expect("restored entity is readable");
3542                assert_eq!(store.entity_cache_stats().entries, 0);
3543                assert_eq!(manager.count(), 1);
3544                assert_eq!(manager.query_all(|_| true).len(), 1);
3545                assert_eq!(stored.sequence_id, sequence);
3546                assert_eq!(
3547                    UnifiedStore::serialize_entity_record(
3548                        &stored,
3549                        manager.get_metadata(id).as_ref(),
3550                        store.format_version()
3551                    ),
3552                    UnifiedStore::serialize_entity_record(
3553                        &restored,
3554                        Some(&metadata),
3555                        store.format_version()
3556                    )
3557                );
3558                assert!(store.get_any(id).is_some());
3559            }
3560        }
3561    }
3562
3563    fn embedded_fixture(
3564        mode: DurabilityMode,
3565        background_bytes: usize,
3566    ) -> (tempfile::TempDir, PathBuf, UnifiedStore) {
3567        let directory = tempfile::tempdir().expect("directory");
3568        let path = directory.path().join("data.rdb");
3569        let mut store =
3570            UnifiedStore::with_config(UnifiedStoreConfig::default().with_durability_mode(mode));
3571        store.create_collection("keys").expect("collection");
3572        store.set_aux_metadata(vec![42; background_bytes]);
3573        crate::storage::EmbeddedRdbArtifact::create_with_snapshot(
3574            &path,
3575            &store.to_binary_dump_bytes(),
3576        )
3577        .expect("snapshot");
3578        store.config.embedded_wal_path = Some(path.clone());
3579        (directory, path, store)
3580    }
3581
3582    #[test]
3583    fn embedded_stale_full_result_does_not_checkpoint_reclaimed_space() {
3584        for mode in [DurabilityMode::Strict, DurabilityMode::WalDurableGrouped] {
3585            let (_directory, path, store) = embedded_fixture(mode, 0);
3586            store
3587                .append_embedded_store_wal_actions(&[StoreWalAction::CreateCollection {
3588                    name: "keys".into(),
3589                }])
3590                .expect("another writer appended after reclaiming space");
3591            let before = crate::storage::EmbeddedRdbArtifact::open(&path).expect("before");
3592            let payloads = vec![StoreWalAction::CreateCollection {
3593                name: "after".into(),
3594            }
3595            .encode()];
3596            let length = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
3597                .expect("encoded length");
3598            // Model a full result obtained before that other writer's checkpoint.
3599            store
3600                .recover_full_embedded_wal(&path, &payloads, length)
3601                .expect("revalidate after acquiring publication");
3602            let after = crate::storage::EmbeddedRdbArtifact::open(&path).expect("after");
3603            assert_eq!(
3604                after.selected_superblock.generation,
3605                before.selected_superblock.generation + 1,
3606                "only the retry is published, without an unnecessary checkpoint"
3607            );
3608            assert_eq!(
3609                crate::storage::EmbeddedRdbArtifact::read_wal_payloads(&after)
3610                    .expect("both appends retained")
3611                    .len(),
3612                2
3613            );
3614        }
3615    }
3616
3617    #[test]
3618    fn embedded_full_wal_reserves_bounded_headroom_for_populated_store() {
3619        for mode in [DurabilityMode::Strict, DurabilityMode::WalDurableGrouped] {
3620            let (_directory, path, store) = embedded_fixture(mode, 2 * 1024 * 1024);
3621            let initial = crate::storage::EmbeddedRdbArtifact::open(&path).expect("initial");
3622            let action = StoreWalAction::CreateCollection {
3623                name: "keys".into(),
3624            };
3625            let payloads = vec![action.encode()];
3626            let length = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
3627                .expect("encoded length");
3628            crate::storage::EmbeddedRdbArtifact::append_wal_payloads(
3629                &path,
3630                &vec![payloads[0].clone(); (initial.manifest.wal_region_bytes / length) as usize],
3631            )
3632            .expect("fill the initial region with valid records");
3633            store
3634                .append_embedded_store_wal_actions(&[action])
3635                .expect("overflow");
3636            let open = crate::storage::EmbeddedRdbArtifact::open(&path).expect("checkpoint");
3637            assert_eq!(open.manifest.wal_region_bytes, 1024 * 1024);
3638            let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
3639                .expect("snapshot")
3640                .expect("populated image");
3641            let recovered =
3642                UnifiedStore::load_from_bytes_with_config(&snapshot, UnifiedStoreConfig::default())
3643                    .expect("recover snapshot");
3644            for payload in
3645                crate::storage::EmbeddedRdbArtifact::read_wal_payloads(&open).expect("WAL")
3646            {
3647                recovered
3648                    .apply_encoded_store_wal_action(&payload)
3649                    .expect("replay");
3650            }
3651            assert_eq!(
3652                recovered.resident.aux_metadata.read().len(),
3653                2 * 1024 * 1024
3654            );
3655            assert!(recovered.get_collection("keys").is_some());
3656        }
3657    }
3658
3659    #[test]
3660    fn embedded_grouped_overwrites_recover_across_repeated_full_wal_regions() {
3661        fn row(writer: usize, round: usize) -> UnifiedEntity {
3662            let mut state = (writer as u64 + 1) * 31 + round as u64 * 13;
3663            let payload: String = (0..4096)
3664                .map(|_| {
3665                    state = state.wrapping_mul(1664525).wrapping_add(1013904223);
3666                    char::from(b'!' + ((state >> 24) % 90) as u8)
3667                })
3668                .collect();
3669            let mut entity = UnifiedEntity::table_row(EntityId::new(0), "keys", 0, vec![]);
3670            entity.data = EntityData::Row(RowData::with_names(
3671                vec![
3672                    Value::text(format!("k{writer}")),
3673                    Value::text(format!("{round}:{payload}")),
3674                ],
3675                vec!["key".into(), "value".into()],
3676            ));
3677            entity
3678        }
3679        let (_directory, path, store) =
3680            embedded_fixture(DurabilityMode::WalDurableGrouped, 2 * 1024 * 1024);
3681        assert!(
3682            StoreWalAction::upsert_entity("keys", &row(0, 0), None, store.format_version())
3683                .encode()
3684                .len()
3685                >= 2048,
3686            "fixture must exert physical WAL pressure after value compression"
3687        );
3688        let mut ids: Vec<_> = (0..8)
3689            .map(|writer| {
3690                store
3691                    .write_keyed_row("keys", row(writer, 0), None, None)
3692                    .expect("seed")
3693            })
3694            .collect();
3695        let initial = crate::storage::EmbeddedRdbArtifact::open(&path).expect("initial roots");
3696        let mut previous_snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&initial)
3697            .expect("initial snapshot")
3698            .expect("image");
3699        // Each wave writes over 2 MiB through the same 1 MiB reservation.
3700        // Checking image changes after each wave prevents a larger WAL from
3701        // merely postponing every checkpoint beyond the test's duration.
3702        for wave in 0..3 {
3703            let barrier = Barrier::new(ids.len());
3704            ids = std::thread::scope(|scope| {
3705                let workers: Vec<_> = ids
3706                    .iter()
3707                    .enumerate()
3708                    .map(|(writer, previous)| {
3709                        let store = &store;
3710                        let barrier = &barrier;
3711                        scope.spawn(move || {
3712                            barrier.wait();
3713                            let mut id = *previous;
3714                            for round in 0..64 {
3715                                id = store
3716                                    .write_keyed_row(
3717                                        "keys",
3718                                        row(writer, wave * 64 + round),
3719                                        None,
3720                                        Some(id),
3721                                    )
3722                                    .expect("durable overwrite");
3723                            }
3724                            id
3725                        })
3726                    })
3727                    .collect();
3728                workers
3729                    .into_iter()
3730                    .map(|worker| worker.join().expect("writer"))
3731                    .collect()
3732            });
3733            let open = crate::storage::EmbeddedRdbArtifact::open(&path).expect("wave roots");
3734            assert_eq!(open.manifest.wal_region_bytes, EMBEDDED_WAL_HEADROOM_LIMIT);
3735            let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
3736                .expect("wave snapshot")
3737                .expect("image");
3738            assert!(snapshot != previous_snapshot, "wave {wave} must checkpoint");
3739            previous_snapshot = snapshot;
3740        }
3741        let open = crate::storage::EmbeddedRdbArtifact::open(&path).expect("recover roots");
3742        let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
3743            .expect("snapshot")
3744            .expect("image");
3745        let recovered =
3746            UnifiedStore::load_from_bytes_with_config(&snapshot, UnifiedStoreConfig::default())
3747                .expect("snapshot replay");
3748        for payload in crate::storage::EmbeddedRdbArtifact::read_wal_payloads(&open).expect("WAL") {
3749            recovered
3750                .apply_encoded_store_wal_action(&payload)
3751                .expect("WAL replay");
3752        }
3753        assert_eq!(recovered.get_collection("keys").expect("keys").count(), 8);
3754        for (writer, id) in ids.iter().enumerate() {
3755            let entity = recovered
3756                .get("keys", *id)
3757                .expect("last acknowledged version");
3758            assert_eq!(
3759                entity.data.as_row().expect("row").get_field("value"),
3760                row(writer, 191)
3761                    .data
3762                    .as_row()
3763                    .expect("expected row")
3764                    .get_field("value")
3765            );
3766        }
3767    }
3768
3769    /// Serialise tests that mutate `REDDB_GROUP_COMMIT_WINDOW_US`.
3770    /// The env table is process-global, so two parallel test threads
3771    /// flipping it would race the assertions in the test that
3772    /// happens to read it last.
3773    fn env_lock() -> &'static StdMutex<()> {
3774        static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
3775        LOCK.get_or_init(|| StdMutex::new(()))
3776    }
3777
3778    fn temp_wal(name: &str) -> PathBuf {
3779        let nanos = SystemTime::now()
3780            .duration_since(std::time::UNIX_EPOCH)
3781            .unwrap()
3782            .as_nanos();
3783        let path = reddb_file::layout::store_commit_coord_temp_wal_path(
3784            &std::env::temp_dir(),
3785            name,
3786            std::process::id(),
3787            nanos,
3788        );
3789        let _ = std::fs::remove_file(&path);
3790        path
3791    }
3792
3793    fn replay_crash_payload(id: u64, round: u64) -> String {
3794        let mut state = id * 31 + round * 13 + 1;
3795        (0..600)
3796            .map(|_| {
3797                state = state.wrapping_mul(1664525).wrapping_add(1013904223);
3798                char::from(b'!' + ((state >> 24) % 90) as u8)
3799            })
3800            .collect()
3801    }
3802
3803    #[cfg(target_os = "linux")]
3804    #[test]
3805    fn interrupted_replay_reclaims_unpublished_pages() {
3806        interrupted_replay_reclaims_pages(false, false);
3807    }
3808
3809    #[cfg(target_os = "linux")]
3810    #[test]
3811    fn interrupted_replay_reclaims_durable_unpublished_pages() {
3812        interrupted_replay_reclaims_pages(false, true);
3813    }
3814
3815    #[cfg(target_os = "linux")]
3816    #[test]
3817    fn interrupted_replay_preserves_published_pages() {
3818        interrupted_replay_reclaims_pages(true, false);
3819    }
3820
3821    #[cfg(target_os = "linux")]
3822    #[test]
3823    fn interrupted_checkpoint_reclaims_unpublished_pages() {
3824        const CHILD_PATH: &str = "REDDB_EXPERIMENTAL_CHECKPOINT_REBUILD_PATH";
3825        let config = || {
3826            UnifiedStoreConfig::default()
3827                .with_durability_mode(DurabilityMode::Strict)
3828                .with_page_cache_slots(4)
3829        };
3830        if let Some(path) = std::env::var_os(CHILD_PATH) {
3831            let store = UnifiedStore::open_with_config(path, config()).unwrap();
3832            // Inject resident changes without a WAL record: after the aborted
3833            // checkpoint the old durable rows must remain authoritative.
3834            for id in 1..=200 {
3835                let entity = UnifiedEntity::table_row(
3836                    EntityId::new(id),
3837                    "rows",
3838                    id,
3839                    vec![Value::text(replay_crash_payload(id, 8))],
3840                );
3841                let record =
3842                    UnifiedStore::serialize_entity_record(&entity, None, STORE_VERSION_V11);
3843                store.apply_replayed_upsert("rows", &record, false).unwrap();
3844            }
3845            store.persist().expect("must exit during checkpoint");
3846            panic!("checkpoint rebuild hook was not reached");
3847        }
3848        let directory = tempfile::tempdir().unwrap();
3849        let path = directory.path().join("data.rdb");
3850        {
3851            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
3852            store.create_collection("rows").unwrap();
3853            for id in 1..=200 {
3854                store
3855                    .insert(
3856                        "rows",
3857                        UnifiedEntity::table_row(
3858                            EntityId::new(id),
3859                            "rows",
3860                            id,
3861                            vec![Value::text(format!("initial-{id}"))],
3862                        ),
3863                    )
3864                    .unwrap();
3865            }
3866            store.persist().unwrap();
3867        }
3868        let mut first = 0;
3869        let mut last = 0;
3870        for cycle in 1..=12 {
3871            let output = std::process::Command::new(std::env::current_exe().unwrap())
3872                .args([
3873                    "--exact",
3874                    "storage::unified::store::commit::tests::interrupted_checkpoint_reclaims_unpublished_pages",
3875                    "--nocapture",
3876                ])
3877                .env(CHILD_PATH, &path)
3878                .env("REDDB_EXPERIMENTAL_EXIT_DURING_CHECKPOINT_REBUILD", "1")
3879                .output()
3880                .unwrap();
3881            assert_eq!(
3882                output.status.code(),
3883                Some(183),
3884                "{}",
3885                String::from_utf8_lossy(&output.stderr)
3886            );
3887            assert!(String::from_utf8_lossy(&output.stderr)
3888                .contains("experimental checkpoint exit before manifest"));
3889            last = std::fs::metadata(&path).unwrap().len();
3890            if cycle == 1 {
3891                first = last;
3892            }
3893            eprintln!("checkpoint_exit_cycle={cycle} data_logical={last}");
3894        }
3895        let recovered = UnifiedStore::open_with_config(&path, config()).unwrap();
3896        assert_eq!(recovered.get_collection("rows").unwrap().count(), 200);
3897        for id in 1..=200 {
3898            assert_eq!(
3899                recovered
3900                    .get("rows", EntityId::new(id))
3901                    .unwrap()
3902                    .data
3903                    .as_row()
3904                    .unwrap()
3905                    .columns,
3906                vec![Value::text(format!("initial-{id}"))]
3907            );
3908        }
3909        assert!(last <= first + 2 * crate::storage::engine::PAGE_SIZE as u64,
3910            "repeated interrupted checkpoint must bound page growth: first={first}, after_12={last}");
3911    }
3912
3913    #[cfg(target_os = "linux")]
3914    #[test]
3915    fn interrupted_checkpoint_with_wal_reclaims_unpublished_pages() {
3916        use std::os::unix::fs::MetadataExt;
3917        const CHILD_PATH: &str = "REDDB_EXPERIMENTAL_CHECKPOINT_WAL_PATH";
3918        const ROUND: &str = "REDDB_EXPERIMENTAL_CHECKPOINT_WAL_ROUND";
3919        let config = || {
3920            UnifiedStoreConfig::default()
3921                .with_durability_mode(DurabilityMode::Strict)
3922                .with_page_cache_slots(4)
3923        };
3924        if let Some(path) = std::env::var_os(CHILD_PATH) {
3925            let round: u64 = std::env::var(ROUND).unwrap().parse().unwrap();
3926            let store = UnifiedStore::open_with_config(path, config()).unwrap();
3927            if round > 1 {
3928                for id in 1..=200 {
3929                    assert_eq!(
3930                        store
3931                            .get("rows", EntityId::new(id))
3932                            .unwrap()
3933                            .data
3934                            .as_row()
3935                            .unwrap()
3936                            .columns,
3937                        vec![Value::text(replay_crash_payload(id, round - 1))]
3938                    );
3939                }
3940            }
3941            let actions: Vec<_> = (1..=200)
3942                .map(|id| {
3943                    let entity = UnifiedEntity::table_row(
3944                        EntityId::new(id),
3945                        "rows",
3946                        id,
3947                        vec![Value::text(replay_crash_payload(id, round))],
3948                    );
3949                    StoreWalAction::upsert_entity("rows", &entity, None, STORE_VERSION_V11)
3950                })
3951                .collect();
3952            for action in &actions {
3953                store.apply_replayed_action(action, false).unwrap();
3954            }
3955            // Use the actual strict WAL coordinator. No checkpoint proof is
3956            // installed, so the replacement-tree path must still be taken.
3957            store
3958                .commit
3959                .as_ref()
3960                .unwrap()
3961                .append_actions(&actions)
3962                .unwrap();
3963            store.persist().expect("must exit during checkpoint");
3964            panic!("checkpoint rebuild hook was not reached");
3965        }
3966        let directory = tempfile::tempdir().unwrap();
3967        let path = directory.path().join("data.rdb");
3968        {
3969            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
3970            store.create_collection("rows").unwrap();
3971            for id in 1..=200 {
3972                store
3973                    .insert(
3974                        "rows",
3975                        UnifiedEntity::table_row(
3976                            EntityId::new(id),
3977                            "rows",
3978                            id,
3979                            vec![Value::text(format!("initial-{id}"))],
3980                        ),
3981                    )
3982                    .unwrap();
3983            }
3984            store.persist().unwrap();
3985        }
3986        let mut fourth = 0;
3987        let mut last = 0;
3988        for round in 1..=12 {
3989            let output = std::process::Command::new(std::env::current_exe().unwrap())
3990                .args([
3991                    "--exact",
3992                    "storage::unified::store::commit::tests::interrupted_checkpoint_with_wal_reclaims_unpublished_pages",
3993                    "--nocapture",
3994                ])
3995                .env(CHILD_PATH, &path)
3996                .env(ROUND, round.to_string())
3997                .env("REDDB_EXPERIMENTAL_EXIT_DURING_CHECKPOINT_REBUILD", "1")
3998                .output().unwrap();
3999            assert_eq!(
4000                output.status.code(),
4001                Some(183),
4002                "round {round}: {}",
4003                String::from_utf8_lossy(&output.stderr)
4004            );
4005            assert!(String::from_utf8_lossy(&output.stderr)
4006                .contains("experimental checkpoint exit before manifest"));
4007            let meta = std::fs::metadata(&path).unwrap();
4008            last = meta.len();
4009            if round == 4 {
4010                fourth = last;
4011            }
4012            eprintln!(
4013                "checkpoint_wal_exit_round={round} data_logical={last} data_allocated={}",
4014                meta.blocks() * 512
4015            );
4016        }
4017        let recovered = UnifiedStore::open_with_config(&path, config()).unwrap();
4018        assert_eq!(recovered.get_collection("rows").unwrap().count(), 200);
4019        for id in 1..=200 {
4020            assert_eq!(
4021                recovered
4022                    .get("rows", EntityId::new(id))
4023                    .unwrap()
4024                    .data
4025                    .as_row()
4026                    .unwrap()
4027                    .columns,
4028                vec![Value::text(replay_crash_payload(id, 12))]
4029            );
4030        }
4031        recovered.persist().unwrap();
4032        drop(recovered);
4033        let reopened = UnifiedStore::open_with_config(&path, config()).unwrap();
4034        for id in 1..=200 {
4035            assert_eq!(
4036                reopened
4037                    .get("rows", EntityId::new(id))
4038                    .unwrap()
4039                    .data
4040                    .as_row()
4041                    .unwrap()
4042                    .columns,
4043                vec![Value::text(replay_crash_payload(id, 12))]
4044            );
4045        }
4046        assert!(last <= fourth + 2 * crate::storage::engine::PAGE_SIZE as u64,
4047            "repeated interrupted WAL-backed checkpoints must bound page growth: round4={fourth}, round12={last}");
4048    }
4049
4050    #[cfg(target_os = "linux")]
4051    #[test]
4052    fn interrupted_retired_reclamation_preserves_reuse() {
4053        const CHILD_PATH: &str = "REDDB_EXPERIMENTAL_RETIRED_PATH";
4054        fn mutate(store: &UnifiedStore, round: u64) {
4055            for id in 1..=200 {
4056                let entity = UnifiedEntity::table_row(
4057                    EntityId::new(id),
4058                    "rows",
4059                    id,
4060                    vec![Value::text(replay_crash_payload(id, round))],
4061                );
4062                let record =
4063                    UnifiedStore::serialize_entity_record(&entity, None, STORE_VERSION_V11);
4064                store.apply_replayed_upsert("rows", &record, false).unwrap();
4065            }
4066        }
4067        let config = || {
4068            UnifiedStoreConfig::default()
4069                .with_durability_mode(DurabilityMode::Strict)
4070                .with_page_cache_slots(4)
4071        };
4072        if let Some(path) = std::env::var_os(CHILD_PATH) {
4073            let store = UnifiedStore::open_with_config(path, config()).unwrap();
4074            mutate(&store, 2);
4075            store.persist().expect("must exit at retired free boundary");
4076            panic!("retired free hook was not reached");
4077        }
4078        let mut reuse = Vec::new();
4079        for (label, env_name, exit_code, message) in [
4080            (
4081                "before",
4082                "REDDB_EXPERIMENTAL_EXIT_BEFORE_RETIRED_FREE",
4083                184,
4084                "experimental exit before retired free",
4085            ),
4086            (
4087                "enqueued",
4088                "REDDB_EXPERIMENTAL_EXIT_AFTER_RETIRED_ENQUEUE",
4089                186,
4090                "experimental exit after retired enqueue",
4091            ),
4092            (
4093                "after",
4094                "REDDB_EXPERIMENTAL_EXIT_AFTER_RETIRED_FREE",
4095                185,
4096                "experimental exit after retired free",
4097            ),
4098        ] {
4099            let directory = tempfile::tempdir().unwrap();
4100            let path = directory.path().join("data.rdb");
4101            {
4102                let store = UnifiedStore::open_with_config(&path, config()).unwrap();
4103                store.create_collection("rows").unwrap();
4104                for id in 1..=200 {
4105                    store
4106                        .insert(
4107                            "rows",
4108                            UnifiedEntity::table_row(
4109                                EntityId::new(id),
4110                                "rows",
4111                                id,
4112                                vec![Value::text(format!("initial-{id}"))],
4113                            ),
4114                        )
4115                        .unwrap();
4116                }
4117                store.persist().unwrap();
4118                mutate(&store, 1);
4119                store.persist().unwrap();
4120            }
4121            let output = std::process::Command::new(std::env::current_exe().unwrap())
4122                .args([
4123                    "--exact",
4124                    "storage::unified::store::commit::tests::interrupted_retired_reclamation_preserves_reuse",
4125                    "--nocapture",
4126                ])
4127                .env(CHILD_PATH, &path)
4128                .env(env_name, "1")
4129                .output().unwrap();
4130            assert_eq!(
4131                output.status.code(),
4132                Some(exit_code),
4133                "{label}: {}",
4134                String::from_utf8_lossy(&output.stderr)
4135            );
4136            assert!(String::from_utf8_lossy(&output.stderr).contains(message));
4137            eprintln!(
4138                "retired_reclaim_{label} child={}",
4139                String::from_utf8_lossy(&output.stderr).trim()
4140            );
4141            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
4142            for id in 1..=200 {
4143                assert_eq!(
4144                    store
4145                        .get("rows", EntityId::new(id))
4146                        .unwrap()
4147                        .data
4148                        .as_row()
4149                        .unwrap()
4150                        .columns,
4151                    vec![Value::text(replay_crash_payload(id, 2))]
4152                );
4153            }
4154            let pager = store.pager.as_ref().unwrap();
4155            let before_pages = pager.page_count().unwrap();
4156            let mut ids = std::collections::HashSet::new();
4157            let mut reused = 0;
4158            for _ in 0..256 {
4159                let page = pager
4160                    .allocate_page(crate::storage::engine::page::PageType::BTreeLeaf)
4161                    .unwrap();
4162                let id = page.page_id();
4163                assert!(ids.insert(id), "duplicate allocation");
4164                reused += u32::from(id < before_pages);
4165                pager.write_page(id, page).unwrap();
4166            }
4167            pager.sync().unwrap();
4168            eprintln!(
4169                "retired_reclaim_{label} before_pages={before_pages} reused={reused} appended={}",
4170                256 - reused
4171            );
4172            drop(store);
4173            let reopened = UnifiedStore::open_with_config(&path, config()).unwrap();
4174            for id in 1..=200 {
4175                assert_eq!(
4176                    reopened
4177                        .get("rows", EntityId::new(id))
4178                        .unwrap()
4179                        .data
4180                        .as_row()
4181                        .unwrap()
4182                        .columns,
4183                    vec![Value::text(replay_crash_payload(id, 2))]
4184                );
4185            }
4186            reuse.push(reused);
4187        }
4188        assert!(
4189            reuse[0] >= reuse[2] && reuse[1] >= reuse[2],
4190            "recovery must not lose retired pages before allocator publication: before={} enqueued={} after={}",
4191            reuse[0],
4192            reuse[1],
4193            reuse[2]
4194        );
4195    }
4196
4197    #[cfg(target_os = "linux")]
4198    #[test]
4199    fn experimental_retaining_released_root_is_not_recoverable() {
4200        let directory = tempfile::tempdir().unwrap();
4201        let path = directory.path().join("data.rdb");
4202        let config = || {
4203            UnifiedStoreConfig::default()
4204                .with_durability_mode(DurabilityMode::Strict)
4205                .with_page_cache_slots(4)
4206        };
4207        {
4208            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
4209            store.create_collection("rows").unwrap();
4210            for id in 1..=200 {
4211                store
4212                    .insert(
4213                        "rows",
4214                        UnifiedEntity::table_row(
4215                            EntityId::new(id),
4216                            "rows",
4217                            id,
4218                            vec![Value::text(format!("initial-{id}"))],
4219                        ),
4220                    )
4221                    .unwrap();
4222            }
4223            store.persist().unwrap();
4224            for id in 1..=200 {
4225                let entity = UnifiedEntity::table_row(
4226                    EntityId::new(id),
4227                    "rows",
4228                    id,
4229                    vec![Value::text(replay_crash_payload(id, 1))],
4230                );
4231                let record =
4232                    UnifiedStore::serialize_entity_record(&entity, None, STORE_VERSION_V11);
4233                store.apply_replayed_upsert("rows", &record, false).unwrap();
4234            }
4235            store.persist().unwrap();
4236        }
4237        let output = std::process::Command::new(std::env::current_exe().unwrap())
4238            .args(["--exact", "storage::unified::store::commit::tests::interrupted_retired_reclamation_preserves_reuse", "--nocapture"])
4239            .env("REDDB_EXPERIMENTAL_RETIRED_PATH", &path)
4240            .env("REDDB_EXPERIMENTAL_RETAIN_RELEASED_ROOT", "1")
4241            .env("REDDB_EXPERIMENTAL_EXIT_AFTER_RETIRED_FREE", "1")
4242            .output().unwrap();
4243        assert_eq!(
4244            output.status.code(),
4245            Some(185),
4246            "{}",
4247            String::from_utf8_lossy(&output.stderr)
4248        );
4249        assert!(String::from_utf8_lossy(&output.stderr)
4250            .contains("experimental exit after retired free"));
4251
4252        let reopened = UnifiedStore::open_with_config(&path, config()).unwrap();
4253        for id in 1..=200 {
4254            assert_eq!(
4255                reopened
4256                    .get("rows", EntityId::new(id))
4257                    .unwrap()
4258                    .data
4259                    .as_row()
4260                    .unwrap()
4261                    .columns,
4262                vec![Value::text(replay_crash_payload(id, 2))]
4263            );
4264        }
4265        let retired_roots: Vec<_> = reopened
4266            .retired_btrees
4267            .lock()
4268            .iter()
4269            .map(|entry| entry.tree.root_page_id())
4270            .collect();
4271        let pager = reopened.pager.as_ref().unwrap();
4272        let root_types: Vec<_> = retired_roots
4273            .iter()
4274            .map(|id| pager.read_page(*id).unwrap().page_type().unwrap())
4275            .collect();
4276        assert!(
4277            root_types.contains(&crate::storage::engine::page::PageType::FreelistTrunk),
4278            "expected a retained root to have become a freelist trunk: {root_types:?}"
4279        );
4280        let error = reopened
4281            .persist()
4282            .expect_err("retained root was reused as allocator metadata");
4283        assert!(
4284            error
4285                .to_string()
4286                .contains("unexpected retired tree page type"),
4287            "{error}"
4288        );
4289        eprintln!("retained_root_types={root_types:?} persist_error={error}");
4290    }
4291
4292    #[cfg(target_os = "linux")]
4293    fn interrupted_replay_reclaims_pages(after_publication: bool, force_sync: bool) {
4294        use std::os::unix::fs::MetadataExt;
4295        const CHILD_PATH: &str = "REDDB_EXPERIMENTAL_REPLAY_REBUILD_PATH";
4296        let config = || {
4297            UnifiedStoreConfig::default()
4298                .with_durability_mode(DurabilityMode::Strict)
4299                .with_page_cache_slots(4)
4300        };
4301        if let Some(path) = std::env::var_os(CHILD_PATH) {
4302            let _store = UnifiedStore::open_with_config(path, config())
4303                .expect("must exit while replay rebuilds");
4304            panic!("replay rebuild hook was not reached");
4305        }
4306        let directory = tempfile::tempdir().unwrap();
4307        let path = directory.path().join("data.rdb");
4308        {
4309            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
4310            store.create_collection("rows").unwrap();
4311            for id in 1..=200 {
4312                store
4313                    .insert(
4314                        "rows",
4315                        UnifiedEntity::table_row(
4316                            EntityId::new(id),
4317                            "rows",
4318                            id,
4319                            vec![Value::text(format!("initial-{id}"))],
4320                        ),
4321                    )
4322                    .unwrap();
4323            }
4324            store.persist().unwrap();
4325        }
4326        {
4327            let coordinator = StoreCommitCoordinator::open(
4328                reddb_file::layout::unified_wal_path(&path),
4329                DurabilityMode::Strict,
4330                GroupCommitOptions::default(),
4331            )
4332            .unwrap();
4333            let actions = (1..=200)
4334                .map(|id| {
4335                    let entity = UnifiedEntity::table_row(
4336                        EntityId::new(id),
4337                        "rows",
4338                        id,
4339                        vec![Value::text(replay_crash_payload(id, 8))],
4340                    );
4341                    StoreWalAction::upsert_entity("rows", &entity, None, STORE_VERSION_V11)
4342                })
4343                .collect::<Vec<_>>();
4344            coordinator.append_actions(&actions).unwrap();
4345        }
4346        let snapshot = || {
4347            let data = std::fs::metadata(&path).unwrap();
4348            let wal = std::fs::metadata(reddb_file::layout::unified_wal_path(&path)).unwrap();
4349            (
4350                data.len(),
4351                data.blocks() * 512,
4352                wal.len(),
4353                wal.blocks() * 512,
4354            )
4355        };
4356        let baseline = snapshot();
4357        let mut previous = baseline;
4358        let mut first_failure = baseline;
4359        for cycle in 1..=12 {
4360            let test_name = if after_publication {
4361                "storage::unified::store::commit::tests::interrupted_replay_preserves_published_pages"
4362            } else if force_sync {
4363                "storage::unified::store::commit::tests::interrupted_replay_reclaims_durable_unpublished_pages"
4364            } else {
4365                "storage::unified::store::commit::tests::interrupted_replay_reclaims_unpublished_pages"
4366            };
4367            let mut command = std::process::Command::new(std::env::current_exe().unwrap());
4368            command
4369                .args(["--exact", test_name, "--nocapture"])
4370                .env(CHILD_PATH, &path);
4371            if !force_sync {
4372                command.env("REDDB_EXPERIMENTAL_REPLAY_NO_SYNC", "1");
4373            } else {
4374                command.env_remove("REDDB_EXPERIMENTAL_REPLAY_NO_SYNC");
4375            }
4376            let message = if after_publication {
4377                command.env("REDDB_EXPERIMENTAL_EXIT_AFTER_REPLAY_PUBLICATION", "1");
4378                "experimental replay exit after manifest"
4379            } else {
4380                command.env("REDDB_EXPERIMENTAL_EXIT_DURING_REPLAY_REBUILD", "1");
4381                "experimental replay rebuild exit before manifest"
4382            };
4383            let output = command.output().unwrap();
4384            assert_eq!(
4385                output.status.code(),
4386                Some(182),
4387                "cycle {cycle}: {}",
4388                String::from_utf8_lossy(&output.stderr)
4389            );
4390            assert!(String::from_utf8_lossy(&output.stderr).contains(message));
4391            let now = snapshot();
4392            eprintln!("replay_exit_cycle={cycle} data_logical={} data_allocated={} wal_logical={} wal_allocated={}",now.0,now.1,now.2,now.3);
4393            if cycle == 1 {
4394                first_failure = now;
4395            }
4396            previous = now;
4397        }
4398        let recovered = UnifiedStore::open_with_config(&path, config()).unwrap();
4399        assert_eq!(recovered.get_collection("rows").unwrap().count(), 200);
4400        for id in 1..=200 {
4401            assert_eq!(
4402                recovered
4403                    .get("rows", EntityId::new(id))
4404                    .unwrap()
4405                    .data
4406                    .as_row()
4407                    .unwrap()
4408                    .columns,
4409                vec![Value::text(replay_crash_payload(id, 8))]
4410            );
4411        }
4412        let pages = recovered.pager.as_ref().unwrap().page_count().unwrap();
4413        let free = recovered.pager.as_ref().unwrap().free_page_count().unwrap();
4414        recovered.persist().unwrap();
4415        drop(recovered);
4416        let final_sizes = snapshot();
4417        let reopened = UnifiedStore::open_with_config(&path, config()).unwrap();
4418        assert_eq!(reopened.get_collection("rows").unwrap().count(), 200);
4419        for id in 1..=200 {
4420            assert_eq!(
4421                reopened
4422                    .get("rows", EntityId::new(id))
4423                    .unwrap()
4424                    .data
4425                    .as_row()
4426                    .unwrap()
4427                    .columns,
4428                vec![Value::text(replay_crash_payload(id, 8))]
4429            );
4430        }
4431        eprintln!("replay_rebuild baseline={baseline:?} after_12={previous:?} after_recovery_checkpoint={final_sizes:?} pages={pages} free={free}");
4432        // Probe actual allocation rather than the cached free-page counter:
4433        // newly allocated IDs reveal whether interrupted generations returned
4434        // to the allocator after recovery and a completed checkpoint.
4435        let pager = reopened.pager.as_ref().unwrap();
4436        let before_probe = pager.page_count().unwrap();
4437        let mut ids = std::collections::HashSet::new();
4438        let mut reused = 0;
4439        for _ in 0..256 {
4440            let page = pager
4441                .allocate_page(crate::storage::engine::page::PageType::BTreeLeaf)
4442                .unwrap();
4443            let id = page.page_id();
4444            assert!(ids.insert(id), "allocator returned the same page twice");
4445            reused += u32::from(id < before_probe);
4446            pager.write_page(id, page).unwrap();
4447        }
4448        pager.sync().unwrap();
4449        let after_probe = pager.page_count().unwrap();
4450        eprintln!("replay_reuse_probe count=256 before_pages={before_probe} after_pages={after_probe} reused={reused} appended={}", 256 - reused);
4451        drop(reopened);
4452        let verified = UnifiedStore::open_with_config(&path, config()).unwrap();
4453        for id in 1..=200 {
4454            assert_eq!(
4455                verified
4456                    .get("rows", EntityId::new(id))
4457                    .unwrap()
4458                    .data
4459                    .as_row()
4460                    .unwrap()
4461                    .columns,
4462                vec![Value::text(replay_crash_payload(id, 8))]
4463            );
4464        }
4465        assert!(
4466            previous.0 <= first_failure.0 + 2 * crate::storage::engine::PAGE_SIZE as u64,
4467            "repeated interrupted replay must bound page growth: first={}, after_12={}",
4468            first_failure.0,
4469            previous.0
4470        );
4471    }
4472
4473    #[test]
4474    fn paged_wal_replay_survives_immediate_process_exit() {
4475        const CHILD_PATH: &str = "REDDB_TEST_REPLAY_CRASH_PATH";
4476        let config = || UnifiedStoreConfig::default().with_page_cache_slots(4);
4477        if let Some(path) = std::env::var_os(CHILD_PATH) {
4478            let store = UnifiedStore::open_with_config(path, config()).expect("replay child");
4479            assert_eq!(store.get_collection("rows").unwrap().count(), 400);
4480            // No Rust destructors or graceful checkpoint may repair the image.
4481            std::process::exit(0);
4482        }
4483        let directory = tempfile::tempdir().unwrap();
4484        let path = directory.path().join("data.rdb");
4485        {
4486            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
4487            store.create_collection("rows").unwrap();
4488            for id in 1..=400 {
4489                store
4490                    .insert(
4491                        "rows",
4492                        UnifiedEntity::table_row(
4493                            EntityId::new(id),
4494                            "rows",
4495                            id,
4496                            vec![Value::text(format!("initial-{id}"))],
4497                        ),
4498                    )
4499                    .unwrap();
4500            }
4501            store.persist().unwrap();
4502        }
4503        {
4504            let coordinator = StoreCommitCoordinator::open(
4505                reddb_file::layout::unified_wal_path(&path),
4506                DurabilityMode::Strict,
4507                GroupCommitOptions::default(),
4508            )
4509            .unwrap();
4510            for round in 0..3 {
4511                let actions = (1..=400)
4512                    .map(|id| {
4513                        let payload = replay_crash_payload(id, round);
4514                        let entity = UnifiedEntity::table_row(
4515                            EntityId::new(id),
4516                            "rows",
4517                            id,
4518                            vec![Value::text(payload)],
4519                        );
4520                        StoreWalAction::upsert_entity("rows", &entity, None, STORE_VERSION_V11)
4521                    })
4522                    .collect::<Vec<_>>();
4523                coordinator.append_actions(&actions).unwrap();
4524            }
4525        }
4526        let status = std::process::Command::new(std::env::current_exe().unwrap())
4527            .args(["--exact", "storage::unified::store::commit::tests::paged_wal_replay_survives_immediate_process_exit", "--nocapture"])
4528            .env(CHILD_PATH, &path).status().unwrap();
4529        assert!(status.success(), "replay process failed");
4530        let reopened = UnifiedStore::open_with_config(&path, config())
4531            .expect("cold reopen after replay crash");
4532        assert_eq!(reopened.get_collection("rows").unwrap().count(), 400);
4533        for id in 1..=400 {
4534            let entity = reopened
4535                .get("rows", EntityId::new(id))
4536                .expect("retained entity");
4537            let EntityData::Row(row) = entity.data else {
4538                panic!("expected row")
4539            };
4540            assert_eq!(row.columns, vec![Value::text(replay_crash_payload(id, 2))]);
4541        }
4542        drop(reopened);
4543        let stable_bytes = std::fs::metadata(&path).unwrap().len();
4544        let repeated = UnifiedStore::open_with_config(&path, config()).unwrap();
4545        assert_eq!(repeated.get_collection("rows").unwrap().count(), 400);
4546        assert_eq!(
4547            std::fs::metadata(&path).unwrap().len(),
4548            stable_bytes,
4549            "idempotent replay must not allocate another tree generation"
4550        );
4551    }
4552
4553    #[test]
4554    fn checkpoint_reset_waits_for_an_enqueued_commit_acknowledgement() {
4555        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
4556        let path = temp_wal("checkpoint-ack");
4557        let coordinator = Arc::new(
4558            StoreCommitCoordinator::open(
4559                path.clone(),
4560                DurabilityMode::WalDurableGrouped,
4561                GroupCommitOptions::default(),
4562            )
4563            .unwrap(),
4564        );
4565        // Pause the writer after enqueue, before it can register/wait for its
4566        // acknowledgement. The write-error preflight now takes the state lock,
4567        // so the fixture must let that preflight finish before holding it.
4568        let (written_tx, written_rx) = std::sync::mpsc::channel();
4569        let (enqueued_tx, enqueued_rx) = std::sync::mpsc::channel();
4570        let (resume_tx, resume_rx) = std::sync::mpsc::channel();
4571        let writer_coordinator = Arc::clone(&coordinator);
4572        let writer = std::thread::spawn(move || {
4573            writer_coordinator.check_write_error().unwrap();
4574            let _epoch = writer_coordinator.queue.epoch.read();
4575            let action = StoreWalAction::CreateCollection {
4576                name: "acknowledged".into(),
4577            }
4578            .encode();
4579            let wal_bytes = action.len() as u64;
4580            let blob = WalRecord::TxCommitBatch {
4581                tx_id: 1,
4582                actions: vec![action],
4583            }
4584            .encode();
4585            let target_lsn = writer_coordinator.queue.enqueue(blob);
4586            enqueued_tx.send(()).unwrap();
4587            resume_rx.recv().unwrap();
4588            let result = writer_coordinator.wait_until_durable_batch(target_lsn, wal_bytes, false);
4589            written_tx.send(result).unwrap();
4590        });
4591        enqueued_rx.recv_timeout(Duration::from_secs(2)).unwrap();
4592        let state = coordinator.state.0.lock();
4593        resume_tx.send(()).unwrap();
4594        let (started_tx, started_rx) = std::sync::mpsc::channel();
4595        let (reset_tx, reset_rx) = std::sync::mpsc::channel();
4596        let reset_coordinator = Arc::clone(&coordinator);
4597        let reset = std::thread::spawn(move || {
4598            started_tx.send(()).unwrap();
4599            reset_tx.send(reset_coordinator.truncate()).unwrap();
4600        });
4601        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
4602        let deadline = Instant::now() + Duration::from_millis(100);
4603        while coordinator.queue.has_pending() && Instant::now() < deadline {
4604            std::thread::sleep(Duration::from_millis(1));
4605        }
4606        let discarded_before_ack = !coordinator.queue.has_pending();
4607        drop(state);
4608        let acknowledged = written_rx.recv_timeout(Duration::from_secs(2));
4609        if acknowledged.is_err() {
4610            // Release an old implementation's stranded waiter before failing
4611            // the assertion, so the regression itself cannot leak a worker.
4612            let mut state = coordinator.state.0.lock();
4613            state.shutdown = true;
4614            state.last_error = Some("checkpoint acknowledgement regression cleanup".into());
4615            coordinator.state.1.notify_all();
4616        }
4617        writer.join().unwrap();
4618        reset_rx
4619            .recv_timeout(Duration::from_secs(2))
4620            .unwrap()
4621            .unwrap();
4622        reset.join().unwrap();
4623        assert!(
4624            !discarded_before_ack,
4625            "checkpoint discarded an unacknowledged WAL record"
4626        );
4627        assert!(
4628            acknowledged.unwrap().is_ok(),
4629            "durable writer did not finish"
4630        );
4631        drop(coordinator);
4632        let _ = std::fs::remove_file(path);
4633    }
4634
4635    #[test]
4636    fn ready_publication_requests_flush_but_waits_for_durability() {
4637        let path = temp_wal("ready-publication");
4638        let options = GroupCommitOptions {
4639            max_statements: 8,
4640            window_ms: 1000,
4641            ..Default::default()
4642        };
4643        let coordinator = Arc::new(
4644            StoreCommitCoordinator::open(path.clone(), DurabilityMode::WalDurableGrouped, options)
4645                .expect("coordinator"),
4646        );
4647        let wal = coordinator.wal.lock();
4648        let acknowledged = Arc::new(std::sync::atomic::AtomicBool::new(false));
4649        let writer = {
4650            let coordinator = Arc::clone(&coordinator);
4651            let acknowledged = Arc::clone(&acknowledged);
4652            std::thread::spawn(move || {
4653                coordinator
4654                    .append_ready_actions(
4655                        &[StoreWalAction::CreateCollection {
4656                            name: "ready".into(),
4657                        }],
4658                        false,
4659                    )
4660                    .expect("durable publication");
4661                acknowledged.store(true, Ordering::Release);
4662            })
4663        };
4664        let deadline = Instant::now() + Duration::from_secs(10);
4665        while coordinator.state.0.lock().pending_statements == 0 {
4666            assert!(Instant::now() < deadline, "writer did not enqueue");
4667            std::thread::yield_now();
4668        }
4669        assert_eq!(
4670            coordinator.state.0.lock().pending_statements,
4671            options.max_statements
4672        );
4673        assert!(
4674            !acknowledged.load(Ordering::Acquire),
4675            "must wait for WAL sync"
4676        );
4677        drop(wal);
4678        writer.join().expect("writer");
4679        assert!(acknowledged.load(Ordering::Acquire));
4680        assert_eq!(coordinator.fsync_count(), 1);
4681        drop(coordinator);
4682        let _ = std::fs::remove_file(path);
4683    }
4684
4685    /// Concurrent autocommits MUST coalesce into far fewer fsyncs
4686    /// than the number of callers when the adaptive group-commit
4687    /// window is active. Without the 200µs floor, every caller
4688    /// would race the drain loop and pay an independent fsync.
4689    ///
4690    /// The test fires 32 concurrent `append_actions` calls and asserts
4691    /// the coordinator issued strictly fewer fsyncs than callers.
4692    /// (We don't pin to "one fsync" because timing on loaded CI hosts
4693    /// can split the burst across a couple of drain cycles — the win
4694    /// is the ratio, not the absolute count.)
4695    #[test]
4696    fn group_commit_coalesces_concurrent_autocommits() {
4697        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
4698        // Make sure no stale env var skews this run — the test
4699        // exercises the default 200µs floor.
4700        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
4701
4702        let path = temp_wal("coalesce");
4703        let coord = Arc::new(
4704            StoreCommitCoordinator::open(
4705                path.clone(),
4706                DurabilityMode::WalDurableGrouped,
4707                GroupCommitOptions::default(),
4708            )
4709            .expect("open commit coordinator"),
4710        );
4711
4712        const WRITERS: usize = 32;
4713        let barrier = Arc::new(Barrier::new(WRITERS));
4714        let mut handles = Vec::with_capacity(WRITERS);
4715        for tx in 0..WRITERS {
4716            let coord_c = Arc::clone(&coord);
4717            let barrier_c = Arc::clone(&barrier);
4718            handles.push(std::thread::spawn(move || {
4719                // Synchronise the start so every writer races the
4720                // drain loop together — this is the workload shape
4721                // the adaptive window is supposed to coalesce.
4722                barrier_c.wait();
4723                let action = StoreWalAction::CreateCollection {
4724                    name: format!("c{tx}"),
4725                };
4726                coord_c
4727                    .append_actions(std::slice::from_ref(&action))
4728                    .expect("append_actions");
4729            }));
4730        }
4731        for h in handles {
4732            h.join().expect("writer thread");
4733        }
4734
4735        let fsyncs = coord.fsync_count();
4736        assert!(fsyncs > 0, "expected at least one fsync, got {fsyncs}");
4737        assert!(
4738            fsyncs < WRITERS as u64,
4739            "expected fsyncs ({fsyncs}) to be strictly less than \
4740             concurrent writers ({WRITERS}); coalescing failed"
4741        );
4742
4743        drop(coord);
4744        let _ = std::fs::remove_file(&path);
4745    }
4746
4747    /// Sanity check: with the env override forcing a zero window,
4748    /// fsync coalescing degrades — callers race and we approach
4749    /// one fsync per caller. This proves the window is the actual
4750    /// knob doing the work above (i.e. the test isn't passing for
4751    /// some unrelated reason like buffered-IO coalescing).
4752    #[test]
4753    fn zero_window_disables_coalescing_floor() {
4754        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
4755        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "0");
4756
4757        let path = temp_wal("zero_window");
4758        let coord = Arc::new(
4759            StoreCommitCoordinator::open(
4760                path.clone(),
4761                DurabilityMode::WalDurableGrouped,
4762                GroupCommitOptions::default(),
4763            )
4764            .expect("open commit coordinator"),
4765        );
4766
4767        const WRITERS: usize = 8;
4768        let barrier = Arc::new(Barrier::new(WRITERS));
4769        let mut handles = Vec::with_capacity(WRITERS);
4770        for tx in 0..WRITERS {
4771            let coord_c = Arc::clone(&coord);
4772            let barrier_c = Arc::clone(&barrier);
4773            handles.push(std::thread::spawn(move || {
4774                barrier_c.wait();
4775                let action = StoreWalAction::CreateCollection {
4776                    name: format!("z{tx}"),
4777                };
4778                coord_c
4779                    .append_actions(std::slice::from_ref(&action))
4780                    .expect("append_actions");
4781            }));
4782        }
4783        for h in handles {
4784            h.join().expect("writer thread");
4785        }
4786
4787        // With zero window, fsync count is bounded above by WRITERS
4788        // (every caller might trigger its own drain) and below by 1
4789        // (the queue may still naturally batch under contention).
4790        // The point of the assertion is to confirm the env override
4791        // is wired through — the open() above used the env knob.
4792        let fsyncs = coord.fsync_count();
4793        assert!(fsyncs >= 1, "expected at least one fsync, got {fsyncs}");
4794
4795        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
4796        drop(coord);
4797        let _ = std::fs::remove_file(&path);
4798    }
4799
4800    /// `resolve_window` precedence: env > config.window_ms > default.
4801    #[test]
4802    fn resolve_window_precedence() {
4803        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
4804        // Default: window_ms=0 → adaptive 200µs floor.
4805        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
4806        let cfg = GroupCommitOptions::default();
4807        assert_eq!(
4808            StoreCommitCoordinator::resolve_window(&cfg),
4809            Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
4810        );
4811
4812        // Explicit ms config wins over the default floor.
4813        let cfg_ms = GroupCommitOptions {
4814            window_ms: 5,
4815            ..GroupCommitOptions::default()
4816        };
4817        assert_eq!(
4818            StoreCommitCoordinator::resolve_window(&cfg_ms),
4819            Duration::from_millis(5)
4820        );
4821
4822        // Env override wins over both.
4823        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "750");
4824        assert_eq!(
4825            StoreCommitCoordinator::resolve_window(&cfg),
4826            Duration::from_micros(750)
4827        );
4828        assert_eq!(
4829            StoreCommitCoordinator::resolve_window(&cfg_ms),
4830            Duration::from_micros(750)
4831        );
4832
4833        // Env=0 explicitly disables the floor.
4834        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "0");
4835        assert_eq!(
4836            StoreCommitCoordinator::resolve_window(&cfg),
4837            Duration::from_micros(0)
4838        );
4839
4840        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
4841    }
4842}