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