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