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/// Shorthand — `Arc<parking_lot::Mutex<WalWriter>>` avoids poisoning
29/// (one writer panicking mid-append used to taint every subsequent
30/// lock acquisition) and shaves a few syscalls off the fast path.
31/// The group-commit coordinator + writer threads all acquire this
32/// mutex in the hot insert path, so the unpoison/fast-park win
33/// compounds under 16-way concurrency.
34type WalMutex = parking_lot::Mutex<WalWriter>;
35
36/// Shorthand for the group-commit coordinator's state pair. Same
37/// non-poisoning + lighter-park motivation as `WalMutex`; writer
38/// threads `wait` on this condvar until the coordinator publishes a
39/// new `durable_lsn`, so the park cost shows up on every
40/// WalDurableGrouped transaction.
41type CommitStateMutex = parking_lot::Mutex<CommitState>;
42type CommitStateCondvar = parking_lot::Condvar;
43use std::time::{Duration, Instant};
44
45static NEXT_STORE_TX_ID: AtomicU64 = AtomicU64::new(1);
46
47#[derive(Debug, Clone)]
48pub(crate) enum StoreWalAction {
49    CreateCollection {
50        name: String,
51    },
52    DropCollection {
53        name: String,
54    },
55    UpsertEntityRecord {
56        collection: String,
57        record: Vec<u8>,
58    },
59    DeleteEntityRecord {
60        collection: String,
61        entity_id: u64,
62    },
63    /// Batched upsert — one WAL action carrying N serialized entity
64    /// records for the same collection. Saves the per-row Begin/
65    /// PageWrite/Commit framing overhead on the bulk insert hot path.
66    /// Replay applies every contained record in order.
67    BulkUpsertEntityRecords {
68        collection: String,
69        records: Vec<Vec<u8>>,
70    },
71    /// Atomic full-collection replace — issue #595 slice 9c.
72    /// Replay drops the in-memory collection state and rebuilds it
73    /// from the contained records. Used by REFRESH MATERIALIZED VIEW
74    /// so a concurrent reader sees either the prior contents or the
75    /// new contents, never a partial state, and a crash mid-refresh
76    /// leaves the prior contents intact on recovery (the action is
77    /// only durable once the WAL commit lands).
78    RefreshCollection {
79        collection: String,
80        records: Vec<Vec<u8>>,
81    },
82}
83
84#[derive(Debug, Default)]
85pub(crate) struct DeferredStoreWalActions {
86    actions: Vec<StoreWalAction>,
87}
88
89impl DeferredStoreWalActions {
90    pub(crate) fn is_empty(&self) -> bool {
91        self.actions.is_empty()
92    }
93
94    pub(crate) fn extend(&mut self, other: Self) {
95        self.actions.extend(other.actions);
96    }
97}
98
99thread_local! {
100    static DEFERRED_STORE_WAL_ACTIONS: RefCell<Option<Vec<StoreWalAction>>> =
101        const { RefCell::new(None) };
102}
103
104fn begin_deferred_store_wal_capture() {
105    DEFERRED_STORE_WAL_ACTIONS.with(|cell| {
106        let mut guard = cell.borrow_mut();
107        debug_assert!(guard.is_none());
108        *guard = Some(Vec::new());
109    });
110}
111
112fn capture_deferred_store_wal_actions(actions: Vec<StoreWalAction>) -> bool {
113    DEFERRED_STORE_WAL_ACTIONS.with(|cell| {
114        let mut guard = cell.borrow_mut();
115        if let Some(pending) = guard.as_mut() {
116            pending.extend(actions);
117            true
118        } else {
119            false
120        }
121    })
122}
123
124fn deferred_store_wal_capture_active() -> bool {
125    DEFERRED_STORE_WAL_ACTIONS.with(|cell| cell.borrow().is_some())
126}
127
128fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
129    DEFERRED_STORE_WAL_ACTIONS.with(|cell| DeferredStoreWalActions {
130        actions: cell.borrow_mut().take().unwrap_or_default(),
131    })
132}
133
134impl StoreWalAction {
135    pub(crate) fn upsert_entity(
136        collection: &str,
137        entity: &UnifiedEntity,
138        metadata: Option<&Metadata>,
139        format_version: u32,
140    ) -> Self {
141        Self::UpsertEntityRecord {
142            collection: collection.to_string(),
143            record: UnifiedStore::serialize_entity_record(entity, metadata, format_version),
144        }
145    }
146
147    fn encode(&self) -> Vec<u8> {
148        reddb_file::encode_store_wal_action_frame(&self.to_frame())
149            .expect("encode store wal action frame")
150    }
151
152    fn to_frame(&self) -> reddb_file::StoreWalActionFrame {
153        match self {
154            Self::CreateCollection { name } => {
155                reddb_file::StoreWalActionFrame::CreateCollection { name: name.clone() }
156            }
157            Self::DropCollection { name } => {
158                reddb_file::StoreWalActionFrame::DropCollection { name: name.clone() }
159            }
160            Self::UpsertEntityRecord { collection, record } => {
161                reddb_file::StoreWalActionFrame::UpsertEntityRecord {
162                    collection: collection.clone(),
163                    record: record.clone(),
164                }
165            }
166            Self::DeleteEntityRecord {
167                collection,
168                entity_id,
169            } => reddb_file::StoreWalActionFrame::DeleteEntityRecord {
170                collection: collection.clone(),
171                entity_id: *entity_id,
172            },
173            Self::BulkUpsertEntityRecords {
174                collection,
175                records,
176            } => reddb_file::StoreWalActionFrame::BulkUpsertEntityRecords {
177                collection: collection.clone(),
178                records: records.clone(),
179            },
180            Self::RefreshCollection {
181                collection,
182                records,
183            } => reddb_file::StoreWalActionFrame::RefreshCollection {
184                collection: collection.clone(),
185                records: records.clone(),
186            },
187        }
188    }
189
190    fn decode(bytes: &[u8]) -> io::Result<Self> {
191        match reddb_file::decode_store_wal_action_frame(bytes)? {
192            reddb_file::StoreWalActionFrame::CreateCollection { name } => {
193                Ok(Self::CreateCollection { name })
194            }
195            reddb_file::StoreWalActionFrame::DropCollection { name } => {
196                Ok(Self::DropCollection { name })
197            }
198            reddb_file::StoreWalActionFrame::UpsertEntityRecord { collection, record } => {
199                Ok(Self::UpsertEntityRecord { collection, record })
200            }
201            reddb_file::StoreWalActionFrame::DeleteEntityRecord {
202                collection,
203                entity_id,
204            } => Ok(Self::DeleteEntityRecord {
205                collection,
206                entity_id,
207            }),
208            reddb_file::StoreWalActionFrame::BulkUpsertEntityRecords {
209                collection,
210                records,
211            } => Ok(Self::BulkUpsertEntityRecords {
212                collection,
213                records,
214            }),
215            reddb_file::StoreWalActionFrame::RefreshCollection {
216                collection,
217                records,
218            } => Ok(Self::RefreshCollection {
219                collection,
220                records,
221            }),
222        }
223    }
224}
225
226#[derive(Debug)]
227struct CommitState {
228    durable_lsn: u64,
229    pending_target_lsn: u64,
230    pending_statements: usize,
231    pending_wal_bytes: u64,
232    first_pending_at: Option<Instant>,
233    shutdown: bool,
234    last_error: Option<String>,
235}
236
237impl CommitState {
238    fn new(initial_durable_lsn: u64) -> Self {
239        Self {
240            durable_lsn: initial_durable_lsn,
241            pending_target_lsn: initial_durable_lsn,
242            pending_statements: 0,
243            pending_wal_bytes: 0,
244            first_pending_at: None,
245            shutdown: false,
246            last_error: None,
247        }
248    }
249}
250
251/// Lock-free append queue sitting in front of `WalWriter`.
252///
253/// Writers atomically reserve a byte range via `next_lsn.fetch_add`
254/// and push their encoded bytes into a parking_lot-guarded vector.
255/// The group-commit coordinator is the sole drainer: it sorts the
256/// pending entries by LSN (so the file bytes land at the offsets
257/// each writer reserved) and hands them to `WalWriter::append_bytes`.
258///
259/// This replaces the old `wal.lock() ... append ... append ... drop`
260/// hot path where 16 concurrent writers serialised on the WAL
261/// mutex for ~13µs each. Hold time on the queue's parking_lot
262/// mutex is ~200ns (just a Vec::push) — 65× shorter, so the mutex
263/// convoy on concurrent inserts disappears.
264pub(crate) struct WalAppendQueue {
265    /// Tuple of (monotonically-increasing LSN, pending-bytes vec)
266    /// protected by one mutex. Keeping the LSN reservation AND the
267    /// push under the same lock guarantees that every queue entry
268    /// is visible the moment its LSN is assigned — no gap between
269    /// `fetch_add` and `push` for the leader to spin on.
270    ///
271    /// Earlier versions reserved LSN with an `AtomicU64::fetch_add`
272    /// outside the lock; the leader drain observed reordered
273    /// `(lsn, bytes)` tuples whose pushes happened in a different
274    /// order than their fetch_add, creating "holes" in the LSN
275    /// sequence that the drain loop interpreted as "wait for the
276    /// missing enqueuer" — under tokio scheduling pressure the
277    /// missing enqueuer was preempted indefinitely and the
278    /// drain loop busy-waited forever (WAL stayed at 8 bytes).
279    pending: parking_lot::Mutex<WalQueueState>,
280    /// Bytes of encoded records sitting in `pending.entries` (ADR 0073 §2,
281    /// the `wal_buffers` pool). A relaxed atomic rather than a field inside
282    /// `WalQueueState` so a reader sampling the accounting never contends
283    /// with an enqueuer for the queue mutex.
284    queued_bytes: AtomicU64,
285}
286
287struct WalQueueState {
288    next_lsn: u64,
289    entries: Vec<(u64, Vec<u8>)>,
290}
291
292impl WalAppendQueue {
293    fn new(initial_lsn: u64) -> Self {
294        Self {
295            pending: parking_lot::Mutex::new(WalQueueState {
296                next_lsn: initial_lsn,
297                entries: Vec::with_capacity(64),
298            }),
299            queued_bytes: AtomicU64::new(0),
300        }
301    }
302
303    /// Reserve an LSN range of `bytes.len()` bytes and push onto the
304    /// queue. Returns the commit LSN (end of reserved range), which
305    /// the caller passes to `wait_until_durable`. LSN assignment and
306    /// push happen under the same mutex — no gap for the drain loop
307    /// to busy-spin on.
308    fn enqueue(&self, bytes: Vec<u8>) -> u64 {
309        let len = bytes.len() as u64;
310        let mut state = self.pending.lock();
311        let start_lsn = state.next_lsn;
312        state.next_lsn = start_lsn + len;
313        state.entries.push((start_lsn, bytes));
314        self.queued_bytes.fetch_add(len, Ordering::Relaxed);
315        start_lsn + len
316    }
317
318    /// Drain all queued entries in LSN order. Caller holds the WAL
319    /// file mutex while writing the drained bytes so the on-disk
320    /// layout matches the reserved LSN offsets.
321    fn drain_sorted(&self) -> Vec<(u64, Vec<u8>)> {
322        let mut state = self.pending.lock();
323        let mut v = std::mem::take(&mut state.entries);
324        let drained: u64 = v.iter().map(|(_, bytes)| bytes.len() as u64).sum();
325        drop(state);
326        // Saturating: the drain is the only consumer, so `queued_bytes` can
327        // never sit below what this call took, but an accounting counter that
328        // wraps would poison `red.stats` far past the bug that caused it.
329        let _ = self
330            .queued_bytes
331            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |queued| {
332                Some(queued.saturating_sub(drained))
333            });
334        v.sort_by_key(|(lsn, _)| *lsn);
335        v
336    }
337
338    /// Whether any entry is queued. Leader uses this to decide
339    /// whether to spin once more or go back to the condvar.
340    fn has_pending(&self) -> bool {
341        !self.pending.lock().entries.is_empty()
342    }
343
344    /// Encoded record bytes currently buffered in memory.
345    fn queued_bytes(&self) -> u64 {
346        self.queued_bytes.load(Ordering::Relaxed)
347    }
348
349    /// Reset the LSN cursor and discard any queued entries. Used
350    /// after `wal.truncate()` — the wal-side byte counter goes back
351    /// to the header size, so the queue (which tracks LSNs in the
352    /// same byte space) must follow or every subsequent enqueue
353    /// returns a target the drain loop can never reach.
354    fn reset(&self, next_lsn: u64) {
355        let mut state = self.pending.lock();
356        state.next_lsn = next_lsn;
357        state.entries.clear();
358        drop(state);
359        self.queued_bytes.store(0, Ordering::Relaxed);
360    }
361}
362
363pub(crate) struct StoreCommitCoordinator {
364    mode: DurabilityMode,
365    config: crate::api::GroupCommitOptions,
366    wal_path: PathBuf,
367    wal: Arc<WalMutex>,
368    /// Lock-free front door for writers. Populated alongside
369    /// `WalDurableGrouped` / `Async` modes so concurrent inserts
370    /// never contend on `wal` for the append step. Strict mode
371    /// bypasses the queue and calls `WalWriter::append` directly
372    /// to preserve the one-fsync-per-commit semantic.
373    queue: Arc<WalAppendQueue>,
374    state: Arc<(CommitStateMutex, CommitStateCondvar)>,
375    /// Number of `wal.sync()` calls issued by the group-commit
376    /// drain loop. Used by tests to observe coalescing — a burst
377    /// of N concurrent commits should bump this by far less than N
378    /// when the adaptive window is doing its job. Strict-mode
379    /// commits go through `force_sync` which also bumps this.
380    fsync_count: Arc<AtomicU64>,
381}
382
383impl StoreCommitCoordinator {
384    pub(crate) fn open(
385        wal_path: impl Into<PathBuf>,
386        mode: DurabilityMode,
387        config: crate::api::GroupCommitOptions,
388    ) -> io::Result<Self> {
389        let wal_path = wal_path.into();
390        let wal = WalWriter::open(&wal_path)?;
391        let initial_durable_lsn = wal.durable_lsn();
392        let initial_current_lsn = wal.current_lsn();
393        let wal = Arc::new(WalMutex::new(wal));
394        let queue = Arc::new(WalAppendQueue::new(initial_current_lsn));
395        let state = Arc::new((
396            CommitStateMutex::new(CommitState::new(initial_durable_lsn)),
397            CommitStateCondvar::new(),
398        ));
399        let fsync_count = Arc::new(AtomicU64::new(0));
400
401        if matches!(
402            mode,
403            DurabilityMode::WalDurableGrouped | DurabilityMode::Async
404        ) {
405            let wal_bg = Arc::clone(&wal);
406            let queue_bg = Arc::clone(&queue);
407            let state_bg = Arc::clone(&state);
408            let fsync_bg = Arc::clone(&fsync_count);
409            // P1: adaptive group-commit window. Historical default is
410            // `window_ms = 0` ("no wait"), which under single-writer
411            // OLTP means one fsync per autocommit row — the throughput
412            // floor. When window_ms is 0 we fall back to a small
413            // microsecond floor (`DEFAULT_ADAPTIVE_WINDOW_US`, override
414            // via `REDDB_GROUP_COMMIT_WINDOW_US`) so a pipelined writer
415            // can drop a second statement into the same drain cycle.
416            // Explicit non-zero `window_ms` config takes precedence.
417            //
418            // The loop already short-circuits on
419            // `pending_statements >= max_statements` /
420            // `pending_wal_bytes >= max_wal_bytes`, so the window only
421            // delays the leader when the queue is otherwise empty —
422            // exactly the case we want to coalesce.
423            let window = Self::resolve_window(&config);
424            let max_statements = config.max_statements.max(1);
425            let max_wal_bytes = config.max_wal_bytes.max(1);
426            std::thread::spawn(move || {
427                Self::run_group_commit_loop(
428                    wal_bg,
429                    queue_bg,
430                    state_bg,
431                    fsync_bg,
432                    window,
433                    max_statements,
434                    max_wal_bytes,
435                );
436            });
437        }
438
439        Ok(Self {
440            mode,
441            config,
442            wal_path,
443            wal,
444            queue,
445            state,
446            fsync_count,
447        })
448    }
449
450    /// Resolve the effective group-commit window from the configured
451    /// options + the `REDDB_GROUP_COMMIT_WINDOW_US` env override.
452    ///
453    /// Precedence (highest first):
454    ///   1. `REDDB_GROUP_COMMIT_WINDOW_US=N` — N µs (0 disables).
455    ///   2. `config.window_ms != 0` — explicit ms config wins.
456    ///   3. `DEFAULT_ADAPTIVE_WINDOW_US` — adaptive floor for the
457    ///      historical zero-default. Set the env var to 0 to opt out.
458    fn resolve_window(config: &crate::api::GroupCommitOptions) -> Duration {
459        if let Ok(raw) = std::env::var("REDDB_GROUP_COMMIT_WINDOW_US") {
460            if let Ok(parsed) = raw.parse::<u64>() {
461                return Duration::from_micros(parsed);
462            }
463        }
464        if config.window_ms != 0 {
465            return Duration::from_millis(config.window_ms);
466        }
467        Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
468    }
469
470    /// Total `wal.sync()` calls issued since this coordinator opened.
471    /// Public for tests that want to observe fsync coalescing under
472    /// concurrent autocommits.
473    #[cfg(test)]
474    pub(crate) fn fsync_count(&self) -> u64 {
475        self.fsync_count.load(Ordering::Relaxed)
476    }
477
478    /// WAL buffer memory held right now: encoded records waiting in the
479    /// group-commit queue plus the writer's fixed append buffer, which exists
480    /// for the coordinator's whole life (ADR 0073 §2, the `wal_buffers` pool).
481    pub(crate) fn buffered_bytes(&self) -> u64 {
482        self.queue.queued_bytes() + crate::storage::wal::WAL_BUFFER_BYTES as u64
483    }
484
485    pub(crate) fn append_actions(&self, actions: &[StoreWalAction]) -> io::Result<()> {
486        if actions.is_empty() {
487            return Ok(());
488        }
489
490        let tx_id = NEXT_STORE_TX_ID.fetch_add(1, Ordering::SeqCst);
491
492        // Strict mode: bypass the queue, write + fsync inline. Strict
493        // commits are exactly one-fsync-per-call by contract, so the
494        // coalescing win of the queue doesn't apply and we'd pay an
495        // extra hop through the drain loop.
496        if matches!(self.mode, DurabilityMode::Strict) {
497            let commit_lsn = {
498                let mut wal = self.wal.lock();
499                wal.append(&WalRecord::TxCommitBatch {
500                    tx_id,
501                    actions: actions.iter().map(StoreWalAction::encode).collect(),
502                })?;
503                wal.current_lsn()
504            };
505            self.force_sync()?;
506            let _ = commit_lsn;
507            return Ok(());
508        }
509
510        // Grouped / Async path — lock-free enqueue. Encode every
511        // WalRecord into one contiguous byte blob OUTSIDE any lock,
512        // then hand it to the queue with a single fetch_add+push.
513        let encoded_actions: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
514        let wal_bytes = encoded_actions.iter().fold(0u64, |total, payload| {
515            total.saturating_add(payload.len() as u64)
516        });
517        let blob = WalRecord::TxCommitBatch {
518            tx_id,
519            actions: encoded_actions,
520        }
521        .encode();
522
523        let commit_lsn = self.queue.enqueue(blob);
524        self.wait_until_durable(commit_lsn, wal_bytes)?;
525        Ok(())
526    }
527
528    /// Encode + enqueue a single, non-batched [`WalRecord`] (issue
529    /// #693). Honours the same Strict / Grouped / Async branching as
530    /// [`Self::append_actions`] so durability semantics are uniform
531    /// across record kinds.
532    pub(crate) fn append_single_record(&self, record: WalRecord) -> io::Result<()> {
533        let blob = record.encode();
534        let wal_bytes = blob.len() as u64;
535        if matches!(self.mode, DurabilityMode::Strict) {
536            {
537                let mut wal = self.wal.lock();
538                wal.append(&record)?;
539            }
540            self.force_sync()?;
541            return Ok(());
542        }
543        let commit_lsn = self.queue.enqueue(blob);
544        self.wait_until_durable(commit_lsn, wal_bytes)?;
545        Ok(())
546    }
547
548    pub(crate) fn force_sync(&self) -> io::Result<()> {
549        {
550            let mut wal = self.wal.lock();
551            wal.sync()?;
552            self.fsync_count.fetch_add(1, Ordering::Relaxed);
553            let durable = wal.durable_lsn();
554            drop(wal);
555            let (state_lock, cond) = &*self.state;
556            let mut state = state_lock.lock();
557            state.durable_lsn = durable;
558            state.pending_target_lsn = durable.max(state.pending_target_lsn);
559            state.pending_statements = 0;
560            state.pending_wal_bytes = 0;
561            state.first_pending_at = None;
562            state.last_error = None;
563            cond.notify_all();
564        }
565        Ok(())
566    }
567
568    pub(crate) fn truncate(&self) -> io::Result<()> {
569        let mut wal = self.wal.lock();
570        wal.truncate()?;
571        let durable = wal.durable_lsn();
572        let current = wal.current_lsn();
573        drop(wal);
574
575        // Queue's next_lsn tracks byte offsets in the same space as
576        // wal.current_lsn. After truncate both must be reset together
577        // — otherwise enqueue returns a target_lsn in the old range
578        // that drain can never reach, and wait_until_durable hangs.
579        self.queue.reset(current);
580
581        let (state_lock, cond) = &*self.state;
582        let mut state = state_lock.lock();
583        state.durable_lsn = durable;
584        state.pending_target_lsn = durable;
585        state.pending_statements = 0;
586        state.pending_wal_bytes = 0;
587        state.first_pending_at = None;
588        state.last_error = None;
589        cond.notify_all();
590        Ok(())
591    }
592
593    pub(crate) fn replay_into(&self, store: &UnifiedStore) -> io::Result<()> {
594        if !self.wal_path.exists() {
595            return Ok(());
596        }
597
598        let reader = match WalReader::open(&self.wal_path) {
599            Ok(reader) => reader,
600            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
601            Err(err) => return Err(err),
602        };
603
604        let mut tx_states = std::collections::HashMap::<u64, bool>::new();
605        let mut pending = Vec::<(u64, Vec<u8>)>::new();
606
607        for record in reader.iter() {
608            let (_lsn, record) = match record {
609                Ok(record) => record,
610                Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break,
611                Err(err) => return Err(err),
612            };
613            match record {
614                WalRecord::TxCommitBatch { actions, .. } => {
615                    for payload in actions {
616                        let action = StoreWalAction::decode(&payload)?;
617                        store.apply_replayed_action(&action).map_err(|err| {
618                            io::Error::other(format!("failed to replay store wal action: {err}"))
619                        })?;
620                    }
621                }
622                WalRecord::Begin { tx_id } => {
623                    tx_states.insert(tx_id, false);
624                }
625                WalRecord::Commit { tx_id } => {
626                    tx_states.insert(tx_id, true);
627                }
628                WalRecord::Rollback { tx_id } => {
629                    tx_states.remove(&tx_id);
630                }
631                WalRecord::PageWrite {
632                    tx_id,
633                    page_id: _,
634                    data,
635                } => pending.push((tx_id, data)),
636                WalRecord::Checkpoint { .. } => {}
637                WalRecord::VectorInsert {
638                    collection,
639                    entity_id,
640                    vector,
641                } => {
642                    // Issue #694 — capture `vector.turbo` WAL inserts so the
643                    // boot-time TurboQuant index rebuild can drain them in
644                    // WAL order (deterministic against the pre-restart
645                    // state under a fixed codec seed). The legacy `vector`
646                    // path doesn't read this map.
647                    let mut map = store.replayed_turbo_inserts.lock();
648                    map.entry(collection).or_default().push((entity_id, vector));
649                }
650                WalRecord::ProbabilisticDelta {
651                    kind,
652                    operation,
653                    name,
654                    operands,
655                } => {
656                    let mut deltas = store.replayed_probabilistic_deltas.lock();
657                    deltas.push((kind, operation, name, operands));
658                }
659                WalRecord::FullPageImage { .. } => {
660                    // Pager-level FPI (gh-478); store replay ignores.
661                }
662            }
663        }
664
665        for (tx_id, payload) in pending {
666            if !tx_states.get(&tx_id).copied().unwrap_or(false) {
667                continue;
668            }
669            let action = StoreWalAction::decode(&payload)?;
670            store.apply_replayed_action(&action).map_err(|err| {
671                io::Error::other(format!("failed to replay store wal action: {err}"))
672            })?;
673        }
674
675        Ok(())
676    }
677
678    fn wait_until_durable(&self, target_lsn: u64, wal_bytes: u64) -> io::Result<()> {
679        match self.mode {
680            DurabilityMode::Strict => self.force_sync(),
681            // Async: record the pending target so the background
682            // flusher eventually covers it, but don't block the
683            // caller. Matches PG `synchronous_commit=off` semantics —
684            // crash inside the flush window loses unflushed commits.
685            DurabilityMode::Async => {
686                let (state_lock, cond) = &*self.state;
687                let mut state = state_lock.lock();
688                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
689                state.pending_statements = state.pending_statements.saturating_add(1);
690                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
691                state.first_pending_at.get_or_insert_with(Instant::now);
692                cond.notify_all();
693                Ok(())
694            }
695            DurabilityMode::WalDurableGrouped => {
696                let (state_lock, cond) = &*self.state;
697                let mut state = state_lock.lock();
698                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
699                state.pending_statements = state.pending_statements.saturating_add(1);
700                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
701                state.first_pending_at.get_or_insert_with(Instant::now);
702                cond.notify_all();
703
704                loop {
705                    if let Some(err) = state.last_error.clone() {
706                        return Err(io::Error::other(err));
707                    }
708                    if state.durable_lsn >= target_lsn {
709                        return Ok(());
710                    }
711                    // parking_lot::Condvar mutates the guard in place —
712                    // no LockResult to unwrap, no poisoning to fold.
713                    cond.wait(&mut state);
714                }
715            }
716        }
717    }
718
719    fn run_group_commit_loop(
720        wal: Arc<WalMutex>,
721        queue: Arc<WalAppendQueue>,
722        state: Arc<(CommitStateMutex, CommitStateCondvar)>,
723        fsync_count: Arc<AtomicU64>,
724        window: Duration,
725        max_statements: usize,
726        max_wal_bytes: u64,
727    ) {
728        let (state_lock, cond) = &*state;
729        loop {
730            let target_lsn = {
731                let mut guard = state_lock.lock();
732
733                while !guard.shutdown && guard.pending_target_lsn <= guard.durable_lsn {
734                    cond.wait(&mut guard);
735                }
736
737                if guard.shutdown {
738                    return;
739                }
740
741                let immediate = window.is_zero()
742                    || guard.pending_statements >= max_statements
743                    || guard.pending_wal_bytes >= max_wal_bytes;
744
745                if !immediate {
746                    let deadline = guard.first_pending_at.unwrap_or_else(Instant::now) + window;
747                    let now = Instant::now();
748                    if now < deadline {
749                        let timeout = deadline.saturating_duration_since(now);
750                        let _ = cond.wait_for(&mut guard, timeout);
751                        if guard.shutdown {
752                            return;
753                        }
754                        if guard.pending_target_lsn <= guard.durable_lsn {
755                            continue;
756                        }
757                        let should_wait_again = guard.pending_statements < max_statements
758                            && guard.pending_wal_bytes < max_wal_bytes
759                            && guard
760                                .first_pending_at
761                                .map(|first| first.elapsed() < window)
762                                .unwrap_or(false);
763                        if should_wait_again {
764                            continue;
765                        }
766                    }
767                }
768
769                guard.pending_target_lsn
770            };
771
772            // Drain all queued entries. Since `WalAppendQueue::enqueue`
773            // assigns LSN and pushes under a single mutex, the drained
774            // tuples are guaranteed to form a contiguous byte range
775            // starting at `wal.current_lsn()` — no gaps, no leftover
776            // handling.
777            let batches = queue.drain_sorted();
778
779            let sync_result = {
780                let mut wal = wal.lock();
781                let mut write_err: Option<io::Error> = None;
782                for (_lsn, bytes) in batches {
783                    if let Err(e) = wal.append_bytes(&bytes) {
784                        write_err = Some(e);
785                        break;
786                    }
787                }
788                match write_err {
789                    Some(e) => Err(e),
790                    None => wal.sync().map(|_| {
791                        // Count the fsync exactly once per drain
792                        // cycle so tests can compare it against the
793                        // number of `append_actions` callers that
794                        // entered the queue.
795                        fsync_count.fetch_add(1, Ordering::Relaxed);
796                        wal.durable_lsn()
797                    }),
798                }
799            };
800
801            // Late enqueuers that arrived after our drain stay in the
802            // queue — don't clear the `pending_*` counters yet and
803            // don't claim we reached `target_lsn` unless the fsync
804            // actually covers it.
805            let more_pending = queue.has_pending();
806
807            let mut guard = state_lock.lock();
808            match sync_result {
809                Ok(durable_lsn) => {
810                    guard.durable_lsn = durable_lsn;
811                    if !more_pending {
812                        guard.pending_statements = 0;
813                        guard.pending_wal_bytes = 0;
814                        guard.first_pending_at = None;
815                    }
816                    guard.last_error = None;
817                    let _ = target_lsn;
818                }
819                Err(err) => {
820                    guard.last_error = Some(err.to_string());
821                }
822            }
823            cond.notify_all();
824        }
825    }
826}
827
828impl Drop for StoreCommitCoordinator {
829    fn drop(&mut self) {
830        let (state_lock, cond) = &*self.state;
831        // parking_lot::Mutex::lock is infallible (no poisoning).
832        let mut state = state_lock.lock();
833        state.shutdown = true;
834        cond.notify_all();
835    }
836}
837
838impl UnifiedStore {
839    pub(crate) fn deferred_store_wal_capture_active() -> bool {
840        deferred_store_wal_capture_active()
841    }
842
843    pub(crate) fn begin_deferred_store_wal_capture() {
844        begin_deferred_store_wal_capture();
845    }
846
847    pub(crate) fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
848        take_deferred_store_wal_capture()
849    }
850
851    pub(crate) fn append_deferred_store_wal_actions(
852        &self,
853        actions: DeferredStoreWalActions,
854    ) -> Result<(), StoreError> {
855        if actions.actions.is_empty() {
856            return Ok(());
857        }
858        if self.config.embedded_wal_path.is_some() {
859            return self.append_embedded_store_wal_actions(&actions.actions);
860        }
861        // Deferred transactions need a committed WAL batch even in Strict
862        // mode. WAL-only versions have no pager pages to flush yet.
863        if let Some(commit) = &self.commit {
864            commit
865                .append_actions(&actions.actions)
866                .map_err(StoreError::Io)
867        } else {
868            self.flush_paged_state()
869        }
870    }
871
872    /// Emit a [`WalRecord::VectorInsert`] for a `vector.turbo`
873    /// collection (issue #693). Returns `Ok(())` when no commit
874    /// coordinator is configured (in-memory mode) so callers don't
875    /// have to special-case the missing WAL — the in-memory index
876    /// update remains durable enough for in-memory runtimes by
877    /// construction.
878    pub(crate) fn append_vector_insert_record(
879        &self,
880        collection: &str,
881        entity_id: u64,
882        vector: &[f32],
883    ) -> std::io::Result<()> {
884        let Some(commit) = &self.commit else {
885            return Ok(());
886        };
887        let record = WalRecord::VectorInsert {
888            collection: collection.to_string(),
889            entity_id,
890            vector: vector.to_vec(),
891        };
892        commit.append_single_record(record)
893    }
894
895    pub(crate) fn append_probabilistic_delta_record(
896        &self,
897        kind: u8,
898        operation: u8,
899        name: &str,
900        operands: Vec<Vec<u8>>,
901    ) -> std::io::Result<()> {
902        let Some(commit) = &self.commit else {
903            return Ok(());
904        };
905        let record = WalRecord::ProbabilisticDelta {
906            kind,
907            operation,
908            name: name.to_string(),
909            operands,
910        };
911        commit.append_single_record(record)
912    }
913
914    pub(crate) fn finish_paged_write(
915        &self,
916        actions: impl IntoIterator<Item = StoreWalAction>,
917    ) -> Result<(), StoreError> {
918        let actions: Vec<StoreWalAction> = actions.into_iter().collect();
919        if deferred_store_wal_capture_active() {
920            let captured = capture_deferred_store_wal_actions(actions);
921            debug_assert!(captured);
922            return Ok(());
923        }
924        if self.config.embedded_wal_path.is_some() {
925            return self.append_embedded_store_wal_actions(&actions);
926        }
927        match self.config.durability_mode {
928            DurabilityMode::Strict => {
929                if let Some(commit) = &self.commit {
930                    commit.append_actions(&actions).map_err(StoreError::Io)?;
931                }
932                self.flush_paged_state()
933            }
934            DurabilityMode::WalDurableGrouped | DurabilityMode::Async => {
935                if let Some(commit) = &self.commit {
936                    commit.append_actions(&actions).map_err(StoreError::Io)?;
937                    Ok(())
938                } else {
939                    self.flush_paged_state()
940                }
941            }
942        }
943    }
944
945    pub(crate) fn apply_encoded_store_wal_action(&self, payload: &[u8]) -> Result<(), StoreError> {
946        let action = StoreWalAction::decode(payload).map_err(StoreError::Io)?;
947        self.apply_replayed_action(&action)
948    }
949
950    fn append_embedded_store_wal_actions(
951        &self,
952        actions: &[StoreWalAction],
953    ) -> Result<(), StoreError> {
954        let Some(path) = self.config.embedded_wal_path.as_deref() else {
955            return Ok(());
956        };
957        if actions.is_empty() {
958            return Ok(());
959        }
960        let payloads: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
961        let encoded_len = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
962            .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
963        match crate::storage::EmbeddedRdbArtifact::append_wal_payloads(path, &payloads) {
964            Ok(_) => Ok(()),
965            Err(crate::api::RedDBError::InvalidOperation(msg))
966                if msg.contains("embedded wal region full") =>
967            {
968                let _vault_guard = self.vault_publication_lock.lock();
969                let snapshot = self.to_binary_dump_bytes();
970                crate::storage::EmbeddedRdbArtifact::write_snapshot_with_wal_capacity(
971                    path,
972                    &snapshot,
973                    encoded_len,
974                )
975                .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
976                crate::storage::EmbeddedRdbArtifact::append_wal_payloads(path, &payloads)
977                    .map(|_| ())
978                    .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))
979            }
980            Err(err) => Err(StoreError::Io(std::io::Error::other(err.to_string()))),
981        }
982    }
983
984    pub(crate) fn apply_replayed_action(&self, action: &StoreWalAction) -> Result<(), StoreError> {
985        match action {
986            StoreWalAction::CreateCollection { name } => {
987                if self.get_collection(name).is_none() {
988                    let _ = self.create_collection_in_memory(name);
989                }
990                Ok(())
991            }
992            StoreWalAction::DropCollection { name } => self.drop_collection_in_memory(name),
993            StoreWalAction::UpsertEntityRecord { collection, record } => {
994                self.apply_replayed_upsert(collection, record)
995            }
996            StoreWalAction::DeleteEntityRecord {
997                collection,
998                entity_id,
999            } => self.apply_replayed_delete(collection, EntityId::new(*entity_id)),
1000            StoreWalAction::BulkUpsertEntityRecords {
1001                collection,
1002                records,
1003            } => {
1004                for record in records {
1005                    self.apply_replayed_upsert(collection, record)?;
1006                }
1007                Ok(())
1008            }
1009            StoreWalAction::RefreshCollection {
1010                collection,
1011                records,
1012            } => self.apply_replayed_refresh_collection(collection, records),
1013        }
1014    }
1015
1016    /// Atomic full-collection replace — issue #595 slice 9c.
1017    ///
1018    /// Builds a fresh `SegmentManager` populated with `entities`,
1019    /// atomically swaps it into the collections map, rebuilds the
1020    /// paged B-tree from the same records, and emits a single
1021    /// `RefreshCollection` WAL action.
1022    ///
1023    /// Concurrent readers that resolved an `Arc<SegmentManager>` for
1024    /// this collection before the swap continue reading the prior
1025    /// contents; readers after the swap see the new contents. The
1026    /// transition is single-pointer so partial state is unobservable.
1027    ///
1028    /// A crash between in-memory mutation and WAL fsync leaves the
1029    /// previous WAL stream intact — on recovery the prior
1030    /// `RefreshCollection` (or whatever last bulk-applied to the
1031    /// collection) is replayed, so the prior contents are observed.
1032    pub fn refresh_collection(
1033        &self,
1034        name: &str,
1035        entities: Vec<UnifiedEntity>,
1036    ) -> Result<Vec<Vec<u8>>, StoreError> {
1037        let fv = self.format_version();
1038
1039        // Build a fresh manager. Done outside the collections lock so
1040        // the critical section is just the pointer swap below.
1041        let new_manager = Arc::new(SegmentManager::with_config(
1042            name,
1043            self.config.manager_config.clone(),
1044        ));
1045
1046        let mut prepared = entities;
1047        for entity in &mut prepared {
1048            if entity.id.raw() == 0 {
1049                entity.id = self.next_entity_id();
1050            } else {
1051                self.register_entity_id(entity.id);
1052            }
1053            if let EntityKind::TableRow { ref mut row_id, .. } = entity.kind {
1054                if *row_id == 0 {
1055                    *row_id = new_manager.next_row_id();
1056                } else {
1057                    new_manager.register_row_id(*row_id);
1058                }
1059            }
1060            entity.ensure_table_logical_id();
1061        }
1062
1063        let serialized: Vec<Vec<u8>> = prepared
1064            .iter()
1065            .map(|e| Self::serialize_entity_record(e, None, fv))
1066            .collect();
1067
1068        new_manager.bulk_insert(prepared.clone()).map_err(|e| {
1069            StoreError::Io(std::io::Error::other(format!(
1070                "refresh_collection: bulk_insert into new manager failed: {e}"
1071            )))
1072        })?;
1073
1074        self.swap_collection_state(name, new_manager, &prepared, &serialized);
1075
1076        self.finish_paged_write([StoreWalAction::RefreshCollection {
1077            collection: name.to_string(),
1078            records: serialized.clone(),
1079        }])?;
1080
1081        Ok(serialized)
1082    }
1083
1084    /// Atomic swap of the in-memory collection state. Used by both
1085    /// the live `refresh_collection` path and WAL replay. The new
1086    /// manager is already populated; this fn replaces the live Arc,
1087    /// purges side-state pointing at the previous contents, and
1088    /// rebuilds the paged B-tree from the supplied records.
1089    fn swap_collection_state(
1090        &self,
1091        name: &str,
1092        new_manager: Arc<SegmentManager>,
1093        prepared: &[UnifiedEntity],
1094        serialized: &[Vec<u8>],
1095    ) {
1096        {
1097            let mut collections = self.collections.write();
1098            collections.insert(name.to_string(), new_manager);
1099        }
1100
1101        self.entity_cache
1102            .retain(|_, (collection, _)| collection != name);
1103        self.remove_from_graph_label_index_batch(
1104            name,
1105            &prepared.iter().map(|e| e.id).collect::<Vec<_>>(),
1106        );
1107
1108        if let Some(pager) = &self.pager {
1109            let new_btree = Arc::new(BTree::new(Arc::clone(pager)));
1110            let mut sorted: Vec<(Vec<u8>, Vec<u8>)> = prepared
1111                .iter()
1112                .zip(serialized.iter())
1113                .map(|(e, r)| (e.id.raw().to_be_bytes().to_vec(), r.clone()))
1114                .collect();
1115            sorted.sort_by(|a, b| a.0.cmp(&b.0));
1116            if !sorted.is_empty() {
1117                let _ = new_btree.bulk_insert_sorted(&sorted);
1118            }
1119            self.btree_indices
1120                .write()
1121                .insert(name.to_string(), new_btree);
1122            self.mark_paged_registry_dirty();
1123        }
1124    }
1125
1126    fn apply_replayed_refresh_collection(
1127        &self,
1128        collection: &str,
1129        records: &[Vec<u8>],
1130    ) -> Result<(), StoreError> {
1131        let new_manager = Arc::new(SegmentManager::with_config(
1132            collection,
1133            self.config.manager_config.clone(),
1134        ));
1135
1136        let mut prepared: Vec<UnifiedEntity> = Vec::with_capacity(records.len());
1137        for record in records {
1138            let (entity, _metadata) =
1139                Self::deserialize_entity_record(record, self.format_version())?;
1140            self.register_entity_id(entity.id);
1141            if let EntityKind::TableRow { row_id, .. } = &entity.kind {
1142                new_manager.register_row_id(*row_id);
1143            }
1144            prepared.push(entity);
1145        }
1146
1147        if !prepared.is_empty() {
1148            new_manager.bulk_insert(prepared.clone()).map_err(|e| {
1149                StoreError::Io(std::io::Error::other(format!(
1150                    "replay refresh_collection: bulk_insert failed: {e}"
1151                )))
1152            })?;
1153        }
1154
1155        self.swap_collection_state(collection, new_manager, &prepared, records);
1156        Ok(())
1157    }
1158
1159    /// Replica-side analogue of [`Self::refresh_collection`] — issue
1160    /// #596 slice 9d. Takes pre-serialized record bytes from the
1161    /// primary's CDC stream (the same bytes the primary wrote into the
1162    /// `RefreshCollection` WAL action), applies the atomic swap, and
1163    /// emits the same `RefreshCollection` WAL action against the
1164    /// replica's local store WAL so the post-swap state survives a
1165    /// replica restart through the normal recovery path.
1166    ///
1167    /// Idempotency: re-applying the same records bytes is a full
1168    /// rebuild from the same payload, so the resulting backing-
1169    /// collection contents are equal to the prior call's result.
1170    /// The primary-side `LogicalChangeApplier` short-circuits exact
1171    /// duplicate LSN+payload combinations before reaching here.
1172    pub fn refresh_collection_from_records(
1173        &self,
1174        name: &str,
1175        records: Vec<Vec<u8>>,
1176    ) -> Result<(), StoreError> {
1177        self.apply_replayed_refresh_collection(name, &records)?;
1178        self.finish_paged_write([StoreWalAction::RefreshCollection {
1179            collection: name.to_string(),
1180            records,
1181        }])?;
1182        Ok(())
1183    }
1184
1185    pub(crate) fn create_collection_in_memory(&self, name: &str) -> Result<(), StoreError> {
1186        let mut collections = self.collections.write();
1187        if collections.contains_key(name) {
1188            return Ok(());
1189        }
1190        let manager = SegmentManager::with_config(name, self.config.manager_config.clone());
1191        collections.insert(name.to_string(), Arc::new(manager));
1192        self.mark_paged_registry_dirty();
1193        Ok(())
1194    }
1195
1196    fn drop_collection_in_memory(&self, name: &str) -> Result<(), StoreError> {
1197        let manager = {
1198            let mut collections = self.collections.write();
1199            match collections.remove(name) {
1200                Some(manager) => manager,
1201                None => return Ok(()),
1202            }
1203        };
1204
1205        let entities = manager.query_all(|_| true);
1206        let entity_ids: Vec<EntityId> = entities.iter().map(|entity| entity.id).collect();
1207        for entity_id in &entity_ids {
1208            self.context_index.remove_entity(*entity_id);
1209            let _ = self.unindex_cross_refs(*entity_id);
1210        }
1211        self.btree_indices.write().remove(name);
1212        self.entity_cache.retain(|entity_id, (collection, _)| {
1213            collection != name && !entity_ids.iter().any(|id| id.raw() == entity_id)
1214        });
1215        self.remove_from_graph_label_index_batch(name, &entity_ids);
1216        self.mark_paged_registry_dirty();
1217        Ok(())
1218    }
1219
1220    fn apply_replayed_upsert(&self, collection: &str, record: &[u8]) -> Result<(), StoreError> {
1221        self.create_collection_in_memory(collection)?;
1222        let (entity, metadata) = Self::deserialize_entity_record(record, self.format_version())?;
1223        let manager = self
1224            .get_collection(collection)
1225            .ok_or_else(|| StoreError::CollectionNotFound(collection.to_string()))?;
1226
1227        self.register_entity_id(entity.id);
1228        if let EntityKind::TableRow { row_id, .. } = &entity.kind {
1229            manager.register_row_id(*row_id);
1230        }
1231
1232        self.context_index.remove_entity(entity.id);
1233        let _ = self.unindex_cross_refs(entity.id);
1234        self.remove_from_graph_label_index(collection, entity.id);
1235
1236        if manager.get(entity.id).is_some() {
1237            manager
1238                .update_with_metadata(entity.clone(), metadata.as_ref())
1239                .map_err(StoreError::from)?;
1240        } else {
1241            manager.insert(entity.clone())?;
1242            if let Some(metadata) = metadata.as_ref() {
1243                manager.set_metadata(entity.id, metadata.clone())?;
1244            }
1245        }
1246
1247        self.context_index.index_entity(collection, &entity);
1248        if let EntityKind::GraphNode(node) = &entity.kind {
1249            self.update_graph_label_index(collection, &node.label, entity.id);
1250        }
1251        self.index_cross_refs(&entity, collection)?;
1252
1253        if let Some(pager) = &self.pager {
1254            let mut btree_indices = self.btree_indices.write();
1255            let btree = btree_indices
1256                .entry(collection.to_string())
1257                .or_insert_with(|| Arc::new(BTree::new(Arc::clone(pager))));
1258            let root_before = btree.root_page_id();
1259            let key = entity.id.raw().to_be_bytes();
1260            match btree.insert(&key, record) {
1261                Ok(_) => {}
1262                Err(BTreeError::DuplicateKey) => {
1263                    let _ = btree.delete(&key);
1264                    let _ = btree.insert(&key, record);
1265                }
1266                Err(err) => {
1267                    return Err(StoreError::Io(io::Error::other(format!(
1268                        "replay upsert btree error: {err}"
1269                    ))));
1270                }
1271            }
1272            if root_before != btree.root_page_id() {
1273                self.mark_paged_registry_dirty();
1274            }
1275        }
1276
1277        Ok(())
1278    }
1279
1280    fn apply_replayed_delete(&self, collection: &str, id: EntityId) -> Result<(), StoreError> {
1281        self.entity_cache.remove(id.raw());
1282        if let Some(manager) = self.get_collection(collection) {
1283            let deleted = manager.delete(id)?;
1284            if !deleted {
1285                return Ok(());
1286            }
1287        } else {
1288            return Ok(());
1289        }
1290
1291        if let Some(_pager) = &self.pager {
1292            let btree_indices = self.btree_indices.read();
1293            if let Some(btree) = btree_indices.get(collection) {
1294                let root_before = btree.root_page_id();
1295                let key = id.raw().to_be_bytes();
1296                let _ = btree.delete(&key);
1297                if root_before != btree.root_page_id() {
1298                    self.mark_paged_registry_dirty();
1299                }
1300            }
1301        }
1302
1303        let _ = self.unindex_cross_refs(id);
1304        self.remove_from_graph_label_index(collection, id);
1305        self.context_index.remove_entity(id);
1306        Ok(())
1307    }
1308}
1309
1310#[cfg(test)]
1311mod tests {
1312    use super::*;
1313    use crate::api::{DurabilityMode, GroupCommitOptions};
1314    use std::sync::{Barrier, Mutex as StdMutex, OnceLock};
1315    use std::time::SystemTime;
1316
1317    /// Serialise tests that mutate `REDDB_GROUP_COMMIT_WINDOW_US`.
1318    /// The env table is process-global, so two parallel test threads
1319    /// flipping it would race the assertions in the test that
1320    /// happens to read it last.
1321    fn env_lock() -> &'static StdMutex<()> {
1322        static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
1323        LOCK.get_or_init(|| StdMutex::new(()))
1324    }
1325
1326    fn temp_wal(name: &str) -> PathBuf {
1327        let nanos = SystemTime::now()
1328            .duration_since(std::time::UNIX_EPOCH)
1329            .unwrap()
1330            .as_nanos();
1331        let path = reddb_file::layout::store_commit_coord_temp_wal_path(
1332            &std::env::temp_dir(),
1333            name,
1334            std::process::id(),
1335            nanos,
1336        );
1337        let _ = std::fs::remove_file(&path);
1338        path
1339    }
1340
1341    /// Concurrent autocommits MUST coalesce into far fewer fsyncs
1342    /// than the number of callers when the adaptive group-commit
1343    /// window is active. Without the 200µs floor, every caller
1344    /// would race the drain loop and pay an independent fsync.
1345    ///
1346    /// The test fires 32 concurrent `append_actions` calls and asserts
1347    /// the coordinator issued strictly fewer fsyncs than callers.
1348    /// (We don't pin to "one fsync" because timing on loaded CI hosts
1349    /// can split the burst across a couple of drain cycles — the win
1350    /// is the ratio, not the absolute count.)
1351    #[test]
1352    fn group_commit_coalesces_concurrent_autocommits() {
1353        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
1354        // Make sure no stale env var skews this run — the test
1355        // exercises the default 200µs floor.
1356        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
1357
1358        let path = temp_wal("coalesce");
1359        let coord = Arc::new(
1360            StoreCommitCoordinator::open(
1361                path.clone(),
1362                DurabilityMode::WalDurableGrouped,
1363                GroupCommitOptions::default(),
1364            )
1365            .expect("open commit coordinator"),
1366        );
1367
1368        const WRITERS: usize = 32;
1369        let barrier = Arc::new(Barrier::new(WRITERS));
1370        let mut handles = Vec::with_capacity(WRITERS);
1371        for tx in 0..WRITERS {
1372            let coord_c = Arc::clone(&coord);
1373            let barrier_c = Arc::clone(&barrier);
1374            handles.push(std::thread::spawn(move || {
1375                // Synchronise the start so every writer races the
1376                // drain loop together — this is the workload shape
1377                // the adaptive window is supposed to coalesce.
1378                barrier_c.wait();
1379                let action = StoreWalAction::CreateCollection {
1380                    name: format!("c{tx}"),
1381                };
1382                coord_c
1383                    .append_actions(std::slice::from_ref(&action))
1384                    .expect("append_actions");
1385            }));
1386        }
1387        for h in handles {
1388            h.join().expect("writer thread");
1389        }
1390
1391        let fsyncs = coord.fsync_count();
1392        assert!(fsyncs > 0, "expected at least one fsync, got {fsyncs}");
1393        assert!(
1394            fsyncs < WRITERS as u64,
1395            "expected fsyncs ({fsyncs}) to be strictly less than \
1396             concurrent writers ({WRITERS}); coalescing failed"
1397        );
1398
1399        drop(coord);
1400        let _ = std::fs::remove_file(&path);
1401    }
1402
1403    /// Sanity check: with the env override forcing a zero window,
1404    /// fsync coalescing degrades — callers race and we approach
1405    /// one fsync per caller. This proves the window is the actual
1406    /// knob doing the work above (i.e. the test isn't passing for
1407    /// some unrelated reason like buffered-IO coalescing).
1408    #[test]
1409    fn zero_window_disables_coalescing_floor() {
1410        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
1411        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "0");
1412
1413        let path = temp_wal("zero_window");
1414        let coord = Arc::new(
1415            StoreCommitCoordinator::open(
1416                path.clone(),
1417                DurabilityMode::WalDurableGrouped,
1418                GroupCommitOptions::default(),
1419            )
1420            .expect("open commit coordinator"),
1421        );
1422
1423        const WRITERS: usize = 8;
1424        let barrier = Arc::new(Barrier::new(WRITERS));
1425        let mut handles = Vec::with_capacity(WRITERS);
1426        for tx in 0..WRITERS {
1427            let coord_c = Arc::clone(&coord);
1428            let barrier_c = Arc::clone(&barrier);
1429            handles.push(std::thread::spawn(move || {
1430                barrier_c.wait();
1431                let action = StoreWalAction::CreateCollection {
1432                    name: format!("z{tx}"),
1433                };
1434                coord_c
1435                    .append_actions(std::slice::from_ref(&action))
1436                    .expect("append_actions");
1437            }));
1438        }
1439        for h in handles {
1440            h.join().expect("writer thread");
1441        }
1442
1443        // With zero window, fsync count is bounded above by WRITERS
1444        // (every caller might trigger its own drain) and below by 1
1445        // (the queue may still naturally batch under contention).
1446        // The point of the assertion is to confirm the env override
1447        // is wired through — the open() above used the env knob.
1448        let fsyncs = coord.fsync_count();
1449        assert!(fsyncs >= 1, "expected at least one fsync, got {fsyncs}");
1450
1451        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
1452        drop(coord);
1453        let _ = std::fs::remove_file(&path);
1454    }
1455
1456    /// `resolve_window` precedence: env > config.window_ms > default.
1457    #[test]
1458    fn resolve_window_precedence() {
1459        let _env = env_lock().lock().unwrap_or_else(|p| p.into_inner());
1460        // Default: window_ms=0 → adaptive 200µs floor.
1461        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
1462        let cfg = GroupCommitOptions::default();
1463        assert_eq!(
1464            StoreCommitCoordinator::resolve_window(&cfg),
1465            Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
1466        );
1467
1468        // Explicit ms config wins over the default floor.
1469        let cfg_ms = GroupCommitOptions {
1470            window_ms: 5,
1471            ..GroupCommitOptions::default()
1472        };
1473        assert_eq!(
1474            StoreCommitCoordinator::resolve_window(&cfg_ms),
1475            Duration::from_millis(5)
1476        );
1477
1478        // Env override wins over both.
1479        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "750");
1480        assert_eq!(
1481            StoreCommitCoordinator::resolve_window(&cfg),
1482            Duration::from_micros(750)
1483        );
1484        assert_eq!(
1485            StoreCommitCoordinator::resolve_window(&cfg_ms),
1486            Duration::from_micros(750)
1487        );
1488
1489        // Env=0 explicitly disables the floor.
1490        std::env::set_var("REDDB_GROUP_COMMIT_WINDOW_US", "0");
1491        assert_eq!(
1492            StoreCommitCoordinator::resolve_window(&cfg),
1493            Duration::from_micros(0)
1494        );
1495
1496        std::env::remove_var("REDDB_GROUP_COMMIT_WINDOW_US");
1497    }
1498}