Skip to main content

reddb_server/storage/unified/store/
commit.rs

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