Skip to main content

reddb_server/storage/unified/store/
commit.rs

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