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