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 std::cell::RefCell;
5use std::io;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, Condvar, Mutex};
9
10/// Adaptive group-commit window applied when the configured
11/// `GroupCommitOptions::window_ms` is 0 (the historical default).
12///
13/// Sub-millisecond so individual single-writer commits don't see a
14/// visible latency penalty (a 200 µs floor sits below typical NVMe
15/// fsync latency of 50–150 µs by ~one fsync), while still giving a
16/// pipelined writer a chance to drop a second statement into the
17/// same drain cycle. A lone synchronous `insert_one` still pays one
18/// fsync per row in the worst case, but two back-to-back inserts on
19/// the same connection now coalesce into one drain. See P1 in
20/// `docs/perf/insert_sequential-2026-05-05.md`.
21///
22/// Override via `REDDB_GROUP_COMMIT_WINDOW_US` (microseconds). Set
23/// to `0` to disable the floor entirely (legacy behaviour). Set
24/// `REDDB_GROUP_COMMIT_WINDOW_MS` to any non-zero value to bypass
25/// this floor — explicit ms config wins.
26const DEFAULT_ADAPTIVE_WINDOW_US: u64 = 200;
27
28// Extra disk reservation for normal embedded overflow checkpoints, not a
29// per-write buffer allocation. Fresh files stay at 64 KiB. A single larger
30// indivisible action retains the existing capacity/oversize contract.
31const EMBEDDED_WAL_HEADROOM_LIMIT: u64 = 1024 * 1024;
32
33/// Shorthand — `Arc<parking_lot::Mutex<WalWriter>>` avoids poisoning
34/// (one writer panicking mid-append used to taint every subsequent
35/// lock acquisition) and shaves a few syscalls off the fast path.
36/// The group-commit coordinator + writer threads all acquire this
37/// mutex in the hot insert path, so the unpoison/fast-park win
38/// compounds under 16-way concurrency.
39type WalMutex = parking_lot::Mutex<WalWriter>;
40
41/// Shorthand for the group-commit coordinator's state pair. Same
42/// non-poisoning + lighter-park motivation as `WalMutex`; writer
43/// threads `wait` on this condvar until the coordinator publishes a
44/// new `durable_lsn`, so the park cost shows up on every
45/// WalDurableGrouped transaction.
46type CommitStateMutex = parking_lot::Mutex<CommitState>;
47type CommitStateCondvar = parking_lot::Condvar;
48use std::time::{Duration, Instant};
49
50static NEXT_STORE_TX_ID: AtomicU64 = AtomicU64::new(1);
51
52#[derive(Debug, Clone)]
53pub(crate) enum StoreWalAction {
54    CreateCollection {
55        name: String,
56    },
57    DropCollection {
58        name: String,
59    },
60    UpsertEntityRecord {
61        collection: String,
62        record: Vec<u8>,
63    },
64    DeleteEntityRecord {
65        collection: String,
66        entity_id: u64,
67    },
68    /// Batched upsert — one WAL action carrying N serialized entity
69    /// records for the same collection. Saves the per-row Begin/
70    /// PageWrite/Commit framing overhead on the bulk insert hot path.
71    /// Replay applies every contained record in order.
72    BulkUpsertEntityRecords {
73        collection: String,
74        records: Vec<Vec<u8>>,
75    },
76    /// Atomic full-collection replace — issue #595 slice 9c.
77    /// Replay drops the in-memory collection state and rebuilds it
78    /// from the contained records. Used by REFRESH MATERIALIZED VIEW
79    /// so a concurrent reader sees either the prior contents or the
80    /// new contents, never a partial state, and a crash mid-refresh
81    /// leaves the prior contents intact on recovery (the action is
82    /// only durable once the WAL commit lands).
83    RefreshCollection {
84        collection: String,
85        records: Vec<Vec<u8>>,
86    },
87}
88
89#[derive(Debug, Default)]
90pub(crate) struct DeferredStoreWalActions {
91    pub(super) actions: Vec<StoreWalAction>,
92}
93
94pub(super) struct StoreWalCaptureGuard<'a> {
95    active: bool,
96    session: Option<&'a crate::storage::embedded::EmbeddedCommitSession>,
97}
98
99impl<'a> StoreWalCaptureGuard<'a> {
100    pub(super) fn begin(
101        session: Option<&'a crate::storage::embedded::EmbeddedCommitSession>,
102    ) -> Self {
103        assert!(
104            !deferred_store_wal_capture_active(),
105            "store WAL captures cannot nest"
106        );
107        begin_deferred_store_wal_capture();
108        Self {
109            active: true,
110            session,
111        }
112    }
113
114    pub(super) fn finish(mut self) -> DeferredStoreWalActions {
115        let actions = take_deferred_store_wal_capture();
116        self.active = false;
117        actions
118    }
119}
120
121impl Drop for StoreWalCaptureGuard<'_> {
122    fn drop(&mut self) {
123        if self.active {
124            if let Some(session) = self.session {
125                session.fence_interrupted_write();
126            }
127            let _ = take_deferred_store_wal_capture();
128        }
129    }
130}
131
132impl DeferredStoreWalActions {
133    pub(crate) fn is_empty(&self) -> bool {
134        self.actions.is_empty()
135    }
136
137    pub(crate) fn extend(&mut self, other: Self) {
138        self.actions.extend(other.actions);
139    }
140}
141
142thread_local! {
143    static DEFERRED_STORE_WAL_ACTIONS: RefCell<Option<Vec<StoreWalAction>>> =
144        const { RefCell::new(None) };
145}
146
147fn begin_deferred_store_wal_capture() {
148    DEFERRED_STORE_WAL_ACTIONS.with(|cell| {
149        let mut guard = cell.borrow_mut();
150        debug_assert!(guard.is_none());
151        *guard = Some(Vec::new());
152    });
153}
154
155fn capture_deferred_store_wal_actions(actions: Vec<StoreWalAction>) -> bool {
156    DEFERRED_STORE_WAL_ACTIONS.with(|cell| {
157        let mut guard = cell.borrow_mut();
158        if let Some(pending) = guard.as_mut() {
159            pending.extend(actions);
160            true
161        } else {
162            false
163        }
164    })
165}
166
167fn deferred_store_wal_capture_active() -> bool {
168    DEFERRED_STORE_WAL_ACTIONS.with(|cell| cell.borrow().is_some())
169}
170
171fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
172    DEFERRED_STORE_WAL_ACTIONS.with(|cell| DeferredStoreWalActions {
173        actions: cell.borrow_mut().take().unwrap_or_default(),
174    })
175}
176
177impl StoreWalAction {
178    pub(crate) fn upsert_entity(
179        collection: &str,
180        entity: &UnifiedEntity,
181        metadata: Option<&Metadata>,
182        format_version: u32,
183    ) -> Self {
184        Self::UpsertEntityRecord {
185            collection: collection.to_string(),
186            record: UnifiedStore::serialize_entity_record(entity, metadata, format_version),
187        }
188    }
189
190    fn encode(&self) -> Vec<u8> {
191        reddb_file::encode_store_wal_action_frame(&self.to_frame())
192            .expect("encode store wal action frame")
193    }
194
195    fn to_frame(&self) -> reddb_file::StoreWalActionFrame {
196        match self {
197            Self::CreateCollection { name } => {
198                reddb_file::StoreWalActionFrame::CreateCollection { name: name.clone() }
199            }
200            Self::DropCollection { name } => {
201                reddb_file::StoreWalActionFrame::DropCollection { name: name.clone() }
202            }
203            Self::UpsertEntityRecord { collection, record } => {
204                reddb_file::StoreWalActionFrame::UpsertEntityRecord {
205                    collection: collection.clone(),
206                    record: record.clone(),
207                }
208            }
209            Self::DeleteEntityRecord {
210                collection,
211                entity_id,
212            } => reddb_file::StoreWalActionFrame::DeleteEntityRecord {
213                collection: collection.clone(),
214                entity_id: *entity_id,
215            },
216            Self::BulkUpsertEntityRecords {
217                collection,
218                records,
219            } => reddb_file::StoreWalActionFrame::BulkUpsertEntityRecords {
220                collection: collection.clone(),
221                records: records.clone(),
222            },
223            Self::RefreshCollection {
224                collection,
225                records,
226            } => reddb_file::StoreWalActionFrame::RefreshCollection {
227                collection: collection.clone(),
228                records: records.clone(),
229            },
230        }
231    }
232
233    fn decode(bytes: &[u8]) -> io::Result<Self> {
234        match reddb_file::decode_store_wal_action_frame(bytes)? {
235            reddb_file::StoreWalActionFrame::CreateCollection { name } => {
236                Ok(Self::CreateCollection { name })
237            }
238            reddb_file::StoreWalActionFrame::DropCollection { name } => {
239                Ok(Self::DropCollection { name })
240            }
241            reddb_file::StoreWalActionFrame::UpsertEntityRecord { collection, record } => {
242                Ok(Self::UpsertEntityRecord { collection, record })
243            }
244            reddb_file::StoreWalActionFrame::DeleteEntityRecord {
245                collection,
246                entity_id,
247            } => Ok(Self::DeleteEntityRecord {
248                collection,
249                entity_id,
250            }),
251            reddb_file::StoreWalActionFrame::BulkUpsertEntityRecords {
252                collection,
253                records,
254            } => Ok(Self::BulkUpsertEntityRecords {
255                collection,
256                records,
257            }),
258            reddb_file::StoreWalActionFrame::RefreshCollection {
259                collection,
260                records,
261            } => Ok(Self::RefreshCollection {
262                collection,
263                records,
264            }),
265        }
266    }
267}
268
269#[derive(Debug)]
270struct CommitState {
271    durable_lsn: u64,
272    pending_target_lsn: u64,
273    pending_statements: usize,
274    pending_wal_bytes: u64,
275    first_pending_at: Option<Instant>,
276    shutdown: bool,
277    last_error: Option<String>,
278}
279
280impl CommitState {
281    fn new(initial_durable_lsn: u64) -> Self {
282        Self {
283            durable_lsn: initial_durable_lsn,
284            pending_target_lsn: initial_durable_lsn,
285            pending_statements: 0,
286            pending_wal_bytes: 0,
287            first_pending_at: None,
288            shutdown: false,
289            last_error: None,
290        }
291    }
292}
293
294/// Lock-free append queue sitting in front of `WalWriter`.
295///
296/// Writers atomically reserve a byte range via `next_lsn.fetch_add`
297/// and push their encoded bytes into a parking_lot-guarded vector.
298/// The group-commit coordinator is the sole drainer: it sorts the
299/// pending entries by LSN (so the file bytes land at the offsets
300/// each writer reserved) and hands them to `WalWriter::append_bytes`.
301///
302/// This replaces the old `wal.lock() ... append ... append ... drop`
303/// hot path where 16 concurrent writers serialised on the WAL
304/// mutex for ~13µs each. Hold time on the queue's parking_lot
305/// mutex is ~200ns (just a Vec::push) — 65× shorter, so the mutex
306/// convoy on concurrent inserts disappears.
307pub(crate) struct WalAppendQueue {
308    /// Keep reserved offsets valid until their callers observe durability.
309    /// Reset also excludes an old flusher publishing state into the new WAL.
310    epoch: parking_lot::RwLock<()>,
311    /// Tuple of (monotonically-increasing LSN, pending-bytes vec)
312    /// protected by one mutex. Keeping the LSN reservation AND the
313    /// push under the same lock guarantees that every queue entry
314    /// is visible the moment its LSN is assigned — no gap between
315    /// `fetch_add` and `push` for the leader to spin on.
316    ///
317    /// Earlier versions reserved LSN with an `AtomicU64::fetch_add`
318    /// outside the lock; the leader drain observed reordered
319    /// `(lsn, bytes)` tuples whose pushes happened in a different
320    /// order than their fetch_add, creating "holes" in the LSN
321    /// sequence that the drain loop interpreted as "wait for the
322    /// missing enqueuer" — under tokio scheduling pressure the
323    /// missing enqueuer was preempted indefinitely and the
324    /// drain loop busy-waited forever (WAL stayed at 8 bytes).
325    pending: parking_lot::Mutex<WalQueueState>,
326    /// Bytes of encoded records sitting in `pending.entries` (ADR 0073 §2,
327    /// the `wal_buffers` pool). A relaxed atomic rather than a field inside
328    /// `WalQueueState` so a reader sampling the accounting never contends
329    /// with an enqueuer for the queue mutex.
330    queued_bytes: AtomicU64,
331}
332
333struct WalQueueState {
334    next_lsn: u64,
335    entries: Vec<(u64, Vec<u8>)>,
336}
337
338impl WalAppendQueue {
339    fn new(initial_lsn: u64) -> Self {
340        Self {
341            epoch: parking_lot::RwLock::new(()),
342            pending: parking_lot::Mutex::new(WalQueueState {
343                next_lsn: initial_lsn,
344                entries: Vec::with_capacity(64),
345            }),
346            queued_bytes: AtomicU64::new(0),
347        }
348    }
349
350    /// Reserve an LSN range of `bytes.len()` bytes and push onto the
351    /// queue. Returns the commit LSN (end of reserved range), which
352    /// the caller passes to `wait_until_durable`. LSN assignment and
353    /// push happen under the same mutex — no gap for the drain loop
354    /// to busy-spin on.
355    fn enqueue(&self, bytes: Vec<u8>) -> u64 {
356        let len = bytes.len() as u64;
357        let mut state = self.pending.lock();
358        let start_lsn = state.next_lsn;
359        state.next_lsn = start_lsn + len;
360        state.entries.push((start_lsn, bytes));
361        self.queued_bytes.fetch_add(len, Ordering::Relaxed);
362        start_lsn + len
363    }
364
365    /// Drain all queued entries in LSN order. Caller holds the WAL
366    /// file mutex while writing the drained bytes so the on-disk
367    /// layout matches the reserved LSN offsets.
368    fn drain_sorted(&self) -> Vec<(u64, Vec<u8>)> {
369        let mut state = self.pending.lock();
370        let mut v = std::mem::take(&mut state.entries);
371        let drained: u64 = v.iter().map(|(_, bytes)| bytes.len() as u64).sum();
372        drop(state);
373        // Saturating: the drain is the only consumer, so `queued_bytes` can
374        // never sit below what this call took, but an accounting counter that
375        // wraps would poison `red.stats` far past the bug that caused it.
376        let _ = self
377            .queued_bytes
378            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |queued| {
379                Some(queued.saturating_sub(drained))
380            });
381        v.sort_by_key(|(lsn, _)| *lsn);
382        v
383    }
384
385    /// Whether any entry is queued. Leader uses this to decide
386    /// whether to spin once more or go back to the condvar.
387    fn has_pending(&self) -> bool {
388        !self.pending.lock().entries.is_empty()
389    }
390
391    /// Encoded record bytes currently buffered in memory.
392    fn queued_bytes(&self) -> u64 {
393        self.queued_bytes.load(Ordering::Relaxed)
394    }
395
396    /// Reset the LSN cursor and discard any queued entries. Used
397    /// after `wal.truncate()` — the wal-side byte counter goes back
398    /// to the header size, so the queue (which tracks LSNs in the
399    /// same byte space) must follow or every subsequent enqueue
400    /// returns a target the drain loop can never reach.
401    fn reset(&self, next_lsn: u64) {
402        let mut state = self.pending.lock();
403        state.next_lsn = next_lsn;
404        state.entries.clear();
405        drop(state);
406        self.queued_bytes.store(0, Ordering::Relaxed);
407    }
408}
409
410pub(crate) struct StoreCommitCoordinator {
411    mode: DurabilityMode,
412    config: crate::api::GroupCommitOptions,
413    wal_path: PathBuf,
414    wal: Arc<WalMutex>,
415    /// Lock-free front door for writers. Populated alongside
416    /// `WalDurableGrouped` / `Async` modes so concurrent inserts
417    /// never contend on `wal` for the append step. Strict mode
418    /// bypasses the queue and calls `WalWriter::append` directly
419    /// to preserve the one-fsync-per-commit semantic.
420    queue: Arc<WalAppendQueue>,
421    state: Arc<(CommitStateMutex, CommitStateCondvar)>,
422    /// Number of `wal.sync()` calls issued by the group-commit
423    /// drain loop. Used by tests to observe coalescing — a burst
424    /// of N concurrent commits should bump this by far less than N
425    /// when the adaptive window is doing its job. Strict-mode
426    /// commits go through `force_sync` which also bumps this.
427    fsync_count: Arc<AtomicU64>,
428}
429
430impl StoreCommitCoordinator {
431    pub(crate) fn open(
432        wal_path: impl Into<PathBuf>,
433        mode: DurabilityMode,
434        config: crate::api::GroupCommitOptions,
435    ) -> io::Result<Self> {
436        let wal_path = wal_path.into();
437        let wal = WalWriter::open(&wal_path)?;
438        let initial_durable_lsn = wal.durable_lsn();
439        let initial_current_lsn = wal.current_lsn();
440        let wal = Arc::new(WalMutex::new(wal));
441        let queue = Arc::new(WalAppendQueue::new(initial_current_lsn));
442        let state = Arc::new((
443            CommitStateMutex::new(CommitState::new(initial_durable_lsn)),
444            CommitStateCondvar::new(),
445        ));
446        let fsync_count = Arc::new(AtomicU64::new(0));
447
448        if matches!(
449            mode,
450            DurabilityMode::WalDurableGrouped | DurabilityMode::Async
451        ) {
452            let wal_bg = Arc::clone(&wal);
453            let queue_bg = Arc::clone(&queue);
454            let state_bg = Arc::clone(&state);
455            let fsync_bg = Arc::clone(&fsync_count);
456            // P1: adaptive group-commit window. Historical default is
457            // `window_ms = 0` ("no wait"), which under single-writer
458            // OLTP means one fsync per autocommit row — the throughput
459            // floor. When window_ms is 0 we fall back to a small
460            // microsecond floor (`DEFAULT_ADAPTIVE_WINDOW_US`, override
461            // via `REDDB_GROUP_COMMIT_WINDOW_US`) so a pipelined writer
462            // can drop a second statement into the same drain cycle.
463            // Explicit non-zero `window_ms` config takes precedence.
464            //
465            // The loop already short-circuits on
466            // `pending_statements >= max_statements` /
467            // `pending_wal_bytes >= max_wal_bytes`, so the window only
468            // delays the leader when the queue is otherwise empty —
469            // exactly the case we want to coalesce.
470            let window = Self::resolve_window(&config);
471            let max_statements = config.max_statements.max(1);
472            let max_wal_bytes = config.max_wal_bytes.max(1);
473            std::thread::spawn(move || {
474                Self::run_group_commit_loop(
475                    wal_bg,
476                    queue_bg,
477                    state_bg,
478                    fsync_bg,
479                    window,
480                    max_statements,
481                    max_wal_bytes,
482                );
483            });
484        }
485
486        Ok(Self {
487            mode,
488            config,
489            wal_path,
490            wal,
491            queue,
492            state,
493            fsync_count,
494        })
495    }
496
497    /// Resolve the effective group-commit window from the configured
498    /// options + the `REDDB_GROUP_COMMIT_WINDOW_US` env override.
499    ///
500    /// Precedence (highest first):
501    ///   1. `REDDB_GROUP_COMMIT_WINDOW_US=N` — N µs (0 disables).
502    ///   2. `config.window_ms != 0` — explicit ms config wins.
503    ///   3. `DEFAULT_ADAPTIVE_WINDOW_US` — adaptive floor for the
504    ///      historical zero-default. Set the env var to 0 to opt out.
505    fn resolve_window(config: &crate::api::GroupCommitOptions) -> Duration {
506        if let Ok(raw) = std::env::var("REDDB_GROUP_COMMIT_WINDOW_US") {
507            if let Ok(parsed) = raw.parse::<u64>() {
508                return Duration::from_micros(parsed);
509            }
510        }
511        if config.window_ms != 0 {
512            return Duration::from_millis(config.window_ms);
513        }
514        Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
515    }
516
517    /// Total `wal.sync()` calls issued since this coordinator opened.
518    /// Public for tests that want to observe fsync coalescing under
519    /// concurrent autocommits.
520    #[cfg(test)]
521    pub(crate) fn fsync_count(&self) -> u64 {
522        self.fsync_count.load(Ordering::Relaxed)
523    }
524
525    /// WAL buffer memory held right now: encoded records waiting in the
526    /// group-commit queue plus the writer's fixed append buffer, which exists
527    /// for the coordinator's whole life (ADR 0073 §2, the `wal_buffers` pool).
528    pub(crate) fn buffered_bytes(&self) -> u64 {
529        self.queue.queued_bytes() + crate::storage::wal::WAL_BUFFER_BYTES as u64
530    }
531
532    pub(crate) fn append_actions(&self, actions: &[StoreWalAction]) -> io::Result<()> {
533        if actions.is_empty() {
534            return Ok(());
535        }
536        let _epoch = self.queue.epoch.read();
537
538        let tx_id = NEXT_STORE_TX_ID.fetch_add(1, Ordering::SeqCst);
539
540        // Strict mode: bypass the queue, write + fsync inline. Strict
541        // commits are exactly one-fsync-per-call by contract, so the
542        // coalescing win of the queue doesn't apply and we'd pay an
543        // extra hop through the drain loop.
544        if matches!(self.mode, DurabilityMode::Strict) {
545            let commit_lsn = {
546                let mut wal = self.wal.lock();
547                wal.append(&WalRecord::TxCommitBatch {
548                    tx_id,
549                    actions: actions.iter().map(StoreWalAction::encode).collect(),
550                })?;
551                wal.current_lsn()
552            };
553            self.force_sync()?;
554            let _ = commit_lsn;
555            return Ok(());
556        }
557
558        // Grouped / Async path — lock-free enqueue. Encode every
559        // WalRecord into one contiguous byte blob OUTSIDE any lock,
560        // then hand it to the queue with a single fetch_add+push.
561        let encoded_actions: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
562        let wal_bytes = encoded_actions.iter().fold(0u64, |total, payload| {
563            total.saturating_add(payload.len() as u64)
564        });
565        let blob = WalRecord::TxCommitBatch {
566            tx_id,
567            actions: encoded_actions,
568        }
569        .encode();
570
571        let commit_lsn = self.queue.enqueue(blob);
572        self.wait_until_durable(commit_lsn, wal_bytes)?;
573        Ok(())
574    }
575
576    /// Encode + enqueue a single, non-batched [`WalRecord`] (issue
577    /// #693). Honours the same Strict / Grouped / Async branching as
578    /// [`Self::append_actions`] so durability semantics are uniform
579    /// across record kinds.
580    pub(crate) fn append_single_record(&self, record: WalRecord) -> io::Result<()> {
581        let _epoch = self.queue.epoch.read();
582        let blob = record.encode();
583        let wal_bytes = blob.len() as u64;
584        if matches!(self.mode, DurabilityMode::Strict) {
585            {
586                let mut wal = self.wal.lock();
587                wal.append(&record)?;
588            }
589            self.force_sync()?;
590            return Ok(());
591        }
592        let commit_lsn = self.queue.enqueue(blob);
593        self.wait_until_durable(commit_lsn, wal_bytes)?;
594        Ok(())
595    }
596
597    pub(crate) fn force_sync(&self) -> io::Result<()> {
598        // Strict append already owns a read lease. Do not wait behind a
599        // checkpoint that needs that append to finish before resetting.
600        let _epoch = self.queue.epoch.read_recursive();
601        {
602            let mut wal = self.wal.lock();
603            wal.sync()?;
604            self.fsync_count.fetch_add(1, Ordering::Relaxed);
605            let durable = wal.durable_lsn();
606            drop(wal);
607            let (state_lock, cond) = &*self.state;
608            let mut state = state_lock.lock();
609            state.durable_lsn = durable;
610            state.pending_target_lsn = durable.max(state.pending_target_lsn);
611            state.pending_statements = 0;
612            state.pending_wal_bytes = 0;
613            state.first_pending_at = None;
614            state.last_error = None;
615            cond.notify_all();
616        }
617        Ok(())
618    }
619
620    pub(crate) fn truncate(&self) -> io::Result<()> {
621        let _epoch = self.queue.epoch.write();
622        let mut wal = self.wal.lock();
623        wal.truncate()?;
624        let durable = wal.durable_lsn();
625        let current = wal.current_lsn();
626        drop(wal);
627
628        // Queue's next_lsn tracks byte offsets in the same space as
629        // wal.current_lsn. After truncate both must be reset together
630        // — otherwise enqueue returns a target_lsn in the old range
631        // that drain can never reach, and wait_until_durable hangs.
632        self.queue.reset(current);
633
634        let (state_lock, cond) = &*self.state;
635        let mut state = state_lock.lock();
636        state.durable_lsn = durable;
637        state.pending_target_lsn = durable;
638        state.pending_statements = 0;
639        state.pending_wal_bytes = 0;
640        state.first_pending_at = None;
641        state.last_error = None;
642        cond.notify_all();
643        Ok(())
644    }
645
646    pub(crate) fn replay_into(&self, store: &UnifiedStore) -> io::Result<()> {
647        if !self.wal_path.exists() {
648            return Ok(());
649        }
650
651        let reader = match WalReader::open(&self.wal_path) {
652            Ok(reader) => reader,
653            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
654            Err(err) => return Err(err),
655        };
656
657        let mut tx_states = std::collections::HashMap::<u64, bool>::new();
658        let mut pending = Vec::<(u64, Vec<u8>)>::new();
659        let mut applied = false;
660
661        for record in reader.iter() {
662            let (_lsn, record) = match record {
663                Ok(record) => record,
664                Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break,
665                Err(err) => return Err(err),
666            };
667            match record {
668                WalRecord::TxCommitBatch { actions, .. } => {
669                    for payload in actions {
670                        let action = StoreWalAction::decode(&payload)?;
671                        applied = true;
672                        store.apply_replayed_action(&action, false).map_err(|err| {
673                            io::Error::other(format!("failed to replay store wal action: {err}"))
674                        })?;
675                    }
676                }
677                WalRecord::Begin { tx_id } => {
678                    tx_states.insert(tx_id, false);
679                }
680                WalRecord::Commit { tx_id } => {
681                    tx_states.insert(tx_id, true);
682                }
683                WalRecord::Rollback { tx_id } => {
684                    tx_states.remove(&tx_id);
685                }
686                WalRecord::PageWrite {
687                    tx_id,
688                    page_id: _,
689                    data,
690                } => pending.push((tx_id, data)),
691                WalRecord::Checkpoint { .. } => {}
692                WalRecord::VectorInsert {
693                    collection,
694                    entity_id,
695                    vector,
696                } => {
697                    // Issue #694 — capture `vector.turbo` WAL inserts so the
698                    // boot-time TurboQuant index rebuild can drain them in
699                    // WAL order (deterministic against the pre-restart
700                    // state under a fixed codec seed). The legacy `vector`
701                    // path doesn't read this map.
702                    let mut map = store.replayed_turbo_inserts.lock();
703                    map.entry(collection).or_default().push((entity_id, vector));
704                }
705                WalRecord::ProbabilisticDelta {
706                    kind,
707                    operation,
708                    name,
709                    operands,
710                } => {
711                    let mut deltas = store.replayed_probabilistic_deltas.lock();
712                    deltas.push((kind, operation, name, operands));
713                }
714                WalRecord::FullPageImage { .. } => {
715                    // Pager-level FPI (gh-478); store replay ignores.
716                }
717            }
718        }
719
720        for (tx_id, payload) in pending {
721            if !tx_states.get(&tx_id).copied().unwrap_or(false) {
722                continue;
723            }
724            let action = StoreWalAction::decode(&payload)?;
725            applied = true;
726            store.apply_replayed_action(&action, false).map_err(|err| {
727                io::Error::other(format!("failed to replay store wal action: {err}"))
728            })?;
729        }
730
731        if applied {
732            store
733                .reconcile_replayed_btrees()
734                .map_err(|err| io::Error::other(err.to_string()))?;
735        }
736        Ok(())
737    }
738
739    fn wait_until_durable(&self, target_lsn: u64, wal_bytes: u64) -> io::Result<()> {
740        match self.mode {
741            DurabilityMode::Strict => self.force_sync(),
742            // Async: record the pending target so the background
743            // flusher eventually covers it, but don't block the
744            // caller. Matches PG `synchronous_commit=off` semantics —
745            // crash inside the flush window loses unflushed commits.
746            DurabilityMode::Async => {
747                let (state_lock, cond) = &*self.state;
748                let mut state = state_lock.lock();
749                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
750                state.pending_statements = state.pending_statements.saturating_add(1);
751                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
752                state.first_pending_at.get_or_insert_with(Instant::now);
753                cond.notify_all();
754                Ok(())
755            }
756            DurabilityMode::WalDurableGrouped => {
757                let (state_lock, cond) = &*self.state;
758                let mut state = state_lock.lock();
759                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
760                state.pending_statements = state.pending_statements.saturating_add(1);
761                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
762                state.first_pending_at.get_or_insert_with(Instant::now);
763                cond.notify_all();
764
765                loop {
766                    if let Some(err) = state.last_error.clone() {
767                        return Err(io::Error::other(err));
768                    }
769                    if state.durable_lsn >= target_lsn {
770                        return Ok(());
771                    }
772                    // parking_lot::Condvar mutates the guard in place —
773                    // no LockResult to unwrap, no poisoning to fold.
774                    cond.wait(&mut state);
775                }
776            }
777        }
778    }
779
780    fn run_group_commit_loop(
781        wal: Arc<WalMutex>,
782        queue: Arc<WalAppendQueue>,
783        state: Arc<(CommitStateMutex, CommitStateCondvar)>,
784        fsync_count: Arc<AtomicU64>,
785        window: Duration,
786        max_statements: usize,
787        max_wal_bytes: u64,
788    ) {
789        let (state_lock, cond) = &*state;
790        loop {
791            let target_lsn = {
792                let mut guard = state_lock.lock();
793
794                while !guard.shutdown && guard.pending_target_lsn <= guard.durable_lsn {
795                    cond.wait(&mut guard);
796                }
797
798                if guard.shutdown {
799                    return;
800                }
801
802                let immediate = window.is_zero()
803                    || guard.pending_statements >= max_statements
804                    || guard.pending_wal_bytes >= max_wal_bytes;
805
806                if !immediate {
807                    let deadline = guard.first_pending_at.unwrap_or_else(Instant::now) + window;
808                    let now = Instant::now();
809                    if now < deadline {
810                        let timeout = deadline.saturating_duration_since(now);
811                        let _ = cond.wait_for(&mut guard, timeout);
812                        if guard.shutdown {
813                            return;
814                        }
815                        if guard.pending_target_lsn <= guard.durable_lsn {
816                            continue;
817                        }
818                        let should_wait_again = guard.pending_statements < max_statements
819                            && guard.pending_wal_bytes < max_wal_bytes
820                            && guard
821                                .first_pending_at
822                                .map(|first| first.elapsed() < window)
823                                .unwrap_or(false);
824                        if should_wait_again {
825                            continue;
826                        }
827                    }
828                }
829
830                guard.pending_target_lsn
831            };
832
833            // Drain the current epoch even when reset is waiting: outstanding
834            // append leases cannot finish until this flusher acknowledges them.
835            // Retain the lease through state publication to exclude stale ACKs
836            // after a checkpoint resets offsets back to the WAL header.
837            let _epoch = queue.epoch.read_recursive();
838
839            // Drain all queued entries. Since `WalAppendQueue::enqueue`
840            // assigns LSN and pushes under a single mutex, the drained
841            // tuples are guaranteed to form a contiguous byte range
842            // starting at `wal.current_lsn()` — no gaps, no leftover
843            // handling.
844            let batches = queue.drain_sorted();
845
846            let sync_result = {
847                let mut wal = wal.lock();
848                let mut write_err: Option<io::Error> = None;
849                for (_lsn, bytes) in batches {
850                    if let Err(e) = wal.append_bytes(&bytes) {
851                        write_err = Some(e);
852                        break;
853                    }
854                }
855                match write_err {
856                    Some(e) => Err(e),
857                    None => wal.sync().map(|_| {
858                        // Count the fsync exactly once per drain
859                        // cycle so tests can compare it against the
860                        // number of `append_actions` callers that
861                        // entered the queue.
862                        fsync_count.fetch_add(1, Ordering::Relaxed);
863                        wal.durable_lsn()
864                    }),
865                }
866            };
867
868            // Late enqueuers that arrived after our drain stay in the
869            // queue — don't clear the `pending_*` counters yet and
870            // don't claim we reached `target_lsn` unless the fsync
871            // actually covers it.
872            let more_pending = queue.has_pending();
873
874            let mut guard = state_lock.lock();
875            match sync_result {
876                Ok(durable_lsn) => {
877                    guard.durable_lsn = durable_lsn;
878                    if !more_pending {
879                        guard.pending_statements = 0;
880                        guard.pending_wal_bytes = 0;
881                        guard.first_pending_at = None;
882                    }
883                    guard.last_error = None;
884                    let _ = target_lsn;
885                }
886                Err(err) => {
887                    guard.last_error = Some(err.to_string());
888                }
889            }
890            cond.notify_all();
891        }
892    }
893}
894
895impl Drop for StoreCommitCoordinator {
896    fn drop(&mut self) {
897        let (state_lock, cond) = &*self.state;
898        // parking_lot::Mutex::lock is infallible (no poisoning).
899        let mut state = state_lock.lock();
900        state.shutdown = true;
901        cond.notify_all();
902    }
903}
904
905impl UnifiedStore {
906    pub(crate) fn deferred_store_wal_capture_active() -> bool {
907        deferred_store_wal_capture_active()
908    }
909
910    pub(crate) fn begin_deferred_store_wal_capture() {
911        begin_deferred_store_wal_capture();
912    }
913
914    pub(crate) fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
915        take_deferred_store_wal_capture()
916    }
917
918    pub(crate) fn append_deferred_store_wal_actions(
919        &self,
920        actions: DeferredStoreWalActions,
921    ) -> Result<(), StoreError> {
922        if actions.actions.is_empty() {
923            return Ok(());
924        }
925        if self.config.embedded_wal_path.is_some() {
926            return self.append_embedded_store_wal_actions(&actions.actions);
927        }
928        // Deferred transactions need a committed WAL batch even in Strict
929        // mode. WAL-only versions have no pager pages to flush yet.
930        if let Some(commit) = &self.commit {
931            commit
932                .append_actions(&actions.actions)
933                .map_err(StoreError::Io)
934        } else {
935            self.flush_paged_state()
936        }
937    }
938
939    /// Emit a [`WalRecord::VectorInsert`] for a `vector.turbo`
940    /// collection (issue #693). Returns `Ok(())` when no commit
941    /// coordinator is configured (in-memory mode) so callers don't
942    /// have to special-case the missing WAL — the in-memory index
943    /// update remains durable enough for in-memory runtimes by
944    /// construction.
945    pub(crate) fn append_vector_insert_record(
946        &self,
947        collection: &str,
948        entity_id: u64,
949        vector: &[f32],
950    ) -> std::io::Result<()> {
951        let Some(commit) = &self.commit else {
952            return Ok(());
953        };
954        let record = WalRecord::VectorInsert {
955            collection: collection.to_string(),
956            entity_id,
957            vector: vector.to_vec(),
958        };
959        commit.append_single_record(record)
960    }
961
962    pub(crate) fn append_probabilistic_delta_record(
963        &self,
964        kind: u8,
965        operation: u8,
966        name: &str,
967        operands: Vec<Vec<u8>>,
968    ) -> std::io::Result<()> {
969        let Some(commit) = &self.commit else {
970            return Ok(());
971        };
972        let record = WalRecord::ProbabilisticDelta {
973            kind,
974            operation,
975            name: name.to_string(),
976            operands,
977        };
978        commit.append_single_record(record)
979    }
980
981    pub(crate) fn finish_paged_write(
982        &self,
983        actions: impl IntoIterator<Item = StoreWalAction>,
984    ) -> Result<(), StoreError> {
985        let actions: Vec<StoreWalAction> = actions.into_iter().collect();
986        if deferred_store_wal_capture_active() {
987            let captured = capture_deferred_store_wal_actions(actions);
988            debug_assert!(captured);
989            return Ok(());
990        }
991        if self.config.embedded_wal_path.is_some() {
992            return self.append_embedded_store_wal_actions(&actions);
993        }
994        match self.config.durability_mode {
995            DurabilityMode::Strict => {
996                if let Some(commit) = &self.commit {
997                    commit.append_actions(&actions).map_err(StoreError::Io)?;
998                }
999                self.flush_paged_state()
1000            }
1001            DurabilityMode::WalDurableGrouped | DurabilityMode::Async => {
1002                if let Some(commit) = &self.commit {
1003                    commit.append_actions(&actions).map_err(StoreError::Io)?;
1004                    Ok(())
1005                } else {
1006                    self.flush_paged_state()
1007                }
1008            }
1009        }
1010    }
1011
1012    pub(crate) fn apply_encoded_store_wal_action(&self, payload: &[u8]) -> Result<(), StoreError> {
1013        let action = StoreWalAction::decode(payload).map_err(StoreError::Io)?;
1014        self.apply_replayed_action(&action, true)
1015    }
1016
1017    fn append_embedded_store_wal_actions(
1018        &self,
1019        actions: &[StoreWalAction],
1020    ) -> Result<(), StoreError> {
1021        let Some(path) = self.config.embedded_wal_path.as_deref() else {
1022            return Ok(());
1023        };
1024        if actions.is_empty() {
1025            return Ok(());
1026        }
1027        let payloads: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
1028        let encoded_len = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
1029            .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
1030        match self.append_embedded_payloads(path, &payloads) {
1031            Ok(_) => Ok(()),
1032            Err(crate::api::RedDBError::InvalidOperation(msg))
1033                if msg.contains("embedded wal region full") =>
1034            {
1035                self.recover_full_embedded_wal(path, &payloads, encoded_len)
1036            }
1037            Err(err) => Err(StoreError::Io(std::io::Error::other(err.to_string()))),
1038        }
1039    }
1040
1041    fn recover_full_embedded_wal(
1042        &self,
1043        path: &Path,
1044        payloads: &[Vec<u8>],
1045        encoded_len: u64,
1046    ) -> Result<(), StoreError> {
1047        let _vault_guard = self.vault_publication_lock.lock();
1048        // The failed append preceded this lock: another writer may already
1049        // have reclaimed space. Retry through the same FIFO coordinator so
1050        // stale full results cannot each serialize another complete snapshot.
1051        match self.append_embedded_payloads(path, payloads) {
1052            Ok(_) => return Ok(()),
1053            Err(crate::api::RedDBError::InvalidOperation(message))
1054                if message.contains("embedded wal region full") => {}
1055            Err(error) => return Err(StoreError::Io(std::io::Error::other(error.to_string()))),
1056        }
1057        // A checkpoint can fail after publishing its image. Preserve the
1058        // session failure fence through errors and unwinding, just as append's
1059        // FlushBatch guard does; in-memory rollback alone cannot resolve disk.
1060        struct CheckpointFence<'a>(Option<&'a crate::storage::embedded::EmbeddedCommitSession>);
1061        impl Drop for CheckpointFence<'_> {
1062            fn drop(&mut self) {
1063                if let Some(session) = self.0 {
1064                    session.fence_interrupted_write();
1065                }
1066            }
1067        }
1068        let mut fence = CheckpointFence(Some(
1069            self.embedded_commit_session
1070                .get()
1071                .expect("WAL-full recovery follows an append attempt"),
1072        ));
1073        let started = Instant::now();
1074        let snapshot = self.to_binary_dump_bytes();
1075        let capacity = encoded_len.max((snapshot.len() as u64).min(EMBEDDED_WAL_HEADROOM_LIMIT));
1076        let checkpoint = crate::storage::EmbeddedRdbArtifact::write_snapshot_with_wal_capacity(
1077            path, &snapshot, capacity,
1078        )
1079        .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
1080        fence.0 = None;
1081        tracing::debug!(
1082            target: "reddb::embedded_checkpoint",
1083            snapshot_bytes = snapshot.len(),
1084            wal_region_bytes = checkpoint.manifest.wal_region_bytes,
1085            elapsed_us = started.elapsed().as_micros() as u64,
1086            "embedded WAL overflow checkpoint"
1087        );
1088        self.append_embedded_payloads(path, payloads)
1089            .map(|_| ())
1090            .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))
1091    }
1092
1093    fn append_embedded_payloads(
1094        &self,
1095        path: &Path,
1096        payloads: &[Vec<u8>],
1097    ) -> crate::RedDBResult<crate::storage::EmbeddedRdbOpen> {
1098        let session = self
1099            .embedded_commit_session
1100            .get_or_init(|| crate::storage::EmbeddedRdbArtifact::group_commit_session(path));
1101        let options = self.config.group_commit;
1102        let grouped = self.config.durability_mode == DurabilityMode::WalDurableGrouped;
1103        let window = if grouped {
1104            StoreCommitCoordinator::resolve_window(&options)
1105        } else {
1106            Duration::ZERO
1107        };
1108        session.append(
1109            payloads,
1110            reddb_file::embedded::EmbeddedGroupCommitOptions {
1111                window,
1112                max_statements: if grouped { options.max_statements } else { 1 },
1113                max_wal_bytes: options.max_wal_bytes,
1114            },
1115        )
1116    }
1117
1118    pub(super) fn enqueue_grouped_actions(
1119        &self,
1120        actions: &[StoreWalAction],
1121    ) -> Result<Option<crate::storage::embedded::PendingEmbeddedAppend>, StoreError> {
1122        if self.config.durability_mode != DurabilityMode::WalDurableGrouped
1123            || deferred_store_wal_capture_active()
1124        {
1125            return Ok(None);
1126        }
1127        let Some(path) = self.config.embedded_wal_path.as_deref() else {
1128            return Ok(None);
1129        };
1130        let session = self
1131            .embedded_commit_session
1132            .get_or_init(|| crate::storage::EmbeddedRdbArtifact::group_commit_session(path));
1133        let payloads: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
1134        let options = self.config.group_commit;
1135        session
1136            .enqueue(
1137                &payloads,
1138                reddb_file::embedded::EmbeddedGroupCommitOptions {
1139                    window: StoreCommitCoordinator::resolve_window(&options),
1140                    max_statements: options.max_statements,
1141                    max_wal_bytes: options.max_wal_bytes,
1142                },
1143            )
1144            .map(Some)
1145            .map_err(|error| StoreError::Io(io::Error::other(error.to_string())))
1146    }
1147
1148    pub(super) fn complete_grouped_actions(
1149        &self,
1150        pending: &crate::storage::embedded::PendingEmbeddedAppend,
1151        actions: &[StoreWalAction],
1152    ) -> Result<(), StoreError> {
1153        match pending.wait() {
1154            Ok(_) => Ok(()),
1155            Err(crate::RedDBError::InvalidOperation(message))
1156                if message.contains("embedded wal region full") =>
1157            {
1158                self.append_embedded_store_wal_actions(actions)
1159            }
1160            Err(error) => Err(StoreError::Io(io::Error::other(error.to_string()))),
1161        }
1162    }
1163
1164    pub(crate) fn apply_replayed_action(
1165        &self,
1166        action: &StoreWalAction,
1167        update_btrees: bool,
1168    ) -> Result<(), StoreError> {
1169        match action {
1170            StoreWalAction::CreateCollection { name } => {
1171                if self.get_collection(name).is_none() {
1172                    let _ = self.create_collection_in_memory(name);
1173                }
1174                Ok(())
1175            }
1176            StoreWalAction::DropCollection { name } => self.drop_collection_in_memory(name),
1177            StoreWalAction::UpsertEntityRecord { collection, record } => {
1178                self.apply_replayed_upsert(collection, record, update_btrees)
1179            }
1180            StoreWalAction::DeleteEntityRecord {
1181                collection,
1182                entity_id,
1183            } => self.apply_replayed_delete(collection, EntityId::new(*entity_id), update_btrees),
1184            StoreWalAction::BulkUpsertEntityRecords {
1185                collection,
1186                records,
1187            } => {
1188                for record in records {
1189                    self.apply_replayed_upsert(collection, record, update_btrees)?;
1190                }
1191                Ok(())
1192            }
1193            StoreWalAction::RefreshCollection {
1194                collection,
1195                records,
1196            } => self.apply_replayed_refresh_collection(collection, records, update_btrees),
1197        }
1198    }
1199
1200    /// Atomic full-collection replace — issue #595 slice 9c.
1201    ///
1202    /// Builds a fresh `SegmentManager` populated with `entities`,
1203    /// atomically swaps it into the collections map, rebuilds the
1204    /// paged B-tree from the same records, and emits a single
1205    /// `RefreshCollection` WAL action.
1206    ///
1207    /// Concurrent readers that resolved an `Arc<SegmentManager>` for
1208    /// this collection before the swap continue reading the prior
1209    /// contents; readers after the swap see the new contents. The
1210    /// transition is single-pointer so partial state is unobservable.
1211    ///
1212    /// A crash between in-memory mutation and WAL fsync leaves the
1213    /// previous WAL stream intact — on recovery the prior
1214    /// `RefreshCollection` (or whatever last bulk-applied to the
1215    /// collection) is replayed, so the prior contents are observed.
1216    pub fn refresh_collection(
1217        &self,
1218        name: &str,
1219        entities: Vec<UnifiedEntity>,
1220    ) -> Result<Vec<Vec<u8>>, StoreError> {
1221        let fv = self.format_version();
1222
1223        // Build a fresh manager. Done outside the collections lock so
1224        // the critical section is just the pointer swap below.
1225        let new_manager = Arc::new(SegmentManager::with_config(
1226            name,
1227            self.config.manager_config.clone(),
1228        ));
1229
1230        let mut prepared = entities;
1231        for entity in &mut prepared {
1232            if entity.id.raw() == 0 {
1233                entity.id = self.next_entity_id();
1234            } else {
1235                self.register_entity_id(entity.id);
1236            }
1237            if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
1238                if *row_id == 0 {
1239                    *row_id = new_manager.next_row_id();
1240                } else {
1241                    new_manager.register_row_id(*row_id);
1242                }
1243            }
1244            entity.ensure_table_logical_id();
1245        }
1246
1247        let serialized: Vec<Vec<u8>> = prepared
1248            .iter()
1249            .map(|e| Self::serialize_entity_record(e, None, fv))
1250            .collect();
1251
1252        new_manager.bulk_insert(prepared.clone()).map_err(|e| {
1253            StoreError::Io(std::io::Error::other(format!(
1254                "refresh_collection: bulk_insert into new manager failed: {e}"
1255            )))
1256        })?;
1257
1258        self.swap_collection_state(name, new_manager, &prepared, &serialized, true);
1259
1260        self.finish_paged_write([StoreWalAction::RefreshCollection {
1261            collection: name.to_string(),
1262            records: serialized.clone(),
1263        }])?;
1264
1265        Ok(serialized)
1266    }
1267
1268    /// Atomic swap of the in-memory collection state. Used by both
1269    /// the live `refresh_collection` path and WAL replay. The new
1270    /// manager is already populated; this fn replaces the live Arc,
1271    /// purges side-state pointing at the previous contents, and
1272    /// rebuilds the paged B-tree from the supplied records.
1273    fn swap_collection_state(
1274        &self,
1275        name: &str,
1276        new_manager: Arc<SegmentManager>,
1277        prepared: &[UnifiedEntity],
1278        serialized: &[Vec<u8>],
1279        update_btrees: bool,
1280    ) {
1281        {
1282            let mut collections = self.collections.write();
1283            collections.insert(name.to_string(), new_manager);
1284        }
1285
1286        self.entity_cache
1287            .retain(|_, (collection, _)| collection != name);
1288        self.remove_from_graph_label_index_batch(
1289            name,
1290            &prepared.iter().map(|e| e.id).collect::<Vec<_>>(),
1291        );
1292
1293        if let Some(pager) = self.pager.as_ref().filter(|_| update_btrees) {
1294            let new_btree = Arc::new(BTree::new(Arc::clone(pager)));
1295            let mut sorted: Vec<(Vec<u8>, Vec<u8>)> = prepared
1296                .iter()
1297                .zip(serialized.iter())
1298                .map(|(e, r)| (e.id.raw().to_be_bytes().to_vec(), r.clone()))
1299                .collect();
1300            sorted.sort_by(|a, b| a.0.cmp(&b.0));
1301            if !sorted.is_empty() {
1302                let _ = new_btree.bulk_insert_sorted(&sorted);
1303            }
1304            self.btree_indices
1305                .write()
1306                .insert(name.to_string(), new_btree);
1307            self.mark_paged_registry_dirty();
1308        }
1309    }
1310
1311    fn apply_replayed_refresh_collection(
1312        &self,
1313        collection: &str,
1314        records: &[Vec<u8>],
1315        update_btrees: bool,
1316    ) -> Result<(), StoreError> {
1317        let new_manager = Arc::new(SegmentManager::with_config(
1318            collection,
1319            self.config.manager_config.clone(),
1320        ));
1321
1322        let mut prepared: Vec<UnifiedEntity> = Vec::with_capacity(records.len());
1323        for record in records {
1324            let (entity, _metadata) =
1325                Self::deserialize_entity_record(record, self.format_version())?;
1326            self.register_entity_id(entity.id);
1327            if let EntityKind::TableRow { row_id, .. } = &entity.kind {
1328                new_manager.register_row_id(*row_id);
1329            }
1330            prepared.push(entity);
1331        }
1332
1333        if !prepared.is_empty() {
1334            new_manager.bulk_insert(prepared.clone()).map_err(|e| {
1335                StoreError::Io(std::io::Error::other(format!(
1336                    "replay refresh_collection: bulk_insert failed: {e}"
1337                )))
1338            })?;
1339        }
1340
1341        self.swap_collection_state(collection, new_manager, &prepared, records, update_btrees);
1342        Ok(())
1343    }
1344
1345    /// Replica-side analogue of [`Self::refresh_collection`] — issue
1346    /// #596 slice 9d. Takes pre-serialized record bytes from the
1347    /// primary's CDC stream (the same bytes the primary wrote into the
1348    /// `RefreshCollection` WAL action), applies the atomic swap, and
1349    /// emits the same `RefreshCollection` WAL action against the
1350    /// replica's local store WAL so the post-swap state survives a
1351    /// replica restart through the normal recovery path.
1352    ///
1353    /// Idempotency: re-applying the same records bytes is a full
1354    /// rebuild from the same payload, so the resulting backing-
1355    /// collection contents are equal to the prior call's result.
1356    /// The primary-side `LogicalChangeApplier` short-circuits exact
1357    /// duplicate LSN+payload combinations before reaching here.
1358    pub fn refresh_collection_from_records(
1359        &self,
1360        name: &str,
1361        records: Vec<Vec<u8>>,
1362    ) -> Result<(), StoreError> {
1363        self.apply_replayed_refresh_collection(name, &records, true)?;
1364        self.finish_paged_write([StoreWalAction::RefreshCollection {
1365            collection: name.to_string(),
1366            records,
1367        }])?;
1368        Ok(())
1369    }
1370
1371    pub(crate) fn create_collection_in_memory(&self, name: &str) -> Result<(), StoreError> {
1372        let mut collections = self.collections.write();
1373        if collections.contains_key(name) {
1374            return Ok(());
1375        }
1376        let manager = SegmentManager::with_config(name, self.config.manager_config.clone());
1377        collections.insert(name.to_string(), Arc::new(manager));
1378        self.mark_paged_registry_dirty();
1379        Ok(())
1380    }
1381
1382    fn drop_collection_in_memory(&self, name: &str) -> Result<(), StoreError> {
1383        let manager = {
1384            let mut collections = self.collections.write();
1385            match collections.remove(name) {
1386                Some(manager) => manager,
1387                None => return Ok(()),
1388            }
1389        };
1390
1391        let entities = manager.query_all(|_| true);
1392        let entity_ids: Vec<EntityId> = entities.iter().map(|entity| entity.id).collect();
1393        for entity_id in &entity_ids {
1394            self.context_index.remove_entity(*entity_id);
1395            let _ = self.unindex_cross_refs(*entity_id);
1396        }
1397        if let Some(tree) = self.btree_indices.write().remove(name) {
1398            self.retire_btree(tree);
1399        }
1400        self.entity_cache.retain(|entity_id, (collection, _)| {
1401            collection != name && !entity_ids.iter().any(|id| id.raw() == entity_id)
1402        });
1403        self.remove_from_graph_label_index_batch(name, &entity_ids);
1404        self.mark_paged_registry_dirty();
1405        Ok(())
1406    }
1407
1408    fn apply_replayed_upsert(
1409        &self,
1410        collection: &str,
1411        record: &[u8],
1412        update_btrees: bool,
1413    ) -> Result<(), StoreError> {
1414        self.create_collection_in_memory(collection)?;
1415        let (entity, metadata) = Self::deserialize_entity_record(record, self.format_version())?;
1416        let manager = self
1417            .get_collection(collection)
1418            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1419
1420        self.register_entity_id(entity.id);
1421        if let EntityKind::TableRow { row_id, .. } = &entity.kind {
1422            manager.register_row_id(*row_id);
1423        }
1424
1425        self.context_index.remove_entity(entity.id);
1426        let _ = self.unindex_cross_refs(entity.id);
1427        self.remove_from_graph_label_index(collection, entity.id);
1428
1429        if manager.get(entity.id).is_some() {
1430            manager
1431                .update_with_metadata(entity.clone(), metadata.as_ref())
1432                .map_err(StoreError::from)?;
1433        } else {
1434            manager.restore_snapshot_entity(entity.clone())?;
1435            if let Some(metadata) = metadata.as_ref() {
1436                manager.set_metadata(entity.id, metadata.clone())?;
1437            }
1438        }
1439
1440        self.context_index.index_entity(collection, &entity);
1441        if let EntityKind::GraphNode(node) = &entity.kind {
1442            self.update_graph_label_index(collection, &node.label, entity.id);
1443        }
1444        self.index_cross_refs(&entity, collection)?;
1445
1446        if let Some(pager) = self.pager.as_ref().filter(|_| update_btrees) {
1447            let mut btree_indices = self.btree_indices.write();
1448            let btree = btree_indices
1449                .entry(collection.to_string())
1450                .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
1451            let root_before = btree.root_page_id();
1452            let key = entity.id.raw().to_be_bytes();
1453            match btree.insert(&key, record) {
1454                Ok(_) => {}
1455                Err(BTreeError::DuplicateKey) => {
1456                    let _ = btree.delete(&key);
1457                    let _ = btree.insert(&key, record);
1458                }
1459                Err(err) => {
1460                    return Err(StoreError::Io(io::Error::other(format!(
1461                        "replay upsert btree error: {err}"
1462                    ))));
1463                }
1464            }
1465            if root_before != btree.root_page_id() {
1466                self.mark_paged_registry_dirty();
1467            }
1468        }
1469
1470        Ok(())
1471    }
1472
1473    fn apply_replayed_delete(
1474        &self,
1475        collection: &str,
1476        id: EntityId,
1477        update_btrees: bool,
1478    ) -> Result<(), StoreError> {
1479        self.entity_cache.remove(id.raw());
1480        if let Some(manager) = self.get_collection(collection) {
1481            let deleted = manager.delete(id)?;
1482            if !deleted {
1483                return Ok(());
1484            }
1485        } else {
1486            return Ok(());
1487        }
1488
1489        if self.pager.is_some() && update_btrees {
1490            let btree_indices = self.btree_indices.read();
1491            if let Some(btree) = btree_indices.get(collection) {
1492                let root_before = btree.root_page_id();
1493                let key = id.raw().to_be_bytes();
1494                let _ = btree.delete(&key);
1495                if root_before != btree.root_page_id() {
1496                    self.mark_paged_registry_dirty();
1497                }
1498            }
1499        }
1500
1501        let _ = self.unindex_cross_refs(id);
1502        self.remove_from_graph_label_index(collection, id);
1503        self.context_index.remove_entity(id);
1504        Ok(())
1505    }
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510    use super::*;
1511    use crate::api::{DurabilityMode, GroupCommitOptions};
1512    use std::sync::{Barrier, Mutex as StdMutex, OnceLock};
1513    use std::time::SystemTime;
1514
1515    fn embedded_fixture(
1516        mode: DurabilityMode,
1517        background_bytes: usize,
1518    ) -> (tempfile::TempDir, PathBuf, UnifiedStore) {
1519        let directory = tempfile::tempdir().expect("directory");
1520        let path = directory.path().join("data.rdb");
1521        let mut store =
1522            UnifiedStore::with_config(UnifiedStoreConfig::default().with_durability_mode(mode));
1523        store.create_collection("keys").expect("collection");
1524        store.set_aux_metadata(vec![42; background_bytes]);
1525        crate::storage::EmbeddedRdbArtifact::create_with_snapshot(
1526            &path,
1527            &store.to_binary_dump_bytes(),
1528        )
1529        .expect("snapshot");
1530        store.config.embedded_wal_path = Some(path.clone());
1531        (directory, path, store)
1532    }
1533
1534    #[test]
1535    fn embedded_stale_full_result_does_not_checkpoint_reclaimed_space() {
1536        for mode in [DurabilityMode::Strict, DurabilityMode::WalDurableGrouped] {
1537            let (_directory, path, store) = embedded_fixture(mode, 0);
1538            store
1539                .append_embedded_store_wal_actions(&[StoreWalAction::CreateCollection {
1540                    name: "keys".into(),
1541                }])
1542                .expect("another writer appended after reclaiming space");
1543            let before = crate::storage::EmbeddedRdbArtifact::open(&path).expect("before");
1544            let payloads = vec![StoreWalAction::CreateCollection {
1545                name: "after".into(),
1546            }
1547            .encode()];
1548            let length = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
1549                .expect("encoded length");
1550            // Model a full result obtained before that other writer's checkpoint.
1551            store
1552                .recover_full_embedded_wal(&path, &payloads, length)
1553                .expect("revalidate after acquiring publication");
1554            let after = crate::storage::EmbeddedRdbArtifact::open(&path).expect("after");
1555            assert_eq!(
1556                after.selected_superblock.generation,
1557                before.selected_superblock.generation + 1,
1558                "only the retry is published, without an unnecessary checkpoint"
1559            );
1560            assert_eq!(
1561                crate::storage::EmbeddedRdbArtifact::read_wal_payloads(&after)
1562                    .expect("both appends retained")
1563                    .len(),
1564                2
1565            );
1566        }
1567    }
1568
1569    #[test]
1570    fn embedded_full_wal_reserves_bounded_headroom_for_populated_store() {
1571        for mode in [DurabilityMode::Strict, DurabilityMode::WalDurableGrouped] {
1572            let (_directory, path, store) = embedded_fixture(mode, 2 * 1024 * 1024);
1573            let initial = crate::storage::EmbeddedRdbArtifact::open(&path).expect("initial");
1574            let action = StoreWalAction::CreateCollection {
1575                name: "keys".into(),
1576            };
1577            let payloads = vec![action.encode()];
1578            let length = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
1579                .expect("encoded length");
1580            crate::storage::EmbeddedRdbArtifact::append_wal_payloads(
1581                &path,
1582                &vec![payloads[0].clone(); (initial.manifest.wal_region_bytes / length) as usize],
1583            )
1584            .expect("fill the initial region with valid records");
1585            store
1586                .append_embedded_store_wal_actions(&[action])
1587                .expect("overflow");
1588            let open = crate::storage::EmbeddedRdbArtifact::open(&path).expect("checkpoint");
1589            assert_eq!(open.manifest.wal_region_bytes, 1024 * 1024);
1590            let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
1591                .expect("snapshot")
1592                .expect("populated image");
1593            let recovered =
1594                UnifiedStore::load_from_bytes_with_config(&snapshot, UnifiedStoreConfig::default())
1595                    .expect("recover snapshot");
1596            for payload in
1597                crate::storage::EmbeddedRdbArtifact::read_wal_payloads(&open).expect("WAL")
1598            {
1599                recovered
1600                    .apply_encoded_store_wal_action(&payload)
1601                    .expect("replay");
1602            }
1603            assert_eq!(recovered.aux_metadata.read().len(), 2 * 1024 * 1024);
1604            assert!(recovered.get_collection("keys").is_some());
1605        }
1606    }
1607
1608    #[test]
1609    fn embedded_grouped_overwrites_recover_across_repeated_full_wal_regions() {
1610        fn row(writer: usize, round: usize) -> UnifiedEntity {
1611            let mut state = (writer as u64 + 1) * 31 + round as u64 * 13;
1612            let payload: String = (0..4096)
1613                .map(|_| {
1614                    state = state.wrapping_mul(1664525).wrapping_add(1013904223);
1615                    char::from(b'!' + ((state >> 24) % 90) as u8)
1616                })
1617                .collect();
1618            let mut entity = UnifiedEntity::table_row(EntityId::new(0), "keys", 0, vec![]);
1619            entity.data = EntityData::Row(RowData::with_names(
1620                vec![
1621                    Value::text(format!("k{writer}")),
1622                    Value::text(format!("{round}:{payload}")),
1623                ],
1624                vec!["key".into(), "value".into()],
1625            ));
1626            entity
1627        }
1628        let (_directory, path, store) =
1629            embedded_fixture(DurabilityMode::WalDurableGrouped, 2 * 1024 * 1024);
1630        assert!(
1631            StoreWalAction::upsert_entity("keys", &row(0, 0), None, store.format_version())
1632                .encode()
1633                .len()
1634                >= 2048,
1635            "fixture must exert physical WAL pressure after value compression"
1636        );
1637        let mut ids: Vec<_> = (0..8)
1638            .map(|writer| {
1639                store
1640                    .write_keyed_row("keys", row(writer, 0), None, None)
1641                    .expect("seed")
1642            })
1643            .collect();
1644        let initial = crate::storage::EmbeddedRdbArtifact::open(&path).expect("initial roots");
1645        let mut previous_snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&initial)
1646            .expect("initial snapshot")
1647            .expect("image");
1648        // Each wave writes over 2 MiB through the same 1 MiB reservation.
1649        // Checking image changes after each wave prevents a larger WAL from
1650        // merely postponing every checkpoint beyond the test's duration.
1651        for wave in 0..3 {
1652            let barrier = Barrier::new(ids.len());
1653            ids = std::thread::scope(|scope| {
1654                let workers: Vec<_> = ids
1655                    .iter()
1656                    .enumerate()
1657                    .map(|(writer, previous)| {
1658                        let store = &store;
1659                        let barrier = &barrier;
1660                        scope.spawn(move || {
1661                            barrier.wait();
1662                            let mut id = *previous;
1663                            for round in 0..64 {
1664                                id = store
1665                                    .write_keyed_row(
1666                                        "keys",
1667                                        row(writer, wave * 64 + round),
1668                                        None,
1669                                        Some(id),
1670                                    )
1671                                    .expect("durable overwrite");
1672                            }
1673                            id
1674                        })
1675                    })
1676                    .collect();
1677                workers
1678                    .into_iter()
1679                    .map(|worker| worker.join().expect("writer"))
1680                    .collect()
1681            });
1682            let open = crate::storage::EmbeddedRdbArtifact::open(&path).expect("wave roots");
1683            assert_eq!(open.manifest.wal_region_bytes, EMBEDDED_WAL_HEADROOM_LIMIT);
1684            let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
1685                .expect("wave snapshot")
1686                .expect("image");
1687            assert!(snapshot != previous_snapshot, "wave {wave} must checkpoint");
1688            previous_snapshot = snapshot;
1689        }
1690        let open = crate::storage::EmbeddedRdbArtifact::open(&path).expect("recover roots");
1691        let snapshot = crate::storage::EmbeddedRdbArtifact::read_snapshot(&open)
1692            .expect("snapshot")
1693            .expect("image");
1694        let recovered =
1695            UnifiedStore::load_from_bytes_with_config(&snapshot, UnifiedStoreConfig::default())
1696                .expect("snapshot replay");
1697        for payload in crate::storage::EmbeddedRdbArtifact::read_wal_payloads(&open).expect("WAL") {
1698            recovered
1699                .apply_encoded_store_wal_action(&payload)
1700                .expect("WAL replay");
1701        }
1702        assert_eq!(recovered.get_collection("keys").expect("keys").count(), 8);
1703        for (writer, id) in ids.iter().enumerate() {
1704            let entity = recovered
1705                .get("keys", *id)
1706                .expect("last acknowledged version");
1707            assert_eq!(
1708                entity.data.as_row().expect("row").get_field("value"),
1709                row(writer, 191)
1710                    .data
1711                    .as_row()
1712                    .expect("expected row")
1713                    .get_field("value")
1714            );
1715        }
1716    }
1717
1718    /// Serialise tests that mutate `REDDB_GROUP_COMMIT_WINDOW_US`.
1719    /// The env table is process-global, so two parallel test threads
1720    /// flipping it would race the assertions in the test that
1721    /// happens to read it last.
1722    fn env_lock() -> &'static StdMutex<()> {
1723        static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
1724        LOCK.get_or_init(|| StdMutex::new(()))
1725    }
1726
1727    fn temp_wal(name: &str) -> PathBuf {
1728        let nanos = SystemTime::now()
1729            .duration_since(std::time::UNIX_EPOCH)
1730            .unwrap()
1731            .as_nanos();
1732        let path = reddb_file::layout::store_commit_coord_temp_wal_path(
1733            &std::env::temp_dir(),
1734            name,
1735            std::process::id(),
1736            nanos,
1737        );
1738        let _ = std::fs::remove_file(&path);
1739        path
1740    }
1741
1742    fn replay_crash_payload(id: u64, round: u64) -> String {
1743        let mut state = id * 31 + round * 13 + 1;
1744        (0..600)
1745            .map(|_| {
1746                state = state.wrapping_mul(1664525).wrapping_add(1013904223);
1747                char::from(b'!' + ((state >> 24) % 90) as u8)
1748            })
1749            .collect()
1750    }
1751
1752    #[test]
1753    fn paged_wal_replay_survives_immediate_process_exit() {
1754        const CHILD_PATH: &str = "REDDB_TEST_REPLAY_CRASH_PATH";
1755        let config = || UnifiedStoreConfig::default().with_page_cache_slots(4);
1756        if let Some(path) = std::env::var_os(CHILD_PATH) {
1757            let store = UnifiedStore::open_with_config(path, config()).expect("replay child");
1758            assert_eq!(store.get_collection("rows").unwrap().count(), 400);
1759            // No Rust destructors or graceful checkpoint may repair the image.
1760            std::process::exit(0);
1761        }
1762        let directory = tempfile::tempdir().unwrap();
1763        let path = directory.path().join("data.rdb");
1764        {
1765            let store = UnifiedStore::open_with_config(&path, config()).unwrap();
1766            store.create_collection("rows").unwrap();
1767            for id in 1..=400 {
1768                store
1769                    .insert(
1770                        "rows",
1771                        UnifiedEntity::table_row(
1772                            EntityId::new(id),
1773                            "rows",
1774                            id,
1775                            vec![Value::text(format!("initial-{id}"))],
1776                        ),
1777                    )
1778                    .unwrap();
1779            }
1780            store.persist().unwrap();
1781        }
1782        {
1783            let coordinator = StoreCommitCoordinator::open(
1784                reddb_file::layout::unified_wal_path(&path),
1785                DurabilityMode::Strict,
1786                GroupCommitOptions::default(),
1787            )
1788            .unwrap();
1789            for round in 0..3 {
1790                let actions = (1..=400)
1791                    .map(|id| {
1792                        let payload = replay_crash_payload(id, round);
1793                        let entity = UnifiedEntity::table_row(
1794                            EntityId::new(id),
1795                            "rows",
1796                            id,
1797                            vec![Value::text(payload)],
1798                        );
1799                        StoreWalAction::upsert_entity("rows", &entity, None, STORE_VERSION_V11)
1800                    })
1801                    .collect::<Vec<_>>();
1802                coordinator.append_actions(&actions).unwrap();
1803            }
1804        }
1805        let status = std::process::Command::new(std::env::current_exe().unwrap())
1806            .args(["--exact", "storage::unified::store::commit::tests::paged_wal_replay_survives_immediate_process_exit", "--nocapture"])
1807            .env(CHILD_PATH, &path).status().unwrap();
1808        assert!(status.success(), "replay process failed");
1809        let reopened = UnifiedStore::open_with_config(&path, config())
1810            .expect("cold reopen after replay crash");
1811        assert_eq!(reopened.get_collection("rows").unwrap().count(), 400);
1812        for id in 1..=400 {
1813            let entity = reopened
1814                .get("rows", EntityId::new(id))
1815                .expect("retained entity");
1816            let EntityData::Row(row) = entity.data else {
1817                panic!("expected row")
1818            };
1819            assert_eq!(row.columns, vec![Value::text(replay_crash_payload(id, 2))]);
1820        }
1821        drop(reopened);
1822        let stable_bytes = std::fs::metadata(&path).unwrap().len();
1823        let repeated = UnifiedStore::open_with_config(&path, config()).unwrap();
1824        assert_eq!(repeated.get_collection("rows").unwrap().count(), 400);
1825        assert_eq!(
1826            std::fs::metadata(&path).unwrap().len(),
1827            stable_bytes,
1828            "idempotent replay must not allocate another tree generation"
1829        );
1830    }
1831
1832    #[test]
1833    fn checkpoint_reset_waits_for_an_enqueued_commit_acknowledgement() {
1834        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
1835        let path = temp_wal("checkpoint-ack");
1836        let coordinator = Arc::new(
1837            StoreCommitCoordinator::open(
1838                path.clone(),
1839                DurabilityMode::WalDurableGrouped,
1840                GroupCommitOptions::default(),
1841            )
1842            .unwrap(),
1843        );
1844        // Pause the writer after enqueue, before it can register/wait for its
1845        // acknowledgement. The flusher also needs this state lock to drain.
1846        let state = coordinator.state.0.lock();
1847        let (written_tx, written_rx) = std::sync::mpsc::channel();
1848        let writer_coordinator = Arc::clone(&coordinator);
1849        let writer = std::thread::spawn(move || {
1850            let result = writer_coordinator.append_actions(&[StoreWalAction::CreateCollection {
1851                name: "acknowledged".into(),
1852            }]);
1853            written_tx.send(result).unwrap();
1854        });
1855        let deadline = Instant::now() + Duration::from_secs(2);
1856        while !coordinator.queue.has_pending() {
1857            assert!(Instant::now() < deadline, "writer never enqueued");
1858            std::thread::yield_now();
1859        }
1860        let (started_tx, started_rx) = std::sync::mpsc::channel();
1861        let (reset_tx, reset_rx) = std::sync::mpsc::channel();
1862        let reset_coordinator = Arc::clone(&coordinator);
1863        let reset = std::thread::spawn(move || {
1864            started_tx.send(()).unwrap();
1865            reset_tx.send(reset_coordinator.truncate()).unwrap();
1866        });
1867        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
1868        let deadline = Instant::now() + Duration::from_millis(100);
1869        while coordinator.queue.has_pending() && Instant::now() < deadline {
1870            std::thread::sleep(Duration::from_millis(1));
1871        }
1872        let discarded_before_ack = !coordinator.queue.has_pending();
1873        drop(state);
1874        let acknowledged = written_rx.recv_timeout(Duration::from_secs(2));
1875        if acknowledged.is_err() {
1876            // Release an old implementation's stranded waiter before failing
1877            // the assertion, so the regression itself cannot leak a worker.
1878            let mut state = coordinator.state.0.lock();
1879            state.shutdown = true;
1880            state.last_error = Some("checkpoint acknowledgement regression cleanup".into());
1881            coordinator.state.1.notify_all();
1882        }
1883        writer.join().unwrap();
1884        reset_rx
1885            .recv_timeout(Duration::from_secs(2))
1886            .unwrap()
1887            .unwrap();
1888        reset.join().unwrap();
1889        assert!(
1890            !discarded_before_ack,
1891            "checkpoint discarded an unacknowledged WAL record"
1892        );
1893        assert!(
1894            acknowledged.unwrap().is_ok(),
1895            "durable writer did not finish"
1896        );
1897        drop(coordinator);
1898        let _ = std::fs::remove_file(path);
1899    }
1900
1901    /// Concurrent autocommits MUST coalesce into far fewer fsyncs
1902    /// than the number of callers when the adaptive group-commit
1903    /// window is active. Without the 200µs floor, every caller
1904    /// would race the drain loop and pay an independent fsync.
1905    ///
1906    /// The test fires 32 concurrent `append_actions` calls and asserts
1907    /// the coordinator issued strictly fewer fsyncs than callers.
1908    /// (We don't pin to "one fsync" because timing on loaded CI hosts
1909    /// can split the burst across a couple of drain cycles — the win
1910    /// is the ratio, not the absolute count.)
1911    #[test]
1912    fn group_commit_coalesces_concurrent_autocommits() {
1913        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
1914        // Make sure no stale env var skews this run — the test
1915        // exercises the default 200µs floor.
1916        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
1917
1918        let path = temp_wal("coalesce");
1919        let coord = Arc::new(
1920            StoreCommitCoordinator::open(
1921                path.clone(),
1922                DurabilityMode::WalDurableGrouped,
1923                GroupCommitOptions::default(),
1924            )
1925            .expect("open commit coordinator"),
1926        );
1927
1928        const WRITERS: usize = 32;
1929        let barrier = Arc::new(Barrier::new(WRITERS));
1930        let mut handles = Vec::with_capacity(WRITERS);
1931        for tx in 0..WRITERS {
1932            let coord_c = Arc::clone(&coord);
1933            let barrier_c = Arc::clone(&barrier);
1934            handles.push(std::thread::spawn(move || {
1935                // Synchronise the start so every writer races the
1936                // drain loop together — this is the workload shape
1937                // the adaptive window is supposed to coalesce.
1938                barrier_c.wait();
1939                let action = StoreWalAction::CreateCollection {
1940                    name: format!("c{tx}"),
1941                };
1942                coord_c
1943                    .append_actions(std::slice::from_ref(&action))
1944                    .expect("append_actions");
1945            }));
1946        }
1947        for h in handles {
1948            h.join().expect("writer thread");
1949        }
1950
1951        let fsyncs = coord.fsync_count();
1952        assert!(fsyncs > 0, "expected at least one fsync, got {fsyncs}");
1953        assert!(
1954            fsyncs < WRITERS as u64,
1955            "expected fsyncs ({fsyncs}) to be strictly less than \
1956             concurrent writers ({WRITERS}); coalescing failed"
1957        );
1958
1959        drop(coord);
1960        let _ = std::fs::remove_file(&path);
1961    }
1962
1963    /// Sanity check: with the env override forcing a zero window,
1964    /// fsync coalescing degrades — callers race and we approach
1965    /// one fsync per caller. This proves the window is the actual
1966    /// knob doing the work above (i.e. the test isn't passing for
1967    /// some unrelated reason like buffered-IO coalescing).
1968    #[test]
1969    fn zero_window_disables_coalescing_floor() {
1970        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
1971        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "0");
1972
1973        let path = temp_wal("zero_window");
1974        let coord = Arc::new(
1975            StoreCommitCoordinator::open(
1976                path.clone(),
1977                DurabilityMode::WalDurableGrouped,
1978                GroupCommitOptions::default(),
1979            )
1980            .expect("open commit coordinator"),
1981        );
1982
1983        const WRITERS: usize = 8;
1984        let barrier = Arc::new(Barrier::new(WRITERS));
1985        let mut handles = Vec::with_capacity(WRITERS);
1986        for tx in 0..WRITERS {
1987            let coord_c = Arc::clone(&coord);
1988            let barrier_c = Arc::clone(&barrier);
1989            handles.push(std::thread::spawn(move || {
1990                barrier_c.wait();
1991                let action = StoreWalAction::CreateCollection {
1992                    name: format!("z{tx}"),
1993                };
1994                coord_c
1995                    .append_actions(std::slice::from_ref(&action))
1996                    .expect("append_actions");
1997            }));
1998        }
1999        for h in handles {
2000            h.join().expect("writer thread");
2001        }
2002
2003        // With zero window, fsync count is bounded above by WRITERS
2004        // (every caller might trigger its own drain) and below by 1
2005        // (the queue may still naturally batch under contention).
2006        // The point of the assertion is to confirm the env override
2007        // is wired through — the open() above used the env knob.
2008        let fsyncs = coord.fsync_count();
2009        assert!(fsyncs >= 1, "expected at least one fsync, got {fsyncs}");
2010
2011        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
2012        drop(coord);
2013        let _ = std::fs::remove_file(&path);
2014    }
2015
2016    /// `resolve_window` precedence: env > config.window_ms > default.
2017    #[test]
2018    fn resolve_window_precedence() {
2019        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
2020        // Default: window_ms=0 → adaptive 200µs floor.
2021        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
2022        let cfg = GroupCommitOptions::default();
2023        assert_eq!(
2024            StoreCommitCoordinator::resolve_window(&cfg),
2025            Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
2026        );
2027
2028        // Explicit ms config wins over the default floor.
2029        let cfg_ms = GroupCommitOptions {
2030            window_ms: 5,
2031            ..GroupCommitOptions::default()
2032        };
2033        assert_eq!(
2034            StoreCommitCoordinator::resolve_window(&cfg_ms),
2035            Duration::from_millis(5)
2036        );
2037
2038        // Env override wins over both.
2039        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "750");
2040        assert_eq!(
2041            StoreCommitCoordinator::resolve_window(&cfg),
2042            Duration::from_micros(750)
2043        );
2044        assert_eq!(
2045            StoreCommitCoordinator::resolve_window(&cfg_ms),
2046            Duration::from_micros(750)
2047        );
2048
2049        // Env=0 explicitly disables the floor.
2050        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "0");
2051        assert_eq!(
2052            StoreCommitCoordinator::resolve_window(&cfg),
2053            Duration::from_micros(0)
2054        );
2055
2056        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
2057    }
2058}