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