Skip to main content

mongreldb_core/
engine.rs

1//! The engine tying the write and read paths together.
2//!
3//! Sub-ms writes: [`Table::put`] appends to the WAL **without fsyncing**, upserts
4//! the Bε-tree memtable, and updates the in-memory HOT index + secondary
5//! indexes. A batch-driven [`Table::commit`] does the group `fsync` and bumps the
6//! epoch. [`Table::flush`] commits, drains the memtable into an immutable sorted
7//! run, and rotates the WAL. Reads merge versions across the live memtable and
8//! all sorted runs ([`Table::get`], [`Table::visible_rows`]).
9
10use crate::columnar;
11use crate::cursor::NativePageCursor;
12use crate::encryption::Kek;
13use crate::encryption::DEK_LEN;
14use crate::epoch::{Epoch, EpochAuthority, EpochGuard, MaintenanceReceipt, Snapshot, VersionStamp};
15use crate::global_idx;
16use crate::index::{
17    AnnIndex, BitmapIndex, ColumnLearnedRange, FmIndex, HotIndex, IndexGeneration, MinHashIndex,
18    SparseIndex,
19};
20use crate::manifest::{self, Manifest, RunRef, TtlPolicy};
21use crate::memtable::{Memtable, MemtableVisibleVersionCursor, Row, Value};
22use crate::mutable_run::{MutableRun, MutableRunVisibleVersionCursor};
23use crate::result_cache::{
24    DrainOutcome, PersistContext, PersistenceDisabledReason, PersistentCacheIdentity,
25    PersistentPublicationState, FRAME_MAGIC,
26};
27use crate::row_id_set::RowIdSet;
28use crate::rowid::{RowId, RowIdAllocator};
29use crate::schema::{AlterColumn, ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
30use crate::sorted_run::{RunReader, RunVisibleVersion, RunVisibleVersionCursor, RunWriter};
31use crate::txn::{GroupCommit, OwnedRow};
32use crate::wal::{Op, SharedWal, Wal};
33use crate::{MongrelError, Result};
34use arc_swap::ArcSwap;
35use mongreldb_types::hlc::HlcTimestamp;
36use std::borrow::Cow;
37use std::cmp::Reverse;
38use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
39use std::path::{Path, PathBuf};
40use std::sync::atomic::AtomicBool;
41use std::sync::Arc;
42use std::time::Instant;
43use zeroize::Zeroizing;
44
45pub const WAL_DIR: &str = "_wal";
46pub const RUNS_DIR: &str = "_runs";
47pub const CACHE_DIR: &str = "_cache";
48pub const META_DIR: &str = "_meta";
49pub const RCACHE_DIR: &str = "_rcache";
50pub const KEYS_FILENAME: &str = "keys";
51pub const SCHEMA_FILENAME: &str = "schema.json";
52
53fn derive_next_run_id(
54    dir: &Path,
55    runs_root: Option<&crate::durable_file::DurableRoot>,
56    active: &[RunRef],
57    retiring: &[crate::manifest::RetiredRun],
58) -> Result<u64> {
59    let mut maximum = 0_u64;
60    for run_id in active
61        .iter()
62        .map(|run| run.run_id)
63        .chain(retiring.iter().map(|run| run.run_id))
64    {
65        let run_id = u64::try_from(run_id)
66            .map_err(|_| MongrelError::Full("run-id namespace exhausted".into()))?;
67        maximum = maximum.max(run_id);
68    }
69    let names = match runs_root {
70        Some(root) => root.list_regular_files(".")?,
71        None => std::fs::read_dir(dir.join(RUNS_DIR))?
72            .map(|entry| entry.map(|entry| entry.file_name()))
73            .collect::<std::io::Result<Vec<_>>>()?,
74    };
75    for name in names {
76        let Some(name) = name.to_str() else {
77            continue;
78        };
79        let Some(digits) = name
80            .strip_prefix("r-")
81            .and_then(|name| name.strip_suffix(".sr"))
82        else {
83            continue;
84        };
85        let Ok(run_id) = digits.parse::<u64>() else {
86            continue;
87        };
88        if name == format!("r-{run_id}.sr") {
89            maximum = maximum.max(run_id);
90        }
91    }
92    maximum
93        .checked_add(1)
94        .map(|next| next.max(1))
95        .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))
96}
97
98enum ControlledVisibleCandidate<'a> {
99    Memory(Row),
100    /// Newest-visible overlay row borrowed from the streaming memtable cursor.
101    /// The cursor yields `Cow<'a, Row>` (borrowed for leaf and buffered-upsert
102    /// rows, owned for buffer tombstones that have to be synthesized on the
103    /// fly); this carries the lifetime parameter so the borrowing variant
104    /// stays zero-copy.
105    Memtable(RowId, Epoch, Cow<'a, Row>),
106    /// Newest-visible overlay row borrowed from the streaming mutable-run cursor.
107    MutableRun(RowId, Epoch, &'a Row),
108    Run(RunVisibleVersion),
109}
110
111impl<'a> ControlledVisibleCandidate<'a> {
112    fn row_id(&self) -> RowId {
113        match self {
114            Self::Memory(row) => row.row_id,
115            Self::Memtable(rid, _, _) => *rid,
116            Self::MutableRun(rid, _, _) => *rid,
117            Self::Run(version) => version.row_id,
118        }
119    }
120
121    fn committed_epoch(&self) -> Epoch {
122        match self {
123            Self::Memory(row) => row.committed_epoch,
124            Self::Memtable(_, epoch, _) => *epoch,
125            Self::MutableRun(_, epoch, _) => *epoch,
126            Self::Run(version) => version.committed_epoch,
127        }
128    }
129
130    fn deleted(&self) -> bool {
131        match self {
132            Self::Memory(row) => row.deleted,
133            Self::Memtable(_, _, row) => row.deleted,
134            Self::MutableRun(_, _, row) => row.deleted,
135            Self::Run(version) => version.deleted,
136        }
137    }
138
139    fn commit_ts(&self) -> Option<mongreldb_types::hlc::HlcTimestamp> {
140        match self {
141            Self::Memory(row) => row.commit_ts,
142            Self::Memtable(_, _, row) => row.commit_ts,
143            Self::MutableRun(_, _, row) => row.commit_ts,
144            // Run candidates carry SYS_COMMIT_TS when the cursor loaded it;
145            // legacy runs without the column leave this None (epoch fallback).
146            Self::Run(version) => version.commit_ts,
147        }
148    }
149}
150
151enum ControlledVisibleCursor<'a> {
152    /// Newest-visible overlay rows, ordered by RowId (full source already small).
153    Memory(std::vec::IntoIter<Row>),
154    /// Batch-bounded overlay drain of a `BTreeMap` of newest-per-rid rows.
155    /// Only `batch_cap` rows live in the active merge buffer at once; the
156    /// remainder stays in the ordered map iterator (no full intermediate `Vec`).
157    MemoryStreaming {
158        active: std::vec::IntoIter<Row>,
159        rest: std::collections::btree_map::IntoValues<RowId, Row>,
160        batch_cap: usize,
161        /// Peak active-buffer length observed (for structural tests).
162        #[allow(dead_code)]
163        peak_active: usize,
164        /// Total rows that will be yielded (map size at construction).
165        #[allow(dead_code)]
166        total: usize,
167    },
168    /// Streaming cursor over the memtable's newest-visible versions. Yields
169    /// `(RowId, Epoch, &Row)` triples borrowing from the underlying memtable
170    /// storage — no per-row clone and no full materialisation.
171    Memtable(MemtableVisibleVersionCursor<'a>),
172    /// Streaming cursor over the mutable run's newest-visible versions.
173    MutableRun(MutableRunVisibleVersionCursor<'a>),
174    Run(Box<RunVisibleVersionCursor>),
175    #[cfg(test)]
176    Synthetic {
177        next: u64,
178        end: u64,
179    },
180}
181
182/// Default batch size for controlled hot-tier sources (memtable / mutable run).
183#[allow(dead_code)] // PR D follow-up: switch hot-tier path to the streaming cursor
184const CONTROLLED_HOT_BATCH: usize = 256;
185
186struct ControlledVisibleSource<'a> {
187    cursor: ControlledVisibleCursor<'a>,
188    current: Option<ControlledVisibleCandidate<'a>>,
189}
190
191impl<'a> ControlledVisibleSource<'a> {
192    /// Test/helper: wrap a pre-built row list (small fixtures only).
193    #[cfg(test)]
194    fn memory(rows: Vec<Row>) -> Self {
195        Self {
196            cursor: ControlledVisibleCursor::Memory(rows.into_iter()),
197            current: None,
198        }
199    }
200
201    /// Stream newest-visible hot-tier rows from an ordered map without first
202    /// collecting a full intermediate `Vec`. Only `CONTROLLED_HOT_BATCH` rows
203    /// occupy the active merge buffer at a time.
204    #[allow(dead_code)] // kept for the legacy map-based callers; new path uses the streaming cursor
205    fn memory_from_map(map: BTreeMap<RowId, Row>) -> Self {
206        let total = map.len();
207        let mut values = map.into_values();
208        if total > CONTROLLED_HOT_BATCH {
209            let active: Vec<Row> = values.by_ref().take(CONTROLLED_HOT_BATCH).collect();
210            let peak = active.len();
211            Self {
212                cursor: ControlledVisibleCursor::MemoryStreaming {
213                    active: active.into_iter(),
214                    rest: values,
215                    batch_cap: CONTROLLED_HOT_BATCH,
216                    peak_active: peak,
217                    total,
218                },
219                current: None,
220            }
221        } else {
222            let active: Vec<Row> = values.collect();
223            Self {
224                cursor: ControlledVisibleCursor::Memory(active.into_iter()),
225                current: None,
226            }
227        }
228    }
229
230    /// Wrap a streaming memtable cursor — preferred hot-tier path when the
231    /// memtable carries visible rows. Avoids the full `BTreeMap` materialisation
232    /// that the `memory_from_map` fallback performs.
233    #[allow(dead_code)] // wired in once the hot tier switches to streaming
234    fn memtable_cursor(cursor: MemtableVisibleVersionCursor<'a>) -> Self {
235        Self {
236            cursor: ControlledVisibleCursor::Memtable(cursor),
237            current: None,
238        }
239    }
240
241    /// Wrap a streaming mutable-run cursor — preferred hot-tier path when the
242    /// mutable run carries visible rows. Avoids the full `BTreeMap` clone that
243    /// the `memory_from_map` fallback performs.
244    #[allow(dead_code)] // wired in once the hot tier switches to streaming
245    fn mutable_run_cursor(cursor: MutableRunVisibleVersionCursor<'a>) -> Self {
246        Self {
247            cursor: ControlledVisibleCursor::MutableRun(cursor),
248            current: None,
249        }
250    }
251
252    fn run(cursor: RunVisibleVersionCursor) -> Self {
253        Self {
254            cursor: ControlledVisibleCursor::Run(Box::new(cursor)),
255            current: None,
256        }
257    }
258
259    #[cfg(test)]
260    fn synthetic(end: u64) -> Self {
261        Self {
262            cursor: ControlledVisibleCursor::Synthetic { next: 1, end },
263            current: None,
264        }
265    }
266
267    fn advance(&mut self, control: &crate::ExecutionControl) -> Result<()> {
268        self.current = match &mut self.cursor {
269            ControlledVisibleCursor::Memory(rows) => {
270                rows.next().map(ControlledVisibleCandidate::Memory)
271            }
272            ControlledVisibleCursor::MemoryStreaming {
273                active,
274                rest,
275                batch_cap,
276                peak_active,
277                total: _,
278            } => {
279                if let Some(row) = active.next() {
280                    Some(ControlledVisibleCandidate::Memory(row))
281                } else {
282                    control.checkpoint()?;
283                    let next_batch: Vec<Row> = rest.by_ref().take(*batch_cap).collect();
284                    if next_batch.is_empty() {
285                        None
286                    } else {
287                        *peak_active = (*peak_active).max(next_batch.len());
288                        *active = next_batch.into_iter();
289                        active.next().map(ControlledVisibleCandidate::Memory)
290                    }
291                }
292            }
293            ControlledVisibleCursor::Memtable(iter) => {
294                let prev_peak = iter.peak_examined;
295                // REM-C: the memtable cursor (and the lazy Bε-tree cursors
296                // beneath it) observe cooperative cancellation during
297                // traversal and large same-row gathers.
298                let next = iter
299                    .next_controlled(control)?
300                    .map(|(rid, epoch, row)| ControlledVisibleCandidate::Memtable(rid, epoch, row));
301                if let Some(peak) = iter.peak_examined.checked_sub(prev_peak) {
302                    crate::trace::QueryTrace::record(|t| {
303                        t.controlled_scan_peak_same_row_versions = t
304                            .controlled_scan_peak_same_row_versions
305                            .saturating_add(peak);
306                    });
307                }
308                next
309            }
310            ControlledVisibleCursor::MutableRun(iter) => {
311                let prev_peak = iter.peak_examined;
312                let next = iter.next().map(|(rid, epoch, row)| {
313                    ControlledVisibleCandidate::MutableRun(rid, epoch, row)
314                });
315                if let Some(peak) = iter.peak_examined.checked_sub(prev_peak) {
316                    crate::trace::QueryTrace::record(|t| {
317                        t.controlled_scan_peak_same_row_versions = t
318                            .controlled_scan_peak_same_row_versions
319                            .saturating_add(peak);
320                    });
321                }
322                next
323            }
324            ControlledVisibleCursor::Run(cursor) => cursor
325                .next_visible_version(control)?
326                .map(ControlledVisibleCandidate::Run),
327            #[cfg(test)]
328            ControlledVisibleCursor::Synthetic { next, end } => {
329                if *next > *end {
330                    None
331                } else {
332                    let row = Row::new(RowId(*next), Epoch(1));
333                    *next += 1;
334                    Some(ControlledVisibleCandidate::Memory(row))
335                }
336            }
337        };
338        Ok(())
339    }
340
341    fn pop(&mut self, control: &crate::ExecutionControl) -> Result<ControlledVisibleCandidate<'a>> {
342        let current = self.current.take().ok_or_else(|| {
343            MongrelError::Other("controlled visible source was not primed".into())
344        })?;
345        self.advance(control)?;
346        Ok(current)
347    }
348
349    fn materialize(
350        &mut self,
351        candidate: ControlledVisibleCandidate<'a>,
352        control: &crate::ExecutionControl,
353    ) -> Result<Row> {
354        match candidate {
355            ControlledVisibleCandidate::Memory(row) => Ok(row),
356            ControlledVisibleCandidate::Memtable(_, _, row) => Ok(row.into_owned()),
357            ControlledVisibleCandidate::MutableRun(_, _, row) => Ok(row.clone()),
358            ControlledVisibleCandidate::Run(version) => match &mut self.cursor {
359                ControlledVisibleCursor::Run(cursor) => cursor.materialize(version, control),
360                _ => Err(MongrelError::Other(
361                    "run candidate escaped its controlled cursor".into(),
362                )),
363            },
364        }
365    }
366
367    #[cfg(test)]
368    fn is_streaming_memory(&self) -> bool {
369        matches!(self.cursor, ControlledVisibleCursor::MemoryStreaming { .. })
370    }
371
372    #[cfg(test)]
373    fn streaming_peak_active(&self) -> Option<usize> {
374        match &self.cursor {
375            ControlledVisibleCursor::MemoryStreaming { peak_active, .. } => Some(*peak_active),
376            _ => None,
377        }
378    }
379
380    #[cfg(test)]
381    fn streaming_total(&self) -> Option<usize> {
382        match &self.cursor {
383            ControlledVisibleCursor::MemoryStreaming { total, .. } => Some(*total),
384            _ => None,
385        }
386    }
387}
388
389fn merge_controlled_visible_sources<'a>(
390    sources: &mut [ControlledVisibleSource<'a>],
391    control: &crate::ExecutionControl,
392    mut expired: impl FnMut(&Row) -> bool,
393    mut visit: impl FnMut(Row) -> Result<()>,
394) -> Result<()> {
395    let mut heap = BinaryHeap::new();
396    for (source_index, source) in sources.iter_mut().enumerate() {
397        source.advance(control)?;
398        if let Some(candidate) = &source.current {
399            heap.push(Reverse((candidate.row_id(), source_index)));
400        }
401    }
402    let mut merged = 0_usize;
403    let mut peak_buffer_rows: usize = heap.len();
404    let mut peak_same_row_versions: usize = 0;
405    let mut cancel_started: Option<std::time::Instant> = None;
406    while let Some(Reverse((row_id, source_index))) = heap.pop() {
407        if merged.is_multiple_of(256) {
408            control.checkpoint()?;
409        }
410        merged += 1;
411        let mut best_source = source_index;
412        let mut best = sources[source_index].pop(control)?;
413        if let Some(next) = &sources[source_index].current {
414            heap.push(Reverse((next.row_id(), source_index)));
415        }
416        let mut same_row_versions: usize = 1;
417        while heap
418            .peek()
419            .is_some_and(|Reverse((candidate, _))| *candidate == row_id)
420        {
421            control.checkpoint()?;
422            let Some(Reverse((_, source_index))) = heap.pop() else {
423                break;
424            };
425            let candidate = sources[source_index].pop(control)?;
426            same_row_versions += 1;
427            // HLC-authoritative: when both candidates carry HLC, the higher
428            // HLC wins regardless of local epoch. Falls back to epoch when
429            // either side lacks HLC (legacy / sorted-run path).
430            if Snapshot::version_is_newer(
431                candidate.committed_epoch(),
432                candidate.commit_ts(),
433                best.committed_epoch(),
434                best.commit_ts(),
435            ) {
436                best = candidate;
437                best_source = source_index;
438            }
439            if let Some(next) = &sources[source_index].current {
440                heap.push(Reverse((next.row_id(), source_index)));
441            }
442        }
443        peak_same_row_versions = peak_same_row_versions.max(same_row_versions);
444        peak_buffer_rows = peak_buffer_rows.max(heap.len());
445        if best.deleted() {
446            continue;
447        }
448        let row = sources[best_source].materialize(best, control)?;
449        if !expired(&row) {
450            visit(row)?;
451        }
452        if cancel_started.is_none() && control.is_cancelled() {
453            cancel_started = Some(std::time::Instant::now());
454        }
455    }
456    crate::trace::QueryTrace::record(|t| {
457        t.controlled_scan_source_refills = t.controlled_scan_source_refills.saturating_add(0); // source refills are counted by each cursor's own advance()
458        t.controlled_scan_peak_source_buffer_rows = t
459            .controlled_scan_peak_source_buffer_rows
460            .saturating_add(peak_buffer_rows);
461        t.controlled_scan_peak_same_row_versions = t
462            .controlled_scan_peak_same_row_versions
463            .saturating_add(peak_same_row_versions);
464    });
465    control.checkpoint()?;
466    Ok(())
467}
468
469#[cfg(test)]
470mod controlled_visible_cursor_tests {
471    use super::*;
472
473    #[test]
474    fn streams_more_than_one_million_rows_without_a_source_cap() {
475        let control = crate::ExecutionControl::new(None);
476        let mut sources = vec![ControlledVisibleSource::synthetic(1_000_001)];
477        let mut count = 0_u64;
478        let mut last = 0_u64;
479        merge_controlled_visible_sources(
480            &mut sources,
481            &control,
482            |_| false,
483            |row| {
484                count += 1;
485                assert!(row.row_id.0 > last);
486                last = row.row_id.0;
487                Ok(())
488            },
489        )
490        .unwrap();
491        assert_eq!(count, 1_000_001);
492        assert_eq!(last, 1_000_001);
493    }
494
495    #[test]
496    fn merge_orders_rows_and_honors_newest_tombstones() {
497        let control = crate::ExecutionControl::new(None);
498        let older = vec![
499            Row::new(RowId(1), Epoch(1)),
500            Row::new(RowId(2), Epoch(1)).with_column(1, Value::Int64(20)),
501            Row::new(RowId(4), Epoch(1)),
502        ];
503        let mut deleted = Row::new(RowId(1), Epoch(2));
504        deleted.deleted = true;
505        let newer = vec![
506            deleted,
507            Row::new(RowId(2), Epoch(2)).with_column(1, Value::Int64(22)),
508            Row::new(RowId(3), Epoch(2)),
509        ];
510        let mut sources = vec![
511            ControlledVisibleSource::memory(older),
512            ControlledVisibleSource::memory(newer),
513        ];
514        let mut rows = Vec::new();
515        merge_controlled_visible_sources(
516            &mut sources,
517            &control,
518            |_| false,
519            |row| {
520                rows.push(row);
521                Ok(())
522            },
523        )
524        .unwrap();
525        assert_eq!(
526            rows.iter().map(|row| row.row_id.0).collect::<Vec<_>>(),
527            vec![2, 3, 4]
528        );
529        assert_eq!(rows[0].columns.get(&1), Some(&Value::Int64(22)));
530    }
531
532    #[test]
533    fn controlled_merge_uses_hlc_authority_when_epochs_inverted() {
534        use mongreldb_types::hlc::HlcTimestamp;
535        let hlc_old = HlcTimestamp {
536            physical_micros: 100,
537            logical: 0,
538            node_tiebreaker: 1,
539        };
540        let hlc_new = HlcTimestamp {
541            physical_micros: 200,
542            logical: 0,
543            node_tiebreaker: 1,
544        };
545        // Source A: high epoch, OLD HLC. Source B: low epoch, NEW HLC.
546        // HLC authority should pick B; legacy epoch-only pick would pick A.
547        let a =
548            vec![Row::new_with_hlc(RowId(1), Epoch(50), hlc_old).with_column(1, Value::Int64(999))];
549        let b =
550            vec![Row::new_with_hlc(RowId(1), Epoch(1), hlc_new).with_column(1, Value::Int64(11))];
551        let control = crate::ExecutionControl::new(None);
552        let mut sources = vec![
553            ControlledVisibleSource::memory(a),
554            ControlledVisibleSource::memory(b),
555        ];
556        let mut rows = Vec::new();
557        merge_controlled_visible_sources(
558            &mut sources,
559            &control,
560            |_| false,
561            |row| {
562                rows.push(row);
563                Ok(())
564            },
565        )
566        .unwrap();
567        assert_eq!(rows.len(), 1);
568        assert_eq!(rows[0].row_id.0, 1);
569        // HLC-newer (source B, value 11) must win despite Epoch(50) on source A.
570        assert_eq!(rows[0].columns.get(&1), Some(&Value::Int64(11)));
571        assert_eq!(rows[0].commit_ts, Some(hlc_new));
572    }
573
574    #[test]
575    fn controlled_merge_epoch_wins_when_one_side_lacks_hlc() {
576        use mongreldb_types::hlc::HlcTimestamp;
577        let hlc_old = HlcTimestamp {
578            physical_micros: 100,
579            logical: 0,
580            node_tiebreaker: 1,
581        };
582        // Source A: HLC-stamped, higher epoch. Source B: no HLC, lower epoch.
583        // Legacy path: epoch wins -> A is newer.
584        let a =
585            vec![Row::new_with_hlc(RowId(1), Epoch(10), hlc_old).with_column(1, Value::Int64(10))];
586        let b = vec![Row::new(RowId(1), Epoch(5)).with_column(1, Value::Int64(5))];
587        let control = crate::ExecutionControl::new(None);
588        let mut sources = vec![
589            ControlledVisibleSource::memory(a),
590            ControlledVisibleSource::memory(b),
591        ];
592        let mut rows = Vec::new();
593        merge_controlled_visible_sources(
594            &mut sources,
595            &control,
596            |_| false,
597            |row| {
598                rows.push(row);
599                Ok(())
600            },
601        )
602        .unwrap();
603        assert_eq!(rows.len(), 1);
604        assert_eq!(rows[0].columns.get(&1), Some(&Value::Int64(10)));
605    }
606
607    /// Memory (low epoch, high HLC) vs Run (high epoch, low HLC) must pick the
608    /// HLC-newer memory version when the run candidate carries SYS_COMMIT_TS.
609    #[test]
610    fn controlled_merge_memory_vs_run_uses_hlc_when_run_stamped() {
611        use crate::sorted_run::{RunReader, RunWriter};
612        use mongreldb_types::hlc::HlcTimestamp;
613        use tempfile::tempdir;
614
615        let hlc_old = HlcTimestamp {
616            physical_micros: 100,
617            logical: 0,
618            node_tiebreaker: 1,
619        };
620        let hlc_new = HlcTimestamp {
621            physical_micros: 200,
622            logical: 0,
623            node_tiebreaker: 1,
624        };
625        let schema = Schema {
626            schema_id: 1,
627            columns: vec![ColumnDef {
628                id: 1,
629                name: "v".into(),
630                ty: TypeId::Int64,
631                flags: ColumnFlags::empty(),
632                default_value: None,
633                embedding_source: None,
634            }],
635            indexes: vec![],
636            colocation: vec![],
637            constraints: Default::default(),
638            clustered: false,
639        };
640        let dir = tempdir().unwrap();
641        let path = dir.path().join("r-hlc.sr");
642        // High epoch, OLD HLC on disk.
643        let run_rows =
644            vec![Row::new_with_hlc(RowId(1), Epoch(50), hlc_old).with_column(1, Value::Int64(999))];
645        RunWriter::new(&schema, 1, Epoch(50), 0)
646            .write(&path, &run_rows)
647            .unwrap();
648        let reader = RunReader::open(&path, schema, None).unwrap();
649        assert!(reader.has_column(crate::sorted_run::SYS_COMMIT_TS));
650
651        // Low epoch, NEW HLC in memory.
652        let mem =
653            vec![Row::new_with_hlc(RowId(1), Epoch(1), hlc_new).with_column(1, Value::Int64(11))];
654        let control = crate::ExecutionControl::new(None);
655        let mut sources = vec![
656            ControlledVisibleSource::memory(mem),
657            ControlledVisibleSource::run(
658                reader.into_visible_version_cursor(Epoch(u64::MAX)).unwrap(),
659            ),
660        ];
661        let mut rows = Vec::new();
662        merge_controlled_visible_sources(
663            &mut sources,
664            &control,
665            |_| false,
666            |row| {
667                rows.push(row);
668                Ok(())
669            },
670        )
671        .unwrap();
672        assert_eq!(rows.len(), 1);
673        assert_eq!(
674            rows[0].columns.get(&1),
675            Some(&Value::Int64(11)),
676            "HLC-newer memory version must beat epoch-newer run"
677        );
678        assert_eq!(rows[0].commit_ts, Some(hlc_new));
679    }
680
681    #[test]
682    fn controlled_memory_source_streams_large_overlays_without_full_active_vec() {
683        let mut map = BTreeMap::new();
684        for i in 1..=500u64 {
685            map.insert(
686                RowId(i),
687                Row::new(RowId(i), Epoch(1)).with_column(1, Value::Int64(i as i64)),
688            );
689        }
690        let source = ControlledVisibleSource::memory_from_map(map);
691        assert!(
692            source.is_streaming_memory(),
693            "overlays larger than CONTROLLED_HOT_BATCH must use streaming cursor"
694        );
695        assert_eq!(source.streaming_total(), Some(500));
696        // Active buffer is capped — never holds the full 500-row set at once.
697        assert!(
698            source.streaming_peak_active().unwrap_or(usize::MAX) <= CONTROLLED_HOT_BATCH,
699            "peak active buffer must be <= CONTROLLED_HOT_BATCH"
700        );
701
702        // Drain fully and re-check peak never exceeds the batch cap.
703        let control = crate::ExecutionControl::new(None);
704        let mut sources = vec![ControlledVisibleSource::memory_from_map({
705            let mut m = BTreeMap::new();
706            for i in 1..=500u64 {
707                m.insert(
708                    RowId(i),
709                    Row::new(RowId(i), Epoch(1)).with_column(1, Value::Int64(i as i64)),
710                );
711            }
712            m
713        })];
714        let mut n = 0usize;
715        merge_controlled_visible_sources(
716            &mut sources,
717            &control,
718            |_| false,
719            |_| {
720                n += 1;
721                Ok(())
722            },
723        )
724        .unwrap();
725        assert_eq!(n, 500);
726        assert!(
727            sources[0].streaming_peak_active().unwrap_or(0) <= CONTROLLED_HOT_BATCH,
728            "after full drain peak active still <= batch cap"
729        );
730    }
731}
732
733/// Current UTC time as an ISO-8601 string in bytes (e.g. `b"2024-07-07T14:30:00Z"`).
734/// Used by `DefaultExpr::Now` at stage time.
735fn iso_now_bytes() -> Vec<u8> {
736    let secs = std::time::SystemTime::now()
737        .duration_since(std::time::UNIX_EPOCH)
738        .map(|d| d.as_secs() as i64)
739        .unwrap_or(0);
740    let days = secs.div_euclid(86_400);
741    let rem = secs.rem_euclid(86_400);
742    let (hour, minute, second) = (rem / 3600, (rem % 3600) / 60, rem % 60);
743    let (year, month, day) = civil_from_days(days);
744    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z").into_bytes()
745}
746
747pub(crate) fn unix_nanos_now() -> i64 {
748    std::time::SystemTime::now()
749        .duration_since(std::time::UNIX_EPOCH)
750        .map(|d| d.as_nanos().min(i64::MAX as u128) as i64)
751        .unwrap_or(0)
752}
753
754fn ann_candidate_cap(
755    index_len: usize,
756    context: Option<&crate::query::AiExecutionContext>,
757) -> usize {
758    index_len
759        .min(crate::query::MAX_RAW_INDEX_CANDIDATES)
760        .min(context.map_or(
761            crate::query::MAX_RAW_INDEX_CANDIDATES,
762            crate::query::AiExecutionContext::max_fused_candidates,
763        ))
764}
765
766#[cfg(test)]
767mod ann_candidate_cap_tests {
768    use super::*;
769
770    #[test]
771    fn raw_and_request_candidate_ceilings_are_both_hard_bounds() {
772        assert_eq!(
773            ann_candidate_cap(crate::query::MAX_RAW_INDEX_CANDIDATES + 1, None),
774            crate::query::MAX_RAW_INDEX_CANDIDATES,
775        );
776        let context = crate::query::AiExecutionContext::with_limits(
777            std::time::Duration::from_secs(1),
778            usize::MAX,
779            17,
780        );
781        assert_eq!(ann_candidate_cap(1_000_000, Some(&context)), 17);
782    }
783}
784
785fn civil_from_days(z: i64) -> (i64, u32, u32) {
786    let z = z + 719_468;
787    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
788    let doe = z - era * 146_097;
789    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
790    let y = yoe + era * 400;
791    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
792    let mp = (5 * doy + 2) / 153;
793    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
794    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
795    (if m <= 2 { y + 1 } else { y }, m, d)
796}
797
798/// Derives the stable physical row id used by clustered (`WITHOUT ROWID`)
799/// tables from the encoded primary-key value.
800///
801/// Replicated tablet bootstrap uses this helper when it constructs the same
802/// logical row on every replica without going through the user transaction
803/// staging path.
804pub fn clustered_row_id(primary_key: &Value) -> RowId {
805    let mut hash: u64 = 0xcbf29ce484222325;
806    for byte in primary_key.encode_key() {
807        hash ^= u64::from(byte);
808        hash = hash.wrapping_mul(0x100000001b3);
809    }
810    RowId(hash.max(1))
811}
812
813const DEFAULT_SYNC_BYTE_THRESHOLD: u64 = 0; // manual commit only (pure group commit)
814pub(crate) const PAGE_CACHE_CAPACITY: u64 = 64 * 1024 * 1024; // 64 MiB shared page cache
815pub(crate) const DECODED_CACHE_CAPACITY: u64 = 64 * 1024 * 1024; // 64 MiB shared decoded-page cache (Phase 15.4)
816/// Default byte watermark at which the PMA mutable-run tier spills to an
817/// immutable `.sr` sorted run (Phase 11.1). Coalesces many small flushes into
818/// one larger run so the read path merges fewer readers.
819const DEFAULT_MUTABLE_RUN_SPILL_BYTES: u64 = 8 * 1024 * 1024;
820
821/// Engine-managed `AUTO_INCREMENT` counter state for a table (present iff the
822/// schema declares an `AUTO_INCREMENT` primary key).
823///
824/// `next` is the next value to hand out (1-based, monotonic, never reused). It
825/// is `0` while *unseeded* — the counter has never been advanced (fresh table or
826/// a legacy manifest predating `auto_inc_next`). When `seeded` is `false` the
827/// first allocation scans `max(PK)` over all visible rows so the counter never
828/// collides with pre-existing rows; a value of `0` after seeding never happens
829/// (ids are never 0). The manifest persists `next` only when `seeded`, so a
830/// reopen that reads `auto_inc_next > 0` is authoritative.
831///
832/// `seeded == false` but `next > 0` is a transient recovery-only state: WAL
833/// replay may bump `next` past replayed ids without marking it seeded, so the
834/// scan still runs to cover rows that were already flushed to sorted runs.
835#[derive(Clone, Copy, Debug)]
836struct AutoIncState {
837    column_id: u16,
838    next: i64,
839    seeded: bool,
840}
841
842pub(crate) struct RecoveryMetadataPlan {
843    live_count: u64,
844    auto_inc: Option<AutoIncState>,
845    changed: bool,
846}
847
848type FilledAutoIncRow = (Vec<(u16, Value)>, Option<i64>);
849
850/// Resolve the auto-increment column (if any) from a schema into initial
851/// counter state. Always called after [`crate::schema::Schema::validate_auto_increment`].
852fn resolve_auto_inc(schema: &Schema) -> Option<AutoIncState> {
853    schema.auto_increment_column().map(|c| AutoIncState {
854        column_id: c.id,
855        next: 0,
856        seeded: false,
857    })
858}
859
860/// When a bulk load (`bulk_load` / `bulk_load_columns` / `bulk_load_fast`)
861/// builds the live in-memory indexes.
862///
863/// The engine is correct under either policy: with [`Self::Deferred`] the
864/// indexes are rebuilt lazily by the first `query`/`flush` (Phase 14.7,
865/// `ensure_indexes_complete`), with [`Self::Eager`] they are built — and
866/// checkpointed to `_idx/global.idx` — inside the bulk load itself. The trade
867/// is *where* the build cost lands: `Deferred` keeps the ingest critical path
868/// minimal (write the run, persist the manifest, return); `Eager` gives
869/// predictable first-query latency at the price of a slower load. Serving
870/// deployments that load then immediately serve point queries (e.g. a warm
871/// daemon) may prefer `Eager`; batch/ETL ingest wants `Deferred`.
872#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
873pub enum IndexBuildPolicy {
874    /// Defer index building to the first query/flush — fastest ingest (default).
875    #[default]
876    Deferred,
877    /// Build and checkpoint indexes inside the bulk load — fastest first query.
878    Eager,
879}
880
881#[derive(Clone)]
882struct ReversePkSegment {
883    values: HashMap<RowId, Vec<u8>>,
884    removed: HashSet<RowId>,
885}
886
887#[derive(Clone)]
888struct ReversePkMap {
889    frozen: Arc<Vec<Arc<ReversePkSegment>>>,
890    active: ReversePkSegment,
891}
892
893impl ReversePkMap {
894    fn new() -> Self {
895        Self {
896            frozen: Arc::new(Vec::new()),
897            active: ReversePkSegment {
898                values: HashMap::new(),
899                removed: HashSet::new(),
900            },
901        }
902    }
903
904    fn from_entries(entries: impl IntoIterator<Item = (RowId, Vec<u8>)>) -> Self {
905        let mut map = Self::new();
906        map.active.values.extend(entries);
907        map
908    }
909
910    fn insert(&mut self, row_id: RowId, key: Vec<u8>) {
911        self.active.removed.remove(&row_id);
912        self.active.values.insert(row_id, key);
913    }
914
915    fn get(&self, row_id: &RowId) -> Option<&Vec<u8>> {
916        if let Some(key) = self.active.values.get(row_id) {
917            return Some(key);
918        }
919        if self.active.removed.contains(row_id) {
920            return None;
921        }
922        for segment in self.frozen.iter().rev() {
923            if let Some(key) = segment.values.get(row_id) {
924                return Some(key);
925            }
926            if segment.removed.contains(row_id) {
927                return None;
928            }
929        }
930        None
931    }
932
933    fn remove(&mut self, row_id: &RowId) -> Option<Vec<u8>> {
934        let previous = self.get(row_id).cloned();
935        self.active.values.remove(row_id);
936        self.active.removed.insert(*row_id);
937        previous
938    }
939
940    fn clear(&mut self) {
941        *self = Self::new();
942    }
943
944    fn entries(&self) -> HashMap<RowId, Vec<u8>> {
945        let mut entries = HashMap::new();
946        for segment in self
947            .frozen
948            .iter()
949            .map(Arc::as_ref)
950            .chain(std::iter::once(&self.active))
951        {
952            for row_id in &segment.removed {
953                entries.remove(row_id);
954            }
955            entries.extend(
956                segment
957                    .values
958                    .iter()
959                    .map(|(row_id, key)| (*row_id, key.clone())),
960            );
961        }
962        entries
963    }
964
965    fn seal(&mut self) {
966        if self.active.values.is_empty() && self.active.removed.is_empty() {
967            return;
968        }
969        let active = std::mem::replace(
970            &mut self.active,
971            ReversePkSegment {
972                values: HashMap::new(),
973                removed: HashSet::new(),
974            },
975        );
976        Arc::make_mut(&mut self.frozen).push(Arc::new(active));
977        if self.frozen.len() >= crate::MAX_READ_GENERATION_LAYERS {
978            self.frozen = Arc::new(vec![Arc::new(ReversePkSegment {
979                values: self.entries(),
980                removed: HashSet::new(),
981            })]);
982        }
983    }
984}
985
986/// S1C-001: an immutable, atomically-published table read view — the
987/// engine-layer counterpart of `database::TableReadGeneration`. Readers pin
988/// an `Arc<ReadGeneration>`; writers publish a replacement with a single
989/// `ArcSwap` store ([`Table::publish_read_generation`]) after sealing their
990/// active deltas, so no write ever clones the complete table/index set
991/// merely because readers exist: every captured piece is either an `Arc`
992/// share of immutable frozen layers or a small metadata copy.
993///
994/// `visible_through` is the engine's commit-epoch watermark (the spec's
995/// `HlcTimestamp` maps onto it at the commit-log layer): the view reflects
996/// every commit whose epoch is `<= visible_through`, and later writes are
997/// invisible through it even though they mutate the publishing [`Table`].
998#[derive(Clone)]
999pub struct ReadGeneration {
1000    schema: Arc<Schema>,
1001    base_runs: Arc<Vec<RunRef>>,
1002    deltas: TableDeltas,
1003    indexes: Arc<IndexGeneration>,
1004    visible_through: Epoch,
1005}
1006
1007/// One fully-built secondary index staged outside the publication barrier.
1008/// The variant carries only the target index. Unrelated live indexes remain
1009/// structurally shared when this artifact is installed.
1010pub(crate) enum SecondaryIndexArtifact {
1011    Bitmap(u16, BitmapIndex),
1012    LearnedRange(u16, ColumnLearnedRange),
1013    Fm(u16, Box<FmIndex>),
1014    Ann(u16, Box<AnnIndex>),
1015    Sparse(u16, SparseIndex),
1016    MinHash(u16, MinHashIndex),
1017}
1018
1019/// The sealed in-memory deltas captured with a [`ReadGeneration`]: memtable,
1020/// mutable-run tier, HOT primary-key index, and the reverse primary-key map.
1021/// Each is a post-seal clone — frozen layers are `Arc`-shared with the
1022/// writer, the active delta is empty — so capturing copies no row data, and
1023/// pinning the view keeps exactly the frozen layers it captured alive.
1024#[derive(Clone)]
1025pub struct TableDeltas {
1026    memtable: Memtable,
1027    mutable_run: MutableRun,
1028    hot: HotIndex,
1029    pk_by_row: ReversePkMap,
1030}
1031
1032impl ReadGeneration {
1033    /// An empty view over `schema`, used to seed the published cell before
1034    /// the first [`Table::publish_read_generation`].
1035    fn empty(schema: &Schema) -> Self {
1036        Self {
1037            schema: Arc::new(schema.clone()),
1038            base_runs: Arc::new(Vec::new()),
1039            deltas: TableDeltas {
1040                memtable: Memtable::new(),
1041                mutable_run: MutableRun::new(),
1042                hot: HotIndex::new(),
1043                pk_by_row: ReversePkMap::new(),
1044            },
1045            indexes: Arc::new(IndexGeneration::default()),
1046            visible_through: Epoch(0),
1047        }
1048    }
1049
1050    /// Table schema as of this generation.
1051    pub fn schema(&self) -> &Arc<Schema> {
1052        &self.schema
1053    }
1054
1055    /// Immutable base sorted runs (`r-*.sr`) visible in this generation.
1056    pub fn base_runs(&self) -> &[RunRef] {
1057        &self.base_runs
1058    }
1059
1060    /// The published index generation (all six families).
1061    pub fn indexes(&self) -> &Arc<IndexGeneration> {
1062        &self.indexes
1063    }
1064
1065    /// Highest commit epoch reflected in this view.
1066    pub fn visible_through(&self) -> Epoch {
1067        self.visible_through
1068    }
1069
1070    /// The sealed in-memory deltas captured with this view. The view owns an
1071    /// `Arc` share of every frozen layer, so the layers stay alive (and
1072    /// unchanged) for as long as the view is pinned.
1073    pub fn deltas(&self) -> &TableDeltas {
1074        &self.deltas
1075    }
1076}
1077
1078impl TableDeltas {
1079    /// Approximate heap bytes held by the captured memtable and mutable-run
1080    /// frozen deltas (diagnostics).
1081    pub fn approx_bytes(&self) -> u64 {
1082        self.memtable
1083            .approx_bytes()
1084            .saturating_add(self.mutable_run.approx_bytes())
1085    }
1086
1087    /// Row versions held in the captured memtable layers.
1088    pub fn memtable_len(&self) -> usize {
1089        self.memtable.len()
1090    }
1091
1092    /// Row versions held in the captured mutable-run layers.
1093    pub fn mutable_run_len(&self) -> usize {
1094        self.mutable_run.len()
1095    }
1096
1097    /// Primary-key entries held in the captured HOT index layers.
1098    pub fn hot_len(&self) -> usize {
1099        self.hot.len()
1100    }
1101
1102    /// Reverse primary-key entries captured for HOT cleanup on deletes.
1103    pub fn reverse_pk_len(&self) -> usize {
1104        self.pk_by_row.entries().len()
1105    }
1106}
1107
1108/// An open MongrelDB table.
1109#[derive(Clone)]
1110pub struct Table {
1111    dir: PathBuf,
1112    _root_guard: Option<Arc<crate::durable_file::DurableRoot>>,
1113    runs_root: Option<Arc<crate::durable_file::DurableRoot>>,
1114    idx_root: Option<Arc<crate::durable_file::DurableRoot>>,
1115    table_id: u64,
1116    /// The table's catalog name, set at mount time. Used by the auth
1117    /// enforcement layer to check `Select`/`Insert`/`Update`/`Delete`
1118    /// permissions against this specific table.
1119    name: String,
1120    /// Optional auth checker for per-operation enforcement. `None` on
1121    /// credentialless databases (the default); `Some` when the database has
1122    /// `require_auth = true`. The checker is shared (via `Arc`) so it sees
1123    /// live updates to the principal and the `require_auth` flag.
1124    auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
1125    /// Logical writes are forbidden when this table belongs to a replication
1126    /// follower. Replication itself appends through the database WAL API.
1127    read_only: bool,
1128    /// A WAL commit reached durable storage but its live publication failed.
1129    /// Reads may continue for diagnostics, but writes require a clean reopen so
1130    /// recovery can rebuild one coherent runtime state from the durable WAL.
1131    durable_commit_failed: bool,
1132    wal: WalSink,
1133    memtable: Memtable,
1134    /// PMA-backed mutable-run LSM tier (Phase 11.1). A flush drains the
1135    /// memtable into this in-memory sorted tier instead of immediately writing
1136    /// a `.sr` run; once it crosses `mutable_run_spill_bytes` it spills to an
1137    /// immutable run. Purely in-memory — rebuilt from WAL replay on reopen.
1138    mutable_run: MutableRun,
1139    /// Byte watermark controlling when `mutable_run` spills to a sorted run.
1140    mutable_run_spill_bytes: u64,
1141    /// Zstd compression level for compaction output (Phase 18.1: default 3;
1142    /// higher = better ratio but slower compaction).
1143    compaction_zstd_level: i32,
1144    allocator: RowIdAllocator,
1145    epoch: Arc<EpochAuthority>,
1146    /// Table-local content generation used by authorization caches. Unlike the
1147    /// shared MVCC epoch, unrelated table commits do not change this value.
1148    data_generation: u64,
1149    schema: Schema,
1150    hot: HotIndex,
1151    /// Table Key-Encryption Key (Argon2id+HKDF from the passphrase). Each run
1152    /// stores a fresh DEK wrapped by this KEK (see §7). `None` when plaintext.
1153    kek: Option<Arc<Kek>>,
1154    /// Per-column indexable-encryption keys + scheme (Phase 10.2) for every
1155    /// ENCRYPTED_INDEXABLE column, derived deterministically from the KEK so
1156    /// tokens are identical across runs. Empty when the table is plaintext.
1157    column_keys: HashMap<u16, ([u8; 32], u8)>,
1158    run_refs: Vec<RunRef>,
1159    /// Runs superseded by compaction, kept on disk for snapshot retention until
1160    /// `gc()` reaps them (spec §6.4). Persisted in the manifest (`retiring`).
1161    retiring: Vec<crate::manifest::RetiredRun>,
1162    next_run_id: u64,
1163    sync_byte_threshold: u64,
1164    /// Next transaction id to assign to a single-table auto-commit txn
1165    /// (`put`/`delete` then `commit`). 0 is reserved for [`wal::SYSTEM_TXN_ID`].
1166    /// The Database transaction layer (P2.5) assigns these globally; the
1167    /// single-table path uses this local counter.
1168    current_txn_id: u64,
1169    /// True after a standalone table appends a private-WAL mutation and until
1170    /// `commit_private` has durably sealed and published that transaction.
1171    /// Mounted tables use `pending_rows` / `pending_dels` instead.
1172    pending_private_mutations: bool,
1173    bitmap: HashMap<u16, BitmapIndex>,
1174    ann: HashMap<u16, AnnIndex>,
1175    fm: HashMap<u16, FmIndex>,
1176    sparse: HashMap<u16, SparseIndex>,
1177    minhash: HashMap<u16, MinHashIndex>,
1178    /// Per-column learned (PGM) range indexes for `IndexKind::LearnedRange`
1179    /// columns, built from the single sorted run.
1180    learned_range: Arc<HashMap<u16, ColumnLearnedRange>>,
1181    /// Reverse primary-key map for HOT cleanup on row-id deletes.
1182    pk_by_row: ReversePkMap,
1183    /// Refcounted pinned read snapshots (epoch → count); compaction must not GC
1184    /// versions an active snapshot still needs.
1185    pinned: BTreeMap<Epoch, usize>,
1186    /// Live (non-deleted) row count — maintained incrementally for O(1)
1187    /// `Table::count()` without a scan.
1188    pub(crate) live_count: u64,
1189    /// Uniform reservoir sample of row ids for approximate analytics
1190    /// (Phase 8.2). Maintained incrementally on insert; repopulated on open.
1191    reservoir: crate::reservoir::Reservoir,
1192    /// False when `reservoir` needs a full rebuild from `visible_rows` before
1193    /// [`Table::approx_aggregate`] can trust it (same lazy pattern as
1194    /// [`Table::ensure_indexes_complete`]). Open and WAL-replay leave this
1195    /// false instead of eagerly materializing every row — a full-table scan
1196    /// no plain insert/update/delete needs — and the first approximate-
1197    /// aggregate call pays the rebuild, after which `.offer()` calls maintain
1198    /// it incrementally.
1199    reservoir_complete: bool,
1200    /// True once any row has been deleted. The incremental aggregate cache
1201    /// (Phase 8.3) is only valid for append-only tables, so a single delete
1202    /// permanently disables incremental maintenance for this table.
1203    had_deletes: bool,
1204    /// Pre-images of pure deletes keyed by encoded PK, retained so a subsequent
1205    /// Kit-style delete+put (new rid, same PK) can re-point Bitmap secondaries
1206    /// via [`Self::maintain_indexes_on_pk_replace`] even though HOT no longer
1207    /// maps the PK. Cleared on successful re-point or index rebuild.
1208    recent_delete_preimages: HashMap<Vec<u8>, Row>,
1209    /// In-memory min/max RowId per run for O(1) skip in [`Self::get`]. Populated
1210    /// from run headers on open/spill; not a manifest field (avoids format bump).
1211    run_row_id_ranges: HashMap<u128, (u64, u64)>,
1212    /// Incremental aggregate cache (Phase 8.3): caller-supplied key → the
1213    /// mergeable aggregate state, the row-id watermark it covers, and the
1214    /// epoch. A re-query after more inserts processes only the delta and merges.
1215    agg_cache: Arc<HashMap<u64, CachedAgg>>,
1216    /// The manifest epoch the on-disk `_idx/global.idx` checkpoint covers (0 if
1217    /// there is no checkpoint). Updated by [`Table::checkpoint_indexes`]; persisted
1218    /// in the manifest so reopen loads the checkpoint instead of rebuilding.
1219    global_idx_epoch: u64,
1220    /// False when the live in-memory indexes are known to be incomplete (e.g.
1221    /// after [`Table::bulk_load_columns`], which bypasses per-row indexing). A
1222    /// flush in that state must NOT checkpoint; reopen rebuilds complete indexes
1223    /// from the runs and resets this to true.
1224    indexes_complete: bool,
1225    /// Where bulk loads put the index-build cost (see [`IndexBuildPolicy`]).
1226    index_build_policy: IndexBuildPolicy,
1227    /// False when `pk_by_row` may be missing entries for rows present in
1228    /// `hot`. Fresh tables start false and puts skip the reverse map — pure
1229    /// ingest never pays for it. The first delete that needs it rebuilds it
1230    /// from `hot` (the same lazy pattern as `ensure_indexes_complete`), after
1231    /// which puts maintain it incrementally so a delete-active workload pays
1232    /// the build exactly once.
1233    pk_by_row_complete: bool,
1234    /// Highest epoch whose data is durable in a sorted run (spec §7.1). Recovery
1235    /// skips replaying WAL records whose commit epoch is `<= flushed_epoch`.
1236    flushed_epoch: u64,
1237    /// Shared, MVCC content-addressed page cache (Phase 9.2). Fed by every
1238    /// `RunReader::read_page` so all readers share raw (decrypted) page bytes.
1239    page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
1240    /// Global snapshot-retention registry shared across all tables in a
1241    /// `Database`. Single-table direct opens get a private one.
1242    snapshots: Arc<crate::retention::SnapshotRegistry>,
1243    /// Cross-table commit serializer (see [`SharedCtx::commit_lock`]).
1244    commit_lock: Arc<parking_lot::Mutex<()>>,
1245    /// Shared decoded-page cache (Phase 15.4): the post-decompress/decrypt typed
1246    /// page, so repeat scans skip decode. Keyed by `(run_id, column_id, page)`.
1247    decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
1248    /// `run_id`s whose on-disk footer checksum has already been verified by a
1249    /// `RunReader` construction in this process. `.sr` runs are immutable once
1250    /// written, so re-hashing an already-verified run's full body on every
1251    /// repeat `open_reader` call (every query, every `remove_hot_for_row`) is
1252    /// pure waste for a warm/long-lived handle — this cache lets
1253    /// `read_header_cached` skip straight to the cheap header+footer-magic
1254    /// check after the first open. Scoped per-`Table` (not shared via
1255    /// `SharedCtx`) since `run_id` is only unique within one table's own
1256    /// manifest.
1257    verified_runs: Arc<parking_lot::Mutex<std::collections::HashSet<u128>>>,
1258    /// Open sorted-run readers keyed by run id. Runs are immutable once
1259    /// written, so a point lookup must not reopen and remap the `.sr` on
1260    /// every row. Drop the entry before deleting that file (Windows will not
1261    /// remove a mapped file).
1262    run_readers: Arc<parking_lot::Mutex<HashMap<u128, RunReader>>>,
1263    /// Table-level result cache (Phase 19.1): `canonical_query_key(conditions,
1264    /// projection, epoch)` → the survivor columns as typed `NativeColumn`s. Shared
1265    /// by the native `Condition` API and (via `query_cached`) the tool-call path,
1266    /// which previously had no caching (only the SQL `MongrelSession` cache did).
1267    /// Hardening (c): epoch is no longer in the key; instead, a `commit()`
1268    /// invalidates only entries whose footprint or condition-columns intersect
1269    /// the committed mutations, tracked in `pending_delete_rids` and
1270    /// `pending_put_cols`.
1271    result_cache: Arc<parking_lot::Mutex<ResultCache>>,
1272    /// WAL DEK (for frame-level encryption). None for plaintext tables.
1273    wal_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1274    /// RowIds deleted since the last `commit()` — used by fine-grained cache
1275    /// invalidation to check footprint intersection.
1276    pending_delete_rids: roaring::RoaringBitmap,
1277    /// Column IDs touched by `put`/`put_batch` since the last `commit()` — used
1278    /// by conservative insert-newly-matches invalidation.
1279    pending_put_cols: std::collections::HashSet<u16>,
1280    /// B1/B2: rows staged by `put`/`put_batch` on a mounted (shared-WAL) table
1281    /// but not yet applied to the memtable. They are re-stamped to the real
1282    /// assigned epoch in `commit` (never a speculative `visible+1`), so a
1283    /// concurrent reader can never observe them before their commit epoch.
1284    /// Always empty on a standalone (private-WAL) table, which applies inline.
1285    pending_rows: Vec<Row>,
1286    pending_rows_auto_inc: Vec<bool>,
1287    /// B1/B2: tombstones staged on a mounted table, applied at the assigned
1288    /// epoch in `commit` (mirror of `pending_rows`).
1289    pending_dels: Vec<RowId>,
1290    /// B1/B2: truncate staged on a mounted table, applied at the assigned epoch
1291    /// in `commit`; standalone tables also defer the physical clear until after
1292    /// the private WAL is fsynced.
1293    pending_truncate: Option<Epoch>,
1294    /// Engine-managed `AUTO_INCREMENT` counter (`None` for tables without an
1295    /// auto-increment primary key). See [`AutoIncState`].
1296    auto_inc: Option<AutoIncState>,
1297    /// Manifest-backed timestamp retention policy. Its wall-clock cutoff is
1298    /// evaluated once per read/compaction operation, never cached by epoch.
1299    ttl: Option<TtlPolicy>,
1300    /// Unified version-retention pin registry (S1C-004). Read generations
1301    /// register [`crate::retention::PinSource::ReadGeneration`] pins here;
1302    /// backup/PITR, replication, and online-index-build wiring from the
1303    /// `Database` layer is a follow-up (they can share this registry via
1304    /// [`Table::pin_registry`]). Compaction and version GC consult it through
1305    /// [`Table::min_active_snapshot`].
1306    pins: Arc<crate::retention::PinRegistry>,
1307    /// The atomically-published immutable read view (S1C-001). Writers store
1308    /// a replacement after sealing their active deltas; readers pin the
1309    /// loaded `Arc`. Read-generation clones get their own frozen cell so a
1310    /// later writer publish can never mutate a pinned generation's view.
1311    published: Arc<ArcSwap<ReadGeneration>>,
1312    /// The [`crate::retention::PinGuard`] keeping this generation's epoch
1313    /// retained. `None` on writer tables; `Some` on clones produced by
1314    /// [`Table::clone_read_generation`], released when the generation drops.
1315    /// Shared behind an `Arc` so cloning a generation shares one pin.
1316    read_generation_pin: Option<Arc<crate::retention::PinGuard>>,
1317    /// Lookup observability counters. HOT hits are the fast-path expectation;
1318    /// any fallback in a healthy workload is a regression to investigate.
1319    /// Each clone of `Table` (e.g. `clone_read_generation`) gets its own
1320    /// counters — readers and writers typically share via `Arc<Table>`.
1321    pub(crate) lookup_metrics: LookupMetrics,
1322    /// Per-table row-to-run lookup directory state (spec §1.2 / §8.4). Derived
1323    /// data only — open must not fail when the checkpoint is missing or stale
1324    /// (the existing range-scan fallback stays the safety net).
1325    run_lookup: RunLookupState,
1326}
1327
1328/// Per-table row-to-run lookup directory state (Issue 4 / spec §8.4).
1329///
1330/// The directory is *derived* state and never authoritative for correctness.
1331/// `complete == true` means the in-memory `directory` is consistent with the
1332/// active run set; `false` means the open path found a missing / corrupt /
1333/// stale checkpoint and the read path should fall back to range scans until
1334/// a rebuild finishes (or a fresh publish lands).
1335#[derive(Debug, Default, Clone)]
1336struct RunLookupState {
1337    directory: Option<std::sync::Arc<crate::run_lookup::RunLookupDirectory>>,
1338    fingerprint: u64,
1339    complete: bool,
1340}
1341
1342#[derive(Debug, Default)]
1343pub struct LookupMetrics {
1344    hot_lookup_hit: std::sync::atomic::AtomicU64,
1345    hot_lookup_fallback: std::sync::atomic::AtomicU64,
1346    hot_lookup_fallback_overlay_rows: std::sync::atomic::AtomicU64,
1347    hot_lookup_fallback_runs: std::sync::atomic::AtomicU64,
1348    result_cache_memory_hit: std::sync::atomic::AtomicU64,
1349    result_cache_disk_hit: std::sync::atomic::AtomicU64,
1350    result_cache_miss: std::sync::atomic::AtomicU64,
1351    result_cache_persistent_write_us: std::sync::atomic::AtomicU64,
1352    /// Point-get run probes: opened vs skipped via `run_row_id_ranges`.
1353    get_run_opened: std::sync::atomic::AtomicU64,
1354    get_run_skipped: std::sync::atomic::AtomicU64,
1355    // ---- TODO §1: point-lookup directory counters ----
1356    pub(crate) directory_lookup_hit: std::sync::atomic::AtomicU64,
1357    pub(crate) directory_lookup_fallback: std::sync::atomic::AtomicU64,
1358    pub(crate) directory_incomplete: std::sync::atomic::AtomicU64,
1359    pub(crate) directory_run_readers_opened: std::sync::atomic::AtomicU64,
1360    pub(crate) directory_early_stop_total: std::sync::atomic::AtomicU64,
1361    /// REM-004: directory returned an empty complete lookup for a row (no
1362    /// postings at all). Distinct from `directory_lookup_fallback`, which
1363    /// records only `UnavailableOrStale` (no usable directory). Incremented
1364    /// alongside `directory_lookup_hit` because the directory itself was
1365    /// usable; the answer just happened to be "no immutable runs".
1366    pub(crate) directory_complete_miss_total: std::sync::atomic::AtomicU64,
1367    // ---- TODO §2: persistent result cache async counters ----
1368    pub(crate) result_cache_persist_enqueued_total: std::sync::atomic::AtomicU64,
1369    pub(crate) result_cache_persist_coalesced_total: std::sync::atomic::AtomicU64,
1370    pub(crate) result_cache_persist_dropped_store_total: std::sync::atomic::AtomicU64,
1371    pub(crate) result_cache_persist_remove_total: std::sync::atomic::AtomicU64,
1372    pub(crate) result_cache_persist_stale_store_skipped_total: std::sync::atomic::AtomicU64,
1373    pub(crate) result_cache_persist_errors_total: std::sync::atomic::AtomicU64,
1374    pub(crate) result_cache_persist_shutdown_abandoned_total: std::sync::atomic::AtomicU64,
1375    pub(crate) result_cache_persist_queue_depth: std::sync::atomic::AtomicU64,
1376    // ---- TODO §5: HOT fallback per-reason counters ----
1377    pub(crate) hot_fallback_reasons: [std::sync::atomic::AtomicU64; 9],
1378    pub(crate) hot_fallback_overlay_versions_total: std::sync::atomic::AtomicU64,
1379    pub(crate) hot_fallback_runs_considered_total: std::sync::atomic::AtomicU64,
1380    pub(crate) hot_fallback_runs_opened_total: std::sync::atomic::AtomicU64,
1381    pub(crate) hot_fallback_pages_decoded_total: std::sync::atomic::AtomicU64,
1382    pub(crate) hot_fallback_rows_materialized_total: std::sync::atomic::AtomicU64,
1383    pub(crate) hot_lookup_duration_nanos: std::sync::atomic::AtomicU64,
1384    pub(crate) hot_fallback_duration_nanos: std::sync::atomic::AtomicU64,
1385    pub(crate) hot_mapping_rebuild_total: std::sync::atomic::AtomicU64,
1386    pub(crate) hot_checkpoint_rejected_total: std::sync::atomic::AtomicU64,
1387}
1388
1389impl Clone for LookupMetrics {
1390    fn clone(&self) -> Self {
1391        let mut hot_fallback_reasons = [
1392            std::sync::atomic::AtomicU64::new(0),
1393            std::sync::atomic::AtomicU64::new(0),
1394            std::sync::atomic::AtomicU64::new(0),
1395            std::sync::atomic::AtomicU64::new(0),
1396            std::sync::atomic::AtomicU64::new(0),
1397            std::sync::atomic::AtomicU64::new(0),
1398            std::sync::atomic::AtomicU64::new(0),
1399            std::sync::atomic::AtomicU64::new(0),
1400            std::sync::atomic::AtomicU64::new(0),
1401        ];
1402        for (dst, src) in hot_fallback_reasons
1403            .iter_mut()
1404            .zip(self.hot_fallback_reasons.iter())
1405        {
1406            dst.store(
1407                src.load(std::sync::atomic::Ordering::Relaxed),
1408                std::sync::atomic::Ordering::Relaxed,
1409            );
1410        }
1411        let copy_atomic = |src: &std::sync::atomic::AtomicU64| {
1412            std::sync::atomic::AtomicU64::new(src.load(std::sync::atomic::Ordering::Relaxed))
1413        };
1414        Self {
1415            hot_lookup_hit: copy_atomic(&self.hot_lookup_hit),
1416            hot_lookup_fallback: copy_atomic(&self.hot_lookup_fallback),
1417            hot_lookup_fallback_overlay_rows: copy_atomic(&self.hot_lookup_fallback_overlay_rows),
1418            hot_lookup_fallback_runs: copy_atomic(&self.hot_lookup_fallback_runs),
1419            result_cache_memory_hit: copy_atomic(&self.result_cache_memory_hit),
1420            result_cache_disk_hit: copy_atomic(&self.result_cache_disk_hit),
1421            result_cache_miss: copy_atomic(&self.result_cache_miss),
1422            result_cache_persistent_write_us: copy_atomic(&self.result_cache_persistent_write_us),
1423            get_run_opened: copy_atomic(&self.get_run_opened),
1424            get_run_skipped: copy_atomic(&self.get_run_skipped),
1425            directory_lookup_hit: copy_atomic(&self.directory_lookup_hit),
1426            directory_lookup_fallback: copy_atomic(&self.directory_lookup_fallback),
1427            directory_incomplete: copy_atomic(&self.directory_incomplete),
1428            directory_run_readers_opened: copy_atomic(&self.directory_run_readers_opened),
1429            directory_early_stop_total: copy_atomic(&self.directory_early_stop_total),
1430            directory_complete_miss_total: copy_atomic(&self.directory_complete_miss_total),
1431            result_cache_persist_enqueued_total: copy_atomic(
1432                &self.result_cache_persist_enqueued_total,
1433            ),
1434            result_cache_persist_coalesced_total: copy_atomic(
1435                &self.result_cache_persist_coalesced_total,
1436            ),
1437            result_cache_persist_dropped_store_total: copy_atomic(
1438                &self.result_cache_persist_dropped_store_total,
1439            ),
1440            result_cache_persist_remove_total: copy_atomic(&self.result_cache_persist_remove_total),
1441            result_cache_persist_stale_store_skipped_total: copy_atomic(
1442                &self.result_cache_persist_stale_store_skipped_total,
1443            ),
1444            result_cache_persist_errors_total: copy_atomic(&self.result_cache_persist_errors_total),
1445            result_cache_persist_shutdown_abandoned_total: copy_atomic(
1446                &self.result_cache_persist_shutdown_abandoned_total,
1447            ),
1448            result_cache_persist_queue_depth: copy_atomic(&self.result_cache_persist_queue_depth),
1449            hot_fallback_reasons,
1450            hot_fallback_overlay_versions_total: copy_atomic(
1451                &self.hot_fallback_overlay_versions_total,
1452            ),
1453            hot_fallback_runs_considered_total: copy_atomic(
1454                &self.hot_fallback_runs_considered_total,
1455            ),
1456            hot_fallback_runs_opened_total: copy_atomic(&self.hot_fallback_runs_opened_total),
1457            hot_fallback_pages_decoded_total: copy_atomic(&self.hot_fallback_pages_decoded_total),
1458            hot_fallback_rows_materialized_total: copy_atomic(
1459                &self.hot_fallback_rows_materialized_total,
1460            ),
1461            hot_lookup_duration_nanos: copy_atomic(&self.hot_lookup_duration_nanos),
1462            hot_fallback_duration_nanos: copy_atomic(&self.hot_fallback_duration_nanos),
1463            hot_mapping_rebuild_total: copy_atomic(&self.hot_mapping_rebuild_total),
1464            hot_checkpoint_rejected_total: copy_atomic(&self.hot_checkpoint_rejected_total),
1465        }
1466    }
1467}
1468
1469impl LookupMetrics {
1470    fn snapshot(&self) -> LookupMetricsSnapshot {
1471        LookupMetricsSnapshot {
1472            hot_lookup_hit: self
1473                .hot_lookup_hit
1474                .load(std::sync::atomic::Ordering::Relaxed),
1475            hot_lookup_fallback: self
1476                .hot_lookup_fallback
1477                .load(std::sync::atomic::Ordering::Relaxed),
1478            hot_lookup_fallback_overlay_rows: self
1479                .hot_lookup_fallback_overlay_rows
1480                .load(std::sync::atomic::Ordering::Relaxed),
1481            hot_lookup_fallback_runs: self
1482                .hot_lookup_fallback_runs
1483                .load(std::sync::atomic::Ordering::Relaxed),
1484            result_cache_memory_hit: self
1485                .result_cache_memory_hit
1486                .load(std::sync::atomic::Ordering::Relaxed),
1487            result_cache_disk_hit: self
1488                .result_cache_disk_hit
1489                .load(std::sync::atomic::Ordering::Relaxed),
1490            result_cache_miss: self
1491                .result_cache_miss
1492                .load(std::sync::atomic::Ordering::Relaxed),
1493            result_cache_persistent_write_us: self
1494                .result_cache_persistent_write_us
1495                .load(std::sync::atomic::Ordering::Relaxed),
1496            get_run_opened: self
1497                .get_run_opened
1498                .load(std::sync::atomic::Ordering::Relaxed),
1499            get_run_skipped: self
1500                .get_run_skipped
1501                .load(std::sync::atomic::Ordering::Relaxed),
1502            directory_lookup_hit: self
1503                .directory_lookup_hit
1504                .load(std::sync::atomic::Ordering::Relaxed),
1505            directory_lookup_fallback: self
1506                .directory_lookup_fallback
1507                .load(std::sync::atomic::Ordering::Relaxed),
1508            directory_incomplete: self
1509                .directory_incomplete
1510                .load(std::sync::atomic::Ordering::Relaxed),
1511            directory_run_readers_opened: self
1512                .directory_run_readers_opened
1513                .load(std::sync::atomic::Ordering::Relaxed),
1514            directory_early_stop_total: self
1515                .directory_early_stop_total
1516                .load(std::sync::atomic::Ordering::Relaxed),
1517            directory_complete_miss_total: self
1518                .directory_complete_miss_total
1519                .load(std::sync::atomic::Ordering::Relaxed),
1520            result_cache_persist_enqueued_total: self
1521                .result_cache_persist_enqueued_total
1522                .load(std::sync::atomic::Ordering::Relaxed),
1523            result_cache_persist_coalesced_total: self
1524                .result_cache_persist_coalesced_total
1525                .load(std::sync::atomic::Ordering::Relaxed),
1526            result_cache_persist_dropped_store_total: self
1527                .result_cache_persist_dropped_store_total
1528                .load(std::sync::atomic::Ordering::Relaxed),
1529            result_cache_persist_remove_total: self
1530                .result_cache_persist_remove_total
1531                .load(std::sync::atomic::Ordering::Relaxed),
1532            result_cache_persist_stale_store_skipped_total: self
1533                .result_cache_persist_stale_store_skipped_total
1534                .load(std::sync::atomic::Ordering::Relaxed),
1535            result_cache_persist_errors_total: self
1536                .result_cache_persist_errors_total
1537                .load(std::sync::atomic::Ordering::Relaxed),
1538            result_cache_persist_shutdown_abandoned_total: self
1539                .result_cache_persist_shutdown_abandoned_total
1540                .load(std::sync::atomic::Ordering::Relaxed),
1541            result_cache_persist_queue_depth: self
1542                .result_cache_persist_queue_depth
1543                .load(std::sync::atomic::Ordering::Relaxed),
1544            // REM-D §8.7: publication-availability counters live on the
1545            // `ResultCache` itself (not on the writer's metrics), so they
1546            // are filled in by `Table::lookup_metrics_snapshot`.
1547            result_cache_persist_unavailable_total: 0,
1548            result_cache_persist_skipped_total: 0,
1549            result_cache_worker_spawn_failures_total: 0,
1550            result_cache_worker_shutdown_total: 0,
1551            hot_fallback_reasons: [
1552                self.hot_fallback_reasons[0].load(std::sync::atomic::Ordering::Relaxed),
1553                self.hot_fallback_reasons[1].load(std::sync::atomic::Ordering::Relaxed),
1554                self.hot_fallback_reasons[2].load(std::sync::atomic::Ordering::Relaxed),
1555                self.hot_fallback_reasons[3].load(std::sync::atomic::Ordering::Relaxed),
1556                self.hot_fallback_reasons[4].load(std::sync::atomic::Ordering::Relaxed),
1557                self.hot_fallback_reasons[5].load(std::sync::atomic::Ordering::Relaxed),
1558                self.hot_fallback_reasons[6].load(std::sync::atomic::Ordering::Relaxed),
1559                self.hot_fallback_reasons[7].load(std::sync::atomic::Ordering::Relaxed),
1560                self.hot_fallback_reasons[8].load(std::sync::atomic::Ordering::Relaxed),
1561            ],
1562            hot_fallback_overlay_versions_total: self
1563                .hot_fallback_overlay_versions_total
1564                .load(std::sync::atomic::Ordering::Relaxed),
1565            hot_fallback_runs_considered_total: self
1566                .hot_fallback_runs_considered_total
1567                .load(std::sync::atomic::Ordering::Relaxed),
1568            hot_fallback_runs_opened_total: self
1569                .hot_fallback_runs_opened_total
1570                .load(std::sync::atomic::Ordering::Relaxed),
1571            hot_fallback_pages_decoded_total: self
1572                .hot_fallback_pages_decoded_total
1573                .load(std::sync::atomic::Ordering::Relaxed),
1574            hot_fallback_rows_materialized_total: self
1575                .hot_fallback_rows_materialized_total
1576                .load(std::sync::atomic::Ordering::Relaxed),
1577            hot_lookup_duration_nanos: self
1578                .hot_lookup_duration_nanos
1579                .load(std::sync::atomic::Ordering::Relaxed),
1580            hot_fallback_duration_nanos: self
1581                .hot_fallback_duration_nanos
1582                .load(std::sync::atomic::Ordering::Relaxed),
1583            hot_mapping_rebuild_total: self
1584                .hot_mapping_rebuild_total
1585                .load(std::sync::atomic::Ordering::Relaxed),
1586            hot_checkpoint_rejected_total: self
1587                .hot_checkpoint_rejected_total
1588                .load(std::sync::atomic::Ordering::Relaxed),
1589        }
1590    }
1591}
1592
1593/// Point-in-time copy of [`LookupMetrics`]. Returned from
1594/// [`Table::lookup_metrics_snapshot`] for `/metrics` exposure or test assertions.
1595#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1596pub struct LookupMetricsSnapshot {
1597    pub hot_lookup_hit: u64,
1598    pub hot_lookup_fallback: u64,
1599    pub hot_lookup_fallback_overlay_rows: u64,
1600    pub hot_lookup_fallback_runs: u64,
1601    pub result_cache_memory_hit: u64,
1602    pub result_cache_disk_hit: u64,
1603    pub result_cache_miss: u64,
1604    pub result_cache_persistent_write_us: u64,
1605    pub get_run_opened: u64,
1606    pub get_run_skipped: u64,
1607    // ---- TODO §1 ----
1608    pub directory_lookup_hit: u64,
1609    pub directory_lookup_fallback: u64,
1610    pub directory_incomplete: u64,
1611    pub directory_run_readers_opened: u64,
1612    pub directory_early_stop_total: u64,
1613    pub directory_complete_miss_total: u64,
1614    // ---- TODO §2 ----
1615    pub result_cache_persist_enqueued_total: u64,
1616    pub result_cache_persist_coalesced_total: u64,
1617    pub result_cache_persist_dropped_store_total: u64,
1618    pub result_cache_persist_remove_total: u64,
1619    pub result_cache_persist_stale_store_skipped_total: u64,
1620    pub result_cache_persist_errors_total: u64,
1621    pub result_cache_persist_shutdown_abandoned_total: u64,
1622    pub result_cache_persist_queue_depth: u64,
1623    // ---- REM-D §8.7: publication-availability counters ----
1624    /// Number of times persistent publication transitioned to unavailable
1625    /// (worker spawn failure, worker shutdown, queue unavailable).
1626    pub result_cache_persist_unavailable_total: u64,
1627    /// Number of query-path persist operations skipped because publication
1628    /// was unavailable (the in-memory entry is kept; nothing hits disk).
1629    pub result_cache_persist_skipped_total: u64,
1630    /// Number of background-worker spawn / I/O-setup failures.
1631    pub result_cache_worker_spawn_failures_total: u64,
1632    /// Number of background-worker shutdowns while the cache was live.
1633    pub result_cache_worker_shutdown_total: u64,
1634    // ---- TODO §5 ----
1635    pub hot_fallback_reasons: [u64; 9],
1636    pub hot_fallback_overlay_versions_total: u64,
1637    pub hot_fallback_runs_considered_total: u64,
1638    pub hot_fallback_runs_opened_total: u64,
1639    pub hot_fallback_pages_decoded_total: u64,
1640    pub hot_fallback_rows_materialized_total: u64,
1641    pub hot_lookup_duration_nanos: u64,
1642    pub hot_fallback_duration_nanos: u64,
1643    pub hot_mapping_rebuild_total: u64,
1644    pub hot_checkpoint_rejected_total: u64,
1645}
1646
1647/// Reason label for one HOT fallback. The integer index is the position in
1648/// `LookupMetrics::hot_fallback_reasons` and MUST stay stable across releases.
1649pub fn hot_fallback_reason_index(r: crate::trace::HotFallbackReason) -> usize {
1650    match r {
1651        crate::trace::HotFallbackReason::MissingMapping => 0,
1652        crate::trace::HotFallbackReason::StaleRowId => 1,
1653        crate::trace::HotFallbackReason::InvisibleAtSnapshot => 2,
1654        crate::trace::HotFallbackReason::HistoricalSnapshot => 3,
1655        crate::trace::HotFallbackReason::Tombstone => 4,
1656        crate::trace::HotFallbackReason::TtlExpired => 5,
1657        crate::trace::HotFallbackReason::PrimaryKeyMismatch => 6,
1658        crate::trace::HotFallbackReason::IndexIncomplete => 7,
1659        crate::trace::HotFallbackReason::CheckpointRejected => 8,
1660    }
1661}
1662
1663// `Table` is `Sync`: every field is either plain data, an `Arc`, a `Vec`/`HashMap`
1664// of `Sync` data, or a thread-safe interior-mutability cell (`parking_lot::Mutex`,
1665// `crossbeam`/`epoch` Arc-shared caches). The only `RefCell`-based type was
1666// `FmIndex` (lazy rebuild of the BWT), which now uses a `Mutex`, so a `&Table`
1667// can be safely shared across read threads (concurrent mutation still requires
1668// the caller's `Mutex<Table>`).
1669const _: () = {
1670    const fn assert_sync<T: ?Sized + Sync>() {}
1671    assert_sync::<Table>();
1672};
1673
1674/// A cached query result — either survivor `Row`s (the tool-call/`query` path)
1675/// or typed survivor columns (the pushdown/`query_columns_native` path). One
1676/// canonical key maps to exactly one variant (a `query` with no projection vs a
1677/// `query_columns_native` with a specific projection produce different keys), so
1678/// there is no representation collision.
1679#[derive(Clone)]
1680enum CachedData {
1681    Rows(Arc<Vec<Row>>),
1682    Columns(Arc<Vec<(u16, columnar::NativeColumn)>>),
1683}
1684
1685impl CachedData {
1686    fn approx_bytes(&self) -> u64 {
1687        match self {
1688            CachedData::Rows(r) => r.iter().map(|r| r.estimated_bytes()).sum::<u64>(),
1689            CachedData::Columns(c) => c
1690                .iter()
1691                .map(|(_, c)| c.approx_bytes())
1692                .sum::<u64>()
1693                .saturating_add(c.len() as u64 * 16),
1694        }
1695    }
1696}
1697
1698/// A cached entry carrying the survivor `RowId` **footprint** (for precise
1699/// delete-based invalidation) and the condition column IDs (for conservative
1700/// insert-based invalidation). Hardening (c).
1701struct CachedEntry {
1702    data: CachedData,
1703    footprint: roaring::RoaringBitmap,
1704    condition_cols: Vec<u16>,
1705}
1706
1707impl CachedEntry {
1708    /// Cheap clone for handing to the persistent-cache worker. The `data`
1709    /// is `Arc`-shared (no row/column copy); only the `condition_cols`
1710    /// vector and the `footprint` bitmap are duplicated. The latter two are
1711    /// small relative to the cached payload, so this is fine on the query
1712    /// path.
1713    fn clone_for_persist(&self) -> Self {
1714        Self {
1715            data: self.data.clone(),
1716            footprint: self.footprint.clone(),
1717            condition_cols: self.condition_cols.clone(),
1718        }
1719    }
1720}
1721
1722/// Size-bounded **access-order LRU** result cache (Phase 19.1 + hardening (a)).
1723/// Every `get_*` assigns a new recency generation; eviction removes the lowest
1724/// generation (least-recently-used) — a true LRU, not FIFO.
1725///
1726/// Hardening (b): an optional on-disk persistent tier (`dir = Some(_)`). On a
1727/// memory miss, the cache tries disk before falling through to re-resolution.
1728/// On `insert`, the caller publishes the entry through `persist_entry`, which
1729/// enqueues the atomic write (temp + fsync + rename) onto the background
1730/// worker — never synchronously on the query thread (REM-D §8.5). On
1731/// `invalidate`/`clear`, the matching disk files are deleted. On
1732/// `Table::open`, existing disk entries are pre-loaded so fine-grained invalidation
1733/// resumes across restart.
1734struct ResultCache {
1735    entries: std::collections::HashMap<u64, CachedEntry>,
1736    order: BTreeSet<(u64, u64)>,
1737    generations: HashMap<u64, u64>,
1738    next_generation: u64,
1739    /// Reverse index for conservative insert invalidation. Its size is bounded
1740    /// by cached query-condition metadata, not by survivor rows.
1741    condition_index: HashMap<u16, HashSet<u64>>,
1742    /// Entries whose row footprint could not be resolved. Any delete must
1743    /// conservatively invalidate these entries.
1744    empty_footprint_entries: HashSet<u64>,
1745    bytes: u64,
1746    max_bytes: u64,
1747    dir: Option<std::path::PathBuf>,
1748    #[allow(dead_code)]
1749    cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1750    /// Cache hit/miss counters (memory vs disk tier) + persistent-write latency.
1751    /// Independent of `LookupMetrics` on the parent `Table` — the cache may be
1752    /// queried by paths that don't pass through the table's Pk arm.
1753    memory_hit: std::sync::atomic::AtomicU64,
1754    disk_hit: std::sync::atomic::AtomicU64,
1755    miss: std::sync::atomic::AtomicU64,
1756    persistent_write_us: std::sync::atomic::AtomicU64,
1757    /// Minimum entry size (approx bytes) before the persistent tier is written.
1758    /// Tiny one-row results stay memory-only so a warm miss is not forced to
1759    /// pay atomic filesystem publish. 0 disables the threshold (always persist
1760    /// when `dir` is set). Default: 4 KiB.
1761    persist_min_bytes: u64,
1762    /// Explicit persistent-publication state (REM-D §8.6). `Async` once the
1763    /// table has been wired to a background worker (`install_persistent_writer`);
1764    /// `Disabled(reason)` before then, after a spawn failure, or after worker
1765    /// shutdown. The query path never performs synchronous disk publication:
1766    /// when the state is `Disabled`, `persist_entry` keeps the in-memory entry,
1767    /// skips publication, and increments the skip metric.
1768    persistence: PersistentPublicationState,
1769    /// Worker join handle, kept on the cache so `shutdown_persistent_cache`
1770    /// can wait for drain to finish.
1771    worker_handle: Option<std::thread::JoinHandle<()>>,
1772    /// Completion-signal receiver. The worker sends `()` on this channel
1773    /// immediately before exiting. `shutdown_persistent_cache(deadline)`
1774    /// uses `recv_timeout(remaining_deadline)` so it can return by its
1775    /// advertised deadline even if the worker is blocked in filesystem I/O.
1776    completion_rx: Option<std::sync::mpsc::Receiver<()>>,
1777    /// Optional DEK for cache payload encryption (binary, not a `Zeroizing`
1778    /// wrapper). Stored separately from the cache writer so the same cipher
1779    /// can be reused for both async and sync encode/decode paths.
1780    cache_payload_cipher: Option<std::sync::Arc<crate::encryption::AesCipher>>,
1781    // ---- REM-D §8.7: publication-availability counters ----
1782    /// Transitions of `persistence` to a `Disabled` state while the cache
1783    /// was expected to publish.
1784    persist_unavailable_total: std::sync::atomic::AtomicU64,
1785    /// Query-path persist operations skipped because publication was disabled.
1786    persist_skipped_total: std::sync::atomic::AtomicU64,
1787    /// Worker spawn / I/O-setup failures observed at wiring time.
1788    worker_spawn_failures_total: std::sync::atomic::AtomicU64,
1789    /// Worker shutdowns observed while the cache was live.
1790    worker_shutdown_total: std::sync::atomic::AtomicU64,
1791}
1792
1793/// Serialised form of a [`CachedEntry`] for the persistent on-disk tier (b).
1794#[derive(serde::Serialize, serde::Deserialize)]
1795struct SerializedEntry {
1796    condition_cols: Vec<u16>,
1797    footprint_bits: Vec<u32>,
1798    data: SerializedData,
1799}
1800
1801#[derive(serde::Serialize, serde::Deserialize)]
1802enum SerializedData {
1803    Rows(Vec<Row>),
1804    Columns(Vec<(u16, columnar::NativeColumn)>),
1805}
1806
1807#[derive(serde::Serialize)]
1808struct SerializedEntryRef<'a> {
1809    condition_cols: &'a [u16],
1810    footprint_bits: Vec<u32>,
1811    data: SerializedDataRef<'a>,
1812}
1813
1814#[derive(serde::Serialize)]
1815enum SerializedDataRef<'a> {
1816    Rows(&'a [Row]),
1817    Columns(&'a [(u16, columnar::NativeColumn)]),
1818}
1819
1820impl<'a> SerializedEntryRef<'a> {
1821    fn from_entry(entry: &'a CachedEntry) -> Self {
1822        let footprint_bits: Vec<u32> = entry.footprint.iter().collect();
1823        let data = match &entry.data {
1824            CachedData::Rows(rows) => SerializedDataRef::Rows(rows.as_slice()),
1825            CachedData::Columns(columns) => SerializedDataRef::Columns(columns.as_slice()),
1826        };
1827        Self {
1828            condition_cols: &entry.condition_cols,
1829            footprint_bits,
1830            data,
1831        }
1832    }
1833}
1834
1835impl SerializedEntry {
1836    fn into_entry(self) -> Option<CachedEntry> {
1837        let footprint: roaring::RoaringBitmap = self.footprint_bits.into_iter().collect();
1838        let data = match self.data {
1839            SerializedData::Rows(r) => CachedData::Rows(Arc::new(r)),
1840            SerializedData::Columns(c) => {
1841                // Validate deserialized columns (hardening (b)): reject corrupt
1842                // data instead of panicking on access.
1843                if !c.iter().all(|(_, col)| col.validate()) {
1844                    return None;
1845                }
1846                CachedData::Columns(Arc::new(c))
1847            }
1848        };
1849        Some(CachedEntry {
1850            data,
1851            footprint,
1852            condition_cols: self.condition_cols,
1853        })
1854    }
1855}
1856
1857impl ResultCache {
1858    const DEFAULT_MAX_BYTES: u64 = 256 * 1024 * 1024;
1859
1860    fn new() -> Self {
1861        Self::with_max_bytes(Self::DEFAULT_MAX_BYTES)
1862    }
1863
1864    fn with_max_bytes(max_bytes: u64) -> Self {
1865        Self {
1866            entries: std::collections::HashMap::new(),
1867            order: BTreeSet::new(),
1868            generations: HashMap::new(),
1869            next_generation: 0,
1870            condition_index: HashMap::new(),
1871            empty_footprint_entries: HashSet::new(),
1872            bytes: 0,
1873            max_bytes,
1874            dir: None,
1875            cache_dek: None,
1876            memory_hit: std::sync::atomic::AtomicU64::new(0),
1877            disk_hit: std::sync::atomic::AtomicU64::new(0),
1878            miss: std::sync::atomic::AtomicU64::new(0),
1879            persistent_write_us: std::sync::atomic::AtomicU64::new(0),
1880            // Skip synchronous disk publish for tiny results (one-row point
1881            // queries). Larger analytical results still hit the durable tier.
1882            persist_min_bytes: 4 * 1024,
1883            persistence: PersistentPublicationState::Disabled(
1884                PersistenceDisabledReason::NoDirectory,
1885            ),
1886            worker_handle: None,
1887            completion_rx: None,
1888            cache_payload_cipher: None,
1889            persist_unavailable_total: std::sync::atomic::AtomicU64::new(0),
1890            persist_skipped_total: std::sync::atomic::AtomicU64::new(0),
1891            worker_spawn_failures_total: std::sync::atomic::AtomicU64::new(0),
1892            worker_shutdown_total: std::sync::atomic::AtomicU64::new(0),
1893        }
1894    }
1895
1896    fn with_dir(mut self, dir: std::path::PathBuf) -> Self {
1897        let _ = std::fs::create_dir_all(&dir);
1898        self.dir = Some(dir);
1899        if matches!(
1900            self.persistence,
1901            PersistentPublicationState::Disabled(PersistenceDisabledReason::NoDirectory)
1902        ) {
1903            self.persistence =
1904                PersistentPublicationState::Disabled(PersistenceDisabledReason::QueueUnavailable);
1905        }
1906        self
1907    }
1908
1909    fn with_cache_dek(mut self, dek: Option<Zeroizing<[u8; DEK_LEN]>>) -> Self {
1910        // Build a single cipher for both async and sync paths. The cipher is
1911        // a thin wrapper around the AES key, so creating it twice (once for
1912        // the cache, once for the worker's own copy) is cheap. We keep the
1913        // raw DEK for backward compatibility with `encrypt_cache` /
1914        // `decrypt_cache`; new code paths should use `cache_payload_cipher`.
1915        self.cache_dek = dek.clone();
1916        if let Some(dek) = dek {
1917            if let Ok(cipher) = crate::encryption::AesCipher::new(&dek[..]) {
1918                self.cache_payload_cipher = Some(std::sync::Arc::new(cipher));
1919            }
1920        }
1921        self
1922    }
1923
1924    /// Install a background writer and its worker. The writer drains the
1925    /// pending-op queue and publishes through the supplied I/O backend.
1926    /// `flush_persistent_cache(deadline)` and `shutdown_persistent_cache(deadline)`
1927    /// rely on the writer being installed.
1928    fn install_persistent_writer(
1929        &mut self,
1930        writer: std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
1931        worker_handle: std::thread::JoinHandle<()>,
1932        completion_rx: std::sync::mpsc::Receiver<()>,
1933    ) {
1934        self.persistence = PersistentPublicationState::Async(writer);
1935        self.worker_handle = Some(worker_handle);
1936        self.completion_rx = Some(completion_rx);
1937    }
1938
1939    /// Record that the background worker (or its I/O setup) failed to start.
1940    /// Publication transitions to `Disabled(WorkerSpawnFailed)`; subsequent
1941    /// query-path persists are skipped with a metric instead of falling back
1942    /// to synchronous query-thread I/O (REM-D §8.5).
1943    fn note_worker_spawn_failure(&mut self) {
1944        self.worker_spawn_failures_total
1945            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1946        self.persist_unavailable_total
1947            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1948        self.persistence =
1949            PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerSpawnFailed);
1950    }
1951
1952    /// Take the worker handle so the caller can join it after shutdown.
1953    /// Returns `None` if no writer is installed.
1954    fn take_persistent_worker(&mut self) -> Option<std::thread::JoinHandle<()>> {
1955        self.worker_handle.take()
1956    }
1957
1958    /// Take the completion-signal receiver so the caller can wait on a
1959    /// bounded deadline. Returns `None` if no writer is installed.
1960    fn take_persistent_completion(&mut self) -> Option<std::sync::mpsc::Receiver<()>> {
1961        self.completion_rx.take()
1962    }
1963
1964    /// Borrow the writer (when installed). Used by `flush_persistent_cache` /
1965    /// `shutdown_persistent_cache` to wait for the queue to drain.
1966    fn persistent_writer(
1967        &self,
1968    ) -> Option<&std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>> {
1969        match &self.persistence {
1970            PersistentPublicationState::Async(writer) => Some(writer),
1971            PersistentPublicationState::Disabled(_) => None,
1972        }
1973    }
1974
1975    fn disk_path(&self, key: u64) -> Option<std::path::PathBuf> {
1976        self.dir.as_ref().map(|d| d.join(format!("{key:016x}.bin")))
1977    }
1978
1979    /// Persist `entry` to the on-disk tier **synchronously** using the MLCP
1980    /// frame format (REM-002). The encoding is shared with the async worker —
1981    /// both paths produce the same frame layout, identity validation, and
1982    /// payload encryption. Best-effort: silently ignores I/O errors (the
1983    /// in-memory cache is authoritative; the cache is disposable —
1984    /// missing/stale files fall through to re-resolution).
1985    ///
1986    /// Maintenance-only entry point (REM-D §8.6): migration tools, explicit
1987    /// administrative flushes, and focused format-parity tests. Never called
1988    /// from `query_cached` / `query_columns_native_cached` — the query path
1989    /// uses [`ResultCache::persist_entry`], which never blocks on disk I/O.
1990    fn persist_entry_synchronously_for_maintenance(
1991        &self,
1992        context: PersistContext,
1993        entry: &CachedEntry,
1994    ) {
1995        let Some(path) = self.disk_path(context.key) else {
1996            return;
1997        };
1998        let serialized = match bincode::serialize(&SerializedEntryRef::from_entry(entry)) {
1999            Ok(s) => s,
2000            Err(_) => return,
2001        };
2002        let bytes = match crate::result_cache::encode_persisted_entry(
2003            context,
2004            &serialized,
2005            self.cache_payload_cipher.as_deref(),
2006        ) {
2007            Ok(b) => b,
2008            Err(_) => return,
2009        };
2010        let tmp = path.with_extension("tmp");
2011        use std::io::Write;
2012        let write = || -> std::io::Result<()> {
2013            let mut f = std::fs::File::create(&tmp)?;
2014            f.write_all(&bytes)?;
2015            f.flush()?;
2016            f.sync_all()?;
2017            Ok(())
2018        };
2019        if write().is_err() {
2020            let _ = std::fs::remove_file(&tmp);
2021            return;
2022        }
2023        if std::fs::rename(&tmp, &path).is_err() {
2024            let _ = std::fs::remove_file(&tmp);
2025            return;
2026        }
2027        if let Ok(dir) = std::fs::File::open(self.dir.as_ref().expect("dir set").clone()) {
2028            let _ = dir.sync_all();
2029        }
2030    }
2031
2032    /// Try loading `key` from disk. Returns `None` on miss or error.
2033    /// Decodes the MLCP frame, validates table / schema / key / generation /
2034    /// format version / CRC, decrypts the payload, and bincode-deserializes
2035    /// the entry. Legacy unframed files (anything that does not start with
2036    /// the MLCP magic) are deleted as a safe migration (REM-002 §18.5).
2037    fn load_from_disk(&self, key: u64, identity: PersistentCacheIdentity) -> Option<CachedEntry> {
2038        let path = self.disk_path(key)?;
2039        let bytes = std::fs::read(&path).ok()?;
2040        // Legacy migration: drop unframed files instead of trying to
2041        // bincode-deserialize a raw entry. The cache is disposable — a
2042        // recompute is cheaper than a fragile backward-compat shim.
2043        if bytes.len() < FRAME_MAGIC.len() || bytes[..FRAME_MAGIC.len()] != FRAME_MAGIC {
2044            let _ = std::fs::remove_file(&path);
2045            return None;
2046        }
2047        let plaintext = match crate::result_cache::decode_persisted_entry(
2048            identity,
2049            key,
2050            &bytes,
2051            self.cache_payload_cipher.as_deref(),
2052        ) {
2053            Ok(p) => p,
2054            Err(_) => {
2055                let _ = std::fs::remove_file(&path);
2056                return None;
2057            }
2058        };
2059        let serialized: SerializedEntry = match bincode::deserialize(&plaintext) {
2060            Ok(s) => s,
2061            Err(_) => {
2062                let _ = std::fs::remove_file(&path);
2063                return None;
2064            }
2065        };
2066        serialized.into_entry()
2067    }
2068
2069    /// Delete the on-disk file for `key` if it exists. Best-effort.
2070    fn remove_from_disk(&self, key: u64) {
2071        if let Some(path) = self.disk_path(key) {
2072            let _ = std::fs::remove_file(&path);
2073        }
2074    }
2075
2076    /// Scan the cache directory and pre-load all entries into memory. Called
2077    /// once on `Table::open`. Best-effort: corrupt / unframed / wrong-identity
2078    /// files are deleted and the corresponding entry is treated as a miss.
2079    fn load_persistent(&mut self, identity: PersistentCacheIdentity) {
2080        let Some(dir) = self.dir.as_ref().cloned() else {
2081            return;
2082        };
2083        let entries = match std::fs::read_dir(&dir) {
2084            Ok(e) => e,
2085            Err(_) => return,
2086        };
2087        for entry in entries.flatten() {
2088            let path = entry.path();
2089            // Clean up orphan .tmp files from crashed atomic-write calls.
2090            if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
2091                let _ = std::fs::remove_file(&path);
2092                continue;
2093            }
2094            if path.extension().and_then(|e| e.to_str()) != Some("bin") {
2095                continue;
2096            }
2097            let stem = match path.file_stem().and_then(|s| s.to_str()) {
2098                Some(s) => s,
2099                None => continue,
2100            };
2101            let key = match u64::from_str_radix(stem, 16) {
2102                Ok(k) => k,
2103                Err(_) => continue,
2104            };
2105            // Reuse `load_from_disk` so the legacy / corruption / identity
2106            // rejection path is consistent across the per-key load and the
2107            // bulk preload. The function deletes bad files itself.
2108            if let Some(entry) = self.load_from_disk(key, identity) {
2109                self.bytes = self.bytes.saturating_add(entry.data.approx_bytes());
2110                self.index_entry(key, &entry);
2111                self.entries.insert(key, entry);
2112                self.touch(key);
2113            }
2114        }
2115        self.evict();
2116    }
2117
2118    fn set_max_bytes(&mut self, max_bytes: u64) {
2119        self.max_bytes = max_bytes;
2120        self.evict();
2121    }
2122
2123    /// Promote `key` to most-recently-used position without scanning every
2124    /// cache entry. The generation-ordered set provides exact LRU in O(log n).
2125    fn touch(&mut self, key: u64) {
2126        if !self.entries.contains_key(&key) {
2127            return;
2128        }
2129        if let Some(previous) = self.generations.remove(&key) {
2130            self.order.remove(&(previous, key));
2131        }
2132        let generation = self.allocate_generation();
2133        self.generations.insert(key, generation);
2134        self.order.insert((generation, key));
2135    }
2136
2137    fn untrack(&mut self, key: u64) {
2138        if let Some(generation) = self.generations.remove(&key) {
2139            self.order.remove(&(generation, key));
2140        }
2141    }
2142
2143    fn index_entry(&mut self, key: u64, entry: &CachedEntry) {
2144        for column in &entry.condition_cols {
2145            self.condition_index.entry(*column).or_default().insert(key);
2146        }
2147        if entry.footprint.is_empty() {
2148            self.empty_footprint_entries.insert(key);
2149        }
2150    }
2151
2152    fn unindex_entry(&mut self, key: u64, entry: &CachedEntry) {
2153        for column in &entry.condition_cols {
2154            let remove_column = self.condition_index.get_mut(column).is_some_and(|keys| {
2155                keys.remove(&key);
2156                keys.is_empty()
2157            });
2158            if remove_column {
2159                self.condition_index.remove(column);
2160            }
2161        }
2162        if entry.footprint.is_empty() {
2163            self.empty_footprint_entries.remove(&key);
2164        }
2165    }
2166
2167    fn allocate_generation(&mut self) -> u64 {
2168        if self.next_generation == u64::MAX {
2169            self.rebase_generations();
2170        }
2171        let generation = self.next_generation;
2172        self.next_generation += 1;
2173        generation
2174    }
2175
2176    fn rebase_generations(&mut self) {
2177        let ordered = std::mem::take(&mut self.order);
2178        self.generations.clear();
2179        for (generation, (_, key)) in ordered.into_iter().enumerate() {
2180            let generation = generation as u64;
2181            self.generations.insert(key, generation);
2182            self.order.insert((generation, key));
2183        }
2184        self.next_generation = self.order.len() as u64;
2185    }
2186
2187    fn get_rows(&mut self, key: u64, identity: PersistentCacheIdentity) -> Option<Arc<Vec<Row>>> {
2188        let res = self.entries.get(&key).and_then(|e| match &e.data {
2189            CachedData::Rows(r) => Some(r.clone()),
2190            CachedData::Columns(_) => None,
2191        });
2192        if res.is_some() {
2193            self.touch(key);
2194            self.memory_hit
2195                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2196            return res;
2197        }
2198        // Memory miss → try the persistent tier (b).
2199        if let Some(entry) = self.load_from_disk(key, identity) {
2200            let res = match &entry.data {
2201                CachedData::Rows(r) => Some(r.clone()),
2202                CachedData::Columns(_) => None,
2203            };
2204            if res.is_some() {
2205                let approx = entry.data.approx_bytes();
2206                self.bytes = self.bytes.saturating_add(approx);
2207                self.index_entry(key, &entry);
2208                self.entries.insert(key, entry);
2209                self.touch(key);
2210                self.evict();
2211                self.disk_hit
2212                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2213                return res;
2214            }
2215        }
2216        self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2217        None
2218    }
2219
2220    fn get_columns(
2221        &mut self,
2222        key: u64,
2223        identity: PersistentCacheIdentity,
2224    ) -> Option<Arc<Vec<(u16, columnar::NativeColumn)>>> {
2225        let res = self.entries.get(&key).and_then(|e| match &e.data {
2226            CachedData::Columns(c) => Some(c.clone()),
2227            CachedData::Rows(_) => None,
2228        });
2229        if res.is_some() {
2230            self.touch(key);
2231            self.memory_hit
2232                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2233            return res;
2234        }
2235        // Memory miss → try the persistent tier (b).
2236        if let Some(entry) = self.load_from_disk(key, identity) {
2237            let res = match &entry.data {
2238                CachedData::Columns(c) => Some(c.clone()),
2239                CachedData::Rows(_) => None,
2240            };
2241            if res.is_some() {
2242                let approx = entry.data.approx_bytes();
2243                self.bytes = self.bytes.saturating_add(approx);
2244                self.index_entry(key, &entry);
2245                self.entries.insert(key, entry);
2246                self.touch(key);
2247                self.evict();
2248                self.disk_hit
2249                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2250                return res;
2251            }
2252        }
2253        self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2254        None
2255    }
2256
2257    /// In-memory insert only. Persistent publication is the caller's job —
2258    /// they call `persist_entry(context, &entry)` (or the legacy
2259    /// `enqueue_persist` for the async path) before this method so the on-
2260    /// disk frame and the in-memory copy can never diverge.
2261    fn insert(&mut self, key: u64, entry: CachedEntry) {
2262        let approx = entry.data.approx_bytes();
2263        if let Some(previous) = self.entries.remove(&key) {
2264            self.bytes = self.bytes.saturating_sub(previous.data.approx_bytes());
2265            self.unindex_entry(key, &previous);
2266            self.untrack(key);
2267        }
2268        self.bytes = self.bytes.saturating_add(approx);
2269        self.index_entry(key, &entry);
2270        self.entries.insert(key, entry);
2271        self.touch(key);
2272        self.evict();
2273    }
2274
2275    /// Persist `entry` using the MLCP frame format (REM-002 §18.3). When
2276    /// the async writer is installed the op is enqueued; when publication is
2277    /// unavailable the entry stays in the in-memory tier and the skip is
2278    /// counted (REM-D §8.5). The query thread never performs disk I/O here.
2279    /// No-op when the entry is below the persistence threshold.
2280    fn persist_entry(&self, context: PersistContext, entry: &CachedEntry) {
2281        let approx = entry.data.approx_bytes();
2282        if self.dir.is_none() {
2283            return;
2284        }
2285        if self.persist_min_bytes > 0 && approx < self.persist_min_bytes {
2286            return;
2287        }
2288        match &self.persistence {
2289            PersistentPublicationState::Async(writer) => {
2290                // Async path: enqueue a `PersistableEntry`. The worker calls
2291                // the same `encode_persisted_entry` helper so the on-disk
2292                // format is byte-for-byte identical to the sync path.
2293                let entry_clone = entry.clone_for_persist();
2294                let payload_factory: Box<dyn FnOnce() -> Option<Vec<u8>> + Send + 'static> =
2295                    Box::new(move || {
2296                        bincode::serialize(&SerializedEntryRef::from_entry(&entry_clone)).ok()
2297                    });
2298                let persistable = crate::result_cache::PersistableEntry {
2299                    key: context.key,
2300                    table_id: context.identity.table_id,
2301                    schema_id: context.identity.schema_id,
2302                    run_generation: context.identity.logical_generation,
2303                    entry_generation: context.entry_generation,
2304                    bytes: approx as usize,
2305                    payload_factory,
2306                };
2307                let write_start = std::time::Instant::now();
2308                writer.enqueue_store(persistable);
2309                let write_us = write_start.elapsed().as_micros() as u64;
2310                self.persistent_write_us
2311                    .fetch_add(write_us, std::sync::atomic::Ordering::Relaxed);
2312            }
2313            PersistentPublicationState::Disabled(reason) => {
2314                // Publication unavailable: keep the in-memory entry, skip the
2315                // persistent write, and make the skip observable (REM-D
2316                // §8.5). The persistent cache is disposable optimization
2317                // state; the next miss simply recomputes.
2318                self.persist_skipped_total
2319                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2320                crate::trace::QueryTrace::record(|trace| {
2321                    trace.result_cache_persist_skipped = true;
2322                    trace.result_cache_persist_skip_reason = Some(reason.label());
2323                });
2324            }
2325        }
2326    }
2327
2328    /// Allocate a fresh per-key entry generation. The generation is what
2329    /// the worker compares against the writer's queue to decide whether a
2330    /// store is still current. A newer invalidation that arrives after the
2331    /// generation was issued supersedes the queued store.
2332    fn allocate_persist_generation(&mut self, key: u64) -> u64 {
2333        if let Some(writer) = self.persistent_writer() {
2334            // Bump the global per-key generation on the writer so a
2335            // subsequent store for the same key is observed as fresh.
2336            let _ = key; // the writer tracks per-key generations internally
2337            writer.bump_persist_generation(key)
2338        } else {
2339            0
2340        }
2341    }
2342
2343    /// Enqueue a `Remove` to the background writer. No-op when no writer is
2344    /// installed.
2345    fn enqueue_persist_remove(&self, key: u64) {
2346        if let Some(writer) = self.persistent_writer() {
2347            writer.enqueue_remove(key);
2348        }
2349    }
2350
2351    /// Enqueue a `Clear` to the background writer. No-op when no writer is
2352    /// installed. Bumping the writer's `clear_generation` is the
2353    /// "shutdown generation" required by REM-002 §18.6 — any in-flight
2354    /// write that re-checks staleness right before publish is then
2355    /// observed as stale and dropped instead of becoming a late durable
2356    /// entry.
2357    fn enqueue_persist_clear(&self) {
2358        if let Some(writer) = self.persistent_writer() {
2359            writer.enqueue_clear();
2360        }
2361    }
2362
2363    /// Drain the writer's queue synchronously until empty or `deadline`
2364    /// expires. The caller invokes this on `Database::close` or before a
2365    /// checkpoint; the worker keeps running and the queue depth is checked
2366    /// between drains. Returns the queue depth at the moment of the call
2367    /// return.
2368    fn flush_persistent_cache(&self, deadline: std::time::Duration) -> u64 {
2369        let Some(writer) = self.persistent_writer() else {
2370            return 0;
2371        };
2372        let start = std::time::Instant::now();
2373        loop {
2374            let depth = writer.queue_depth() as u64;
2375            // Wait until the queue is empty AND no dequeued op is unfinished.
2376            // The worker counts an op as in flight from the moment it leaves
2377            // the queue, including the staleness check before I/O. Observing
2378            // both counters at zero means the directory rename has finished,
2379            // not merely that the op was popped.
2380            let in_flight = writer.writes_in_flight();
2381            if depth == 0 && in_flight == 0 {
2382                return 0;
2383            }
2384            if start.elapsed() >= deadline {
2385                return depth;
2386            }
2387            std::thread::sleep(std::time::Duration::from_millis(2));
2388        }
2389    }
2390
2391    /// Shut the writer down. The worker drains remaining ops until the
2392    /// queue is empty or `deadline` expires; any ops still queued are
2393    /// counted as abandoned. The completion signal is waited on with the
2394    /// *remaining* deadline (REM-002 §18.6) — if it does not arrive in
2395    /// time, the timeout counter is bumped and the worker is detached
2396    /// (its `Arc`-shared state keeps it safe to outlive this method).
2397    /// Publication transitions to `Disabled(WorkerShutdown)` so subsequent
2398    /// `persist_entry` calls skip persistent publication with a metric
2399    /// instead of falling back to synchronous query-thread I/O (REM-D §8.5).
2400    fn shutdown_persistent_cache(&mut self, deadline: std::time::Duration) {
2401        let start = Instant::now();
2402        // Phase 1: wait for the queue to drain or the deadline to expire.
2403        if let Some(writer) = self.persistent_writer() {
2404            loop {
2405                if writer.queue_depth() == 0 {
2406                    break;
2407                }
2408                if start.elapsed() >= deadline {
2409                    break;
2410                }
2411                std::thread::sleep(std::time::Duration::from_millis(2));
2412            }
2413        }
2414        // Phase 2: mark the writer closed. `enqueue_clear` advances the
2415        // global clear_generation so the worker's final staleness check
2416        // (right before publish) aborts any late in-flight write.
2417        let writer = self.persistent_writer().cloned();
2418        if let Some(writer) = writer.as_ref() {
2419            writer.shutdown();
2420            let _ = writer.drain_all_as_abandoned();
2421        }
2422        // Phase 3: wait for the completion signal with the *remaining*
2423        // deadline. `JoinHandle::join` has no timed variant, so we use
2424        // the channel as the deadline-bounded wait point. If the worker
2425        // is blocked in filesystem I/O, the recv returns Err on timeout
2426        // and we detach the handle (state is `Arc`-shared, so the worker
2427        // can still complete safely).
2428        let mut completion = self.take_persistent_completion();
2429        let completed = if let (Some(rx), Some(_writer)) = (completion.as_mut(), writer.as_ref()) {
2430            let elapsed = start.elapsed();
2431            let remaining = deadline.saturating_sub(elapsed);
2432            crate::result_cache::recv_completion_with_timeout(rx, remaining)
2433        } else {
2434            true
2435        };
2436        if completed {
2437            if let Some(handle) = self.take_persistent_worker() {
2438                let _ = handle.join();
2439            }
2440            // Drain any signal we did not consume.
2441            drop(completion.take());
2442        } else {
2443            // Timeout: bump the abandoned counter and detach the handle.
2444            // The worker is still running and may eventually finish; the
2445            // in-flight I/O either completes or fails on its own.
2446            if let Some(writer) = writer.as_ref() {
2447                writer.record_outcome(DrainOutcome::Abandoned);
2448            }
2449            self.take_persistent_worker(); // drop the handle, do not join
2450        }
2451        // Transition publication to `Disabled(WorkerShutdown)`: subsequent
2452        // inserts keep their in-memory entry and skip persistent publication
2453        // (REM-D §8.5). The transition and the shutdown are both counted.
2454        if matches!(self.persistence, PersistentPublicationState::Async(_)) {
2455            self.worker_shutdown_total
2456                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2457            self.persist_unavailable_total
2458                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2459            self.persistence =
2460                PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerShutdown);
2461        }
2462    }
2463
2464    /// Set the minimum entry size (approx bytes) before the persistent tier
2465    /// is written. 0 always persists. Exposed as a `pub(crate)` so the test
2466    /// seam on `Table` can drive sub-4KiB fixtures through the on-disk path.
2467    pub(crate) fn set_persist_min_bytes(&mut self, min: u64) {
2468        self.persist_min_bytes = min;
2469    }
2470
2471    /// True when the last insert of an entry of size `approx` would hit disk.
2472    #[cfg(test)]
2473    fn would_persist(&self, approx: u64) -> bool {
2474        self.dir.is_some() && (self.persist_min_bytes == 0 || approx >= self.persist_min_bytes)
2475    }
2476
2477    /// Read the per-tier counters. Returned as `(memory_hit, disk_hit, miss,
2478    /// persistent_write_us)` so callers can roll them into their own snapshot.
2479    fn cache_counters(&self) -> (u64, u64, u64, u64) {
2480        (
2481            self.memory_hit.load(std::sync::atomic::Ordering::Relaxed),
2482            self.disk_hit.load(std::sync::atomic::Ordering::Relaxed),
2483            self.miss.load(std::sync::atomic::Ordering::Relaxed),
2484            self.persistent_write_us
2485                .load(std::sync::atomic::Ordering::Relaxed),
2486        )
2487    }
2488
2489    /// Read the REM-D §8.7 publication-availability counters. Returned as
2490    /// `(persist_unavailable_total, persist_skipped_total,
2491    /// worker_spawn_failures_total, worker_shutdown_total)`.
2492    fn publication_counters(&self) -> (u64, u64, u64, u64) {
2493        (
2494            self.persist_unavailable_total
2495                .load(std::sync::atomic::Ordering::Relaxed),
2496            self.persist_skipped_total
2497                .load(std::sync::atomic::Ordering::Relaxed),
2498            self.worker_spawn_failures_total
2499                .load(std::sync::atomic::Ordering::Relaxed),
2500            self.worker_shutdown_total
2501                .load(std::sync::atomic::Ordering::Relaxed),
2502        )
2503    }
2504
2505    /// Snapshot of the writer's persist counters. `None` when no writer is
2506    /// installed (publication disabled).
2507    fn persist_snapshot(&self) -> Option<LookupMetricsSnapshot> {
2508        self.persistent_writer().map(|w| w.persist_snapshot())
2509    }
2510
2511    /// Fine-grained invalidation (hardening (c)). Drop only entries that are
2512    /// actually affected by the committed mutations:
2513    /// - **Delete path**: if `delete_rids` intersects an entry's footprint, a
2514    ///   survivor was deleted → stale. If the footprint is empty (multi-run or
2515    ///   non-empty memtable — we couldn't resolve it), **any** delete
2516    ///   conservatively invalidates the entry (correctness over precision).
2517    /// - **Insert path**: if `put_cols` intersects an entry's `condition_cols`,
2518    ///   a newly-inserted row might match the query → conservatively stale.
2519    fn invalidate(
2520        &mut self,
2521        delete_rids: &roaring::RoaringBitmap,
2522        put_cols: &std::collections::HashSet<u16>,
2523    ) {
2524        if self.entries.is_empty() {
2525            return;
2526        }
2527        let has_deletes = !delete_rids.is_empty();
2528        let mut to_remove = HashSet::new();
2529
2530        // Inserts/updates are the common mutation path. Resolve affected cache
2531        // keys directly from the condition-column reverse index instead of
2532        // scanning every cached result on every commit.
2533        for column in put_cols {
2534            if let Some(keys) = self.condition_index.get(column) {
2535                to_remove.extend(keys.iter().copied());
2536            }
2537        }
2538
2539        if has_deletes {
2540            // Entries with an unknown footprint are conservatively stale after
2541            // any delete. Known footprints still require a bitmap intersection;
2542            // this scan is paid only by delete commits, not every insert.
2543            to_remove.extend(self.empty_footprint_entries.iter().copied());
2544            for (&key, entry) in &self.entries {
2545                if !to_remove.contains(&key)
2546                    && !entry.footprint.is_empty()
2547                    && entry.footprint.intersection_len(delete_rids) > 0
2548                {
2549                    to_remove.insert(key);
2550                }
2551            }
2552        }
2553
2554        for key in to_remove {
2555            if let Some(entry) = self.entries.remove(&key) {
2556                self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2557                self.unindex_entry(key, &entry);
2558            }
2559            // When a background writer is installed, the on-disk file is
2560            // removed asynchronously by the worker; otherwise, fall back to
2561            // the legacy synchronous `remove_from_disk` so early test paths
2562            // (which build a `ResultCache` directly) keep working.
2563            if self.persistent_writer().is_some() {
2564                self.enqueue_persist_remove(key);
2565            } else {
2566                self.remove_from_disk(key);
2567            }
2568            self.untrack(key);
2569        }
2570    }
2571
2572    fn clear(&mut self) {
2573        // Delete all persistent files (b). When a background writer is
2574        // installed, the on-disk files are removed asynchronously by the
2575        // worker; otherwise, fall back to the legacy synchronous scan.
2576        if self.dir.is_some() {
2577            if self.persistent_writer().is_some() {
2578                self.enqueue_persist_clear();
2579            } else if let Some(dir) = &self.dir {
2580                if let Ok(entries) = std::fs::read_dir(dir) {
2581                    for entry in entries.flatten() {
2582                        let path = entry.path();
2583                        if path.extension().and_then(|e| e.to_str()) == Some("bin") {
2584                            let _ = std::fs::remove_file(&path);
2585                        }
2586                    }
2587                }
2588            }
2589        }
2590        self.entries.clear();
2591        self.order.clear();
2592        self.generations.clear();
2593        self.next_generation = 0;
2594        self.condition_index.clear();
2595        self.empty_footprint_entries.clear();
2596        self.bytes = 0;
2597    }
2598
2599    fn evict(&mut self) {
2600        while self.bytes > self.max_bytes {
2601            let Some((_, key)) = self.order.pop_first() else {
2602                break;
2603            };
2604            self.generations.remove(&key);
2605            if let Some(entry) = self.entries.remove(&key) {
2606                self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2607                self.unindex_entry(key, &entry);
2608                // The on-disk file is left in place. The persistent
2609                // loader validates the frame's `logical_generation` on
2610                // every load (REM-002 §18.4), so a stale file from a
2611                // pre-commit epoch is rejected as `GenerationMismatch` and
2612                // deleted on read. Deleting the file at eviction time
2613                // would defeat the "memory eviction → disk hit" path
2614                // exercised by the production tests.
2615            }
2616        }
2617    }
2618}
2619
2620/// Set up the persistent-publication writer for a fresh `ResultCache`. The
2621/// returned tuple is `(writer, worker_join_handle, completion_receiver)`;
2622/// pass `writer` and `worker_join_handle` to
2623/// [`ResultCache::install_persistent_writer`], and the `completion_receiver`
2624/// to the cache so `shutdown_persistent_cache(deadline)` can wait on a
2625/// bounded deadline. The caller is responsible for joining the worker on
2626/// `shutdown_persistent_cache(deadline)`.
2627fn spawn_persistent_cache_worker(
2628    dir: std::path::PathBuf,
2629    cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
2630    metrics: LookupMetrics,
2631) -> std::io::Result<(
2632    std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
2633    std::thread::JoinHandle<()>,
2634    std::sync::mpsc::Receiver<()>,
2635)> {
2636    use crate::result_cache::{
2637        spawn_persistent_cache_worker as spawn, RealPersistentCacheIo, StalenessGuard,
2638        WorkerConfig, WriterStalenessGuard,
2639    };
2640    // Test seam (REM-D §8.8): force worker startup failure through the real
2641    // `Table::create` / `Table::open` wiring. Thread-local so parallel tests
2642    // in the same process are unaffected.
2643    if PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.get()) {
2644        return Err(std::io::Error::other(
2645            "persistent-cache worker spawn failure forced by test seam",
2646        ));
2647    }
2648    let io: std::sync::Arc<dyn crate::result_cache::PersistentCacheIo> =
2649        std::sync::Arc::new(RealPersistentCacheIo::new(dir)?);
2650    let cipher = match cache_dek {
2651        Some(dek) => {
2652            let cipher = crate::encryption::AesCipher::new(&dek[..])
2653                .map_err(|e| std::io::Error::other(format!("aes: {e}")))?;
2654            Some(std::sync::Arc::new(cipher))
2655        }
2656        None => None,
2657    };
2658    let writer = std::sync::Arc::new(crate::result_cache::PersistentResultCacheWriter::new(
2659        metrics,
2660        crate::result_cache::WriterLimits::default(),
2661    ));
2662    let staleness: std::sync::Arc<dyn StalenessGuard> =
2663        std::sync::Arc::new(WriterStalenessGuard::new(writer.clone()));
2664    let (completion_tx, completion_rx) = std::sync::mpsc::channel();
2665    let config = WorkerConfig {
2666        writer: writer.clone(),
2667        io,
2668        cipher,
2669        staleness,
2670        max_staleness_retries: 8,
2671        completion: Some(completion_tx),
2672    };
2673    let handle = spawn(config);
2674    Ok((writer, handle, completion_rx))
2675}
2676
2677thread_local! {
2678    /// Thread-local test seam (REM-D §8.8): when set,
2679    /// [`spawn_persistent_cache_worker`] fails deterministically so tests can
2680    /// exercise the "worker startup failure" path through the real
2681    /// `Table::create` / `Table::open` wiring. Thread-local so concurrently
2682    /// running tests are unaffected. Reset by
2683    /// [`Table::_force_persistent_worker_spawn_failure_for_test`].
2684    static PERSISTENT_WORKER_SPAWN_FAILURE: std::cell::Cell<bool> =
2685        const { std::cell::Cell::new(false) };
2686}
2687
2688#[cfg(test)]
2689mod result_cache_lru_tests {
2690    use super::*;
2691
2692    fn row_entry(row_id: u64) -> CachedEntry {
2693        CachedEntry {
2694            data: CachedData::Rows(Arc::new(vec![Row::new(RowId(row_id), Epoch(1))])),
2695            footprint: std::iter::once(row_id as u32).collect(),
2696            condition_cols: vec![1],
2697        }
2698    }
2699
2700    #[test]
2701    fn hits_update_recency_without_growing_an_order_queue() {
2702        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2703        let identity = PersistentCacheIdentity {
2704            table_id: 0,
2705            schema_id: 0,
2706            logical_generation: 0,
2707        };
2708        cache.insert(1, row_entry(1));
2709        cache.insert(2, row_entry(2));
2710        assert_eq!(cache.order.len(), cache.entries.len());
2711
2712        for _ in 0..1_000 {
2713            assert!(cache.get_rows(1, identity).is_some());
2714        }
2715
2716        assert_eq!(cache.order.len(), cache.entries.len());
2717        assert_eq!(cache.order.first().map(|(_, key)| *key), Some(2));
2718
2719        let one_entry = cache.entries[&1].data.approx_bytes();
2720        cache.set_max_bytes(one_entry);
2721        assert!(cache.entries.contains_key(&1));
2722        assert!(!cache.entries.contains_key(&2));
2723        assert_eq!(cache.order.len(), cache.entries.len());
2724    }
2725
2726    #[test]
2727    fn tiny_entries_skip_persistent_tier_by_default() {
2728        let dir = tempfile::tempdir().unwrap();
2729        let mut cache = ResultCache::with_max_bytes(u64::MAX).with_dir(dir.path().to_path_buf());
2730        let tiny = row_entry(1).data.approx_bytes();
2731        assert!(
2732            tiny < 4 * 1024,
2733            "row_entry fixture must be below default 4KiB threshold"
2734        );
2735        assert!(
2736            !cache.would_persist(tiny),
2737            "tiny entry must not force synchronous disk publish"
2738        );
2739        assert!(
2740            cache.would_persist(8 * 1024),
2741            "large entry must still persist when dir is set"
2742        );
2743        cache.set_persist_min_bytes(0);
2744        assert!(
2745            cache.would_persist(tiny),
2746            "persist_min_bytes=0 restores always-persist policy"
2747        );
2748    }
2749
2750    #[test]
2751    fn insert_invalidation_uses_the_condition_reverse_index() {
2752        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2753        let mut first = row_entry(1);
2754        first.condition_cols = vec![1];
2755        let mut second = row_entry(2);
2756        second.condition_cols = vec![2];
2757        cache.insert(1, first);
2758        cache.insert(2, second);
2759
2760        let put_cols = std::iter::once(1_u16).collect();
2761        cache.invalidate(&roaring::RoaringBitmap::new(), &put_cols);
2762
2763        assert!(!cache.entries.contains_key(&1));
2764        assert!(cache.entries.contains_key(&2));
2765        assert!(!cache
2766            .condition_index
2767            .get(&1)
2768            .is_some_and(|keys| keys.contains(&1)));
2769        assert!(cache
2770            .condition_index
2771            .get(&2)
2772            .is_some_and(|keys| keys.contains(&2)));
2773        assert_eq!(cache.order.len(), cache.entries.len());
2774    }
2775
2776    #[test]
2777    fn delete_invalidation_preserves_known_and_unknown_footprint_semantics() {
2778        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2779        cache.insert(1, row_entry(1));
2780        cache.insert(2, row_entry(2));
2781        let mut unknown = row_entry(3);
2782        unknown.footprint.clear();
2783        cache.insert(3, unknown);
2784
2785        let delete_rids: roaring::RoaringBitmap = std::iter::once(1_u32).collect();
2786        cache.invalidate(&delete_rids, &HashSet::new());
2787
2788        assert!(!cache.entries.contains_key(&1));
2789        assert!(cache.entries.contains_key(&2));
2790        assert!(!cache.entries.contains_key(&3));
2791        assert!(cache.empty_footprint_entries.is_empty());
2792        assert_eq!(cache.order.len(), cache.entries.len());
2793    }
2794
2795    #[test]
2796    fn borrowed_persistence_encoding_matches_the_existing_owned_format() {
2797        let entry = row_entry(7);
2798        let borrowed = bincode::serialize(&SerializedEntryRef::from_entry(&entry)).unwrap();
2799        let owned = bincode::serialize(&SerializedEntry {
2800            condition_cols: entry.condition_cols.clone(),
2801            footprint_bits: entry.footprint.iter().collect(),
2802            data: match &entry.data {
2803                CachedData::Rows(rows) => SerializedData::Rows((**rows).clone()),
2804                CachedData::Columns(columns) => SerializedData::Columns((**columns).clone()),
2805            },
2806        })
2807        .unwrap();
2808        assert_eq!(borrowed, owned);
2809    }
2810}
2811
2812/// Derive per-column indexable-encryption keys (Phase 10.2) for every
2813/// ENCRYPTED_INDEXABLE column from the KEK. Scheme is `OPE_RANGE` if the column
2814/// has a `LearnedRange` index, else `HMAC_EQ` (equality). Keys are derived
2815/// deterministically from the KEK so tokens are stable across runs. Empty when
2816/// the table is plaintext (no KEK).
2817/// Derive WAL and cache DEKs from the KEK (None when no encryption).
2818type DekaOpt = Option<Zeroizing<[u8; DEK_LEN]>>;
2819
2820fn derive_subkeys(kek: Option<&Kek>, _table_id: u64) -> (DekaOpt, DekaOpt) {
2821    let _ = kek;
2822    {
2823        if let Some(k) = kek {
2824            return (
2825                Some(k.derive_table_wal_key(_table_id)),
2826                Some(k.derive_cache_key()),
2827            );
2828        }
2829    }
2830    (None, None)
2831}
2832
2833fn read_table_encryption_salt_root(
2834    root: &crate::durable_file::DurableRoot,
2835) -> Result<[u8; crate::encryption::SALT_LEN]> {
2836    use std::io::Read;
2837
2838    let mut file = root
2839        .open_regular(Path::new(META_DIR).join(KEYS_FILENAME))
2840        .map_err(|error| MongrelError::NotFound(format!("encryption salt file: {error}")))?;
2841    let length = file.metadata()?.len();
2842    if length != crate::encryption::SALT_LEN as u64 {
2843        return Err(MongrelError::InvalidArgument(format!(
2844            "salt file is {length} bytes, expected {}",
2845            crate::encryption::SALT_LEN
2846        )));
2847    }
2848    let mut salt = [0_u8; crate::encryption::SALT_LEN];
2849    file.read_exact(&mut salt)?;
2850    Ok(salt)
2851}
2852
2853/// Create a boxed cipher from a DEK.
2854fn make_cipher(dek: &Zeroizing<[u8; DEK_LEN]>) -> Box<dyn crate::encryption::Cipher> {
2855    Box::new(crate::encryption::AesCipher::new(&dek[..]).expect("DEK is 32 bytes"))
2856}
2857
2858fn build_column_keys(kek: Option<&Kek>, schema: &Schema) -> HashMap<u16, ([u8; 32], u8)> {
2859    let Some(kek) = kek else {
2860        return HashMap::new();
2861    };
2862    {
2863        use crate::encryption::{SCHEME_HMAC_EQ, SCHEME_OPE_RANGE};
2864        schema
2865            .columns
2866            .iter()
2867            .filter(|c| c.flags.contains(ColumnFlags::ENCRYPTED_INDEXABLE))
2868            .map(|c| {
2869                let scheme = if schema
2870                    .indexes
2871                    .iter()
2872                    .any(|i| i.column_id == c.id && i.kind == IndexKind::LearnedRange)
2873                {
2874                    SCHEME_OPE_RANGE
2875                } else {
2876                    SCHEME_HMAC_EQ
2877                };
2878                let key: [u8; 32] = *kek.derive_column_key(c.id);
2879                (c.id, (key, scheme))
2880            })
2881            .collect()
2882    }
2883}
2884
2885/// Shared services injected into every `Table` owned by a `Database`: one epoch
2886/// authority (single commit clock), one raw-page cache, one decoded-page cache,
2887/// one snapshot-retention registry, and the DB-wide KEK. A directly-opened
2888/// single table builds a private `SharedCtx` of its own.
2889pub(crate) struct SharedCtx {
2890    pub root_guard: Option<Arc<crate::durable_file::DurableRoot>>,
2891    pub epoch: Arc<EpochAuthority>,
2892    pub page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
2893    pub decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
2894    pub snapshots: Arc<crate::retention::SnapshotRegistry>,
2895    pub kek: Option<Arc<Kek>>,
2896    /// Serializes the commit critical section across all tables sharing this
2897    /// context so the dual-counter's in-order-publish invariant holds: the
2898    /// assigned ticket is reserved, the WAL fsynced, the manifest persisted,
2899    /// and `visible` published as one atomic unit. P3 replaces this with the
2900    /// bounded validate-first sequencer + group commit (overlapping fsync).
2901    pub commit_lock: Arc<parking_lot::Mutex<()>>,
2902    /// B1: when `Some`, the table is mounted in a `Database` and routes every
2903    /// write through the one shared WAL (no private `_wal/` dir is created).
2904    /// `None` for a directly-opened standalone table, which keeps a private WAL.
2905    pub shared: Option<SharedWalCtx>,
2906    /// The table's catalog name (for auth enforcement). `None` on standalone
2907    /// direct-open tables that have no catalog entry.
2908    pub table_name: Option<String>,
2909    /// Auth checker for per-operation enforcement. `None` on credentialless
2910    /// databases; cloned from the `Database`'s `auth_state` wrapper.
2911    pub auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
2912    /// Whether logical writes must be rejected for a replica database.
2913    pub read_only: bool,
2914}
2915
2916/// Handles a mounted table needs to write to the database's single shared WAL
2917/// (B1): the WAL itself, the group-commit coordinator + poison flag (so a
2918/// single-table commit honors the same durability/§9.3e semantics as a cross-
2919/// table txn), and the shared txn-id allocator (so auto-commit ids never alias
2920/// cross-table ones in the merged log).
2921#[derive(Clone)]
2922pub(crate) struct SharedWalCtx {
2923    pub wal: Arc<parking_lot::Mutex<SharedWal>>,
2924    pub group: Arc<GroupCommit>,
2925    pub poisoned: Arc<AtomicBool>,
2926    pub txn_ids: Arc<parking_lot::Mutex<u64>>,
2927    pub change_wake: tokio::sync::broadcast::Sender<()>,
2928    /// S1A-004: the owning core's lifecycle, poisoned at every fsync-error
2929    /// site so the whole core rejects later operations.
2930    pub lifecycle: Arc<crate::core::LifecycleController>,
2931    /// Database HLC clock used to stamp single-table commit row versions (P0.5).
2932    pub hlc: Arc<mongreldb_types::hlc::HlcClock>,
2933}
2934
2935/// Where a table's WAL records go. A standalone table owns a `Private` WAL; a
2936/// `Database`-mounted table writes to the one `Shared` WAL (B1).
2937enum WalSink {
2938    Private(Wal),
2939    Shared(SharedWalCtx),
2940    ReadOnly,
2941}
2942
2943impl Clone for WalSink {
2944    fn clone(&self) -> Self {
2945        match self {
2946            Self::Shared(shared) => Self::Shared(shared.clone()),
2947            Self::Private(_) | Self::ReadOnly => Self::ReadOnly,
2948        }
2949    }
2950}
2951
2952impl SharedCtx {
2953    /// Build a fresh private (standalone) context. `cache_dir = Some(_)` enables
2954    /// on-disk page cache persistence (single-table direct open); `None` keeps
2955    /// it in-memory (shared across tables in a `Database`).
2956    pub(crate) fn new(kek: Option<Arc<Kek>>, cache_dir: Option<PathBuf>) -> Self {
2957        // §5.8: shard the caches to reduce lock contention under parallel
2958        // rayon scans. The persistent (single-table) path uses 1 shard (no
2959        // contention) so its on-disk load/spill stays simple.
2960        let n_shards = if cache_dir.is_some() {
2961            1
2962        } else {
2963            crate::cache::CACHE_SHARDS
2964        };
2965        let per_shard = PAGE_CACHE_CAPACITY / n_shards as u64;
2966        let page_cache = if let Some(d) = cache_dir {
2967            Arc::new(crate::cache::Sharded::new(1, || {
2968                crate::cache::PageCache::new(PAGE_CACHE_CAPACITY).with_persistence(d.clone())
2969            }))
2970        } else {
2971            Arc::new(crate::cache::Sharded::new(n_shards, || {
2972                crate::cache::PageCache::new(per_shard)
2973            }))
2974        };
2975        let decoded_per_shard = DECODED_CACHE_CAPACITY / crate::cache::CACHE_SHARDS as u64;
2976        let decoded_cache = Arc::new(crate::cache::Sharded::new(
2977            crate::cache::CACHE_SHARDS,
2978            || crate::cache::DecodedPageCache::new(decoded_per_shard),
2979        ));
2980        Self {
2981            root_guard: None,
2982            epoch: Arc::new(EpochAuthority::new(0)),
2983            page_cache,
2984            decoded_cache,
2985            snapshots: Arc::new(crate::retention::SnapshotRegistry::new()),
2986            kek,
2987            commit_lock: Arc::new(parking_lot::Mutex::new(())),
2988            shared: None,
2989            table_name: None,
2990            auth: None,
2991            read_only: false,
2992        }
2993    }
2994}
2995
2996/// §5.5: estimated per-condition resolution cost for cheap-first conjunction
2997/// ordering. Lower is resolved first so a selective O(1) index lookup can
2998/// short-circuit an expensive range/FM/vector scan.
2999fn condition_cost_rank(c: &crate::query::Condition) -> u8 {
3000    use crate::query::Condition;
3001    match c {
3002        // O(1) index lookups — resolve first.
3003        Condition::Pk(_)
3004        | Condition::BitmapEq { .. }
3005        | Condition::BitmapIn { .. }
3006        | Condition::BytesPrefix { .. }
3007        | Condition::IsNull { .. }
3008        | Condition::IsNotNull { .. } => 0,
3009        // Page-pruned scan or LSH candidate lookup.
3010        Condition::Range { .. } | Condition::RangeF64 { .. } | Condition::MinHashSimilar { .. } => {
3011            1
3012        }
3013        // FM locate / vector scans — most expensive, resolve last.
3014        Condition::FmContains { .. }
3015        | Condition::FmContainsAll { .. }
3016        | Condition::Ann { .. }
3017        | Condition::SparseMatch { .. } => 2,
3018    }
3019}
3020
3021impl Table {
3022    /// Build one hidden secondary index from authoritative visible rows.
3023    /// Callers run this against a pinned read generation, outside the final
3024    /// publication barrier. `checkpoint` supplies cooperative cancellation,
3025    /// resource checks, and progress reporting without coupling the engine to
3026    /// the jobs framework.
3027    pub(crate) fn build_secondary_index_artifact<F>(
3028        &self,
3029        definition: &IndexDef,
3030        rows: &[Row],
3031        mut checkpoint: F,
3032    ) -> Result<SecondaryIndexArtifact>
3033    where
3034        F: FnMut(usize, usize) -> Result<()>,
3035    {
3036        let mut build_schema = self.schema.clone();
3037        build_schema.indexes = vec![definition.clone()];
3038        let (mut bitmap, mut ann, mut fm, mut sparse, mut minhash) = empty_indexes(&build_schema);
3039        let name_to_id: HashMap<&str, u16> = self
3040            .schema
3041            .columns
3042            .iter()
3043            .map(|column| (column.name.as_str(), column.id))
3044            .collect();
3045        let mut hot = HotIndex::new();
3046        let mut accepted = Vec::with_capacity(rows.len());
3047
3048        for (offset, row) in rows.iter().enumerate() {
3049            checkpoint(offset, rows.len())?;
3050            if row.deleted {
3051                continue;
3052            }
3053            if let Some(predicate) = &definition.predicate {
3054                let columns: HashMap<u16, &Value> =
3055                    row.columns.iter().map(|(id, value)| (*id, value)).collect();
3056                if !eval_partial_predicate(predicate, &columns, &name_to_id) {
3057                    continue;
3058                }
3059            }
3060            accepted.push(row);
3061            if definition.kind == IndexKind::LearnedRange {
3062                continue;
3063            }
3064            let effective = if self.column_keys.is_empty() {
3065                row.clone()
3066            } else {
3067                self.tokenized_for_indexes(row)
3068            };
3069            if definition.kind == IndexKind::Ann {
3070                if let (Some(index), Some(vector)) = (
3071                    ann.get_mut(&definition.column_id),
3072                    effective
3073                        .columns
3074                        .get(&definition.column_id)
3075                        .and_then(Value::as_embedding),
3076                ) {
3077                    index.insert_validated_with_checkpoint(vector, effective.row_id, || {
3078                        checkpoint(offset, rows.len())
3079                    })?;
3080                }
3081            } else {
3082                index_into_single(
3083                    definition,
3084                    &build_schema,
3085                    &effective,
3086                    &mut hot,
3087                    &mut bitmap,
3088                    &mut ann,
3089                    &mut fm,
3090                    &mut sparse,
3091                    &mut minhash,
3092                );
3093            }
3094        }
3095        checkpoint(rows.len(), rows.len())?;
3096
3097        if let Some(index) = ann.get_mut(&definition.column_id) {
3098            index.seal_with_checkpoint(|| checkpoint(rows.len(), rows.len()))?;
3099        }
3100
3101        let column_id = definition.column_id;
3102        match definition.kind {
3103            IndexKind::Bitmap => bitmap
3104                .remove(&column_id)
3105                .map(|index| SecondaryIndexArtifact::Bitmap(column_id, index)),
3106            IndexKind::Ann => ann
3107                .remove(&column_id)
3108                .map(|index| SecondaryIndexArtifact::Ann(column_id, Box::new(index))),
3109            IndexKind::FmIndex => fm
3110                .remove(&column_id)
3111                .map(|index| SecondaryIndexArtifact::Fm(column_id, Box::new(index))),
3112            IndexKind::Sparse => sparse
3113                .remove(&column_id)
3114                .map(|index| SecondaryIndexArtifact::Sparse(column_id, index)),
3115            IndexKind::MinHash => minhash
3116                .remove(&column_id)
3117                .map(|index| SecondaryIndexArtifact::MinHash(column_id, index)),
3118            IndexKind::LearnedRange => {
3119                let epsilon = definition
3120                    .options
3121                    .learned_range
3122                    .as_ref()
3123                    .map(|options| options.epsilon)
3124                    .unwrap_or(16);
3125                let column = self
3126                    .schema
3127                    .columns
3128                    .iter()
3129                    .find(|column| column.id == column_id)
3130                    .ok_or_else(|| {
3131                        MongrelError::Schema(format!(
3132                            "index {} references unknown column {column_id}",
3133                            definition.name
3134                        ))
3135                    })?;
3136                let index = match column.ty {
3137                    TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
3138                        let pairs: Vec<_> = accepted
3139                            .iter()
3140                            .filter_map(|row| match row.columns.get(&column_id) {
3141                                Some(Value::Int64(value)) if !row.deleted => {
3142                                    Some((*value, row.row_id.0))
3143                                }
3144                                _ => None,
3145                            })
3146                            .collect();
3147                        ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon)
3148                    }
3149                    TypeId::Float32 | TypeId::Float64 => {
3150                        let pairs: Vec<_> = accepted
3151                            .iter()
3152                            .filter_map(|row| match row.columns.get(&column_id) {
3153                                Some(Value::Float64(value)) if !row.deleted => {
3154                                    Some((*value, row.row_id.0))
3155                                }
3156                                _ => None,
3157                            })
3158                            .collect();
3159                        ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon)
3160                    }
3161                    ref ty => {
3162                        return Err(MongrelError::Schema(format!(
3163                            "LearnedRange index {} does not support {ty:?}",
3164                            definition.name
3165                        )));
3166                    }
3167                };
3168                Some(SecondaryIndexArtifact::LearnedRange(column_id, index))
3169            }
3170        }
3171        .ok_or_else(|| {
3172            MongrelError::Other(format!(
3173                "failed to construct hidden index {}",
3174                definition.name
3175            ))
3176        })
3177    }
3178
3179    pub fn create(dir: impl AsRef<Path>, schema: Schema, table_id: u64) -> Result<Self> {
3180        let dir = dir.as_ref().to_path_buf();
3181        // Use std::fs (no eager parent-fsync) — the deferred root's finalize
3182        // pass makes the entry durable at the end of create.
3183        std::fs::create_dir_all(&dir)?;
3184        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3185        let pinned = root.io_path()?;
3186        let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3187        ctx.root_guard = Some(root.clone());
3188        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3189        // Shallow finalize: root-level files (schema, manifest) are
3190        // data-durable, root + immediate subdirs are entry-durable. Files
3191        // inside `_wal/` and `_runs/` rely on the first commit/flush (same
3192        // contract as the pre-hardening path). Encrypted tables use the full
3193        // recursive `finalize_deferred_sync` via `create_encrypted`.
3194        root.finalize_deferred_sync_shallow()?;
3195        Ok(table)
3196    }
3197
3198    /// Create a new encrypted table, deriving the table Key-Encryption Key
3199    /// (KEK) from `passphrase` via Argon2id + HKDF (§7). A fresh random salt is
3200    /// generated and persisted under `_meta/keys` so the same passphrase
3201    /// recreates the KEK on reopen. Each run gets its own wrapped DEK.
3202    ///
3203    /// **Scope (§7):** encryption is *page-granular* — only sorted-run page
3204    /// payloads are encrypted. The live WAL (`_wal/`) holds rows as plaintext
3205    /// between `put` and `flush`; call `flush()` (which rotates the WAL) before
3206    /// treating sensitive data as fully at-rest-protected. Full WAL encryption
3207    /// is deferred.
3208    pub fn create_encrypted(
3209        dir: impl AsRef<Path>,
3210        schema: Schema,
3211        table_id: u64,
3212        passphrase: &str,
3213    ) -> Result<Self> {
3214        let dir = dir.as_ref().to_path_buf();
3215        std::fs::create_dir_all(&dir)?;
3216        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3217        root.create_directory_all(META_DIR)?;
3218        let salt = crate::encryption::random_salt()?;
3219        root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3220        let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3221        let pinned = root.io_path()?;
3222        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3223        ctx.root_guard = Some(root.clone());
3224        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3225        root.finalize_deferred_sync()?;
3226        Ok(table)
3227    }
3228
3229    /// Create a new encrypted table using a raw key (e.g. from a key file)
3230    /// instead of a passphrase. Skips Argon2id — the key must already be
3231    /// high-entropy (>= 32 bytes of random data). ~0.1ms vs ~50ms for the
3232    /// passphrase path.
3233    pub fn create_with_key(
3234        dir: impl AsRef<Path>,
3235        schema: Schema,
3236        table_id: u64,
3237        key: &[u8],
3238    ) -> Result<Self> {
3239        let dir = dir.as_ref().to_path_buf();
3240        std::fs::create_dir_all(&dir)?;
3241        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3242        root.create_directory_all(META_DIR)?;
3243        let salt = crate::encryption::random_salt()?;
3244        root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3245        let kek: Arc<Kek> = Arc::new(Kek::from_raw_key(key, &salt)?);
3246        let pinned = root.io_path()?;
3247        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3248        ctx.root_guard = Some(root.clone());
3249        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3250        root.finalize_deferred_sync()?;
3251        Ok(table)
3252    }
3253
3254    /// Open an existing encrypted table using a raw key.
3255    pub fn open_with_key(dir: impl AsRef<Path>, key: &[u8]) -> Result<Self> {
3256        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3257        let salt = read_table_encryption_salt_root(&root)?;
3258        let kek = Arc::new(Kek::from_raw_key(key, &salt)?);
3259        let pinned = root.io_path()?;
3260        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3261        ctx.root_guard = Some(root);
3262        Self::open_in(&pinned, ctx)
3263    }
3264
3265    pub(crate) fn create_in(
3266        dir: impl AsRef<Path>,
3267        schema: Schema,
3268        table_id: u64,
3269        ctx: SharedCtx,
3270    ) -> Result<Self> {
3271        schema.validate_auto_increment()?;
3272        schema.validate_defaults()?;
3273        schema.validate_ai()?;
3274        for index in &schema.indexes {
3275            index.validate_options()?;
3276        }
3277        let dir = dir.as_ref().to_path_buf();
3278        let runs_root = match ctx.root_guard.as_ref() {
3279            Some(root) => Some(Arc::new(root.create_directory_all_pinned(RUNS_DIR)?)),
3280            None => {
3281                crate::durable_file::create_directory_all(&dir)?;
3282                crate::durable_file::create_directory_all(&dir.join(RUNS_DIR))?;
3283                None
3284            }
3285        };
3286        match ctx.root_guard.as_deref() {
3287            Some(root) => write_schema_durable(root, &schema)?,
3288            None => write_schema(&dir, &schema)?,
3289        }
3290        let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), table_id);
3291        // B1: a mounted table routes writes through the shared WAL and never
3292        // creates its own `_wal/` dir. A standalone table owns a private WAL.
3293        let (wal, current_txn_id) = match ctx.shared.clone() {
3294            Some(s) => (WalSink::Shared(s), 0),
3295            None => {
3296                let pinned_wal_root = match ctx.root_guard.as_deref() {
3297                    Some(root) => Some(root.create_directory_all_pinned(WAL_DIR)?),
3298                    None => None,
3299                };
3300                let wal_dir = if let Some(root) = pinned_wal_root.as_ref() {
3301                    root.io_path()?
3302                } else {
3303                    let wal_dir = dir.join(WAL_DIR);
3304                    std::fs::create_dir_all(&wal_dir)?;
3305                    wal_dir
3306                };
3307                let mut w = match (pinned_wal_root.as_ref(), wal_dek.as_ref()) {
3308                    (Some(root), Some(dk)) => {
3309                        Wal::create_in_root(root, 0, Epoch(0), Some(make_cipher(dk)))?
3310                    }
3311                    (Some(root), None) => Wal::create_in_root(root, 0, Epoch(0), None)?,
3312                    (None, Some(dk)) => Wal::create_with_cipher(
3313                        wal_dir.join("seg-000000.wal"),
3314                        Epoch(0),
3315                        Some(make_cipher(dk)),
3316                        0,
3317                    )?,
3318                    (None, None) => Wal::create(wal_dir.join("seg-000000.wal"), Epoch(0))?,
3319                };
3320                w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3321                (WalSink::Private(w), 1)
3322            }
3323        };
3324        let mut manifest = Manifest::new(table_id, schema.schema_id);
3325        // Seal the create-time manifest with the meta DEK so an encrypted table
3326        // reopens even if no write/flush ever re-persists it (otherwise the
3327        // reopen's encrypted manifest read fails to authenticate a plaintext
3328        // blob — see `manifest_meta_dek`).
3329        let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3330        match ctx.root_guard.as_deref() {
3331            Some(root) => manifest::write_durable(root, &mut manifest, manifest_meta_dek.as_ref())?,
3332            None => manifest::write_atomic(&dir, &mut manifest, manifest_meta_dek.as_ref())?,
3333        }
3334        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&schema);
3335        let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3336        let auto_inc = resolve_auto_inc(&schema);
3337        let rcache_dir = dir.join(RCACHE_DIR);
3338        let initial_view = ReadGeneration::empty(&schema);
3339        Ok(Self {
3340            dir,
3341            _root_guard: ctx.root_guard,
3342            runs_root,
3343            idx_root: None,
3344            table_id,
3345            name: ctx.table_name.unwrap_or_default(),
3346            auth: ctx.auth,
3347            read_only: ctx.read_only,
3348            durable_commit_failed: false,
3349            wal,
3350            memtable: Memtable::new(),
3351            mutable_run: MutableRun::new(),
3352            mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3353            compaction_zstd_level: 3,
3354            allocator: RowIdAllocator::new(0),
3355            epoch: ctx.epoch,
3356            data_generation: 0,
3357            schema,
3358            hot: HotIndex::new(),
3359            kek: ctx.kek,
3360            column_keys,
3361            run_refs: Vec::new(),
3362            retiring: Vec::new(),
3363            next_run_id: 1,
3364            sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3365            current_txn_id,
3366            pending_private_mutations: false,
3367            bitmap,
3368            ann,
3369            fm,
3370            sparse,
3371            minhash,
3372            learned_range: Arc::new(HashMap::new()),
3373            pk_by_row: ReversePkMap::new(),
3374            pinned: BTreeMap::new(),
3375            live_count: 0,
3376            reservoir: crate::reservoir::Reservoir::default(),
3377            reservoir_complete: true,
3378            had_deletes: false,
3379            recent_delete_preimages: HashMap::new(),
3380            run_row_id_ranges: HashMap::new(),
3381            agg_cache: Arc::new(HashMap::new()),
3382            global_idx_epoch: 0,
3383            indexes_complete: true,
3384            index_build_policy: IndexBuildPolicy::default(),
3385            pk_by_row_complete: false,
3386            flushed_epoch: 0,
3387            page_cache: ctx.page_cache,
3388            decoded_cache: ctx.decoded_cache,
3389            verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3390            run_readers: Arc::new(parking_lot::Mutex::new(HashMap::new())),
3391            snapshots: ctx.snapshots,
3392            commit_lock: ctx.commit_lock,
3393            // Build the persistent-cache result cache. We attempt to spawn a
3394            // background writer; if that fails (e.g. the OS won't let us
3395            // create the temp file), publication is marked
3396            // `Disabled(WorkerSpawnFailed)` — the table still opens and
3397            // query-path persists are skipped with a metric, never performed
3398            // synchronously on the query thread (REM-D §8.5).
3399            result_cache: {
3400                let cache = ResultCache::new()
3401                    .with_dir(rcache_dir.clone())
3402                    .with_cache_dek(cache_dek.clone());
3403                // Reuse a per-table `LookupMetrics` so the writer's
3404                // enqueue/coalesce/drop counters are visible through
3405                // `Table::lookup_metrics_snapshot`.
3406                let metrics = Arc::new(LookupMetrics::default());
3407                let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3408                match spawn_persistent_cache_worker(
3409                    rcache_dir.clone(),
3410                    cache_dek.clone(),
3411                    (*metrics).clone(),
3412                ) {
3413                    Ok((writer, handle, completion_rx)) => {
3414                        cache_arc
3415                            .lock()
3416                            .install_persistent_writer(writer, handle, completion_rx);
3417                    }
3418                    Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3419                }
3420                cache_arc
3421            },
3422            pending_delete_rids: roaring::RoaringBitmap::new(),
3423            pending_put_cols: std::collections::HashSet::new(),
3424            pending_rows: Vec::new(),
3425            pending_rows_auto_inc: Vec::new(),
3426            pending_dels: Vec::new(),
3427            pending_truncate: None,
3428            wal_dek,
3429            auto_inc,
3430            ttl: None,
3431            pins: Arc::new(crate::retention::PinRegistry::new()),
3432            published: Arc::new(ArcSwap::from_pointee(initial_view)),
3433            read_generation_pin: None,
3434            lookup_metrics: LookupMetrics::default(),
3435            run_lookup: RunLookupState::default(),
3436        })
3437    }
3438
3439    /// Open an existing table: load the manifest, replay the active WAL segment
3440    /// into the memtable, and rebuild the HOT + secondary indexes from the runs
3441    /// and replayed rows.
3442    pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
3443        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3444        let pinned = root.io_path()?;
3445        let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3446        ctx.root_guard = Some(root);
3447        Self::open_in(&pinned, ctx)
3448    }
3449
3450    /// Open an existing encrypted table. `passphrase` must match the one used at
3451    /// create time (combined with the persisted salt to re-derive the KEK).
3452    pub fn open_encrypted(dir: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
3453        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3454        let salt = read_table_encryption_salt_root(&root)?;
3455        let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3456        let pinned = root.io_path()?;
3457        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3458        ctx.root_guard = Some(root);
3459        let t = Self::open_in(&pinned, ctx)?;
3460        Ok(t)
3461    }
3462
3463    pub(crate) fn open_in(dir: impl AsRef<Path>, ctx: SharedCtx) -> Result<Self> {
3464        let dir = dir.as_ref().to_path_buf();
3465        let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3466        let mut manifest = match ctx.root_guard.as_ref() {
3467            Some(root) => manifest::read_durable(root, "", manifest_meta_dek.as_ref())?,
3468            None => manifest::read(&dir, manifest_meta_dek.as_ref())?,
3469        };
3470        let schema: Schema = match ctx.root_guard.as_ref() {
3471            Some(root) => read_schema_file(root.open_regular(SCHEMA_FILENAME)?)?,
3472            None => read_schema(&dir)?,
3473        };
3474        // A standalone schema change publishes the schema before its matching
3475        // manifest. If the process dies in that narrow window, the newer,
3476        // fully validated schema is authoritative and the manifest identity is
3477        // repaired only after the rest of open has passed preflight. A manifest
3478        // claiming a schema newer than the durable schema remains corruption.
3479        let schema_manifest_repair = manifest.schema_id < schema.schema_id;
3480        let runs_root = match ctx.root_guard.as_ref() {
3481            Some(root) => Some(Arc::new(root.open_directory(RUNS_DIR)?)),
3482            None => None,
3483        };
3484        let idx_root = match ctx.root_guard.as_ref() {
3485            Some(root) => match root.open_directory(global_idx::IDX_DIR) {
3486                Ok(root) => Some(Arc::new(root)),
3487                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
3488                Err(error) => return Err(error.into()),
3489            },
3490            None => None,
3491        };
3492        schema.validate_auto_increment()?;
3493        schema.validate_defaults()?;
3494        schema.validate_ai()?;
3495        for index in &schema.indexes {
3496            index.validate_options()?;
3497        }
3498        let replay_epoch = Epoch(manifest.current_epoch);
3499        let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), manifest.table_id);
3500        let private_replayed = if ctx.shared.is_none() {
3501            match latest_wal_segment(&dir.join(WAL_DIR))? {
3502                Some(path) => {
3503                    let cipher = wal_dek.as_ref().map(|dk| make_cipher(dk));
3504                    crate::wal::replay_with_cipher(path, cipher)?
3505                }
3506                None => Vec::new(),
3507            }
3508        } else {
3509            Vec::new()
3510        };
3511        if ctx.shared.is_none() {
3512            preflight_standalone_open(
3513                &dir,
3514                runs_root.as_deref(),
3515                idx_root.as_deref(),
3516                &manifest,
3517                &schema,
3518                &private_replayed,
3519                ctx.kek.clone(),
3520            )?;
3521        }
3522        let next_run_id = derive_next_run_id(
3523            &dir,
3524            runs_root.as_deref(),
3525            &manifest.runs,
3526            &manifest.retiring,
3527        )?;
3528        // B1: a mounted table has no private WAL — its committed records live in
3529        // the shared WAL and are replayed by `Database::recover_shared_wal`. A
3530        // standalone table replays + reopens its own `_wal/` segment here.
3531        let (wal, replayed, current_txn_id) = match ctx.shared.clone() {
3532            Some(s) => (WalSink::Shared(s), Vec::new(), 0),
3533            None => {
3534                let replayed = private_replayed;
3535                // Never truncate the only durable recovery source. Re-encode
3536                // every valid frame into a synced staging segment, then publish
3537                // it atomically under the next segment number. A crash before
3538                // publication leaves the old segment authoritative; a crash
3539                // afterward finds the complete replacement as the latest WAL.
3540                let wal_dir = dir.join(WAL_DIR);
3541                crate::durable_file::create_directory_all(&wal_dir)?;
3542                let segment = next_wal_segment(&wal_dir)?;
3543                let segment_no = wal_segment_number(&segment).unwrap_or(0);
3544                let temporary = wal_dir.join(format!(
3545                    ".recovery-{}-{}-{segment_no:06}.tmp",
3546                    std::process::id(),
3547                    std::time::SystemTime::now()
3548                        .duration_since(std::time::UNIX_EPOCH)
3549                        .unwrap_or_default()
3550                        .as_nanos()
3551                ));
3552                let mut w = Wal::create_with_cipher(
3553                    &temporary,
3554                    replay_epoch,
3555                    wal_dek.as_ref().map(|dk| make_cipher(dk)),
3556                    segment_no,
3557                )?;
3558                for record in &replayed {
3559                    w.append_txn(record.txn_id, record.op.clone())?;
3560                }
3561                let mut w = w.publish_as(segment)?;
3562                w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3563                let next_txn_id = replayed
3564                    .iter()
3565                    .map(|record| record.txn_id)
3566                    .filter(|txn_id| *txn_id != crate::wal::SYSTEM_TXN_ID)
3567                    .max()
3568                    .map(|txn_id| txn_id.checked_add(1).unwrap_or(0))
3569                    .unwrap_or(1);
3570                (WalSink::Private(w), replayed, next_txn_id)
3571            }
3572        };
3573
3574        let mut memtable = Memtable::new();
3575        let mut allocator = RowIdAllocator::new(manifest.next_row_id);
3576        let persisted_epoch = manifest.current_epoch;
3577        // Seed the auto-increment counter from the manifest. `auto_inc_next == 0`
3578        // means unseeded (fresh table, or a legacy manifest migrated forward) —
3579        // the first allocation scans `max(PK)` to avoid colliding with existing
3580        // rows. WAL replay (below) and `recover_apply` additionally bump `next`
3581        // past replayed ids without marking it seeded, so the scan still covers
3582        // any rows that were already flushed to sorted runs.
3583        let mut auto_inc = resolve_auto_inc(&schema).map(|mut s| {
3584            s.next = manifest.auto_inc_next;
3585            s.seeded = manifest.auto_inc_next > 0;
3586            s
3587        });
3588
3589        // 1. Replay is two-phase and TxnCommit-gated: data records (Put/Delete)
3590        //    are staged per `txn_id` and only applied when a durable
3591        //    `TxnCommit{epoch}` for that txn is seen. Uncommitted / aborted /
3592        //    torn-tail txns are discarded. Indexing happens AFTER loading any
3593        //    checkpoint / run data (below) so the newer replayed versions
3594        //    overwrite the older run versions in the HOT index.
3595        let mut staged_puts: HashMap<u64, Vec<Row>> = HashMap::new();
3596        let mut staged_deletes: HashMap<u64, Vec<RowId>> = HashMap::new();
3597        let mut staged_truncates: std::collections::HashSet<u64> = std::collections::HashSet::new();
3598        let mut replayed_puts: std::collections::BTreeMap<Epoch, Vec<Row>> =
3599            std::collections::BTreeMap::new();
3600        let mut replayed_deletes: Vec<(RowId, Epoch)> = Vec::new();
3601        let mut recovered_epoch = manifest.current_epoch;
3602        let mut recovered_manifest_dirty = schema_manifest_repair;
3603        let mut saw_delete = false;
3604        for record in replayed {
3605            let txn_id = record.txn_id;
3606            match record.op {
3607                Op::Put { rows, .. } => {
3608                    let rows: Vec<Row> = bincode::deserialize(&rows)?;
3609                    for row in &rows {
3610                        allocator.advance_to(row.row_id)?;
3611                        if let Some(ai) = auto_inc.as_mut() {
3612                            if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
3613                                let next = n.checked_add(1).ok_or_else(|| {
3614                                    MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
3615                                })?;
3616                                if next > ai.next {
3617                                    ai.next = next;
3618                                }
3619                            }
3620                        }
3621                    }
3622                    staged_puts.entry(txn_id).or_default().extend(rows);
3623                }
3624                Op::Delete { row_ids, .. } => {
3625                    staged_deletes.entry(txn_id).or_default().extend(row_ids);
3626                }
3627                Op::TxnCommit { epoch, .. } => {
3628                    let commit_epoch = Epoch(epoch);
3629                    recovered_epoch = recovered_epoch.max(epoch);
3630                    if staged_truncates.remove(&txn_id) && commit_epoch.0 > manifest.flushed_epoch {
3631                        memtable = Memtable::new();
3632                        replayed_puts.clear();
3633                        replayed_deletes.clear();
3634                        manifest.runs.clear();
3635                        manifest.retiring.clear();
3636                        manifest.live_count = 0;
3637                        manifest.global_idx_epoch = 0;
3638                        manifest.current_epoch = manifest.current_epoch.max(epoch);
3639                        recovered_manifest_dirty = true;
3640                        saw_delete = true;
3641                    }
3642                    if let Some(puts) = staged_puts.remove(&txn_id) {
3643                        if commit_epoch.0 > manifest.flushed_epoch {
3644                            for row in &puts {
3645                                memtable.upsert(row.clone());
3646                            }
3647                            replayed_puts.entry(commit_epoch).or_default().extend(puts);
3648                        }
3649                    }
3650                    if let Some(dels) = staged_deletes.remove(&txn_id) {
3651                        saw_delete = true;
3652                        if commit_epoch.0 > manifest.flushed_epoch {
3653                            for rid in dels {
3654                                memtable.tombstone(rid, commit_epoch);
3655                                replayed_deletes.push((rid, commit_epoch));
3656                            }
3657                        }
3658                    }
3659                }
3660                Op::TxnAbort => {
3661                    staged_puts.remove(&txn_id);
3662                    staged_deletes.remove(&txn_id);
3663                    staged_truncates.remove(&txn_id);
3664                }
3665                Op::TruncateTable { .. } => {
3666                    staged_puts.remove(&txn_id);
3667                    staged_deletes.remove(&txn_id);
3668                    staged_truncates.insert(txn_id);
3669                }
3670                Op::ExternalTableState { .. }
3671                | Op::Flush { .. }
3672                | Op::Ddl(_)
3673                | Op::BeforeImage { .. }
3674                | Op::CommitTimestamp { .. }
3675                | Op::SpilledRows { .. } => {}
3676            }
3677        }
3678
3679        let rcache_dir = dir.join(RCACHE_DIR);
3680        let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3681        let initial_view = ReadGeneration::empty(&schema);
3682        let mut db = Self {
3683            dir,
3684            _root_guard: ctx.root_guard,
3685            runs_root,
3686            idx_root,
3687            table_id: manifest.table_id,
3688            name: ctx.table_name.unwrap_or_default(),
3689            auth: ctx.auth,
3690            read_only: ctx.read_only,
3691            durable_commit_failed: false,
3692            wal,
3693            memtable,
3694            mutable_run: MutableRun::new(),
3695            mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3696            compaction_zstd_level: 3,
3697            allocator,
3698            epoch: ctx.epoch,
3699            data_generation: persisted_epoch,
3700            schema,
3701            hot: HotIndex::new(),
3702            kek: ctx.kek,
3703            column_keys,
3704            run_refs: manifest.runs.clone(),
3705            retiring: manifest.retiring.clone(),
3706            next_run_id,
3707            sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3708            current_txn_id,
3709            pending_private_mutations: false,
3710            bitmap: HashMap::new(),
3711            ann: HashMap::new(),
3712            fm: HashMap::new(),
3713            sparse: HashMap::new(),
3714            minhash: HashMap::new(),
3715            learned_range: Arc::new(HashMap::new()),
3716            pk_by_row: ReversePkMap::new(),
3717            pinned: BTreeMap::new(),
3718            live_count: manifest.live_count,
3719            reservoir: crate::reservoir::Reservoir::default(),
3720            reservoir_complete: false,
3721            had_deletes: saw_delete
3722                || manifest.runs.iter().map(|run| run.row_count).sum::<u64>()
3723                    != manifest.live_count,
3724            recent_delete_preimages: HashMap::new(),
3725            run_row_id_ranges: HashMap::new(),
3726            agg_cache: Arc::new(HashMap::new()),
3727            global_idx_epoch: manifest.global_idx_epoch,
3728            indexes_complete: true,
3729            index_build_policy: IndexBuildPolicy::default(),
3730            pk_by_row_complete: false,
3731            flushed_epoch: manifest.flushed_epoch,
3732            page_cache: ctx.page_cache,
3733            decoded_cache: ctx.decoded_cache,
3734            verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3735            run_readers: Arc::new(parking_lot::Mutex::new(HashMap::new())),
3736            snapshots: ctx.snapshots,
3737            commit_lock: ctx.commit_lock,
3738            result_cache: {
3739                let cache = ResultCache::new()
3740                    .with_dir(rcache_dir.clone())
3741                    .with_cache_dek(cache_dek.clone());
3742                let metrics = LookupMetrics::default();
3743                let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3744                match spawn_persistent_cache_worker(rcache_dir.clone(), cache_dek.clone(), metrics)
3745                {
3746                    Ok((writer, handle, completion_rx)) => {
3747                        cache_arc
3748                            .lock()
3749                            .install_persistent_writer(writer, handle, completion_rx);
3750                    }
3751                    // Spawn / I/O-setup failure: publication is disabled and
3752                    // query-path persists are skipped with a metric (REM-D
3753                    // §8.5) — never a synchronous query-thread write.
3754                    Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3755                }
3756                cache_arc
3757            },
3758            pending_delete_rids: roaring::RoaringBitmap::new(),
3759            pending_put_cols: std::collections::HashSet::new(),
3760            pending_rows: Vec::new(),
3761            pending_rows_auto_inc: Vec::new(),
3762            pending_dels: Vec::new(),
3763            pending_truncate: None,
3764            wal_dek,
3765            auto_inc,
3766            ttl: manifest.ttl,
3767            pins: Arc::new(crate::retention::PinRegistry::new()),
3768            published: Arc::new(ArcSwap::from_pointee(initial_view)),
3769            read_generation_pin: None,
3770            lookup_metrics: LookupMetrics::default(),
3771            run_lookup: RunLookupState::default(),
3772        };
3773
3774        // Advance the (possibly shared) epoch authority to this table's manifest
3775        // epoch so rebuild/index reads below observe the recovered watermark.
3776        db.epoch.advance_recovered(Epoch(recovered_epoch));
3777
3778        // 2. Fast path: load the persisted global-index checkpoint (Phase 9.1).
3779        //    Valid only when its embedded epoch matches the manifest-endorsed
3780        //    `global_idx_epoch` and every run was created at or before it, so the
3781        //    checkpoint covers all run data. Otherwise rebuild from the runs.
3782        let checkpoint = match db.idx_root.as_deref() {
3783            Some(root) => {
3784                global_idx::read_root(root, db.table_id, &db.schema, db.idx_dek().as_deref())?
3785            }
3786            None => global_idx::read(&db.dir, db.table_id, &db.schema, db.idx_dek().as_deref())?,
3787        };
3788        let checkpoint_valid = checkpoint.as_ref().is_some_and(|c| {
3789            c.epoch_built == manifest.global_idx_epoch
3790                && manifest.global_idx_epoch > 0
3791                && manifest
3792                    .runs
3793                    .iter()
3794                    .all(|r| r.epoch_created <= manifest.global_idx_epoch)
3795        });
3796        if let Some(loaded) = checkpoint {
3797            if checkpoint_valid {
3798                db.hot = loaded.hot;
3799                db.bitmap = loaded.bitmap;
3800                db.ann = loaded.ann;
3801                db.fm = loaded.fm;
3802                db.sparse = loaded.sparse;
3803                db.minhash = loaded.minhash;
3804                db.learned_range = Arc::new(loaded.learned_range);
3805                // Checkpoints omit empty secondary indexes (e.g. ANN with no
3806                // vectors yet). Re-seed any schema-declared maps that were
3807                // skipped so retrievers like ANN do not fail with "has no
3808                // ANN index" after reopen.
3809                let (bitmap0, ann0, fm0, sparse0, minhash0) = empty_indexes(&db.schema);
3810                for (cid, idx) in bitmap0 {
3811                    db.bitmap.entry(cid).or_insert(idx);
3812                }
3813                for (cid, idx) in ann0 {
3814                    db.ann.entry(cid).or_insert(idx);
3815                }
3816                for (cid, idx) in fm0 {
3817                    db.fm.entry(cid).or_insert(idx);
3818                }
3819                for (cid, idx) in sparse0 {
3820                    db.sparse.entry(cid).or_insert(idx);
3821                }
3822                for (cid, idx) in minhash0 {
3823                    db.minhash.entry(cid).or_insert(idx);
3824                }
3825                // `pk_by_row` stays lazy (`pk_by_row_complete == false`): the
3826                // first delete rebuilds it from the loaded HOT.
3827            }
3828        }
3829        if !checkpoint_valid {
3830            let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&db.schema);
3831            db.bitmap = bitmap;
3832            db.ann = ann;
3833            db.fm = fm;
3834            db.sparse = sparse;
3835            db.minhash = minhash;
3836            db.rebuild_indexes_from_runs()?;
3837            db.build_learned_ranges()?;
3838        }
3839
3840        // 3. Replay overlay: PK winner/loser tombstone maintenance always
3841        //    runs (rebuild is per-RowId and does not apply same-PK replace
3842        //    tombstones). Index the replayed rows only when the checkpoint
3843        //    was loaded — a full rebuild already folded the memtable, which
3844        //    already contains these rows. Re-inserting would double Sparse
3845        //    scores and duplicate ANN nodes.
3846        for (epoch, group) in replayed_puts {
3847            let (losers, winner_pks) = db.partition_pk_winners(&group);
3848            for (key, &row_id) in &winner_pks {
3849                if let Some(old_rid) = db.hot.get(key) {
3850                    if old_rid != row_id {
3851                        db.tombstone_row(old_rid, epoch, None, false);
3852                    }
3853                }
3854            }
3855            for &loser_rid in &losers {
3856                db.tombstone_row(loser_rid, epoch, None, false);
3857            }
3858            for (key, row_id) in winner_pks {
3859                db.insert_hot_pk(key, row_id);
3860            }
3861            if db.schema.primary_key().is_none() {
3862                for r in &group {
3863                    db.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
3864                }
3865            }
3866            if checkpoint_valid {
3867                for r in &group {
3868                    if !losers.contains(&r.row_id) {
3869                        db.index_row(r);
3870                    }
3871                }
3872            }
3873        }
3874        // Apply replayed deletes after the puts: a delete targets a specific row
3875        // id and only removes the HOT entry if it still points to that id, so a
3876        // newer upsert for the same PK is not accidentally erased.
3877        for (rid, epoch) in &replayed_deletes {
3878            db.remove_hot_for_row(*rid, *epoch);
3879        }
3880
3881        if recovered_manifest_dirty {
3882            let rows = db.visible_rows(Snapshot::unbounded())?;
3883            db.live_count = rows.len() as u64;
3884            db.persist_manifest(Epoch(recovered_epoch))?;
3885        }
3886
3887        // The reservoir stays lazy (`reservoir_complete == false`, set above):
3888        // rebuilding it means materializing every visible row, which no plain
3889        // open/insert/update/delete needs. `ensure_reservoir_complete` pays
3890        // that cost on the first `approx_aggregate` call instead.
3891        // Load the persistent result-cache tier (hardening (b)) so fine-grained
3892        // invalidation resumes across restart.
3893        let identity = crate::result_cache::PersistentCacheIdentity {
3894            table_id: db.table_id,
3895            schema_id: db.schema.schema_id,
3896            logical_generation: db.epoch.visible().0,
3897        };
3898        db.result_cache.lock().load_persistent(identity);
3899        // Populate RowId range directory so point get can skip irrelevant runs.
3900        db.refresh_run_row_id_ranges();
3901        // Issue 4 / spec §8.4 step 3 — try to install the row-to-run lookup
3902        // directory from the sharded checkpoint. Failure is non-fatal: the
3903        // open succeeds, the read path falls back to range scans, and the
3904        // next flush/compaction rebuilds + publishes a fresh directory.
3905        db.load_run_lookup_directory();
3906        Ok(db)
3907    }
3908
3909    /// Best-effort load of the run-lookup directory on open. Tries the
3910    /// sharded checkpoint first; if it's missing, corrupt, or stale, the
3911    /// in-memory state is left in `complete = false` and the existing
3912    /// range-scan fallback stays the read path's safety net.
3913    fn load_run_lookup_directory(&mut self) {
3914        let active_runs = self.run_refs.clone();
3915        let schema_id = self.schema.schema_id;
3916        let run_generation = active_runs.len() as u64;
3917        let index_generation = self.global_idx_epoch;
3918        let fingerprint = crate::run_lookup::compute_fingerprint(
3919            &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
3920            schema_id,
3921            index_generation,
3922            run_generation,
3923            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
3924        );
3925        // Build a candidate from the sharded checkpoint in `_runs/`.
3926        let runs_dir = match self.runs_root.as_deref() {
3927            Some(root) => match root.io_path() {
3928                Ok(p) => p,
3929                Err(_) => self.dir.join(RUNS_DIR),
3930            },
3931            None => self.dir.join(RUNS_DIR),
3932        };
3933        match crate::run_lookup::RunLookupDirectory::read_checkpoint_sharded(&runs_dir, fingerprint)
3934        {
3935            Ok(dir) => {
3936                self.run_lookup = RunLookupState {
3937                    directory: Some(std::sync::Arc::new(dir)),
3938                    fingerprint,
3939                    complete: true,
3940                };
3941            }
3942            Err(error) => {
3943                self.lookup_metrics
3944                    .directory_incomplete
3945                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3946                self.lookup_metrics
3947                    .directory_lookup_fallback
3948                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3949                self.run_lookup = RunLookupState {
3950                    directory: None,
3951                    fingerprint,
3952                    complete: false,
3953                };
3954                // Trace the load failure so smoke tests catch silent fallbacks
3955                // during the closure audit. The error kind is enough; full
3956                // path is preserved by the trace.
3957                let _ = error;
3958            }
3959        }
3960    }
3961
3962    /// Rebuild `reservoir` from every visible row if it isn't already
3963    /// complete (lazy — same pattern as [`Self::ensure_indexes_complete`]).
3964    /// Open and WAL replay leave the reservoir stale rather than eagerly
3965    /// paying a full-table scan; this pays it once, on the first
3966    /// [`Self::approx_aggregate`] call.
3967    fn ensure_reservoir_complete(&mut self) -> Result<()> {
3968        if self.reservoir_complete {
3969            return Ok(());
3970        }
3971        self.rebuild_reservoir()?;
3972        self.reservoir_complete = true;
3973        Ok(())
3974    }
3975
3976    /// Repopulate the reservoir sample from all visible rows (used on open so a
3977    /// reopened table has an analytics sample without further inserts).
3978    fn rebuild_reservoir(&mut self) -> Result<()> {
3979        let snap = self.snapshot();
3980        let rows = self.visible_rows(snap)?;
3981        self.reservoir.reset();
3982        for r in rows {
3983            self.reservoir.offer(r.row_id.0);
3984        }
3985        Ok(())
3986    }
3987
3988    /// Rebuild HOT + every secondary index from durable runs, the mutable run,
3989    /// and the memtable. Safe to call online; used by recovery tooling and the
3990    /// public [`crate::Database::rebuild_indexes`] path after index desync.
3991    pub fn rebuild_indexes(&mut self) -> Result<()> {
3992        self.rebuild_indexes_from_runs_inner(None)
3993    }
3994
3995    /// Test-only fault-injection seam: install an arbitrary HOT mapping.
3996    ///
3997    /// Bypasses the per-row index maintenance path so regression tests for the
3998    /// HOT fallback (issue 2) can deliberately corrupt the HOT map and assert
3999    /// that the [`Self::resolve_pk_with_hot_fallback`] path still returns the
4000    /// correct, scanned row instead of the mismatched mapped one.
4001    ///
4002    /// Always public so integration tests in `tests/` can reach it; the
4003    /// `__` prefix + the explicit "for_test" name is the convention used
4004    /// elsewhere in the codebase to discourage production callers.
4005    pub fn __force_hot_map_for_test(&mut self, pk_bytes: &[u8], row_id: RowId) {
4006        self.hot.insert(pk_bytes.to_vec(), row_id);
4007    }
4008
4009    /// Test-only helper: drop a single HOT mapping so a test can simulate
4010    /// the missing-mapping fallback path without tearing down the table.
4011    pub fn hot_for_test_remove(&mut self, pk_bytes: &[u8]) {
4012        self.hot.remove(pk_bytes);
4013    }
4014
4015    /// Test-only helper: force the `indexes_complete` flag to `false` so a
4016    /// test can drive the `IndexIncomplete` branch of the fallback path.
4017    pub fn set_indexes_incomplete_for_test(&mut self) {
4018        self.indexes_complete = false;
4019    }
4020
4021    /// Test-only helper: bump the `hot_checkpoint_rejected_total` counter by
4022    /// one so a test can drive the `CheckpointRejected` path. The counter
4023    /// is `pub(crate)` so the helper bumps it directly.
4024    pub fn bump_hot_checkpoint_rejected_for_test(&self) {
4025        self.lookup_metrics
4026            .hot_checkpoint_rejected_total
4027            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4028    }
4029
4030    /// Test-only seam: write `rows` as a synthetic immutable run and link it
4031    /// into the active run set so point-directory tests can control exact
4032    /// (epoch, HLC) stamps and run topology — the public write path stamps
4033    /// every commit with `hlc.now()`, so neither is injectable otherwise.
4034    /// Rows are sorted by `(RowId, epoch)` before writing (sorted-run layout
4035    /// requires ascending `RowId`); returns the allocated run id.
4036    pub fn __install_run_for_test(&mut self, rows: &[Row]) -> Result<u128> {
4037        let mut rows = rows.to_vec();
4038        rows.sort_by_key(|r| (r.row_id, r.committed_epoch));
4039        let epoch = rows
4040            .iter()
4041            .map(|r| r.committed_epoch)
4042            .max()
4043            .unwrap_or(Epoch::ZERO);
4044        let run_id = self.alloc_run_id()?;
4045        let path = self.run_path(run_id);
4046        if let Some(parent) = path.parent() {
4047            std::fs::create_dir_all(parent)
4048                .map_err(|e| MongrelError::Other(format!("create runs dir: {e}")))?;
4049        }
4050        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
4051        if let Some(kek) = &self.kek {
4052            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
4053        }
4054        let header = match self.create_run_file(run_id)? {
4055            Some(file) => writer.write_file(file, &rows)?,
4056            None => writer.write(&path, &rows)?,
4057        };
4058        self.run_refs.push(RunRef {
4059            run_id: run_id as u128,
4060            level: 0,
4061            epoch_created: epoch.0,
4062            row_count: header.row_count,
4063        });
4064        self.run_row_id_ranges
4065            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
4066        Ok(run_id as u128)
4067    }
4068
4069    /// Test-only seam: rebuild and publish the run-lookup directory over the
4070    /// current active run set so directory-assisted `Table::get` tests can
4071    /// drive the synthetic topologies installed via
4072    /// [`Self::__install_run_for_test`].
4073    pub fn __rebuild_run_lookup_for_test(&mut self) -> Result<()> {
4074        self.publish_run_lookup_directory()
4075    }
4076
4077    /// Test-only seam: toggle the directory-assisted point-lookup path. With
4078    /// `complete == false`, `Table::get` takes the `UnavailableOrStale`
4079    /// branch and opens every active run — the forced full-run oracle the
4080    /// point-directory correctness tests compare against. The installed
4081    /// directory is kept, so `complete == true` restores the
4082    /// directory-assisted path.
4083    pub fn __set_run_lookup_complete_for_test(&mut self, complete: bool) {
4084        self.run_lookup.complete = complete;
4085    }
4086
4087    pub(crate) fn rebuild_indexes_from_runs(&mut self) -> Result<()> {
4088        self.rebuild_indexes_from_runs_inner(None)
4089    }
4090
4091    /// Scan overlay + runs for a live row whose PK encode matches `lookup`.
4092    /// Used when the HOT map misses a key that may still exist on disk.
4093    ///
4094    /// Returns `(result, reason)`. The caller in `resolve_condition_with_allowed`
4095    /// is the sole authority for `record_hot_fallback_reason` so that the HOT
4096    /// hit branch (which already recorded e.g. `HistoricalSnapshot`) does not
4097    /// double-bookkeep when it delegates the actual scan here. The returned
4098    /// reason is always set:
4099    ///   - tombstone observed at `snapshot` -> `Tombstone`
4100    ///   - live row found on disk              -> `MissingMapping`
4101    ///   - nothing found                       -> `MissingMapping` (a genuine
4102    ///     miss is still a HOT-fallback event for observability).
4103    ///
4104    /// Correctness contract:
4105    ///   - obeys the full `Snapshot` (epoch + HLC) through `visible_*`
4106    ///     iterators and `range_scan_i64`;
4107    ///   - ignores deleted rows in the overlay and durable runs;
4108    ///   - ignores TTL-expired rows via [`Self::row_expired_at`];
4109    ///   - compares the **materialized** PK against the requested encoded
4110    ///     key (post-HMAC tokenization) so that HMAC-eq columns and bytes
4111    ///     PKs both produce exact matches;
4112    ///   - dedups the resulting `RowId` set so a row referenced from
4113    ///     multiple paths (overlay + run, multi-run) is reported once;
4114    ///   - works across the memtable, mutable-run, and every sorted run;
4115    ///   - preserves historical snapshots — pinned-snapshot readers see the
4116    ///     historical row, not the latest.
4117    fn pk_equality_fallback(
4118        &self,
4119        pk_column_id: u16,
4120        lookup: &[u8],
4121        snapshot: Snapshot,
4122    ) -> Result<(RowIdSet, crate::trace::HotFallbackReason)> {
4123        let mut tombstone_hit = false;
4124        let mut overlay_versions = 0u64;
4125        let now_nanos = unix_nanos_now();
4126        // Overlay first (newest versions).
4127        for row in self.memtable.visible_versions_at(snapshot) {
4128            overlay_versions += 1;
4129            self.lookup_metrics
4130                .hot_lookup_fallback_overlay_rows
4131                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4132            if row.deleted {
4133                tombstone_hit = true;
4134                continue;
4135            }
4136            if self.row_expired_at(&row, now_nanos) {
4137                continue;
4138            }
4139            if let Some(pk_val) = row.columns.get(&pk_column_id) {
4140                if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4141                    self.lookup_metrics
4142                        .hot_fallback_overlay_versions_total
4143                        .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4144                    return Ok((
4145                        RowIdSet::one(row.row_id.0),
4146                        crate::trace::HotFallbackReason::MissingMapping,
4147                    ));
4148                }
4149            }
4150        }
4151        for row in self.mutable_run.visible_versions_at(snapshot) {
4152            overlay_versions += 1;
4153            self.lookup_metrics
4154                .hot_lookup_fallback_overlay_rows
4155                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4156            if row.deleted {
4157                tombstone_hit = true;
4158                continue;
4159            }
4160            if self.row_expired_at(&row, now_nanos) {
4161                continue;
4162            }
4163            if let Some(pk_val) = row.columns.get(&pk_column_id) {
4164                if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4165                    self.lookup_metrics
4166                        .hot_fallback_overlay_versions_total
4167                        .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4168                    return Ok((
4169                        RowIdSet::one(row.row_id.0),
4170                        crate::trace::HotFallbackReason::MissingMapping,
4171                    ));
4172                }
4173            }
4174        }
4175        // Durable runs: prefer int64 point range when the encoded key is 8
4176        // bytes of big-endian i64 (the common Kit PK shape).
4177        if lookup.len() == 8 {
4178            if let Ok(arr) = <[u8; 8]>::try_from(lookup) {
4179                let n = i64::from_be_bytes(arr);
4180                let result = self.range_scan_i64(pk_column_id, n, n, snapshot)?;
4181                self.lookup_metrics
4182                    .hot_lookup_fallback_runs
4183                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4184                // Count this as a considered run for the lookup-metrics
4185                // invariant (every HOT fallback must record exactly one reason
4186                // and advance the run accounting by at least one).
4187                self.lookup_metrics
4188                    .hot_fallback_runs_considered_total
4189                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4190                self.lookup_metrics
4191                    .hot_fallback_overlay_versions_total
4192                    .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4193                let reason = if result.is_empty() {
4194                    if tombstone_hit {
4195                        crate::trace::HotFallbackReason::Tombstone
4196                    } else {
4197                        crate::trace::HotFallbackReason::MissingMapping
4198                    }
4199                } else {
4200                    crate::trace::HotFallbackReason::MissingMapping
4201                };
4202                return Ok((result, reason));
4203            }
4204        }
4205        // Bytes / other PK types: linear visible scan of runs is expensive but
4206        // correctness-first for rare HOT misses.
4207        let mut found: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
4208        let overlay = self.overlay_rid_set(snapshot);
4209        let mut runs_considered = 0u64;
4210        for rr in &self.run_refs {
4211            runs_considered += 1;
4212            self.lookup_metrics
4213                .hot_lookup_fallback_runs
4214                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4215            let mut reader = self.open_reader(rr.run_id)?;
4216            for row in reader.visible_versions_at(snapshot)? {
4217                if overlay.contains(&row.row_id.0) || row.deleted {
4218                    if row.deleted {
4219                        tombstone_hit = true;
4220                    }
4221                    continue;
4222                }
4223                if self.row_expired_at(&row, now_nanos) {
4224                    continue;
4225                }
4226                if let Some(pk_val) = row.columns.get(&pk_column_id) {
4227                    if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4228                        found.insert(row.row_id.0);
4229                    }
4230                }
4231            }
4232        }
4233        let reason = if tombstone_hit {
4234            crate::trace::HotFallbackReason::Tombstone
4235        } else {
4236            // Found or not: the HOT entry was missing, so this is a mapping
4237            // miss regardless of whether the row exists on disk.
4238            crate::trace::HotFallbackReason::MissingMapping
4239        };
4240        self.lookup_metrics
4241            .hot_fallback_overlay_versions_total
4242            .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4243        self.lookup_metrics
4244            .hot_fallback_runs_considered_total
4245            .fetch_add(runs_considered, std::sync::atomic::Ordering::Relaxed);
4246        Ok((RowIdSet::from_unsorted(found.into_iter().collect()), reason))
4247    }
4248
4249    /// TODO §5.1/§5.2 — record a HOT fallback reason. Increments the
4250    /// per-reason counter, the global `hot_lookup_fallback` total, the
4251    /// per-query trace, and the active-call duration bucket.
4252    fn record_hot_fallback_reason(&self, reason: crate::trace::HotFallbackReason) {
4253        let idx = hot_fallback_reason_index(reason);
4254        self.lookup_metrics.hot_fallback_reasons[idx]
4255            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4256        self.lookup_metrics
4257            .hot_lookup_fallback
4258            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4259        crate::trace::QueryTrace::record(|t| {
4260            t.hot_lookup_attempted = true;
4261            t.hot_lookup_hit = false;
4262            t.hot_fallback_reason = Some(reason.as_str());
4263        });
4264    }
4265
4266    fn rebuild_indexes_from_runs_inner(
4267        &mut self,
4268        control: Option<&crate::ExecutionControl>,
4269    ) -> Result<()> {
4270        // S1C-004: online index rebuild pins the current visible epoch so
4271        // version GC cannot reclaim rows while the rebuild scans them.
4272        let _index_build_pin = Arc::clone(self.pin_registry()).pin(
4273            crate::retention::PinSource::OnlineIndexBuild,
4274            self.current_epoch(),
4275        );
4276        self.hot = HotIndex::new();
4277        self.pk_by_row.clear();
4278        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
4279        self.bitmap = bitmap;
4280        self.ann = ann;
4281        self.fm = fm;
4282        self.sparse = sparse;
4283        self.minhash = minhash;
4284        // REM-001: rebuild the current-state index from a *globally merged*
4285        // candidate set rather than indexing each run's visible versions in
4286        // iteration order. For every RowId we collect the candidate from each
4287        // run + the overlay tiers, select the winner using full version
4288        // authority (HLC when both sides are stamped), and index the winner
4289        // exactly once. Tombstones drop the entry entirely. Physical run
4290        // order is no longer a substitute for HLC authority.
4291        //
4292        // TTL-expired rows ARE indexed (HOT and every secondary), matching
4293        // what incremental maintenance would have produced had the rows been
4294        // written after the rebuild: expiry is a query-time eligibility
4295        // filter ([`Self::row_expired_at`]), not an index-content rule.
4296        // Skipping them here would lose the HOT entry a later same-PK put
4297        // needs to tombstone the old row, and would strand the row's
4298        // secondary postings if the TTL policy is ever cleared or relaxed —
4299        // both observed as stale rows resurfacing after `clear_ttl`.
4300        //
4301        // Visibility spans every epoch — a row just upserted in the memtable
4302        // lives at `pending_epoch = visible + 1` (no commit yet) so a snapshot
4303        // pinned at `visible` would silently hide it. Use [`Snapshot::unbounded`]
4304        // so the fold observes every durable row, regardless of whether the
4305        // caller has committed since the upsert.
4306        let snapshot = Snapshot::unbounded();
4307        let ttl_now = unix_nanos_now();
4308        let mut scanned = 0_usize;
4309        let mut winners: HashMap<RowId, (VersionStamp, Row)> = HashMap::new();
4310        let fold =
4311            |row: Row, winners: &mut HashMap<RowId, (VersionStamp, Row)>, scanned: &mut usize| {
4312                *scanned += 1;
4313                let stamp = VersionStamp {
4314                    epoch: row.committed_epoch,
4315                    commit_ts: row.commit_ts,
4316                };
4317                winners
4318                    .entry(row.row_id)
4319                    .and_modify(|entry| {
4320                        if stamp.is_newer_than(entry.0) {
4321                            *entry = (stamp, row.clone());
4322                        }
4323                    })
4324                    .or_insert((stamp, row));
4325            };
4326        for rr in self.run_refs.clone() {
4327            if let Some(control) = control {
4328                control.checkpoint()?;
4329            }
4330            let mut reader = self.open_reader(rr.run_id)?;
4331            for row in reader.visible_versions_at(snapshot)? {
4332                if scanned.is_multiple_of(256) {
4333                    if let Some(control) = control {
4334                        control.checkpoint()?;
4335                    }
4336                }
4337                // Tombstones are still folded: a tombstone's stamp may beat a
4338                // older live row's stamp and clear the entry; folding both
4339                // lets the merge decide the final state per RowId.
4340                fold(row, &mut winners, &mut scanned);
4341            }
4342        }
4343        for (index, row) in self
4344            .memtable
4345            .visible_versions_at(snapshot)
4346            .into_iter()
4347            .enumerate()
4348        {
4349            if index & 255 == 0 {
4350                if let Some(control) = control {
4351                    control.checkpoint()?;
4352                }
4353            }
4354            fold(row, &mut winners, &mut scanned);
4355        }
4356        for (index, row) in self
4357            .mutable_run
4358            .visible_versions_at(snapshot)
4359            .into_iter()
4360            .enumerate()
4361        {
4362            if index & 255 == 0 {
4363                if let Some(control) = control {
4364                    control.checkpoint()?;
4365                }
4366            }
4367            fold(row, &mut winners, &mut scanned);
4368        }
4369        // Partial-index predicates filter the rebuild the same way they
4370        // filter incremental puts (`index_row`): a winner row enters only
4371        // the indexes whose predicate it matches. The HOT map is the
4372        // primary-key map, not a partial index, and is always populated.
4373        let any_predicate = self
4374            .schema
4375            .indexes
4376            .iter()
4377            .any(|idx| idx.predicate.is_some());
4378        let name_to_id: HashMap<&str, u16> = self
4379            .schema
4380            .columns
4381            .iter()
4382            .map(|c| (c.name.as_str(), c.id))
4383            .collect();
4384        for (_rid, (stamp, row)) in winners.drain() {
4385            if row.deleted {
4386                // Tombstone: nothing to index. Anything that was about to be
4387                // promoted under this rid is suppressed by the merge above.
4388                let _ = stamp;
4389                continue;
4390            }
4391            // See the rebuild comment above: TTL-expired winners are indexed
4392            // on purpose; expiry is applied at query time.
4393            let tok_row = self.tokenized_for_indexes(&row);
4394            if !any_predicate {
4395                index_into(
4396                    &self.schema,
4397                    &tok_row,
4398                    &mut self.hot,
4399                    &mut self.bitmap,
4400                    &mut self.ann,
4401                    &mut self.fm,
4402                    &mut self.sparse,
4403                    &mut self.minhash,
4404                );
4405                continue;
4406            }
4407            if let Some(pk_col) = self.schema.primary_key() {
4408                if let Some(pk_val) = tok_row.columns.get(&pk_col.id) {
4409                    self.hot.insert(pk_val.encode_key(), tok_row.row_id);
4410                }
4411            }
4412            let columns_map: HashMap<u16, &Value> =
4413                row.columns.iter().map(|(k, v)| (*k, v)).collect();
4414            for idef in &self.schema.indexes {
4415                if let Some(pred) = &idef.predicate {
4416                    if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4417                        continue;
4418                    }
4419                }
4420                index_into_single(
4421                    idef,
4422                    &self.schema,
4423                    &tok_row,
4424                    &mut self.hot,
4425                    &mut self.bitmap,
4426                    &mut self.ann,
4427                    &mut self.fm,
4428                    &mut self.sparse,
4429                    &mut self.minhash,
4430                );
4431            }
4432        }
4433        // Pin-aware historical discovery for EVERY active pin source that
4434        // compact honors via min_active_snapshot — local pin_snapshot pins,
4435        // Database SnapshotRegistry pins, PinRegistry (backup/replication/
4436        // read-generation/…), and history_floor. Winner-takes-all at the
4437        // unbounded snapshot drops rows only pinned readers still need;
4438        // restore those rows into every secondary (not just Bitmap) so
4439        // retrieve_at / BitmapEq / FmContains still answer at the pin.
4440        // Dedup by RowId: Sparse/MinHash/ANN insert is additive, and the
4441        // same historical rid can be visible at more than one pin epoch.
4442        let pin_epochs = self.active_pin_epochs_for_rebuild();
4443        if !pin_epochs.is_empty() {
4444            let current_snap = Snapshot::at(Epoch(u64::MAX));
4445            let mut historical: HashMap<RowId, Row> = HashMap::new();
4446            for pin_epoch in pin_epochs {
4447                if let Some(control) = control {
4448                    control.checkpoint()?;
4449                }
4450                let pin_snap = Snapshot::at(pin_epoch);
4451                for rr in self.run_refs.clone() {
4452                    if let Some(control) = control {
4453                        control.checkpoint()?;
4454                    }
4455                    let mut reader = self.open_reader(rr.run_id)?;
4456                    for row in reader.visible_rows(pin_epoch)? {
4457                        if row.deleted || self.row_expired_at(&row, ttl_now) {
4458                            continue;
4459                        }
4460                        if historical.contains_key(&row.row_id) {
4461                            continue;
4462                        }
4463                        if self.get(row.row_id, current_snap).is_none() {
4464                            historical.insert(row.row_id, row);
4465                        }
4466                    }
4467                }
4468                for row in self
4469                    .mutable_run
4470                    .visible_versions_at(pin_snap)
4471                    .into_iter()
4472                    .chain(self.memtable.visible_versions_at(pin_snap))
4473                {
4474                    if row.deleted || self.row_expired_at(&row, ttl_now) {
4475                        continue;
4476                    }
4477                    if historical.contains_key(&row.row_id) {
4478                        continue;
4479                    }
4480                    if self.get(row.row_id, current_snap).is_none() {
4481                        historical.insert(row.row_id, row);
4482                    }
4483                }
4484            }
4485            for row in historical.into_values() {
4486                self.index_secondary_membership_only(&row);
4487            }
4488        }
4489        self.recent_delete_preimages.clear();
4490        self.refresh_pk_by_row_from_hot();
4491        Ok(())
4492    }
4493
4494    /// Index every secondary for `row` without touching HOT. Used to restore
4495    /// pin-needed discovery / retrieval keys after a live-only rebuild.
4496    /// Bitmap keeps the HMAC-aware `bitmap_key_for_column` path; other kinds
4497    /// go through `index_into_single` so Sparse/MinHash/ANN/FM match put.
4498    fn index_secondary_membership_only(&mut self, row: &Row) {
4499        if row.deleted {
4500            return;
4501        }
4502        self.index_bitmap_membership_only(row);
4503        let effective = if self.column_keys.is_empty() {
4504            None
4505        } else {
4506            Some(self.tokenized_for_indexes(row))
4507        };
4508        let source = effective.as_ref().unwrap_or(row);
4509        let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4510        let name_to_id: HashMap<&str, u16> = self
4511            .schema
4512            .columns
4513            .iter()
4514            .map(|c| (c.name.as_str(), c.id))
4515            .collect();
4516        for idef in &self.schema.indexes {
4517            if idef.kind == crate::schema::IndexKind::Bitmap {
4518                continue;
4519            }
4520            if let Some(pred) = &idef.predicate {
4521                if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4522                    continue;
4523                }
4524            }
4525            index_into_single(
4526                idef,
4527                &self.schema,
4528                source,
4529                &mut self.hot,
4530                &mut self.bitmap,
4531                &mut self.ann,
4532                &mut self.fm,
4533                &mut self.sparse,
4534                &mut self.minhash,
4535            );
4536        }
4537    }
4538
4539    /// Index Bitmap secondaries for `row` without touching HOT / ANN / etc.
4540    /// Used to restore pin-needed discovery keys after a live-only rebuild.
4541    fn index_bitmap_membership_only(&mut self, row: &Row) {
4542        if row.deleted {
4543            return;
4544        }
4545        let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4546        let name_to_id: HashMap<&str, u16> = self
4547            .schema
4548            .columns
4549            .iter()
4550            .map(|c| (c.name.as_str(), c.id))
4551            .collect();
4552        for idef in &self.schema.indexes {
4553            if idef.kind != crate::schema::IndexKind::Bitmap {
4554                continue;
4555            }
4556            if let Some(pred) = &idef.predicate {
4557                if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4558                    continue;
4559                }
4560            }
4561            if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
4562                if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
4563                    b.insert(key, row.row_id);
4564                }
4565            }
4566        }
4567    }
4568
4569    fn refresh_pk_by_row_from_hot(&mut self) {
4570        self.pk_by_row_complete = true;
4571        if self.schema.primary_key().is_none() {
4572            self.pk_by_row.clear();
4573            return;
4574        }
4575        // `.collect()` drives `HashMap`'s bulk-build `FromIterator` (reserves
4576        // once from the exact-size iterator), instead of growing-and-rehashing
4577        // through a one-at-a-time `insert()` loop — same fix as
4578        // `HotIndex::from_entries`, same hot path (first delete after a put
4579        // streak rebuilds this from the full HOT index).
4580        self.pk_by_row = ReversePkMap::from_entries(
4581            self.hot
4582                .entries()
4583                .into_iter()
4584                .map(|(key, row_id)| (row_id, key)),
4585        );
4586    }
4587
4588    fn insert_hot_pk(&mut self, key: Vec<u8>, row_id: RowId) {
4589        if self.schema.primary_key().is_some() {
4590            self.pk_by_row.insert(row_id, key.clone());
4591        }
4592        self.hot.insert(key, row_id);
4593    }
4594
4595    /// (Re)build per-column learned (PGM) range indexes for `LearnedRange`
4596    /// columns from the single sorted run. Serves `Condition::Range` sub-linearly
4597    /// on the fast path; no-op when there isn't exactly one run.
4598    pub(crate) fn build_learned_ranges(&mut self) -> Result<()> {
4599        self.build_learned_ranges_inner(None)
4600    }
4601
4602    fn build_learned_ranges_inner(
4603        &mut self,
4604        control: Option<&crate::ExecutionControl>,
4605    ) -> Result<()> {
4606        self.learned_range = Arc::new(HashMap::new());
4607        if self.run_refs.len() != 1 {
4608            return Ok(());
4609        }
4610        let cols: Vec<(u16, usize)> = self
4611            .schema
4612            .indexes
4613            .iter()
4614            .filter(|i| i.kind == IndexKind::LearnedRange)
4615            .map(|i| {
4616                (
4617                    i.column_id,
4618                    i.options
4619                        .learned_range
4620                        .as_ref()
4621                        .map(|options| options.epsilon)
4622                        .unwrap_or(16),
4623                )
4624            })
4625            .collect();
4626        if cols.is_empty() {
4627            return Ok(());
4628        }
4629        // Build the PGM from the newest *visible* (non-tombstoned, snapshot-
4630        // eligible) row per RowId. The run's raw column pages also hold prior
4631        // versions and tombstones (deletes are physical, not logical); feeding
4632        // those into the PGM would surface stale rids from `ColumnLearnedRange::
4633        // range` that the engine's overlay merge cannot strip — a leaked
4634        // tombstone is a wrong hit (tested by `churn_oracle_learned_range`).
4635        // REM-001: route through the full-Snapshot visibility API so HLC-pinned
4636        // tables pick the HLC-newer winner across run versions instead of the
4637        // higher-epoch legacy fallback. Same `unbounded` rationale as the
4638        // rebuild — every durable run row must be eligible for the PGM input.
4639        let snapshot = Snapshot::unbounded();
4640        let mut reader = self.open_reader(self.run_refs[0].run_id)?;
4641        let (visible_positions, visible_rids) = reader.visible_positions_with_rids_at(snapshot)?;
4642        let row_ids: Vec<u64> = visible_rids.iter().map(|r| *r as u64).collect();
4643        for (column_index, (cid, epsilon)) in cols.into_iter().enumerate() {
4644            if column_index % 256 == 0 {
4645                if let Some(control) = control {
4646                    control.checkpoint()?;
4647                }
4648            }
4649            let ty = self
4650                .schema
4651                .columns
4652                .iter()
4653                .find(|c| c.id == cid)
4654                .map(|c| c.ty.clone())
4655                .unwrap_or(TypeId::Int64);
4656            match ty {
4657                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
4658                    if let columnar::NativeColumn::Int64 { data, .. } = reader.column_native(cid)? {
4659                        let pairs: Vec<(i64, u64)> = visible_positions
4660                            .iter()
4661                            .zip(row_ids.iter())
4662                            .map(|(&p, &r)| (data[p], r))
4663                            .collect();
4664                        Arc::make_mut(&mut self.learned_range).insert(
4665                            cid,
4666                            ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon),
4667                        );
4668                    }
4669                }
4670                TypeId::Float64 => {
4671                    if let columnar::NativeColumn::Float64 { data, .. } =
4672                        reader.column_native(cid)?
4673                    {
4674                        let pairs: Vec<(f64, u64)> = visible_positions
4675                            .iter()
4676                            .zip(row_ids.iter())
4677                            .map(|(&p, &r)| (data[p], r))
4678                            .collect();
4679                        Arc::make_mut(&mut self.learned_range).insert(
4680                            cid,
4681                            ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon),
4682                        );
4683                    }
4684                }
4685                _ => {}
4686            }
4687        }
4688        Ok(())
4689    }
4690
4691    /// Phase 14.7: if the live indexes are known incomplete (after a bulk
4692    /// ingest that deferred index building — see [`IndexBuildPolicy`]),
4693    /// rebuild them from the runs now. Called lazily by `query` /
4694    /// `query_columns_native` / `flush`; public so external index consumers
4695    /// (SQL scans, joins, PK point lookups on a shared handle) can pay the
4696    /// one-time build before reading a `&self` index view.
4697    pub fn ensure_indexes_complete(&mut self) -> Result<()> {
4698        if self.indexes_complete {
4699            crate::trace::QueryTrace::record(|t| {
4700                t.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4701            });
4702            return Ok(());
4703        }
4704        crate::trace::QueryTrace::record(|t| {
4705            t.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4706        });
4707        self.rebuild_indexes_from_runs()?;
4708        self.build_learned_ranges()?;
4709        self.indexes_complete = true;
4710        let epoch = self.current_epoch();
4711        self.checkpoint_indexes(epoch);
4712        Ok(())
4713    }
4714
4715    /// Rebuild derived indexes cooperatively, publishing their checkpoint only
4716    /// after `before_publish` succeeds.
4717    #[doc(hidden)]
4718    pub fn ensure_indexes_complete_controlled<F>(
4719        &mut self,
4720        control: &crate::ExecutionControl,
4721        before_publish: F,
4722    ) -> Result<bool>
4723    where
4724        F: FnOnce() -> bool,
4725    {
4726        self.ensure_indexes_complete_controlled_with_receipt(control, before_publish)
4727            .map(|(changed, _)| changed)
4728    }
4729
4730    /// Rebuild derived indexes cooperatively and return the exact table
4731    /// snapshot used by the rebuild. No receipt is returned for a no-op.
4732    #[doc(hidden)]
4733    pub fn ensure_indexes_complete_controlled_with_receipt<F>(
4734        &mut self,
4735        control: &crate::ExecutionControl,
4736        before_publish: F,
4737    ) -> Result<(bool, Option<MaintenanceReceipt>)>
4738    where
4739        F: FnOnce() -> bool,
4740    {
4741        if self.indexes_complete {
4742            crate::trace::QueryTrace::record(|trace| {
4743                trace.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4744            });
4745            return Ok((false, None));
4746        }
4747        crate::trace::QueryTrace::record(|trace| {
4748            trace.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4749        });
4750        control.checkpoint()?;
4751        let maintenance_epoch = self.current_epoch();
4752        self.rebuild_indexes_from_runs_inner(Some(control))?;
4753        self.build_learned_ranges_inner(Some(control))?;
4754        control.checkpoint()?;
4755        if !before_publish() {
4756            return Err(MongrelError::Cancelled);
4757        }
4758        self.indexes_complete = true;
4759        self.checkpoint_indexes(maintenance_epoch);
4760        Ok((
4761            true,
4762            Some(MaintenanceReceipt {
4763                epoch: maintenance_epoch,
4764            }),
4765        ))
4766    }
4767
4768    fn pending_epoch(&self) -> Epoch {
4769        Epoch(self.epoch.visible().0 + 1)
4770    }
4771
4772    /// True when this table is mounted in a `Database` (writes route through the
4773    /// shared WAL).
4774    fn is_shared(&self) -> bool {
4775        matches!(self.wal, WalSink::Shared(_))
4776    }
4777
4778    /// Return the current auto-commit txn id, allocating a fresh one from the
4779    /// shared allocator on a mounted table when a new span starts (sentinel 0).
4780    /// A standalone table uses its private monotonic counter (never 0).
4781    fn ensure_txn_id(&mut self) -> Result<u64> {
4782        if self.current_txn_id == 0 {
4783            let id = match &self.wal {
4784                WalSink::Shared(s) => crate::txn::allocate_txn_id(&s.txn_ids)?,
4785                WalSink::Private(_) => {
4786                    return Err(MongrelError::Full(
4787                        "standalone transaction id namespace exhausted".into(),
4788                    ))
4789                }
4790                WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4791            };
4792            self.current_txn_id = id;
4793        }
4794        Ok(self.current_txn_id)
4795    }
4796
4797    /// Append a data record (`Put`/`Delete`) for the current auto-commit txn to
4798    /// whichever WAL backs this table.
4799    fn wal_append_data(&mut self, op: Op) -> Result<()> {
4800        self.ensure_writable()?;
4801        let txn_id = self.ensure_txn_id()?;
4802        let table_id = self.table_id;
4803        match &mut self.wal {
4804            WalSink::Private(w) => {
4805                w.append_txn(txn_id, op)?;
4806                self.pending_private_mutations = true;
4807            }
4808            WalSink::Shared(s) => {
4809                s.wal.lock().append(txn_id, table_id, op)?;
4810            }
4811            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4812        }
4813        Ok(())
4814    }
4815
4816    fn ensure_writable(&self) -> Result<()> {
4817        if self.read_only || matches!(self.wal, WalSink::ReadOnly) {
4818            return Err(MongrelError::ReadOnlyReplica);
4819        }
4820        if self.durable_commit_failed {
4821            return Err(MongrelError::Other(
4822                "table poisoned by post-commit failure; reopen required".into(),
4823            ));
4824        }
4825        Ok(())
4826    }
4827
4828    /// Upsert a row. Allocates a [`RowId`], appends a (non-fsynced) WAL record,
4829    /// and updates the memtable + indexes. Returns the new row id. Durability
4830    /// arrives at the next [`Table::commit`] (or [`Table::flush`]).
4831    ///
4832    /// For an `AUTO_INCREMENT` primary key, omit the column (or pass
4833    /// Auth enforcement helpers. Each delegates to the optional
4834    /// [`TableAuthChecker`] (set at mount time from the `Database`'s auth
4835    /// state). On a credentialless database (`auth = None`), these are
4836    /// no-ops. The `name` field provides the table name for the permission
4837    /// check without needing a reference back to `Database`.
4838    fn require(&self, perm: crate::auth_state::RequiredPermission) -> Result<()> {
4839        match &self.auth {
4840            Some(checker) => checker.check(&self.name, perm),
4841            None => Ok(()),
4842        }
4843    }
4844    /// Check `Select` permission on this table. Public so that read entry
4845    /// points that don't go through `Table::query` (e.g. `MongrelProvider::scan`,
4846    /// `Table::count`) can enforce before reading. On a credentialless database
4847    /// this is a no-op.
4848    pub fn require_select(&self) -> Result<()> {
4849        self.require(crate::auth_state::RequiredPermission::Select)
4850    }
4851    fn require_insert(&self) -> Result<()> {
4852        self.require(crate::auth_state::RequiredPermission::Insert)
4853    }
4854    /// Currently unused on `Table` directly (updates go through `Transaction`),
4855    /// but kept for API completeness — the four `require_*` helpers mirror the
4856    /// four table-level permission kinds.
4857    #[allow(dead_code)]
4858    fn require_update(&self) -> Result<()> {
4859        self.require(crate::auth_state::RequiredPermission::Update)
4860    }
4861    fn require_delete(&self) -> Result<()> {
4862        self.require(crate::auth_state::RequiredPermission::Delete)
4863    }
4864
4865    /// [`Value::Null`]) and the engine assigns the next counter value; use
4866    /// [`Table::put_returning`] to learn that assigned value.
4867    pub fn put(&mut self, columns: Vec<(u16, Value)>) -> Result<RowId> {
4868        self.require_insert()?;
4869        Ok(self.put_returning(columns)?.0)
4870    }
4871
4872    /// Like [`Table::put`] but also returns the engine-assigned `AUTO_INCREMENT`
4873    /// value (`Some` only when the column was omitted/null and the engine filled
4874    /// it; `None` when the table has no auto-increment column or the caller
4875    /// supplied an explicit value).
4876    pub fn put_returning(
4877        &mut self,
4878        mut columns: Vec<(u16, Value)>,
4879    ) -> Result<(RowId, Option<i64>)> {
4880        self.require_insert()?;
4881        let assigned = self.fill_auto_inc(&mut columns)?;
4882        self.apply_defaults(&mut columns)?;
4883        self.schema.validate_values(&columns)?;
4884        // For clustered (WITHOUT ROWID) tables, derive RowId deterministically
4885        // from the PK value so the same PK always maps to the same row (no
4886        // allocator waste, idempotent upserts). For standard tables, use the
4887        // monotonic allocator.
4888        let row_id = if self.schema.clustered {
4889            self.derive_clustered_row_id(&columns)?
4890        } else {
4891            self.allocator.alloc()?
4892        };
4893        let epoch = self.pending_epoch();
4894        let mut row = Row::new(row_id, epoch);
4895        for (col_id, val) in columns {
4896            row.columns.insert(col_id, val);
4897        }
4898        self.commit_rows(vec![row], assigned.is_some())?;
4899        Ok((row_id, assigned))
4900    }
4901
4902    /// Bulk upsert: many rows under a single WAL record + one index pass. Far
4903    /// cheaper than `put` in a loop for batch ingest.
4904    pub fn put_batch(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Vec<RowId>> {
4905        self.require_insert()?;
4906        Ok(self
4907            .put_batch_returning(batch)?
4908            .into_iter()
4909            .map(|(r, _)| r)
4910            .collect())
4911    }
4912
4913    /// Like [`Table::put_batch`] but each entry is paired with the engine-
4914    /// assigned `AUTO_INCREMENT` value (`Some` only when filled by the engine).
4915    pub fn put_batch_returning(
4916        &mut self,
4917        batch: Vec<Vec<(u16, Value)>>,
4918    ) -> Result<Vec<(RowId, Option<i64>)>> {
4919        let mut filled: Vec<FilledAutoIncRow> = Vec::with_capacity(batch.len());
4920        for mut cols in batch {
4921            let assigned = self.fill_auto_inc(&mut cols)?;
4922            self.apply_defaults(&mut cols)?;
4923            filled.push((cols, assigned));
4924        }
4925        for (cols, _) in &filled {
4926            self.schema.validate_values(cols)?;
4927        }
4928        let epoch = self.pending_epoch();
4929        let mut rows = Vec::with_capacity(filled.len());
4930        let mut ids = Vec::with_capacity(filled.len());
4931        let first_row_id = if self.schema.clustered {
4932            None
4933        } else {
4934            let count = u64::try_from(filled.len())
4935                .map_err(|_| MongrelError::Full("row-id allocation request is too large".into()))?;
4936            Some(self.allocator.alloc_range(count)?.0)
4937        };
4938        for (row_index, (cols, assigned)) in filled.into_iter().enumerate() {
4939            let row_id = match first_row_id {
4940                Some(first) => RowId(first + row_index as u64),
4941                None => self.derive_clustered_row_id(&cols)?,
4942            };
4943            let mut row = Row::new(row_id, epoch);
4944            for (c, v) in cols {
4945                row.columns.insert(c, v);
4946            }
4947            ids.push((row_id, assigned));
4948            rows.push(row);
4949        }
4950        let all_auto_generated = ids.iter().all(|(_, assigned)| assigned.is_some());
4951        self.commit_rows(rows, all_auto_generated)?;
4952        Ok(ids)
4953    }
4954
4955    /// Fill the `AUTO_INCREMENT` column for an upcoming row. When the column is
4956    /// omitted or [`Value::Null`] the next counter value is allocated and the
4957    /// cell is appended/replaced in `columns`; an explicit `Int64` is honored
4958    /// and advances the counter past it. Returns `Some(value)` when the engine
4959    /// allocated (so the caller can surface it), `None` otherwise.
4960    pub fn fill_auto_inc(&mut self, columns: &mut Vec<(u16, Value)>) -> Result<Option<i64>> {
4961        self.ensure_writable()?;
4962        let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
4963            return Ok(None);
4964        };
4965        let pos = columns.iter().position(|(c, _)| *c == cid);
4966        let assigned = match pos {
4967            Some(i) => match &columns[i].1 {
4968                Value::Null => {
4969                    let next = self.alloc_auto_inc_value()?;
4970                    columns[i].1 = Value::Int64(next);
4971                    Some(next)
4972                }
4973                Value::Int64(n) => {
4974                    self.advance_auto_inc_past(*n)?;
4975                    None
4976                }
4977                other => {
4978                    return Err(MongrelError::InvalidArgument(format!(
4979                        "AUTO_INCREMENT column {cid} must be Int64 or NULL, got {:?}",
4980                        other
4981                    )))
4982                }
4983            },
4984            None => {
4985                let next = self.alloc_auto_inc_value()?;
4986                columns.push((cid, Value::Int64(next)));
4987                Some(next)
4988            }
4989        };
4990        Ok(assigned)
4991    }
4992
4993    /// Apply column default expressions to `columns` at stage time (before
4994    /// NOT NULL validation). For each column carrying a `default_value`, if the
4995    /// column is omitted or explicitly `Null`, the default is applied. Explicit
4996    /// values are never overridden. Called after [`fill_auto_inc`](Self::fill_auto_inc)
4997    /// and before `validate_not_null`.
4998    pub fn apply_defaults(&self, columns: &mut Vec<(u16, Value)>) -> Result<()> {
4999        for col in &self.schema.columns {
5000            let Some(expr) = &col.default_value else {
5001                continue;
5002            };
5003            // Skip AUTO_INCREMENT columns — handled by fill_auto_inc.
5004            if col.flags.contains(ColumnFlags::AUTO_INCREMENT) {
5005                continue;
5006            }
5007            let pos = columns.iter().position(|(c, _)| *c == col.id);
5008            let needs_default = match pos {
5009                None => true,
5010                Some(i) => matches!(columns[i].1, Value::Null),
5011            };
5012            if !needs_default {
5013                continue;
5014            }
5015            let v = match expr {
5016                crate::schema::DefaultExpr::Static(v) => v.clone(),
5017                crate::schema::DefaultExpr::Now => Value::Bytes(iso_now_bytes()),
5018                crate::schema::DefaultExpr::Uuid => {
5019                    let mut buf = [0u8; 16];
5020                    getrandom::fill(&mut buf)
5021                        .map_err(|e| MongrelError::Other(format!("UUID generation failed: {e}")))?;
5022                    Value::Uuid(buf)
5023                }
5024            };
5025            match pos {
5026                None => columns.push((col.id, v)),
5027                Some(i) => columns[i].1 = v,
5028            }
5029        }
5030        Ok(())
5031    }
5032
5033    /// Allocate the next identity value, seeding the counter first if needed.
5034    fn alloc_auto_inc_value(&mut self) -> Result<i64> {
5035        self.ensure_auto_inc_seeded()?;
5036        // Borrow checker: re-read after the mutable `ensure` call returns.
5037        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5038        let v = ai.next;
5039        ai.next = ai
5040            .next
5041            .checked_add(1)
5042            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5043        Ok(v)
5044    }
5045
5046    /// Advance the counter past an explicit id, seeding first if needed so a
5047    /// pre-existing higher id elsewhere is never ignored.
5048    fn advance_auto_inc_past(&mut self, used: i64) -> Result<()> {
5049        self.ensure_auto_inc_seeded()?;
5050        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5051        let floor = used
5052            .checked_add(1)
5053            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5054            .max(1);
5055        if ai.next < floor {
5056            ai.next = floor;
5057        }
5058        Ok(())
5059    }
5060
5061    /// Seed the counter on first use by scanning `max(PK)` over all visible
5062    /// rows, so an upgraded table (legacy client-assigned ids, or a manifest
5063    /// migrated from `auto_inc_next == 0`) never hands out a colliding id.
5064    /// Idempotent: a no-op once seeded.
5065    fn ensure_auto_inc_seeded(&mut self) -> Result<()> {
5066        let needs_seed = match self.auto_inc {
5067            Some(ai) => !ai.seeded,
5068            None => return Ok(()),
5069        };
5070        if !needs_seed {
5071            return Ok(());
5072        }
5073        if self.seed_empty_auto_inc() {
5074            return Ok(());
5075        }
5076        let cid = self
5077            .auto_inc
5078            .as_ref()
5079            .expect("auto-inc column present")
5080            .column_id;
5081        let max = self.scan_max_int64(cid)?;
5082        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5083        let floor = max
5084            .checked_add(1)
5085            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5086            .max(1);
5087        if ai.next < floor {
5088            ai.next = floor;
5089        }
5090        ai.seeded = true;
5091        Ok(())
5092    }
5093
5094    fn alloc_auto_inc_range(&mut self, n: usize) -> Result<Option<i64>> {
5095        if n == 0 || self.auto_inc.is_none() {
5096            return Ok(None);
5097        }
5098        self.ensure_auto_inc_seeded()?;
5099        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5100        let start = ai.next;
5101        let count = i64::try_from(n)
5102            .map_err(|_| MongrelError::Full("AUTO_INCREMENT range is too large".into()))?;
5103        ai.next = ai
5104            .next
5105            .checked_add(count)
5106            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5107        Ok(Some(start))
5108    }
5109
5110    /// One-time `max(Int64 column)` over all MVCC-visible rows. Used to seed the
5111    /// auto-increment counter. Runs at most once per table (the manifest then
5112    /// checkpoints the seeded counter).
5113    fn scan_max_int64(&mut self, column_id: u16) -> Result<i64> {
5114        let mut max: i64 = 0;
5115        for r in self.memtable.visible_versions_at(Snapshot::unbounded()) {
5116            if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5117                if *n > max {
5118                    max = *n;
5119                }
5120            }
5121        }
5122        for r in self.mutable_run.visible_versions(Epoch(u64::MAX)) {
5123            if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5124                if *n > max {
5125                    max = *n;
5126                }
5127            }
5128        }
5129        for rr in self.run_refs.clone() {
5130            let reader = self.open_reader(rr.run_id)?;
5131            if let Some(stats) = reader.column_page_stats(column_id) {
5132                for s in stats {
5133                    if let Some(n) = crate::sorted_run::be_i64(s.max.as_deref()) {
5134                        if n > max {
5135                            max = n;
5136                        }
5137                    }
5138                }
5139            } else if reader.has_column(column_id) {
5140                if let columnar::NativeColumn::Int64 { data, validity } =
5141                    reader.column_native_shared(column_id)?
5142                {
5143                    for (i, n) in data.iter().enumerate() {
5144                        if (validity.is_empty() || columnar::validity_bit(&validity, i)) && *n > max
5145                        {
5146                            max = *n;
5147                        }
5148                    }
5149                }
5150            }
5151        }
5152        Ok(max)
5153    }
5154
5155    fn seed_empty_auto_inc(&mut self) -> bool {
5156        let Some(ai) = self.auto_inc.as_mut() else {
5157            return false;
5158        };
5159        if ai.seeded || self.live_count != 0 {
5160            return false;
5161        }
5162        if ai.next < 1 {
5163            ai.next = 1;
5164        }
5165        ai.seeded = true;
5166        true
5167    }
5168
5169    fn advance_auto_inc_from_native_columns(
5170        &mut self,
5171        columns: &[(u16, columnar::NativeColumn)],
5172        n: usize,
5173        live_before: u64,
5174    ) -> Result<()> {
5175        let Some(ai) = self.auto_inc.as_mut() else {
5176            return Ok(());
5177        };
5178        let Some((_, col)) = columns.iter().find(|(cid, _)| *cid == ai.column_id) else {
5179            return Ok(());
5180        };
5181        let columnar::NativeColumn::Int64 { data, validity } = col else {
5182            return Err(MongrelError::InvalidArgument(format!(
5183                "AUTO_INCREMENT column {} must be Int64",
5184                ai.column_id
5185            )));
5186        };
5187        let max = if native_int64_strictly_increasing(col, n) {
5188            data.get(n.saturating_sub(1)).copied()
5189        } else {
5190            data.iter()
5191                .take(n)
5192                .enumerate()
5193                .filter_map(|(i, v)| {
5194                    if validity.is_empty() || columnar::validity_bit(validity, i) {
5195                        Some(*v)
5196                    } else {
5197                        None
5198                    }
5199                })
5200                .max()
5201        };
5202        if let Some(max) = max {
5203            let floor = max
5204                .checked_add(1)
5205                .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5206                .max(1);
5207            if ai.next < floor {
5208                ai.next = floor;
5209            }
5210            if ai.seeded || live_before == 0 {
5211                ai.seeded = true;
5212            }
5213        }
5214        Ok(())
5215    }
5216
5217    fn fill_auto_inc_native_columns(
5218        &mut self,
5219        columns: &mut Vec<(u16, columnar::NativeColumn)>,
5220        n: usize,
5221    ) -> Result<()> {
5222        let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
5223            return Ok(());
5224        };
5225        let Some(pos) = columns.iter().position(|(id, _)| *id == cid) else {
5226            if let Some(start) = self.alloc_auto_inc_range(n)? {
5227                columns.push((
5228                    cid,
5229                    columnar::NativeColumn::Int64 {
5230                        data: (start..start.saturating_add(n as i64)).collect(),
5231                        validity: vec![0xFF; n.div_ceil(8)],
5232                    },
5233                ));
5234            }
5235            return Ok(());
5236        };
5237
5238        let columnar::NativeColumn::Int64 { data, validity } = &mut columns[pos].1 else {
5239            return Err(MongrelError::InvalidArgument(format!(
5240                "AUTO_INCREMENT column {cid} must be Int64"
5241            )));
5242        };
5243        if data.len() < n {
5244            return Err(MongrelError::InvalidArgument(format!(
5245                "AUTO_INCREMENT column {cid} has {} rows, expected {n}",
5246                data.len()
5247            )));
5248        }
5249        if columnar::all_non_null(validity, n) {
5250            return Ok(());
5251        }
5252        if validity.iter().all(|b| *b == 0) {
5253            if let Some(start) = self.alloc_auto_inc_range(n)? {
5254                for (i, slot) in data.iter_mut().take(n).enumerate() {
5255                    *slot = start.saturating_add(i as i64);
5256                }
5257                *validity = vec![0xFF; n.div_ceil(8)];
5258            }
5259            return Ok(());
5260        }
5261
5262        let new_validity = vec![0xFF; data.len().div_ceil(8)];
5263        for (i, slot) in data.iter_mut().enumerate().take(n) {
5264            if columnar::validity_bit(validity, i) {
5265                self.advance_auto_inc_past(*slot)?;
5266            } else {
5267                *slot = self.alloc_auto_inc_value()?;
5268            }
5269        }
5270        *validity = new_validity;
5271        Ok(())
5272    }
5273
5274    /// Reserve (but do not insert) the next `AUTO_INCREMENT` value, advancing
5275    /// the in-memory counter. Returns `None` when the table has no
5276    /// auto-increment column.
5277    ///
5278    /// This is the escape hatch for callers that stage the row with an explicit
5279    /// id inside a cross-table [`crate::Transaction`] — where the engine cannot
5280    /// fill the column on the `put` path (the row id + cells are only assembled
5281    /// at commit). Unlike the old Kit `__kit_sequences` sequence row, the
5282    /// reservation is a pure in-memory counter bump: no hot row, no second
5283    /// commit. It becomes durable when a row carrying the reserved id commits
5284    /// (the counter is checkpointed to the manifest in the same commit); an
5285    /// aborted reservation simply leaves a gap, which the never-reuse rule
5286    /// permits.
5287    pub fn reserve_auto_inc(&mut self) -> Result<Option<i64>> {
5288        self.ensure_writable()?;
5289        if self.auto_inc.is_none() {
5290            return Ok(None);
5291        }
5292        Ok(Some(self.alloc_auto_inc_value()?))
5293    }
5294
5295    /// Append `rows` under one WAL record. On a standalone table they are folded
5296    /// into the memtable + indexes immediately (single clock — no speculative-
5297    /// epoch hazard). On a mounted table (B1/B2) they are staged in
5298    /// `pending_rows` and applied at the real assigned epoch in `commit`, so a
5299    /// concurrent reader can never see them before their commit epoch.
5300    fn commit_rows(&mut self, rows: Vec<Row>, auto_inc_generated: bool) -> Result<()> {
5301        let payload = bincode::serialize(&rows)?;
5302        self.wal_append_data(Op::Put {
5303            table_id: self.table_id,
5304            rows: payload,
5305        })?;
5306        if self.is_shared() {
5307            self.pending_rows_auto_inc
5308                .extend(std::iter::repeat_n(auto_inc_generated, rows.len()));
5309            self.pending_rows.extend(rows);
5310        } else {
5311            self.apply_put_rows_inner(rows, !auto_inc_generated)?;
5312        }
5313        Ok(())
5314    }
5315
5316    /// Complete every fallible read/index preparation before a WAL commit can
5317    /// become durable. After this succeeds, row application is in-memory only.
5318    pub(crate) fn prepare_durable_publish(&mut self) -> Result<()> {
5319        self.ensure_indexes_complete()
5320    }
5321
5322    pub(crate) fn prepare_durable_publish_controlled(
5323        &mut self,
5324        control: &crate::ExecutionControl,
5325    ) -> Result<()> {
5326        self.ensure_indexes_complete_controlled(control, || true)?;
5327        Ok(())
5328    }
5329
5330    pub(crate) fn apply_put_rows_prepared(&mut self, rows: Vec<Row>) {
5331        self.apply_put_rows_inner_prepared(rows, true);
5332    }
5333
5334    fn apply_put_rows_inner(&mut self, rows: Vec<Row>, check_existing_pk: bool) -> Result<()> {
5335        if check_existing_pk {
5336            self.ensure_indexes_complete()?;
5337        }
5338        self.apply_put_rows_inner_prepared(rows, check_existing_pk);
5339        Ok(())
5340    }
5341
5342    /// Apply rows after [`Self::ensure_indexes_complete`] has succeeded. Every
5343    /// operation below is in-memory and infallible, so durable publication can
5344    /// never stop halfway through a batch on an I/O error.
5345    fn apply_put_rows_inner_prepared(&mut self, rows: Vec<Row>, check_existing_pk: bool) {
5346        // Single-row puts — the hot operational path — cannot contain an
5347        // intra-batch duplicate, so the winner/loser partition maps are pure
5348        // overhead. Same semantics as the batch path below with `losers = ∅`.
5349        if rows.len() == 1 {
5350            let row = rows.into_iter().next().expect("len checked");
5351            self.apply_put_row_single(row, check_existing_pk);
5352            return;
5353        }
5354        // One pass per row: track mutated columns, tombstone the previous
5355        // owner of the row's PK, index (which places the HOT entry), sample,
5356        // and materialize. Each row is applied completely — including its
5357        // memtable upsert — before the next row processes, so "the last row
5358        // wins" falls out naturally for an intra-batch duplicate PK: the
5359        // earlier row is already materialized and gets tombstoned like any
5360        // other displaced owner (same visible state as pre-partitioning the
5361        // batch into winners and losers, without materializing a winner map
5362        // over the whole batch).
5363        //
5364        // Upsert probing is skipped entirely when no PK owner can be
5365        // displaced: `check_existing_pk == false` means every PK is a fresh
5366        // engine-assigned AUTO_INCREMENT value; an empty HOT index plus
5367        // strictly-increasing batch PKs (the append-style batch, mirroring
5368        // `bulk_pk_winner_indices`' fast path) rules out both pre-existing
5369        // owners and intra-batch duplicates.
5370        let pk_id = self.schema.primary_key().map(|c| c.id);
5371        let probe = match pk_id {
5372            Some(pid) => {
5373                check_existing_pk
5374                    && !(self.hot.is_empty() && rows_pk_strictly_increasing(&rows, pid))
5375            }
5376            None => false,
5377        };
5378        // The PK reverse map is maintained inline only once a delete has built
5379        // it (`pk_by_row_complete`); ingest-only tables never pay for it.
5380        let maintain_pk_by_row = pk_id.is_some() && self.pk_by_row_complete;
5381        for r in rows {
5382            for &cid in r.columns.keys() {
5383                self.pending_put_cols.insert(cid);
5384            }
5385            let mut replaced_image: Option<Row> = None;
5386            match pk_id {
5387                Some(pid) if probe || maintain_pk_by_row => {
5388                    if let Some(pk_val) = r.columns.get(&pid) {
5389                        let key = self.index_lookup_key(pid, pk_val);
5390                        if probe {
5391                            // Prefer `recent_delete_preimages` (Kit
5392                            // delete+put: the pre-image is needed to drive
5393                            // Bitmap delta maintenance). Fall back to the
5394                            // stale HOT entry when the preimage was cleared
5395                            // (e.g., after a rebuild). `apply_delete_at`
5396                            // preserves the HOT entry so the stale-entry
5397                            // branch is the common one for a same-PK Kit
5398                            // delete+put.
5399                            if let Some(old) = self.recent_delete_preimages.remove(&key) {
5400                                replaced_image = Some(old);
5401                                if let Some(old_rid) = self.hot.get(&key) {
5402                                    if old_rid != r.row_id {
5403                                        self.tombstone_row(
5404                                            old_rid,
5405                                            r.committed_epoch,
5406                                            r.commit_ts,
5407                                            true,
5408                                        );
5409                                    }
5410                                }
5411                            } else if let Some(old_rid) = self.hot.get(&key) {
5412                                if old_rid != r.row_id {
5413                                    replaced_image = self.get(old_rid, self.snapshot());
5414                                    self.tombstone_row(
5415                                        old_rid,
5416                                        r.committed_epoch,
5417                                        r.commit_ts,
5418                                        true,
5419                                    );
5420                                }
5421                            }
5422                        }
5423                        if maintain_pk_by_row {
5424                            self.pk_by_row.insert(r.row_id, key);
5425                        }
5426                    }
5427                }
5428                Some(_) => {}
5429                None => {
5430                    self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5431                }
5432            }
5433            if let Some(old) = replaced_image {
5434                self.maintain_indexes_on_pk_replace(&old, &r);
5435            } else {
5436                self.index_row(&r);
5437            }
5438            self.reservoir.offer(r.row_id.0);
5439            self.memtable.upsert(r);
5440            // Count as each row lands so a later duplicate's tombstone
5441            // decrement (in `tombstone_row`) sees an up-to-date value.
5442            self.live_count = self.live_count.saturating_add(1);
5443        }
5444        self.data_generation = self.data_generation.wrapping_add(1);
5445    }
5446
5447    /// One-row specialization of [`Table::apply_put_rows_inner`]: identical
5448    /// upsert semantics (tombstone the previous PK owner, insert into HOT,
5449    /// index, sample, materialize) without the per-batch winner/loser maps.
5450    ///
5451    /// When a same-PK put replaces an older live row (the product update path
5452    /// after delete+put normalize, or a direct upsert), Bitmap secondary indexes
5453    /// are maintained via [`crate::index::maintain_bitmap_secondary_on_replace`]
5454    /// so unchanged equality keys only re-point row ids and changed keys move —
5455    /// rather than leaving tombstoned row ids permanently in the bitmaps.
5456    fn apply_put_row_single(&mut self, row: Row, check_existing_pk: bool) {
5457        for &cid in row.columns.keys() {
5458            self.pending_put_cols.insert(cid);
5459        }
5460        let epoch = row.committed_epoch;
5461        let mut replaced_image: Option<Row> = None;
5462        if let Some(pk_col) = self.schema.primary_key() {
5463            let pk_id = pk_col.id;
5464            if let Some(pk_val) = row.columns.get(&pk_id) {
5465                // `index_row` / HOT-only path below writes the HOT entry. The
5466                // reverse map is maintained inline only once a delete has built
5467                // it; ingest-only tables never pay for it.
5468                let maintain_pk_by_row = self.pk_by_row_complete;
5469                if check_existing_pk || maintain_pk_by_row {
5470                    let key = self.index_lookup_key(pk_id, pk_val);
5471                    if check_existing_pk {
5472                        // Prefer `recent_delete_preimages` (Kit delete+put:
5473                        // the pre-image is needed to drive Bitmap delta
5474                        // maintenance). Fall back to the stale HOT entry for
5475                        // cases where `recent_delete_preimages` was cleared
5476                        // (e.g., after a rebuild) but HOT still maps to the
5477                        // old rid. `apply_delete_at` preserves the HOT entry
5478                        // so the stale-entry branch is the common one for a
5479                        // same-PK Kit delete+put.
5480                        if let Some(old) = self.recent_delete_preimages.remove(&key) {
5481                            replaced_image = Some(old);
5482                            if let Some(old_rid) = self.hot.get(&key) {
5483                                if old_rid != row.row_id {
5484                                    self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5485                                }
5486                            }
5487                        } else if let Some(old_rid) = self.hot.get(&key) {
5488                            if old_rid != row.row_id {
5489                                // Capture the pre-image while it is still live so
5490                                // secondary-index delta maintenance can drop the
5491                                // old row-id from Bitmap keys.
5492                                replaced_image = self.get(old_rid, self.snapshot());
5493                                self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5494                            }
5495                        }
5496                    }
5497                    if maintain_pk_by_row {
5498                        self.pk_by_row.insert(row.row_id, key);
5499                    }
5500                }
5501            }
5502        } else {
5503            self.hot
5504                .insert(row.row_id.0.to_be_bytes().to_vec(), row.row_id);
5505        }
5506        if let Some(old) = replaced_image {
5507            self.maintain_indexes_on_pk_replace(&old, &row);
5508        } else {
5509            self.index_row(&row);
5510        }
5511        self.reservoir.offer(row.row_id.0);
5512        self.memtable.upsert(row);
5513        self.live_count = self.live_count.saturating_add(1);
5514        self.data_generation = self.data_generation.wrapping_add(1);
5515    }
5516
5517    /// PK-replace index maintenance: Bitmap secondaries via delta plan; other
5518    /// secondary kinds + HOT via the existing full path for those families.
5519    fn maintain_indexes_on_pk_replace(&mut self, old: &Row, new: &Row) {
5520        let has_partial = self
5521            .schema
5522            .indexes
5523            .iter()
5524            .any(|idx| idx.predicate.is_some());
5525        if has_partial {
5526            // Partial predicates make selective unindex subtle; drop old Bitmap
5527            // memberships then full-index the new image (still cleans tombstone
5528            // pollution for Bitmap keys on the replace path only).
5529            self.unindex_bitmap_membership(old);
5530            self.index_row(new);
5531            return;
5532        }
5533
5534        crate::index::maintain_bitmap_secondary_on_replace(
5535            &self.schema,
5536            &mut self.bitmap,
5537            old,
5538            new,
5539        );
5540        self.index_row_non_bitmap(new);
5541    }
5542
5543    /// Index HOT + every non-Bitmap secondary for `row`. Bitmap secondaries are
5544    /// assumed already maintained by a delta plan on the replace path.
5545    fn index_row_non_bitmap(&mut self, row: &Row) {
5546        if row.deleted {
5547            return;
5548        }
5549        let effective = if self.column_keys.is_empty() {
5550            None
5551        } else {
5552            Some(self.tokenized_for_indexes(row))
5553        };
5554        let source = effective.as_ref().unwrap_or(row);
5555        for idef in &self.schema.indexes {
5556            if idef.kind == crate::schema::IndexKind::Bitmap {
5557                continue;
5558            }
5559            index_into_single(
5560                idef,
5561                &self.schema,
5562                source,
5563                &mut self.hot,
5564                &mut self.bitmap,
5565                &mut self.ann,
5566                &mut self.fm,
5567                &mut self.sparse,
5568                &mut self.minhash,
5569            );
5570        }
5571        if let Some(pk_col) = self.schema.primary_key() {
5572            if let Some(pk_val) = source.columns.get(&pk_col.id) {
5573                let key = if self.column_keys.is_empty() {
5574                    pk_val.encode_key()
5575                } else {
5576                    self.index_lookup_key(pk_col.id, pk_val)
5577                };
5578                self.hot.insert(key, source.row_id);
5579            }
5580        }
5581    }
5582
5583    /// Allocate a fresh row id (advancing the table's allocator). Used by the
5584    /// cross-table `Transaction` to assign ids before sealing a row.
5585    pub(crate) fn alloc_row_id(&mut self) -> Result<RowId> {
5586        self.allocator.alloc()
5587    }
5588
5589    /// For clustered (WITHOUT ROWID) tables: derive a deterministic `RowId`
5590    /// from the primary-key value so the same PK always maps to the same row.
5591    /// Uses a stable hash of the PK's `encode_key()` bytes, cast to `u64`.
5592    /// This gives WITHOUT ROWID tables idempotent upsert semantics (same PK →
5593    /// same RowId, no allocator waste) without changing the storage format.
5594    fn derive_clustered_row_id(&self, columns: &[(u16, Value)]) -> Result<RowId> {
5595        let pk = self.schema.primary_key().ok_or_else(|| {
5596            MongrelError::Schema("clustered table requires a single-column primary key".into())
5597        })?;
5598        let pk_val = columns
5599            .iter()
5600            .find(|(id, _)| *id == pk.id)
5601            .map(|(_, v)| v)
5602            .ok_or_else(|| {
5603                MongrelError::Schema(format!(
5604                    "clustered table missing primary key column {} ({})",
5605                    pk.id, pk.name
5606                ))
5607            })?;
5608        Ok(clustered_row_id(pk_val))
5609    }
5610
5611    /// Apply the metadata for rows that were spilled to a linked uniform-epoch
5612    /// run (P3.4): update the HOT + secondary indexes, the reservoir, the
5613    /// allocator high-water mark, and `live_count` — but **do NOT** insert the
5614    /// rows into the memtable. The rows are served from the linked run (which the
5615    /// scan/merge path reads at the run's commit epoch), so materializing them in
5616    /// the memtable too would defeat the point of spilling (peak memory stays
5617    /// bounded). Caller must have linked the run before reads can resolve indexes.
5618    pub(crate) fn apply_run_metadata_prepared(&mut self, rows: &[Row]) -> Result<()> {
5619        if rows.iter().any(|row| row.row_id.0 >= u64::MAX - 1) {
5620            return Err(MongrelError::Full("row-id namespace exhausted".into()));
5621        }
5622        let n = rows.len();
5623        for r in rows {
5624            for &cid in r.columns.keys() {
5625                self.pending_put_cols.insert(cid);
5626            }
5627        }
5628        let (losers, winner_pks) = self.partition_pk_winners(rows);
5629        let epoch = rows.first().map(|r| r.committed_epoch).unwrap_or(Epoch(0));
5630        // Tombstone pre-existing rows that conflict with winners.
5631        let group_ts = rows.first().and_then(|r| r.commit_ts);
5632        for (key, &row_id) in &winner_pks {
5633            if let Some(old_rid) = self.hot.get(key) {
5634                if old_rid != row_id {
5635                    self.tombstone_row(old_rid, epoch, group_ts, true);
5636                }
5637            }
5638        }
5639        // Hide duplicate-PK rows inside this uniform-epoch run by tombstoning
5640        // their row ids in the memtable overlay (the overlay wins over the run).
5641        for &loser_rid in &losers {
5642            self.tombstone_row(loser_rid, epoch, group_ts, false);
5643        }
5644        // Insert the winners into HOT.
5645        for (key, row_id) in winner_pks {
5646            self.insert_hot_pk(key, row_id);
5647        }
5648        if self.schema.primary_key().is_none() {
5649            for r in rows {
5650                self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5651            }
5652        }
5653        for r in rows {
5654            self.allocator.advance_to(r.row_id)?;
5655            if !losers.contains(&r.row_id) {
5656                self.index_row(r);
5657            }
5658        }
5659        for r in rows {
5660            if !losers.contains(&r.row_id) {
5661                self.reservoir.offer(r.row_id.0);
5662            }
5663        }
5664        self.live_count = self.live_count.saturating_add((n - losers.len()) as u64);
5665        self.data_generation = self.data_generation.wrapping_add(1);
5666        Ok(())
5667    }
5668
5669    /// Apply already-committed puts + tombstones during shared-WAL recovery
5670    /// (spec §15 pass 2). Advances the allocator, upserts/tombstones the
5671    /// memtable, and indexes the rows — but does NOT touch `live_count` (the
5672    /// manifest is authoritative) and does NOT append to the WAL.
5673    pub(crate) fn recover_apply(
5674        &mut self,
5675        rows: Vec<Row>,
5676        deletes: Vec<(RowId, Epoch)>,
5677    ) -> Result<()> {
5678        // Rows from different transactions have different epochs and can be
5679        // upserted sequentially. Rows inside one transaction share an epoch, so
5680        // duplicate PKs within that transaction must keep only the last winner.
5681        let mut by_epoch: std::collections::BTreeMap<Epoch, Vec<Row>> =
5682            std::collections::BTreeMap::new();
5683        for row in rows {
5684            if row.row_id.0 >= u64::MAX - 1 {
5685                return Err(MongrelError::Full("row-id namespace exhausted".into()));
5686            }
5687            self.allocator.advance_to(row.row_id)?;
5688            // Mirror the row-id advance for the AUTO_INCREMENT counter: WAL
5689            // replay must not hand out an id a recovered row already claimed.
5690            // `seeded` is intentionally left untouched so a still-unseeded
5691            // counter still scans `max(PK)` to cover already-flushed rows.
5692            if let Some(ai) = self.auto_inc.as_mut() {
5693                if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
5694                    let next = n.checked_add(1).ok_or_else(|| {
5695                        MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
5696                    })?;
5697                    if next > ai.next {
5698                        ai.next = next;
5699                    }
5700                }
5701            }
5702            by_epoch.entry(row.committed_epoch).or_default().push(row);
5703        }
5704        for (epoch, group) in by_epoch {
5705            let (losers, winner_pks) = self.partition_pk_winners(&group);
5706            // Tombstone pre-existing PK owners.
5707            let group_ts = group.first().and_then(|r| r.commit_ts);
5708            for (key, &row_id) in &winner_pks {
5709                if let Some(old_rid) = self.hot.get(key) {
5710                    if old_rid != row_id {
5711                        self.tombstone_row(old_rid, epoch, group_ts, false);
5712                    }
5713                }
5714            }
5715            for (key, row_id) in winner_pks {
5716                self.insert_hot_pk(key, row_id);
5717            }
5718            if self.schema.primary_key().is_none() {
5719                for r in &group {
5720                    self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5721                }
5722            }
5723            for r in &group {
5724                if !losers.contains(&r.row_id) {
5725                    self.memtable.upsert(r.clone());
5726                    self.index_row(r);
5727                }
5728            }
5729        }
5730        for (rid, epoch) in deletes {
5731            self.memtable.tombstone(rid, epoch);
5732            self.remove_hot_for_row(rid, epoch);
5733        }
5734        // Reservoir stays lazy — see `ensure_reservoir_complete` — rather than
5735        // eagerly materializing every row on every WAL-replay batch.
5736        self.reservoir_complete = false;
5737        Ok(())
5738    }
5739
5740    /// Highest epoch whose data is durable in a sorted run (spec §7.1).
5741    pub(crate) fn flushed_epoch(&self) -> u64 {
5742        self.flushed_epoch
5743    }
5744
5745    pub(crate) fn set_flushed_epoch(&mut self, epoch: Epoch) {
5746        self.flushed_epoch = self.flushed_epoch.max(epoch.0);
5747    }
5748
5749    /// Validate that `cells` satisfy the schema's NOT NULL constraints.
5750    pub(crate) fn validate_cells_not_null(&self, cells: &[(u16, Value)]) -> Result<()> {
5751        self.schema.validate_values(cells)
5752    }
5753
5754    /// Column-major NOT NULL validation for the bulk-load paths. Every schema
5755    /// column that is not marked NULLABLE must be present in `columns` and have
5756    /// no null validity bits over its first `n` rows.
5757    fn validate_columns_not_null(
5758        &self,
5759        columns: &[(u16, columnar::NativeColumn)],
5760        n: usize,
5761    ) -> Result<()> {
5762        let by_id: HashMap<u16, &columnar::NativeColumn> =
5763            columns.iter().map(|(id, c)| (*id, c)).collect();
5764        for col in &self.schema.columns {
5765            if !col.flags.contains(ColumnFlags::NULLABLE) {
5766                match by_id.get(&col.id) {
5767                    None => {
5768                        return Err(MongrelError::InvalidArgument(format!(
5769                            "column '{}' ({}) is NOT NULL but was omitted from the bulk load",
5770                            col.name, col.id
5771                        )));
5772                    }
5773                    Some(c) => {
5774                        if c.null_count(n) != 0 {
5775                            return Err(MongrelError::InvalidArgument(format!(
5776                                "column '{}' ({}) is NOT NULL but the bulk load contains nulls",
5777                                col.name, col.id
5778                            )));
5779                        }
5780                    }
5781                }
5782            }
5783            if let TypeId::Enum { variants } = &col.ty {
5784                let Some(columnar::NativeColumn::Bytes { .. }) = by_id.get(&col.id).copied() else {
5785                    if by_id.contains_key(&col.id) {
5786                        return Err(MongrelError::InvalidArgument(format!(
5787                            "column '{}' ({}) enum requires a bytes column",
5788                            col.name, col.id
5789                        )));
5790                    }
5791                    continue;
5792                };
5793                for index in 0..n {
5794                    let Some(value) = columnar::native_bytes_at(by_id[&col.id], index) else {
5795                        continue;
5796                    };
5797                    if !variants.iter().any(|variant| variant.as_bytes() == value) {
5798                        return Err(MongrelError::InvalidArgument(format!(
5799                            "column '{}' ({}) enum value {:?} is not one of {:?}",
5800                            col.name,
5801                            col.id,
5802                            String::from_utf8_lossy(value),
5803                            variants
5804                        )));
5805                    }
5806                }
5807            }
5808        }
5809        Ok(())
5810    }
5811
5812    /// For a bulk-loaded batch, compute the row indices that survive primary-
5813    /// key upsert: for each PK value the last occurrence wins, earlier
5814    /// duplicates are dropped. Rows with a null PK value are always kept. Returns
5815    /// `None` when there is no primary key or no compaction is needed.
5816    fn bulk_pk_winner_indices(
5817        &self,
5818        columns: &[(u16, columnar::NativeColumn)],
5819        n: usize,
5820    ) -> Option<Vec<usize>> {
5821        let pk_col = self.schema.primary_key()?;
5822        let pk_id = pk_col.id;
5823        let pk_ty = pk_col.ty.clone();
5824        let by_id: HashMap<u16, &columnar::NativeColumn> =
5825            columns.iter().map(|(id, c)| (*id, c)).collect();
5826        let pk_native = by_id.get(&pk_id)?;
5827        if native_int64_strictly_increasing(pk_native, n) {
5828            return None;
5829        }
5830        // key -> index of the last row that carried that PK value.
5831        let mut last: HashMap<Vec<u8>, usize> = HashMap::new();
5832        let mut null_pk_rows: Vec<usize> = Vec::new();
5833        for i in 0..n {
5834            match bulk_index_key(&self.column_keys, pk_id, pk_ty.clone(), pk_native, i) {
5835                Some(key) => {
5836                    last.insert(key, i);
5837                }
5838                None => null_pk_rows.push(i),
5839            }
5840        }
5841        let mut winners: HashSet<usize> = last.values().copied().collect();
5842        for i in null_pk_rows {
5843            winners.insert(i);
5844        }
5845        Some((0..n).filter(|i| winners.contains(i)).collect())
5846    }
5847
5848    /// Logically delete `row_id` (effective at the next commit).
5849    pub fn delete(&mut self, row_id: RowId) -> Result<()> {
5850        self.require_delete()?;
5851        let epoch = self.pending_epoch();
5852        self.wal_append_data(Op::Delete {
5853            table_id: self.table_id,
5854            row_ids: vec![row_id],
5855        })?;
5856        if self.is_shared() {
5857            self.pending_dels.push(row_id);
5858        } else {
5859            self.apply_delete(row_id, epoch);
5860        }
5861        Ok(())
5862    }
5863
5864    pub fn delete_returning(&mut self, row_id: RowId) -> Result<Option<OwnedRow>> {
5865        let pre = self.get(row_id, self.snapshot());
5866        self.delete(row_id)?;
5867        Ok(pre.map(|row| {
5868            let mut columns: Vec<_> = row.columns.into_iter().collect();
5869            columns.sort_by_key(|(id, _)| *id);
5870            OwnedRow { columns }
5871        }))
5872    }
5873
5874    /// Durably remove every row in the table once the current write span commits.
5875    pub fn truncate(&mut self) -> Result<()> {
5876        self.require_delete()?;
5877        let epoch = self.pending_epoch();
5878        self.wal_append_data(Op::TruncateTable {
5879            table_id: self.table_id,
5880        })?;
5881        self.pending_rows.clear();
5882        self.pending_rows_auto_inc.clear();
5883        self.pending_dels.clear();
5884        self.pending_truncate = Some(epoch);
5885        Ok(())
5886    }
5887
5888    /// Apply an already-durable truncate without appending to the WAL.
5889    pub(crate) fn apply_truncate(&mut self, _epoch: Epoch) {
5890        // Unlink active topology in the next manifest before removing any run
5891        // file. A crash before that manifest is durable must still be able to
5892        // open the old manifest and replay the durable truncate from WAL.
5893        // Unreferenced files are safe orphans and `gc()` removes them later.
5894        self.run_refs.clear();
5895        self.retiring.clear();
5896        self.memtable = Memtable::new();
5897        self.mutable_run = MutableRun::new();
5898        self.hot = HotIndex::new();
5899        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
5900        self.bitmap = bitmap;
5901        self.ann = ann;
5902        self.fm = fm;
5903        self.sparse = sparse;
5904        self.minhash = minhash;
5905        self.learned_range = Arc::new(HashMap::new());
5906        self.pk_by_row.clear();
5907        self.pk_by_row_complete = false;
5908        self.live_count = 0;
5909        self.reservoir = crate::reservoir::Reservoir::default();
5910        self.reservoir_complete = true;
5911        self.had_deletes = true;
5912        self.agg_cache = Arc::new(HashMap::new());
5913        self.global_idx_epoch = 0;
5914        self.indexes_complete = true;
5915        self.pending_delete_rids.clear();
5916        self.pending_put_cols.clear();
5917        self.pending_rows.clear();
5918        self.pending_rows_auto_inc.clear();
5919        self.pending_dels.clear();
5920        self.clear_result_cache();
5921        self.invalidate_index_checkpoint();
5922        self.data_generation = self.data_generation.wrapping_add(1);
5923    }
5924
5925    /// Apply a tombstone (already-durable on the WAL) at `epoch` without
5926    /// appending to the per-table WAL. Used by the cross-table `Transaction`.
5927    pub(crate) fn apply_delete(&mut self, row_id: RowId, epoch: Epoch) {
5928        self.apply_delete_at(row_id, epoch, None);
5929    }
5930
5931    /// Apply a tombstone stamped with an optional HLC commit timestamp (P0.5).
5932    pub(crate) fn apply_delete_at(
5933        &mut self,
5934        row_id: RowId,
5935        epoch: Epoch,
5936        commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
5937    ) {
5938        // Capture pre-image before the tombstone lands so (1) Kit delete+put
5939        // can re-point Bitmap keys via `recent_delete_preimages` (the subsequent
5940        // put finds a stale HOT entry, and `index_row` reads the preimage from
5941        // `recent_delete_preimages` to drive delta maintenance), and (2) the
5942        // HOT entry is preserved so a `Condition::Pk` lookup can observe the
5943        // tombstone via `self.get(r, snap) == None` and record
5944        // `HotFallbackReason::Tombstone` (and so a pinned-snapshot lookup
5945        // records `HistoricalSnapshot` on the HOT-hit branch instead of
5946        // degrading to `MissingMapping` on the HOT-miss branch).
5947        let preimage = self.get(row_id, self.snapshot());
5948        if let Some(row) = preimage {
5949            if let Some(pk_col) = self.schema.primary_key() {
5950                if let Some(pk_val) = row.columns.get(&pk_col.id) {
5951                    let key = self.index_lookup_key(pk_col.id, pk_val);
5952                    self.recent_delete_preimages.insert(key, row);
5953                }
5954            }
5955        }
5956        self.tombstone_row(row_id, epoch, commit_ts, true);
5957        self.data_generation = self.data_generation.wrapping_add(1);
5958    }
5959
5960    /// Drop this row's membership from every Bitmap secondary (best-effort).
5961    /// Used on replace / partial-predicate paths that must re-point equality
5962    /// keys; pure deletes keep membership so historical snapshots can still
5963    /// discover the rid via BitmapEq (see [`Self::apply_delete_at`]).
5964    fn unindex_bitmap_membership(&mut self, row: &Row) {
5965        if row.deleted {
5966            return;
5967        }
5968        for idef in &self.schema.indexes {
5969            if idef.kind != crate::schema::IndexKind::Bitmap {
5970                continue;
5971            }
5972            if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
5973                if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
5974                    b.remove(&key, row.row_id);
5975                }
5976            }
5977        }
5978    }
5979
5980    /// Union Bitmap membership for a point (`lo == hi`) int64 range query into
5981    /// `set`, then re-merge overlay so pure-memtable rows still win. No-op when
5982    /// the column has no Bitmap index.
5983    fn union_bitmap_point_i64(
5984        &self,
5985        set: &mut RowIdSet,
5986        column_id: u16,
5987        value: i64,
5988        snapshot: Snapshot,
5989    ) {
5990        let Some(b) = self.bitmap.get(&column_id) else {
5991            return;
5992        };
5993        let encoded = Value::Int64(value).encode_key();
5994        let lookup = self.index_lookup_key_bytes(column_id, &encoded);
5995        for rid in b.get(&lookup).iter() {
5996            set.insert(u64::from(rid));
5997        }
5998        // Drop rids whose newest overlay version is a tombstone (append-only
5999        // leftovers). Live overlay versions for this value are re-inserted by
6000        // the overlay range scan.
6001        set.remove_many(self.overlay_tombstoned_rids(snapshot));
6002        self.range_scan_overlay_i64(set, column_id, value, value, snapshot);
6003    }
6004
6005    /// Tombstone `row_id` at `epoch`. When `adjust_live_count` is true the
6006    /// table's `live_count` is decremented (used on the live write path); during
6007    /// recovery the manifest is authoritative so the flag is false.
6008    ///
6009    /// `live_count` is decremented only when the prior visible version of
6010    /// `row_id` was a live row. A prior tombstone (either from earlier in this
6011    /// commit or from a previous commit) means the live-count adjustment has
6012    /// already happened — the cross-table `Transaction` path can call
6013    /// `tombstone_row` on the same rid twice in one commit (Delete + the
6014    /// Put's stale HOT tombstone), and standalone callers can hit the same
6015    /// rid twice across commits. Without this guard `live_count` drifts
6016    /// negative (saturating to 0) and `Table::count()` returns a value below
6017    /// the true live-row count.
6018    fn tombstone_row(
6019        &mut self,
6020        row_id: RowId,
6021        epoch: Epoch,
6022        commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
6023        adjust_live_count: bool,
6024    ) {
6025        let prev_was_live = if adjust_live_count {
6026            match self.memtable.get_version(row_id, epoch) {
6027                Some((_, prev)) => !prev.deleted,
6028                None => true,
6029            }
6030        } else {
6031            false
6032        };
6033        let tombstone = Row {
6034            row_id,
6035            committed_epoch: epoch,
6036            columns: std::collections::HashMap::new(),
6037            deleted: true,
6038            commit_ts,
6039        };
6040        self.memtable.upsert(tombstone);
6041        self.pk_by_row.remove(&row_id);
6042        if prev_was_live {
6043            self.live_count = self.live_count.saturating_sub(1);
6044        }
6045        // Track for fine-grained cache invalidation (c).
6046        self.pending_delete_rids.insert(row_id.0 as u32);
6047        // A delete makes the incremental aggregate cache (row-id watermark
6048        // delta) unsafe — permanently disable it for this table.
6049        self.had_deletes = true;
6050        self.agg_cache = Arc::new(HashMap::new());
6051    }
6052
6053    /// If `row_id` has a primary-key value and the HOT index currently maps
6054    /// that PK to this row id, remove the entry. Keeps the PK→RowId mapping
6055    /// consistent after deletes and before upserts.
6056    fn remove_hot_for_row(&mut self, row_id: RowId, epoch: Epoch) {
6057        let Some(pk_col) = self.schema.primary_key() else {
6058            return;
6059        };
6060        // Warm path: a prior delete in this process already paid the
6061        // reverse-map rebuild below, so it's kept up to date — O(1).
6062        if self.pk_by_row_complete {
6063            if let Some(key) = self.pk_by_row.remove(&row_id) {
6064                if self.hot.get(&key) == Some(row_id) {
6065                    self.hot.remove(&key);
6066                }
6067            }
6068            return;
6069        }
6070        // Cold path (the common case: a short-lived process — CLI,
6071        // NAPI-per-call — that deletes once and exits): derive the PK
6072        // straight from the row's own pre-delete version via a targeted
6073        // get_version lookup (memtable -> mutable_run -> runs, the same
6074        // page-pruned lookup `Table::get` uses) instead of paying
6075        // `refresh_pk_by_row_from_hot`'s O(table-size) rebuild for a single
6076        // delete. `pk_by_row` is deliberately left incomplete here — same
6077        // "puts leave the reverse map stale" tradeoff, extended to this path.
6078        //
6079        // Look up at `epoch - 1`, not `epoch`: on the live-delete call site
6080        // this delete's own tombstone hasn't landed yet either way, but on
6081        // the WAL-replay call sites (`recover_apply`, `open_in`) the
6082        // memtable tombstone for this exact row/epoch is already applied
6083        // before this runs. Querying `epoch` would see that tombstone
6084        // (empty columns) and fall through to the full rebuild every time a
6085        // replayed delete exists; `epoch - 1` is still >= any real prior
6086        // version's committed_epoch (epochs are unique and monotonic), so it
6087        // finds the same pre-delete row either way.
6088        let lookup_epoch = Epoch(epoch.0.saturating_sub(1));
6089        if self.indexes_complete {
6090            let pk_val = self
6091                .memtable
6092                .get_version(row_id, lookup_epoch)
6093                .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6094                .or_else(|| {
6095                    self.mutable_run
6096                        .get_version(row_id, lookup_epoch)
6097                        .filter(|(_, r)| !r.deleted)
6098                        .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6099                })
6100                .or_else(|| {
6101                    self.run_refs.iter().find_map(|rr| {
6102                        let mut reader = self.open_reader(rr.run_id).ok()?;
6103                        let (_, deleted, val) = reader
6104                            .get_version_column(row_id, lookup_epoch, pk_col.id)
6105                            .ok()??;
6106                        if deleted {
6107                            return None;
6108                        }
6109                        val
6110                    })
6111                });
6112            if let Some(pk_val) = pk_val {
6113                let key = self.index_lookup_key(pk_col.id, &pk_val);
6114                if self.hot.get(&key) == Some(row_id) {
6115                    self.hot.remove(&key);
6116                }
6117                return;
6118            }
6119        }
6120        // Fallback: full reverse-map rebuild, guaranteed correct. Reached
6121        // when indexes aren't complete yet, or the row was already gone by
6122        // the time this ran (e.g. already tombstoned in an overlay ahead of
6123        // this HOT cleanup, as `rebuild_indexes_from_runs` does).
6124        self.refresh_pk_by_row_from_hot();
6125        if let Some(key) = self.pk_by_row.remove(&row_id) {
6126            if self.hot.get(&key) == Some(row_id) {
6127                self.hot.remove(&key);
6128            }
6129        }
6130    }
6131
6132    /// For a batch of rows that share the same commit epoch, decide which rows
6133    /// win for each primary-key value. Returns the set of "loser" row ids that
6134    /// must be skipped/overwritten, and a map from PK lookup key to the winning
6135    /// row id. Rows without a PK value are always winners.
6136    fn partition_pk_winners(
6137        &self,
6138        rows: &[Row],
6139    ) -> (
6140        std::collections::HashSet<RowId>,
6141        std::collections::HashMap<Vec<u8>, RowId>,
6142    ) {
6143        let mut losers = std::collections::HashSet::new();
6144        let Some(pk_col) = self.schema.primary_key() else {
6145            return (losers, std::collections::HashMap::new());
6146        };
6147        let pk_id = pk_col.id;
6148        let mut winners: std::collections::HashMap<Vec<u8>, RowId> =
6149            std::collections::HashMap::new();
6150        for r in rows {
6151            let Some(pk_val) = r.columns.get(&pk_id) else {
6152                continue;
6153            };
6154            let key = self.index_lookup_key(pk_id, pk_val);
6155            if let Some(&old_rid) = winners.get(&key) {
6156                losers.insert(old_rid);
6157            }
6158            winners.insert(key, r.row_id);
6159        }
6160        (losers, winners)
6161    }
6162
6163    fn index_row(&mut self, row: &Row) {
6164        if row.deleted {
6165            return;
6166        }
6167        // Partial index filtering: skip rows that don't match any index's
6168        // predicate. The predicate is a SQL WHERE clause string evaluated
6169        // against the row's column values. For now, we support a simple
6170        // "column_name IS NOT NULL" and "column_name = value" syntax that
6171        // covers the common partial-index patterns (e.g. WHERE deleted_at
6172        // IS NULL). More complex predicates require a full expression
6173        // evaluator in core (future work).
6174        let any_predicate = self
6175            .schema
6176            .indexes
6177            .iter()
6178            .any(|idx| idx.predicate.is_some());
6179        if any_predicate {
6180            let columns_map: HashMap<u16, &Value> =
6181                row.columns.iter().map(|(k, v)| (*k, v)).collect();
6182            let name_to_id: HashMap<&str, u16> = self
6183                .schema
6184                .columns
6185                .iter()
6186                .map(|c| (c.name.as_str(), c.id))
6187                .collect();
6188            for idx in &self.schema.indexes {
6189                if let Some(pred) = &idx.predicate {
6190                    if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
6191                        continue; // skip this index for this row
6192                    }
6193                }
6194                // Index the row into this specific index only.
6195                index_into_single(
6196                    idx,
6197                    &self.schema,
6198                    row,
6199                    &mut self.hot,
6200                    &mut self.bitmap,
6201                    &mut self.ann,
6202                    &mut self.fm,
6203                    &mut self.sparse,
6204                    &mut self.minhash,
6205                );
6206            }
6207            return;
6208        }
6209        // Plaintext tables index the row as-is; only ENCRYPTED_INDEXABLE
6210        // columns need the tokenized copy (`tokenized_for_indexes` clones the
6211        // whole row, which would tax every put on unencrypted tables).
6212        if self.column_keys.is_empty() {
6213            index_into(
6214                &self.schema,
6215                row,
6216                &mut self.hot,
6217                &mut self.bitmap,
6218                &mut self.ann,
6219                &mut self.fm,
6220                &mut self.sparse,
6221                &mut self.minhash,
6222            );
6223            return;
6224        }
6225        let effective_row = self.tokenized_for_indexes(row);
6226        index_into(
6227            &self.schema,
6228            &effective_row,
6229            &mut self.hot,
6230            &mut self.bitmap,
6231            &mut self.ann,
6232            &mut self.fm,
6233            &mut self.sparse,
6234            &mut self.minhash,
6235        );
6236    }
6237
6238    /// Produce the row view that indexes should see. For ENCRYPTED_INDEXABLE
6239    /// equality (HMAC-eq) columns the plaintext value is replaced by its token,
6240    /// so the bitmap/HOT indexes store tokens. OPE-range columns keep their raw
6241    /// value (their range index is rebuilt from runs over plaintext). Plaintext
6242    /// tables return the row unchanged.
6243    fn tokenized_for_indexes(&self, row: &Row) -> Row {
6244        if self.column_keys.is_empty() {
6245            return row.clone();
6246        }
6247        {
6248            use crate::encryption::SCHEME_HMAC_EQ;
6249            let mut tok = row.clone();
6250            for (&cid, &(_, scheme)) in &self.column_keys {
6251                if scheme != SCHEME_HMAC_EQ {
6252                    continue;
6253                }
6254                if let Some(v) = tok.columns.get(&cid).cloned() {
6255                    if let Some(t) = self.tokenize_value(cid, &v) {
6256                        tok.columns.insert(cid, t);
6257                    }
6258                }
6259            }
6260            tok
6261        }
6262    }
6263
6264    /// Group-commit: make all pending writes durable, advance the epoch so they
6265    /// become visible, and persist the manifest. Dispatches on the WAL sink: a
6266    /// standalone table fsyncs its private WAL; a mounted table seals into the
6267    /// shared WAL and defers the fsync to the group-commit coordinator (B1).
6268    pub fn commit(&mut self) -> Result<Epoch> {
6269        self.commit_inner(None)
6270    }
6271
6272    /// Prepare a pending commit cooperatively, then invoke `before_commit`
6273    /// immediately before the durable transaction marker is appended.
6274    #[doc(hidden)]
6275    pub fn commit_controlled<F>(
6276        &mut self,
6277        control: &crate::ExecutionControl,
6278        mut before_commit: F,
6279    ) -> Result<Epoch>
6280    where
6281        F: FnMut() -> Result<()>,
6282    {
6283        self.commit_inner(Some((control, &mut before_commit)))
6284    }
6285
6286    fn commit_inner(
6287        &mut self,
6288        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6289    ) -> Result<Epoch> {
6290        self.ensure_writable()?;
6291        if !self.has_pending_mutations() {
6292            if self.current_txn_id == 0 && matches!(&self.wal, WalSink::Private(_)) {
6293                return Err(MongrelError::Full(
6294                    "standalone transaction id namespace exhausted".into(),
6295                ));
6296            }
6297            return Ok(self.epoch.visible());
6298        }
6299        self.commit_new_epoch_inner(controlled)
6300    }
6301
6302    /// Seal a real logical write at a fresh epoch. Bulk-load paths publish
6303    /// their run directly rather than staging rows in the WAL, so they call
6304    /// this after proving the input is non-empty.
6305    fn commit_new_epoch(&mut self) -> Result<Epoch> {
6306        self.commit_new_epoch_inner(None)
6307    }
6308
6309    fn commit_new_epoch_inner(
6310        &mut self,
6311        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6312    ) -> Result<Epoch> {
6313        self.ensure_writable()?;
6314        if self.is_shared() {
6315            self.commit_shared(controlled)
6316        } else {
6317            self.commit_private(controlled)
6318        }
6319    }
6320
6321    /// Standalone commit: fsync the private WAL under the commit lock.
6322    fn commit_private(
6323        &mut self,
6324        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6325    ) -> Result<Epoch> {
6326        // Serialize the assign→fsync→publish critical section across all tables
6327        // sharing the epoch authority so `visible` is published strictly in
6328        // assigned order (the dual-counter invariant).
6329        let commit_lock = Arc::clone(&self.commit_lock);
6330        let _g = commit_lock.lock();
6331        // Validate the private transaction namespace before allocating an
6332        // epoch or appending any terminal WAL record.
6333        let txn_id = self.ensure_txn_id()?;
6334        if let Some((control, before_commit)) = controlled {
6335            control.checkpoint()?;
6336            before_commit()?;
6337        }
6338        let new_epoch = self.epoch.bump_assigned();
6339        let epoch_authority = Arc::clone(&self.epoch);
6340        let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6341        // Seal the staged records under a TxnCommit marker carrying the commit
6342        // epoch, then a single group fsync. Recovery applies only records whose
6343        // txn has a durable TxnCommit (uncommitted/torn tails are discarded).
6344        let wal_result = match &mut self.wal {
6345            WalSink::Private(w) => w
6346                .append_txn(
6347                    txn_id,
6348                    Op::TxnCommit {
6349                        epoch: new_epoch.0,
6350                        added_runs: Vec::new(),
6351                    },
6352                )
6353                .and_then(|_| w.sync()),
6354            WalSink::Shared(_) => unreachable!("commit_private on a shared sink"),
6355            WalSink::ReadOnly => Err(MongrelError::ReadOnlyReplica),
6356        };
6357        if let Err(error) = wal_result {
6358            self.durable_commit_failed = true;
6359            return Err(MongrelError::CommitOutcomeUnknown {
6360                epoch: new_epoch.0,
6361                message: error.to_string(),
6362            });
6363        }
6364        // The commit marker is durable. Resolve the assigned epoch even when a
6365        // live publish/checkpoint step fails, and report the exact outcome.
6366        if let Some(epoch) = self.pending_truncate.take() {
6367            self.apply_truncate(epoch);
6368        }
6369        self.invalidate_pending_cache();
6370        let publish_result = self.persist_manifest(new_epoch);
6371        // Publish through the shared in-order gate so a `Table::commit` can never
6372        // advance the watermark past an in-flight cross-table transaction's
6373        // lower assigned epoch whose writes are not yet applied (spec §9.3e).
6374        self.epoch.publish_in_order(new_epoch);
6375        epoch_guard.disarm();
6376        if let Err(error) = publish_result {
6377            self.durable_commit_failed = true;
6378            return Err(MongrelError::DurableCommit {
6379                epoch: new_epoch.0,
6380                message: error.to_string(),
6381            });
6382        }
6383        self.current_txn_id = txn_id.checked_add(1).unwrap_or(0);
6384        self.pending_private_mutations = false;
6385        self.data_generation = self.data_generation.wrapping_add(1);
6386        Ok(new_epoch)
6387    }
6388
6389    /// Mounted commit (B1/B2): mirror the cross-table sequencer. Seal a
6390    /// `TxnCommit` into the shared WAL under the WAL lock (assigning the epoch in
6391    /// WAL-append order), make it durable via the group-commit coordinator (one
6392    /// leader fsync for the whole batch), then apply the staged rows at the
6393    /// assigned epoch and publish in order. Honors the shared poison flag.
6394    fn commit_shared(
6395        &mut self,
6396        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6397    ) -> Result<Epoch> {
6398        use std::sync::atomic::Ordering;
6399        let s = match &self.wal {
6400            WalSink::Shared(s) => s.clone(),
6401            WalSink::Private(_) => unreachable!("commit_shared on a private sink"),
6402            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6403        };
6404        if s.poisoned.load(Ordering::Relaxed) {
6405            return Err(MongrelError::Other(
6406                "database poisoned by fsync error".into(),
6407            ));
6408        }
6409        // Serialize the whole single-table commit critical section (assign →
6410        // durable → publish) under the shared commit lock so concurrent
6411        // `Table::commit`s publish strictly in assigned order and each returns
6412        // only once its epoch is visible (read-your-writes after commit). The
6413        // fsync still defers to the group-commit coordinator, which can batch a
6414        // held commit with concurrent cross-table `transaction()` committers.
6415        let commit_lock = Arc::clone(&self.commit_lock);
6416        let _g = commit_lock.lock();
6417        if !self.pending_rows.is_empty() {
6418            match controlled.as_ref() {
6419                Some((control, _)) => self.prepare_durable_publish_controlled(control)?,
6420                None => self.prepare_durable_publish()?,
6421            }
6422        }
6423        // Always seal a txn (allocating an id if this span had no writes) so the
6424        // epoch advances monotonically like the standalone path.
6425        let txn_id = self.ensure_txn_id()?;
6426        let mut wal = s.wal.lock();
6427        if let Some((control, before_commit)) = controlled {
6428            control.checkpoint()?;
6429            before_commit()?;
6430        }
6431        let new_epoch = self.epoch.bump_assigned();
6432        let epoch_authority = Arc::clone(&self.epoch);
6433        let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6434        // P0.5: stamp every row version with the database HLC so visibility is
6435        // HLC-authoritative on the single-table commit path too.
6436        let commit_ts = s.hlc.now().map_err(|skew| {
6437            MongrelError::Other(format!(
6438                "clock skew rejected commit timestamp allocation: {skew}"
6439            ))
6440        })?;
6441        let commit_seq = match wal.append_commit_at(
6442            txn_id,
6443            new_epoch,
6444            &[],
6445            commit_ts.physical_micros.saturating_mul(1_000),
6446        ) {
6447            Ok(commit_seq) => commit_seq,
6448            Err(error) => {
6449                s.poisoned.store(true, Ordering::Relaxed);
6450                s.lifecycle.poison();
6451                return Err(MongrelError::CommitOutcomeUnknown {
6452                    epoch: new_epoch.0,
6453                    message: error.to_string(),
6454                });
6455            }
6456        };
6457        drop(wal);
6458        if let Err(error) = s.group.await_durable(&s.wal, commit_seq) {
6459            s.poisoned.store(true, Ordering::Relaxed);
6460            s.lifecycle.poison();
6461            return Err(MongrelError::CommitOutcomeUnknown {
6462                epoch: new_epoch.0,
6463                message: error.to_string(),
6464            });
6465        }
6466
6467        // Apply staged state after durability, but never lose the durable
6468        // outcome if a live apply or manifest checkpoint fails.
6469        if self.pending_truncate.take().is_some() {
6470            self.apply_truncate(new_epoch);
6471        }
6472        let mut rows = std::mem::take(&mut self.pending_rows);
6473        if !rows.is_empty() {
6474            for r in &mut rows {
6475                r.committed_epoch = new_epoch;
6476                r.commit_ts = Some(commit_ts);
6477            }
6478            let auto_inc_flags = std::mem::take(&mut self.pending_rows_auto_inc);
6479            let all_auto_generated =
6480                auto_inc_flags.len() == rows.len() && auto_inc_flags.iter().all(|b| *b);
6481            self.apply_put_rows_inner_prepared(rows, !all_auto_generated);
6482        } else {
6483            self.pending_rows_auto_inc.clear();
6484        }
6485        let dels = std::mem::take(&mut self.pending_dels);
6486        for rid in dels {
6487            self.apply_delete_at(rid, new_epoch, Some(commit_ts));
6488        }
6489
6490        self.invalidate_pending_cache();
6491        let publish_result = self.persist_manifest(new_epoch);
6492        self.epoch.publish_in_order(new_epoch);
6493        epoch_guard.disarm();
6494        let _ = s.change_wake.send(());
6495        if let Err(error) = publish_result {
6496            self.durable_commit_failed = true;
6497            s.poisoned.store(true, Ordering::Relaxed);
6498            s.lifecycle.poison();
6499            return Err(MongrelError::DurableCommit {
6500                epoch: new_epoch.0,
6501                message: error.to_string(),
6502            });
6503        }
6504        // Next auto-commit span allocates a fresh shared txn id.
6505        self.current_txn_id = 0;
6506        self.data_generation = self.data_generation.wrapping_add(1);
6507        Ok(new_epoch)
6508    }
6509
6510    /// Commit, then drain the memtable into the mutable-run LSM tier (Phase
6511    /// 11.1). The tier absorbs flushes in place and only spills to an immutable
6512    /// `.sr` sorted run once it crosses the spill watermark — coalescing many
6513    /// small flushes into fewer, larger runs. While the tier holds un-spilled
6514    /// data the WAL is **not** rotated: the Flush marker / WAL rotation is
6515    /// deferred until the data is durably in a run, so crash recovery replays
6516    /// those rows back into the memtable (the tier rebuilds from replay).
6517    pub fn flush(&mut self) -> Result<Epoch> {
6518        self.flush_with_outcome().map(|(epoch, _)| epoch)
6519    }
6520
6521    /// Flush and report whether this call published pending logical mutations.
6522    pub fn flush_with_outcome(&mut self) -> Result<(Epoch, bool)> {
6523        self.flush_with_outcome_inner(None)
6524    }
6525
6526    /// Cooperatively prepare a flush, entering the commit fence immediately
6527    /// before its transaction marker can become durable.
6528    #[doc(hidden)]
6529    pub fn flush_with_outcome_controlled<F>(
6530        &mut self,
6531        control: &crate::ExecutionControl,
6532        mut before_commit: F,
6533    ) -> Result<(Epoch, bool)>
6534    where
6535        F: FnMut() -> Result<()>,
6536    {
6537        self.flush_with_outcome_inner(Some((control, &mut before_commit)))
6538    }
6539
6540    fn flush_with_outcome_inner(
6541        &mut self,
6542        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6543    ) -> Result<(Epoch, bool)> {
6544        match controlled.as_ref() {
6545            Some((control, _)) => {
6546                self.ensure_indexes_complete_controlled(control, || true)?;
6547            }
6548            None => self.ensure_indexes_complete()?,
6549        }
6550        let committed = self.has_pending_mutations();
6551        let epoch = self.commit_inner(controlled)?;
6552        let finish: Result<(Epoch, bool)> = (|| {
6553            let rows = self.memtable.drain_sorted();
6554            if !rows.is_empty() {
6555                self.mutable_run.insert_many(rows);
6556            }
6557            if self.mutable_run.approx_bytes() >= self.mutable_run_spill_bytes {
6558                self.spill_mutable_run(epoch)?;
6559                // The tier is now empty and its data is durably in a run → safe to
6560                // mark the WAL flushed (and, for a private WAL, rotate to a fresh
6561                // segment so the flushed records aren't replayed).
6562                self.mark_flushed(epoch)?;
6563                self.persist_manifest(epoch)?;
6564                self.build_learned_ranges()?;
6565                // Memtable is drained and runs are stable → checkpoint the indexes so
6566                // the next open skips the full run scan (Phase 9.1).
6567                self.checkpoint_indexes(epoch);
6568                // Issue 4: rebuild + publish the run-lookup directory so the
6569                // next open fast-paths point lookups. Failure is non-fatal —
6570                // the manifest is already durable so the table reopens and
6571                // rebuilds the directory lazily.
6572                let _ = self.publish_run_lookup_directory();
6573            }
6574            // else: data coalesced in the in-memory tier; the WAL still covers it
6575            // and the manifest epoch was already persisted by `commit`.
6576            Ok((epoch, committed))
6577        })();
6578        let outcome = match finish {
6579            Err(error) if committed => Err(MongrelError::DurableCommit {
6580                epoch: epoch.0,
6581                message: error.to_string(),
6582            }),
6583            result => result,
6584        };
6585        if outcome.is_ok() {
6586            // S1C-001: the base changed (the memtable drained into the
6587            // mutable-run tier and may have spilled to a new run) — publish a
6588            // fresh immutable view for generation readers. Indexes were
6589            // ensured complete above, so publishing cannot fail; if it ever
6590            // did, the previous (still valid) view stays published.
6591            let _ = self.publish_read_generation();
6592        }
6593        outcome
6594    }
6595
6596    pub(crate) fn has_pending_mutations(&self) -> bool {
6597        self.pending_private_mutations
6598            || !self.pending_rows.is_empty()
6599            || !self.pending_dels.is_empty()
6600            || self.pending_truncate.is_some()
6601    }
6602
6603    pub fn has_pending_writes(&self) -> bool {
6604        self.has_pending_mutations()
6605    }
6606
6607    /// Force a full flush to a `.sr` sorted run regardless of the spill
6608    /// threshold. Temporarily lowers `mutable_run_spill_bytes` to 1 so the
6609    /// threshold check in [`Self::flush`] always fires. Used by
6610    /// [`Self::close`] and the Kit's flush-on-close path (§4.4) so a
6611    /// short-lived process (CLI, one-shot script) leaves all pending writes
6612    /// durable in a run — keeping WAL segment count bounded across repeated
6613    /// invocations. Best-effort: errors are propagated but the threshold is
6614    /// always restored.
6615    pub fn force_flush(&mut self) -> Result<Epoch> {
6616        let saved = self.mutable_run_spill_bytes;
6617        self.mutable_run_spill_bytes = 1;
6618        let result = self.flush();
6619        self.mutable_run_spill_bytes = saved;
6620        result
6621    }
6622
6623    /// Best-effort close: force-flush any pending writes to a sorted run so
6624    /// the WAL segments can be reaped on the next open. Never panics — a
6625    /// flush error is logged and returned but the threshold is always
6626    /// restored. Call this as the last action before a short-lived process
6627    /// exits (CLI, one-shot script). Not needed for the daemon (its
6628    /// background auto-compactor handles run management). (§4.4)
6629    pub fn close(&mut self) -> Result<()> {
6630        if self.memtable_len() > 0 || self.mutable_run_len() > 0 {
6631            self.force_flush()?;
6632        }
6633        // Drain the persistent result cache: best-effort, deadline-bounded
6634        // shutdown of the background writer. Closing the table should not
6635        // block forever; ops still queued at the deadline are abandoned
6636        // (counted on the writer's `result_cache_persist_shutdown_abandoned_total`
6637        // metric) but the queue lock is released.
6638        self.result_cache
6639            .lock()
6640            .shutdown_persistent_cache(std::time::Duration::from_secs(5));
6641        Ok(())
6642    }
6643
6644    /// Mark `epoch` as flushed: append a `Flush` marker to the WAL, advance
6645    /// `flushed_epoch`, and — for a private WAL only — rotate to a fresh segment
6646    /// so the now-durable-in-a-run records are not replayed. A mounted table's
6647    /// shared WAL is never rotated per-table; recovery skips its already-flushed
6648    /// records via the manifest `flushed_epoch` gate, and segment GC (B3c) reaps
6649    /// them once every table has flushed past them.
6650    /// True when this table has no WAL replay gate to advance (read-only
6651    /// replica sink). Compaction consults this before advancing
6652    /// `flushed_epoch`.
6653    pub(crate) fn wal_is_read_only(&self) -> bool {
6654        matches!(self.wal, WalSink::ReadOnly)
6655    }
6656
6657    /// Move committed memtable rows (committed at or below `epoch`) into the
6658    /// mutable run, leaving pending, uncommitted rows (which sit at
6659    /// `pending_epoch = visible + 1`) in the memtable. Compaction calls this
6660    /// before snapshotting the merge input so publishing can advance the WAL
6661    /// replay gate without stranding committed rows outside the runs.
6662    pub(crate) fn drain_committed_memtable_rows(&mut self, epoch: Epoch) {
6663        if self.memtable_len() == 0 {
6664            return;
6665        }
6666        let rows = self.memtable.drain_sorted();
6667        let mut pending = Vec::new();
6668        let mut committed = Vec::new();
6669        for row in rows {
6670            if row.committed_epoch > epoch {
6671                pending.push(row);
6672            } else {
6673                committed.push(row);
6674            }
6675        }
6676        if !committed.is_empty() {
6677            self.mutable_run.insert_many(committed);
6678        }
6679        for row in pending {
6680            self.memtable.upsert(row);
6681        }
6682    }
6683
6684    pub(crate) fn mark_flushed(&mut self, epoch: Epoch) -> Result<()> {
6685        let op = Op::Flush {
6686            table_id: self.table_id,
6687            flushed_epoch: epoch.0,
6688        };
6689        match &mut self.wal {
6690            WalSink::Private(w) => {
6691                w.append_system(op)?;
6692                w.sync()?;
6693            }
6694            WalSink::Shared(s) => {
6695                // Informational in the shared log (recovery gates on the manifest
6696                // `flushed_epoch`); not separately fsynced — the run + manifest
6697                // are the durability point and the underlying rows were already
6698                // fsynced at their commit.
6699                s.wal.lock().append_system(op)?;
6700            }
6701            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6702        }
6703        self.flushed_epoch = epoch.0;
6704        if matches!(self.wal, WalSink::Private(_)) {
6705            self.rotate_wal(epoch)?;
6706        }
6707        Ok(())
6708    }
6709
6710    /// Spill the mutable-run tier to a new immutable level-0 sorted run. The
6711    /// caller owns the Flush-marker / WAL-rotation / manifest steps (only valid
6712    /// once all in-flight data is in runs). No-op when the tier is empty.
6713    fn spill_mutable_run(&mut self, epoch: Epoch) -> Result<()> {
6714        if self.mutable_run.is_empty() {
6715            return Ok(());
6716        }
6717        let run_id = self.alloc_run_id()?;
6718        let rows = self.mutable_run.drain_sorted();
6719        if rows.is_empty() {
6720            return Ok(());
6721        }
6722        let path = self.run_path(run_id);
6723        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
6724        if let Some(kek) = &self.kek {
6725            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6726        }
6727        let header = match self.create_run_file(run_id)? {
6728            Some(file) => writer.write_file(file, &rows)?,
6729            None => writer.write(&path, &rows)?,
6730        };
6731        self.run_refs.push(RunRef {
6732            run_id: run_id as u128,
6733            level: 0,
6734            epoch_created: epoch.0,
6735            row_count: header.row_count,
6736        });
6737        self.run_row_id_ranges
6738            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6739        Ok(())
6740    }
6741
6742    /// Tune the mutable-run spill watermark (bytes). A smaller threshold spills
6743    /// sooner (more, smaller runs — closer to the pre-Phase-11.1 behavior); a
6744    /// larger one coalesces more flushes in memory.
6745    pub fn set_mutable_run_spill_bytes(&mut self, bytes: u64) {
6746        self.mutable_run_spill_bytes = bytes.max(1);
6747    }
6748
6749    /// Set the zstd compression level for compaction output (Phase 18.1).
6750    /// Default 3; higher values give better compression ratio at the cost of
6751    /// slower compaction.
6752    pub fn set_compaction_zstd_level(&mut self, level: i32) {
6753        self.compaction_zstd_level = level;
6754    }
6755
6756    /// Set the result-cache byte budget (Phase 19.1 hardening (a)). Entries are
6757    /// evicted in access-order LRU past this limit. Takes effect immediately
6758    /// (may evict entries if the new limit is smaller than the current footprint).
6759    pub fn set_result_cache_max_bytes(&mut self, max_bytes: u64) {
6760        self.result_cache.lock().set_max_bytes(max_bytes);
6761    }
6762
6763    /// Wait for the persistent-cache writer to drain the pending queue, up
6764    /// to `deadline_ms` milliseconds. Returns the queue depth observed at
6765    /// the moment of the return (0 if fully drained). Tests use this to
6766    /// observe on-disk state without sleeping.
6767    pub fn flush_persistent_cache(&self, deadline_ms: u64) -> u64 {
6768        self.result_cache
6769            .lock()
6770            .flush_persistent_cache(std::time::Duration::from_millis(deadline_ms))
6771    }
6772
6773    /// Shut down the persistent-cache writer, draining pending ops until
6774    /// either the queue is empty or `deadline_ms` milliseconds have passed.
6775    /// The worker thread is joined on return. Tests and `Database::close`
6776    /// use this.
6777    pub fn shutdown_persistent_cache(&mut self, deadline_ms: u64) {
6778        self.result_cache
6779            .lock()
6780            .shutdown_persistent_cache(std::time::Duration::from_millis(deadline_ms));
6781    }
6782
6783    /// Test-only: set the minimum cache entry size (approx bytes) below
6784    /// which the persistent tier is skipped. A value of `0` always
6785    /// publishes to disk. Used by the REM-002 production tests so small
6786    /// fixtures can exercise the on-disk path without 4 KiB of data.
6787    #[doc(hidden)]
6788    pub fn _set_persist_min_bytes_for_test(&mut self, min: u64) {
6789        self.result_cache.lock().set_persist_min_bytes(min);
6790    }
6791
6792    /// Test seam (REM-D §8.8): when `enabled`, the next
6793    /// `Table::create` / `Table::open` on **this thread** fails its
6794    /// persistent-cache worker spawn and marks publication
6795    /// `Disabled(WorkerSpawnFailed)`. Thread-local, so concurrently running
6796    /// tests are unaffected. Callers should reset it with
6797    /// `_force_persistent_worker_spawn_failure_for_test(false)` after use.
6798    #[doc(hidden)]
6799    pub fn _force_persistent_worker_spawn_failure_for_test(enabled: bool) {
6800        PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.set(enabled));
6801    }
6802
6803    /// Explicit administrative flush (REM-D §8.6): synchronously persist the
6804    /// in-memory cached entry for `q` through the maintenance path
6805    /// (`persist_entry_synchronously_for_maintenance`), even when the
6806    /// background writer is unavailable. Returns `true` when an in-memory
6807    /// entry existed and a frame write was attempted. Never used by the
6808    /// query path; intended for migration tools and format-parity tests.
6809    #[doc(hidden)]
6810    pub fn _persist_cached_entry_synchronously_for_maintenance(
6811        &mut self,
6812        q: &crate::query::Query,
6813    ) -> bool {
6814        let key = crate::query::canonical_query_key(&q.conditions, None, 0)
6815            ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
6816            ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
6817        let identity = PersistentCacheIdentity {
6818            table_id: self.table_id(),
6819            schema_id: self.schema.schema_id,
6820            logical_generation: self.current_epoch().0,
6821        };
6822        let mut cache = self.result_cache.lock();
6823        let Some(entry) = cache.entries.get(&key).map(|e| e.clone_for_persist()) else {
6824            return false;
6825        };
6826        let entry_generation = cache.allocate_persist_generation(key);
6827        let context = PersistContext {
6828            identity,
6829            key,
6830            entry_generation,
6831        };
6832        cache.persist_entry_synchronously_for_maintenance(context, &entry);
6833        true
6834    }
6835
6836    /// Drop every cached result (used by compaction, schema evolution, and bulk
6837    /// load — paths that change run layout or data without going through the
6838    /// fine-grained `pending_*` tracking).
6839    pub(crate) fn clear_result_cache(&mut self) {
6840        self.result_cache.lock().clear();
6841    }
6842
6843    /// Number of versions currently held in the mutable-run tier.
6844    pub fn mutable_run_len(&self) -> usize {
6845        self.mutable_run.len()
6846    }
6847
6848    /// Drain every version from the mutable-run tier (ascending `(RowId,
6849    /// Epoch)` order). Used by compaction to fold the tier into its merge.
6850    pub(crate) fn drain_mutable_run(&mut self) -> Vec<Row> {
6851        self.mutable_run.drain_sorted()
6852    }
6853
6854    /// Snapshot the mutable-run tier without changing live table state.
6855    pub(crate) fn snapshot_mutable_run(&self) -> Vec<Row> {
6856        let mut snapshot = self.mutable_run.clone();
6857        snapshot.drain_sorted()
6858    }
6859
6860    /// Bulk-load: write `batch` directly to a new sorted run, bypassing the WAL
6861    /// and the memtable entirely (no per-row bincode, no skip-list inserts). The
6862    /// run + a rotated WAL + the manifest are fsynced once — the fast ingest
6863    /// path for large analytical loads. Indexes are still maintained.
6864    pub fn bulk_load(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Epoch> {
6865        self.ensure_writable()?;
6866        let n = batch.len();
6867        if n == 0 {
6868            return Ok(self.current_epoch());
6869        }
6870        for row in &batch {
6871            self.schema.validate_values(row)?;
6872        }
6873        let epoch = self.commit_new_epoch()?;
6874        let live_before = self.live_count;
6875        // Spill any pending mutable-run data first: bulk_load writes a Flush
6876        // marker + rotates the WAL below, which is only safe once all in-flight
6877        // data is durably in a run.
6878        self.spill_mutable_run(epoch)?;
6879        let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
6880            && self.indexes_complete
6881            && self.run_refs.is_empty()
6882            && self.memtable.is_empty()
6883            && self.mutable_run.is_empty();
6884        // Phase 14.7: route the legacy Value API through the same parallel
6885        // encode + typed batch-index path as `bulk_load_columns`. Transpose the
6886        // row-major sparse batch → column-major typed columns (in parallel),
6887        // then `write_native` + `index_columns_bulk`, instead of per-row
6888        // `Row { HashMap }` + `index_into` + the sequential `Value` writer.
6889        let mut user_columns: Vec<(u16, columnar::NativeColumn)> = {
6890            use rayon::prelude::*;
6891            self.schema
6892                .columns
6893                .par_iter()
6894                .map(|cdef| {
6895                    (
6896                        cdef.id,
6897                        columnar::rows_to_native(cdef.ty.clone(), &batch, cdef.id),
6898                    )
6899                })
6900                .collect::<Vec<_>>()
6901        };
6902        drop(batch);
6903        // Enforce NOT NULL constraints and primary-key upsert semantics before
6904        // any row id is allocated or bytes hit the run file. Losers of a
6905        // duplicate primary key are dropped from the encoded run entirely so
6906        // the dedup survives reopen (no ephemeral memtable tombstone).
6907        self.fill_auto_inc_native_columns(&mut user_columns, n)?;
6908        self.validate_columns_not_null(&user_columns, n)?;
6909        let winner_idx = self
6910            .bulk_pk_winner_indices(&user_columns, n)
6911            .filter(|idx| idx.len() != n);
6912        let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
6913            match winner_idx.as_deref() {
6914                Some(idx) => {
6915                    let compacted = user_columns
6916                        .iter()
6917                        .map(|(id, c)| (*id, c.gather(idx)))
6918                        .collect();
6919                    (compacted, idx.len())
6920                }
6921                None => (std::mem::take(&mut user_columns), n),
6922            };
6923        self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
6924        let first = self.allocator.alloc_range(write_n as u64)?.0;
6925        for rid in first..first + write_n as u64 {
6926            self.reservoir.offer(rid);
6927        }
6928        let run_id = self.alloc_run_id()?;
6929        let path = self.run_path(run_id);
6930        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0)
6931            .clean(true)
6932            .with_lz4()
6933            .with_native_endian();
6934        if let Some(kek) = &self.kek {
6935            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6936        }
6937        let header = match self.create_run_file(run_id)? {
6938            Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
6939            None => writer.write_native(&path, &write_columns, write_n, first)?,
6940        };
6941        self.run_refs.push(RunRef {
6942            run_id: run_id as u128,
6943            level: 0,
6944            epoch_created: epoch.0,
6945            row_count: header.row_count,
6946        });
6947        self.run_row_id_ranges
6948            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6949        self.live_count = self.live_count.saturating_add(write_n as u64);
6950        if eager_index_build {
6951            let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
6952            self.index_columns_bulk(&write_columns, &row_ids);
6953            self.indexes_complete = true;
6954            self.build_learned_ranges()?;
6955        } else {
6956            self.indexes_complete = false;
6957        }
6958        self.mark_flushed(epoch)?;
6959        self.persist_manifest(epoch)?;
6960        if eager_index_build {
6961            self.checkpoint_indexes(epoch);
6962        }
6963        self.clear_result_cache();
6964        Ok(epoch)
6965    }
6966
6967    /// Rotate the private WAL to a fresh segment. Only valid for a standalone
6968    /// table — a mounted table never rotates the shared WAL per-table.
6969    fn rotate_wal(&mut self, epoch: Epoch) -> Result<()> {
6970        let segment = next_wal_segment(&self.dir.join(WAL_DIR))?;
6971        let cipher = self.wal_dek.as_ref().map(|dk| make_cipher(dk));
6972        // The segment number (from the filename) namespaces nonces under the
6973        // constant WAL DEK — pass it through to the writer.
6974        let segment_no = segment
6975            .file_stem()
6976            .and_then(|s| s.to_str())
6977            .and_then(|s| s.strip_prefix("seg-"))
6978            .and_then(|s| s.parse::<u64>().ok())
6979            .unwrap_or(0);
6980        let mut wal = Wal::create_with_cipher(segment, epoch, cipher, segment_no)?;
6981        wal.set_sync_byte_threshold(self.sync_byte_threshold);
6982        wal.sync()?;
6983        self.wal = WalSink::Private(wal);
6984        Ok(())
6985    }
6986
6987    /// Fine-grained result-cache invalidation (hardening (c)): drop only
6988    /// entries whose footprint intersects a deleted RowId or whose
6989    /// condition-columns intersect a mutated column, then clear the pending
6990    /// sets. Called by `commit` and the cross-table transaction path.
6991    pub(crate) fn invalidate_pending_cache(&mut self) {
6992        self.result_cache
6993            .lock()
6994            .invalidate(&self.pending_delete_rids, &self.pending_put_cols);
6995        self.pending_delete_rids.clear();
6996        self.pending_put_cols.clear();
6997    }
6998
6999    pub(crate) fn persist_manifest(&self, epoch: Epoch) -> Result<()> {
7000        let mut m = Manifest::new(self.table_id, self.schema.schema_id);
7001        m.current_epoch = epoch.0;
7002        m.next_row_id = self.allocator.current().0;
7003        m.runs = self.run_refs.clone();
7004        m.live_count = self.live_count;
7005        m.global_idx_epoch = self.global_idx_epoch;
7006        m.flushed_epoch = self.flushed_epoch;
7007        m.retiring = self.retiring.clone();
7008        // Persist the authoritative counter only when seeded; otherwise write 0
7009        // so the next open still scans `max(PK)` on first use (an unseeded
7010        // lower bound from WAL replay is not safe to trust across a flush).
7011        m.auto_inc_next = match self.auto_inc {
7012            Some(ai) if ai.seeded => ai.next,
7013            _ => 0,
7014        };
7015        m.ttl = self.ttl;
7016        let meta_dek = self.manifest_meta_dek();
7017        match self._root_guard.as_deref() {
7018            Some(root) => manifest::write_durable(root, &mut m, meta_dek.as_ref())?,
7019            None => manifest::write_atomic(&self.dir, &mut m, meta_dek.as_ref())?,
7020        }
7021        Ok(())
7022    }
7023
7024    /// Rebuild the row-to-run lookup directory from the active run set and
7025    /// publish it as a sharded checkpoint in `_runs/`. Failure is non-fatal:
7026    /// the manifest is the authoritative source, the next open falls back to
7027    /// the range-scan path, and a subsequent flush rebuilds + republishes.
7028    /// Returns the resulting directory state so callers can keep the
7029    /// in-memory state in sync.
7030    pub(crate) fn publish_run_lookup_directory(&mut self) -> Result<()> {
7031        // Fire the `manifest.publication` fault hook so tests can simulate a
7032        // crash after the manifest is durable but before the directory
7033        // checkpoint lands.
7034        mongreldb_fault::inject("manifest.publication")
7035            .map_err(|e| MongrelError::Other(format!("manifest.publication fault: {e}")))?;
7036        let active_runs = self.run_refs.clone();
7037        let schema_id = self.schema.schema_id;
7038        let index_generation = self.global_idx_epoch;
7039        let run_generation = active_runs.len() as u64;
7040        let fingerprint = crate::run_lookup::compute_fingerprint(
7041            &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
7042            schema_id,
7043            index_generation,
7044            run_generation,
7045            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7046        );
7047        let dir = match crate::run_lookup::RunLookupDirectory::rebuild_from_runs(&active_runs, self)
7048        {
7049            Ok(d) => d,
7050            Err(error) => {
7051                // Failure to rebuild is non-fatal: the manifest is durable
7052                // and the next open will retry.
7053                self.run_lookup.complete = false;
7054                self.lookup_metrics
7055                    .directory_incomplete
7056                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7057                return Err(error);
7058            }
7059        };
7060        // Stamp the fingerprint on the in-memory directory before publishing
7061        // so the on-disk shards carry the exact value the open path will
7062        // compare against.
7063        let mut dir = dir;
7064        dir.set_fingerprint(fingerprint);
7065        let runs_dir = match self.runs_root.as_deref() {
7066            Some(root) => match root.io_path() {
7067                Ok(p) => p,
7068                Err(_) => self.dir.join(RUNS_DIR),
7069            },
7070            None => self.dir.join(RUNS_DIR),
7071        };
7072        // Best-effort fault hook so tests can intercept the temp-write + rename
7073        // boundary.
7074        mongreldb_fault::inject("directory.temp_write")
7075            .map_err(|e| MongrelError::Other(format!("directory.temp_write fault: {e}")))?;
7076        let publish =
7077            dir.write_checkpoint_sharded(&runs_dir, crate::run_lookup::DEFAULT_SHARD_BYTES);
7078        mongreldb_fault::inject("directory.sync")
7079            .map_err(|e| MongrelError::Other(format!("directory.sync fault: {e}")))?;
7080        mongreldb_fault::inject("directory.rename")
7081            .map_err(|e| MongrelError::Other(format!("directory.rename fault: {e}")))?;
7082        if let Err(error) = publish {
7083            // The manifest is still durable; mark the directory incomplete
7084            // and let the next open rebuild lazily.
7085            self.run_lookup = RunLookupState {
7086                directory: None,
7087                fingerprint,
7088                complete: false,
7089            };
7090            self.lookup_metrics
7091                .directory_incomplete
7092                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7093            self.lookup_metrics
7094                .directory_lookup_fallback
7095                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7096            return Err(error.into());
7097        }
7098        self.run_lookup = RunLookupState {
7099            directory: Some(std::sync::Arc::new(dir)),
7100            fingerprint,
7101            complete: true,
7102        };
7103        Ok(())
7104    }
7105
7106    pub(crate) fn plan_recovered_metadata(&mut self) -> Result<RecoveryMetadataPlan> {
7107        // `live_count` tracks logical tombstones, not wall-clock TTL expiry.
7108        // Use a time before every representable timestamp so TTL cannot hide a
7109        // row while rebuilding authoritative manifest metadata.
7110        let rows = self.visible_rows_at_time(Snapshot::unbounded(), i64::MIN)?;
7111        let live_count = u64::try_from(rows.len())
7112            .map_err(|_| MongrelError::Full("table live-row count exceeds u64".into()))?;
7113        let auto_inc = match self.auto_inc {
7114            Some(mut state) => {
7115                let maximum = self.scan_max_int64(state.column_id)?;
7116                let after_maximum = maximum.checked_add(1).ok_or_else(|| {
7117                    MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
7118                })?;
7119                state.next = state.next.max(after_maximum).max(1);
7120                state.seeded = true;
7121                Some(state)
7122            }
7123            None => None,
7124        };
7125        Ok(RecoveryMetadataPlan {
7126            live_count,
7127            auto_inc,
7128            changed: live_count != self.live_count
7129                || auto_inc.is_some_and(|planned| {
7130                    self.auto_inc.is_none_or(|current| {
7131                        current.next != planned.next || current.seeded != planned.seeded
7132                    })
7133                }),
7134        })
7135    }
7136
7137    pub(crate) fn apply_recovered_metadata(
7138        &mut self,
7139        plan: RecoveryMetadataPlan,
7140        epoch: Epoch,
7141    ) -> Result<()> {
7142        if !plan.changed {
7143            return Ok(());
7144        }
7145        self.live_count = plan.live_count;
7146        self.auto_inc = plan.auto_inc;
7147        self.persist_manifest(epoch)
7148    }
7149
7150    /// Checkpoint the in-memory secondary indexes to `_idx/global.idx` and stamp
7151    /// the manifest's `global_idx_epoch` (Phase 9.1). Call after the runs are
7152    /// stable and the memtable is drained (flush/bulk-load/compact) so the
7153    /// checkpoint exactly matches the run data; subsequent [`Table::open`] loads it
7154    /// directly instead of scanning every run.
7155    pub(crate) fn checkpoint_indexes(&mut self, epoch: Epoch) {
7156        // Never persist an incomplete index set (e.g. after bulk_load_columns,
7157        // which bypasses per-row indexing) — reopen rebuilds from the runs.
7158        if !self.indexes_complete {
7159            return;
7160        }
7161        // The reopen replay gate is the manifest's `flushed_epoch`: every
7162        // commit past it is re-applied (and re-indexed) from the WAL on open.
7163        // The live index maps also cover committed-but-unflushed rows
7164        // (memtable / mutable-run content), so a checkpoint stamped past
7165        // `flushed_epoch` would make replay double-index those rows (Sparse
7166        // dot-product scores double-count; ANN graphs gain duplicate nodes).
7167        // Only persist an image whose content is fully behind the gate.
7168        if epoch.0 > self.flushed_epoch {
7169            return;
7170        }
7171        // FND-006: a fired fault behaves like a failed checkpoint — the write
7172        // is best-effort and the next open simply rebuilds from the runs.
7173        if crate::catalog::inject_hook("index.publish.before").is_err() {
7174            return;
7175        }
7176        if self.idx_root.is_none() {
7177            if let Some(root) = self._root_guard.as_ref() {
7178                let Ok(idx_root) = root.create_directory_all_pinned(global_idx::IDX_DIR) else {
7179                    return;
7180                };
7181                self.idx_root = Some(Arc::new(idx_root));
7182            }
7183        }
7184        let snap = global_idx::IndexSnapshot {
7185            hot: &self.hot,
7186            bitmap: &self.bitmap,
7187            ann: &self.ann,
7188            fm: &self.fm,
7189            sparse: &self.sparse,
7190            minhash: &self.minhash,
7191            learned_range: &self.learned_range,
7192        };
7193        // Best-effort: a failed checkpoint just means the next open rebuilds.
7194        let idx_dek = self.idx_dek();
7195        let written = match self.idx_root.as_deref() {
7196            Some(root) => global_idx::write_atomic_root(
7197                root,
7198                self.table_id,
7199                epoch.0,
7200                snap,
7201                idx_dek.as_deref(),
7202            ),
7203            None => global_idx::write_atomic(
7204                &self.dir,
7205                self.table_id,
7206                epoch.0,
7207                snap,
7208                idx_dek.as_deref(),
7209            ),
7210        };
7211        if written.is_ok() {
7212            self.global_idx_epoch = epoch.0;
7213            let _ = self.persist_manifest(epoch);
7214            // FND-006: the index generation is published.
7215            let _ = crate::catalog::inject_hook("index.publish.after");
7216        }
7217    }
7218
7219    /// Drop any on-disk index checkpoint so the next open rebuilds from runs
7220    /// (used when the live indexes are known stale, e.g. compaction to empty).
7221    pub(crate) fn invalidate_index_checkpoint(&mut self) {
7222        self.global_idx_epoch = 0;
7223        if let Some(root) = self.idx_root.as_deref() {
7224            let _ = root.remove_file(global_idx::IDX_FILENAME);
7225        } else {
7226            global_idx::remove(&self.dir);
7227        }
7228        let _ = self.persist_manifest(self.epoch.visible());
7229    }
7230
7231    /// Prepare for replacing every run without publishing a second manifest.
7232    /// The caller persists the replacement topology after this returns.  An
7233    /// older checkpoint may remain on disk if deletion fails, but a manifest
7234    /// with `global_idx_epoch = 0` will never endorse it on reopen.
7235    pub(crate) fn prepare_indexes_for_run_replacement(&mut self) {
7236        self.indexes_complete = false;
7237        self.global_idx_epoch = 0;
7238        if let Some(root) = self.idx_root.as_deref() {
7239            let _ = root.remove_file(global_idx::IDX_FILENAME);
7240        } else {
7241            global_idx::remove(&self.dir);
7242        }
7243    }
7244
7245    pub(crate) fn finish_indexes_for_run_replacement(&mut self) {
7246        self.indexes_complete = true;
7247    }
7248
7249    /// A maintenance operation changed live run topology and could not prove
7250    /// the matching manifest publication.  Fail closed until recovery rebuilds
7251    /// one coherent view from durable state.  Mounted tables also poison their
7252    /// owning database so GC, DDL, and transactions cannot continue around the
7253    /// uncertain topology.
7254    pub(crate) fn poison_after_maintenance_publish_failure(&mut self) {
7255        self.durable_commit_failed = true;
7256        if let WalSink::Shared(shared) = &self.wal {
7257            shared
7258                .poisoned
7259                .store(true, std::sync::atomic::Ordering::Relaxed);
7260        }
7261    }
7262
7263    /// Invalidate a stale handle after DOCTOR has durably dropped its catalog
7264    /// entry. Other tables remain usable, but this handle must never append new
7265    /// writes for the quarantined table id.
7266    pub(crate) fn mark_unavailable_after_quarantine(&mut self) {
7267        self.durable_commit_failed = true;
7268    }
7269
7270    /// Read the row at `row_id` visible to `snapshot`, merging the newest
7271    /// version across the memtable, mutable-run tier, and all sorted runs.
7272    ///
7273    /// In-memory tiers use full-[`Snapshot`] HLC visibility (P0.5-T3). Sorted
7274    /// runs restore optional [`crate::sorted_run::SYS_COMMIT_TS`] when present
7275    /// and fall back to epoch-only for legacy runs; candidates are filtered
7276    /// with [`Snapshot::observes_row`] so HLC-stamped versions never win under
7277    /// an epoch-only pin.
7278    ///
7279    /// When the run-lookup directory is complete, the read path consults it
7280    /// to open only the runs whose locators may contain a visible version for
7281    /// this `row_id`. The existing range-scan path stays the safety net when
7282    /// the directory is missing or stale.
7283    ///
7284    /// REM-004: the directory consultation returns one of three explicit
7285    /// decisions ([`crate::run_lookup::DirectoryLookupDecision`]):
7286    ///
7287    /// - [`CompleteMiss`](crate::run_lookup::DirectoryLookupDecision::CompleteMiss) —
7288    ///   authoritative "no immutable run hosts this row"; open zero readers.
7289    /// - [`Candidates`](crate::run_lookup::DirectoryLookupDecision::Candidates) —
7290    ///   walk locators with the conservative filter plus a safe early-stop
7291    ///   proof ([`crate::run_lookup::RunLocator::can_contain_version_newer_than`]).
7292    /// - [`UnavailableOrStale`](crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale) —
7293    ///   fall back to the existing per-run range filter.
7294    pub fn get(&self, row_id: RowId, snapshot: Snapshot) -> Option<Row> {
7295        let mut best: Option<Row> = None;
7296        // `consider` is a free function (not a closure) so the caller can
7297        // also inspect `best` between iterations without colliding borrows.
7298        fn consider(best: &mut Option<Row>, row: Row, snapshot: Snapshot) {
7299            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7300                return;
7301            }
7302            if best.as_ref().is_none_or(|current| {
7303                Snapshot::version_is_newer(
7304                    row.committed_epoch,
7305                    row.commit_ts,
7306                    current.committed_epoch,
7307                    current.commit_ts,
7308                )
7309            }) {
7310                *best = Some(row);
7311            }
7312        }
7313        if let Some((_, row)) = self.memtable.get_version_at(row_id, snapshot) {
7314            consider(&mut best, row, snapshot);
7315        }
7316        if let Some((_, row)) = self.mutable_run.get_version_at(row_id, snapshot) {
7317            consider(&mut best, row, snapshot);
7318        }
7319        // Decide which runs to open. The directory is consulted only when it
7320        // is marked complete AND the active run set is non-empty; otherwise
7321        // we fall back to the per-run range filter below.
7322        let decision = if self.run_lookup.complete {
7323            // Defensive: verify the in-memory directory's fingerprint is
7324            // still consistent with the active run set. A divergence means
7325            // the directory is stale and we should fall back rather than
7326            // miss versions.
7327            let active_ids: Vec<u128> = self.run_refs.iter().map(|r| r.run_id).collect();
7328            let expected_fp = crate::run_lookup::compute_fingerprint(
7329                &active_ids,
7330                self.schema.schema_id,
7331                self.global_idx_epoch,
7332                active_ids.len() as u64,
7333                crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7334            );
7335            if self.run_lookup.fingerprint == expected_fp {
7336                match self.run_lookup.directory.as_ref() {
7337                    Some(dir) => dir.decide(row_id),
7338                    None => crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale,
7339                }
7340            } else {
7341                self.lookup_metrics
7342                    .directory_lookup_fallback
7343                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7344                crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7345            }
7346        } else {
7347            self.lookup_metrics
7348                .directory_lookup_fallback
7349                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7350            crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7351        };
7352        match decision {
7353            crate::run_lookup::DirectoryLookupDecision::CompleteMiss => {
7354                // REM-004: a complete directory miss is authoritative — the
7355                // memtable + mutable-run tiers have already been searched,
7356                // so no immutable run can host a visible version. Skip the
7357                // range scan and return whatever the in-memory tiers said.
7358                self.lookup_metrics
7359                    .directory_lookup_hit
7360                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7361                self.lookup_metrics
7362                    .directory_complete_miss_total
7363                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7364            }
7365            crate::run_lookup::DirectoryLookupDecision::Candidates(mut locators) => {
7366                // Snapshot-aware candidate ordering (REM-B §6.13): an
7367                // HLC-authoritative snapshot considers fully stamped
7368                // locators by newest possible visible HLC first; an
7369                // epoch-only snapshot stays epoch-first. Ordering is a
7370                // performance hint only — early-stop correctness never
7371                // depends on it.
7372                locators.sort_by(|a, b| {
7373                    if snapshot.uses_hlc_authority() {
7374                        b.max_hlc
7375                            .cmp(&a.max_hlc)
7376                            .then_with(|| b.max_epoch.cmp(&a.max_epoch))
7377                    } else {
7378                        b.max_epoch
7379                            .cmp(&a.max_epoch)
7380                            .then_with(|| b.max_hlc.cmp(&a.max_hlc))
7381                    }
7382                });
7383                // Apply the conservative snapshot filter and the safe
7384                // early-stop proof — locators that provably cannot contain a
7385                // visible version, or whose maximum visible version is
7386                // provably ≤ the current winner, are skipped. The remainder
7387                // is opened in newest-first order.
7388                let mut opened: std::collections::HashSet<u128> = std::collections::HashSet::new();
7389                let mut early_stopped: u64 = 0;
7390                for locator in &locators {
7391                    // REM-004 early-stop: once we have a winner, skip
7392                    // locators that provably cannot beat it.
7393                    let stamp = best
7394                        .as_ref()
7395                        .map(|current| crate::run_lookup::VersionStamp {
7396                            epoch: current.committed_epoch,
7397                            hlc: current.commit_ts,
7398                        });
7399                    if let Some(s) = stamp {
7400                        if !locator.can_contain_version_newer_than(s, snapshot) {
7401                            early_stopped += 1;
7402                            continue;
7403                        }
7404                    }
7405                    if locator.is_impossible_for(snapshot) {
7406                        continue;
7407                    }
7408                    if !opened.insert(locator.run_id) {
7409                        continue;
7410                    }
7411                    self.lookup_metrics
7412                        .directory_run_readers_opened
7413                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7414                    self.lookup_metrics
7415                        .get_run_opened
7416                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7417                    let Ok(Ok(Some((_, row)))) = self.with_run_reader(locator.run_id, |reader| {
7418                        reader.get_version_at(row_id, snapshot)
7419                    }) else {
7420                        continue;
7421                    };
7422                    consider(&mut best, row, snapshot);
7423                }
7424                if early_stopped > 0 {
7425                    self.lookup_metrics
7426                        .directory_early_stop_total
7427                        .fetch_add(early_stopped, std::sync::atomic::Ordering::Relaxed);
7428                }
7429                self.lookup_metrics
7430                    .directory_lookup_hit
7431                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7432            }
7433            crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale => {
7434                // Exact directory miss OR no directory: range-scan fallback.
7435                for rr in &self.run_refs {
7436                    // Skip runs whose RowId range cannot contain this key
7437                    // (populated from run headers on open/spill). Missing
7438                    // range falls through.
7439                    if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
7440                        if row_id.0 < min_rid || row_id.0 > max_rid {
7441                            self.lookup_metrics
7442                                .get_run_skipped
7443                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7444                            continue;
7445                        }
7446                    }
7447                    self.lookup_metrics
7448                        .get_run_opened
7449                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7450                    let Ok(Ok(Some((_, row)))) = self.with_run_reader(rr.run_id, |reader| {
7451                        reader.get_version_at(row_id, snapshot)
7452                    }) else {
7453                        continue;
7454                    };
7455                    consider(&mut best, row, snapshot);
7456                }
7457            }
7458        }
7459        let now_nanos = unix_nanos_now();
7460        match best {
7461            Some(r) if r.deleted || self.row_expired_at(&r, now_nanos) => None,
7462            Some(r) => Some(r),
7463            None => None,
7464        }
7465    }
7466
7467    /// All rows visible at `snapshot` (newest version per `RowId`, tombstones
7468    /// dropped), merged across the memtable, the mutable-run tier, and all
7469    /// runs. Ascending `RowId`.
7470    pub fn visible_rows(&self, snapshot: Snapshot) -> Result<Vec<Row>> {
7471        self.visible_rows_at_time(snapshot, unix_nanos_now())
7472    }
7473
7474    /// Materialize visible rows with cooperative checkpoints while merging
7475    /// page-bounded, already ordered tier cursors.
7476    #[doc(hidden)]
7477    pub fn visible_rows_controlled(
7478        &self,
7479        snapshot: Snapshot,
7480        control: &crate::ExecutionControl,
7481    ) -> Result<Vec<Row>> {
7482        let mut out = Vec::new();
7483        self.for_each_visible_row_controlled(snapshot, control, |row| {
7484            out.push(row);
7485            Ok(())
7486        })?;
7487        Ok(out)
7488    }
7489
7490    /// Visit visible rows in row-id order with a k-way merge over ordered tier
7491    /// cursors. No full-table merge map or row-id sort is constructed.
7492    #[doc(hidden)]
7493    pub fn for_each_visible_row_controlled<F>(
7494        &self,
7495        snapshot: Snapshot,
7496        control: &crate::ExecutionControl,
7497        mut visit: F,
7498    ) -> Result<()>
7499    where
7500        F: FnMut(Row) -> Result<()>,
7501    {
7502        // TODO §3: trace metrics for the controlled-scan path. The fields are
7503        // populated on the streaming path; today (memory_from_map +
7504        // into_visible_version_cursor) the buffer is still bounded, so the
7505        // counts are the right shape even if some are zero on this impl.
7506        // `versions_examined` is incremented inside the visitor closure so
7507        // cancellation is observed within the bounded buffer.
7508        let setup_start = std::time::Instant::now();
7509        let mut versions_examined: u64 = 0;
7510        let mut rows_emitted: u64 = 0;
7511        let mut checkpoints: u64 = 0;
7512        let mut first_row_recorded = false;
7513        let mut sources: Vec<ControlledVisibleSource<'_>> =
7514            Vec::with_capacity(self.run_refs.len() + 2);
7515        control.checkpoint()?;
7516        checkpoints += 1;
7517        // Hot-tier sources use borrowing cursors: only the current version
7518        // group is retained, so setup does not scale with the live row count.
7519        if !self.memtable.is_empty() {
7520            sources.push(ControlledVisibleSource::memtable_cursor(
7521                self.memtable.newest_visible_iter(&snapshot),
7522            ));
7523        }
7524        control.checkpoint()?;
7525        checkpoints += 1;
7526        if !self.mutable_run.is_empty() {
7527            sources.push(ControlledVisibleSource::mutable_run_cursor(
7528                self.mutable_run.newest_visible_iter(&snapshot),
7529            ));
7530        }
7531        for run in &self.run_refs {
7532            control.checkpoint()?;
7533            checkpoints += 1;
7534            let reader = self.open_reader(run.run_id)?;
7535            sources.push(ControlledVisibleSource::run(
7536                reader.into_visible_version_cursor_at(snapshot)?,
7537            ));
7538        }
7539        // Time-to-first-row includes source construction; setup_us captures
7540        // the construction cost separately.
7541        let first_row_start = setup_start;
7542        let _setup_us = setup_start.elapsed().as_micros() as u64;
7543        let now_nanos = unix_nanos_now();
7544        let mut first_row_us: u64 = 0;
7545        let result = merge_controlled_visible_sources(
7546            &mut sources,
7547            control,
7548            |row| self.row_expired_at(row, now_nanos),
7549            |row| {
7550                if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7551                    return Ok(());
7552                }
7553                versions_examined += 1;
7554                if !first_row_recorded {
7555                    first_row_us = first_row_start.elapsed().as_micros() as u64;
7556                    first_row_recorded = true;
7557                }
7558                rows_emitted += 1;
7559                visit(row)
7560            },
7561        );
7562        let time_to_first_row_us = if first_row_recorded { first_row_us } else { 0 };
7563        crate::trace::QueryTrace::record(|t| {
7564            t.controlled_scan_versions_examined = t
7565                .controlled_scan_versions_examined
7566                .saturating_add(versions_examined as usize);
7567            t.controlled_scan_rows_emitted = t
7568                .controlled_scan_rows_emitted
7569                .saturating_add(rows_emitted as usize);
7570            t.controlled_scan_checkpoints = t
7571                .controlled_scan_checkpoints
7572                .saturating_add(checkpoints as usize);
7573            t.controlled_scan_time_to_first_row_us = t
7574                .controlled_scan_time_to_first_row_us
7575                .saturating_add(time_to_first_row_us);
7576            t.controlled_scan_setup_time_us =
7577                t.controlled_scan_setup_time_us.saturating_add(_setup_us);
7578        });
7579        result
7580    }
7581
7582    #[doc(hidden)]
7583    pub fn visible_rows_at_time(&self, snapshot: Snapshot, now_nanos: i64) -> Result<Vec<Row>> {
7584        let mut best: HashMap<u64, Row> = HashMap::new();
7585        let mut fold = |row: Row| {
7586            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7587                return;
7588            }
7589            best.entry(row.row_id.0)
7590                .and_modify(|existing| {
7591                    if Snapshot::version_is_newer(
7592                        row.committed_epoch,
7593                        row.commit_ts,
7594                        existing.committed_epoch,
7595                        existing.commit_ts,
7596                    ) {
7597                        *existing = row.clone();
7598                    }
7599                })
7600                .or_insert(row);
7601        };
7602        for row in self.memtable.visible_versions_at(snapshot) {
7603            fold(row);
7604        }
7605        for row in self.mutable_run.visible_versions_at(snapshot) {
7606            fold(row);
7607        }
7608        for rr in &self.run_refs {
7609            let mut reader = self.open_reader(rr.run_id)?;
7610            // P0.5-T3: optional SYS_COMMIT_TS restored when present on the run.
7611            for row in reader.visible_versions_at(snapshot)? {
7612                fold(row);
7613            }
7614        }
7615        let mut out: Vec<Row> = best
7616            .into_values()
7617            .filter_map(|r| {
7618                if r.deleted || self.row_expired_at(&r, now_nanos) {
7619                    None
7620                } else {
7621                    Some(r)
7622                }
7623            })
7624            .collect();
7625        out.sort_by_key(|r| r.row_id);
7626        Ok(out)
7627    }
7628
7629    /// Visible data as columns (column_id → values) rather than rows — the
7630    /// vectorized scan path. Fast path: when the memtable is empty and there is
7631    /// exactly one run (the common post-flush analytical case), it computes the
7632    /// visible index set once and gathers each column, with **no per-row
7633    /// `HashMap`/`Row` materialization**. Falls back to [`Self::visible_rows`]
7634    /// pivoted to columns when the memtable is live or runs overlap.
7635    pub fn visible_columns(&self, snapshot: Snapshot) -> Result<Vec<(u16, Vec<Value>)>> {
7636        if self.ttl.is_none()
7637            && self.memtable.is_empty()
7638            && self.mutable_run.is_empty()
7639            && self.run_refs.len() == 1
7640        {
7641            let rr = self.run_refs[0].clone();
7642            let mut reader = self.open_reader(rr.run_id)?;
7643            let idxs = reader.visible_indices_at(snapshot)?;
7644            let mut cols = Vec::with_capacity(self.schema.columns.len());
7645            for cdef in &self.schema.columns {
7646                cols.push((cdef.id, reader.gather_column(cdef.id, &idxs)?));
7647            }
7648            return Ok(cols);
7649        }
7650        // Fallback: row merge, then pivot to columns.
7651        let rows = self.visible_rows(snapshot)?;
7652        let mut cols: Vec<(u16, Vec<Value>)> = self
7653            .schema
7654            .columns
7655            .iter()
7656            .map(|c| (c.id, Vec::with_capacity(rows.len())))
7657            .collect();
7658        for r in &rows {
7659            for (cid, vec) in cols.iter_mut() {
7660                vec.push(r.columns.get(cid).cloned().unwrap_or(Value::Null));
7661            }
7662        }
7663        Ok(cols)
7664    }
7665
7666    /// Resolve a primary-key value to a row id (latest version).
7667    pub fn lookup_pk(&self, key: &[u8]) -> Option<RowId> {
7668        let row_id = self.hot.get(key)?;
7669        if self.ttl.is_none() || self.get(row_id, Snapshot::unbounded()).is_some() {
7670            Some(row_id)
7671        } else {
7672            None
7673        }
7674    }
7675
7676    /// Snapshot of lookup + result-cache counters. Point-in-time copy suitable
7677    /// for `/metrics` exposition or test assertions. Cache counts come from the
7678    /// [`ResultCache`] mutex; HOT counts come from the in-table atomics.
7679    pub fn lookup_metrics_snapshot(&self) -> LookupMetricsSnapshot {
7680        let mut snap = self.lookup_metrics.snapshot();
7681        let cache = self.result_cache.lock();
7682        let (mem, disk, miss, write_us) = cache.cache_counters();
7683        snap.result_cache_memory_hit = mem;
7684        snap.result_cache_disk_hit = disk;
7685        snap.result_cache_miss = miss;
7686        snap.result_cache_persistent_write_us = write_us;
7687        // REM-D §8.7: publication-availability counters live on the cache.
7688        let (unavailable, skipped, spawn_failures, worker_shutdowns) = cache.publication_counters();
7689        snap.result_cache_persist_unavailable_total = unavailable;
7690        snap.result_cache_persist_skipped_total = skipped;
7691        snap.result_cache_worker_spawn_failures_total = spawn_failures;
7692        snap.result_cache_worker_shutdown_total = worker_shutdowns;
7693        // Merge the writer's persist counters so tests and observability
7694        // surfaces see the full picture.
7695        if let Some(writer_snap) = cache.persist_snapshot() {
7696            snap.result_cache_persist_enqueued_total =
7697                writer_snap.result_cache_persist_enqueued_total;
7698            snap.result_cache_persist_coalesced_total =
7699                writer_snap.result_cache_persist_coalesced_total;
7700            snap.result_cache_persist_dropped_store_total =
7701                writer_snap.result_cache_persist_dropped_store_total;
7702            snap.result_cache_persist_remove_total = writer_snap.result_cache_persist_remove_total;
7703            snap.result_cache_persist_stale_store_skipped_total =
7704                writer_snap.result_cache_persist_stale_store_skipped_total;
7705            snap.result_cache_persist_errors_total = writer_snap.result_cache_persist_errors_total;
7706            snap.result_cache_persist_shutdown_abandoned_total =
7707                writer_snap.result_cache_persist_shutdown_abandoned_total;
7708            snap.result_cache_persist_queue_depth = writer_snap.result_cache_persist_queue_depth;
7709        }
7710        snap
7711    }
7712
7713    /// Run a conjunctive query over the shared row-id space: each condition
7714    /// yields a candidate row-id set, the sets are intersected, and the
7715    /// survivors are materialized at the current snapshot. This is the AI-native
7716    /// "compose primitives" surface (`semsearch ∩ fm_contains ∩ cat_in`).
7717    pub fn query(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
7718        self.query_at_with_allowed(q, self.snapshot(), None)
7719    }
7720
7721    /// Run a native conjunctive query with cooperative cancellation through
7722    /// index resolution, scans, filtering, and row materialization.
7723    pub fn query_controlled(
7724        &mut self,
7725        q: &crate::query::Query,
7726        control: &crate::ExecutionControl,
7727    ) -> Result<Vec<Row>> {
7728        self.query_at_with_allowed_controlled(q, self.snapshot(), None, control)
7729    }
7730
7731    /// Execute a conjunctive query at one snapshot, applying authorization
7732    /// before ranked ANN, Sparse, and MinHash top-k selection.
7733    pub fn query_at_with_allowed(
7734        &mut self,
7735        q: &crate::query::Query,
7736        snapshot: Snapshot,
7737        allowed: Option<&std::collections::HashSet<RowId>>,
7738    ) -> Result<Vec<Row>> {
7739        self.query_at_with_allowed_after(q, snapshot, allowed, None)
7740    }
7741
7742    #[doc(hidden)]
7743    pub fn query_at_with_allowed_controlled(
7744        &mut self,
7745        q: &crate::query::Query,
7746        snapshot: Snapshot,
7747        allowed: Option<&std::collections::HashSet<RowId>>,
7748        control: &crate::ExecutionControl,
7749    ) -> Result<Vec<Row>> {
7750        self.require_select()?;
7751        self.ensure_indexes_complete_controlled(control, || true)?;
7752        self.validate_native_query(q)?;
7753        self.query_conditions_at(
7754            &q.conditions,
7755            snapshot,
7756            allowed,
7757            q.limit,
7758            q.offset,
7759            None,
7760            unix_nanos_now(),
7761            Some(control),
7762        )
7763    }
7764
7765    #[doc(hidden)]
7766    pub fn query_at_with_allowed_after(
7767        &mut self,
7768        q: &crate::query::Query,
7769        snapshot: Snapshot,
7770        allowed: Option<&std::collections::HashSet<RowId>>,
7771        after_row_id: Option<RowId>,
7772    ) -> Result<Vec<Row>> {
7773        self.query_at_with_allowed_after_at_time(
7774            q,
7775            snapshot,
7776            allowed,
7777            after_row_id,
7778            unix_nanos_now(),
7779        )
7780    }
7781
7782    #[doc(hidden)]
7783    pub fn query_at_with_allowed_after_at_time(
7784        &mut self,
7785        q: &crate::query::Query,
7786        snapshot: Snapshot,
7787        allowed: Option<&std::collections::HashSet<RowId>>,
7788        after_row_id: Option<RowId>,
7789        query_time_nanos: i64,
7790    ) -> Result<Vec<Row>> {
7791        self.require_select()?;
7792        self.ensure_indexes_complete()?;
7793        self.validate_native_query(q)?;
7794        self.query_conditions_at(
7795            &q.conditions,
7796            snapshot,
7797            allowed,
7798            q.limit,
7799            q.offset,
7800            after_row_id,
7801            query_time_nanos,
7802            None,
7803        )
7804    }
7805
7806    fn validate_native_query(&self, q: &crate::query::Query) -> Result<()> {
7807        if q.conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7808            return Err(MongrelError::InvalidArgument(format!(
7809                "query exceeds {} conditions",
7810                crate::query::MAX_HARD_CONDITIONS
7811            )));
7812        }
7813        if let Some(limit) = q.limit {
7814            if limit == 0 || limit > crate::query::MAX_FINAL_LIMIT {
7815                return Err(MongrelError::InvalidArgument(format!(
7816                    "query limit must be between 1 and {}",
7817                    crate::query::MAX_FINAL_LIMIT
7818                )));
7819            }
7820        }
7821        if q.offset > crate::query::MAX_QUERY_OFFSET {
7822            return Err(MongrelError::InvalidArgument(format!(
7823                "query offset exceeds {}",
7824                crate::query::MAX_QUERY_OFFSET
7825            )));
7826        }
7827        Ok(())
7828    }
7829
7830    /// Unbounded internal SQL join helper. Public request surfaces must use
7831    /// [`Self::query_at_with_allowed`] and its result ceiling.
7832    #[doc(hidden)]
7833    pub fn query_all_at(
7834        &mut self,
7835        conditions: &[crate::query::Condition],
7836        snapshot: Snapshot,
7837    ) -> Result<Vec<Row>> {
7838        self.require_select()?;
7839        self.ensure_indexes_complete()?;
7840        if conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7841            return Err(MongrelError::InvalidArgument(format!(
7842                "query exceeds {} conditions",
7843                crate::query::MAX_HARD_CONDITIONS
7844            )));
7845        }
7846        self.query_conditions_at(
7847            conditions,
7848            snapshot,
7849            None,
7850            None,
7851            0,
7852            None,
7853            unix_nanos_now(),
7854            None,
7855        )
7856    }
7857
7858    #[allow(clippy::too_many_arguments)]
7859    fn query_conditions_at(
7860        &self,
7861        conditions: &[crate::query::Condition],
7862        snapshot: Snapshot,
7863        allowed: Option<&std::collections::HashSet<RowId>>,
7864        limit: Option<usize>,
7865        offset: usize,
7866        after_row_id: Option<RowId>,
7867        query_time_nanos: i64,
7868        control: Option<&crate::ExecutionControl>,
7869    ) -> Result<Vec<Row>> {
7870        control
7871            .map(crate::ExecutionControl::checkpoint)
7872            .transpose()?;
7873        crate::trace::QueryTrace::record(|t| {
7874            t.run_count = self.run_refs.len();
7875            t.memtable_rows = self.memtable.len();
7876            t.mutable_run_rows = self.mutable_run.len();
7877        });
7878        // A conjunction with no predicates matches every visible row (the
7879        // documented "Empty ⇒ all rows" contract); `intersect_sets` of zero
7880        // sets would otherwise wrongly yield the empty set.
7881        if conditions.is_empty() {
7882            crate::trace::QueryTrace::record(|t| {
7883                t.scan_mode = crate::trace::ScanMode::Materialized;
7884                t.row_materialized = true;
7885            });
7886            let mut rows = match control {
7887                Some(control) => self.visible_rows_controlled(snapshot, control)?,
7888                None => self.visible_rows_at_time(snapshot, query_time_nanos)?,
7889            };
7890            if let Some(allowed) = allowed {
7891                let mut filtered = Vec::with_capacity(rows.len());
7892                for (index, row) in rows.into_iter().enumerate() {
7893                    if index & 255 == 0 {
7894                        control
7895                            .map(crate::ExecutionControl::checkpoint)
7896                            .transpose()?;
7897                    }
7898                    if allowed.contains(&row.row_id) {
7899                        filtered.push(row);
7900                    }
7901                }
7902                rows = filtered;
7903            }
7904            if let Some(after_row_id) = after_row_id {
7905                rows.retain(|row| row.row_id > after_row_id);
7906            }
7907            rows.drain(..offset.min(rows.len()));
7908            if let Some(limit) = limit {
7909                rows.truncate(limit);
7910            }
7911            return Ok(rows);
7912        }
7913        crate::trace::QueryTrace::record(|t| {
7914            t.conditions_pushed = conditions.len();
7915            t.scan_mode = crate::trace::ScanMode::Materialized;
7916            t.row_materialized = true;
7917        });
7918        // §5.5: resolve conditions CHEAP-FIRST and early-exit the moment a
7919        // condition yields an empty survivor set. Previously every condition
7920        // (including an expensive range/FM page scan) was resolved before
7921        // `intersect_many` noticed an empty set; now a selective bitmap/PK that
7922        // eliminates all rows short-circuits the rest. Correctness is unchanged
7923        // (intersection with an empty set is empty either way).
7924        let mut ordered: Vec<&crate::query::Condition> = conditions.iter().collect();
7925        ordered.sort_by_key(|c| condition_cost_rank(c));
7926        let mut sets: Vec<RowIdSet> = Vec::with_capacity(ordered.len());
7927        for c in &ordered {
7928            control
7929                .map(crate::ExecutionControl::checkpoint)
7930                .transpose()?;
7931            let s = self.resolve_condition_with_allowed(c, snapshot, allowed)?;
7932            let empty = s.is_empty();
7933            sets.push(s);
7934            if empty {
7935                break;
7936            }
7937        }
7938        let mut rids = RowIdSet::intersect_many(sets).into_sorted_vec();
7939        if let Some(allowed) = allowed {
7940            rids.retain(|row_id| allowed.contains(&RowId(*row_id)));
7941        }
7942        if let Some(after_row_id) = after_row_id {
7943            let first = rids.partition_point(|row_id| *row_id <= after_row_id.0);
7944            rids.drain(..first);
7945        }
7946        rids.drain(..offset.min(rids.len()));
7947        if let Some(limit) = limit {
7948            rids.truncate(limit);
7949        }
7950        control
7951            .map(crate::ExecutionControl::checkpoint)
7952            .transpose()?;
7953        self.rows_for_rids_at_time(&rids, snapshot, query_time_nanos, control)
7954    }
7955
7956    /// Return an index's ordered candidates without discarding scores.
7957    pub fn retrieve(
7958        &mut self,
7959        retriever: &crate::query::Retriever,
7960    ) -> Result<Vec<crate::query::RetrieverHit>> {
7961        self.retrieve_with_allowed(retriever, None)
7962    }
7963
7964    pub fn retrieve_at(
7965        &mut self,
7966        retriever: &crate::query::Retriever,
7967        snapshot: Snapshot,
7968        allowed: Option<&std::collections::HashSet<RowId>>,
7969    ) -> Result<Vec<crate::query::RetrieverHit>> {
7970        self.retrieve_at_with_allowed(retriever, snapshot, allowed)
7971    }
7972
7973    /// Scored retrieval restricted to caller-authorized row IDs. Core MVCC,
7974    /// tombstone, and TTL eligibility is always applied before ranking.
7975    pub fn retrieve_with_allowed(
7976        &mut self,
7977        retriever: &crate::query::Retriever,
7978        allowed: Option<&std::collections::HashSet<RowId>>,
7979    ) -> Result<Vec<crate::query::RetrieverHit>> {
7980        self.retrieve_at_with_allowed(retriever, self.snapshot(), allowed)
7981    }
7982
7983    pub fn retrieve_at_with_allowed(
7984        &mut self,
7985        retriever: &crate::query::Retriever,
7986        snapshot: Snapshot,
7987        allowed: Option<&std::collections::HashSet<RowId>>,
7988    ) -> Result<Vec<crate::query::RetrieverHit>> {
7989        self.retrieve_at_with_allowed_and_context(retriever, snapshot, allowed, None)
7990    }
7991
7992    pub fn retrieve_at_with_allowed_and_context(
7993        &mut self,
7994        retriever: &crate::query::Retriever,
7995        snapshot: Snapshot,
7996        allowed: Option<&std::collections::HashSet<RowId>>,
7997        context: Option<&crate::query::AiExecutionContext>,
7998    ) -> Result<Vec<crate::query::RetrieverHit>> {
7999        self.require_select()?;
8000        self.ensure_indexes_complete()?;
8001        self.validate_retriever(retriever)?;
8002        self.retrieve_filtered(retriever, snapshot, None, allowed, None, context)
8003    }
8004
8005    pub fn retrieve_at_with_candidate_authorization_and_context(
8006        &mut self,
8007        retriever: &crate::query::Retriever,
8008        snapshot: Snapshot,
8009        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8010        context: Option<&crate::query::AiExecutionContext>,
8011    ) -> Result<Vec<crate::query::RetrieverHit>> {
8012        self.require_select()?;
8013        self.ensure_indexes_complete()?;
8014        self.retrieve_at_with_candidate_authorization_on_generation(
8015            retriever,
8016            snapshot,
8017            authorization,
8018            context,
8019        )
8020    }
8021
8022    #[doc(hidden)]
8023    pub fn retrieve_at_with_candidate_authorization_on_generation(
8024        &self,
8025        retriever: &crate::query::Retriever,
8026        snapshot: Snapshot,
8027        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8028        context: Option<&crate::query::AiExecutionContext>,
8029    ) -> Result<Vec<crate::query::RetrieverHit>> {
8030        self.require_select()?;
8031        self.validate_retriever(retriever)?;
8032        self.retrieve_filtered(retriever, snapshot, None, None, authorization, context)
8033    }
8034
8035    fn validate_retriever(&self, retriever: &crate::query::Retriever) -> Result<()> {
8036        use crate::query::{Retriever, MAX_RETRIEVER_K, MAX_SET_MEMBERS, MAX_SPARSE_TERMS};
8037        let (column_id, k) = match retriever {
8038            Retriever::Ann {
8039                column_id,
8040                query,
8041                k,
8042            } => {
8043                let index = self.ann.get(column_id).ok_or_else(|| {
8044                    MongrelError::InvalidArgument(format!("column {column_id} has no ANN index"))
8045                })?;
8046                if query.len() != index.dim() {
8047                    return Err(MongrelError::InvalidArgument(format!(
8048                        "ANN query dimension must be {}, got {}",
8049                        index.dim(),
8050                        query.len()
8051                    )));
8052                }
8053                if query.iter().any(|value| !value.is_finite()) {
8054                    return Err(MongrelError::InvalidArgument(
8055                        "ANN query values must be finite".into(),
8056                    ));
8057                }
8058                (*column_id, *k)
8059            }
8060            Retriever::Sparse {
8061                column_id,
8062                query,
8063                k,
8064            } => {
8065                if !self.sparse.contains_key(column_id) {
8066                    return Err(MongrelError::InvalidArgument(format!(
8067                        "column {column_id} has no Sparse index"
8068                    )));
8069                }
8070                if query.is_empty() || query.iter().any(|(_, weight)| !weight.is_finite()) {
8071                    return Err(MongrelError::InvalidArgument(
8072                        "Sparse query must be non-empty with finite weights".into(),
8073                    ));
8074                }
8075                if query.len() > MAX_SPARSE_TERMS {
8076                    return Err(MongrelError::InvalidArgument(format!(
8077                        "Sparse query exceeds {MAX_SPARSE_TERMS} terms"
8078                    )));
8079                }
8080                (*column_id, *k)
8081            }
8082            Retriever::MinHash {
8083                column_id,
8084                members,
8085                k,
8086            } => {
8087                if !self.minhash.contains_key(column_id) {
8088                    return Err(MongrelError::InvalidArgument(format!(
8089                        "column {column_id} has no MinHash index"
8090                    )));
8091                }
8092                if members.is_empty() {
8093                    return Err(MongrelError::InvalidArgument(
8094                        "MinHash members must not be empty".into(),
8095                    ));
8096                }
8097                if members.len() > MAX_SET_MEMBERS {
8098                    return Err(MongrelError::InvalidArgument(format!(
8099                        "MinHash query exceeds {MAX_SET_MEMBERS} members"
8100                    )));
8101                }
8102                let mut total_bytes = 0usize;
8103                for member in members {
8104                    let bytes = member.encoded_len();
8105                    if bytes > crate::query::MAX_SET_MEMBER_BYTES {
8106                        return Err(MongrelError::InvalidArgument(format!(
8107                            "MinHash member exceeds {} bytes",
8108                            crate::query::MAX_SET_MEMBER_BYTES
8109                        )));
8110                    }
8111                    total_bytes = total_bytes.checked_add(bytes).ok_or_else(|| {
8112                        MongrelError::InvalidArgument("MinHash input size overflow".into())
8113                    })?;
8114                }
8115                if total_bytes > crate::query::MAX_SET_INPUT_BYTES {
8116                    return Err(MongrelError::InvalidArgument(format!(
8117                        "MinHash input exceeds {} bytes",
8118                        crate::query::MAX_SET_INPUT_BYTES
8119                    )));
8120                }
8121                (*column_id, *k)
8122            }
8123        };
8124        if k == 0 {
8125            return Err(MongrelError::InvalidArgument(
8126                "retriever k must be > 0".into(),
8127            ));
8128        }
8129        if k > MAX_RETRIEVER_K {
8130            return Err(MongrelError::InvalidArgument(format!(
8131                "retriever k exceeds {MAX_RETRIEVER_K}"
8132            )));
8133        }
8134        debug_assert!(self
8135            .schema
8136            .columns
8137            .iter()
8138            .any(|column| column.id == column_id));
8139        Ok(())
8140    }
8141
8142    fn validate_condition(&self, condition: &crate::query::Condition) -> Result<()> {
8143        use crate::query::Condition;
8144        match condition {
8145            Condition::Ann {
8146                column_id,
8147                query,
8148                k,
8149            } => self.validate_retriever(&crate::query::Retriever::Ann {
8150                column_id: *column_id,
8151                query: query.clone(),
8152                k: *k,
8153            }),
8154            Condition::SparseMatch {
8155                column_id,
8156                query,
8157                k,
8158            } => self.validate_retriever(&crate::query::Retriever::Sparse {
8159                column_id: *column_id,
8160                query: query.clone(),
8161                k: *k,
8162            }),
8163            Condition::MinHashSimilar {
8164                column_id,
8165                query,
8166                k,
8167            } => {
8168                if !self.minhash.contains_key(column_id) {
8169                    return Err(MongrelError::InvalidArgument(format!(
8170                        "column {column_id} has no MinHash index"
8171                    )));
8172                }
8173                if query.is_empty() || *k == 0 {
8174                    return Err(MongrelError::InvalidArgument(
8175                        "MinHash query must be non-empty and k must be > 0".into(),
8176                    ));
8177                }
8178                if query.len() > crate::query::MAX_SET_MEMBERS || *k > crate::query::MAX_RETRIEVER_K
8179                {
8180                    return Err(MongrelError::InvalidArgument(format!(
8181                        "MinHash query must have <= {} members and k <= {}",
8182                        crate::query::MAX_SET_MEMBERS,
8183                        crate::query::MAX_RETRIEVER_K
8184                    )));
8185                }
8186                Ok(())
8187            }
8188            Condition::BitmapIn { values, .. } if values.len() > crate::query::MAX_SET_MEMBERS => {
8189                Err(MongrelError::InvalidArgument(format!(
8190                    "bitmap IN exceeds {} values",
8191                    crate::query::MAX_SET_MEMBERS
8192                )))
8193            }
8194            Condition::FmContainsAll { patterns, .. }
8195                if patterns.len() > crate::query::MAX_HARD_CONDITIONS =>
8196            {
8197                Err(MongrelError::InvalidArgument(format!(
8198                    "FM query exceeds {} patterns",
8199                    crate::query::MAX_HARD_CONDITIONS
8200                )))
8201            }
8202            _ => Ok(()),
8203        }
8204    }
8205
8206    fn retrieve_filtered(
8207        &self,
8208        retriever: &crate::query::Retriever,
8209        snapshot: Snapshot,
8210        hard_filter: Option<&RowIdSet>,
8211        allowed: Option<&std::collections::HashSet<RowId>>,
8212        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8213        context: Option<&crate::query::AiExecutionContext>,
8214    ) -> Result<Vec<crate::query::RetrieverHit>> {
8215        use crate::query::{Retriever, RetrieverHit, RetrieverScore};
8216        let started = std::time::Instant::now();
8217        let scored: Vec<(RowId, RetrieverScore)> = match retriever {
8218            Retriever::Ann {
8219                column_id,
8220                query,
8221                k,
8222            } => {
8223                let Some(index) = self.ann.get(column_id) else {
8224                    return Ok(Vec::new());
8225                };
8226                let cap = ann_candidate_cap(index.len(), context);
8227                crate::trace::QueryTrace::record(|trace| trace.candidate_cap = cap);
8228                if cap == 0 {
8229                    return Ok(Vec::new());
8230                }
8231                let mut breadth = (*k).max(1).min(cap);
8232                let mut eligibility = std::collections::HashMap::new();
8233                // Cumulative trace counters across widening iterations
8234                // (spec §7.5: raw / visibility / authorization rejection
8235                // accounting; the candidate cap and `candidate_cap_hit`
8236                // are written when the loop terminates).
8237                let mut raw_candidates_total: usize = 0;
8238                let mut visibility_rejected_total: usize = 0;
8239                let mut authorization_rejected_total: usize = 0;
8240                let mut candidate_cap_hit_final = false;
8241                let mut filtered = loop {
8242                    let mut seen = std::collections::HashSet::new();
8243                    if let Some(context) = context {
8244                        context.checkpoint()?;
8245                    }
8246                    let raw = index.search_with_context(query, breadth, context)?;
8247                    crate::trace::QueryTrace::record(|trace| {
8248                        trace.raw_candidates = raw.len();
8249                        let unique = raw
8250                            .iter()
8251                            .map(|(row_id, _)| *row_id)
8252                            .collect::<std::collections::HashSet<_>>()
8253                            .len();
8254                        trace.unique_candidates = unique;
8255                        trace.duplicate_candidates = raw.len().saturating_sub(unique);
8256                        trace.authorization_rejected = raw
8257                            .iter()
8258                            .filter(|(row_id, _)| {
8259                                allowed.is_some_and(|allowed| !allowed.contains(row_id))
8260                            })
8261                            .count();
8262                        trace.hard_filter_rejected = raw
8263                            .iter()
8264                            .filter(|(row_id, _)| {
8265                                hard_filter.is_some_and(|filter| !filter.contains(row_id.0))
8266                            })
8267                            .count();
8268                    });
8269                    raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8270                    let unchecked: Vec<_> = raw
8271                        .iter()
8272                        .map(|(row_id, _)| *row_id)
8273                        .filter(|row_id| !eligibility.contains_key(row_id))
8274                        .filter(|row_id| {
8275                            hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8276                                && allowed.is_none_or(|allowed| allowed.contains(row_id))
8277                        })
8278                        .collect();
8279                    let eligible = self.eligible_and_authorized_candidate_ids(
8280                        &unchecked,
8281                        *column_id,
8282                        snapshot,
8283                        candidate_authorization,
8284                        context,
8285                    )?;
8286                    for row_id in &unchecked {
8287                        eligibility.insert(*row_id, eligible.contains(row_id));
8288                    }
8289                    // Account for newly rejected rows: anything not in
8290                    // `eligible` (visibility or tombstone/TTL or authorization).
8291                    let new_visibility_or_auth_rejected = unchecked
8292                        .iter()
8293                        .filter(|row_id| !eligible.contains(row_id))
8294                        .count();
8295                    // Distinguish visibility vs authorization rejections for
8296                    // the trace. Authorization rejections are rows that pass
8297                    // visibility but fail the candidate-authorization check;
8298                    // visibility rejections are the remainder.
8299                    let mut new_auth_rejected = 0usize;
8300                    if let Some(authorization) = candidate_authorization {
8301                        if authorization.security.rls_enabled(authorization.table)
8302                            && !authorization.principal.is_admin
8303                        {
8304                            // Re-eligibility-check only the auth layer to
8305                            // count how many were dropped at authorization
8306                            // specifically (eligible already merged auth
8307                            // into its result; treat non-eligible as
8308                            // auth-rejected when RLS is on).
8309                            new_auth_rejected = new_visibility_or_auth_rejected;
8310                        }
8311                    }
8312                    let new_visibility_rejected =
8313                        new_visibility_or_auth_rejected.saturating_sub(new_auth_rejected);
8314                    visibility_rejected_total =
8315                        visibility_rejected_total.saturating_add(new_visibility_rejected);
8316                    authorization_rejected_total =
8317                        authorization_rejected_total.saturating_add(new_auth_rejected);
8318                    let filtered: Vec<_> = raw
8319                        .into_iter()
8320                        .filter(|(row_id, _)| {
8321                            seen.insert(*row_id)
8322                                && eligibility.get(row_id).copied().unwrap_or(false)
8323                        })
8324                        .map(|(row_id, score)| {
8325                            let score = match score {
8326                                crate::index::AnnDistance::Hamming(d) => {
8327                                    RetrieverScore::AnnHammingDistance(d)
8328                                }
8329                                crate::index::AnnDistance::Cosine(d) => {
8330                                    RetrieverScore::AnnCosineDistance(d)
8331                                }
8332                            };
8333                            (row_id, score)
8334                        })
8335                        .collect();
8336                    if filtered.len() >= *k || breadth >= cap {
8337                        if filtered.len() < *k && index.len() > cap && breadth >= cap {
8338                            crate::trace::QueryTrace::record(|trace| {
8339                                trace.ann_candidate_cap_hit = true;
8340                                trace.candidate_cap_hit = true;
8341                            });
8342                            candidate_cap_hit_final = true;
8343                        }
8344                        break filtered;
8345                    }
8346                    breadth = breadth.saturating_mul(2).min(cap);
8347                };
8348                // Final trace write for ANN: candidate cap, cap-hit flag,
8349                // cumulative raw / rejection counts, and final hit count.
8350                let final_hits = filtered.len();
8351                let index_len = index.len();
8352                crate::trace::QueryTrace::record(|trace| {
8353                    trace.candidate_cap = cap;
8354                    trace.candidate_cap_hit = candidate_cap_hit_final;
8355                    trace.ann_candidate_cap_hit = candidate_cap_hit_final;
8356                    trace.raw_candidates =
8357                        trace.raw_candidates.saturating_add(raw_candidates_total);
8358                    trace.visibility_rejected = trace
8359                        .visibility_rejected
8360                        .saturating_add(visibility_rejected_total);
8361                    trace.authorization_rejected = trace
8362                        .authorization_rejected
8363                        .saturating_add(authorization_rejected_total);
8364                    trace.final_hits = trace.final_hits.saturating_add(final_hits);
8365                    // Suppress the unused warning on index_len — it is a
8366                    // useful diagnostic when paired with `candidate_cap_hit`.
8367                    let _ = index_len;
8368                });
8369                filtered.truncate(*k);
8370                filtered
8371            }
8372            Retriever::Sparse {
8373                column_id,
8374                query,
8375                k,
8376            } => self
8377                .sparse
8378                .get(column_id)
8379                .map(|index| -> Result<Vec<_>> {
8380                    let mut breadth = (*k).max(1);
8381                    let mut eligibility = std::collections::HashMap::new();
8382                    // Cumulative trace counters across widening iterations
8383                    // (same §7.5 accounting as the ANN branch above).
8384                    let mut raw_candidates_total: usize = 0;
8385                    let mut visibility_rejected_total: usize = 0;
8386                    let mut authorization_rejected_total: usize = 0;
8387                    let filtered = loop {
8388                        if let Some(context) = context {
8389                            context.checkpoint()?;
8390                        }
8391                        let raw = index.search_with_context(query, breadth, context)?;
8392                        raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8393                        authorization_rejected_total = authorization_rejected_total.saturating_add(
8394                            raw.iter()
8395                                .filter(|(row_id, _)| {
8396                                    allowed.is_some_and(|allowed| !allowed.contains(row_id))
8397                                })
8398                                .count(),
8399                        );
8400                        let unchecked: Vec<_> = raw
8401                            .iter()
8402                            .map(|(row_id, _)| *row_id)
8403                            .filter(|row_id| !eligibility.contains_key(row_id))
8404                            .filter(|row_id| {
8405                                hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8406                                    && allowed.is_none_or(|allowed| allowed.contains(row_id))
8407                            })
8408                            .collect();
8409                        let eligible = self.eligible_and_authorized_candidate_ids(
8410                            &unchecked,
8411                            *column_id,
8412                            snapshot,
8413                            candidate_authorization,
8414                            context,
8415                        )?;
8416                        visibility_rejected_total = visibility_rejected_total.saturating_add(
8417                            unchecked
8418                                .iter()
8419                                .filter(|row_id| !eligible.contains(row_id))
8420                                .count(),
8421                        );
8422                        for row_id in unchecked {
8423                            eligibility.insert(row_id, eligible.contains(&row_id));
8424                        }
8425                        let filtered: Vec<_> = raw
8426                            .iter()
8427                            .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8428                            .take(*k)
8429                            .map(|(row_id, score)| {
8430                                (*row_id, RetrieverScore::SparseDotProduct(*score))
8431                            })
8432                            .collect();
8433                        if filtered.len() >= *k || raw.len() < breadth {
8434                            break filtered;
8435                        }
8436                        let next = breadth.saturating_mul(2);
8437                        if next == breadth {
8438                            break filtered;
8439                        }
8440                        breadth = next;
8441                    };
8442                    crate::trace::QueryTrace::record(|trace| {
8443                        trace.raw_candidates =
8444                            trace.raw_candidates.saturating_add(raw_candidates_total);
8445                        trace.visibility_rejected = trace
8446                            .visibility_rejected
8447                            .saturating_add(visibility_rejected_total);
8448                        trace.authorization_rejected = trace
8449                            .authorization_rejected
8450                            .saturating_add(authorization_rejected_total);
8451                    });
8452                    Ok(filtered)
8453                })
8454                .transpose()?
8455                .unwrap_or_default(),
8456            Retriever::MinHash {
8457                column_id,
8458                members,
8459                k,
8460            } => self
8461                .minhash
8462                .get(column_id)
8463                .map(|index| -> Result<Vec<_>> {
8464                    let mut hashes = Vec::with_capacity(members.len());
8465                    for member in members {
8466                        if let Some(context) = context {
8467                            context.consume(crate::query::work_units(
8468                                member.encoded_len(),
8469                                crate::query::PARSE_WORK_QUANTUM,
8470                            ))?;
8471                        }
8472                        hashes.push(member.hash_v1());
8473                    }
8474                    let mut breadth = (*k).max(1);
8475                    let mut eligibility = std::collections::HashMap::new();
8476                    let mut raw_candidates_total: usize = 0;
8477                    let mut visibility_rejected_total: usize = 0;
8478                    let mut authorization_rejected_total: usize = 0;
8479                    let filtered = loop {
8480                        if let Some(context) = context {
8481                            context.checkpoint()?;
8482                        }
8483                        let raw = index.search_with_context(&hashes, breadth, context)?;
8484                        raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8485                        authorization_rejected_total = authorization_rejected_total.saturating_add(
8486                            raw.iter()
8487                                .filter(|(row_id, _)| {
8488                                    allowed.is_some_and(|allowed| !allowed.contains(row_id))
8489                                })
8490                                .count(),
8491                        );
8492                        let unchecked: Vec<_> = raw
8493                            .iter()
8494                            .map(|(row_id, _)| *row_id)
8495                            .filter(|row_id| !eligibility.contains_key(row_id))
8496                            .filter(|row_id| {
8497                                hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8498                                    && allowed.is_none_or(|allowed| allowed.contains(row_id))
8499                            })
8500                            .collect();
8501                        let eligible = self.eligible_and_authorized_candidate_ids(
8502                            &unchecked,
8503                            *column_id,
8504                            snapshot,
8505                            candidate_authorization,
8506                            context,
8507                        )?;
8508                        visibility_rejected_total = visibility_rejected_total.saturating_add(
8509                            unchecked
8510                                .iter()
8511                                .filter(|row_id| !eligible.contains(row_id))
8512                                .count(),
8513                        );
8514                        for row_id in unchecked {
8515                            eligibility.insert(row_id, eligible.contains(&row_id));
8516                        }
8517                        let filtered: Vec<_> = raw
8518                            .iter()
8519                            .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8520                            .take(*k)
8521                            .map(|(row_id, score)| {
8522                                (*row_id, RetrieverScore::MinHashEstimatedJaccard(*score))
8523                            })
8524                            .collect();
8525                        if filtered.len() >= *k || raw.len() < breadth {
8526                            break filtered;
8527                        }
8528                        let next = breadth.saturating_mul(2);
8529                        if next == breadth {
8530                            break filtered;
8531                        }
8532                        breadth = next;
8533                    };
8534                    crate::trace::QueryTrace::record(|trace| {
8535                        trace.raw_candidates =
8536                            trace.raw_candidates.saturating_add(raw_candidates_total);
8537                        trace.visibility_rejected = trace
8538                            .visibility_rejected
8539                            .saturating_add(visibility_rejected_total);
8540                        trace.authorization_rejected = trace
8541                            .authorization_rejected
8542                            .saturating_add(authorization_rejected_total);
8543                    });
8544                    Ok(filtered)
8545                })
8546                .transpose()?
8547                .unwrap_or_default(),
8548        };
8549        let requested_k = match retriever {
8550            Retriever::Ann { k, .. }
8551            | Retriever::Sparse { k, .. }
8552            | Retriever::MinHash { k, .. } => *k,
8553        };
8554        crate::trace::QueryTrace::record(|trace| {
8555            trace.final_hits = scored.len();
8556            if scored.len() < requested_k {
8557                trace.underfill_reason = Some(if trace.candidate_cap_hit {
8558                    "candidate_cap"
8559                } else {
8560                    "eligible_candidates_exhausted"
8561                });
8562            }
8563        });
8564        let elapsed = started.elapsed().as_nanos() as u64;
8565        crate::trace::QueryTrace::record(|trace| {
8566            match retriever {
8567                Retriever::Ann { .. } => {
8568                    trace.ann_candidate_nanos = trace.ann_candidate_nanos.saturating_add(elapsed);
8569                    if let Retriever::Ann { column_id, .. } = retriever {
8570                        if let Some(index) = self.ann.get(column_id) {
8571                            trace.ann_algorithm = Some(index.algorithm());
8572                            trace.ann_quantization = Some(index.quantization());
8573                            trace.ann_backend = Some(index.backend_name());
8574                        }
8575                    }
8576                }
8577                Retriever::Sparse { .. } => {
8578                    trace.sparse_candidate_nanos =
8579                        trace.sparse_candidate_nanos.saturating_add(elapsed)
8580                }
8581                Retriever::MinHash { .. } => {
8582                    trace.minhash_candidate_nanos =
8583                        trace.minhash_candidate_nanos.saturating_add(elapsed)
8584                }
8585            }
8586            trace.candidate_count = trace.candidate_count.saturating_add(scored.len());
8587        });
8588        Ok(scored
8589            .into_iter()
8590            .enumerate()
8591            .map(|(rank, (row_id, score))| RetrieverHit {
8592                row_id,
8593                rank: rank + 1,
8594                score,
8595            })
8596            .collect())
8597    }
8598
8599    fn eligible_candidate_ids(
8600        &self,
8601        candidates: &[RowId],
8602        _column_id: u16,
8603        snapshot: Snapshot,
8604        context: Option<&crate::query::AiExecutionContext>,
8605    ) -> Result<std::collections::HashSet<RowId>> {
8606        // Candidate eligibility is a pure snapshot read — the same
8607        // visibility rule point lookups (`get`) use. The in-flight
8608        // private-WAL batch lands in the memtable at `pending_epoch =
8609        // visible + 1` (puts and matching tombstones), above every reader
8610        // snapshot, so the un-advanced snapshot already hides it. Unlike
8611        // `resolve_pk_with_hot_fallback`, retrievers must NOT advance to
8612        // `pending_epoch`: an uncommitted row whose embedding is the exact
8613        // query match would outrank every committed row and leak into the
8614        // hits (see tests/retriever_uncommitted.rs). Committed versions
8615        // remain eligible under the caller snapshot, including HLC-stamped
8616        // winners admitted by `observes_row` (REM-001).
8617        let lookup_snapshot = snapshot;
8618        let mut readers: Vec<_> = self
8619            .run_refs
8620            .iter()
8621            .map(|run| self.open_reader(run.run_id))
8622            .collect::<Result<_>>()?;
8623        let now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8624        let mut eligible = std::collections::HashSet::with_capacity(candidates.len());
8625        for &row_id in candidates {
8626            if let Some(context) = context {
8627                context.consume(1)?;
8628            }
8629            let mem = self.memtable.get_version_at(row_id, lookup_snapshot);
8630            let mutable = self.mutable_run.get_version_at(row_id, lookup_snapshot);
8631            let overlay = match (mem, mutable) {
8632                (Some(left), Some(right)) => Some(
8633                    if Snapshot::version_is_newer(
8634                        left.1.committed_epoch,
8635                        left.1.commit_ts,
8636                        right.1.committed_epoch,
8637                        right.1.commit_ts,
8638                    ) {
8639                        left
8640                    } else {
8641                        right
8642                    },
8643                ),
8644                (Some(value), None) | (None, Some(value)) => Some(value),
8645                (None, None) => None,
8646            };
8647            if let Some((_, row)) = overlay {
8648                if !row.deleted && !self.row_expired_at(&row, now) {
8649                    eligible.insert(row_id);
8650                }
8651                continue;
8652            }
8653            // REM-001: keep the full version stamp across runs so the eligibility fold
8654            // honors HLC authority when candidates are stamped. The legacy
8655            // `(epoch, deleted, reader_index)` tuple dropped `commit_ts` and
8656            // could admit a stale high-epoch row over an HLC-newer low-epoch
8657            // candidate.
8658            let mut best: Option<(crate::sorted_run::VersionVisibility, usize)> = None;
8659            for (index, reader) in readers.iter_mut().enumerate() {
8660                if let Some(visibility) =
8661                    reader.get_version_visibility_full_at(row_id, lookup_snapshot)?
8662                {
8663                    if best
8664                        .as_ref()
8665                        .map(|(current, _)| visibility.stamp.is_newer_than(current.stamp))
8666                        .unwrap_or(true)
8667                    {
8668                        best = Some((visibility, index));
8669                    }
8670                }
8671            }
8672            let Some((visibility, reader_index)) = best else {
8673                continue;
8674            };
8675            if visibility.deleted {
8676                continue;
8677            }
8678            if let Some(ttl) = self.ttl {
8679                if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
8680                    row_id,
8681                    lookup_snapshot,
8682                    ttl.column_id,
8683                )? {
8684                    if let Some(Value::Int64(timestamp)) = ttl_value.value {
8685                        if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
8686                            continue;
8687                        }
8688                    }
8689                }
8690            }
8691            eligible.insert(row_id);
8692        }
8693        Ok(eligible)
8694    }
8695
8696    fn eligible_and_authorized_candidate_ids(
8697        &self,
8698        candidates: &[RowId],
8699        column_id: u16,
8700        snapshot: Snapshot,
8701        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8702        context: Option<&crate::query::AiExecutionContext>,
8703    ) -> Result<std::collections::HashSet<RowId>> {
8704        let eligible = self.eligible_candidate_ids(candidates, column_id, snapshot, context)?;
8705        let Some(authorization) = authorization else {
8706            return Ok(eligible);
8707        };
8708        let candidates: Vec<_> = eligible.into_iter().collect();
8709        self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, context)
8710    }
8711
8712    fn policy_allowed_candidate_ids(
8713        &self,
8714        candidates: &[RowId],
8715        snapshot: Snapshot,
8716        authorization: &crate::security::CandidateAuthorization<'_>,
8717        context: Option<&crate::query::AiExecutionContext>,
8718    ) -> Result<std::collections::HashSet<RowId>> {
8719        let started = std::time::Instant::now();
8720        if candidates.is_empty()
8721            || authorization.principal.is_admin
8722            || !authorization.security.rls_enabled(authorization.table)
8723        {
8724            return Ok(candidates.iter().copied().collect());
8725        }
8726        if let Some(context) = context {
8727            context.checkpoint()?;
8728        }
8729        let row_ids: Vec<_> = candidates.iter().map(|row_id| row_id.0).collect();
8730        let mut rows: std::collections::HashMap<RowId, Row> = candidates
8731            .iter()
8732            .map(|row_id| {
8733                (
8734                    *row_id,
8735                    Row {
8736                        row_id: *row_id,
8737                        committed_epoch: snapshot.epoch,
8738                        columns: std::collections::HashMap::new(),
8739                        deleted: false,
8740                        commit_ts: None,
8741                    },
8742                )
8743            })
8744            .collect();
8745        let columns = authorization
8746            .security
8747            .select_policy_columns(authorization.table, authorization.principal);
8748        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8749        let mut decoded = 0usize;
8750        for column_id in &columns {
8751            if let Some(context) = context {
8752                context.checkpoint()?;
8753            }
8754            for (row_id, value) in self.values_for_rids_batch_at_with_context(
8755                &row_ids, *column_id, snapshot, query_now, context,
8756            )? {
8757                if let Some(row) = rows.get_mut(&row_id) {
8758                    row.columns.insert(*column_id, value);
8759                    decoded = decoded.saturating_add(1);
8760                }
8761            }
8762        }
8763        if let Some(context) = context {
8764            context.consume(candidates.len().saturating_add(decoded))?;
8765        }
8766        let allowed = rows
8767            .into_values()
8768            .filter_map(|row| {
8769                authorization
8770                    .security
8771                    .row_allowed(
8772                        authorization.table,
8773                        crate::security::PolicyCommand::Select,
8774                        &row,
8775                        authorization.principal,
8776                        false,
8777                    )
8778                    .then_some(row.row_id)
8779            })
8780            .collect();
8781        crate::trace::QueryTrace::record(|trace| {
8782            trace.rls_rows_evaluated = trace.rls_rows_evaluated.saturating_add(candidates.len());
8783            trace.rls_policy_columns_decoded =
8784                trace.rls_policy_columns_decoded.saturating_add(decoded);
8785            trace.authorization_nanos = trace
8786                .authorization_nanos
8787                .saturating_add(started.elapsed().as_nanos() as u64);
8788        });
8789        Ok(allowed)
8790    }
8791
8792    /// Filter-aware union and reciprocal-rank fusion over scored retrievers.
8793    pub fn search(
8794        &mut self,
8795        request: &crate::query::SearchRequest,
8796    ) -> Result<Vec<crate::query::SearchHit>> {
8797        self.search_with_allowed(request, None)
8798    }
8799
8800    pub fn search_at(
8801        &mut self,
8802        request: &crate::query::SearchRequest,
8803        snapshot: Snapshot,
8804        authorized: Option<&std::collections::HashSet<RowId>>,
8805    ) -> Result<Vec<crate::query::SearchHit>> {
8806        self.search_at_with_allowed(request, snapshot, authorized)
8807    }
8808
8809    pub fn search_with_allowed(
8810        &mut self,
8811        request: &crate::query::SearchRequest,
8812        authorized: Option<&std::collections::HashSet<RowId>>,
8813    ) -> Result<Vec<crate::query::SearchHit>> {
8814        self.search_at_with_allowed(request, self.snapshot(), authorized)
8815    }
8816
8817    pub fn search_at_with_allowed(
8818        &mut self,
8819        request: &crate::query::SearchRequest,
8820        snapshot: Snapshot,
8821        authorized: Option<&std::collections::HashSet<RowId>>,
8822    ) -> Result<Vec<crate::query::SearchHit>> {
8823        self.search_at_with_allowed_and_context(request, snapshot, authorized, None)
8824    }
8825
8826    pub fn search_at_with_allowed_and_context(
8827        &mut self,
8828        request: &crate::query::SearchRequest,
8829        snapshot: Snapshot,
8830        authorized: Option<&std::collections::HashSet<RowId>>,
8831        context: Option<&crate::query::AiExecutionContext>,
8832    ) -> Result<Vec<crate::query::SearchHit>> {
8833        self.ensure_indexes_complete()?;
8834        self.search_at_with_filters_and_context(request, snapshot, authorized, None, context, None)
8835    }
8836
8837    pub fn search_at_with_candidate_authorization_and_context(
8838        &mut self,
8839        request: &crate::query::SearchRequest,
8840        snapshot: Snapshot,
8841        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8842        context: Option<&crate::query::AiExecutionContext>,
8843    ) -> Result<Vec<crate::query::SearchHit>> {
8844        self.ensure_indexes_complete()?;
8845        self.search_at_with_filters_and_context(
8846            request,
8847            snapshot,
8848            None,
8849            authorization,
8850            context,
8851            None,
8852        )
8853    }
8854
8855    #[doc(hidden)]
8856    pub fn search_at_with_candidate_authorization_on_generation(
8857        &self,
8858        request: &crate::query::SearchRequest,
8859        snapshot: Snapshot,
8860        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8861        context: Option<&crate::query::AiExecutionContext>,
8862    ) -> Result<Vec<crate::query::SearchHit>> {
8863        self.search_at_with_filters_and_context(
8864            request,
8865            snapshot,
8866            None,
8867            authorization,
8868            context,
8869            None,
8870        )
8871    }
8872
8873    #[doc(hidden)]
8874    pub fn search_at_with_candidate_authorization_on_generation_after(
8875        &self,
8876        request: &crate::query::SearchRequest,
8877        snapshot: Snapshot,
8878        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8879        context: Option<&crate::query::AiExecutionContext>,
8880        after: Option<crate::query::SearchAfter>,
8881    ) -> Result<Vec<crate::query::SearchHit>> {
8882        self.search_at_with_filters_and_context(
8883            request,
8884            snapshot,
8885            None,
8886            authorization,
8887            context,
8888            after,
8889        )
8890    }
8891
8892    fn search_at_with_filters_and_context(
8893        &self,
8894        request: &crate::query::SearchRequest,
8895        snapshot: Snapshot,
8896        authorized: Option<&std::collections::HashSet<RowId>>,
8897        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8898        context: Option<&crate::query::AiExecutionContext>,
8899        after: Option<crate::query::SearchAfter>,
8900    ) -> Result<Vec<crate::query::SearchHit>> {
8901        use crate::query::{
8902            ComponentScore, Condition, Fusion, SearchHit, MAX_FINAL_LIMIT, MAX_HARD_CONDITIONS,
8903            MAX_PROJECTION_COLUMNS, MAX_RETRIEVERS, MAX_RETRIEVER_WEIGHT,
8904        };
8905        let total_started = std::time::Instant::now();
8906        let rank_offset = after.map_or(0, |after| after.returned_count);
8907        self.require_select()?;
8908        if request.limit == 0 {
8909            return Err(MongrelError::InvalidArgument(
8910                "search limit must be > 0".into(),
8911            ));
8912        }
8913        if request.limit > MAX_FINAL_LIMIT {
8914            return Err(MongrelError::InvalidArgument(format!(
8915                "search limit exceeds {MAX_FINAL_LIMIT}"
8916            )));
8917        }
8918        if after.is_some_and(|cursor| !cursor.final_score.is_finite()) {
8919            return Err(MongrelError::InvalidArgument(
8920                "search-after score must be finite".into(),
8921            ));
8922        }
8923        if request.retrievers.is_empty() {
8924            return Err(MongrelError::InvalidArgument(
8925                "search requires at least one retriever".into(),
8926            ));
8927        }
8928        if request.retrievers.len() > MAX_RETRIEVERS {
8929            return Err(MongrelError::InvalidArgument(format!(
8930                "search exceeds {MAX_RETRIEVERS} retrievers"
8931            )));
8932        }
8933        if request.must.len() > MAX_HARD_CONDITIONS {
8934            return Err(MongrelError::InvalidArgument(format!(
8935                "search exceeds {MAX_HARD_CONDITIONS} hard conditions"
8936            )));
8937        }
8938        for condition in &request.must {
8939            self.validate_condition(condition)?;
8940        }
8941        if request.must.iter().any(|condition| {
8942            matches!(
8943                condition,
8944                Condition::Ann { .. }
8945                    | Condition::SparseMatch { .. }
8946                    | Condition::MinHashSimilar { .. }
8947            )
8948        }) {
8949            return Err(MongrelError::InvalidArgument(
8950                "ranked ANN, Sparse, and MinHash conditions must be retrievers, not must filters"
8951                    .into(),
8952            ));
8953        }
8954        let mut names = std::collections::HashSet::new();
8955        for named in &request.retrievers {
8956            if named.name.is_empty()
8957                || named.name.len() > crate::query::MAX_RETRIEVER_NAME_BYTES
8958                || !names.insert(named.name.as_str())
8959            {
8960                return Err(MongrelError::InvalidArgument(format!(
8961                    "retriever names must be non-empty, unique, and at most {} UTF-8 bytes",
8962                    crate::query::MAX_RETRIEVER_NAME_BYTES
8963                )));
8964            }
8965            if !named.weight.is_finite()
8966                || named.weight < 0.0
8967                || named.weight > MAX_RETRIEVER_WEIGHT
8968            {
8969                return Err(MongrelError::InvalidArgument(format!(
8970                    "retriever weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
8971                )));
8972            }
8973            self.validate_retriever(&named.retriever)?;
8974        }
8975        let projection = request
8976            .projection
8977            .clone()
8978            .unwrap_or_else(|| self.schema.columns.iter().map(|column| column.id).collect());
8979        if projection.len() > MAX_PROJECTION_COLUMNS {
8980            return Err(MongrelError::InvalidArgument(format!(
8981                "projection exceeds {MAX_PROJECTION_COLUMNS} columns"
8982            )));
8983        }
8984        for column_id in &projection {
8985            if !self
8986                .schema
8987                .columns
8988                .iter()
8989                .any(|column| column.id == *column_id)
8990            {
8991                return Err(MongrelError::ColumnNotFound(column_id.to_string()));
8992            }
8993        }
8994        if let Some(crate::query::Rerank::ExactVector {
8995            embedding_column,
8996            query,
8997            candidate_limit,
8998            weight,
8999            ..
9000        }) = &request.rerank
9001        {
9002            if *candidate_limit < request.limit || *candidate_limit > crate::query::MAX_RETRIEVER_K
9003            {
9004                return Err(MongrelError::InvalidArgument(format!(
9005                    "rerank candidate_limit must be between search limit and {}",
9006                    crate::query::MAX_RETRIEVER_K
9007                )));
9008            }
9009            if !weight.is_finite() || *weight < 0.0 || *weight > MAX_RETRIEVER_WEIGHT {
9010                return Err(MongrelError::InvalidArgument(format!(
9011                    "rerank weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
9012                )));
9013            }
9014            let column = self
9015                .schema
9016                .columns
9017                .iter()
9018                .find(|column| column.id == *embedding_column)
9019                .ok_or_else(|| MongrelError::ColumnNotFound(embedding_column.to_string()))?;
9020            let crate::schema::TypeId::Embedding { dim } = column.ty else {
9021                return Err(MongrelError::InvalidArgument(format!(
9022                    "rerank column {embedding_column} is not an embedding"
9023                )));
9024            };
9025            if query.len() != dim as usize || query.iter().any(|value| !value.is_finite()) {
9026                return Err(MongrelError::InvalidArgument(format!(
9027                    "rerank query must contain {dim} finite values"
9028                )));
9029            }
9030        }
9031
9032        let hard_filter_started = std::time::Instant::now();
9033        let hard_filter = if request.must.is_empty() {
9034            None
9035        } else {
9036            let mut sets = Vec::with_capacity(request.must.len());
9037            for condition in &request.must {
9038                if let Some(context) = context {
9039                    context.checkpoint()?;
9040                }
9041                sets.push(self.resolve_condition(condition, snapshot)?);
9042            }
9043            Some(RowIdSet::intersect_many(sets))
9044        };
9045        crate::trace::QueryTrace::record(|trace| {
9046            trace.hard_filter_nanos = trace
9047                .hard_filter_nanos
9048                .saturating_add(hard_filter_started.elapsed().as_nanos() as u64);
9049        });
9050        if hard_filter.as_ref().is_some_and(RowIdSet::is_empty) {
9051            return Ok(Vec::new());
9052        }
9053
9054        let constant = match request.fusion {
9055            Fusion::ReciprocalRank { constant } => constant,
9056        };
9057        let mut retrievers: Vec<_> = request.retrievers.iter().collect();
9058        retrievers.sort_by(|a, b| a.name.cmp(&b.name));
9059        let mut fusion_nanos = 0u64;
9060        let mut fused: std::collections::HashMap<RowId, (f64, Vec<ComponentScore>)> =
9061            std::collections::HashMap::new();
9062        for named in retrievers {
9063            if named.weight == 0.0 {
9064                continue;
9065            }
9066            if let Some(context) = context {
9067                context.checkpoint()?;
9068            }
9069            let hits = self.retrieve_filtered(
9070                &named.retriever,
9071                snapshot,
9072                hard_filter.as_ref(),
9073                authorized,
9074                candidate_authorization,
9075                context,
9076            )?;
9077            let retriever_name: std::sync::Arc<str> = named.name.as_str().into();
9078            let fusion_started = std::time::Instant::now();
9079            for hit in hits {
9080                if let Some(context) = context {
9081                    context.consume(1)?;
9082                }
9083                let contribution = named.weight / (constant as f64 + hit.rank as f64);
9084                if !contribution.is_finite() {
9085                    return Err(MongrelError::InvalidArgument(
9086                        "retriever contribution must be finite".into(),
9087                    ));
9088                }
9089                let max_fused_candidates = context.map_or(
9090                    crate::query::MAX_FUSED_CANDIDATES,
9091                    crate::query::AiExecutionContext::max_fused_candidates,
9092                );
9093                if !fused.contains_key(&hit.row_id) && fused.len() >= max_fused_candidates {
9094                    return Err(MongrelError::WorkBudgetExceeded);
9095                }
9096                let entry = fused.entry(hit.row_id).or_default();
9097                entry.0 += contribution;
9098                if !entry.0.is_finite() {
9099                    return Err(MongrelError::InvalidArgument(
9100                        "fused score must be finite".into(),
9101                    ));
9102                }
9103                entry.1.push(ComponentScore {
9104                    retriever_name: retriever_name.clone(),
9105                    rank: hit.rank,
9106                    raw_score: hit.score,
9107                    contribution,
9108                });
9109            }
9110            fusion_nanos = fusion_nanos.saturating_add(fusion_started.elapsed().as_nanos() as u64);
9111        }
9112        let union_size = fused.len();
9113        let mut ranked: Vec<_> = fused
9114            .into_iter()
9115            .map(|(row_id, (fused_score, components))| {
9116                (row_id, fused_score, components, None, fused_score)
9117            })
9118            .collect();
9119        let order = |(a_row, _, _, _, a_score): &(
9120            RowId,
9121            f64,
9122            Vec<ComponentScore>,
9123            Option<f32>,
9124            f64,
9125        ),
9126                     (b_row, _, _, _, b_score): &(
9127            RowId,
9128            f64,
9129            Vec<ComponentScore>,
9130            Option<f32>,
9131            f64,
9132        )| { b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row)) };
9133        if let Some(crate::query::Rerank::ExactVector {
9134            embedding_column,
9135            query,
9136            metric,
9137            candidate_limit,
9138            weight,
9139        }) = &request.rerank
9140        {
9141            let fused_order = |(a_row, a_score, ..): &(
9142                RowId,
9143                f64,
9144                Vec<ComponentScore>,
9145                Option<f32>,
9146                f64,
9147            ),
9148                               (b_row, b_score, ..): &(
9149                RowId,
9150                f64,
9151                Vec<ComponentScore>,
9152                Option<f32>,
9153                f64,
9154            )| {
9155                b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row))
9156            };
9157            let selection_started = std::time::Instant::now();
9158            if let Some(context) = context {
9159                context.consume(ranked.len())?;
9160            }
9161            if ranked.len() > *candidate_limit {
9162                let (_, _, _) = ranked.select_nth_unstable_by(*candidate_limit, fused_order);
9163                ranked.truncate(*candidate_limit);
9164            }
9165            ranked.sort_by(fused_order);
9166            fusion_nanos =
9167                fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9168            let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9169            if let Some(context) = context {
9170                context.consume(row_ids.len())?;
9171            }
9172            let query_now =
9173                context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9174            let gather_started = std::time::Instant::now();
9175            let vectors = self.values_for_rids_batch_at_with_context(
9176                &row_ids,
9177                *embedding_column,
9178                snapshot,
9179                query_now,
9180                context,
9181            )?;
9182            let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9183            let vector_work =
9184                crate::query::work_units(query.len(), crate::query::VECTOR_WORK_QUANTUM);
9185            let query_norm = if matches!(metric, crate::query::VectorMetric::Cosine) {
9186                if let Some(context) = context {
9187                    context.consume(vector_work)?;
9188                }
9189                query
9190                    .iter()
9191                    .map(|value| f64::from(*value).powi(2))
9192                    .sum::<f64>()
9193                    .sqrt()
9194            } else {
9195                0.0
9196            };
9197            let score_started = std::time::Instant::now();
9198            let mut scores = std::collections::HashMap::with_capacity(vectors.len());
9199            for (row_id, value) in vectors {
9200                if let Some(meta) = value.generated_embedding_metadata() {
9201                    if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9202                        continue;
9203                    }
9204                }
9205                let Some(vector) = value.as_embedding() else {
9206                    continue;
9207                };
9208                let score = match metric {
9209                    crate::query::VectorMetric::DotProduct => {
9210                        if let Some(context) = context {
9211                            context.consume(vector_work)?;
9212                        }
9213                        query
9214                            .iter()
9215                            .zip(vector)
9216                            .map(|(left, right)| f64::from(*left) * f64::from(*right))
9217                            .sum::<f64>()
9218                    }
9219                    crate::query::VectorMetric::Cosine => {
9220                        if let Some(context) = context {
9221                            context.consume(vector_work.saturating_mul(2))?;
9222                        }
9223                        let dot = query
9224                            .iter()
9225                            .zip(vector)
9226                            .map(|(left, right)| f64::from(*left) * f64::from(*right))
9227                            .sum::<f64>();
9228                        let norm = vector
9229                            .iter()
9230                            .map(|value| f64::from(*value).powi(2))
9231                            .sum::<f64>()
9232                            .sqrt();
9233                        if query_norm == 0.0 || norm == 0.0 {
9234                            0.0
9235                        } else {
9236                            dot / (query_norm * norm)
9237                        }
9238                    }
9239                    crate::query::VectorMetric::Euclidean => {
9240                        if let Some(context) = context {
9241                            context.consume(vector_work)?;
9242                        }
9243                        query
9244                            .iter()
9245                            .zip(vector)
9246                            .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9247                            .sum::<f64>()
9248                            .sqrt()
9249                    }
9250                };
9251                if !score.is_finite() {
9252                    return Err(MongrelError::InvalidArgument(
9253                        "exact rerank score must be finite".into(),
9254                    ));
9255                }
9256                scores.insert(row_id, score as f32);
9257            }
9258            let mut reranked = Vec::with_capacity(ranked.len());
9259            for (row_id, fused_score, components, _, _) in ranked.drain(..) {
9260                let Some(score) = scores.get(&row_id).copied() else {
9261                    continue;
9262                };
9263                let ordering_score = match metric {
9264                    crate::query::VectorMetric::Euclidean => -f64::from(score),
9265                    crate::query::VectorMetric::Cosine | crate::query::VectorMetric::DotProduct => {
9266                        f64::from(score)
9267                    }
9268                };
9269                let final_score = fused_score + *weight * ordering_score;
9270                if !final_score.is_finite() {
9271                    return Err(MongrelError::InvalidArgument(
9272                        "final rerank score must be finite".into(),
9273                    ));
9274                }
9275                reranked.push((row_id, fused_score, components, Some(score), final_score));
9276            }
9277            ranked = reranked;
9278            ranked.sort_by(order);
9279            crate::trace::QueryTrace::record(|trace| {
9280                trace.exact_vector_gather_nanos =
9281                    trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9282                trace.exact_vector_score_nanos = trace
9283                    .exact_vector_score_nanos
9284                    .saturating_add(score_started.elapsed().as_nanos() as u64);
9285            });
9286        }
9287        if let Some(after) = after {
9288            ranked.retain(|(row_id, _, _, _, final_score)| {
9289                final_score.total_cmp(&after.final_score).is_lt()
9290                    || (final_score.total_cmp(&after.final_score).is_eq() && *row_id > after.row_id)
9291            });
9292        }
9293        let projection_started = std::time::Instant::now();
9294        let sentinel = projection
9295            .first()
9296            .copied()
9297            .or_else(|| self.schema.columns.first().map(|column| column.id));
9298        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9299        let mut out = Vec::with_capacity(request.limit.min(ranked.len()));
9300        let mut projection_rows = 0usize;
9301        let mut projection_cells = 0usize;
9302        while out.len() < request.limit && !ranked.is_empty() {
9303            if let Some(context) = context {
9304                context.checkpoint()?;
9305                context.consume(ranked.len())?;
9306            }
9307            let needed = request.limit - out.len();
9308            let window_size = ranked
9309                .len()
9310                .min(needed.saturating_mul(2).max(needed.saturating_add(8)));
9311            let selection_started = std::time::Instant::now();
9312            let mut remainder = if ranked.len() > window_size {
9313                let (_, _, _) = ranked.select_nth_unstable_by(window_size, order);
9314                ranked.split_off(window_size)
9315            } else {
9316                Vec::new()
9317            };
9318            ranked.sort_by(order);
9319            fusion_nanos =
9320                fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9321            let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9322            let gathered_columns = projection.len().max(usize::from(sentinel.is_some()));
9323            if let Some(context) = context {
9324                context.consume(row_ids.len().saturating_mul(gathered_columns))?;
9325            }
9326            projection_rows = projection_rows.saturating_add(row_ids.len());
9327            projection_cells =
9328                projection_cells.saturating_add(row_ids.len().saturating_mul(gathered_columns));
9329            let mut cells: std::collections::HashMap<RowId, std::collections::HashMap<u16, Value>> =
9330                std::collections::HashMap::new();
9331            if let Some(column_id) = sentinel {
9332                for (row_id, value) in self.values_for_rids_batch_at_with_context(
9333                    &row_ids, column_id, snapshot, query_now, context,
9334                )? {
9335                    cells.entry(row_id).or_default().insert(column_id, value);
9336                }
9337            }
9338            for &column_id in &projection {
9339                if Some(column_id) == sentinel {
9340                    continue;
9341                }
9342                for (row_id, value) in self.values_for_rids_batch_at_with_context(
9343                    &row_ids, column_id, snapshot, query_now, context,
9344                )? {
9345                    cells.entry(row_id).or_default().insert(column_id, value);
9346                }
9347            }
9348            for (row_id, fused_score, mut components, exact_rerank_score, final_score) in
9349                ranked.drain(..)
9350            {
9351                let Some(row_cells) = cells.remove(&row_id) else {
9352                    continue;
9353                };
9354                components.sort_by(|a, b| a.retriever_name.cmp(&b.retriever_name));
9355                let final_rank = rank_offset.saturating_add(out.len()).saturating_add(1);
9356                out.push(SearchHit {
9357                    row_id,
9358                    cells: projection
9359                        .iter()
9360                        .filter_map(|column_id| {
9361                            row_cells
9362                                .get(column_id)
9363                                .cloned()
9364                                .map(|value| (*column_id, value))
9365                        })
9366                        .collect(),
9367                    components,
9368                    fused_score,
9369                    exact_rerank_score,
9370                    final_score,
9371                    final_rank,
9372                });
9373                if out.len() == request.limit {
9374                    break;
9375                }
9376            }
9377            ranked.append(&mut remainder);
9378        }
9379        crate::trace::QueryTrace::record(|trace| {
9380            trace.union_size = union_size;
9381            trace.fusion_nanos = trace.fusion_nanos.saturating_add(fusion_nanos);
9382            trace.projection_nanos = trace
9383                .projection_nanos
9384                .saturating_add(projection_started.elapsed().as_nanos() as u64);
9385            trace.total_nanos = trace
9386                .total_nanos
9387                .saturating_add(total_started.elapsed().as_nanos() as u64);
9388            trace.projection_rows = trace.projection_rows.saturating_add(projection_rows);
9389            trace.projection_cells = trace.projection_cells.saturating_add(projection_cells);
9390            if let Some(context) = context {
9391                trace.work_consumed = trace.work_consumed.saturating_add(context.consumed_work());
9392            }
9393        });
9394        Ok(out)
9395    }
9396
9397    /// MinHash candidate generation followed by exact Jaccard verification.
9398    /// An empty query set returns no hits.
9399    pub fn set_similarity(
9400        &mut self,
9401        request: &crate::query::SetSimilarityRequest,
9402    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9403        self.set_similarity_with_allowed(request, None)
9404    }
9405
9406    pub fn set_similarity_at(
9407        &mut self,
9408        request: &crate::query::SetSimilarityRequest,
9409        snapshot: Snapshot,
9410        allowed: Option<&std::collections::HashSet<RowId>>,
9411    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9412        self.set_similarity_explained_at(request, snapshot, allowed)
9413            .map(|(hits, _)| hits)
9414    }
9415
9416    /// Binary ANN candidate generation followed by exact float-vector reranking.
9417    pub fn ann_rerank(
9418        &mut self,
9419        request: &crate::query::AnnRerankRequest,
9420    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9421        self.ann_rerank_with_allowed(request, None)
9422    }
9423
9424    pub fn ann_rerank_with_allowed(
9425        &mut self,
9426        request: &crate::query::AnnRerankRequest,
9427        allowed: Option<&std::collections::HashSet<RowId>>,
9428    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9429        self.ann_rerank_at(request, self.snapshot(), allowed)
9430    }
9431
9432    pub fn ann_rerank_at(
9433        &mut self,
9434        request: &crate::query::AnnRerankRequest,
9435        snapshot: Snapshot,
9436        allowed: Option<&std::collections::HashSet<RowId>>,
9437    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9438        self.ann_rerank_at_with_context(request, snapshot, allowed, None)
9439    }
9440
9441    pub fn ann_rerank_at_with_context(
9442        &mut self,
9443        request: &crate::query::AnnRerankRequest,
9444        snapshot: Snapshot,
9445        allowed: Option<&std::collections::HashSet<RowId>>,
9446        context: Option<&crate::query::AiExecutionContext>,
9447    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9448        self.ensure_indexes_complete()?;
9449        self.ann_rerank_at_with_filters_and_context(request, snapshot, allowed, None, context)
9450    }
9451
9452    pub fn ann_rerank_at_with_candidate_authorization_and_context(
9453        &mut self,
9454        request: &crate::query::AnnRerankRequest,
9455        snapshot: Snapshot,
9456        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9457        context: Option<&crate::query::AiExecutionContext>,
9458    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9459        self.ensure_indexes_complete()?;
9460        self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9461    }
9462
9463    #[doc(hidden)]
9464    pub fn ann_rerank_at_with_candidate_authorization_on_generation(
9465        &self,
9466        request: &crate::query::AnnRerankRequest,
9467        snapshot: Snapshot,
9468        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9469        context: Option<&crate::query::AiExecutionContext>,
9470    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9471        self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9472    }
9473
9474    fn ann_rerank_at_with_filters_and_context(
9475        &self,
9476        request: &crate::query::AnnRerankRequest,
9477        snapshot: Snapshot,
9478        allowed: Option<&std::collections::HashSet<RowId>>,
9479        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9480        context: Option<&crate::query::AiExecutionContext>,
9481    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9482        use crate::query::{
9483            AnnCandidateDistance, AnnRerankHit, Retriever, RetrieverScore, VectorMetric,
9484            MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9485        };
9486        if request.candidate_k == 0 || request.limit == 0 {
9487            return Err(MongrelError::InvalidArgument(
9488                "candidate_k and limit must be > 0".into(),
9489            ));
9490        }
9491        if request.candidate_k > MAX_RETRIEVER_K || request.limit > MAX_FINAL_LIMIT {
9492            return Err(MongrelError::InvalidArgument(format!(
9493                "candidate_k must be <= {MAX_RETRIEVER_K} and limit <= {MAX_FINAL_LIMIT}"
9494            )));
9495        }
9496        let retriever = Retriever::Ann {
9497            column_id: request.column_id,
9498            query: request.query.clone(),
9499            k: request.candidate_k,
9500        };
9501        self.require_select()?;
9502        self.validate_retriever(&retriever)?;
9503        let hits = self.retrieve_filtered(
9504            &retriever,
9505            snapshot,
9506            None,
9507            allowed,
9508            candidate_authorization,
9509            context,
9510        )?;
9511        let distances: std::collections::HashMap<_, _> = hits
9512            .iter()
9513            .filter_map(|hit| match hit.score {
9514                RetrieverScore::AnnHammingDistance(distance) => {
9515                    Some((hit.row_id, AnnCandidateDistance::Hamming(distance)))
9516                }
9517                RetrieverScore::AnnCosineDistance(distance) => {
9518                    Some((hit.row_id, AnnCandidateDistance::Cosine(distance)))
9519                }
9520                _ => None,
9521            })
9522            .collect();
9523        let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9524        if let Some(context) = context {
9525            context.consume(row_ids.len())?;
9526        }
9527        let gather_started = std::time::Instant::now();
9528        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9529        let values = self.values_for_rids_batch_at_with_context(
9530            &row_ids,
9531            request.column_id,
9532            snapshot,
9533            query_now,
9534            context,
9535        )?;
9536        let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9537        let score_started = std::time::Instant::now();
9538        let vector_work =
9539            crate::query::work_units(request.query.len(), crate::query::VECTOR_WORK_QUANTUM);
9540        let query_norm = if matches!(request.metric, VectorMetric::Cosine) {
9541            if let Some(context) = context {
9542                context.consume(vector_work)?;
9543            }
9544            request
9545                .query
9546                .iter()
9547                .map(|value| f64::from(*value).powi(2))
9548                .sum::<f64>()
9549                .sqrt()
9550        } else {
9551            0.0
9552        };
9553        let mut reranked = Vec::with_capacity(values.len().min(request.limit));
9554        for (row_id, value) in values {
9555            if let Some(meta) = value.generated_embedding_metadata() {
9556                if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9557                    continue;
9558                }
9559            }
9560            let Some(vector) = value.as_embedding() else {
9561                continue;
9562            };
9563            let exact_score = match request.metric {
9564                VectorMetric::DotProduct => {
9565                    if let Some(context) = context {
9566                        context.consume(vector_work)?;
9567                    }
9568                    request
9569                        .query
9570                        .iter()
9571                        .zip(vector)
9572                        .map(|(left, right)| f64::from(*left) * f64::from(*right))
9573                        .sum::<f64>()
9574                }
9575                VectorMetric::Cosine => {
9576                    if let Some(context) = context {
9577                        context.consume(vector_work.saturating_mul(2))?;
9578                    }
9579                    let dot = request
9580                        .query
9581                        .iter()
9582                        .zip(vector)
9583                        .map(|(left, right)| f64::from(*left) * f64::from(*right))
9584                        .sum::<f64>();
9585                    let norm = vector
9586                        .iter()
9587                        .map(|value| f64::from(*value).powi(2))
9588                        .sum::<f64>()
9589                        .sqrt();
9590                    if query_norm == 0.0 || norm == 0.0 {
9591                        0.0
9592                    } else {
9593                        dot / (query_norm * norm)
9594                    }
9595                }
9596                VectorMetric::Euclidean => {
9597                    if let Some(context) = context {
9598                        context.consume(vector_work)?;
9599                    }
9600                    request
9601                        .query
9602                        .iter()
9603                        .zip(vector)
9604                        .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9605                        .sum::<f64>()
9606                        .sqrt()
9607                }
9608            };
9609            let exact_score = exact_score as f32;
9610            if !exact_score.is_finite() {
9611                return Err(MongrelError::InvalidArgument(
9612                    "exact ANN score must be finite".into(),
9613                ));
9614            }
9615            let Some(candidate_distance) = distances.get(&row_id).copied() else {
9616                continue;
9617            };
9618            reranked.push(AnnRerankHit {
9619                row_id,
9620                candidate_distance,
9621                exact_score,
9622            });
9623        }
9624        reranked.sort_by(|left, right| {
9625            let score = match request.metric {
9626                VectorMetric::Euclidean => left.exact_score.total_cmp(&right.exact_score),
9627                VectorMetric::Cosine | VectorMetric::DotProduct => {
9628                    right.exact_score.total_cmp(&left.exact_score)
9629                }
9630            };
9631            score.then_with(|| left.row_id.cmp(&right.row_id))
9632        });
9633        reranked.truncate(request.limit);
9634        crate::trace::QueryTrace::record(|trace| {
9635            trace.exact_vector_gather_nanos =
9636                trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9637            trace.exact_vector_score_nanos = trace
9638                .exact_vector_score_nanos
9639                .saturating_add(score_started.elapsed().as_nanos() as u64);
9640        });
9641        Ok(reranked)
9642    }
9643
9644    pub fn set_similarity_with_allowed(
9645        &mut self,
9646        request: &crate::query::SetSimilarityRequest,
9647        allowed: Option<&std::collections::HashSet<RowId>>,
9648    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9649        self.set_similarity_explained_at(request, self.snapshot(), allowed)
9650            .map(|(hits, _)| hits)
9651    }
9652
9653    pub fn set_similarity_explained(
9654        &mut self,
9655        request: &crate::query::SetSimilarityRequest,
9656    ) -> Result<(
9657        Vec<crate::query::SetSimilarityHit>,
9658        crate::query::SetSimilarityTrace,
9659    )> {
9660        self.set_similarity_explained_at(request, self.snapshot(), None)
9661    }
9662
9663    fn set_similarity_explained_at(
9664        &mut self,
9665        request: &crate::query::SetSimilarityRequest,
9666        snapshot: Snapshot,
9667        allowed: Option<&std::collections::HashSet<RowId>>,
9668    ) -> Result<(
9669        Vec<crate::query::SetSimilarityHit>,
9670        crate::query::SetSimilarityTrace,
9671    )> {
9672        self.ensure_indexes_complete()?;
9673        self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, None)
9674    }
9675
9676    pub fn set_similarity_at_with_context(
9677        &mut self,
9678        request: &crate::query::SetSimilarityRequest,
9679        snapshot: Snapshot,
9680        allowed: Option<&std::collections::HashSet<RowId>>,
9681        context: Option<&crate::query::AiExecutionContext>,
9682    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9683        self.ensure_indexes_complete()?;
9684        self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, context)
9685            .map(|(hits, _)| hits)
9686    }
9687
9688    pub fn set_similarity_at_with_candidate_authorization_and_context(
9689        &mut self,
9690        request: &crate::query::SetSimilarityRequest,
9691        snapshot: Snapshot,
9692        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9693        context: Option<&crate::query::AiExecutionContext>,
9694    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9695        self.ensure_indexes_complete()?;
9696        self.set_similarity_explained_at_with_context(
9697            request,
9698            snapshot,
9699            None,
9700            authorization,
9701            context,
9702        )
9703        .map(|(hits, _)| hits)
9704    }
9705
9706    #[doc(hidden)]
9707    pub fn set_similarity_at_with_candidate_authorization_on_generation(
9708        &self,
9709        request: &crate::query::SetSimilarityRequest,
9710        snapshot: Snapshot,
9711        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9712        context: Option<&crate::query::AiExecutionContext>,
9713    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9714        self.set_similarity_explained_at_with_context(
9715            request,
9716            snapshot,
9717            None,
9718            authorization,
9719            context,
9720        )
9721        .map(|(hits, _)| hits)
9722    }
9723
9724    fn set_similarity_explained_at_with_context(
9725        &self,
9726        request: &crate::query::SetSimilarityRequest,
9727        snapshot: Snapshot,
9728        allowed: Option<&std::collections::HashSet<RowId>>,
9729        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9730        context: Option<&crate::query::AiExecutionContext>,
9731    ) -> Result<(
9732        Vec<crate::query::SetSimilarityHit>,
9733        crate::query::SetSimilarityTrace,
9734    )> {
9735        use crate::query::{
9736            Retriever, RetrieverScore, SetSimilarityHit, MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9737            MAX_SET_MEMBERS,
9738        };
9739        let mut trace = crate::query::SetSimilarityTrace::default();
9740        if request.members.is_empty() {
9741            return Ok((Vec::new(), trace));
9742        }
9743        if request.candidate_k == 0 || request.limit == 0 {
9744            return Err(MongrelError::InvalidArgument(
9745                "candidate_k and limit must be > 0".into(),
9746            ));
9747        }
9748        if request.candidate_k > MAX_RETRIEVER_K
9749            || request.limit > MAX_FINAL_LIMIT
9750            || request.members.len() > MAX_SET_MEMBERS
9751        {
9752            return Err(MongrelError::InvalidArgument(format!(
9753                "candidate_k must be <= {MAX_RETRIEVER_K}, limit <= {MAX_FINAL_LIMIT}, and members <= {MAX_SET_MEMBERS}"
9754            )));
9755        }
9756        if !request.min_jaccard.is_finite() || !(0.0..=1.0).contains(&request.min_jaccard) {
9757            return Err(MongrelError::InvalidArgument(
9758                "min_jaccard must be finite and between 0 and 1".into(),
9759            ));
9760        }
9761        let started = std::time::Instant::now();
9762        let retriever = Retriever::MinHash {
9763            column_id: request.column_id,
9764            members: request.members.clone(),
9765            k: request.candidate_k,
9766        };
9767        self.require_select()?;
9768        self.validate_retriever(&retriever)?;
9769        let hits = self.retrieve_filtered(
9770            &retriever,
9771            snapshot,
9772            None,
9773            allowed,
9774            candidate_authorization,
9775            context,
9776        )?;
9777        trace.candidate_generation_us = started.elapsed().as_micros() as u64;
9778        trace.candidate_count = hits.len();
9779        let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9780        if let Some(context) = context {
9781            context.consume(row_ids.len())?;
9782        }
9783        let started = std::time::Instant::now();
9784        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9785        let values = self.values_for_rids_batch_at_with_context(
9786            &row_ids,
9787            request.column_id,
9788            snapshot,
9789            query_now,
9790            context,
9791        )?;
9792        trace.gather_us = started.elapsed().as_micros() as u64;
9793        if let Some(context) = context {
9794            context.consume(request.members.len())?;
9795        }
9796        let query: std::collections::HashSet<_> = request.members.iter().cloned().collect();
9797        let estimates: std::collections::HashMap<_, _> = hits
9798            .into_iter()
9799            .filter_map(|hit| match hit.score {
9800                RetrieverScore::MinHashEstimatedJaccard(score) => Some((hit.row_id, score)),
9801                _ => None,
9802            })
9803            .collect();
9804        let started = std::time::Instant::now();
9805        let mut parsed = Vec::with_capacity(values.len());
9806        for (row_id, value) in values {
9807            let Value::Bytes(bytes) = value else {
9808                continue;
9809            };
9810            if let Some(context) = context {
9811                context.consume(crate::query::work_units(
9812                    bytes.len(),
9813                    crate::query::PARSE_WORK_QUANTUM,
9814                ))?;
9815            }
9816            let Ok(serde_json::Value::Array(members)) = serde_json::from_slice(&bytes) else {
9817                continue;
9818            };
9819            if let Some(context) = context {
9820                context.consume(members.len())?;
9821            }
9822            let stored = members
9823                .into_iter()
9824                .filter_map(|member| match member {
9825                    serde_json::Value::String(value) => {
9826                        Some(crate::query::SetMember::String(value))
9827                    }
9828                    serde_json::Value::Number(value) => {
9829                        Some(crate::query::SetMember::Number(value))
9830                    }
9831                    serde_json::Value::Bool(value) => Some(crate::query::SetMember::Boolean(value)),
9832                    _ => None,
9833                })
9834                .collect::<std::collections::HashSet<_>>();
9835            parsed.push((row_id, stored));
9836        }
9837        trace.parse_us = started.elapsed().as_micros() as u64;
9838        trace.verified_count = parsed.len();
9839        let started = std::time::Instant::now();
9840        let mut exact = Vec::new();
9841        for (row_id, stored) in parsed {
9842            if let Some(context) = context {
9843                context.consume(query.len().saturating_add(stored.len()))?;
9844            }
9845            let union = query.union(&stored).count();
9846            let score = if union == 0 {
9847                1.0
9848            } else {
9849                query.intersection(&stored).count() as f32 / union as f32
9850            };
9851            if score >= request.min_jaccard {
9852                exact.push(SetSimilarityHit {
9853                    row_id,
9854                    estimated_jaccard: estimates.get(&row_id).copied().unwrap_or_default(),
9855                    exact_jaccard: score,
9856                });
9857            }
9858        }
9859        exact.sort_by(|a, b| {
9860            b.exact_jaccard
9861                .total_cmp(&a.exact_jaccard)
9862                .then_with(|| a.row_id.cmp(&b.row_id))
9863        });
9864        exact.truncate(request.limit);
9865        trace.score_us = started.elapsed().as_micros() as u64;
9866        crate::trace::QueryTrace::record(|query_trace| {
9867            query_trace.exact_set_gather_nanos = query_trace
9868                .exact_set_gather_nanos
9869                .saturating_add(trace.gather_us.saturating_mul(1_000));
9870            query_trace.exact_set_parse_nanos = query_trace
9871                .exact_set_parse_nanos
9872                .saturating_add(trace.parse_us.saturating_mul(1_000));
9873            query_trace.exact_set_score_nanos = query_trace
9874                .exact_set_score_nanos
9875                .saturating_add(trace.score_us.saturating_mul(1_000));
9876        });
9877        Ok((exact, trace))
9878    }
9879
9880    /// Fetch one column for visible row ids without decoding unrelated columns.
9881    fn values_for_rids_batch_at(
9882        &self,
9883        row_ids: &[u64],
9884        column_id: u16,
9885        snapshot: Snapshot,
9886        now: i64,
9887    ) -> Result<Vec<(RowId, Value)>> {
9888        if self.ttl.is_none()
9889            && self.memtable.is_empty()
9890            && self.mutable_run.is_empty()
9891            && self.run_refs.len() == 1
9892        {
9893            let mut reader = self.open_reader(self.run_refs[0].run_id)?;
9894            // Small projections should not decode and scan the run's entire
9895            // row-id column. Resolve each requested row through the page-pruned
9896            // point path until a full visibility pass becomes cheaper. Keep
9897            // this crossover aligned with `rows_for_rids_at_time`.
9898            if row_ids.len().saturating_mul(24) < reader.row_count() {
9899                let mut values = Vec::with_capacity(row_ids.len());
9900                for &raw_row_id in row_ids {
9901                    let row_id = RowId(raw_row_id);
9902                    if let Some((_, false, Some(value))) =
9903                        reader.get_version_column_at(row_id, snapshot, column_id)?
9904                    {
9905                        values.push((row_id, value));
9906                    }
9907                }
9908                return Ok(values);
9909            }
9910            let (positions, visible_row_ids) = reader.visible_positions_with_rids_at(snapshot)?;
9911            let requested: Vec<(RowId, usize)> = row_ids
9912                .iter()
9913                .filter_map(|raw| {
9914                    visible_row_ids
9915                        .binary_search(&(*raw as i64))
9916                        .ok()
9917                        .map(|index| (RowId(*raw), positions[index]))
9918                })
9919                .collect();
9920            let values = reader.gather_column(
9921                column_id,
9922                &requested
9923                    .iter()
9924                    .map(|(_, position)| *position)
9925                    .collect::<Vec<_>>(),
9926            )?;
9927            return Ok(requested
9928                .into_iter()
9929                .zip(values)
9930                .map(|((row_id, _), value)| (row_id, value))
9931                .collect());
9932        }
9933        self.values_for_rids_at(row_ids, column_id, snapshot, now)
9934    }
9935
9936    fn values_for_rids_batch_at_with_context(
9937        &self,
9938        row_ids: &[u64],
9939        column_id: u16,
9940        snapshot: Snapshot,
9941        now: i64,
9942        context: Option<&crate::query::AiExecutionContext>,
9943    ) -> Result<Vec<(RowId, Value)>> {
9944        let Some(context) = context else {
9945            return self.values_for_rids_batch_at(row_ids, column_id, snapshot, now);
9946        };
9947        let mut values = Vec::with_capacity(row_ids.len());
9948        for chunk in row_ids.chunks(256) {
9949            context.checkpoint()?;
9950            values.extend(self.values_for_rids_batch_at(chunk, column_id, snapshot, now)?);
9951        }
9952        Ok(values)
9953    }
9954
9955    /// Fetch one column for visible row ids without decoding unrelated columns.
9956    fn values_for_rids_at(
9957        &self,
9958        row_ids: &[u64],
9959        column_id: u16,
9960        snapshot: Snapshot,
9961        now: i64,
9962    ) -> Result<Vec<(RowId, Value)>> {
9963        let mut readers: Vec<_> = self
9964            .run_refs
9965            .iter()
9966            .map(|run| self.open_reader(run.run_id))
9967            .collect::<Result<_>>()?;
9968        let mut out = Vec::with_capacity(row_ids.len());
9969        for &raw_row_id in row_ids {
9970            let row_id = RowId(raw_row_id);
9971            let mem = self.memtable.get_version_at(row_id, snapshot);
9972            let mutable = self.mutable_run.get_version_at(row_id, snapshot);
9973            let overlay = match (mem, mutable) {
9974                (Some((_, a)), Some((_, b))) => Some(
9975                    if Snapshot::version_is_newer(
9976                        a.committed_epoch,
9977                        a.commit_ts,
9978                        b.committed_epoch,
9979                        b.commit_ts,
9980                    ) {
9981                        a
9982                    } else {
9983                        b
9984                    },
9985                ),
9986                (Some((_, value)), None) | (None, Some((_, value))) => Some(value),
9987                (None, None) => None,
9988            };
9989            if let Some(row) = overlay {
9990                if !row.deleted && !self.row_expired_at(&row, now) {
9991                    if let Some(value) = row.columns.get(&column_id) {
9992                        out.push((row_id, value.clone()));
9993                    }
9994                }
9995                continue;
9996            }
9997
9998            // REM-001: keep `commit_ts` on the cross-run candidate so the winner is
9999            // selected under full HLC authority instead of the legacy epoch-only
10000            // tuple. The metadata-preserving `get_version_column_full_at`
10001            // returns a `VersionedColumnValue` (stamp, deleted, value).
10002            let mut best: Option<(crate::sorted_run::VersionedColumnValue, usize)> = None;
10003            for (index, reader) in readers.iter_mut().enumerate() {
10004                if let Some(versioned) =
10005                    reader.get_version_column_full_at(row_id, snapshot, column_id)?
10006                {
10007                    if best
10008                        .as_ref()
10009                        .map(|(current, _)| versioned.stamp.is_newer_than(current.stamp))
10010                        .unwrap_or(true)
10011                    {
10012                        best = Some((versioned, index));
10013                    }
10014                }
10015            }
10016            let Some((candidate, reader_index)) = best else {
10017                continue;
10018            };
10019            if candidate.deleted {
10020                continue;
10021            }
10022            let Some(value) = candidate.value.clone() else {
10023                continue;
10024            };
10025            if let Some(ttl) = self.ttl {
10026                if ttl.column_id != column_id {
10027                    if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
10028                        row_id,
10029                        snapshot,
10030                        ttl.column_id,
10031                    )? {
10032                        if let Some(Value::Int64(timestamp)) = ttl_value.value {
10033                            if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10034                                continue;
10035                            }
10036                        }
10037                    }
10038                } else if let Value::Int64(timestamp) = &value {
10039                    if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10040                        continue;
10041                    }
10042                }
10043            }
10044            out.push((row_id, value));
10045        }
10046        Ok(out)
10047    }
10048
10049    /// Materialize the MVCC-visible, non-deleted rows for `rids` at `snapshot`,
10050    /// preserving the input order. Rows whose newest visible version is a
10051    /// tombstone, or that no longer exist, are omitted. Shared by index-served
10052    /// [`query`] and the Phase 8.1 FK-join path.
10053    pub fn rows_for_rids(&self, rids: &[u64], snapshot: Snapshot) -> Result<Vec<Row>> {
10054        self.rows_for_rids_at_time(rids, snapshot, unix_nanos_now(), None)
10055    }
10056
10057    pub fn rows_for_rids_with_context(
10058        &self,
10059        rids: &[u64],
10060        snapshot: Snapshot,
10061        context: &crate::query::AiExecutionContext,
10062    ) -> Result<Vec<Row>> {
10063        context.consume(rids.len().saturating_mul(self.schema.columns.len()))?;
10064        self.rows_for_rids_at_time(rids, snapshot, context.query_time_nanos(), None)
10065    }
10066
10067    fn rows_for_rids_at_time(
10068        &self,
10069        rids: &[u64],
10070        snapshot: Snapshot,
10071        ttl_now: i64,
10072        control: Option<&crate::ExecutionControl>,
10073    ) -> Result<Vec<Row>> {
10074        use std::collections::HashMap;
10075        let mut rows = Vec::with_capacity(rids.len());
10076        // Overlay (memtable + mutable-run) newest visible version per rid —
10077        // these shadow any stale version stored in a run. Prefer HLC order via
10078        // version_is_newer when stamps are present (P0.5-T3).
10079        //
10080        // `rids` is already index-resolved (the caller's condition set), so it
10081        // is normally tiny relative to the memtable/mutable-run tiers — a
10082        // single-row PK/unique check feeding insert/update/delete resolves to
10083        // 0 or 1 rid. Materializing every version in both tiers (the old
10084        // behavior) cost O(tier size) regardless, which meant an unrelated
10085        // full-table-sized scan (plus the drop cost of the resulting map) on
10086        // every point lookup once the table grew large. Below the crossover,
10087        // a direct per-rid probe (`get_version_at`) wins; once `rids` approaches
10088        // tier size, one linear materializing pass beats `rids.len()` separate
10089        // probes, so fall back to it.
10090        let tier_size = self.memtable.len() + self.mutable_run.len();
10091        let mut overlay: HashMap<u64, Row> = HashMap::with_capacity(rids.len());
10092        if rids.len().saturating_mul(24) < tier_size {
10093            for &rid in rids {
10094                if overlay.len() & 255 == 0 {
10095                    control
10096                        .map(crate::ExecutionControl::checkpoint)
10097                        .transpose()?;
10098                }
10099                let mem = self.memtable.get_version_at(RowId(rid), snapshot);
10100                let mrun = self.mutable_run.get_version_at(RowId(rid), snapshot);
10101                let newest = match (mem, mrun) {
10102                    (Some((_, mr)), Some((_, rr))) => Some(
10103                        if Snapshot::version_is_newer(
10104                            mr.committed_epoch,
10105                            mr.commit_ts,
10106                            rr.committed_epoch,
10107                            rr.commit_ts,
10108                        ) {
10109                            mr
10110                        } else {
10111                            rr
10112                        },
10113                    ),
10114                    (Some((_, mr)), None) => Some(mr),
10115                    (None, Some((_, rr))) => Some(rr),
10116                    (None, None) => None,
10117                };
10118                if let Some(row) = newest {
10119                    overlay.insert(rid, row);
10120                }
10121            }
10122        } else {
10123            let fold_newest = |row: Row, overlay: &mut HashMap<u64, Row>| {
10124                overlay
10125                    .entry(row.row_id.0)
10126                    .and_modify(|e| {
10127                        if Snapshot::version_is_newer(
10128                            row.committed_epoch,
10129                            row.commit_ts,
10130                            e.committed_epoch,
10131                            e.commit_ts,
10132                        ) {
10133                            *e = row.clone();
10134                        }
10135                    })
10136                    .or_insert(row);
10137            };
10138            for (index, row) in self
10139                .memtable
10140                .visible_versions_at(snapshot)
10141                .into_iter()
10142                .enumerate()
10143            {
10144                if index & 255 == 0 {
10145                    control
10146                        .map(crate::ExecutionControl::checkpoint)
10147                        .transpose()?;
10148                }
10149                fold_newest(row, &mut overlay);
10150            }
10151            for (index, row) in self
10152                .mutable_run
10153                .visible_versions_at(snapshot)
10154                .into_iter()
10155                .enumerate()
10156            {
10157                if index & 255 == 0 {
10158                    control
10159                        .map(crate::ExecutionControl::checkpoint)
10160                        .transpose()?;
10161                }
10162                fold_newest(row, &mut overlay);
10163            }
10164        }
10165        if self.run_refs.len() == 1 {
10166            let mut reader = self.open_reader(self.run_refs[0].run_id)?;
10167            // Same crossover as the overlay above: `visible_positions_with_rids`
10168            // decodes/scans the run's *entire* row-id column regardless of
10169            // `rids.len()`, so a point lookup (0 or 1 rid, the common
10170            // insert/update/delete case) paid an O(run size) tax for a single
10171            // row. Below the crossover, `get_version`'s page-pruned lookup
10172            // (`SYS_ROW_ID` pages carry exact row-id bounds) resolves each rid
10173            // by decoding only its page, no whole-column decode.
10174            if rids.len().saturating_mul(24) < reader.row_count() {
10175                for (index, &rid) in rids.iter().enumerate() {
10176                    if index & 255 == 0 {
10177                        control
10178                            .map(crate::ExecutionControl::checkpoint)
10179                            .transpose()?;
10180                    }
10181                    if let Some(r) = overlay.get(&rid) {
10182                        if !r.deleted {
10183                            rows.push(r.clone());
10184                        }
10185                        continue;
10186                    }
10187                    if let Some((_, row)) = reader.get_version_at(RowId(rid), snapshot)? {
10188                        if !row.deleted {
10189                            rows.push(row);
10190                        }
10191                    }
10192                }
10193                rows.retain(|row| !self.row_expired_at(row, ttl_now));
10194                return Ok(rows);
10195            }
10196            // Phase 16.3b: decode the system columns ONCE (via the clean-run-
10197            // shortcut visibility pass) and binary-search each requested rid,
10198            // instead of `get_version`-per-rid which re-decoded + cloned the
10199            // full system columns on every call (the ~350 ms native-query tax).
10200            // Phase 16.3b finish: batch the survivor positions into ONE
10201            // `materialize_batch` call so user columns are decoded once each via
10202            // the typed, page-cached path (not a per-rid `Vec<Value>` decode +
10203            // `.cloned()`).
10204            let (positions, vis_rids) = reader.visible_positions_with_rids_at(snapshot)?;
10205            // First pass: classify each input rid (overlay / run position /
10206            // not-found), recording the run positions to fetch in input order.
10207            enum Src {
10208                Overlay,
10209                Run,
10210            }
10211            let mut plan: Vec<Src> = Vec::with_capacity(rids.len());
10212            let mut fetch: Vec<usize> = Vec::with_capacity(rids.len());
10213            for (index, rid) in rids.iter().enumerate() {
10214                if index & 255 == 0 {
10215                    control
10216                        .map(crate::ExecutionControl::checkpoint)
10217                        .transpose()?;
10218                }
10219                if overlay.contains_key(rid) {
10220                    plan.push(Src::Overlay);
10221                    continue;
10222                }
10223                match vis_rids.binary_search(&(*rid as i64)) {
10224                    Ok(i) => {
10225                        plan.push(Src::Run);
10226                        fetch.push(positions[i]);
10227                    }
10228                    Err(_) => { /* not found — omitted from output */ }
10229                }
10230            }
10231            let fetched = reader.materialize_batch(&fetch)?;
10232            let mut fetched_iter = fetched.into_iter();
10233            for (index, (rid, src)) in rids.iter().zip(plan).enumerate() {
10234                if index & 255 == 0 {
10235                    control
10236                        .map(crate::ExecutionControl::checkpoint)
10237                        .transpose()?;
10238                }
10239                match src {
10240                    Src::Overlay => {
10241                        if let Some(r) = overlay.get(rid) {
10242                            if !r.deleted {
10243                                rows.push(r.clone());
10244                            }
10245                        }
10246                    }
10247                    Src::Run => {
10248                        if let Some(row) = fetched_iter.next() {
10249                            if !row.deleted {
10250                                rows.push(row);
10251                            }
10252                        }
10253                    }
10254                }
10255            }
10256            rows.retain(|row| !self.row_expired_at(row, ttl_now));
10257            return Ok(rows);
10258        }
10259        // Multi-run: one reader per run; newest visible version across all runs
10260        // + the overlay. (Per-rid `get_version` here is unavoidable without a
10261        // cross-run merge, but multi-run is the uncommon cold case.)
10262        let mut readers: Vec<_> = self
10263            .run_refs
10264            .iter()
10265            .map(|rr| self.open_reader(rr.run_id))
10266            .collect::<Result<Vec<_>>>()?;
10267        for (index, rid) in rids.iter().enumerate() {
10268            if index & 255 == 0 {
10269                control
10270                    .map(crate::ExecutionControl::checkpoint)
10271                    .transpose()?;
10272            }
10273            if let Some(r) = overlay.get(rid) {
10274                if !r.deleted {
10275                    rows.push(r.clone());
10276                }
10277                continue;
10278            }
10279            // REM-001: keep the full VersionStamp so the cross-run fold uses HLC
10280            // authority when both candidates are stamped (the legacy
10281            // `(epoch, _)` tuple discarded `commit_ts` and let a higher-epoch
10282            // run silently outrank an HLC-newer run).
10283            let mut best: Option<(VersionStamp, Row)> = None;
10284            for reader in readers.iter_mut() {
10285                if let Ok(Some((stamp, row))) = reader.get_version_stamp_at(RowId(*rid), snapshot) {
10286                    if best
10287                        .as_ref()
10288                        .map(|(current, _)| stamp.is_newer_than(*current))
10289                        .unwrap_or(true)
10290                    {
10291                        best = Some((stamp, row));
10292                    }
10293                }
10294            }
10295            if let Some((_, r)) = best {
10296                if !r.deleted {
10297                    rows.push(r);
10298                }
10299            }
10300        }
10301        rows.retain(|row| !self.row_expired_at(row, ttl_now));
10302        Ok(rows)
10303    }
10304
10305    /// Resolve the referencing (FK) side of a primary-key ↔ foreign-key join as
10306    /// a row-id set (Phase 8.1): union the roaring-bitmap entries of
10307    /// `fk_column_id` for every value in `pk_values` — the surviving
10308    /// primary-key values — then intersect with `fk_conditions`, i.e. any
10309    /// FK-side predicates (`ann_search ∩ fm_contains`, bitmap equality, range,
10310    /// …). Returns the survivor row-ids ascending. Requires a bitmap index on
10311    /// `fk_column_id`; returns an empty set when there is none.
10312    /// Whether live indexes are complete (Phase 14.7 + 17.2: the broadcast
10313    /// join path checks this before using the HOT index).
10314    pub fn indexes_complete(&self) -> bool {
10315        self.indexes_complete
10316    }
10317
10318    /// Where bulk loads put the index-build cost (see [`IndexBuildPolicy`]).
10319    pub fn index_build_policy(&self) -> IndexBuildPolicy {
10320        self.index_build_policy
10321    }
10322
10323    /// Set the bulk-load index-build policy. Takes effect on the next
10324    /// `bulk_load` / `bulk_load_columns` / `bulk_load_fast`; never changes
10325    /// already-built indexes.
10326    pub fn set_index_build_policy(&mut self, policy: IndexBuildPolicy) {
10327        self.index_build_policy = policy;
10328    }
10329
10330    /// Phase 17.2: broadcast join — return the distinct values in this table's
10331    /// bitmap index for `column_id` that also exist as a key in `pk_db`'s HOT
10332    /// index. Avoids loading the entire PK table when the FK column has low
10333    /// cardinality. Returns `None` if no bitmap index exists for the column.
10334    pub fn broadcast_join_values(&self, column_id: u16, pk_db: &Table) -> Option<Vec<Vec<u8>>> {
10335        // A deferred bulk load leaves the bitmap unbuilt — its (empty) key set
10336        // would silently produce an empty join. Decline; the caller falls back
10337        // to the PK-side query path, which completes indexes lazily.
10338        if !self.indexes_complete {
10339            return None;
10340        }
10341        let b = self.bitmap.get(&column_id)?;
10342        let result: Vec<Vec<u8>> = b
10343            .keys()
10344            .into_iter()
10345            .filter(|k| pk_db.hot.get(k.as_slice()).is_some())
10346            .collect();
10347        Some(result)
10348    }
10349
10350    pub fn fk_join_row_ids(
10351        &self,
10352        fk_column_id: u16,
10353        pk_values: &[Vec<u8>],
10354        fk_conditions: &[crate::query::Condition],
10355        snapshot: Snapshot,
10356    ) -> Result<Vec<u64>> {
10357        let Some(b) = self.bitmap.get(&fk_column_id) else {
10358            return Ok(Vec::new());
10359        };
10360        let mut join_set = {
10361            let mut acc = roaring::RoaringBitmap::new();
10362            for v in pk_values {
10363                acc |= b.get(v);
10364            }
10365            RowIdSet::from_roaring(acc)
10366        };
10367        if !fk_conditions.is_empty() {
10368            let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10369            sets.push(join_set);
10370            for c in fk_conditions {
10371                sets.push(self.resolve_condition(c, snapshot)?);
10372            }
10373            join_set = RowIdSet::intersect_many(sets);
10374        }
10375        Ok(join_set.into_sorted_vec())
10376    }
10377
10378    /// Like [`fk_join_row_ids`] but returns only the **cardinality** of the FK
10379    /// survivor set — without materializing or sorting it. For a bare
10380    /// `COUNT(*)` join with no FK-side filter this is O(1) on the bitmap union
10381    /// (Phase 17.4): the prior path built a `HashSet<u64>` + `Vec<u64>` +
10382    /// `sort_unstable` over up to N rows only to read `.len()`.
10383    pub fn fk_join_count(
10384        &self,
10385        fk_column_id: u16,
10386        pk_values: &[Vec<u8>],
10387        fk_conditions: &[crate::query::Condition],
10388        snapshot: Snapshot,
10389    ) -> Result<u64> {
10390        let Some(b) = self.bitmap.get(&fk_column_id) else {
10391            return Ok(0);
10392        };
10393        let mut acc = roaring::RoaringBitmap::new();
10394        for v in pk_values {
10395            acc |= b.get(v);
10396        }
10397        if fk_conditions.is_empty() {
10398            return Ok(acc.len());
10399        }
10400        let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10401        sets.push(RowIdSet::from_roaring(acc));
10402        for c in fk_conditions {
10403            sets.push(self.resolve_condition(c, snapshot)?);
10404        }
10405        Ok(RowIdSet::intersect_many(sets).len() as u64)
10406    }
10407
10408    /// Inspect the row at `rid` directly — without going through
10409    /// [`Self::get`] (which collapses tombstones and TTL-expired rows into
10410    /// `None`). Used by [`Self::resolve_pk_with_hot_fallback`] so the
10411    /// fallback reason can distinguish Tombstone from TtlExpired.
10412    fn inspect_row_at(&self, rid: RowId, snapshot: Snapshot) -> Option<crate::memtable::Row> {
10413        let mut best: Option<crate::memtable::Row> = None;
10414        let mut consider = |row: crate::memtable::Row| {
10415            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
10416                return;
10417            }
10418            if best.as_ref().is_none_or(|current| {
10419                Snapshot::version_is_newer(
10420                    row.committed_epoch,
10421                    row.commit_ts,
10422                    current.committed_epoch,
10423                    current.commit_ts,
10424                )
10425            }) {
10426                best = Some(row);
10427            }
10428        };
10429        if let Some((_, row)) = self.memtable.get_version_at(rid, snapshot) {
10430            consider(row);
10431        }
10432        if let Some((_, row)) = self.mutable_run.get_version_at(rid, snapshot) {
10433            consider(row);
10434        }
10435        for rr in &self.run_refs {
10436            if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
10437                if rid.0 < min_rid || rid.0 > max_rid {
10438                    continue;
10439                }
10440            }
10441            let Ok(mut reader) = self.open_reader(rr.run_id) else {
10442                continue;
10443            };
10444            // REM-001: route through the full-Snapshot run API so HLC-stamped
10445            // row versions are admitted by `observes_row` and recency selection
10446            // uses `commit_ts` instead of discarding it at the epoch boundary.
10447            let Ok(Some((_stamp, row))) = reader.get_version_stamp_at(rid, snapshot) else {
10448                continue;
10449            };
10450            consider(row);
10451        }
10452        best
10453    }
10454
10455    fn resolve_pk_with_hot_fallback(
10456        &self,
10457        pk_column_id: u16,
10458        lookup: &[u8],
10459        snapshot: Snapshot,
10460    ) -> Result<RowIdSet> {
10461        // Private WAL: the in-flight batch lands in the memtable at
10462        // `pending_epoch = visible + 1` (puts and matching tombstones). A
10463        // caller snapshot pinned at the *current* visible epoch predates
10464        // every pending write, so a PK lookup would resolve a just-replaced
10465        // PK to the stale pre-image (or resurrect a just-deleted row).
10466        // Advance to `pending_epoch` and let the batch participate — the
10467        // same read-your-writes rule as `eligible_candidate_ids` and
10468        // `range_scan_i64`. A strictly *historical* pinned snapshot is
10469        // honored as-is: the pending batch is uncommitted and must stay
10470        // invisible to it. Shared WAL tables keep the original snapshot
10471        // because their pending rows live in `pending_rows` and haven't
10472        // been materialised into the memtable yet.
10473        let snapshot = if self.is_shared()
10474            || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10475            || snapshot.epoch.0 != self.epoch.visible().0
10476        {
10477            snapshot
10478        } else {
10479            Snapshot::at(self.pending_epoch())
10480        };
10481        // Indexes incomplete: record `IndexIncomplete` and run the scanner
10482        // directly. The HOT map may be stale or absent, but the scanner's
10483        // result is still correct because it reads durable runs.
10484        if !self.indexes_complete {
10485            let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10486            self.record_hot_fallback_reason(crate::trace::HotFallbackReason::IndexIncomplete);
10487            return Ok(result);
10488        }
10489        // Step 1 — HOT hit attempt. Look up the mapped `RowId`; if absent,
10490        // delegate straight to the scanner (which classifies the reason).
10491        let mapped = self.hot.get(lookup);
10492        let Some(r) = mapped else {
10493            let (result, reason) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10494            self.record_hot_fallback_reason(reason);
10495            return Ok(result);
10496        };
10497        // Step 2 — historical snapshot: the HOT map is keyed on the latest
10498        // RowId, not the historical one. The historical branch records its
10499        // own reason and runs the scanner; the inner scanner is suppressed
10500        // from recording a second reason (see `pk_equality_fallback`).
10501        if snapshot.epoch < self.current_epoch() {
10502            self.record_hot_fallback_reason(crate::trace::HotFallbackReason::HistoricalSnapshot);
10503            let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10504            return Ok(result);
10505        }
10506        // Step 3 — materialize the mapped candidate and classify it.
10507        // `inspect_row_at` does not collapse TTL-expired rows into `None`,
10508        // so the inspection can distinguish Tombstone from TtlExpired.
10509        let materialized = self.inspect_row_at(r, snapshot);
10510        let now_nanos = unix_nanos_now();
10511        let inspection = crate::trace::inspect_hot_candidate(
10512            materialized.as_ref(),
10513            snapshot,
10514            self.ttl,
10515            now_nanos,
10516            pk_column_id,
10517            lookup,
10518            |row| {
10519                let pk_value = row.columns.get(&pk_column_id);
10520                pk_value
10521                    .map(|v| self.index_lookup_key(pk_column_id, v))
10522                    .unwrap_or_default()
10523            },
10524        );
10525        match inspection {
10526            crate::trace::HotCandidateInspection::Hit(row) => {
10527                self.lookup_metrics
10528                    .hot_lookup_hit
10529                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10530                crate::trace::QueryTrace::record(|t| {
10531                    t.hot_lookup_attempted = true;
10532                    t.hot_lookup_hit = true;
10533                });
10534                Ok(RowIdSet::one(row.row_id.0))
10535            }
10536            failure => {
10537                let reason = match &failure {
10538                    crate::trace::HotCandidateInspection::Hit(_) => unreachable!(),
10539                    crate::trace::HotCandidateInspection::MissingRow => {
10540                        // `inspect_row_at` could not find any version at this
10541                        // RowId. The HOT map pointed at a `RowId` that does
10542                        // not exist; the closest label is Tombstone (the row
10543                        // used to be there and is now gone).
10544                        crate::trace::HotFallbackReason::Tombstone
10545                    }
10546                    crate::trace::HotCandidateInspection::Invisible => {
10547                        crate::trace::HotFallbackReason::InvisibleAtSnapshot
10548                    }
10549                    crate::trace::HotCandidateInspection::Tombstone => {
10550                        crate::trace::HotFallbackReason::Tombstone
10551                    }
10552                    crate::trace::HotCandidateInspection::TtlExpired => {
10553                        crate::trace::HotFallbackReason::TtlExpired
10554                    }
10555                    crate::trace::HotCandidateInspection::PrimaryKeyMismatch { .. } => {
10556                        crate::trace::HotFallbackReason::PrimaryKeyMismatch
10557                    }
10558                };
10559                // The HOT map may have a stale RowId; the inner scanner is
10560                // the only source of the verified RowIdSet. Suppress the
10561                // inner `record_hot_fallback_reason` call by passing
10562                // `snapshot` unchanged — the historical/PK-mismatch branches
10563                // already short-circuit before re-recording.
10564                let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10565                self.record_hot_fallback_reason(reason);
10566                Ok(result)
10567            }
10568        }
10569    }
10570
10571    /// Resolve a single condition to its row-id set. Index-served conditions use
10572    /// the in-memory indexes; `Range`/`RangeF64` prefer the learned (PGM) index
10573    /// or the reader's page-index-skipping path on the single-run fast path, and
10574    /// only fall back to a `visible_rows` scan off the fast path (multi-run).
10575    fn resolve_condition(
10576        &self,
10577        c: &crate::query::Condition,
10578        snapshot: Snapshot,
10579    ) -> Result<RowIdSet> {
10580        self.resolve_condition_with_allowed(c, snapshot, None)
10581    }
10582
10583    fn resolve_condition_with_allowed(
10584        &self,
10585        c: &crate::query::Condition,
10586        snapshot: Snapshot,
10587        allowed: Option<&std::collections::HashSet<RowId>>,
10588    ) -> Result<RowIdSet> {
10589        use crate::query::Condition;
10590        self.validate_condition(c)?;
10591        Ok(match c {
10592            Condition::Pk(key) => {
10593                let lookup = self
10594                    .schema
10595                    .primary_key()
10596                    .map(|pk| self.index_lookup_key_bytes(pk.id, key))
10597                    .unwrap_or_else(|| key.clone());
10598                if let Some(pk_col) = self.schema.primary_key() {
10599                    return self.resolve_pk_with_hot_fallback(pk_col.id, &lookup, snapshot);
10600                }
10601                // No primary key column — HOT is meaningless. Match the
10602                // legacy behavior: every PK condition collapses to an empty
10603                // set.
10604                RowIdSet::empty()
10605            }
10606            Condition::BitmapEq { column_id, value } => {
10607                let lookup = self.index_lookup_key_bytes(*column_id, value);
10608                self.bitmap
10609                    .get(column_id)
10610                    .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
10611                    .unwrap_or_else(RowIdSet::empty)
10612            }
10613            Condition::BitmapIn { column_id, values } => {
10614                let bm = self.bitmap.get(column_id);
10615                let mut acc = roaring::RoaringBitmap::new();
10616                if let Some(b) = bm {
10617                    for v in values {
10618                        let lookup = self.index_lookup_key_bytes(*column_id, v);
10619                        acc |= b.get(&lookup);
10620                    }
10621                }
10622                RowIdSet::from_roaring(acc)
10623            }
10624            Condition::BytesPrefix { column_id, prefix } => {
10625                // §5.6: enumerate bitmap keys sharing the prefix for an exact
10626                // prefix match (anchored `LIKE 'prefix%'`), tighter than the
10627                // FM substring superset. The caller only emits this when the
10628                // column has a bitmap index.
10629                if let Some(b) = self.bitmap.get(column_id) {
10630                    let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
10631                    let mut acc = roaring::RoaringBitmap::new();
10632                    for key in b.keys() {
10633                        if key.starts_with(&lookup_prefix) {
10634                            acc |= b.get(&key);
10635                        }
10636                    }
10637                    RowIdSet::from_roaring(acc)
10638                } else {
10639                    RowIdSet::empty()
10640                }
10641            }
10642            Condition::FmContains { column_id, pattern } => self
10643                .fm
10644                .get(column_id)
10645                .map(|f| {
10646                    RowIdSet::from_unsorted(f.locate(pattern).into_iter().map(|r| r.0).collect())
10647                })
10648                .unwrap_or_else(RowIdSet::empty),
10649            Condition::FmContainsAll {
10650                column_id,
10651                patterns,
10652            } => {
10653                // Multi-segment intersection (Priority 12): resolve each segment
10654                // via FM and intersect — much tighter than the single longest.
10655                if let Some(f) = self.fm.get(column_id) {
10656                    let sets: Vec<RowIdSet> = patterns
10657                        .iter()
10658                        .map(|pat| {
10659                            RowIdSet::from_unsorted(
10660                                f.locate(pat).into_iter().map(|r| r.0).collect(),
10661                            )
10662                        })
10663                        .collect();
10664                    RowIdSet::intersect_many(sets)
10665                } else {
10666                    RowIdSet::empty()
10667                }
10668            }
10669            Condition::Ann {
10670                column_id,
10671                query,
10672                k,
10673            } => RowIdSet::from_unsorted(
10674                self.retrieve_filtered(
10675                    &crate::query::Retriever::Ann {
10676                        column_id: *column_id,
10677                        query: query.clone(),
10678                        k: *k,
10679                    },
10680                    snapshot,
10681                    None,
10682                    allowed,
10683                    None,
10684                    None,
10685                )?
10686                .into_iter()
10687                .map(|hit| hit.row_id.0)
10688                .collect(),
10689            ),
10690            Condition::SparseMatch {
10691                column_id,
10692                query,
10693                k,
10694            } => RowIdSet::from_unsorted(
10695                self.retrieve_filtered(
10696                    &crate::query::Retriever::Sparse {
10697                        column_id: *column_id,
10698                        query: query.clone(),
10699                        k: *k,
10700                    },
10701                    snapshot,
10702                    None,
10703                    allowed,
10704                    None,
10705                    None,
10706                )?
10707                .into_iter()
10708                .map(|hit| hit.row_id.0)
10709                .collect(),
10710            ),
10711            Condition::MinHashSimilar {
10712                column_id,
10713                query,
10714                k,
10715            } => match self.minhash.get(column_id) {
10716                Some(index) => {
10717                    let candidates = index.candidate_row_ids(query);
10718                    let eligible =
10719                        self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
10720                    RowIdSet::from_unsorted(
10721                        index
10722                            .search_filtered(query, *k, |row_id| {
10723                                eligible.contains(&row_id)
10724                                    && allowed.is_none_or(|allowed| allowed.contains(&row_id))
10725                            })
10726                            .into_iter()
10727                            .map(|(row_id, _)| row_id.0)
10728                            .collect(),
10729                    )
10730                }
10731                None => RowIdSet::empty(),
10732            },
10733            Condition::Range { column_id, lo, hi } => {
10734                // Build the candidate set from the durable tier — the learned
10735                // index (built from sorted runs) or a single page-pruned run —
10736                // then merge the memtable/mutable-run overlay. An overlay row
10737                // supersedes its run version (it may have been updated out of
10738                // range or deleted), so overlay rids are dropped from the run
10739                // set and re-evaluated from the overlay directly. Without this
10740                // merge, rows still in the memtable are invisible to a ranged
10741                // read whenever a LearnedRange index is present.
10742                //
10743                // Point equality (`lo == hi`) additionally unions the Bitmap
10744                // secondary when one exists on this column. The TypeScript Kit
10745                // always pushes int64 `eq()` as RangeInt (not BitmapEq / Pk),
10746                // so product listing-by-FK would never hit the Bitmap that
10747                // `maintain_bitmap_secondary_on_replace` keeps correct after
10748                // updates. Dual-sourcing Range + Bitmap closes that gap: a
10749                // desynced run/LearnedRange plan can no longer hide a live row
10750                // that still has a correct Bitmap membership (and vice versa
10751                // the overlay merge still covers pure-memtable puts).
10752                let mut set = if let Some(li) = self.learned_range.get(column_id) {
10753                    if self.run_refs.len() == 1 {
10754                        // Single-run: learned_range was built from this run and
10755                        // excludes tombstones, so it's MVCC-correct.
10756                        RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
10757                    } else {
10758                        // Multi-run: learned_range only covers run_refs[0]; a
10759                        // tombstone in a later run wouldn't strip its alive
10760                        // preimage rid from the PGM, and the overlay merge
10761                        // (memtable + mutable_run) is empty after a spill, so a
10762                        // leaked rid would surface as a wrong hit. Fall through
10763                        // to the MVCC-aware multi-run path so deletes land in
10764                        // any run are honored.
10765                        let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10766                        if lo == hi {
10767                            self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10768                        }
10769                        return Ok(multi);
10770                    }
10771                } else if self.run_refs.len() == 1 {
10772                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10773                    r.range_row_id_set_i64(*column_id, *lo, *hi)?
10774                } else {
10775                    // Multi-run / no learned index: full range_scan already
10776                    // merges overlay; union Bitmap for point queries below.
10777                    let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10778                    if lo == hi {
10779                        self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10780                    }
10781                    return Ok(multi);
10782                };
10783                if self.learned_range.get(column_id).is_none() && self.run_refs.len() == 1 {
10784                    let candidates: Vec<RowId> =
10785                        set.into_sorted_vec().into_iter().map(RowId).collect();
10786                    set = RowIdSet::from_unsorted(
10787                        self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?
10788                            .into_iter()
10789                            .map(|row_id| row_id.0)
10790                            .collect(),
10791                    );
10792                }
10793                set.remove_many(self.overlay_rid_set(snapshot));
10794                self.range_scan_overlay_i64(&mut set, *column_id, *lo, *hi, snapshot);
10795                if lo == hi {
10796                    self.union_bitmap_point_i64(&mut set, *column_id, *lo, snapshot);
10797                }
10798                RowIdSet::from_unsorted(
10799                    set.into_sorted_vec()
10800                        .into_iter()
10801                        .filter(|row_id| self.get(RowId(*row_id), snapshot).is_some())
10802                        .collect(),
10803                )
10804            }
10805            Condition::RangeF64 {
10806                column_id,
10807                lo,
10808                lo_inclusive,
10809                hi,
10810                hi_inclusive,
10811            } => {
10812                // See the `Range` arm: merge the overlay over the durable
10813                // candidate set so memtable/mutable-run rows are visible.
10814                let mut set = if let Some(li) = self.learned_range.get(column_id) {
10815                    RowIdSet::from_unsorted(
10816                        li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
10817                            .into_iter()
10818                            .collect(),
10819                    )
10820                } else if self.run_refs.len() == 1 {
10821                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10822                    r.range_row_id_set_f64(*column_id, *lo, *lo_inclusive, *hi, *hi_inclusive)?
10823                } else {
10824                    return self.range_scan_f64(
10825                        *column_id,
10826                        *lo,
10827                        *lo_inclusive,
10828                        *hi,
10829                        *hi_inclusive,
10830                        snapshot,
10831                    );
10832                };
10833                set.remove_many(self.overlay_rid_set(snapshot));
10834                self.range_scan_overlay_f64(
10835                    &mut set,
10836                    *column_id,
10837                    *lo,
10838                    *lo_inclusive,
10839                    *hi,
10840                    *hi_inclusive,
10841                    snapshot,
10842                );
10843                set
10844            }
10845            Condition::IsNull { column_id } => {
10846                let mut set = if self.run_refs.len() == 1 {
10847                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10848                    r.null_row_id_set(*column_id, true)?
10849                } else {
10850                    return self.null_scan(*column_id, true, snapshot);
10851                };
10852                set.remove_many(self.overlay_rid_set(snapshot));
10853                self.null_scan_overlay(&mut set, *column_id, true, snapshot);
10854                set
10855            }
10856            Condition::IsNotNull { column_id } => {
10857                let mut set = if self.run_refs.len() == 1 {
10858                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10859                    r.null_row_id_set(*column_id, false)?
10860                } else {
10861                    return self.null_scan(*column_id, false, snapshot);
10862                };
10863                set.remove_many(self.overlay_rid_set(snapshot));
10864                self.null_scan_overlay(&mut set, *column_id, false, snapshot);
10865                set
10866            }
10867        })
10868    }
10869
10870    /// Vectorized range scan for Int64 columns (Phase 13.2 / 16.3). Resolves the
10871    /// survivor set via the reader's **page-pruned** path — pages whose `[min,max]`
10872    /// excludes `[lo,hi]` are never decoded — restricted to MVCC-visible rows.
10873    /// This is layout-independent: correct under any memtable / multi-run state,
10874    /// so it is always safe to call (no "single clean run" gate). Overlay rows
10875    /// (memtable / mutable-run) are excluded from the run portion and checked
10876    /// directly via [`Self::range_scan_overlay_i64`].
10877    fn range_scan_i64(
10878        &self,
10879        column_id: u16,
10880        lo: i64,
10881        hi: i64,
10882        snapshot: Snapshot,
10883    ) -> Result<RowIdSet> {
10884        let mut row_ids = Vec::new();
10885        // Collect per-run tombstones whose newest visible version is a
10886        // tombstone: they must strip any alive preimage rid that landed in
10887        // an older run from the survivor set. Without this, a delete-after-
10888        // put whose tombstone lands in a newer run can't override the
10889        // preimage that `range_row_ids_visible_i64` happily returned for the
10890        // older run — the model filters them out, the engine must too.
10891        let mut tomb_rids: HashSet<u64> = HashSet::new();
10892        let overlay_rids = self.overlay_rid_set(snapshot);
10893        for rr in &self.run_refs {
10894            let mut reader = self.open_reader(rr.run_id)?;
10895            let matched = reader.range_row_ids_visible_i64_at(column_id, lo, hi, snapshot)?;
10896            for rid in matched {
10897                if !overlay_rids.contains(&rid) {
10898                    row_ids.push(rid);
10899                }
10900            }
10901            for rid in reader.tombstoned_row_ids_at(snapshot)? {
10902                tomb_rids.insert(rid);
10903            }
10904        }
10905        // Overlay tombstones strip matching run preimages. Collect them
10906        // under the same read-your-writes rule as
10907        // `eligible_candidate_ids`: a snapshot pinned at the current
10908        // visible epoch advances over the in-flight batch; a strictly
10909        // historical pinned snapshot must NOT see pending (uncommitted)
10910        // tombstones.
10911        let overlay_tombstone_snapshot = if self.is_shared()
10912            || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10913            || snapshot.epoch.0 != self.epoch.visible().0
10914        {
10915            snapshot
10916        } else {
10917            Snapshot::at(self.pending_epoch())
10918        };
10919        for row in self
10920            .memtable
10921            .visible_versions_at(overlay_tombstone_snapshot)
10922            .into_iter()
10923            .chain(
10924                self.mutable_run
10925                    .visible_versions_at(overlay_tombstone_snapshot),
10926            )
10927        {
10928            if row.deleted {
10929                tomb_rids.insert(row.row_id.0);
10930            }
10931        }
10932        let mut s = RowIdSet::from_unsorted(row_ids);
10933        s.remove_many(tomb_rids);
10934        let candidates: Vec<RowId> = s.into_sorted_vec().into_iter().map(RowId).collect();
10935        let eligible = self.eligible_candidate_ids(&candidates, column_id, snapshot, None)?;
10936        let mut s = RowIdSet::from_unsorted(eligible.into_iter().map(|row_id| row_id.0).collect());
10937        self.range_scan_overlay_i64(&mut s, column_id, lo, hi, snapshot);
10938        Ok(s)
10939    }
10940
10941    /// Float64 analogue of [`Self::range_scan_i64`] with per-bound inclusivity
10942    /// (Phase 13.2 / 16.3).
10943    fn range_scan_f64(
10944        &self,
10945        column_id: u16,
10946        lo: f64,
10947        lo_inclusive: bool,
10948        hi: f64,
10949        hi_inclusive: bool,
10950        snapshot: Snapshot,
10951    ) -> Result<RowIdSet> {
10952        let mut row_ids = Vec::new();
10953        let overlay_rids = self.overlay_rid_set(snapshot);
10954        for rr in &self.run_refs {
10955            let mut reader = self.open_reader(rr.run_id)?;
10956            let matched = reader.range_row_ids_visible_f64_at(
10957                column_id,
10958                lo,
10959                lo_inclusive,
10960                hi,
10961                hi_inclusive,
10962                snapshot,
10963            )?;
10964            for rid in matched {
10965                if !overlay_rids.contains(&rid) {
10966                    row_ids.push(rid);
10967                }
10968            }
10969        }
10970        let mut s = RowIdSet::from_unsorted(row_ids);
10971        self.range_scan_overlay_f64(
10972            &mut s,
10973            column_id,
10974            lo,
10975            lo_inclusive,
10976            hi,
10977            hi_inclusive,
10978            snapshot,
10979        );
10980        Ok(s)
10981    }
10982
10983    /// Collect the set of row-ids visible in the memtable / mutable-run overlay.
10984    fn overlay_rid_set(&self, snapshot: Snapshot) -> HashSet<u64> {
10985        let mut s = HashSet::new();
10986        for row in self.memtable.visible_versions_at(snapshot) {
10987            s.insert(row.row_id.0);
10988        }
10989        for row in self.mutable_run.visible_versions_at(snapshot) {
10990            s.insert(row.row_id.0);
10991        }
10992        s
10993    }
10994
10995    fn range_scan_overlay_i64(
10996        &self,
10997        s: &mut RowIdSet,
10998        column_id: u16,
10999        lo: i64,
11000        hi: i64,
11001        snapshot: Snapshot,
11002    ) {
11003        // Collapse both overlay tiers to the newest visible version per row id
11004        // (HLC-aware when stamped; P0.5-T3) before range-checking, so a stale
11005        // in-range mutable-run version cannot shadow a newer out-of-range
11006        // memtable version of the same row.
11007        // Both tiers already applied version_is_newer within themselves; when
11008        // both report a rid, prefer the HLC-newer of the two.
11009        let mut newest: HashMap<u64, Row> = HashMap::new();
11010        for r in self.mutable_run.visible_versions_at(snapshot) {
11011            newest.insert(r.row_id.0, r);
11012        }
11013        for r in self.memtable.visible_versions_at(snapshot) {
11014            newest
11015                .entry(r.row_id.0)
11016                .and_modify(|cur| {
11017                    if Snapshot::version_is_newer(
11018                        r.committed_epoch,
11019                        r.commit_ts,
11020                        cur.committed_epoch,
11021                        cur.commit_ts,
11022                    ) {
11023                        *cur = r.clone();
11024                    }
11025                })
11026                .or_insert(r);
11027        }
11028        for row in newest.values() {
11029            if !row.deleted {
11030                if let Some(Value::Int64(v)) = row.columns.get(&column_id) {
11031                    if *v >= lo && *v <= hi && !self.row_expired_at(row, unix_nanos_now()) {
11032                        s.insert(row.row_id.0);
11033                    }
11034                }
11035            }
11036        }
11037    }
11038
11039    #[allow(clippy::too_many_arguments)]
11040    fn range_scan_overlay_f64(
11041        &self,
11042        s: &mut RowIdSet,
11043        column_id: u16,
11044        lo: f64,
11045        lo_inclusive: bool,
11046        hi: f64,
11047        hi_inclusive: bool,
11048        snapshot: Snapshot,
11049    ) {
11050        // See `range_scan_overlay_i64`: dedup to the newest version per row id
11051        // across the memtable + mutable run before range-checking.
11052        let mut newest: HashMap<u64, Row> = HashMap::new();
11053        for r in self.mutable_run.visible_versions_at(snapshot) {
11054            newest.insert(r.row_id.0, r);
11055        }
11056        for r in self.memtable.visible_versions_at(snapshot) {
11057            newest
11058                .entry(r.row_id.0)
11059                .and_modify(|cur| {
11060                    if Snapshot::version_is_newer(
11061                        r.committed_epoch,
11062                        r.commit_ts,
11063                        cur.committed_epoch,
11064                        cur.commit_ts,
11065                    ) {
11066                        *cur = r.clone();
11067                    }
11068                })
11069                .or_insert(r);
11070        }
11071        for row in newest.values() {
11072            if !row.deleted {
11073                if let Some(Value::Float64(v)) = row.columns.get(&column_id) {
11074                    let ok_lo = if lo_inclusive { *v >= lo } else { *v > lo };
11075                    let ok_hi = if hi_inclusive { *v <= hi } else { *v < hi };
11076                    if ok_lo && ok_hi && !self.row_expired_at(row, unix_nanos_now()) {
11077                        s.insert(row.row_id.0);
11078                    }
11079                }
11080            }
11081        }
11082    }
11083
11084    /// Multi-run fallback for `IS NULL` / `IS NOT NULL`. Calls each run's
11085    /// MVCC-aware null scan and merges with the overlay.
11086    fn null_scan(&self, column_id: u16, want_nulls: bool, snapshot: Snapshot) -> Result<RowIdSet> {
11087        let mut row_ids = Vec::new();
11088        let overlay_rids = self.overlay_rid_set(snapshot);
11089        for rr in &self.run_refs {
11090            let mut reader = self.open_reader(rr.run_id)?;
11091            let matched = reader.null_row_ids_visible_at(column_id, want_nulls, snapshot)?;
11092            for rid in matched {
11093                if !overlay_rids.contains(&rid) {
11094                    row_ids.push(rid);
11095                }
11096            }
11097        }
11098        let mut s = RowIdSet::from_unsorted(row_ids);
11099        self.null_scan_overlay(&mut s, column_id, want_nulls, snapshot);
11100        Ok(s)
11101    }
11102
11103    /// Merge overlay rows for `IS NULL` / `IS NOT NULL`. An overlay row
11104    /// supersedes its run version, so overlay rids are removed from the run
11105    /// set and re-evaluated from the overlay values directly.
11106    fn null_scan_overlay(
11107        &self,
11108        s: &mut RowIdSet,
11109        column_id: u16,
11110        want_nulls: bool,
11111        snapshot: Snapshot,
11112    ) {
11113        let mut newest: HashMap<u64, Row> = HashMap::new();
11114        for r in self.mutable_run.visible_versions_at(snapshot) {
11115            newest.insert(r.row_id.0, r);
11116        }
11117        for r in self.memtable.visible_versions_at(snapshot) {
11118            newest
11119                .entry(r.row_id.0)
11120                .and_modify(|cur| {
11121                    if Snapshot::version_is_newer(
11122                        r.committed_epoch,
11123                        r.commit_ts,
11124                        cur.committed_epoch,
11125                        cur.commit_ts,
11126                    ) {
11127                        *cur = r.clone();
11128                    }
11129                })
11130                .or_insert(r);
11131        }
11132        for row in newest.values() {
11133            if row.deleted {
11134                continue;
11135            }
11136            let is_null = !row.columns.contains_key(&column_id)
11137                || matches!(row.columns.get(&column_id), Some(Value::Null) | None);
11138            if is_null == want_nulls {
11139                s.insert(row.row_id.0);
11140            }
11141        }
11142    }
11143
11144    pub fn snapshot(&self) -> Snapshot {
11145        let epoch = self.epoch.visible();
11146        // P0.5: mounted tables pin the shared HLC so HLC-stamped row versions
11147        // remain visible under at_hlc. Standalone private-WAL tables fall back
11148        // to epoch-only (private commits do not stamp HLC today).
11149        match &self.wal {
11150            WalSink::Shared(shared) => match shared.hlc.now() {
11151                Ok(commit_ts) => Snapshot::at_hlc(epoch, commit_ts),
11152                // Clock skew must not hide committed HLC rows from product reads.
11153                Err(_) => Snapshot::at_hlc(epoch, mongreldb_types::hlc::HlcTimestamp::MAX),
11154            },
11155            WalSink::Private(_) | WalSink::ReadOnly => Snapshot::at(epoch),
11156        }
11157    }
11158
11159    /// Generation of this table's row contents for table-local caches.
11160    pub fn data_generation(&self) -> u64 {
11161        self.data_generation
11162    }
11163
11164    pub(crate) fn bump_data_generation(&mut self) {
11165        self.data_generation = self.data_generation.wrapping_add(1);
11166    }
11167
11168    /// Stable catalog table id for this mounted table.
11169    pub fn table_id(&self) -> u64 {
11170        self.table_id
11171    }
11172
11173    /// Seal every active delta (memtable, mutable-run tier, HOT, reverse-PK
11174    /// map, and every secondary index) so the current state can be captured
11175    /// as an immutable generation. Sealing moves the active delta behind the
11176    /// shared frozen `Arc` without copying row data; the writer keeps
11177    /// appending to a fresh, empty active delta (S1C-001).
11178    fn seal_generations(&mut self) {
11179        self.memtable.seal();
11180        self.mutable_run.seal();
11181        self.hot.seal();
11182        for index in self.bitmap.values_mut() {
11183            index.seal();
11184        }
11185        for index in self.ann.values_mut() {
11186            index.seal();
11187        }
11188        for index in self.fm.values_mut() {
11189            index.seal();
11190        }
11191        for index in self.sparse.values_mut() {
11192            index.seal();
11193        }
11194        for index in self.minhash.values_mut() {
11195            index.seal();
11196        }
11197        self.pk_by_row.seal();
11198    }
11199
11200    /// Capture the current (freshly sealed) state as an immutable
11201    /// [`ReadGeneration`]. Cheap by construction: frozen layers are
11202    /// `Arc`-shared, schema/run-refs are small metadata copies, and every
11203    /// active delta is empty post-seal.
11204    fn capture_read_generation(&self) -> ReadGeneration {
11205        let visible_through = self.current_epoch();
11206        ReadGeneration {
11207            schema: Arc::new(self.schema.clone()),
11208            base_runs: Arc::new(self.run_refs.clone()),
11209            deltas: TableDeltas {
11210                memtable: self.memtable.clone(),
11211                mutable_run: self.mutable_run.clone(),
11212                hot: self.hot.clone(),
11213                pk_by_row: self.pk_by_row.clone(),
11214            },
11215            indexes: Arc::new(IndexGeneration::capture(
11216                &self.bitmap,
11217                &self.learned_range,
11218                &self.fm,
11219                &self.ann,
11220                &self.sparse,
11221                &self.minhash,
11222                visible_through,
11223                // P0.5-T5: authoritative HLC readiness watermark.
11224                match &self.wal {
11225                    WalSink::Shared(shared) => shared
11226                        .hlc
11227                        .now()
11228                        .unwrap_or(mongreldb_types::hlc::HlcTimestamp::MAX),
11229                    _ => mongreldb_types::hlc::HlcTimestamp::MAX,
11230                },
11231            )),
11232            visible_through,
11233        }
11234    }
11235
11236    /// Seal the active deltas and atomically publish a replacement
11237    /// [`ReadGeneration`] (S1C-001/S1C-002). The publish is a single
11238    /// `ArcSwap` store: readers that pinned the previous `Arc` keep their
11239    /// stable view, new readers see this one. Returns the published view.
11240    pub fn publish_read_generation(&mut self) -> Result<Arc<ReadGeneration>> {
11241        self.ensure_indexes_complete()?;
11242        self.seal_generations();
11243        let view = Arc::new(self.capture_read_generation());
11244        self.published.store(Arc::clone(&view));
11245        Ok(view)
11246    }
11247
11248    /// The most recently published immutable read view. Pinning the returned
11249    /// `Arc` keeps its structurally-shared frozen layers alive. The view is
11250    /// seeded empty at open/create and refreshed by
11251    /// [`Table::publish_read_generation`], [`Table::flush`], and read-
11252    /// generation creation.
11253    pub fn published_read_generation(&self) -> Arc<ReadGeneration> {
11254        self.published.load_full()
11255    }
11256
11257    /// The table's unified version-retention pin registry (S1C-004).
11258    pub fn pin_registry(&self) -> &Arc<crate::retention::PinRegistry> {
11259        &self.pins
11260    }
11261
11262    /// S1C-004: the epoch floor for version reclamation — a version may be
11263    /// reclaimed only when older than every pin source. Equals
11264    /// [`Table::min_active_snapshot`], or the current visible epoch when
11265    /// nothing is pinned (nothing older than the floor can still be needed).
11266    pub fn version_gc_floor(&self) -> Epoch {
11267        self.min_active_snapshot()
11268            .unwrap_or_else(|| self.current_epoch())
11269    }
11270
11271    /// S1C-004 diagnostics: every active version-retention pin source.
11272    /// Registered pins (read generations, and later backup/PITR, replication,
11273    /// online index builds) come from the [`crate::retention::PinRegistry`];
11274    /// the oldest transaction snapshot (local pins plus the shared
11275    /// [`crate::retention::SnapshotRegistry`]) and the configured history
11276    /// window are projected into the report so all six sources are visible.
11277    pub fn version_pins_report(&self) -> crate::retention::PinsReport {
11278        let mut report = self.pins.report();
11279        let transaction_floor = [
11280            self.pinned.keys().next().copied(),
11281            self.snapshots.min_pinned(),
11282        ]
11283        .into_iter()
11284        .flatten()
11285        .min();
11286        if let Some(epoch) = transaction_floor {
11287            report.record_projection(crate::retention::PinSource::TransactionSnapshot, epoch);
11288        }
11289        if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11290            report.record_projection(crate::retention::PinSource::HistoryRetention, floor);
11291        }
11292        report
11293    }
11294
11295    pub(crate) fn clone_read_generation(&mut self) -> Result<Self> {
11296        self.publish_read_generation()?;
11297        let mut generation = self.clone();
11298        generation.read_only = true;
11299        generation.wal = WalSink::ReadOnly;
11300        generation.pending_delete_rids.clear();
11301        generation.pending_put_cols.clear();
11302        generation.pending_rows.clear();
11303        generation.pending_rows_auto_inc.clear();
11304        generation.pending_dels.clear();
11305        generation.pending_truncate = None;
11306        generation.agg_cache = Arc::new(HashMap::new());
11307        // The pinned generation keeps the view published at its birth, not
11308        // the writer's live cell: later publishes must not mutate it.
11309        generation.published = Arc::new(ArcSwap::new(self.published.load_full()));
11310        // S1C-004: the generation pins its birth epoch until it drops, so
11311        // version GC can never reclaim versions it still reads.
11312        generation.read_generation_pin = Some(Arc::new(self.pins.pin(
11313            crate::retention::PinSource::ReadGeneration,
11314            self.current_epoch(),
11315        )));
11316        Ok(generation)
11317    }
11318
11319    pub(crate) fn estimated_clone_bytes(&self) -> u64 {
11320        (std::mem::size_of::<Self>() as u64)
11321            .saturating_add(self.memtable.approx_bytes())
11322            .saturating_add(self.mutable_run.approx_bytes())
11323            .saturating_add(self.live_count.saturating_mul(64))
11324    }
11325
11326    /// Pin the current read snapshot; compaction will preserve the versions it
11327    /// needs until [`Table::unpin_snapshot`] is called.
11328    ///
11329    /// Mounted (shared-WAL) tables pin HLC via [`Snapshot::at_hlc`] so HLC is
11330    /// the cluster-wide authority. Standalone private-WAL tables remain
11331    /// epoch-only until they stamp HLC on commit.
11332    pub fn pin_snapshot(&mut self) -> Snapshot {
11333        let snap = self.snapshot();
11334        *self.pinned.entry(snap.epoch).or_insert(0) += 1;
11335        snap
11336    }
11337
11338    /// Every epoch that pin-aware index rebuild must restore secondary
11339    /// discovery / retrieval for — the full set of reader/retention pins that
11340    /// [`Self::min_active_snapshot`] folds into compaction GC, not just the
11341    /// oldest and not just the standalone `pin_snapshot` map.
11342    ///
11343    /// Sources (union, ascending, deduped):
11344    /// - local `self.pinned` ([`Self::pin_snapshot`])
11345    /// - [`crate::retention::SnapshotRegistry`] live pins (`Database::snapshot`)
11346    /// - [`crate::retention::PinRegistry`] live pins (backup/PITR, replication,
11347    ///   read-generation, online-index-build, …)
11348    /// - history-retention floor when configured
11349    fn active_pin_epochs_for_rebuild(&self) -> Vec<Epoch> {
11350        let mut set = BTreeSet::new();
11351        for epoch in self.pinned.keys().copied() {
11352            set.insert(epoch);
11353        }
11354        for epoch in self.snapshots.live_pinned_epochs() {
11355            set.insert(epoch);
11356        }
11357        for epoch in self.pins.live_pin_epochs() {
11358            set.insert(epoch);
11359        }
11360        if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11361            set.insert(floor);
11362        }
11363        set.into_iter().collect()
11364    }
11365
11366    /// P0.5-T6: report the HLC GC floor as named pin sources.
11367    ///
11368    /// Epoch pins that cannot yet be projected to a durable HLC report
11369    /// [`HlcTimestamp::ZERO`](mongreldb_types::hlc::HlcTimestamp::ZERO). Physical
11370    /// reclamation still consults the epoch floor ([`Self::version_gc_floor`]).
11371    ///
11372    /// `project_epoch` maps a local pin epoch to an HLC (typically
11373    /// [`crate::Database::commit_ts_for_epoch`]); return `None` / `ZERO` when
11374    /// the epoch has no durable stamp.
11375    pub fn hlc_gc_floor(
11376        &self,
11377        mut project_epoch: impl FnMut(Epoch) -> Option<mongreldb_types::hlc::HlcTimestamp>,
11378    ) -> crate::epoch::GcFloor {
11379        let mut project = |epoch: Option<Epoch>| -> mongreldb_types::hlc::HlcTimestamp {
11380            epoch
11381                .and_then(&mut project_epoch)
11382                .filter(|ts| *ts != mongreldb_types::hlc::HlcTimestamp::ZERO)
11383                .unwrap_or(mongreldb_types::hlc::HlcTimestamp::ZERO)
11384        };
11385        let transaction = [
11386            self.pinned.keys().next().copied(),
11387            self.snapshots.min_pinned(),
11388        ]
11389        .into_iter()
11390        .flatten()
11391        .min();
11392        let history = self.snapshots.history_floor(self.current_epoch());
11393        crate::epoch::GcFloor {
11394            transaction_snapshot: project(transaction),
11395            history_retention: project(history),
11396            backup_pitr: project(
11397                self.pins
11398                    .oldest_for(crate::retention::PinSource::BackupPitr),
11399            ),
11400            replication: project(
11401                self.pins
11402                    .oldest_for(crate::retention::PinSource::Replication),
11403            ),
11404            read_generation: project(
11405                self.pins
11406                    .oldest_for(crate::retention::PinSource::ReadGeneration),
11407            ),
11408            online_index_build: project(
11409                self.pins
11410                    .oldest_for(crate::retention::PinSource::OnlineIndexBuild),
11411            ),
11412        }
11413    }
11414
11415    /// Release a pinned snapshot.
11416    pub fn unpin_snapshot(&mut self, snap: Snapshot) {
11417        if let Some(count) = self.pinned.get_mut(&snap.epoch) {
11418            *count -= 1;
11419            if *count == 0 {
11420                self.pinned.remove(&snap.epoch);
11421            }
11422        }
11423    }
11424
11425    /// Oldest pinned snapshot epoch, or `None` if no snapshot is active.
11426    /// Lowest snapshot epoch that compaction must preserve a version for, or
11427    /// `None` when no reader is pinned anywhere. Considers BOTH the single-table
11428    /// local pin set (`self.pinned`, used by the standalone `pin_snapshot` API)
11429    /// AND the shared `Database` snapshot registry (`db.snapshot()` readers) —
11430    /// otherwise a multi-table reader's version could be dropped by a compaction
11431    /// triggered on its table (the registry-gated reaper would then keep the
11432    /// old run *files*, but readers only scan the merged run, so the version
11433    /// would still be lost). Also folds in the unified [`crate::retention::PinRegistry`]
11434    /// (S1C-004): backup/PITR, replication, cursor/read-generation, and
11435    /// online-index-build pins all gate version reclamation here.
11436    pub(crate) fn min_active_snapshot(&self) -> Option<Epoch> {
11437        let local = self.pinned.keys().next().copied();
11438        let global = self.snapshots.min_pinned();
11439        let history = self.snapshots.history_floor(self.current_epoch());
11440        let pinned = self.pins.oldest_pinned();
11441        [local, global, history, pinned].into_iter().flatten().min()
11442    }
11443
11444    /// Configure timestamp-column retention on a standalone table. Mounted
11445    /// databases should use [`crate::Database::set_table_ttl`] so the DDL is
11446    /// WAL-replicated.
11447    pub fn set_ttl(&mut self, column_name: &str, duration_nanos: u64) -> Result<()> {
11448        self.ensure_writable()?;
11449        let policy = self.prepare_ttl_policy(column_name, duration_nanos)?;
11450        self.apply_ttl_policy_at(Some(policy), self.current_epoch())
11451    }
11452
11453    pub fn clear_ttl(&mut self) -> Result<()> {
11454        self.ensure_writable()?;
11455        self.apply_ttl_policy_at(None, self.current_epoch())
11456    }
11457
11458    pub fn ttl(&self) -> Option<TtlPolicy> {
11459        self.ttl
11460    }
11461
11462    pub(crate) fn prepare_ttl_policy(
11463        &self,
11464        column_name: &str,
11465        duration_nanos: u64,
11466    ) -> Result<TtlPolicy> {
11467        if duration_nanos == 0 || duration_nanos > i64::MAX as u64 {
11468            return Err(MongrelError::InvalidArgument(
11469                "TTL duration must be between 1 and i64::MAX nanoseconds".into(),
11470            ));
11471        }
11472        let column = self
11473            .schema
11474            .columns
11475            .iter()
11476            .find(|column| column.name == column_name)
11477            .ok_or_else(|| MongrelError::Schema(format!("unknown TTL column {column_name}")))?;
11478        if column.ty != TypeId::TimestampNanos {
11479            return Err(MongrelError::Schema(format!(
11480                "TTL column {column_name} must be TimestampNanos, is {:?}",
11481                column.ty
11482            )));
11483        }
11484        Ok(TtlPolicy {
11485            column_id: column.id,
11486            duration_nanos,
11487        })
11488    }
11489
11490    pub(crate) fn apply_ttl_policy_at(
11491        &mut self,
11492        policy: Option<TtlPolicy>,
11493        epoch: Epoch,
11494    ) -> Result<()> {
11495        if let Some(policy) = policy {
11496            let column = self
11497                .schema
11498                .columns
11499                .iter()
11500                .find(|column| column.id == policy.column_id)
11501                .ok_or_else(|| {
11502                    MongrelError::Schema(format!("unknown TTL column id {}", policy.column_id))
11503                })?;
11504            if column.ty != TypeId::TimestampNanos
11505                || policy.duration_nanos == 0
11506                || policy.duration_nanos > i64::MAX as u64
11507            {
11508                return Err(MongrelError::Schema("invalid TTL policy".into()));
11509            }
11510        }
11511        self.ttl = policy;
11512        self.agg_cache = Arc::new(HashMap::new());
11513        self.clear_result_cache();
11514        let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
11515        self.persist_manifest(epoch)
11516    }
11517
11518    pub(crate) fn row_expired_at(&self, row: &Row, now_nanos: i64) -> bool {
11519        let Some(policy) = self.ttl else {
11520            return false;
11521        };
11522        let Some(Value::Int64(timestamp)) = row.columns.get(&policy.column_id) else {
11523            return false;
11524        };
11525        timestamp.saturating_add(policy.duration_nanos as i64) <= now_nanos
11526    }
11527
11528    pub fn current_epoch(&self) -> Epoch {
11529        self.epoch.visible()
11530    }
11531
11532    pub fn memtable_len(&self) -> usize {
11533        self.memtable.len()
11534    }
11535
11536    /// Live row count. O(1) without TTL; TTL tables scan because wall-clock
11537    /// expiry can change without a commit epoch.
11538    pub fn count(&self) -> u64 {
11539        if self.ttl.is_none()
11540            && self.pending_put_cols.is_empty()
11541            && self.pending_delete_rids.is_empty()
11542            && self.pending_rows.is_empty()
11543            && self.pending_dels.is_empty()
11544            && self.pending_truncate.is_none()
11545        {
11546            self.live_count
11547        } else {
11548            self.visible_rows(self.snapshot())
11549                .map(|rows| rows.len() as u64)
11550                .unwrap_or(self.live_count)
11551        }
11552    }
11553
11554    /// Count rows matching an index-backed conjunctive predicate without
11555    /// materializing projected columns. Returns `None` when a condition cannot
11556    /// be served by the native predicate resolver.
11557    pub fn count_conditions(
11558        &mut self,
11559        conditions: &[crate::query::Condition],
11560        snapshot: Snapshot,
11561    ) -> Result<Option<u64>> {
11562        use crate::query::Condition;
11563        if self.ttl.is_some() {
11564            if conditions.is_empty() {
11565                return Ok(Some(self.visible_rows(snapshot)?.len() as u64));
11566            }
11567            let mut sets = Vec::with_capacity(conditions.len());
11568            for condition in conditions {
11569                sets.push(self.resolve_condition(condition, snapshot)?);
11570            }
11571            let survivors = RowIdSet::intersect_many(sets);
11572            let rows = self.visible_rows(snapshot)?;
11573            return Ok(Some(
11574                rows.into_iter()
11575                    .filter(|row| survivors.contains(row.row_id.0))
11576                    .count() as u64,
11577            ));
11578        }
11579        if conditions.is_empty() {
11580            return Ok(Some(self.count()));
11581        }
11582        let served = |c: &Condition| {
11583            matches!(
11584                c,
11585                Condition::Pk(_)
11586                    | Condition::BitmapEq { .. }
11587                    | Condition::BitmapIn { .. }
11588                    | Condition::BytesPrefix { .. }
11589                    | Condition::FmContains { .. }
11590                    | Condition::FmContainsAll { .. }
11591                    | Condition::Ann { .. }
11592                    | Condition::Range { .. }
11593                    | Condition::RangeF64 { .. }
11594                    | Condition::SparseMatch { .. }
11595                    | Condition::MinHashSimilar { .. }
11596                    | Condition::IsNull { .. }
11597                    | Condition::IsNotNull { .. }
11598            )
11599        };
11600        if !conditions.iter().all(served) {
11601            return Ok(None);
11602        }
11603        self.ensure_indexes_complete()?;
11604        if !self.pending_put_cols.is_empty()
11605            || !self.pending_delete_rids.is_empty()
11606            || !self.pending_rows.is_empty()
11607            || !self.pending_dels.is_empty()
11608            || self.pending_truncate.is_some()
11609        {
11610            let mut sets = Vec::with_capacity(conditions.len());
11611            for condition in conditions {
11612                sets.push(self.resolve_condition(condition, snapshot)?);
11613            }
11614            let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
11615            return Ok(Some(self.rows_for_rids(&rids, snapshot)?.len() as u64));
11616        }
11617        let mut sets = Vec::with_capacity(conditions.len());
11618        for condition in conditions {
11619            sets.push(self.resolve_condition(condition, snapshot)?);
11620        }
11621        let rids = RowIdSet::intersect_many(sets);
11622        // §5.1: secondary indexes are append-only across pure deletes, so
11623        // tombstoned rids linger under equality keys until a pin-aware rebuild
11624        // / compaction. Materialize paths already filter via MVCC. The count
11625        // path must not trust raw index cardinality whenever deletes have ever
11626        // happened (including after flush/spill emptied the overlay and after
11627        // reopen of a checkpoint that still carries stale memberships).
11628        // `had_deletes` is reconstructed on open from run_count vs live_count.
11629        if self.had_deletes || !self.memtable.is_empty() || !self.mutable_run.is_empty() {
11630            let sorted = rids.into_sorted_vec();
11631            let count = self.rows_for_rids(&sorted, snapshot)?.len() as u64;
11632            crate::trace::QueryTrace::record(|t| {
11633                t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11634                t.survivor_count = Some(count as usize);
11635                t.conditions_pushed = conditions.len();
11636            });
11637            return Ok(Some(count));
11638        }
11639        let count = rids.len() as u64;
11640        crate::trace::QueryTrace::record(|t| {
11641            t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11642            t.survivor_count = Some(count as usize);
11643            t.conditions_pushed = conditions.len();
11644        });
11645        Ok(Some(count))
11646    }
11647
11648    /// Row-ids whose newest visible overlay version is a tombstone. Used to
11649    /// prune stale entries left behind by the append-only in-memory indexes
11650    /// (see point dual-source / overlay merge). Tombstones may also live in
11651    /// sorted runs after flush; callers that need full correctness use
11652    /// materialize (`rows_for_rids`) instead of this overlay-only set. (§5.1)
11653    fn overlay_tombstoned_rids(&self, snapshot: Snapshot) -> Vec<u64> {
11654        let mut out = Vec::new();
11655        for row in self.memtable.visible_versions_at(snapshot) {
11656            if row.deleted {
11657                out.push(row.row_id.0);
11658            }
11659        }
11660        for row in self.mutable_run.visible_versions_at(snapshot) {
11661            if row.deleted {
11662                out.push(row.row_id.0);
11663            }
11664        }
11665        out
11666    }
11667
11668    /// Bulk-load typed columns straight to a new run — the fast ingest path.
11669    /// Bypasses the WAL, the memtable, and the `Value` enum entirely; writes one
11670    /// compressed run (delta for sorted Int64, dictionary for low-card Bytes)
11671    /// with **LZ4** (Phase 15.3 — fast decode for scan-heavy analytical runs),
11672    /// rotates the WAL, and persists the manifest in a single fsync group.
11673    /// Index building follows [`Table::index_build_policy`]: deferred to the
11674    /// first query/flush by default, or bulk-built inline from the typed
11675    /// columns (Phase 14.2) under [`IndexBuildPolicy::Eager`].
11676    pub fn bulk_load_columns(
11677        &mut self,
11678        user_columns: Vec<(u16, columnar::NativeColumn)>,
11679    ) -> Result<Epoch> {
11680        self.bulk_load_columns_with(user_columns, 3, false, true)
11681    }
11682
11683    /// Maximal-throughput bulk ingest (Phase 14.4): skip zstd entirely and write
11684    /// raw `ALGO_PLAIN` pages. ~3–4× the encode throughput of
11685    /// [`Self::bulk_load_columns`] at ~3–4× the on-disk size — the right choice
11686    /// when ingest latency dominates and a background compaction will re-compress
11687    /// later. Indexing, WAL rotation, and the manifest are identical to
11688    /// [`Self::bulk_load_columns`].
11689    pub fn bulk_load_fast(
11690        &mut self,
11691        user_columns: Vec<(u16, columnar::NativeColumn)>,
11692    ) -> Result<Epoch> {
11693        self.bulk_load_columns_with(user_columns, -1, true, false)
11694    }
11695
11696    fn bulk_load_columns_with(
11697        &mut self,
11698        mut user_columns: Vec<(u16, columnar::NativeColumn)>,
11699        zstd_level: i32,
11700        force_plain: bool,
11701        lz4: bool,
11702    ) -> Result<Epoch> {
11703        self.ensure_writable()?;
11704        let n = user_columns.first().map(|(_, c)| c.len()).unwrap_or(0);
11705        if n == 0 {
11706            return Ok(self.current_epoch());
11707        }
11708        let epoch = self.commit_new_epoch()?;
11709        let live_before = self.live_count;
11710        // Spill pending mutable-run data before the Flush marker + WAL rotation.
11711        self.spill_mutable_run(epoch)?;
11712        let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
11713            && self.indexes_complete
11714            && self.run_refs.is_empty()
11715            && self.memtable.is_empty()
11716            && self.mutable_run.is_empty();
11717        // Enforce NOT NULL constraints and primary-key upsert semantics before
11718        // any row id is allocated or bytes hit the run file.
11719        self.fill_auto_inc_native_columns(&mut user_columns, n)?;
11720        self.validate_columns_not_null(&user_columns, n)?;
11721        let winner_idx = self
11722            .bulk_pk_winner_indices(&user_columns, n)
11723            .filter(|idx| idx.len() != n);
11724        let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
11725            match winner_idx.as_deref() {
11726                Some(idx) => {
11727                    let compacted = user_columns
11728                        .iter()
11729                        .map(|(id, c)| (*id, c.gather(idx)))
11730                        .collect();
11731                    (compacted, idx.len())
11732                }
11733                None => (user_columns, n),
11734            };
11735        self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
11736        let first = self.allocator.alloc_range(write_n as u64)?.0;
11737        for rid in first..first + write_n as u64 {
11738            self.reservoir.offer(rid);
11739        }
11740        let run_id = self.alloc_run_id()?;
11741        let path = self.run_path(run_id);
11742        let mut writer =
11743            RunWriter::new(&self.schema, run_id as u128, epoch, 0).with_native_endian();
11744        if force_plain {
11745            writer = writer.with_plain();
11746        } else if lz4 {
11747            // Phase 15.3: bulk-loaded analytical runs are scan-heavy, so encode
11748            // them with LZ4 (3–5× faster decode, ~10% worse ratio than zstd).
11749            writer = writer.with_lz4();
11750        } else {
11751            writer = writer.with_zstd_level(zstd_level);
11752        }
11753        if let Some(kek) = &self.kek {
11754            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
11755        }
11756        let header = match self.create_run_file(run_id)? {
11757            Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
11758            None => writer.write_native(&path, &write_columns, write_n, first)?,
11759        };
11760        self.run_refs.push(RunRef {
11761            run_id: run_id as u128,
11762            level: 0,
11763            epoch_created: epoch.0,
11764            row_count: header.row_count,
11765        });
11766        self.run_row_id_ranges
11767            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
11768        self.live_count = self.live_count.saturating_add(write_n as u64);
11769        if eager_index_build {
11770            let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
11771            self.index_columns_bulk(&write_columns, &row_ids);
11772            self.indexes_complete = true;
11773            self.build_learned_ranges()?;
11774        } else {
11775            // Phase 14.7: defer index building off the ingest critical path for
11776            // non-empty tables where cross-run PK/update semantics must be
11777            // reconstructed from durable state.
11778            self.indexes_complete = false;
11779        }
11780        self.mark_flushed(epoch)?;
11781        self.persist_manifest(epoch)?;
11782        if eager_index_build {
11783            self.checkpoint_indexes(epoch);
11784        }
11785        self.clear_result_cache();
11786        self.data_generation = self.data_generation.wrapping_add(1);
11787        Ok(epoch)
11788    }
11789
11790    /// Bulk-build the live in-memory indexes (HOT/bitmap/FM/sparse) straight
11791    /// from typed columns — the deferred batch-indexing path (Phase 14.2).
11792    ///
11793    /// Replaces the per-row `index_into` loop: no `Row`, no per-row
11794    /// `HashMap<u16, Value>`, no `Value` enum. Index keys are computed directly
11795    /// from the typed buffers via [`columnar::encode_key_native`], tokenized for
11796    /// `ENCRYPTED_INDEXABLE` columns the same way `index_into` on a tokenized
11797    /// row would. FM is appended dirty and rebuilt once on the next query; the
11798    /// others are populated in a single typed pass. Entries are merged into the
11799    /// existing indexes so this is correct under multi-run loads and partial
11800    /// reindexes.
11801    ///
11802    /// `row_ids[i]` is the `RowId` of element `i` of every column. ANN
11803    /// (`IndexKind::Ann`) is intentionally skipped: the native codec carries no
11804    /// embeddings, so an `Embedding` column can never reach this path (a native
11805    /// bulk load of an embedding schema fails at encode). LearnedRange is built
11806    /// separately from the runs by [`Self::build_learned_ranges`].
11807    fn index_columns_bulk(&mut self, columns: &[(u16, columnar::NativeColumn)], row_ids: &[u64]) {
11808        let n = row_ids.len();
11809        if n == 0 {
11810            return;
11811        }
11812        let by_id: std::collections::HashMap<u16, &columnar::NativeColumn> =
11813            columns.iter().map(|(id, c)| (*id, c)).collect();
11814        let ty_of: std::collections::HashMap<u16, TypeId> = self
11815            .schema
11816            .columns
11817            .iter()
11818            .map(|c| (c.id, c.ty.clone()))
11819            .collect();
11820        let pk_id = self.schema.primary_key().map(|c| c.id);
11821
11822        for (i, &rid) in row_ids.iter().enumerate() {
11823            let row_id = RowId(rid);
11824            if let Some(pid) = pk_id {
11825                if let Some(col) = by_id.get(&pid) {
11826                    let ty = ty_of.get(&pid).cloned().unwrap_or(TypeId::Int64);
11827                    if let Some(key) = bulk_index_key(&self.column_keys, pid, ty, col, i) {
11828                        self.insert_hot_pk(key, row_id);
11829                    }
11830                }
11831            }
11832            for idef in &self.schema.indexes {
11833                let Some(col) = by_id.get(&idef.column_id) else {
11834                    continue;
11835                };
11836                let ty = ty_of.get(&idef.column_id).cloned().unwrap_or(TypeId::Int64);
11837                match idef.kind {
11838                    IndexKind::Bitmap => {
11839                        if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
11840                            if let Some(key) =
11841                                bulk_index_key(&self.column_keys, idef.column_id, ty, col, i)
11842                            {
11843                                b.insert(key, row_id);
11844                            }
11845                        }
11846                    }
11847                    IndexKind::FmIndex => {
11848                        if let Some(f) = self.fm.get_mut(&idef.column_id) {
11849                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11850                                f.insert(bytes.to_vec(), row_id);
11851                            }
11852                        }
11853                    }
11854                    IndexKind::Sparse => {
11855                        if let Some(s) = self.sparse.get_mut(&idef.column_id) {
11856                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11857                                if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(bytes) {
11858                                    s.insert(&terms, row_id);
11859                                }
11860                            }
11861                        }
11862                    }
11863                    IndexKind::MinHash => {
11864                        if let Some(mh) = self.minhash.get_mut(&idef.column_id) {
11865                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11866                                let tokens = crate::index::token_hashes_from_bytes(bytes);
11867                                mh.insert(&tokens, row_id);
11868                            }
11869                        }
11870                    }
11871                    _ => {}
11872                }
11873            }
11874        }
11875    }
11876
11877    /// no `Value`). Fast path: empty memtable + single run decodes columns
11878    /// directly and gathers visible indices; falls back to the `Value` path
11879    /// pivoted to native columns otherwise. `projection` (a set of column ids)
11880    /// limits decoding to the requested columns — `None` ⇒ all user columns.
11881    pub fn visible_columns_native(
11882        &self,
11883        snapshot: Snapshot,
11884        projection: Option<&[u16]>,
11885    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11886        self.visible_columns_native_inner(snapshot, projection, None)
11887    }
11888
11889    pub fn visible_columns_native_with_control(
11890        &self,
11891        snapshot: Snapshot,
11892        projection: Option<&[u16]>,
11893        control: &crate::ExecutionControl,
11894    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11895        self.visible_columns_native_inner(snapshot, projection, Some(control))
11896    }
11897
11898    fn visible_columns_native_inner(
11899        &self,
11900        snapshot: Snapshot,
11901        projection: Option<&[u16]>,
11902        control: Option<&crate::ExecutionControl>,
11903    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11904        execution_checkpoint(control, 0)?;
11905        let wanted: Vec<u16> = match projection {
11906            Some(p) => p.to_vec(),
11907            None => self.schema.columns.iter().map(|c| c.id).collect(),
11908        };
11909        if self.ttl.is_none()
11910            && self.memtable.is_empty()
11911            && self.mutable_run.is_empty()
11912            && self.run_refs.len() == 1
11913        {
11914            let rr = self.run_refs[0].clone();
11915            let mut reader = self.open_reader(rr.run_id)?;
11916            let idxs = reader.visible_indices_native_at(snapshot)?;
11917            execution_checkpoint(control, 0)?;
11918            let all_visible = idxs.len() == reader.row_count();
11919            // Phase 15.1: decode every requested column in parallel when the
11920            // reader is mmap-backed. Each column already parallel-decodes its
11921            // own pages, so a wide table saturates the pool via nested rayon
11922            // without oversubscribing (work-stealing handles it). Falls back to
11923            // the sequential `&mut` path when mmap is unavailable.
11924            if reader.has_mmap() && control.is_none() {
11925                use rayon::prelude::*;
11926                // Pre-resolve the requested ids that exist in the schema (don't
11927                // capture `self` inside the rayon closure).
11928                let valid: Vec<u16> = wanted
11929                    .iter()
11930                    .filter(|cid| self.schema.columns.iter().any(|c| c.id == **cid))
11931                    .copied()
11932                    .collect();
11933                // Decode concurrently; `collect` preserves `valid` order.
11934                let decoded: Vec<(u16, columnar::NativeColumn)> = valid
11935                    .par_iter()
11936                    .filter_map(|cid| {
11937                        reader
11938                            .column_native_shared(*cid)
11939                            .ok()
11940                            .map(|col| (*cid, col))
11941                    })
11942                    .collect();
11943                let cols = decoded
11944                    .into_iter()
11945                    .map(|(id, col)| (id, if all_visible { col } else { col.gather(&idxs) }))
11946                    .collect();
11947                return Ok(cols);
11948            }
11949            let mut cols = Vec::with_capacity(wanted.len());
11950            for (index, cid) in wanted.iter().enumerate() {
11951                execution_checkpoint(control, index)?;
11952                let cdef = match self.schema.columns.iter().find(|c| c.id == *cid) {
11953                    Some(c) => c,
11954                    None => continue,
11955                };
11956                let col = reader.column_native(cdef.id)?;
11957                cols.push((cdef.id, if all_visible { col } else { col.gather(&idxs) }));
11958            }
11959            return Ok(cols);
11960        }
11961        let vcols = self.visible_columns(snapshot)?;
11962        execution_checkpoint(control, 0)?;
11963        let want_set: std::collections::HashSet<u16> = wanted.iter().copied().collect();
11964        let out: Vec<(u16, columnar::NativeColumn)> = vcols
11965            .into_iter()
11966            .filter(|(id, _)| want_set.contains(id))
11967            .map(|(id, vals)| {
11968                let ty = self
11969                    .schema
11970                    .columns
11971                    .iter()
11972                    .find(|c| c.id == id)
11973                    .map(|c| c.ty.clone())
11974                    .unwrap_or(TypeId::Bytes);
11975                (id, columnar::values_to_native(ty, &vals))
11976            })
11977            .collect();
11978        Ok(out)
11979    }
11980
11981    pub fn run_count(&self) -> usize {
11982        self.run_refs.len()
11983    }
11984
11985    /// Whether the memtable is empty (no unflushed puts).
11986    pub fn memtable_is_empty(&self) -> bool {
11987        self.memtable.is_empty()
11988    }
11989
11990    /// Cumulative raw-page-cache hit/miss counts (Priority 14: hit visibility).
11991    /// Useful for confirming a repeat scan is served from cache or measuring a
11992    /// query's locality after [`reset_page_cache_stats`](Self::reset_page_cache_stats).
11993    pub fn page_cache_stats(&self) -> crate::cache::CacheStats {
11994        self.page_cache.stats()
11995    }
11996
11997    /// Zero the raw-page-cache hit/miss counters.
11998    pub fn reset_page_cache_stats(&self) {
11999        self.page_cache.reset_stats();
12000    }
12001
12002    /// The run IDs in level order (Phase 15.5: used by the Arrow IPC shadow to
12003    /// key shadow files and detect stale shadows).
12004    pub fn run_ids(&self) -> Vec<u128> {
12005        self.run_refs.iter().map(|r| r.run_id).collect()
12006    }
12007
12008    /// Whether the single run (if exactly one) is clean — i.e. has
12009    /// `RUN_FLAG_CLEAN` set (Phase 15.5: the shadow is zero-copy only for clean
12010    /// runs).
12011    pub fn single_run_is_clean(&self) -> bool {
12012        if self.ttl.is_some() || self.run_refs.len() != 1 {
12013            return false;
12014        }
12015        self.open_reader(self.run_refs[0].run_id)
12016            .map(|r| r.is_clean())
12017            .unwrap_or(false)
12018    }
12019
12020    /// Best-effort resolve of the survivor RowId set for fine-grained cache
12021    /// invalidation (hardening (c)). On the single-run fast path, opens a reader
12022    /// and calls `resolve_survivor_rids`. On the multi-run/memtable path,
12023    /// returns an empty bitmap — conservative (condition_cols still catches
12024    /// column mutations, and deletes are caught by the epoch-free design falling
12025    /// through to the multi-run path which re-resolves).
12026    fn resolve_footprint(
12027        &self,
12028        conditions: &[crate::query::Condition],
12029        snapshot: Snapshot,
12030    ) -> roaring::RoaringBitmap {
12031        if !self.memtable.is_empty() || !self.mutable_run.is_empty() {
12032            return roaring::RoaringBitmap::new();
12033        }
12034        if self.run_refs.is_empty() {
12035            return roaring::RoaringBitmap::new();
12036        }
12037        // Try the single-run fast path.
12038        if self.run_refs.len() == 1 {
12039            if let Ok(mut reader) = self.open_reader(self.run_refs[0].run_id) {
12040                if let Ok(rids) = self.resolve_survivor_rids(conditions, &mut reader, snapshot) {
12041                    return rids.to_roaring_lossy();
12042                }
12043            }
12044        }
12045        roaring::RoaringBitmap::new()
12046    }
12047
12048    /// Phase 19.1 + hardening (c): a cached form of
12049    /// [`Table::query_columns_native`]. The cache key embeds the snapshot epoch
12050    /// so two queries at different pinned snapshots never share an entry;
12051    /// invalidation is fine-grained — a `commit()` drops only entries whose
12052    /// footprint intersects a deleted RowId or whose condition-columns intersect
12053    /// a mutated column. On a miss the underlying `query_columns_native` runs and
12054    /// the result is cached as typed `NativeColumn`s. Returns `None` exactly when
12055    /// the non-cached path would (conditions not pushdown-served). Strictly
12056    /// additive — callers wanting fresh results keep using
12057    /// `query_columns_native`.
12058    pub fn query_columns_native_cached(
12059        &mut self,
12060        conditions: &[crate::query::Condition],
12061        projection: Option<&[u16]>,
12062        snapshot: Snapshot,
12063    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12064        self.query_columns_native_cached_inner(conditions, projection, snapshot, None)
12065    }
12066
12067    pub fn query_columns_native_cached_with_control(
12068        &mut self,
12069        conditions: &[crate::query::Condition],
12070        projection: Option<&[u16]>,
12071        snapshot: Snapshot,
12072        control: &crate::ExecutionControl,
12073    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12074        self.query_columns_native_cached_inner(conditions, projection, snapshot, Some(control))
12075    }
12076
12077    fn query_columns_native_cached_inner(
12078        &mut self,
12079        conditions: &[crate::query::Condition],
12080        projection: Option<&[u16]>,
12081        snapshot: Snapshot,
12082        control: Option<&crate::ExecutionControl>,
12083    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12084        execution_checkpoint(control, 0)?;
12085        // Wall-clock expiry changes without an MVCC epoch, so an epoch-keyed
12086        // result can become stale while sitting in the cache.
12087        if self.ttl.is_some() {
12088            return self.query_columns_native_inner(conditions, projection, snapshot, control);
12089        }
12090        if conditions.is_empty() {
12091            return self.query_columns_native_inner(conditions, projection, snapshot, control);
12092        }
12093        // The snapshot epoch is part of the key so two queries with identical
12094        // conditions/projection but pinned at different snapshots never share a
12095        // cached result (MVCC isolation for the explicit-snapshot API).
12096        let key = crate::query::canonical_query_key(conditions, projection, snapshot.epoch.0);
12097        let identity = PersistentCacheIdentity {
12098            table_id: self.table_id(),
12099            schema_id: self.schema.schema_id,
12100            logical_generation: self.current_epoch().0,
12101        };
12102        if let Some(hit) = self.result_cache.lock().get_columns(key, identity) {
12103            crate::trace::QueryTrace::record(|t| {
12104                t.result_cache_hit = true;
12105                t.scan_mode = crate::trace::ScanMode::NativePushdown;
12106            });
12107            return Ok(Some((*hit).clone()));
12108        }
12109        let res = self.query_columns_native_inner(conditions, projection, snapshot, control)?;
12110        execution_checkpoint(control, 0)?;
12111        if let Some(cols) = &res {
12112            let footprint = self.resolve_footprint(conditions, snapshot);
12113            let condition_cols = crate::query::condition_columns(conditions);
12114            execution_checkpoint(control, 0)?;
12115            let entry = CachedEntry {
12116                data: CachedData::Columns(Arc::new(cols.clone())),
12117                footprint,
12118                condition_cols,
12119            };
12120            // Compute everything we need, then take the lock once. The
12121            // `ResultCache` lock is a non-reentrant `parking_lot::Mutex` so
12122            // `persist_entry` + `insert` must run in the same critical
12123            // section. `persist_entry` enqueues onto the background writer
12124            // or skips publication with a metric — never query-thread I/O.
12125            let mut cache = self.result_cache.lock();
12126            let entry_generation = cache.allocate_persist_generation(key);
12127            let context = PersistContext {
12128                identity,
12129                key,
12130                entry_generation,
12131            };
12132            cache.persist_entry(context, &entry);
12133            cache.insert(key, entry);
12134        }
12135        Ok(res)
12136    }
12137
12138    /// Phase 19.1 + hardening (c): a cached form of [`Table::query`]. The cache key
12139    /// is epoch-independent; invalidation is fine-grained (see
12140    /// [`Table::query_columns_native_cached`]). On a hit returns the cached rows (no
12141    /// re-resolve, no re-decode).
12142    pub fn query_cached(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
12143        if self.ttl.is_some() {
12144            return self.query(q);
12145        }
12146        if q.conditions.is_empty() {
12147            return self.query(q);
12148        }
12149        let key = crate::query::canonical_query_key(&q.conditions, None, 0)
12150            ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
12151            ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
12152        let identity = PersistentCacheIdentity {
12153            table_id: self.table_id(),
12154            schema_id: self.schema.schema_id,
12155            logical_generation: self.current_epoch().0,
12156        };
12157        if let Some(hit) = self.result_cache.lock().get_rows(key, identity) {
12158            crate::trace::QueryTrace::record(|t| {
12159                t.result_cache_hit = true;
12160                t.scan_mode = crate::trace::ScanMode::Materialized;
12161            });
12162            return Ok((*hit).clone());
12163        }
12164        let rows = self.query(q)?;
12165        let footprint = rows.iter().map(|r| r.row_id.0 as u32).collect();
12166        let condition_cols = crate::query::condition_columns(&q.conditions);
12167        let entry = CachedEntry {
12168            data: CachedData::Rows(Arc::new(rows.clone())),
12169            footprint,
12170            condition_cols,
12171        };
12172        // Take the lock once: persist_entry + insert must run atomically
12173        // because `ResultCache` uses a non-reentrant `parking_lot::Mutex`.
12174        // `persist_entry` enqueues onto the background writer or skips
12175        // publication with a metric — never query-thread I/O (REM-D §8.5).
12176        let mut cache = self.result_cache.lock();
12177        let entry_generation = cache.allocate_persist_generation(key);
12178        let context = PersistContext {
12179            identity,
12180            key,
12181            entry_generation,
12182        };
12183        cache.persist_entry(context, &entry);
12184        cache.insert(key, entry);
12185        Ok(rows)
12186    }
12187
12188    // -----------------------------------------------------------------------
12189    // Traced query wrappers (OPTIMIZATIONS.md Priority 0 / 16).
12190    //
12191    // Each `_traced` method runs its underlying query inside a
12192    // [`crate::trace::QueryTrace::capture`] scope and returns the result
12193    // alongside the captured path trace. The trace records which physical path
12194    // served the query (cursor / pushdown / materialized / count-shortcut),
12195    // whether indexes were rebuilt, whether the result cache hit, overlay size,
12196    // survivor count, and the fast row-id map usage. Recording is zero-cost
12197    // when no `_traced` method is on the call stack (the plain methods are
12198    // unchanged).
12199    // -----------------------------------------------------------------------
12200
12201    /// [`Self::query_columns_native`] with a captured [`crate::trace::QueryTrace`].
12202    #[allow(clippy::type_complexity)]
12203    pub fn query_columns_native_traced(
12204        &mut self,
12205        conditions: &[crate::query::Condition],
12206        projection: Option<&[u16]>,
12207        snapshot: Snapshot,
12208    ) -> Result<(
12209        Option<Vec<(u16, columnar::NativeColumn)>>,
12210        crate::trace::QueryTrace,
12211    )> {
12212        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12213            self.query_columns_native(conditions, projection, snapshot)
12214        });
12215        Ok((result?, trace))
12216    }
12217
12218    /// [`Self::query_columns_native_cached`] with a captured
12219    /// [`crate::trace::QueryTrace`] (records result-cache hits too).
12220    #[allow(clippy::type_complexity)]
12221    pub fn query_columns_native_cached_traced(
12222        &mut self,
12223        conditions: &[crate::query::Condition],
12224        projection: Option<&[u16]>,
12225        snapshot: Snapshot,
12226    ) -> Result<(
12227        Option<Vec<(u16, columnar::NativeColumn)>>,
12228        crate::trace::QueryTrace,
12229    )> {
12230        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12231            self.query_columns_native_cached(conditions, projection, snapshot)
12232        });
12233        Ok((result?, trace))
12234    }
12235
12236    /// [`Self::native_page_cursor`] with a captured [`crate::trace::QueryTrace`].
12237    pub fn native_page_cursor_traced(
12238        &self,
12239        snapshot: Snapshot,
12240        projection: Vec<(u16, TypeId)>,
12241        conditions: &[crate::query::Condition],
12242    ) -> Result<(Option<NativePageCursor>, crate::trace::QueryTrace)> {
12243        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12244            self.native_page_cursor(snapshot, projection, conditions)
12245        });
12246        Ok((result?, trace))
12247    }
12248
12249    /// [`Self::native_multi_run_cursor`] with a captured [`crate::trace::QueryTrace`].
12250    pub fn native_multi_run_cursor_traced(
12251        &self,
12252        snapshot: Snapshot,
12253        projection: Vec<(u16, TypeId)>,
12254        conditions: &[crate::query::Condition],
12255    ) -> Result<(
12256        Option<crate::cursor::MultiRunCursor>,
12257        crate::trace::QueryTrace,
12258    )> {
12259        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12260            self.native_multi_run_cursor(snapshot, projection, conditions)
12261        });
12262        Ok((result?, trace))
12263    }
12264
12265    /// [`Self::count_conditions`] with a captured [`crate::trace::QueryTrace`].
12266    pub fn count_conditions_traced(
12267        &mut self,
12268        conditions: &[crate::query::Condition],
12269        snapshot: Snapshot,
12270    ) -> Result<(Option<u64>, crate::trace::QueryTrace)> {
12271        let (result, trace) =
12272            crate::trace::QueryTrace::capture(|| self.count_conditions(conditions, snapshot));
12273        Ok((result?, trace))
12274    }
12275
12276    /// [`Self::query`] with a captured [`crate::trace::QueryTrace`].
12277    pub fn query_traced(
12278        &mut self,
12279        q: &crate::query::Query,
12280    ) -> Result<(Vec<Row>, crate::trace::QueryTrace)> {
12281        let (result, trace) = crate::trace::QueryTrace::capture(|| self.query(q));
12282        Ok((result?, trace))
12283    }
12284
12285    /// Predicate pushdown: resolve `conditions` via indexes to find the matching
12286    /// row-id set, then decode only those rows' columns — not the whole table.
12287    /// Returns `None` if the conditions can't be served by indexes (caller falls
12288    /// back to a full scan). This is the fast path for `WHERE col = 'value'`.
12289    pub fn query_columns_native(
12290        &mut self,
12291        conditions: &[crate::query::Condition],
12292        projection: Option<&[u16]>,
12293        snapshot: Snapshot,
12294    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12295        self.query_columns_native_inner(conditions, projection, snapshot, None)
12296    }
12297
12298    pub fn query_columns_native_with_control(
12299        &mut self,
12300        conditions: &[crate::query::Condition],
12301        projection: Option<&[u16]>,
12302        snapshot: Snapshot,
12303        control: &crate::ExecutionControl,
12304    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12305        self.query_columns_native_inner(conditions, projection, snapshot, Some(control))
12306    }
12307
12308    fn query_columns_native_inner(
12309        &mut self,
12310        conditions: &[crate::query::Condition],
12311        projection: Option<&[u16]>,
12312        snapshot: Snapshot,
12313        control: Option<&crate::ExecutionControl>,
12314    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12315        use crate::query::Condition;
12316        execution_checkpoint(control, 0)?;
12317        // TTL reads use the materialized visibility path so the wall-clock
12318        // cutoff is captured once and applied to every storage tier.
12319        if self.ttl.is_some() {
12320            return Ok(None);
12321        }
12322        if conditions.is_empty() {
12323            return Ok(None);
12324        }
12325        self.ensure_indexes_complete()?;
12326
12327        // Only these conditions are pushdown-served. Range/RangeF64 need a
12328        // column read on the single-run fast path; off it they fall back to a
12329        // visible-rows scan via `resolve_condition` (still correct for any
12330        // layout, just not page-pruned).
12331        let served = |c: &Condition| {
12332            matches!(
12333                c,
12334                Condition::Pk(_)
12335                    | Condition::BitmapEq { .. }
12336                    | Condition::BitmapIn { .. }
12337                    | Condition::BytesPrefix { .. }
12338                    | Condition::FmContains { .. }
12339                    | Condition::FmContainsAll { .. }
12340                    | Condition::Ann { .. }
12341                    | Condition::Range { .. }
12342                    | Condition::RangeF64 { .. }
12343                    | Condition::SparseMatch { .. }
12344                    | Condition::MinHashSimilar { .. }
12345                    | Condition::IsNull { .. }
12346                    | Condition::IsNotNull { .. }
12347            )
12348        };
12349        if !conditions.iter().all(served) {
12350            return Ok(None);
12351        }
12352        let fast_path =
12353            self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
12354        crate::trace::QueryTrace::record(|t| {
12355            t.run_count = self.run_refs.len();
12356            t.memtable_rows = self.memtable.len();
12357            t.mutable_run_rows = self.mutable_run.len();
12358            t.conditions_pushed = conditions.len();
12359            t.learned_range_used = conditions.iter().any(|c| match c {
12360                Condition::Range { column_id, .. } | Condition::RangeF64 { column_id, .. } => {
12361                    self.learned_range.contains_key(column_id)
12362                }
12363                _ => false,
12364            });
12365        });
12366        // Build column list (projected or all user columns) + projection pairs.
12367        let col_ids: Vec<u16> = projection
12368            .map(|p| p.to_vec())
12369            .unwrap_or_else(|| self.schema.columns.iter().map(|c| c.id).collect());
12370        let proj_pairs: Vec<(u16, TypeId)> = col_ids
12371            .iter()
12372            .map(|&cid| {
12373                let ty = self
12374                    .schema
12375                    .columns
12376                    .iter()
12377                    .find(|c| c.id == cid)
12378                    .map(|c| c.ty.clone())
12379                    .unwrap_or(TypeId::Bytes);
12380                (cid, ty)
12381            })
12382            .collect();
12383
12384        // -----------------------------------------------------------------------
12385        // Fast path: single run, empty memtable/mutable-run → resolve survivors,
12386        // binary-search positions, gather only the projected columns from one
12387        // reader. This is the fastest pushdown path (no cursor overhead).
12388        // -----------------------------------------------------------------------
12389        if fast_path {
12390            // A Range/RangeF64 needs a column read *unless* its column has a
12391            // learned (PGM) range index, in which case it's served in-memory.
12392            let needs_column = conditions.iter().any(|c| match c {
12393                Condition::Range { column_id, .. } => !self.learned_range.contains_key(column_id),
12394                Condition::RangeF64 { column_id, .. } => {
12395                    !self.learned_range.contains_key(column_id)
12396                }
12397                _ => false,
12398            });
12399            let mut reader_opt: Option<RunReader> = if needs_column {
12400                Some(self.open_reader(self.run_refs[0].run_id)?)
12401            } else {
12402                None
12403            };
12404            let mut sets: Vec<RowIdSet> = Vec::new();
12405            for (index, c) in conditions.iter().enumerate() {
12406                execution_checkpoint(control, index)?;
12407                let s = match c {
12408                    Condition::Range { column_id, lo, hi }
12409                        if !self.learned_range.contains_key(column_id) =>
12410                    {
12411                        if reader_opt.is_none() {
12412                            reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12413                        }
12414                        reader_opt
12415                            .as_mut()
12416                            .expect("reader opened for range")
12417                            .range_row_id_set_i64(*column_id, *lo, *hi)?
12418                    }
12419                    Condition::RangeF64 {
12420                        column_id,
12421                        lo,
12422                        lo_inclusive,
12423                        hi,
12424                        hi_inclusive,
12425                    } if !self.learned_range.contains_key(column_id) => {
12426                        if reader_opt.is_none() {
12427                            reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12428                        }
12429                        reader_opt
12430                            .as_mut()
12431                            .expect("reader opened for range")
12432                            .range_row_id_set_f64(
12433                                *column_id,
12434                                *lo,
12435                                *lo_inclusive,
12436                                *hi,
12437                                *hi_inclusive,
12438                            )?
12439                    }
12440                    _ => self.resolve_condition(c, snapshot)?,
12441                };
12442                sets.push(s);
12443            }
12444            let candidates = RowIdSet::intersect_many(sets);
12445            crate::trace::QueryTrace::record(|t| {
12446                t.survivor_count = Some(candidates.len());
12447            });
12448            if candidates.is_empty() {
12449                let cols: Vec<(u16, columnar::NativeColumn)> = col_ids
12450                    .iter()
12451                    .map(|&id| {
12452                        (
12453                            id,
12454                            columnar::null_native(
12455                                proj_pairs
12456                                    .iter()
12457                                    .find(|(c, _)| c == &id)
12458                                    .map(|(_, t)| t.clone())
12459                                    .unwrap_or(TypeId::Bytes),
12460                                0,
12461                            ),
12462                        )
12463                    })
12464                    .collect();
12465                return Ok(Some(cols));
12466            }
12467            let mut reader = match reader_opt.take() {
12468                Some(r) => r,
12469                None => self.open_reader(self.run_refs[0].run_id)?,
12470            };
12471            let candidate_ids = candidates.into_sorted_vec();
12472            let (positions, fast_rid) = if let Some(positions) =
12473                reader.positions_for_row_ids_fast(&candidate_ids)
12474            {
12475                (positions, true)
12476            } else {
12477                let col = reader.column_native(crate::sorted_run::SYS_ROW_ID)?;
12478                match col {
12479                    columnar::NativeColumn::Int64 { data, .. } => {
12480                        let mut p = Vec::with_capacity(candidate_ids.len());
12481                        for (index, rid) in candidate_ids.iter().enumerate() {
12482                            execution_checkpoint(control, index)?;
12483                            if let Ok(position) = data.binary_search(&(*rid as i64)) {
12484                                p.push(position);
12485                            }
12486                        }
12487                        p.sort_unstable();
12488                        (p, false)
12489                    }
12490                    _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
12491                }
12492            };
12493            crate::trace::QueryTrace::record(|t| {
12494                t.scan_mode = crate::trace::ScanMode::NativePushdown;
12495                t.fast_row_id_map = fast_rid;
12496            });
12497            let mut cols = Vec::with_capacity(col_ids.len());
12498            for (index, cid) in col_ids.iter().enumerate() {
12499                execution_checkpoint(control, index)?;
12500                let col = reader.column_native(*cid)?;
12501                cols.push((*cid, col.gather(&positions)));
12502            }
12503            return Ok(Some(cols));
12504        }
12505
12506        // -----------------------------------------------------------------------
12507        // Non-fast path (multi-run / non-empty overlay). Route through the
12508        // columnar cursor (OPTIMIZATIONS.md Priority 1 + 4): the cursor builder
12509        // resolves MVCC, predicates, and overlay internally in batch, then
12510        // streams projected columns page-by-page. This avoids the per-rid
12511        // `rows_for_rids` `get_version`-across-all-runs cost that made multi-run
12512        // pushdown ~1000× slower than the single-run fast path.
12513        //
12514        // The cursor handles both single-run-with-overlay (`native_page_cursor`)
12515        // and multi-run (`native_multi_run_cursor`) layouts. The empty-table
12516        // (no runs, memtable-only) edge case falls through to `rows_for_rids`.
12517        // -----------------------------------------------------------------------
12518        if !self.run_refs.is_empty() {
12519            use crate::cursor::{
12520                drain_cursor_to_columns, drain_cursor_to_columns_with_control, Cursor,
12521            };
12522            let remaining: usize;
12523            let mut cursor: Box<dyn crate::cursor::Cursor> = if self.run_refs.len() == 1 {
12524                let c = self
12525                    .native_page_cursor(snapshot, proj_pairs.clone(), conditions)?
12526                    .expect("single-run cursor should build when run_refs.len() == 1");
12527                remaining = c.remaining_rows();
12528                Box::new(c)
12529            } else {
12530                let c = self
12531                    .native_multi_run_cursor(snapshot, proj_pairs.clone(), conditions)?
12532                    .expect("multi-run cursor should build when run_refs.len() >= 1");
12533                remaining = c.remaining_rows();
12534                Box::new(c)
12535            };
12536            crate::trace::QueryTrace::record(|t| {
12537                if t.survivor_count.is_none() {
12538                    t.survivor_count = Some(remaining);
12539                }
12540            });
12541            let cols = match control {
12542                Some(control) => {
12543                    drain_cursor_to_columns_with_control(cursor.as_mut(), &proj_pairs, control)?
12544                }
12545                None => drain_cursor_to_columns(cursor.as_mut(), &proj_pairs)?,
12546            };
12547            return Ok(Some(cols));
12548        }
12549
12550        // Empty-table fallback (no sorted runs, memtable/mutable-run only): the
12551        // cursor builders return `None` for `run_refs.is_empty()`, so resolve
12552        // from overlay indexes and materialize via `rows_for_rids`. This is the
12553        // rare edge case (fresh table with only `put`s, no `flush`/`bulk_load`).
12554        crate::trace::QueryTrace::record(|t| {
12555            t.scan_mode = crate::trace::ScanMode::Materialized;
12556            t.row_materialized = true;
12557        });
12558        let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12559        for (index, c) in conditions.iter().enumerate() {
12560            execution_checkpoint(control, index)?;
12561            sets.push(self.resolve_condition(c, snapshot)?);
12562        }
12563        let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
12564        let rows = self.rows_for_rids(&rids, snapshot)?;
12565        let mut cols: Vec<(u16, columnar::NativeColumn)> = Vec::with_capacity(col_ids.len());
12566        for (index, (cid, ty)) in proj_pairs.iter().enumerate() {
12567            execution_checkpoint(control, index)?;
12568            let vals: Vec<Value> = rows
12569                .iter()
12570                .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
12571                .collect();
12572            cols.push((*cid, columnar::values_to_native(ty.clone(), &vals)));
12573        }
12574        Ok(Some(cols))
12575    }
12576
12577    /// Build a lazy, page-aware [`NativePageCursor`] for the single-run fast
12578    /// path. MVCC visibility and predicate survivor resolution are settled up
12579    /// front (so they see the live indexes under the DB lock); the cursor then
12580    /// owns the reader and decodes only the projected columns of pages that
12581    /// contain survivors, lazily. This is the fused-predicate + page-skip +
12582    /// late-materialization scan.
12583    ///
12584    /// Phase 13.1: the memtable / mutable-run overlay is now handled. Rows with
12585    /// a newer version in the overlay are excluded from the run's page plans
12586    /// (their run version is stale); the overlay rows are pre-materialized and
12587    /// appended as a final batch via [`NativePageCursor::new_with_overlay`].
12588    ///
12589    /// Returns `None` only for multiple sorted runs; the caller falls back to
12590    /// the materialize-then-stream scan for that layout.
12591    pub fn native_page_cursor(
12592        &self,
12593        snapshot: Snapshot,
12594        projection: Vec<(u16, TypeId)>,
12595        conditions: &[crate::query::Condition],
12596    ) -> Result<Option<NativePageCursor>> {
12597        use crate::cursor::build_page_plans;
12598        if self.ttl.is_some() {
12599            return Ok(None);
12600        }
12601        // See `scan_cursor`: incomplete (deferred) indexes cannot resolve
12602        // conditions — signal "can't serve" instead of empty survivor sets.
12603        if !conditions.is_empty() && !self.indexes_complete {
12604            return Ok(None);
12605        }
12606        if self.run_refs.len() != 1 {
12607            return Ok(None);
12608        }
12609        let mut reader = self.open_reader(self.run_refs[0].run_id)?;
12610        let (positions, rids) = reader.visible_positions_with_rids_at(snapshot)?;
12611
12612        // Collect overlay rows from memtable + mutable_run (visible, newest
12613        // version per row). These shadow any stale version in the run.
12614        let overlay_rids: HashSet<u64> = {
12615            let mut s = HashSet::new();
12616            for row in self.memtable.visible_versions_at(snapshot) {
12617                s.insert(row.row_id.0);
12618            }
12619            for row in self.mutable_run.visible_versions_at(snapshot) {
12620                s.insert(row.row_id.0);
12621            }
12622            s
12623        };
12624
12625        // Resolve survivor rids via indexes (covers overlay rows for index-
12626        // served conditions: PK, bitmap, FM, ANN, sparse — all maintained on
12627        // every put).
12628        let survivors = if conditions.is_empty() {
12629            None
12630        } else {
12631            Some(self.resolve_survivor_rids(conditions, &mut reader, snapshot)?)
12632        };
12633
12634        // Exclude overlay rids from the run portion: their version in the run
12635        // is stale (updated/deleted in the overlay) or they don't exist in the
12636        // run (new inserts). When there are conditions, we remove overlay rids
12637        // from the survivor set. When there are no conditions, we synthesize a
12638        // survivor set = (all visible run rids) − (overlay rids) so the stale
12639        // run rows are pruned.
12640        let run_survivors: Option<RowIdSet> = if overlay_rids.is_empty() {
12641            survivors.clone()
12642        } else if let Some(s) = &survivors {
12643            let mut run_set = s.clone();
12644            run_set.remove_many(overlay_rids.iter().copied());
12645            Some(run_set)
12646        } else {
12647            Some(RowIdSet::from_unsorted(
12648                rids.iter()
12649                    .map(|&r| r as u64)
12650                    .filter(|r| !overlay_rids.contains(r))
12651                    .collect(),
12652            ))
12653        };
12654
12655        let overlay_rows = if overlay_rids.is_empty() {
12656            Vec::new()
12657        } else {
12658            let bound = Self::overlay_materialization_bound(conditions, &survivors);
12659            self.overlay_visible_rows(snapshot, bound)
12660        };
12661
12662        // Build page plans for the run portion.
12663        let plans = if positions.is_empty() {
12664            Vec::new()
12665        } else {
12666            let page_rows = reader.page_row_counts(crate::sorted_run::SYS_ROW_ID)?;
12667            build_page_plans(&positions, &rids, &page_rows, run_survivors.as_ref())
12668        };
12669
12670        // Filter and materialize the overlay.
12671        let overlay = if overlay_rows.is_empty() {
12672            None
12673        } else {
12674            let filtered =
12675                self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12676            if filtered.is_empty() {
12677                None
12678            } else {
12679                Some(self.materialize_overlay(&filtered, &projection))
12680            }
12681        };
12682
12683        let overlay_row_count = overlay
12684            .as_ref()
12685            .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12686            .unwrap_or(0);
12687        crate::trace::QueryTrace::record(|t| {
12688            t.scan_mode = crate::trace::ScanMode::NativePageCursor;
12689            t.run_count = self.run_refs.len();
12690            t.memtable_rows = self.memtable.len();
12691            t.mutable_run_rows = self.mutable_run.len();
12692            t.overlay_rows = overlay_row_count;
12693            t.conditions_pushed = conditions.len();
12694            t.pages_decoded = plans
12695                .iter()
12696                .map(|p| p.positions.len())
12697                .sum::<usize>()
12698                .min(1);
12699        });
12700
12701        Ok(Some(NativePageCursor::new_with_overlay(
12702            reader, projection, plans, overlay,
12703        )))
12704    }
12705    /// Generalizes [`Self::native_page_cursor`] (single-run) to arbitrary run
12706    /// counts via a k-way merge by `RowId`. Cross-run MVCC resolution (newest
12707    /// visible version per `RowId`) and predicate survivor resolution are settled
12708    /// up front from the cheap system columns + global indexes; the cursor then
12709    /// lazily decodes the projected data columns of just the pages that own
12710    /// survivors, each page at most once. The memtable / mutable-run overlay is
12711    /// materialized and yielded as a final batch (mirroring the single-run path).
12712    ///
12713    /// Returns `None` only when there are no runs at all (caller falls back).
12714    #[allow(clippy::type_complexity)]
12715    pub fn native_multi_run_cursor(
12716        &self,
12717        snapshot: Snapshot,
12718        projection: Vec<(u16, TypeId)>,
12719        conditions: &[crate::query::Condition],
12720    ) -> Result<Option<crate::cursor::MultiRunCursor>> {
12721        use crate::cursor::{MultiRunCursor, RunStream};
12722        use crate::sorted_run::SYS_ROW_ID;
12723        use std::collections::{BinaryHeap, HashMap, HashSet};
12724        if self.ttl.is_some() {
12725            return Ok(None);
12726        }
12727        // See `scan_cursor`: incomplete (deferred) indexes cannot resolve
12728        // conditions — signal "can't serve" instead of empty survivor sets.
12729        if !conditions.is_empty() && !self.indexes_complete {
12730            return Ok(None);
12731        }
12732        if self.run_refs.is_empty() {
12733            return Ok(None);
12734        }
12735
12736        // Open each run once; read its system columns + page layout.
12737        let mut run_meta: Vec<(
12738            RunReader,
12739            Vec<i64>,
12740            Vec<i64>,
12741            Vec<u8>,
12742            Option<Vec<Option<HlcTimestamp>>>,
12743            Vec<usize>,
12744        )> = Vec::with_capacity(self.run_refs.len());
12745        for rr in &self.run_refs {
12746            let mut reader = self.open_reader(rr.run_id)?;
12747            let (rids, eps, del) = reader.system_columns_native()?;
12748            let page_rows = reader.page_row_counts(SYS_ROW_ID)?;
12749            let commit_ts: Option<Vec<Option<HlcTimestamp>>> =
12750                if reader.has_column(crate::sorted_run::SYS_COMMIT_TS) {
12751                    let col = reader.column_native(crate::sorted_run::SYS_COMMIT_TS)?;
12752                    Some(
12753                        (0..rids.len())
12754                            .map(|i| {
12755                                crate::sorted_run::decode_commit_ts_value(col.value_at(i).as_ref())
12756                            })
12757                            .collect(),
12758                    )
12759                } else {
12760                    None
12761                };
12762            run_meta.push((reader, rids, eps, del, commit_ts, page_rows));
12763        }
12764
12765        // Global cross-run newest-version resolution: rid -> (epoch, run_idx,
12766        // position, deleted). Mirrors `visible_rows`, tracking which run owns
12767        // the newest MVCC-visible version. HLC stamps participate via
12768        // `Snapshot::observes_row` and `version_is_newer` so an HLC-pinned
12769        // snapshot surfaces the HLC-newer winner regardless of local epoch.
12770        let mut best: HashMap<u64, (Epoch, Option<HlcTimestamp>, usize, usize, bool)> =
12771            HashMap::new();
12772        for (run_idx, (_, rids, eps, del, commit_ts, _)) in run_meta.iter().enumerate() {
12773            for i in 0..rids.len() {
12774                let rid = rids[i] as u64;
12775                let e = Epoch(eps[i] as u64);
12776                let ts = commit_ts.as_ref().and_then(|v| v.get(i).copied().flatten());
12777                if !snapshot.observes_row(e, ts) {
12778                    continue;
12779                }
12780                let is_del = del[i] != 0;
12781                best.entry(rid)
12782                    .and_modify(|cur| {
12783                        if Snapshot::version_is_newer(e, ts, cur.0, cur.1) {
12784                            *cur = (e, ts, run_idx, i, is_del);
12785                        }
12786                    })
12787                    .or_insert((e, ts, run_idx, i, is_del));
12788            }
12789        }
12790
12791        // Overlay rids (memtable + mutable-run) shadow every run version.
12792        let overlay_rids: HashSet<u64> = {
12793            let mut s = HashSet::new();
12794            for row in self.memtable.visible_versions_at(snapshot) {
12795                s.insert(row.row_id.0);
12796            }
12797            for row in self.mutable_run.visible_versions_at(snapshot) {
12798                s.insert(row.row_id.0);
12799            }
12800            s
12801        };
12802
12803        // Predicate survivors (global, layout-independent).
12804        let survivors: Option<RowIdSet> = if conditions.is_empty() {
12805            None
12806        } else {
12807            let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12808            for c in conditions {
12809                sets.push(self.resolve_condition(c, snapshot)?);
12810            }
12811            Some(RowIdSet::intersect_many(sets))
12812        };
12813
12814        // Per-run owned survivors: (rid, position), ascending by rid. A row is
12815        // owned by the run holding its newest visible version, is not deleted,
12816        // is not shadowed by the overlay, and satisfies the predicate.
12817        let mut per_run: Vec<Vec<(u64, usize)>> = vec![Vec::new(); run_meta.len()];
12818        for (rid, (_, _, run_idx, pos, deleted)) in &best {
12819            if *deleted {
12820                continue;
12821            }
12822            if overlay_rids.contains(rid) {
12823                continue;
12824            }
12825            if let Some(s) = &survivors {
12826                if !s.contains(*rid) {
12827                    continue;
12828                }
12829            }
12830            per_run[*run_idx].push((*rid, *pos));
12831        }
12832        for v in per_run.iter_mut() {
12833            v.sort_unstable_by_key(|&(rid, _)| rid);
12834        }
12835
12836        // Build the merge streams: map each owned position to (page_seq, within).
12837        let mut streams = Vec::with_capacity(run_meta.len());
12838        let mut heap: BinaryHeap<std::cmp::Reverse<(u64, usize)>> = BinaryHeap::new();
12839        let mut total = 0usize;
12840        for (run_idx, (reader, _, _, _, _, page_rows)) in run_meta.into_iter().enumerate() {
12841            let mut starts = Vec::with_capacity(page_rows.len());
12842            let mut acc = 0usize;
12843            for &r in &page_rows {
12844                starts.push(acc);
12845                acc += r;
12846            }
12847            let mut survivors_vec: Vec<(u64, usize, usize)> =
12848                Vec::with_capacity(per_run[run_idx].len());
12849            for &(rid, pos) in &per_run[run_idx] {
12850                let page_seq = match starts.partition_point(|&s| s <= pos) {
12851                    0 => continue,
12852                    p => p - 1,
12853                };
12854                let within = pos - starts[page_seq];
12855                survivors_vec.push((rid, page_seq, within));
12856            }
12857            total += survivors_vec.len();
12858            if let Some(&(rid, _, _)) = survivors_vec.first() {
12859                heap.push(std::cmp::Reverse((rid, run_idx)));
12860            }
12861            streams.push(RunStream::new(reader, survivors_vec, page_rows));
12862        }
12863
12864        // Materialize the overlay (filtered + projected), yielded as the final batch.
12865        let overlay_rows = if overlay_rids.is_empty() {
12866            Vec::new()
12867        } else {
12868            let bound = Self::overlay_materialization_bound(conditions, &survivors);
12869            self.overlay_visible_rows(snapshot, bound)
12870        };
12871        let overlay = if overlay_rows.is_empty() {
12872            None
12873        } else {
12874            let filtered =
12875                self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12876            if filtered.is_empty() {
12877                None
12878            } else {
12879                Some(self.materialize_overlay(&filtered, &projection))
12880            }
12881        };
12882
12883        let overlay_row_count = overlay
12884            .as_ref()
12885            .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12886            .unwrap_or(0);
12887        crate::trace::QueryTrace::record(|t| {
12888            t.scan_mode = crate::trace::ScanMode::MultiRunCursor;
12889            t.run_count = self.run_refs.len();
12890            t.memtable_rows = self.memtable.len();
12891            t.mutable_run_rows = self.mutable_run.len();
12892            t.overlay_rows = overlay_row_count;
12893            t.conditions_pushed = conditions.len();
12894            t.survivor_count = Some(total);
12895        });
12896
12897        Ok(Some(MultiRunCursor::new(
12898            streams, projection, heap, total, overlay,
12899        )))
12900    }
12901
12902    /// Collect visible, non-deleted overlay rows from the memtable and mutable-
12903    /// run tier at `snapshot`. These are the rows whose data lives only in the
12904    /// in-memory buffers (not yet in a sorted run), or that shadow a stale
12905    /// version in the run.
12906    /// The survivor set that bounds overlay materialization (Priority 2), or
12907    /// `None` when overlay rows must be fully materialized — i.e. there is a
12908    /// `Range`/`RangeF64` residual, for which the index-served survivor set does
12909    /// not cover matching overlay rows (those are evaluated downstream). This
12910    /// mirrors the `all_index_served` branch of
12911    /// [`filter_overlay_rows`](Self::filter_overlay_rows), so bounding here is
12912    /// result-preserving.
12913    fn overlay_materialization_bound<'a>(
12914        conditions: &[crate::query::Condition],
12915        survivors: &'a Option<RowIdSet>,
12916    ) -> Option<&'a RowIdSet> {
12917        use crate::query::Condition;
12918        let has_range = conditions
12919            .iter()
12920            .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12921        if has_range {
12922            None
12923        } else {
12924            survivors.as_ref()
12925        }
12926    }
12927
12928    /// Materialize the visible overlay rows (memtable + mutable-run, newest
12929    /// version per row, non-deleted).
12930    ///
12931    /// Priority 2 (selective overlay probing): when `bound` is `Some`, only rows
12932    /// whose id is in it are materialized. The caller passes the index-resolved
12933    /// survivor set as `bound` exactly when every condition is index-served — in
12934    /// which case [`filter_overlay_rows`](Self::filter_overlay_rows) would discard
12935    /// any non-survivor overlay row anyway, so this prunes the materialization
12936    /// without changing the result. With a Range/RangeF64 residual the survivor
12937    /// set is incomplete for overlay rows, so the caller passes `None` (full
12938    /// materialization) and the range is re-evaluated downstream.
12939    fn overlay_visible_rows(&self, snapshot: Snapshot, bound: Option<&RowIdSet>) -> Vec<Row> {
12940        let mut best: HashMap<u64, (Epoch, Row)> = HashMap::new();
12941        let mut fold = |row: Row| {
12942            if let Some(b) = bound {
12943                if !b.contains(row.row_id.0) {
12944                    return;
12945                }
12946            }
12947            best.entry(row.row_id.0)
12948                .and_modify(|(be, br)| {
12949                    if row.committed_epoch > *be {
12950                        *be = row.committed_epoch;
12951                        *br = row.clone();
12952                    }
12953                })
12954                .or_insert_with(|| (row.committed_epoch, row));
12955        };
12956        for row in self.memtable.visible_versions_at(snapshot) {
12957            fold(row);
12958        }
12959        for row in self.mutable_run.visible_versions_at(snapshot) {
12960            fold(row);
12961        }
12962        let mut out: Vec<Row> = best
12963            .into_values()
12964            .filter_map(|(_, r)| if r.deleted { None } else { Some(r) })
12965            .collect();
12966        out.sort_by_key(|r| r.row_id);
12967        out
12968    }
12969
12970    /// Filter overlay rows against the conjunctive predicate. Range / RangeF64
12971    /// are evaluated directly (the reader-served survivor set misses overlay
12972    /// rows). All other conditions are index-served (indexes maintained on
12973    /// every `put`) so the intersected `survivors` set includes overlay rows
12974    /// that match — but ONLY when every condition is index-served. When there
12975    /// is a mix, we compute per-condition index sets for non-range conditions
12976    /// and evaluate range conditions directly, so the intersection is correct.
12977    fn filter_overlay_rows(
12978        &self,
12979        rows: Vec<Row>,
12980        conditions: &[crate::query::Condition],
12981        survivors: Option<&RowIdSet>,
12982        snapshot: Snapshot,
12983    ) -> Result<Vec<Row>> {
12984        if conditions.is_empty() {
12985            return Ok(rows);
12986        }
12987        use crate::query::Condition;
12988        // Determine whether every condition is index-served (survivors set is
12989        // then complete for overlay rows). If so, a simple membership check
12990        // suffices and is cheapest.
12991        let all_index_served = !conditions
12992            .iter()
12993            .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12994        if all_index_served {
12995            return Ok(rows
12996                .into_iter()
12997                .filter(|r| survivors.is_none_or(|s| s.contains(r.row_id.0)))
12998                .collect());
12999        }
13000        // Mixed: compute per-condition index sets for non-range conditions, and
13001        // evaluate range conditions directly on column values.
13002        let mut per_cond_sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
13003        for c in conditions {
13004            let s = match c {
13005                Condition::Range { .. } | Condition::RangeF64 { .. } => RowIdSet::empty(),
13006                _ => self.resolve_condition(c, snapshot)?,
13007            };
13008            per_cond_sets.push(s);
13009        }
13010        Ok(rows
13011            .into_iter()
13012            .filter(|row| {
13013                conditions.iter().enumerate().all(|(i, c)| match c {
13014                    Condition::Range { column_id, lo, hi } => {
13015                        matches!(row.columns.get(column_id), Some(Value::Int64(v)) if *v >= *lo && *v <= *hi)
13016                    }
13017                    Condition::RangeF64 { column_id, lo, lo_inclusive, hi, hi_inclusive } => {
13018                        match row.columns.get(column_id) {
13019                            Some(Value::Float64(v)) => {
13020                                let lo_ok = if *lo_inclusive { *v >= *lo } else { *v > *lo };
13021                                let hi_ok = if *hi_inclusive { *v <= *hi } else { *v < *hi };
13022                                lo_ok && hi_ok
13023                            }
13024                            _ => false,
13025                        }
13026                    }
13027                    _ => per_cond_sets[i].contains(row.row_id.0),
13028                })
13029            })
13030            .collect())
13031    }
13032
13033    /// Materialize overlay rows into typed `NativeColumn`s for the cursor's
13034    /// final batch.
13035    fn materialize_overlay(
13036        &self,
13037        rows: &[Row],
13038        projection: &[(u16, TypeId)],
13039    ) -> Vec<columnar::NativeColumn> {
13040        if projection.is_empty() {
13041            return vec![columnar::null_native(TypeId::Int64, rows.len())];
13042        }
13043        let mut cols = Vec::with_capacity(projection.len());
13044        for (cid, ty) in projection {
13045            let vals: Vec<Value> = rows
13046                .iter()
13047                .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
13048                .collect();
13049            cols.push(columnar::values_to_native(ty.clone(), &vals));
13050        }
13051        cols
13052    }
13053
13054    /// Resolve a conjunctive predicate to its surviving `RowId` set on the
13055    /// single-run fast path: each condition becomes a `RowId` set via the
13056    /// in-memory indexes or the reader's page-pruned range scan, then they are
13057    /// intersected. Mirrors the resolution inside [`Self::query_columns_native`].
13058    fn resolve_survivor_rids(
13059        &self,
13060        conditions: &[crate::query::Condition],
13061        reader: &mut RunReader,
13062        snapshot: Snapshot,
13063    ) -> Result<RowIdSet> {
13064        use crate::query::Condition;
13065        let mut sets: Vec<RowIdSet> = Vec::new();
13066        for c in conditions {
13067            self.validate_condition(c)?;
13068            let s: RowIdSet = match c {
13069                Condition::Pk(key) => {
13070                    let lookup = self
13071                        .schema
13072                        .primary_key()
13073                        .map(|pk| self.index_lookup_key_bytes(pk.id, key))
13074                        .unwrap_or_else(|| key.clone());
13075                    self.hot
13076                        .get(&lookup)
13077                        .map(|r| RowIdSet::one(r.0))
13078                        .unwrap_or_else(RowIdSet::empty)
13079                }
13080                Condition::BitmapEq { column_id, value } => {
13081                    let lookup = self.index_lookup_key_bytes(*column_id, value);
13082                    self.bitmap
13083                        .get(column_id)
13084                        .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
13085                        .unwrap_or_else(RowIdSet::empty)
13086                }
13087                Condition::BitmapIn { column_id, values } => {
13088                    let bm = self.bitmap.get(column_id);
13089                    let mut acc = roaring::RoaringBitmap::new();
13090                    if let Some(b) = bm {
13091                        for v in values {
13092                            let lookup = self.index_lookup_key_bytes(*column_id, v);
13093                            acc |= b.get(&lookup);
13094                        }
13095                    }
13096                    RowIdSet::from_roaring(acc)
13097                }
13098                Condition::BytesPrefix { column_id, prefix } => {
13099                    if let Some(b) = self.bitmap.get(column_id) {
13100                        let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
13101                        let mut acc = roaring::RoaringBitmap::new();
13102                        for key in b.keys() {
13103                            if key.starts_with(&lookup_prefix) {
13104                                acc |= b.get(&key);
13105                            }
13106                        }
13107                        RowIdSet::from_roaring(acc)
13108                    } else {
13109                        RowIdSet::empty()
13110                    }
13111                }
13112                Condition::FmContains { column_id, pattern } => self
13113                    .fm
13114                    .get(column_id)
13115                    .map(|f| {
13116                        RowIdSet::from_unsorted(
13117                            f.locate(pattern).into_iter().map(|r| r.0).collect(),
13118                        )
13119                    })
13120                    .unwrap_or_else(RowIdSet::empty),
13121                Condition::FmContainsAll {
13122                    column_id,
13123                    patterns,
13124                } => {
13125                    if let Some(f) = self.fm.get(column_id) {
13126                        let sets: Vec<RowIdSet> = patterns
13127                            .iter()
13128                            .map(|pat| {
13129                                RowIdSet::from_unsorted(
13130                                    f.locate(pat).into_iter().map(|r| r.0).collect(),
13131                                )
13132                            })
13133                            .collect();
13134                        RowIdSet::intersect_many(sets)
13135                    } else {
13136                        RowIdSet::empty()
13137                    }
13138                }
13139                Condition::Ann {
13140                    column_id,
13141                    query,
13142                    k,
13143                } => RowIdSet::from_unsorted(
13144                    self.retrieve_filtered(
13145                        &crate::query::Retriever::Ann {
13146                            column_id: *column_id,
13147                            query: query.clone(),
13148                            k: *k,
13149                        },
13150                        snapshot,
13151                        None,
13152                        None,
13153                        None,
13154                        None,
13155                    )?
13156                    .into_iter()
13157                    .map(|hit| hit.row_id.0)
13158                    .collect(),
13159                ),
13160                Condition::SparseMatch {
13161                    column_id,
13162                    query,
13163                    k,
13164                } => RowIdSet::from_unsorted(
13165                    self.retrieve_filtered(
13166                        &crate::query::Retriever::Sparse {
13167                            column_id: *column_id,
13168                            query: query.clone(),
13169                            k: *k,
13170                        },
13171                        snapshot,
13172                        None,
13173                        None,
13174                        None,
13175                        None,
13176                    )?
13177                    .into_iter()
13178                    .map(|hit| hit.row_id.0)
13179                    .collect(),
13180                ),
13181                Condition::MinHashSimilar {
13182                    column_id,
13183                    query,
13184                    k,
13185                } => match self.minhash.get(column_id) {
13186                    Some(index) => {
13187                        let candidates = index.candidate_row_ids(query);
13188                        let eligible =
13189                            self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
13190                        RowIdSet::from_unsorted(
13191                            index
13192                                .search_filtered(query, *k, |row_id| eligible.contains(&row_id))
13193                                .into_iter()
13194                                .map(|(row_id, _)| row_id.0)
13195                                .collect(),
13196                        )
13197                    }
13198                    None => RowIdSet::empty(),
13199                },
13200                Condition::Range { column_id, lo, hi } => {
13201                    if let Some(li) = self.learned_range.get(column_id) {
13202                        RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
13203                    } else {
13204                        reader.range_row_id_set_i64(*column_id, *lo, *hi)?
13205                    }
13206                }
13207                Condition::RangeF64 {
13208                    column_id,
13209                    lo,
13210                    lo_inclusive,
13211                    hi,
13212                    hi_inclusive,
13213                } => {
13214                    if let Some(li) = self.learned_range.get(column_id) {
13215                        RowIdSet::from_unsorted(
13216                            li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
13217                                .into_iter()
13218                                .collect(),
13219                        )
13220                    } else {
13221                        reader.range_row_id_set_f64(
13222                            *column_id,
13223                            *lo,
13224                            *lo_inclusive,
13225                            *hi,
13226                            *hi_inclusive,
13227                        )?
13228                    }
13229                }
13230                Condition::IsNull { column_id } => reader.null_row_id_set(*column_id, true)?,
13231                Condition::IsNotNull { column_id } => reader.null_row_id_set(*column_id, false)?,
13232            };
13233            sets.push(s);
13234        }
13235        Ok(RowIdSet::intersect_many(sets))
13236    }
13237
13238    /// Native vectorized aggregate over a (possibly filtered) column on the
13239    /// single-run fast path (Phase 7.2). Resolves survivors via the same
13240    /// page-pruned cursor as the scan, then accumulates the aggregate in one
13241    /// pass over the typed buffer — no `Value`, no Arrow `RecordBatch`.
13242    ///
13243    /// `column` is `None` for `COUNT(*)`. Returns `Ok(None)` when the fast path
13244    /// does not apply (multi-run / non-empty memtable); the caller scans.
13245    /// Open the streaming [`Cursor`](crate::cursor::Cursor) matching the current
13246    /// run layout: the single-run page cursor when there is exactly one sorted
13247    /// run, otherwise the multi-run k-way merge cursor. Both fuse the predicate,
13248    /// skip non-surviving pages, and fold the memtable / mutable-run overlay, so
13249    /// callers stay columnar end-to-end and never materialize `Row`s. Returns
13250    /// `None` when no cursor applies (e.g. an overlay-only table with no sorted
13251    /// run), leaving the caller to fall back.
13252    ///
13253    /// This is the single source of truth for layout-aware cursor selection,
13254    /// shared by the column scan ([`Self::query_columns_native`] / the SQL
13255    /// provider) and the aggregate path ([`Self::aggregate_native`]). New
13256    /// streaming consumers should build on this rather than re-deciding the
13257    /// cursor by run count.
13258    pub fn scan_cursor(
13259        &self,
13260        snapshot: Snapshot,
13261        projection: Vec<(u16, TypeId)>,
13262        conditions: &[crate::query::Condition],
13263    ) -> Result<Option<Box<dyn crate::cursor::Cursor>>> {
13264        if self.ttl.is_some() {
13265            return Ok(None);
13266        }
13267        // A deferred bulk load leaves the live indexes unbuilt; resolving
13268        // conditions against them would return silently-empty survivor sets.
13269        // Signal "can't serve" so the caller falls back to a `&mut` path that
13270        // runs `ensure_indexes_complete`. (Condition-free scans don't touch
13271        // the indexes and stay served.)
13272        if !conditions.is_empty() && !self.indexes_complete {
13273            return Ok(None);
13274        }
13275        if self.run_refs.len() == 1 {
13276            Ok(self
13277                .native_page_cursor(snapshot, projection, conditions)?
13278                .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13279        } else {
13280            Ok(self
13281                .native_multi_run_cursor(snapshot, projection, conditions)?
13282                .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13283        }
13284    }
13285
13286    /// Native vectorized aggregate over a (possibly filtered) column, in one
13287    /// pass over the typed buffers — no `Value`, no Arrow batch. Layout-agnostic:
13288    /// survivors stream through [`Self::scan_cursor`] (single- or multi-run,
13289    /// overlay-folded), so the same path serves every sorted-run layout.
13290    ///
13291    /// `column` is `None` for `COUNT(*)`. Order of attempts:
13292    /// 1. Single clean run + no `WHERE` ⇒ `MIN`/`MAX`/`COUNT(col)` straight from
13293    ///    page `min`/`max`/`null_count` (no decode).
13294    /// 2. `COUNT(*)` ⇒ survivor cardinality from the cursor's page plans.
13295    /// 3. Otherwise accumulate the projected column over the cursor.
13296    ///
13297    /// Returns `Ok(None)` (caller scans) when no native path applies: an
13298    /// overlay-only table with no sorted run, or a non-numeric column.
13299    pub fn aggregate_native(
13300        &self,
13301        snapshot: Snapshot,
13302        column: Option<u16>,
13303        conditions: &[crate::query::Condition],
13304        agg: NativeAgg,
13305    ) -> Result<Option<NativeAggResult>> {
13306        self.aggregate_native_inner(snapshot, column, conditions, agg, None)
13307    }
13308
13309    pub fn aggregate_native_with_control(
13310        &self,
13311        snapshot: Snapshot,
13312        column: Option<u16>,
13313        conditions: &[crate::query::Condition],
13314        agg: NativeAgg,
13315        control: &crate::ExecutionControl,
13316    ) -> Result<Option<NativeAggResult>> {
13317        self.aggregate_native_inner(snapshot, column, conditions, agg, Some(control))
13318    }
13319
13320    fn aggregate_native_inner(
13321        &self,
13322        snapshot: Snapshot,
13323        column: Option<u16>,
13324        conditions: &[crate::query::Condition],
13325        agg: NativeAgg,
13326        control: Option<&crate::ExecutionControl>,
13327    ) -> Result<Option<NativeAggResult>> {
13328        execution_checkpoint(control, 0)?;
13329        if self.ttl.is_some() {
13330            return Ok(None);
13331        }
13332        // 1. Single clean run + no WHERE ⇒ MIN/MAX/COUNT(col) from page stats.
13333        if self.run_refs.len() == 1 && conditions.is_empty() {
13334            if let Some(res) = self.aggregate_from_stats(snapshot, column, agg)? {
13335                return Ok(Some(res));
13336            }
13337        }
13338        // 2. COUNT(*) ⇒ survivor count from the cursor's page plans, no decode.
13339        //    Overlay-only replicas (no sorted run yet) fall through to a
13340        //    visible-row scan so aggregate_native still serves correctly.
13341        if matches!(agg, NativeAgg::Count) && column.is_none() {
13342            if let Some(c) = self.scan_cursor(snapshot, Vec::new(), conditions)? {
13343                return Ok(Some(NativeAggResult::Count(c.remaining_rows() as u64)));
13344            }
13345            let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13346            return Ok(Some(NativeAggResult::Count(rows.len() as u64)));
13347        }
13348        // 3. Accumulate the projected column. COUNT(col) excludes nulls — the
13349        //    accumulator's count is the non-null count, which `pack_*` returns.
13350        let cid = match column {
13351            Some(c) => c,
13352            None => return Ok(None),
13353        };
13354        let ty = self.column_type(cid);
13355        if let Some(mut cursor) = self.scan_cursor(snapshot, vec![(cid, ty.clone())], conditions)? {
13356            execution_checkpoint(control, 0)?;
13357            return match ty {
13358                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13359                    let (count, sum, mn, mx) = accumulate_int(cursor.as_mut(), control)?;
13360                    Ok(Some(pack_int(agg, count, sum, mn, mx)))
13361                }
13362                TypeId::Float64 => {
13363                    let (count, sum, mn, mx) = accumulate_float(cursor.as_mut(), control)?;
13364                    Ok(Some(pack_float(agg, count, sum, mn, mx)))
13365                }
13366                _ => Ok(None),
13367            };
13368        }
13369        // Overlay-only / replica path: fold over visible rows in memory.
13370        let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13371        execution_checkpoint(control, 0)?;
13372        match ty {
13373            TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13374                let mut count = 0u64;
13375                let mut sum = 0i128;
13376                let mut mn = i64::MAX;
13377                let mut mx = i64::MIN;
13378                for row in &rows {
13379                    if let Some(Value::Int64(v)) = row.columns.get(&cid) {
13380                        count += 1;
13381                        sum += i128::from(*v);
13382                        mn = mn.min(*v);
13383                        mx = mx.max(*v);
13384                    }
13385                }
13386                Ok(Some(pack_int(agg, count, sum, mn, mx)))
13387            }
13388            TypeId::Float64 => {
13389                let mut count = 0u64;
13390                let mut sum = 0.0f64;
13391                let mut mn = f64::INFINITY;
13392                let mut mx = f64::NEG_INFINITY;
13393                for row in &rows {
13394                    if let Some(Value::Float64(v)) = row.columns.get(&cid) {
13395                        count += 1;
13396                        sum += *v;
13397                        mn = mn.min(*v);
13398                        mx = mx.max(*v);
13399                    }
13400                }
13401                Ok(Some(pack_float(agg, count, sum, mn, mx)))
13402            }
13403            _ => Ok(None),
13404        }
13405    }
13406
13407    /// Visible rows matching `conditions`, for overlay-only aggregate fallbacks.
13408    fn visible_rows_filtered(
13409        &self,
13410        snapshot: Snapshot,
13411        conditions: &[crate::query::Condition],
13412        control: Option<&crate::ExecutionControl>,
13413    ) -> Result<Vec<Row>> {
13414        let rows = if let Some(control) = control {
13415            self.visible_rows_controlled(snapshot, control)?
13416        } else {
13417            self.visible_rows(snapshot)?
13418        };
13419        if conditions.is_empty() {
13420            return Ok(rows);
13421        }
13422        Ok(rows
13423            .into_iter()
13424            .filter(|row| {
13425                conditions
13426                    .iter()
13427                    .all(|cond| condition_matches_row(cond, row, &self.schema))
13428            })
13429            .collect())
13430    }
13431
13432    /// Phase 7.1 metadata fast path: answer an unfiltered `MIN`/`MAX`/`COUNT(col)`
13433    /// straight from page `min`/`max`/`null_count` — no column decode. Returns
13434    /// `None` (caller decodes) for `COUNT(*)`/`SUM`/`AVG`, when exact stats are
13435    /// unavailable (multi-version run; [`Table::exact_column_stats`] gates this),
13436    /// or for a column whose stats omit `min`/`max` while it still holds values
13437    /// (e.g. an encrypted column) — returning `NULL` there would be a wrong
13438    /// answer, so we fall back to decoding.
13439    fn aggregate_from_stats(
13440        &self,
13441        snapshot: Snapshot,
13442        column: Option<u16>,
13443        agg: NativeAgg,
13444    ) -> Result<Option<NativeAggResult>> {
13445        let cid = match (agg, column) {
13446            (NativeAgg::Count | NativeAgg::Min | NativeAgg::Max, Some(c)) => c,
13447            _ => return Ok(None), // COUNT(*), SUM, AVG: not served from page stats
13448        };
13449        let Some(stats) = self.exact_column_stats(snapshot, &[cid])? else {
13450            return Ok(None);
13451        };
13452        let Some(cs) = stats.get(&cid) else {
13453            return Ok(None);
13454        };
13455        match agg {
13456            // COUNT(col) excludes NULLs: live rows minus the column's null count.
13457            NativeAgg::Count => Ok(Some(NativeAggResult::Count(
13458                self.live_count.saturating_sub(cs.null_count),
13459            ))),
13460            NativeAgg::Min | NativeAgg::Max => {
13461                let bound = if agg == NativeAgg::Min {
13462                    &cs.min
13463                } else {
13464                    &cs.max
13465                };
13466                match bound {
13467                    Some(Value::Int64(x)) => Ok(Some(NativeAggResult::Int(*x))),
13468                    Some(Value::Float64(x)) => Ok(Some(NativeAggResult::Float(*x))),
13469                    Some(_) => Ok(None), // unexpected stat type ⇒ decode
13470                    // No bound: a genuine SQL NULL only when the column is wholly
13471                    // null. Otherwise the stats are simply unavailable (encrypted),
13472                    // so decode for a correct answer.
13473                    None if cs.null_count >= self.live_count => Ok(Some(NativeAggResult::Null)),
13474                    None => Ok(None),
13475                }
13476            }
13477            _ => Ok(None),
13478        }
13479    }
13480
13481    /// Phase 7.1c: exact `COUNT(DISTINCT col)` from the bitmap index's partition
13482    /// cardinality — the number of distinct indexed values — with no scan. Each
13483    /// distinct value is one bitmap key; under the insert-only invariant (empty
13484    /// overlay, single run, `live_count == row_count`) every key has at least one
13485    /// live row, so the key count is exact. `NULL` is excluded from
13486    /// `COUNT(DISTINCT)`, so a null key (from an explicit `Value::Null` put) is
13487    /// discounted. Returns `None` (caller scans) without a bitmap index on the
13488    /// column or when the invariant does not hold.
13489    pub fn count_distinct_from_bitmap(&mut self, column_id: u16) -> Result<Option<u64>> {
13490        if self.ttl.is_some() {
13491            return Ok(None);
13492        }
13493        if !(self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1) {
13494            return Ok(None);
13495        }
13496        // A deferred bulk load leaves the bitmap unbuilt; complete it before
13497        // trusting its key count (same lazy contract as `query`/`flush`).
13498        self.ensure_indexes_complete()?;
13499        let reader = self.open_reader(self.run_refs[0].run_id)?;
13500        if self.live_count != reader.row_count() as u64 {
13501            return Ok(None);
13502        }
13503        let Some(bm) = self.bitmap.get(&column_id) else {
13504            return Ok(None); // no bitmap index ⇒ let the caller scan
13505        };
13506        let mut distinct = bm.value_count() as u64;
13507        // A null key (explicit `Value::Null`) is indexed but excluded from
13508        // COUNT(DISTINCT). (Schema-evolution-absent columns are never indexed.)
13509        if !bm.get(&Value::Null.encode_key()).is_empty() {
13510            distinct = distinct.saturating_sub(1);
13511        }
13512        Ok(Some(distinct))
13513    }
13514
13515    /// Incremental aggregate over the live table (Phase 8.3). For an append-only
13516    /// table, a warm cache entry (same `cache_key`) lets the result be refreshed
13517    /// by aggregating **only the newly inserted rows** (row-id watermark delta)
13518    /// and merging, instead of a full recompute. The caller supplies a stable
13519    /// `cache_key` (e.g. a hash of the SQL + projection); distinct queries must
13520    /// use distinct keys.
13521    ///
13522    /// Returns [`IncrementalAggResult`] with the merged state and whether the
13523    /// delta path was taken. A single `delete` (ever) disables the incremental
13524    /// path for the table, so correctness never relies on append-only behavior
13525    /// that deletes invalidate.
13526    pub fn aggregate_incremental(
13527        &mut self,
13528        cache_key: u64,
13529        conditions: &[crate::query::Condition],
13530        column: Option<u16>,
13531        agg: NativeAgg,
13532    ) -> Result<IncrementalAggResult> {
13533        self.aggregate_incremental_inner(cache_key, conditions, column, agg, None)
13534    }
13535
13536    pub fn aggregate_incremental_with_control(
13537        &mut self,
13538        cache_key: u64,
13539        conditions: &[crate::query::Condition],
13540        column: Option<u16>,
13541        agg: NativeAgg,
13542        control: &crate::ExecutionControl,
13543    ) -> Result<IncrementalAggResult> {
13544        self.aggregate_incremental_inner(cache_key, conditions, column, agg, Some(control))
13545    }
13546
13547    fn aggregate_incremental_inner(
13548        &mut self,
13549        cache_key: u64,
13550        conditions: &[crate::query::Condition],
13551        column: Option<u16>,
13552        agg: NativeAgg,
13553        control: Option<&crate::ExecutionControl>,
13554    ) -> Result<IncrementalAggResult> {
13555        execution_checkpoint(control, 0)?;
13556        let snap = self.snapshot();
13557        let cur_wm = self.allocator.current().0;
13558        let cur_epoch = snap.epoch.0;
13559        // The watermark equals the committed row count only when the memtable is
13560        // empty (every allocated row id is durably in a run). With pending
13561        // (uncommitted) writes the allocator is ahead of the visible set, so the
13562        // delta range would silently skip just-committed rows — disable the
13563        // incremental path entirely in that case. The mutable-run tier holding
13564        // un-spilled data also disables it (those rows aren't in a run yet).
13565        let incremental_ok = self.ttl.is_none()
13566            && !self.had_deletes
13567            && self.memtable.is_empty()
13568            && self.mutable_run.is_empty();
13569
13570        // Incremental path: append-only, no pending writes, warm cache, advanced
13571        // epoch.
13572        if incremental_ok {
13573            if let Some(cached) = self.agg_cache.get(&cache_key).cloned() {
13574                if cached.epoch == cur_epoch {
13575                    return Ok(IncrementalAggResult {
13576                        state: cached.state,
13577                        incremental: true,
13578                        delta_rows: 0,
13579                    });
13580                }
13581                if cached.epoch < cur_epoch && cached.watermark <= cur_wm {
13582                    let delta_len = cur_wm.saturating_sub(cached.watermark) as usize;
13583                    let mut delta_rids = Vec::with_capacity(delta_len);
13584                    for (index, row_id) in (cached.watermark..cur_wm).enumerate() {
13585                        execution_checkpoint(control, index)?;
13586                        delta_rids.push(row_id);
13587                    }
13588                    let delta_rows = self.rows_for_rids(&delta_rids, snap)?;
13589                    execution_checkpoint(control, 0)?;
13590                    let index_sets = self.resolve_index_conditions(conditions, snap)?;
13591                    let delta_state = agg_state_from_rows(
13592                        &delta_rows,
13593                        conditions,
13594                        &index_sets,
13595                        column,
13596                        agg,
13597                        &self.schema,
13598                        control,
13599                    )?;
13600                    let merged = cached.state.merge(delta_state);
13601                    let delta_n = delta_rids.len() as u64;
13602                    Arc::make_mut(&mut self.agg_cache).insert(
13603                        cache_key,
13604                        CachedAgg {
13605                            state: merged.clone(),
13606                            watermark: cur_wm,
13607                            epoch: cur_epoch,
13608                        },
13609                    );
13610                    return Ok(IncrementalAggResult {
13611                        state: merged,
13612                        incremental: true,
13613                        delta_rows: delta_n,
13614                    });
13615                }
13616            }
13617        }
13618
13619        // Cold path. For Count/Sum/Min/Max the fast vectorized cursor produces a
13620        // directly-seedable state; for Avg it returns only the mean (losing the
13621        // sum+count needed to merge a future delta), so Avg falls back to a
13622        // visible-rows scan that captures both.
13623        let cursor_ok =
13624            self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
13625        let state = if cursor_ok && agg != NativeAgg::Avg {
13626            match self.aggregate_native_inner(snap, column, conditions, agg, control)? {
13627                Some(result) => {
13628                    AggState::from_native(result, agg, column.map(|c| self.column_type(c)))
13629                }
13630                None => self.agg_state_full_scan(conditions, column, agg, snap, control)?,
13631            }
13632        } else {
13633            self.agg_state_full_scan(conditions, column, agg, snap, control)?
13634        };
13635        // Seed only when the watermark is meaningful (no pending writes).
13636        if incremental_ok {
13637            Arc::make_mut(&mut self.agg_cache).insert(
13638                cache_key,
13639                CachedAgg {
13640                    state: state.clone(),
13641                    watermark: cur_wm,
13642                    epoch: cur_epoch,
13643                },
13644            );
13645        }
13646        Ok(IncrementalAggResult {
13647            state,
13648            incremental: false,
13649            delta_rows: 0,
13650        })
13651    }
13652
13653    /// Full visible-rows scan → [`AggState`] (cold path; captures sum+count for
13654    /// correct Avg seeding).
13655    fn agg_state_full_scan(
13656        &self,
13657        conditions: &[crate::query::Condition],
13658        column: Option<u16>,
13659        agg: NativeAgg,
13660        snap: Snapshot,
13661        control: Option<&crate::ExecutionControl>,
13662    ) -> Result<AggState> {
13663        execution_checkpoint(control, 0)?;
13664        let rows = self.visible_rows(snap)?;
13665        execution_checkpoint(control, 0)?;
13666        let index_sets = self.resolve_index_conditions(conditions, snap)?;
13667        agg_state_from_rows(
13668            &rows,
13669            conditions,
13670            &index_sets,
13671            column,
13672            agg,
13673            &self.schema,
13674            control,
13675        )
13676    }
13677
13678    /// Resolve only the index-defined conditions (`Ann`/`SparseMatch`) to row-id
13679    /// sets for membership testing during row-wise aggregation.
13680    fn resolve_index_conditions(
13681        &self,
13682        conditions: &[crate::query::Condition],
13683        snapshot: Snapshot,
13684    ) -> Result<Vec<RowIdSet>> {
13685        use crate::query::Condition;
13686        let mut sets = Vec::new();
13687        for c in conditions {
13688            if matches!(
13689                c,
13690                Condition::Ann { .. }
13691                    | Condition::SparseMatch { .. }
13692                    | Condition::MinHashSimilar { .. }
13693            ) {
13694                sets.push(self.resolve_condition(c, snapshot)?);
13695            }
13696        }
13697        Ok(sets)
13698    }
13699
13700    fn column_type(&self, cid: u16) -> TypeId {
13701        self.schema
13702            .columns
13703            .iter()
13704            .find(|c| c.id == cid)
13705            .map(|c| c.ty.clone())
13706            .unwrap_or(TypeId::Bytes)
13707    }
13708
13709    /// Approximate `COUNT`/`SUM`/`AVG` over a filtered set, computed from the
13710    /// in-memory reservoir sample (Phase 8.2). Returns a point estimate plus a
13711    /// normal-theory confidence interval at the supplied z-score (1.96 ≈ 95 %).
13712    ///
13713    /// The WHERE predicates are evaluated **exactly** on each sampled row (so
13714    /// LIKE/FM and equality/range contribute no index bias); `Ann`/`SparseMatch`
13715    /// are index-defined and resolved once to a row-id set that sampled rows are
13716    /// tested against. `Ok(None)` when there is no usable sample.
13717    pub fn approx_aggregate(
13718        &mut self,
13719        conditions: &[crate::query::Condition],
13720        column: Option<u16>,
13721        agg: ApproxAgg,
13722        z: f64,
13723    ) -> Result<Option<ApproxResult>> {
13724        self.approx_aggregate_with_candidate_authorization(conditions, column, agg, z, None)
13725    }
13726
13727    /// Security-aware approximate aggregate. RLS is evaluated only for the
13728    /// reservoir candidates, and column masks are applied before aggregation.
13729    pub fn approx_aggregate_with_candidate_authorization(
13730        &mut self,
13731        conditions: &[crate::query::Condition],
13732        column: Option<u16>,
13733        agg: ApproxAgg,
13734        z: f64,
13735        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
13736    ) -> Result<Option<ApproxResult>> {
13737        use crate::query::Condition;
13738        self.ensure_reservoir_complete()?;
13739        // Approx stats estimate the current live population. Prefer the table
13740        // snapshot, but if HLC dual-model visibility filters the entire
13741        // reservoir sample (epoch-only vs HLC-stamped), fall back to an
13742        // unbounded product snapshot so Count/Sum estimates remain available.
13743        let mut snapshot = self.snapshot();
13744        let n_pop = self.count();
13745        let sample_rids: Vec<u64> = self.reservoir.row_ids().to_vec();
13746        if sample_rids.is_empty() {
13747            return Ok(None);
13748        }
13749        // Materialize the live, non-deleted sampled rows.
13750        let mut live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13751        if live_sample.is_empty() {
13752            snapshot = Snapshot::unbounded();
13753            live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13754        }
13755        let s = live_sample.len();
13756        if s == 0 {
13757            return Ok(None);
13758        }
13759        let authorized = authorization
13760            .map(|authorization| {
13761                let candidates = live_sample.iter().map(|row| row.row_id).collect::<Vec<_>>();
13762                self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, None)
13763            })
13764            .transpose()?;
13765
13766        // Pre-resolve Ann/Sparse conditions (index-defined predicates) to row-id
13767        // sets; the per-row predicates below are evaluated exactly.
13768        let mut index_sets: Vec<RowIdSet> = Vec::new();
13769        for c in conditions {
13770            if matches!(
13771                c,
13772                Condition::Ann { .. }
13773                    | Condition::SparseMatch { .. }
13774                    | Condition::MinHashSimilar { .. }
13775            ) {
13776                index_sets.push(self.resolve_condition(c, snapshot)?);
13777            }
13778        }
13779
13780        // For Sum/Avg, gather the numeric column value of each passing row.
13781        let cid = match (agg, column) {
13782            (ApproxAgg::Count, _) => None,
13783            (_, Some(c)) => Some(c),
13784            _ => return Ok(None),
13785        };
13786        let mut passing_vals: Vec<f64> = Vec::with_capacity(s);
13787        for r in &live_sample {
13788            if authorized
13789                .as_ref()
13790                .is_some_and(|authorized| !authorized.contains(&r.row_id))
13791            {
13792                continue;
13793            }
13794            // Exact per-row predicate evaluation.
13795            if !conditions
13796                .iter()
13797                .all(|c| condition_matches_row(c, r, &self.schema))
13798            {
13799                continue;
13800            }
13801            // Ann/Sparse membership.
13802            if !index_sets.iter().all(|set| set.contains(r.row_id.0)) {
13803                continue;
13804            }
13805            if let Some(cid) = cid {
13806                let mut cells = r
13807                    .columns
13808                    .get(&cid)
13809                    .cloned()
13810                    .map(|value| vec![(cid, value)])
13811                    .unwrap_or_default();
13812                if let Some(authorization) = authorization {
13813                    authorization.security.apply_masks_to_cells(
13814                        authorization.table,
13815                        &mut cells,
13816                        authorization.principal,
13817                    );
13818                }
13819                if let Some(v) = as_f64(cells.first().map(|(_, value)| value)) {
13820                    passing_vals.push(v);
13821                } // nulls ⇒ excluded (matching SQL AVG/SUM null semantics)
13822            } else {
13823                passing_vals.push(0.0); // placeholder for COUNT
13824            }
13825        }
13826        let m = passing_vals.len();
13827
13828        let (point, half) = match agg {
13829            ApproxAgg::Count => {
13830                // Proportion estimate scaled to the population.
13831                let p = m as f64 / s as f64;
13832                let point = n_pop as f64 * p;
13833                let var = if s > 1 {
13834                    n_pop as f64 * n_pop as f64 * p * (1.0 - p) / s as f64
13835                        * (1.0 - s as f64 / n_pop as f64).max(0.0)
13836                } else {
13837                    0.0
13838                };
13839                (point, z * var.sqrt())
13840            }
13841            ApproxAgg::Sum => {
13842                // Horvitz–Thompson: each sampled row represents n_pop/s rows.
13843                let y: Vec<f64> = live_sample
13844                    .iter()
13845                    .map(|r| {
13846                        let passes_row = authorized
13847                            .as_ref()
13848                            .is_none_or(|authorized| authorized.contains(&r.row_id))
13849                            && conditions
13850                                .iter()
13851                                .all(|c| condition_matches_row(c, r, &self.schema))
13852                            && index_sets.iter().all(|set| set.contains(r.row_id.0));
13853                        if passes_row {
13854                            cid.and_then(|cid| {
13855                                let mut cells = r
13856                                    .columns
13857                                    .get(&cid)
13858                                    .cloned()
13859                                    .map(|value| vec![(cid, value)])
13860                                    .unwrap_or_default();
13861                                if let Some(authorization) = authorization {
13862                                    authorization.security.apply_masks_to_cells(
13863                                        authorization.table,
13864                                        &mut cells,
13865                                        authorization.principal,
13866                                    );
13867                                }
13868                                as_f64(cells.first().map(|(_, value)| value))
13869                            })
13870                            .unwrap_or(0.0)
13871                        } else {
13872                            0.0
13873                        }
13874                    })
13875                    .collect();
13876                let mean_y = y.iter().sum::<f64>() / s as f64;
13877                let point = n_pop as f64 * mean_y;
13878                let var = if s > 1 {
13879                    let ss: f64 = y.iter().map(|v| (v - mean_y).powi(2)).sum();
13880                    let var_y = ss / (s - 1) as f64;
13881                    n_pop as f64 * n_pop as f64 * var_y / s as f64
13882                        * (1.0 - s as f64 / n_pop as f64).max(0.0)
13883                } else {
13884                    0.0
13885                };
13886                (point, z * var.sqrt())
13887            }
13888            ApproxAgg::Avg => {
13889                if m == 0 {
13890                    return Ok(Some(ApproxResult {
13891                        point: 0.0,
13892                        ci_low: 0.0,
13893                        ci_high: 0.0,
13894                        n_population: n_pop,
13895                        n_sample_live: s,
13896                        n_passing: 0,
13897                    }));
13898                }
13899                let mean = passing_vals.iter().sum::<f64>() / m as f64;
13900                let half = if m > 1 {
13901                    let ss: f64 = passing_vals.iter().map(|v| (v - mean).powi(2)).sum();
13902                    let sd = (ss / (m - 1) as f64).sqrt();
13903                    let fpc = (1.0 - s as f64 / n_pop as f64).max(0.0);
13904                    z * sd / (m as f64).sqrt() * fpc.sqrt()
13905                } else {
13906                    0.0
13907                };
13908                (mean, half)
13909            }
13910        };
13911
13912        Ok(Some(ApproxResult {
13913            point,
13914            ci_low: point - half,
13915            ci_high: point + half,
13916            n_population: n_pop,
13917            n_sample_live: s,
13918            n_passing: m,
13919        }))
13920    }
13921
13922    /// Exact per-column statistics for the analytical aggregate fast path
13923    /// (Phase 7.1: `MIN`/`MAX`/`COUNT(col)` from page stats). Returns `None`
13924    /// unless the table is effectively insert-only at `snapshot` — empty
13925    /// memtable, a single sorted run, and `live_count == run.row_count()` — so
13926    /// the run's page `min`/`max`/`null_count` are exact (no tombstoned or
13927    /// superseded versions skew them). Under deletes/updates the caller falls
13928    /// back to scanning.
13929    pub fn exact_column_stats(
13930        &self,
13931        _snapshot: Snapshot,
13932        projection: &[u16],
13933    ) -> Result<Option<HashMap<u16, ColumnStat>>> {
13934        if self.ttl.is_some()
13935            || !(self.memtable.is_empty()
13936                && self.mutable_run.is_empty()
13937                && self.run_refs.len() == 1)
13938        {
13939            return Ok(None);
13940        }
13941        let reader = self.open_reader(self.run_refs[0].run_id)?;
13942        if self.live_count != reader.row_count() as u64 {
13943            return Ok(None);
13944        }
13945        let mut out = HashMap::new();
13946        for &cid in projection {
13947            let cdef = match self.schema.columns.iter().find(|c| c.id == cid) {
13948                Some(c) => c,
13949                None => continue,
13950            };
13951            // Absent column (schema evolution) ⇒ all rows null.
13952            let Some(stats) = reader.column_page_stats(cid) else {
13953                out.insert(
13954                    cid,
13955                    ColumnStat {
13956                        min: None,
13957                        max: None,
13958                        null_count: self.live_count,
13959                    },
13960                );
13961                continue;
13962            };
13963            let stat = match cdef.ty {
13964                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13965                    agg_int(stats, crate::sorted_run::be_i64).map(|(mn, mx, n)| ColumnStat {
13966                        min: mn.map(Value::Int64),
13967                        max: mx.map(Value::Int64),
13968                        null_count: n,
13969                    })
13970                }
13971                TypeId::Float64 => {
13972                    agg_float(stats, crate::sorted_run::be_f64).map(|(mn, mx, n)| ColumnStat {
13973                        min: mn.map(Value::Float64),
13974                        max: mx.map(Value::Float64),
13975                        null_count: n,
13976                    })
13977                }
13978                _ => None,
13979            };
13980            if let Some(s) = stat {
13981                out.insert(cid, s);
13982            }
13983        }
13984        Ok(Some(out))
13985    }
13986
13987    pub fn dir(&self) -> &Path {
13988        &self.dir
13989    }
13990
13991    pub fn schema(&self) -> &Schema {
13992        &self.schema
13993    }
13994
13995    pub fn ann_index(&self, column_id: u16) -> Option<&crate::index::AnnIndex> {
13996        self.ann.get(&column_id)
13997    }
13998
13999    pub fn ann_index_mut(&mut self, column_id: u16) -> Option<&mut crate::index::AnnIndex> {
14000        self.ann.get_mut(&column_id)
14001    }
14002
14003    pub(crate) fn set_catalog_name(&mut self, name: String) {
14004        self.name = name;
14005    }
14006
14007    pub(crate) fn prepare_alter_column(
14008        &mut self,
14009        column_name: &str,
14010        change: &AlterColumn,
14011    ) -> Result<(ColumnDef, Option<Schema>)> {
14012        if !self.pending_rows.is_empty() || !self.pending_dels.is_empty() {
14013            return Err(MongrelError::InvalidArgument(
14014                "ALTER COLUMN requires committing staged writes first".into(),
14015            ));
14016        }
14017        let old = self
14018            .schema
14019            .columns
14020            .iter()
14021            .find(|c| c.name == column_name)
14022            .cloned()
14023            .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14024        let mut next = old.clone();
14025
14026        if let Some(name) = &change.name {
14027            let trimmed = name.trim();
14028            if trimmed.is_empty() {
14029                return Err(MongrelError::InvalidArgument(
14030                    "ALTER COLUMN name must not be empty".into(),
14031                ));
14032            }
14033            if trimmed != old.name && self.schema.columns.iter().any(|c| c.name == trimmed) {
14034                return Err(MongrelError::Schema(format!(
14035                    "column {trimmed} already exists"
14036                )));
14037            }
14038            next.name = trimmed.to_string();
14039        }
14040
14041        if let Some(ty) = &change.ty {
14042            next.ty = ty.clone();
14043        }
14044        if let Some(flags) = change.flags {
14045            validate_alter_column_flags(old.flags, flags)?;
14046            next.flags = flags;
14047        }
14048
14049        if let Some(default_change) = &change.default_value {
14050            next.default_value = default_change.clone();
14051        }
14052        if let Some(source_change) = &change.embedding_source {
14053            next.embedding_source = source_change.clone();
14054        }
14055
14056        validate_alter_column_type(&self.schema, &old, &next, self.has_stored_versions())?;
14057        if old.flags.contains(ColumnFlags::NULLABLE)
14058            && !next.flags.contains(ColumnFlags::NULLABLE)
14059            && self.column_has_nulls(old.id)?
14060        {
14061            return Err(MongrelError::InvalidArgument(format!(
14062                "column '{}' contains NULL values",
14063                old.name
14064            )));
14065        }
14066        if next == old {
14067            return Ok((next, None));
14068        }
14069        let mut schema = self.schema.clone();
14070        let index = schema
14071            .columns
14072            .iter()
14073            .position(|column| column.id == next.id)
14074            .ok_or_else(|| MongrelError::Schema(format!("unknown column {}", next.id)))?;
14075        schema.columns[index] = next.clone();
14076        schema.schema_id = schema
14077            .schema_id
14078            .checked_add(1)
14079            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14080        schema.validate_auto_increment()?;
14081        schema.validate_defaults()?;
14082        Ok((next, Some(schema)))
14083    }
14084
14085    pub(crate) fn apply_altered_schema_prepared(&mut self, schema: Schema) {
14086        self.schema = schema;
14087        self.auto_inc = resolve_auto_inc(&self.schema);
14088        self.column_keys = build_column_keys(self.kek.as_deref(), &self.schema);
14089        self.clear_result_cache();
14090        let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
14091    }
14092
14093    /// Publish one hidden index artifact with its prepared schema. Callers
14094    /// hold the final commit barrier and have already verified that
14095    /// `artifact` covers the table's exact current epoch.
14096    pub(crate) fn publish_index_schema_change(
14097        &mut self,
14098        schema: Schema,
14099        artifact: SecondaryIndexArtifact,
14100    ) -> Result<()> {
14101        self.apply_altered_schema_prepared(schema);
14102        self.prune_index_maps_to_schema();
14103        match artifact {
14104            SecondaryIndexArtifact::Bitmap(column_id, index) => {
14105                self.bitmap.insert(column_id, index);
14106            }
14107            SecondaryIndexArtifact::LearnedRange(column_id, index) => {
14108                Arc::make_mut(&mut self.learned_range).insert(column_id, index);
14109            }
14110            SecondaryIndexArtifact::Fm(column_id, index) => {
14111                self.fm.insert(column_id, *index);
14112            }
14113            SecondaryIndexArtifact::Ann(column_id, index) => {
14114                self.ann.insert(column_id, *index);
14115            }
14116            SecondaryIndexArtifact::Sparse(column_id, index) => {
14117                self.sparse.insert(column_id, index);
14118            }
14119            SecondaryIndexArtifact::MinHash(column_id, index) => {
14120                self.minhash.insert(column_id, index);
14121            }
14122        }
14123        self.indexes_complete = true;
14124        self.seal_generations();
14125        let view = Arc::new(self.capture_read_generation());
14126        self.published.store(Arc::clone(&view));
14127        checkpoint_current_schema(self)?;
14128        // The catalog + rows are authoritative. A later flush/checkpoint
14129        // persists this derived generation without extending the write fence.
14130        self.invalidate_index_checkpoint();
14131        Ok(())
14132    }
14133
14134    /// Drop one secondary index from the live maps without rewriting table
14135    /// rows. Installs `schema` (already missing the dropped index), prunes
14136    /// maps, publishes a new generation, and invalidates the derived
14137    /// global-index checkpoint so reopen rebuilds from the authoritative
14138    /// schema + rows.
14139    pub(crate) fn publish_index_drop(&mut self, schema: Schema) -> Result<()> {
14140        self.apply_altered_schema_prepared(schema);
14141        self.prune_index_maps_to_schema();
14142        self.indexes_complete = true;
14143        self.seal_generations();
14144        let view = Arc::new(self.capture_read_generation());
14145        self.published.store(Arc::clone(&view));
14146        checkpoint_current_schema(self)?;
14147        // Dropped-index maps no longer match any prior checkpoint image.
14148        self.invalidate_index_checkpoint();
14149        Ok(())
14150    }
14151
14152    fn prune_index_maps_to_schema(&mut self) {
14153        let keep_bitmap: std::collections::HashSet<u16> = self
14154            .schema
14155            .indexes
14156            .iter()
14157            .filter(|index| index.kind == IndexKind::Bitmap)
14158            .map(|index| index.column_id)
14159            .collect();
14160        let keep_ann: std::collections::HashSet<u16> = self
14161            .schema
14162            .indexes
14163            .iter()
14164            .filter(|index| index.kind == IndexKind::Ann)
14165            .map(|index| index.column_id)
14166            .collect();
14167        let keep_fm: std::collections::HashSet<u16> = self
14168            .schema
14169            .indexes
14170            .iter()
14171            .filter(|index| index.kind == IndexKind::FmIndex)
14172            .map(|index| index.column_id)
14173            .collect();
14174        let keep_sparse: std::collections::HashSet<u16> = self
14175            .schema
14176            .indexes
14177            .iter()
14178            .filter(|index| index.kind == IndexKind::Sparse)
14179            .map(|index| index.column_id)
14180            .collect();
14181        let keep_minhash: std::collections::HashSet<u16> = self
14182            .schema
14183            .indexes
14184            .iter()
14185            .filter(|index| index.kind == IndexKind::MinHash)
14186            .map(|index| index.column_id)
14187            .collect();
14188        let keep_learned: std::collections::HashSet<u16> = self
14189            .schema
14190            .indexes
14191            .iter()
14192            .filter(|index| index.kind == IndexKind::LearnedRange)
14193            .map(|index| index.column_id)
14194            .collect();
14195        self.bitmap
14196            .retain(|column_id, _| keep_bitmap.contains(column_id));
14197        self.ann.retain(|column_id, _| keep_ann.contains(column_id));
14198        self.fm.retain(|column_id, _| keep_fm.contains(column_id));
14199        self.sparse
14200            .retain(|column_id, _| keep_sparse.contains(column_id));
14201        self.minhash
14202            .retain(|column_id, _| keep_minhash.contains(column_id));
14203        {
14204            let learned = Arc::make_mut(&mut self.learned_range);
14205            learned.retain(|column_id, _| keep_learned.contains(column_id));
14206        }
14207    }
14208
14209    pub(crate) fn checkpoint_altered_schema(&mut self) -> Result<()> {
14210        checkpoint_current_schema(self)
14211    }
14212
14213    pub fn alter_column(&mut self, column_name: &str, change: AlterColumn) -> Result<ColumnDef> {
14214        self.ensure_writable()?;
14215        let previous_schema = self.schema.clone();
14216        let (column, schema) = self.prepare_alter_column(column_name, &change)?;
14217        if let Some(schema) = schema {
14218            self.apply_altered_schema_prepared(schema);
14219            self.checkpoint_standalone_schema_change(previous_schema)?;
14220        }
14221        Ok(column)
14222    }
14223
14224    fn column_has_nulls(&mut self, column_id: u16) -> Result<bool> {
14225        if self.live_count == 0 {
14226            return Ok(false);
14227        }
14228        let snap = self.snapshot();
14229        let columns = self.visible_columns_native(snap, Some(&[column_id]))?;
14230        Ok(columns
14231            .first()
14232            .map(|(_, col)| col.null_count(col.len()) != 0)
14233            .unwrap_or(true))
14234    }
14235
14236    fn has_stored_versions(&self) -> bool {
14237        !self.memtable.is_empty()
14238            || !self.mutable_run.is_empty()
14239            || self.run_refs.iter().any(|r| r.row_count > 0)
14240            || !self.retiring.is_empty()
14241    }
14242
14243    /// Add a column to the schema (schema evolution). Existing runs simply read
14244    /// back as null for the new column until re-written. Persists the new schema
14245    /// and manifest. The caller supplies the full [`ColumnFlags`] so migrations
14246    /// can add `PRIMARY KEY` / `AUTO_INCREMENT` columns correctly.
14247    pub fn add_column(
14248        &mut self,
14249        name: &str,
14250        ty: TypeId,
14251        flags: ColumnFlags,
14252        default_value: Option<crate::schema::DefaultExpr>,
14253    ) -> Result<u16> {
14254        self.add_column_with_id(name, ty, flags, default_value, None)
14255    }
14256
14257    pub fn add_column_with_id(
14258        &mut self,
14259        name: &str,
14260        ty: TypeId,
14261        flags: ColumnFlags,
14262        default_value: Option<crate::schema::DefaultExpr>,
14263        requested_id: Option<u16>,
14264    ) -> Result<u16> {
14265        self.ensure_writable()?;
14266        let previous_schema = self.schema.clone();
14267        let (column, schema) =
14268            self.prepare_add_column(name, ty, flags, default_value, requested_id)?;
14269        self.apply_altered_schema_prepared(schema);
14270        self.checkpoint_standalone_schema_change(previous_schema)?;
14271        Ok(column.id)
14272    }
14273
14274    pub(crate) fn prepare_add_column(
14275        &mut self,
14276        name: &str,
14277        ty: TypeId,
14278        flags: ColumnFlags,
14279        default_value: Option<crate::schema::DefaultExpr>,
14280        requested_id: Option<u16>,
14281    ) -> Result<(ColumnDef, Schema)> {
14282        self.ensure_writable()?;
14283        if self.schema.columns.iter().any(|c| c.name == name) {
14284            return Err(MongrelError::Schema(format!(
14285                "column {name} already exists"
14286            )));
14287        }
14288        let id = if let Some(id) = requested_id.filter(|id| *id != 0) {
14289            if self.schema.columns.iter().any(|c| c.id == id) {
14290                return Err(MongrelError::Schema(format!(
14291                    "column id {id} already exists"
14292                )));
14293            }
14294            id
14295        } else {
14296            self.schema
14297                .columns
14298                .iter()
14299                .map(|c| c.id)
14300                .max()
14301                .unwrap_or(0)
14302                .checked_add(1)
14303                .ok_or_else(|| MongrelError::Schema("column id space exhausted".into()))?
14304        };
14305        let column = ColumnDef {
14306            id,
14307            name: name.to_string(),
14308            ty,
14309            flags,
14310            default_value,
14311            embedding_source: None,
14312        };
14313        let mut next_schema = self.schema.clone();
14314        next_schema.columns.push(column.clone());
14315        next_schema.schema_id = next_schema
14316            .schema_id
14317            .checked_add(1)
14318            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14319        next_schema.validate_auto_increment()?;
14320        next_schema.validate_defaults()?;
14321        Ok((column, next_schema))
14322    }
14323
14324    /// Declare a `LearnedRange` (PGM) index on an existing numeric column and
14325    /// build it immediately from the current sorted run (Phase 13.3). After
14326    /// this, `Condition::Range` / `Condition::RangeF64` on that column resolve
14327    /// survivors sub-linearly (O(log segments + log ε)) instead of scanning the
14328    /// full column.
14329    ///
14330    /// Requires exactly one sorted run (call after `flush`). The index is
14331    /// rebuilt automatically on subsequent flushes.
14332    pub fn add_learned_range_index(&mut self, column_name: &str) -> Result<()> {
14333        self.ensure_writable()?;
14334        let cid = self
14335            .schema
14336            .columns
14337            .iter()
14338            .find(|c| c.name == column_name)
14339            .map(|c| c.id)
14340            .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14341        let ty = self
14342            .schema
14343            .columns
14344            .iter()
14345            .find(|c| c.id == cid)
14346            .map(|c| c.ty.clone())
14347            .unwrap_or(TypeId::Int64);
14348        if !matches!(
14349            ty,
14350            TypeId::Int64 | TypeId::Float64 | TypeId::TimestampNanos | TypeId::Date32
14351        ) {
14352            return Err(MongrelError::Schema(format!(
14353                "LearnedRange requires a numeric column; {column_name} is {ty:?}"
14354            )));
14355        }
14356        if self
14357            .schema
14358            .indexes
14359            .iter()
14360            .any(|i| i.column_id == cid && i.kind == IndexKind::LearnedRange)
14361        {
14362            return Ok(()); // already declared
14363        }
14364        let previous_schema = self.schema.clone();
14365        let previous_learned_range = Arc::clone(&self.learned_range);
14366        let mut next_schema = previous_schema.clone();
14367        next_schema.indexes.push(IndexDef {
14368            name: format!("{}_learned_range", column_name),
14369            column_id: cid,
14370            kind: IndexKind::LearnedRange,
14371            predicate: None,
14372            options: Default::default(),
14373        });
14374        next_schema.schema_id = next_schema
14375            .schema_id
14376            .checked_add(1)
14377            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14378        self.apply_altered_schema_prepared(next_schema);
14379        if let Err(error) = self.build_learned_ranges() {
14380            self.apply_altered_schema_prepared(previous_schema);
14381            self.learned_range = previous_learned_range;
14382            return Err(error);
14383        }
14384        if let Err(error) = self.checkpoint_standalone_schema_change(previous_schema) {
14385            if !matches!(
14386                &error,
14387                MongrelError::DurableCommit { .. } | MongrelError::CommitOutcomeUnknown { .. }
14388            ) {
14389                self.learned_range = previous_learned_range;
14390            }
14391            return Err(error);
14392        }
14393        Ok(())
14394    }
14395
14396    fn checkpoint_standalone_schema_change(&mut self, previous_schema: Schema) -> Result<()> {
14397        let mut schema_published = false;
14398        let schema_result = match self._root_guard.as_deref() {
14399            Some(root) => write_schema_durable_with_after(root, &self.schema, || {
14400                schema_published = true;
14401            }),
14402            None => write_schema_with_after(&self.dir, &self.schema, || {
14403                schema_published = true;
14404            }),
14405        };
14406        if schema_result.is_err() && !schema_published {
14407            self.apply_altered_schema_prepared(previous_schema);
14408            return schema_result;
14409        }
14410
14411        let manifest_result = self.persist_manifest(self.current_epoch());
14412        match (schema_result, manifest_result) {
14413            (_, Ok(())) => Ok(()),
14414            (Ok(()), Err(error)) => {
14415                self.poison_after_maintenance_publish_failure();
14416                Err(MongrelError::DurableCommit {
14417                    epoch: self.current_epoch().0,
14418                    message: format!(
14419                        "schema is durable but matching manifest publication failed: {error}"
14420                    ),
14421                })
14422            }
14423            (Err(schema_error), Err(manifest_error)) => {
14424                self.poison_after_maintenance_publish_failure();
14425                Err(MongrelError::CommitOutcomeUnknown {
14426                    epoch: self.current_epoch().0,
14427                    message: format!(
14428                        "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
14429                    ),
14430                })
14431            }
14432        }
14433    }
14434
14435    /// Tuning knob for the WAL auto-sync threshold. A no-op on a mounted table
14436    /// (the shared WAL's durability is governed by the group-commit coordinator).
14437    pub fn set_sync_byte_threshold(&mut self, threshold: u64) {
14438        self.sync_byte_threshold = threshold;
14439        if let WalSink::Private(w) = &mut self.wal {
14440            w.set_sync_byte_threshold(threshold);
14441        }
14442    }
14443
14444    /// Flush all live page-cache entries to the persistent `_cache/` backing
14445    /// directory (best-effort). Useful before a clean shutdown so hot pages
14446    /// survive restart.
14447    pub fn page_cache_flush(&self) {
14448        self.page_cache.flush_to_disk();
14449    }
14450
14451    /// Number of entries currently in the shared page cache (diagnostic).
14452    pub fn page_cache_len(&self) -> usize {
14453        self.page_cache.len()
14454    }
14455
14456    /// Number of entries currently in the shared decoded-page cache (Phase
14457    /// 15.4 diagnostic).
14458    pub fn decoded_cache_len(&self) -> usize {
14459        self.decoded_cache.len()
14460    }
14461
14462    /// Drain the live memtable (prototype/testing helper used by the flush path
14463    /// demos). Prefer [`Table::flush`] for the durable path.
14464    pub fn drain_memtable_sorted(&mut self) -> Vec<Row> {
14465        self.memtable.drain_sorted()
14466    }
14467
14468    pub(crate) fn run_path(&self, run_id: u64) -> PathBuf {
14469        self.runs_dir().join(format!("r-{run_id}.sr"))
14470    }
14471
14472    pub(crate) fn create_run_file(&self, run_id: u64) -> Result<Option<std::fs::File>> {
14473        match self.runs_root.as_deref() {
14474            Some(root) => Ok(Some(root.create_regular_new(format!("r-{run_id}.sr"))?)),
14475            None => Ok(None),
14476        }
14477    }
14478
14479    pub(crate) fn create_run_entry(&self, name: &Path) -> Result<Option<std::fs::File>> {
14480        match self.runs_root.as_deref() {
14481            Some(root) => Ok(Some(root.create_regular_new(name)?)),
14482            None => Ok(None),
14483        }
14484    }
14485
14486    pub(crate) fn release_run_reader(&self, run_id: u128) {
14487        self.run_readers.lock().remove(&run_id);
14488    }
14489
14490    pub(crate) fn remove_run_entry(&self, name: &Path) -> Result<()> {
14491        if let Some(run_id) = Self::run_id_from_entry_name(name) {
14492            self.release_run_reader(run_id);
14493        }
14494        match self.runs_root.as_deref() {
14495            Some(root) => match root.remove_file(name) {
14496                Ok(()) => Ok(()),
14497                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14498                Err(error) => Err(error.into()),
14499            },
14500            None => match std::fs::remove_file(self.runs_dir().join(name)) {
14501                Ok(()) => Ok(()),
14502                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14503                Err(error) => Err(error.into()),
14504            },
14505        }
14506    }
14507
14508    pub(crate) fn publish_run_entry(&self, source: &Path, destination: &Path) -> Result<()> {
14509        match self.runs_root.as_deref() {
14510            Some(root) => root
14511                .rename_file_new(source, destination)
14512                .map_err(Into::into),
14513            None => crate::durable_file::rename(
14514                &self.runs_dir().join(source),
14515                &self.runs_dir().join(destination),
14516            )
14517            .map_err(Into::into),
14518        }
14519    }
14520
14521    pub(crate) fn active_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14522        self.run_refs.iter().map(|run| run.run_id)
14523    }
14524
14525    pub(crate) fn table_dir(&self) -> &Path {
14526        &self.dir
14527    }
14528
14529    pub(crate) fn schema_ref(&self) -> &crate::schema::Schema {
14530        &self.schema
14531    }
14532
14533    pub(crate) fn alloc_run_id(&mut self) -> Result<u64> {
14534        let id = self.next_run_id;
14535        self.next_run_id = self
14536            .next_run_id
14537            .checked_add(1)
14538            .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))?;
14539        Ok(id)
14540    }
14541
14542    pub(crate) fn link_run(&mut self, run_ref: crate::manifest::RunRef) {
14543        self.run_refs.push(run_ref);
14544    }
14545
14546    /// Link a spilled run found during shared-WAL recovery (spec §8.5).
14547    /// **Idempotent**: if the run is already in the manifest (the publish phase
14548    /// persisted it before the crash, or this is a clean reopen with the
14549    /// `TxnCommit` still in the WAL) this is a no-op returning `false`, so the
14550    /// caller never double-links or double-counts. Otherwise — a crash *after*
14551    /// the commit fsync but *before* publish persisted the manifest — the run is
14552    /// Enqueue a compaction-superseded run for retention-gated deletion (spec
14553    /// §6.4). The file stays on disk until [`Self::reap_retiring`] removes it
14554    /// once `min_active_snapshot` has advanced past `retire_epoch`.
14555    pub(crate) fn retire_run(&mut self, run_id: u128, retire_epoch: u64) {
14556        self.retiring.push(crate::manifest::RetiredRun {
14557            run_id,
14558            retire_epoch,
14559        });
14560    }
14561
14562    /// Physically delete retired run files whose `retire_epoch` no pinned reader
14563    /// can still need (`min_active >= retire_epoch`), drop them from the queue,
14564    /// and persist the manifest if anything changed. Returns the count reaped.
14565    pub(crate) fn reap_retiring(
14566        &mut self,
14567        min_active: Epoch,
14568        backup_pinned: &std::collections::HashSet<u128>,
14569    ) -> Result<usize> {
14570        if self.retiring.is_empty() {
14571            return Ok(0);
14572        }
14573        let mut reaped = 0;
14574        let mut kept: Vec<crate::manifest::RetiredRun> = Vec::new();
14575        // Delete-then-persist is crash-idempotent: if we crash after unlinking
14576        // some files but before persisting, the manifest still lists them in
14577        // `retiring`; the next `reap_retiring` re-issues `remove_file` (the
14578        // error is ignored) and `check()` excludes `retiring` ids from orphan
14579        // detection, so the lingering entries are harmless until then.
14580        for r in std::mem::take(&mut self.retiring) {
14581            if min_active.0 >= r.retire_epoch && !backup_pinned.contains(&r.run_id) {
14582                let _ = self.remove_run_entry(Path::new(&format!("r-{}.sr", r.run_id)));
14583                reaped += 1;
14584            } else {
14585                kept.push(r);
14586            }
14587        }
14588        self.retiring = kept;
14589        if reaped > 0 {
14590            self.persist_manifest(self.current_epoch())?;
14591        }
14592        Ok(reaped)
14593    }
14594
14595    pub(crate) fn has_reapable_retiring(
14596        &self,
14597        min_active: Epoch,
14598        backup_pinned: &std::collections::HashSet<u128>,
14599    ) -> bool {
14600        self.retiring
14601            .iter()
14602            .any(|run| min_active.0 >= run.retire_epoch && !backup_pinned.contains(&run.run_id))
14603    }
14604
14605    pub(crate) fn recover_spilled_run(&mut self, run_ref: crate::manifest::RunRef) -> bool {
14606        if self.run_refs.iter().any(|r| r.run_id == run_ref.run_id) {
14607            return false;
14608        }
14609        self.live_count = self.live_count.saturating_add(run_ref.row_count);
14610        self.run_refs.push(run_ref);
14611        self.indexes_complete = false;
14612        true
14613    }
14614
14615    pub(crate) fn kek_ref(&self) -> Option<&Arc<Kek>> {
14616        self.kek.as_ref()
14617    }
14618
14619    /// Borrow the immutable reader for `run_id`, opening it once per table.
14620    fn with_run_reader<T>(
14621        &self,
14622        run_id: u128,
14623        body: impl FnOnce(&mut RunReader) -> T,
14624    ) -> Result<T> {
14625        let mut cache = self.run_readers.lock();
14626        if !cache.contains_key(&run_id) {
14627            drop(cache);
14628            let reader = self.open_reader(run_id)?;
14629            cache = self.run_readers.lock();
14630            // Bound the map to the warm fixtures (16 and 64 runs). A long-lived
14631            // table must not pin every run it has ever point-queried.
14632            if cache.len() >= 64 && !cache.contains_key(&run_id) {
14633                cache.clear();
14634            }
14635            cache.entry(run_id).or_insert(reader);
14636        }
14637        let reader = cache
14638            .get_mut(&run_id)
14639            .expect("sorted-run reader is cached for this lookup");
14640        Ok(body(reader))
14641    }
14642
14643    fn run_id_from_entry_name(name: &Path) -> Option<u128> {
14644        let file_name = name.file_name()?.to_str()?;
14645        file_name
14646            .strip_prefix("r-")?
14647            .strip_suffix(".sr")?
14648            .parse()
14649            .ok()
14650    }
14651
14652    pub(crate) fn open_reader(&self, run_id: u128) -> Result<RunReader> {
14653        let mut reader = match self.runs_root.as_deref() {
14654            Some(root) => RunReader::open_file_with_cache(
14655                root.open_regular(format!("r-{run_id}.sr"))?,
14656                self.schema.clone(),
14657                self.kek.clone(),
14658                Some(self.page_cache.clone()),
14659                Some(self.decoded_cache.clone()),
14660                self.table_id,
14661                Some(&self.verified_runs),
14662                None,
14663            )?,
14664            None => RunReader::open_with_cache(
14665                self.dir.join(RUNS_DIR).join(format!("r-{run_id}.sr")),
14666                self.schema.clone(),
14667                self.kek.clone(),
14668                Some(self.page_cache.clone()),
14669                Some(self.decoded_cache.clone()),
14670                self.table_id,
14671                Some(&self.verified_runs),
14672            )?,
14673        };
14674        // Overlay the real commit epoch for uniform-epoch (large-txn spill) runs:
14675        // their stored `_epoch` is a placeholder; the manifest RunRef carries the
14676        // assigned epoch. A no-op for ordinary runs.
14677        if let Some(rr) = self.run_refs.iter().find(|r| r.run_id == run_id) {
14678            reader.set_uniform_epoch(Epoch(rr.epoch_created));
14679        }
14680        Ok(reader)
14681    }
14682
14683    pub(crate) fn run_refs(&self) -> &[RunRef] {
14684        &self.run_refs
14685    }
14686
14687    pub(crate) fn retiring_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14688        self.retiring.iter().map(|run| run.run_id)
14689    }
14690
14691    pub(crate) fn runs_dir(&self) -> PathBuf {
14692        self.runs_root
14693            .as_deref()
14694            .and_then(|root| root.io_path().ok())
14695            .unwrap_or_else(|| self.dir.join(RUNS_DIR))
14696    }
14697
14698    pub(crate) fn wal_dir(&self) -> PathBuf {
14699        self.dir.join(WAL_DIR)
14700    }
14701
14702    pub(crate) fn set_run_refs(&mut self, refs: Vec<RunRef>) {
14703        self.run_refs = refs;
14704        self.refresh_run_row_id_ranges();
14705    }
14706
14707    /// `(min_row_id, max_row_id)` for the given run, when known. Used by
14708    /// compaction to enforce L1+ disjointness without re-opening every
14709    /// existing run header.
14710    pub(crate) fn run_row_id_range(&self, run_id: u128) -> Option<(u64, u64)> {
14711        self.run_row_id_ranges.get(&run_id).copied()
14712    }
14713
14714    /// Populate `run_row_id_ranges` from each run's on-disk header so
14715    /// [`Self::get`] can skip runs that cannot contain a given RowId.
14716    pub(crate) fn refresh_run_row_id_ranges(&mut self) {
14717        let mut ranges = HashMap::with_capacity(self.run_refs.len());
14718        for rr in &self.run_refs {
14719            if let Ok(reader) = self.open_reader(rr.run_id) {
14720                let h = reader.header();
14721                ranges.insert(rr.run_id, (h.min_row_id, h.max_row_id));
14722            }
14723        }
14724        self.run_row_id_ranges = ranges;
14725    }
14726
14727    pub(crate) fn compaction_zstd_level(&self) -> i32 {
14728        self.compaction_zstd_level
14729    }
14730
14731    pub(crate) fn kek(&self) -> Option<Arc<Kek>> {
14732        self.kek.clone()
14733    }
14734
14735    /// The index-checkpoint DEK (KEK-derived) for encrypted tables; `None` for
14736    /// plaintext tables. The checkpoint embeds index keys / PGM segment values
14737    /// derived from user data, so an encrypted table must encrypt it at rest.
14738    fn idx_dek(&self) -> Option<Zeroizing<[u8; DEK_LEN]>> {
14739        self.kek.as_ref().map(|k| k.derive_idx_key())
14740    }
14741
14742    /// Manifest (and other DB-wide metadata) meta DEK, derived from the KEK so
14743    /// the on-disk manifest is encrypted + authenticated at rest for encrypted
14744    /// tables. `None` for plaintext.
14745    fn manifest_meta_dek(&self) -> Option<[u8; DEK_LEN]> {
14746        self.kek.as_ref().map(|k| *k.derive_meta_key())
14747    }
14748
14749    /// `(column_id, scheme)` for every ENCRYPTED_INDEXABLE column — passed to
14750    /// the run writer so each run's descriptor records the column keys.
14751    pub(crate) fn indexable_column_specs(&self) -> Vec<(u16, u8)> {
14752        self.column_keys
14753            .iter()
14754            .map(|(&id, &(_, scheme))| (id, scheme))
14755            .collect()
14756    }
14757
14758    /// Tokenize a value for an ENCRYPTED_INDEXABLE column (HMAC-eq or OPE-range,
14759    /// per the column's scheme). Returns `None` for plaintext columns. Indexes
14760    /// over such columns store tokens, and queries tokenize literals the same
14761    /// way — so lookups never decrypt the stored (encrypted) page payloads.
14762    fn tokenize_value(&self, column_id: u16, v: &Value) -> Option<Value> {
14763        self.tokenize_value_enc(column_id, v)
14764    }
14765
14766    fn tokenize_value_enc(&self, column_id: u16, v: &Value) -> Option<Value> {
14767        use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
14768        let (key, scheme) = self.column_keys.get(&column_id)?;
14769        let token: Vec<u8> = match (*scheme, v) {
14770            (SCHEME_HMAC_EQ, _) => hmac_token(key, &v.encode_key()).to_vec(),
14771            (_, Value::Int64(x)) => ope_token_i64(key, *x).to_vec(),
14772            (_, Value::Float64(x)) => ope_token_f64(key, *x).to_vec(),
14773            _ => hmac_token(key, &v.encode_key()).to_vec(),
14774        };
14775        Some(Value::Bytes(token))
14776    }
14777
14778    /// Encoded index key for a `Value`, tokenized for HMAC-eq columns.
14779    fn index_lookup_key(&self, column_id: u16, v: &Value) -> Vec<u8> {
14780        self.index_lookup_key_bytes(column_id, &v.encode_key())
14781    }
14782
14783    /// Tokenize an already-encoded lookup key (equality queries pass the
14784    /// encoded search value; HMAC-eq columns wrap it under the column key).
14785    fn index_lookup_key_bytes(&self, column_id: u16, encoded: &[u8]) -> Vec<u8> {
14786        {
14787            use crate::encryption::{hmac_token, SCHEME_HMAC_EQ};
14788            if let Some((key, scheme)) = self.column_keys.get(&column_id) {
14789                if *scheme == SCHEME_HMAC_EQ {
14790                    return hmac_token(key, encoded).to_vec();
14791                }
14792            }
14793        }
14794        let _ = column_id;
14795        encoded.to_vec()
14796    }
14797}
14798
14799fn native_int64_strictly_increasing(col: &columnar::NativeColumn, n: usize) -> bool {
14800    let columnar::NativeColumn::Int64 { data, validity } = col else {
14801        return false;
14802    };
14803    if data.len() < n || !columnar::all_non_null(validity, n) {
14804        return false;
14805    }
14806    data.iter()
14807        .take(n)
14808        .zip(data.iter().skip(1))
14809        .all(|(a, b)| a < b)
14810}
14811
14812/// Exact aggregate of a column's page stats into a min/max/null_count triple
14813/// (Phase 7.1). Only meaningful when the owning table is insert-only, which
14814/// [`Table::exact_column_stats`] gates on.
14815#[derive(Debug, Clone)]
14816pub struct ColumnStat {
14817    pub min: Option<Value>,
14818    pub max: Option<Value>,
14819    pub null_count: u64,
14820}
14821
14822/// A supported native aggregate (Phase 7.2).
14823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14824pub enum NativeAgg {
14825    Count,
14826    Sum,
14827    Min,
14828    Max,
14829    Avg,
14830}
14831
14832/// The typed result of a [`NativeAgg`] over a column.
14833#[derive(Debug, Clone, PartialEq)]
14834pub enum NativeAggResult {
14835    Count(u64),
14836    Int(i64),
14837    Float(f64),
14838    /// No non-null inputs (SUM/MIN/MAX/AVG over zero rows ⇒ SQL NULL).
14839    Null,
14840}
14841
14842/// A supported approximate aggregate over the reservoir sample (Phase 8.2).
14843#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14844pub enum ApproxAgg {
14845    Count,
14846    Sum,
14847    Avg,
14848}
14849
14850/// Point estimate with a normal-theory confidence interval from the reservoir
14851/// sample (Phase 8.2). `ci_low`/`ci_high` bracket `point` at the requested
14852/// z-score; the interval has zero width when the sample equals the whole table.
14853#[derive(Debug, Clone)]
14854pub struct ApproxResult {
14855    /// Point estimate of the aggregate.
14856    pub point: f64,
14857    /// Lower bound (`point − z·SE`).
14858    pub ci_low: f64,
14859    /// Upper bound (`point + z·SE`).
14860    pub ci_high: f64,
14861    /// Live population size (the table's `count()`).
14862    pub n_population: u64,
14863    /// Live rows in the sample (`≤` reservoir capacity).
14864    pub n_sample_live: usize,
14865    /// Sampled rows passing the WHERE predicate.
14866    pub n_passing: usize,
14867}
14868
14869/// A mergeable running aggregate state (Phase 8.3). Two states over disjoint
14870/// row sets `merge` into the state over their union, so a cached analytical
14871/// aggregate can be updated by merging in only the delta (newly inserted rows)
14872/// instead of a full recompute.
14873#[derive(Debug, Clone, PartialEq)]
14874pub enum AggState {
14875    /// `COUNT(*)` or `COUNT(col)` over `n` matching rows.
14876    Count(u64),
14877    /// Int64 `SUM`: running `i128` sum + non-null count.
14878    SumI {
14879        sum: i128,
14880        count: u64,
14881    },
14882    /// Float64 `SUM`: running `f64` sum + non-null count.
14883    SumF {
14884        sum: f64,
14885        count: u64,
14886    },
14887    /// Int64 `AVG`: running `i128` sum + non-null count (avg = sum/count).
14888    AvgI {
14889        sum: i128,
14890        count: u64,
14891    },
14892    /// Float64 `AVG`: running `f64` sum + non-null count.
14893    AvgF {
14894        sum: f64,
14895        count: u64,
14896    },
14897    /// Int64 `MIN`/`MAX`.
14898    MinI(i64),
14899    MaxI(i64),
14900    /// Float64 `MIN`/`MAX`.
14901    MinF(f64),
14902    MaxF(f64),
14903    /// No matching rows observed yet.
14904    Empty,
14905}
14906
14907impl AggState {
14908    /// Combine two states over disjoint row sets into the state over the union.
14909    pub fn merge(self, other: AggState) -> AggState {
14910        use AggState::*;
14911        match (self, other) {
14912            (Empty, x) | (x, Empty) => x,
14913            (Count(a), Count(b)) => Count(a + b),
14914            (SumI { sum: sa, count: ca }, SumI { sum: sb, count: cb }) => SumI {
14915                sum: sa + sb,
14916                count: ca + cb,
14917            },
14918            (SumF { sum: sa, count: ca }, SumF { sum: sb, count: cb }) => SumF {
14919                sum: sa + sb,
14920                count: ca + cb,
14921            },
14922            (AvgI { sum: sa, count: ca }, AvgI { sum: sb, count: cb }) => AvgI {
14923                sum: sa + sb,
14924                count: ca + cb,
14925            },
14926            (AvgF { sum: sa, count: ca }, AvgF { sum: sb, count: cb }) => AvgF {
14927                sum: sa + sb,
14928                count: ca + cb,
14929            },
14930            (MinI(a), MinI(b)) => MinI(a.min(b)),
14931            (MaxI(a), MaxI(b)) => MaxI(a.max(b)),
14932            (MinF(a), MinF(b)) => MinF(a.min(b)),
14933            (MaxF(a), MaxF(b)) => MaxF(a.max(b)),
14934            _ => Empty, // mismatched kinds — shouldn't happen (same query)
14935        }
14936    }
14937
14938    /// The scalar point value (`f64`), or `None` when there were no inputs.
14939    pub fn point(&self) -> Option<f64> {
14940        match self {
14941            AggState::Count(n) => Some(*n as f64),
14942            AggState::SumI { sum, .. } => Some(*sum as f64),
14943            AggState::SumF { sum, .. } => Some(*sum),
14944            AggState::AvgI { sum, count } if *count > 0 => Some(*sum as f64 / *count as f64),
14945            AggState::AvgF { sum, count } if *count > 0 => Some(*sum / *count as f64),
14946            AggState::MinI(n) => Some(*n as f64),
14947            AggState::MaxI(n) => Some(*n as f64),
14948            AggState::MinF(n) => Some(*n),
14949            AggState::MaxF(n) => Some(*n),
14950            AggState::AvgI { .. } | AggState::AvgF { .. } | AggState::Empty => None,
14951        }
14952    }
14953
14954    /// Convert a vectorized [`NativeAggResult`] (from the cursor path) into a
14955    /// mergeable [`AggState`], so the incremental cache can be seeded from the
14956    /// fast cold path. `ty` is the column's type (`None` for COUNT(*)).
14957    pub fn from_native(result: NativeAggResult, agg: NativeAgg, ty: Option<TypeId>) -> Self {
14958        let is_float = matches!(ty, Some(TypeId::Float64));
14959        match (agg, result) {
14960            (NativeAgg::Count, NativeAggResult::Count(n)) => AggState::Count(n),
14961            (NativeAgg::Sum, NativeAggResult::Int(x)) => AggState::SumI {
14962                sum: x as i128,
14963                count: 1, // count unknown from NativeAggResult; use sentinel
14964            },
14965            (NativeAgg::Sum, NativeAggResult::Float(x)) => AggState::SumF { sum: x, count: 1 },
14966            (NativeAgg::Avg, NativeAggResult::Float(x)) => AggState::AvgF { sum: x, count: 1 },
14967            (NativeAgg::Min, NativeAggResult::Int(x)) => AggState::MinI(x),
14968            (NativeAgg::Max, NativeAggResult::Int(x)) => AggState::MaxI(x),
14969            (NativeAgg::Min, NativeAggResult::Float(x)) => AggState::MinF(x),
14970            (NativeAgg::Max, NativeAggResult::Float(x)) => AggState::MaxF(x),
14971            (NativeAgg::Count, _) => AggState::Empty,
14972            (_, NativeAggResult::Null) => AggState::Empty,
14973            _ => {
14974                let _ = is_float;
14975                AggState::Empty
14976            }
14977        }
14978    }
14979}
14980
14981/// A cached incremental aggregate (Phase 8.3): the mergeable state, the row-id
14982/// watermark it covers (rows `[0, watermark)`), and the snapshot epoch.
14983#[derive(Debug, Clone)]
14984pub struct CachedAgg {
14985    pub state: AggState,
14986    pub watermark: u64,
14987    pub epoch: u64,
14988}
14989
14990/// Outcome of [`Table::aggregate_incremental`].
14991#[derive(Debug, Clone)]
14992pub struct IncrementalAggResult {
14993    /// The aggregate state covering all rows at the current epoch.
14994    pub state: AggState,
14995    /// `true` when produced by merging only the delta (new rows); `false` when
14996    /// a full recompute was required (cold cache, deletes, or same epoch).
14997    pub incremental: bool,
14998    /// Rows processed in the delta pass (`0` for a full recompute).
14999    pub delta_rows: u64,
15000}
15001
15002/// Compute a mergeable [`AggState`] over `rows` that pass every per-row
15003/// `conditions` conjunct (and whose row id is in every pre-resolved
15004/// `index_sets`). Shared by the cold (full) and warm (delta) incremental paths.
15005fn agg_state_from_rows(
15006    rows: &[Row],
15007    conditions: &[crate::query::Condition],
15008    index_sets: &[RowIdSet],
15009    column: Option<u16>,
15010    agg: NativeAgg,
15011    schema: &Schema,
15012    control: Option<&crate::ExecutionControl>,
15013) -> Result<AggState> {
15014    let mut count: u64 = 0;
15015    let mut sum_i: i128 = 0;
15016    let mut sum_f: f64 = 0.0;
15017    let mut mn_i: i64 = i64::MAX;
15018    let mut mx_i: i64 = i64::MIN;
15019    let mut mn_f: f64 = f64::INFINITY;
15020    let mut mx_f: f64 = f64::NEG_INFINITY;
15021    let mut saw_int = false;
15022    let mut saw_float = false;
15023    for (index, r) in rows.iter().enumerate() {
15024        execution_checkpoint(control, index)?;
15025        if !conditions
15026            .iter()
15027            .all(|c| condition_matches_row(c, r, schema))
15028        {
15029            continue;
15030        }
15031        if !index_sets.iter().all(|s| s.contains(r.row_id.0)) {
15032            continue;
15033        }
15034        match agg {
15035            NativeAgg::Count => match column {
15036                // COUNT(*) counts every passing row.
15037                None => count += 1,
15038                // COUNT(col) excludes NULLs — explicit `Value::Null` and a column
15039                // absent from the row (schema evolution) are both NULL.
15040                Some(cid) => match r.columns.get(&cid) {
15041                    None | Some(Value::Null) => {}
15042                    Some(_) => count += 1,
15043                },
15044            },
15045            _ => match column.and_then(|cid| r.columns.get(&cid)) {
15046                Some(Value::Int64(n)) => {
15047                    count += 1;
15048                    sum_i += *n as i128;
15049                    mn_i = mn_i.min(*n);
15050                    mx_i = mx_i.max(*n);
15051                    saw_int = true;
15052                }
15053                Some(Value::Float64(f)) => {
15054                    count += 1;
15055                    sum_f += f;
15056                    mn_f = mn_f.min(*f);
15057                    mx_f = mx_f.max(*f);
15058                    saw_float = true;
15059                }
15060                _ => {}
15061            },
15062        }
15063    }
15064    Ok(match agg {
15065        NativeAgg::Count => {
15066            if count == 0 {
15067                AggState::Empty
15068            } else {
15069                AggState::Count(count)
15070            }
15071        }
15072        NativeAgg::Sum => {
15073            if count == 0 {
15074                AggState::Empty
15075            } else if saw_int {
15076                AggState::SumI { sum: sum_i, count }
15077            } else {
15078                AggState::SumF { sum: sum_f, count }
15079            }
15080        }
15081        NativeAgg::Avg => {
15082            if count == 0 {
15083                AggState::Empty
15084            } else if saw_int {
15085                AggState::AvgI { sum: sum_i, count }
15086            } else {
15087                AggState::AvgF { sum: sum_f, count }
15088            }
15089        }
15090        NativeAgg::Min => {
15091            if !saw_int && !saw_float {
15092                AggState::Empty
15093            } else if saw_int {
15094                AggState::MinI(mn_i)
15095            } else {
15096                AggState::MinF(mn_f)
15097            }
15098        }
15099        NativeAgg::Max => {
15100            if !saw_int && !saw_float {
15101                AggState::Empty
15102            } else if saw_int {
15103                AggState::MaxI(mx_i)
15104            } else {
15105                AggState::MaxF(mx_f)
15106            }
15107        }
15108    })
15109}
15110
15111/// Evaluate an index-served [`Condition`] exactly against a materialized row.
15112/// `Ann`/`SparseMatch` (index-defined) always pass here; callers test those via a
15113/// pre-resolved row-id set.
15114fn condition_matches_row(c: &crate::query::Condition, row: &Row, schema: &Schema) -> bool {
15115    use crate::query::Condition;
15116    match c {
15117        Condition::Pk(key) => match schema.primary_key() {
15118            Some(pk) => row
15119                .columns
15120                .get(&pk.id)
15121                .map(|v| v.encode_key() == *key)
15122                .unwrap_or(false),
15123            None => false,
15124        },
15125        Condition::BitmapEq { column_id, value } => row
15126            .columns
15127            .get(column_id)
15128            .map(|v| v.encode_key() == *value)
15129            .unwrap_or(false),
15130        Condition::BitmapIn { column_id, values } => {
15131            let key = row.columns.get(column_id).map(|v| v.encode_key());
15132            match key {
15133                Some(k) => values.contains(&k),
15134                None => false,
15135            }
15136        }
15137        Condition::BytesPrefix { column_id, prefix } => row
15138            .columns
15139            .get(column_id)
15140            .map(|v| v.encode_key().starts_with(prefix))
15141            .unwrap_or(false),
15142        Condition::Range { column_id, lo, hi } => match row.columns.get(column_id) {
15143            Some(Value::Int64(n)) => *n >= *lo && *n <= *hi,
15144            _ => false,
15145        },
15146        Condition::RangeF64 {
15147            column_id,
15148            lo,
15149            lo_inclusive,
15150            hi,
15151            hi_inclusive,
15152        } => match row.columns.get(column_id) {
15153            Some(Value::Float64(n)) => {
15154                let lo_ok = if *lo_inclusive { *n >= *lo } else { *n > *lo };
15155                let hi_ok = if *hi_inclusive { *n <= *hi } else { *n < *hi };
15156                lo_ok && hi_ok
15157            }
15158            _ => false,
15159        },
15160        Condition::FmContains { column_id, pattern } => match row.columns.get(column_id) {
15161            Some(Value::Bytes(b)) => {
15162                !pattern.is_empty() && b.windows(pattern.len()).any(|w| w == &pattern[..])
15163            }
15164            _ => false,
15165        },
15166        Condition::FmContainsAll {
15167            column_id,
15168            patterns,
15169        } => match row.columns.get(column_id) {
15170            Some(Value::Bytes(b)) => patterns
15171                .iter()
15172                .all(|pat| !pat.is_empty() && b.windows(pat.len()).any(|w| w == &pat[..])),
15173            _ => false,
15174        },
15175        Condition::Ann { .. }
15176        | Condition::SparseMatch { .. }
15177        | Condition::MinHashSimilar { .. } => true,
15178        Condition::IsNull { column_id } => {
15179            matches!(row.columns.get(column_id), Some(Value::Null) | None)
15180        }
15181        Condition::IsNotNull { column_id } => {
15182            !matches!(row.columns.get(column_id), Some(Value::Null) | None)
15183        }
15184    }
15185}
15186
15187/// Coerce a cell to `f64` for Sum/Avg (Int64/Float64 only).
15188fn as_f64(v: Option<&Value>) -> Option<f64> {
15189    match v {
15190        Some(Value::Int64(n)) => Some(*n as f64),
15191        Some(Value::Float64(f)) => Some(*f),
15192        _ => None,
15193    }
15194}
15195
15196/// One-pass vectorized accumulation of `(non-null count, sum, min, max)` over an
15197/// Int64 column streamed through `cursor`. The inner loop over a contiguous
15198/// `&[i64]` autovectorizes (SIMD) for the all-non-null prefix.
15199fn accumulate_int(
15200    cursor: &mut dyn crate::cursor::Cursor,
15201    control: Option<&crate::ExecutionControl>,
15202) -> Result<(u64, i128, i64, i64)> {
15203    let mut count: u64 = 0;
15204    let mut sum: i128 = 0;
15205    let mut mn: i64 = i64::MAX;
15206    let mut mx: i64 = i64::MIN;
15207    while let Some(cols) = cursor.next_batch()? {
15208        execution_checkpoint(control, 0)?;
15209        if let Some(crate::columnar::NativeColumn::Int64 { data, validity }) = cols.first() {
15210            if crate::columnar::all_non_null(validity, data.len()) {
15211                // All-non-null: vectorized sum/min/max with no per-element branch.
15212                count += data.len() as u64;
15213                for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15214                    execution_checkpoint(control, chunk_index * 1024)?;
15215                    sum += chunk.iter().map(|&v| v as i128).sum::<i128>();
15216                    mn = mn.min(*chunk.iter().min().unwrap_or(&mn));
15217                    mx = mx.max(*chunk.iter().max().unwrap_or(&mx));
15218                }
15219            } else {
15220                for (i, &v) in data.iter().enumerate() {
15221                    execution_checkpoint(control, i)?;
15222                    if crate::columnar::validity_bit(validity, i) {
15223                        count += 1;
15224                        sum += v as i128;
15225                        mn = mn.min(v);
15226                        mx = mx.max(v);
15227                    }
15228                }
15229            }
15230        }
15231    }
15232    Ok((count, sum, mn, mx))
15233}
15234
15235/// f64 analogue of [`accumulate_int`].
15236fn accumulate_float(
15237    cursor: &mut dyn crate::cursor::Cursor,
15238    control: Option<&crate::ExecutionControl>,
15239) -> Result<(u64, f64, f64, f64)> {
15240    let mut count: u64 = 0;
15241    let mut sum: f64 = 0.0;
15242    let mut mn: f64 = f64::INFINITY;
15243    let mut mx: f64 = f64::NEG_INFINITY;
15244    while let Some(cols) = cursor.next_batch()? {
15245        execution_checkpoint(control, 0)?;
15246        if let Some(crate::columnar::NativeColumn::Float64 { data, validity }) = cols.first() {
15247            if crate::columnar::all_non_null(validity, data.len()) {
15248                count += data.len() as u64;
15249                for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15250                    execution_checkpoint(control, chunk_index * 1024)?;
15251                    sum += chunk.iter().sum::<f64>();
15252                    mn = mn.min(chunk.iter().copied().fold(f64::INFINITY, f64::min));
15253                    mx = mx.max(chunk.iter().copied().fold(f64::NEG_INFINITY, f64::max));
15254                }
15255            } else {
15256                for (i, &v) in data.iter().enumerate() {
15257                    execution_checkpoint(control, i)?;
15258                    if crate::columnar::validity_bit(validity, i) {
15259                        count += 1;
15260                        sum += v;
15261                        mn = mn.min(v);
15262                        mx = mx.max(v);
15263                    }
15264                }
15265            }
15266        }
15267    }
15268    Ok((count, sum, mn, mx))
15269}
15270
15271#[inline]
15272fn execution_checkpoint(control: Option<&crate::ExecutionControl>, index: usize) -> Result<()> {
15273    if index.is_multiple_of(256) {
15274        control
15275            .map(crate::ExecutionControl::checkpoint)
15276            .transpose()?;
15277    }
15278    Ok(())
15279}
15280
15281fn pack_int(agg: NativeAgg, count: u64, sum: i128, mn: i64, mx: i64) -> NativeAggResult {
15282    if count == 0 && !matches!(agg, NativeAgg::Count) {
15283        return NativeAggResult::Null;
15284    }
15285    match agg {
15286        NativeAgg::Count => NativeAggResult::Count(count),
15287        // i64 overflow on Sum ⇒ SQL NULL (DataFusion errors on overflow; null is
15288        // a safe, non-misleading fallback rather than a saturated wrong value).
15289        NativeAgg::Sum => match sum.try_into() {
15290            Ok(v) => NativeAggResult::Int(v),
15291            Err(_) => NativeAggResult::Null,
15292        },
15293        NativeAgg::Min => NativeAggResult::Int(mn),
15294        NativeAgg::Max => NativeAggResult::Int(mx),
15295        NativeAgg::Avg => NativeAggResult::Float((sum as f64) / (count as f64)),
15296    }
15297}
15298
15299fn pack_float(agg: NativeAgg, count: u64, sum: f64, mn: f64, mx: f64) -> NativeAggResult {
15300    if count == 0 && !matches!(agg, NativeAgg::Count) {
15301        return NativeAggResult::Null;
15302    }
15303    match agg {
15304        NativeAgg::Count => NativeAggResult::Count(count),
15305        NativeAgg::Sum => NativeAggResult::Float(sum),
15306        NativeAgg::Min => NativeAggResult::Float(mn),
15307        NativeAgg::Max => NativeAggResult::Float(mx),
15308        NativeAgg::Avg => NativeAggResult::Float(sum / (count as f64)),
15309    }
15310}
15311
15312/// Aggregate per-page `min`/`max`/`null_count` into a column-wide i64 triple.
15313/// Returns `None` if no page contributes a non-null min/max (all-null column).
15314fn agg_int(
15315    stats: &[crate::page::PageStat],
15316    decode: fn(Option<&[u8]>) -> Option<i64>,
15317) -> Option<(Option<i64>, Option<i64>, u64)> {
15318    let (mut mn, mut mx, mut nulls) = (i64::MAX, i64::MIN, 0u64);
15319    let mut any = false;
15320    for s in stats {
15321        if let Some(v) = decode(s.min.as_deref()) {
15322            mn = mn.min(v);
15323            any = true;
15324        }
15325        if let Some(v) = decode(s.max.as_deref()) {
15326            mx = mx.max(v);
15327            any = true;
15328        }
15329        nulls += s.null_count;
15330    }
15331    any.then_some((Some(mn), Some(mx), nulls))
15332}
15333
15334/// f64 analogue of [`agg_int`] (compares as f64, not as bit patterns).
15335fn agg_float(
15336    stats: &[crate::page::PageStat],
15337    decode: fn(Option<&[u8]>) -> Option<f64>,
15338) -> Option<(Option<f64>, Option<f64>, u64)> {
15339    let (mut mn, mut mx, mut nulls) = (f64::INFINITY, f64::NEG_INFINITY, 0u64);
15340    let mut any = false;
15341    for s in stats {
15342        if let Some(v) = decode(s.min.as_deref()) {
15343            mn = mn.min(v);
15344            any = true;
15345        }
15346        if let Some(v) = decode(s.max.as_deref()) {
15347            mx = mx.max(v);
15348            any = true;
15349        }
15350        nulls += s.null_count;
15351    }
15352    any.then_some((Some(mn), Some(mx), nulls))
15353}
15354
15355/// The four maintained secondary-index maps, keyed by column id.
15356type SecondaryIndexes = (
15357    HashMap<u16, BitmapIndex>,
15358    HashMap<u16, AnnIndex>,
15359    HashMap<u16, FmIndex>,
15360    HashMap<u16, SparseIndex>,
15361    HashMap<u16, MinHashIndex>,
15362);
15363
15364fn empty_indexes(schema: &Schema) -> SecondaryIndexes {
15365    let mut bitmap = HashMap::new();
15366    let mut ann = HashMap::new();
15367    let mut fm = HashMap::new();
15368    let mut sparse = HashMap::new();
15369    let mut minhash = HashMap::new();
15370    for idef in &schema.indexes {
15371        match idef.kind {
15372            IndexKind::Bitmap => {
15373                bitmap.insert(idef.column_id, BitmapIndex::new());
15374            }
15375            IndexKind::Ann => {
15376                let dim = schema
15377                    .columns
15378                    .iter()
15379                    .find(|c| c.id == idef.column_id)
15380                    .and_then(|c| match c.ty {
15381                        TypeId::Embedding { dim } => Some(dim as usize),
15382                        _ => None,
15383                    })
15384                    .unwrap_or(0);
15385                let options = idef.options.ann.clone().unwrap_or_default();
15386                ann.insert(
15387                    idef.column_id,
15388                    AnnIndex::with_full_options(
15389                        dim,
15390                        options.m,
15391                        options.ef_construction,
15392                        options.ef_search,
15393                        &options,
15394                    ),
15395                );
15396            }
15397            IndexKind::FmIndex => {
15398                fm.insert(idef.column_id, FmIndex::new());
15399            }
15400            IndexKind::Sparse => {
15401                sparse.insert(idef.column_id, SparseIndex::new());
15402            }
15403            IndexKind::MinHash => {
15404                let options = idef.options.minhash.clone().unwrap_or_default();
15405                minhash.insert(
15406                    idef.column_id,
15407                    MinHashIndex::with_options(options.permutations, options.bands),
15408                );
15409            }
15410            _ => {}
15411        }
15412    }
15413    (bitmap, ann, fm, sparse, minhash)
15414}
15415
15416const ALTER_COLUMN_PROTECTED_FLAGS: u32 = ColumnFlags::PRIMARY_KEY
15417    | ColumnFlags::AUTO_INCREMENT
15418    | ColumnFlags::ENCRYPTED
15419    | ColumnFlags::ENCRYPTED_INDEXABLE
15420    | ColumnFlags::EMBEDDING_BINARY_QUANTIZED;
15421
15422fn validate_alter_column_flags(old: ColumnFlags, new: ColumnFlags) -> Result<()> {
15423    if (old.bits() ^ new.bits()) & ALTER_COLUMN_PROTECTED_FLAGS != 0 {
15424        return Err(MongrelError::Schema(
15425            "ALTER COLUMN may only change NULLABLE; primary key, auto-increment, encryption, and embedding flags are immutable".into(),
15426        ));
15427    }
15428    Ok(())
15429}
15430
15431fn validate_alter_column_type(
15432    schema: &Schema,
15433    old: &ColumnDef,
15434    next: &ColumnDef,
15435    has_stored_versions: bool,
15436) -> Result<()> {
15437    if old.ty == next.ty {
15438        return Ok(());
15439    }
15440    if schema.indexes.iter().any(|i| i.column_id == old.id) {
15441        return Err(MongrelError::Schema(format!(
15442            "ALTER COLUMN TYPE is not supported for indexed column '{}'",
15443            old.name
15444        )));
15445    }
15446    if !has_stored_versions || storage_compatible_type_change(old.ty.clone(), next.ty.clone()) {
15447        return Ok(());
15448    }
15449    Err(MongrelError::Schema(format!(
15450        "ALTER COLUMN TYPE from {:?} to {:?} requires an empty column or a representation-compatible type",
15451        old.ty, next.ty
15452    )))
15453}
15454
15455fn storage_compatible_type_change(old: TypeId, new: TypeId) -> bool {
15456    matches!(
15457        (old, new),
15458        (TypeId::Int64, TypeId::TimestampNanos) | (TypeId::TimestampNanos, TypeId::Int64)
15459    )
15460}
15461
15462/// True when every row carries an `Int64` PK value and the sequence is
15463/// strictly increasing — no intra-batch duplicate is possible. The row-major
15464/// mirror of `native_int64_strictly_increasing` (the `bulk_pk_winner_indices`
15465/// fast path), used by `apply_put_rows_inner` to skip upsert probing for
15466/// append-style batches.
15467fn rows_pk_strictly_increasing(rows: &[Row], pk_id: u16) -> bool {
15468    let mut prev: Option<i64> = None;
15469    for r in rows {
15470        match r.columns.get(&pk_id) {
15471            Some(Value::Int64(v)) => {
15472                if prev.is_some_and(|p| p >= *v) {
15473                    return false;
15474                }
15475                prev = Some(*v);
15476            }
15477            _ => return false,
15478        }
15479    }
15480    true
15481}
15482
15483#[allow(clippy::too_many_arguments)]
15484fn index_into(
15485    schema: &Schema,
15486    row: &Row,
15487    hot: &mut HotIndex,
15488    bitmap: &mut HashMap<u16, BitmapIndex>,
15489    ann: &mut HashMap<u16, AnnIndex>,
15490    fm: &mut HashMap<u16, FmIndex>,
15491    sparse: &mut HashMap<u16, SparseIndex>,
15492    minhash: &mut HashMap<u16, MinHashIndex>,
15493) {
15494    for idef in &schema.indexes {
15495        let Some(val) = row.columns.get(&idef.column_id) else {
15496            continue;
15497        };
15498        match idef.kind {
15499            IndexKind::Bitmap => {
15500                if let Some(b) = bitmap.get_mut(&idef.column_id) {
15501                    b.insert(val.encode_key(), row.row_id);
15502                }
15503            }
15504            IndexKind::Ann => {
15505                if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15506                    if let Some(meta) = val.generated_embedding_metadata() {
15507                        // P1.5-T3: pending/failed generated vectors stay out of ANN.
15508                        if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15509                            continue;
15510                        }
15511                        if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15512                            .is_err()
15513                        {
15514                            continue;
15515                        }
15516                    }
15517                    a.insert_validated(v, row.row_id);
15518                }
15519            }
15520            IndexKind::FmIndex => {
15521                if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15522                    f.insert(b.clone(), row.row_id);
15523                }
15524            }
15525            IndexKind::Sparse => {
15526                if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15527                    // A sparse vector is stored as a bincode'd `Vec<(u32, f32)>`
15528                    // in a Bytes column (SPLADE weights in, retrieval out).
15529                    if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15530                        s.insert(&terms, row.row_id);
15531                    }
15532                }
15533            }
15534            IndexKind::MinHash => {
15535                if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15536                    // The set is a JSON array (the Kit's `set_similarity` shape);
15537                    // tokenize + hash its members into the MinHash signature.
15538                    let tokens = crate::index::token_hashes_from_bytes(b);
15539                    mh.insert(&tokens, row.row_id);
15540                }
15541            }
15542            _ => {}
15543        }
15544    }
15545    if let Some(pk_col) = schema.primary_key() {
15546        if let Some(pk_val) = row.columns.get(&pk_col.id) {
15547            hot.insert(pk_val.encode_key(), row.row_id);
15548        }
15549    }
15550}
15551
15552/// Index a row into a single specific index (used for partial indexes where
15553/// only matching indexes should receive the row).
15554#[allow(clippy::too_many_arguments)]
15555fn index_into_single(
15556    idef: &IndexDef,
15557    _schema: &Schema,
15558    row: &Row,
15559    _hot: &mut HotIndex,
15560    bitmap: &mut HashMap<u16, BitmapIndex>,
15561    ann: &mut HashMap<u16, AnnIndex>,
15562    fm: &mut HashMap<u16, FmIndex>,
15563    sparse: &mut HashMap<u16, SparseIndex>,
15564    minhash: &mut HashMap<u16, MinHashIndex>,
15565) {
15566    let Some(val) = row.columns.get(&idef.column_id) else {
15567        return;
15568    };
15569    match idef.kind {
15570        IndexKind::Bitmap => {
15571            if let Some(b) = bitmap.get_mut(&idef.column_id) {
15572                b.insert(val.encode_key(), row.row_id);
15573            }
15574        }
15575        IndexKind::Ann => {
15576            if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15577                if let Some(meta) = val.generated_embedding_metadata() {
15578                    // P1.5-T3: pending/failed generated vectors stay out of ANN.
15579                    if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15580                        return;
15581                    }
15582                    if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15583                        .is_err()
15584                    {
15585                        return;
15586                    }
15587                }
15588                a.insert_validated(v, row.row_id);
15589            }
15590        }
15591        IndexKind::FmIndex => {
15592            if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15593                f.insert(b.clone(), row.row_id);
15594            }
15595        }
15596        IndexKind::Sparse => {
15597            if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15598                if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15599                    s.insert(&terms, row.row_id);
15600                }
15601            }
15602        }
15603        IndexKind::MinHash => {
15604            if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15605                let tokens = crate::index::token_hashes_from_bytes(b);
15606                mh.insert(&tokens, row.row_id);
15607            }
15608        }
15609        _ => {}
15610    }
15611}
15612
15613/// Evaluate a partial-index predicate against a row. Supports the most common
15614/// patterns: `"column IS NOT NULL"` and `"column IS NULL"`. More complex
15615/// expressions require a full SQL evaluator in core (future work); the
15616/// predicate string is stored verbatim and this function provides a pragmatic
15617/// subset. Returns `true` if the row should be indexed.
15618fn eval_partial_predicate(
15619    pred: &str,
15620    columns_map: &HashMap<u16, &Value>,
15621    name_to_id: &HashMap<&str, u16>,
15622) -> bool {
15623    let lower = pred.trim().to_ascii_lowercase();
15624    // Pattern: "column_name IS NOT NULL"
15625    if let Some(rest) = lower.strip_suffix(" is not null") {
15626        let col_name = rest.trim();
15627        if let Some(col_id) = name_to_id.get(col_name) {
15628            return columns_map
15629                .get(col_id)
15630                .is_some_and(|v| !matches!(v, Value::Null));
15631        }
15632    }
15633    // Pattern: "column_name IS NULL"
15634    if let Some(rest) = lower.strip_suffix(" is null") {
15635        let col_name = rest.trim();
15636        if let Some(col_id) = name_to_id.get(col_name) {
15637            return columns_map
15638                .get(col_id)
15639                .is_none_or(|v| matches!(v, Value::Null));
15640        }
15641    }
15642    // Unknown predicate syntax: index the row (conservative — better to
15643    // over-index than to miss rows).
15644    true
15645}
15646
15647/// Per-element index key for the typed bulk-index path (Phase 14.2): mirrors
15648/// `index_into` on a `tokenized_for_indexes(row)` — encodes the element the way
15649/// [`Value::encode_key`] would, then applies the column's
15650/// `ENCRYPTED_INDEXABLE` tokenization (HMAC-eq / OPE) so bitmap/HOT keys match
15651/// what the incremental path stores. Returns `None` for null slots.
15652#[allow(dead_code)]
15653fn bulk_index_key(
15654    column_keys: &HashMap<u16, ([u8; 32], u8)>,
15655    column_id: u16,
15656    ty: TypeId,
15657    col: &columnar::NativeColumn,
15658    i: usize,
15659) -> Option<Vec<u8>> {
15660    let encoded = columnar::encode_key_native(ty, col, i)?;
15661    {
15662        use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
15663        if let Some((key, scheme)) = column_keys.get(&column_id) {
15664            return Some(match (*scheme, col) {
15665                (SCHEME_HMAC_EQ, _) => hmac_token(key, &encoded).to_vec(),
15666                (_, columnar::NativeColumn::Int64 { data, .. }) => {
15667                    ope_token_i64(key, data[i]).to_vec()
15668                }
15669                (_, columnar::NativeColumn::Float64 { data, .. }) => {
15670                    ope_token_f64(key, data[i]).to_vec()
15671                }
15672                _ => hmac_token(key, &encoded).to_vec(),
15673            });
15674        }
15675    }
15676    Some(encoded)
15677}
15678
15679pub(crate) fn write_schema(dir: &Path, schema: &Schema) -> Result<()> {
15680    write_schema_with_after(dir, schema, || {})
15681}
15682
15683pub(crate) fn write_schema_durable(
15684    root: &crate::durable_file::DurableRoot,
15685    schema: &Schema,
15686) -> Result<()> {
15687    write_schema_durable_with_after(root, schema, || {})
15688}
15689
15690fn write_schema_with_after<F>(dir: &Path, schema: &Schema, after_publish: F) -> Result<()>
15691where
15692    F: FnOnce(),
15693{
15694    let json = serde_json::to_string_pretty(schema)
15695        .map_err(|e| MongrelError::Schema(format!("encode schema: {e}")))?;
15696    crate::durable_file::write_atomic_with_after(
15697        &dir.join(SCHEMA_FILENAME),
15698        json.as_bytes(),
15699        after_publish,
15700    )?;
15701    Ok(())
15702}
15703
15704fn write_schema_durable_with_after<F>(
15705    root: &crate::durable_file::DurableRoot,
15706    schema: &Schema,
15707    after_publish: F,
15708) -> Result<()>
15709where
15710    F: FnOnce(),
15711{
15712    let json = serde_json::to_string_pretty(schema)
15713        .map_err(|error| MongrelError::Schema(format!("encode schema: {error}")))?;
15714    root.write_atomic_with_after(SCHEMA_FILENAME, json.as_bytes(), after_publish)?;
15715    Ok(())
15716}
15717
15718fn checkpoint_current_schema(table: &mut Table) -> Result<()> {
15719    let mut schema_published = false;
15720    let schema_result = match table._root_guard.as_deref() {
15721        Some(root) => write_schema_durable_with_after(root, &table.schema, || {
15722            schema_published = true;
15723        }),
15724        None => write_schema_with_after(&table.dir, &table.schema, || {
15725            schema_published = true;
15726        }),
15727    };
15728    if schema_result.is_err() && !schema_published {
15729        return schema_result;
15730    }
15731    match table.persist_manifest(table.current_epoch()) {
15732        Ok(()) => Ok(()),
15733        Err(manifest_error) => Err(match schema_result {
15734            Ok(()) => manifest_error,
15735            Err(schema_error) => MongrelError::Other(format!(
15736                "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
15737            )),
15738        }),
15739    }
15740}
15741
15742fn read_schema(dir: &Path) -> Result<Schema> {
15743    let file = crate::durable_file::open_regular_nofollow(&dir.join(SCHEMA_FILENAME))?;
15744    read_schema_file(file)
15745}
15746
15747fn read_schema_file(file: std::fs::File) -> Result<Schema> {
15748    const MAX_SCHEMA_BYTES: u64 = 16 * 1024 * 1024;
15749    use std::io::Read;
15750
15751    let length = file.metadata()?.len();
15752    if length > MAX_SCHEMA_BYTES {
15753        return Err(MongrelError::ResourceLimitExceeded {
15754            resource: "schema bytes",
15755            requested: usize::try_from(length).unwrap_or(usize::MAX),
15756            limit: MAX_SCHEMA_BYTES as usize,
15757        });
15758    }
15759    let mut bytes = Vec::with_capacity(length as usize);
15760    file.take(MAX_SCHEMA_BYTES + 1).read_to_end(&mut bytes)?;
15761    if bytes.len() as u64 != length {
15762        return Err(MongrelError::Schema(
15763            "schema length changed while reading".into(),
15764        ));
15765    }
15766    serde_json::from_slice(&bytes).map_err(|e| MongrelError::Schema(format!("decode schema: {e}")))
15767}
15768
15769fn preflight_standalone_open(
15770    dir: &Path,
15771    runs_root: Option<&crate::durable_file::DurableRoot>,
15772    idx_root: Option<&crate::durable_file::DurableRoot>,
15773    manifest: &Manifest,
15774    schema: &Schema,
15775    records: &[crate::wal::Record],
15776    kek: Option<Arc<Kek>>,
15777) -> Result<()> {
15778    crate::wal::validate_shared_transaction_framing(records)?;
15779    if manifest.schema_id > schema.schema_id
15780        || manifest.flushed_epoch > manifest.current_epoch
15781        || manifest.global_idx_epoch > manifest.current_epoch
15782        || manifest.next_row_id == u64::MAX
15783        || manifest.auto_inc_next < 0
15784        || manifest.auto_inc_next == i64::MAX
15785        || (schema.auto_increment_column().is_none() && manifest.auto_inc_next != 0)
15786    {
15787        return Err(MongrelError::InvalidArgument(
15788            "manifest counters or schema identity are invalid".into(),
15789        ));
15790    }
15791    let mut run_ids = HashSet::new();
15792    let mut maximum_row_id = None::<u64>;
15793    for run in &manifest.runs {
15794        if run.run_id >= u64::MAX as u128
15795            || !run_ids.insert(run.run_id)
15796            || run.epoch_created > manifest.current_epoch
15797        {
15798            return Err(MongrelError::InvalidArgument(
15799                "manifest contains an invalid or duplicate active run".into(),
15800            ));
15801        }
15802        let mut reader = match runs_root {
15803            Some(root) => RunReader::open_file(
15804                root.open_regular(format!("r-{}.sr", run.run_id as u64))?,
15805                schema.clone(),
15806                kek.clone(),
15807            )?,
15808            None => RunReader::open(
15809                dir.join(RUNS_DIR)
15810                    .join(format!("r-{}.sr", run.run_id as u64)),
15811                schema.clone(),
15812                kek.clone(),
15813            )?,
15814        };
15815        let header = reader.header();
15816        if header.run_id != run.run_id
15817            || header.level != run.level
15818            || header.row_count != run.row_count
15819            || !header.is_uniform_epoch() && header.epoch_created != run.epoch_created
15820            || header.is_uniform_epoch() && header.epoch_created != 0
15821            || header.schema_id > schema.schema_id
15822        {
15823            return Err(MongrelError::InvalidArgument(format!(
15824                "run {} differs from its manifest",
15825                run.run_id
15826            )));
15827        }
15828        if header.row_count != 0 {
15829            maximum_row_id = Some(
15830                maximum_row_id.map_or(header.max_row_id, |value| value.max(header.max_row_id)),
15831            );
15832        }
15833        reader.validate_all_pages()?;
15834    }
15835    if maximum_row_id.is_some_and(|maximum| manifest.next_row_id <= maximum) {
15836        return Err(MongrelError::InvalidArgument(
15837            "manifest next_row_id does not advance beyond persisted rows".into(),
15838        ));
15839    }
15840    for run in &manifest.retiring {
15841        if run.run_id >= u64::MAX as u128
15842            || run.retire_epoch > manifest.current_epoch
15843            || !run_ids.insert(run.run_id)
15844        {
15845            return Err(MongrelError::InvalidArgument(
15846                "manifest contains an invalid or duplicate retired run".into(),
15847            ));
15848        }
15849    }
15850    let idx_dek = kek.as_ref().map(|key| key.derive_idx_key());
15851    match idx_root {
15852        Some(root) => {
15853            global_idx::read_root(root, manifest.table_id, schema, idx_dek.as_deref())?;
15854        }
15855        None => {
15856            global_idx::read(dir, manifest.table_id, schema, idx_dek.as_deref())?;
15857        }
15858    }
15859
15860    let committed = records
15861        .iter()
15862        .filter_map(|record| match record.op {
15863            Op::TxnCommit { epoch, .. } => Some((record.txn_id, epoch)),
15864            _ => None,
15865        })
15866        .collect::<HashMap<_, _>>();
15867    for record in records {
15868        let Some(&_commit_epoch) = committed.get(&record.txn_id) else {
15869            continue;
15870        };
15871        match &record.op {
15872            Op::Put { table_id, rows } => {
15873                if *table_id != manifest.table_id {
15874                    return Err(MongrelError::CorruptWal {
15875                        offset: record.seq.0,
15876                        reason: format!(
15877                            "private WAL record references table {table_id}, expected {}",
15878                            manifest.table_id
15879                        ),
15880                    });
15881                }
15882                let rows: Vec<Row> =
15883                    bincode::deserialize(rows).map_err(|error| MongrelError::CorruptWal {
15884                        offset: record.seq.0,
15885                        reason: format!("committed Put payload could not be decoded: {error}"),
15886                    })?;
15887                for row in rows {
15888                    if row.deleted || row.row_id.0 == u64::MAX {
15889                        return Err(MongrelError::CorruptWal {
15890                            offset: record.seq.0,
15891                            reason: "committed Put contains an invalid row identity".into(),
15892                        });
15893                    }
15894                    let cells = row.columns.into_iter().collect::<Vec<_>>();
15895                    schema
15896                        .validate_values(&cells)
15897                        .map_err(|error| MongrelError::CorruptWal {
15898                            offset: record.seq.0,
15899                            reason: format!("committed Put violates table schema: {error}"),
15900                        })?;
15901                    if schema.auto_increment_column().is_some_and(|column| {
15902                        matches!(
15903                            cells.iter().find(|(id, _)| *id == column.id),
15904                            Some((_, Value::Int64(value))) if *value == i64::MAX
15905                        )
15906                    }) {
15907                        return Err(MongrelError::CorruptWal {
15908                            offset: record.seq.0,
15909                            reason: "committed Put exhausts AUTO_INCREMENT".into(),
15910                        });
15911                    }
15912                }
15913            }
15914            Op::Delete { table_id, .. } | Op::TruncateTable { table_id }
15915                if *table_id != manifest.table_id =>
15916            {
15917                return Err(MongrelError::CorruptWal {
15918                    offset: record.seq.0,
15919                    reason: format!(
15920                        "private WAL record references table {table_id}, expected {}",
15921                        manifest.table_id
15922                    ),
15923                });
15924            }
15925            Op::TxnCommit { added_runs, .. } if !added_runs.is_empty() => {
15926                return Err(MongrelError::CorruptWal {
15927                    offset: record.seq.0,
15928                    reason: "private WAL contains shared spilled-run metadata".into(),
15929                });
15930            }
15931            _ => {}
15932        }
15933    }
15934    Ok(())
15935}
15936
15937fn next_wal_segment(wal_dir: &Path) -> Result<PathBuf> {
15938    Ok(wal_dir.join(format!("seg-{:06}.wal", next_wal_number(wal_dir)?)))
15939}
15940
15941fn wal_segment_number(path: &Path) -> Option<u64> {
15942    path.file_stem()
15943        .and_then(|stem| stem.to_str())
15944        .and_then(|stem| stem.strip_prefix("seg-"))
15945        .and_then(|number| number.parse().ok())
15946}
15947
15948fn latest_wal_segment(wal_dir: &Path) -> Result<Option<PathBuf>> {
15949    let n = list_wal_numbers(wal_dir)?;
15950    Ok(n.map(|max| wal_dir.join(format!("seg-{max:06}.wal"))))
15951}
15952
15953fn next_wal_number(wal_dir: &Path) -> Result<u32> {
15954    list_wal_numbers(wal_dir)?
15955        .map(|maximum| {
15956            maximum
15957                .checked_add(1)
15958                .ok_or_else(|| MongrelError::Full("WAL segment namespace exhausted".into()))
15959        })
15960        .unwrap_or(Ok(0))
15961}
15962
15963fn list_wal_numbers(wal_dir: &Path) -> Result<Option<u32>> {
15964    let mut max_n = None;
15965    let entries = match std::fs::read_dir(wal_dir) {
15966        Ok(entries) => entries,
15967        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
15968        Err(error) => return Err(error.into()),
15969    };
15970    for entry in entries {
15971        let entry = entry?;
15972        let fname = entry.file_name();
15973        let Some(s) = fname.to_str() else {
15974            continue;
15975        };
15976        let Some(stripped) = s.strip_prefix("seg-") else {
15977            continue;
15978        };
15979        let Some(number) = stripped.strip_suffix(".wal") else {
15980            return Err(MongrelError::CorruptWal {
15981                offset: 0,
15982                reason: format!("malformed WAL segment name {s:?}"),
15983            });
15984        };
15985        let n = number
15986            .parse::<u32>()
15987            .map_err(|_| MongrelError::CorruptWal {
15988                offset: 0,
15989                reason: format!("malformed WAL segment name {s:?}"),
15990            })?;
15991        if s != format!("seg-{n:06}.wal") || !entry.file_type()?.is_file() {
15992            return Err(MongrelError::CorruptWal {
15993                offset: n as u64,
15994                reason: format!("noncanonical or nonregular WAL segment {s:?}"),
15995            });
15996        }
15997        max_n = Some(max_n.map(|m: u32| m.max(n)).unwrap_or(n));
15998    }
15999    Ok(max_n)
16000}
16001
16002// =========================================================================
16003// REM-001: full HLC authority across multi-run merge paths.
16004//
16005// These tests are the canonical inversion fixture from spec §6.1 / §9:
16006//
16007//   Run A:  epoch=low    HLC=high   payload="newer-by-HLC"
16008//   Run B:  epoch=high   HLC=low    payload="older-by-HLC"
16009//   Snapshot: epoch=10   HLC=600
16010//   Expected winner: "newer-by-HLC"
16011//
16012// Before the fix, every affected path stored `Option<(Epoch, ...)>` and
16013// picked the cross-run winner by `epoch > best_epoch`. An epoch-only fold
16014// selects Run B (high epoch) over Run A (low epoch), even though the HLC
16015// watermark is above both rows' stamps and HLC is the authority.
16016//
16017// The fix threads `commit_ts` through every cross-run fold via
16018// `crate::epoch::VersionStamp`; the run APIs return metadata-preserving
16019// `VersionedColumnValue` / `VersionVisibility` structs so the engine merge
16020// can compare candidates by full version stamp instead of epoch alone.
16021//
16022// The tests live inside this module so they can exercise private helpers
16023// (`values_for_rids_at`, `eligible_candidate_ids`, `rebuild_indexes_from_runs`).
16024// =========================================================================
16025
16026#[cfg(test)]
16027mod rem001_multi_run_hlc_authority {
16028    use super::*;
16029    use crate::epoch::{Epoch, Snapshot, VersionStamp};
16030    use crate::memtable::{Row, Value};
16031    use crate::query::{Condition, Query};
16032    use crate::schema::{ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
16033    use mongreldb_types::hlc::HlcTimestamp;
16034    use tempfile::tempdir;
16035
16036    fn hlc(physical_micros: u64) -> HlcTimestamp {
16037        HlcTimestamp {
16038            physical_micros,
16039            logical: 0,
16040            node_tiebreaker: 1,
16041        }
16042    }
16043
16044    fn pk_schema() -> Schema {
16045        Schema {
16046            schema_id: 1,
16047            columns: vec![
16048                ColumnDef {
16049                    id: 1,
16050                    name: "id".into(),
16051                    ty: TypeId::Int64,
16052                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16053                    default_value: None,
16054                    embedding_source: None,
16055                },
16056                ColumnDef {
16057                    id: 2,
16058                    name: "name".into(),
16059                    ty: TypeId::Bytes,
16060                    flags: ColumnFlags::empty(),
16061                    default_value: None,
16062                    embedding_source: None,
16063                },
16064            ],
16065            indexes: Vec::new(),
16066            colocation: vec![],
16067            constraints: Default::default(),
16068            clustered: false,
16069        }
16070    }
16071
16072    fn pk_schema_with_bitmap() -> Schema {
16073        Schema {
16074            schema_id: 1,
16075            columns: vec![
16076                ColumnDef {
16077                    id: 1,
16078                    name: "id".into(),
16079                    ty: TypeId::Int64,
16080                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16081                    default_value: None,
16082                    embedding_source: None,
16083                },
16084                ColumnDef {
16085                    id: 2,
16086                    name: "name".into(),
16087                    ty: TypeId::Bytes,
16088                    flags: ColumnFlags::empty(),
16089                    default_value: None,
16090                    embedding_source: None,
16091                },
16092            ],
16093            // Bitmap index on `name` so we can verify BitmapEq membership
16094            // reflects the HLC-winning run after the index rebuild.
16095            indexes: vec![IndexDef {
16096                name: "name_bitmap".into(),
16097                column_id: 2,
16098                kind: IndexKind::Bitmap,
16099                predicate: None,
16100                options: Default::default(),
16101            }],
16102            colocation: vec![],
16103            constraints: Default::default(),
16104            clustered: false,
16105        }
16106    }
16107
16108    fn encode_put(table_id: u64, row: &Row) -> Vec<u8> {
16109        use crate::database::StagedTxnWrite;
16110        bincode::serialize(&StagedTxnWrite::Put {
16111            table_id,
16112            rows: bincode::serialize(&vec![row.clone()]).expect("encode row"),
16113        })
16114        .expect("encode payload")
16115    }
16116
16117    /// Build the canonical two-run inversion:
16118    ///
16119    /// 1. apply the HLC-newer row first (lower committed_epoch because the
16120    ///    commit happens before any other write);
16121    /// 2. force-flush → `Run A` with `(epoch=1, HLC=500, payload="newer-by-HLC")`;
16122    /// 3. apply the HLC-older row second (higher committed_epoch because the
16123    ///    commit advances `epoch.visible()`);
16124    /// 4. force-flush → `Run B` with `(epoch=2, HLC=400, payload="older-by-HLC")`.
16125    ///
16126    /// After both flushes the table owns two immutable `.sr` files; Run A
16127    /// holds the HLC-newer payload, Run B holds the HLC-older payload, and
16128    /// Run B has the higher epoch because it was written later. Epoch-only
16129    /// cross-run folding picks Run B; HLC authority picks Run A.
16130    fn build_inverted_database(dir: &std::path::Path, schema: Schema) -> crate::Database {
16131        let db = crate::Database::create(dir).unwrap();
16132        db.create_table("t", schema).unwrap();
16133        let table_id = db.table_id("t").unwrap();
16134        let rid = RowId(7);
16135
16136        let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16137            .with_column(1, Value::Int64(7))
16138            .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()));
16139        let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16140            .with_column(1, Value::Int64(7))
16141            .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()));
16142
16143        db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16144            .expect("first apply");
16145        {
16146            let table = db.table("t").unwrap();
16147            table.lock().force_flush().expect("flush run A");
16148        }
16149
16150        db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16151            .expect("second apply");
16152        {
16153            let table = db.table("t").unwrap();
16154            table.lock().force_flush().expect("flush run B");
16155        }
16156
16157        db
16158    }
16159
16160    /// TTL fixture: HLC-newer row carries a far-future `ttl_ts`; HLC-older
16161    /// row carries a far-past `ttl_ts`. The TTL eligibility path must read
16162    /// the timestamp from the HLC-newer run (live), not from the HLC-older
16163    /// run (expired), and admit the rid.
16164    fn build_inverted_ttl_database(dir: &std::path::Path) -> crate::Database {
16165        let db = crate::Database::create(dir).unwrap();
16166        db.create_table("t", ttl_schema()).unwrap();
16167        let table_id = db.table_id("t").unwrap();
16168        let rid = RowId(7);
16169        let read_time_ns: i64 = 1_000_000_000;
16170        let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16171            .with_column(1, Value::Int64(7))
16172            .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()))
16173            .with_column(3, Value::Int64(read_time_ns + 60 * 1_000_000_000));
16174        let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16175            .with_column(1, Value::Int64(7))
16176            .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()))
16177            .with_column(3, Value::Int64(read_time_ns - 60 * 1_000_000_000));
16178
16179        db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16180            .expect("first apply");
16181        {
16182            let table = db.table("t").unwrap();
16183            table.lock().force_flush().expect("flush run A");
16184        }
16185        db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16186            .expect("second apply");
16187        {
16188            let table = db.table("t").unwrap();
16189            table.lock().force_flush().expect("flush run B");
16190        }
16191
16192        db
16193    }
16194
16195    fn ttl_schema() -> Schema {
16196        Schema {
16197            schema_id: 1,
16198            columns: vec![
16199                ColumnDef {
16200                    id: 1,
16201                    name: "id".into(),
16202                    ty: TypeId::Int64,
16203                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16204                    default_value: None,
16205                    embedding_source: None,
16206                },
16207                ColumnDef {
16208                    id: 2,
16209                    name: "name".into(),
16210                    ty: TypeId::Bytes,
16211                    flags: ColumnFlags::empty(),
16212                    default_value: None,
16213                    embedding_source: None,
16214                },
16215                ColumnDef {
16216                    id: 3,
16217                    name: "ttl_ts".into(),
16218                    ty: TypeId::Int64,
16219                    flags: ColumnFlags::empty(),
16220                    default_value: None,
16221                    embedding_source: None,
16222                },
16223            ],
16224            indexes: Vec::new(),
16225            colocation: vec![],
16226            constraints: Default::default(),
16227            clustered: false,
16228        }
16229    }
16230
16231    #[test]
16232    fn multi_run_rows_for_rids_uses_hlc_winner_when_epoch_is_inverted() {
16233        let dir = tempdir().unwrap();
16234        let db = build_inverted_database(dir.path(), pk_schema());
16235        let table = db.table("t").unwrap();
16236        let table = table.lock();
16237        // HLC-pinned snapshot at HLC=600 — both rows are visible, the
16238        // HLC-newer (Run A) must win. An epoch-only fold would silently
16239        // return Run B's "older-by-HLC" payload because its epoch=2 > 1.
16240        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16241        let rows = table
16242            .rows_for_rids(&[7], snap)
16243            .expect("rows_for_rids across two runs");
16244        assert_eq!(rows.len(), 1, "one row materialised across two runs");
16245        assert_eq!(
16246            rows[0].columns.get(&2),
16247            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16248            "multi-run rows_for_rids must honor HLC authority"
16249        );
16250    }
16251
16252    #[test]
16253    fn multi_run_projected_column_uses_hlc_winner_when_epoch_is_inverted() {
16254        let dir = tempdir().unwrap();
16255        let db = build_inverted_database(dir.path(), pk_schema());
16256        let table = db.table("t").unwrap();
16257        let table = table.lock();
16258        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16259        let projected = table
16260            .values_for_rids_at(&[7], 2, snap, i64::MAX)
16261            .expect("values_for_rids_at across two runs");
16262        assert_eq!(projected.len(), 1);
16263        assert_eq!(
16264            projected[0].1,
16265            Value::Bytes(b"newer-by-HLC".to_vec()),
16266            "multi-run projection must pick the HLC-newer column"
16267        );
16268    }
16269
16270    #[test]
16271    fn ann_candidate_eligibility_uses_hlc_winner_across_runs() {
16272        let dir = tempdir().unwrap();
16273        let db = build_inverted_database(dir.path(), pk_schema());
16274        let table = db.table("t").unwrap();
16275        let table = table.lock();
16276        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16277        // ANN/Sparse/MinHash all funnel through `eligible_candidate_ids`.
16278        // The HLC-newer row must survive the visibility fold.
16279        let eligible = table
16280            .eligible_candidate_ids(&[RowId(7)], 2, snap, None)
16281            .expect("eligibility across runs");
16282        assert!(
16283            eligible.contains(&RowId(7)),
16284            "HLC-newer rid must remain eligible across runs"
16285        );
16286    }
16287
16288    #[test]
16289    fn ttl_inverted_run_is_admitted_via_values_for_rids_at() {
16290        let dir = tempdir().unwrap();
16291        let db = build_inverted_ttl_database(dir.path());
16292        let table = db.table("t").unwrap();
16293        let table = table.lock();
16294        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16295        let now_ns: i64 = 1_000_000_000;
16296        // HLC-newer row's ttl_ts = now+60s (live); HLC-older row's ttl_ts =
16297        // now-60s (expired). The TTL eligibility path must read the
16298        // timestamp from the HLC-newer run (live) and surface the rid.
16299        let projected = table
16300            .values_for_rids_at(&[7], 2, snap, now_ns)
16301            .expect("ttl-aware projection");
16302        assert_eq!(projected.len(), 1, "TTL must admit the HLC-newer row");
16303        assert_eq!(
16304            projected[0].1,
16305            Value::Bytes(b"newer-by-HLC".to_vec()),
16306            "TTL must be read from the HLC-newer run; older run's timestamp is expired"
16307        );
16308    }
16309
16310    #[test]
16311    fn hot_candidate_inspection_uses_full_snapshot_for_run_versions() {
16312        // The HOT-fallback inspection path. `inspect_row_at` is invoked via
16313        // `Table::get` for rid-resolved lookups (the same merge logic
16314        // applies); the test exercises the production read path and asserts
16315        // the HLC-newer payload wins across runs.
16316        let dir = tempdir().unwrap();
16317        let db = build_inverted_database(dir.path(), pk_schema());
16318        let table = db.table("t").unwrap();
16319        let table = table.lock();
16320        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16321        let row = table
16322            .get(RowId(7), snap)
16323            .expect("Table::get across two runs");
16324        assert_eq!(
16325            row.columns.get(&2),
16326            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16327            "Table::get must surface the HLC-newer winner"
16328        );
16329    }
16330
16331    #[test]
16332    fn learned_range_rebuild_indexes_only_hlc_visible_winners() {
16333        // The learned-range rebuild path (`build_learned_ranges_inner`) is
16334        // only exercised when the table has exactly one run; we therefore
16335        // exercise the more general `rebuild_indexes_from_runs` path, which
16336        // performs the global merge. After rebuild the projected column for
16337        // rid=7 must come from the HLC-newer run even though Run B was
16338        // iterated last.
16339        let dir = tempdir().unwrap();
16340        let db = build_inverted_database(dir.path(), pk_schema());
16341        let handle = db.table("t").unwrap();
16342        let mut table = handle.lock();
16343        table.rebuild_indexes_from_runs().expect("rebuild");
16344        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16345        let rows = table
16346            .rows_for_rids(&[7], snap)
16347            .expect("post-rebuild rows_for_rids");
16348        assert_eq!(rows.len(), 1);
16349        assert_eq!(
16350            rows[0].columns.get(&2),
16351            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16352            "post-rebuild row must be the HLC-newer winner"
16353        );
16354    }
16355
16356    #[test]
16357    fn rebuild_indexes_uses_global_hlc_winners_not_run_iteration_order() {
16358        // REM-001 §7.6: after `rebuild_indexes` the primary-key lookup and
16359        // the Bitmap index membership must both reflect the HLC-winning run,
16360        // not whichever run was iterated last.
16361        //
16362        // Close + reopen preservation of the HLC-newer winner is covered by
16363        // `sorted_run_hlc_visibility::reopen_from_disk_preserves_hlc_visibility`
16364        // (and by the merged `pk_equality_fallback` path through `Table::get`).
16365        // Re-running it on top of `rebuild_indexes` would require writing two
16366        // `Op::Put` records for the same rid across two WAL segments, which
16367        // trips the recovery-time duplicate-row-id guard — that guard is
16368        // orthogonal to REM-001 and would mask the actual fix we want to
16369        // exercise here.
16370        let dir = tempdir().unwrap();
16371        let db = build_inverted_database(dir.path(), pk_schema_with_bitmap());
16372        let handle = db.table("t").unwrap();
16373        let mut table = handle.lock();
16374        table.rebuild_indexes_from_runs().expect("rebuild");
16375        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16376        // 1. PK lookup resolves to the HLC winner.
16377        let row = table.get(RowId(7), snap).expect("post-rebuild Table::get");
16378        assert_eq!(
16379            row.columns.get(&2),
16380            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16381            "PK lookup must resolve to the HLC-newer winner"
16382        );
16383        // 2. Bitmap membership: name="newer-by-HLC" must contain rid=7
16384        //    and name="older-by-HLC" must NOT (the older version was
16385        //    suppressed by the global merge before indexing).
16386        let query_newer = Query::new().and(Condition::BitmapEq {
16387            column_id: 2,
16388            value: b"newer-by-HLC".to_vec(),
16389        });
16390        let rows_newer = table.query(&query_newer).expect("bitmap eq newer");
16391        let rids_newer: Vec<u64> = rows_newer.iter().map(|r| r.row_id.0).collect();
16392        assert!(
16393            rids_newer.contains(&7),
16394            "bitmap must include the HLC-newer value (got {rids_newer:?})"
16395        );
16396        let query_older = Query::new().and(Condition::BitmapEq {
16397            column_id: 2,
16398            value: b"older-by-HLC".to_vec(),
16399        });
16400        let rows_older = table.query(&query_older).expect("bitmap eq older");
16401        let rids_older: Vec<u64> = rows_older.iter().map(|r| r.row_id.0).collect();
16402        assert!(
16403            !rids_older.contains(&7),
16404            "bitmap must NOT include the HLC-older value (got {rids_older:?})"
16405        );
16406    }
16407
16408    #[test]
16409    fn version_stamp_is_newer_than_matches_snapshot_rule() {
16410        // Unit test for the new VersionStamp helper: HLC-newer wins despite
16411        // a smaller epoch; both-unstamped falls back to epoch.
16412        let early = hlc(100);
16413        let late = hlc(200);
16414        let newer = VersionStamp {
16415            epoch: Epoch(9),
16416            commit_ts: Some(late),
16417        };
16418        let older = VersionStamp {
16419            epoch: Epoch(50),
16420            commit_ts: Some(early),
16421        };
16422        assert!(newer.is_newer_than(older));
16423        assert!(!older.is_newer_than(newer));
16424        let a = VersionStamp {
16425            epoch: Epoch(5),
16426            commit_ts: None,
16427        };
16428        let b = VersionStamp {
16429            epoch: Epoch(4),
16430            commit_ts: None,
16431        };
16432        assert!(a.is_newer_than(b));
16433    }
16434}