Skip to main content

reddb_server/storage/unified/store/
commit.rs

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