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 should_open(path: &Path, mode: DurabilityMode) -> bool {
385        matches!(
386            mode,
387            DurabilityMode::WalDurableGrouped | DurabilityMode::Async
388        ) || path.exists()
389    }
390
391    pub(crate) fn open(
392        wal_path: impl Into<PathBuf>,
393        mode: DurabilityMode,
394        config: crate::api::GroupCommitOptions,
395    ) -> io::Result<Self> {
396        let wal_path = wal_path.into();
397        let wal = WalWriter::open(&wal_path)?;
398        let initial_durable_lsn = wal.durable_lsn();
399        let initial_current_lsn = wal.current_lsn();
400        let wal = Arc::new(WalMutex::new(wal));
401        let queue = Arc::new(WalAppendQueue::new(initial_current_lsn));
402        let state = Arc::new((
403            CommitStateMutex::new(CommitState::new(initial_durable_lsn)),
404            CommitStateCondvar::new(),
405        ));
406        let fsync_count = Arc::new(AtomicU64::new(0));
407
408        if matches!(
409            mode,
410            DurabilityMode::WalDurableGrouped | DurabilityMode::Async
411        ) {
412            let wal_bg = Arc::clone(&wal);
413            let queue_bg = Arc::clone(&queue);
414            let state_bg = Arc::clone(&state);
415            let fsync_bg = Arc::clone(&fsync_count);
416            // P1: adaptive group-commit window. Historical default is
417            // `window_ms = 0` ("no wait"), which under single-writer
418            // OLTP means one fsync per autocommit row — the throughput
419            // floor. When window_ms is 0 we fall back to a small
420            // microsecond floor (`DEFAULT_ADAPTIVE_WINDOW_US`, override
421            // via `REDDB_GROUP_COMMIT_WINDOW_US`) so a pipelined writer
422            // can drop a second statement into the same drain cycle.
423            // Explicit non-zero `window_ms` config takes precedence.
424            //
425            // The loop already short-circuits on
426            // `pending_statements >= max_statements` /
427            // `pending_wal_bytes >= max_wal_bytes`, so the window only
428            // delays the leader when the queue is otherwise empty —
429            // exactly the case we want to coalesce.
430            let window = Self::resolve_window(&config);
431            let max_statements = config.max_statements.max(1);
432            let max_wal_bytes = config.max_wal_bytes.max(1);
433            std::thread::spawn(move || {
434                Self::run_group_commit_loop(
435                    wal_bg,
436                    queue_bg,
437                    state_bg,
438                    fsync_bg,
439                    window,
440                    max_statements,
441                    max_wal_bytes,
442                );
443            });
444        }
445
446        Ok(Self {
447            mode,
448            config,
449            wal_path,
450            wal,
451            queue,
452            state,
453            fsync_count,
454        })
455    }
456
457    /// Resolve the effective group-commit window from the configured
458    /// options + the `REDDB_GROUP_COMMIT_WINDOW_US` env override.
459    ///
460    /// Precedence (highest first):
461    ///   1. `REDDB_GROUP_COMMIT_WINDOW_US=N` — N µs (0 disables).
462    ///   2. `config.window_ms != 0` — explicit ms config wins.
463    ///   3. `DEFAULT_ADAPTIVE_WINDOW_US` — adaptive floor for the
464    ///      historical zero-default. Set the env var to 0 to opt out.
465    fn resolve_window(config: &crate::api::GroupCommitOptions) -> Duration {
466        if let Ok(raw) = std::env::var("REDDB_GROUP_COMMIT_WINDOW_US") {
467            if let Ok(parsed) = raw.parse::<u64>() {
468                return Duration::from_micros(parsed);
469            }
470        }
471        if config.window_ms != 0 {
472            return Duration::from_millis(config.window_ms);
473        }
474        Duration::from_micros(DEFAULT_ADAPTIVE_WINDOW_US)
475    }
476
477    /// Total `wal.sync()` calls issued since this coordinator opened.
478    /// Public for tests that want to observe fsync coalescing under
479    /// concurrent autocommits.
480    #[cfg(test)]
481    pub(crate) fn fsync_count(&self) -> u64 {
482        self.fsync_count.load(Ordering::Relaxed)
483    }
484
485    /// WAL buffer memory held right now: encoded records waiting in the
486    /// group-commit queue plus the writer's fixed append buffer, which exists
487    /// for the coordinator's whole life (ADR 0073 §2, the `wal_buffers` pool).
488    pub(crate) fn buffered_bytes(&self) -> u64 {
489        self.queue.queued_bytes() + crate::storage::wal::WAL_BUFFER_BYTES as u64
490    }
491
492    pub(crate) fn append_actions(&self, actions: &[StoreWalAction]) -> io::Result<()> {
493        if actions.is_empty() {
494            return Ok(());
495        }
496
497        let tx_id = NEXT_STORE_TX_ID.fetch_add(1, Ordering::SeqCst);
498
499        // Strict mode: bypass the queue, write + fsync inline. Strict
500        // commits are exactly one-fsync-per-call by contract, so the
501        // coalescing win of the queue doesn't apply and we'd pay an
502        // extra hop through the drain loop.
503        if matches!(self.mode, DurabilityMode::Strict) {
504            let commit_lsn = {
505                let mut wal = self.wal.lock();
506                wal.append(&WalRecord::TxCommitBatch {
507                    tx_id,
508                    actions: actions.iter().map(StoreWalAction::encode).collect(),
509                })?;
510                wal.current_lsn()
511            };
512            self.force_sync()?;
513            let _ = commit_lsn;
514            return Ok(());
515        }
516
517        // Grouped / Async path — lock-free enqueue. Encode every
518        // WalRecord into one contiguous byte blob OUTSIDE any lock,
519        // then hand it to the queue with a single fetch_add+push.
520        let encoded_actions: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
521        let wal_bytes = encoded_actions.iter().fold(0u64, |total, payload| {
522            total.saturating_add(payload.len() as u64)
523        });
524        let blob = WalRecord::TxCommitBatch {
525            tx_id,
526            actions: encoded_actions,
527        }
528        .encode();
529
530        let commit_lsn = self.queue.enqueue(blob);
531        self.wait_until_durable(commit_lsn, wal_bytes)?;
532        Ok(())
533    }
534
535    /// Encode + enqueue a single, non-batched [`WalRecord`] (issue
536    /// #693). Honours the same Strict / Grouped / Async branching as
537    /// [`Self::append_actions`] so durability semantics are uniform
538    /// across record kinds.
539    pub(crate) fn append_single_record(&self, record: WalRecord) -> io::Result<()> {
540        let blob = record.encode();
541        let wal_bytes = blob.len() as u64;
542        if matches!(self.mode, DurabilityMode::Strict) {
543            {
544                let mut wal = self.wal.lock();
545                wal.append(&record)?;
546            }
547            self.force_sync()?;
548            return Ok(());
549        }
550        let commit_lsn = self.queue.enqueue(blob);
551        self.wait_until_durable(commit_lsn, wal_bytes)?;
552        Ok(())
553    }
554
555    pub(crate) fn force_sync(&self) -> io::Result<()> {
556        {
557            let mut wal = self.wal.lock();
558            wal.sync()?;
559            self.fsync_count.fetch_add(1, Ordering::Relaxed);
560            let durable = wal.durable_lsn();
561            drop(wal);
562            let (state_lock, cond) = &*self.state;
563            let mut state = state_lock.lock();
564            state.durable_lsn = durable;
565            state.pending_target_lsn = durable.max(state.pending_target_lsn);
566            state.pending_statements = 0;
567            state.pending_wal_bytes = 0;
568            state.first_pending_at = None;
569            state.last_error = None;
570            cond.notify_all();
571        }
572        Ok(())
573    }
574
575    pub(crate) fn truncate(&self) -> io::Result<()> {
576        let mut wal = self.wal.lock();
577        wal.truncate()?;
578        let durable = wal.durable_lsn();
579        let current = wal.current_lsn();
580        drop(wal);
581
582        // Queue's next_lsn tracks byte offsets in the same space as
583        // wal.current_lsn. After truncate both must be reset together
584        // — otherwise enqueue returns a target_lsn in the old range
585        // that drain can never reach, and wait_until_durable hangs.
586        self.queue.reset(current);
587
588        let (state_lock, cond) = &*self.state;
589        let mut state = state_lock.lock();
590        state.durable_lsn = durable;
591        state.pending_target_lsn = durable;
592        state.pending_statements = 0;
593        state.pending_wal_bytes = 0;
594        state.first_pending_at = None;
595        state.last_error = None;
596        cond.notify_all();
597        Ok(())
598    }
599
600    pub(crate) fn replay_into(&self, store: &UnifiedStore) -> io::Result<()> {
601        if !self.wal_path.exists() {
602            return Ok(());
603        }
604
605        let reader = match WalReader::open(&self.wal_path) {
606            Ok(reader) => reader,
607            Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()),
608            Err(err) => return Err(err),
609        };
610
611        let mut tx_states = std::collections::HashMap::<u64, bool>::new();
612        let mut pending = Vec::<(u64, Vec<u8>)>::new();
613
614        for record in reader.iter() {
615            let (_lsn, record) = match record {
616                Ok(record) => record,
617                Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => break,
618                Err(err) => return Err(err),
619            };
620            match record {
621                WalRecord::TxCommitBatch { actions, .. } => {
622                    for payload in actions {
623                        let action = StoreWalAction::decode(&payload)?;
624                        store.apply_replayed_action(&action).map_err(|err| {
625                            io::Error::other(format!("failed to replay store wal action: {err}"))
626                        })?;
627                    }
628                }
629                WalRecord::Begin { tx_id } => {
630                    tx_states.insert(tx_id, false);
631                }
632                WalRecord::Commit { tx_id } => {
633                    tx_states.insert(tx_id, true);
634                }
635                WalRecord::Rollback { tx_id } => {
636                    tx_states.remove(&tx_id);
637                }
638                WalRecord::PageWrite {
639                    tx_id,
640                    page_id: _,
641                    data,
642                } => pending.push((tx_id, data)),
643                WalRecord::Checkpoint { .. } => {}
644                WalRecord::VectorInsert {
645                    collection,
646                    entity_id,
647                    vector,
648                } => {
649                    // Issue #694 — capture `vector.turbo` WAL inserts so the
650                    // boot-time TurboQuant index rebuild can drain them in
651                    // WAL order (deterministic against the pre-restart
652                    // state under a fixed codec seed). The legacy `vector`
653                    // path doesn't read this map.
654                    let mut map = store.replayed_turbo_inserts.lock();
655                    map.entry(collection).or_default().push((entity_id, vector));
656                }
657                WalRecord::ProbabilisticDelta {
658                    kind,
659                    operation,
660                    name,
661                    operands,
662                } => {
663                    let mut deltas = store.replayed_probabilistic_deltas.lock();
664                    deltas.push((kind, operation, name, operands));
665                }
666                WalRecord::FullPageImage { .. } => {
667                    // Pager-level FPI (gh-478); store replay ignores.
668                }
669            }
670        }
671
672        for (tx_id, payload) in pending {
673            if !tx_states.get(&tx_id).copied().unwrap_or(false) {
674                continue;
675            }
676            let action = StoreWalAction::decode(&payload)?;
677            store.apply_replayed_action(&action).map_err(|err| {
678                io::Error::other(format!("failed to replay store wal action: {err}"))
679            })?;
680        }
681
682        Ok(())
683    }
684
685    fn wait_until_durable(&self, target_lsn: u64, wal_bytes: u64) -> io::Result<()> {
686        match self.mode {
687            DurabilityMode::Strict => self.force_sync(),
688            // Async: record the pending target so the background
689            // flusher eventually covers it, but don't block the
690            // caller. Matches PG `synchronous_commit=off` semantics —
691            // crash inside the flush window loses unflushed commits.
692            DurabilityMode::Async => {
693                let (state_lock, cond) = &*self.state;
694                let mut state = state_lock.lock();
695                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
696                state.pending_statements = state.pending_statements.saturating_add(1);
697                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
698                state.first_pending_at.get_or_insert_with(Instant::now);
699                cond.notify_all();
700                Ok(())
701            }
702            DurabilityMode::WalDurableGrouped => {
703                let (state_lock, cond) = &*self.state;
704                let mut state = state_lock.lock();
705                state.pending_target_lsn = state.pending_target_lsn.max(target_lsn);
706                state.pending_statements = state.pending_statements.saturating_add(1);
707                state.pending_wal_bytes = state.pending_wal_bytes.saturating_add(wal_bytes);
708                state.first_pending_at.get_or_insert_with(Instant::now);
709                cond.notify_all();
710
711                loop {
712                    if let Some(err) = state.last_error.clone() {
713                        return Err(io::Error::other(err));
714                    }
715                    if state.durable_lsn >= target_lsn {
716                        return Ok(());
717                    }
718                    // parking_lot::Condvar mutates the guard in place —
719                    // no LockResult to unwrap, no poisoning to fold.
720                    cond.wait(&mut state);
721                }
722            }
723        }
724    }
725
726    fn run_group_commit_loop(
727        wal: Arc<WalMutex>,
728        queue: Arc<WalAppendQueue>,
729        state: Arc<(CommitStateMutex, CommitStateCondvar)>,
730        fsync_count: Arc<AtomicU64>,
731        window: Duration,
732        max_statements: usize,
733        max_wal_bytes: u64,
734    ) {
735        let (state_lock, cond) = &*state;
736        loop {
737            let target_lsn = {
738                let mut guard = state_lock.lock();
739
740                while !guard.shutdown && guard.pending_target_lsn <= guard.durable_lsn {
741                    cond.wait(&mut guard);
742                }
743
744                if guard.shutdown {
745                    return;
746                }
747
748                let immediate = window.is_zero()
749                    || guard.pending_statements >= max_statements
750                    || guard.pending_wal_bytes >= max_wal_bytes;
751
752                if !immediate {
753                    let deadline = guard.first_pending_at.unwrap_or_else(Instant::now) + window;
754                    let now = Instant::now();
755                    if now < deadline {
756                        let timeout = deadline.saturating_duration_since(now);
757                        let _ = cond.wait_for(&mut guard, timeout);
758                        if guard.shutdown {
759                            return;
760                        }
761                        if guard.pending_target_lsn <= guard.durable_lsn {
762                            continue;
763                        }
764                        let should_wait_again = guard.pending_statements < max_statements
765                            && guard.pending_wal_bytes < max_wal_bytes
766                            && guard
767                                .first_pending_at
768                                .map(|first| first.elapsed() < window)
769                                .unwrap_or(false);
770                        if should_wait_again {
771                            continue;
772                        }
773                    }
774                }
775
776                guard.pending_target_lsn
777            };
778
779            // Drain all queued entries. Since `WalAppendQueue::enqueue`
780            // assigns LSN and pushes under a single mutex, the drained
781            // tuples are guaranteed to form a contiguous byte range
782            // starting at `wal.current_lsn()` — no gaps, no leftover
783            // handling.
784            let batches = queue.drain_sorted();
785
786            let sync_result = {
787                let mut wal = wal.lock();
788                let mut write_err: Option<io::Error> = None;
789                for (_lsn, bytes) in batches {
790                    if let Err(e) = wal.append_bytes(&bytes) {
791                        write_err = Some(e);
792                        break;
793                    }
794                }
795                match write_err {
796                    Some(e) => Err(e),
797                    None => wal.sync().map(|_| {
798                        // Count the fsync exactly once per drain
799                        // cycle so tests can compare it against the
800                        // number of `append_actions` callers that
801                        // entered the queue.
802                        fsync_count.fetch_add(1, Ordering::Relaxed);
803                        wal.durable_lsn()
804                    }),
805                }
806            };
807
808            // Late enqueuers that arrived after our drain stay in the
809            // queue — don't clear the `pending_*` counters yet and
810            // don't claim we reached `target_lsn` unless the fsync
811            // actually covers it.
812            let more_pending = queue.has_pending();
813
814            let mut guard = state_lock.lock();
815            match sync_result {
816                Ok(durable_lsn) => {
817                    guard.durable_lsn = durable_lsn;
818                    if !more_pending {
819                        guard.pending_statements = 0;
820                        guard.pending_wal_bytes = 0;
821                        guard.first_pending_at = None;
822                    }
823                    guard.last_error = None;
824                    let _ = target_lsn;
825                }
826                Err(err) => {
827                    guard.last_error = Some(err.to_string());
828                }
829            }
830            cond.notify_all();
831        }
832    }
833}
834
835impl Drop for StoreCommitCoordinator {
836    fn drop(&mut self) {
837        let (state_lock, cond) = &*self.state;
838        // parking_lot::Mutex::lock is infallible (no poisoning).
839        let mut state = state_lock.lock();
840        state.shutdown = true;
841        cond.notify_all();
842    }
843}
844
845impl UnifiedStore {
846    pub(crate) fn begin_deferred_store_wal_capture() {
847        begin_deferred_store_wal_capture();
848    }
849
850    pub(crate) fn take_deferred_store_wal_capture() -> DeferredStoreWalActions {
851        take_deferred_store_wal_capture()
852    }
853
854    pub(crate) fn append_deferred_store_wal_actions(
855        &self,
856        actions: DeferredStoreWalActions,
857    ) -> Result<(), StoreError> {
858        if actions.actions.is_empty() {
859            return Ok(());
860        }
861        if self.config.embedded_wal_path.is_some() {
862            return self.append_embedded_store_wal_actions(&actions.actions);
863        }
864        match self.config.durability_mode {
865            DurabilityMode::Strict => self.flush_paged_state(),
866            DurabilityMode::WalDurableGrouped | DurabilityMode::Async => {
867                if let Some(commit) = &self.commit {
868                    commit
869                        .append_actions(&actions.actions)
870                        .map_err(StoreError::Io)
871                } else {
872                    self.flush_paged_state()
873                }
874            }
875        }
876    }
877
878    /// Emit a [`WalRecord::VectorInsert`] for a `vector.turbo`
879    /// collection (issue #693). Returns `Ok(())` when no commit
880    /// coordinator is configured (in-memory mode) so callers don't
881    /// have to special-case the missing WAL — the in-memory index
882    /// update remains durable enough for in-memory runtimes by
883    /// construction.
884    pub(crate) fn append_vector_insert_record(
885        &self,
886        collection: &str,
887        entity_id: u64,
888        vector: &[f32],
889    ) -> std::io::Result<()> {
890        let Some(commit) = &self.commit else {
891            return Ok(());
892        };
893        let record = WalRecord::VectorInsert {
894            collection: collection.to_string(),
895            entity_id,
896            vector: vector.to_vec(),
897        };
898        commit.append_single_record(record)
899    }
900
901    pub(crate) fn append_probabilistic_delta_record(
902        &self,
903        kind: u8,
904        operation: u8,
905        name: &str,
906        operands: Vec<Vec<u8>>,
907    ) -> std::io::Result<()> {
908        let Some(commit) = &self.commit else {
909            return Ok(());
910        };
911        let record = WalRecord::ProbabilisticDelta {
912            kind,
913            operation,
914            name: name.to_string(),
915            operands,
916        };
917        commit.append_single_record(record)
918    }
919
920    pub(crate) fn finish_paged_write(
921        &self,
922        actions: impl IntoIterator<Item = StoreWalAction>,
923    ) -> Result<(), StoreError> {
924        let actions: Vec<StoreWalAction> = actions.into_iter().collect();
925        if deferred_store_wal_capture_active() {
926            let captured = capture_deferred_store_wal_actions(actions);
927            debug_assert!(captured);
928            return Ok(());
929        }
930        if self.config.embedded_wal_path.is_some() {
931            return self.append_embedded_store_wal_actions(&actions);
932        }
933        match self.config.durability_mode {
934            DurabilityMode::Strict => self.flush_paged_state(),
935            DurabilityMode::WalDurableGrouped | DurabilityMode::Async => {
936                if let Some(commit) = &self.commit {
937                    commit.append_actions(&actions).map_err(StoreError::Io)?;
938                    Ok(())
939                } else {
940                    self.flush_paged_state()
941                }
942            }
943        }
944    }
945
946    pub(crate) fn apply_encoded_store_wal_action(&self, payload: &[u8]) -> Result<(), StoreError> {
947        let action = StoreWalAction::decode(payload).map_err(StoreError::Io)?;
948        self.apply_replayed_action(&action)
949    }
950
951    fn append_embedded_store_wal_actions(
952        &self,
953        actions: &[StoreWalAction],
954    ) -> Result<(), StoreError> {
955        let Some(path) = self.config.embedded_wal_path.as_deref() else {
956            return Ok(());
957        };
958        if actions.is_empty() {
959            return Ok(());
960        }
961        let payloads: Vec<Vec<u8>> = actions.iter().map(StoreWalAction::encode).collect();
962        let encoded_len = crate::storage::EmbeddedRdbArtifact::wal_payloads_encoded_len(&payloads)
963            .map_err(|err| StoreError::Io(std::io::Error::other(err.to_string())))?;
964        match crate::storage::EmbeddedRdbArtifact::append_wal_payloads(path, &payloads) {
965            Ok(_) => Ok(()),
966            Err(crate::api::RedDBError::InvalidOperation(msg))
967                if msg.contains("embedded wal region full") =>
968            {
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}