Skip to main content

mongreldb_core/
compaction.rs

1//! Tiered compaction (Phase 5) with snapshot retention.
2//!
3//! Merges all sorted runs into one, dropping superseded versions and tombstones
4//! — but preserving the version each pinned read snapshot still needs. Identical
5//! re-encoded pages reuse their content hash, so the page cache keeps hitting.
6//!
7//! # HLC visibility (P0.5-T3)
8//!
9//! When versions carry `commit_ts`, newest-version selection uses
10//! [`crate::epoch::Snapshot::version_is_newer`] so HLC order wins over local
11//! epoch order. Physical reclamation still consults the epoch GC floor
12//! ([`Table::min_active_snapshot`]) until every pin source projects a durable
13//! HLC (`GcFloor` is diagnostic until that cutover). Sorted-run materialisation
14//! currently drops `commit_ts` (no system column yet), so run-resident versions
15//! are retained under epoch rules only after spill.
16
17use crate::engine::Table;
18use crate::epoch::{Epoch, MaintenanceReceipt, Snapshot};
19use crate::manifest::RunRef;
20use crate::memtable::Row;
21use crate::sorted_run::RunWriter;
22use crate::{ExecutionControl, MongrelError, Result};
23use std::collections::HashMap;
24use std::path::Path;
25
26impl Table {
27    /// Background-compaction run-count threshold (§5.9). When a table accumulates
28    /// at least this many sorted runs, every multi-run query pays decode work
29    /// proportional to the run count; `maybe_compact` collapses them back to one.
30    /// Conservative so a steady write stream doesn't compact too eagerly.
31    pub const AUTO_COMPACT_RUN_THRESHOLD: usize = 8;
32
33    /// Maximum number of L0 runs permitted to overlap one another before
34    /// compaction is forced (TODO §1.2 closure gate). L0 is the mutable-run
35    /// spill tier — every flush that exceeds the mutable-run spill threshold
36    /// produces a fresh L0 run, and once their row-id ranges start to pile up
37    /// the read path pays decode work proportional to the overlap. Compaction
38    /// collapses every L0 (and any L1+ disjoint from the result) into a single
39    /// L1 run with a disjoint range.
40    pub const MAX_L0_OVERLAPPING_RUNS: usize = 64;
41
42    /// Whether this table would benefit from compaction right now — the
43    /// query-cost signal for §5.9. Pure run-count topology (no per-query
44    /// bookkeeping): once runs have accumulated past the threshold, scans and
45    /// pushdown queries are paying multi-run fallback cost, so compaction is
46    /// worthwhile. A daemon (or any long-lived holder) polls this.
47    pub fn should_compact(&self) -> bool {
48        if self.run_refs().len() >= Self::AUTO_COMPACT_RUN_THRESHOLD {
49            return true;
50        }
51        // Force-compact before the L0 overlap cap is exceeded. Reading the
52        // count is O(runs) and cheaper than a TTL scan, so it can run on every
53        // `should_compact` poll without bookkeeping.
54        if self.l0_run_count() >= Self::MAX_L0_OVERLAPPING_RUNS {
55            return true;
56        }
57        self.ttl().is_some()
58            && !self.run_refs().is_empty()
59            && self.has_expired_run_rows().unwrap_or(false)
60    }
61
62    /// Number of run-refs currently at L0 (mutable-run spill tier).
63    pub fn l0_run_count(&self) -> usize {
64        self.run_refs().iter().filter(|rr| rr.level == 0).count()
65    }
66
67    /// `true` when `candidate` (min_row_id, max_row_id) overlaps any L1+ run
68    /// still alive after `retire` is removed. L1+ runs must stay disjoint so
69    /// the read path can binary-search the level and only open the single
70    /// covering run. `retire` is the set of run-ids this compaction is about
71    /// to supersede — the freshly merged L1 will replace them, so a
72    /// self-overlap against them is expected and ignored.
73    fn l1_range_overlaps(
74        &self,
75        min_row_id: u64,
76        max_row_id: u64,
77        retire: &std::collections::HashSet<u128>,
78    ) -> bool {
79        if min_row_id > max_row_id {
80            return false;
81        }
82        for rr in self.run_refs() {
83            if rr.level < 1 || retire.contains(&rr.run_id) {
84                continue;
85            }
86            if let Some((lo, hi)) = self.run_row_id_range(rr.run_id) {
87                // Two closed intervals [a, b] and [c, d] overlap iff a <= d
88                // and c <= b. Empty existing ranges (row_count == 0) trivially
89                // do not overlap.
90                if rr.row_count == 0 {
91                    continue;
92                }
93                if min_row_id <= hi && lo <= max_row_id {
94                    return true;
95                }
96            }
97        }
98        false
99    }
100
101    fn has_expired_run_rows(&self) -> Result<bool> {
102        self.has_expired_run_rows_inner(None)
103    }
104
105    fn has_expired_run_rows_inner(&self, control: Option<&ExecutionControl>) -> Result<bool> {
106        let now_nanos = crate::engine::unix_nanos_now();
107        for (run_index, run) in self.run_refs().iter().enumerate() {
108            if run_index % 256 == 0 {
109                if let Some(control) = control {
110                    control.checkpoint()?;
111                }
112            }
113            let mut reader = self.open_reader(run.run_id)?;
114            for (row_index, row) in reader.all_rows()?.iter().enumerate() {
115                if row_index % 256 == 0 {
116                    if let Some(control) = control {
117                        control.checkpoint()?;
118                    }
119                }
120                if self.row_expired_at(row, now_nanos) {
121                    return Ok(true);
122                }
123            }
124        }
125        Ok(false)
126    }
127
128    /// Compaction as a query optimization (§5.9): if [`should_compact`] reports
129    /// that runs have accumulated past the cost threshold, run [`compact`] and
130    /// return `true`; otherwise no-op and return `false`. Safe to call
131    /// periodically from a background task — [`compact`] is itself a no-op below
132    /// two runs and honors snapshot retention. Returns whether a compaction ran.
133    pub fn maybe_compact(&mut self) -> Result<bool> {
134        if !self.should_compact() {
135            return Ok(false);
136        }
137        self.compact()?;
138        Ok(true)
139    }
140
141    /// Merge all runs into a single level-1 run, dropping superseded versions
142    /// and tombstones — **but preserving** the version each pinned snapshot
143    /// still needs. No-op if there are fewer than two runs, unless a one-run
144    /// TTL table has expired payloads to reclaim.
145    pub fn compact(&mut self) -> Result<()> {
146        let control = ExecutionControl::new(None);
147        self.compact_controlled(&control, || true).map(|_| ())
148    }
149
150    /// Build replacement output cooperatively. Live state is unchanged until
151    /// `before_publish` succeeds. No cancellation checkpoint runs after that
152    /// manifest-publication boundary.
153    #[doc(hidden)]
154    pub fn compact_controlled<F>(
155        &mut self,
156        control: &ExecutionControl,
157        before_publish: F,
158    ) -> Result<bool>
159    where
160        F: FnOnce() -> bool,
161    {
162        self.compact_controlled_with_receipt(control, before_publish)
163            .map(|(changed, _)| changed)
164    }
165
166    /// Build replacement output cooperatively and return the exact table
167    /// snapshot used by the compaction. No receipt is returned for a no-op.
168    #[doc(hidden)]
169    pub fn compact_controlled_with_receipt<F>(
170        &mut self,
171        control: &ExecutionControl,
172        before_publish: F,
173    ) -> Result<(bool, Option<MaintenanceReceipt>)>
174    where
175        F: FnOnce() -> bool,
176    {
177        control.checkpoint()?;
178        let maintenance_epoch = self.current_epoch();
179        // The merge below makes every mutable-run row durable in the
180        // replacement run, and publishing advances the WAL replay gate
181        // (`flushed_epoch`) to `maintenance_epoch` so replay does not
182        // re-apply (and double-index) those rows. The gate is a single epoch,
183        // so both steps are only safe once every committed row is inside the
184        // merge input. When no mutations are pending, every memtable row is
185        // committed: drain them into the mutable run so the input is complete
186        // (a committed row's stamp never exceeds the visible watermark).
187        // When mutations ARE pending, committed and uncommitted rows may
188        // interleave in the memtable — on a mounted table the shared epoch
189        // authority can advance past a pending row's stamp — so the merge
190        // must exclude both in-memory tiers and the gate must stay put:
191        // nothing beyond it may become run-resident.
192        let pending_uncommitted = self.has_pending_mutations();
193        if !pending_uncommitted {
194            self.drain_committed_memtable_rows(maintenance_epoch);
195        }
196        let reclaim_ttl = self.ttl().is_some() && self.has_expired_run_rows_inner(Some(control))?;
197        if self.run_refs().len() < 2 && !reclaim_ttl {
198            return Ok((false, None));
199        }
200        let min_active = self.min_active_snapshot();
201        let old_refs: Vec<RunRef> = self.run_refs().to_vec();
202        let now_nanos = crate::engine::unix_nanos_now();
203        let mutable_rows = if !pending_uncommitted && self.mutable_run_len() > 0 {
204            self.snapshot_mutable_run()
205        } else {
206            Vec::new()
207        };
208
209        let mut all: HashMap<u64, Vec<Row>> = HashMap::new();
210        let mut scanned = 0_usize;
211        for rr in &old_refs {
212            control.checkpoint()?;
213            let mut reader = self.open_reader(rr.run_id)?;
214            for row in reader.all_rows()? {
215                if scanned.is_multiple_of(256) {
216                    control.checkpoint()?;
217                }
218                scanned += 1;
219                all.entry(row.row_id.0).or_default().push(row);
220            }
221        }
222        for row in mutable_rows {
223            if scanned.is_multiple_of(256) {
224                control.checkpoint()?;
225            }
226            scanned += 1;
227            all.entry(row.row_id.0).or_default().push(row);
228        }
229
230        let mut rows = Vec::new();
231        let mut current_live_count = 0u64;
232        for (row_index, (_, mut versions)) in all.into_iter().enumerate() {
233            if row_index % 256 == 0 {
234                control.checkpoint()?;
235            }
236            // Epoch-ascending for the floor partition in select_keep (physical
237            // reclamation is still epoch-gated). Newest-live selection uses HLC
238            // via version_is_newer when stamps are present (P0.5-T3).
239            versions.sort_by_key(|row| row.committed_epoch);
240            let Some(newest) = versions
241                .iter()
242                .max_by(|a, b| cmp_version_order(a, b))
243                .cloned()
244            else {
245                continue;
246            };
247            let newest_epoch = newest.committed_epoch;
248            if !newest.deleted && !self.row_expired_at(&newest, now_nanos) {
249                current_live_count += 1;
250            }
251            for row in select_keep(&versions, min_active) {
252                if self.row_expired_at(&row, now_nanos) {
253                    if is_same_version(&row, &newest)
254                        && min_active.is_some_and(|epoch| newest_epoch > epoch)
255                    {
256                        let mut tombstone = row;
257                        tombstone.deleted = true;
258                        tombstone.columns.clear();
259                        rows.push(tombstone);
260                    }
261                } else {
262                    rows.push(row);
263                }
264            }
265        }
266        rows.sort_by_key(|row| (row.row_id, row.committed_epoch));
267
268        let mut staged_run = None;
269        if !rows.is_empty() {
270            // L1+ disjointness gate (TODO §1.2): the merged run is destined
271            // for L1, and L1+ runs must cover disjoint row-id ranges so the
272            // read path can binary-search the level. Runs being retired by
273            // this compaction (every L0 plus any L1 being replaced) are
274            // excluded from the check — the new L1 will atomically swap
275            // them out on publish. A self-overlap against a run we own is
276            // expected; a collision with a run we DON'T own means a prior
277            // compaction is still settling, so refuse and let the caller
278            // retry once the topology has calmed.
279            let retire: std::collections::HashSet<u128> =
280                old_refs.iter().map(|rr| rr.run_id).collect();
281            let new_min = rows.first().map(|r| r.row_id.0).unwrap_or(0);
282            let new_max = rows.last().map(|r| r.row_id.0).unwrap_or(0);
283            if self.l1_range_overlaps(new_min, new_max, &retire) {
284                return Err(MongrelError::InvalidArgument(format!(
285                    "compaction would publish an L1 run overlapping an existing L1+ \
286                     range [{new_min}, {new_max}]; wait for prior compactions to retire"
287                )));
288            }
289
290            let run_id = self.alloc_run_id()?;
291            let final_name = format!("r-{run_id}.sr");
292            let stage_name = format!(
293                "{final_name}.compact-stage-{}-{}",
294                std::process::id(),
295                std::time::SystemTime::now()
296                    .duration_since(std::time::UNIX_EPOCH)
297                    .unwrap_or_default()
298                    .as_nanos()
299            );
300            let kek = self.kek();
301            let mut writer = RunWriter::new(self.schema(), run_id as u128, maintenance_epoch, 1)
302                .clean(min_active.is_none())
303                .with_zstd_level(self.compaction_zstd_level());
304            if let Some(k) = &kek {
305                writer = writer.with_encryption(k.as_ref(), self.indexable_column_specs());
306            }
307            let header = match self.create_run_entry(Path::new(&stage_name))? {
308                Some(file) => writer.write_file(file, &rows),
309                None => writer.write(self.runs_dir().join(&stage_name), &rows),
310            };
311            let header = match header {
312                Ok(header) => header,
313                Err(error) => {
314                    let _ = self.remove_run_entry(Path::new(&stage_name));
315                    return Err(error);
316                }
317            };
318            staged_run = Some((
319                stage_name,
320                final_name,
321                RunRef {
322                    run_id: run_id as u128,
323                    level: 1,
324                    epoch_created: header.epoch_created,
325                    row_count: header.row_count,
326                },
327            ));
328        }
329
330        if let Err(error) = control.checkpoint() {
331            if let Some((stage_name, _, _)) = staged_run {
332                let _ = self.remove_run_entry(Path::new(&stage_name));
333            }
334            return Err(error);
335        }
336        if !before_publish() {
337            if let Some((stage_name, _, _)) = staged_run {
338                let _ = self.remove_run_entry(Path::new(&stage_name));
339            }
340            return Err(MongrelError::Cancelled);
341        }
342
343        // Publish the staged file before changing any live topology. A failed
344        // rename or directory sync can leave only an unreferenced run file;
345        // the old manifest, mutable run, and in-memory refs remain intact.
346        let replacement_ref = if let Some((stage_name, final_name, staged_ref)) = staged_run {
347            self.publish_run_entry(Path::new(&stage_name), Path::new(&final_name))?;
348            Some(staged_ref)
349        } else {
350            None
351        };
352
353        if !pending_uncommitted && self.mutable_run_len() > 0 {
354            self.drain_mutable_run();
355        }
356        self.live_count = current_live_count;
357        let retire_epoch = maintenance_epoch.0;
358        if let Some(replacement_ref) = replacement_ref {
359            self.set_run_refs(vec![replacement_ref]);
360            for run in &old_refs {
361                self.retire_run(run.run_id, retire_epoch);
362            }
363        } else {
364            self.set_run_refs(Vec::new());
365            for run in &old_refs {
366                self.retire_run(run.run_id, retire_epoch);
367            }
368        }
369
370        // The new manifest must explicitly reject the old global-index
371        // checkpoint.  Compaction does not advance the data epoch, so leaving
372        // the old epoch stamped here could make reopen accept indexes for the
373        // superseded runs.
374        self.prepare_indexes_for_run_replacement();
375        // The replacement run now carries every committed row at or below
376        // `maintenance_epoch` (the merge input above covers all runs, the
377        // drained mutable run, and the committed memtable rows drained at the
378        // start) — but only when no mutations were pending; otherwise the
379        // in-memory tiers stayed out of the merge and the gate must not move.
380        // Advance the WAL replay gate past the merged content — before the
381        // manifest makes the new topology durable — so reopen does not
382        // re-apply and double-index rows that are already run-resident.
383        // Read-only replicas never replay a WAL, so there is no gate to move.
384        if let Err(error) = (|| {
385            if !pending_uncommitted && !self.wal_is_read_only() {
386                self.mark_flushed(maintenance_epoch)?;
387            }
388            self.persist_manifest(maintenance_epoch)
389        })() {
390            self.poison_after_maintenance_publish_failure();
391            return Err(MongrelError::CommitOutcomeUnknown {
392                epoch: maintenance_epoch.0,
393                message: format!("compaction manifest publication failed: {error}"),
394            });
395        }
396        self.clear_result_cache();
397        self.bump_data_generation();
398
399        // The replacement topology is durable.  Index rebuild failures do not
400        // make row data uncertain: keep the indexes marked incomplete so the
401        // next indexed operation or reopen rebuilds them from the new runs.
402        if let Err(error) = self
403            .rebuild_indexes_from_runs()
404            .and_then(|_| self.build_learned_ranges())
405        {
406            return Err(MongrelError::DurableCommit {
407                epoch: maintenance_epoch.0,
408                message: format!("compaction committed but index rebuild failed: {error}"),
409            });
410        }
411        self.finish_indexes_for_run_replacement();
412        self.checkpoint_indexes(maintenance_epoch);
413        // Issue 4 / spec §8.4 step 5: republish the run-lookup directory so
414        // the next open fast-paths point lookups against the post-compaction
415        // run set. A directory publish failure is logged but does not poison
416        // the compaction — the manifest is already durable, and the next
417        // flush will rebuild the directory lazily.
418        let _ = mongreldb_fault::inject("compaction.replacement_publication");
419        if let Err(error) = self.publish_run_lookup_directory() {
420            // Mark the directory incomplete so the read path falls back to
421            // range scans until a future publish succeeds.
422            self.lookup_metrics
423                .directory_incomplete
424                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
425            self.lookup_metrics
426                .directory_lookup_fallback
427                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
428            // Best-effort log via the trace shape; tests that arm the fault
429            // hook will assert the metric moved.
430            let _ = error;
431        }
432        Ok((
433            true,
434            Some(MaintenanceReceipt {
435                epoch: maintenance_epoch,
436            }),
437        ))
438    }
439}
440
441/// Compare two versions for recency: HLC when both stamped, else local epoch.
442fn cmp_version_order(a: &Row, b: &Row) -> std::cmp::Ordering {
443    if Snapshot::version_is_newer(
444        a.committed_epoch,
445        a.commit_ts,
446        b.committed_epoch,
447        b.commit_ts,
448    ) {
449        std::cmp::Ordering::Greater
450    } else if Snapshot::version_is_newer(
451        b.committed_epoch,
452        b.commit_ts,
453        a.committed_epoch,
454        a.commit_ts,
455    ) {
456        std::cmp::Ordering::Less
457    } else {
458        a.committed_epoch
459            .cmp(&b.committed_epoch)
460            .then_with(|| a.commit_ts.cmp(&b.commit_ts))
461    }
462}
463
464fn is_same_version(a: &Row, b: &Row) -> bool {
465    a.committed_epoch == b.committed_epoch && a.commit_ts == b.commit_ts
466}
467
468/// Versions to keep for one `RowId` given the oldest queryable snapshot. Every
469/// transition at or after the floor is retained, plus the boundary version
470/// visible at the floor. With no floor, only the current live version remains
471/// (chosen by HLC when stamps are present — P0.5-T3 / P0.5-X8).
472///
473/// `vers` must be sorted ascending by `committed_epoch` (the floor partition
474/// is still epoch-based; see module residual). HLC-only pins without epoch
475/// projection still report ZERO on [`crate::epoch::GcFloor`] and do not lower
476/// this floor.
477fn select_keep(vers: &[Row], min_active: Option<Epoch>) -> Vec<Row> {
478    let Some(newest) = vers.iter().max_by(|a, b| cmp_version_order(a, b)).cloned() else {
479        return Vec::new();
480    };
481    match min_active {
482        None => {
483            if newest.deleted {
484                Vec::new()
485            } else {
486                vec![newest]
487            }
488        }
489        Some(min_e) => {
490            let recent_start = vers.partition_point(|row| row.committed_epoch < min_e);
491            let mut keep = vers[recent_start..].to_vec();
492            if recent_start > 0 && keep.first().is_none_or(|row| row.committed_epoch > min_e) {
493                let boundary = vers[recent_start - 1].clone();
494                if keep.is_empty() && boundary.deleted {
495                    return Vec::new();
496                }
497                keep.insert(0, boundary);
498            }
499            // Rid-reuse guard: when a rid is tombstoned and then re-allocated to
500            // a new pk at the same committed_epoch, both versions sit at that
501            // epoch with no way for the sort key to break the tie. If the
502            // version chosen as the "boundary" above is a live row while a
503            // tombstone sits at the same epoch, the live row would survive into
504            // the new run even though the tombstone was the last write to the
505            // old pk. Drop the whole rid so the live row cannot leak into a
506            // range/hit set — pinned snapshots still see the tombstone as
507            // `deleted=true` (the run reader's MVCC pass would too, but only
508            // for the older "deleted" column; a rid reuse leaves the same
509            // physical rid serving a different row, which `visible_rows` and
510            // range scans must reject).
511            if keep.len() == 1
512                && !keep[0].deleted
513                && vers
514                    .iter()
515                    .any(|r| r.deleted && r.committed_epoch == keep[0].committed_epoch)
516            {
517                return Vec::new();
518            }
519            keep
520        }
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use crate::schema::{ColumnDef, ColumnFlags, Schema, TypeId};
528    use crate::{Database, Snapshot, Value};
529    use tempfile::tempdir;
530
531    fn schema() -> Schema {
532        Schema {
533            schema_id: 1,
534            columns: vec![ColumnDef {
535                id: 1,
536                name: "v".into(),
537                ty: TypeId::Int64,
538                flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
539                default_value: None,
540                embedding_source: None,
541            }],
542            indexes: Vec::new(),
543            colocation: vec![],
544            constraints: Default::default(),
545            clustered: false,
546        }
547    }
548
549    #[test]
550    fn compaction_merges_runs_and_gcs_tombstoned_row() {
551        let dir = tempdir().unwrap();
552        let mut db = Table::create(dir.path(), schema(), 1).unwrap();
553        // Spill every flush to a run (this test exercises run-level merging).
554        db.set_mutable_run_spill_bytes(1);
555        let mut ids = Vec::new();
556        for i in 1..=5i64 {
557            ids.push(db.put(vec![(1, Value::Int64(i))]).unwrap());
558        }
559        db.flush().unwrap();
560        db.delete(ids[2]).unwrap();
561        db.flush().unwrap();
562        db.put(vec![(1, Value::Int64(60))]).unwrap();
563        db.flush().unwrap();
564        assert_eq!(db.run_count(), 3);
565
566        db.compact().unwrap();
567        assert_eq!(db.run_count(), 1);
568        let rows = db.visible_rows(db.snapshot()).unwrap();
569        let row_ids: Vec<u64> = rows.iter().map(|r| r.row_id.0).collect();
570        assert!(!row_ids.contains(&ids[2].0), "tombstoned row must be GC'd");
571        assert_eq!(rows.len(), 5);
572    }
573
574    #[test]
575    fn pinned_snapshot_survives_compaction() {
576        let dir = tempdir().unwrap();
577        let mut db = Table::create(dir.path(), schema(), 1).unwrap();
578        let r = db.put(vec![(1, Value::Int64(1))]).unwrap();
579        db.flush().unwrap(); // run 1: live version of r
580
581        // Pin a snapshot that sees the live version.
582        let pinned = db.pin_snapshot();
583        assert_eq!(
584            db.get(r, pinned)
585                .and_then(|row| row.columns.get(&1).cloned()),
586            Some(Value::Int64(1))
587        );
588
589        // Delete r, flush a second run, then compact with the pin still active.
590        db.delete(r).unwrap();
591        db.commit().unwrap();
592        db.flush().unwrap(); // run 2: tombstone for r
593        db.compact().unwrap(); // merges run1 + run2
594
595        // Pinned snapshot must still see the live version (retention kept it).
596        assert_eq!(
597            db.get(r, pinned)
598                .and_then(|row| row.columns.get(&1).cloned()),
599            Some(Value::Int64(1))
600        );
601        // Current snapshot sees the tombstone → row is gone.
602        assert_eq!(
603            db.get(r, db.snapshot())
604                .and_then(|row| row.columns.get(&1).cloned()),
605            None
606        );
607
608        // Release the pin; the next compaction may GC the live version.
609        db.unpin_snapshot(pinned);
610        db.compact().unwrap();
611        assert_eq!(
612            db.get(r, db.snapshot())
613                .and_then(|row| row.columns.get(&1).cloned()),
614            None
615        );
616    }
617
618    /// Schema with a Sparse secondary index on a bincode-packed
619    /// `Vec<(u32, f32)>` Bytes column (the engine's sparse wire format).
620    fn sparse_schema() -> Schema {
621        Schema {
622            schema_id: 1,
623            columns: vec![
624                ColumnDef {
625                    id: 1,
626                    name: "v".into(),
627                    ty: TypeId::Int64,
628                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
629                    default_value: None,
630                    embedding_source: None,
631                },
632                ColumnDef {
633                    id: 2,
634                    name: "terms".into(),
635                    ty: TypeId::Bytes,
636                    flags: ColumnFlags::empty(),
637                    default_value: None,
638                    embedding_source: None,
639                },
640            ],
641            indexes: vec![crate::schema::IndexDef {
642                name: "terms_sparse".into(),
643                column_id: 2,
644                kind: crate::schema::IndexKind::Sparse,
645                predicate: None,
646                options: Default::default(),
647            }],
648            colocation: vec![],
649            constraints: Default::default(),
650            clustered: false,
651        }
652    }
653
654    #[test]
655    fn compaction_advances_wal_gate_over_merged_mutable_run_content() {
656        // Regression: compaction makes mutable-run content durable in the
657        // replacement run; without advancing the WAL replay gate
658        // (`flushed_epoch`) to match, the next open replayed those commits and
659        // re-indexed rows that were already run-resident — Sparse dot-product
660        // scores double-counted (2×) after close+reopen.
661        let dir = tempdir().unwrap();
662        let mut db = Table::create(dir.path(), sparse_schema(), 1).unwrap();
663        let pack = |terms: &[(u32, f32)]| Value::Bytes(bincode::serialize(terms).unwrap());
664        // Two spilled runs so compaction really merges.
665        db.set_mutable_run_spill_bytes(1);
666        db.put(vec![(1, Value::Int64(1)), (2, pack(&[(1, 1.0)]))])
667            .unwrap();
668        db.commit().unwrap();
669        db.flush().unwrap();
670        db.put(vec![(1, Value::Int64(2)), (2, pack(&[(1, 0.5)]))])
671            .unwrap();
672        db.commit().unwrap();
673        db.flush().unwrap();
674        assert_eq!(db.run_count(), 2);
675
676        // A third committed row that never reaches a sorted run before the
677        // compaction: with the watermark raised, `flush` only drains the
678        // memtable into the in-memory mutable run.
679        db.set_mutable_run_spill_bytes(u64::MAX);
680        let rid_c = db
681            .put(vec![(1, Value::Int64(3)), (2, pack(&[(1, 2.0)]))])
682            .unwrap();
683        db.commit().unwrap();
684        db.flush().unwrap();
685        assert_eq!(db.run_count(), 2, "no spill past the raised watermark");
686
687        // The merge carries rid_c; the WAL gate must cover it afterwards.
688        db.compact().unwrap();
689        assert_eq!(db.run_count(), 1);
690        db.close().unwrap(); // memtable and mutable run are empty: no flush
691        let mut db = Table::open(dir.path()).unwrap();
692
693        let hits = db
694            .retrieve_at(
695                &crate::query::Retriever::Sparse {
696                    column_id: 2,
697                    query: vec![(1u32, 1.0)],
698                    k: 10,
699                },
700                db.snapshot(),
701                None,
702            )
703            .unwrap();
704        let by_rid: std::collections::HashMap<u64, f64> = hits
705            .into_iter()
706            .map(|h| match h.score {
707                crate::query::RetrieverScore::SparseDotProduct(d) => (h.row_id.0, d),
708                _ => (h.row_id.0, f64::NAN),
709            })
710            .collect();
711        assert_eq!(by_rid.len(), 3, "each row indexed exactly once: {by_rid:?}");
712        assert_eq!(by_rid[&rid_c.0], 2.0, "replayed rid would score 4.0");
713    }
714
715    #[test]
716    fn controlled_compaction_cancel_before_publish_preserves_live_state() {
717        let dir = tempdir().unwrap();
718        let mut table = Table::create(dir.path(), schema(), 1).unwrap();
719        table.set_mutable_run_spill_bytes(1);
720        table.put(vec![(1, Value::Int64(1))]).unwrap();
721        table.flush().unwrap();
722        table.put(vec![(1, Value::Int64(2))]).unwrap();
723        table.flush().unwrap();
724        let before_refs: Vec<_> = table
725            .run_refs()
726            .iter()
727            .map(|run| (run.run_id, run.level, run.epoch_created, run.row_count))
728            .collect();
729
730        let error = table
731            .compact_controlled(&ExecutionControl::new(None), || false)
732            .unwrap_err();
733        assert!(matches!(error, MongrelError::Cancelled));
734        let after_refs: Vec<_> = table
735            .run_refs()
736            .iter()
737            .map(|run| (run.run_id, run.level, run.epoch_created, run.row_count))
738            .collect();
739        assert_eq!(after_refs, before_refs);
740        assert_eq!(table.visible_rows(table.snapshot()).unwrap().len(), 2);
741        assert!(std::fs::read_dir(table.runs_dir())
742            .unwrap()
743            .all(|entry| !entry
744                .unwrap()
745                .file_name()
746                .to_string_lossy()
747                .contains("compact-stage")));
748    }
749
750    #[test]
751    fn compaction_manifest_failure_poisons_standalone_table_until_reopen() {
752        let dir = tempdir().unwrap();
753        let mut table = Table::create(dir.path(), schema(), 1).unwrap();
754        table.set_mutable_run_spill_bytes(1);
755        table.put(vec![(1, Value::Int64(1))]).unwrap();
756        table.flush().unwrap();
757        table.put(vec![(1, Value::Int64(2))]).unwrap();
758        table.flush().unwrap();
759        let manifest = dir.path().join(crate::manifest::MANIFEST_FILENAME);
760        let saved_manifest = dir.path().join("_mf.saved");
761        std::fs::rename(&manifest, &saved_manifest).unwrap();
762        std::fs::create_dir(&manifest).unwrap();
763
764        let error = table.compact().unwrap_err();
765        assert!(matches!(error, MongrelError::CommitOutcomeUnknown { .. }));
766        assert_eq!(table.visible_rows(table.snapshot()).unwrap().len(), 2);
767        assert!(table
768            .put(vec![(1, Value::Int64(3))])
769            .unwrap_err()
770            .to_string()
771            .contains("reopen required"));
772
773        drop(table);
774        std::fs::remove_dir(&manifest).unwrap();
775        std::fs::rename(saved_manifest, manifest).unwrap();
776        let reopened = Table::open(dir.path()).unwrap();
777        assert_eq!(reopened.visible_rows(reopened.snapshot()).unwrap().len(), 2);
778    }
779
780    #[test]
781    fn compaction_manifest_failure_poisons_mounted_database() {
782        let dir = tempdir().unwrap();
783        let db = Database::create(dir.path()).unwrap();
784        let table_id = db.create_table("items", schema()).unwrap();
785        let handle = db.table("items").unwrap();
786        {
787            let mut table = handle.lock();
788            table.set_mutable_run_spill_bytes(1);
789            table.put(vec![(1, Value::Int64(1))]).unwrap();
790            table.flush().unwrap();
791            table.put(vec![(1, Value::Int64(2))]).unwrap();
792            table.flush().unwrap();
793        }
794        let manifest = dir
795            .path()
796            .join("tables")
797            .join(table_id.to_string())
798            .join(crate::manifest::MANIFEST_FILENAME);
799        let saved_manifest = manifest.with_extension("saved");
800        std::fs::rename(&manifest, &saved_manifest).unwrap();
801        std::fs::create_dir(&manifest).unwrap();
802
803        let error = handle.lock().compact().unwrap_err();
804        assert!(matches!(error, MongrelError::CommitOutcomeUnknown { .. }));
805        assert!(db
806            .create_table("blocked", schema())
807            .unwrap_err()
808            .to_string()
809            .contains("database poisoned"));
810    }
811
812    #[test]
813    fn _snapshot_import_used() {
814        let _ = Snapshot::at(Epoch(0));
815    }
816
817    fn hlc(physical_micros: u64) -> mongreldb_types::hlc::HlcTimestamp {
818        mongreldb_types::hlc::HlcTimestamp {
819            physical_micros,
820            logical: 0,
821            node_tiebreaker: 1,
822        }
823    }
824
825    fn stamped(id: u64, epoch: u64, ts: mongreldb_types::hlc::HlcTimestamp, v: i64) -> Row {
826        crate::memtable::Row::new_with_hlc(crate::rowid::RowId(id), Epoch(epoch), ts)
827            .with_column(1, Value::Int64(v))
828    }
829
830    /// P0.5-X8 (HLC): when versions carry commit_ts, select_keep retains the
831    /// HLC-newest live version under no pin — even if that version has a lower
832    /// local epoch than an older-HLC rewrite.
833    #[test]
834    fn select_keep_preserves_hlc_visibility_under_inverted_epoch_order() {
835        let early = hlc(100);
836        let mid = hlc(150);
837        let late = hlc(200);
838        // Must be epoch-ascending for the floor partition.
839        let mut versions = vec![
840            stamped(1, 1, late, 99),  // high HLC, low epoch
841            stamped(1, 2, mid, 50),   // mid HLC
842            stamped(1, 50, early, 1), // low HLC, high epoch
843        ];
844        versions.sort_by_key(|row| row.committed_epoch);
845        // No pin: only the HLC-newest live version remains (late, epoch 1).
846        let kept = select_keep(&versions, None);
847        assert_eq!(kept.len(), 1);
848        assert_eq!(kept[0].commit_ts, Some(late));
849        assert_eq!(kept[0].committed_epoch, Epoch(1));
850        assert_eq!(kept[0].columns.get(&1), Some(&Value::Int64(99)));
851
852        // Epoch floor at 2: retain epoch >= 2. Physical floor is still
853        // epoch-gated (P0.5-T6 residual); HLC-newest at epoch 1 is not kept
854        // when a version exists exactly at the floor.
855        let kept = select_keep(&versions, Some(Epoch(2)));
856        assert!(kept.iter().any(|r| r.commit_ts == Some(mid)));
857        assert!(kept.iter().any(|r| r.commit_ts == Some(early)));
858        assert!(!kept.iter().any(|r| r.commit_ts == Some(late)));
859
860        // Floor between versions (epoch 10): recent starts at epoch 50, so the
861        // boundary version just below the floor (epoch 2, mid) is retained.
862        let kept = select_keep(&versions, Some(Epoch(10)));
863        assert!(kept.iter().any(|r| r.commit_ts == Some(early)));
864        assert!(
865            kept.iter().any(|r| r.commit_ts == Some(mid)),
866            "boundary version below floor must be retained"
867        );
868        assert!(!kept.iter().any(|r| r.commit_ts == Some(late)));
869    }
870
871    #[test]
872    fn cmp_version_order_prefers_hlc_when_both_stamped() {
873        let early = stamped(1, 99, hlc(100), 1);
874        let late = stamped(1, 1, hlc(200), 2);
875        assert_eq!(cmp_version_order(&early, &late), std::cmp::Ordering::Less);
876        assert_eq!(
877            cmp_version_order(&late, &early),
878            std::cmp::Ordering::Greater
879        );
880        // Unstamped falls back to epoch.
881        let a = crate::memtable::Row::new(crate::rowid::RowId(1), Epoch(1));
882        let b = crate::memtable::Row::new(crate::rowid::RowId(1), Epoch(3));
883        assert_eq!(cmp_version_order(&a, &b), std::cmp::Ordering::Less);
884    }
885}