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