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    /// Table-level result cache (Phase 19.1): `canonical_query_key(conditions,
1259    /// projection, epoch)` → the survivor columns as typed `NativeColumn`s. Shared
1260    /// by the native `Condition` API and (via `query_cached`) the tool-call path,
1261    /// which previously had no caching (only the SQL `MongrelSession` cache did).
1262    /// Hardening (c): epoch is no longer in the key; instead, a `commit()`
1263    /// invalidates only entries whose footprint or condition-columns intersect
1264    /// the committed mutations, tracked in `pending_delete_rids` and
1265    /// `pending_put_cols`.
1266    result_cache: Arc<parking_lot::Mutex<ResultCache>>,
1267    /// WAL DEK (for frame-level encryption). None for plaintext tables.
1268    wal_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1269    /// RowIds deleted since the last `commit()` — used by fine-grained cache
1270    /// invalidation to check footprint intersection.
1271    pending_delete_rids: roaring::RoaringBitmap,
1272    /// Column IDs touched by `put`/`put_batch` since the last `commit()` — used
1273    /// by conservative insert-newly-matches invalidation.
1274    pending_put_cols: std::collections::HashSet<u16>,
1275    /// B1/B2: rows staged by `put`/`put_batch` on a mounted (shared-WAL) table
1276    /// but not yet applied to the memtable. They are re-stamped to the real
1277    /// assigned epoch in `commit` (never a speculative `visible+1`), so a
1278    /// concurrent reader can never observe them before their commit epoch.
1279    /// Always empty on a standalone (private-WAL) table, which applies inline.
1280    pending_rows: Vec<Row>,
1281    pending_rows_auto_inc: Vec<bool>,
1282    /// B1/B2: tombstones staged on a mounted table, applied at the assigned
1283    /// epoch in `commit` (mirror of `pending_rows`).
1284    pending_dels: Vec<RowId>,
1285    /// B1/B2: truncate staged on a mounted table, applied at the assigned epoch
1286    /// in `commit`; standalone tables also defer the physical clear until after
1287    /// the private WAL is fsynced.
1288    pending_truncate: Option<Epoch>,
1289    /// Engine-managed `AUTO_INCREMENT` counter (`None` for tables without an
1290    /// auto-increment primary key). See [`AutoIncState`].
1291    auto_inc: Option<AutoIncState>,
1292    /// Manifest-backed timestamp retention policy. Its wall-clock cutoff is
1293    /// evaluated once per read/compaction operation, never cached by epoch.
1294    ttl: Option<TtlPolicy>,
1295    /// Unified version-retention pin registry (S1C-004). Read generations
1296    /// register [`crate::retention::PinSource::ReadGeneration`] pins here;
1297    /// backup/PITR, replication, and online-index-build wiring from the
1298    /// `Database` layer is a follow-up (they can share this registry via
1299    /// [`Table::pin_registry`]). Compaction and version GC consult it through
1300    /// [`Table::min_active_snapshot`].
1301    pins: Arc<crate::retention::PinRegistry>,
1302    /// The atomically-published immutable read view (S1C-001). Writers store
1303    /// a replacement after sealing their active deltas; readers pin the
1304    /// loaded `Arc`. Read-generation clones get their own frozen cell so a
1305    /// later writer publish can never mutate a pinned generation's view.
1306    published: Arc<ArcSwap<ReadGeneration>>,
1307    /// The [`crate::retention::PinGuard`] keeping this generation's epoch
1308    /// retained. `None` on writer tables; `Some` on clones produced by
1309    /// [`Table::clone_read_generation`], released when the generation drops.
1310    /// Shared behind an `Arc` so cloning a generation shares one pin.
1311    read_generation_pin: Option<Arc<crate::retention::PinGuard>>,
1312    /// Lookup observability counters. HOT hits are the fast-path expectation;
1313    /// any fallback in a healthy workload is a regression to investigate.
1314    /// Each clone of `Table` (e.g. `clone_read_generation`) gets its own
1315    /// counters — readers and writers typically share via `Arc<Table>`.
1316    pub(crate) lookup_metrics: LookupMetrics,
1317    /// Per-table row-to-run lookup directory state (spec §1.2 / §8.4). Derived
1318    /// data only — open must not fail when the checkpoint is missing or stale
1319    /// (the existing range-scan fallback stays the safety net).
1320    run_lookup: RunLookupState,
1321}
1322
1323/// Per-table row-to-run lookup directory state (Issue 4 / spec §8.4).
1324///
1325/// The directory is *derived* state and never authoritative for correctness.
1326/// `complete == true` means the in-memory `directory` is consistent with the
1327/// active run set; `false` means the open path found a missing / corrupt /
1328/// stale checkpoint and the read path should fall back to range scans until
1329/// a rebuild finishes (or a fresh publish lands).
1330#[derive(Debug, Default, Clone)]
1331struct RunLookupState {
1332    directory: Option<std::sync::Arc<crate::run_lookup::RunLookupDirectory>>,
1333    fingerprint: u64,
1334    complete: bool,
1335}
1336
1337#[derive(Debug, Default)]
1338pub struct LookupMetrics {
1339    hot_lookup_hit: std::sync::atomic::AtomicU64,
1340    hot_lookup_fallback: std::sync::atomic::AtomicU64,
1341    hot_lookup_fallback_overlay_rows: std::sync::atomic::AtomicU64,
1342    hot_lookup_fallback_runs: std::sync::atomic::AtomicU64,
1343    result_cache_memory_hit: std::sync::atomic::AtomicU64,
1344    result_cache_disk_hit: std::sync::atomic::AtomicU64,
1345    result_cache_miss: std::sync::atomic::AtomicU64,
1346    result_cache_persistent_write_us: std::sync::atomic::AtomicU64,
1347    /// Point-get run probes: opened vs skipped via `run_row_id_ranges`.
1348    get_run_opened: std::sync::atomic::AtomicU64,
1349    get_run_skipped: std::sync::atomic::AtomicU64,
1350    // ---- TODO §1: point-lookup directory counters ----
1351    pub(crate) directory_lookup_hit: std::sync::atomic::AtomicU64,
1352    pub(crate) directory_lookup_fallback: std::sync::atomic::AtomicU64,
1353    pub(crate) directory_incomplete: std::sync::atomic::AtomicU64,
1354    pub(crate) directory_run_readers_opened: std::sync::atomic::AtomicU64,
1355    pub(crate) directory_early_stop_total: std::sync::atomic::AtomicU64,
1356    /// REM-004: directory returned an empty complete lookup for a row (no
1357    /// postings at all). Distinct from `directory_lookup_fallback`, which
1358    /// records only `UnavailableOrStale` (no usable directory). Incremented
1359    /// alongside `directory_lookup_hit` because the directory itself was
1360    /// usable; the answer just happened to be "no immutable runs".
1361    pub(crate) directory_complete_miss_total: std::sync::atomic::AtomicU64,
1362    // ---- TODO §2: persistent result cache async counters ----
1363    pub(crate) result_cache_persist_enqueued_total: std::sync::atomic::AtomicU64,
1364    pub(crate) result_cache_persist_coalesced_total: std::sync::atomic::AtomicU64,
1365    pub(crate) result_cache_persist_dropped_store_total: std::sync::atomic::AtomicU64,
1366    pub(crate) result_cache_persist_remove_total: std::sync::atomic::AtomicU64,
1367    pub(crate) result_cache_persist_stale_store_skipped_total: std::sync::atomic::AtomicU64,
1368    pub(crate) result_cache_persist_errors_total: std::sync::atomic::AtomicU64,
1369    pub(crate) result_cache_persist_shutdown_abandoned_total: std::sync::atomic::AtomicU64,
1370    pub(crate) result_cache_persist_queue_depth: std::sync::atomic::AtomicU64,
1371    // ---- TODO §5: HOT fallback per-reason counters ----
1372    pub(crate) hot_fallback_reasons: [std::sync::atomic::AtomicU64; 9],
1373    pub(crate) hot_fallback_overlay_versions_total: std::sync::atomic::AtomicU64,
1374    pub(crate) hot_fallback_runs_considered_total: std::sync::atomic::AtomicU64,
1375    pub(crate) hot_fallback_runs_opened_total: std::sync::atomic::AtomicU64,
1376    pub(crate) hot_fallback_pages_decoded_total: std::sync::atomic::AtomicU64,
1377    pub(crate) hot_fallback_rows_materialized_total: std::sync::atomic::AtomicU64,
1378    pub(crate) hot_lookup_duration_nanos: std::sync::atomic::AtomicU64,
1379    pub(crate) hot_fallback_duration_nanos: std::sync::atomic::AtomicU64,
1380    pub(crate) hot_mapping_rebuild_total: std::sync::atomic::AtomicU64,
1381    pub(crate) hot_checkpoint_rejected_total: std::sync::atomic::AtomicU64,
1382}
1383
1384impl Clone for LookupMetrics {
1385    fn clone(&self) -> Self {
1386        let mut hot_fallback_reasons = [
1387            std::sync::atomic::AtomicU64::new(0),
1388            std::sync::atomic::AtomicU64::new(0),
1389            std::sync::atomic::AtomicU64::new(0),
1390            std::sync::atomic::AtomicU64::new(0),
1391            std::sync::atomic::AtomicU64::new(0),
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        ];
1397        for (dst, src) in hot_fallback_reasons
1398            .iter_mut()
1399            .zip(self.hot_fallback_reasons.iter())
1400        {
1401            dst.store(
1402                src.load(std::sync::atomic::Ordering::Relaxed),
1403                std::sync::atomic::Ordering::Relaxed,
1404            );
1405        }
1406        let copy_atomic = |src: &std::sync::atomic::AtomicU64| {
1407            std::sync::atomic::AtomicU64::new(src.load(std::sync::atomic::Ordering::Relaxed))
1408        };
1409        Self {
1410            hot_lookup_hit: copy_atomic(&self.hot_lookup_hit),
1411            hot_lookup_fallback: copy_atomic(&self.hot_lookup_fallback),
1412            hot_lookup_fallback_overlay_rows: copy_atomic(&self.hot_lookup_fallback_overlay_rows),
1413            hot_lookup_fallback_runs: copy_atomic(&self.hot_lookup_fallback_runs),
1414            result_cache_memory_hit: copy_atomic(&self.result_cache_memory_hit),
1415            result_cache_disk_hit: copy_atomic(&self.result_cache_disk_hit),
1416            result_cache_miss: copy_atomic(&self.result_cache_miss),
1417            result_cache_persistent_write_us: copy_atomic(&self.result_cache_persistent_write_us),
1418            get_run_opened: copy_atomic(&self.get_run_opened),
1419            get_run_skipped: copy_atomic(&self.get_run_skipped),
1420            directory_lookup_hit: copy_atomic(&self.directory_lookup_hit),
1421            directory_lookup_fallback: copy_atomic(&self.directory_lookup_fallback),
1422            directory_incomplete: copy_atomic(&self.directory_incomplete),
1423            directory_run_readers_opened: copy_atomic(&self.directory_run_readers_opened),
1424            directory_early_stop_total: copy_atomic(&self.directory_early_stop_total),
1425            directory_complete_miss_total: copy_atomic(&self.directory_complete_miss_total),
1426            result_cache_persist_enqueued_total: copy_atomic(
1427                &self.result_cache_persist_enqueued_total,
1428            ),
1429            result_cache_persist_coalesced_total: copy_atomic(
1430                &self.result_cache_persist_coalesced_total,
1431            ),
1432            result_cache_persist_dropped_store_total: copy_atomic(
1433                &self.result_cache_persist_dropped_store_total,
1434            ),
1435            result_cache_persist_remove_total: copy_atomic(&self.result_cache_persist_remove_total),
1436            result_cache_persist_stale_store_skipped_total: copy_atomic(
1437                &self.result_cache_persist_stale_store_skipped_total,
1438            ),
1439            result_cache_persist_errors_total: copy_atomic(&self.result_cache_persist_errors_total),
1440            result_cache_persist_shutdown_abandoned_total: copy_atomic(
1441                &self.result_cache_persist_shutdown_abandoned_total,
1442            ),
1443            result_cache_persist_queue_depth: copy_atomic(&self.result_cache_persist_queue_depth),
1444            hot_fallback_reasons,
1445            hot_fallback_overlay_versions_total: copy_atomic(
1446                &self.hot_fallback_overlay_versions_total,
1447            ),
1448            hot_fallback_runs_considered_total: copy_atomic(
1449                &self.hot_fallback_runs_considered_total,
1450            ),
1451            hot_fallback_runs_opened_total: copy_atomic(&self.hot_fallback_runs_opened_total),
1452            hot_fallback_pages_decoded_total: copy_atomic(&self.hot_fallback_pages_decoded_total),
1453            hot_fallback_rows_materialized_total: copy_atomic(
1454                &self.hot_fallback_rows_materialized_total,
1455            ),
1456            hot_lookup_duration_nanos: copy_atomic(&self.hot_lookup_duration_nanos),
1457            hot_fallback_duration_nanos: copy_atomic(&self.hot_fallback_duration_nanos),
1458            hot_mapping_rebuild_total: copy_atomic(&self.hot_mapping_rebuild_total),
1459            hot_checkpoint_rejected_total: copy_atomic(&self.hot_checkpoint_rejected_total),
1460        }
1461    }
1462}
1463
1464impl LookupMetrics {
1465    fn snapshot(&self) -> LookupMetricsSnapshot {
1466        LookupMetricsSnapshot {
1467            hot_lookup_hit: self
1468                .hot_lookup_hit
1469                .load(std::sync::atomic::Ordering::Relaxed),
1470            hot_lookup_fallback: self
1471                .hot_lookup_fallback
1472                .load(std::sync::atomic::Ordering::Relaxed),
1473            hot_lookup_fallback_overlay_rows: self
1474                .hot_lookup_fallback_overlay_rows
1475                .load(std::sync::atomic::Ordering::Relaxed),
1476            hot_lookup_fallback_runs: self
1477                .hot_lookup_fallback_runs
1478                .load(std::sync::atomic::Ordering::Relaxed),
1479            result_cache_memory_hit: self
1480                .result_cache_memory_hit
1481                .load(std::sync::atomic::Ordering::Relaxed),
1482            result_cache_disk_hit: self
1483                .result_cache_disk_hit
1484                .load(std::sync::atomic::Ordering::Relaxed),
1485            result_cache_miss: self
1486                .result_cache_miss
1487                .load(std::sync::atomic::Ordering::Relaxed),
1488            result_cache_persistent_write_us: self
1489                .result_cache_persistent_write_us
1490                .load(std::sync::atomic::Ordering::Relaxed),
1491            get_run_opened: self
1492                .get_run_opened
1493                .load(std::sync::atomic::Ordering::Relaxed),
1494            get_run_skipped: self
1495                .get_run_skipped
1496                .load(std::sync::atomic::Ordering::Relaxed),
1497            directory_lookup_hit: self
1498                .directory_lookup_hit
1499                .load(std::sync::atomic::Ordering::Relaxed),
1500            directory_lookup_fallback: self
1501                .directory_lookup_fallback
1502                .load(std::sync::atomic::Ordering::Relaxed),
1503            directory_incomplete: self
1504                .directory_incomplete
1505                .load(std::sync::atomic::Ordering::Relaxed),
1506            directory_run_readers_opened: self
1507                .directory_run_readers_opened
1508                .load(std::sync::atomic::Ordering::Relaxed),
1509            directory_early_stop_total: self
1510                .directory_early_stop_total
1511                .load(std::sync::atomic::Ordering::Relaxed),
1512            directory_complete_miss_total: self
1513                .directory_complete_miss_total
1514                .load(std::sync::atomic::Ordering::Relaxed),
1515            result_cache_persist_enqueued_total: self
1516                .result_cache_persist_enqueued_total
1517                .load(std::sync::atomic::Ordering::Relaxed),
1518            result_cache_persist_coalesced_total: self
1519                .result_cache_persist_coalesced_total
1520                .load(std::sync::atomic::Ordering::Relaxed),
1521            result_cache_persist_dropped_store_total: self
1522                .result_cache_persist_dropped_store_total
1523                .load(std::sync::atomic::Ordering::Relaxed),
1524            result_cache_persist_remove_total: self
1525                .result_cache_persist_remove_total
1526                .load(std::sync::atomic::Ordering::Relaxed),
1527            result_cache_persist_stale_store_skipped_total: self
1528                .result_cache_persist_stale_store_skipped_total
1529                .load(std::sync::atomic::Ordering::Relaxed),
1530            result_cache_persist_errors_total: self
1531                .result_cache_persist_errors_total
1532                .load(std::sync::atomic::Ordering::Relaxed),
1533            result_cache_persist_shutdown_abandoned_total: self
1534                .result_cache_persist_shutdown_abandoned_total
1535                .load(std::sync::atomic::Ordering::Relaxed),
1536            result_cache_persist_queue_depth: self
1537                .result_cache_persist_queue_depth
1538                .load(std::sync::atomic::Ordering::Relaxed),
1539            // REM-D §8.7: publication-availability counters live on the
1540            // `ResultCache` itself (not on the writer's metrics), so they
1541            // are filled in by `Table::lookup_metrics_snapshot`.
1542            result_cache_persist_unavailable_total: 0,
1543            result_cache_persist_skipped_total: 0,
1544            result_cache_worker_spawn_failures_total: 0,
1545            result_cache_worker_shutdown_total: 0,
1546            hot_fallback_reasons: [
1547                self.hot_fallback_reasons[0].load(std::sync::atomic::Ordering::Relaxed),
1548                self.hot_fallback_reasons[1].load(std::sync::atomic::Ordering::Relaxed),
1549                self.hot_fallback_reasons[2].load(std::sync::atomic::Ordering::Relaxed),
1550                self.hot_fallback_reasons[3].load(std::sync::atomic::Ordering::Relaxed),
1551                self.hot_fallback_reasons[4].load(std::sync::atomic::Ordering::Relaxed),
1552                self.hot_fallback_reasons[5].load(std::sync::atomic::Ordering::Relaxed),
1553                self.hot_fallback_reasons[6].load(std::sync::atomic::Ordering::Relaxed),
1554                self.hot_fallback_reasons[7].load(std::sync::atomic::Ordering::Relaxed),
1555                self.hot_fallback_reasons[8].load(std::sync::atomic::Ordering::Relaxed),
1556            ],
1557            hot_fallback_overlay_versions_total: self
1558                .hot_fallback_overlay_versions_total
1559                .load(std::sync::atomic::Ordering::Relaxed),
1560            hot_fallback_runs_considered_total: self
1561                .hot_fallback_runs_considered_total
1562                .load(std::sync::atomic::Ordering::Relaxed),
1563            hot_fallback_runs_opened_total: self
1564                .hot_fallback_runs_opened_total
1565                .load(std::sync::atomic::Ordering::Relaxed),
1566            hot_fallback_pages_decoded_total: self
1567                .hot_fallback_pages_decoded_total
1568                .load(std::sync::atomic::Ordering::Relaxed),
1569            hot_fallback_rows_materialized_total: self
1570                .hot_fallback_rows_materialized_total
1571                .load(std::sync::atomic::Ordering::Relaxed),
1572            hot_lookup_duration_nanos: self
1573                .hot_lookup_duration_nanos
1574                .load(std::sync::atomic::Ordering::Relaxed),
1575            hot_fallback_duration_nanos: self
1576                .hot_fallback_duration_nanos
1577                .load(std::sync::atomic::Ordering::Relaxed),
1578            hot_mapping_rebuild_total: self
1579                .hot_mapping_rebuild_total
1580                .load(std::sync::atomic::Ordering::Relaxed),
1581            hot_checkpoint_rejected_total: self
1582                .hot_checkpoint_rejected_total
1583                .load(std::sync::atomic::Ordering::Relaxed),
1584        }
1585    }
1586}
1587
1588/// Point-in-time copy of [`LookupMetrics`]. Returned from
1589/// [`Table::lookup_metrics_snapshot`] for `/metrics` exposure or test assertions.
1590#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1591pub struct LookupMetricsSnapshot {
1592    pub hot_lookup_hit: u64,
1593    pub hot_lookup_fallback: u64,
1594    pub hot_lookup_fallback_overlay_rows: u64,
1595    pub hot_lookup_fallback_runs: u64,
1596    pub result_cache_memory_hit: u64,
1597    pub result_cache_disk_hit: u64,
1598    pub result_cache_miss: u64,
1599    pub result_cache_persistent_write_us: u64,
1600    pub get_run_opened: u64,
1601    pub get_run_skipped: u64,
1602    // ---- TODO §1 ----
1603    pub directory_lookup_hit: u64,
1604    pub directory_lookup_fallback: u64,
1605    pub directory_incomplete: u64,
1606    pub directory_run_readers_opened: u64,
1607    pub directory_early_stop_total: u64,
1608    pub directory_complete_miss_total: u64,
1609    // ---- TODO §2 ----
1610    pub result_cache_persist_enqueued_total: u64,
1611    pub result_cache_persist_coalesced_total: u64,
1612    pub result_cache_persist_dropped_store_total: u64,
1613    pub result_cache_persist_remove_total: u64,
1614    pub result_cache_persist_stale_store_skipped_total: u64,
1615    pub result_cache_persist_errors_total: u64,
1616    pub result_cache_persist_shutdown_abandoned_total: u64,
1617    pub result_cache_persist_queue_depth: u64,
1618    // ---- REM-D §8.7: publication-availability counters ----
1619    /// Number of times persistent publication transitioned to unavailable
1620    /// (worker spawn failure, worker shutdown, queue unavailable).
1621    pub result_cache_persist_unavailable_total: u64,
1622    /// Number of query-path persist operations skipped because publication
1623    /// was unavailable (the in-memory entry is kept; nothing hits disk).
1624    pub result_cache_persist_skipped_total: u64,
1625    /// Number of background-worker spawn / I/O-setup failures.
1626    pub result_cache_worker_spawn_failures_total: u64,
1627    /// Number of background-worker shutdowns while the cache was live.
1628    pub result_cache_worker_shutdown_total: u64,
1629    // ---- TODO §5 ----
1630    pub hot_fallback_reasons: [u64; 9],
1631    pub hot_fallback_overlay_versions_total: u64,
1632    pub hot_fallback_runs_considered_total: u64,
1633    pub hot_fallback_runs_opened_total: u64,
1634    pub hot_fallback_pages_decoded_total: u64,
1635    pub hot_fallback_rows_materialized_total: u64,
1636    pub hot_lookup_duration_nanos: u64,
1637    pub hot_fallback_duration_nanos: u64,
1638    pub hot_mapping_rebuild_total: u64,
1639    pub hot_checkpoint_rejected_total: u64,
1640}
1641
1642/// Reason label for one HOT fallback. The integer index is the position in
1643/// `LookupMetrics::hot_fallback_reasons` and MUST stay stable across releases.
1644pub fn hot_fallback_reason_index(r: crate::trace::HotFallbackReason) -> usize {
1645    match r {
1646        crate::trace::HotFallbackReason::MissingMapping => 0,
1647        crate::trace::HotFallbackReason::StaleRowId => 1,
1648        crate::trace::HotFallbackReason::InvisibleAtSnapshot => 2,
1649        crate::trace::HotFallbackReason::HistoricalSnapshot => 3,
1650        crate::trace::HotFallbackReason::Tombstone => 4,
1651        crate::trace::HotFallbackReason::TtlExpired => 5,
1652        crate::trace::HotFallbackReason::PrimaryKeyMismatch => 6,
1653        crate::trace::HotFallbackReason::IndexIncomplete => 7,
1654        crate::trace::HotFallbackReason::CheckpointRejected => 8,
1655    }
1656}
1657
1658// `Table` is `Sync`: every field is either plain data, an `Arc`, a `Vec`/`HashMap`
1659// of `Sync` data, or a thread-safe interior-mutability cell (`parking_lot::Mutex`,
1660// `crossbeam`/`epoch` Arc-shared caches). The only `RefCell`-based type was
1661// `FmIndex` (lazy rebuild of the BWT), which now uses a `Mutex`, so a `&Table`
1662// can be safely shared across read threads (concurrent mutation still requires
1663// the caller's `Mutex<Table>`).
1664const _: () = {
1665    const fn assert_sync<T: ?Sized + Sync>() {}
1666    assert_sync::<Table>();
1667};
1668
1669/// A cached query result — either survivor `Row`s (the tool-call/`query` path)
1670/// or typed survivor columns (the pushdown/`query_columns_native` path). One
1671/// canonical key maps to exactly one variant (a `query` with no projection vs a
1672/// `query_columns_native` with a specific projection produce different keys), so
1673/// there is no representation collision.
1674#[derive(Clone)]
1675enum CachedData {
1676    Rows(Arc<Vec<Row>>),
1677    Columns(Arc<Vec<(u16, columnar::NativeColumn)>>),
1678}
1679
1680impl CachedData {
1681    fn approx_bytes(&self) -> u64 {
1682        match self {
1683            CachedData::Rows(r) => r.iter().map(|r| r.estimated_bytes()).sum::<u64>(),
1684            CachedData::Columns(c) => c
1685                .iter()
1686                .map(|(_, c)| c.approx_bytes())
1687                .sum::<u64>()
1688                .saturating_add(c.len() as u64 * 16),
1689        }
1690    }
1691}
1692
1693/// A cached entry carrying the survivor `RowId` **footprint** (for precise
1694/// delete-based invalidation) and the condition column IDs (for conservative
1695/// insert-based invalidation). Hardening (c).
1696struct CachedEntry {
1697    data: CachedData,
1698    footprint: roaring::RoaringBitmap,
1699    condition_cols: Vec<u16>,
1700}
1701
1702impl CachedEntry {
1703    /// Cheap clone for handing to the persistent-cache worker. The `data`
1704    /// is `Arc`-shared (no row/column copy); only the `condition_cols`
1705    /// vector and the `footprint` bitmap are duplicated. The latter two are
1706    /// small relative to the cached payload, so this is fine on the query
1707    /// path.
1708    fn clone_for_persist(&self) -> Self {
1709        Self {
1710            data: self.data.clone(),
1711            footprint: self.footprint.clone(),
1712            condition_cols: self.condition_cols.clone(),
1713        }
1714    }
1715}
1716
1717/// Size-bounded **access-order LRU** result cache (Phase 19.1 + hardening (a)).
1718/// Every `get_*` assigns a new recency generation; eviction removes the lowest
1719/// generation (least-recently-used) — a true LRU, not FIFO.
1720///
1721/// Hardening (b): an optional on-disk persistent tier (`dir = Some(_)`). On a
1722/// memory miss, the cache tries disk before falling through to re-resolution.
1723/// On `insert`, the caller publishes the entry through `persist_entry`, which
1724/// enqueues the atomic write (temp + fsync + rename) onto the background
1725/// worker — never synchronously on the query thread (REM-D §8.5). On
1726/// `invalidate`/`clear`, the matching disk files are deleted. On
1727/// `Table::open`, existing disk entries are pre-loaded so fine-grained invalidation
1728/// resumes across restart.
1729struct ResultCache {
1730    entries: std::collections::HashMap<u64, CachedEntry>,
1731    order: BTreeSet<(u64, u64)>,
1732    generations: HashMap<u64, u64>,
1733    next_generation: u64,
1734    /// Reverse index for conservative insert invalidation. Its size is bounded
1735    /// by cached query-condition metadata, not by survivor rows.
1736    condition_index: HashMap<u16, HashSet<u64>>,
1737    /// Entries whose row footprint could not be resolved. Any delete must
1738    /// conservatively invalidate these entries.
1739    empty_footprint_entries: HashSet<u64>,
1740    bytes: u64,
1741    max_bytes: u64,
1742    dir: Option<std::path::PathBuf>,
1743    #[allow(dead_code)]
1744    cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1745    /// Cache hit/miss counters (memory vs disk tier) + persistent-write latency.
1746    /// Independent of `LookupMetrics` on the parent `Table` — the cache may be
1747    /// queried by paths that don't pass through the table's Pk arm.
1748    memory_hit: std::sync::atomic::AtomicU64,
1749    disk_hit: std::sync::atomic::AtomicU64,
1750    miss: std::sync::atomic::AtomicU64,
1751    persistent_write_us: std::sync::atomic::AtomicU64,
1752    /// Minimum entry size (approx bytes) before the persistent tier is written.
1753    /// Tiny one-row results stay memory-only so a warm miss is not forced to
1754    /// pay atomic filesystem publish. 0 disables the threshold (always persist
1755    /// when `dir` is set). Default: 4 KiB.
1756    persist_min_bytes: u64,
1757    /// Explicit persistent-publication state (REM-D §8.6). `Async` once the
1758    /// table has been wired to a background worker (`install_persistent_writer`);
1759    /// `Disabled(reason)` before then, after a spawn failure, or after worker
1760    /// shutdown. The query path never performs synchronous disk publication:
1761    /// when the state is `Disabled`, `persist_entry` keeps the in-memory entry,
1762    /// skips publication, and increments the skip metric.
1763    persistence: PersistentPublicationState,
1764    /// Worker join handle, kept on the cache so `shutdown_persistent_cache`
1765    /// can wait for drain to finish.
1766    worker_handle: Option<std::thread::JoinHandle<()>>,
1767    /// Completion-signal receiver. The worker sends `()` on this channel
1768    /// immediately before exiting. `shutdown_persistent_cache(deadline)`
1769    /// uses `recv_timeout(remaining_deadline)` so it can return by its
1770    /// advertised deadline even if the worker is blocked in filesystem I/O.
1771    completion_rx: Option<std::sync::mpsc::Receiver<()>>,
1772    /// Optional DEK for cache payload encryption (binary, not a `Zeroizing`
1773    /// wrapper). Stored separately from the cache writer so the same cipher
1774    /// can be reused for both async and sync encode/decode paths.
1775    cache_payload_cipher: Option<std::sync::Arc<crate::encryption::AesCipher>>,
1776    // ---- REM-D §8.7: publication-availability counters ----
1777    /// Transitions of `persistence` to a `Disabled` state while the cache
1778    /// was expected to publish.
1779    persist_unavailable_total: std::sync::atomic::AtomicU64,
1780    /// Query-path persist operations skipped because publication was disabled.
1781    persist_skipped_total: std::sync::atomic::AtomicU64,
1782    /// Worker spawn / I/O-setup failures observed at wiring time.
1783    worker_spawn_failures_total: std::sync::atomic::AtomicU64,
1784    /// Worker shutdowns observed while the cache was live.
1785    worker_shutdown_total: std::sync::atomic::AtomicU64,
1786}
1787
1788/// Serialised form of a [`CachedEntry`] for the persistent on-disk tier (b).
1789#[derive(serde::Serialize, serde::Deserialize)]
1790struct SerializedEntry {
1791    condition_cols: Vec<u16>,
1792    footprint_bits: Vec<u32>,
1793    data: SerializedData,
1794}
1795
1796#[derive(serde::Serialize, serde::Deserialize)]
1797enum SerializedData {
1798    Rows(Vec<Row>),
1799    Columns(Vec<(u16, columnar::NativeColumn)>),
1800}
1801
1802#[derive(serde::Serialize)]
1803struct SerializedEntryRef<'a> {
1804    condition_cols: &'a [u16],
1805    footprint_bits: Vec<u32>,
1806    data: SerializedDataRef<'a>,
1807}
1808
1809#[derive(serde::Serialize)]
1810enum SerializedDataRef<'a> {
1811    Rows(&'a [Row]),
1812    Columns(&'a [(u16, columnar::NativeColumn)]),
1813}
1814
1815impl<'a> SerializedEntryRef<'a> {
1816    fn from_entry(entry: &'a CachedEntry) -> Self {
1817        let footprint_bits: Vec<u32> = entry.footprint.iter().collect();
1818        let data = match &entry.data {
1819            CachedData::Rows(rows) => SerializedDataRef::Rows(rows.as_slice()),
1820            CachedData::Columns(columns) => SerializedDataRef::Columns(columns.as_slice()),
1821        };
1822        Self {
1823            condition_cols: &entry.condition_cols,
1824            footprint_bits,
1825            data,
1826        }
1827    }
1828}
1829
1830impl SerializedEntry {
1831    fn into_entry(self) -> Option<CachedEntry> {
1832        let footprint: roaring::RoaringBitmap = self.footprint_bits.into_iter().collect();
1833        let data = match self.data {
1834            SerializedData::Rows(r) => CachedData::Rows(Arc::new(r)),
1835            SerializedData::Columns(c) => {
1836                // Validate deserialized columns (hardening (b)): reject corrupt
1837                // data instead of panicking on access.
1838                if !c.iter().all(|(_, col)| col.validate()) {
1839                    return None;
1840                }
1841                CachedData::Columns(Arc::new(c))
1842            }
1843        };
1844        Some(CachedEntry {
1845            data,
1846            footprint,
1847            condition_cols: self.condition_cols,
1848        })
1849    }
1850}
1851
1852impl ResultCache {
1853    const DEFAULT_MAX_BYTES: u64 = 256 * 1024 * 1024;
1854
1855    fn new() -> Self {
1856        Self::with_max_bytes(Self::DEFAULT_MAX_BYTES)
1857    }
1858
1859    fn with_max_bytes(max_bytes: u64) -> Self {
1860        Self {
1861            entries: std::collections::HashMap::new(),
1862            order: BTreeSet::new(),
1863            generations: HashMap::new(),
1864            next_generation: 0,
1865            condition_index: HashMap::new(),
1866            empty_footprint_entries: HashSet::new(),
1867            bytes: 0,
1868            max_bytes,
1869            dir: None,
1870            cache_dek: None,
1871            memory_hit: std::sync::atomic::AtomicU64::new(0),
1872            disk_hit: std::sync::atomic::AtomicU64::new(0),
1873            miss: std::sync::atomic::AtomicU64::new(0),
1874            persistent_write_us: std::sync::atomic::AtomicU64::new(0),
1875            // Skip synchronous disk publish for tiny results (one-row point
1876            // queries). Larger analytical results still hit the durable tier.
1877            persist_min_bytes: 4 * 1024,
1878            persistence: PersistentPublicationState::Disabled(
1879                PersistenceDisabledReason::NoDirectory,
1880            ),
1881            worker_handle: None,
1882            completion_rx: None,
1883            cache_payload_cipher: None,
1884            persist_unavailable_total: std::sync::atomic::AtomicU64::new(0),
1885            persist_skipped_total: std::sync::atomic::AtomicU64::new(0),
1886            worker_spawn_failures_total: std::sync::atomic::AtomicU64::new(0),
1887            worker_shutdown_total: std::sync::atomic::AtomicU64::new(0),
1888        }
1889    }
1890
1891    fn with_dir(mut self, dir: std::path::PathBuf) -> Self {
1892        let _ = std::fs::create_dir_all(&dir);
1893        self.dir = Some(dir);
1894        if matches!(
1895            self.persistence,
1896            PersistentPublicationState::Disabled(PersistenceDisabledReason::NoDirectory)
1897        ) {
1898            self.persistence =
1899                PersistentPublicationState::Disabled(PersistenceDisabledReason::QueueUnavailable);
1900        }
1901        self
1902    }
1903
1904    fn with_cache_dek(mut self, dek: Option<Zeroizing<[u8; DEK_LEN]>>) -> Self {
1905        // Build a single cipher for both async and sync paths. The cipher is
1906        // a thin wrapper around the AES key, so creating it twice (once for
1907        // the cache, once for the worker's own copy) is cheap. We keep the
1908        // raw DEK for backward compatibility with `encrypt_cache` /
1909        // `decrypt_cache`; new code paths should use `cache_payload_cipher`.
1910        self.cache_dek = dek.clone();
1911        if let Some(dek) = dek {
1912            if let Ok(cipher) = crate::encryption::AesCipher::new(&dek[..]) {
1913                self.cache_payload_cipher = Some(std::sync::Arc::new(cipher));
1914            }
1915        }
1916        self
1917    }
1918
1919    /// Install a background writer and its worker. The writer drains the
1920    /// pending-op queue and publishes through the supplied I/O backend.
1921    /// `flush_persistent_cache(deadline)` and `shutdown_persistent_cache(deadline)`
1922    /// rely on the writer being installed.
1923    fn install_persistent_writer(
1924        &mut self,
1925        writer: std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
1926        worker_handle: std::thread::JoinHandle<()>,
1927        completion_rx: std::sync::mpsc::Receiver<()>,
1928    ) {
1929        self.persistence = PersistentPublicationState::Async(writer);
1930        self.worker_handle = Some(worker_handle);
1931        self.completion_rx = Some(completion_rx);
1932    }
1933
1934    /// Record that the background worker (or its I/O setup) failed to start.
1935    /// Publication transitions to `Disabled(WorkerSpawnFailed)`; subsequent
1936    /// query-path persists are skipped with a metric instead of falling back
1937    /// to synchronous query-thread I/O (REM-D §8.5).
1938    fn note_worker_spawn_failure(&mut self) {
1939        self.worker_spawn_failures_total
1940            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1941        self.persist_unavailable_total
1942            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1943        self.persistence =
1944            PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerSpawnFailed);
1945    }
1946
1947    /// Take the worker handle so the caller can join it after shutdown.
1948    /// Returns `None` if no writer is installed.
1949    fn take_persistent_worker(&mut self) -> Option<std::thread::JoinHandle<()>> {
1950        self.worker_handle.take()
1951    }
1952
1953    /// Take the completion-signal receiver so the caller can wait on a
1954    /// bounded deadline. Returns `None` if no writer is installed.
1955    fn take_persistent_completion(&mut self) -> Option<std::sync::mpsc::Receiver<()>> {
1956        self.completion_rx.take()
1957    }
1958
1959    /// Borrow the writer (when installed). Used by `flush_persistent_cache` /
1960    /// `shutdown_persistent_cache` to wait for the queue to drain.
1961    fn persistent_writer(
1962        &self,
1963    ) -> Option<&std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>> {
1964        match &self.persistence {
1965            PersistentPublicationState::Async(writer) => Some(writer),
1966            PersistentPublicationState::Disabled(_) => None,
1967        }
1968    }
1969
1970    fn disk_path(&self, key: u64) -> Option<std::path::PathBuf> {
1971        self.dir.as_ref().map(|d| d.join(format!("{key:016x}.bin")))
1972    }
1973
1974    /// Persist `entry` to the on-disk tier **synchronously** using the MLCP
1975    /// frame format (REM-002). The encoding is shared with the async worker —
1976    /// both paths produce the same frame layout, identity validation, and
1977    /// payload encryption. Best-effort: silently ignores I/O errors (the
1978    /// in-memory cache is authoritative; the cache is disposable —
1979    /// missing/stale files fall through to re-resolution).
1980    ///
1981    /// Maintenance-only entry point (REM-D §8.6): migration tools, explicit
1982    /// administrative flushes, and focused format-parity tests. Never called
1983    /// from `query_cached` / `query_columns_native_cached` — the query path
1984    /// uses [`ResultCache::persist_entry`], which never blocks on disk I/O.
1985    fn persist_entry_synchronously_for_maintenance(
1986        &self,
1987        context: PersistContext,
1988        entry: &CachedEntry,
1989    ) {
1990        let Some(path) = self.disk_path(context.key) else {
1991            return;
1992        };
1993        let serialized = match bincode::serialize(&SerializedEntryRef::from_entry(entry)) {
1994            Ok(s) => s,
1995            Err(_) => return,
1996        };
1997        let bytes = match crate::result_cache::encode_persisted_entry(
1998            context,
1999            &serialized,
2000            self.cache_payload_cipher.as_deref(),
2001        ) {
2002            Ok(b) => b,
2003            Err(_) => return,
2004        };
2005        let tmp = path.with_extension("tmp");
2006        use std::io::Write;
2007        let write = || -> std::io::Result<()> {
2008            let mut f = std::fs::File::create(&tmp)?;
2009            f.write_all(&bytes)?;
2010            f.flush()?;
2011            f.sync_all()?;
2012            Ok(())
2013        };
2014        if write().is_err() {
2015            let _ = std::fs::remove_file(&tmp);
2016            return;
2017        }
2018        if std::fs::rename(&tmp, &path).is_err() {
2019            let _ = std::fs::remove_file(&tmp);
2020            return;
2021        }
2022        if let Ok(dir) = std::fs::File::open(self.dir.as_ref().expect("dir set").clone()) {
2023            let _ = dir.sync_all();
2024        }
2025    }
2026
2027    /// Try loading `key` from disk. Returns `None` on miss or error.
2028    /// Decodes the MLCP frame, validates table / schema / key / generation /
2029    /// format version / CRC, decrypts the payload, and bincode-deserializes
2030    /// the entry. Legacy unframed files (anything that does not start with
2031    /// the MLCP magic) are deleted as a safe migration (REM-002 §18.5).
2032    fn load_from_disk(&self, key: u64, identity: PersistentCacheIdentity) -> Option<CachedEntry> {
2033        let path = self.disk_path(key)?;
2034        let bytes = std::fs::read(&path).ok()?;
2035        // Legacy migration: drop unframed files instead of trying to
2036        // bincode-deserialize a raw entry. The cache is disposable — a
2037        // recompute is cheaper than a fragile backward-compat shim.
2038        if bytes.len() < FRAME_MAGIC.len() || bytes[..FRAME_MAGIC.len()] != FRAME_MAGIC {
2039            let _ = std::fs::remove_file(&path);
2040            return None;
2041        }
2042        let plaintext = match crate::result_cache::decode_persisted_entry(
2043            identity,
2044            key,
2045            &bytes,
2046            self.cache_payload_cipher.as_deref(),
2047        ) {
2048            Ok(p) => p,
2049            Err(_) => {
2050                let _ = std::fs::remove_file(&path);
2051                return None;
2052            }
2053        };
2054        let serialized: SerializedEntry = match bincode::deserialize(&plaintext) {
2055            Ok(s) => s,
2056            Err(_) => {
2057                let _ = std::fs::remove_file(&path);
2058                return None;
2059            }
2060        };
2061        serialized.into_entry()
2062    }
2063
2064    /// Delete the on-disk file for `key` if it exists. Best-effort.
2065    fn remove_from_disk(&self, key: u64) {
2066        if let Some(path) = self.disk_path(key) {
2067            let _ = std::fs::remove_file(&path);
2068        }
2069    }
2070
2071    /// Scan the cache directory and pre-load all entries into memory. Called
2072    /// once on `Table::open`. Best-effort: corrupt / unframed / wrong-identity
2073    /// files are deleted and the corresponding entry is treated as a miss.
2074    fn load_persistent(&mut self, identity: PersistentCacheIdentity) {
2075        let Some(dir) = self.dir.as_ref().cloned() else {
2076            return;
2077        };
2078        let entries = match std::fs::read_dir(&dir) {
2079            Ok(e) => e,
2080            Err(_) => return,
2081        };
2082        for entry in entries.flatten() {
2083            let path = entry.path();
2084            // Clean up orphan .tmp files from crashed atomic-write calls.
2085            if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
2086                let _ = std::fs::remove_file(&path);
2087                continue;
2088            }
2089            if path.extension().and_then(|e| e.to_str()) != Some("bin") {
2090                continue;
2091            }
2092            let stem = match path.file_stem().and_then(|s| s.to_str()) {
2093                Some(s) => s,
2094                None => continue,
2095            };
2096            let key = match u64::from_str_radix(stem, 16) {
2097                Ok(k) => k,
2098                Err(_) => continue,
2099            };
2100            // Reuse `load_from_disk` so the legacy / corruption / identity
2101            // rejection path is consistent across the per-key load and the
2102            // bulk preload. The function deletes bad files itself.
2103            if let Some(entry) = self.load_from_disk(key, identity) {
2104                self.bytes = self.bytes.saturating_add(entry.data.approx_bytes());
2105                self.index_entry(key, &entry);
2106                self.entries.insert(key, entry);
2107                self.touch(key);
2108            }
2109        }
2110        self.evict();
2111    }
2112
2113    fn set_max_bytes(&mut self, max_bytes: u64) {
2114        self.max_bytes = max_bytes;
2115        self.evict();
2116    }
2117
2118    /// Promote `key` to most-recently-used position without scanning every
2119    /// cache entry. The generation-ordered set provides exact LRU in O(log n).
2120    fn touch(&mut self, key: u64) {
2121        if !self.entries.contains_key(&key) {
2122            return;
2123        }
2124        if let Some(previous) = self.generations.remove(&key) {
2125            self.order.remove(&(previous, key));
2126        }
2127        let generation = self.allocate_generation();
2128        self.generations.insert(key, generation);
2129        self.order.insert((generation, key));
2130    }
2131
2132    fn untrack(&mut self, key: u64) {
2133        if let Some(generation) = self.generations.remove(&key) {
2134            self.order.remove(&(generation, key));
2135        }
2136    }
2137
2138    fn index_entry(&mut self, key: u64, entry: &CachedEntry) {
2139        for column in &entry.condition_cols {
2140            self.condition_index.entry(*column).or_default().insert(key);
2141        }
2142        if entry.footprint.is_empty() {
2143            self.empty_footprint_entries.insert(key);
2144        }
2145    }
2146
2147    fn unindex_entry(&mut self, key: u64, entry: &CachedEntry) {
2148        for column in &entry.condition_cols {
2149            let remove_column = self.condition_index.get_mut(column).is_some_and(|keys| {
2150                keys.remove(&key);
2151                keys.is_empty()
2152            });
2153            if remove_column {
2154                self.condition_index.remove(column);
2155            }
2156        }
2157        if entry.footprint.is_empty() {
2158            self.empty_footprint_entries.remove(&key);
2159        }
2160    }
2161
2162    fn allocate_generation(&mut self) -> u64 {
2163        if self.next_generation == u64::MAX {
2164            self.rebase_generations();
2165        }
2166        let generation = self.next_generation;
2167        self.next_generation += 1;
2168        generation
2169    }
2170
2171    fn rebase_generations(&mut self) {
2172        let ordered = std::mem::take(&mut self.order);
2173        self.generations.clear();
2174        for (generation, (_, key)) in ordered.into_iter().enumerate() {
2175            let generation = generation as u64;
2176            self.generations.insert(key, generation);
2177            self.order.insert((generation, key));
2178        }
2179        self.next_generation = self.order.len() as u64;
2180    }
2181
2182    fn get_rows(&mut self, key: u64, identity: PersistentCacheIdentity) -> Option<Arc<Vec<Row>>> {
2183        let res = self.entries.get(&key).and_then(|e| match &e.data {
2184            CachedData::Rows(r) => Some(r.clone()),
2185            CachedData::Columns(_) => None,
2186        });
2187        if res.is_some() {
2188            self.touch(key);
2189            self.memory_hit
2190                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2191            return res;
2192        }
2193        // Memory miss → try the persistent tier (b).
2194        if let Some(entry) = self.load_from_disk(key, identity) {
2195            let res = match &entry.data {
2196                CachedData::Rows(r) => Some(r.clone()),
2197                CachedData::Columns(_) => None,
2198            };
2199            if res.is_some() {
2200                let approx = entry.data.approx_bytes();
2201                self.bytes = self.bytes.saturating_add(approx);
2202                self.index_entry(key, &entry);
2203                self.entries.insert(key, entry);
2204                self.touch(key);
2205                self.evict();
2206                self.disk_hit
2207                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2208                return res;
2209            }
2210        }
2211        self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2212        None
2213    }
2214
2215    fn get_columns(
2216        &mut self,
2217        key: u64,
2218        identity: PersistentCacheIdentity,
2219    ) -> Option<Arc<Vec<(u16, columnar::NativeColumn)>>> {
2220        let res = self.entries.get(&key).and_then(|e| match &e.data {
2221            CachedData::Columns(c) => Some(c.clone()),
2222            CachedData::Rows(_) => None,
2223        });
2224        if res.is_some() {
2225            self.touch(key);
2226            self.memory_hit
2227                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2228            return res;
2229        }
2230        // Memory miss → try the persistent tier (b).
2231        if let Some(entry) = self.load_from_disk(key, identity) {
2232            let res = match &entry.data {
2233                CachedData::Columns(c) => Some(c.clone()),
2234                CachedData::Rows(_) => None,
2235            };
2236            if res.is_some() {
2237                let approx = entry.data.approx_bytes();
2238                self.bytes = self.bytes.saturating_add(approx);
2239                self.index_entry(key, &entry);
2240                self.entries.insert(key, entry);
2241                self.touch(key);
2242                self.evict();
2243                self.disk_hit
2244                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2245                return res;
2246            }
2247        }
2248        self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2249        None
2250    }
2251
2252    /// In-memory insert only. Persistent publication is the caller's job —
2253    /// they call `persist_entry(context, &entry)` (or the legacy
2254    /// `enqueue_persist` for the async path) before this method so the on-
2255    /// disk frame and the in-memory copy can never diverge.
2256    fn insert(&mut self, key: u64, entry: CachedEntry) {
2257        let approx = entry.data.approx_bytes();
2258        if let Some(previous) = self.entries.remove(&key) {
2259            self.bytes = self.bytes.saturating_sub(previous.data.approx_bytes());
2260            self.unindex_entry(key, &previous);
2261            self.untrack(key);
2262        }
2263        self.bytes = self.bytes.saturating_add(approx);
2264        self.index_entry(key, &entry);
2265        self.entries.insert(key, entry);
2266        self.touch(key);
2267        self.evict();
2268    }
2269
2270    /// Persist `entry` using the MLCP frame format (REM-002 §18.3). When
2271    /// the async writer is installed the op is enqueued; when publication is
2272    /// unavailable the entry stays in the in-memory tier and the skip is
2273    /// counted (REM-D §8.5). The query thread never performs disk I/O here.
2274    /// No-op when the entry is below the persistence threshold.
2275    fn persist_entry(&self, context: PersistContext, entry: &CachedEntry) {
2276        let approx = entry.data.approx_bytes();
2277        if self.dir.is_none() {
2278            return;
2279        }
2280        if self.persist_min_bytes > 0 && approx < self.persist_min_bytes {
2281            return;
2282        }
2283        match &self.persistence {
2284            PersistentPublicationState::Async(writer) => {
2285                // Async path: enqueue a `PersistableEntry`. The worker calls
2286                // the same `encode_persisted_entry` helper so the on-disk
2287                // format is byte-for-byte identical to the sync path.
2288                let entry_clone = entry.clone_for_persist();
2289                let payload_factory: Box<dyn FnOnce() -> Option<Vec<u8>> + Send + 'static> =
2290                    Box::new(move || {
2291                        bincode::serialize(&SerializedEntryRef::from_entry(&entry_clone)).ok()
2292                    });
2293                let persistable = crate::result_cache::PersistableEntry {
2294                    key: context.key,
2295                    table_id: context.identity.table_id,
2296                    schema_id: context.identity.schema_id,
2297                    run_generation: context.identity.logical_generation,
2298                    entry_generation: context.entry_generation,
2299                    bytes: approx as usize,
2300                    payload_factory,
2301                };
2302                let write_start = std::time::Instant::now();
2303                writer.enqueue_store(persistable);
2304                let write_us = write_start.elapsed().as_micros() as u64;
2305                self.persistent_write_us
2306                    .fetch_add(write_us, std::sync::atomic::Ordering::Relaxed);
2307            }
2308            PersistentPublicationState::Disabled(reason) => {
2309                // Publication unavailable: keep the in-memory entry, skip the
2310                // persistent write, and make the skip observable (REM-D
2311                // §8.5). The persistent cache is disposable optimization
2312                // state; the next miss simply recomputes.
2313                self.persist_skipped_total
2314                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2315                crate::trace::QueryTrace::record(|trace| {
2316                    trace.result_cache_persist_skipped = true;
2317                    trace.result_cache_persist_skip_reason = Some(reason.label());
2318                });
2319            }
2320        }
2321    }
2322
2323    /// Allocate a fresh per-key entry generation. The generation is what
2324    /// the worker compares against the writer's queue to decide whether a
2325    /// store is still current. A newer invalidation that arrives after the
2326    /// generation was issued supersedes the queued store.
2327    fn allocate_persist_generation(&mut self, key: u64) -> u64 {
2328        if let Some(writer) = self.persistent_writer() {
2329            // Bump the global per-key generation on the writer so a
2330            // subsequent store for the same key is observed as fresh.
2331            let _ = key; // the writer tracks per-key generations internally
2332            writer.bump_persist_generation(key)
2333        } else {
2334            0
2335        }
2336    }
2337
2338    /// Enqueue a `Remove` to the background writer. No-op when no writer is
2339    /// installed.
2340    fn enqueue_persist_remove(&self, key: u64) {
2341        if let Some(writer) = self.persistent_writer() {
2342            writer.enqueue_remove(key);
2343        }
2344    }
2345
2346    /// Enqueue a `Clear` to the background writer. No-op when no writer is
2347    /// installed. Bumping the writer's `clear_generation` is the
2348    /// "shutdown generation" required by REM-002 §18.6 — any in-flight
2349    /// write that re-checks staleness right before publish is then
2350    /// observed as stale and dropped instead of becoming a late durable
2351    /// entry.
2352    fn enqueue_persist_clear(&self) {
2353        if let Some(writer) = self.persistent_writer() {
2354            writer.enqueue_clear();
2355        }
2356    }
2357
2358    /// Drain the writer's queue synchronously until empty or `deadline`
2359    /// expires. The caller invokes this on `Database::close` or before a
2360    /// checkpoint; the worker keeps running and the queue depth is checked
2361    /// between drains. Returns the queue depth at the moment of the call
2362    /// return.
2363    fn flush_persistent_cache(&self, deadline: std::time::Duration) -> u64 {
2364        let Some(writer) = self.persistent_writer() else {
2365            return 0;
2366        };
2367        let start = std::time::Instant::now();
2368        loop {
2369            let depth = writer.queue_depth() as u64;
2370            // Wait until the queue is empty AND no writes are in flight. The
2371            // worker increments `writes_in_flight` before calling I/O and
2372            // decrements after; this catches the "queue empty, write still
2373            // in progress" race that would otherwise report a half-written
2374            // `.tmp` file as the durable state.
2375            let in_flight = writer.writes_in_flight();
2376            if depth == 0 && in_flight == 0 {
2377                return 0;
2378            }
2379            if start.elapsed() >= deadline {
2380                return depth;
2381            }
2382            std::thread::sleep(std::time::Duration::from_millis(2));
2383        }
2384    }
2385
2386    /// Shut the writer down. The worker drains remaining ops until the
2387    /// queue is empty or `deadline` expires; any ops still queued are
2388    /// counted as abandoned. The completion signal is waited on with the
2389    /// *remaining* deadline (REM-002 §18.6) — if it does not arrive in
2390    /// time, the timeout counter is bumped and the worker is detached
2391    /// (its `Arc`-shared state keeps it safe to outlive this method).
2392    /// Publication transitions to `Disabled(WorkerShutdown)` so subsequent
2393    /// `persist_entry` calls skip persistent publication with a metric
2394    /// instead of falling back to synchronous query-thread I/O (REM-D §8.5).
2395    fn shutdown_persistent_cache(&mut self, deadline: std::time::Duration) {
2396        let start = Instant::now();
2397        // Phase 1: wait for the queue to drain or the deadline to expire.
2398        if let Some(writer) = self.persistent_writer() {
2399            loop {
2400                if writer.queue_depth() == 0 {
2401                    break;
2402                }
2403                if start.elapsed() >= deadline {
2404                    break;
2405                }
2406                std::thread::sleep(std::time::Duration::from_millis(2));
2407            }
2408        }
2409        // Phase 2: mark the writer closed. `enqueue_clear` advances the
2410        // global clear_generation so the worker's final staleness check
2411        // (right before publish) aborts any late in-flight write.
2412        let writer = self.persistent_writer().cloned();
2413        if let Some(writer) = writer.as_ref() {
2414            writer.shutdown();
2415            let _ = writer.drain_all_as_abandoned();
2416        }
2417        // Phase 3: wait for the completion signal with the *remaining*
2418        // deadline. `JoinHandle::join` has no timed variant, so we use
2419        // the channel as the deadline-bounded wait point. If the worker
2420        // is blocked in filesystem I/O, the recv returns Err on timeout
2421        // and we detach the handle (state is `Arc`-shared, so the worker
2422        // can still complete safely).
2423        let mut completion = self.take_persistent_completion();
2424        let completed = if let (Some(rx), Some(_writer)) = (completion.as_mut(), writer.as_ref()) {
2425            let elapsed = start.elapsed();
2426            let remaining = deadline.saturating_sub(elapsed);
2427            crate::result_cache::recv_completion_with_timeout(rx, remaining)
2428        } else {
2429            true
2430        };
2431        if completed {
2432            if let Some(handle) = self.take_persistent_worker() {
2433                let _ = handle.join();
2434            }
2435            // Drain any signal we did not consume.
2436            drop(completion.take());
2437        } else {
2438            // Timeout: bump the abandoned counter and detach the handle.
2439            // The worker is still running and may eventually finish; the
2440            // in-flight I/O either completes or fails on its own.
2441            if let Some(writer) = writer.as_ref() {
2442                writer.record_outcome(DrainOutcome::Abandoned);
2443            }
2444            self.take_persistent_worker(); // drop the handle, do not join
2445        }
2446        // Transition publication to `Disabled(WorkerShutdown)`: subsequent
2447        // inserts keep their in-memory entry and skip persistent publication
2448        // (REM-D §8.5). The transition and the shutdown are both counted.
2449        if matches!(self.persistence, PersistentPublicationState::Async(_)) {
2450            self.worker_shutdown_total
2451                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2452            self.persist_unavailable_total
2453                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2454            self.persistence =
2455                PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerShutdown);
2456        }
2457    }
2458
2459    /// Set the minimum entry size (approx bytes) before the persistent tier
2460    /// is written. 0 always persists. Exposed as a `pub(crate)` so the test
2461    /// seam on `Table` can drive sub-4KiB fixtures through the on-disk path.
2462    pub(crate) fn set_persist_min_bytes(&mut self, min: u64) {
2463        self.persist_min_bytes = min;
2464    }
2465
2466    /// True when the last insert of an entry of size `approx` would hit disk.
2467    #[cfg(test)]
2468    fn would_persist(&self, approx: u64) -> bool {
2469        self.dir.is_some() && (self.persist_min_bytes == 0 || approx >= self.persist_min_bytes)
2470    }
2471
2472    /// Read the per-tier counters. Returned as `(memory_hit, disk_hit, miss,
2473    /// persistent_write_us)` so callers can roll them into their own snapshot.
2474    fn cache_counters(&self) -> (u64, u64, u64, u64) {
2475        (
2476            self.memory_hit.load(std::sync::atomic::Ordering::Relaxed),
2477            self.disk_hit.load(std::sync::atomic::Ordering::Relaxed),
2478            self.miss.load(std::sync::atomic::Ordering::Relaxed),
2479            self.persistent_write_us
2480                .load(std::sync::atomic::Ordering::Relaxed),
2481        )
2482    }
2483
2484    /// Read the REM-D §8.7 publication-availability counters. Returned as
2485    /// `(persist_unavailable_total, persist_skipped_total,
2486    /// worker_spawn_failures_total, worker_shutdown_total)`.
2487    fn publication_counters(&self) -> (u64, u64, u64, u64) {
2488        (
2489            self.persist_unavailable_total
2490                .load(std::sync::atomic::Ordering::Relaxed),
2491            self.persist_skipped_total
2492                .load(std::sync::atomic::Ordering::Relaxed),
2493            self.worker_spawn_failures_total
2494                .load(std::sync::atomic::Ordering::Relaxed),
2495            self.worker_shutdown_total
2496                .load(std::sync::atomic::Ordering::Relaxed),
2497        )
2498    }
2499
2500    /// Snapshot of the writer's persist counters. `None` when no writer is
2501    /// installed (publication disabled).
2502    fn persist_snapshot(&self) -> Option<LookupMetricsSnapshot> {
2503        self.persistent_writer().map(|w| w.persist_snapshot())
2504    }
2505
2506    /// Fine-grained invalidation (hardening (c)). Drop only entries that are
2507    /// actually affected by the committed mutations:
2508    /// - **Delete path**: if `delete_rids` intersects an entry's footprint, a
2509    ///   survivor was deleted → stale. If the footprint is empty (multi-run or
2510    ///   non-empty memtable — we couldn't resolve it), **any** delete
2511    ///   conservatively invalidates the entry (correctness over precision).
2512    /// - **Insert path**: if `put_cols` intersects an entry's `condition_cols`,
2513    ///   a newly-inserted row might match the query → conservatively stale.
2514    fn invalidate(
2515        &mut self,
2516        delete_rids: &roaring::RoaringBitmap,
2517        put_cols: &std::collections::HashSet<u16>,
2518    ) {
2519        if self.entries.is_empty() {
2520            return;
2521        }
2522        let has_deletes = !delete_rids.is_empty();
2523        let mut to_remove = HashSet::new();
2524
2525        // Inserts/updates are the common mutation path. Resolve affected cache
2526        // keys directly from the condition-column reverse index instead of
2527        // scanning every cached result on every commit.
2528        for column in put_cols {
2529            if let Some(keys) = self.condition_index.get(column) {
2530                to_remove.extend(keys.iter().copied());
2531            }
2532        }
2533
2534        if has_deletes {
2535            // Entries with an unknown footprint are conservatively stale after
2536            // any delete. Known footprints still require a bitmap intersection;
2537            // this scan is paid only by delete commits, not every insert.
2538            to_remove.extend(self.empty_footprint_entries.iter().copied());
2539            for (&key, entry) in &self.entries {
2540                if !to_remove.contains(&key)
2541                    && !entry.footprint.is_empty()
2542                    && entry.footprint.intersection_len(delete_rids) > 0
2543                {
2544                    to_remove.insert(key);
2545                }
2546            }
2547        }
2548
2549        for key in to_remove {
2550            if let Some(entry) = self.entries.remove(&key) {
2551                self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2552                self.unindex_entry(key, &entry);
2553            }
2554            // When a background writer is installed, the on-disk file is
2555            // removed asynchronously by the worker; otherwise, fall back to
2556            // the legacy synchronous `remove_from_disk` so early test paths
2557            // (which build a `ResultCache` directly) keep working.
2558            if self.persistent_writer().is_some() {
2559                self.enqueue_persist_remove(key);
2560            } else {
2561                self.remove_from_disk(key);
2562            }
2563            self.untrack(key);
2564        }
2565    }
2566
2567    fn clear(&mut self) {
2568        // Delete all persistent files (b). When a background writer is
2569        // installed, the on-disk files are removed asynchronously by the
2570        // worker; otherwise, fall back to the legacy synchronous scan.
2571        if self.dir.is_some() {
2572            if self.persistent_writer().is_some() {
2573                self.enqueue_persist_clear();
2574            } else if let Some(dir) = &self.dir {
2575                if let Ok(entries) = std::fs::read_dir(dir) {
2576                    for entry in entries.flatten() {
2577                        let path = entry.path();
2578                        if path.extension().and_then(|e| e.to_str()) == Some("bin") {
2579                            let _ = std::fs::remove_file(&path);
2580                        }
2581                    }
2582                }
2583            }
2584        }
2585        self.entries.clear();
2586        self.order.clear();
2587        self.generations.clear();
2588        self.next_generation = 0;
2589        self.condition_index.clear();
2590        self.empty_footprint_entries.clear();
2591        self.bytes = 0;
2592    }
2593
2594    fn evict(&mut self) {
2595        while self.bytes > self.max_bytes {
2596            let Some((_, key)) = self.order.pop_first() else {
2597                break;
2598            };
2599            self.generations.remove(&key);
2600            if let Some(entry) = self.entries.remove(&key) {
2601                self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2602                self.unindex_entry(key, &entry);
2603                // The on-disk file is left in place. The persistent
2604                // loader validates the frame's `logical_generation` on
2605                // every load (REM-002 §18.4), so a stale file from a
2606                // pre-commit epoch is rejected as `GenerationMismatch` and
2607                // deleted on read. Deleting the file at eviction time
2608                // would defeat the "memory eviction → disk hit" path
2609                // exercised by the production tests.
2610            }
2611        }
2612    }
2613}
2614
2615/// Set up the persistent-publication writer for a fresh `ResultCache`. The
2616/// returned tuple is `(writer, worker_join_handle, completion_receiver)`;
2617/// pass `writer` and `worker_join_handle` to
2618/// [`ResultCache::install_persistent_writer`], and the `completion_receiver`
2619/// to the cache so `shutdown_persistent_cache(deadline)` can wait on a
2620/// bounded deadline. The caller is responsible for joining the worker on
2621/// `shutdown_persistent_cache(deadline)`.
2622fn spawn_persistent_cache_worker(
2623    dir: std::path::PathBuf,
2624    cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
2625    metrics: LookupMetrics,
2626) -> std::io::Result<(
2627    std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
2628    std::thread::JoinHandle<()>,
2629    std::sync::mpsc::Receiver<()>,
2630)> {
2631    use crate::result_cache::{
2632        spawn_persistent_cache_worker as spawn, RealPersistentCacheIo, StalenessGuard,
2633        WorkerConfig, WriterStalenessGuard,
2634    };
2635    // Test seam (REM-D §8.8): force worker startup failure through the real
2636    // `Table::create` / `Table::open` wiring. Thread-local so parallel tests
2637    // in the same process are unaffected.
2638    if PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.get()) {
2639        return Err(std::io::Error::other(
2640            "persistent-cache worker spawn failure forced by test seam",
2641        ));
2642    }
2643    let io: std::sync::Arc<dyn crate::result_cache::PersistentCacheIo> =
2644        std::sync::Arc::new(RealPersistentCacheIo::new(dir)?);
2645    let cipher = match cache_dek {
2646        Some(dek) => {
2647            let cipher = crate::encryption::AesCipher::new(&dek[..])
2648                .map_err(|e| std::io::Error::other(format!("aes: {e}")))?;
2649            Some(std::sync::Arc::new(cipher))
2650        }
2651        None => None,
2652    };
2653    let writer = std::sync::Arc::new(crate::result_cache::PersistentResultCacheWriter::new(
2654        metrics,
2655        crate::result_cache::WriterLimits::default(),
2656    ));
2657    let staleness: std::sync::Arc<dyn StalenessGuard> =
2658        std::sync::Arc::new(WriterStalenessGuard::new(writer.clone()));
2659    let (completion_tx, completion_rx) = std::sync::mpsc::channel();
2660    let config = WorkerConfig {
2661        writer: writer.clone(),
2662        io,
2663        cipher,
2664        staleness,
2665        max_staleness_retries: 8,
2666        completion: Some(completion_tx),
2667    };
2668    let handle = spawn(config);
2669    Ok((writer, handle, completion_rx))
2670}
2671
2672thread_local! {
2673    /// Thread-local test seam (REM-D §8.8): when set,
2674    /// [`spawn_persistent_cache_worker`] fails deterministically so tests can
2675    /// exercise the "worker startup failure" path through the real
2676    /// `Table::create` / `Table::open` wiring. Thread-local so concurrently
2677    /// running tests are unaffected. Reset by
2678    /// [`Table::_force_persistent_worker_spawn_failure_for_test`].
2679    static PERSISTENT_WORKER_SPAWN_FAILURE: std::cell::Cell<bool> =
2680        const { std::cell::Cell::new(false) };
2681}
2682
2683#[cfg(test)]
2684mod result_cache_lru_tests {
2685    use super::*;
2686
2687    fn row_entry(row_id: u64) -> CachedEntry {
2688        CachedEntry {
2689            data: CachedData::Rows(Arc::new(vec![Row::new(RowId(row_id), Epoch(1))])),
2690            footprint: std::iter::once(row_id as u32).collect(),
2691            condition_cols: vec![1],
2692        }
2693    }
2694
2695    #[test]
2696    fn hits_update_recency_without_growing_an_order_queue() {
2697        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2698        let identity = PersistentCacheIdentity {
2699            table_id: 0,
2700            schema_id: 0,
2701            logical_generation: 0,
2702        };
2703        cache.insert(1, row_entry(1));
2704        cache.insert(2, row_entry(2));
2705        assert_eq!(cache.order.len(), cache.entries.len());
2706
2707        for _ in 0..1_000 {
2708            assert!(cache.get_rows(1, identity).is_some());
2709        }
2710
2711        assert_eq!(cache.order.len(), cache.entries.len());
2712        assert_eq!(cache.order.first().map(|(_, key)| *key), Some(2));
2713
2714        let one_entry = cache.entries[&1].data.approx_bytes();
2715        cache.set_max_bytes(one_entry);
2716        assert!(cache.entries.contains_key(&1));
2717        assert!(!cache.entries.contains_key(&2));
2718        assert_eq!(cache.order.len(), cache.entries.len());
2719    }
2720
2721    #[test]
2722    fn tiny_entries_skip_persistent_tier_by_default() {
2723        let dir = tempfile::tempdir().unwrap();
2724        let mut cache = ResultCache::with_max_bytes(u64::MAX).with_dir(dir.path().to_path_buf());
2725        let tiny = row_entry(1).data.approx_bytes();
2726        assert!(
2727            tiny < 4 * 1024,
2728            "row_entry fixture must be below default 4KiB threshold"
2729        );
2730        assert!(
2731            !cache.would_persist(tiny),
2732            "tiny entry must not force synchronous disk publish"
2733        );
2734        assert!(
2735            cache.would_persist(8 * 1024),
2736            "large entry must still persist when dir is set"
2737        );
2738        cache.set_persist_min_bytes(0);
2739        assert!(
2740            cache.would_persist(tiny),
2741            "persist_min_bytes=0 restores always-persist policy"
2742        );
2743    }
2744
2745    #[test]
2746    fn insert_invalidation_uses_the_condition_reverse_index() {
2747        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2748        let mut first = row_entry(1);
2749        first.condition_cols = vec![1];
2750        let mut second = row_entry(2);
2751        second.condition_cols = vec![2];
2752        cache.insert(1, first);
2753        cache.insert(2, second);
2754
2755        let put_cols = std::iter::once(1_u16).collect();
2756        cache.invalidate(&roaring::RoaringBitmap::new(), &put_cols);
2757
2758        assert!(!cache.entries.contains_key(&1));
2759        assert!(cache.entries.contains_key(&2));
2760        assert!(!cache
2761            .condition_index
2762            .get(&1)
2763            .is_some_and(|keys| keys.contains(&1)));
2764        assert!(cache
2765            .condition_index
2766            .get(&2)
2767            .is_some_and(|keys| keys.contains(&2)));
2768        assert_eq!(cache.order.len(), cache.entries.len());
2769    }
2770
2771    #[test]
2772    fn delete_invalidation_preserves_known_and_unknown_footprint_semantics() {
2773        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2774        cache.insert(1, row_entry(1));
2775        cache.insert(2, row_entry(2));
2776        let mut unknown = row_entry(3);
2777        unknown.footprint.clear();
2778        cache.insert(3, unknown);
2779
2780        let delete_rids: roaring::RoaringBitmap = std::iter::once(1_u32).collect();
2781        cache.invalidate(&delete_rids, &HashSet::new());
2782
2783        assert!(!cache.entries.contains_key(&1));
2784        assert!(cache.entries.contains_key(&2));
2785        assert!(!cache.entries.contains_key(&3));
2786        assert!(cache.empty_footprint_entries.is_empty());
2787        assert_eq!(cache.order.len(), cache.entries.len());
2788    }
2789
2790    #[test]
2791    fn borrowed_persistence_encoding_matches_the_existing_owned_format() {
2792        let entry = row_entry(7);
2793        let borrowed = bincode::serialize(&SerializedEntryRef::from_entry(&entry)).unwrap();
2794        let owned = bincode::serialize(&SerializedEntry {
2795            condition_cols: entry.condition_cols.clone(),
2796            footprint_bits: entry.footprint.iter().collect(),
2797            data: match &entry.data {
2798                CachedData::Rows(rows) => SerializedData::Rows((**rows).clone()),
2799                CachedData::Columns(columns) => SerializedData::Columns((**columns).clone()),
2800            },
2801        })
2802        .unwrap();
2803        assert_eq!(borrowed, owned);
2804    }
2805}
2806
2807/// Derive per-column indexable-encryption keys (Phase 10.2) for every
2808/// ENCRYPTED_INDEXABLE column from the KEK. Scheme is `OPE_RANGE` if the column
2809/// has a `LearnedRange` index, else `HMAC_EQ` (equality). Keys are derived
2810/// deterministically from the KEK so tokens are stable across runs. Empty when
2811/// the table is plaintext (no KEK).
2812/// Derive WAL and cache DEKs from the KEK (None when no encryption).
2813type DekaOpt = Option<Zeroizing<[u8; DEK_LEN]>>;
2814
2815fn derive_subkeys(kek: Option<&Kek>, _table_id: u64) -> (DekaOpt, DekaOpt) {
2816    let _ = kek;
2817    {
2818        if let Some(k) = kek {
2819            return (
2820                Some(k.derive_table_wal_key(_table_id)),
2821                Some(k.derive_cache_key()),
2822            );
2823        }
2824    }
2825    (None, None)
2826}
2827
2828fn read_table_encryption_salt_root(
2829    root: &crate::durable_file::DurableRoot,
2830) -> Result<[u8; crate::encryption::SALT_LEN]> {
2831    use std::io::Read;
2832
2833    let mut file = root
2834        .open_regular(Path::new(META_DIR).join(KEYS_FILENAME))
2835        .map_err(|error| MongrelError::NotFound(format!("encryption salt file: {error}")))?;
2836    let length = file.metadata()?.len();
2837    if length != crate::encryption::SALT_LEN as u64 {
2838        return Err(MongrelError::InvalidArgument(format!(
2839            "salt file is {length} bytes, expected {}",
2840            crate::encryption::SALT_LEN
2841        )));
2842    }
2843    let mut salt = [0_u8; crate::encryption::SALT_LEN];
2844    file.read_exact(&mut salt)?;
2845    Ok(salt)
2846}
2847
2848/// Create a boxed cipher from a DEK.
2849fn make_cipher(dek: &Zeroizing<[u8; DEK_LEN]>) -> Box<dyn crate::encryption::Cipher> {
2850    Box::new(crate::encryption::AesCipher::new(&dek[..]).expect("DEK is 32 bytes"))
2851}
2852
2853fn build_column_keys(kek: Option<&Kek>, schema: &Schema) -> HashMap<u16, ([u8; 32], u8)> {
2854    let Some(kek) = kek else {
2855        return HashMap::new();
2856    };
2857    {
2858        use crate::encryption::{SCHEME_HMAC_EQ, SCHEME_OPE_RANGE};
2859        schema
2860            .columns
2861            .iter()
2862            .filter(|c| c.flags.contains(ColumnFlags::ENCRYPTED_INDEXABLE))
2863            .map(|c| {
2864                let scheme = if schema
2865                    .indexes
2866                    .iter()
2867                    .any(|i| i.column_id == c.id && i.kind == IndexKind::LearnedRange)
2868                {
2869                    SCHEME_OPE_RANGE
2870                } else {
2871                    SCHEME_HMAC_EQ
2872                };
2873                let key: [u8; 32] = *kek.derive_column_key(c.id);
2874                (c.id, (key, scheme))
2875            })
2876            .collect()
2877    }
2878}
2879
2880/// Shared services injected into every `Table` owned by a `Database`: one epoch
2881/// authority (single commit clock), one raw-page cache, one decoded-page cache,
2882/// one snapshot-retention registry, and the DB-wide KEK. A directly-opened
2883/// single table builds a private `SharedCtx` of its own.
2884pub(crate) struct SharedCtx {
2885    pub root_guard: Option<Arc<crate::durable_file::DurableRoot>>,
2886    pub epoch: Arc<EpochAuthority>,
2887    pub page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
2888    pub decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
2889    pub snapshots: Arc<crate::retention::SnapshotRegistry>,
2890    pub kek: Option<Arc<Kek>>,
2891    /// Serializes the commit critical section across all tables sharing this
2892    /// context so the dual-counter's in-order-publish invariant holds: the
2893    /// assigned ticket is reserved, the WAL fsynced, the manifest persisted,
2894    /// and `visible` published as one atomic unit. P3 replaces this with the
2895    /// bounded validate-first sequencer + group commit (overlapping fsync).
2896    pub commit_lock: Arc<parking_lot::Mutex<()>>,
2897    /// B1: when `Some`, the table is mounted in a `Database` and routes every
2898    /// write through the one shared WAL (no private `_wal/` dir is created).
2899    /// `None` for a directly-opened standalone table, which keeps a private WAL.
2900    pub shared: Option<SharedWalCtx>,
2901    /// The table's catalog name (for auth enforcement). `None` on standalone
2902    /// direct-open tables that have no catalog entry.
2903    pub table_name: Option<String>,
2904    /// Auth checker for per-operation enforcement. `None` on credentialless
2905    /// databases; cloned from the `Database`'s `auth_state` wrapper.
2906    pub auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
2907    /// Whether logical writes must be rejected for a replica database.
2908    pub read_only: bool,
2909}
2910
2911/// Handles a mounted table needs to write to the database's single shared WAL
2912/// (B1): the WAL itself, the group-commit coordinator + poison flag (so a
2913/// single-table commit honors the same durability/§9.3e semantics as a cross-
2914/// table txn), and the shared txn-id allocator (so auto-commit ids never alias
2915/// cross-table ones in the merged log).
2916#[derive(Clone)]
2917pub(crate) struct SharedWalCtx {
2918    pub wal: Arc<parking_lot::Mutex<SharedWal>>,
2919    pub group: Arc<GroupCommit>,
2920    pub poisoned: Arc<AtomicBool>,
2921    pub txn_ids: Arc<parking_lot::Mutex<u64>>,
2922    pub change_wake: tokio::sync::broadcast::Sender<()>,
2923    /// S1A-004: the owning core's lifecycle, poisoned at every fsync-error
2924    /// site so the whole core rejects later operations.
2925    pub lifecycle: Arc<crate::core::LifecycleController>,
2926    /// Database HLC clock used to stamp single-table commit row versions (P0.5).
2927    pub hlc: Arc<mongreldb_types::hlc::HlcClock>,
2928}
2929
2930/// Where a table's WAL records go. A standalone table owns a `Private` WAL; a
2931/// `Database`-mounted table writes to the one `Shared` WAL (B1).
2932enum WalSink {
2933    Private(Wal),
2934    Shared(SharedWalCtx),
2935    ReadOnly,
2936}
2937
2938impl Clone for WalSink {
2939    fn clone(&self) -> Self {
2940        match self {
2941            Self::Shared(shared) => Self::Shared(shared.clone()),
2942            Self::Private(_) | Self::ReadOnly => Self::ReadOnly,
2943        }
2944    }
2945}
2946
2947impl SharedCtx {
2948    /// Build a fresh private (standalone) context. `cache_dir = Some(_)` enables
2949    /// on-disk page cache persistence (single-table direct open); `None` keeps
2950    /// it in-memory (shared across tables in a `Database`).
2951    pub(crate) fn new(kek: Option<Arc<Kek>>, cache_dir: Option<PathBuf>) -> Self {
2952        // §5.8: shard the caches to reduce lock contention under parallel
2953        // rayon scans. The persistent (single-table) path uses 1 shard (no
2954        // contention) so its on-disk load/spill stays simple.
2955        let n_shards = if cache_dir.is_some() {
2956            1
2957        } else {
2958            crate::cache::CACHE_SHARDS
2959        };
2960        let per_shard = PAGE_CACHE_CAPACITY / n_shards as u64;
2961        let page_cache = if let Some(d) = cache_dir {
2962            Arc::new(crate::cache::Sharded::new(1, || {
2963                crate::cache::PageCache::new(PAGE_CACHE_CAPACITY).with_persistence(d.clone())
2964            }))
2965        } else {
2966            Arc::new(crate::cache::Sharded::new(n_shards, || {
2967                crate::cache::PageCache::new(per_shard)
2968            }))
2969        };
2970        let decoded_per_shard = DECODED_CACHE_CAPACITY / crate::cache::CACHE_SHARDS as u64;
2971        let decoded_cache = Arc::new(crate::cache::Sharded::new(
2972            crate::cache::CACHE_SHARDS,
2973            || crate::cache::DecodedPageCache::new(decoded_per_shard),
2974        ));
2975        Self {
2976            root_guard: None,
2977            epoch: Arc::new(EpochAuthority::new(0)),
2978            page_cache,
2979            decoded_cache,
2980            snapshots: Arc::new(crate::retention::SnapshotRegistry::new()),
2981            kek,
2982            commit_lock: Arc::new(parking_lot::Mutex::new(())),
2983            shared: None,
2984            table_name: None,
2985            auth: None,
2986            read_only: false,
2987        }
2988    }
2989}
2990
2991/// §5.5: estimated per-condition resolution cost for cheap-first conjunction
2992/// ordering. Lower is resolved first so a selective O(1) index lookup can
2993/// short-circuit an expensive range/FM/vector scan.
2994fn condition_cost_rank(c: &crate::query::Condition) -> u8 {
2995    use crate::query::Condition;
2996    match c {
2997        // O(1) index lookups — resolve first.
2998        Condition::Pk(_)
2999        | Condition::BitmapEq { .. }
3000        | Condition::BitmapIn { .. }
3001        | Condition::BytesPrefix { .. }
3002        | Condition::IsNull { .. }
3003        | Condition::IsNotNull { .. } => 0,
3004        // Page-pruned scan or LSH candidate lookup.
3005        Condition::Range { .. } | Condition::RangeF64 { .. } | Condition::MinHashSimilar { .. } => {
3006            1
3007        }
3008        // FM locate / vector scans — most expensive, resolve last.
3009        Condition::FmContains { .. }
3010        | Condition::FmContainsAll { .. }
3011        | Condition::Ann { .. }
3012        | Condition::SparseMatch { .. } => 2,
3013    }
3014}
3015
3016impl Table {
3017    /// Build one hidden secondary index from authoritative visible rows.
3018    /// Callers run this against a pinned read generation, outside the final
3019    /// publication barrier. `checkpoint` supplies cooperative cancellation,
3020    /// resource checks, and progress reporting without coupling the engine to
3021    /// the jobs framework.
3022    pub(crate) fn build_secondary_index_artifact<F>(
3023        &self,
3024        definition: &IndexDef,
3025        rows: &[Row],
3026        mut checkpoint: F,
3027    ) -> Result<SecondaryIndexArtifact>
3028    where
3029        F: FnMut(usize, usize) -> Result<()>,
3030    {
3031        let mut build_schema = self.schema.clone();
3032        build_schema.indexes = vec![definition.clone()];
3033        let (mut bitmap, mut ann, mut fm, mut sparse, mut minhash) = empty_indexes(&build_schema);
3034        let name_to_id: HashMap<&str, u16> = self
3035            .schema
3036            .columns
3037            .iter()
3038            .map(|column| (column.name.as_str(), column.id))
3039            .collect();
3040        let mut hot = HotIndex::new();
3041        let mut accepted = Vec::with_capacity(rows.len());
3042
3043        for (offset, row) in rows.iter().enumerate() {
3044            checkpoint(offset, rows.len())?;
3045            if row.deleted {
3046                continue;
3047            }
3048            if let Some(predicate) = &definition.predicate {
3049                let columns: HashMap<u16, &Value> =
3050                    row.columns.iter().map(|(id, value)| (*id, value)).collect();
3051                if !eval_partial_predicate(predicate, &columns, &name_to_id) {
3052                    continue;
3053                }
3054            }
3055            accepted.push(row);
3056            if definition.kind == IndexKind::LearnedRange {
3057                continue;
3058            }
3059            let effective = if self.column_keys.is_empty() {
3060                row.clone()
3061            } else {
3062                self.tokenized_for_indexes(row)
3063            };
3064            if definition.kind == IndexKind::Ann {
3065                if let (Some(index), Some(vector)) = (
3066                    ann.get_mut(&definition.column_id),
3067                    effective
3068                        .columns
3069                        .get(&definition.column_id)
3070                        .and_then(Value::as_embedding),
3071                ) {
3072                    index.insert_validated_with_checkpoint(vector, effective.row_id, || {
3073                        checkpoint(offset, rows.len())
3074                    })?;
3075                }
3076            } else {
3077                index_into_single(
3078                    definition,
3079                    &build_schema,
3080                    &effective,
3081                    &mut hot,
3082                    &mut bitmap,
3083                    &mut ann,
3084                    &mut fm,
3085                    &mut sparse,
3086                    &mut minhash,
3087                );
3088            }
3089        }
3090        checkpoint(rows.len(), rows.len())?;
3091
3092        if let Some(index) = ann.get_mut(&definition.column_id) {
3093            index.seal_with_checkpoint(|| checkpoint(rows.len(), rows.len()))?;
3094        }
3095
3096        let column_id = definition.column_id;
3097        match definition.kind {
3098            IndexKind::Bitmap => bitmap
3099                .remove(&column_id)
3100                .map(|index| SecondaryIndexArtifact::Bitmap(column_id, index)),
3101            IndexKind::Ann => ann
3102                .remove(&column_id)
3103                .map(|index| SecondaryIndexArtifact::Ann(column_id, Box::new(index))),
3104            IndexKind::FmIndex => fm
3105                .remove(&column_id)
3106                .map(|index| SecondaryIndexArtifact::Fm(column_id, Box::new(index))),
3107            IndexKind::Sparse => sparse
3108                .remove(&column_id)
3109                .map(|index| SecondaryIndexArtifact::Sparse(column_id, index)),
3110            IndexKind::MinHash => minhash
3111                .remove(&column_id)
3112                .map(|index| SecondaryIndexArtifact::MinHash(column_id, index)),
3113            IndexKind::LearnedRange => {
3114                let epsilon = definition
3115                    .options
3116                    .learned_range
3117                    .as_ref()
3118                    .map(|options| options.epsilon)
3119                    .unwrap_or(16);
3120                let column = self
3121                    .schema
3122                    .columns
3123                    .iter()
3124                    .find(|column| column.id == column_id)
3125                    .ok_or_else(|| {
3126                        MongrelError::Schema(format!(
3127                            "index {} references unknown column {column_id}",
3128                            definition.name
3129                        ))
3130                    })?;
3131                let index = match column.ty {
3132                    TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
3133                        let pairs: Vec<_> = accepted
3134                            .iter()
3135                            .filter_map(|row| match row.columns.get(&column_id) {
3136                                Some(Value::Int64(value)) if !row.deleted => {
3137                                    Some((*value, row.row_id.0))
3138                                }
3139                                _ => None,
3140                            })
3141                            .collect();
3142                        ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon)
3143                    }
3144                    TypeId::Float32 | TypeId::Float64 => {
3145                        let pairs: Vec<_> = accepted
3146                            .iter()
3147                            .filter_map(|row| match row.columns.get(&column_id) {
3148                                Some(Value::Float64(value)) if !row.deleted => {
3149                                    Some((*value, row.row_id.0))
3150                                }
3151                                _ => None,
3152                            })
3153                            .collect();
3154                        ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon)
3155                    }
3156                    ref ty => {
3157                        return Err(MongrelError::Schema(format!(
3158                            "LearnedRange index {} does not support {ty:?}",
3159                            definition.name
3160                        )));
3161                    }
3162                };
3163                Some(SecondaryIndexArtifact::LearnedRange(column_id, index))
3164            }
3165        }
3166        .ok_or_else(|| {
3167            MongrelError::Other(format!(
3168                "failed to construct hidden index {}",
3169                definition.name
3170            ))
3171        })
3172    }
3173
3174    pub fn create(dir: impl AsRef<Path>, schema: Schema, table_id: u64) -> Result<Self> {
3175        let dir = dir.as_ref().to_path_buf();
3176        // Use std::fs (no eager parent-fsync) — the deferred root's finalize
3177        // pass makes the entry durable at the end of create.
3178        std::fs::create_dir_all(&dir)?;
3179        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3180        let pinned = root.io_path()?;
3181        let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3182        ctx.root_guard = Some(root.clone());
3183        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3184        // Shallow finalize: root-level files (schema, manifest) are
3185        // data-durable, root + immediate subdirs are entry-durable. Files
3186        // inside `_wal/` and `_runs/` rely on the first commit/flush (same
3187        // contract as the pre-hardening path). Encrypted tables use the full
3188        // recursive `finalize_deferred_sync` via `create_encrypted`.
3189        root.finalize_deferred_sync_shallow()?;
3190        Ok(table)
3191    }
3192
3193    /// Create a new encrypted table, deriving the table Key-Encryption Key
3194    /// (KEK) from `passphrase` via Argon2id + HKDF (§7). A fresh random salt is
3195    /// generated and persisted under `_meta/keys` so the same passphrase
3196    /// recreates the KEK on reopen. Each run gets its own wrapped DEK.
3197    ///
3198    /// **Scope (§7):** encryption is *page-granular* — only sorted-run page
3199    /// payloads are encrypted. The live WAL (`_wal/`) holds rows as plaintext
3200    /// between `put` and `flush`; call `flush()` (which rotates the WAL) before
3201    /// treating sensitive data as fully at-rest-protected. Full WAL encryption
3202    /// is deferred.
3203    pub fn create_encrypted(
3204        dir: impl AsRef<Path>,
3205        schema: Schema,
3206        table_id: u64,
3207        passphrase: &str,
3208    ) -> Result<Self> {
3209        let dir = dir.as_ref().to_path_buf();
3210        std::fs::create_dir_all(&dir)?;
3211        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3212        root.create_directory_all(META_DIR)?;
3213        let salt = crate::encryption::random_salt()?;
3214        root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3215        let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3216        let pinned = root.io_path()?;
3217        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3218        ctx.root_guard = Some(root.clone());
3219        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3220        root.finalize_deferred_sync()?;
3221        Ok(table)
3222    }
3223
3224    /// Create a new encrypted table using a raw key (e.g. from a key file)
3225    /// instead of a passphrase. Skips Argon2id — the key must already be
3226    /// high-entropy (>= 32 bytes of random data). ~0.1ms vs ~50ms for the
3227    /// passphrase path.
3228    pub fn create_with_key(
3229        dir: impl AsRef<Path>,
3230        schema: Schema,
3231        table_id: u64,
3232        key: &[u8],
3233    ) -> Result<Self> {
3234        let dir = dir.as_ref().to_path_buf();
3235        std::fs::create_dir_all(&dir)?;
3236        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3237        root.create_directory_all(META_DIR)?;
3238        let salt = crate::encryption::random_salt()?;
3239        root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3240        let kek: Arc<Kek> = Arc::new(Kek::from_raw_key(key, &salt)?);
3241        let pinned = root.io_path()?;
3242        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3243        ctx.root_guard = Some(root.clone());
3244        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3245        root.finalize_deferred_sync()?;
3246        Ok(table)
3247    }
3248
3249    /// Open an existing encrypted table using a raw key.
3250    pub fn open_with_key(dir: impl AsRef<Path>, key: &[u8]) -> Result<Self> {
3251        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3252        let salt = read_table_encryption_salt_root(&root)?;
3253        let kek = Arc::new(Kek::from_raw_key(key, &salt)?);
3254        let pinned = root.io_path()?;
3255        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3256        ctx.root_guard = Some(root);
3257        Self::open_in(&pinned, ctx)
3258    }
3259
3260    pub(crate) fn create_in(
3261        dir: impl AsRef<Path>,
3262        schema: Schema,
3263        table_id: u64,
3264        ctx: SharedCtx,
3265    ) -> Result<Self> {
3266        schema.validate_auto_increment()?;
3267        schema.validate_defaults()?;
3268        schema.validate_ai()?;
3269        for index in &schema.indexes {
3270            index.validate_options()?;
3271        }
3272        let dir = dir.as_ref().to_path_buf();
3273        let runs_root = match ctx.root_guard.as_ref() {
3274            Some(root) => Some(Arc::new(root.create_directory_all_pinned(RUNS_DIR)?)),
3275            None => {
3276                crate::durable_file::create_directory_all(&dir)?;
3277                crate::durable_file::create_directory_all(&dir.join(RUNS_DIR))?;
3278                None
3279            }
3280        };
3281        match ctx.root_guard.as_deref() {
3282            Some(root) => write_schema_durable(root, &schema)?,
3283            None => write_schema(&dir, &schema)?,
3284        }
3285        let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), table_id);
3286        // B1: a mounted table routes writes through the shared WAL and never
3287        // creates its own `_wal/` dir. A standalone table owns a private WAL.
3288        let (wal, current_txn_id) = match ctx.shared.clone() {
3289            Some(s) => (WalSink::Shared(s), 0),
3290            None => {
3291                let pinned_wal_root = match ctx.root_guard.as_deref() {
3292                    Some(root) => Some(root.create_directory_all_pinned(WAL_DIR)?),
3293                    None => None,
3294                };
3295                let wal_dir = if let Some(root) = pinned_wal_root.as_ref() {
3296                    root.io_path()?
3297                } else {
3298                    let wal_dir = dir.join(WAL_DIR);
3299                    std::fs::create_dir_all(&wal_dir)?;
3300                    wal_dir
3301                };
3302                let mut w = match (pinned_wal_root.as_ref(), wal_dek.as_ref()) {
3303                    (Some(root), Some(dk)) => {
3304                        Wal::create_in_root(root, 0, Epoch(0), Some(make_cipher(dk)))?
3305                    }
3306                    (Some(root), None) => Wal::create_in_root(root, 0, Epoch(0), None)?,
3307                    (None, Some(dk)) => Wal::create_with_cipher(
3308                        wal_dir.join("seg-000000.wal"),
3309                        Epoch(0),
3310                        Some(make_cipher(dk)),
3311                        0,
3312                    )?,
3313                    (None, None) => Wal::create(wal_dir.join("seg-000000.wal"), Epoch(0))?,
3314                };
3315                w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3316                (WalSink::Private(w), 1)
3317            }
3318        };
3319        let mut manifest = Manifest::new(table_id, schema.schema_id);
3320        // Seal the create-time manifest with the meta DEK so an encrypted table
3321        // reopens even if no write/flush ever re-persists it (otherwise the
3322        // reopen's encrypted manifest read fails to authenticate a plaintext
3323        // blob — see `manifest_meta_dek`).
3324        let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3325        match ctx.root_guard.as_deref() {
3326            Some(root) => manifest::write_durable(root, &mut manifest, manifest_meta_dek.as_ref())?,
3327            None => manifest::write_atomic(&dir, &mut manifest, manifest_meta_dek.as_ref())?,
3328        }
3329        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&schema);
3330        let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3331        let auto_inc = resolve_auto_inc(&schema);
3332        let rcache_dir = dir.join(RCACHE_DIR);
3333        let initial_view = ReadGeneration::empty(&schema);
3334        Ok(Self {
3335            dir,
3336            _root_guard: ctx.root_guard,
3337            runs_root,
3338            idx_root: None,
3339            table_id,
3340            name: ctx.table_name.unwrap_or_default(),
3341            auth: ctx.auth,
3342            read_only: ctx.read_only,
3343            durable_commit_failed: false,
3344            wal,
3345            memtable: Memtable::new(),
3346            mutable_run: MutableRun::new(),
3347            mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3348            compaction_zstd_level: 3,
3349            allocator: RowIdAllocator::new(0),
3350            epoch: ctx.epoch,
3351            data_generation: 0,
3352            schema,
3353            hot: HotIndex::new(),
3354            kek: ctx.kek,
3355            column_keys,
3356            run_refs: Vec::new(),
3357            retiring: Vec::new(),
3358            next_run_id: 1,
3359            sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3360            current_txn_id,
3361            pending_private_mutations: false,
3362            bitmap,
3363            ann,
3364            fm,
3365            sparse,
3366            minhash,
3367            learned_range: Arc::new(HashMap::new()),
3368            pk_by_row: ReversePkMap::new(),
3369            pinned: BTreeMap::new(),
3370            live_count: 0,
3371            reservoir: crate::reservoir::Reservoir::default(),
3372            reservoir_complete: true,
3373            had_deletes: false,
3374            recent_delete_preimages: HashMap::new(),
3375            run_row_id_ranges: HashMap::new(),
3376            agg_cache: Arc::new(HashMap::new()),
3377            global_idx_epoch: 0,
3378            indexes_complete: true,
3379            index_build_policy: IndexBuildPolicy::default(),
3380            pk_by_row_complete: false,
3381            flushed_epoch: 0,
3382            page_cache: ctx.page_cache,
3383            decoded_cache: ctx.decoded_cache,
3384            verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3385            snapshots: ctx.snapshots,
3386            commit_lock: ctx.commit_lock,
3387            // Build the persistent-cache result cache. We attempt to spawn a
3388            // background writer; if that fails (e.g. the OS won't let us
3389            // create the temp file), publication is marked
3390            // `Disabled(WorkerSpawnFailed)` — the table still opens and
3391            // query-path persists are skipped with a metric, never performed
3392            // synchronously on the query thread (REM-D §8.5).
3393            result_cache: {
3394                let cache = ResultCache::new()
3395                    .with_dir(rcache_dir.clone())
3396                    .with_cache_dek(cache_dek.clone());
3397                // Reuse a per-table `LookupMetrics` so the writer's
3398                // enqueue/coalesce/drop counters are visible through
3399                // `Table::lookup_metrics_snapshot`.
3400                let metrics = Arc::new(LookupMetrics::default());
3401                let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3402                match spawn_persistent_cache_worker(
3403                    rcache_dir.clone(),
3404                    cache_dek.clone(),
3405                    (*metrics).clone(),
3406                ) {
3407                    Ok((writer, handle, completion_rx)) => {
3408                        cache_arc
3409                            .lock()
3410                            .install_persistent_writer(writer, handle, completion_rx);
3411                    }
3412                    Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3413                }
3414                cache_arc
3415            },
3416            pending_delete_rids: roaring::RoaringBitmap::new(),
3417            pending_put_cols: std::collections::HashSet::new(),
3418            pending_rows: Vec::new(),
3419            pending_rows_auto_inc: Vec::new(),
3420            pending_dels: Vec::new(),
3421            pending_truncate: None,
3422            wal_dek,
3423            auto_inc,
3424            ttl: None,
3425            pins: Arc::new(crate::retention::PinRegistry::new()),
3426            published: Arc::new(ArcSwap::from_pointee(initial_view)),
3427            read_generation_pin: None,
3428            lookup_metrics: LookupMetrics::default(),
3429            run_lookup: RunLookupState::default(),
3430        })
3431    }
3432
3433    /// Open an existing table: load the manifest, replay the active WAL segment
3434    /// into the memtable, and rebuild the HOT + secondary indexes from the runs
3435    /// and replayed rows.
3436    pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
3437        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3438        let pinned = root.io_path()?;
3439        let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3440        ctx.root_guard = Some(root);
3441        Self::open_in(&pinned, ctx)
3442    }
3443
3444    /// Open an existing encrypted table. `passphrase` must match the one used at
3445    /// create time (combined with the persisted salt to re-derive the KEK).
3446    pub fn open_encrypted(dir: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
3447        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3448        let salt = read_table_encryption_salt_root(&root)?;
3449        let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3450        let pinned = root.io_path()?;
3451        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3452        ctx.root_guard = Some(root);
3453        let t = Self::open_in(&pinned, ctx)?;
3454        Ok(t)
3455    }
3456
3457    pub(crate) fn open_in(dir: impl AsRef<Path>, ctx: SharedCtx) -> Result<Self> {
3458        let dir = dir.as_ref().to_path_buf();
3459        let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3460        let mut manifest = match ctx.root_guard.as_ref() {
3461            Some(root) => manifest::read_durable(root, "", manifest_meta_dek.as_ref())?,
3462            None => manifest::read(&dir, manifest_meta_dek.as_ref())?,
3463        };
3464        let schema: Schema = match ctx.root_guard.as_ref() {
3465            Some(root) => read_schema_file(root.open_regular(SCHEMA_FILENAME)?)?,
3466            None => read_schema(&dir)?,
3467        };
3468        // A standalone schema change publishes the schema before its matching
3469        // manifest. If the process dies in that narrow window, the newer,
3470        // fully validated schema is authoritative and the manifest identity is
3471        // repaired only after the rest of open has passed preflight. A manifest
3472        // claiming a schema newer than the durable schema remains corruption.
3473        let schema_manifest_repair = manifest.schema_id < schema.schema_id;
3474        let runs_root = match ctx.root_guard.as_ref() {
3475            Some(root) => Some(Arc::new(root.open_directory(RUNS_DIR)?)),
3476            None => None,
3477        };
3478        let idx_root = match ctx.root_guard.as_ref() {
3479            Some(root) => match root.open_directory(global_idx::IDX_DIR) {
3480                Ok(root) => Some(Arc::new(root)),
3481                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
3482                Err(error) => return Err(error.into()),
3483            },
3484            None => None,
3485        };
3486        schema.validate_auto_increment()?;
3487        schema.validate_defaults()?;
3488        schema.validate_ai()?;
3489        for index in &schema.indexes {
3490            index.validate_options()?;
3491        }
3492        let replay_epoch = Epoch(manifest.current_epoch);
3493        let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), manifest.table_id);
3494        let private_replayed = if ctx.shared.is_none() {
3495            match latest_wal_segment(&dir.join(WAL_DIR))? {
3496                Some(path) => {
3497                    let cipher = wal_dek.as_ref().map(|dk| make_cipher(dk));
3498                    crate::wal::replay_with_cipher(path, cipher)?
3499                }
3500                None => Vec::new(),
3501            }
3502        } else {
3503            Vec::new()
3504        };
3505        if ctx.shared.is_none() {
3506            preflight_standalone_open(
3507                &dir,
3508                runs_root.as_deref(),
3509                idx_root.as_deref(),
3510                &manifest,
3511                &schema,
3512                &private_replayed,
3513                ctx.kek.clone(),
3514            )?;
3515        }
3516        let next_run_id = derive_next_run_id(
3517            &dir,
3518            runs_root.as_deref(),
3519            &manifest.runs,
3520            &manifest.retiring,
3521        )?;
3522        // B1: a mounted table has no private WAL — its committed records live in
3523        // the shared WAL and are replayed by `Database::recover_shared_wal`. A
3524        // standalone table replays + reopens its own `_wal/` segment here.
3525        let (wal, replayed, current_txn_id) = match ctx.shared.clone() {
3526            Some(s) => (WalSink::Shared(s), Vec::new(), 0),
3527            None => {
3528                let replayed = private_replayed;
3529                // Never truncate the only durable recovery source. Re-encode
3530                // every valid frame into a synced staging segment, then publish
3531                // it atomically under the next segment number. A crash before
3532                // publication leaves the old segment authoritative; a crash
3533                // afterward finds the complete replacement as the latest WAL.
3534                let wal_dir = dir.join(WAL_DIR);
3535                crate::durable_file::create_directory_all(&wal_dir)?;
3536                let segment = next_wal_segment(&wal_dir)?;
3537                let segment_no = wal_segment_number(&segment).unwrap_or(0);
3538                let temporary = wal_dir.join(format!(
3539                    ".recovery-{}-{}-{segment_no:06}.tmp",
3540                    std::process::id(),
3541                    std::time::SystemTime::now()
3542                        .duration_since(std::time::UNIX_EPOCH)
3543                        .unwrap_or_default()
3544                        .as_nanos()
3545                ));
3546                let mut w = Wal::create_with_cipher(
3547                    &temporary,
3548                    replay_epoch,
3549                    wal_dek.as_ref().map(|dk| make_cipher(dk)),
3550                    segment_no,
3551                )?;
3552                for record in &replayed {
3553                    w.append_txn(record.txn_id, record.op.clone())?;
3554                }
3555                let mut w = w.publish_as(segment)?;
3556                w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3557                let next_txn_id = replayed
3558                    .iter()
3559                    .map(|record| record.txn_id)
3560                    .filter(|txn_id| *txn_id != crate::wal::SYSTEM_TXN_ID)
3561                    .max()
3562                    .map(|txn_id| txn_id.checked_add(1).unwrap_or(0))
3563                    .unwrap_or(1);
3564                (WalSink::Private(w), replayed, next_txn_id)
3565            }
3566        };
3567
3568        let mut memtable = Memtable::new();
3569        let mut allocator = RowIdAllocator::new(manifest.next_row_id);
3570        let persisted_epoch = manifest.current_epoch;
3571        // Seed the auto-increment counter from the manifest. `auto_inc_next == 0`
3572        // means unseeded (fresh table, or a legacy manifest migrated forward) —
3573        // the first allocation scans `max(PK)` to avoid colliding with existing
3574        // rows. WAL replay (below) and `recover_apply` additionally bump `next`
3575        // past replayed ids without marking it seeded, so the scan still covers
3576        // any rows that were already flushed to sorted runs.
3577        let mut auto_inc = resolve_auto_inc(&schema).map(|mut s| {
3578            s.next = manifest.auto_inc_next;
3579            s.seeded = manifest.auto_inc_next > 0;
3580            s
3581        });
3582
3583        // 1. Replay is two-phase and TxnCommit-gated: data records (Put/Delete)
3584        //    are staged per `txn_id` and only applied when a durable
3585        //    `TxnCommit{epoch}` for that txn is seen. Uncommitted / aborted /
3586        //    torn-tail txns are discarded. Indexing happens AFTER loading any
3587        //    checkpoint / run data (below) so the newer replayed versions
3588        //    overwrite the older run versions in the HOT index.
3589        let mut staged_puts: HashMap<u64, Vec<Row>> = HashMap::new();
3590        let mut staged_deletes: HashMap<u64, Vec<RowId>> = HashMap::new();
3591        let mut staged_truncates: std::collections::HashSet<u64> = std::collections::HashSet::new();
3592        let mut replayed_puts: std::collections::BTreeMap<Epoch, Vec<Row>> =
3593            std::collections::BTreeMap::new();
3594        let mut replayed_deletes: Vec<(RowId, Epoch)> = Vec::new();
3595        let mut recovered_epoch = manifest.current_epoch;
3596        let mut recovered_manifest_dirty = schema_manifest_repair;
3597        let mut saw_delete = false;
3598        for record in replayed {
3599            let txn_id = record.txn_id;
3600            match record.op {
3601                Op::Put { rows, .. } => {
3602                    let rows: Vec<Row> = bincode::deserialize(&rows)?;
3603                    for row in &rows {
3604                        allocator.advance_to(row.row_id)?;
3605                        if let Some(ai) = auto_inc.as_mut() {
3606                            if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
3607                                let next = n.checked_add(1).ok_or_else(|| {
3608                                    MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
3609                                })?;
3610                                if next > ai.next {
3611                                    ai.next = next;
3612                                }
3613                            }
3614                        }
3615                    }
3616                    staged_puts.entry(txn_id).or_default().extend(rows);
3617                }
3618                Op::Delete { row_ids, .. } => {
3619                    staged_deletes.entry(txn_id).or_default().extend(row_ids);
3620                }
3621                Op::TxnCommit { epoch, .. } => {
3622                    let commit_epoch = Epoch(epoch);
3623                    recovered_epoch = recovered_epoch.max(epoch);
3624                    if staged_truncates.remove(&txn_id) && commit_epoch.0 > manifest.flushed_epoch {
3625                        memtable = Memtable::new();
3626                        replayed_puts.clear();
3627                        replayed_deletes.clear();
3628                        manifest.runs.clear();
3629                        manifest.retiring.clear();
3630                        manifest.live_count = 0;
3631                        manifest.global_idx_epoch = 0;
3632                        manifest.current_epoch = manifest.current_epoch.max(epoch);
3633                        recovered_manifest_dirty = true;
3634                        saw_delete = true;
3635                    }
3636                    if let Some(puts) = staged_puts.remove(&txn_id) {
3637                        if commit_epoch.0 > manifest.flushed_epoch {
3638                            for row in &puts {
3639                                memtable.upsert(row.clone());
3640                            }
3641                            replayed_puts.entry(commit_epoch).or_default().extend(puts);
3642                        }
3643                    }
3644                    if let Some(dels) = staged_deletes.remove(&txn_id) {
3645                        saw_delete = true;
3646                        if commit_epoch.0 > manifest.flushed_epoch {
3647                            for rid in dels {
3648                                memtable.tombstone(rid, commit_epoch);
3649                                replayed_deletes.push((rid, commit_epoch));
3650                            }
3651                        }
3652                    }
3653                }
3654                Op::TxnAbort => {
3655                    staged_puts.remove(&txn_id);
3656                    staged_deletes.remove(&txn_id);
3657                    staged_truncates.remove(&txn_id);
3658                }
3659                Op::TruncateTable { .. } => {
3660                    staged_puts.remove(&txn_id);
3661                    staged_deletes.remove(&txn_id);
3662                    staged_truncates.insert(txn_id);
3663                }
3664                Op::ExternalTableState { .. }
3665                | Op::Flush { .. }
3666                | Op::Ddl(_)
3667                | Op::BeforeImage { .. }
3668                | Op::CommitTimestamp { .. }
3669                | Op::SpilledRows { .. } => {}
3670            }
3671        }
3672
3673        let rcache_dir = dir.join(RCACHE_DIR);
3674        let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3675        let initial_view = ReadGeneration::empty(&schema);
3676        let mut db = Self {
3677            dir,
3678            _root_guard: ctx.root_guard,
3679            runs_root,
3680            idx_root,
3681            table_id: manifest.table_id,
3682            name: ctx.table_name.unwrap_or_default(),
3683            auth: ctx.auth,
3684            read_only: ctx.read_only,
3685            durable_commit_failed: false,
3686            wal,
3687            memtable,
3688            mutable_run: MutableRun::new(),
3689            mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3690            compaction_zstd_level: 3,
3691            allocator,
3692            epoch: ctx.epoch,
3693            data_generation: persisted_epoch,
3694            schema,
3695            hot: HotIndex::new(),
3696            kek: ctx.kek,
3697            column_keys,
3698            run_refs: manifest.runs.clone(),
3699            retiring: manifest.retiring.clone(),
3700            next_run_id,
3701            sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3702            current_txn_id,
3703            pending_private_mutations: false,
3704            bitmap: HashMap::new(),
3705            ann: HashMap::new(),
3706            fm: HashMap::new(),
3707            sparse: HashMap::new(),
3708            minhash: HashMap::new(),
3709            learned_range: Arc::new(HashMap::new()),
3710            pk_by_row: ReversePkMap::new(),
3711            pinned: BTreeMap::new(),
3712            live_count: manifest.live_count,
3713            reservoir: crate::reservoir::Reservoir::default(),
3714            reservoir_complete: false,
3715            had_deletes: saw_delete
3716                || manifest.runs.iter().map(|run| run.row_count).sum::<u64>()
3717                    != manifest.live_count,
3718            recent_delete_preimages: HashMap::new(),
3719            run_row_id_ranges: HashMap::new(),
3720            agg_cache: Arc::new(HashMap::new()),
3721            global_idx_epoch: manifest.global_idx_epoch,
3722            indexes_complete: true,
3723            index_build_policy: IndexBuildPolicy::default(),
3724            pk_by_row_complete: false,
3725            flushed_epoch: manifest.flushed_epoch,
3726            page_cache: ctx.page_cache,
3727            decoded_cache: ctx.decoded_cache,
3728            verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3729            snapshots: ctx.snapshots,
3730            commit_lock: ctx.commit_lock,
3731            result_cache: {
3732                let cache = ResultCache::new()
3733                    .with_dir(rcache_dir.clone())
3734                    .with_cache_dek(cache_dek.clone());
3735                let metrics = LookupMetrics::default();
3736                let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3737                match spawn_persistent_cache_worker(rcache_dir.clone(), cache_dek.clone(), metrics)
3738                {
3739                    Ok((writer, handle, completion_rx)) => {
3740                        cache_arc
3741                            .lock()
3742                            .install_persistent_writer(writer, handle, completion_rx);
3743                    }
3744                    // Spawn / I/O-setup failure: publication is disabled and
3745                    // query-path persists are skipped with a metric (REM-D
3746                    // §8.5) — never a synchronous query-thread write.
3747                    Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3748                }
3749                cache_arc
3750            },
3751            pending_delete_rids: roaring::RoaringBitmap::new(),
3752            pending_put_cols: std::collections::HashSet::new(),
3753            pending_rows: Vec::new(),
3754            pending_rows_auto_inc: Vec::new(),
3755            pending_dels: Vec::new(),
3756            pending_truncate: None,
3757            wal_dek,
3758            auto_inc,
3759            ttl: manifest.ttl,
3760            pins: Arc::new(crate::retention::PinRegistry::new()),
3761            published: Arc::new(ArcSwap::from_pointee(initial_view)),
3762            read_generation_pin: None,
3763            lookup_metrics: LookupMetrics::default(),
3764            run_lookup: RunLookupState::default(),
3765        };
3766
3767        // Advance the (possibly shared) epoch authority to this table's manifest
3768        // epoch so rebuild/index reads below observe the recovered watermark.
3769        db.epoch.advance_recovered(Epoch(recovered_epoch));
3770
3771        // 2. Fast path: load the persisted global-index checkpoint (Phase 9.1).
3772        //    Valid only when its embedded epoch matches the manifest-endorsed
3773        //    `global_idx_epoch` and every run was created at or before it, so the
3774        //    checkpoint covers all run data. Otherwise rebuild from the runs.
3775        let checkpoint = match db.idx_root.as_deref() {
3776            Some(root) => {
3777                global_idx::read_root(root, db.table_id, &db.schema, db.idx_dek().as_deref())?
3778            }
3779            None => global_idx::read(&db.dir, db.table_id, &db.schema, db.idx_dek().as_deref())?,
3780        };
3781        let checkpoint_valid = checkpoint.as_ref().is_some_and(|c| {
3782            c.epoch_built == manifest.global_idx_epoch
3783                && manifest.global_idx_epoch > 0
3784                && manifest
3785                    .runs
3786                    .iter()
3787                    .all(|r| r.epoch_created <= manifest.global_idx_epoch)
3788        });
3789        if let Some(loaded) = checkpoint {
3790            if checkpoint_valid {
3791                db.hot = loaded.hot;
3792                db.bitmap = loaded.bitmap;
3793                db.ann = loaded.ann;
3794                db.fm = loaded.fm;
3795                db.sparse = loaded.sparse;
3796                db.minhash = loaded.minhash;
3797                db.learned_range = Arc::new(loaded.learned_range);
3798                // Checkpoints omit empty secondary indexes (e.g. ANN with no
3799                // vectors yet). Re-seed any schema-declared maps that were
3800                // skipped so retrievers like ANN do not fail with "has no
3801                // ANN index" after reopen.
3802                let (bitmap0, ann0, fm0, sparse0, minhash0) = empty_indexes(&db.schema);
3803                for (cid, idx) in bitmap0 {
3804                    db.bitmap.entry(cid).or_insert(idx);
3805                }
3806                for (cid, idx) in ann0 {
3807                    db.ann.entry(cid).or_insert(idx);
3808                }
3809                for (cid, idx) in fm0 {
3810                    db.fm.entry(cid).or_insert(idx);
3811                }
3812                for (cid, idx) in sparse0 {
3813                    db.sparse.entry(cid).or_insert(idx);
3814                }
3815                for (cid, idx) in minhash0 {
3816                    db.minhash.entry(cid).or_insert(idx);
3817                }
3818                // `pk_by_row` stays lazy (`pk_by_row_complete == false`): the
3819                // first delete rebuilds it from the loaded HOT.
3820            }
3821        }
3822        if !checkpoint_valid {
3823            let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&db.schema);
3824            db.bitmap = bitmap;
3825            db.ann = ann;
3826            db.fm = fm;
3827            db.sparse = sparse;
3828            db.minhash = minhash;
3829            db.rebuild_indexes_from_runs()?;
3830            db.build_learned_ranges()?;
3831        }
3832
3833        // 3. Replay overlay: PK winner/loser tombstone maintenance always
3834        //    runs (rebuild is per-RowId and does not apply same-PK replace
3835        //    tombstones). Index the replayed rows only when the checkpoint
3836        //    was loaded — a full rebuild already folded the memtable, which
3837        //    already contains these rows. Re-inserting would double Sparse
3838        //    scores and duplicate ANN nodes.
3839        for (epoch, group) in replayed_puts {
3840            let (losers, winner_pks) = db.partition_pk_winners(&group);
3841            for (key, &row_id) in &winner_pks {
3842                if let Some(old_rid) = db.hot.get(key) {
3843                    if old_rid != row_id {
3844                        db.tombstone_row(old_rid, epoch, None, false);
3845                    }
3846                }
3847            }
3848            for &loser_rid in &losers {
3849                db.tombstone_row(loser_rid, epoch, None, false);
3850            }
3851            for (key, row_id) in winner_pks {
3852                db.insert_hot_pk(key, row_id);
3853            }
3854            if db.schema.primary_key().is_none() {
3855                for r in &group {
3856                    db.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
3857                }
3858            }
3859            if checkpoint_valid {
3860                for r in &group {
3861                    if !losers.contains(&r.row_id) {
3862                        db.index_row(r);
3863                    }
3864                }
3865            }
3866        }
3867        // Apply replayed deletes after the puts: a delete targets a specific row
3868        // id and only removes the HOT entry if it still points to that id, so a
3869        // newer upsert for the same PK is not accidentally erased.
3870        for (rid, epoch) in &replayed_deletes {
3871            db.remove_hot_for_row(*rid, *epoch);
3872        }
3873
3874        if recovered_manifest_dirty {
3875            let rows = db.visible_rows(Snapshot::unbounded())?;
3876            db.live_count = rows.len() as u64;
3877            db.persist_manifest(Epoch(recovered_epoch))?;
3878        }
3879
3880        // The reservoir stays lazy (`reservoir_complete == false`, set above):
3881        // rebuilding it means materializing every visible row, which no plain
3882        // open/insert/update/delete needs. `ensure_reservoir_complete` pays
3883        // that cost on the first `approx_aggregate` call instead.
3884        // Load the persistent result-cache tier (hardening (b)) so fine-grained
3885        // invalidation resumes across restart.
3886        let identity = crate::result_cache::PersistentCacheIdentity {
3887            table_id: db.table_id,
3888            schema_id: db.schema.schema_id,
3889            logical_generation: db.epoch.visible().0,
3890        };
3891        db.result_cache.lock().load_persistent(identity);
3892        // Populate RowId range directory so point get can skip irrelevant runs.
3893        db.refresh_run_row_id_ranges();
3894        // Issue 4 / spec §8.4 step 3 — try to install the row-to-run lookup
3895        // directory from the sharded checkpoint. Failure is non-fatal: the
3896        // open succeeds, the read path falls back to range scans, and the
3897        // next flush/compaction rebuilds + publishes a fresh directory.
3898        db.load_run_lookup_directory();
3899        Ok(db)
3900    }
3901
3902    /// Best-effort load of the run-lookup directory on open. Tries the
3903    /// sharded checkpoint first; if it's missing, corrupt, or stale, the
3904    /// in-memory state is left in `complete = false` and the existing
3905    /// range-scan fallback stays the read path's safety net.
3906    fn load_run_lookup_directory(&mut self) {
3907        let active_runs = self.run_refs.clone();
3908        let schema_id = self.schema.schema_id;
3909        let run_generation = active_runs.len() as u64;
3910        let index_generation = self.global_idx_epoch;
3911        let fingerprint = crate::run_lookup::compute_fingerprint(
3912            &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
3913            schema_id,
3914            index_generation,
3915            run_generation,
3916            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
3917        );
3918        // Build a candidate from the sharded checkpoint in `_runs/`.
3919        let runs_dir = match self.runs_root.as_deref() {
3920            Some(root) => match root.io_path() {
3921                Ok(p) => p,
3922                Err(_) => self.dir.join(RUNS_DIR),
3923            },
3924            None => self.dir.join(RUNS_DIR),
3925        };
3926        match crate::run_lookup::RunLookupDirectory::read_checkpoint_sharded(&runs_dir, fingerprint)
3927        {
3928            Ok(dir) => {
3929                self.run_lookup = RunLookupState {
3930                    directory: Some(std::sync::Arc::new(dir)),
3931                    fingerprint,
3932                    complete: true,
3933                };
3934            }
3935            Err(error) => {
3936                self.lookup_metrics
3937                    .directory_incomplete
3938                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3939                self.lookup_metrics
3940                    .directory_lookup_fallback
3941                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3942                self.run_lookup = RunLookupState {
3943                    directory: None,
3944                    fingerprint,
3945                    complete: false,
3946                };
3947                // Trace the load failure so smoke tests catch silent fallbacks
3948                // during the closure audit. The error kind is enough; full
3949                // path is preserved by the trace.
3950                let _ = error;
3951            }
3952        }
3953    }
3954
3955    /// Rebuild `reservoir` from every visible row if it isn't already
3956    /// complete (lazy — same pattern as [`Self::ensure_indexes_complete`]).
3957    /// Open and WAL replay leave the reservoir stale rather than eagerly
3958    /// paying a full-table scan; this pays it once, on the first
3959    /// [`Self::approx_aggregate`] call.
3960    fn ensure_reservoir_complete(&mut self) -> Result<()> {
3961        if self.reservoir_complete {
3962            return Ok(());
3963        }
3964        self.rebuild_reservoir()?;
3965        self.reservoir_complete = true;
3966        Ok(())
3967    }
3968
3969    /// Repopulate the reservoir sample from all visible rows (used on open so a
3970    /// reopened table has an analytics sample without further inserts).
3971    fn rebuild_reservoir(&mut self) -> Result<()> {
3972        let snap = self.snapshot();
3973        let rows = self.visible_rows(snap)?;
3974        self.reservoir.reset();
3975        for r in rows {
3976            self.reservoir.offer(r.row_id.0);
3977        }
3978        Ok(())
3979    }
3980
3981    /// Rebuild HOT + every secondary index from durable runs, the mutable run,
3982    /// and the memtable. Safe to call online; used by recovery tooling and the
3983    /// public [`crate::Database::rebuild_indexes`] path after index desync.
3984    pub fn rebuild_indexes(&mut self) -> Result<()> {
3985        self.rebuild_indexes_from_runs_inner(None)
3986    }
3987
3988    /// Test-only fault-injection seam: install an arbitrary HOT mapping.
3989    ///
3990    /// Bypasses the per-row index maintenance path so regression tests for the
3991    /// HOT fallback (issue 2) can deliberately corrupt the HOT map and assert
3992    /// that the [`Self::resolve_pk_with_hot_fallback`] path still returns the
3993    /// correct, scanned row instead of the mismatched mapped one.
3994    ///
3995    /// Always public so integration tests in `tests/` can reach it; the
3996    /// `__` prefix + the explicit "for_test" name is the convention used
3997    /// elsewhere in the codebase to discourage production callers.
3998    pub fn __force_hot_map_for_test(&mut self, pk_bytes: &[u8], row_id: RowId) {
3999        self.hot.insert(pk_bytes.to_vec(), row_id);
4000    }
4001
4002    /// Test-only helper: drop a single HOT mapping so a test can simulate
4003    /// the missing-mapping fallback path without tearing down the table.
4004    pub fn hot_for_test_remove(&mut self, pk_bytes: &[u8]) {
4005        self.hot.remove(pk_bytes);
4006    }
4007
4008    /// Test-only helper: force the `indexes_complete` flag to `false` so a
4009    /// test can drive the `IndexIncomplete` branch of the fallback path.
4010    pub fn set_indexes_incomplete_for_test(&mut self) {
4011        self.indexes_complete = false;
4012    }
4013
4014    /// Test-only helper: bump the `hot_checkpoint_rejected_total` counter by
4015    /// one so a test can drive the `CheckpointRejected` path. The counter
4016    /// is `pub(crate)` so the helper bumps it directly.
4017    pub fn bump_hot_checkpoint_rejected_for_test(&self) {
4018        self.lookup_metrics
4019            .hot_checkpoint_rejected_total
4020            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4021    }
4022
4023    /// Test-only seam: write `rows` as a synthetic immutable run and link it
4024    /// into the active run set so point-directory tests can control exact
4025    /// (epoch, HLC) stamps and run topology — the public write path stamps
4026    /// every commit with `hlc.now()`, so neither is injectable otherwise.
4027    /// Rows are sorted by `(RowId, epoch)` before writing (sorted-run layout
4028    /// requires ascending `RowId`); returns the allocated run id.
4029    pub fn __install_run_for_test(&mut self, rows: &[Row]) -> Result<u128> {
4030        let mut rows = rows.to_vec();
4031        rows.sort_by_key(|r| (r.row_id, r.committed_epoch));
4032        let epoch = rows
4033            .iter()
4034            .map(|r| r.committed_epoch)
4035            .max()
4036            .unwrap_or(Epoch::ZERO);
4037        let run_id = self.alloc_run_id()?;
4038        let path = self.run_path(run_id);
4039        if let Some(parent) = path.parent() {
4040            std::fs::create_dir_all(parent)
4041                .map_err(|e| MongrelError::Other(format!("create runs dir: {e}")))?;
4042        }
4043        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
4044        if let Some(kek) = &self.kek {
4045            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
4046        }
4047        let header = match self.create_run_file(run_id)? {
4048            Some(file) => writer.write_file(file, &rows)?,
4049            None => writer.write(&path, &rows)?,
4050        };
4051        self.run_refs.push(RunRef {
4052            run_id: run_id as u128,
4053            level: 0,
4054            epoch_created: epoch.0,
4055            row_count: header.row_count,
4056        });
4057        self.run_row_id_ranges
4058            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
4059        Ok(run_id as u128)
4060    }
4061
4062    /// Test-only seam: rebuild and publish the run-lookup directory over the
4063    /// current active run set so directory-assisted `Table::get` tests can
4064    /// drive the synthetic topologies installed via
4065    /// [`Self::__install_run_for_test`].
4066    pub fn __rebuild_run_lookup_for_test(&mut self) -> Result<()> {
4067        self.publish_run_lookup_directory()
4068    }
4069
4070    /// Test-only seam: toggle the directory-assisted point-lookup path. With
4071    /// `complete == false`, `Table::get` takes the `UnavailableOrStale`
4072    /// branch and opens every active run — the forced full-run oracle the
4073    /// point-directory correctness tests compare against. The installed
4074    /// directory is kept, so `complete == true` restores the
4075    /// directory-assisted path.
4076    pub fn __set_run_lookup_complete_for_test(&mut self, complete: bool) {
4077        self.run_lookup.complete = complete;
4078    }
4079
4080    pub(crate) fn rebuild_indexes_from_runs(&mut self) -> Result<()> {
4081        self.rebuild_indexes_from_runs_inner(None)
4082    }
4083
4084    /// Scan overlay + runs for a live row whose PK encode matches `lookup`.
4085    /// Used when the HOT map misses a key that may still exist on disk.
4086    ///
4087    /// Returns `(result, reason)`. The caller in `resolve_condition_with_allowed`
4088    /// is the sole authority for `record_hot_fallback_reason` so that the HOT
4089    /// hit branch (which already recorded e.g. `HistoricalSnapshot`) does not
4090    /// double-bookkeep when it delegates the actual scan here. The returned
4091    /// reason is always set:
4092    ///   - tombstone observed at `snapshot` -> `Tombstone`
4093    ///   - live row found on disk              -> `MissingMapping`
4094    ///   - nothing found                       -> `MissingMapping` (a genuine
4095    ///     miss is still a HOT-fallback event for observability).
4096    ///
4097    /// Correctness contract:
4098    ///   - obeys the full `Snapshot` (epoch + HLC) through `visible_*`
4099    ///     iterators and `range_scan_i64`;
4100    ///   - ignores deleted rows in the overlay and durable runs;
4101    ///   - ignores TTL-expired rows via [`Self::row_expired_at`];
4102    ///   - compares the **materialized** PK against the requested encoded
4103    ///     key (post-HMAC tokenization) so that HMAC-eq columns and bytes
4104    ///     PKs both produce exact matches;
4105    ///   - dedups the resulting `RowId` set so a row referenced from
4106    ///     multiple paths (overlay + run, multi-run) is reported once;
4107    ///   - works across the memtable, mutable-run, and every sorted run;
4108    ///   - preserves historical snapshots — pinned-snapshot readers see the
4109    ///     historical row, not the latest.
4110    fn pk_equality_fallback(
4111        &self,
4112        pk_column_id: u16,
4113        lookup: &[u8],
4114        snapshot: Snapshot,
4115    ) -> Result<(RowIdSet, crate::trace::HotFallbackReason)> {
4116        let mut tombstone_hit = false;
4117        let mut overlay_versions = 0u64;
4118        let now_nanos = unix_nanos_now();
4119        // Overlay first (newest versions).
4120        for row in self.memtable.visible_versions_at(snapshot) {
4121            overlay_versions += 1;
4122            self.lookup_metrics
4123                .hot_lookup_fallback_overlay_rows
4124                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4125            if row.deleted {
4126                tombstone_hit = true;
4127                continue;
4128            }
4129            if self.row_expired_at(&row, now_nanos) {
4130                continue;
4131            }
4132            if let Some(pk_val) = row.columns.get(&pk_column_id) {
4133                if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4134                    self.lookup_metrics
4135                        .hot_fallback_overlay_versions_total
4136                        .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4137                    return Ok((
4138                        RowIdSet::one(row.row_id.0),
4139                        crate::trace::HotFallbackReason::MissingMapping,
4140                    ));
4141                }
4142            }
4143        }
4144        for row in self.mutable_run.visible_versions_at(snapshot) {
4145            overlay_versions += 1;
4146            self.lookup_metrics
4147                .hot_lookup_fallback_overlay_rows
4148                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4149            if row.deleted {
4150                tombstone_hit = true;
4151                continue;
4152            }
4153            if self.row_expired_at(&row, now_nanos) {
4154                continue;
4155            }
4156            if let Some(pk_val) = row.columns.get(&pk_column_id) {
4157                if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4158                    self.lookup_metrics
4159                        .hot_fallback_overlay_versions_total
4160                        .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4161                    return Ok((
4162                        RowIdSet::one(row.row_id.0),
4163                        crate::trace::HotFallbackReason::MissingMapping,
4164                    ));
4165                }
4166            }
4167        }
4168        // Durable runs: prefer int64 point range when the encoded key is 8
4169        // bytes of big-endian i64 (the common Kit PK shape).
4170        if lookup.len() == 8 {
4171            if let Ok(arr) = <[u8; 8]>::try_from(lookup) {
4172                let n = i64::from_be_bytes(arr);
4173                let result = self.range_scan_i64(pk_column_id, n, n, snapshot)?;
4174                self.lookup_metrics
4175                    .hot_lookup_fallback_runs
4176                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4177                // Count this as a considered run for the lookup-metrics
4178                // invariant (every HOT fallback must record exactly one reason
4179                // and advance the run accounting by at least one).
4180                self.lookup_metrics
4181                    .hot_fallback_runs_considered_total
4182                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4183                self.lookup_metrics
4184                    .hot_fallback_overlay_versions_total
4185                    .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4186                let reason = if result.is_empty() {
4187                    if tombstone_hit {
4188                        crate::trace::HotFallbackReason::Tombstone
4189                    } else {
4190                        crate::trace::HotFallbackReason::MissingMapping
4191                    }
4192                } else {
4193                    crate::trace::HotFallbackReason::MissingMapping
4194                };
4195                return Ok((result, reason));
4196            }
4197        }
4198        // Bytes / other PK types: linear visible scan of runs is expensive but
4199        // correctness-first for rare HOT misses.
4200        let mut found: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
4201        let overlay = self.overlay_rid_set(snapshot);
4202        let mut runs_considered = 0u64;
4203        for rr in &self.run_refs {
4204            runs_considered += 1;
4205            self.lookup_metrics
4206                .hot_lookup_fallback_runs
4207                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4208            let mut reader = self.open_reader(rr.run_id)?;
4209            for row in reader.visible_versions_at(snapshot)? {
4210                if overlay.contains(&row.row_id.0) || row.deleted {
4211                    if row.deleted {
4212                        tombstone_hit = true;
4213                    }
4214                    continue;
4215                }
4216                if self.row_expired_at(&row, now_nanos) {
4217                    continue;
4218                }
4219                if let Some(pk_val) = row.columns.get(&pk_column_id) {
4220                    if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4221                        found.insert(row.row_id.0);
4222                    }
4223                }
4224            }
4225        }
4226        let reason = if tombstone_hit {
4227            crate::trace::HotFallbackReason::Tombstone
4228        } else {
4229            // Found or not: the HOT entry was missing, so this is a mapping
4230            // miss regardless of whether the row exists on disk.
4231            crate::trace::HotFallbackReason::MissingMapping
4232        };
4233        self.lookup_metrics
4234            .hot_fallback_overlay_versions_total
4235            .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4236        self.lookup_metrics
4237            .hot_fallback_runs_considered_total
4238            .fetch_add(runs_considered, std::sync::atomic::Ordering::Relaxed);
4239        Ok((RowIdSet::from_unsorted(found.into_iter().collect()), reason))
4240    }
4241
4242    /// TODO §5.1/§5.2 — record a HOT fallback reason. Increments the
4243    /// per-reason counter, the global `hot_lookup_fallback` total, the
4244    /// per-query trace, and the active-call duration bucket.
4245    fn record_hot_fallback_reason(&self, reason: crate::trace::HotFallbackReason) {
4246        let idx = hot_fallback_reason_index(reason);
4247        self.lookup_metrics.hot_fallback_reasons[idx]
4248            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4249        self.lookup_metrics
4250            .hot_lookup_fallback
4251            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4252        crate::trace::QueryTrace::record(|t| {
4253            t.hot_lookup_attempted = true;
4254            t.hot_lookup_hit = false;
4255            t.hot_fallback_reason = Some(reason.as_str());
4256        });
4257    }
4258
4259    fn rebuild_indexes_from_runs_inner(
4260        &mut self,
4261        control: Option<&crate::ExecutionControl>,
4262    ) -> Result<()> {
4263        // S1C-004: online index rebuild pins the current visible epoch so
4264        // version GC cannot reclaim rows while the rebuild scans them.
4265        let _index_build_pin = Arc::clone(self.pin_registry()).pin(
4266            crate::retention::PinSource::OnlineIndexBuild,
4267            self.current_epoch(),
4268        );
4269        self.hot = HotIndex::new();
4270        self.pk_by_row.clear();
4271        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
4272        self.bitmap = bitmap;
4273        self.ann = ann;
4274        self.fm = fm;
4275        self.sparse = sparse;
4276        self.minhash = minhash;
4277        // REM-001: rebuild the current-state index from a *globally merged*
4278        // candidate set rather than indexing each run's visible versions in
4279        // iteration order. For every RowId we collect the candidate from each
4280        // run + the overlay tiers, select the winner using full version
4281        // authority (HLC when both sides are stamped), and index the winner
4282        // exactly once. Tombstones drop the entry entirely. Physical run
4283        // order is no longer a substitute for HLC authority.
4284        //
4285        // TTL-expired rows ARE indexed (HOT and every secondary), matching
4286        // what incremental maintenance would have produced had the rows been
4287        // written after the rebuild: expiry is a query-time eligibility
4288        // filter ([`Self::row_expired_at`]), not an index-content rule.
4289        // Skipping them here would lose the HOT entry a later same-PK put
4290        // needs to tombstone the old row, and would strand the row's
4291        // secondary postings if the TTL policy is ever cleared or relaxed —
4292        // both observed as stale rows resurfacing after `clear_ttl`.
4293        //
4294        // Visibility spans every epoch — a row just upserted in the memtable
4295        // lives at `pending_epoch = visible + 1` (no commit yet) so a snapshot
4296        // pinned at `visible` would silently hide it. Use [`Snapshot::unbounded`]
4297        // so the fold observes every durable row, regardless of whether the
4298        // caller has committed since the upsert.
4299        let snapshot = Snapshot::unbounded();
4300        let ttl_now = unix_nanos_now();
4301        let mut scanned = 0_usize;
4302        let mut winners: HashMap<RowId, (VersionStamp, Row)> = HashMap::new();
4303        let fold =
4304            |row: Row, winners: &mut HashMap<RowId, (VersionStamp, Row)>, scanned: &mut usize| {
4305                *scanned += 1;
4306                let stamp = VersionStamp {
4307                    epoch: row.committed_epoch,
4308                    commit_ts: row.commit_ts,
4309                };
4310                winners
4311                    .entry(row.row_id)
4312                    .and_modify(|entry| {
4313                        if stamp.is_newer_than(entry.0) {
4314                            *entry = (stamp, row.clone());
4315                        }
4316                    })
4317                    .or_insert((stamp, row));
4318            };
4319        for rr in self.run_refs.clone() {
4320            if let Some(control) = control {
4321                control.checkpoint()?;
4322            }
4323            let mut reader = self.open_reader(rr.run_id)?;
4324            for row in reader.visible_versions_at(snapshot)? {
4325                if scanned.is_multiple_of(256) {
4326                    if let Some(control) = control {
4327                        control.checkpoint()?;
4328                    }
4329                }
4330                // Tombstones are still folded: a tombstone's stamp may beat a
4331                // older live row's stamp and clear the entry; folding both
4332                // lets the merge decide the final state per RowId.
4333                fold(row, &mut winners, &mut scanned);
4334            }
4335        }
4336        for (index, row) in self
4337            .memtable
4338            .visible_versions_at(snapshot)
4339            .into_iter()
4340            .enumerate()
4341        {
4342            if index & 255 == 0 {
4343                if let Some(control) = control {
4344                    control.checkpoint()?;
4345                }
4346            }
4347            fold(row, &mut winners, &mut scanned);
4348        }
4349        for (index, row) in self
4350            .mutable_run
4351            .visible_versions_at(snapshot)
4352            .into_iter()
4353            .enumerate()
4354        {
4355            if index & 255 == 0 {
4356                if let Some(control) = control {
4357                    control.checkpoint()?;
4358                }
4359            }
4360            fold(row, &mut winners, &mut scanned);
4361        }
4362        // Partial-index predicates filter the rebuild the same way they
4363        // filter incremental puts (`index_row`): a winner row enters only
4364        // the indexes whose predicate it matches. The HOT map is the
4365        // primary-key map, not a partial index, and is always populated.
4366        let any_predicate = self
4367            .schema
4368            .indexes
4369            .iter()
4370            .any(|idx| idx.predicate.is_some());
4371        let name_to_id: HashMap<&str, u16> = self
4372            .schema
4373            .columns
4374            .iter()
4375            .map(|c| (c.name.as_str(), c.id))
4376            .collect();
4377        for (_rid, (stamp, row)) in winners.drain() {
4378            if row.deleted {
4379                // Tombstone: nothing to index. Anything that was about to be
4380                // promoted under this rid is suppressed by the merge above.
4381                let _ = stamp;
4382                continue;
4383            }
4384            // See the rebuild comment above: TTL-expired winners are indexed
4385            // on purpose; expiry is applied at query time.
4386            let tok_row = self.tokenized_for_indexes(&row);
4387            if !any_predicate {
4388                index_into(
4389                    &self.schema,
4390                    &tok_row,
4391                    &mut self.hot,
4392                    &mut self.bitmap,
4393                    &mut self.ann,
4394                    &mut self.fm,
4395                    &mut self.sparse,
4396                    &mut self.minhash,
4397                );
4398                continue;
4399            }
4400            if let Some(pk_col) = self.schema.primary_key() {
4401                if let Some(pk_val) = tok_row.columns.get(&pk_col.id) {
4402                    self.hot.insert(pk_val.encode_key(), tok_row.row_id);
4403                }
4404            }
4405            let columns_map: HashMap<u16, &Value> =
4406                row.columns.iter().map(|(k, v)| (*k, v)).collect();
4407            for idef in &self.schema.indexes {
4408                if let Some(pred) = &idef.predicate {
4409                    if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4410                        continue;
4411                    }
4412                }
4413                index_into_single(
4414                    idef,
4415                    &self.schema,
4416                    &tok_row,
4417                    &mut self.hot,
4418                    &mut self.bitmap,
4419                    &mut self.ann,
4420                    &mut self.fm,
4421                    &mut self.sparse,
4422                    &mut self.minhash,
4423                );
4424            }
4425        }
4426        // Pin-aware historical discovery for EVERY active pin source that
4427        // compact honors via min_active_snapshot — local pin_snapshot pins,
4428        // Database SnapshotRegistry pins, PinRegistry (backup/replication/
4429        // read-generation/…), and history_floor. Winner-takes-all at the
4430        // unbounded snapshot drops rows only pinned readers still need;
4431        // restore those rows into every secondary (not just Bitmap) so
4432        // retrieve_at / BitmapEq / FmContains still answer at the pin.
4433        // Dedup by RowId: Sparse/MinHash/ANN insert is additive, and the
4434        // same historical rid can be visible at more than one pin epoch.
4435        let pin_epochs = self.active_pin_epochs_for_rebuild();
4436        if !pin_epochs.is_empty() {
4437            let current_snap = Snapshot::at(Epoch(u64::MAX));
4438            let mut historical: HashMap<RowId, Row> = HashMap::new();
4439            for pin_epoch in pin_epochs {
4440                if let Some(control) = control {
4441                    control.checkpoint()?;
4442                }
4443                let pin_snap = Snapshot::at(pin_epoch);
4444                for rr in self.run_refs.clone() {
4445                    if let Some(control) = control {
4446                        control.checkpoint()?;
4447                    }
4448                    let mut reader = self.open_reader(rr.run_id)?;
4449                    for row in reader.visible_rows(pin_epoch)? {
4450                        if row.deleted || self.row_expired_at(&row, ttl_now) {
4451                            continue;
4452                        }
4453                        if historical.contains_key(&row.row_id) {
4454                            continue;
4455                        }
4456                        if self.get(row.row_id, current_snap).is_none() {
4457                            historical.insert(row.row_id, row);
4458                        }
4459                    }
4460                }
4461                for row in self
4462                    .mutable_run
4463                    .visible_versions_at(pin_snap)
4464                    .into_iter()
4465                    .chain(self.memtable.visible_versions_at(pin_snap))
4466                {
4467                    if row.deleted || self.row_expired_at(&row, ttl_now) {
4468                        continue;
4469                    }
4470                    if historical.contains_key(&row.row_id) {
4471                        continue;
4472                    }
4473                    if self.get(row.row_id, current_snap).is_none() {
4474                        historical.insert(row.row_id, row);
4475                    }
4476                }
4477            }
4478            for row in historical.into_values() {
4479                self.index_secondary_membership_only(&row);
4480            }
4481        }
4482        self.recent_delete_preimages.clear();
4483        self.refresh_pk_by_row_from_hot();
4484        Ok(())
4485    }
4486
4487    /// Index every secondary for `row` without touching HOT. Used to restore
4488    /// pin-needed discovery / retrieval keys after a live-only rebuild.
4489    /// Bitmap keeps the HMAC-aware `bitmap_key_for_column` path; other kinds
4490    /// go through `index_into_single` so Sparse/MinHash/ANN/FM match put.
4491    fn index_secondary_membership_only(&mut self, row: &Row) {
4492        if row.deleted {
4493            return;
4494        }
4495        self.index_bitmap_membership_only(row);
4496        let effective = if self.column_keys.is_empty() {
4497            None
4498        } else {
4499            Some(self.tokenized_for_indexes(row))
4500        };
4501        let source = effective.as_ref().unwrap_or(row);
4502        let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4503        let name_to_id: HashMap<&str, u16> = self
4504            .schema
4505            .columns
4506            .iter()
4507            .map(|c| (c.name.as_str(), c.id))
4508            .collect();
4509        for idef in &self.schema.indexes {
4510            if idef.kind == crate::schema::IndexKind::Bitmap {
4511                continue;
4512            }
4513            if let Some(pred) = &idef.predicate {
4514                if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4515                    continue;
4516                }
4517            }
4518            index_into_single(
4519                idef,
4520                &self.schema,
4521                source,
4522                &mut self.hot,
4523                &mut self.bitmap,
4524                &mut self.ann,
4525                &mut self.fm,
4526                &mut self.sparse,
4527                &mut self.minhash,
4528            );
4529        }
4530    }
4531
4532    /// Index Bitmap secondaries for `row` without touching HOT / ANN / etc.
4533    /// Used to restore pin-needed discovery keys after a live-only rebuild.
4534    fn index_bitmap_membership_only(&mut self, row: &Row) {
4535        if row.deleted {
4536            return;
4537        }
4538        let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4539        let name_to_id: HashMap<&str, u16> = self
4540            .schema
4541            .columns
4542            .iter()
4543            .map(|c| (c.name.as_str(), c.id))
4544            .collect();
4545        for idef in &self.schema.indexes {
4546            if idef.kind != crate::schema::IndexKind::Bitmap {
4547                continue;
4548            }
4549            if let Some(pred) = &idef.predicate {
4550                if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4551                    continue;
4552                }
4553            }
4554            if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
4555                if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
4556                    b.insert(key, row.row_id);
4557                }
4558            }
4559        }
4560    }
4561
4562    fn refresh_pk_by_row_from_hot(&mut self) {
4563        self.pk_by_row_complete = true;
4564        if self.schema.primary_key().is_none() {
4565            self.pk_by_row.clear();
4566            return;
4567        }
4568        // `.collect()` drives `HashMap`'s bulk-build `FromIterator` (reserves
4569        // once from the exact-size iterator), instead of growing-and-rehashing
4570        // through a one-at-a-time `insert()` loop — same fix as
4571        // `HotIndex::from_entries`, same hot path (first delete after a put
4572        // streak rebuilds this from the full HOT index).
4573        self.pk_by_row = ReversePkMap::from_entries(
4574            self.hot
4575                .entries()
4576                .into_iter()
4577                .map(|(key, row_id)| (row_id, key)),
4578        );
4579    }
4580
4581    fn insert_hot_pk(&mut self, key: Vec<u8>, row_id: RowId) {
4582        if self.schema.primary_key().is_some() {
4583            self.pk_by_row.insert(row_id, key.clone());
4584        }
4585        self.hot.insert(key, row_id);
4586    }
4587
4588    /// (Re)build per-column learned (PGM) range indexes for `LearnedRange`
4589    /// columns from the single sorted run. Serves `Condition::Range` sub-linearly
4590    /// on the fast path; no-op when there isn't exactly one run.
4591    pub(crate) fn build_learned_ranges(&mut self) -> Result<()> {
4592        self.build_learned_ranges_inner(None)
4593    }
4594
4595    fn build_learned_ranges_inner(
4596        &mut self,
4597        control: Option<&crate::ExecutionControl>,
4598    ) -> Result<()> {
4599        self.learned_range = Arc::new(HashMap::new());
4600        if self.run_refs.len() != 1 {
4601            return Ok(());
4602        }
4603        let cols: Vec<(u16, usize)> = self
4604            .schema
4605            .indexes
4606            .iter()
4607            .filter(|i| i.kind == IndexKind::LearnedRange)
4608            .map(|i| {
4609                (
4610                    i.column_id,
4611                    i.options
4612                        .learned_range
4613                        .as_ref()
4614                        .map(|options| options.epsilon)
4615                        .unwrap_or(16),
4616                )
4617            })
4618            .collect();
4619        if cols.is_empty() {
4620            return Ok(());
4621        }
4622        // Build the PGM from the newest *visible* (non-tombstoned, snapshot-
4623        // eligible) row per RowId. The run's raw column pages also hold prior
4624        // versions and tombstones (deletes are physical, not logical); feeding
4625        // those into the PGM would surface stale rids from `ColumnLearnedRange::
4626        // range` that the engine's overlay merge cannot strip — a leaked
4627        // tombstone is a wrong hit (tested by `churn_oracle_learned_range`).
4628        // REM-001: route through the full-Snapshot visibility API so HLC-pinned
4629        // tables pick the HLC-newer winner across run versions instead of the
4630        // higher-epoch legacy fallback. Same `unbounded` rationale as the
4631        // rebuild — every durable run row must be eligible for the PGM input.
4632        let snapshot = Snapshot::unbounded();
4633        let mut reader = self.open_reader(self.run_refs[0].run_id)?;
4634        let (visible_positions, visible_rids) = reader.visible_positions_with_rids_at(snapshot)?;
4635        let row_ids: Vec<u64> = visible_rids.iter().map(|r| *r as u64).collect();
4636        for (column_index, (cid, epsilon)) in cols.into_iter().enumerate() {
4637            if column_index % 256 == 0 {
4638                if let Some(control) = control {
4639                    control.checkpoint()?;
4640                }
4641            }
4642            let ty = self
4643                .schema
4644                .columns
4645                .iter()
4646                .find(|c| c.id == cid)
4647                .map(|c| c.ty.clone())
4648                .unwrap_or(TypeId::Int64);
4649            match ty {
4650                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
4651                    if let columnar::NativeColumn::Int64 { data, .. } = reader.column_native(cid)? {
4652                        let pairs: Vec<(i64, u64)> = visible_positions
4653                            .iter()
4654                            .zip(row_ids.iter())
4655                            .map(|(&p, &r)| (data[p], r))
4656                            .collect();
4657                        Arc::make_mut(&mut self.learned_range).insert(
4658                            cid,
4659                            ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon),
4660                        );
4661                    }
4662                }
4663                TypeId::Float64 => {
4664                    if let columnar::NativeColumn::Float64 { data, .. } =
4665                        reader.column_native(cid)?
4666                    {
4667                        let pairs: Vec<(f64, u64)> = visible_positions
4668                            .iter()
4669                            .zip(row_ids.iter())
4670                            .map(|(&p, &r)| (data[p], r))
4671                            .collect();
4672                        Arc::make_mut(&mut self.learned_range).insert(
4673                            cid,
4674                            ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon),
4675                        );
4676                    }
4677                }
4678                _ => {}
4679            }
4680        }
4681        Ok(())
4682    }
4683
4684    /// Phase 14.7: if the live indexes are known incomplete (after a bulk
4685    /// ingest that deferred index building — see [`IndexBuildPolicy`]),
4686    /// rebuild them from the runs now. Called lazily by `query` /
4687    /// `query_columns_native` / `flush`; public so external index consumers
4688    /// (SQL scans, joins, PK point lookups on a shared handle) can pay the
4689    /// one-time build before reading a `&self` index view.
4690    pub fn ensure_indexes_complete(&mut self) -> Result<()> {
4691        if self.indexes_complete {
4692            crate::trace::QueryTrace::record(|t| {
4693                t.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4694            });
4695            return Ok(());
4696        }
4697        crate::trace::QueryTrace::record(|t| {
4698            t.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4699        });
4700        self.rebuild_indexes_from_runs()?;
4701        self.build_learned_ranges()?;
4702        self.indexes_complete = true;
4703        let epoch = self.current_epoch();
4704        self.checkpoint_indexes(epoch);
4705        Ok(())
4706    }
4707
4708    /// Rebuild derived indexes cooperatively, publishing their checkpoint only
4709    /// after `before_publish` succeeds.
4710    #[doc(hidden)]
4711    pub fn ensure_indexes_complete_controlled<F>(
4712        &mut self,
4713        control: &crate::ExecutionControl,
4714        before_publish: F,
4715    ) -> Result<bool>
4716    where
4717        F: FnOnce() -> bool,
4718    {
4719        self.ensure_indexes_complete_controlled_with_receipt(control, before_publish)
4720            .map(|(changed, _)| changed)
4721    }
4722
4723    /// Rebuild derived indexes cooperatively and return the exact table
4724    /// snapshot used by the rebuild. No receipt is returned for a no-op.
4725    #[doc(hidden)]
4726    pub fn ensure_indexes_complete_controlled_with_receipt<F>(
4727        &mut self,
4728        control: &crate::ExecutionControl,
4729        before_publish: F,
4730    ) -> Result<(bool, Option<MaintenanceReceipt>)>
4731    where
4732        F: FnOnce() -> bool,
4733    {
4734        if self.indexes_complete {
4735            crate::trace::QueryTrace::record(|trace| {
4736                trace.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4737            });
4738            return Ok((false, None));
4739        }
4740        crate::trace::QueryTrace::record(|trace| {
4741            trace.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4742        });
4743        control.checkpoint()?;
4744        let maintenance_epoch = self.current_epoch();
4745        self.rebuild_indexes_from_runs_inner(Some(control))?;
4746        self.build_learned_ranges_inner(Some(control))?;
4747        control.checkpoint()?;
4748        if !before_publish() {
4749            return Err(MongrelError::Cancelled);
4750        }
4751        self.indexes_complete = true;
4752        self.checkpoint_indexes(maintenance_epoch);
4753        Ok((
4754            true,
4755            Some(MaintenanceReceipt {
4756                epoch: maintenance_epoch,
4757            }),
4758        ))
4759    }
4760
4761    fn pending_epoch(&self) -> Epoch {
4762        Epoch(self.epoch.visible().0 + 1)
4763    }
4764
4765    /// True when this table is mounted in a `Database` (writes route through the
4766    /// shared WAL).
4767    fn is_shared(&self) -> bool {
4768        matches!(self.wal, WalSink::Shared(_))
4769    }
4770
4771    /// Return the current auto-commit txn id, allocating a fresh one from the
4772    /// shared allocator on a mounted table when a new span starts (sentinel 0).
4773    /// A standalone table uses its private monotonic counter (never 0).
4774    fn ensure_txn_id(&mut self) -> Result<u64> {
4775        if self.current_txn_id == 0 {
4776            let id = match &self.wal {
4777                WalSink::Shared(s) => crate::txn::allocate_txn_id(&s.txn_ids)?,
4778                WalSink::Private(_) => {
4779                    return Err(MongrelError::Full(
4780                        "standalone transaction id namespace exhausted".into(),
4781                    ))
4782                }
4783                WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4784            };
4785            self.current_txn_id = id;
4786        }
4787        Ok(self.current_txn_id)
4788    }
4789
4790    /// Append a data record (`Put`/`Delete`) for the current auto-commit txn to
4791    /// whichever WAL backs this table.
4792    fn wal_append_data(&mut self, op: Op) -> Result<()> {
4793        self.ensure_writable()?;
4794        let txn_id = self.ensure_txn_id()?;
4795        let table_id = self.table_id;
4796        match &mut self.wal {
4797            WalSink::Private(w) => {
4798                w.append_txn(txn_id, op)?;
4799                self.pending_private_mutations = true;
4800            }
4801            WalSink::Shared(s) => {
4802                s.wal.lock().append(txn_id, table_id, op)?;
4803            }
4804            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4805        }
4806        Ok(())
4807    }
4808
4809    fn ensure_writable(&self) -> Result<()> {
4810        if self.read_only || matches!(self.wal, WalSink::ReadOnly) {
4811            return Err(MongrelError::ReadOnlyReplica);
4812        }
4813        if self.durable_commit_failed {
4814            return Err(MongrelError::Other(
4815                "table poisoned by post-commit failure; reopen required".into(),
4816            ));
4817        }
4818        Ok(())
4819    }
4820
4821    /// Upsert a row. Allocates a [`RowId`], appends a (non-fsynced) WAL record,
4822    /// and updates the memtable + indexes. Returns the new row id. Durability
4823    /// arrives at the next [`Table::commit`] (or [`Table::flush`]).
4824    ///
4825    /// For an `AUTO_INCREMENT` primary key, omit the column (or pass
4826    /// Auth enforcement helpers. Each delegates to the optional
4827    /// [`TableAuthChecker`] (set at mount time from the `Database`'s auth
4828    /// state). On a credentialless database (`auth = None`), these are
4829    /// no-ops. The `name` field provides the table name for the permission
4830    /// check without needing a reference back to `Database`.
4831    fn require(&self, perm: crate::auth_state::RequiredPermission) -> Result<()> {
4832        match &self.auth {
4833            Some(checker) => checker.check(&self.name, perm),
4834            None => Ok(()),
4835        }
4836    }
4837    /// Check `Select` permission on this table. Public so that read entry
4838    /// points that don't go through `Table::query` (e.g. `MongrelProvider::scan`,
4839    /// `Table::count`) can enforce before reading. On a credentialless database
4840    /// this is a no-op.
4841    pub fn require_select(&self) -> Result<()> {
4842        self.require(crate::auth_state::RequiredPermission::Select)
4843    }
4844    fn require_insert(&self) -> Result<()> {
4845        self.require(crate::auth_state::RequiredPermission::Insert)
4846    }
4847    /// Currently unused on `Table` directly (updates go through `Transaction`),
4848    /// but kept for API completeness — the four `require_*` helpers mirror the
4849    /// four table-level permission kinds.
4850    #[allow(dead_code)]
4851    fn require_update(&self) -> Result<()> {
4852        self.require(crate::auth_state::RequiredPermission::Update)
4853    }
4854    fn require_delete(&self) -> Result<()> {
4855        self.require(crate::auth_state::RequiredPermission::Delete)
4856    }
4857
4858    /// [`Value::Null`]) and the engine assigns the next counter value; use
4859    /// [`Table::put_returning`] to learn that assigned value.
4860    pub fn put(&mut self, columns: Vec<(u16, Value)>) -> Result<RowId> {
4861        self.require_insert()?;
4862        Ok(self.put_returning(columns)?.0)
4863    }
4864
4865    /// Like [`Table::put`] but also returns the engine-assigned `AUTO_INCREMENT`
4866    /// value (`Some` only when the column was omitted/null and the engine filled
4867    /// it; `None` when the table has no auto-increment column or the caller
4868    /// supplied an explicit value).
4869    pub fn put_returning(
4870        &mut self,
4871        mut columns: Vec<(u16, Value)>,
4872    ) -> Result<(RowId, Option<i64>)> {
4873        self.require_insert()?;
4874        let assigned = self.fill_auto_inc(&mut columns)?;
4875        self.apply_defaults(&mut columns)?;
4876        self.schema.validate_values(&columns)?;
4877        // For clustered (WITHOUT ROWID) tables, derive RowId deterministically
4878        // from the PK value so the same PK always maps to the same row (no
4879        // allocator waste, idempotent upserts). For standard tables, use the
4880        // monotonic allocator.
4881        let row_id = if self.schema.clustered {
4882            self.derive_clustered_row_id(&columns)?
4883        } else {
4884            self.allocator.alloc()?
4885        };
4886        let epoch = self.pending_epoch();
4887        let mut row = Row::new(row_id, epoch);
4888        for (col_id, val) in columns {
4889            row.columns.insert(col_id, val);
4890        }
4891        self.commit_rows(vec![row], assigned.is_some())?;
4892        Ok((row_id, assigned))
4893    }
4894
4895    /// Bulk upsert: many rows under a single WAL record + one index pass. Far
4896    /// cheaper than `put` in a loop for batch ingest.
4897    pub fn put_batch(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Vec<RowId>> {
4898        self.require_insert()?;
4899        Ok(self
4900            .put_batch_returning(batch)?
4901            .into_iter()
4902            .map(|(r, _)| r)
4903            .collect())
4904    }
4905
4906    /// Like [`Table::put_batch`] but each entry is paired with the engine-
4907    /// assigned `AUTO_INCREMENT` value (`Some` only when filled by the engine).
4908    pub fn put_batch_returning(
4909        &mut self,
4910        batch: Vec<Vec<(u16, Value)>>,
4911    ) -> Result<Vec<(RowId, Option<i64>)>> {
4912        let mut filled: Vec<FilledAutoIncRow> = Vec::with_capacity(batch.len());
4913        for mut cols in batch {
4914            let assigned = self.fill_auto_inc(&mut cols)?;
4915            self.apply_defaults(&mut cols)?;
4916            filled.push((cols, assigned));
4917        }
4918        for (cols, _) in &filled {
4919            self.schema.validate_values(cols)?;
4920        }
4921        let epoch = self.pending_epoch();
4922        let mut rows = Vec::with_capacity(filled.len());
4923        let mut ids = Vec::with_capacity(filled.len());
4924        let first_row_id = if self.schema.clustered {
4925            None
4926        } else {
4927            let count = u64::try_from(filled.len())
4928                .map_err(|_| MongrelError::Full("row-id allocation request is too large".into()))?;
4929            Some(self.allocator.alloc_range(count)?.0)
4930        };
4931        for (row_index, (cols, assigned)) in filled.into_iter().enumerate() {
4932            let row_id = match first_row_id {
4933                Some(first) => RowId(first + row_index as u64),
4934                None => self.derive_clustered_row_id(&cols)?,
4935            };
4936            let mut row = Row::new(row_id, epoch);
4937            for (c, v) in cols {
4938                row.columns.insert(c, v);
4939            }
4940            ids.push((row_id, assigned));
4941            rows.push(row);
4942        }
4943        let all_auto_generated = ids.iter().all(|(_, assigned)| assigned.is_some());
4944        self.commit_rows(rows, all_auto_generated)?;
4945        Ok(ids)
4946    }
4947
4948    /// Fill the `AUTO_INCREMENT` column for an upcoming row. When the column is
4949    /// omitted or [`Value::Null`] the next counter value is allocated and the
4950    /// cell is appended/replaced in `columns`; an explicit `Int64` is honored
4951    /// and advances the counter past it. Returns `Some(value)` when the engine
4952    /// allocated (so the caller can surface it), `None` otherwise.
4953    pub fn fill_auto_inc(&mut self, columns: &mut Vec<(u16, Value)>) -> Result<Option<i64>> {
4954        self.ensure_writable()?;
4955        let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
4956            return Ok(None);
4957        };
4958        let pos = columns.iter().position(|(c, _)| *c == cid);
4959        let assigned = match pos {
4960            Some(i) => match &columns[i].1 {
4961                Value::Null => {
4962                    let next = self.alloc_auto_inc_value()?;
4963                    columns[i].1 = Value::Int64(next);
4964                    Some(next)
4965                }
4966                Value::Int64(n) => {
4967                    self.advance_auto_inc_past(*n)?;
4968                    None
4969                }
4970                other => {
4971                    return Err(MongrelError::InvalidArgument(format!(
4972                        "AUTO_INCREMENT column {cid} must be Int64 or NULL, got {:?}",
4973                        other
4974                    )))
4975                }
4976            },
4977            None => {
4978                let next = self.alloc_auto_inc_value()?;
4979                columns.push((cid, Value::Int64(next)));
4980                Some(next)
4981            }
4982        };
4983        Ok(assigned)
4984    }
4985
4986    /// Apply column default expressions to `columns` at stage time (before
4987    /// NOT NULL validation). For each column carrying a `default_value`, if the
4988    /// column is omitted or explicitly `Null`, the default is applied. Explicit
4989    /// values are never overridden. Called after [`fill_auto_inc`](Self::fill_auto_inc)
4990    /// and before `validate_not_null`.
4991    pub fn apply_defaults(&self, columns: &mut Vec<(u16, Value)>) -> Result<()> {
4992        for col in &self.schema.columns {
4993            let Some(expr) = &col.default_value else {
4994                continue;
4995            };
4996            // Skip AUTO_INCREMENT columns — handled by fill_auto_inc.
4997            if col.flags.contains(ColumnFlags::AUTO_INCREMENT) {
4998                continue;
4999            }
5000            let pos = columns.iter().position(|(c, _)| *c == col.id);
5001            let needs_default = match pos {
5002                None => true,
5003                Some(i) => matches!(columns[i].1, Value::Null),
5004            };
5005            if !needs_default {
5006                continue;
5007            }
5008            let v = match expr {
5009                crate::schema::DefaultExpr::Static(v) => v.clone(),
5010                crate::schema::DefaultExpr::Now => Value::Bytes(iso_now_bytes()),
5011                crate::schema::DefaultExpr::Uuid => {
5012                    let mut buf = [0u8; 16];
5013                    getrandom::fill(&mut buf)
5014                        .map_err(|e| MongrelError::Other(format!("UUID generation failed: {e}")))?;
5015                    Value::Uuid(buf)
5016                }
5017            };
5018            match pos {
5019                None => columns.push((col.id, v)),
5020                Some(i) => columns[i].1 = v,
5021            }
5022        }
5023        Ok(())
5024    }
5025
5026    /// Allocate the next identity value, seeding the counter first if needed.
5027    fn alloc_auto_inc_value(&mut self) -> Result<i64> {
5028        self.ensure_auto_inc_seeded()?;
5029        // Borrow checker: re-read after the mutable `ensure` call returns.
5030        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5031        let v = ai.next;
5032        ai.next = ai
5033            .next
5034            .checked_add(1)
5035            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5036        Ok(v)
5037    }
5038
5039    /// Advance the counter past an explicit id, seeding first if needed so a
5040    /// pre-existing higher id elsewhere is never ignored.
5041    fn advance_auto_inc_past(&mut self, used: i64) -> Result<()> {
5042        self.ensure_auto_inc_seeded()?;
5043        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5044        let floor = used
5045            .checked_add(1)
5046            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5047            .max(1);
5048        if ai.next < floor {
5049            ai.next = floor;
5050        }
5051        Ok(())
5052    }
5053
5054    /// Seed the counter on first use by scanning `max(PK)` over all visible
5055    /// rows, so an upgraded table (legacy client-assigned ids, or a manifest
5056    /// migrated from `auto_inc_next == 0`) never hands out a colliding id.
5057    /// Idempotent: a no-op once seeded.
5058    fn ensure_auto_inc_seeded(&mut self) -> Result<()> {
5059        let needs_seed = match self.auto_inc {
5060            Some(ai) => !ai.seeded,
5061            None => return Ok(()),
5062        };
5063        if !needs_seed {
5064            return Ok(());
5065        }
5066        if self.seed_empty_auto_inc() {
5067            return Ok(());
5068        }
5069        let cid = self
5070            .auto_inc
5071            .as_ref()
5072            .expect("auto-inc column present")
5073            .column_id;
5074        let max = self.scan_max_int64(cid)?;
5075        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5076        let floor = max
5077            .checked_add(1)
5078            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5079            .max(1);
5080        if ai.next < floor {
5081            ai.next = floor;
5082        }
5083        ai.seeded = true;
5084        Ok(())
5085    }
5086
5087    fn alloc_auto_inc_range(&mut self, n: usize) -> Result<Option<i64>> {
5088        if n == 0 || self.auto_inc.is_none() {
5089            return Ok(None);
5090        }
5091        self.ensure_auto_inc_seeded()?;
5092        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5093        let start = ai.next;
5094        let count = i64::try_from(n)
5095            .map_err(|_| MongrelError::Full("AUTO_INCREMENT range is too large".into()))?;
5096        ai.next = ai
5097            .next
5098            .checked_add(count)
5099            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5100        Ok(Some(start))
5101    }
5102
5103    /// One-time `max(Int64 column)` over all MVCC-visible rows. Used to seed the
5104    /// auto-increment counter. Runs at most once per table (the manifest then
5105    /// checkpoints the seeded counter).
5106    fn scan_max_int64(&mut self, column_id: u16) -> Result<i64> {
5107        let mut max: i64 = 0;
5108        for r in self.memtable.visible_versions_at(Snapshot::unbounded()) {
5109            if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5110                if *n > max {
5111                    max = *n;
5112                }
5113            }
5114        }
5115        for r in self.mutable_run.visible_versions(Epoch(u64::MAX)) {
5116            if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5117                if *n > max {
5118                    max = *n;
5119                }
5120            }
5121        }
5122        for rr in self.run_refs.clone() {
5123            let reader = self.open_reader(rr.run_id)?;
5124            if let Some(stats) = reader.column_page_stats(column_id) {
5125                for s in stats {
5126                    if let Some(n) = crate::sorted_run::be_i64(s.max.as_deref()) {
5127                        if n > max {
5128                            max = n;
5129                        }
5130                    }
5131                }
5132            } else if reader.has_column(column_id) {
5133                if let columnar::NativeColumn::Int64 { data, validity } =
5134                    reader.column_native_shared(column_id)?
5135                {
5136                    for (i, n) in data.iter().enumerate() {
5137                        if (validity.is_empty() || columnar::validity_bit(&validity, i)) && *n > max
5138                        {
5139                            max = *n;
5140                        }
5141                    }
5142                }
5143            }
5144        }
5145        Ok(max)
5146    }
5147
5148    fn seed_empty_auto_inc(&mut self) -> bool {
5149        let Some(ai) = self.auto_inc.as_mut() else {
5150            return false;
5151        };
5152        if ai.seeded || self.live_count != 0 {
5153            return false;
5154        }
5155        if ai.next < 1 {
5156            ai.next = 1;
5157        }
5158        ai.seeded = true;
5159        true
5160    }
5161
5162    fn advance_auto_inc_from_native_columns(
5163        &mut self,
5164        columns: &[(u16, columnar::NativeColumn)],
5165        n: usize,
5166        live_before: u64,
5167    ) -> Result<()> {
5168        let Some(ai) = self.auto_inc.as_mut() else {
5169            return Ok(());
5170        };
5171        let Some((_, col)) = columns.iter().find(|(cid, _)| *cid == ai.column_id) else {
5172            return Ok(());
5173        };
5174        let columnar::NativeColumn::Int64 { data, validity } = col else {
5175            return Err(MongrelError::InvalidArgument(format!(
5176                "AUTO_INCREMENT column {} must be Int64",
5177                ai.column_id
5178            )));
5179        };
5180        let max = if native_int64_strictly_increasing(col, n) {
5181            data.get(n.saturating_sub(1)).copied()
5182        } else {
5183            data.iter()
5184                .take(n)
5185                .enumerate()
5186                .filter_map(|(i, v)| {
5187                    if validity.is_empty() || columnar::validity_bit(validity, i) {
5188                        Some(*v)
5189                    } else {
5190                        None
5191                    }
5192                })
5193                .max()
5194        };
5195        if let Some(max) = max {
5196            let floor = max
5197                .checked_add(1)
5198                .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5199                .max(1);
5200            if ai.next < floor {
5201                ai.next = floor;
5202            }
5203            if ai.seeded || live_before == 0 {
5204                ai.seeded = true;
5205            }
5206        }
5207        Ok(())
5208    }
5209
5210    fn fill_auto_inc_native_columns(
5211        &mut self,
5212        columns: &mut Vec<(u16, columnar::NativeColumn)>,
5213        n: usize,
5214    ) -> Result<()> {
5215        let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
5216            return Ok(());
5217        };
5218        let Some(pos) = columns.iter().position(|(id, _)| *id == cid) else {
5219            if let Some(start) = self.alloc_auto_inc_range(n)? {
5220                columns.push((
5221                    cid,
5222                    columnar::NativeColumn::Int64 {
5223                        data: (start..start.saturating_add(n as i64)).collect(),
5224                        validity: vec![0xFF; n.div_ceil(8)],
5225                    },
5226                ));
5227            }
5228            return Ok(());
5229        };
5230
5231        let columnar::NativeColumn::Int64 { data, validity } = &mut columns[pos].1 else {
5232            return Err(MongrelError::InvalidArgument(format!(
5233                "AUTO_INCREMENT column {cid} must be Int64"
5234            )));
5235        };
5236        if data.len() < n {
5237            return Err(MongrelError::InvalidArgument(format!(
5238                "AUTO_INCREMENT column {cid} has {} rows, expected {n}",
5239                data.len()
5240            )));
5241        }
5242        if columnar::all_non_null(validity, n) {
5243            return Ok(());
5244        }
5245        if validity.iter().all(|b| *b == 0) {
5246            if let Some(start) = self.alloc_auto_inc_range(n)? {
5247                for (i, slot) in data.iter_mut().take(n).enumerate() {
5248                    *slot = start.saturating_add(i as i64);
5249                }
5250                *validity = vec![0xFF; n.div_ceil(8)];
5251            }
5252            return Ok(());
5253        }
5254
5255        let new_validity = vec![0xFF; data.len().div_ceil(8)];
5256        for (i, slot) in data.iter_mut().enumerate().take(n) {
5257            if columnar::validity_bit(validity, i) {
5258                self.advance_auto_inc_past(*slot)?;
5259            } else {
5260                *slot = self.alloc_auto_inc_value()?;
5261            }
5262        }
5263        *validity = new_validity;
5264        Ok(())
5265    }
5266
5267    /// Reserve (but do not insert) the next `AUTO_INCREMENT` value, advancing
5268    /// the in-memory counter. Returns `None` when the table has no
5269    /// auto-increment column.
5270    ///
5271    /// This is the escape hatch for callers that stage the row with an explicit
5272    /// id inside a cross-table [`crate::Transaction`] — where the engine cannot
5273    /// fill the column on the `put` path (the row id + cells are only assembled
5274    /// at commit). Unlike the old Kit `__kit_sequences` sequence row, the
5275    /// reservation is a pure in-memory counter bump: no hot row, no second
5276    /// commit. It becomes durable when a row carrying the reserved id commits
5277    /// (the counter is checkpointed to the manifest in the same commit); an
5278    /// aborted reservation simply leaves a gap, which the never-reuse rule
5279    /// permits.
5280    pub fn reserve_auto_inc(&mut self) -> Result<Option<i64>> {
5281        self.ensure_writable()?;
5282        if self.auto_inc.is_none() {
5283            return Ok(None);
5284        }
5285        Ok(Some(self.alloc_auto_inc_value()?))
5286    }
5287
5288    /// Append `rows` under one WAL record. On a standalone table they are folded
5289    /// into the memtable + indexes immediately (single clock — no speculative-
5290    /// epoch hazard). On a mounted table (B1/B2) they are staged in
5291    /// `pending_rows` and applied at the real assigned epoch in `commit`, so a
5292    /// concurrent reader can never see them before their commit epoch.
5293    fn commit_rows(&mut self, rows: Vec<Row>, auto_inc_generated: bool) -> Result<()> {
5294        let payload = bincode::serialize(&rows)?;
5295        self.wal_append_data(Op::Put {
5296            table_id: self.table_id,
5297            rows: payload,
5298        })?;
5299        if self.is_shared() {
5300            self.pending_rows_auto_inc
5301                .extend(std::iter::repeat_n(auto_inc_generated, rows.len()));
5302            self.pending_rows.extend(rows);
5303        } else {
5304            self.apply_put_rows_inner(rows, !auto_inc_generated)?;
5305        }
5306        Ok(())
5307    }
5308
5309    /// Complete every fallible read/index preparation before a WAL commit can
5310    /// become durable. After this succeeds, row application is in-memory only.
5311    pub(crate) fn prepare_durable_publish(&mut self) -> Result<()> {
5312        self.ensure_indexes_complete()
5313    }
5314
5315    pub(crate) fn prepare_durable_publish_controlled(
5316        &mut self,
5317        control: &crate::ExecutionControl,
5318    ) -> Result<()> {
5319        self.ensure_indexes_complete_controlled(control, || true)?;
5320        Ok(())
5321    }
5322
5323    pub(crate) fn apply_put_rows_prepared(&mut self, rows: Vec<Row>) {
5324        self.apply_put_rows_inner_prepared(rows, true);
5325    }
5326
5327    fn apply_put_rows_inner(&mut self, rows: Vec<Row>, check_existing_pk: bool) -> Result<()> {
5328        if check_existing_pk {
5329            self.ensure_indexes_complete()?;
5330        }
5331        self.apply_put_rows_inner_prepared(rows, check_existing_pk);
5332        Ok(())
5333    }
5334
5335    /// Apply rows after [`Self::ensure_indexes_complete`] has succeeded. Every
5336    /// operation below is in-memory and infallible, so durable publication can
5337    /// never stop halfway through a batch on an I/O error.
5338    fn apply_put_rows_inner_prepared(&mut self, rows: Vec<Row>, check_existing_pk: bool) {
5339        // Single-row puts — the hot operational path — cannot contain an
5340        // intra-batch duplicate, so the winner/loser partition maps are pure
5341        // overhead. Same semantics as the batch path below with `losers = ∅`.
5342        if rows.len() == 1 {
5343            let row = rows.into_iter().next().expect("len checked");
5344            self.apply_put_row_single(row, check_existing_pk);
5345            return;
5346        }
5347        // One pass per row: track mutated columns, tombstone the previous
5348        // owner of the row's PK, index (which places the HOT entry), sample,
5349        // and materialize. Each row is applied completely — including its
5350        // memtable upsert — before the next row processes, so "the last row
5351        // wins" falls out naturally for an intra-batch duplicate PK: the
5352        // earlier row is already materialized and gets tombstoned like any
5353        // other displaced owner (same visible state as pre-partitioning the
5354        // batch into winners and losers, without materializing a winner map
5355        // over the whole batch).
5356        //
5357        // Upsert probing is skipped entirely when no PK owner can be
5358        // displaced: `check_existing_pk == false` means every PK is a fresh
5359        // engine-assigned AUTO_INCREMENT value; an empty HOT index plus
5360        // strictly-increasing batch PKs (the append-style batch, mirroring
5361        // `bulk_pk_winner_indices`' fast path) rules out both pre-existing
5362        // owners and intra-batch duplicates.
5363        let pk_id = self.schema.primary_key().map(|c| c.id);
5364        let probe = match pk_id {
5365            Some(pid) => {
5366                check_existing_pk
5367                    && !(self.hot.is_empty() && rows_pk_strictly_increasing(&rows, pid))
5368            }
5369            None => false,
5370        };
5371        // The PK reverse map is maintained inline only once a delete has built
5372        // it (`pk_by_row_complete`); ingest-only tables never pay for it.
5373        let maintain_pk_by_row = pk_id.is_some() && self.pk_by_row_complete;
5374        for r in rows {
5375            for &cid in r.columns.keys() {
5376                self.pending_put_cols.insert(cid);
5377            }
5378            let mut replaced_image: Option<Row> = None;
5379            match pk_id {
5380                Some(pid) if probe || maintain_pk_by_row => {
5381                    if let Some(pk_val) = r.columns.get(&pid) {
5382                        let key = self.index_lookup_key(pid, pk_val);
5383                        if probe {
5384                            // Prefer `recent_delete_preimages` (Kit
5385                            // delete+put: the pre-image is needed to drive
5386                            // Bitmap delta maintenance). Fall back to the
5387                            // stale HOT entry when the preimage was cleared
5388                            // (e.g., after a rebuild). `apply_delete_at`
5389                            // preserves the HOT entry so the stale-entry
5390                            // branch is the common one for a same-PK Kit
5391                            // delete+put.
5392                            if let Some(old) = self.recent_delete_preimages.remove(&key) {
5393                                replaced_image = Some(old);
5394                                if let Some(old_rid) = self.hot.get(&key) {
5395                                    if old_rid != r.row_id {
5396                                        self.tombstone_row(
5397                                            old_rid,
5398                                            r.committed_epoch,
5399                                            r.commit_ts,
5400                                            true,
5401                                        );
5402                                    }
5403                                }
5404                            } else if let Some(old_rid) = self.hot.get(&key) {
5405                                if old_rid != r.row_id {
5406                                    replaced_image = self.get(old_rid, self.snapshot());
5407                                    self.tombstone_row(
5408                                        old_rid,
5409                                        r.committed_epoch,
5410                                        r.commit_ts,
5411                                        true,
5412                                    );
5413                                }
5414                            }
5415                        }
5416                        if maintain_pk_by_row {
5417                            self.pk_by_row.insert(r.row_id, key);
5418                        }
5419                    }
5420                }
5421                Some(_) => {}
5422                None => {
5423                    self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5424                }
5425            }
5426            if let Some(old) = replaced_image {
5427                self.maintain_indexes_on_pk_replace(&old, &r);
5428            } else {
5429                self.index_row(&r);
5430            }
5431            self.reservoir.offer(r.row_id.0);
5432            self.memtable.upsert(r);
5433            // Count as each row lands so a later duplicate's tombstone
5434            // decrement (in `tombstone_row`) sees an up-to-date value.
5435            self.live_count = self.live_count.saturating_add(1);
5436        }
5437        self.data_generation = self.data_generation.wrapping_add(1);
5438    }
5439
5440    /// One-row specialization of [`Table::apply_put_rows_inner`]: identical
5441    /// upsert semantics (tombstone the previous PK owner, insert into HOT,
5442    /// index, sample, materialize) without the per-batch winner/loser maps.
5443    ///
5444    /// When a same-PK put replaces an older live row (the product update path
5445    /// after delete+put normalize, or a direct upsert), Bitmap secondary indexes
5446    /// are maintained via [`crate::index::maintain_bitmap_secondary_on_replace`]
5447    /// so unchanged equality keys only re-point row ids and changed keys move —
5448    /// rather than leaving tombstoned row ids permanently in the bitmaps.
5449    fn apply_put_row_single(&mut self, row: Row, check_existing_pk: bool) {
5450        for &cid in row.columns.keys() {
5451            self.pending_put_cols.insert(cid);
5452        }
5453        let epoch = row.committed_epoch;
5454        let mut replaced_image: Option<Row> = None;
5455        if let Some(pk_col) = self.schema.primary_key() {
5456            let pk_id = pk_col.id;
5457            if let Some(pk_val) = row.columns.get(&pk_id) {
5458                // `index_row` / HOT-only path below writes the HOT entry. The
5459                // reverse map is maintained inline only once a delete has built
5460                // it; ingest-only tables never pay for it.
5461                let maintain_pk_by_row = self.pk_by_row_complete;
5462                if check_existing_pk || maintain_pk_by_row {
5463                    let key = self.index_lookup_key(pk_id, pk_val);
5464                    if check_existing_pk {
5465                        // Prefer `recent_delete_preimages` (Kit delete+put:
5466                        // the pre-image is needed to drive Bitmap delta
5467                        // maintenance). Fall back to the stale HOT entry for
5468                        // cases where `recent_delete_preimages` was cleared
5469                        // (e.g., after a rebuild) but HOT still maps to the
5470                        // old rid. `apply_delete_at` preserves the HOT entry
5471                        // so the stale-entry branch is the common one for a
5472                        // same-PK Kit delete+put.
5473                        if let Some(old) = self.recent_delete_preimages.remove(&key) {
5474                            replaced_image = Some(old);
5475                            if let Some(old_rid) = self.hot.get(&key) {
5476                                if old_rid != row.row_id {
5477                                    self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5478                                }
5479                            }
5480                        } else if let Some(old_rid) = self.hot.get(&key) {
5481                            if old_rid != row.row_id {
5482                                // Capture the pre-image while it is still live so
5483                                // secondary-index delta maintenance can drop the
5484                                // old row-id from Bitmap keys.
5485                                replaced_image = self.get(old_rid, self.snapshot());
5486                                self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5487                            }
5488                        }
5489                    }
5490                    if maintain_pk_by_row {
5491                        self.pk_by_row.insert(row.row_id, key);
5492                    }
5493                }
5494            }
5495        } else {
5496            self.hot
5497                .insert(row.row_id.0.to_be_bytes().to_vec(), row.row_id);
5498        }
5499        if let Some(old) = replaced_image {
5500            self.maintain_indexes_on_pk_replace(&old, &row);
5501        } else {
5502            self.index_row(&row);
5503        }
5504        self.reservoir.offer(row.row_id.0);
5505        self.memtable.upsert(row);
5506        self.live_count = self.live_count.saturating_add(1);
5507        self.data_generation = self.data_generation.wrapping_add(1);
5508    }
5509
5510    /// PK-replace index maintenance: Bitmap secondaries via delta plan; other
5511    /// secondary kinds + HOT via the existing full path for those families.
5512    fn maintain_indexes_on_pk_replace(&mut self, old: &Row, new: &Row) {
5513        let has_partial = self
5514            .schema
5515            .indexes
5516            .iter()
5517            .any(|idx| idx.predicate.is_some());
5518        if has_partial {
5519            // Partial predicates make selective unindex subtle; drop old Bitmap
5520            // memberships then full-index the new image (still cleans tombstone
5521            // pollution for Bitmap keys on the replace path only).
5522            self.unindex_bitmap_membership(old);
5523            self.index_row(new);
5524            return;
5525        }
5526
5527        crate::index::maintain_bitmap_secondary_on_replace(
5528            &self.schema,
5529            &mut self.bitmap,
5530            old,
5531            new,
5532        );
5533        self.index_row_non_bitmap(new);
5534    }
5535
5536    /// Index HOT + every non-Bitmap secondary for `row`. Bitmap secondaries are
5537    /// assumed already maintained by a delta plan on the replace path.
5538    fn index_row_non_bitmap(&mut self, row: &Row) {
5539        if row.deleted {
5540            return;
5541        }
5542        let effective = if self.column_keys.is_empty() {
5543            None
5544        } else {
5545            Some(self.tokenized_for_indexes(row))
5546        };
5547        let source = effective.as_ref().unwrap_or(row);
5548        for idef in &self.schema.indexes {
5549            if idef.kind == crate::schema::IndexKind::Bitmap {
5550                continue;
5551            }
5552            index_into_single(
5553                idef,
5554                &self.schema,
5555                source,
5556                &mut self.hot,
5557                &mut self.bitmap,
5558                &mut self.ann,
5559                &mut self.fm,
5560                &mut self.sparse,
5561                &mut self.minhash,
5562            );
5563        }
5564        if let Some(pk_col) = self.schema.primary_key() {
5565            if let Some(pk_val) = source.columns.get(&pk_col.id) {
5566                let key = if self.column_keys.is_empty() {
5567                    pk_val.encode_key()
5568                } else {
5569                    self.index_lookup_key(pk_col.id, pk_val)
5570                };
5571                self.hot.insert(key, source.row_id);
5572            }
5573        }
5574    }
5575
5576    /// Allocate a fresh row id (advancing the table's allocator). Used by the
5577    /// cross-table `Transaction` to assign ids before sealing a row.
5578    pub(crate) fn alloc_row_id(&mut self) -> Result<RowId> {
5579        self.allocator.alloc()
5580    }
5581
5582    /// For clustered (WITHOUT ROWID) tables: derive a deterministic `RowId`
5583    /// from the primary-key value so the same PK always maps to the same row.
5584    /// Uses a stable hash of the PK's `encode_key()` bytes, cast to `u64`.
5585    /// This gives WITHOUT ROWID tables idempotent upsert semantics (same PK →
5586    /// same RowId, no allocator waste) without changing the storage format.
5587    fn derive_clustered_row_id(&self, columns: &[(u16, Value)]) -> Result<RowId> {
5588        let pk = self.schema.primary_key().ok_or_else(|| {
5589            MongrelError::Schema("clustered table requires a single-column primary key".into())
5590        })?;
5591        let pk_val = columns
5592            .iter()
5593            .find(|(id, _)| *id == pk.id)
5594            .map(|(_, v)| v)
5595            .ok_or_else(|| {
5596                MongrelError::Schema(format!(
5597                    "clustered table missing primary key column {} ({})",
5598                    pk.id, pk.name
5599                ))
5600            })?;
5601        Ok(clustered_row_id(pk_val))
5602    }
5603
5604    /// Apply the metadata for rows that were spilled to a linked uniform-epoch
5605    /// run (P3.4): update the HOT + secondary indexes, the reservoir, the
5606    /// allocator high-water mark, and `live_count` — but **do NOT** insert the
5607    /// rows into the memtable. The rows are served from the linked run (which the
5608    /// scan/merge path reads at the run's commit epoch), so materializing them in
5609    /// the memtable too would defeat the point of spilling (peak memory stays
5610    /// bounded). Caller must have linked the run before reads can resolve indexes.
5611    pub(crate) fn apply_run_metadata_prepared(&mut self, rows: &[Row]) -> Result<()> {
5612        if rows.iter().any(|row| row.row_id.0 >= u64::MAX - 1) {
5613            return Err(MongrelError::Full("row-id namespace exhausted".into()));
5614        }
5615        let n = rows.len();
5616        for r in rows {
5617            for &cid in r.columns.keys() {
5618                self.pending_put_cols.insert(cid);
5619            }
5620        }
5621        let (losers, winner_pks) = self.partition_pk_winners(rows);
5622        let epoch = rows.first().map(|r| r.committed_epoch).unwrap_or(Epoch(0));
5623        // Tombstone pre-existing rows that conflict with winners.
5624        let group_ts = rows.first().and_then(|r| r.commit_ts);
5625        for (key, &row_id) in &winner_pks {
5626            if let Some(old_rid) = self.hot.get(key) {
5627                if old_rid != row_id {
5628                    self.tombstone_row(old_rid, epoch, group_ts, true);
5629                }
5630            }
5631        }
5632        // Hide duplicate-PK rows inside this uniform-epoch run by tombstoning
5633        // their row ids in the memtable overlay (the overlay wins over the run).
5634        for &loser_rid in &losers {
5635            self.tombstone_row(loser_rid, epoch, group_ts, false);
5636        }
5637        // Insert the winners into HOT.
5638        for (key, row_id) in winner_pks {
5639            self.insert_hot_pk(key, row_id);
5640        }
5641        if self.schema.primary_key().is_none() {
5642            for r in rows {
5643                self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5644            }
5645        }
5646        for r in rows {
5647            self.allocator.advance_to(r.row_id)?;
5648            if !losers.contains(&r.row_id) {
5649                self.index_row(r);
5650            }
5651        }
5652        for r in rows {
5653            if !losers.contains(&r.row_id) {
5654                self.reservoir.offer(r.row_id.0);
5655            }
5656        }
5657        self.live_count = self.live_count.saturating_add((n - losers.len()) as u64);
5658        self.data_generation = self.data_generation.wrapping_add(1);
5659        Ok(())
5660    }
5661
5662    /// Apply already-committed puts + tombstones during shared-WAL recovery
5663    /// (spec §15 pass 2). Advances the allocator, upserts/tombstones the
5664    /// memtable, and indexes the rows — but does NOT touch `live_count` (the
5665    /// manifest is authoritative) and does NOT append to the WAL.
5666    pub(crate) fn recover_apply(
5667        &mut self,
5668        rows: Vec<Row>,
5669        deletes: Vec<(RowId, Epoch)>,
5670    ) -> Result<()> {
5671        // Rows from different transactions have different epochs and can be
5672        // upserted sequentially. Rows inside one transaction share an epoch, so
5673        // duplicate PKs within that transaction must keep only the last winner.
5674        let mut by_epoch: std::collections::BTreeMap<Epoch, Vec<Row>> =
5675            std::collections::BTreeMap::new();
5676        for row in rows {
5677            if row.row_id.0 >= u64::MAX - 1 {
5678                return Err(MongrelError::Full("row-id namespace exhausted".into()));
5679            }
5680            self.allocator.advance_to(row.row_id)?;
5681            // Mirror the row-id advance for the AUTO_INCREMENT counter: WAL
5682            // replay must not hand out an id a recovered row already claimed.
5683            // `seeded` is intentionally left untouched so a still-unseeded
5684            // counter still scans `max(PK)` to cover already-flushed rows.
5685            if let Some(ai) = self.auto_inc.as_mut() {
5686                if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
5687                    let next = n.checked_add(1).ok_or_else(|| {
5688                        MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
5689                    })?;
5690                    if next > ai.next {
5691                        ai.next = next;
5692                    }
5693                }
5694            }
5695            by_epoch.entry(row.committed_epoch).or_default().push(row);
5696        }
5697        for (epoch, group) in by_epoch {
5698            let (losers, winner_pks) = self.partition_pk_winners(&group);
5699            // Tombstone pre-existing PK owners.
5700            let group_ts = group.first().and_then(|r| r.commit_ts);
5701            for (key, &row_id) in &winner_pks {
5702                if let Some(old_rid) = self.hot.get(key) {
5703                    if old_rid != row_id {
5704                        self.tombstone_row(old_rid, epoch, group_ts, false);
5705                    }
5706                }
5707            }
5708            for (key, row_id) in winner_pks {
5709                self.insert_hot_pk(key, row_id);
5710            }
5711            if self.schema.primary_key().is_none() {
5712                for r in &group {
5713                    self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5714                }
5715            }
5716            for r in &group {
5717                if !losers.contains(&r.row_id) {
5718                    self.memtable.upsert(r.clone());
5719                    self.index_row(r);
5720                }
5721            }
5722        }
5723        for (rid, epoch) in deletes {
5724            self.memtable.tombstone(rid, epoch);
5725            self.remove_hot_for_row(rid, epoch);
5726        }
5727        // Reservoir stays lazy — see `ensure_reservoir_complete` — rather than
5728        // eagerly materializing every row on every WAL-replay batch.
5729        self.reservoir_complete = false;
5730        Ok(())
5731    }
5732
5733    /// Highest epoch whose data is durable in a sorted run (spec §7.1).
5734    pub(crate) fn flushed_epoch(&self) -> u64 {
5735        self.flushed_epoch
5736    }
5737
5738    pub(crate) fn set_flushed_epoch(&mut self, epoch: Epoch) {
5739        self.flushed_epoch = self.flushed_epoch.max(epoch.0);
5740    }
5741
5742    /// Validate that `cells` satisfy the schema's NOT NULL constraints.
5743    pub(crate) fn validate_cells_not_null(&self, cells: &[(u16, Value)]) -> Result<()> {
5744        self.schema.validate_values(cells)
5745    }
5746
5747    /// Column-major NOT NULL validation for the bulk-load paths. Every schema
5748    /// column that is not marked NULLABLE must be present in `columns` and have
5749    /// no null validity bits over its first `n` rows.
5750    fn validate_columns_not_null(
5751        &self,
5752        columns: &[(u16, columnar::NativeColumn)],
5753        n: usize,
5754    ) -> Result<()> {
5755        let by_id: HashMap<u16, &columnar::NativeColumn> =
5756            columns.iter().map(|(id, c)| (*id, c)).collect();
5757        for col in &self.schema.columns {
5758            if !col.flags.contains(ColumnFlags::NULLABLE) {
5759                match by_id.get(&col.id) {
5760                    None => {
5761                        return Err(MongrelError::InvalidArgument(format!(
5762                            "column '{}' ({}) is NOT NULL but was omitted from the bulk load",
5763                            col.name, col.id
5764                        )));
5765                    }
5766                    Some(c) => {
5767                        if c.null_count(n) != 0 {
5768                            return Err(MongrelError::InvalidArgument(format!(
5769                                "column '{}' ({}) is NOT NULL but the bulk load contains nulls",
5770                                col.name, col.id
5771                            )));
5772                        }
5773                    }
5774                }
5775            }
5776            if let TypeId::Enum { variants } = &col.ty {
5777                let Some(columnar::NativeColumn::Bytes { .. }) = by_id.get(&col.id).copied() else {
5778                    if by_id.contains_key(&col.id) {
5779                        return Err(MongrelError::InvalidArgument(format!(
5780                            "column '{}' ({}) enum requires a bytes column",
5781                            col.name, col.id
5782                        )));
5783                    }
5784                    continue;
5785                };
5786                for index in 0..n {
5787                    let Some(value) = columnar::native_bytes_at(by_id[&col.id], index) else {
5788                        continue;
5789                    };
5790                    if !variants.iter().any(|variant| variant.as_bytes() == value) {
5791                        return Err(MongrelError::InvalidArgument(format!(
5792                            "column '{}' ({}) enum value {:?} is not one of {:?}",
5793                            col.name,
5794                            col.id,
5795                            String::from_utf8_lossy(value),
5796                            variants
5797                        )));
5798                    }
5799                }
5800            }
5801        }
5802        Ok(())
5803    }
5804
5805    /// For a bulk-loaded batch, compute the row indices that survive primary-
5806    /// key upsert: for each PK value the last occurrence wins, earlier
5807    /// duplicates are dropped. Rows with a null PK value are always kept. Returns
5808    /// `None` when there is no primary key or no compaction is needed.
5809    fn bulk_pk_winner_indices(
5810        &self,
5811        columns: &[(u16, columnar::NativeColumn)],
5812        n: usize,
5813    ) -> Option<Vec<usize>> {
5814        let pk_col = self.schema.primary_key()?;
5815        let pk_id = pk_col.id;
5816        let pk_ty = pk_col.ty.clone();
5817        let by_id: HashMap<u16, &columnar::NativeColumn> =
5818            columns.iter().map(|(id, c)| (*id, c)).collect();
5819        let pk_native = by_id.get(&pk_id)?;
5820        if native_int64_strictly_increasing(pk_native, n) {
5821            return None;
5822        }
5823        // key -> index of the last row that carried that PK value.
5824        let mut last: HashMap<Vec<u8>, usize> = HashMap::new();
5825        let mut null_pk_rows: Vec<usize> = Vec::new();
5826        for i in 0..n {
5827            match bulk_index_key(&self.column_keys, pk_id, pk_ty.clone(), pk_native, i) {
5828                Some(key) => {
5829                    last.insert(key, i);
5830                }
5831                None => null_pk_rows.push(i),
5832            }
5833        }
5834        let mut winners: HashSet<usize> = last.values().copied().collect();
5835        for i in null_pk_rows {
5836            winners.insert(i);
5837        }
5838        Some((0..n).filter(|i| winners.contains(i)).collect())
5839    }
5840
5841    /// Logically delete `row_id` (effective at the next commit).
5842    pub fn delete(&mut self, row_id: RowId) -> Result<()> {
5843        self.require_delete()?;
5844        let epoch = self.pending_epoch();
5845        self.wal_append_data(Op::Delete {
5846            table_id: self.table_id,
5847            row_ids: vec![row_id],
5848        })?;
5849        if self.is_shared() {
5850            self.pending_dels.push(row_id);
5851        } else {
5852            self.apply_delete(row_id, epoch);
5853        }
5854        Ok(())
5855    }
5856
5857    pub fn delete_returning(&mut self, row_id: RowId) -> Result<Option<OwnedRow>> {
5858        let pre = self.get(row_id, self.snapshot());
5859        self.delete(row_id)?;
5860        Ok(pre.map(|row| {
5861            let mut columns: Vec<_> = row.columns.into_iter().collect();
5862            columns.sort_by_key(|(id, _)| *id);
5863            OwnedRow { columns }
5864        }))
5865    }
5866
5867    /// Durably remove every row in the table once the current write span commits.
5868    pub fn truncate(&mut self) -> Result<()> {
5869        self.require_delete()?;
5870        let epoch = self.pending_epoch();
5871        self.wal_append_data(Op::TruncateTable {
5872            table_id: self.table_id,
5873        })?;
5874        self.pending_rows.clear();
5875        self.pending_rows_auto_inc.clear();
5876        self.pending_dels.clear();
5877        self.pending_truncate = Some(epoch);
5878        Ok(())
5879    }
5880
5881    /// Apply an already-durable truncate without appending to the WAL.
5882    pub(crate) fn apply_truncate(&mut self, _epoch: Epoch) {
5883        // Unlink active topology in the next manifest before removing any run
5884        // file. A crash before that manifest is durable must still be able to
5885        // open the old manifest and replay the durable truncate from WAL.
5886        // Unreferenced files are safe orphans and `gc()` removes them later.
5887        self.run_refs.clear();
5888        self.retiring.clear();
5889        self.memtable = Memtable::new();
5890        self.mutable_run = MutableRun::new();
5891        self.hot = HotIndex::new();
5892        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
5893        self.bitmap = bitmap;
5894        self.ann = ann;
5895        self.fm = fm;
5896        self.sparse = sparse;
5897        self.minhash = minhash;
5898        self.learned_range = Arc::new(HashMap::new());
5899        self.pk_by_row.clear();
5900        self.pk_by_row_complete = false;
5901        self.live_count = 0;
5902        self.reservoir = crate::reservoir::Reservoir::default();
5903        self.reservoir_complete = true;
5904        self.had_deletes = true;
5905        self.agg_cache = Arc::new(HashMap::new());
5906        self.global_idx_epoch = 0;
5907        self.indexes_complete = true;
5908        self.pending_delete_rids.clear();
5909        self.pending_put_cols.clear();
5910        self.pending_rows.clear();
5911        self.pending_rows_auto_inc.clear();
5912        self.pending_dels.clear();
5913        self.clear_result_cache();
5914        self.invalidate_index_checkpoint();
5915        self.data_generation = self.data_generation.wrapping_add(1);
5916    }
5917
5918    /// Apply a tombstone (already-durable on the WAL) at `epoch` without
5919    /// appending to the per-table WAL. Used by the cross-table `Transaction`.
5920    pub(crate) fn apply_delete(&mut self, row_id: RowId, epoch: Epoch) {
5921        self.apply_delete_at(row_id, epoch, None);
5922    }
5923
5924    /// Apply a tombstone stamped with an optional HLC commit timestamp (P0.5).
5925    pub(crate) fn apply_delete_at(
5926        &mut self,
5927        row_id: RowId,
5928        epoch: Epoch,
5929        commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
5930    ) {
5931        // Capture pre-image before the tombstone lands so (1) Kit delete+put
5932        // can re-point Bitmap keys via `recent_delete_preimages` (the subsequent
5933        // put finds a stale HOT entry, and `index_row` reads the preimage from
5934        // `recent_delete_preimages` to drive delta maintenance), and (2) the
5935        // HOT entry is preserved so a `Condition::Pk` lookup can observe the
5936        // tombstone via `self.get(r, snap) == None` and record
5937        // `HotFallbackReason::Tombstone` (and so a pinned-snapshot lookup
5938        // records `HistoricalSnapshot` on the HOT-hit branch instead of
5939        // degrading to `MissingMapping` on the HOT-miss branch).
5940        let preimage = self.get(row_id, self.snapshot());
5941        if let Some(row) = preimage {
5942            if let Some(pk_col) = self.schema.primary_key() {
5943                if let Some(pk_val) = row.columns.get(&pk_col.id) {
5944                    let key = self.index_lookup_key(pk_col.id, pk_val);
5945                    self.recent_delete_preimages.insert(key, row);
5946                }
5947            }
5948        }
5949        self.tombstone_row(row_id, epoch, commit_ts, true);
5950        self.data_generation = self.data_generation.wrapping_add(1);
5951    }
5952
5953    /// Drop this row's membership from every Bitmap secondary (best-effort).
5954    /// Used on replace / partial-predicate paths that must re-point equality
5955    /// keys; pure deletes keep membership so historical snapshots can still
5956    /// discover the rid via BitmapEq (see [`Self::apply_delete_at`]).
5957    fn unindex_bitmap_membership(&mut self, row: &Row) {
5958        if row.deleted {
5959            return;
5960        }
5961        for idef in &self.schema.indexes {
5962            if idef.kind != crate::schema::IndexKind::Bitmap {
5963                continue;
5964            }
5965            if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
5966                if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
5967                    b.remove(&key, row.row_id);
5968                }
5969            }
5970        }
5971    }
5972
5973    /// Union Bitmap membership for a point (`lo == hi`) int64 range query into
5974    /// `set`, then re-merge overlay so pure-memtable rows still win. No-op when
5975    /// the column has no Bitmap index.
5976    fn union_bitmap_point_i64(
5977        &self,
5978        set: &mut RowIdSet,
5979        column_id: u16,
5980        value: i64,
5981        snapshot: Snapshot,
5982    ) {
5983        let Some(b) = self.bitmap.get(&column_id) else {
5984            return;
5985        };
5986        let encoded = Value::Int64(value).encode_key();
5987        let lookup = self.index_lookup_key_bytes(column_id, &encoded);
5988        for rid in b.get(&lookup).iter() {
5989            set.insert(u64::from(rid));
5990        }
5991        // Drop rids whose newest overlay version is a tombstone (append-only
5992        // leftovers). Live overlay versions for this value are re-inserted by
5993        // the overlay range scan.
5994        set.remove_many(self.overlay_tombstoned_rids(snapshot));
5995        self.range_scan_overlay_i64(set, column_id, value, value, snapshot);
5996    }
5997
5998    /// Tombstone `row_id` at `epoch`. When `adjust_live_count` is true the
5999    /// table's `live_count` is decremented (used on the live write path); during
6000    /// recovery the manifest is authoritative so the flag is false.
6001    ///
6002    /// `live_count` is decremented only when the prior visible version of
6003    /// `row_id` was a live row. A prior tombstone (either from earlier in this
6004    /// commit or from a previous commit) means the live-count adjustment has
6005    /// already happened — the cross-table `Transaction` path can call
6006    /// `tombstone_row` on the same rid twice in one commit (Delete + the
6007    /// Put's stale HOT tombstone), and standalone callers can hit the same
6008    /// rid twice across commits. Without this guard `live_count` drifts
6009    /// negative (saturating to 0) and `Table::count()` returns a value below
6010    /// the true live-row count.
6011    fn tombstone_row(
6012        &mut self,
6013        row_id: RowId,
6014        epoch: Epoch,
6015        commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
6016        adjust_live_count: bool,
6017    ) {
6018        let prev_was_live = if adjust_live_count {
6019            match self.memtable.get_version(row_id, epoch) {
6020                Some((_, prev)) => !prev.deleted,
6021                None => true,
6022            }
6023        } else {
6024            false
6025        };
6026        let tombstone = Row {
6027            row_id,
6028            committed_epoch: epoch,
6029            columns: std::collections::HashMap::new(),
6030            deleted: true,
6031            commit_ts,
6032        };
6033        self.memtable.upsert(tombstone);
6034        self.pk_by_row.remove(&row_id);
6035        if prev_was_live {
6036            self.live_count = self.live_count.saturating_sub(1);
6037        }
6038        // Track for fine-grained cache invalidation (c).
6039        self.pending_delete_rids.insert(row_id.0 as u32);
6040        // A delete makes the incremental aggregate cache (row-id watermark
6041        // delta) unsafe — permanently disable it for this table.
6042        self.had_deletes = true;
6043        self.agg_cache = Arc::new(HashMap::new());
6044    }
6045
6046    /// If `row_id` has a primary-key value and the HOT index currently maps
6047    /// that PK to this row id, remove the entry. Keeps the PK→RowId mapping
6048    /// consistent after deletes and before upserts.
6049    fn remove_hot_for_row(&mut self, row_id: RowId, epoch: Epoch) {
6050        let Some(pk_col) = self.schema.primary_key() else {
6051            return;
6052        };
6053        // Warm path: a prior delete in this process already paid the
6054        // reverse-map rebuild below, so it's kept up to date — O(1).
6055        if self.pk_by_row_complete {
6056            if let Some(key) = self.pk_by_row.remove(&row_id) {
6057                if self.hot.get(&key) == Some(row_id) {
6058                    self.hot.remove(&key);
6059                }
6060            }
6061            return;
6062        }
6063        // Cold path (the common case: a short-lived process — CLI,
6064        // NAPI-per-call — that deletes once and exits): derive the PK
6065        // straight from the row's own pre-delete version via a targeted
6066        // get_version lookup (memtable -> mutable_run -> runs, the same
6067        // page-pruned lookup `Table::get` uses) instead of paying
6068        // `refresh_pk_by_row_from_hot`'s O(table-size) rebuild for a single
6069        // delete. `pk_by_row` is deliberately left incomplete here — same
6070        // "puts leave the reverse map stale" tradeoff, extended to this path.
6071        //
6072        // Look up at `epoch - 1`, not `epoch`: on the live-delete call site
6073        // this delete's own tombstone hasn't landed yet either way, but on
6074        // the WAL-replay call sites (`recover_apply`, `open_in`) the
6075        // memtable tombstone for this exact row/epoch is already applied
6076        // before this runs. Querying `epoch` would see that tombstone
6077        // (empty columns) and fall through to the full rebuild every time a
6078        // replayed delete exists; `epoch - 1` is still >= any real prior
6079        // version's committed_epoch (epochs are unique and monotonic), so it
6080        // finds the same pre-delete row either way.
6081        let lookup_epoch = Epoch(epoch.0.saturating_sub(1));
6082        if self.indexes_complete {
6083            let pk_val = self
6084                .memtable
6085                .get_version(row_id, lookup_epoch)
6086                .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6087                .or_else(|| {
6088                    self.mutable_run
6089                        .get_version(row_id, lookup_epoch)
6090                        .filter(|(_, r)| !r.deleted)
6091                        .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6092                })
6093                .or_else(|| {
6094                    self.run_refs.iter().find_map(|rr| {
6095                        let mut reader = self.open_reader(rr.run_id).ok()?;
6096                        let (_, deleted, val) = reader
6097                            .get_version_column(row_id, lookup_epoch, pk_col.id)
6098                            .ok()??;
6099                        if deleted {
6100                            return None;
6101                        }
6102                        val
6103                    })
6104                });
6105            if let Some(pk_val) = pk_val {
6106                let key = self.index_lookup_key(pk_col.id, &pk_val);
6107                if self.hot.get(&key) == Some(row_id) {
6108                    self.hot.remove(&key);
6109                }
6110                return;
6111            }
6112        }
6113        // Fallback: full reverse-map rebuild, guaranteed correct. Reached
6114        // when indexes aren't complete yet, or the row was already gone by
6115        // the time this ran (e.g. already tombstoned in an overlay ahead of
6116        // this HOT cleanup, as `rebuild_indexes_from_runs` does).
6117        self.refresh_pk_by_row_from_hot();
6118        if let Some(key) = self.pk_by_row.remove(&row_id) {
6119            if self.hot.get(&key) == Some(row_id) {
6120                self.hot.remove(&key);
6121            }
6122        }
6123    }
6124
6125    /// For a batch of rows that share the same commit epoch, decide which rows
6126    /// win for each primary-key value. Returns the set of "loser" row ids that
6127    /// must be skipped/overwritten, and a map from PK lookup key to the winning
6128    /// row id. Rows without a PK value are always winners.
6129    fn partition_pk_winners(
6130        &self,
6131        rows: &[Row],
6132    ) -> (
6133        std::collections::HashSet<RowId>,
6134        std::collections::HashMap<Vec<u8>, RowId>,
6135    ) {
6136        let mut losers = std::collections::HashSet::new();
6137        let Some(pk_col) = self.schema.primary_key() else {
6138            return (losers, std::collections::HashMap::new());
6139        };
6140        let pk_id = pk_col.id;
6141        let mut winners: std::collections::HashMap<Vec<u8>, RowId> =
6142            std::collections::HashMap::new();
6143        for r in rows {
6144            let Some(pk_val) = r.columns.get(&pk_id) else {
6145                continue;
6146            };
6147            let key = self.index_lookup_key(pk_id, pk_val);
6148            if let Some(&old_rid) = winners.get(&key) {
6149                losers.insert(old_rid);
6150            }
6151            winners.insert(key, r.row_id);
6152        }
6153        (losers, winners)
6154    }
6155
6156    fn index_row(&mut self, row: &Row) {
6157        if row.deleted {
6158            return;
6159        }
6160        // Partial index filtering: skip rows that don't match any index's
6161        // predicate. The predicate is a SQL WHERE clause string evaluated
6162        // against the row's column values. For now, we support a simple
6163        // "column_name IS NOT NULL" and "column_name = value" syntax that
6164        // covers the common partial-index patterns (e.g. WHERE deleted_at
6165        // IS NULL). More complex predicates require a full expression
6166        // evaluator in core (future work).
6167        let any_predicate = self
6168            .schema
6169            .indexes
6170            .iter()
6171            .any(|idx| idx.predicate.is_some());
6172        if any_predicate {
6173            let columns_map: HashMap<u16, &Value> =
6174                row.columns.iter().map(|(k, v)| (*k, v)).collect();
6175            let name_to_id: HashMap<&str, u16> = self
6176                .schema
6177                .columns
6178                .iter()
6179                .map(|c| (c.name.as_str(), c.id))
6180                .collect();
6181            for idx in &self.schema.indexes {
6182                if let Some(pred) = &idx.predicate {
6183                    if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
6184                        continue; // skip this index for this row
6185                    }
6186                }
6187                // Index the row into this specific index only.
6188                index_into_single(
6189                    idx,
6190                    &self.schema,
6191                    row,
6192                    &mut self.hot,
6193                    &mut self.bitmap,
6194                    &mut self.ann,
6195                    &mut self.fm,
6196                    &mut self.sparse,
6197                    &mut self.minhash,
6198                );
6199            }
6200            return;
6201        }
6202        // Plaintext tables index the row as-is; only ENCRYPTED_INDEXABLE
6203        // columns need the tokenized copy (`tokenized_for_indexes` clones the
6204        // whole row, which would tax every put on unencrypted tables).
6205        if self.column_keys.is_empty() {
6206            index_into(
6207                &self.schema,
6208                row,
6209                &mut self.hot,
6210                &mut self.bitmap,
6211                &mut self.ann,
6212                &mut self.fm,
6213                &mut self.sparse,
6214                &mut self.minhash,
6215            );
6216            return;
6217        }
6218        let effective_row = self.tokenized_for_indexes(row);
6219        index_into(
6220            &self.schema,
6221            &effective_row,
6222            &mut self.hot,
6223            &mut self.bitmap,
6224            &mut self.ann,
6225            &mut self.fm,
6226            &mut self.sparse,
6227            &mut self.minhash,
6228        );
6229    }
6230
6231    /// Produce the row view that indexes should see. For ENCRYPTED_INDEXABLE
6232    /// equality (HMAC-eq) columns the plaintext value is replaced by its token,
6233    /// so the bitmap/HOT indexes store tokens. OPE-range columns keep their raw
6234    /// value (their range index is rebuilt from runs over plaintext). Plaintext
6235    /// tables return the row unchanged.
6236    fn tokenized_for_indexes(&self, row: &Row) -> Row {
6237        if self.column_keys.is_empty() {
6238            return row.clone();
6239        }
6240        {
6241            use crate::encryption::SCHEME_HMAC_EQ;
6242            let mut tok = row.clone();
6243            for (&cid, &(_, scheme)) in &self.column_keys {
6244                if scheme != SCHEME_HMAC_EQ {
6245                    continue;
6246                }
6247                if let Some(v) = tok.columns.get(&cid).cloned() {
6248                    if let Some(t) = self.tokenize_value(cid, &v) {
6249                        tok.columns.insert(cid, t);
6250                    }
6251                }
6252            }
6253            tok
6254        }
6255    }
6256
6257    /// Group-commit: make all pending writes durable, advance the epoch so they
6258    /// become visible, and persist the manifest. Dispatches on the WAL sink: a
6259    /// standalone table fsyncs its private WAL; a mounted table seals into the
6260    /// shared WAL and defers the fsync to the group-commit coordinator (B1).
6261    pub fn commit(&mut self) -> Result<Epoch> {
6262        self.commit_inner(None)
6263    }
6264
6265    /// Prepare a pending commit cooperatively, then invoke `before_commit`
6266    /// immediately before the durable transaction marker is appended.
6267    #[doc(hidden)]
6268    pub fn commit_controlled<F>(
6269        &mut self,
6270        control: &crate::ExecutionControl,
6271        mut before_commit: F,
6272    ) -> Result<Epoch>
6273    where
6274        F: FnMut() -> Result<()>,
6275    {
6276        self.commit_inner(Some((control, &mut before_commit)))
6277    }
6278
6279    fn commit_inner(
6280        &mut self,
6281        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6282    ) -> Result<Epoch> {
6283        self.ensure_writable()?;
6284        if !self.has_pending_mutations() {
6285            if self.current_txn_id == 0 && matches!(&self.wal, WalSink::Private(_)) {
6286                return Err(MongrelError::Full(
6287                    "standalone transaction id namespace exhausted".into(),
6288                ));
6289            }
6290            return Ok(self.epoch.visible());
6291        }
6292        self.commit_new_epoch_inner(controlled)
6293    }
6294
6295    /// Seal a real logical write at a fresh epoch. Bulk-load paths publish
6296    /// their run directly rather than staging rows in the WAL, so they call
6297    /// this after proving the input is non-empty.
6298    fn commit_new_epoch(&mut self) -> Result<Epoch> {
6299        self.commit_new_epoch_inner(None)
6300    }
6301
6302    fn commit_new_epoch_inner(
6303        &mut self,
6304        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6305    ) -> Result<Epoch> {
6306        self.ensure_writable()?;
6307        if self.is_shared() {
6308            self.commit_shared(controlled)
6309        } else {
6310            self.commit_private(controlled)
6311        }
6312    }
6313
6314    /// Standalone commit: fsync the private WAL under the commit lock.
6315    fn commit_private(
6316        &mut self,
6317        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6318    ) -> Result<Epoch> {
6319        // Serialize the assign→fsync→publish critical section across all tables
6320        // sharing the epoch authority so `visible` is published strictly in
6321        // assigned order (the dual-counter invariant).
6322        let commit_lock = Arc::clone(&self.commit_lock);
6323        let _g = commit_lock.lock();
6324        // Validate the private transaction namespace before allocating an
6325        // epoch or appending any terminal WAL record.
6326        let txn_id = self.ensure_txn_id()?;
6327        if let Some((control, before_commit)) = controlled {
6328            control.checkpoint()?;
6329            before_commit()?;
6330        }
6331        let new_epoch = self.epoch.bump_assigned();
6332        let epoch_authority = Arc::clone(&self.epoch);
6333        let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6334        // Seal the staged records under a TxnCommit marker carrying the commit
6335        // epoch, then a single group fsync. Recovery applies only records whose
6336        // txn has a durable TxnCommit (uncommitted/torn tails are discarded).
6337        let wal_result = match &mut self.wal {
6338            WalSink::Private(w) => w
6339                .append_txn(
6340                    txn_id,
6341                    Op::TxnCommit {
6342                        epoch: new_epoch.0,
6343                        added_runs: Vec::new(),
6344                    },
6345                )
6346                .and_then(|_| w.sync()),
6347            WalSink::Shared(_) => unreachable!("commit_private on a shared sink"),
6348            WalSink::ReadOnly => Err(MongrelError::ReadOnlyReplica),
6349        };
6350        if let Err(error) = wal_result {
6351            self.durable_commit_failed = true;
6352            return Err(MongrelError::CommitOutcomeUnknown {
6353                epoch: new_epoch.0,
6354                message: error.to_string(),
6355            });
6356        }
6357        // The commit marker is durable. Resolve the assigned epoch even when a
6358        // live publish/checkpoint step fails, and report the exact outcome.
6359        if let Some(epoch) = self.pending_truncate.take() {
6360            self.apply_truncate(epoch);
6361        }
6362        self.invalidate_pending_cache();
6363        let publish_result = self.persist_manifest(new_epoch);
6364        // Publish through the shared in-order gate so a `Table::commit` can never
6365        // advance the watermark past an in-flight cross-table transaction's
6366        // lower assigned epoch whose writes are not yet applied (spec §9.3e).
6367        self.epoch.publish_in_order(new_epoch);
6368        epoch_guard.disarm();
6369        if let Err(error) = publish_result {
6370            self.durable_commit_failed = true;
6371            return Err(MongrelError::DurableCommit {
6372                epoch: new_epoch.0,
6373                message: error.to_string(),
6374            });
6375        }
6376        self.current_txn_id = txn_id.checked_add(1).unwrap_or(0);
6377        self.pending_private_mutations = false;
6378        self.data_generation = self.data_generation.wrapping_add(1);
6379        Ok(new_epoch)
6380    }
6381
6382    /// Mounted commit (B1/B2): mirror the cross-table sequencer. Seal a
6383    /// `TxnCommit` into the shared WAL under the WAL lock (assigning the epoch in
6384    /// WAL-append order), make it durable via the group-commit coordinator (one
6385    /// leader fsync for the whole batch), then apply the staged rows at the
6386    /// assigned epoch and publish in order. Honors the shared poison flag.
6387    fn commit_shared(
6388        &mut self,
6389        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6390    ) -> Result<Epoch> {
6391        use std::sync::atomic::Ordering;
6392        let s = match &self.wal {
6393            WalSink::Shared(s) => s.clone(),
6394            WalSink::Private(_) => unreachable!("commit_shared on a private sink"),
6395            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6396        };
6397        if s.poisoned.load(Ordering::Relaxed) {
6398            return Err(MongrelError::Other(
6399                "database poisoned by fsync error".into(),
6400            ));
6401        }
6402        // Serialize the whole single-table commit critical section (assign →
6403        // durable → publish) under the shared commit lock so concurrent
6404        // `Table::commit`s publish strictly in assigned order and each returns
6405        // only once its epoch is visible (read-your-writes after commit). The
6406        // fsync still defers to the group-commit coordinator, which can batch a
6407        // held commit with concurrent cross-table `transaction()` committers.
6408        let commit_lock = Arc::clone(&self.commit_lock);
6409        let _g = commit_lock.lock();
6410        if !self.pending_rows.is_empty() {
6411            match controlled.as_ref() {
6412                Some((control, _)) => self.prepare_durable_publish_controlled(control)?,
6413                None => self.prepare_durable_publish()?,
6414            }
6415        }
6416        // Always seal a txn (allocating an id if this span had no writes) so the
6417        // epoch advances monotonically like the standalone path.
6418        let txn_id = self.ensure_txn_id()?;
6419        let mut wal = s.wal.lock();
6420        if let Some((control, before_commit)) = controlled {
6421            control.checkpoint()?;
6422            before_commit()?;
6423        }
6424        let new_epoch = self.epoch.bump_assigned();
6425        let epoch_authority = Arc::clone(&self.epoch);
6426        let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6427        // P0.5: stamp every row version with the database HLC so visibility is
6428        // HLC-authoritative on the single-table commit path too.
6429        let commit_ts = s.hlc.now().map_err(|skew| {
6430            MongrelError::Other(format!(
6431                "clock skew rejected commit timestamp allocation: {skew}"
6432            ))
6433        })?;
6434        let commit_seq = match wal.append_commit_at(
6435            txn_id,
6436            new_epoch,
6437            &[],
6438            commit_ts.physical_micros.saturating_mul(1_000),
6439        ) {
6440            Ok(commit_seq) => commit_seq,
6441            Err(error) => {
6442                s.poisoned.store(true, Ordering::Relaxed);
6443                s.lifecycle.poison();
6444                return Err(MongrelError::CommitOutcomeUnknown {
6445                    epoch: new_epoch.0,
6446                    message: error.to_string(),
6447                });
6448            }
6449        };
6450        drop(wal);
6451        if let Err(error) = s.group.await_durable(&s.wal, commit_seq) {
6452            s.poisoned.store(true, Ordering::Relaxed);
6453            s.lifecycle.poison();
6454            return Err(MongrelError::CommitOutcomeUnknown {
6455                epoch: new_epoch.0,
6456                message: error.to_string(),
6457            });
6458        }
6459
6460        // Apply staged state after durability, but never lose the durable
6461        // outcome if a live apply or manifest checkpoint fails.
6462        if self.pending_truncate.take().is_some() {
6463            self.apply_truncate(new_epoch);
6464        }
6465        let mut rows = std::mem::take(&mut self.pending_rows);
6466        if !rows.is_empty() {
6467            for r in &mut rows {
6468                r.committed_epoch = new_epoch;
6469                r.commit_ts = Some(commit_ts);
6470            }
6471            let auto_inc_flags = std::mem::take(&mut self.pending_rows_auto_inc);
6472            let all_auto_generated =
6473                auto_inc_flags.len() == rows.len() && auto_inc_flags.iter().all(|b| *b);
6474            self.apply_put_rows_inner_prepared(rows, !all_auto_generated);
6475        } else {
6476            self.pending_rows_auto_inc.clear();
6477        }
6478        let dels = std::mem::take(&mut self.pending_dels);
6479        for rid in dels {
6480            self.apply_delete_at(rid, new_epoch, Some(commit_ts));
6481        }
6482
6483        self.invalidate_pending_cache();
6484        let publish_result = self.persist_manifest(new_epoch);
6485        self.epoch.publish_in_order(new_epoch);
6486        epoch_guard.disarm();
6487        let _ = s.change_wake.send(());
6488        if let Err(error) = publish_result {
6489            self.durable_commit_failed = true;
6490            s.poisoned.store(true, Ordering::Relaxed);
6491            s.lifecycle.poison();
6492            return Err(MongrelError::DurableCommit {
6493                epoch: new_epoch.0,
6494                message: error.to_string(),
6495            });
6496        }
6497        // Next auto-commit span allocates a fresh shared txn id.
6498        self.current_txn_id = 0;
6499        self.data_generation = self.data_generation.wrapping_add(1);
6500        Ok(new_epoch)
6501    }
6502
6503    /// Commit, then drain the memtable into the mutable-run LSM tier (Phase
6504    /// 11.1). The tier absorbs flushes in place and only spills to an immutable
6505    /// `.sr` sorted run once it crosses the spill watermark — coalescing many
6506    /// small flushes into fewer, larger runs. While the tier holds un-spilled
6507    /// data the WAL is **not** rotated: the Flush marker / WAL rotation is
6508    /// deferred until the data is durably in a run, so crash recovery replays
6509    /// those rows back into the memtable (the tier rebuilds from replay).
6510    pub fn flush(&mut self) -> Result<Epoch> {
6511        self.flush_with_outcome().map(|(epoch, _)| epoch)
6512    }
6513
6514    /// Flush and report whether this call published pending logical mutations.
6515    pub fn flush_with_outcome(&mut self) -> Result<(Epoch, bool)> {
6516        self.flush_with_outcome_inner(None)
6517    }
6518
6519    /// Cooperatively prepare a flush, entering the commit fence immediately
6520    /// before its transaction marker can become durable.
6521    #[doc(hidden)]
6522    pub fn flush_with_outcome_controlled<F>(
6523        &mut self,
6524        control: &crate::ExecutionControl,
6525        mut before_commit: F,
6526    ) -> Result<(Epoch, bool)>
6527    where
6528        F: FnMut() -> Result<()>,
6529    {
6530        self.flush_with_outcome_inner(Some((control, &mut before_commit)))
6531    }
6532
6533    fn flush_with_outcome_inner(
6534        &mut self,
6535        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6536    ) -> Result<(Epoch, bool)> {
6537        match controlled.as_ref() {
6538            Some((control, _)) => {
6539                self.ensure_indexes_complete_controlled(control, || true)?;
6540            }
6541            None => self.ensure_indexes_complete()?,
6542        }
6543        let committed = self.has_pending_mutations();
6544        let epoch = self.commit_inner(controlled)?;
6545        let finish: Result<(Epoch, bool)> = (|| {
6546            let rows = self.memtable.drain_sorted();
6547            if !rows.is_empty() {
6548                self.mutable_run.insert_many(rows);
6549            }
6550            if self.mutable_run.approx_bytes() >= self.mutable_run_spill_bytes {
6551                self.spill_mutable_run(epoch)?;
6552                // The tier is now empty and its data is durably in a run → safe to
6553                // mark the WAL flushed (and, for a private WAL, rotate to a fresh
6554                // segment so the flushed records aren't replayed).
6555                self.mark_flushed(epoch)?;
6556                self.persist_manifest(epoch)?;
6557                self.build_learned_ranges()?;
6558                // Memtable is drained and runs are stable → checkpoint the indexes so
6559                // the next open skips the full run scan (Phase 9.1).
6560                self.checkpoint_indexes(epoch);
6561                // Issue 4: rebuild + publish the run-lookup directory so the
6562                // next open fast-paths point lookups. Failure is non-fatal —
6563                // the manifest is already durable so the table reopens and
6564                // rebuilds the directory lazily.
6565                let _ = self.publish_run_lookup_directory();
6566            }
6567            // else: data coalesced in the in-memory tier; the WAL still covers it
6568            // and the manifest epoch was already persisted by `commit`.
6569            Ok((epoch, committed))
6570        })();
6571        let outcome = match finish {
6572            Err(error) if committed => Err(MongrelError::DurableCommit {
6573                epoch: epoch.0,
6574                message: error.to_string(),
6575            }),
6576            result => result,
6577        };
6578        if outcome.is_ok() {
6579            // S1C-001: the base changed (the memtable drained into the
6580            // mutable-run tier and may have spilled to a new run) — publish a
6581            // fresh immutable view for generation readers. Indexes were
6582            // ensured complete above, so publishing cannot fail; if it ever
6583            // did, the previous (still valid) view stays published.
6584            let _ = self.publish_read_generation();
6585        }
6586        outcome
6587    }
6588
6589    pub(crate) fn has_pending_mutations(&self) -> bool {
6590        self.pending_private_mutations
6591            || !self.pending_rows.is_empty()
6592            || !self.pending_dels.is_empty()
6593            || self.pending_truncate.is_some()
6594    }
6595
6596    pub fn has_pending_writes(&self) -> bool {
6597        self.has_pending_mutations()
6598    }
6599
6600    /// Force a full flush to a `.sr` sorted run regardless of the spill
6601    /// threshold. Temporarily lowers `mutable_run_spill_bytes` to 1 so the
6602    /// threshold check in [`Self::flush`] always fires. Used by
6603    /// [`Self::close`] and the Kit's flush-on-close path (§4.4) so a
6604    /// short-lived process (CLI, one-shot script) leaves all pending writes
6605    /// durable in a run — keeping WAL segment count bounded across repeated
6606    /// invocations. Best-effort: errors are propagated but the threshold is
6607    /// always restored.
6608    pub fn force_flush(&mut self) -> Result<Epoch> {
6609        let saved = self.mutable_run_spill_bytes;
6610        self.mutable_run_spill_bytes = 1;
6611        let result = self.flush();
6612        self.mutable_run_spill_bytes = saved;
6613        result
6614    }
6615
6616    /// Best-effort close: force-flush any pending writes to a sorted run so
6617    /// the WAL segments can be reaped on the next open. Never panics — a
6618    /// flush error is logged and returned but the threshold is always
6619    /// restored. Call this as the last action before a short-lived process
6620    /// exits (CLI, one-shot script). Not needed for the daemon (its
6621    /// background auto-compactor handles run management). (§4.4)
6622    pub fn close(&mut self) -> Result<()> {
6623        if self.memtable_len() > 0 || self.mutable_run_len() > 0 {
6624            self.force_flush()?;
6625        }
6626        // Drain the persistent result cache: best-effort, deadline-bounded
6627        // shutdown of the background writer. Closing the table should not
6628        // block forever; ops still queued at the deadline are abandoned
6629        // (counted on the writer's `result_cache_persist_shutdown_abandoned_total`
6630        // metric) but the queue lock is released.
6631        self.result_cache
6632            .lock()
6633            .shutdown_persistent_cache(std::time::Duration::from_secs(5));
6634        Ok(())
6635    }
6636
6637    /// Mark `epoch` as flushed: append a `Flush` marker to the WAL, advance
6638    /// `flushed_epoch`, and — for a private WAL only — rotate to a fresh segment
6639    /// so the now-durable-in-a-run records are not replayed. A mounted table's
6640    /// shared WAL is never rotated per-table; recovery skips its already-flushed
6641    /// records via the manifest `flushed_epoch` gate, and segment GC (B3c) reaps
6642    /// them once every table has flushed past them.
6643    /// True when this table has no WAL replay gate to advance (read-only
6644    /// replica sink). Compaction consults this before advancing
6645    /// `flushed_epoch`.
6646    pub(crate) fn wal_is_read_only(&self) -> bool {
6647        matches!(self.wal, WalSink::ReadOnly)
6648    }
6649
6650    /// Move committed memtable rows (committed at or below `epoch`) into the
6651    /// mutable run, leaving pending, uncommitted rows (which sit at
6652    /// `pending_epoch = visible + 1`) in the memtable. Compaction calls this
6653    /// before snapshotting the merge input so publishing can advance the WAL
6654    /// replay gate without stranding committed rows outside the runs.
6655    pub(crate) fn drain_committed_memtable_rows(&mut self, epoch: Epoch) {
6656        if self.memtable_len() == 0 {
6657            return;
6658        }
6659        let rows = self.memtable.drain_sorted();
6660        let mut pending = Vec::new();
6661        let mut committed = Vec::new();
6662        for row in rows {
6663            if row.committed_epoch > epoch {
6664                pending.push(row);
6665            } else {
6666                committed.push(row);
6667            }
6668        }
6669        if !committed.is_empty() {
6670            self.mutable_run.insert_many(committed);
6671        }
6672        for row in pending {
6673            self.memtable.upsert(row);
6674        }
6675    }
6676
6677    pub(crate) fn mark_flushed(&mut self, epoch: Epoch) -> Result<()> {
6678        let op = Op::Flush {
6679            table_id: self.table_id,
6680            flushed_epoch: epoch.0,
6681        };
6682        match &mut self.wal {
6683            WalSink::Private(w) => {
6684                w.append_system(op)?;
6685                w.sync()?;
6686            }
6687            WalSink::Shared(s) => {
6688                // Informational in the shared log (recovery gates on the manifest
6689                // `flushed_epoch`); not separately fsynced — the run + manifest
6690                // are the durability point and the underlying rows were already
6691                // fsynced at their commit.
6692                s.wal.lock().append_system(op)?;
6693            }
6694            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6695        }
6696        self.flushed_epoch = epoch.0;
6697        if matches!(self.wal, WalSink::Private(_)) {
6698            self.rotate_wal(epoch)?;
6699        }
6700        Ok(())
6701    }
6702
6703    /// Spill the mutable-run tier to a new immutable level-0 sorted run. The
6704    /// caller owns the Flush-marker / WAL-rotation / manifest steps (only valid
6705    /// once all in-flight data is in runs). No-op when the tier is empty.
6706    fn spill_mutable_run(&mut self, epoch: Epoch) -> Result<()> {
6707        if self.mutable_run.is_empty() {
6708            return Ok(());
6709        }
6710        let run_id = self.alloc_run_id()?;
6711        let rows = self.mutable_run.drain_sorted();
6712        if rows.is_empty() {
6713            return Ok(());
6714        }
6715        let path = self.run_path(run_id);
6716        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
6717        if let Some(kek) = &self.kek {
6718            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6719        }
6720        let header = match self.create_run_file(run_id)? {
6721            Some(file) => writer.write_file(file, &rows)?,
6722            None => writer.write(&path, &rows)?,
6723        };
6724        self.run_refs.push(RunRef {
6725            run_id: run_id as u128,
6726            level: 0,
6727            epoch_created: epoch.0,
6728            row_count: header.row_count,
6729        });
6730        self.run_row_id_ranges
6731            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6732        Ok(())
6733    }
6734
6735    /// Tune the mutable-run spill watermark (bytes). A smaller threshold spills
6736    /// sooner (more, smaller runs — closer to the pre-Phase-11.1 behavior); a
6737    /// larger one coalesces more flushes in memory.
6738    pub fn set_mutable_run_spill_bytes(&mut self, bytes: u64) {
6739        self.mutable_run_spill_bytes = bytes.max(1);
6740    }
6741
6742    /// Set the zstd compression level for compaction output (Phase 18.1).
6743    /// Default 3; higher values give better compression ratio at the cost of
6744    /// slower compaction.
6745    pub fn set_compaction_zstd_level(&mut self, level: i32) {
6746        self.compaction_zstd_level = level;
6747    }
6748
6749    /// Set the result-cache byte budget (Phase 19.1 hardening (a)). Entries are
6750    /// evicted in access-order LRU past this limit. Takes effect immediately
6751    /// (may evict entries if the new limit is smaller than the current footprint).
6752    pub fn set_result_cache_max_bytes(&mut self, max_bytes: u64) {
6753        self.result_cache.lock().set_max_bytes(max_bytes);
6754    }
6755
6756    /// Wait for the persistent-cache writer to drain the pending queue, up
6757    /// to `deadline_ms` milliseconds. Returns the queue depth observed at
6758    /// the moment of the return (0 if fully drained). Tests use this to
6759    /// observe on-disk state without sleeping.
6760    pub fn flush_persistent_cache(&self, deadline_ms: u64) -> u64 {
6761        self.result_cache
6762            .lock()
6763            .flush_persistent_cache(std::time::Duration::from_millis(deadline_ms))
6764    }
6765
6766    /// Shut down the persistent-cache writer, draining pending ops until
6767    /// either the queue is empty or `deadline_ms` milliseconds have passed.
6768    /// The worker thread is joined on return. Tests and `Database::close`
6769    /// use this.
6770    pub fn shutdown_persistent_cache(&mut self, deadline_ms: u64) {
6771        self.result_cache
6772            .lock()
6773            .shutdown_persistent_cache(std::time::Duration::from_millis(deadline_ms));
6774    }
6775
6776    /// Test-only: set the minimum cache entry size (approx bytes) below
6777    /// which the persistent tier is skipped. A value of `0` always
6778    /// publishes to disk. Used by the REM-002 production tests so small
6779    /// fixtures can exercise the on-disk path without 4 KiB of data.
6780    #[doc(hidden)]
6781    pub fn _set_persist_min_bytes_for_test(&mut self, min: u64) {
6782        self.result_cache.lock().set_persist_min_bytes(min);
6783    }
6784
6785    /// Test seam (REM-D §8.8): when `enabled`, the next
6786    /// `Table::create` / `Table::open` on **this thread** fails its
6787    /// persistent-cache worker spawn and marks publication
6788    /// `Disabled(WorkerSpawnFailed)`. Thread-local, so concurrently running
6789    /// tests are unaffected. Callers should reset it with
6790    /// `_force_persistent_worker_spawn_failure_for_test(false)` after use.
6791    #[doc(hidden)]
6792    pub fn _force_persistent_worker_spawn_failure_for_test(enabled: bool) {
6793        PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.set(enabled));
6794    }
6795
6796    /// Explicit administrative flush (REM-D §8.6): synchronously persist the
6797    /// in-memory cached entry for `q` through the maintenance path
6798    /// (`persist_entry_synchronously_for_maintenance`), even when the
6799    /// background writer is unavailable. Returns `true` when an in-memory
6800    /// entry existed and a frame write was attempted. Never used by the
6801    /// query path; intended for migration tools and format-parity tests.
6802    #[doc(hidden)]
6803    pub fn _persist_cached_entry_synchronously_for_maintenance(
6804        &mut self,
6805        q: &crate::query::Query,
6806    ) -> bool {
6807        let key = crate::query::canonical_query_key(&q.conditions, None, 0)
6808            ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
6809            ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
6810        let identity = PersistentCacheIdentity {
6811            table_id: self.table_id(),
6812            schema_id: self.schema.schema_id,
6813            logical_generation: self.current_epoch().0,
6814        };
6815        let mut cache = self.result_cache.lock();
6816        let Some(entry) = cache.entries.get(&key).map(|e| e.clone_for_persist()) else {
6817            return false;
6818        };
6819        let entry_generation = cache.allocate_persist_generation(key);
6820        let context = PersistContext {
6821            identity,
6822            key,
6823            entry_generation,
6824        };
6825        cache.persist_entry_synchronously_for_maintenance(context, &entry);
6826        true
6827    }
6828
6829    /// Drop every cached result (used by compaction, schema evolution, and bulk
6830    /// load — paths that change run layout or data without going through the
6831    /// fine-grained `pending_*` tracking).
6832    pub(crate) fn clear_result_cache(&mut self) {
6833        self.result_cache.lock().clear();
6834    }
6835
6836    /// Number of versions currently held in the mutable-run tier.
6837    pub fn mutable_run_len(&self) -> usize {
6838        self.mutable_run.len()
6839    }
6840
6841    /// Drain every version from the mutable-run tier (ascending `(RowId,
6842    /// Epoch)` order). Used by compaction to fold the tier into its merge.
6843    pub(crate) fn drain_mutable_run(&mut self) -> Vec<Row> {
6844        self.mutable_run.drain_sorted()
6845    }
6846
6847    /// Snapshot the mutable-run tier without changing live table state.
6848    pub(crate) fn snapshot_mutable_run(&self) -> Vec<Row> {
6849        let mut snapshot = self.mutable_run.clone();
6850        snapshot.drain_sorted()
6851    }
6852
6853    /// Bulk-load: write `batch` directly to a new sorted run, bypassing the WAL
6854    /// and the memtable entirely (no per-row bincode, no skip-list inserts). The
6855    /// run + a rotated WAL + the manifest are fsynced once — the fast ingest
6856    /// path for large analytical loads. Indexes are still maintained.
6857    pub fn bulk_load(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Epoch> {
6858        self.ensure_writable()?;
6859        let n = batch.len();
6860        if n == 0 {
6861            return Ok(self.current_epoch());
6862        }
6863        for row in &batch {
6864            self.schema.validate_values(row)?;
6865        }
6866        let epoch = self.commit_new_epoch()?;
6867        let live_before = self.live_count;
6868        // Spill any pending mutable-run data first: bulk_load writes a Flush
6869        // marker + rotates the WAL below, which is only safe once all in-flight
6870        // data is durably in a run.
6871        self.spill_mutable_run(epoch)?;
6872        let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
6873            && self.indexes_complete
6874            && self.run_refs.is_empty()
6875            && self.memtable.is_empty()
6876            && self.mutable_run.is_empty();
6877        // Phase 14.7: route the legacy Value API through the same parallel
6878        // encode + typed batch-index path as `bulk_load_columns`. Transpose the
6879        // row-major sparse batch → column-major typed columns (in parallel),
6880        // then `write_native` + `index_columns_bulk`, instead of per-row
6881        // `Row { HashMap }` + `index_into` + the sequential `Value` writer.
6882        let mut user_columns: Vec<(u16, columnar::NativeColumn)> = {
6883            use rayon::prelude::*;
6884            self.schema
6885                .columns
6886                .par_iter()
6887                .map(|cdef| {
6888                    (
6889                        cdef.id,
6890                        columnar::rows_to_native(cdef.ty.clone(), &batch, cdef.id),
6891                    )
6892                })
6893                .collect::<Vec<_>>()
6894        };
6895        drop(batch);
6896        // Enforce NOT NULL constraints and primary-key upsert semantics before
6897        // any row id is allocated or bytes hit the run file. Losers of a
6898        // duplicate primary key are dropped from the encoded run entirely so
6899        // the dedup survives reopen (no ephemeral memtable tombstone).
6900        self.fill_auto_inc_native_columns(&mut user_columns, n)?;
6901        self.validate_columns_not_null(&user_columns, n)?;
6902        let winner_idx = self
6903            .bulk_pk_winner_indices(&user_columns, n)
6904            .filter(|idx| idx.len() != n);
6905        let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
6906            match winner_idx.as_deref() {
6907                Some(idx) => {
6908                    let compacted = user_columns
6909                        .iter()
6910                        .map(|(id, c)| (*id, c.gather(idx)))
6911                        .collect();
6912                    (compacted, idx.len())
6913                }
6914                None => (std::mem::take(&mut user_columns), n),
6915            };
6916        self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
6917        let first = self.allocator.alloc_range(write_n as u64)?.0;
6918        for rid in first..first + write_n as u64 {
6919            self.reservoir.offer(rid);
6920        }
6921        let run_id = self.alloc_run_id()?;
6922        let path = self.run_path(run_id);
6923        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0)
6924            .clean(true)
6925            .with_lz4()
6926            .with_native_endian();
6927        if let Some(kek) = &self.kek {
6928            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6929        }
6930        let header = match self.create_run_file(run_id)? {
6931            Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
6932            None => writer.write_native(&path, &write_columns, write_n, first)?,
6933        };
6934        self.run_refs.push(RunRef {
6935            run_id: run_id as u128,
6936            level: 0,
6937            epoch_created: epoch.0,
6938            row_count: header.row_count,
6939        });
6940        self.run_row_id_ranges
6941            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6942        self.live_count = self.live_count.saturating_add(write_n as u64);
6943        if eager_index_build {
6944            let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
6945            self.index_columns_bulk(&write_columns, &row_ids);
6946            self.indexes_complete = true;
6947            self.build_learned_ranges()?;
6948        } else {
6949            self.indexes_complete = false;
6950        }
6951        self.mark_flushed(epoch)?;
6952        self.persist_manifest(epoch)?;
6953        if eager_index_build {
6954            self.checkpoint_indexes(epoch);
6955        }
6956        self.clear_result_cache();
6957        Ok(epoch)
6958    }
6959
6960    /// Rotate the private WAL to a fresh segment. Only valid for a standalone
6961    /// table — a mounted table never rotates the shared WAL per-table.
6962    fn rotate_wal(&mut self, epoch: Epoch) -> Result<()> {
6963        let segment = next_wal_segment(&self.dir.join(WAL_DIR))?;
6964        let cipher = self.wal_dek.as_ref().map(|dk| make_cipher(dk));
6965        // The segment number (from the filename) namespaces nonces under the
6966        // constant WAL DEK — pass it through to the writer.
6967        let segment_no = segment
6968            .file_stem()
6969            .and_then(|s| s.to_str())
6970            .and_then(|s| s.strip_prefix("seg-"))
6971            .and_then(|s| s.parse::<u64>().ok())
6972            .unwrap_or(0);
6973        let mut wal = Wal::create_with_cipher(segment, epoch, cipher, segment_no)?;
6974        wal.set_sync_byte_threshold(self.sync_byte_threshold);
6975        wal.sync()?;
6976        self.wal = WalSink::Private(wal);
6977        Ok(())
6978    }
6979
6980    /// Fine-grained result-cache invalidation (hardening (c)): drop only
6981    /// entries whose footprint intersects a deleted RowId or whose
6982    /// condition-columns intersect a mutated column, then clear the pending
6983    /// sets. Called by `commit` and the cross-table transaction path.
6984    pub(crate) fn invalidate_pending_cache(&mut self) {
6985        self.result_cache
6986            .lock()
6987            .invalidate(&self.pending_delete_rids, &self.pending_put_cols);
6988        self.pending_delete_rids.clear();
6989        self.pending_put_cols.clear();
6990    }
6991
6992    pub(crate) fn persist_manifest(&self, epoch: Epoch) -> Result<()> {
6993        let mut m = Manifest::new(self.table_id, self.schema.schema_id);
6994        m.current_epoch = epoch.0;
6995        m.next_row_id = self.allocator.current().0;
6996        m.runs = self.run_refs.clone();
6997        m.live_count = self.live_count;
6998        m.global_idx_epoch = self.global_idx_epoch;
6999        m.flushed_epoch = self.flushed_epoch;
7000        m.retiring = self.retiring.clone();
7001        // Persist the authoritative counter only when seeded; otherwise write 0
7002        // so the next open still scans `max(PK)` on first use (an unseeded
7003        // lower bound from WAL replay is not safe to trust across a flush).
7004        m.auto_inc_next = match self.auto_inc {
7005            Some(ai) if ai.seeded => ai.next,
7006            _ => 0,
7007        };
7008        m.ttl = self.ttl;
7009        let meta_dek = self.manifest_meta_dek();
7010        match self._root_guard.as_deref() {
7011            Some(root) => manifest::write_durable(root, &mut m, meta_dek.as_ref())?,
7012            None => manifest::write_atomic(&self.dir, &mut m, meta_dek.as_ref())?,
7013        }
7014        Ok(())
7015    }
7016
7017    /// Rebuild the row-to-run lookup directory from the active run set and
7018    /// publish it as a sharded checkpoint in `_runs/`. Failure is non-fatal:
7019    /// the manifest is the authoritative source, the next open falls back to
7020    /// the range-scan path, and a subsequent flush rebuilds + republishes.
7021    /// Returns the resulting directory state so callers can keep the
7022    /// in-memory state in sync.
7023    pub(crate) fn publish_run_lookup_directory(&mut self) -> Result<()> {
7024        // Fire the `manifest.publication` fault hook so tests can simulate a
7025        // crash after the manifest is durable but before the directory
7026        // checkpoint lands.
7027        mongreldb_fault::inject("manifest.publication")
7028            .map_err(|e| MongrelError::Other(format!("manifest.publication fault: {e}")))?;
7029        let active_runs = self.run_refs.clone();
7030        let schema_id = self.schema.schema_id;
7031        let index_generation = self.global_idx_epoch;
7032        let run_generation = active_runs.len() as u64;
7033        let fingerprint = crate::run_lookup::compute_fingerprint(
7034            &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
7035            schema_id,
7036            index_generation,
7037            run_generation,
7038            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7039        );
7040        let dir = match crate::run_lookup::RunLookupDirectory::rebuild_from_runs(&active_runs, self)
7041        {
7042            Ok(d) => d,
7043            Err(error) => {
7044                // Failure to rebuild is non-fatal: the manifest is durable
7045                // and the next open will retry.
7046                self.run_lookup.complete = false;
7047                self.lookup_metrics
7048                    .directory_incomplete
7049                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7050                return Err(error);
7051            }
7052        };
7053        // Stamp the fingerprint on the in-memory directory before publishing
7054        // so the on-disk shards carry the exact value the open path will
7055        // compare against.
7056        let mut dir = dir;
7057        dir.set_fingerprint(fingerprint);
7058        let runs_dir = match self.runs_root.as_deref() {
7059            Some(root) => match root.io_path() {
7060                Ok(p) => p,
7061                Err(_) => self.dir.join(RUNS_DIR),
7062            },
7063            None => self.dir.join(RUNS_DIR),
7064        };
7065        // Best-effort fault hook so tests can intercept the temp-write + rename
7066        // boundary.
7067        mongreldb_fault::inject("directory.temp_write")
7068            .map_err(|e| MongrelError::Other(format!("directory.temp_write fault: {e}")))?;
7069        let publish =
7070            dir.write_checkpoint_sharded(&runs_dir, crate::run_lookup::DEFAULT_SHARD_BYTES);
7071        mongreldb_fault::inject("directory.sync")
7072            .map_err(|e| MongrelError::Other(format!("directory.sync fault: {e}")))?;
7073        mongreldb_fault::inject("directory.rename")
7074            .map_err(|e| MongrelError::Other(format!("directory.rename fault: {e}")))?;
7075        if let Err(error) = publish {
7076            // The manifest is still durable; mark the directory incomplete
7077            // and let the next open rebuild lazily.
7078            self.run_lookup = RunLookupState {
7079                directory: None,
7080                fingerprint,
7081                complete: false,
7082            };
7083            self.lookup_metrics
7084                .directory_incomplete
7085                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7086            self.lookup_metrics
7087                .directory_lookup_fallback
7088                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7089            return Err(error.into());
7090        }
7091        self.run_lookup = RunLookupState {
7092            directory: Some(std::sync::Arc::new(dir)),
7093            fingerprint,
7094            complete: true,
7095        };
7096        Ok(())
7097    }
7098
7099    pub(crate) fn plan_recovered_metadata(&mut self) -> Result<RecoveryMetadataPlan> {
7100        // `live_count` tracks logical tombstones, not wall-clock TTL expiry.
7101        // Use a time before every representable timestamp so TTL cannot hide a
7102        // row while rebuilding authoritative manifest metadata.
7103        let rows = self.visible_rows_at_time(Snapshot::unbounded(), i64::MIN)?;
7104        let live_count = u64::try_from(rows.len())
7105            .map_err(|_| MongrelError::Full("table live-row count exceeds u64".into()))?;
7106        let auto_inc = match self.auto_inc {
7107            Some(mut state) => {
7108                let maximum = self.scan_max_int64(state.column_id)?;
7109                let after_maximum = maximum.checked_add(1).ok_or_else(|| {
7110                    MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
7111                })?;
7112                state.next = state.next.max(after_maximum).max(1);
7113                state.seeded = true;
7114                Some(state)
7115            }
7116            None => None,
7117        };
7118        Ok(RecoveryMetadataPlan {
7119            live_count,
7120            auto_inc,
7121            changed: live_count != self.live_count
7122                || auto_inc.is_some_and(|planned| {
7123                    self.auto_inc.is_none_or(|current| {
7124                        current.next != planned.next || current.seeded != planned.seeded
7125                    })
7126                }),
7127        })
7128    }
7129
7130    pub(crate) fn apply_recovered_metadata(
7131        &mut self,
7132        plan: RecoveryMetadataPlan,
7133        epoch: Epoch,
7134    ) -> Result<()> {
7135        if !plan.changed {
7136            return Ok(());
7137        }
7138        self.live_count = plan.live_count;
7139        self.auto_inc = plan.auto_inc;
7140        self.persist_manifest(epoch)
7141    }
7142
7143    /// Checkpoint the in-memory secondary indexes to `_idx/global.idx` and stamp
7144    /// the manifest's `global_idx_epoch` (Phase 9.1). Call after the runs are
7145    /// stable and the memtable is drained (flush/bulk-load/compact) so the
7146    /// checkpoint exactly matches the run data; subsequent [`Table::open`] loads it
7147    /// directly instead of scanning every run.
7148    pub(crate) fn checkpoint_indexes(&mut self, epoch: Epoch) {
7149        // Never persist an incomplete index set (e.g. after bulk_load_columns,
7150        // which bypasses per-row indexing) — reopen rebuilds from the runs.
7151        if !self.indexes_complete {
7152            return;
7153        }
7154        // The reopen replay gate is the manifest's `flushed_epoch`: every
7155        // commit past it is re-applied (and re-indexed) from the WAL on open.
7156        // The live index maps also cover committed-but-unflushed rows
7157        // (memtable / mutable-run content), so a checkpoint stamped past
7158        // `flushed_epoch` would make replay double-index those rows (Sparse
7159        // dot-product scores double-count; ANN graphs gain duplicate nodes).
7160        // Only persist an image whose content is fully behind the gate.
7161        if epoch.0 > self.flushed_epoch {
7162            return;
7163        }
7164        // FND-006: a fired fault behaves like a failed checkpoint — the write
7165        // is best-effort and the next open simply rebuilds from the runs.
7166        if crate::catalog::inject_hook("index.publish.before").is_err() {
7167            return;
7168        }
7169        if self.idx_root.is_none() {
7170            if let Some(root) = self._root_guard.as_ref() {
7171                let Ok(idx_root) = root.create_directory_all_pinned(global_idx::IDX_DIR) else {
7172                    return;
7173                };
7174                self.idx_root = Some(Arc::new(idx_root));
7175            }
7176        }
7177        let snap = global_idx::IndexSnapshot {
7178            hot: &self.hot,
7179            bitmap: &self.bitmap,
7180            ann: &self.ann,
7181            fm: &self.fm,
7182            sparse: &self.sparse,
7183            minhash: &self.minhash,
7184            learned_range: &self.learned_range,
7185        };
7186        // Best-effort: a failed checkpoint just means the next open rebuilds.
7187        let idx_dek = self.idx_dek();
7188        let written = match self.idx_root.as_deref() {
7189            Some(root) => global_idx::write_atomic_root(
7190                root,
7191                self.table_id,
7192                epoch.0,
7193                snap,
7194                idx_dek.as_deref(),
7195            ),
7196            None => global_idx::write_atomic(
7197                &self.dir,
7198                self.table_id,
7199                epoch.0,
7200                snap,
7201                idx_dek.as_deref(),
7202            ),
7203        };
7204        if written.is_ok() {
7205            self.global_idx_epoch = epoch.0;
7206            let _ = self.persist_manifest(epoch);
7207            // FND-006: the index generation is published.
7208            let _ = crate::catalog::inject_hook("index.publish.after");
7209        }
7210    }
7211
7212    /// Drop any on-disk index checkpoint so the next open rebuilds from runs
7213    /// (used when the live indexes are known stale, e.g. compaction to empty).
7214    pub(crate) fn invalidate_index_checkpoint(&mut self) {
7215        self.global_idx_epoch = 0;
7216        if let Some(root) = self.idx_root.as_deref() {
7217            let _ = root.remove_file(global_idx::IDX_FILENAME);
7218        } else {
7219            global_idx::remove(&self.dir);
7220        }
7221        let _ = self.persist_manifest(self.epoch.visible());
7222    }
7223
7224    /// Prepare for replacing every run without publishing a second manifest.
7225    /// The caller persists the replacement topology after this returns.  An
7226    /// older checkpoint may remain on disk if deletion fails, but a manifest
7227    /// with `global_idx_epoch = 0` will never endorse it on reopen.
7228    pub(crate) fn prepare_indexes_for_run_replacement(&mut self) {
7229        self.indexes_complete = false;
7230        self.global_idx_epoch = 0;
7231        if let Some(root) = self.idx_root.as_deref() {
7232            let _ = root.remove_file(global_idx::IDX_FILENAME);
7233        } else {
7234            global_idx::remove(&self.dir);
7235        }
7236    }
7237
7238    pub(crate) fn finish_indexes_for_run_replacement(&mut self) {
7239        self.indexes_complete = true;
7240    }
7241
7242    /// A maintenance operation changed live run topology and could not prove
7243    /// the matching manifest publication.  Fail closed until recovery rebuilds
7244    /// one coherent view from durable state.  Mounted tables also poison their
7245    /// owning database so GC, DDL, and transactions cannot continue around the
7246    /// uncertain topology.
7247    pub(crate) fn poison_after_maintenance_publish_failure(&mut self) {
7248        self.durable_commit_failed = true;
7249        if let WalSink::Shared(shared) = &self.wal {
7250            shared
7251                .poisoned
7252                .store(true, std::sync::atomic::Ordering::Relaxed);
7253        }
7254    }
7255
7256    /// Invalidate a stale handle after DOCTOR has durably dropped its catalog
7257    /// entry. Other tables remain usable, but this handle must never append new
7258    /// writes for the quarantined table id.
7259    pub(crate) fn mark_unavailable_after_quarantine(&mut self) {
7260        self.durable_commit_failed = true;
7261    }
7262
7263    /// Read the row at `row_id` visible to `snapshot`, merging the newest
7264    /// version across the memtable, mutable-run tier, and all sorted runs.
7265    ///
7266    /// In-memory tiers use full-[`Snapshot`] HLC visibility (P0.5-T3). Sorted
7267    /// runs restore optional [`crate::sorted_run::SYS_COMMIT_TS`] when present
7268    /// and fall back to epoch-only for legacy runs; candidates are filtered
7269    /// with [`Snapshot::observes_row`] so HLC-stamped versions never win under
7270    /// an epoch-only pin.
7271    ///
7272    /// When the run-lookup directory is complete, the read path consults it
7273    /// to open only the runs whose locators may contain a visible version for
7274    /// this `row_id`. The existing range-scan path stays the safety net when
7275    /// the directory is missing or stale.
7276    ///
7277    /// REM-004: the directory consultation returns one of three explicit
7278    /// decisions ([`crate::run_lookup::DirectoryLookupDecision`]):
7279    ///
7280    /// - [`CompleteMiss`](crate::run_lookup::DirectoryLookupDecision::CompleteMiss) —
7281    ///   authoritative "no immutable run hosts this row"; open zero readers.
7282    /// - [`Candidates`](crate::run_lookup::DirectoryLookupDecision::Candidates) —
7283    ///   walk locators with the conservative filter plus a safe early-stop
7284    ///   proof ([`crate::run_lookup::RunLocator::can_contain_version_newer_than`]).
7285    /// - [`UnavailableOrStale`](crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale) —
7286    ///   fall back to the existing per-run range filter.
7287    pub fn get(&self, row_id: RowId, snapshot: Snapshot) -> Option<Row> {
7288        let mut best: Option<Row> = None;
7289        // `consider` is a free function (not a closure) so the caller can
7290        // also inspect `best` between iterations without colliding borrows.
7291        fn consider(best: &mut Option<Row>, row: Row, snapshot: Snapshot) {
7292            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7293                return;
7294            }
7295            if best.as_ref().is_none_or(|current| {
7296                Snapshot::version_is_newer(
7297                    row.committed_epoch,
7298                    row.commit_ts,
7299                    current.committed_epoch,
7300                    current.commit_ts,
7301                )
7302            }) {
7303                *best = Some(row);
7304            }
7305        }
7306        if let Some((_, row)) = self.memtable.get_version_at(row_id, snapshot) {
7307            consider(&mut best, row, snapshot);
7308        }
7309        if let Some((_, row)) = self.mutable_run.get_version_at(row_id, snapshot) {
7310            consider(&mut best, row, snapshot);
7311        }
7312        // Decide which runs to open. The directory is consulted only when it
7313        // is marked complete AND the active run set is non-empty; otherwise
7314        // we fall back to the per-run range filter below.
7315        let decision = if self.run_lookup.complete {
7316            // Defensive: verify the in-memory directory's fingerprint is
7317            // still consistent with the active run set. A divergence means
7318            // the directory is stale and we should fall back rather than
7319            // miss versions.
7320            let active_ids: Vec<u128> = self.run_refs.iter().map(|r| r.run_id).collect();
7321            let expected_fp = crate::run_lookup::compute_fingerprint(
7322                &active_ids,
7323                self.schema.schema_id,
7324                self.global_idx_epoch,
7325                active_ids.len() as u64,
7326                crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7327            );
7328            if self.run_lookup.fingerprint == expected_fp {
7329                match self.run_lookup.directory.as_ref() {
7330                    Some(dir) => dir.decide(row_id),
7331                    None => crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale,
7332                }
7333            } else {
7334                self.lookup_metrics
7335                    .directory_lookup_fallback
7336                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7337                crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7338            }
7339        } else {
7340            self.lookup_metrics
7341                .directory_lookup_fallback
7342                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7343            crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7344        };
7345        match decision {
7346            crate::run_lookup::DirectoryLookupDecision::CompleteMiss => {
7347                // REM-004: a complete directory miss is authoritative — the
7348                // memtable + mutable-run tiers have already been searched,
7349                // so no immutable run can host a visible version. Skip the
7350                // range scan and return whatever the in-memory tiers said.
7351                self.lookup_metrics
7352                    .directory_lookup_hit
7353                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7354                self.lookup_metrics
7355                    .directory_complete_miss_total
7356                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7357            }
7358            crate::run_lookup::DirectoryLookupDecision::Candidates(mut locators) => {
7359                // Snapshot-aware candidate ordering (REM-B §6.13): an
7360                // HLC-authoritative snapshot considers fully stamped
7361                // locators by newest possible visible HLC first; an
7362                // epoch-only snapshot stays epoch-first. Ordering is a
7363                // performance hint only — early-stop correctness never
7364                // depends on it.
7365                locators.sort_by(|a, b| {
7366                    if snapshot.uses_hlc_authority() {
7367                        b.max_hlc
7368                            .cmp(&a.max_hlc)
7369                            .then_with(|| b.max_epoch.cmp(&a.max_epoch))
7370                    } else {
7371                        b.max_epoch
7372                            .cmp(&a.max_epoch)
7373                            .then_with(|| b.max_hlc.cmp(&a.max_hlc))
7374                    }
7375                });
7376                // Apply the conservative snapshot filter and the safe
7377                // early-stop proof — locators that provably cannot contain a
7378                // visible version, or whose maximum visible version is
7379                // provably ≤ the current winner, are skipped. The remainder
7380                // is opened in newest-first order.
7381                let mut opened: std::collections::HashSet<u128> = std::collections::HashSet::new();
7382                let mut early_stopped: u64 = 0;
7383                for locator in &locators {
7384                    // REM-004 early-stop: once we have a winner, skip
7385                    // locators that provably cannot beat it.
7386                    let stamp = best
7387                        .as_ref()
7388                        .map(|current| crate::run_lookup::VersionStamp {
7389                            epoch: current.committed_epoch,
7390                            hlc: current.commit_ts,
7391                        });
7392                    if let Some(s) = stamp {
7393                        if !locator.can_contain_version_newer_than(s, snapshot) {
7394                            early_stopped += 1;
7395                            continue;
7396                        }
7397                    }
7398                    if locator.is_impossible_for(snapshot) {
7399                        continue;
7400                    }
7401                    if !opened.insert(locator.run_id) {
7402                        continue;
7403                    }
7404                    self.lookup_metrics
7405                        .directory_run_readers_opened
7406                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7407                    self.lookup_metrics
7408                        .get_run_opened
7409                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7410                    let Ok(mut reader) = self.open_reader(locator.run_id) else {
7411                        continue;
7412                    };
7413                    // P0.5-T3: run materialisation restores SYS_COMMIT_TS when present;
7414                    // legacy runs without the column fall back to epoch visibility.
7415                    let Ok(Some((_, row))) = reader.get_version_at(row_id, snapshot) else {
7416                        continue;
7417                    };
7418                    consider(&mut best, row, snapshot);
7419                }
7420                if early_stopped > 0 {
7421                    self.lookup_metrics
7422                        .directory_early_stop_total
7423                        .fetch_add(early_stopped, std::sync::atomic::Ordering::Relaxed);
7424                }
7425                self.lookup_metrics
7426                    .directory_lookup_hit
7427                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7428            }
7429            crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale => {
7430                // Exact directory miss OR no directory: range-scan fallback.
7431                for rr in &self.run_refs {
7432                    // Skip runs whose RowId range cannot contain this key
7433                    // (populated from run headers on open/spill). Missing
7434                    // range falls through.
7435                    if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
7436                        if row_id.0 < min_rid || row_id.0 > max_rid {
7437                            self.lookup_metrics
7438                                .get_run_skipped
7439                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7440                            continue;
7441                        }
7442                    }
7443                    self.lookup_metrics
7444                        .get_run_opened
7445                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7446                    let Ok(mut reader) = self.open_reader(rr.run_id) else {
7447                        continue;
7448                    };
7449                    // P0.5-T3: run materialisation restores SYS_COMMIT_TS when present;
7450                    // legacy runs without the column fall back to epoch visibility.
7451                    let Ok(Some((_, row))) = reader.get_version_at(row_id, snapshot) else {
7452                        continue;
7453                    };
7454                    consider(&mut best, row, snapshot);
7455                }
7456            }
7457        }
7458        let now_nanos = unix_nanos_now();
7459        match best {
7460            Some(r) if r.deleted || self.row_expired_at(&r, now_nanos) => None,
7461            Some(r) => Some(r),
7462            None => None,
7463        }
7464    }
7465
7466    /// All rows visible at `snapshot` (newest version per `RowId`, tombstones
7467    /// dropped), merged across the memtable, the mutable-run tier, and all
7468    /// runs. Ascending `RowId`.
7469    pub fn visible_rows(&self, snapshot: Snapshot) -> Result<Vec<Row>> {
7470        self.visible_rows_at_time(snapshot, unix_nanos_now())
7471    }
7472
7473    /// Materialize visible rows with cooperative checkpoints while merging
7474    /// page-bounded, already ordered tier cursors.
7475    #[doc(hidden)]
7476    pub fn visible_rows_controlled(
7477        &self,
7478        snapshot: Snapshot,
7479        control: &crate::ExecutionControl,
7480    ) -> Result<Vec<Row>> {
7481        let mut out = Vec::new();
7482        self.for_each_visible_row_controlled(snapshot, control, |row| {
7483            out.push(row);
7484            Ok(())
7485        })?;
7486        Ok(out)
7487    }
7488
7489    /// Visit visible rows in row-id order with a k-way merge over ordered tier
7490    /// cursors. No full-table merge map or row-id sort is constructed.
7491    #[doc(hidden)]
7492    pub fn for_each_visible_row_controlled<F>(
7493        &self,
7494        snapshot: Snapshot,
7495        control: &crate::ExecutionControl,
7496        mut visit: F,
7497    ) -> Result<()>
7498    where
7499        F: FnMut(Row) -> Result<()>,
7500    {
7501        // TODO §3: trace metrics for the controlled-scan path. The fields are
7502        // populated on the streaming path; today (memory_from_map +
7503        // into_visible_version_cursor) the buffer is still bounded, so the
7504        // counts are the right shape even if some are zero on this impl.
7505        // `versions_examined` is incremented inside the visitor closure so
7506        // cancellation is observed within the bounded buffer.
7507        let setup_start = std::time::Instant::now();
7508        let mut versions_examined: u64 = 0;
7509        let mut rows_emitted: u64 = 0;
7510        let mut checkpoints: u64 = 0;
7511        let mut first_row_recorded = false;
7512        let mut sources: Vec<ControlledVisibleSource<'_>> =
7513            Vec::with_capacity(self.run_refs.len() + 2);
7514        control.checkpoint()?;
7515        checkpoints += 1;
7516        // Hot-tier sources use borrowing cursors: only the current version
7517        // group is retained, so setup does not scale with the live row count.
7518        if !self.memtable.is_empty() {
7519            sources.push(ControlledVisibleSource::memtable_cursor(
7520                self.memtable.newest_visible_iter(&snapshot),
7521            ));
7522        }
7523        control.checkpoint()?;
7524        checkpoints += 1;
7525        if !self.mutable_run.is_empty() {
7526            sources.push(ControlledVisibleSource::mutable_run_cursor(
7527                self.mutable_run.newest_visible_iter(&snapshot),
7528            ));
7529        }
7530        for run in &self.run_refs {
7531            control.checkpoint()?;
7532            checkpoints += 1;
7533            let reader = self.open_reader(run.run_id)?;
7534            sources.push(ControlledVisibleSource::run(
7535                reader.into_visible_version_cursor_at(snapshot)?,
7536            ));
7537        }
7538        // Time-to-first-row includes source construction; setup_us captures
7539        // the construction cost separately.
7540        let first_row_start = setup_start;
7541        let _setup_us = setup_start.elapsed().as_micros() as u64;
7542        let now_nanos = unix_nanos_now();
7543        let mut first_row_us: u64 = 0;
7544        let result = merge_controlled_visible_sources(
7545            &mut sources,
7546            control,
7547            |row| self.row_expired_at(row, now_nanos),
7548            |row| {
7549                if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7550                    return Ok(());
7551                }
7552                versions_examined += 1;
7553                if !first_row_recorded {
7554                    first_row_us = first_row_start.elapsed().as_micros() as u64;
7555                    first_row_recorded = true;
7556                }
7557                rows_emitted += 1;
7558                visit(row)
7559            },
7560        );
7561        let time_to_first_row_us = if first_row_recorded { first_row_us } else { 0 };
7562        crate::trace::QueryTrace::record(|t| {
7563            t.controlled_scan_versions_examined = t
7564                .controlled_scan_versions_examined
7565                .saturating_add(versions_examined as usize);
7566            t.controlled_scan_rows_emitted = t
7567                .controlled_scan_rows_emitted
7568                .saturating_add(rows_emitted as usize);
7569            t.controlled_scan_checkpoints = t
7570                .controlled_scan_checkpoints
7571                .saturating_add(checkpoints as usize);
7572            t.controlled_scan_time_to_first_row_us = t
7573                .controlled_scan_time_to_first_row_us
7574                .saturating_add(time_to_first_row_us);
7575            t.controlled_scan_setup_time_us =
7576                t.controlled_scan_setup_time_us.saturating_add(_setup_us);
7577        });
7578        result
7579    }
7580
7581    #[doc(hidden)]
7582    pub fn visible_rows_at_time(&self, snapshot: Snapshot, now_nanos: i64) -> Result<Vec<Row>> {
7583        let mut best: HashMap<u64, Row> = HashMap::new();
7584        let mut fold = |row: Row| {
7585            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7586                return;
7587            }
7588            best.entry(row.row_id.0)
7589                .and_modify(|existing| {
7590                    if Snapshot::version_is_newer(
7591                        row.committed_epoch,
7592                        row.commit_ts,
7593                        existing.committed_epoch,
7594                        existing.commit_ts,
7595                    ) {
7596                        *existing = row.clone();
7597                    }
7598                })
7599                .or_insert(row);
7600        };
7601        for row in self.memtable.visible_versions_at(snapshot) {
7602            fold(row);
7603        }
7604        for row in self.mutable_run.visible_versions_at(snapshot) {
7605            fold(row);
7606        }
7607        for rr in &self.run_refs {
7608            let mut reader = self.open_reader(rr.run_id)?;
7609            // P0.5-T3: optional SYS_COMMIT_TS restored when present on the run.
7610            for row in reader.visible_versions_at(snapshot)? {
7611                fold(row);
7612            }
7613        }
7614        let mut out: Vec<Row> = best
7615            .into_values()
7616            .filter_map(|r| {
7617                if r.deleted || self.row_expired_at(&r, now_nanos) {
7618                    None
7619                } else {
7620                    Some(r)
7621                }
7622            })
7623            .collect();
7624        out.sort_by_key(|r| r.row_id);
7625        Ok(out)
7626    }
7627
7628    /// Visible data as columns (column_id → values) rather than rows — the
7629    /// vectorized scan path. Fast path: when the memtable is empty and there is
7630    /// exactly one run (the common post-flush analytical case), it computes the
7631    /// visible index set once and gathers each column, with **no per-row
7632    /// `HashMap`/`Row` materialization**. Falls back to [`Self::visible_rows`]
7633    /// pivoted to columns when the memtable is live or runs overlap.
7634    pub fn visible_columns(&self, snapshot: Snapshot) -> Result<Vec<(u16, Vec<Value>)>> {
7635        if self.ttl.is_none()
7636            && self.memtable.is_empty()
7637            && self.mutable_run.is_empty()
7638            && self.run_refs.len() == 1
7639        {
7640            let rr = self.run_refs[0].clone();
7641            let mut reader = self.open_reader(rr.run_id)?;
7642            let idxs = reader.visible_indices_at(snapshot)?;
7643            let mut cols = Vec::with_capacity(self.schema.columns.len());
7644            for cdef in &self.schema.columns {
7645                cols.push((cdef.id, reader.gather_column(cdef.id, &idxs)?));
7646            }
7647            return Ok(cols);
7648        }
7649        // Fallback: row merge, then pivot to columns.
7650        let rows = self.visible_rows(snapshot)?;
7651        let mut cols: Vec<(u16, Vec<Value>)> = self
7652            .schema
7653            .columns
7654            .iter()
7655            .map(|c| (c.id, Vec::with_capacity(rows.len())))
7656            .collect();
7657        for r in &rows {
7658            for (cid, vec) in cols.iter_mut() {
7659                vec.push(r.columns.get(cid).cloned().unwrap_or(Value::Null));
7660            }
7661        }
7662        Ok(cols)
7663    }
7664
7665    /// Resolve a primary-key value to a row id (latest version).
7666    pub fn lookup_pk(&self, key: &[u8]) -> Option<RowId> {
7667        let row_id = self.hot.get(key)?;
7668        if self.ttl.is_none() || self.get(row_id, Snapshot::unbounded()).is_some() {
7669            Some(row_id)
7670        } else {
7671            None
7672        }
7673    }
7674
7675    /// Snapshot of lookup + result-cache counters. Point-in-time copy suitable
7676    /// for `/metrics` exposition or test assertions. Cache counts come from the
7677    /// [`ResultCache`] mutex; HOT counts come from the in-table atomics.
7678    pub fn lookup_metrics_snapshot(&self) -> LookupMetricsSnapshot {
7679        let mut snap = self.lookup_metrics.snapshot();
7680        let cache = self.result_cache.lock();
7681        let (mem, disk, miss, write_us) = cache.cache_counters();
7682        snap.result_cache_memory_hit = mem;
7683        snap.result_cache_disk_hit = disk;
7684        snap.result_cache_miss = miss;
7685        snap.result_cache_persistent_write_us = write_us;
7686        // REM-D §8.7: publication-availability counters live on the cache.
7687        let (unavailable, skipped, spawn_failures, worker_shutdowns) = cache.publication_counters();
7688        snap.result_cache_persist_unavailable_total = unavailable;
7689        snap.result_cache_persist_skipped_total = skipped;
7690        snap.result_cache_worker_spawn_failures_total = spawn_failures;
7691        snap.result_cache_worker_shutdown_total = worker_shutdowns;
7692        // Merge the writer's persist counters so tests and observability
7693        // surfaces see the full picture.
7694        if let Some(writer_snap) = cache.persist_snapshot() {
7695            snap.result_cache_persist_enqueued_total =
7696                writer_snap.result_cache_persist_enqueued_total;
7697            snap.result_cache_persist_coalesced_total =
7698                writer_snap.result_cache_persist_coalesced_total;
7699            snap.result_cache_persist_dropped_store_total =
7700                writer_snap.result_cache_persist_dropped_store_total;
7701            snap.result_cache_persist_remove_total = writer_snap.result_cache_persist_remove_total;
7702            snap.result_cache_persist_stale_store_skipped_total =
7703                writer_snap.result_cache_persist_stale_store_skipped_total;
7704            snap.result_cache_persist_errors_total = writer_snap.result_cache_persist_errors_total;
7705            snap.result_cache_persist_shutdown_abandoned_total =
7706                writer_snap.result_cache_persist_shutdown_abandoned_total;
7707            snap.result_cache_persist_queue_depth = writer_snap.result_cache_persist_queue_depth;
7708        }
7709        snap
7710    }
7711
7712    /// Run a conjunctive query over the shared row-id space: each condition
7713    /// yields a candidate row-id set, the sets are intersected, and the
7714    /// survivors are materialized at the current snapshot. This is the AI-native
7715    /// "compose primitives" surface (`semsearch ∩ fm_contains ∩ cat_in`).
7716    pub fn query(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
7717        self.query_at_with_allowed(q, self.snapshot(), None)
7718    }
7719
7720    /// Run a native conjunctive query with cooperative cancellation through
7721    /// index resolution, scans, filtering, and row materialization.
7722    pub fn query_controlled(
7723        &mut self,
7724        q: &crate::query::Query,
7725        control: &crate::ExecutionControl,
7726    ) -> Result<Vec<Row>> {
7727        self.query_at_with_allowed_controlled(q, self.snapshot(), None, control)
7728    }
7729
7730    /// Execute a conjunctive query at one snapshot, applying authorization
7731    /// before ranked ANN, Sparse, and MinHash top-k selection.
7732    pub fn query_at_with_allowed(
7733        &mut self,
7734        q: &crate::query::Query,
7735        snapshot: Snapshot,
7736        allowed: Option<&std::collections::HashSet<RowId>>,
7737    ) -> Result<Vec<Row>> {
7738        self.query_at_with_allowed_after(q, snapshot, allowed, None)
7739    }
7740
7741    #[doc(hidden)]
7742    pub fn query_at_with_allowed_controlled(
7743        &mut self,
7744        q: &crate::query::Query,
7745        snapshot: Snapshot,
7746        allowed: Option<&std::collections::HashSet<RowId>>,
7747        control: &crate::ExecutionControl,
7748    ) -> Result<Vec<Row>> {
7749        self.require_select()?;
7750        self.ensure_indexes_complete_controlled(control, || true)?;
7751        self.validate_native_query(q)?;
7752        self.query_conditions_at(
7753            &q.conditions,
7754            snapshot,
7755            allowed,
7756            q.limit,
7757            q.offset,
7758            None,
7759            unix_nanos_now(),
7760            Some(control),
7761        )
7762    }
7763
7764    #[doc(hidden)]
7765    pub fn query_at_with_allowed_after(
7766        &mut self,
7767        q: &crate::query::Query,
7768        snapshot: Snapshot,
7769        allowed: Option<&std::collections::HashSet<RowId>>,
7770        after_row_id: Option<RowId>,
7771    ) -> Result<Vec<Row>> {
7772        self.query_at_with_allowed_after_at_time(
7773            q,
7774            snapshot,
7775            allowed,
7776            after_row_id,
7777            unix_nanos_now(),
7778        )
7779    }
7780
7781    #[doc(hidden)]
7782    pub fn query_at_with_allowed_after_at_time(
7783        &mut self,
7784        q: &crate::query::Query,
7785        snapshot: Snapshot,
7786        allowed: Option<&std::collections::HashSet<RowId>>,
7787        after_row_id: Option<RowId>,
7788        query_time_nanos: i64,
7789    ) -> Result<Vec<Row>> {
7790        self.require_select()?;
7791        self.ensure_indexes_complete()?;
7792        self.validate_native_query(q)?;
7793        self.query_conditions_at(
7794            &q.conditions,
7795            snapshot,
7796            allowed,
7797            q.limit,
7798            q.offset,
7799            after_row_id,
7800            query_time_nanos,
7801            None,
7802        )
7803    }
7804
7805    fn validate_native_query(&self, q: &crate::query::Query) -> Result<()> {
7806        if q.conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7807            return Err(MongrelError::InvalidArgument(format!(
7808                "query exceeds {} conditions",
7809                crate::query::MAX_HARD_CONDITIONS
7810            )));
7811        }
7812        if let Some(limit) = q.limit {
7813            if limit == 0 || limit > crate::query::MAX_FINAL_LIMIT {
7814                return Err(MongrelError::InvalidArgument(format!(
7815                    "query limit must be between 1 and {}",
7816                    crate::query::MAX_FINAL_LIMIT
7817                )));
7818            }
7819        }
7820        if q.offset > crate::query::MAX_QUERY_OFFSET {
7821            return Err(MongrelError::InvalidArgument(format!(
7822                "query offset exceeds {}",
7823                crate::query::MAX_QUERY_OFFSET
7824            )));
7825        }
7826        Ok(())
7827    }
7828
7829    /// Unbounded internal SQL join helper. Public request surfaces must use
7830    /// [`Self::query_at_with_allowed`] and its result ceiling.
7831    #[doc(hidden)]
7832    pub fn query_all_at(
7833        &mut self,
7834        conditions: &[crate::query::Condition],
7835        snapshot: Snapshot,
7836    ) -> Result<Vec<Row>> {
7837        self.require_select()?;
7838        self.ensure_indexes_complete()?;
7839        if conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7840            return Err(MongrelError::InvalidArgument(format!(
7841                "query exceeds {} conditions",
7842                crate::query::MAX_HARD_CONDITIONS
7843            )));
7844        }
7845        self.query_conditions_at(
7846            conditions,
7847            snapshot,
7848            None,
7849            None,
7850            0,
7851            None,
7852            unix_nanos_now(),
7853            None,
7854        )
7855    }
7856
7857    #[allow(clippy::too_many_arguments)]
7858    fn query_conditions_at(
7859        &self,
7860        conditions: &[crate::query::Condition],
7861        snapshot: Snapshot,
7862        allowed: Option<&std::collections::HashSet<RowId>>,
7863        limit: Option<usize>,
7864        offset: usize,
7865        after_row_id: Option<RowId>,
7866        query_time_nanos: i64,
7867        control: Option<&crate::ExecutionControl>,
7868    ) -> Result<Vec<Row>> {
7869        control
7870            .map(crate::ExecutionControl::checkpoint)
7871            .transpose()?;
7872        crate::trace::QueryTrace::record(|t| {
7873            t.run_count = self.run_refs.len();
7874            t.memtable_rows = self.memtable.len();
7875            t.mutable_run_rows = self.mutable_run.len();
7876        });
7877        // A conjunction with no predicates matches every visible row (the
7878        // documented "Empty ⇒ all rows" contract); `intersect_sets` of zero
7879        // sets would otherwise wrongly yield the empty set.
7880        if conditions.is_empty() {
7881            crate::trace::QueryTrace::record(|t| {
7882                t.scan_mode = crate::trace::ScanMode::Materialized;
7883                t.row_materialized = true;
7884            });
7885            let mut rows = match control {
7886                Some(control) => self.visible_rows_controlled(snapshot, control)?,
7887                None => self.visible_rows_at_time(snapshot, query_time_nanos)?,
7888            };
7889            if let Some(allowed) = allowed {
7890                let mut filtered = Vec::with_capacity(rows.len());
7891                for (index, row) in rows.into_iter().enumerate() {
7892                    if index & 255 == 0 {
7893                        control
7894                            .map(crate::ExecutionControl::checkpoint)
7895                            .transpose()?;
7896                    }
7897                    if allowed.contains(&row.row_id) {
7898                        filtered.push(row);
7899                    }
7900                }
7901                rows = filtered;
7902            }
7903            if let Some(after_row_id) = after_row_id {
7904                rows.retain(|row| row.row_id > after_row_id);
7905            }
7906            rows.drain(..offset.min(rows.len()));
7907            if let Some(limit) = limit {
7908                rows.truncate(limit);
7909            }
7910            return Ok(rows);
7911        }
7912        crate::trace::QueryTrace::record(|t| {
7913            t.conditions_pushed = conditions.len();
7914            t.scan_mode = crate::trace::ScanMode::Materialized;
7915            t.row_materialized = true;
7916        });
7917        // §5.5: resolve conditions CHEAP-FIRST and early-exit the moment a
7918        // condition yields an empty survivor set. Previously every condition
7919        // (including an expensive range/FM page scan) was resolved before
7920        // `intersect_many` noticed an empty set; now a selective bitmap/PK that
7921        // eliminates all rows short-circuits the rest. Correctness is unchanged
7922        // (intersection with an empty set is empty either way).
7923        let mut ordered: Vec<&crate::query::Condition> = conditions.iter().collect();
7924        ordered.sort_by_key(|c| condition_cost_rank(c));
7925        let mut sets: Vec<RowIdSet> = Vec::with_capacity(ordered.len());
7926        for c in &ordered {
7927            control
7928                .map(crate::ExecutionControl::checkpoint)
7929                .transpose()?;
7930            let s = self.resolve_condition_with_allowed(c, snapshot, allowed)?;
7931            let empty = s.is_empty();
7932            sets.push(s);
7933            if empty {
7934                break;
7935            }
7936        }
7937        let mut rids = RowIdSet::intersect_many(sets).into_sorted_vec();
7938        if let Some(allowed) = allowed {
7939            rids.retain(|row_id| allowed.contains(&RowId(*row_id)));
7940        }
7941        if let Some(after_row_id) = after_row_id {
7942            let first = rids.partition_point(|row_id| *row_id <= after_row_id.0);
7943            rids.drain(..first);
7944        }
7945        rids.drain(..offset.min(rids.len()));
7946        if let Some(limit) = limit {
7947            rids.truncate(limit);
7948        }
7949        control
7950            .map(crate::ExecutionControl::checkpoint)
7951            .transpose()?;
7952        self.rows_for_rids_at_time(&rids, snapshot, query_time_nanos, control)
7953    }
7954
7955    /// Return an index's ordered candidates without discarding scores.
7956    pub fn retrieve(
7957        &mut self,
7958        retriever: &crate::query::Retriever,
7959    ) -> Result<Vec<crate::query::RetrieverHit>> {
7960        self.retrieve_with_allowed(retriever, None)
7961    }
7962
7963    pub fn retrieve_at(
7964        &mut self,
7965        retriever: &crate::query::Retriever,
7966        snapshot: Snapshot,
7967        allowed: Option<&std::collections::HashSet<RowId>>,
7968    ) -> Result<Vec<crate::query::RetrieverHit>> {
7969        self.retrieve_at_with_allowed(retriever, snapshot, allowed)
7970    }
7971
7972    /// Scored retrieval restricted to caller-authorized row IDs. Core MVCC,
7973    /// tombstone, and TTL eligibility is always applied before ranking.
7974    pub fn retrieve_with_allowed(
7975        &mut self,
7976        retriever: &crate::query::Retriever,
7977        allowed: Option<&std::collections::HashSet<RowId>>,
7978    ) -> Result<Vec<crate::query::RetrieverHit>> {
7979        self.retrieve_at_with_allowed(retriever, self.snapshot(), allowed)
7980    }
7981
7982    pub fn retrieve_at_with_allowed(
7983        &mut self,
7984        retriever: &crate::query::Retriever,
7985        snapshot: Snapshot,
7986        allowed: Option<&std::collections::HashSet<RowId>>,
7987    ) -> Result<Vec<crate::query::RetrieverHit>> {
7988        self.retrieve_at_with_allowed_and_context(retriever, snapshot, allowed, None)
7989    }
7990
7991    pub fn retrieve_at_with_allowed_and_context(
7992        &mut self,
7993        retriever: &crate::query::Retriever,
7994        snapshot: Snapshot,
7995        allowed: Option<&std::collections::HashSet<RowId>>,
7996        context: Option<&crate::query::AiExecutionContext>,
7997    ) -> Result<Vec<crate::query::RetrieverHit>> {
7998        self.require_select()?;
7999        self.ensure_indexes_complete()?;
8000        self.validate_retriever(retriever)?;
8001        self.retrieve_filtered(retriever, snapshot, None, allowed, None, context)
8002    }
8003
8004    pub fn retrieve_at_with_candidate_authorization_and_context(
8005        &mut self,
8006        retriever: &crate::query::Retriever,
8007        snapshot: Snapshot,
8008        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8009        context: Option<&crate::query::AiExecutionContext>,
8010    ) -> Result<Vec<crate::query::RetrieverHit>> {
8011        self.require_select()?;
8012        self.ensure_indexes_complete()?;
8013        self.retrieve_at_with_candidate_authorization_on_generation(
8014            retriever,
8015            snapshot,
8016            authorization,
8017            context,
8018        )
8019    }
8020
8021    #[doc(hidden)]
8022    pub fn retrieve_at_with_candidate_authorization_on_generation(
8023        &self,
8024        retriever: &crate::query::Retriever,
8025        snapshot: Snapshot,
8026        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8027        context: Option<&crate::query::AiExecutionContext>,
8028    ) -> Result<Vec<crate::query::RetrieverHit>> {
8029        self.require_select()?;
8030        self.validate_retriever(retriever)?;
8031        self.retrieve_filtered(retriever, snapshot, None, None, authorization, context)
8032    }
8033
8034    fn validate_retriever(&self, retriever: &crate::query::Retriever) -> Result<()> {
8035        use crate::query::{Retriever, MAX_RETRIEVER_K, MAX_SET_MEMBERS, MAX_SPARSE_TERMS};
8036        let (column_id, k) = match retriever {
8037            Retriever::Ann {
8038                column_id,
8039                query,
8040                k,
8041            } => {
8042                let index = self.ann.get(column_id).ok_or_else(|| {
8043                    MongrelError::InvalidArgument(format!("column {column_id} has no ANN index"))
8044                })?;
8045                if query.len() != index.dim() {
8046                    return Err(MongrelError::InvalidArgument(format!(
8047                        "ANN query dimension must be {}, got {}",
8048                        index.dim(),
8049                        query.len()
8050                    )));
8051                }
8052                if query.iter().any(|value| !value.is_finite()) {
8053                    return Err(MongrelError::InvalidArgument(
8054                        "ANN query values must be finite".into(),
8055                    ));
8056                }
8057                (*column_id, *k)
8058            }
8059            Retriever::Sparse {
8060                column_id,
8061                query,
8062                k,
8063            } => {
8064                if !self.sparse.contains_key(column_id) {
8065                    return Err(MongrelError::InvalidArgument(format!(
8066                        "column {column_id} has no Sparse index"
8067                    )));
8068                }
8069                if query.is_empty() || query.iter().any(|(_, weight)| !weight.is_finite()) {
8070                    return Err(MongrelError::InvalidArgument(
8071                        "Sparse query must be non-empty with finite weights".into(),
8072                    ));
8073                }
8074                if query.len() > MAX_SPARSE_TERMS {
8075                    return Err(MongrelError::InvalidArgument(format!(
8076                        "Sparse query exceeds {MAX_SPARSE_TERMS} terms"
8077                    )));
8078                }
8079                (*column_id, *k)
8080            }
8081            Retriever::MinHash {
8082                column_id,
8083                members,
8084                k,
8085            } => {
8086                if !self.minhash.contains_key(column_id) {
8087                    return Err(MongrelError::InvalidArgument(format!(
8088                        "column {column_id} has no MinHash index"
8089                    )));
8090                }
8091                if members.is_empty() {
8092                    return Err(MongrelError::InvalidArgument(
8093                        "MinHash members must not be empty".into(),
8094                    ));
8095                }
8096                if members.len() > MAX_SET_MEMBERS {
8097                    return Err(MongrelError::InvalidArgument(format!(
8098                        "MinHash query exceeds {MAX_SET_MEMBERS} members"
8099                    )));
8100                }
8101                let mut total_bytes = 0usize;
8102                for member in members {
8103                    let bytes = member.encoded_len();
8104                    if bytes > crate::query::MAX_SET_MEMBER_BYTES {
8105                        return Err(MongrelError::InvalidArgument(format!(
8106                            "MinHash member exceeds {} bytes",
8107                            crate::query::MAX_SET_MEMBER_BYTES
8108                        )));
8109                    }
8110                    total_bytes = total_bytes.checked_add(bytes).ok_or_else(|| {
8111                        MongrelError::InvalidArgument("MinHash input size overflow".into())
8112                    })?;
8113                }
8114                if total_bytes > crate::query::MAX_SET_INPUT_BYTES {
8115                    return Err(MongrelError::InvalidArgument(format!(
8116                        "MinHash input exceeds {} bytes",
8117                        crate::query::MAX_SET_INPUT_BYTES
8118                    )));
8119                }
8120                (*column_id, *k)
8121            }
8122        };
8123        if k == 0 {
8124            return Err(MongrelError::InvalidArgument(
8125                "retriever k must be > 0".into(),
8126            ));
8127        }
8128        if k > MAX_RETRIEVER_K {
8129            return Err(MongrelError::InvalidArgument(format!(
8130                "retriever k exceeds {MAX_RETRIEVER_K}"
8131            )));
8132        }
8133        debug_assert!(self
8134            .schema
8135            .columns
8136            .iter()
8137            .any(|column| column.id == column_id));
8138        Ok(())
8139    }
8140
8141    fn validate_condition(&self, condition: &crate::query::Condition) -> Result<()> {
8142        use crate::query::Condition;
8143        match condition {
8144            Condition::Ann {
8145                column_id,
8146                query,
8147                k,
8148            } => self.validate_retriever(&crate::query::Retriever::Ann {
8149                column_id: *column_id,
8150                query: query.clone(),
8151                k: *k,
8152            }),
8153            Condition::SparseMatch {
8154                column_id,
8155                query,
8156                k,
8157            } => self.validate_retriever(&crate::query::Retriever::Sparse {
8158                column_id: *column_id,
8159                query: query.clone(),
8160                k: *k,
8161            }),
8162            Condition::MinHashSimilar {
8163                column_id,
8164                query,
8165                k,
8166            } => {
8167                if !self.minhash.contains_key(column_id) {
8168                    return Err(MongrelError::InvalidArgument(format!(
8169                        "column {column_id} has no MinHash index"
8170                    )));
8171                }
8172                if query.is_empty() || *k == 0 {
8173                    return Err(MongrelError::InvalidArgument(
8174                        "MinHash query must be non-empty and k must be > 0".into(),
8175                    ));
8176                }
8177                if query.len() > crate::query::MAX_SET_MEMBERS || *k > crate::query::MAX_RETRIEVER_K
8178                {
8179                    return Err(MongrelError::InvalidArgument(format!(
8180                        "MinHash query must have <= {} members and k <= {}",
8181                        crate::query::MAX_SET_MEMBERS,
8182                        crate::query::MAX_RETRIEVER_K
8183                    )));
8184                }
8185                Ok(())
8186            }
8187            Condition::BitmapIn { values, .. } if values.len() > crate::query::MAX_SET_MEMBERS => {
8188                Err(MongrelError::InvalidArgument(format!(
8189                    "bitmap IN exceeds {} values",
8190                    crate::query::MAX_SET_MEMBERS
8191                )))
8192            }
8193            Condition::FmContainsAll { patterns, .. }
8194                if patterns.len() > crate::query::MAX_HARD_CONDITIONS =>
8195            {
8196                Err(MongrelError::InvalidArgument(format!(
8197                    "FM query exceeds {} patterns",
8198                    crate::query::MAX_HARD_CONDITIONS
8199                )))
8200            }
8201            _ => Ok(()),
8202        }
8203    }
8204
8205    fn retrieve_filtered(
8206        &self,
8207        retriever: &crate::query::Retriever,
8208        snapshot: Snapshot,
8209        hard_filter: Option<&RowIdSet>,
8210        allowed: Option<&std::collections::HashSet<RowId>>,
8211        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8212        context: Option<&crate::query::AiExecutionContext>,
8213    ) -> Result<Vec<crate::query::RetrieverHit>> {
8214        use crate::query::{Retriever, RetrieverHit, RetrieverScore};
8215        let started = std::time::Instant::now();
8216        let scored: Vec<(RowId, RetrieverScore)> = match retriever {
8217            Retriever::Ann {
8218                column_id,
8219                query,
8220                k,
8221            } => {
8222                let Some(index) = self.ann.get(column_id) else {
8223                    return Ok(Vec::new());
8224                };
8225                let cap = ann_candidate_cap(index.len(), context);
8226                crate::trace::QueryTrace::record(|trace| trace.candidate_cap = cap);
8227                if cap == 0 {
8228                    return Ok(Vec::new());
8229                }
8230                let mut breadth = (*k).max(1).min(cap);
8231                let mut eligibility = std::collections::HashMap::new();
8232                // Cumulative trace counters across widening iterations
8233                // (spec §7.5: raw / visibility / authorization rejection
8234                // accounting; the candidate cap and `candidate_cap_hit`
8235                // are written when the loop terminates).
8236                let mut raw_candidates_total: usize = 0;
8237                let mut visibility_rejected_total: usize = 0;
8238                let mut authorization_rejected_total: usize = 0;
8239                let mut candidate_cap_hit_final = false;
8240                let mut filtered = loop {
8241                    let mut seen = std::collections::HashSet::new();
8242                    if let Some(context) = context {
8243                        context.checkpoint()?;
8244                    }
8245                    let raw = index.search_with_context(query, breadth, context)?;
8246                    crate::trace::QueryTrace::record(|trace| {
8247                        trace.raw_candidates = raw.len();
8248                        let unique = raw
8249                            .iter()
8250                            .map(|(row_id, _)| *row_id)
8251                            .collect::<std::collections::HashSet<_>>()
8252                            .len();
8253                        trace.unique_candidates = unique;
8254                        trace.duplicate_candidates = raw.len().saturating_sub(unique);
8255                        trace.authorization_rejected = raw
8256                            .iter()
8257                            .filter(|(row_id, _)| {
8258                                allowed.is_some_and(|allowed| !allowed.contains(row_id))
8259                            })
8260                            .count();
8261                        trace.hard_filter_rejected = raw
8262                            .iter()
8263                            .filter(|(row_id, _)| {
8264                                hard_filter.is_some_and(|filter| !filter.contains(row_id.0))
8265                            })
8266                            .count();
8267                    });
8268                    raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8269                    let unchecked: Vec<_> = raw
8270                        .iter()
8271                        .map(|(row_id, _)| *row_id)
8272                        .filter(|row_id| !eligibility.contains_key(row_id))
8273                        .filter(|row_id| {
8274                            hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8275                                && allowed.is_none_or(|allowed| allowed.contains(row_id))
8276                        })
8277                        .collect();
8278                    let eligible = self.eligible_and_authorized_candidate_ids(
8279                        &unchecked,
8280                        *column_id,
8281                        snapshot,
8282                        candidate_authorization,
8283                        context,
8284                    )?;
8285                    for row_id in &unchecked {
8286                        eligibility.insert(*row_id, eligible.contains(row_id));
8287                    }
8288                    // Account for newly rejected rows: anything not in
8289                    // `eligible` (visibility or tombstone/TTL or authorization).
8290                    let new_visibility_or_auth_rejected = unchecked
8291                        .iter()
8292                        .filter(|row_id| !eligible.contains(row_id))
8293                        .count();
8294                    // Distinguish visibility vs authorization rejections for
8295                    // the trace. Authorization rejections are rows that pass
8296                    // visibility but fail the candidate-authorization check;
8297                    // visibility rejections are the remainder.
8298                    let mut new_auth_rejected = 0usize;
8299                    if let Some(authorization) = candidate_authorization {
8300                        if authorization.security.rls_enabled(authorization.table)
8301                            && !authorization.principal.is_admin
8302                        {
8303                            // Re-eligibility-check only the auth layer to
8304                            // count how many were dropped at authorization
8305                            // specifically (eligible already merged auth
8306                            // into its result; treat non-eligible as
8307                            // auth-rejected when RLS is on).
8308                            new_auth_rejected = new_visibility_or_auth_rejected;
8309                        }
8310                    }
8311                    let new_visibility_rejected =
8312                        new_visibility_or_auth_rejected.saturating_sub(new_auth_rejected);
8313                    visibility_rejected_total =
8314                        visibility_rejected_total.saturating_add(new_visibility_rejected);
8315                    authorization_rejected_total =
8316                        authorization_rejected_total.saturating_add(new_auth_rejected);
8317                    let filtered: Vec<_> = raw
8318                        .into_iter()
8319                        .filter(|(row_id, _)| {
8320                            seen.insert(*row_id)
8321                                && eligibility.get(row_id).copied().unwrap_or(false)
8322                        })
8323                        .map(|(row_id, score)| {
8324                            let score = match score {
8325                                crate::index::AnnDistance::Hamming(d) => {
8326                                    RetrieverScore::AnnHammingDistance(d)
8327                                }
8328                                crate::index::AnnDistance::Cosine(d) => {
8329                                    RetrieverScore::AnnCosineDistance(d)
8330                                }
8331                            };
8332                            (row_id, score)
8333                        })
8334                        .collect();
8335                    if filtered.len() >= *k || breadth >= cap {
8336                        if filtered.len() < *k && index.len() > cap && breadth >= cap {
8337                            crate::trace::QueryTrace::record(|trace| {
8338                                trace.ann_candidate_cap_hit = true;
8339                                trace.candidate_cap_hit = true;
8340                            });
8341                            candidate_cap_hit_final = true;
8342                        }
8343                        break filtered;
8344                    }
8345                    breadth = breadth.saturating_mul(2).min(cap);
8346                };
8347                // Final trace write for ANN: candidate cap, cap-hit flag,
8348                // cumulative raw / rejection counts, and final hit count.
8349                let final_hits = filtered.len();
8350                let index_len = index.len();
8351                crate::trace::QueryTrace::record(|trace| {
8352                    trace.candidate_cap = cap;
8353                    trace.candidate_cap_hit = candidate_cap_hit_final;
8354                    trace.ann_candidate_cap_hit = candidate_cap_hit_final;
8355                    trace.raw_candidates =
8356                        trace.raw_candidates.saturating_add(raw_candidates_total);
8357                    trace.visibility_rejected = trace
8358                        .visibility_rejected
8359                        .saturating_add(visibility_rejected_total);
8360                    trace.authorization_rejected = trace
8361                        .authorization_rejected
8362                        .saturating_add(authorization_rejected_total);
8363                    trace.final_hits = trace.final_hits.saturating_add(final_hits);
8364                    // Suppress the unused warning on index_len — it is a
8365                    // useful diagnostic when paired with `candidate_cap_hit`.
8366                    let _ = index_len;
8367                });
8368                filtered.truncate(*k);
8369                filtered
8370            }
8371            Retriever::Sparse {
8372                column_id,
8373                query,
8374                k,
8375            } => self
8376                .sparse
8377                .get(column_id)
8378                .map(|index| -> Result<Vec<_>> {
8379                    let mut breadth = (*k).max(1);
8380                    let mut eligibility = std::collections::HashMap::new();
8381                    // Cumulative trace counters across widening iterations
8382                    // (same §7.5 accounting as the ANN branch above).
8383                    let mut raw_candidates_total: usize = 0;
8384                    let mut visibility_rejected_total: usize = 0;
8385                    let mut authorization_rejected_total: usize = 0;
8386                    let filtered = loop {
8387                        if let Some(context) = context {
8388                            context.checkpoint()?;
8389                        }
8390                        let raw = index.search_with_context(query, breadth, context)?;
8391                        raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8392                        authorization_rejected_total = authorization_rejected_total.saturating_add(
8393                            raw.iter()
8394                                .filter(|(row_id, _)| {
8395                                    allowed.is_some_and(|allowed| !allowed.contains(row_id))
8396                                })
8397                                .count(),
8398                        );
8399                        let unchecked: Vec<_> = raw
8400                            .iter()
8401                            .map(|(row_id, _)| *row_id)
8402                            .filter(|row_id| !eligibility.contains_key(row_id))
8403                            .filter(|row_id| {
8404                                hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8405                                    && allowed.is_none_or(|allowed| allowed.contains(row_id))
8406                            })
8407                            .collect();
8408                        let eligible = self.eligible_and_authorized_candidate_ids(
8409                            &unchecked,
8410                            *column_id,
8411                            snapshot,
8412                            candidate_authorization,
8413                            context,
8414                        )?;
8415                        visibility_rejected_total = visibility_rejected_total.saturating_add(
8416                            unchecked
8417                                .iter()
8418                                .filter(|row_id| !eligible.contains(row_id))
8419                                .count(),
8420                        );
8421                        for row_id in unchecked {
8422                            eligibility.insert(row_id, eligible.contains(&row_id));
8423                        }
8424                        let filtered: Vec<_> = raw
8425                            .iter()
8426                            .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8427                            .take(*k)
8428                            .map(|(row_id, score)| {
8429                                (*row_id, RetrieverScore::SparseDotProduct(*score))
8430                            })
8431                            .collect();
8432                        if filtered.len() >= *k || raw.len() < breadth {
8433                            break filtered;
8434                        }
8435                        let next = breadth.saturating_mul(2);
8436                        if next == breadth {
8437                            break filtered;
8438                        }
8439                        breadth = next;
8440                    };
8441                    crate::trace::QueryTrace::record(|trace| {
8442                        trace.raw_candidates =
8443                            trace.raw_candidates.saturating_add(raw_candidates_total);
8444                        trace.visibility_rejected = trace
8445                            .visibility_rejected
8446                            .saturating_add(visibility_rejected_total);
8447                        trace.authorization_rejected = trace
8448                            .authorization_rejected
8449                            .saturating_add(authorization_rejected_total);
8450                    });
8451                    Ok(filtered)
8452                })
8453                .transpose()?
8454                .unwrap_or_default(),
8455            Retriever::MinHash {
8456                column_id,
8457                members,
8458                k,
8459            } => self
8460                .minhash
8461                .get(column_id)
8462                .map(|index| -> Result<Vec<_>> {
8463                    let mut hashes = Vec::with_capacity(members.len());
8464                    for member in members {
8465                        if let Some(context) = context {
8466                            context.consume(crate::query::work_units(
8467                                member.encoded_len(),
8468                                crate::query::PARSE_WORK_QUANTUM,
8469                            ))?;
8470                        }
8471                        hashes.push(member.hash_v1());
8472                    }
8473                    let mut breadth = (*k).max(1);
8474                    let mut eligibility = std::collections::HashMap::new();
8475                    let mut raw_candidates_total: usize = 0;
8476                    let mut visibility_rejected_total: usize = 0;
8477                    let mut authorization_rejected_total: usize = 0;
8478                    let filtered = loop {
8479                        if let Some(context) = context {
8480                            context.checkpoint()?;
8481                        }
8482                        let raw = index.search_with_context(&hashes, breadth, context)?;
8483                        raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8484                        authorization_rejected_total = authorization_rejected_total.saturating_add(
8485                            raw.iter()
8486                                .filter(|(row_id, _)| {
8487                                    allowed.is_some_and(|allowed| !allowed.contains(row_id))
8488                                })
8489                                .count(),
8490                        );
8491                        let unchecked: Vec<_> = raw
8492                            .iter()
8493                            .map(|(row_id, _)| *row_id)
8494                            .filter(|row_id| !eligibility.contains_key(row_id))
8495                            .filter(|row_id| {
8496                                hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8497                                    && allowed.is_none_or(|allowed| allowed.contains(row_id))
8498                            })
8499                            .collect();
8500                        let eligible = self.eligible_and_authorized_candidate_ids(
8501                            &unchecked,
8502                            *column_id,
8503                            snapshot,
8504                            candidate_authorization,
8505                            context,
8506                        )?;
8507                        visibility_rejected_total = visibility_rejected_total.saturating_add(
8508                            unchecked
8509                                .iter()
8510                                .filter(|row_id| !eligible.contains(row_id))
8511                                .count(),
8512                        );
8513                        for row_id in unchecked {
8514                            eligibility.insert(row_id, eligible.contains(&row_id));
8515                        }
8516                        let filtered: Vec<_> = raw
8517                            .iter()
8518                            .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8519                            .take(*k)
8520                            .map(|(row_id, score)| {
8521                                (*row_id, RetrieverScore::MinHashEstimatedJaccard(*score))
8522                            })
8523                            .collect();
8524                        if filtered.len() >= *k || raw.len() < breadth {
8525                            break filtered;
8526                        }
8527                        let next = breadth.saturating_mul(2);
8528                        if next == breadth {
8529                            break filtered;
8530                        }
8531                        breadth = next;
8532                    };
8533                    crate::trace::QueryTrace::record(|trace| {
8534                        trace.raw_candidates =
8535                            trace.raw_candidates.saturating_add(raw_candidates_total);
8536                        trace.visibility_rejected = trace
8537                            .visibility_rejected
8538                            .saturating_add(visibility_rejected_total);
8539                        trace.authorization_rejected = trace
8540                            .authorization_rejected
8541                            .saturating_add(authorization_rejected_total);
8542                    });
8543                    Ok(filtered)
8544                })
8545                .transpose()?
8546                .unwrap_or_default(),
8547        };
8548        let requested_k = match retriever {
8549            Retriever::Ann { k, .. }
8550            | Retriever::Sparse { k, .. }
8551            | Retriever::MinHash { k, .. } => *k,
8552        };
8553        crate::trace::QueryTrace::record(|trace| {
8554            trace.final_hits = scored.len();
8555            if scored.len() < requested_k {
8556                trace.underfill_reason = Some(if trace.candidate_cap_hit {
8557                    "candidate_cap"
8558                } else {
8559                    "eligible_candidates_exhausted"
8560                });
8561            }
8562        });
8563        let elapsed = started.elapsed().as_nanos() as u64;
8564        crate::trace::QueryTrace::record(|trace| {
8565            match retriever {
8566                Retriever::Ann { .. } => {
8567                    trace.ann_candidate_nanos = trace.ann_candidate_nanos.saturating_add(elapsed);
8568                    if let Retriever::Ann { column_id, .. } = retriever {
8569                        if let Some(index) = self.ann.get(column_id) {
8570                            trace.ann_algorithm = Some(index.algorithm());
8571                            trace.ann_quantization = Some(index.quantization());
8572                            trace.ann_backend = Some(index.backend_name());
8573                        }
8574                    }
8575                }
8576                Retriever::Sparse { .. } => {
8577                    trace.sparse_candidate_nanos =
8578                        trace.sparse_candidate_nanos.saturating_add(elapsed)
8579                }
8580                Retriever::MinHash { .. } => {
8581                    trace.minhash_candidate_nanos =
8582                        trace.minhash_candidate_nanos.saturating_add(elapsed)
8583                }
8584            }
8585            trace.candidate_count = trace.candidate_count.saturating_add(scored.len());
8586        });
8587        Ok(scored
8588            .into_iter()
8589            .enumerate()
8590            .map(|(rank, (row_id, score))| RetrieverHit {
8591                row_id,
8592                rank: rank + 1,
8593                score,
8594            })
8595            .collect())
8596    }
8597
8598    fn eligible_candidate_ids(
8599        &self,
8600        candidates: &[RowId],
8601        _column_id: u16,
8602        snapshot: Snapshot,
8603        context: Option<&crate::query::AiExecutionContext>,
8604    ) -> Result<std::collections::HashSet<RowId>> {
8605        // Candidate eligibility is a pure snapshot read — the same
8606        // visibility rule point lookups (`get`) use. The in-flight
8607        // private-WAL batch lands in the memtable at `pending_epoch =
8608        // visible + 1` (puts and matching tombstones), above every reader
8609        // snapshot, so the un-advanced snapshot already hides it. Unlike
8610        // `resolve_pk_with_hot_fallback`, retrievers must NOT advance to
8611        // `pending_epoch`: an uncommitted row whose embedding is the exact
8612        // query match would outrank every committed row and leak into the
8613        // hits (see tests/retriever_uncommitted.rs). Committed versions
8614        // remain eligible under the caller snapshot, including HLC-stamped
8615        // winners admitted by `observes_row` (REM-001).
8616        let lookup_snapshot = snapshot;
8617        let mut readers: Vec<_> = self
8618            .run_refs
8619            .iter()
8620            .map(|run| self.open_reader(run.run_id))
8621            .collect::<Result<_>>()?;
8622        let now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8623        let mut eligible = std::collections::HashSet::with_capacity(candidates.len());
8624        for &row_id in candidates {
8625            if let Some(context) = context {
8626                context.consume(1)?;
8627            }
8628            let mem = self.memtable.get_version_at(row_id, lookup_snapshot);
8629            let mutable = self.mutable_run.get_version_at(row_id, lookup_snapshot);
8630            let overlay = match (mem, mutable) {
8631                (Some(left), Some(right)) => Some(
8632                    if Snapshot::version_is_newer(
8633                        left.1.committed_epoch,
8634                        left.1.commit_ts,
8635                        right.1.committed_epoch,
8636                        right.1.commit_ts,
8637                    ) {
8638                        left
8639                    } else {
8640                        right
8641                    },
8642                ),
8643                (Some(value), None) | (None, Some(value)) => Some(value),
8644                (None, None) => None,
8645            };
8646            if let Some((_, row)) = overlay {
8647                if !row.deleted && !self.row_expired_at(&row, now) {
8648                    eligible.insert(row_id);
8649                }
8650                continue;
8651            }
8652            // REM-001: keep the full version stamp across runs so the eligibility fold
8653            // honors HLC authority when candidates are stamped. The legacy
8654            // `(epoch, deleted, reader_index)` tuple dropped `commit_ts` and
8655            // could admit a stale high-epoch row over an HLC-newer low-epoch
8656            // candidate.
8657            let mut best: Option<(crate::sorted_run::VersionVisibility, usize)> = None;
8658            for (index, reader) in readers.iter_mut().enumerate() {
8659                if let Some(visibility) =
8660                    reader.get_version_visibility_full_at(row_id, lookup_snapshot)?
8661                {
8662                    if best
8663                        .as_ref()
8664                        .map(|(current, _)| visibility.stamp.is_newer_than(current.stamp))
8665                        .unwrap_or(true)
8666                    {
8667                        best = Some((visibility, index));
8668                    }
8669                }
8670            }
8671            let Some((visibility, reader_index)) = best else {
8672                continue;
8673            };
8674            if visibility.deleted {
8675                continue;
8676            }
8677            if let Some(ttl) = self.ttl {
8678                if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
8679                    row_id,
8680                    lookup_snapshot,
8681                    ttl.column_id,
8682                )? {
8683                    if let Some(Value::Int64(timestamp)) = ttl_value.value {
8684                        if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
8685                            continue;
8686                        }
8687                    }
8688                }
8689            }
8690            eligible.insert(row_id);
8691        }
8692        Ok(eligible)
8693    }
8694
8695    fn eligible_and_authorized_candidate_ids(
8696        &self,
8697        candidates: &[RowId],
8698        column_id: u16,
8699        snapshot: Snapshot,
8700        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8701        context: Option<&crate::query::AiExecutionContext>,
8702    ) -> Result<std::collections::HashSet<RowId>> {
8703        let eligible = self.eligible_candidate_ids(candidates, column_id, snapshot, context)?;
8704        let Some(authorization) = authorization else {
8705            return Ok(eligible);
8706        };
8707        let candidates: Vec<_> = eligible.into_iter().collect();
8708        self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, context)
8709    }
8710
8711    fn policy_allowed_candidate_ids(
8712        &self,
8713        candidates: &[RowId],
8714        snapshot: Snapshot,
8715        authorization: &crate::security::CandidateAuthorization<'_>,
8716        context: Option<&crate::query::AiExecutionContext>,
8717    ) -> Result<std::collections::HashSet<RowId>> {
8718        let started = std::time::Instant::now();
8719        if candidates.is_empty()
8720            || authorization.principal.is_admin
8721            || !authorization.security.rls_enabled(authorization.table)
8722        {
8723            return Ok(candidates.iter().copied().collect());
8724        }
8725        if let Some(context) = context {
8726            context.checkpoint()?;
8727        }
8728        let row_ids: Vec<_> = candidates.iter().map(|row_id| row_id.0).collect();
8729        let mut rows: std::collections::HashMap<RowId, Row> = candidates
8730            .iter()
8731            .map(|row_id| {
8732                (
8733                    *row_id,
8734                    Row {
8735                        row_id: *row_id,
8736                        committed_epoch: snapshot.epoch,
8737                        columns: std::collections::HashMap::new(),
8738                        deleted: false,
8739                        commit_ts: None,
8740                    },
8741                )
8742            })
8743            .collect();
8744        let columns = authorization
8745            .security
8746            .select_policy_columns(authorization.table, authorization.principal);
8747        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8748        let mut decoded = 0usize;
8749        for column_id in &columns {
8750            if let Some(context) = context {
8751                context.checkpoint()?;
8752            }
8753            for (row_id, value) in self.values_for_rids_batch_at_with_context(
8754                &row_ids, *column_id, snapshot, query_now, context,
8755            )? {
8756                if let Some(row) = rows.get_mut(&row_id) {
8757                    row.columns.insert(*column_id, value);
8758                    decoded = decoded.saturating_add(1);
8759                }
8760            }
8761        }
8762        if let Some(context) = context {
8763            context.consume(candidates.len().saturating_add(decoded))?;
8764        }
8765        let allowed = rows
8766            .into_values()
8767            .filter_map(|row| {
8768                authorization
8769                    .security
8770                    .row_allowed(
8771                        authorization.table,
8772                        crate::security::PolicyCommand::Select,
8773                        &row,
8774                        authorization.principal,
8775                        false,
8776                    )
8777                    .then_some(row.row_id)
8778            })
8779            .collect();
8780        crate::trace::QueryTrace::record(|trace| {
8781            trace.rls_rows_evaluated = trace.rls_rows_evaluated.saturating_add(candidates.len());
8782            trace.rls_policy_columns_decoded =
8783                trace.rls_policy_columns_decoded.saturating_add(decoded);
8784            trace.authorization_nanos = trace
8785                .authorization_nanos
8786                .saturating_add(started.elapsed().as_nanos() as u64);
8787        });
8788        Ok(allowed)
8789    }
8790
8791    /// Filter-aware union and reciprocal-rank fusion over scored retrievers.
8792    pub fn search(
8793        &mut self,
8794        request: &crate::query::SearchRequest,
8795    ) -> Result<Vec<crate::query::SearchHit>> {
8796        self.search_with_allowed(request, None)
8797    }
8798
8799    pub fn search_at(
8800        &mut self,
8801        request: &crate::query::SearchRequest,
8802        snapshot: Snapshot,
8803        authorized: Option<&std::collections::HashSet<RowId>>,
8804    ) -> Result<Vec<crate::query::SearchHit>> {
8805        self.search_at_with_allowed(request, snapshot, authorized)
8806    }
8807
8808    pub fn search_with_allowed(
8809        &mut self,
8810        request: &crate::query::SearchRequest,
8811        authorized: Option<&std::collections::HashSet<RowId>>,
8812    ) -> Result<Vec<crate::query::SearchHit>> {
8813        self.search_at_with_allowed(request, self.snapshot(), authorized)
8814    }
8815
8816    pub fn search_at_with_allowed(
8817        &mut self,
8818        request: &crate::query::SearchRequest,
8819        snapshot: Snapshot,
8820        authorized: Option<&std::collections::HashSet<RowId>>,
8821    ) -> Result<Vec<crate::query::SearchHit>> {
8822        self.search_at_with_allowed_and_context(request, snapshot, authorized, None)
8823    }
8824
8825    pub fn search_at_with_allowed_and_context(
8826        &mut self,
8827        request: &crate::query::SearchRequest,
8828        snapshot: Snapshot,
8829        authorized: Option<&std::collections::HashSet<RowId>>,
8830        context: Option<&crate::query::AiExecutionContext>,
8831    ) -> Result<Vec<crate::query::SearchHit>> {
8832        self.ensure_indexes_complete()?;
8833        self.search_at_with_filters_and_context(request, snapshot, authorized, None, context, None)
8834    }
8835
8836    pub fn search_at_with_candidate_authorization_and_context(
8837        &mut self,
8838        request: &crate::query::SearchRequest,
8839        snapshot: Snapshot,
8840        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8841        context: Option<&crate::query::AiExecutionContext>,
8842    ) -> Result<Vec<crate::query::SearchHit>> {
8843        self.ensure_indexes_complete()?;
8844        self.search_at_with_filters_and_context(
8845            request,
8846            snapshot,
8847            None,
8848            authorization,
8849            context,
8850            None,
8851        )
8852    }
8853
8854    #[doc(hidden)]
8855    pub fn search_at_with_candidate_authorization_on_generation(
8856        &self,
8857        request: &crate::query::SearchRequest,
8858        snapshot: Snapshot,
8859        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8860        context: Option<&crate::query::AiExecutionContext>,
8861    ) -> Result<Vec<crate::query::SearchHit>> {
8862        self.search_at_with_filters_and_context(
8863            request,
8864            snapshot,
8865            None,
8866            authorization,
8867            context,
8868            None,
8869        )
8870    }
8871
8872    #[doc(hidden)]
8873    pub fn search_at_with_candidate_authorization_on_generation_after(
8874        &self,
8875        request: &crate::query::SearchRequest,
8876        snapshot: Snapshot,
8877        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8878        context: Option<&crate::query::AiExecutionContext>,
8879        after: Option<crate::query::SearchAfter>,
8880    ) -> Result<Vec<crate::query::SearchHit>> {
8881        self.search_at_with_filters_and_context(
8882            request,
8883            snapshot,
8884            None,
8885            authorization,
8886            context,
8887            after,
8888        )
8889    }
8890
8891    fn search_at_with_filters_and_context(
8892        &self,
8893        request: &crate::query::SearchRequest,
8894        snapshot: Snapshot,
8895        authorized: Option<&std::collections::HashSet<RowId>>,
8896        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8897        context: Option<&crate::query::AiExecutionContext>,
8898        after: Option<crate::query::SearchAfter>,
8899    ) -> Result<Vec<crate::query::SearchHit>> {
8900        use crate::query::{
8901            ComponentScore, Condition, Fusion, SearchHit, MAX_FINAL_LIMIT, MAX_HARD_CONDITIONS,
8902            MAX_PROJECTION_COLUMNS, MAX_RETRIEVERS, MAX_RETRIEVER_WEIGHT,
8903        };
8904        let total_started = std::time::Instant::now();
8905        let rank_offset = after.map_or(0, |after| after.returned_count);
8906        self.require_select()?;
8907        if request.limit == 0 {
8908            return Err(MongrelError::InvalidArgument(
8909                "search limit must be > 0".into(),
8910            ));
8911        }
8912        if request.limit > MAX_FINAL_LIMIT {
8913            return Err(MongrelError::InvalidArgument(format!(
8914                "search limit exceeds {MAX_FINAL_LIMIT}"
8915            )));
8916        }
8917        if after.is_some_and(|cursor| !cursor.final_score.is_finite()) {
8918            return Err(MongrelError::InvalidArgument(
8919                "search-after score must be finite".into(),
8920            ));
8921        }
8922        if request.retrievers.is_empty() {
8923            return Err(MongrelError::InvalidArgument(
8924                "search requires at least one retriever".into(),
8925            ));
8926        }
8927        if request.retrievers.len() > MAX_RETRIEVERS {
8928            return Err(MongrelError::InvalidArgument(format!(
8929                "search exceeds {MAX_RETRIEVERS} retrievers"
8930            )));
8931        }
8932        if request.must.len() > MAX_HARD_CONDITIONS {
8933            return Err(MongrelError::InvalidArgument(format!(
8934                "search exceeds {MAX_HARD_CONDITIONS} hard conditions"
8935            )));
8936        }
8937        for condition in &request.must {
8938            self.validate_condition(condition)?;
8939        }
8940        if request.must.iter().any(|condition| {
8941            matches!(
8942                condition,
8943                Condition::Ann { .. }
8944                    | Condition::SparseMatch { .. }
8945                    | Condition::MinHashSimilar { .. }
8946            )
8947        }) {
8948            return Err(MongrelError::InvalidArgument(
8949                "ranked ANN, Sparse, and MinHash conditions must be retrievers, not must filters"
8950                    .into(),
8951            ));
8952        }
8953        let mut names = std::collections::HashSet::new();
8954        for named in &request.retrievers {
8955            if named.name.is_empty()
8956                || named.name.len() > crate::query::MAX_RETRIEVER_NAME_BYTES
8957                || !names.insert(named.name.as_str())
8958            {
8959                return Err(MongrelError::InvalidArgument(format!(
8960                    "retriever names must be non-empty, unique, and at most {} UTF-8 bytes",
8961                    crate::query::MAX_RETRIEVER_NAME_BYTES
8962                )));
8963            }
8964            if !named.weight.is_finite()
8965                || named.weight < 0.0
8966                || named.weight > MAX_RETRIEVER_WEIGHT
8967            {
8968                return Err(MongrelError::InvalidArgument(format!(
8969                    "retriever weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
8970                )));
8971            }
8972            self.validate_retriever(&named.retriever)?;
8973        }
8974        let projection = request
8975            .projection
8976            .clone()
8977            .unwrap_or_else(|| self.schema.columns.iter().map(|column| column.id).collect());
8978        if projection.len() > MAX_PROJECTION_COLUMNS {
8979            return Err(MongrelError::InvalidArgument(format!(
8980                "projection exceeds {MAX_PROJECTION_COLUMNS} columns"
8981            )));
8982        }
8983        for column_id in &projection {
8984            if !self
8985                .schema
8986                .columns
8987                .iter()
8988                .any(|column| column.id == *column_id)
8989            {
8990                return Err(MongrelError::ColumnNotFound(column_id.to_string()));
8991            }
8992        }
8993        if let Some(crate::query::Rerank::ExactVector {
8994            embedding_column,
8995            query,
8996            candidate_limit,
8997            weight,
8998            ..
8999        }) = &request.rerank
9000        {
9001            if *candidate_limit < request.limit || *candidate_limit > crate::query::MAX_RETRIEVER_K
9002            {
9003                return Err(MongrelError::InvalidArgument(format!(
9004                    "rerank candidate_limit must be between search limit and {}",
9005                    crate::query::MAX_RETRIEVER_K
9006                )));
9007            }
9008            if !weight.is_finite() || *weight < 0.0 || *weight > MAX_RETRIEVER_WEIGHT {
9009                return Err(MongrelError::InvalidArgument(format!(
9010                    "rerank weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
9011                )));
9012            }
9013            let column = self
9014                .schema
9015                .columns
9016                .iter()
9017                .find(|column| column.id == *embedding_column)
9018                .ok_or_else(|| MongrelError::ColumnNotFound(embedding_column.to_string()))?;
9019            let crate::schema::TypeId::Embedding { dim } = column.ty else {
9020                return Err(MongrelError::InvalidArgument(format!(
9021                    "rerank column {embedding_column} is not an embedding"
9022                )));
9023            };
9024            if query.len() != dim as usize || query.iter().any(|value| !value.is_finite()) {
9025                return Err(MongrelError::InvalidArgument(format!(
9026                    "rerank query must contain {dim} finite values"
9027                )));
9028            }
9029        }
9030
9031        let hard_filter_started = std::time::Instant::now();
9032        let hard_filter = if request.must.is_empty() {
9033            None
9034        } else {
9035            let mut sets = Vec::with_capacity(request.must.len());
9036            for condition in &request.must {
9037                if let Some(context) = context {
9038                    context.checkpoint()?;
9039                }
9040                sets.push(self.resolve_condition(condition, snapshot)?);
9041            }
9042            Some(RowIdSet::intersect_many(sets))
9043        };
9044        crate::trace::QueryTrace::record(|trace| {
9045            trace.hard_filter_nanos = trace
9046                .hard_filter_nanos
9047                .saturating_add(hard_filter_started.elapsed().as_nanos() as u64);
9048        });
9049        if hard_filter.as_ref().is_some_and(RowIdSet::is_empty) {
9050            return Ok(Vec::new());
9051        }
9052
9053        let constant = match request.fusion {
9054            Fusion::ReciprocalRank { constant } => constant,
9055        };
9056        let mut retrievers: Vec<_> = request.retrievers.iter().collect();
9057        retrievers.sort_by(|a, b| a.name.cmp(&b.name));
9058        let mut fusion_nanos = 0u64;
9059        let mut fused: std::collections::HashMap<RowId, (f64, Vec<ComponentScore>)> =
9060            std::collections::HashMap::new();
9061        for named in retrievers {
9062            if named.weight == 0.0 {
9063                continue;
9064            }
9065            if let Some(context) = context {
9066                context.checkpoint()?;
9067            }
9068            let hits = self.retrieve_filtered(
9069                &named.retriever,
9070                snapshot,
9071                hard_filter.as_ref(),
9072                authorized,
9073                candidate_authorization,
9074                context,
9075            )?;
9076            let retriever_name: std::sync::Arc<str> = named.name.as_str().into();
9077            let fusion_started = std::time::Instant::now();
9078            for hit in hits {
9079                if let Some(context) = context {
9080                    context.consume(1)?;
9081                }
9082                let contribution = named.weight / (constant as f64 + hit.rank as f64);
9083                if !contribution.is_finite() {
9084                    return Err(MongrelError::InvalidArgument(
9085                        "retriever contribution must be finite".into(),
9086                    ));
9087                }
9088                let max_fused_candidates = context.map_or(
9089                    crate::query::MAX_FUSED_CANDIDATES,
9090                    crate::query::AiExecutionContext::max_fused_candidates,
9091                );
9092                if !fused.contains_key(&hit.row_id) && fused.len() >= max_fused_candidates {
9093                    return Err(MongrelError::WorkBudgetExceeded);
9094                }
9095                let entry = fused.entry(hit.row_id).or_default();
9096                entry.0 += contribution;
9097                if !entry.0.is_finite() {
9098                    return Err(MongrelError::InvalidArgument(
9099                        "fused score must be finite".into(),
9100                    ));
9101                }
9102                entry.1.push(ComponentScore {
9103                    retriever_name: retriever_name.clone(),
9104                    rank: hit.rank,
9105                    raw_score: hit.score,
9106                    contribution,
9107                });
9108            }
9109            fusion_nanos = fusion_nanos.saturating_add(fusion_started.elapsed().as_nanos() as u64);
9110        }
9111        let union_size = fused.len();
9112        let mut ranked: Vec<_> = fused
9113            .into_iter()
9114            .map(|(row_id, (fused_score, components))| {
9115                (row_id, fused_score, components, None, fused_score)
9116            })
9117            .collect();
9118        let order = |(a_row, _, _, _, a_score): &(
9119            RowId,
9120            f64,
9121            Vec<ComponentScore>,
9122            Option<f32>,
9123            f64,
9124        ),
9125                     (b_row, _, _, _, b_score): &(
9126            RowId,
9127            f64,
9128            Vec<ComponentScore>,
9129            Option<f32>,
9130            f64,
9131        )| { b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row)) };
9132        if let Some(crate::query::Rerank::ExactVector {
9133            embedding_column,
9134            query,
9135            metric,
9136            candidate_limit,
9137            weight,
9138        }) = &request.rerank
9139        {
9140            let fused_order = |(a_row, a_score, ..): &(
9141                RowId,
9142                f64,
9143                Vec<ComponentScore>,
9144                Option<f32>,
9145                f64,
9146            ),
9147                               (b_row, b_score, ..): &(
9148                RowId,
9149                f64,
9150                Vec<ComponentScore>,
9151                Option<f32>,
9152                f64,
9153            )| {
9154                b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row))
9155            };
9156            let selection_started = std::time::Instant::now();
9157            if let Some(context) = context {
9158                context.consume(ranked.len())?;
9159            }
9160            if ranked.len() > *candidate_limit {
9161                let (_, _, _) = ranked.select_nth_unstable_by(*candidate_limit, fused_order);
9162                ranked.truncate(*candidate_limit);
9163            }
9164            ranked.sort_by(fused_order);
9165            fusion_nanos =
9166                fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9167            let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9168            if let Some(context) = context {
9169                context.consume(row_ids.len())?;
9170            }
9171            let query_now =
9172                context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9173            let gather_started = std::time::Instant::now();
9174            let vectors = self.values_for_rids_batch_at_with_context(
9175                &row_ids,
9176                *embedding_column,
9177                snapshot,
9178                query_now,
9179                context,
9180            )?;
9181            let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9182            let vector_work =
9183                crate::query::work_units(query.len(), crate::query::VECTOR_WORK_QUANTUM);
9184            let query_norm = if matches!(metric, crate::query::VectorMetric::Cosine) {
9185                if let Some(context) = context {
9186                    context.consume(vector_work)?;
9187                }
9188                query
9189                    .iter()
9190                    .map(|value| f64::from(*value).powi(2))
9191                    .sum::<f64>()
9192                    .sqrt()
9193            } else {
9194                0.0
9195            };
9196            let score_started = std::time::Instant::now();
9197            let mut scores = std::collections::HashMap::with_capacity(vectors.len());
9198            for (row_id, value) in vectors {
9199                if let Some(meta) = value.generated_embedding_metadata() {
9200                    if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9201                        continue;
9202                    }
9203                }
9204                let Some(vector) = value.as_embedding() else {
9205                    continue;
9206                };
9207                let score = match metric {
9208                    crate::query::VectorMetric::DotProduct => {
9209                        if let Some(context) = context {
9210                            context.consume(vector_work)?;
9211                        }
9212                        query
9213                            .iter()
9214                            .zip(vector)
9215                            .map(|(left, right)| f64::from(*left) * f64::from(*right))
9216                            .sum::<f64>()
9217                    }
9218                    crate::query::VectorMetric::Cosine => {
9219                        if let Some(context) = context {
9220                            context.consume(vector_work.saturating_mul(2))?;
9221                        }
9222                        let dot = query
9223                            .iter()
9224                            .zip(vector)
9225                            .map(|(left, right)| f64::from(*left) * f64::from(*right))
9226                            .sum::<f64>();
9227                        let norm = vector
9228                            .iter()
9229                            .map(|value| f64::from(*value).powi(2))
9230                            .sum::<f64>()
9231                            .sqrt();
9232                        if query_norm == 0.0 || norm == 0.0 {
9233                            0.0
9234                        } else {
9235                            dot / (query_norm * norm)
9236                        }
9237                    }
9238                    crate::query::VectorMetric::Euclidean => {
9239                        if let Some(context) = context {
9240                            context.consume(vector_work)?;
9241                        }
9242                        query
9243                            .iter()
9244                            .zip(vector)
9245                            .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9246                            .sum::<f64>()
9247                            .sqrt()
9248                    }
9249                };
9250                if !score.is_finite() {
9251                    return Err(MongrelError::InvalidArgument(
9252                        "exact rerank score must be finite".into(),
9253                    ));
9254                }
9255                scores.insert(row_id, score as f32);
9256            }
9257            let mut reranked = Vec::with_capacity(ranked.len());
9258            for (row_id, fused_score, components, _, _) in ranked.drain(..) {
9259                let Some(score) = scores.get(&row_id).copied() else {
9260                    continue;
9261                };
9262                let ordering_score = match metric {
9263                    crate::query::VectorMetric::Euclidean => -f64::from(score),
9264                    crate::query::VectorMetric::Cosine | crate::query::VectorMetric::DotProduct => {
9265                        f64::from(score)
9266                    }
9267                };
9268                let final_score = fused_score + *weight * ordering_score;
9269                if !final_score.is_finite() {
9270                    return Err(MongrelError::InvalidArgument(
9271                        "final rerank score must be finite".into(),
9272                    ));
9273                }
9274                reranked.push((row_id, fused_score, components, Some(score), final_score));
9275            }
9276            ranked = reranked;
9277            ranked.sort_by(order);
9278            crate::trace::QueryTrace::record(|trace| {
9279                trace.exact_vector_gather_nanos =
9280                    trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9281                trace.exact_vector_score_nanos = trace
9282                    .exact_vector_score_nanos
9283                    .saturating_add(score_started.elapsed().as_nanos() as u64);
9284            });
9285        }
9286        if let Some(after) = after {
9287            ranked.retain(|(row_id, _, _, _, final_score)| {
9288                final_score.total_cmp(&after.final_score).is_lt()
9289                    || (final_score.total_cmp(&after.final_score).is_eq() && *row_id > after.row_id)
9290            });
9291        }
9292        let projection_started = std::time::Instant::now();
9293        let sentinel = projection
9294            .first()
9295            .copied()
9296            .or_else(|| self.schema.columns.first().map(|column| column.id));
9297        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9298        let mut out = Vec::with_capacity(request.limit.min(ranked.len()));
9299        let mut projection_rows = 0usize;
9300        let mut projection_cells = 0usize;
9301        while out.len() < request.limit && !ranked.is_empty() {
9302            if let Some(context) = context {
9303                context.checkpoint()?;
9304                context.consume(ranked.len())?;
9305            }
9306            let needed = request.limit - out.len();
9307            let window_size = ranked
9308                .len()
9309                .min(needed.saturating_mul(2).max(needed.saturating_add(8)));
9310            let selection_started = std::time::Instant::now();
9311            let mut remainder = if ranked.len() > window_size {
9312                let (_, _, _) = ranked.select_nth_unstable_by(window_size, order);
9313                ranked.split_off(window_size)
9314            } else {
9315                Vec::new()
9316            };
9317            ranked.sort_by(order);
9318            fusion_nanos =
9319                fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9320            let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9321            let gathered_columns = projection.len().max(usize::from(sentinel.is_some()));
9322            if let Some(context) = context {
9323                context.consume(row_ids.len().saturating_mul(gathered_columns))?;
9324            }
9325            projection_rows = projection_rows.saturating_add(row_ids.len());
9326            projection_cells =
9327                projection_cells.saturating_add(row_ids.len().saturating_mul(gathered_columns));
9328            let mut cells: std::collections::HashMap<RowId, std::collections::HashMap<u16, Value>> =
9329                std::collections::HashMap::new();
9330            if let Some(column_id) = sentinel {
9331                for (row_id, value) in self.values_for_rids_batch_at_with_context(
9332                    &row_ids, column_id, snapshot, query_now, context,
9333                )? {
9334                    cells.entry(row_id).or_default().insert(column_id, value);
9335                }
9336            }
9337            for &column_id in &projection {
9338                if Some(column_id) == sentinel {
9339                    continue;
9340                }
9341                for (row_id, value) in self.values_for_rids_batch_at_with_context(
9342                    &row_ids, column_id, snapshot, query_now, context,
9343                )? {
9344                    cells.entry(row_id).or_default().insert(column_id, value);
9345                }
9346            }
9347            for (row_id, fused_score, mut components, exact_rerank_score, final_score) in
9348                ranked.drain(..)
9349            {
9350                let Some(row_cells) = cells.remove(&row_id) else {
9351                    continue;
9352                };
9353                components.sort_by(|a, b| a.retriever_name.cmp(&b.retriever_name));
9354                let final_rank = rank_offset.saturating_add(out.len()).saturating_add(1);
9355                out.push(SearchHit {
9356                    row_id,
9357                    cells: projection
9358                        .iter()
9359                        .filter_map(|column_id| {
9360                            row_cells
9361                                .get(column_id)
9362                                .cloned()
9363                                .map(|value| (*column_id, value))
9364                        })
9365                        .collect(),
9366                    components,
9367                    fused_score,
9368                    exact_rerank_score,
9369                    final_score,
9370                    final_rank,
9371                });
9372                if out.len() == request.limit {
9373                    break;
9374                }
9375            }
9376            ranked.append(&mut remainder);
9377        }
9378        crate::trace::QueryTrace::record(|trace| {
9379            trace.union_size = union_size;
9380            trace.fusion_nanos = trace.fusion_nanos.saturating_add(fusion_nanos);
9381            trace.projection_nanos = trace
9382                .projection_nanos
9383                .saturating_add(projection_started.elapsed().as_nanos() as u64);
9384            trace.total_nanos = trace
9385                .total_nanos
9386                .saturating_add(total_started.elapsed().as_nanos() as u64);
9387            trace.projection_rows = trace.projection_rows.saturating_add(projection_rows);
9388            trace.projection_cells = trace.projection_cells.saturating_add(projection_cells);
9389            if let Some(context) = context {
9390                trace.work_consumed = trace.work_consumed.saturating_add(context.consumed_work());
9391            }
9392        });
9393        Ok(out)
9394    }
9395
9396    /// MinHash candidate generation followed by exact Jaccard verification.
9397    /// An empty query set returns no hits.
9398    pub fn set_similarity(
9399        &mut self,
9400        request: &crate::query::SetSimilarityRequest,
9401    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9402        self.set_similarity_with_allowed(request, None)
9403    }
9404
9405    pub fn set_similarity_at(
9406        &mut self,
9407        request: &crate::query::SetSimilarityRequest,
9408        snapshot: Snapshot,
9409        allowed: Option<&std::collections::HashSet<RowId>>,
9410    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9411        self.set_similarity_explained_at(request, snapshot, allowed)
9412            .map(|(hits, _)| hits)
9413    }
9414
9415    /// Binary ANN candidate generation followed by exact float-vector reranking.
9416    pub fn ann_rerank(
9417        &mut self,
9418        request: &crate::query::AnnRerankRequest,
9419    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9420        self.ann_rerank_with_allowed(request, None)
9421    }
9422
9423    pub fn ann_rerank_with_allowed(
9424        &mut self,
9425        request: &crate::query::AnnRerankRequest,
9426        allowed: Option<&std::collections::HashSet<RowId>>,
9427    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9428        self.ann_rerank_at(request, self.snapshot(), allowed)
9429    }
9430
9431    pub fn ann_rerank_at(
9432        &mut self,
9433        request: &crate::query::AnnRerankRequest,
9434        snapshot: Snapshot,
9435        allowed: Option<&std::collections::HashSet<RowId>>,
9436    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9437        self.ann_rerank_at_with_context(request, snapshot, allowed, None)
9438    }
9439
9440    pub fn ann_rerank_at_with_context(
9441        &mut self,
9442        request: &crate::query::AnnRerankRequest,
9443        snapshot: Snapshot,
9444        allowed: Option<&std::collections::HashSet<RowId>>,
9445        context: Option<&crate::query::AiExecutionContext>,
9446    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9447        self.ensure_indexes_complete()?;
9448        self.ann_rerank_at_with_filters_and_context(request, snapshot, allowed, None, context)
9449    }
9450
9451    pub fn ann_rerank_at_with_candidate_authorization_and_context(
9452        &mut self,
9453        request: &crate::query::AnnRerankRequest,
9454        snapshot: Snapshot,
9455        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9456        context: Option<&crate::query::AiExecutionContext>,
9457    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9458        self.ensure_indexes_complete()?;
9459        self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9460    }
9461
9462    #[doc(hidden)]
9463    pub fn ann_rerank_at_with_candidate_authorization_on_generation(
9464        &self,
9465        request: &crate::query::AnnRerankRequest,
9466        snapshot: Snapshot,
9467        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9468        context: Option<&crate::query::AiExecutionContext>,
9469    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9470        self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9471    }
9472
9473    fn ann_rerank_at_with_filters_and_context(
9474        &self,
9475        request: &crate::query::AnnRerankRequest,
9476        snapshot: Snapshot,
9477        allowed: Option<&std::collections::HashSet<RowId>>,
9478        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9479        context: Option<&crate::query::AiExecutionContext>,
9480    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9481        use crate::query::{
9482            AnnCandidateDistance, AnnRerankHit, Retriever, RetrieverScore, VectorMetric,
9483            MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9484        };
9485        if request.candidate_k == 0 || request.limit == 0 {
9486            return Err(MongrelError::InvalidArgument(
9487                "candidate_k and limit must be > 0".into(),
9488            ));
9489        }
9490        if request.candidate_k > MAX_RETRIEVER_K || request.limit > MAX_FINAL_LIMIT {
9491            return Err(MongrelError::InvalidArgument(format!(
9492                "candidate_k must be <= {MAX_RETRIEVER_K} and limit <= {MAX_FINAL_LIMIT}"
9493            )));
9494        }
9495        let retriever = Retriever::Ann {
9496            column_id: request.column_id,
9497            query: request.query.clone(),
9498            k: request.candidate_k,
9499        };
9500        self.require_select()?;
9501        self.validate_retriever(&retriever)?;
9502        let hits = self.retrieve_filtered(
9503            &retriever,
9504            snapshot,
9505            None,
9506            allowed,
9507            candidate_authorization,
9508            context,
9509        )?;
9510        let distances: std::collections::HashMap<_, _> = hits
9511            .iter()
9512            .filter_map(|hit| match hit.score {
9513                RetrieverScore::AnnHammingDistance(distance) => {
9514                    Some((hit.row_id, AnnCandidateDistance::Hamming(distance)))
9515                }
9516                RetrieverScore::AnnCosineDistance(distance) => {
9517                    Some((hit.row_id, AnnCandidateDistance::Cosine(distance)))
9518                }
9519                _ => None,
9520            })
9521            .collect();
9522        let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9523        if let Some(context) = context {
9524            context.consume(row_ids.len())?;
9525        }
9526        let gather_started = std::time::Instant::now();
9527        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9528        let values = self.values_for_rids_batch_at_with_context(
9529            &row_ids,
9530            request.column_id,
9531            snapshot,
9532            query_now,
9533            context,
9534        )?;
9535        let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9536        let score_started = std::time::Instant::now();
9537        let vector_work =
9538            crate::query::work_units(request.query.len(), crate::query::VECTOR_WORK_QUANTUM);
9539        let query_norm = if matches!(request.metric, VectorMetric::Cosine) {
9540            if let Some(context) = context {
9541                context.consume(vector_work)?;
9542            }
9543            request
9544                .query
9545                .iter()
9546                .map(|value| f64::from(*value).powi(2))
9547                .sum::<f64>()
9548                .sqrt()
9549        } else {
9550            0.0
9551        };
9552        let mut reranked = Vec::with_capacity(values.len().min(request.limit));
9553        for (row_id, value) in values {
9554            if let Some(meta) = value.generated_embedding_metadata() {
9555                if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9556                    continue;
9557                }
9558            }
9559            let Some(vector) = value.as_embedding() else {
9560                continue;
9561            };
9562            let exact_score = match request.metric {
9563                VectorMetric::DotProduct => {
9564                    if let Some(context) = context {
9565                        context.consume(vector_work)?;
9566                    }
9567                    request
9568                        .query
9569                        .iter()
9570                        .zip(vector)
9571                        .map(|(left, right)| f64::from(*left) * f64::from(*right))
9572                        .sum::<f64>()
9573                }
9574                VectorMetric::Cosine => {
9575                    if let Some(context) = context {
9576                        context.consume(vector_work.saturating_mul(2))?;
9577                    }
9578                    let dot = request
9579                        .query
9580                        .iter()
9581                        .zip(vector)
9582                        .map(|(left, right)| f64::from(*left) * f64::from(*right))
9583                        .sum::<f64>();
9584                    let norm = vector
9585                        .iter()
9586                        .map(|value| f64::from(*value).powi(2))
9587                        .sum::<f64>()
9588                        .sqrt();
9589                    if query_norm == 0.0 || norm == 0.0 {
9590                        0.0
9591                    } else {
9592                        dot / (query_norm * norm)
9593                    }
9594                }
9595                VectorMetric::Euclidean => {
9596                    if let Some(context) = context {
9597                        context.consume(vector_work)?;
9598                    }
9599                    request
9600                        .query
9601                        .iter()
9602                        .zip(vector)
9603                        .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9604                        .sum::<f64>()
9605                        .sqrt()
9606                }
9607            };
9608            let exact_score = exact_score as f32;
9609            if !exact_score.is_finite() {
9610                return Err(MongrelError::InvalidArgument(
9611                    "exact ANN score must be finite".into(),
9612                ));
9613            }
9614            let Some(candidate_distance) = distances.get(&row_id).copied() else {
9615                continue;
9616            };
9617            reranked.push(AnnRerankHit {
9618                row_id,
9619                candidate_distance,
9620                exact_score,
9621            });
9622        }
9623        reranked.sort_by(|left, right| {
9624            let score = match request.metric {
9625                VectorMetric::Euclidean => left.exact_score.total_cmp(&right.exact_score),
9626                VectorMetric::Cosine | VectorMetric::DotProduct => {
9627                    right.exact_score.total_cmp(&left.exact_score)
9628                }
9629            };
9630            score.then_with(|| left.row_id.cmp(&right.row_id))
9631        });
9632        reranked.truncate(request.limit);
9633        crate::trace::QueryTrace::record(|trace| {
9634            trace.exact_vector_gather_nanos =
9635                trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9636            trace.exact_vector_score_nanos = trace
9637                .exact_vector_score_nanos
9638                .saturating_add(score_started.elapsed().as_nanos() as u64);
9639        });
9640        Ok(reranked)
9641    }
9642
9643    pub fn set_similarity_with_allowed(
9644        &mut self,
9645        request: &crate::query::SetSimilarityRequest,
9646        allowed: Option<&std::collections::HashSet<RowId>>,
9647    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9648        self.set_similarity_explained_at(request, self.snapshot(), allowed)
9649            .map(|(hits, _)| hits)
9650    }
9651
9652    pub fn set_similarity_explained(
9653        &mut self,
9654        request: &crate::query::SetSimilarityRequest,
9655    ) -> Result<(
9656        Vec<crate::query::SetSimilarityHit>,
9657        crate::query::SetSimilarityTrace,
9658    )> {
9659        self.set_similarity_explained_at(request, self.snapshot(), None)
9660    }
9661
9662    fn set_similarity_explained_at(
9663        &mut self,
9664        request: &crate::query::SetSimilarityRequest,
9665        snapshot: Snapshot,
9666        allowed: Option<&std::collections::HashSet<RowId>>,
9667    ) -> Result<(
9668        Vec<crate::query::SetSimilarityHit>,
9669        crate::query::SetSimilarityTrace,
9670    )> {
9671        self.ensure_indexes_complete()?;
9672        self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, None)
9673    }
9674
9675    pub fn set_similarity_at_with_context(
9676        &mut self,
9677        request: &crate::query::SetSimilarityRequest,
9678        snapshot: Snapshot,
9679        allowed: Option<&std::collections::HashSet<RowId>>,
9680        context: Option<&crate::query::AiExecutionContext>,
9681    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9682        self.ensure_indexes_complete()?;
9683        self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, context)
9684            .map(|(hits, _)| hits)
9685    }
9686
9687    pub fn set_similarity_at_with_candidate_authorization_and_context(
9688        &mut self,
9689        request: &crate::query::SetSimilarityRequest,
9690        snapshot: Snapshot,
9691        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9692        context: Option<&crate::query::AiExecutionContext>,
9693    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9694        self.ensure_indexes_complete()?;
9695        self.set_similarity_explained_at_with_context(
9696            request,
9697            snapshot,
9698            None,
9699            authorization,
9700            context,
9701        )
9702        .map(|(hits, _)| hits)
9703    }
9704
9705    #[doc(hidden)]
9706    pub fn set_similarity_at_with_candidate_authorization_on_generation(
9707        &self,
9708        request: &crate::query::SetSimilarityRequest,
9709        snapshot: Snapshot,
9710        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9711        context: Option<&crate::query::AiExecutionContext>,
9712    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9713        self.set_similarity_explained_at_with_context(
9714            request,
9715            snapshot,
9716            None,
9717            authorization,
9718            context,
9719        )
9720        .map(|(hits, _)| hits)
9721    }
9722
9723    fn set_similarity_explained_at_with_context(
9724        &self,
9725        request: &crate::query::SetSimilarityRequest,
9726        snapshot: Snapshot,
9727        allowed: Option<&std::collections::HashSet<RowId>>,
9728        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9729        context: Option<&crate::query::AiExecutionContext>,
9730    ) -> Result<(
9731        Vec<crate::query::SetSimilarityHit>,
9732        crate::query::SetSimilarityTrace,
9733    )> {
9734        use crate::query::{
9735            Retriever, RetrieverScore, SetSimilarityHit, MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9736            MAX_SET_MEMBERS,
9737        };
9738        let mut trace = crate::query::SetSimilarityTrace::default();
9739        if request.members.is_empty() {
9740            return Ok((Vec::new(), trace));
9741        }
9742        if request.candidate_k == 0 || request.limit == 0 {
9743            return Err(MongrelError::InvalidArgument(
9744                "candidate_k and limit must be > 0".into(),
9745            ));
9746        }
9747        if request.candidate_k > MAX_RETRIEVER_K
9748            || request.limit > MAX_FINAL_LIMIT
9749            || request.members.len() > MAX_SET_MEMBERS
9750        {
9751            return Err(MongrelError::InvalidArgument(format!(
9752                "candidate_k must be <= {MAX_RETRIEVER_K}, limit <= {MAX_FINAL_LIMIT}, and members <= {MAX_SET_MEMBERS}"
9753            )));
9754        }
9755        if !request.min_jaccard.is_finite() || !(0.0..=1.0).contains(&request.min_jaccard) {
9756            return Err(MongrelError::InvalidArgument(
9757                "min_jaccard must be finite and between 0 and 1".into(),
9758            ));
9759        }
9760        let started = std::time::Instant::now();
9761        let retriever = Retriever::MinHash {
9762            column_id: request.column_id,
9763            members: request.members.clone(),
9764            k: request.candidate_k,
9765        };
9766        self.require_select()?;
9767        self.validate_retriever(&retriever)?;
9768        let hits = self.retrieve_filtered(
9769            &retriever,
9770            snapshot,
9771            None,
9772            allowed,
9773            candidate_authorization,
9774            context,
9775        )?;
9776        trace.candidate_generation_us = started.elapsed().as_micros() as u64;
9777        trace.candidate_count = hits.len();
9778        let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9779        if let Some(context) = context {
9780            context.consume(row_ids.len())?;
9781        }
9782        let started = std::time::Instant::now();
9783        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9784        let values = self.values_for_rids_batch_at_with_context(
9785            &row_ids,
9786            request.column_id,
9787            snapshot,
9788            query_now,
9789            context,
9790        )?;
9791        trace.gather_us = started.elapsed().as_micros() as u64;
9792        if let Some(context) = context {
9793            context.consume(request.members.len())?;
9794        }
9795        let query: std::collections::HashSet<_> = request.members.iter().cloned().collect();
9796        let estimates: std::collections::HashMap<_, _> = hits
9797            .into_iter()
9798            .filter_map(|hit| match hit.score {
9799                RetrieverScore::MinHashEstimatedJaccard(score) => Some((hit.row_id, score)),
9800                _ => None,
9801            })
9802            .collect();
9803        let started = std::time::Instant::now();
9804        let mut parsed = Vec::with_capacity(values.len());
9805        for (row_id, value) in values {
9806            let Value::Bytes(bytes) = value else {
9807                continue;
9808            };
9809            if let Some(context) = context {
9810                context.consume(crate::query::work_units(
9811                    bytes.len(),
9812                    crate::query::PARSE_WORK_QUANTUM,
9813                ))?;
9814            }
9815            let Ok(serde_json::Value::Array(members)) = serde_json::from_slice(&bytes) else {
9816                continue;
9817            };
9818            if let Some(context) = context {
9819                context.consume(members.len())?;
9820            }
9821            let stored = members
9822                .into_iter()
9823                .filter_map(|member| match member {
9824                    serde_json::Value::String(value) => {
9825                        Some(crate::query::SetMember::String(value))
9826                    }
9827                    serde_json::Value::Number(value) => {
9828                        Some(crate::query::SetMember::Number(value))
9829                    }
9830                    serde_json::Value::Bool(value) => Some(crate::query::SetMember::Boolean(value)),
9831                    _ => None,
9832                })
9833                .collect::<std::collections::HashSet<_>>();
9834            parsed.push((row_id, stored));
9835        }
9836        trace.parse_us = started.elapsed().as_micros() as u64;
9837        trace.verified_count = parsed.len();
9838        let started = std::time::Instant::now();
9839        let mut exact = Vec::new();
9840        for (row_id, stored) in parsed {
9841            if let Some(context) = context {
9842                context.consume(query.len().saturating_add(stored.len()))?;
9843            }
9844            let union = query.union(&stored).count();
9845            let score = if union == 0 {
9846                1.0
9847            } else {
9848                query.intersection(&stored).count() as f32 / union as f32
9849            };
9850            if score >= request.min_jaccard {
9851                exact.push(SetSimilarityHit {
9852                    row_id,
9853                    estimated_jaccard: estimates.get(&row_id).copied().unwrap_or_default(),
9854                    exact_jaccard: score,
9855                });
9856            }
9857        }
9858        exact.sort_by(|a, b| {
9859            b.exact_jaccard
9860                .total_cmp(&a.exact_jaccard)
9861                .then_with(|| a.row_id.cmp(&b.row_id))
9862        });
9863        exact.truncate(request.limit);
9864        trace.score_us = started.elapsed().as_micros() as u64;
9865        crate::trace::QueryTrace::record(|query_trace| {
9866            query_trace.exact_set_gather_nanos = query_trace
9867                .exact_set_gather_nanos
9868                .saturating_add(trace.gather_us.saturating_mul(1_000));
9869            query_trace.exact_set_parse_nanos = query_trace
9870                .exact_set_parse_nanos
9871                .saturating_add(trace.parse_us.saturating_mul(1_000));
9872            query_trace.exact_set_score_nanos = query_trace
9873                .exact_set_score_nanos
9874                .saturating_add(trace.score_us.saturating_mul(1_000));
9875        });
9876        Ok((exact, trace))
9877    }
9878
9879    /// Fetch one column for visible row ids without decoding unrelated columns.
9880    fn values_for_rids_batch_at(
9881        &self,
9882        row_ids: &[u64],
9883        column_id: u16,
9884        snapshot: Snapshot,
9885        now: i64,
9886    ) -> Result<Vec<(RowId, Value)>> {
9887        if self.ttl.is_none()
9888            && self.memtable.is_empty()
9889            && self.mutable_run.is_empty()
9890            && self.run_refs.len() == 1
9891        {
9892            let mut reader = self.open_reader(self.run_refs[0].run_id)?;
9893            // Small projections should not decode and scan the run's entire
9894            // row-id column. Resolve each requested row through the page-pruned
9895            // point path until a full visibility pass becomes cheaper. Keep
9896            // this crossover aligned with `rows_for_rids_at_time`.
9897            if row_ids.len().saturating_mul(24) < reader.row_count() {
9898                let mut values = Vec::with_capacity(row_ids.len());
9899                for &raw_row_id in row_ids {
9900                    let row_id = RowId(raw_row_id);
9901                    if let Some((_, false, Some(value))) =
9902                        reader.get_version_column_at(row_id, snapshot, column_id)?
9903                    {
9904                        values.push((row_id, value));
9905                    }
9906                }
9907                return Ok(values);
9908            }
9909            let (positions, visible_row_ids) = reader.visible_positions_with_rids_at(snapshot)?;
9910            let requested: Vec<(RowId, usize)> = row_ids
9911                .iter()
9912                .filter_map(|raw| {
9913                    visible_row_ids
9914                        .binary_search(&(*raw as i64))
9915                        .ok()
9916                        .map(|index| (RowId(*raw), positions[index]))
9917                })
9918                .collect();
9919            let values = reader.gather_column(
9920                column_id,
9921                &requested
9922                    .iter()
9923                    .map(|(_, position)| *position)
9924                    .collect::<Vec<_>>(),
9925            )?;
9926            return Ok(requested
9927                .into_iter()
9928                .zip(values)
9929                .map(|((row_id, _), value)| (row_id, value))
9930                .collect());
9931        }
9932        self.values_for_rids_at(row_ids, column_id, snapshot, now)
9933    }
9934
9935    fn values_for_rids_batch_at_with_context(
9936        &self,
9937        row_ids: &[u64],
9938        column_id: u16,
9939        snapshot: Snapshot,
9940        now: i64,
9941        context: Option<&crate::query::AiExecutionContext>,
9942    ) -> Result<Vec<(RowId, Value)>> {
9943        let Some(context) = context else {
9944            return self.values_for_rids_batch_at(row_ids, column_id, snapshot, now);
9945        };
9946        let mut values = Vec::with_capacity(row_ids.len());
9947        for chunk in row_ids.chunks(256) {
9948            context.checkpoint()?;
9949            values.extend(self.values_for_rids_batch_at(chunk, column_id, snapshot, now)?);
9950        }
9951        Ok(values)
9952    }
9953
9954    /// Fetch one column for visible row ids without decoding unrelated columns.
9955    fn values_for_rids_at(
9956        &self,
9957        row_ids: &[u64],
9958        column_id: u16,
9959        snapshot: Snapshot,
9960        now: i64,
9961    ) -> Result<Vec<(RowId, Value)>> {
9962        let mut readers: Vec<_> = self
9963            .run_refs
9964            .iter()
9965            .map(|run| self.open_reader(run.run_id))
9966            .collect::<Result<_>>()?;
9967        let mut out = Vec::with_capacity(row_ids.len());
9968        for &raw_row_id in row_ids {
9969            let row_id = RowId(raw_row_id);
9970            let mem = self.memtable.get_version_at(row_id, snapshot);
9971            let mutable = self.mutable_run.get_version_at(row_id, snapshot);
9972            let overlay = match (mem, mutable) {
9973                (Some((_, a)), Some((_, b))) => Some(
9974                    if Snapshot::version_is_newer(
9975                        a.committed_epoch,
9976                        a.commit_ts,
9977                        b.committed_epoch,
9978                        b.commit_ts,
9979                    ) {
9980                        a
9981                    } else {
9982                        b
9983                    },
9984                ),
9985                (Some((_, value)), None) | (None, Some((_, value))) => Some(value),
9986                (None, None) => None,
9987            };
9988            if let Some(row) = overlay {
9989                if !row.deleted && !self.row_expired_at(&row, now) {
9990                    if let Some(value) = row.columns.get(&column_id) {
9991                        out.push((row_id, value.clone()));
9992                    }
9993                }
9994                continue;
9995            }
9996
9997            // REM-001: keep `commit_ts` on the cross-run candidate so the winner is
9998            // selected under full HLC authority instead of the legacy epoch-only
9999            // tuple. The metadata-preserving `get_version_column_full_at`
10000            // returns a `VersionedColumnValue` (stamp, deleted, value).
10001            let mut best: Option<(crate::sorted_run::VersionedColumnValue, usize)> = None;
10002            for (index, reader) in readers.iter_mut().enumerate() {
10003                if let Some(versioned) =
10004                    reader.get_version_column_full_at(row_id, snapshot, column_id)?
10005                {
10006                    if best
10007                        .as_ref()
10008                        .map(|(current, _)| versioned.stamp.is_newer_than(current.stamp))
10009                        .unwrap_or(true)
10010                    {
10011                        best = Some((versioned, index));
10012                    }
10013                }
10014            }
10015            let Some((candidate, reader_index)) = best else {
10016                continue;
10017            };
10018            if candidate.deleted {
10019                continue;
10020            }
10021            let Some(value) = candidate.value.clone() else {
10022                continue;
10023            };
10024            if let Some(ttl) = self.ttl {
10025                if ttl.column_id != column_id {
10026                    if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
10027                        row_id,
10028                        snapshot,
10029                        ttl.column_id,
10030                    )? {
10031                        if let Some(Value::Int64(timestamp)) = ttl_value.value {
10032                            if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10033                                continue;
10034                            }
10035                        }
10036                    }
10037                } else if let Value::Int64(timestamp) = &value {
10038                    if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10039                        continue;
10040                    }
10041                }
10042            }
10043            out.push((row_id, value));
10044        }
10045        Ok(out)
10046    }
10047
10048    /// Materialize the MVCC-visible, non-deleted rows for `rids` at `snapshot`,
10049    /// preserving the input order. Rows whose newest visible version is a
10050    /// tombstone, or that no longer exist, are omitted. Shared by index-served
10051    /// [`query`] and the Phase 8.1 FK-join path.
10052    pub fn rows_for_rids(&self, rids: &[u64], snapshot: Snapshot) -> Result<Vec<Row>> {
10053        self.rows_for_rids_at_time(rids, snapshot, unix_nanos_now(), None)
10054    }
10055
10056    pub fn rows_for_rids_with_context(
10057        &self,
10058        rids: &[u64],
10059        snapshot: Snapshot,
10060        context: &crate::query::AiExecutionContext,
10061    ) -> Result<Vec<Row>> {
10062        context.consume(rids.len().saturating_mul(self.schema.columns.len()))?;
10063        self.rows_for_rids_at_time(rids, snapshot, context.query_time_nanos(), None)
10064    }
10065
10066    fn rows_for_rids_at_time(
10067        &self,
10068        rids: &[u64],
10069        snapshot: Snapshot,
10070        ttl_now: i64,
10071        control: Option<&crate::ExecutionControl>,
10072    ) -> Result<Vec<Row>> {
10073        use std::collections::HashMap;
10074        let mut rows = Vec::with_capacity(rids.len());
10075        // Overlay (memtable + mutable-run) newest visible version per rid —
10076        // these shadow any stale version stored in a run. Prefer HLC order via
10077        // version_is_newer when stamps are present (P0.5-T3).
10078        //
10079        // `rids` is already index-resolved (the caller's condition set), so it
10080        // is normally tiny relative to the memtable/mutable-run tiers — a
10081        // single-row PK/unique check feeding insert/update/delete resolves to
10082        // 0 or 1 rid. Materializing every version in both tiers (the old
10083        // behavior) cost O(tier size) regardless, which meant an unrelated
10084        // full-table-sized scan (plus the drop cost of the resulting map) on
10085        // every point lookup once the table grew large. Below the crossover,
10086        // a direct per-rid probe (`get_version_at`) wins; once `rids` approaches
10087        // tier size, one linear materializing pass beats `rids.len()` separate
10088        // probes, so fall back to it.
10089        let tier_size = self.memtable.len() + self.mutable_run.len();
10090        let mut overlay: HashMap<u64, Row> = HashMap::with_capacity(rids.len());
10091        if rids.len().saturating_mul(24) < tier_size {
10092            for &rid in rids {
10093                if overlay.len() & 255 == 0 {
10094                    control
10095                        .map(crate::ExecutionControl::checkpoint)
10096                        .transpose()?;
10097                }
10098                let mem = self.memtable.get_version_at(RowId(rid), snapshot);
10099                let mrun = self.mutable_run.get_version_at(RowId(rid), snapshot);
10100                let newest = match (mem, mrun) {
10101                    (Some((_, mr)), Some((_, rr))) => Some(
10102                        if Snapshot::version_is_newer(
10103                            mr.committed_epoch,
10104                            mr.commit_ts,
10105                            rr.committed_epoch,
10106                            rr.commit_ts,
10107                        ) {
10108                            mr
10109                        } else {
10110                            rr
10111                        },
10112                    ),
10113                    (Some((_, mr)), None) => Some(mr),
10114                    (None, Some((_, rr))) => Some(rr),
10115                    (None, None) => None,
10116                };
10117                if let Some(row) = newest {
10118                    overlay.insert(rid, row);
10119                }
10120            }
10121        } else {
10122            let fold_newest = |row: Row, overlay: &mut HashMap<u64, Row>| {
10123                overlay
10124                    .entry(row.row_id.0)
10125                    .and_modify(|e| {
10126                        if Snapshot::version_is_newer(
10127                            row.committed_epoch,
10128                            row.commit_ts,
10129                            e.committed_epoch,
10130                            e.commit_ts,
10131                        ) {
10132                            *e = row.clone();
10133                        }
10134                    })
10135                    .or_insert(row);
10136            };
10137            for (index, row) in self
10138                .memtable
10139                .visible_versions_at(snapshot)
10140                .into_iter()
10141                .enumerate()
10142            {
10143                if index & 255 == 0 {
10144                    control
10145                        .map(crate::ExecutionControl::checkpoint)
10146                        .transpose()?;
10147                }
10148                fold_newest(row, &mut overlay);
10149            }
10150            for (index, row) in self
10151                .mutable_run
10152                .visible_versions_at(snapshot)
10153                .into_iter()
10154                .enumerate()
10155            {
10156                if index & 255 == 0 {
10157                    control
10158                        .map(crate::ExecutionControl::checkpoint)
10159                        .transpose()?;
10160                }
10161                fold_newest(row, &mut overlay);
10162            }
10163        }
10164        if self.run_refs.len() == 1 {
10165            let mut reader = self.open_reader(self.run_refs[0].run_id)?;
10166            // Same crossover as the overlay above: `visible_positions_with_rids`
10167            // decodes/scans the run's *entire* row-id column regardless of
10168            // `rids.len()`, so a point lookup (0 or 1 rid, the common
10169            // insert/update/delete case) paid an O(run size) tax for a single
10170            // row. Below the crossover, `get_version`'s page-pruned lookup
10171            // (`SYS_ROW_ID` pages carry exact row-id bounds) resolves each rid
10172            // by decoding only its page, no whole-column decode.
10173            if rids.len().saturating_mul(24) < reader.row_count() {
10174                for (index, &rid) in rids.iter().enumerate() {
10175                    if index & 255 == 0 {
10176                        control
10177                            .map(crate::ExecutionControl::checkpoint)
10178                            .transpose()?;
10179                    }
10180                    if let Some(r) = overlay.get(&rid) {
10181                        if !r.deleted {
10182                            rows.push(r.clone());
10183                        }
10184                        continue;
10185                    }
10186                    if let Some((_, row)) = reader.get_version_at(RowId(rid), snapshot)? {
10187                        if !row.deleted {
10188                            rows.push(row);
10189                        }
10190                    }
10191                }
10192                rows.retain(|row| !self.row_expired_at(row, ttl_now));
10193                return Ok(rows);
10194            }
10195            // Phase 16.3b: decode the system columns ONCE (via the clean-run-
10196            // shortcut visibility pass) and binary-search each requested rid,
10197            // instead of `get_version`-per-rid which re-decoded + cloned the
10198            // full system columns on every call (the ~350 ms native-query tax).
10199            // Phase 16.3b finish: batch the survivor positions into ONE
10200            // `materialize_batch` call so user columns are decoded once each via
10201            // the typed, page-cached path (not a per-rid `Vec<Value>` decode +
10202            // `.cloned()`).
10203            let (positions, vis_rids) = reader.visible_positions_with_rids_at(snapshot)?;
10204            // First pass: classify each input rid (overlay / run position /
10205            // not-found), recording the run positions to fetch in input order.
10206            enum Src {
10207                Overlay,
10208                Run,
10209            }
10210            let mut plan: Vec<Src> = Vec::with_capacity(rids.len());
10211            let mut fetch: Vec<usize> = Vec::with_capacity(rids.len());
10212            for (index, rid) in rids.iter().enumerate() {
10213                if index & 255 == 0 {
10214                    control
10215                        .map(crate::ExecutionControl::checkpoint)
10216                        .transpose()?;
10217                }
10218                if overlay.contains_key(rid) {
10219                    plan.push(Src::Overlay);
10220                    continue;
10221                }
10222                match vis_rids.binary_search(&(*rid as i64)) {
10223                    Ok(i) => {
10224                        plan.push(Src::Run);
10225                        fetch.push(positions[i]);
10226                    }
10227                    Err(_) => { /* not found — omitted from output */ }
10228                }
10229            }
10230            let fetched = reader.materialize_batch(&fetch)?;
10231            let mut fetched_iter = fetched.into_iter();
10232            for (index, (rid, src)) in rids.iter().zip(plan).enumerate() {
10233                if index & 255 == 0 {
10234                    control
10235                        .map(crate::ExecutionControl::checkpoint)
10236                        .transpose()?;
10237                }
10238                match src {
10239                    Src::Overlay => {
10240                        if let Some(r) = overlay.get(rid) {
10241                            if !r.deleted {
10242                                rows.push(r.clone());
10243                            }
10244                        }
10245                    }
10246                    Src::Run => {
10247                        if let Some(row) = fetched_iter.next() {
10248                            if !row.deleted {
10249                                rows.push(row);
10250                            }
10251                        }
10252                    }
10253                }
10254            }
10255            rows.retain(|row| !self.row_expired_at(row, ttl_now));
10256            return Ok(rows);
10257        }
10258        // Multi-run: one reader per run; newest visible version across all runs
10259        // + the overlay. (Per-rid `get_version` here is unavoidable without a
10260        // cross-run merge, but multi-run is the uncommon cold case.)
10261        let mut readers: Vec<_> = self
10262            .run_refs
10263            .iter()
10264            .map(|rr| self.open_reader(rr.run_id))
10265            .collect::<Result<Vec<_>>>()?;
10266        for (index, rid) in rids.iter().enumerate() {
10267            if index & 255 == 0 {
10268                control
10269                    .map(crate::ExecutionControl::checkpoint)
10270                    .transpose()?;
10271            }
10272            if let Some(r) = overlay.get(rid) {
10273                if !r.deleted {
10274                    rows.push(r.clone());
10275                }
10276                continue;
10277            }
10278            // REM-001: keep the full VersionStamp so the cross-run fold uses HLC
10279            // authority when both candidates are stamped (the legacy
10280            // `(epoch, _)` tuple discarded `commit_ts` and let a higher-epoch
10281            // run silently outrank an HLC-newer run).
10282            let mut best: Option<(VersionStamp, Row)> = None;
10283            for reader in readers.iter_mut() {
10284                if let Ok(Some((stamp, row))) = reader.get_version_stamp_at(RowId(*rid), snapshot) {
10285                    if best
10286                        .as_ref()
10287                        .map(|(current, _)| stamp.is_newer_than(*current))
10288                        .unwrap_or(true)
10289                    {
10290                        best = Some((stamp, row));
10291                    }
10292                }
10293            }
10294            if let Some((_, r)) = best {
10295                if !r.deleted {
10296                    rows.push(r);
10297                }
10298            }
10299        }
10300        rows.retain(|row| !self.row_expired_at(row, ttl_now));
10301        Ok(rows)
10302    }
10303
10304    /// Resolve the referencing (FK) side of a primary-key ↔ foreign-key join as
10305    /// a row-id set (Phase 8.1): union the roaring-bitmap entries of
10306    /// `fk_column_id` for every value in `pk_values` — the surviving
10307    /// primary-key values — then intersect with `fk_conditions`, i.e. any
10308    /// FK-side predicates (`ann_search ∩ fm_contains`, bitmap equality, range,
10309    /// …). Returns the survivor row-ids ascending. Requires a bitmap index on
10310    /// `fk_column_id`; returns an empty set when there is none.
10311    /// Whether live indexes are complete (Phase 14.7 + 17.2: the broadcast
10312    /// join path checks this before using the HOT index).
10313    pub fn indexes_complete(&self) -> bool {
10314        self.indexes_complete
10315    }
10316
10317    /// Where bulk loads put the index-build cost (see [`IndexBuildPolicy`]).
10318    pub fn index_build_policy(&self) -> IndexBuildPolicy {
10319        self.index_build_policy
10320    }
10321
10322    /// Set the bulk-load index-build policy. Takes effect on the next
10323    /// `bulk_load` / `bulk_load_columns` / `bulk_load_fast`; never changes
10324    /// already-built indexes.
10325    pub fn set_index_build_policy(&mut self, policy: IndexBuildPolicy) {
10326        self.index_build_policy = policy;
10327    }
10328
10329    /// Phase 17.2: broadcast join — return the distinct values in this table's
10330    /// bitmap index for `column_id` that also exist as a key in `pk_db`'s HOT
10331    /// index. Avoids loading the entire PK table when the FK column has low
10332    /// cardinality. Returns `None` if no bitmap index exists for the column.
10333    pub fn broadcast_join_values(&self, column_id: u16, pk_db: &Table) -> Option<Vec<Vec<u8>>> {
10334        // A deferred bulk load leaves the bitmap unbuilt — its (empty) key set
10335        // would silently produce an empty join. Decline; the caller falls back
10336        // to the PK-side query path, which completes indexes lazily.
10337        if !self.indexes_complete {
10338            return None;
10339        }
10340        let b = self.bitmap.get(&column_id)?;
10341        let result: Vec<Vec<u8>> = b
10342            .keys()
10343            .into_iter()
10344            .filter(|k| pk_db.hot.get(k.as_slice()).is_some())
10345            .collect();
10346        Some(result)
10347    }
10348
10349    pub fn fk_join_row_ids(
10350        &self,
10351        fk_column_id: u16,
10352        pk_values: &[Vec<u8>],
10353        fk_conditions: &[crate::query::Condition],
10354        snapshot: Snapshot,
10355    ) -> Result<Vec<u64>> {
10356        let Some(b) = self.bitmap.get(&fk_column_id) else {
10357            return Ok(Vec::new());
10358        };
10359        let mut join_set = {
10360            let mut acc = roaring::RoaringBitmap::new();
10361            for v in pk_values {
10362                acc |= b.get(v);
10363            }
10364            RowIdSet::from_roaring(acc)
10365        };
10366        if !fk_conditions.is_empty() {
10367            let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10368            sets.push(join_set);
10369            for c in fk_conditions {
10370                sets.push(self.resolve_condition(c, snapshot)?);
10371            }
10372            join_set = RowIdSet::intersect_many(sets);
10373        }
10374        Ok(join_set.into_sorted_vec())
10375    }
10376
10377    /// Like [`fk_join_row_ids`] but returns only the **cardinality** of the FK
10378    /// survivor set — without materializing or sorting it. For a bare
10379    /// `COUNT(*)` join with no FK-side filter this is O(1) on the bitmap union
10380    /// (Phase 17.4): the prior path built a `HashSet<u64>` + `Vec<u64>` +
10381    /// `sort_unstable` over up to N rows only to read `.len()`.
10382    pub fn fk_join_count(
10383        &self,
10384        fk_column_id: u16,
10385        pk_values: &[Vec<u8>],
10386        fk_conditions: &[crate::query::Condition],
10387        snapshot: Snapshot,
10388    ) -> Result<u64> {
10389        let Some(b) = self.bitmap.get(&fk_column_id) else {
10390            return Ok(0);
10391        };
10392        let mut acc = roaring::RoaringBitmap::new();
10393        for v in pk_values {
10394            acc |= b.get(v);
10395        }
10396        if fk_conditions.is_empty() {
10397            return Ok(acc.len());
10398        }
10399        let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10400        sets.push(RowIdSet::from_roaring(acc));
10401        for c in fk_conditions {
10402            sets.push(self.resolve_condition(c, snapshot)?);
10403        }
10404        Ok(RowIdSet::intersect_many(sets).len() as u64)
10405    }
10406
10407    /// Inspect the row at `rid` directly — without going through
10408    /// [`Self::get`] (which collapses tombstones and TTL-expired rows into
10409    /// `None`). Used by [`Self::resolve_pk_with_hot_fallback`] so the
10410    /// fallback reason can distinguish Tombstone from TtlExpired.
10411    fn inspect_row_at(&self, rid: RowId, snapshot: Snapshot) -> Option<crate::memtable::Row> {
10412        let mut best: Option<crate::memtable::Row> = None;
10413        let mut consider = |row: crate::memtable::Row| {
10414            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
10415                return;
10416            }
10417            if best.as_ref().is_none_or(|current| {
10418                Snapshot::version_is_newer(
10419                    row.committed_epoch,
10420                    row.commit_ts,
10421                    current.committed_epoch,
10422                    current.commit_ts,
10423                )
10424            }) {
10425                best = Some(row);
10426            }
10427        };
10428        if let Some((_, row)) = self.memtable.get_version_at(rid, snapshot) {
10429            consider(row);
10430        }
10431        if let Some((_, row)) = self.mutable_run.get_version_at(rid, snapshot) {
10432            consider(row);
10433        }
10434        for rr in &self.run_refs {
10435            if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
10436                if rid.0 < min_rid || rid.0 > max_rid {
10437                    continue;
10438                }
10439            }
10440            let Ok(mut reader) = self.open_reader(rr.run_id) else {
10441                continue;
10442            };
10443            // REM-001: route through the full-Snapshot run API so HLC-stamped
10444            // row versions are admitted by `observes_row` and recency selection
10445            // uses `commit_ts` instead of discarding it at the epoch boundary.
10446            let Ok(Some((_stamp, row))) = reader.get_version_stamp_at(rid, snapshot) else {
10447                continue;
10448            };
10449            consider(row);
10450        }
10451        best
10452    }
10453
10454    fn resolve_pk_with_hot_fallback(
10455        &self,
10456        pk_column_id: u16,
10457        lookup: &[u8],
10458        snapshot: Snapshot,
10459    ) -> Result<RowIdSet> {
10460        // Private WAL: the in-flight batch lands in the memtable at
10461        // `pending_epoch = visible + 1` (puts and matching tombstones). A
10462        // caller snapshot pinned at the *current* visible epoch predates
10463        // every pending write, so a PK lookup would resolve a just-replaced
10464        // PK to the stale pre-image (or resurrect a just-deleted row).
10465        // Advance to `pending_epoch` and let the batch participate — the
10466        // same read-your-writes rule as `eligible_candidate_ids` and
10467        // `range_scan_i64`. A strictly *historical* pinned snapshot is
10468        // honored as-is: the pending batch is uncommitted and must stay
10469        // invisible to it. Shared WAL tables keep the original snapshot
10470        // because their pending rows live in `pending_rows` and haven't
10471        // been materialised into the memtable yet.
10472        let snapshot = if self.is_shared()
10473            || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10474            || snapshot.epoch.0 != self.epoch.visible().0
10475        {
10476            snapshot
10477        } else {
10478            Snapshot::at(self.pending_epoch())
10479        };
10480        // Indexes incomplete: record `IndexIncomplete` and run the scanner
10481        // directly. The HOT map may be stale or absent, but the scanner's
10482        // result is still correct because it reads durable runs.
10483        if !self.indexes_complete {
10484            let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10485            self.record_hot_fallback_reason(crate::trace::HotFallbackReason::IndexIncomplete);
10486            return Ok(result);
10487        }
10488        // Step 1 — HOT hit attempt. Look up the mapped `RowId`; if absent,
10489        // delegate straight to the scanner (which classifies the reason).
10490        let mapped = self.hot.get(lookup);
10491        let Some(r) = mapped else {
10492            let (result, reason) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10493            self.record_hot_fallback_reason(reason);
10494            return Ok(result);
10495        };
10496        // Step 2 — historical snapshot: the HOT map is keyed on the latest
10497        // RowId, not the historical one. The historical branch records its
10498        // own reason and runs the scanner; the inner scanner is suppressed
10499        // from recording a second reason (see `pk_equality_fallback`).
10500        if snapshot.epoch < self.current_epoch() {
10501            self.record_hot_fallback_reason(crate::trace::HotFallbackReason::HistoricalSnapshot);
10502            let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10503            return Ok(result);
10504        }
10505        // Step 3 — materialize the mapped candidate and classify it.
10506        // `inspect_row_at` does not collapse TTL-expired rows into `None`,
10507        // so the inspection can distinguish Tombstone from TtlExpired.
10508        let materialized = self.inspect_row_at(r, snapshot);
10509        let now_nanos = unix_nanos_now();
10510        let inspection = crate::trace::inspect_hot_candidate(
10511            materialized.as_ref(),
10512            snapshot,
10513            self.ttl,
10514            now_nanos,
10515            pk_column_id,
10516            lookup,
10517            |row| {
10518                let pk_value = row.columns.get(&pk_column_id);
10519                pk_value
10520                    .map(|v| self.index_lookup_key(pk_column_id, v))
10521                    .unwrap_or_default()
10522            },
10523        );
10524        match inspection {
10525            crate::trace::HotCandidateInspection::Hit(row) => {
10526                self.lookup_metrics
10527                    .hot_lookup_hit
10528                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10529                crate::trace::QueryTrace::record(|t| {
10530                    t.hot_lookup_attempted = true;
10531                    t.hot_lookup_hit = true;
10532                });
10533                Ok(RowIdSet::one(row.row_id.0))
10534            }
10535            failure => {
10536                let reason = match &failure {
10537                    crate::trace::HotCandidateInspection::Hit(_) => unreachable!(),
10538                    crate::trace::HotCandidateInspection::MissingRow => {
10539                        // `inspect_row_at` could not find any version at this
10540                        // RowId. The HOT map pointed at a `RowId` that does
10541                        // not exist; the closest label is Tombstone (the row
10542                        // used to be there and is now gone).
10543                        crate::trace::HotFallbackReason::Tombstone
10544                    }
10545                    crate::trace::HotCandidateInspection::Invisible => {
10546                        crate::trace::HotFallbackReason::InvisibleAtSnapshot
10547                    }
10548                    crate::trace::HotCandidateInspection::Tombstone => {
10549                        crate::trace::HotFallbackReason::Tombstone
10550                    }
10551                    crate::trace::HotCandidateInspection::TtlExpired => {
10552                        crate::trace::HotFallbackReason::TtlExpired
10553                    }
10554                    crate::trace::HotCandidateInspection::PrimaryKeyMismatch { .. } => {
10555                        crate::trace::HotFallbackReason::PrimaryKeyMismatch
10556                    }
10557                };
10558                // The HOT map may have a stale RowId; the inner scanner is
10559                // the only source of the verified RowIdSet. Suppress the
10560                // inner `record_hot_fallback_reason` call by passing
10561                // `snapshot` unchanged — the historical/PK-mismatch branches
10562                // already short-circuit before re-recording.
10563                let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10564                self.record_hot_fallback_reason(reason);
10565                Ok(result)
10566            }
10567        }
10568    }
10569
10570    /// Resolve a single condition to its row-id set. Index-served conditions use
10571    /// the in-memory indexes; `Range`/`RangeF64` prefer the learned (PGM) index
10572    /// or the reader's page-index-skipping path on the single-run fast path, and
10573    /// only fall back to a `visible_rows` scan off the fast path (multi-run).
10574    fn resolve_condition(
10575        &self,
10576        c: &crate::query::Condition,
10577        snapshot: Snapshot,
10578    ) -> Result<RowIdSet> {
10579        self.resolve_condition_with_allowed(c, snapshot, None)
10580    }
10581
10582    fn resolve_condition_with_allowed(
10583        &self,
10584        c: &crate::query::Condition,
10585        snapshot: Snapshot,
10586        allowed: Option<&std::collections::HashSet<RowId>>,
10587    ) -> Result<RowIdSet> {
10588        use crate::query::Condition;
10589        self.validate_condition(c)?;
10590        Ok(match c {
10591            Condition::Pk(key) => {
10592                let lookup = self
10593                    .schema
10594                    .primary_key()
10595                    .map(|pk| self.index_lookup_key_bytes(pk.id, key))
10596                    .unwrap_or_else(|| key.clone());
10597                if let Some(pk_col) = self.schema.primary_key() {
10598                    return self.resolve_pk_with_hot_fallback(pk_col.id, &lookup, snapshot);
10599                }
10600                // No primary key column — HOT is meaningless. Match the
10601                // legacy behavior: every PK condition collapses to an empty
10602                // set.
10603                RowIdSet::empty()
10604            }
10605            Condition::BitmapEq { column_id, value } => {
10606                let lookup = self.index_lookup_key_bytes(*column_id, value);
10607                self.bitmap
10608                    .get(column_id)
10609                    .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
10610                    .unwrap_or_else(RowIdSet::empty)
10611            }
10612            Condition::BitmapIn { column_id, values } => {
10613                let bm = self.bitmap.get(column_id);
10614                let mut acc = roaring::RoaringBitmap::new();
10615                if let Some(b) = bm {
10616                    for v in values {
10617                        let lookup = self.index_lookup_key_bytes(*column_id, v);
10618                        acc |= b.get(&lookup);
10619                    }
10620                }
10621                RowIdSet::from_roaring(acc)
10622            }
10623            Condition::BytesPrefix { column_id, prefix } => {
10624                // §5.6: enumerate bitmap keys sharing the prefix for an exact
10625                // prefix match (anchored `LIKE 'prefix%'`), tighter than the
10626                // FM substring superset. The caller only emits this when the
10627                // column has a bitmap index.
10628                if let Some(b) = self.bitmap.get(column_id) {
10629                    let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
10630                    let mut acc = roaring::RoaringBitmap::new();
10631                    for key in b.keys() {
10632                        if key.starts_with(&lookup_prefix) {
10633                            acc |= b.get(&key);
10634                        }
10635                    }
10636                    RowIdSet::from_roaring(acc)
10637                } else {
10638                    RowIdSet::empty()
10639                }
10640            }
10641            Condition::FmContains { column_id, pattern } => self
10642                .fm
10643                .get(column_id)
10644                .map(|f| {
10645                    RowIdSet::from_unsorted(f.locate(pattern).into_iter().map(|r| r.0).collect())
10646                })
10647                .unwrap_or_else(RowIdSet::empty),
10648            Condition::FmContainsAll {
10649                column_id,
10650                patterns,
10651            } => {
10652                // Multi-segment intersection (Priority 12): resolve each segment
10653                // via FM and intersect — much tighter than the single longest.
10654                if let Some(f) = self.fm.get(column_id) {
10655                    let sets: Vec<RowIdSet> = patterns
10656                        .iter()
10657                        .map(|pat| {
10658                            RowIdSet::from_unsorted(
10659                                f.locate(pat).into_iter().map(|r| r.0).collect(),
10660                            )
10661                        })
10662                        .collect();
10663                    RowIdSet::intersect_many(sets)
10664                } else {
10665                    RowIdSet::empty()
10666                }
10667            }
10668            Condition::Ann {
10669                column_id,
10670                query,
10671                k,
10672            } => RowIdSet::from_unsorted(
10673                self.retrieve_filtered(
10674                    &crate::query::Retriever::Ann {
10675                        column_id: *column_id,
10676                        query: query.clone(),
10677                        k: *k,
10678                    },
10679                    snapshot,
10680                    None,
10681                    allowed,
10682                    None,
10683                    None,
10684                )?
10685                .into_iter()
10686                .map(|hit| hit.row_id.0)
10687                .collect(),
10688            ),
10689            Condition::SparseMatch {
10690                column_id,
10691                query,
10692                k,
10693            } => RowIdSet::from_unsorted(
10694                self.retrieve_filtered(
10695                    &crate::query::Retriever::Sparse {
10696                        column_id: *column_id,
10697                        query: query.clone(),
10698                        k: *k,
10699                    },
10700                    snapshot,
10701                    None,
10702                    allowed,
10703                    None,
10704                    None,
10705                )?
10706                .into_iter()
10707                .map(|hit| hit.row_id.0)
10708                .collect(),
10709            ),
10710            Condition::MinHashSimilar {
10711                column_id,
10712                query,
10713                k,
10714            } => match self.minhash.get(column_id) {
10715                Some(index) => {
10716                    let candidates = index.candidate_row_ids(query);
10717                    let eligible =
10718                        self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
10719                    RowIdSet::from_unsorted(
10720                        index
10721                            .search_filtered(query, *k, |row_id| {
10722                                eligible.contains(&row_id)
10723                                    && allowed.is_none_or(|allowed| allowed.contains(&row_id))
10724                            })
10725                            .into_iter()
10726                            .map(|(row_id, _)| row_id.0)
10727                            .collect(),
10728                    )
10729                }
10730                None => RowIdSet::empty(),
10731            },
10732            Condition::Range { column_id, lo, hi } => {
10733                // Build the candidate set from the durable tier — the learned
10734                // index (built from sorted runs) or a single page-pruned run —
10735                // then merge the memtable/mutable-run overlay. An overlay row
10736                // supersedes its run version (it may have been updated out of
10737                // range or deleted), so overlay rids are dropped from the run
10738                // set and re-evaluated from the overlay directly. Without this
10739                // merge, rows still in the memtable are invisible to a ranged
10740                // read whenever a LearnedRange index is present.
10741                //
10742                // Point equality (`lo == hi`) additionally unions the Bitmap
10743                // secondary when one exists on this column. The TypeScript Kit
10744                // always pushes int64 `eq()` as RangeInt (not BitmapEq / Pk),
10745                // so product listing-by-FK would never hit the Bitmap that
10746                // `maintain_bitmap_secondary_on_replace` keeps correct after
10747                // updates. Dual-sourcing Range + Bitmap closes that gap: a
10748                // desynced run/LearnedRange plan can no longer hide a live row
10749                // that still has a correct Bitmap membership (and vice versa
10750                // the overlay merge still covers pure-memtable puts).
10751                let mut set = if let Some(li) = self.learned_range.get(column_id) {
10752                    if self.run_refs.len() == 1 {
10753                        // Single-run: learned_range was built from this run and
10754                        // excludes tombstones, so it's MVCC-correct.
10755                        RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
10756                    } else {
10757                        // Multi-run: learned_range only covers run_refs[0]; a
10758                        // tombstone in a later run wouldn't strip its alive
10759                        // preimage rid from the PGM, and the overlay merge
10760                        // (memtable + mutable_run) is empty after a spill, so a
10761                        // leaked rid would surface as a wrong hit. Fall through
10762                        // to the MVCC-aware multi-run path so deletes land in
10763                        // any run are honored.
10764                        let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10765                        if lo == hi {
10766                            self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10767                        }
10768                        return Ok(multi);
10769                    }
10770                } else if self.run_refs.len() == 1 {
10771                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10772                    r.range_row_id_set_i64(*column_id, *lo, *hi)?
10773                } else {
10774                    // Multi-run / no learned index: full range_scan already
10775                    // merges overlay; union Bitmap for point queries below.
10776                    let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10777                    if lo == hi {
10778                        self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10779                    }
10780                    return Ok(multi);
10781                };
10782                if self.learned_range.get(column_id).is_none() && self.run_refs.len() == 1 {
10783                    let candidates: Vec<RowId> =
10784                        set.into_sorted_vec().into_iter().map(RowId).collect();
10785                    set = RowIdSet::from_unsorted(
10786                        self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?
10787                            .into_iter()
10788                            .map(|row_id| row_id.0)
10789                            .collect(),
10790                    );
10791                }
10792                set.remove_many(self.overlay_rid_set(snapshot));
10793                self.range_scan_overlay_i64(&mut set, *column_id, *lo, *hi, snapshot);
10794                if lo == hi {
10795                    self.union_bitmap_point_i64(&mut set, *column_id, *lo, snapshot);
10796                }
10797                RowIdSet::from_unsorted(
10798                    set.into_sorted_vec()
10799                        .into_iter()
10800                        .filter(|row_id| self.get(RowId(*row_id), snapshot).is_some())
10801                        .collect(),
10802                )
10803            }
10804            Condition::RangeF64 {
10805                column_id,
10806                lo,
10807                lo_inclusive,
10808                hi,
10809                hi_inclusive,
10810            } => {
10811                // See the `Range` arm: merge the overlay over the durable
10812                // candidate set so memtable/mutable-run rows are visible.
10813                let mut set = if let Some(li) = self.learned_range.get(column_id) {
10814                    RowIdSet::from_unsorted(
10815                        li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
10816                            .into_iter()
10817                            .collect(),
10818                    )
10819                } else if self.run_refs.len() == 1 {
10820                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10821                    r.range_row_id_set_f64(*column_id, *lo, *lo_inclusive, *hi, *hi_inclusive)?
10822                } else {
10823                    return self.range_scan_f64(
10824                        *column_id,
10825                        *lo,
10826                        *lo_inclusive,
10827                        *hi,
10828                        *hi_inclusive,
10829                        snapshot,
10830                    );
10831                };
10832                set.remove_many(self.overlay_rid_set(snapshot));
10833                self.range_scan_overlay_f64(
10834                    &mut set,
10835                    *column_id,
10836                    *lo,
10837                    *lo_inclusive,
10838                    *hi,
10839                    *hi_inclusive,
10840                    snapshot,
10841                );
10842                set
10843            }
10844            Condition::IsNull { column_id } => {
10845                let mut set = if self.run_refs.len() == 1 {
10846                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10847                    r.null_row_id_set(*column_id, true)?
10848                } else {
10849                    return self.null_scan(*column_id, true, snapshot);
10850                };
10851                set.remove_many(self.overlay_rid_set(snapshot));
10852                self.null_scan_overlay(&mut set, *column_id, true, snapshot);
10853                set
10854            }
10855            Condition::IsNotNull { column_id } => {
10856                let mut set = if self.run_refs.len() == 1 {
10857                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10858                    r.null_row_id_set(*column_id, false)?
10859                } else {
10860                    return self.null_scan(*column_id, false, snapshot);
10861                };
10862                set.remove_many(self.overlay_rid_set(snapshot));
10863                self.null_scan_overlay(&mut set, *column_id, false, snapshot);
10864                set
10865            }
10866        })
10867    }
10868
10869    /// Vectorized range scan for Int64 columns (Phase 13.2 / 16.3). Resolves the
10870    /// survivor set via the reader's **page-pruned** path — pages whose `[min,max]`
10871    /// excludes `[lo,hi]` are never decoded — restricted to MVCC-visible rows.
10872    /// This is layout-independent: correct under any memtable / multi-run state,
10873    /// so it is always safe to call (no "single clean run" gate). Overlay rows
10874    /// (memtable / mutable-run) are excluded from the run portion and checked
10875    /// directly via [`Self::range_scan_overlay_i64`].
10876    fn range_scan_i64(
10877        &self,
10878        column_id: u16,
10879        lo: i64,
10880        hi: i64,
10881        snapshot: Snapshot,
10882    ) -> Result<RowIdSet> {
10883        let mut row_ids = Vec::new();
10884        // Collect per-run tombstones whose newest visible version is a
10885        // tombstone: they must strip any alive preimage rid that landed in
10886        // an older run from the survivor set. Without this, a delete-after-
10887        // put whose tombstone lands in a newer run can't override the
10888        // preimage that `range_row_ids_visible_i64` happily returned for the
10889        // older run — the model filters them out, the engine must too.
10890        let mut tomb_rids: HashSet<u64> = HashSet::new();
10891        let overlay_rids = self.overlay_rid_set(snapshot);
10892        for rr in &self.run_refs {
10893            let mut reader = self.open_reader(rr.run_id)?;
10894            let matched = reader.range_row_ids_visible_i64_at(column_id, lo, hi, snapshot)?;
10895            for rid in matched {
10896                if !overlay_rids.contains(&rid) {
10897                    row_ids.push(rid);
10898                }
10899            }
10900            for rid in reader.tombstoned_row_ids_at(snapshot)? {
10901                tomb_rids.insert(rid);
10902            }
10903        }
10904        // Overlay tombstones strip matching run preimages. Collect them
10905        // under the same read-your-writes rule as
10906        // `eligible_candidate_ids`: a snapshot pinned at the current
10907        // visible epoch advances over the in-flight batch; a strictly
10908        // historical pinned snapshot must NOT see pending (uncommitted)
10909        // tombstones.
10910        let overlay_tombstone_snapshot = if self.is_shared()
10911            || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10912            || snapshot.epoch.0 != self.epoch.visible().0
10913        {
10914            snapshot
10915        } else {
10916            Snapshot::at(self.pending_epoch())
10917        };
10918        for row in self
10919            .memtable
10920            .visible_versions_at(overlay_tombstone_snapshot)
10921            .into_iter()
10922            .chain(
10923                self.mutable_run
10924                    .visible_versions_at(overlay_tombstone_snapshot),
10925            )
10926        {
10927            if row.deleted {
10928                tomb_rids.insert(row.row_id.0);
10929            }
10930        }
10931        let mut s = RowIdSet::from_unsorted(row_ids);
10932        s.remove_many(tomb_rids);
10933        let candidates: Vec<RowId> = s.into_sorted_vec().into_iter().map(RowId).collect();
10934        let eligible = self.eligible_candidate_ids(&candidates, column_id, snapshot, None)?;
10935        let mut s = RowIdSet::from_unsorted(eligible.into_iter().map(|row_id| row_id.0).collect());
10936        self.range_scan_overlay_i64(&mut s, column_id, lo, hi, snapshot);
10937        Ok(s)
10938    }
10939
10940    /// Float64 analogue of [`Self::range_scan_i64`] with per-bound inclusivity
10941    /// (Phase 13.2 / 16.3).
10942    fn range_scan_f64(
10943        &self,
10944        column_id: u16,
10945        lo: f64,
10946        lo_inclusive: bool,
10947        hi: f64,
10948        hi_inclusive: bool,
10949        snapshot: Snapshot,
10950    ) -> Result<RowIdSet> {
10951        let mut row_ids = Vec::new();
10952        let overlay_rids = self.overlay_rid_set(snapshot);
10953        for rr in &self.run_refs {
10954            let mut reader = self.open_reader(rr.run_id)?;
10955            let matched = reader.range_row_ids_visible_f64_at(
10956                column_id,
10957                lo,
10958                lo_inclusive,
10959                hi,
10960                hi_inclusive,
10961                snapshot,
10962            )?;
10963            for rid in matched {
10964                if !overlay_rids.contains(&rid) {
10965                    row_ids.push(rid);
10966                }
10967            }
10968        }
10969        let mut s = RowIdSet::from_unsorted(row_ids);
10970        self.range_scan_overlay_f64(
10971            &mut s,
10972            column_id,
10973            lo,
10974            lo_inclusive,
10975            hi,
10976            hi_inclusive,
10977            snapshot,
10978        );
10979        Ok(s)
10980    }
10981
10982    /// Collect the set of row-ids visible in the memtable / mutable-run overlay.
10983    fn overlay_rid_set(&self, snapshot: Snapshot) -> HashSet<u64> {
10984        let mut s = HashSet::new();
10985        for row in self.memtable.visible_versions_at(snapshot) {
10986            s.insert(row.row_id.0);
10987        }
10988        for row in self.mutable_run.visible_versions_at(snapshot) {
10989            s.insert(row.row_id.0);
10990        }
10991        s
10992    }
10993
10994    fn range_scan_overlay_i64(
10995        &self,
10996        s: &mut RowIdSet,
10997        column_id: u16,
10998        lo: i64,
10999        hi: i64,
11000        snapshot: Snapshot,
11001    ) {
11002        // Collapse both overlay tiers to the newest visible version per row id
11003        // (HLC-aware when stamped; P0.5-T3) before range-checking, so a stale
11004        // in-range mutable-run version cannot shadow a newer out-of-range
11005        // memtable version of the same row.
11006        // Both tiers already applied version_is_newer within themselves; when
11007        // both report a rid, prefer the HLC-newer of the two.
11008        let mut newest: HashMap<u64, Row> = HashMap::new();
11009        for r in self.mutable_run.visible_versions_at(snapshot) {
11010            newest.insert(r.row_id.0, r);
11011        }
11012        for r in self.memtable.visible_versions_at(snapshot) {
11013            newest
11014                .entry(r.row_id.0)
11015                .and_modify(|cur| {
11016                    if Snapshot::version_is_newer(
11017                        r.committed_epoch,
11018                        r.commit_ts,
11019                        cur.committed_epoch,
11020                        cur.commit_ts,
11021                    ) {
11022                        *cur = r.clone();
11023                    }
11024                })
11025                .or_insert(r);
11026        }
11027        for row in newest.values() {
11028            if !row.deleted {
11029                if let Some(Value::Int64(v)) = row.columns.get(&column_id) {
11030                    if *v >= lo && *v <= hi && !self.row_expired_at(row, unix_nanos_now()) {
11031                        s.insert(row.row_id.0);
11032                    }
11033                }
11034            }
11035        }
11036    }
11037
11038    #[allow(clippy::too_many_arguments)]
11039    fn range_scan_overlay_f64(
11040        &self,
11041        s: &mut RowIdSet,
11042        column_id: u16,
11043        lo: f64,
11044        lo_inclusive: bool,
11045        hi: f64,
11046        hi_inclusive: bool,
11047        snapshot: Snapshot,
11048    ) {
11049        // See `range_scan_overlay_i64`: dedup to the newest version per row id
11050        // across the memtable + mutable run before range-checking.
11051        let mut newest: HashMap<u64, Row> = HashMap::new();
11052        for r in self.mutable_run.visible_versions_at(snapshot) {
11053            newest.insert(r.row_id.0, r);
11054        }
11055        for r in self.memtable.visible_versions_at(snapshot) {
11056            newest
11057                .entry(r.row_id.0)
11058                .and_modify(|cur| {
11059                    if Snapshot::version_is_newer(
11060                        r.committed_epoch,
11061                        r.commit_ts,
11062                        cur.committed_epoch,
11063                        cur.commit_ts,
11064                    ) {
11065                        *cur = r.clone();
11066                    }
11067                })
11068                .or_insert(r);
11069        }
11070        for row in newest.values() {
11071            if !row.deleted {
11072                if let Some(Value::Float64(v)) = row.columns.get(&column_id) {
11073                    let ok_lo = if lo_inclusive { *v >= lo } else { *v > lo };
11074                    let ok_hi = if hi_inclusive { *v <= hi } else { *v < hi };
11075                    if ok_lo && ok_hi && !self.row_expired_at(row, unix_nanos_now()) {
11076                        s.insert(row.row_id.0);
11077                    }
11078                }
11079            }
11080        }
11081    }
11082
11083    /// Multi-run fallback for `IS NULL` / `IS NOT NULL`. Calls each run's
11084    /// MVCC-aware null scan and merges with the overlay.
11085    fn null_scan(&self, column_id: u16, want_nulls: bool, snapshot: Snapshot) -> Result<RowIdSet> {
11086        let mut row_ids = Vec::new();
11087        let overlay_rids = self.overlay_rid_set(snapshot);
11088        for rr in &self.run_refs {
11089            let mut reader = self.open_reader(rr.run_id)?;
11090            let matched = reader.null_row_ids_visible_at(column_id, want_nulls, snapshot)?;
11091            for rid in matched {
11092                if !overlay_rids.contains(&rid) {
11093                    row_ids.push(rid);
11094                }
11095            }
11096        }
11097        let mut s = RowIdSet::from_unsorted(row_ids);
11098        self.null_scan_overlay(&mut s, column_id, want_nulls, snapshot);
11099        Ok(s)
11100    }
11101
11102    /// Merge overlay rows for `IS NULL` / `IS NOT NULL`. An overlay row
11103    /// supersedes its run version, so overlay rids are removed from the run
11104    /// set and re-evaluated from the overlay values directly.
11105    fn null_scan_overlay(
11106        &self,
11107        s: &mut RowIdSet,
11108        column_id: u16,
11109        want_nulls: bool,
11110        snapshot: Snapshot,
11111    ) {
11112        let mut newest: HashMap<u64, Row> = HashMap::new();
11113        for r in self.mutable_run.visible_versions_at(snapshot) {
11114            newest.insert(r.row_id.0, r);
11115        }
11116        for r in self.memtable.visible_versions_at(snapshot) {
11117            newest
11118                .entry(r.row_id.0)
11119                .and_modify(|cur| {
11120                    if Snapshot::version_is_newer(
11121                        r.committed_epoch,
11122                        r.commit_ts,
11123                        cur.committed_epoch,
11124                        cur.commit_ts,
11125                    ) {
11126                        *cur = r.clone();
11127                    }
11128                })
11129                .or_insert(r);
11130        }
11131        for row in newest.values() {
11132            if row.deleted {
11133                continue;
11134            }
11135            let is_null = !row.columns.contains_key(&column_id)
11136                || matches!(row.columns.get(&column_id), Some(Value::Null) | None);
11137            if is_null == want_nulls {
11138                s.insert(row.row_id.0);
11139            }
11140        }
11141    }
11142
11143    pub fn snapshot(&self) -> Snapshot {
11144        let epoch = self.epoch.visible();
11145        // P0.5: mounted tables pin the shared HLC so HLC-stamped row versions
11146        // remain visible under at_hlc. Standalone private-WAL tables fall back
11147        // to epoch-only (private commits do not stamp HLC today).
11148        match &self.wal {
11149            WalSink::Shared(shared) => match shared.hlc.now() {
11150                Ok(commit_ts) => Snapshot::at_hlc(epoch, commit_ts),
11151                // Clock skew must not hide committed HLC rows from product reads.
11152                Err(_) => Snapshot::at_hlc(epoch, mongreldb_types::hlc::HlcTimestamp::MAX),
11153            },
11154            WalSink::Private(_) | WalSink::ReadOnly => Snapshot::at(epoch),
11155        }
11156    }
11157
11158    /// Generation of this table's row contents for table-local caches.
11159    pub fn data_generation(&self) -> u64 {
11160        self.data_generation
11161    }
11162
11163    pub(crate) fn bump_data_generation(&mut self) {
11164        self.data_generation = self.data_generation.wrapping_add(1);
11165    }
11166
11167    /// Stable catalog table id for this mounted table.
11168    pub fn table_id(&self) -> u64 {
11169        self.table_id
11170    }
11171
11172    /// Seal every active delta (memtable, mutable-run tier, HOT, reverse-PK
11173    /// map, and every secondary index) so the current state can be captured
11174    /// as an immutable generation. Sealing moves the active delta behind the
11175    /// shared frozen `Arc` without copying row data; the writer keeps
11176    /// appending to a fresh, empty active delta (S1C-001).
11177    fn seal_generations(&mut self) {
11178        self.memtable.seal();
11179        self.mutable_run.seal();
11180        self.hot.seal();
11181        for index in self.bitmap.values_mut() {
11182            index.seal();
11183        }
11184        for index in self.ann.values_mut() {
11185            index.seal();
11186        }
11187        for index in self.fm.values_mut() {
11188            index.seal();
11189        }
11190        for index in self.sparse.values_mut() {
11191            index.seal();
11192        }
11193        for index in self.minhash.values_mut() {
11194            index.seal();
11195        }
11196        self.pk_by_row.seal();
11197    }
11198
11199    /// Capture the current (freshly sealed) state as an immutable
11200    /// [`ReadGeneration`]. Cheap by construction: frozen layers are
11201    /// `Arc`-shared, schema/run-refs are small metadata copies, and every
11202    /// active delta is empty post-seal.
11203    fn capture_read_generation(&self) -> ReadGeneration {
11204        let visible_through = self.current_epoch();
11205        ReadGeneration {
11206            schema: Arc::new(self.schema.clone()),
11207            base_runs: Arc::new(self.run_refs.clone()),
11208            deltas: TableDeltas {
11209                memtable: self.memtable.clone(),
11210                mutable_run: self.mutable_run.clone(),
11211                hot: self.hot.clone(),
11212                pk_by_row: self.pk_by_row.clone(),
11213            },
11214            indexes: Arc::new(IndexGeneration::capture(
11215                &self.bitmap,
11216                &self.learned_range,
11217                &self.fm,
11218                &self.ann,
11219                &self.sparse,
11220                &self.minhash,
11221                visible_through,
11222                // P0.5-T5: authoritative HLC readiness watermark.
11223                match &self.wal {
11224                    WalSink::Shared(shared) => shared
11225                        .hlc
11226                        .now()
11227                        .unwrap_or(mongreldb_types::hlc::HlcTimestamp::MAX),
11228                    _ => mongreldb_types::hlc::HlcTimestamp::MAX,
11229                },
11230            )),
11231            visible_through,
11232        }
11233    }
11234
11235    /// Seal the active deltas and atomically publish a replacement
11236    /// [`ReadGeneration`] (S1C-001/S1C-002). The publish is a single
11237    /// `ArcSwap` store: readers that pinned the previous `Arc` keep their
11238    /// stable view, new readers see this one. Returns the published view.
11239    pub fn publish_read_generation(&mut self) -> Result<Arc<ReadGeneration>> {
11240        self.ensure_indexes_complete()?;
11241        self.seal_generations();
11242        let view = Arc::new(self.capture_read_generation());
11243        self.published.store(Arc::clone(&view));
11244        Ok(view)
11245    }
11246
11247    /// The most recently published immutable read view. Pinning the returned
11248    /// `Arc` keeps its structurally-shared frozen layers alive. The view is
11249    /// seeded empty at open/create and refreshed by
11250    /// [`Table::publish_read_generation`], [`Table::flush`], and read-
11251    /// generation creation.
11252    pub fn published_read_generation(&self) -> Arc<ReadGeneration> {
11253        self.published.load_full()
11254    }
11255
11256    /// The table's unified version-retention pin registry (S1C-004).
11257    pub fn pin_registry(&self) -> &Arc<crate::retention::PinRegistry> {
11258        &self.pins
11259    }
11260
11261    /// S1C-004: the epoch floor for version reclamation — a version may be
11262    /// reclaimed only when older than every pin source. Equals
11263    /// [`Table::min_active_snapshot`], or the current visible epoch when
11264    /// nothing is pinned (nothing older than the floor can still be needed).
11265    pub fn version_gc_floor(&self) -> Epoch {
11266        self.min_active_snapshot()
11267            .unwrap_or_else(|| self.current_epoch())
11268    }
11269
11270    /// S1C-004 diagnostics: every active version-retention pin source.
11271    /// Registered pins (read generations, and later backup/PITR, replication,
11272    /// online index builds) come from the [`crate::retention::PinRegistry`];
11273    /// the oldest transaction snapshot (local pins plus the shared
11274    /// [`crate::retention::SnapshotRegistry`]) and the configured history
11275    /// window are projected into the report so all six sources are visible.
11276    pub fn version_pins_report(&self) -> crate::retention::PinsReport {
11277        let mut report = self.pins.report();
11278        let transaction_floor = [
11279            self.pinned.keys().next().copied(),
11280            self.snapshots.min_pinned(),
11281        ]
11282        .into_iter()
11283        .flatten()
11284        .min();
11285        if let Some(epoch) = transaction_floor {
11286            report.record_projection(crate::retention::PinSource::TransactionSnapshot, epoch);
11287        }
11288        if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11289            report.record_projection(crate::retention::PinSource::HistoryRetention, floor);
11290        }
11291        report
11292    }
11293
11294    pub(crate) fn clone_read_generation(&mut self) -> Result<Self> {
11295        self.publish_read_generation()?;
11296        let mut generation = self.clone();
11297        generation.read_only = true;
11298        generation.wal = WalSink::ReadOnly;
11299        generation.pending_delete_rids.clear();
11300        generation.pending_put_cols.clear();
11301        generation.pending_rows.clear();
11302        generation.pending_rows_auto_inc.clear();
11303        generation.pending_dels.clear();
11304        generation.pending_truncate = None;
11305        generation.agg_cache = Arc::new(HashMap::new());
11306        // The pinned generation keeps the view published at its birth, not
11307        // the writer's live cell: later publishes must not mutate it.
11308        generation.published = Arc::new(ArcSwap::new(self.published.load_full()));
11309        // S1C-004: the generation pins its birth epoch until it drops, so
11310        // version GC can never reclaim versions it still reads.
11311        generation.read_generation_pin = Some(Arc::new(self.pins.pin(
11312            crate::retention::PinSource::ReadGeneration,
11313            self.current_epoch(),
11314        )));
11315        Ok(generation)
11316    }
11317
11318    pub(crate) fn estimated_clone_bytes(&self) -> u64 {
11319        (std::mem::size_of::<Self>() as u64)
11320            .saturating_add(self.memtable.approx_bytes())
11321            .saturating_add(self.mutable_run.approx_bytes())
11322            .saturating_add(self.live_count.saturating_mul(64))
11323    }
11324
11325    /// Pin the current read snapshot; compaction will preserve the versions it
11326    /// needs until [`Table::unpin_snapshot`] is called.
11327    ///
11328    /// Mounted (shared-WAL) tables pin HLC via [`Snapshot::at_hlc`] so HLC is
11329    /// the cluster-wide authority. Standalone private-WAL tables remain
11330    /// epoch-only until they stamp HLC on commit.
11331    pub fn pin_snapshot(&mut self) -> Snapshot {
11332        let snap = self.snapshot();
11333        *self.pinned.entry(snap.epoch).or_insert(0) += 1;
11334        snap
11335    }
11336
11337    /// Every epoch that pin-aware index rebuild must restore secondary
11338    /// discovery / retrieval for — the full set of reader/retention pins that
11339    /// [`Self::min_active_snapshot`] folds into compaction GC, not just the
11340    /// oldest and not just the standalone `pin_snapshot` map.
11341    ///
11342    /// Sources (union, ascending, deduped):
11343    /// - local `self.pinned` ([`Self::pin_snapshot`])
11344    /// - [`crate::retention::SnapshotRegistry`] live pins (`Database::snapshot`)
11345    /// - [`crate::retention::PinRegistry`] live pins (backup/PITR, replication,
11346    ///   read-generation, online-index-build, …)
11347    /// - history-retention floor when configured
11348    fn active_pin_epochs_for_rebuild(&self) -> Vec<Epoch> {
11349        let mut set = BTreeSet::new();
11350        for epoch in self.pinned.keys().copied() {
11351            set.insert(epoch);
11352        }
11353        for epoch in self.snapshots.live_pinned_epochs() {
11354            set.insert(epoch);
11355        }
11356        for epoch in self.pins.live_pin_epochs() {
11357            set.insert(epoch);
11358        }
11359        if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11360            set.insert(floor);
11361        }
11362        set.into_iter().collect()
11363    }
11364
11365    /// P0.5-T6: report the HLC GC floor as named pin sources.
11366    ///
11367    /// Epoch pins that cannot yet be projected to a durable HLC report
11368    /// [`HlcTimestamp::ZERO`](mongreldb_types::hlc::HlcTimestamp::ZERO). Physical
11369    /// reclamation still consults the epoch floor ([`Self::version_gc_floor`]).
11370    ///
11371    /// `project_epoch` maps a local pin epoch to an HLC (typically
11372    /// [`crate::Database::commit_ts_for_epoch`]); return `None` / `ZERO` when
11373    /// the epoch has no durable stamp.
11374    pub fn hlc_gc_floor(
11375        &self,
11376        mut project_epoch: impl FnMut(Epoch) -> Option<mongreldb_types::hlc::HlcTimestamp>,
11377    ) -> crate::epoch::GcFloor {
11378        let mut project = |epoch: Option<Epoch>| -> mongreldb_types::hlc::HlcTimestamp {
11379            epoch
11380                .and_then(&mut project_epoch)
11381                .filter(|ts| *ts != mongreldb_types::hlc::HlcTimestamp::ZERO)
11382                .unwrap_or(mongreldb_types::hlc::HlcTimestamp::ZERO)
11383        };
11384        let transaction = [
11385            self.pinned.keys().next().copied(),
11386            self.snapshots.min_pinned(),
11387        ]
11388        .into_iter()
11389        .flatten()
11390        .min();
11391        let history = self.snapshots.history_floor(self.current_epoch());
11392        crate::epoch::GcFloor {
11393            transaction_snapshot: project(transaction),
11394            history_retention: project(history),
11395            backup_pitr: project(
11396                self.pins
11397                    .oldest_for(crate::retention::PinSource::BackupPitr),
11398            ),
11399            replication: project(
11400                self.pins
11401                    .oldest_for(crate::retention::PinSource::Replication),
11402            ),
11403            read_generation: project(
11404                self.pins
11405                    .oldest_for(crate::retention::PinSource::ReadGeneration),
11406            ),
11407            online_index_build: project(
11408                self.pins
11409                    .oldest_for(crate::retention::PinSource::OnlineIndexBuild),
11410            ),
11411        }
11412    }
11413
11414    /// Release a pinned snapshot.
11415    pub fn unpin_snapshot(&mut self, snap: Snapshot) {
11416        if let Some(count) = self.pinned.get_mut(&snap.epoch) {
11417            *count -= 1;
11418            if *count == 0 {
11419                self.pinned.remove(&snap.epoch);
11420            }
11421        }
11422    }
11423
11424    /// Oldest pinned snapshot epoch, or `None` if no snapshot is active.
11425    /// Lowest snapshot epoch that compaction must preserve a version for, or
11426    /// `None` when no reader is pinned anywhere. Considers BOTH the single-table
11427    /// local pin set (`self.pinned`, used by the standalone `pin_snapshot` API)
11428    /// AND the shared `Database` snapshot registry (`db.snapshot()` readers) —
11429    /// otherwise a multi-table reader's version could be dropped by a compaction
11430    /// triggered on its table (the registry-gated reaper would then keep the
11431    /// old run *files*, but readers only scan the merged run, so the version
11432    /// would still be lost). Also folds in the unified [`crate::retention::PinRegistry`]
11433    /// (S1C-004): backup/PITR, replication, cursor/read-generation, and
11434    /// online-index-build pins all gate version reclamation here.
11435    pub(crate) fn min_active_snapshot(&self) -> Option<Epoch> {
11436        let local = self.pinned.keys().next().copied();
11437        let global = self.snapshots.min_pinned();
11438        let history = self.snapshots.history_floor(self.current_epoch());
11439        let pinned = self.pins.oldest_pinned();
11440        [local, global, history, pinned].into_iter().flatten().min()
11441    }
11442
11443    /// Configure timestamp-column retention on a standalone table. Mounted
11444    /// databases should use [`crate::Database::set_table_ttl`] so the DDL is
11445    /// WAL-replicated.
11446    pub fn set_ttl(&mut self, column_name: &str, duration_nanos: u64) -> Result<()> {
11447        self.ensure_writable()?;
11448        let policy = self.prepare_ttl_policy(column_name, duration_nanos)?;
11449        self.apply_ttl_policy_at(Some(policy), self.current_epoch())
11450    }
11451
11452    pub fn clear_ttl(&mut self) -> Result<()> {
11453        self.ensure_writable()?;
11454        self.apply_ttl_policy_at(None, self.current_epoch())
11455    }
11456
11457    pub fn ttl(&self) -> Option<TtlPolicy> {
11458        self.ttl
11459    }
11460
11461    pub(crate) fn prepare_ttl_policy(
11462        &self,
11463        column_name: &str,
11464        duration_nanos: u64,
11465    ) -> Result<TtlPolicy> {
11466        if duration_nanos == 0 || duration_nanos > i64::MAX as u64 {
11467            return Err(MongrelError::InvalidArgument(
11468                "TTL duration must be between 1 and i64::MAX nanoseconds".into(),
11469            ));
11470        }
11471        let column = self
11472            .schema
11473            .columns
11474            .iter()
11475            .find(|column| column.name == column_name)
11476            .ok_or_else(|| MongrelError::Schema(format!("unknown TTL column {column_name}")))?;
11477        if column.ty != TypeId::TimestampNanos {
11478            return Err(MongrelError::Schema(format!(
11479                "TTL column {column_name} must be TimestampNanos, is {:?}",
11480                column.ty
11481            )));
11482        }
11483        Ok(TtlPolicy {
11484            column_id: column.id,
11485            duration_nanos,
11486        })
11487    }
11488
11489    pub(crate) fn apply_ttl_policy_at(
11490        &mut self,
11491        policy: Option<TtlPolicy>,
11492        epoch: Epoch,
11493    ) -> Result<()> {
11494        if let Some(policy) = policy {
11495            let column = self
11496                .schema
11497                .columns
11498                .iter()
11499                .find(|column| column.id == policy.column_id)
11500                .ok_or_else(|| {
11501                    MongrelError::Schema(format!("unknown TTL column id {}", policy.column_id))
11502                })?;
11503            if column.ty != TypeId::TimestampNanos
11504                || policy.duration_nanos == 0
11505                || policy.duration_nanos > i64::MAX as u64
11506            {
11507                return Err(MongrelError::Schema("invalid TTL policy".into()));
11508            }
11509        }
11510        self.ttl = policy;
11511        self.agg_cache = Arc::new(HashMap::new());
11512        self.clear_result_cache();
11513        let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
11514        self.persist_manifest(epoch)
11515    }
11516
11517    pub(crate) fn row_expired_at(&self, row: &Row, now_nanos: i64) -> bool {
11518        let Some(policy) = self.ttl else {
11519            return false;
11520        };
11521        let Some(Value::Int64(timestamp)) = row.columns.get(&policy.column_id) else {
11522            return false;
11523        };
11524        timestamp.saturating_add(policy.duration_nanos as i64) <= now_nanos
11525    }
11526
11527    pub fn current_epoch(&self) -> Epoch {
11528        self.epoch.visible()
11529    }
11530
11531    pub fn memtable_len(&self) -> usize {
11532        self.memtable.len()
11533    }
11534
11535    /// Live row count. O(1) without TTL; TTL tables scan because wall-clock
11536    /// expiry can change without a commit epoch.
11537    pub fn count(&self) -> u64 {
11538        if self.ttl.is_none()
11539            && self.pending_put_cols.is_empty()
11540            && self.pending_delete_rids.is_empty()
11541            && self.pending_rows.is_empty()
11542            && self.pending_dels.is_empty()
11543            && self.pending_truncate.is_none()
11544        {
11545            self.live_count
11546        } else {
11547            self.visible_rows(self.snapshot())
11548                .map(|rows| rows.len() as u64)
11549                .unwrap_or(self.live_count)
11550        }
11551    }
11552
11553    /// Count rows matching an index-backed conjunctive predicate without
11554    /// materializing projected columns. Returns `None` when a condition cannot
11555    /// be served by the native predicate resolver.
11556    pub fn count_conditions(
11557        &mut self,
11558        conditions: &[crate::query::Condition],
11559        snapshot: Snapshot,
11560    ) -> Result<Option<u64>> {
11561        use crate::query::Condition;
11562        if self.ttl.is_some() {
11563            if conditions.is_empty() {
11564                return Ok(Some(self.visible_rows(snapshot)?.len() as u64));
11565            }
11566            let mut sets = Vec::with_capacity(conditions.len());
11567            for condition in conditions {
11568                sets.push(self.resolve_condition(condition, snapshot)?);
11569            }
11570            let survivors = RowIdSet::intersect_many(sets);
11571            let rows = self.visible_rows(snapshot)?;
11572            return Ok(Some(
11573                rows.into_iter()
11574                    .filter(|row| survivors.contains(row.row_id.0))
11575                    .count() as u64,
11576            ));
11577        }
11578        if conditions.is_empty() {
11579            return Ok(Some(self.count()));
11580        }
11581        let served = |c: &Condition| {
11582            matches!(
11583                c,
11584                Condition::Pk(_)
11585                    | Condition::BitmapEq { .. }
11586                    | Condition::BitmapIn { .. }
11587                    | Condition::BytesPrefix { .. }
11588                    | Condition::FmContains { .. }
11589                    | Condition::FmContainsAll { .. }
11590                    | Condition::Ann { .. }
11591                    | Condition::Range { .. }
11592                    | Condition::RangeF64 { .. }
11593                    | Condition::SparseMatch { .. }
11594                    | Condition::MinHashSimilar { .. }
11595                    | Condition::IsNull { .. }
11596                    | Condition::IsNotNull { .. }
11597            )
11598        };
11599        if !conditions.iter().all(served) {
11600            return Ok(None);
11601        }
11602        self.ensure_indexes_complete()?;
11603        if !self.pending_put_cols.is_empty()
11604            || !self.pending_delete_rids.is_empty()
11605            || !self.pending_rows.is_empty()
11606            || !self.pending_dels.is_empty()
11607            || self.pending_truncate.is_some()
11608        {
11609            let mut sets = Vec::with_capacity(conditions.len());
11610            for condition in conditions {
11611                sets.push(self.resolve_condition(condition, snapshot)?);
11612            }
11613            let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
11614            return Ok(Some(self.rows_for_rids(&rids, snapshot)?.len() as u64));
11615        }
11616        let mut sets = Vec::with_capacity(conditions.len());
11617        for condition in conditions {
11618            sets.push(self.resolve_condition(condition, snapshot)?);
11619        }
11620        let rids = RowIdSet::intersect_many(sets);
11621        // §5.1: secondary indexes are append-only across pure deletes, so
11622        // tombstoned rids linger under equality keys until a pin-aware rebuild
11623        // / compaction. Materialize paths already filter via MVCC. The count
11624        // path must not trust raw index cardinality whenever deletes have ever
11625        // happened (including after flush/spill emptied the overlay and after
11626        // reopen of a checkpoint that still carries stale memberships).
11627        // `had_deletes` is reconstructed on open from run_count vs live_count.
11628        if self.had_deletes || !self.memtable.is_empty() || !self.mutable_run.is_empty() {
11629            let sorted = rids.into_sorted_vec();
11630            let count = self.rows_for_rids(&sorted, snapshot)?.len() as u64;
11631            crate::trace::QueryTrace::record(|t| {
11632                t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11633                t.survivor_count = Some(count as usize);
11634                t.conditions_pushed = conditions.len();
11635            });
11636            return Ok(Some(count));
11637        }
11638        let count = rids.len() as u64;
11639        crate::trace::QueryTrace::record(|t| {
11640            t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11641            t.survivor_count = Some(count as usize);
11642            t.conditions_pushed = conditions.len();
11643        });
11644        Ok(Some(count))
11645    }
11646
11647    /// Row-ids whose newest visible overlay version is a tombstone. Used to
11648    /// prune stale entries left behind by the append-only in-memory indexes
11649    /// (see point dual-source / overlay merge). Tombstones may also live in
11650    /// sorted runs after flush; callers that need full correctness use
11651    /// materialize (`rows_for_rids`) instead of this overlay-only set. (§5.1)
11652    fn overlay_tombstoned_rids(&self, snapshot: Snapshot) -> Vec<u64> {
11653        let mut out = Vec::new();
11654        for row in self.memtable.visible_versions_at(snapshot) {
11655            if row.deleted {
11656                out.push(row.row_id.0);
11657            }
11658        }
11659        for row in self.mutable_run.visible_versions_at(snapshot) {
11660            if row.deleted {
11661                out.push(row.row_id.0);
11662            }
11663        }
11664        out
11665    }
11666
11667    /// Bulk-load typed columns straight to a new run — the fast ingest path.
11668    /// Bypasses the WAL, the memtable, and the `Value` enum entirely; writes one
11669    /// compressed run (delta for sorted Int64, dictionary for low-card Bytes)
11670    /// with **LZ4** (Phase 15.3 — fast decode for scan-heavy analytical runs),
11671    /// rotates the WAL, and persists the manifest in a single fsync group.
11672    /// Index building follows [`Table::index_build_policy`]: deferred to the
11673    /// first query/flush by default, or bulk-built inline from the typed
11674    /// columns (Phase 14.2) under [`IndexBuildPolicy::Eager`].
11675    pub fn bulk_load_columns(
11676        &mut self,
11677        user_columns: Vec<(u16, columnar::NativeColumn)>,
11678    ) -> Result<Epoch> {
11679        self.bulk_load_columns_with(user_columns, 3, false, true)
11680    }
11681
11682    /// Maximal-throughput bulk ingest (Phase 14.4): skip zstd entirely and write
11683    /// raw `ALGO_PLAIN` pages. ~3–4× the encode throughput of
11684    /// [`Self::bulk_load_columns`] at ~3–4× the on-disk size — the right choice
11685    /// when ingest latency dominates and a background compaction will re-compress
11686    /// later. Indexing, WAL rotation, and the manifest are identical to
11687    /// [`Self::bulk_load_columns`].
11688    pub fn bulk_load_fast(
11689        &mut self,
11690        user_columns: Vec<(u16, columnar::NativeColumn)>,
11691    ) -> Result<Epoch> {
11692        self.bulk_load_columns_with(user_columns, -1, true, false)
11693    }
11694
11695    fn bulk_load_columns_with(
11696        &mut self,
11697        mut user_columns: Vec<(u16, columnar::NativeColumn)>,
11698        zstd_level: i32,
11699        force_plain: bool,
11700        lz4: bool,
11701    ) -> Result<Epoch> {
11702        self.ensure_writable()?;
11703        let n = user_columns.first().map(|(_, c)| c.len()).unwrap_or(0);
11704        if n == 0 {
11705            return Ok(self.current_epoch());
11706        }
11707        let epoch = self.commit_new_epoch()?;
11708        let live_before = self.live_count;
11709        // Spill pending mutable-run data before the Flush marker + WAL rotation.
11710        self.spill_mutable_run(epoch)?;
11711        let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
11712            && self.indexes_complete
11713            && self.run_refs.is_empty()
11714            && self.memtable.is_empty()
11715            && self.mutable_run.is_empty();
11716        // Enforce NOT NULL constraints and primary-key upsert semantics before
11717        // any row id is allocated or bytes hit the run file.
11718        self.fill_auto_inc_native_columns(&mut user_columns, n)?;
11719        self.validate_columns_not_null(&user_columns, n)?;
11720        let winner_idx = self
11721            .bulk_pk_winner_indices(&user_columns, n)
11722            .filter(|idx| idx.len() != n);
11723        let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
11724            match winner_idx.as_deref() {
11725                Some(idx) => {
11726                    let compacted = user_columns
11727                        .iter()
11728                        .map(|(id, c)| (*id, c.gather(idx)))
11729                        .collect();
11730                    (compacted, idx.len())
11731                }
11732                None => (user_columns, n),
11733            };
11734        self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
11735        let first = self.allocator.alloc_range(write_n as u64)?.0;
11736        for rid in first..first + write_n as u64 {
11737            self.reservoir.offer(rid);
11738        }
11739        let run_id = self.alloc_run_id()?;
11740        let path = self.run_path(run_id);
11741        let mut writer =
11742            RunWriter::new(&self.schema, run_id as u128, epoch, 0).with_native_endian();
11743        if force_plain {
11744            writer = writer.with_plain();
11745        } else if lz4 {
11746            // Phase 15.3: bulk-loaded analytical runs are scan-heavy, so encode
11747            // them with LZ4 (3–5× faster decode, ~10% worse ratio than zstd).
11748            writer = writer.with_lz4();
11749        } else {
11750            writer = writer.with_zstd_level(zstd_level);
11751        }
11752        if let Some(kek) = &self.kek {
11753            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
11754        }
11755        let header = match self.create_run_file(run_id)? {
11756            Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
11757            None => writer.write_native(&path, &write_columns, write_n, first)?,
11758        };
11759        self.run_refs.push(RunRef {
11760            run_id: run_id as u128,
11761            level: 0,
11762            epoch_created: epoch.0,
11763            row_count: header.row_count,
11764        });
11765        self.run_row_id_ranges
11766            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
11767        self.live_count = self.live_count.saturating_add(write_n as u64);
11768        if eager_index_build {
11769            let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
11770            self.index_columns_bulk(&write_columns, &row_ids);
11771            self.indexes_complete = true;
11772            self.build_learned_ranges()?;
11773        } else {
11774            // Phase 14.7: defer index building off the ingest critical path for
11775            // non-empty tables where cross-run PK/update semantics must be
11776            // reconstructed from durable state.
11777            self.indexes_complete = false;
11778        }
11779        self.mark_flushed(epoch)?;
11780        self.persist_manifest(epoch)?;
11781        if eager_index_build {
11782            self.checkpoint_indexes(epoch);
11783        }
11784        self.clear_result_cache();
11785        self.data_generation = self.data_generation.wrapping_add(1);
11786        Ok(epoch)
11787    }
11788
11789    /// Bulk-build the live in-memory indexes (HOT/bitmap/FM/sparse) straight
11790    /// from typed columns — the deferred batch-indexing path (Phase 14.2).
11791    ///
11792    /// Replaces the per-row `index_into` loop: no `Row`, no per-row
11793    /// `HashMap<u16, Value>`, no `Value` enum. Index keys are computed directly
11794    /// from the typed buffers via [`columnar::encode_key_native`], tokenized for
11795    /// `ENCRYPTED_INDEXABLE` columns the same way `index_into` on a tokenized
11796    /// row would. FM is appended dirty and rebuilt once on the next query; the
11797    /// others are populated in a single typed pass. Entries are merged into the
11798    /// existing indexes so this is correct under multi-run loads and partial
11799    /// reindexes.
11800    ///
11801    /// `row_ids[i]` is the `RowId` of element `i` of every column. ANN
11802    /// (`IndexKind::Ann`) is intentionally skipped: the native codec carries no
11803    /// embeddings, so an `Embedding` column can never reach this path (a native
11804    /// bulk load of an embedding schema fails at encode). LearnedRange is built
11805    /// separately from the runs by [`Self::build_learned_ranges`].
11806    fn index_columns_bulk(&mut self, columns: &[(u16, columnar::NativeColumn)], row_ids: &[u64]) {
11807        let n = row_ids.len();
11808        if n == 0 {
11809            return;
11810        }
11811        let by_id: std::collections::HashMap<u16, &columnar::NativeColumn> =
11812            columns.iter().map(|(id, c)| (*id, c)).collect();
11813        let ty_of: std::collections::HashMap<u16, TypeId> = self
11814            .schema
11815            .columns
11816            .iter()
11817            .map(|c| (c.id, c.ty.clone()))
11818            .collect();
11819        let pk_id = self.schema.primary_key().map(|c| c.id);
11820
11821        for (i, &rid) in row_ids.iter().enumerate() {
11822            let row_id = RowId(rid);
11823            if let Some(pid) = pk_id {
11824                if let Some(col) = by_id.get(&pid) {
11825                    let ty = ty_of.get(&pid).cloned().unwrap_or(TypeId::Int64);
11826                    if let Some(key) = bulk_index_key(&self.column_keys, pid, ty, col, i) {
11827                        self.insert_hot_pk(key, row_id);
11828                    }
11829                }
11830            }
11831            for idef in &self.schema.indexes {
11832                let Some(col) = by_id.get(&idef.column_id) else {
11833                    continue;
11834                };
11835                let ty = ty_of.get(&idef.column_id).cloned().unwrap_or(TypeId::Int64);
11836                match idef.kind {
11837                    IndexKind::Bitmap => {
11838                        if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
11839                            if let Some(key) =
11840                                bulk_index_key(&self.column_keys, idef.column_id, ty, col, i)
11841                            {
11842                                b.insert(key, row_id);
11843                            }
11844                        }
11845                    }
11846                    IndexKind::FmIndex => {
11847                        if let Some(f) = self.fm.get_mut(&idef.column_id) {
11848                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11849                                f.insert(bytes.to_vec(), row_id);
11850                            }
11851                        }
11852                    }
11853                    IndexKind::Sparse => {
11854                        if let Some(s) = self.sparse.get_mut(&idef.column_id) {
11855                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11856                                if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(bytes) {
11857                                    s.insert(&terms, row_id);
11858                                }
11859                            }
11860                        }
11861                    }
11862                    IndexKind::MinHash => {
11863                        if let Some(mh) = self.minhash.get_mut(&idef.column_id) {
11864                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11865                                let tokens = crate::index::token_hashes_from_bytes(bytes);
11866                                mh.insert(&tokens, row_id);
11867                            }
11868                        }
11869                    }
11870                    _ => {}
11871                }
11872            }
11873        }
11874    }
11875
11876    /// no `Value`). Fast path: empty memtable + single run decodes columns
11877    /// directly and gathers visible indices; falls back to the `Value` path
11878    /// pivoted to native columns otherwise. `projection` (a set of column ids)
11879    /// limits decoding to the requested columns — `None` ⇒ all user columns.
11880    pub fn visible_columns_native(
11881        &self,
11882        snapshot: Snapshot,
11883        projection: Option<&[u16]>,
11884    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11885        self.visible_columns_native_inner(snapshot, projection, None)
11886    }
11887
11888    pub fn visible_columns_native_with_control(
11889        &self,
11890        snapshot: Snapshot,
11891        projection: Option<&[u16]>,
11892        control: &crate::ExecutionControl,
11893    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11894        self.visible_columns_native_inner(snapshot, projection, Some(control))
11895    }
11896
11897    fn visible_columns_native_inner(
11898        &self,
11899        snapshot: Snapshot,
11900        projection: Option<&[u16]>,
11901        control: Option<&crate::ExecutionControl>,
11902    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11903        execution_checkpoint(control, 0)?;
11904        let wanted: Vec<u16> = match projection {
11905            Some(p) => p.to_vec(),
11906            None => self.schema.columns.iter().map(|c| c.id).collect(),
11907        };
11908        if self.ttl.is_none()
11909            && self.memtable.is_empty()
11910            && self.mutable_run.is_empty()
11911            && self.run_refs.len() == 1
11912        {
11913            let rr = self.run_refs[0].clone();
11914            let mut reader = self.open_reader(rr.run_id)?;
11915            let idxs = reader.visible_indices_native_at(snapshot)?;
11916            execution_checkpoint(control, 0)?;
11917            let all_visible = idxs.len() == reader.row_count();
11918            // Phase 15.1: decode every requested column in parallel when the
11919            // reader is mmap-backed. Each column already parallel-decodes its
11920            // own pages, so a wide table saturates the pool via nested rayon
11921            // without oversubscribing (work-stealing handles it). Falls back to
11922            // the sequential `&mut` path when mmap is unavailable.
11923            if reader.has_mmap() && control.is_none() {
11924                use rayon::prelude::*;
11925                // Pre-resolve the requested ids that exist in the schema (don't
11926                // capture `self` inside the rayon closure).
11927                let valid: Vec<u16> = wanted
11928                    .iter()
11929                    .filter(|cid| self.schema.columns.iter().any(|c| c.id == **cid))
11930                    .copied()
11931                    .collect();
11932                // Decode concurrently; `collect` preserves `valid` order.
11933                let decoded: Vec<(u16, columnar::NativeColumn)> = valid
11934                    .par_iter()
11935                    .filter_map(|cid| {
11936                        reader
11937                            .column_native_shared(*cid)
11938                            .ok()
11939                            .map(|col| (*cid, col))
11940                    })
11941                    .collect();
11942                let cols = decoded
11943                    .into_iter()
11944                    .map(|(id, col)| (id, if all_visible { col } else { col.gather(&idxs) }))
11945                    .collect();
11946                return Ok(cols);
11947            }
11948            let mut cols = Vec::with_capacity(wanted.len());
11949            for (index, cid) in wanted.iter().enumerate() {
11950                execution_checkpoint(control, index)?;
11951                let cdef = match self.schema.columns.iter().find(|c| c.id == *cid) {
11952                    Some(c) => c,
11953                    None => continue,
11954                };
11955                let col = reader.column_native(cdef.id)?;
11956                cols.push((cdef.id, if all_visible { col } else { col.gather(&idxs) }));
11957            }
11958            return Ok(cols);
11959        }
11960        let vcols = self.visible_columns(snapshot)?;
11961        execution_checkpoint(control, 0)?;
11962        let want_set: std::collections::HashSet<u16> = wanted.iter().copied().collect();
11963        let out: Vec<(u16, columnar::NativeColumn)> = vcols
11964            .into_iter()
11965            .filter(|(id, _)| want_set.contains(id))
11966            .map(|(id, vals)| {
11967                let ty = self
11968                    .schema
11969                    .columns
11970                    .iter()
11971                    .find(|c| c.id == id)
11972                    .map(|c| c.ty.clone())
11973                    .unwrap_or(TypeId::Bytes);
11974                (id, columnar::values_to_native(ty, &vals))
11975            })
11976            .collect();
11977        Ok(out)
11978    }
11979
11980    pub fn run_count(&self) -> usize {
11981        self.run_refs.len()
11982    }
11983
11984    /// Whether the memtable is empty (no unflushed puts).
11985    pub fn memtable_is_empty(&self) -> bool {
11986        self.memtable.is_empty()
11987    }
11988
11989    /// Cumulative raw-page-cache hit/miss counts (Priority 14: hit visibility).
11990    /// Useful for confirming a repeat scan is served from cache or measuring a
11991    /// query's locality after [`reset_page_cache_stats`](Self::reset_page_cache_stats).
11992    pub fn page_cache_stats(&self) -> crate::cache::CacheStats {
11993        self.page_cache.stats()
11994    }
11995
11996    /// Zero the raw-page-cache hit/miss counters.
11997    pub fn reset_page_cache_stats(&self) {
11998        self.page_cache.reset_stats();
11999    }
12000
12001    /// The run IDs in level order (Phase 15.5: used by the Arrow IPC shadow to
12002    /// key shadow files and detect stale shadows).
12003    pub fn run_ids(&self) -> Vec<u128> {
12004        self.run_refs.iter().map(|r| r.run_id).collect()
12005    }
12006
12007    /// Whether the single run (if exactly one) is clean — i.e. has
12008    /// `RUN_FLAG_CLEAN` set (Phase 15.5: the shadow is zero-copy only for clean
12009    /// runs).
12010    pub fn single_run_is_clean(&self) -> bool {
12011        if self.ttl.is_some() || self.run_refs.len() != 1 {
12012            return false;
12013        }
12014        self.open_reader(self.run_refs[0].run_id)
12015            .map(|r| r.is_clean())
12016            .unwrap_or(false)
12017    }
12018
12019    /// Best-effort resolve of the survivor RowId set for fine-grained cache
12020    /// invalidation (hardening (c)). On the single-run fast path, opens a reader
12021    /// and calls `resolve_survivor_rids`. On the multi-run/memtable path,
12022    /// returns an empty bitmap — conservative (condition_cols still catches
12023    /// column mutations, and deletes are caught by the epoch-free design falling
12024    /// through to the multi-run path which re-resolves).
12025    fn resolve_footprint(
12026        &self,
12027        conditions: &[crate::query::Condition],
12028        snapshot: Snapshot,
12029    ) -> roaring::RoaringBitmap {
12030        if !self.memtable.is_empty() || !self.mutable_run.is_empty() {
12031            return roaring::RoaringBitmap::new();
12032        }
12033        if self.run_refs.is_empty() {
12034            return roaring::RoaringBitmap::new();
12035        }
12036        // Try the single-run fast path.
12037        if self.run_refs.len() == 1 {
12038            if let Ok(mut reader) = self.open_reader(self.run_refs[0].run_id) {
12039                if let Ok(rids) = self.resolve_survivor_rids(conditions, &mut reader, snapshot) {
12040                    return rids.to_roaring_lossy();
12041                }
12042            }
12043        }
12044        roaring::RoaringBitmap::new()
12045    }
12046
12047    /// Phase 19.1 + hardening (c): a cached form of
12048    /// [`Table::query_columns_native`]. The cache key embeds the snapshot epoch
12049    /// so two queries at different pinned snapshots never share an entry;
12050    /// invalidation is fine-grained — a `commit()` drops only entries whose
12051    /// footprint intersects a deleted RowId or whose condition-columns intersect
12052    /// a mutated column. On a miss the underlying `query_columns_native` runs and
12053    /// the result is cached as typed `NativeColumn`s. Returns `None` exactly when
12054    /// the non-cached path would (conditions not pushdown-served). Strictly
12055    /// additive — callers wanting fresh results keep using
12056    /// `query_columns_native`.
12057    pub fn query_columns_native_cached(
12058        &mut self,
12059        conditions: &[crate::query::Condition],
12060        projection: Option<&[u16]>,
12061        snapshot: Snapshot,
12062    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12063        self.query_columns_native_cached_inner(conditions, projection, snapshot, None)
12064    }
12065
12066    pub fn query_columns_native_cached_with_control(
12067        &mut self,
12068        conditions: &[crate::query::Condition],
12069        projection: Option<&[u16]>,
12070        snapshot: Snapshot,
12071        control: &crate::ExecutionControl,
12072    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12073        self.query_columns_native_cached_inner(conditions, projection, snapshot, Some(control))
12074    }
12075
12076    fn query_columns_native_cached_inner(
12077        &mut self,
12078        conditions: &[crate::query::Condition],
12079        projection: Option<&[u16]>,
12080        snapshot: Snapshot,
12081        control: Option<&crate::ExecutionControl>,
12082    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12083        execution_checkpoint(control, 0)?;
12084        // Wall-clock expiry changes without an MVCC epoch, so an epoch-keyed
12085        // result can become stale while sitting in the cache.
12086        if self.ttl.is_some() {
12087            return self.query_columns_native_inner(conditions, projection, snapshot, control);
12088        }
12089        if conditions.is_empty() {
12090            return self.query_columns_native_inner(conditions, projection, snapshot, control);
12091        }
12092        // The snapshot epoch is part of the key so two queries with identical
12093        // conditions/projection but pinned at different snapshots never share a
12094        // cached result (MVCC isolation for the explicit-snapshot API).
12095        let key = crate::query::canonical_query_key(conditions, projection, snapshot.epoch.0);
12096        let identity = PersistentCacheIdentity {
12097            table_id: self.table_id(),
12098            schema_id: self.schema.schema_id,
12099            logical_generation: self.current_epoch().0,
12100        };
12101        if let Some(hit) = self.result_cache.lock().get_columns(key, identity) {
12102            crate::trace::QueryTrace::record(|t| {
12103                t.result_cache_hit = true;
12104                t.scan_mode = crate::trace::ScanMode::NativePushdown;
12105            });
12106            return Ok(Some((*hit).clone()));
12107        }
12108        let res = self.query_columns_native_inner(conditions, projection, snapshot, control)?;
12109        execution_checkpoint(control, 0)?;
12110        if let Some(cols) = &res {
12111            let footprint = self.resolve_footprint(conditions, snapshot);
12112            let condition_cols = crate::query::condition_columns(conditions);
12113            execution_checkpoint(control, 0)?;
12114            let entry = CachedEntry {
12115                data: CachedData::Columns(Arc::new(cols.clone())),
12116                footprint,
12117                condition_cols,
12118            };
12119            // Compute everything we need, then take the lock once. The
12120            // `ResultCache` lock is a non-reentrant `parking_lot::Mutex` so
12121            // `persist_entry` + `insert` must run in the same critical
12122            // section. `persist_entry` enqueues onto the background writer
12123            // or skips publication with a metric — never query-thread I/O.
12124            let mut cache = self.result_cache.lock();
12125            let entry_generation = cache.allocate_persist_generation(key);
12126            let context = PersistContext {
12127                identity,
12128                key,
12129                entry_generation,
12130            };
12131            cache.persist_entry(context, &entry);
12132            cache.insert(key, entry);
12133        }
12134        Ok(res)
12135    }
12136
12137    /// Phase 19.1 + hardening (c): a cached form of [`Table::query`]. The cache key
12138    /// is epoch-independent; invalidation is fine-grained (see
12139    /// [`Table::query_columns_native_cached`]). On a hit returns the cached rows (no
12140    /// re-resolve, no re-decode).
12141    pub fn query_cached(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
12142        if self.ttl.is_some() {
12143            return self.query(q);
12144        }
12145        if q.conditions.is_empty() {
12146            return self.query(q);
12147        }
12148        let key = crate::query::canonical_query_key(&q.conditions, None, 0)
12149            ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
12150            ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
12151        let identity = PersistentCacheIdentity {
12152            table_id: self.table_id(),
12153            schema_id: self.schema.schema_id,
12154            logical_generation: self.current_epoch().0,
12155        };
12156        if let Some(hit) = self.result_cache.lock().get_rows(key, identity) {
12157            crate::trace::QueryTrace::record(|t| {
12158                t.result_cache_hit = true;
12159                t.scan_mode = crate::trace::ScanMode::Materialized;
12160            });
12161            return Ok((*hit).clone());
12162        }
12163        let rows = self.query(q)?;
12164        let footprint = rows.iter().map(|r| r.row_id.0 as u32).collect();
12165        let condition_cols = crate::query::condition_columns(&q.conditions);
12166        let entry = CachedEntry {
12167            data: CachedData::Rows(Arc::new(rows.clone())),
12168            footprint,
12169            condition_cols,
12170        };
12171        // Take the lock once: persist_entry + insert must run atomically
12172        // because `ResultCache` uses a non-reentrant `parking_lot::Mutex`.
12173        // `persist_entry` enqueues onto the background writer or skips
12174        // publication with a metric — never query-thread I/O (REM-D §8.5).
12175        let mut cache = self.result_cache.lock();
12176        let entry_generation = cache.allocate_persist_generation(key);
12177        let context = PersistContext {
12178            identity,
12179            key,
12180            entry_generation,
12181        };
12182        cache.persist_entry(context, &entry);
12183        cache.insert(key, entry);
12184        Ok(rows)
12185    }
12186
12187    // -----------------------------------------------------------------------
12188    // Traced query wrappers (OPTIMIZATIONS.md Priority 0 / 16).
12189    //
12190    // Each `_traced` method runs its underlying query inside a
12191    // [`crate::trace::QueryTrace::capture`] scope and returns the result
12192    // alongside the captured path trace. The trace records which physical path
12193    // served the query (cursor / pushdown / materialized / count-shortcut),
12194    // whether indexes were rebuilt, whether the result cache hit, overlay size,
12195    // survivor count, and the fast row-id map usage. Recording is zero-cost
12196    // when no `_traced` method is on the call stack (the plain methods are
12197    // unchanged).
12198    // -----------------------------------------------------------------------
12199
12200    /// [`Self::query_columns_native`] with a captured [`crate::trace::QueryTrace`].
12201    #[allow(clippy::type_complexity)]
12202    pub fn query_columns_native_traced(
12203        &mut self,
12204        conditions: &[crate::query::Condition],
12205        projection: Option<&[u16]>,
12206        snapshot: Snapshot,
12207    ) -> Result<(
12208        Option<Vec<(u16, columnar::NativeColumn)>>,
12209        crate::trace::QueryTrace,
12210    )> {
12211        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12212            self.query_columns_native(conditions, projection, snapshot)
12213        });
12214        Ok((result?, trace))
12215    }
12216
12217    /// [`Self::query_columns_native_cached`] with a captured
12218    /// [`crate::trace::QueryTrace`] (records result-cache hits too).
12219    #[allow(clippy::type_complexity)]
12220    pub fn query_columns_native_cached_traced(
12221        &mut self,
12222        conditions: &[crate::query::Condition],
12223        projection: Option<&[u16]>,
12224        snapshot: Snapshot,
12225    ) -> Result<(
12226        Option<Vec<(u16, columnar::NativeColumn)>>,
12227        crate::trace::QueryTrace,
12228    )> {
12229        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12230            self.query_columns_native_cached(conditions, projection, snapshot)
12231        });
12232        Ok((result?, trace))
12233    }
12234
12235    /// [`Self::native_page_cursor`] with a captured [`crate::trace::QueryTrace`].
12236    pub fn native_page_cursor_traced(
12237        &self,
12238        snapshot: Snapshot,
12239        projection: Vec<(u16, TypeId)>,
12240        conditions: &[crate::query::Condition],
12241    ) -> Result<(Option<NativePageCursor>, crate::trace::QueryTrace)> {
12242        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12243            self.native_page_cursor(snapshot, projection, conditions)
12244        });
12245        Ok((result?, trace))
12246    }
12247
12248    /// [`Self::native_multi_run_cursor`] with a captured [`crate::trace::QueryTrace`].
12249    pub fn native_multi_run_cursor_traced(
12250        &self,
12251        snapshot: Snapshot,
12252        projection: Vec<(u16, TypeId)>,
12253        conditions: &[crate::query::Condition],
12254    ) -> Result<(
12255        Option<crate::cursor::MultiRunCursor>,
12256        crate::trace::QueryTrace,
12257    )> {
12258        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12259            self.native_multi_run_cursor(snapshot, projection, conditions)
12260        });
12261        Ok((result?, trace))
12262    }
12263
12264    /// [`Self::count_conditions`] with a captured [`crate::trace::QueryTrace`].
12265    pub fn count_conditions_traced(
12266        &mut self,
12267        conditions: &[crate::query::Condition],
12268        snapshot: Snapshot,
12269    ) -> Result<(Option<u64>, crate::trace::QueryTrace)> {
12270        let (result, trace) =
12271            crate::trace::QueryTrace::capture(|| self.count_conditions(conditions, snapshot));
12272        Ok((result?, trace))
12273    }
12274
12275    /// [`Self::query`] with a captured [`crate::trace::QueryTrace`].
12276    pub fn query_traced(
12277        &mut self,
12278        q: &crate::query::Query,
12279    ) -> Result<(Vec<Row>, crate::trace::QueryTrace)> {
12280        let (result, trace) = crate::trace::QueryTrace::capture(|| self.query(q));
12281        Ok((result?, trace))
12282    }
12283
12284    /// Predicate pushdown: resolve `conditions` via indexes to find the matching
12285    /// row-id set, then decode only those rows' columns — not the whole table.
12286    /// Returns `None` if the conditions can't be served by indexes (caller falls
12287    /// back to a full scan). This is the fast path for `WHERE col = 'value'`.
12288    pub fn query_columns_native(
12289        &mut self,
12290        conditions: &[crate::query::Condition],
12291        projection: Option<&[u16]>,
12292        snapshot: Snapshot,
12293    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12294        self.query_columns_native_inner(conditions, projection, snapshot, None)
12295    }
12296
12297    pub fn query_columns_native_with_control(
12298        &mut self,
12299        conditions: &[crate::query::Condition],
12300        projection: Option<&[u16]>,
12301        snapshot: Snapshot,
12302        control: &crate::ExecutionControl,
12303    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12304        self.query_columns_native_inner(conditions, projection, snapshot, Some(control))
12305    }
12306
12307    fn query_columns_native_inner(
12308        &mut self,
12309        conditions: &[crate::query::Condition],
12310        projection: Option<&[u16]>,
12311        snapshot: Snapshot,
12312        control: Option<&crate::ExecutionControl>,
12313    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12314        use crate::query::Condition;
12315        execution_checkpoint(control, 0)?;
12316        // TTL reads use the materialized visibility path so the wall-clock
12317        // cutoff is captured once and applied to every storage tier.
12318        if self.ttl.is_some() {
12319            return Ok(None);
12320        }
12321        if conditions.is_empty() {
12322            return Ok(None);
12323        }
12324        self.ensure_indexes_complete()?;
12325
12326        // Only these conditions are pushdown-served. Range/RangeF64 need a
12327        // column read on the single-run fast path; off it they fall back to a
12328        // visible-rows scan via `resolve_condition` (still correct for any
12329        // layout, just not page-pruned).
12330        let served = |c: &Condition| {
12331            matches!(
12332                c,
12333                Condition::Pk(_)
12334                    | Condition::BitmapEq { .. }
12335                    | Condition::BitmapIn { .. }
12336                    | Condition::BytesPrefix { .. }
12337                    | Condition::FmContains { .. }
12338                    | Condition::FmContainsAll { .. }
12339                    | Condition::Ann { .. }
12340                    | Condition::Range { .. }
12341                    | Condition::RangeF64 { .. }
12342                    | Condition::SparseMatch { .. }
12343                    | Condition::MinHashSimilar { .. }
12344                    | Condition::IsNull { .. }
12345                    | Condition::IsNotNull { .. }
12346            )
12347        };
12348        if !conditions.iter().all(served) {
12349            return Ok(None);
12350        }
12351        let fast_path =
12352            self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
12353        crate::trace::QueryTrace::record(|t| {
12354            t.run_count = self.run_refs.len();
12355            t.memtable_rows = self.memtable.len();
12356            t.mutable_run_rows = self.mutable_run.len();
12357            t.conditions_pushed = conditions.len();
12358            t.learned_range_used = conditions.iter().any(|c| match c {
12359                Condition::Range { column_id, .. } | Condition::RangeF64 { column_id, .. } => {
12360                    self.learned_range.contains_key(column_id)
12361                }
12362                _ => false,
12363            });
12364        });
12365        // Build column list (projected or all user columns) + projection pairs.
12366        let col_ids: Vec<u16> = projection
12367            .map(|p| p.to_vec())
12368            .unwrap_or_else(|| self.schema.columns.iter().map(|c| c.id).collect());
12369        let proj_pairs: Vec<(u16, TypeId)> = col_ids
12370            .iter()
12371            .map(|&cid| {
12372                let ty = self
12373                    .schema
12374                    .columns
12375                    .iter()
12376                    .find(|c| c.id == cid)
12377                    .map(|c| c.ty.clone())
12378                    .unwrap_or(TypeId::Bytes);
12379                (cid, ty)
12380            })
12381            .collect();
12382
12383        // -----------------------------------------------------------------------
12384        // Fast path: single run, empty memtable/mutable-run → resolve survivors,
12385        // binary-search positions, gather only the projected columns from one
12386        // reader. This is the fastest pushdown path (no cursor overhead).
12387        // -----------------------------------------------------------------------
12388        if fast_path {
12389            // A Range/RangeF64 needs a column read *unless* its column has a
12390            // learned (PGM) range index, in which case it's served in-memory.
12391            let needs_column = conditions.iter().any(|c| match c {
12392                Condition::Range { column_id, .. } => !self.learned_range.contains_key(column_id),
12393                Condition::RangeF64 { column_id, .. } => {
12394                    !self.learned_range.contains_key(column_id)
12395                }
12396                _ => false,
12397            });
12398            let mut reader_opt: Option<RunReader> = if needs_column {
12399                Some(self.open_reader(self.run_refs[0].run_id)?)
12400            } else {
12401                None
12402            };
12403            let mut sets: Vec<RowIdSet> = Vec::new();
12404            for (index, c) in conditions.iter().enumerate() {
12405                execution_checkpoint(control, index)?;
12406                let s = match c {
12407                    Condition::Range { column_id, lo, hi }
12408                        if !self.learned_range.contains_key(column_id) =>
12409                    {
12410                        if reader_opt.is_none() {
12411                            reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12412                        }
12413                        reader_opt
12414                            .as_mut()
12415                            .expect("reader opened for range")
12416                            .range_row_id_set_i64(*column_id, *lo, *hi)?
12417                    }
12418                    Condition::RangeF64 {
12419                        column_id,
12420                        lo,
12421                        lo_inclusive,
12422                        hi,
12423                        hi_inclusive,
12424                    } if !self.learned_range.contains_key(column_id) => {
12425                        if reader_opt.is_none() {
12426                            reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12427                        }
12428                        reader_opt
12429                            .as_mut()
12430                            .expect("reader opened for range")
12431                            .range_row_id_set_f64(
12432                                *column_id,
12433                                *lo,
12434                                *lo_inclusive,
12435                                *hi,
12436                                *hi_inclusive,
12437                            )?
12438                    }
12439                    _ => self.resolve_condition(c, snapshot)?,
12440                };
12441                sets.push(s);
12442            }
12443            let candidates = RowIdSet::intersect_many(sets);
12444            crate::trace::QueryTrace::record(|t| {
12445                t.survivor_count = Some(candidates.len());
12446            });
12447            if candidates.is_empty() {
12448                let cols: Vec<(u16, columnar::NativeColumn)> = col_ids
12449                    .iter()
12450                    .map(|&id| {
12451                        (
12452                            id,
12453                            columnar::null_native(
12454                                proj_pairs
12455                                    .iter()
12456                                    .find(|(c, _)| c == &id)
12457                                    .map(|(_, t)| t.clone())
12458                                    .unwrap_or(TypeId::Bytes),
12459                                0,
12460                            ),
12461                        )
12462                    })
12463                    .collect();
12464                return Ok(Some(cols));
12465            }
12466            let mut reader = match reader_opt.take() {
12467                Some(r) => r,
12468                None => self.open_reader(self.run_refs[0].run_id)?,
12469            };
12470            let candidate_ids = candidates.into_sorted_vec();
12471            let (positions, fast_rid) = if let Some(positions) =
12472                reader.positions_for_row_ids_fast(&candidate_ids)
12473            {
12474                (positions, true)
12475            } else {
12476                let col = reader.column_native(crate::sorted_run::SYS_ROW_ID)?;
12477                match col {
12478                    columnar::NativeColumn::Int64 { data, .. } => {
12479                        let mut p = Vec::with_capacity(candidate_ids.len());
12480                        for (index, rid) in candidate_ids.iter().enumerate() {
12481                            execution_checkpoint(control, index)?;
12482                            if let Ok(position) = data.binary_search(&(*rid as i64)) {
12483                                p.push(position);
12484                            }
12485                        }
12486                        p.sort_unstable();
12487                        (p, false)
12488                    }
12489                    _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
12490                }
12491            };
12492            crate::trace::QueryTrace::record(|t| {
12493                t.scan_mode = crate::trace::ScanMode::NativePushdown;
12494                t.fast_row_id_map = fast_rid;
12495            });
12496            let mut cols = Vec::with_capacity(col_ids.len());
12497            for (index, cid) in col_ids.iter().enumerate() {
12498                execution_checkpoint(control, index)?;
12499                let col = reader.column_native(*cid)?;
12500                cols.push((*cid, col.gather(&positions)));
12501            }
12502            return Ok(Some(cols));
12503        }
12504
12505        // -----------------------------------------------------------------------
12506        // Non-fast path (multi-run / non-empty overlay). Route through the
12507        // columnar cursor (OPTIMIZATIONS.md Priority 1 + 4): the cursor builder
12508        // resolves MVCC, predicates, and overlay internally in batch, then
12509        // streams projected columns page-by-page. This avoids the per-rid
12510        // `rows_for_rids` `get_version`-across-all-runs cost that made multi-run
12511        // pushdown ~1000× slower than the single-run fast path.
12512        //
12513        // The cursor handles both single-run-with-overlay (`native_page_cursor`)
12514        // and multi-run (`native_multi_run_cursor`) layouts. The empty-table
12515        // (no runs, memtable-only) edge case falls through to `rows_for_rids`.
12516        // -----------------------------------------------------------------------
12517        if !self.run_refs.is_empty() {
12518            use crate::cursor::{
12519                drain_cursor_to_columns, drain_cursor_to_columns_with_control, Cursor,
12520            };
12521            let remaining: usize;
12522            let mut cursor: Box<dyn crate::cursor::Cursor> = if self.run_refs.len() == 1 {
12523                let c = self
12524                    .native_page_cursor(snapshot, proj_pairs.clone(), conditions)?
12525                    .expect("single-run cursor should build when run_refs.len() == 1");
12526                remaining = c.remaining_rows();
12527                Box::new(c)
12528            } else {
12529                let c = self
12530                    .native_multi_run_cursor(snapshot, proj_pairs.clone(), conditions)?
12531                    .expect("multi-run cursor should build when run_refs.len() >= 1");
12532                remaining = c.remaining_rows();
12533                Box::new(c)
12534            };
12535            crate::trace::QueryTrace::record(|t| {
12536                if t.survivor_count.is_none() {
12537                    t.survivor_count = Some(remaining);
12538                }
12539            });
12540            let cols = match control {
12541                Some(control) => {
12542                    drain_cursor_to_columns_with_control(cursor.as_mut(), &proj_pairs, control)?
12543                }
12544                None => drain_cursor_to_columns(cursor.as_mut(), &proj_pairs)?,
12545            };
12546            return Ok(Some(cols));
12547        }
12548
12549        // Empty-table fallback (no sorted runs, memtable/mutable-run only): the
12550        // cursor builders return `None` for `run_refs.is_empty()`, so resolve
12551        // from overlay indexes and materialize via `rows_for_rids`. This is the
12552        // rare edge case (fresh table with only `put`s, no `flush`/`bulk_load`).
12553        crate::trace::QueryTrace::record(|t| {
12554            t.scan_mode = crate::trace::ScanMode::Materialized;
12555            t.row_materialized = true;
12556        });
12557        let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12558        for (index, c) in conditions.iter().enumerate() {
12559            execution_checkpoint(control, index)?;
12560            sets.push(self.resolve_condition(c, snapshot)?);
12561        }
12562        let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
12563        let rows = self.rows_for_rids(&rids, snapshot)?;
12564        let mut cols: Vec<(u16, columnar::NativeColumn)> = Vec::with_capacity(col_ids.len());
12565        for (index, (cid, ty)) in proj_pairs.iter().enumerate() {
12566            execution_checkpoint(control, index)?;
12567            let vals: Vec<Value> = rows
12568                .iter()
12569                .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
12570                .collect();
12571            cols.push((*cid, columnar::values_to_native(ty.clone(), &vals)));
12572        }
12573        Ok(Some(cols))
12574    }
12575
12576    /// Build a lazy, page-aware [`NativePageCursor`] for the single-run fast
12577    /// path. MVCC visibility and predicate survivor resolution are settled up
12578    /// front (so they see the live indexes under the DB lock); the cursor then
12579    /// owns the reader and decodes only the projected columns of pages that
12580    /// contain survivors, lazily. This is the fused-predicate + page-skip +
12581    /// late-materialization scan.
12582    ///
12583    /// Phase 13.1: the memtable / mutable-run overlay is now handled. Rows with
12584    /// a newer version in the overlay are excluded from the run's page plans
12585    /// (their run version is stale); the overlay rows are pre-materialized and
12586    /// appended as a final batch via [`NativePageCursor::new_with_overlay`].
12587    ///
12588    /// Returns `None` only for multiple sorted runs; the caller falls back to
12589    /// the materialize-then-stream scan for that layout.
12590    pub fn native_page_cursor(
12591        &self,
12592        snapshot: Snapshot,
12593        projection: Vec<(u16, TypeId)>,
12594        conditions: &[crate::query::Condition],
12595    ) -> Result<Option<NativePageCursor>> {
12596        use crate::cursor::build_page_plans;
12597        if self.ttl.is_some() {
12598            return Ok(None);
12599        }
12600        // See `scan_cursor`: incomplete (deferred) indexes cannot resolve
12601        // conditions — signal "can't serve" instead of empty survivor sets.
12602        if !conditions.is_empty() && !self.indexes_complete {
12603            return Ok(None);
12604        }
12605        if self.run_refs.len() != 1 {
12606            return Ok(None);
12607        }
12608        let mut reader = self.open_reader(self.run_refs[0].run_id)?;
12609        let (positions, rids) = reader.visible_positions_with_rids_at(snapshot)?;
12610
12611        // Collect overlay rows from memtable + mutable_run (visible, newest
12612        // version per row). These shadow any stale version in the run.
12613        let overlay_rids: HashSet<u64> = {
12614            let mut s = HashSet::new();
12615            for row in self.memtable.visible_versions_at(snapshot) {
12616                s.insert(row.row_id.0);
12617            }
12618            for row in self.mutable_run.visible_versions_at(snapshot) {
12619                s.insert(row.row_id.0);
12620            }
12621            s
12622        };
12623
12624        // Resolve survivor rids via indexes (covers overlay rows for index-
12625        // served conditions: PK, bitmap, FM, ANN, sparse — all maintained on
12626        // every put).
12627        let survivors = if conditions.is_empty() {
12628            None
12629        } else {
12630            Some(self.resolve_survivor_rids(conditions, &mut reader, snapshot)?)
12631        };
12632
12633        // Exclude overlay rids from the run portion: their version in the run
12634        // is stale (updated/deleted in the overlay) or they don't exist in the
12635        // run (new inserts). When there are conditions, we remove overlay rids
12636        // from the survivor set. When there are no conditions, we synthesize a
12637        // survivor set = (all visible run rids) − (overlay rids) so the stale
12638        // run rows are pruned.
12639        let run_survivors: Option<RowIdSet> = if overlay_rids.is_empty() {
12640            survivors.clone()
12641        } else if let Some(s) = &survivors {
12642            let mut run_set = s.clone();
12643            run_set.remove_many(overlay_rids.iter().copied());
12644            Some(run_set)
12645        } else {
12646            Some(RowIdSet::from_unsorted(
12647                rids.iter()
12648                    .map(|&r| r as u64)
12649                    .filter(|r| !overlay_rids.contains(r))
12650                    .collect(),
12651            ))
12652        };
12653
12654        let overlay_rows = if overlay_rids.is_empty() {
12655            Vec::new()
12656        } else {
12657            let bound = Self::overlay_materialization_bound(conditions, &survivors);
12658            self.overlay_visible_rows(snapshot, bound)
12659        };
12660
12661        // Build page plans for the run portion.
12662        let plans = if positions.is_empty() {
12663            Vec::new()
12664        } else {
12665            let page_rows = reader.page_row_counts(crate::sorted_run::SYS_ROW_ID)?;
12666            build_page_plans(&positions, &rids, &page_rows, run_survivors.as_ref())
12667        };
12668
12669        // Filter and materialize the overlay.
12670        let overlay = if overlay_rows.is_empty() {
12671            None
12672        } else {
12673            let filtered =
12674                self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12675            if filtered.is_empty() {
12676                None
12677            } else {
12678                Some(self.materialize_overlay(&filtered, &projection))
12679            }
12680        };
12681
12682        let overlay_row_count = overlay
12683            .as_ref()
12684            .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12685            .unwrap_or(0);
12686        crate::trace::QueryTrace::record(|t| {
12687            t.scan_mode = crate::trace::ScanMode::NativePageCursor;
12688            t.run_count = self.run_refs.len();
12689            t.memtable_rows = self.memtable.len();
12690            t.mutable_run_rows = self.mutable_run.len();
12691            t.overlay_rows = overlay_row_count;
12692            t.conditions_pushed = conditions.len();
12693            t.pages_decoded = plans
12694                .iter()
12695                .map(|p| p.positions.len())
12696                .sum::<usize>()
12697                .min(1);
12698        });
12699
12700        Ok(Some(NativePageCursor::new_with_overlay(
12701            reader, projection, plans, overlay,
12702        )))
12703    }
12704    /// Generalizes [`Self::native_page_cursor`] (single-run) to arbitrary run
12705    /// counts via a k-way merge by `RowId`. Cross-run MVCC resolution (newest
12706    /// visible version per `RowId`) and predicate survivor resolution are settled
12707    /// up front from the cheap system columns + global indexes; the cursor then
12708    /// lazily decodes the projected data columns of just the pages that own
12709    /// survivors, each page at most once. The memtable / mutable-run overlay is
12710    /// materialized and yielded as a final batch (mirroring the single-run path).
12711    ///
12712    /// Returns `None` only when there are no runs at all (caller falls back).
12713    #[allow(clippy::type_complexity)]
12714    pub fn native_multi_run_cursor(
12715        &self,
12716        snapshot: Snapshot,
12717        projection: Vec<(u16, TypeId)>,
12718        conditions: &[crate::query::Condition],
12719    ) -> Result<Option<crate::cursor::MultiRunCursor>> {
12720        use crate::cursor::{MultiRunCursor, RunStream};
12721        use crate::sorted_run::SYS_ROW_ID;
12722        use std::collections::{BinaryHeap, HashMap, HashSet};
12723        if self.ttl.is_some() {
12724            return Ok(None);
12725        }
12726        // See `scan_cursor`: incomplete (deferred) indexes cannot resolve
12727        // conditions — signal "can't serve" instead of empty survivor sets.
12728        if !conditions.is_empty() && !self.indexes_complete {
12729            return Ok(None);
12730        }
12731        if self.run_refs.is_empty() {
12732            return Ok(None);
12733        }
12734
12735        // Open each run once; read its system columns + page layout.
12736        let mut run_meta: Vec<(
12737            RunReader,
12738            Vec<i64>,
12739            Vec<i64>,
12740            Vec<u8>,
12741            Option<Vec<Option<HlcTimestamp>>>,
12742            Vec<usize>,
12743        )> = Vec::with_capacity(self.run_refs.len());
12744        for rr in &self.run_refs {
12745            let mut reader = self.open_reader(rr.run_id)?;
12746            let (rids, eps, del) = reader.system_columns_native()?;
12747            let page_rows = reader.page_row_counts(SYS_ROW_ID)?;
12748            let commit_ts: Option<Vec<Option<HlcTimestamp>>> =
12749                if reader.has_column(crate::sorted_run::SYS_COMMIT_TS) {
12750                    let col = reader.column_native(crate::sorted_run::SYS_COMMIT_TS)?;
12751                    Some(
12752                        (0..rids.len())
12753                            .map(|i| {
12754                                crate::sorted_run::decode_commit_ts_value(col.value_at(i).as_ref())
12755                            })
12756                            .collect(),
12757                    )
12758                } else {
12759                    None
12760                };
12761            run_meta.push((reader, rids, eps, del, commit_ts, page_rows));
12762        }
12763
12764        // Global cross-run newest-version resolution: rid -> (epoch, run_idx,
12765        // position, deleted). Mirrors `visible_rows`, tracking which run owns
12766        // the newest MVCC-visible version. HLC stamps participate via
12767        // `Snapshot::observes_row` and `version_is_newer` so an HLC-pinned
12768        // snapshot surfaces the HLC-newer winner regardless of local epoch.
12769        let mut best: HashMap<u64, (Epoch, Option<HlcTimestamp>, usize, usize, bool)> =
12770            HashMap::new();
12771        for (run_idx, (_, rids, eps, del, commit_ts, _)) in run_meta.iter().enumerate() {
12772            for i in 0..rids.len() {
12773                let rid = rids[i] as u64;
12774                let e = Epoch(eps[i] as u64);
12775                let ts = commit_ts.as_ref().and_then(|v| v.get(i).copied().flatten());
12776                if !snapshot.observes_row(e, ts) {
12777                    continue;
12778                }
12779                let is_del = del[i] != 0;
12780                best.entry(rid)
12781                    .and_modify(|cur| {
12782                        if Snapshot::version_is_newer(e, ts, cur.0, cur.1) {
12783                            *cur = (e, ts, run_idx, i, is_del);
12784                        }
12785                    })
12786                    .or_insert((e, ts, run_idx, i, is_del));
12787            }
12788        }
12789
12790        // Overlay rids (memtable + mutable-run) shadow every run version.
12791        let overlay_rids: HashSet<u64> = {
12792            let mut s = HashSet::new();
12793            for row in self.memtable.visible_versions_at(snapshot) {
12794                s.insert(row.row_id.0);
12795            }
12796            for row in self.mutable_run.visible_versions_at(snapshot) {
12797                s.insert(row.row_id.0);
12798            }
12799            s
12800        };
12801
12802        // Predicate survivors (global, layout-independent).
12803        let survivors: Option<RowIdSet> = if conditions.is_empty() {
12804            None
12805        } else {
12806            let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12807            for c in conditions {
12808                sets.push(self.resolve_condition(c, snapshot)?);
12809            }
12810            Some(RowIdSet::intersect_many(sets))
12811        };
12812
12813        // Per-run owned survivors: (rid, position), ascending by rid. A row is
12814        // owned by the run holding its newest visible version, is not deleted,
12815        // is not shadowed by the overlay, and satisfies the predicate.
12816        let mut per_run: Vec<Vec<(u64, usize)>> = vec![Vec::new(); run_meta.len()];
12817        for (rid, (_, _, run_idx, pos, deleted)) in &best {
12818            if *deleted {
12819                continue;
12820            }
12821            if overlay_rids.contains(rid) {
12822                continue;
12823            }
12824            if let Some(s) = &survivors {
12825                if !s.contains(*rid) {
12826                    continue;
12827                }
12828            }
12829            per_run[*run_idx].push((*rid, *pos));
12830        }
12831        for v in per_run.iter_mut() {
12832            v.sort_unstable_by_key(|&(rid, _)| rid);
12833        }
12834
12835        // Build the merge streams: map each owned position to (page_seq, within).
12836        let mut streams = Vec::with_capacity(run_meta.len());
12837        let mut heap: BinaryHeap<std::cmp::Reverse<(u64, usize)>> = BinaryHeap::new();
12838        let mut total = 0usize;
12839        for (run_idx, (reader, _, _, _, _, page_rows)) in run_meta.into_iter().enumerate() {
12840            let mut starts = Vec::with_capacity(page_rows.len());
12841            let mut acc = 0usize;
12842            for &r in &page_rows {
12843                starts.push(acc);
12844                acc += r;
12845            }
12846            let mut survivors_vec: Vec<(u64, usize, usize)> =
12847                Vec::with_capacity(per_run[run_idx].len());
12848            for &(rid, pos) in &per_run[run_idx] {
12849                let page_seq = match starts.partition_point(|&s| s <= pos) {
12850                    0 => continue,
12851                    p => p - 1,
12852                };
12853                let within = pos - starts[page_seq];
12854                survivors_vec.push((rid, page_seq, within));
12855            }
12856            total += survivors_vec.len();
12857            if let Some(&(rid, _, _)) = survivors_vec.first() {
12858                heap.push(std::cmp::Reverse((rid, run_idx)));
12859            }
12860            streams.push(RunStream::new(reader, survivors_vec, page_rows));
12861        }
12862
12863        // Materialize the overlay (filtered + projected), yielded as the final batch.
12864        let overlay_rows = if overlay_rids.is_empty() {
12865            Vec::new()
12866        } else {
12867            let bound = Self::overlay_materialization_bound(conditions, &survivors);
12868            self.overlay_visible_rows(snapshot, bound)
12869        };
12870        let overlay = if overlay_rows.is_empty() {
12871            None
12872        } else {
12873            let filtered =
12874                self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12875            if filtered.is_empty() {
12876                None
12877            } else {
12878                Some(self.materialize_overlay(&filtered, &projection))
12879            }
12880        };
12881
12882        let overlay_row_count = overlay
12883            .as_ref()
12884            .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12885            .unwrap_or(0);
12886        crate::trace::QueryTrace::record(|t| {
12887            t.scan_mode = crate::trace::ScanMode::MultiRunCursor;
12888            t.run_count = self.run_refs.len();
12889            t.memtable_rows = self.memtable.len();
12890            t.mutable_run_rows = self.mutable_run.len();
12891            t.overlay_rows = overlay_row_count;
12892            t.conditions_pushed = conditions.len();
12893            t.survivor_count = Some(total);
12894        });
12895
12896        Ok(Some(MultiRunCursor::new(
12897            streams, projection, heap, total, overlay,
12898        )))
12899    }
12900
12901    /// Collect visible, non-deleted overlay rows from the memtable and mutable-
12902    /// run tier at `snapshot`. These are the rows whose data lives only in the
12903    /// in-memory buffers (not yet in a sorted run), or that shadow a stale
12904    /// version in the run.
12905    /// The survivor set that bounds overlay materialization (Priority 2), or
12906    /// `None` when overlay rows must be fully materialized — i.e. there is a
12907    /// `Range`/`RangeF64` residual, for which the index-served survivor set does
12908    /// not cover matching overlay rows (those are evaluated downstream). This
12909    /// mirrors the `all_index_served` branch of
12910    /// [`filter_overlay_rows`](Self::filter_overlay_rows), so bounding here is
12911    /// result-preserving.
12912    fn overlay_materialization_bound<'a>(
12913        conditions: &[crate::query::Condition],
12914        survivors: &'a Option<RowIdSet>,
12915    ) -> Option<&'a RowIdSet> {
12916        use crate::query::Condition;
12917        let has_range = conditions
12918            .iter()
12919            .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12920        if has_range {
12921            None
12922        } else {
12923            survivors.as_ref()
12924        }
12925    }
12926
12927    /// Materialize the visible overlay rows (memtable + mutable-run, newest
12928    /// version per row, non-deleted).
12929    ///
12930    /// Priority 2 (selective overlay probing): when `bound` is `Some`, only rows
12931    /// whose id is in it are materialized. The caller passes the index-resolved
12932    /// survivor set as `bound` exactly when every condition is index-served — in
12933    /// which case [`filter_overlay_rows`](Self::filter_overlay_rows) would discard
12934    /// any non-survivor overlay row anyway, so this prunes the materialization
12935    /// without changing the result. With a Range/RangeF64 residual the survivor
12936    /// set is incomplete for overlay rows, so the caller passes `None` (full
12937    /// materialization) and the range is re-evaluated downstream.
12938    fn overlay_visible_rows(&self, snapshot: Snapshot, bound: Option<&RowIdSet>) -> Vec<Row> {
12939        let mut best: HashMap<u64, (Epoch, Row)> = HashMap::new();
12940        let mut fold = |row: Row| {
12941            if let Some(b) = bound {
12942                if !b.contains(row.row_id.0) {
12943                    return;
12944                }
12945            }
12946            best.entry(row.row_id.0)
12947                .and_modify(|(be, br)| {
12948                    if row.committed_epoch > *be {
12949                        *be = row.committed_epoch;
12950                        *br = row.clone();
12951                    }
12952                })
12953                .or_insert_with(|| (row.committed_epoch, row));
12954        };
12955        for row in self.memtable.visible_versions_at(snapshot) {
12956            fold(row);
12957        }
12958        for row in self.mutable_run.visible_versions_at(snapshot) {
12959            fold(row);
12960        }
12961        let mut out: Vec<Row> = best
12962            .into_values()
12963            .filter_map(|(_, r)| if r.deleted { None } else { Some(r) })
12964            .collect();
12965        out.sort_by_key(|r| r.row_id);
12966        out
12967    }
12968
12969    /// Filter overlay rows against the conjunctive predicate. Range / RangeF64
12970    /// are evaluated directly (the reader-served survivor set misses overlay
12971    /// rows). All other conditions are index-served (indexes maintained on
12972    /// every `put`) so the intersected `survivors` set includes overlay rows
12973    /// that match — but ONLY when every condition is index-served. When there
12974    /// is a mix, we compute per-condition index sets for non-range conditions
12975    /// and evaluate range conditions directly, so the intersection is correct.
12976    fn filter_overlay_rows(
12977        &self,
12978        rows: Vec<Row>,
12979        conditions: &[crate::query::Condition],
12980        survivors: Option<&RowIdSet>,
12981        snapshot: Snapshot,
12982    ) -> Result<Vec<Row>> {
12983        if conditions.is_empty() {
12984            return Ok(rows);
12985        }
12986        use crate::query::Condition;
12987        // Determine whether every condition is index-served (survivors set is
12988        // then complete for overlay rows). If so, a simple membership check
12989        // suffices and is cheapest.
12990        let all_index_served = !conditions
12991            .iter()
12992            .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12993        if all_index_served {
12994            return Ok(rows
12995                .into_iter()
12996                .filter(|r| survivors.is_none_or(|s| s.contains(r.row_id.0)))
12997                .collect());
12998        }
12999        // Mixed: compute per-condition index sets for non-range conditions, and
13000        // evaluate range conditions directly on column values.
13001        let mut per_cond_sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
13002        for c in conditions {
13003            let s = match c {
13004                Condition::Range { .. } | Condition::RangeF64 { .. } => RowIdSet::empty(),
13005                _ => self.resolve_condition(c, snapshot)?,
13006            };
13007            per_cond_sets.push(s);
13008        }
13009        Ok(rows
13010            .into_iter()
13011            .filter(|row| {
13012                conditions.iter().enumerate().all(|(i, c)| match c {
13013                    Condition::Range { column_id, lo, hi } => {
13014                        matches!(row.columns.get(column_id), Some(Value::Int64(v)) if *v >= *lo && *v <= *hi)
13015                    }
13016                    Condition::RangeF64 { column_id, lo, lo_inclusive, hi, hi_inclusive } => {
13017                        match row.columns.get(column_id) {
13018                            Some(Value::Float64(v)) => {
13019                                let lo_ok = if *lo_inclusive { *v >= *lo } else { *v > *lo };
13020                                let hi_ok = if *hi_inclusive { *v <= *hi } else { *v < *hi };
13021                                lo_ok && hi_ok
13022                            }
13023                            _ => false,
13024                        }
13025                    }
13026                    _ => per_cond_sets[i].contains(row.row_id.0),
13027                })
13028            })
13029            .collect())
13030    }
13031
13032    /// Materialize overlay rows into typed `NativeColumn`s for the cursor's
13033    /// final batch.
13034    fn materialize_overlay(
13035        &self,
13036        rows: &[Row],
13037        projection: &[(u16, TypeId)],
13038    ) -> Vec<columnar::NativeColumn> {
13039        if projection.is_empty() {
13040            return vec![columnar::null_native(TypeId::Int64, rows.len())];
13041        }
13042        let mut cols = Vec::with_capacity(projection.len());
13043        for (cid, ty) in projection {
13044            let vals: Vec<Value> = rows
13045                .iter()
13046                .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
13047                .collect();
13048            cols.push(columnar::values_to_native(ty.clone(), &vals));
13049        }
13050        cols
13051    }
13052
13053    /// Resolve a conjunctive predicate to its surviving `RowId` set on the
13054    /// single-run fast path: each condition becomes a `RowId` set via the
13055    /// in-memory indexes or the reader's page-pruned range scan, then they are
13056    /// intersected. Mirrors the resolution inside [`Self::query_columns_native`].
13057    fn resolve_survivor_rids(
13058        &self,
13059        conditions: &[crate::query::Condition],
13060        reader: &mut RunReader,
13061        snapshot: Snapshot,
13062    ) -> Result<RowIdSet> {
13063        use crate::query::Condition;
13064        let mut sets: Vec<RowIdSet> = Vec::new();
13065        for c in conditions {
13066            self.validate_condition(c)?;
13067            let s: RowIdSet = match c {
13068                Condition::Pk(key) => {
13069                    let lookup = self
13070                        .schema
13071                        .primary_key()
13072                        .map(|pk| self.index_lookup_key_bytes(pk.id, key))
13073                        .unwrap_or_else(|| key.clone());
13074                    self.hot
13075                        .get(&lookup)
13076                        .map(|r| RowIdSet::one(r.0))
13077                        .unwrap_or_else(RowIdSet::empty)
13078                }
13079                Condition::BitmapEq { column_id, value } => {
13080                    let lookup = self.index_lookup_key_bytes(*column_id, value);
13081                    self.bitmap
13082                        .get(column_id)
13083                        .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
13084                        .unwrap_or_else(RowIdSet::empty)
13085                }
13086                Condition::BitmapIn { column_id, values } => {
13087                    let bm = self.bitmap.get(column_id);
13088                    let mut acc = roaring::RoaringBitmap::new();
13089                    if let Some(b) = bm {
13090                        for v in values {
13091                            let lookup = self.index_lookup_key_bytes(*column_id, v);
13092                            acc |= b.get(&lookup);
13093                        }
13094                    }
13095                    RowIdSet::from_roaring(acc)
13096                }
13097                Condition::BytesPrefix { column_id, prefix } => {
13098                    if let Some(b) = self.bitmap.get(column_id) {
13099                        let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
13100                        let mut acc = roaring::RoaringBitmap::new();
13101                        for key in b.keys() {
13102                            if key.starts_with(&lookup_prefix) {
13103                                acc |= b.get(&key);
13104                            }
13105                        }
13106                        RowIdSet::from_roaring(acc)
13107                    } else {
13108                        RowIdSet::empty()
13109                    }
13110                }
13111                Condition::FmContains { column_id, pattern } => self
13112                    .fm
13113                    .get(column_id)
13114                    .map(|f| {
13115                        RowIdSet::from_unsorted(
13116                            f.locate(pattern).into_iter().map(|r| r.0).collect(),
13117                        )
13118                    })
13119                    .unwrap_or_else(RowIdSet::empty),
13120                Condition::FmContainsAll {
13121                    column_id,
13122                    patterns,
13123                } => {
13124                    if let Some(f) = self.fm.get(column_id) {
13125                        let sets: Vec<RowIdSet> = patterns
13126                            .iter()
13127                            .map(|pat| {
13128                                RowIdSet::from_unsorted(
13129                                    f.locate(pat).into_iter().map(|r| r.0).collect(),
13130                                )
13131                            })
13132                            .collect();
13133                        RowIdSet::intersect_many(sets)
13134                    } else {
13135                        RowIdSet::empty()
13136                    }
13137                }
13138                Condition::Ann {
13139                    column_id,
13140                    query,
13141                    k,
13142                } => RowIdSet::from_unsorted(
13143                    self.retrieve_filtered(
13144                        &crate::query::Retriever::Ann {
13145                            column_id: *column_id,
13146                            query: query.clone(),
13147                            k: *k,
13148                        },
13149                        snapshot,
13150                        None,
13151                        None,
13152                        None,
13153                        None,
13154                    )?
13155                    .into_iter()
13156                    .map(|hit| hit.row_id.0)
13157                    .collect(),
13158                ),
13159                Condition::SparseMatch {
13160                    column_id,
13161                    query,
13162                    k,
13163                } => RowIdSet::from_unsorted(
13164                    self.retrieve_filtered(
13165                        &crate::query::Retriever::Sparse {
13166                            column_id: *column_id,
13167                            query: query.clone(),
13168                            k: *k,
13169                        },
13170                        snapshot,
13171                        None,
13172                        None,
13173                        None,
13174                        None,
13175                    )?
13176                    .into_iter()
13177                    .map(|hit| hit.row_id.0)
13178                    .collect(),
13179                ),
13180                Condition::MinHashSimilar {
13181                    column_id,
13182                    query,
13183                    k,
13184                } => match self.minhash.get(column_id) {
13185                    Some(index) => {
13186                        let candidates = index.candidate_row_ids(query);
13187                        let eligible =
13188                            self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
13189                        RowIdSet::from_unsorted(
13190                            index
13191                                .search_filtered(query, *k, |row_id| eligible.contains(&row_id))
13192                                .into_iter()
13193                                .map(|(row_id, _)| row_id.0)
13194                                .collect(),
13195                        )
13196                    }
13197                    None => RowIdSet::empty(),
13198                },
13199                Condition::Range { column_id, lo, hi } => {
13200                    if let Some(li) = self.learned_range.get(column_id) {
13201                        RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
13202                    } else {
13203                        reader.range_row_id_set_i64(*column_id, *lo, *hi)?
13204                    }
13205                }
13206                Condition::RangeF64 {
13207                    column_id,
13208                    lo,
13209                    lo_inclusive,
13210                    hi,
13211                    hi_inclusive,
13212                } => {
13213                    if let Some(li) = self.learned_range.get(column_id) {
13214                        RowIdSet::from_unsorted(
13215                            li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
13216                                .into_iter()
13217                                .collect(),
13218                        )
13219                    } else {
13220                        reader.range_row_id_set_f64(
13221                            *column_id,
13222                            *lo,
13223                            *lo_inclusive,
13224                            *hi,
13225                            *hi_inclusive,
13226                        )?
13227                    }
13228                }
13229                Condition::IsNull { column_id } => reader.null_row_id_set(*column_id, true)?,
13230                Condition::IsNotNull { column_id } => reader.null_row_id_set(*column_id, false)?,
13231            };
13232            sets.push(s);
13233        }
13234        Ok(RowIdSet::intersect_many(sets))
13235    }
13236
13237    /// Native vectorized aggregate over a (possibly filtered) column on the
13238    /// single-run fast path (Phase 7.2). Resolves survivors via the same
13239    /// page-pruned cursor as the scan, then accumulates the aggregate in one
13240    /// pass over the typed buffer — no `Value`, no Arrow `RecordBatch`.
13241    ///
13242    /// `column` is `None` for `COUNT(*)`. Returns `Ok(None)` when the fast path
13243    /// does not apply (multi-run / non-empty memtable); the caller scans.
13244    /// Open the streaming [`Cursor`](crate::cursor::Cursor) matching the current
13245    /// run layout: the single-run page cursor when there is exactly one sorted
13246    /// run, otherwise the multi-run k-way merge cursor. Both fuse the predicate,
13247    /// skip non-surviving pages, and fold the memtable / mutable-run overlay, so
13248    /// callers stay columnar end-to-end and never materialize `Row`s. Returns
13249    /// `None` when no cursor applies (e.g. an overlay-only table with no sorted
13250    /// run), leaving the caller to fall back.
13251    ///
13252    /// This is the single source of truth for layout-aware cursor selection,
13253    /// shared by the column scan ([`Self::query_columns_native`] / the SQL
13254    /// provider) and the aggregate path ([`Self::aggregate_native`]). New
13255    /// streaming consumers should build on this rather than re-deciding the
13256    /// cursor by run count.
13257    pub fn scan_cursor(
13258        &self,
13259        snapshot: Snapshot,
13260        projection: Vec<(u16, TypeId)>,
13261        conditions: &[crate::query::Condition],
13262    ) -> Result<Option<Box<dyn crate::cursor::Cursor>>> {
13263        if self.ttl.is_some() {
13264            return Ok(None);
13265        }
13266        // A deferred bulk load leaves the live indexes unbuilt; resolving
13267        // conditions against them would return silently-empty survivor sets.
13268        // Signal "can't serve" so the caller falls back to a `&mut` path that
13269        // runs `ensure_indexes_complete`. (Condition-free scans don't touch
13270        // the indexes and stay served.)
13271        if !conditions.is_empty() && !self.indexes_complete {
13272            return Ok(None);
13273        }
13274        if self.run_refs.len() == 1 {
13275            Ok(self
13276                .native_page_cursor(snapshot, projection, conditions)?
13277                .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13278        } else {
13279            Ok(self
13280                .native_multi_run_cursor(snapshot, projection, conditions)?
13281                .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13282        }
13283    }
13284
13285    /// Native vectorized aggregate over a (possibly filtered) column, in one
13286    /// pass over the typed buffers — no `Value`, no Arrow batch. Layout-agnostic:
13287    /// survivors stream through [`Self::scan_cursor`] (single- or multi-run,
13288    /// overlay-folded), so the same path serves every sorted-run layout.
13289    ///
13290    /// `column` is `None` for `COUNT(*)`. Order of attempts:
13291    /// 1. Single clean run + no `WHERE` ⇒ `MIN`/`MAX`/`COUNT(col)` straight from
13292    ///    page `min`/`max`/`null_count` (no decode).
13293    /// 2. `COUNT(*)` ⇒ survivor cardinality from the cursor's page plans.
13294    /// 3. Otherwise accumulate the projected column over the cursor.
13295    ///
13296    /// Returns `Ok(None)` (caller scans) when no native path applies: an
13297    /// overlay-only table with no sorted run, or a non-numeric column.
13298    pub fn aggregate_native(
13299        &self,
13300        snapshot: Snapshot,
13301        column: Option<u16>,
13302        conditions: &[crate::query::Condition],
13303        agg: NativeAgg,
13304    ) -> Result<Option<NativeAggResult>> {
13305        self.aggregate_native_inner(snapshot, column, conditions, agg, None)
13306    }
13307
13308    pub fn aggregate_native_with_control(
13309        &self,
13310        snapshot: Snapshot,
13311        column: Option<u16>,
13312        conditions: &[crate::query::Condition],
13313        agg: NativeAgg,
13314        control: &crate::ExecutionControl,
13315    ) -> Result<Option<NativeAggResult>> {
13316        self.aggregate_native_inner(snapshot, column, conditions, agg, Some(control))
13317    }
13318
13319    fn aggregate_native_inner(
13320        &self,
13321        snapshot: Snapshot,
13322        column: Option<u16>,
13323        conditions: &[crate::query::Condition],
13324        agg: NativeAgg,
13325        control: Option<&crate::ExecutionControl>,
13326    ) -> Result<Option<NativeAggResult>> {
13327        execution_checkpoint(control, 0)?;
13328        if self.ttl.is_some() {
13329            return Ok(None);
13330        }
13331        // 1. Single clean run + no WHERE ⇒ MIN/MAX/COUNT(col) from page stats.
13332        if self.run_refs.len() == 1 && conditions.is_empty() {
13333            if let Some(res) = self.aggregate_from_stats(snapshot, column, agg)? {
13334                return Ok(Some(res));
13335            }
13336        }
13337        // 2. COUNT(*) ⇒ survivor count from the cursor's page plans, no decode.
13338        //    Overlay-only replicas (no sorted run yet) fall through to a
13339        //    visible-row scan so aggregate_native still serves correctly.
13340        if matches!(agg, NativeAgg::Count) && column.is_none() {
13341            if let Some(c) = self.scan_cursor(snapshot, Vec::new(), conditions)? {
13342                return Ok(Some(NativeAggResult::Count(c.remaining_rows() as u64)));
13343            }
13344            let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13345            return Ok(Some(NativeAggResult::Count(rows.len() as u64)));
13346        }
13347        // 3. Accumulate the projected column. COUNT(col) excludes nulls — the
13348        //    accumulator's count is the non-null count, which `pack_*` returns.
13349        let cid = match column {
13350            Some(c) => c,
13351            None => return Ok(None),
13352        };
13353        let ty = self.column_type(cid);
13354        if let Some(mut cursor) = self.scan_cursor(snapshot, vec![(cid, ty.clone())], conditions)? {
13355            execution_checkpoint(control, 0)?;
13356            return match ty {
13357                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13358                    let (count, sum, mn, mx) = accumulate_int(cursor.as_mut(), control)?;
13359                    Ok(Some(pack_int(agg, count, sum, mn, mx)))
13360                }
13361                TypeId::Float64 => {
13362                    let (count, sum, mn, mx) = accumulate_float(cursor.as_mut(), control)?;
13363                    Ok(Some(pack_float(agg, count, sum, mn, mx)))
13364                }
13365                _ => Ok(None),
13366            };
13367        }
13368        // Overlay-only / replica path: fold over visible rows in memory.
13369        let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13370        execution_checkpoint(control, 0)?;
13371        match ty {
13372            TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13373                let mut count = 0u64;
13374                let mut sum = 0i128;
13375                let mut mn = i64::MAX;
13376                let mut mx = i64::MIN;
13377                for row in &rows {
13378                    if let Some(Value::Int64(v)) = row.columns.get(&cid) {
13379                        count += 1;
13380                        sum += i128::from(*v);
13381                        mn = mn.min(*v);
13382                        mx = mx.max(*v);
13383                    }
13384                }
13385                Ok(Some(pack_int(agg, count, sum, mn, mx)))
13386            }
13387            TypeId::Float64 => {
13388                let mut count = 0u64;
13389                let mut sum = 0.0f64;
13390                let mut mn = f64::INFINITY;
13391                let mut mx = f64::NEG_INFINITY;
13392                for row in &rows {
13393                    if let Some(Value::Float64(v)) = row.columns.get(&cid) {
13394                        count += 1;
13395                        sum += *v;
13396                        mn = mn.min(*v);
13397                        mx = mx.max(*v);
13398                    }
13399                }
13400                Ok(Some(pack_float(agg, count, sum, mn, mx)))
13401            }
13402            _ => Ok(None),
13403        }
13404    }
13405
13406    /// Visible rows matching `conditions`, for overlay-only aggregate fallbacks.
13407    fn visible_rows_filtered(
13408        &self,
13409        snapshot: Snapshot,
13410        conditions: &[crate::query::Condition],
13411        control: Option<&crate::ExecutionControl>,
13412    ) -> Result<Vec<Row>> {
13413        let rows = if let Some(control) = control {
13414            self.visible_rows_controlled(snapshot, control)?
13415        } else {
13416            self.visible_rows(snapshot)?
13417        };
13418        if conditions.is_empty() {
13419            return Ok(rows);
13420        }
13421        Ok(rows
13422            .into_iter()
13423            .filter(|row| {
13424                conditions
13425                    .iter()
13426                    .all(|cond| condition_matches_row(cond, row, &self.schema))
13427            })
13428            .collect())
13429    }
13430
13431    /// Phase 7.1 metadata fast path: answer an unfiltered `MIN`/`MAX`/`COUNT(col)`
13432    /// straight from page `min`/`max`/`null_count` — no column decode. Returns
13433    /// `None` (caller decodes) for `COUNT(*)`/`SUM`/`AVG`, when exact stats are
13434    /// unavailable (multi-version run; [`Table::exact_column_stats`] gates this),
13435    /// or for a column whose stats omit `min`/`max` while it still holds values
13436    /// (e.g. an encrypted column) — returning `NULL` there would be a wrong
13437    /// answer, so we fall back to decoding.
13438    fn aggregate_from_stats(
13439        &self,
13440        snapshot: Snapshot,
13441        column: Option<u16>,
13442        agg: NativeAgg,
13443    ) -> Result<Option<NativeAggResult>> {
13444        let cid = match (agg, column) {
13445            (NativeAgg::Count | NativeAgg::Min | NativeAgg::Max, Some(c)) => c,
13446            _ => return Ok(None), // COUNT(*), SUM, AVG: not served from page stats
13447        };
13448        let Some(stats) = self.exact_column_stats(snapshot, &[cid])? else {
13449            return Ok(None);
13450        };
13451        let Some(cs) = stats.get(&cid) else {
13452            return Ok(None);
13453        };
13454        match agg {
13455            // COUNT(col) excludes NULLs: live rows minus the column's null count.
13456            NativeAgg::Count => Ok(Some(NativeAggResult::Count(
13457                self.live_count.saturating_sub(cs.null_count),
13458            ))),
13459            NativeAgg::Min | NativeAgg::Max => {
13460                let bound = if agg == NativeAgg::Min {
13461                    &cs.min
13462                } else {
13463                    &cs.max
13464                };
13465                match bound {
13466                    Some(Value::Int64(x)) => Ok(Some(NativeAggResult::Int(*x))),
13467                    Some(Value::Float64(x)) => Ok(Some(NativeAggResult::Float(*x))),
13468                    Some(_) => Ok(None), // unexpected stat type ⇒ decode
13469                    // No bound: a genuine SQL NULL only when the column is wholly
13470                    // null. Otherwise the stats are simply unavailable (encrypted),
13471                    // so decode for a correct answer.
13472                    None if cs.null_count >= self.live_count => Ok(Some(NativeAggResult::Null)),
13473                    None => Ok(None),
13474                }
13475            }
13476            _ => Ok(None),
13477        }
13478    }
13479
13480    /// Phase 7.1c: exact `COUNT(DISTINCT col)` from the bitmap index's partition
13481    /// cardinality — the number of distinct indexed values — with no scan. Each
13482    /// distinct value is one bitmap key; under the insert-only invariant (empty
13483    /// overlay, single run, `live_count == row_count`) every key has at least one
13484    /// live row, so the key count is exact. `NULL` is excluded from
13485    /// `COUNT(DISTINCT)`, so a null key (from an explicit `Value::Null` put) is
13486    /// discounted. Returns `None` (caller scans) without a bitmap index on the
13487    /// column or when the invariant does not hold.
13488    pub fn count_distinct_from_bitmap(&mut self, column_id: u16) -> Result<Option<u64>> {
13489        if self.ttl.is_some() {
13490            return Ok(None);
13491        }
13492        if !(self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1) {
13493            return Ok(None);
13494        }
13495        // A deferred bulk load leaves the bitmap unbuilt; complete it before
13496        // trusting its key count (same lazy contract as `query`/`flush`).
13497        self.ensure_indexes_complete()?;
13498        let reader = self.open_reader(self.run_refs[0].run_id)?;
13499        if self.live_count != reader.row_count() as u64 {
13500            return Ok(None);
13501        }
13502        let Some(bm) = self.bitmap.get(&column_id) else {
13503            return Ok(None); // no bitmap index ⇒ let the caller scan
13504        };
13505        let mut distinct = bm.value_count() as u64;
13506        // A null key (explicit `Value::Null`) is indexed but excluded from
13507        // COUNT(DISTINCT). (Schema-evolution-absent columns are never indexed.)
13508        if !bm.get(&Value::Null.encode_key()).is_empty() {
13509            distinct = distinct.saturating_sub(1);
13510        }
13511        Ok(Some(distinct))
13512    }
13513
13514    /// Incremental aggregate over the live table (Phase 8.3). For an append-only
13515    /// table, a warm cache entry (same `cache_key`) lets the result be refreshed
13516    /// by aggregating **only the newly inserted rows** (row-id watermark delta)
13517    /// and merging, instead of a full recompute. The caller supplies a stable
13518    /// `cache_key` (e.g. a hash of the SQL + projection); distinct queries must
13519    /// use distinct keys.
13520    ///
13521    /// Returns [`IncrementalAggResult`] with the merged state and whether the
13522    /// delta path was taken. A single `delete` (ever) disables the incremental
13523    /// path for the table, so correctness never relies on append-only behavior
13524    /// that deletes invalidate.
13525    pub fn aggregate_incremental(
13526        &mut self,
13527        cache_key: u64,
13528        conditions: &[crate::query::Condition],
13529        column: Option<u16>,
13530        agg: NativeAgg,
13531    ) -> Result<IncrementalAggResult> {
13532        self.aggregate_incremental_inner(cache_key, conditions, column, agg, None)
13533    }
13534
13535    pub fn aggregate_incremental_with_control(
13536        &mut self,
13537        cache_key: u64,
13538        conditions: &[crate::query::Condition],
13539        column: Option<u16>,
13540        agg: NativeAgg,
13541        control: &crate::ExecutionControl,
13542    ) -> Result<IncrementalAggResult> {
13543        self.aggregate_incremental_inner(cache_key, conditions, column, agg, Some(control))
13544    }
13545
13546    fn aggregate_incremental_inner(
13547        &mut self,
13548        cache_key: u64,
13549        conditions: &[crate::query::Condition],
13550        column: Option<u16>,
13551        agg: NativeAgg,
13552        control: Option<&crate::ExecutionControl>,
13553    ) -> Result<IncrementalAggResult> {
13554        execution_checkpoint(control, 0)?;
13555        let snap = self.snapshot();
13556        let cur_wm = self.allocator.current().0;
13557        let cur_epoch = snap.epoch.0;
13558        // The watermark equals the committed row count only when the memtable is
13559        // empty (every allocated row id is durably in a run). With pending
13560        // (uncommitted) writes the allocator is ahead of the visible set, so the
13561        // delta range would silently skip just-committed rows — disable the
13562        // incremental path entirely in that case. The mutable-run tier holding
13563        // un-spilled data also disables it (those rows aren't in a run yet).
13564        let incremental_ok = self.ttl.is_none()
13565            && !self.had_deletes
13566            && self.memtable.is_empty()
13567            && self.mutable_run.is_empty();
13568
13569        // Incremental path: append-only, no pending writes, warm cache, advanced
13570        // epoch.
13571        if incremental_ok {
13572            if let Some(cached) = self.agg_cache.get(&cache_key).cloned() {
13573                if cached.epoch == cur_epoch {
13574                    return Ok(IncrementalAggResult {
13575                        state: cached.state,
13576                        incremental: true,
13577                        delta_rows: 0,
13578                    });
13579                }
13580                if cached.epoch < cur_epoch && cached.watermark <= cur_wm {
13581                    let delta_len = cur_wm.saturating_sub(cached.watermark) as usize;
13582                    let mut delta_rids = Vec::with_capacity(delta_len);
13583                    for (index, row_id) in (cached.watermark..cur_wm).enumerate() {
13584                        execution_checkpoint(control, index)?;
13585                        delta_rids.push(row_id);
13586                    }
13587                    let delta_rows = self.rows_for_rids(&delta_rids, snap)?;
13588                    execution_checkpoint(control, 0)?;
13589                    let index_sets = self.resolve_index_conditions(conditions, snap)?;
13590                    let delta_state = agg_state_from_rows(
13591                        &delta_rows,
13592                        conditions,
13593                        &index_sets,
13594                        column,
13595                        agg,
13596                        &self.schema,
13597                        control,
13598                    )?;
13599                    let merged = cached.state.merge(delta_state);
13600                    let delta_n = delta_rids.len() as u64;
13601                    Arc::make_mut(&mut self.agg_cache).insert(
13602                        cache_key,
13603                        CachedAgg {
13604                            state: merged.clone(),
13605                            watermark: cur_wm,
13606                            epoch: cur_epoch,
13607                        },
13608                    );
13609                    return Ok(IncrementalAggResult {
13610                        state: merged,
13611                        incremental: true,
13612                        delta_rows: delta_n,
13613                    });
13614                }
13615            }
13616        }
13617
13618        // Cold path. For Count/Sum/Min/Max the fast vectorized cursor produces a
13619        // directly-seedable state; for Avg it returns only the mean (losing the
13620        // sum+count needed to merge a future delta), so Avg falls back to a
13621        // visible-rows scan that captures both.
13622        let cursor_ok =
13623            self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
13624        let state = if cursor_ok && agg != NativeAgg::Avg {
13625            match self.aggregate_native_inner(snap, column, conditions, agg, control)? {
13626                Some(result) => {
13627                    AggState::from_native(result, agg, column.map(|c| self.column_type(c)))
13628                }
13629                None => self.agg_state_full_scan(conditions, column, agg, snap, control)?,
13630            }
13631        } else {
13632            self.agg_state_full_scan(conditions, column, agg, snap, control)?
13633        };
13634        // Seed only when the watermark is meaningful (no pending writes).
13635        if incremental_ok {
13636            Arc::make_mut(&mut self.agg_cache).insert(
13637                cache_key,
13638                CachedAgg {
13639                    state: state.clone(),
13640                    watermark: cur_wm,
13641                    epoch: cur_epoch,
13642                },
13643            );
13644        }
13645        Ok(IncrementalAggResult {
13646            state,
13647            incremental: false,
13648            delta_rows: 0,
13649        })
13650    }
13651
13652    /// Full visible-rows scan → [`AggState`] (cold path; captures sum+count for
13653    /// correct Avg seeding).
13654    fn agg_state_full_scan(
13655        &self,
13656        conditions: &[crate::query::Condition],
13657        column: Option<u16>,
13658        agg: NativeAgg,
13659        snap: Snapshot,
13660        control: Option<&crate::ExecutionControl>,
13661    ) -> Result<AggState> {
13662        execution_checkpoint(control, 0)?;
13663        let rows = self.visible_rows(snap)?;
13664        execution_checkpoint(control, 0)?;
13665        let index_sets = self.resolve_index_conditions(conditions, snap)?;
13666        agg_state_from_rows(
13667            &rows,
13668            conditions,
13669            &index_sets,
13670            column,
13671            agg,
13672            &self.schema,
13673            control,
13674        )
13675    }
13676
13677    /// Resolve only the index-defined conditions (`Ann`/`SparseMatch`) to row-id
13678    /// sets for membership testing during row-wise aggregation.
13679    fn resolve_index_conditions(
13680        &self,
13681        conditions: &[crate::query::Condition],
13682        snapshot: Snapshot,
13683    ) -> Result<Vec<RowIdSet>> {
13684        use crate::query::Condition;
13685        let mut sets = Vec::new();
13686        for c in conditions {
13687            if matches!(
13688                c,
13689                Condition::Ann { .. }
13690                    | Condition::SparseMatch { .. }
13691                    | Condition::MinHashSimilar { .. }
13692            ) {
13693                sets.push(self.resolve_condition(c, snapshot)?);
13694            }
13695        }
13696        Ok(sets)
13697    }
13698
13699    fn column_type(&self, cid: u16) -> TypeId {
13700        self.schema
13701            .columns
13702            .iter()
13703            .find(|c| c.id == cid)
13704            .map(|c| c.ty.clone())
13705            .unwrap_or(TypeId::Bytes)
13706    }
13707
13708    /// Approximate `COUNT`/`SUM`/`AVG` over a filtered set, computed from the
13709    /// in-memory reservoir sample (Phase 8.2). Returns a point estimate plus a
13710    /// normal-theory confidence interval at the supplied z-score (1.96 ≈ 95 %).
13711    ///
13712    /// The WHERE predicates are evaluated **exactly** on each sampled row (so
13713    /// LIKE/FM and equality/range contribute no index bias); `Ann`/`SparseMatch`
13714    /// are index-defined and resolved once to a row-id set that sampled rows are
13715    /// tested against. `Ok(None)` when there is no usable sample.
13716    pub fn approx_aggregate(
13717        &mut self,
13718        conditions: &[crate::query::Condition],
13719        column: Option<u16>,
13720        agg: ApproxAgg,
13721        z: f64,
13722    ) -> Result<Option<ApproxResult>> {
13723        self.approx_aggregate_with_candidate_authorization(conditions, column, agg, z, None)
13724    }
13725
13726    /// Security-aware approximate aggregate. RLS is evaluated only for the
13727    /// reservoir candidates, and column masks are applied before aggregation.
13728    pub fn approx_aggregate_with_candidate_authorization(
13729        &mut self,
13730        conditions: &[crate::query::Condition],
13731        column: Option<u16>,
13732        agg: ApproxAgg,
13733        z: f64,
13734        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
13735    ) -> Result<Option<ApproxResult>> {
13736        use crate::query::Condition;
13737        self.ensure_reservoir_complete()?;
13738        // Approx stats estimate the current live population. Prefer the table
13739        // snapshot, but if HLC dual-model visibility filters the entire
13740        // reservoir sample (epoch-only vs HLC-stamped), fall back to an
13741        // unbounded product snapshot so Count/Sum estimates remain available.
13742        let mut snapshot = self.snapshot();
13743        let n_pop = self.count();
13744        let sample_rids: Vec<u64> = self.reservoir.row_ids().to_vec();
13745        if sample_rids.is_empty() {
13746            return Ok(None);
13747        }
13748        // Materialize the live, non-deleted sampled rows.
13749        let mut live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13750        if live_sample.is_empty() {
13751            snapshot = Snapshot::unbounded();
13752            live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13753        }
13754        let s = live_sample.len();
13755        if s == 0 {
13756            return Ok(None);
13757        }
13758        let authorized = authorization
13759            .map(|authorization| {
13760                let candidates = live_sample.iter().map(|row| row.row_id).collect::<Vec<_>>();
13761                self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, None)
13762            })
13763            .transpose()?;
13764
13765        // Pre-resolve Ann/Sparse conditions (index-defined predicates) to row-id
13766        // sets; the per-row predicates below are evaluated exactly.
13767        let mut index_sets: Vec<RowIdSet> = Vec::new();
13768        for c in conditions {
13769            if matches!(
13770                c,
13771                Condition::Ann { .. }
13772                    | Condition::SparseMatch { .. }
13773                    | Condition::MinHashSimilar { .. }
13774            ) {
13775                index_sets.push(self.resolve_condition(c, snapshot)?);
13776            }
13777        }
13778
13779        // For Sum/Avg, gather the numeric column value of each passing row.
13780        let cid = match (agg, column) {
13781            (ApproxAgg::Count, _) => None,
13782            (_, Some(c)) => Some(c),
13783            _ => return Ok(None),
13784        };
13785        let mut passing_vals: Vec<f64> = Vec::with_capacity(s);
13786        for r in &live_sample {
13787            if authorized
13788                .as_ref()
13789                .is_some_and(|authorized| !authorized.contains(&r.row_id))
13790            {
13791                continue;
13792            }
13793            // Exact per-row predicate evaluation.
13794            if !conditions
13795                .iter()
13796                .all(|c| condition_matches_row(c, r, &self.schema))
13797            {
13798                continue;
13799            }
13800            // Ann/Sparse membership.
13801            if !index_sets.iter().all(|set| set.contains(r.row_id.0)) {
13802                continue;
13803            }
13804            if let Some(cid) = cid {
13805                let mut cells = r
13806                    .columns
13807                    .get(&cid)
13808                    .cloned()
13809                    .map(|value| vec![(cid, value)])
13810                    .unwrap_or_default();
13811                if let Some(authorization) = authorization {
13812                    authorization.security.apply_masks_to_cells(
13813                        authorization.table,
13814                        &mut cells,
13815                        authorization.principal,
13816                    );
13817                }
13818                if let Some(v) = as_f64(cells.first().map(|(_, value)| value)) {
13819                    passing_vals.push(v);
13820                } // nulls ⇒ excluded (matching SQL AVG/SUM null semantics)
13821            } else {
13822                passing_vals.push(0.0); // placeholder for COUNT
13823            }
13824        }
13825        let m = passing_vals.len();
13826
13827        let (point, half) = match agg {
13828            ApproxAgg::Count => {
13829                // Proportion estimate scaled to the population.
13830                let p = m as f64 / s as f64;
13831                let point = n_pop as f64 * p;
13832                let var = if s > 1 {
13833                    n_pop as f64 * n_pop as f64 * p * (1.0 - p) / s as f64
13834                        * (1.0 - s as f64 / n_pop as f64).max(0.0)
13835                } else {
13836                    0.0
13837                };
13838                (point, z * var.sqrt())
13839            }
13840            ApproxAgg::Sum => {
13841                // Horvitz–Thompson: each sampled row represents n_pop/s rows.
13842                let y: Vec<f64> = live_sample
13843                    .iter()
13844                    .map(|r| {
13845                        let passes_row = authorized
13846                            .as_ref()
13847                            .is_none_or(|authorized| authorized.contains(&r.row_id))
13848                            && conditions
13849                                .iter()
13850                                .all(|c| condition_matches_row(c, r, &self.schema))
13851                            && index_sets.iter().all(|set| set.contains(r.row_id.0));
13852                        if passes_row {
13853                            cid.and_then(|cid| {
13854                                let mut cells = r
13855                                    .columns
13856                                    .get(&cid)
13857                                    .cloned()
13858                                    .map(|value| vec![(cid, value)])
13859                                    .unwrap_or_default();
13860                                if let Some(authorization) = authorization {
13861                                    authorization.security.apply_masks_to_cells(
13862                                        authorization.table,
13863                                        &mut cells,
13864                                        authorization.principal,
13865                                    );
13866                                }
13867                                as_f64(cells.first().map(|(_, value)| value))
13868                            })
13869                            .unwrap_or(0.0)
13870                        } else {
13871                            0.0
13872                        }
13873                    })
13874                    .collect();
13875                let mean_y = y.iter().sum::<f64>() / s as f64;
13876                let point = n_pop as f64 * mean_y;
13877                let var = if s > 1 {
13878                    let ss: f64 = y.iter().map(|v| (v - mean_y).powi(2)).sum();
13879                    let var_y = ss / (s - 1) as f64;
13880                    n_pop as f64 * n_pop as f64 * var_y / s as f64
13881                        * (1.0 - s as f64 / n_pop as f64).max(0.0)
13882                } else {
13883                    0.0
13884                };
13885                (point, z * var.sqrt())
13886            }
13887            ApproxAgg::Avg => {
13888                if m == 0 {
13889                    return Ok(Some(ApproxResult {
13890                        point: 0.0,
13891                        ci_low: 0.0,
13892                        ci_high: 0.0,
13893                        n_population: n_pop,
13894                        n_sample_live: s,
13895                        n_passing: 0,
13896                    }));
13897                }
13898                let mean = passing_vals.iter().sum::<f64>() / m as f64;
13899                let half = if m > 1 {
13900                    let ss: f64 = passing_vals.iter().map(|v| (v - mean).powi(2)).sum();
13901                    let sd = (ss / (m - 1) as f64).sqrt();
13902                    let fpc = (1.0 - s as f64 / n_pop as f64).max(0.0);
13903                    z * sd / (m as f64).sqrt() * fpc.sqrt()
13904                } else {
13905                    0.0
13906                };
13907                (mean, half)
13908            }
13909        };
13910
13911        Ok(Some(ApproxResult {
13912            point,
13913            ci_low: point - half,
13914            ci_high: point + half,
13915            n_population: n_pop,
13916            n_sample_live: s,
13917            n_passing: m,
13918        }))
13919    }
13920
13921    /// Exact per-column statistics for the analytical aggregate fast path
13922    /// (Phase 7.1: `MIN`/`MAX`/`COUNT(col)` from page stats). Returns `None`
13923    /// unless the table is effectively insert-only at `snapshot` — empty
13924    /// memtable, a single sorted run, and `live_count == run.row_count()` — so
13925    /// the run's page `min`/`max`/`null_count` are exact (no tombstoned or
13926    /// superseded versions skew them). Under deletes/updates the caller falls
13927    /// back to scanning.
13928    pub fn exact_column_stats(
13929        &self,
13930        _snapshot: Snapshot,
13931        projection: &[u16],
13932    ) -> Result<Option<HashMap<u16, ColumnStat>>> {
13933        if self.ttl.is_some()
13934            || !(self.memtable.is_empty()
13935                && self.mutable_run.is_empty()
13936                && self.run_refs.len() == 1)
13937        {
13938            return Ok(None);
13939        }
13940        let reader = self.open_reader(self.run_refs[0].run_id)?;
13941        if self.live_count != reader.row_count() as u64 {
13942            return Ok(None);
13943        }
13944        let mut out = HashMap::new();
13945        for &cid in projection {
13946            let cdef = match self.schema.columns.iter().find(|c| c.id == cid) {
13947                Some(c) => c,
13948                None => continue,
13949            };
13950            // Absent column (schema evolution) ⇒ all rows null.
13951            let Some(stats) = reader.column_page_stats(cid) else {
13952                out.insert(
13953                    cid,
13954                    ColumnStat {
13955                        min: None,
13956                        max: None,
13957                        null_count: self.live_count,
13958                    },
13959                );
13960                continue;
13961            };
13962            let stat = match cdef.ty {
13963                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13964                    agg_int(stats, crate::sorted_run::be_i64).map(|(mn, mx, n)| ColumnStat {
13965                        min: mn.map(Value::Int64),
13966                        max: mx.map(Value::Int64),
13967                        null_count: n,
13968                    })
13969                }
13970                TypeId::Float64 => {
13971                    agg_float(stats, crate::sorted_run::be_f64).map(|(mn, mx, n)| ColumnStat {
13972                        min: mn.map(Value::Float64),
13973                        max: mx.map(Value::Float64),
13974                        null_count: n,
13975                    })
13976                }
13977                _ => None,
13978            };
13979            if let Some(s) = stat {
13980                out.insert(cid, s);
13981            }
13982        }
13983        Ok(Some(out))
13984    }
13985
13986    pub fn dir(&self) -> &Path {
13987        &self.dir
13988    }
13989
13990    pub fn schema(&self) -> &Schema {
13991        &self.schema
13992    }
13993
13994    pub fn ann_index(&self, column_id: u16) -> Option<&crate::index::AnnIndex> {
13995        self.ann.get(&column_id)
13996    }
13997
13998    pub fn ann_index_mut(&mut self, column_id: u16) -> Option<&mut crate::index::AnnIndex> {
13999        self.ann.get_mut(&column_id)
14000    }
14001
14002    pub(crate) fn set_catalog_name(&mut self, name: String) {
14003        self.name = name;
14004    }
14005
14006    pub(crate) fn prepare_alter_column(
14007        &mut self,
14008        column_name: &str,
14009        change: &AlterColumn,
14010    ) -> Result<(ColumnDef, Option<Schema>)> {
14011        if !self.pending_rows.is_empty() || !self.pending_dels.is_empty() {
14012            return Err(MongrelError::InvalidArgument(
14013                "ALTER COLUMN requires committing staged writes first".into(),
14014            ));
14015        }
14016        let old = self
14017            .schema
14018            .columns
14019            .iter()
14020            .find(|c| c.name == column_name)
14021            .cloned()
14022            .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14023        let mut next = old.clone();
14024
14025        if let Some(name) = &change.name {
14026            let trimmed = name.trim();
14027            if trimmed.is_empty() {
14028                return Err(MongrelError::InvalidArgument(
14029                    "ALTER COLUMN name must not be empty".into(),
14030                ));
14031            }
14032            if trimmed != old.name && self.schema.columns.iter().any(|c| c.name == trimmed) {
14033                return Err(MongrelError::Schema(format!(
14034                    "column {trimmed} already exists"
14035                )));
14036            }
14037            next.name = trimmed.to_string();
14038        }
14039
14040        if let Some(ty) = &change.ty {
14041            next.ty = ty.clone();
14042        }
14043        if let Some(flags) = change.flags {
14044            validate_alter_column_flags(old.flags, flags)?;
14045            next.flags = flags;
14046        }
14047
14048        if let Some(default_change) = &change.default_value {
14049            next.default_value = default_change.clone();
14050        }
14051        if let Some(source_change) = &change.embedding_source {
14052            next.embedding_source = source_change.clone();
14053        }
14054
14055        validate_alter_column_type(&self.schema, &old, &next, self.has_stored_versions())?;
14056        if old.flags.contains(ColumnFlags::NULLABLE)
14057            && !next.flags.contains(ColumnFlags::NULLABLE)
14058            && self.column_has_nulls(old.id)?
14059        {
14060            return Err(MongrelError::InvalidArgument(format!(
14061                "column '{}' contains NULL values",
14062                old.name
14063            )));
14064        }
14065        if next == old {
14066            return Ok((next, None));
14067        }
14068        let mut schema = self.schema.clone();
14069        let index = schema
14070            .columns
14071            .iter()
14072            .position(|column| column.id == next.id)
14073            .ok_or_else(|| MongrelError::Schema(format!("unknown column {}", next.id)))?;
14074        schema.columns[index] = next.clone();
14075        schema.schema_id = schema
14076            .schema_id
14077            .checked_add(1)
14078            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14079        schema.validate_auto_increment()?;
14080        schema.validate_defaults()?;
14081        Ok((next, Some(schema)))
14082    }
14083
14084    pub(crate) fn apply_altered_schema_prepared(&mut self, schema: Schema) {
14085        self.schema = schema;
14086        self.auto_inc = resolve_auto_inc(&self.schema);
14087        self.column_keys = build_column_keys(self.kek.as_deref(), &self.schema);
14088        self.clear_result_cache();
14089        let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
14090    }
14091
14092    /// Publish one hidden index artifact with its prepared schema. Callers
14093    /// hold the final commit barrier and have already verified that
14094    /// `artifact` covers the table's exact current epoch.
14095    pub(crate) fn publish_index_schema_change(
14096        &mut self,
14097        schema: Schema,
14098        artifact: SecondaryIndexArtifact,
14099    ) -> Result<()> {
14100        self.apply_altered_schema_prepared(schema);
14101        self.prune_index_maps_to_schema();
14102        match artifact {
14103            SecondaryIndexArtifact::Bitmap(column_id, index) => {
14104                self.bitmap.insert(column_id, index);
14105            }
14106            SecondaryIndexArtifact::LearnedRange(column_id, index) => {
14107                Arc::make_mut(&mut self.learned_range).insert(column_id, index);
14108            }
14109            SecondaryIndexArtifact::Fm(column_id, index) => {
14110                self.fm.insert(column_id, *index);
14111            }
14112            SecondaryIndexArtifact::Ann(column_id, index) => {
14113                self.ann.insert(column_id, *index);
14114            }
14115            SecondaryIndexArtifact::Sparse(column_id, index) => {
14116                self.sparse.insert(column_id, index);
14117            }
14118            SecondaryIndexArtifact::MinHash(column_id, index) => {
14119                self.minhash.insert(column_id, index);
14120            }
14121        }
14122        self.indexes_complete = true;
14123        self.seal_generations();
14124        let view = Arc::new(self.capture_read_generation());
14125        self.published.store(Arc::clone(&view));
14126        checkpoint_current_schema(self)?;
14127        // The catalog + rows are authoritative. A later flush/checkpoint
14128        // persists this derived generation without extending the write fence.
14129        self.invalidate_index_checkpoint();
14130        Ok(())
14131    }
14132
14133    /// Drop one secondary index from the live maps without rewriting table
14134    /// rows. Installs `schema` (already missing the dropped index), prunes
14135    /// maps, publishes a new generation, and invalidates the derived
14136    /// global-index checkpoint so reopen rebuilds from the authoritative
14137    /// schema + rows.
14138    pub(crate) fn publish_index_drop(&mut self, schema: Schema) -> Result<()> {
14139        self.apply_altered_schema_prepared(schema);
14140        self.prune_index_maps_to_schema();
14141        self.indexes_complete = true;
14142        self.seal_generations();
14143        let view = Arc::new(self.capture_read_generation());
14144        self.published.store(Arc::clone(&view));
14145        checkpoint_current_schema(self)?;
14146        // Dropped-index maps no longer match any prior checkpoint image.
14147        self.invalidate_index_checkpoint();
14148        Ok(())
14149    }
14150
14151    fn prune_index_maps_to_schema(&mut self) {
14152        let keep_bitmap: std::collections::HashSet<u16> = self
14153            .schema
14154            .indexes
14155            .iter()
14156            .filter(|index| index.kind == IndexKind::Bitmap)
14157            .map(|index| index.column_id)
14158            .collect();
14159        let keep_ann: std::collections::HashSet<u16> = self
14160            .schema
14161            .indexes
14162            .iter()
14163            .filter(|index| index.kind == IndexKind::Ann)
14164            .map(|index| index.column_id)
14165            .collect();
14166        let keep_fm: std::collections::HashSet<u16> = self
14167            .schema
14168            .indexes
14169            .iter()
14170            .filter(|index| index.kind == IndexKind::FmIndex)
14171            .map(|index| index.column_id)
14172            .collect();
14173        let keep_sparse: std::collections::HashSet<u16> = self
14174            .schema
14175            .indexes
14176            .iter()
14177            .filter(|index| index.kind == IndexKind::Sparse)
14178            .map(|index| index.column_id)
14179            .collect();
14180        let keep_minhash: std::collections::HashSet<u16> = self
14181            .schema
14182            .indexes
14183            .iter()
14184            .filter(|index| index.kind == IndexKind::MinHash)
14185            .map(|index| index.column_id)
14186            .collect();
14187        let keep_learned: std::collections::HashSet<u16> = self
14188            .schema
14189            .indexes
14190            .iter()
14191            .filter(|index| index.kind == IndexKind::LearnedRange)
14192            .map(|index| index.column_id)
14193            .collect();
14194        self.bitmap
14195            .retain(|column_id, _| keep_bitmap.contains(column_id));
14196        self.ann.retain(|column_id, _| keep_ann.contains(column_id));
14197        self.fm.retain(|column_id, _| keep_fm.contains(column_id));
14198        self.sparse
14199            .retain(|column_id, _| keep_sparse.contains(column_id));
14200        self.minhash
14201            .retain(|column_id, _| keep_minhash.contains(column_id));
14202        {
14203            let learned = Arc::make_mut(&mut self.learned_range);
14204            learned.retain(|column_id, _| keep_learned.contains(column_id));
14205        }
14206    }
14207
14208    pub(crate) fn checkpoint_altered_schema(&mut self) -> Result<()> {
14209        checkpoint_current_schema(self)
14210    }
14211
14212    pub fn alter_column(&mut self, column_name: &str, change: AlterColumn) -> Result<ColumnDef> {
14213        self.ensure_writable()?;
14214        let previous_schema = self.schema.clone();
14215        let (column, schema) = self.prepare_alter_column(column_name, &change)?;
14216        if let Some(schema) = schema {
14217            self.apply_altered_schema_prepared(schema);
14218            self.checkpoint_standalone_schema_change(previous_schema)?;
14219        }
14220        Ok(column)
14221    }
14222
14223    fn column_has_nulls(&mut self, column_id: u16) -> Result<bool> {
14224        if self.live_count == 0 {
14225            return Ok(false);
14226        }
14227        let snap = self.snapshot();
14228        let columns = self.visible_columns_native(snap, Some(&[column_id]))?;
14229        Ok(columns
14230            .first()
14231            .map(|(_, col)| col.null_count(col.len()) != 0)
14232            .unwrap_or(true))
14233    }
14234
14235    fn has_stored_versions(&self) -> bool {
14236        !self.memtable.is_empty()
14237            || !self.mutable_run.is_empty()
14238            || self.run_refs.iter().any(|r| r.row_count > 0)
14239            || !self.retiring.is_empty()
14240    }
14241
14242    /// Add a column to the schema (schema evolution). Existing runs simply read
14243    /// back as null for the new column until re-written. Persists the new schema
14244    /// and manifest. The caller supplies the full [`ColumnFlags`] so migrations
14245    /// can add `PRIMARY KEY` / `AUTO_INCREMENT` columns correctly.
14246    pub fn add_column(
14247        &mut self,
14248        name: &str,
14249        ty: TypeId,
14250        flags: ColumnFlags,
14251        default_value: Option<crate::schema::DefaultExpr>,
14252    ) -> Result<u16> {
14253        self.add_column_with_id(name, ty, flags, default_value, None)
14254    }
14255
14256    pub fn add_column_with_id(
14257        &mut self,
14258        name: &str,
14259        ty: TypeId,
14260        flags: ColumnFlags,
14261        default_value: Option<crate::schema::DefaultExpr>,
14262        requested_id: Option<u16>,
14263    ) -> Result<u16> {
14264        self.ensure_writable()?;
14265        let previous_schema = self.schema.clone();
14266        let (column, schema) =
14267            self.prepare_add_column(name, ty, flags, default_value, requested_id)?;
14268        self.apply_altered_schema_prepared(schema);
14269        self.checkpoint_standalone_schema_change(previous_schema)?;
14270        Ok(column.id)
14271    }
14272
14273    pub(crate) fn prepare_add_column(
14274        &mut self,
14275        name: &str,
14276        ty: TypeId,
14277        flags: ColumnFlags,
14278        default_value: Option<crate::schema::DefaultExpr>,
14279        requested_id: Option<u16>,
14280    ) -> Result<(ColumnDef, Schema)> {
14281        self.ensure_writable()?;
14282        if self.schema.columns.iter().any(|c| c.name == name) {
14283            return Err(MongrelError::Schema(format!(
14284                "column {name} already exists"
14285            )));
14286        }
14287        let id = if let Some(id) = requested_id.filter(|id| *id != 0) {
14288            if self.schema.columns.iter().any(|c| c.id == id) {
14289                return Err(MongrelError::Schema(format!(
14290                    "column id {id} already exists"
14291                )));
14292            }
14293            id
14294        } else {
14295            self.schema
14296                .columns
14297                .iter()
14298                .map(|c| c.id)
14299                .max()
14300                .unwrap_or(0)
14301                .checked_add(1)
14302                .ok_or_else(|| MongrelError::Schema("column id space exhausted".into()))?
14303        };
14304        let column = ColumnDef {
14305            id,
14306            name: name.to_string(),
14307            ty,
14308            flags,
14309            default_value,
14310            embedding_source: None,
14311        };
14312        let mut next_schema = self.schema.clone();
14313        next_schema.columns.push(column.clone());
14314        next_schema.schema_id = next_schema
14315            .schema_id
14316            .checked_add(1)
14317            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14318        next_schema.validate_auto_increment()?;
14319        next_schema.validate_defaults()?;
14320        Ok((column, next_schema))
14321    }
14322
14323    /// Declare a `LearnedRange` (PGM) index on an existing numeric column and
14324    /// build it immediately from the current sorted run (Phase 13.3). After
14325    /// this, `Condition::Range` / `Condition::RangeF64` on that column resolve
14326    /// survivors sub-linearly (O(log segments + log ε)) instead of scanning the
14327    /// full column.
14328    ///
14329    /// Requires exactly one sorted run (call after `flush`). The index is
14330    /// rebuilt automatically on subsequent flushes.
14331    pub fn add_learned_range_index(&mut self, column_name: &str) -> Result<()> {
14332        self.ensure_writable()?;
14333        let cid = self
14334            .schema
14335            .columns
14336            .iter()
14337            .find(|c| c.name == column_name)
14338            .map(|c| c.id)
14339            .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14340        let ty = self
14341            .schema
14342            .columns
14343            .iter()
14344            .find(|c| c.id == cid)
14345            .map(|c| c.ty.clone())
14346            .unwrap_or(TypeId::Int64);
14347        if !matches!(
14348            ty,
14349            TypeId::Int64 | TypeId::Float64 | TypeId::TimestampNanos | TypeId::Date32
14350        ) {
14351            return Err(MongrelError::Schema(format!(
14352                "LearnedRange requires a numeric column; {column_name} is {ty:?}"
14353            )));
14354        }
14355        if self
14356            .schema
14357            .indexes
14358            .iter()
14359            .any(|i| i.column_id == cid && i.kind == IndexKind::LearnedRange)
14360        {
14361            return Ok(()); // already declared
14362        }
14363        let previous_schema = self.schema.clone();
14364        let previous_learned_range = Arc::clone(&self.learned_range);
14365        let mut next_schema = previous_schema.clone();
14366        next_schema.indexes.push(IndexDef {
14367            name: format!("{}_learned_range", column_name),
14368            column_id: cid,
14369            kind: IndexKind::LearnedRange,
14370            predicate: None,
14371            options: Default::default(),
14372        });
14373        next_schema.schema_id = next_schema
14374            .schema_id
14375            .checked_add(1)
14376            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14377        self.apply_altered_schema_prepared(next_schema);
14378        if let Err(error) = self.build_learned_ranges() {
14379            self.apply_altered_schema_prepared(previous_schema);
14380            self.learned_range = previous_learned_range;
14381            return Err(error);
14382        }
14383        if let Err(error) = self.checkpoint_standalone_schema_change(previous_schema) {
14384            if !matches!(
14385                &error,
14386                MongrelError::DurableCommit { .. } | MongrelError::CommitOutcomeUnknown { .. }
14387            ) {
14388                self.learned_range = previous_learned_range;
14389            }
14390            return Err(error);
14391        }
14392        Ok(())
14393    }
14394
14395    fn checkpoint_standalone_schema_change(&mut self, previous_schema: Schema) -> Result<()> {
14396        let mut schema_published = false;
14397        let schema_result = match self._root_guard.as_deref() {
14398            Some(root) => write_schema_durable_with_after(root, &self.schema, || {
14399                schema_published = true;
14400            }),
14401            None => write_schema_with_after(&self.dir, &self.schema, || {
14402                schema_published = true;
14403            }),
14404        };
14405        if schema_result.is_err() && !schema_published {
14406            self.apply_altered_schema_prepared(previous_schema);
14407            return schema_result;
14408        }
14409
14410        let manifest_result = self.persist_manifest(self.current_epoch());
14411        match (schema_result, manifest_result) {
14412            (_, Ok(())) => Ok(()),
14413            (Ok(()), Err(error)) => {
14414                self.poison_after_maintenance_publish_failure();
14415                Err(MongrelError::DurableCommit {
14416                    epoch: self.current_epoch().0,
14417                    message: format!(
14418                        "schema is durable but matching manifest publication failed: {error}"
14419                    ),
14420                })
14421            }
14422            (Err(schema_error), Err(manifest_error)) => {
14423                self.poison_after_maintenance_publish_failure();
14424                Err(MongrelError::CommitOutcomeUnknown {
14425                    epoch: self.current_epoch().0,
14426                    message: format!(
14427                        "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
14428                    ),
14429                })
14430            }
14431        }
14432    }
14433
14434    /// Tuning knob for the WAL auto-sync threshold. A no-op on a mounted table
14435    /// (the shared WAL's durability is governed by the group-commit coordinator).
14436    pub fn set_sync_byte_threshold(&mut self, threshold: u64) {
14437        self.sync_byte_threshold = threshold;
14438        if let WalSink::Private(w) = &mut self.wal {
14439            w.set_sync_byte_threshold(threshold);
14440        }
14441    }
14442
14443    /// Flush all live page-cache entries to the persistent `_cache/` backing
14444    /// directory (best-effort). Useful before a clean shutdown so hot pages
14445    /// survive restart.
14446    pub fn page_cache_flush(&self) {
14447        self.page_cache.flush_to_disk();
14448    }
14449
14450    /// Number of entries currently in the shared page cache (diagnostic).
14451    pub fn page_cache_len(&self) -> usize {
14452        self.page_cache.len()
14453    }
14454
14455    /// Number of entries currently in the shared decoded-page cache (Phase
14456    /// 15.4 diagnostic).
14457    pub fn decoded_cache_len(&self) -> usize {
14458        self.decoded_cache.len()
14459    }
14460
14461    /// Drain the live memtable (prototype/testing helper used by the flush path
14462    /// demos). Prefer [`Table::flush`] for the durable path.
14463    pub fn drain_memtable_sorted(&mut self) -> Vec<Row> {
14464        self.memtable.drain_sorted()
14465    }
14466
14467    pub(crate) fn run_path(&self, run_id: u64) -> PathBuf {
14468        self.runs_dir().join(format!("r-{run_id}.sr"))
14469    }
14470
14471    pub(crate) fn create_run_file(&self, run_id: u64) -> Result<Option<std::fs::File>> {
14472        match self.runs_root.as_deref() {
14473            Some(root) => Ok(Some(root.create_regular_new(format!("r-{run_id}.sr"))?)),
14474            None => Ok(None),
14475        }
14476    }
14477
14478    pub(crate) fn create_run_entry(&self, name: &Path) -> Result<Option<std::fs::File>> {
14479        match self.runs_root.as_deref() {
14480            Some(root) => Ok(Some(root.create_regular_new(name)?)),
14481            None => Ok(None),
14482        }
14483    }
14484
14485    pub(crate) fn remove_run_entry(&self, name: &Path) -> Result<()> {
14486        match self.runs_root.as_deref() {
14487            Some(root) => match root.remove_file(name) {
14488                Ok(()) => Ok(()),
14489                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14490                Err(error) => Err(error.into()),
14491            },
14492            None => match std::fs::remove_file(self.runs_dir().join(name)) {
14493                Ok(()) => Ok(()),
14494                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14495                Err(error) => Err(error.into()),
14496            },
14497        }
14498    }
14499
14500    pub(crate) fn publish_run_entry(&self, source: &Path, destination: &Path) -> Result<()> {
14501        match self.runs_root.as_deref() {
14502            Some(root) => root
14503                .rename_file_new(source, destination)
14504                .map_err(Into::into),
14505            None => crate::durable_file::rename(
14506                &self.runs_dir().join(source),
14507                &self.runs_dir().join(destination),
14508            )
14509            .map_err(Into::into),
14510        }
14511    }
14512
14513    pub(crate) fn active_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14514        self.run_refs.iter().map(|run| run.run_id)
14515    }
14516
14517    pub(crate) fn table_dir(&self) -> &Path {
14518        &self.dir
14519    }
14520
14521    pub(crate) fn schema_ref(&self) -> &crate::schema::Schema {
14522        &self.schema
14523    }
14524
14525    pub(crate) fn alloc_run_id(&mut self) -> Result<u64> {
14526        let id = self.next_run_id;
14527        self.next_run_id = self
14528            .next_run_id
14529            .checked_add(1)
14530            .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))?;
14531        Ok(id)
14532    }
14533
14534    pub(crate) fn link_run(&mut self, run_ref: crate::manifest::RunRef) {
14535        self.run_refs.push(run_ref);
14536    }
14537
14538    /// Link a spilled run found during shared-WAL recovery (spec §8.5).
14539    /// **Idempotent**: if the run is already in the manifest (the publish phase
14540    /// persisted it before the crash, or this is a clean reopen with the
14541    /// `TxnCommit` still in the WAL) this is a no-op returning `false`, so the
14542    /// caller never double-links or double-counts. Otherwise — a crash *after*
14543    /// the commit fsync but *before* publish persisted the manifest — the run is
14544    /// Enqueue a compaction-superseded run for retention-gated deletion (spec
14545    /// §6.4). The file stays on disk until [`Self::reap_retiring`] removes it
14546    /// once `min_active_snapshot` has advanced past `retire_epoch`.
14547    pub(crate) fn retire_run(&mut self, run_id: u128, retire_epoch: u64) {
14548        self.retiring.push(crate::manifest::RetiredRun {
14549            run_id,
14550            retire_epoch,
14551        });
14552    }
14553
14554    /// Physically delete retired run files whose `retire_epoch` no pinned reader
14555    /// can still need (`min_active >= retire_epoch`), drop them from the queue,
14556    /// and persist the manifest if anything changed. Returns the count reaped.
14557    pub(crate) fn reap_retiring(
14558        &mut self,
14559        min_active: Epoch,
14560        backup_pinned: &std::collections::HashSet<u128>,
14561    ) -> Result<usize> {
14562        if self.retiring.is_empty() {
14563            return Ok(0);
14564        }
14565        let mut reaped = 0;
14566        let mut kept: Vec<crate::manifest::RetiredRun> = Vec::new();
14567        // Delete-then-persist is crash-idempotent: if we crash after unlinking
14568        // some files but before persisting, the manifest still lists them in
14569        // `retiring`; the next `reap_retiring` re-issues `remove_file` (the
14570        // error is ignored) and `check()` excludes `retiring` ids from orphan
14571        // detection, so the lingering entries are harmless until then.
14572        for r in std::mem::take(&mut self.retiring) {
14573            if min_active.0 >= r.retire_epoch && !backup_pinned.contains(&r.run_id) {
14574                let _ = self.remove_run_entry(Path::new(&format!("r-{}.sr", r.run_id)));
14575                reaped += 1;
14576            } else {
14577                kept.push(r);
14578            }
14579        }
14580        self.retiring = kept;
14581        if reaped > 0 {
14582            self.persist_manifest(self.current_epoch())?;
14583        }
14584        Ok(reaped)
14585    }
14586
14587    pub(crate) fn has_reapable_retiring(
14588        &self,
14589        min_active: Epoch,
14590        backup_pinned: &std::collections::HashSet<u128>,
14591    ) -> bool {
14592        self.retiring
14593            .iter()
14594            .any(|run| min_active.0 >= run.retire_epoch && !backup_pinned.contains(&run.run_id))
14595    }
14596
14597    pub(crate) fn recover_spilled_run(&mut self, run_ref: crate::manifest::RunRef) -> bool {
14598        if self.run_refs.iter().any(|r| r.run_id == run_ref.run_id) {
14599            return false;
14600        }
14601        self.live_count = self.live_count.saturating_add(run_ref.row_count);
14602        self.run_refs.push(run_ref);
14603        self.indexes_complete = false;
14604        true
14605    }
14606
14607    pub(crate) fn kek_ref(&self) -> Option<&Arc<Kek>> {
14608        self.kek.as_ref()
14609    }
14610
14611    pub(crate) fn open_reader(&self, run_id: u128) -> Result<RunReader> {
14612        let mut reader = match self.runs_root.as_deref() {
14613            Some(root) => RunReader::open_file_with_cache(
14614                root.open_regular(format!("r-{run_id}.sr"))?,
14615                self.schema.clone(),
14616                self.kek.clone(),
14617                Some(self.page_cache.clone()),
14618                Some(self.decoded_cache.clone()),
14619                self.table_id,
14620                Some(&self.verified_runs),
14621                None,
14622            )?,
14623            None => RunReader::open_with_cache(
14624                self.dir.join(RUNS_DIR).join(format!("r-{run_id}.sr")),
14625                self.schema.clone(),
14626                self.kek.clone(),
14627                Some(self.page_cache.clone()),
14628                Some(self.decoded_cache.clone()),
14629                self.table_id,
14630                Some(&self.verified_runs),
14631            )?,
14632        };
14633        // Overlay the real commit epoch for uniform-epoch (large-txn spill) runs:
14634        // their stored `_epoch` is a placeholder; the manifest RunRef carries the
14635        // assigned epoch. A no-op for ordinary runs.
14636        if let Some(rr) = self.run_refs.iter().find(|r| r.run_id == run_id) {
14637            reader.set_uniform_epoch(Epoch(rr.epoch_created));
14638        }
14639        Ok(reader)
14640    }
14641
14642    pub(crate) fn run_refs(&self) -> &[RunRef] {
14643        &self.run_refs
14644    }
14645
14646    pub(crate) fn retiring_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14647        self.retiring.iter().map(|run| run.run_id)
14648    }
14649
14650    pub(crate) fn runs_dir(&self) -> PathBuf {
14651        self.runs_root
14652            .as_deref()
14653            .and_then(|root| root.io_path().ok())
14654            .unwrap_or_else(|| self.dir.join(RUNS_DIR))
14655    }
14656
14657    pub(crate) fn wal_dir(&self) -> PathBuf {
14658        self.dir.join(WAL_DIR)
14659    }
14660
14661    pub(crate) fn set_run_refs(&mut self, refs: Vec<RunRef>) {
14662        self.run_refs = refs;
14663        self.refresh_run_row_id_ranges();
14664    }
14665
14666    /// `(min_row_id, max_row_id)` for the given run, when known. Used by
14667    /// compaction to enforce L1+ disjointness without re-opening every
14668    /// existing run header.
14669    pub(crate) fn run_row_id_range(&self, run_id: u128) -> Option<(u64, u64)> {
14670        self.run_row_id_ranges.get(&run_id).copied()
14671    }
14672
14673    /// Populate `run_row_id_ranges` from each run's on-disk header so
14674    /// [`Self::get`] can skip runs that cannot contain a given RowId.
14675    pub(crate) fn refresh_run_row_id_ranges(&mut self) {
14676        let mut ranges = HashMap::with_capacity(self.run_refs.len());
14677        for rr in &self.run_refs {
14678            if let Ok(reader) = self.open_reader(rr.run_id) {
14679                let h = reader.header();
14680                ranges.insert(rr.run_id, (h.min_row_id, h.max_row_id));
14681            }
14682        }
14683        self.run_row_id_ranges = ranges;
14684    }
14685
14686    pub(crate) fn compaction_zstd_level(&self) -> i32 {
14687        self.compaction_zstd_level
14688    }
14689
14690    pub(crate) fn kek(&self) -> Option<Arc<Kek>> {
14691        self.kek.clone()
14692    }
14693
14694    /// The index-checkpoint DEK (KEK-derived) for encrypted tables; `None` for
14695    /// plaintext tables. The checkpoint embeds index keys / PGM segment values
14696    /// derived from user data, so an encrypted table must encrypt it at rest.
14697    fn idx_dek(&self) -> Option<Zeroizing<[u8; DEK_LEN]>> {
14698        self.kek.as_ref().map(|k| k.derive_idx_key())
14699    }
14700
14701    /// Manifest (and other DB-wide metadata) meta DEK, derived from the KEK so
14702    /// the on-disk manifest is encrypted + authenticated at rest for encrypted
14703    /// tables. `None` for plaintext.
14704    fn manifest_meta_dek(&self) -> Option<[u8; DEK_LEN]> {
14705        self.kek.as_ref().map(|k| *k.derive_meta_key())
14706    }
14707
14708    /// `(column_id, scheme)` for every ENCRYPTED_INDEXABLE column — passed to
14709    /// the run writer so each run's descriptor records the column keys.
14710    pub(crate) fn indexable_column_specs(&self) -> Vec<(u16, u8)> {
14711        self.column_keys
14712            .iter()
14713            .map(|(&id, &(_, scheme))| (id, scheme))
14714            .collect()
14715    }
14716
14717    /// Tokenize a value for an ENCRYPTED_INDEXABLE column (HMAC-eq or OPE-range,
14718    /// per the column's scheme). Returns `None` for plaintext columns. Indexes
14719    /// over such columns store tokens, and queries tokenize literals the same
14720    /// way — so lookups never decrypt the stored (encrypted) page payloads.
14721    fn tokenize_value(&self, column_id: u16, v: &Value) -> Option<Value> {
14722        self.tokenize_value_enc(column_id, v)
14723    }
14724
14725    fn tokenize_value_enc(&self, column_id: u16, v: &Value) -> Option<Value> {
14726        use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
14727        let (key, scheme) = self.column_keys.get(&column_id)?;
14728        let token: Vec<u8> = match (*scheme, v) {
14729            (SCHEME_HMAC_EQ, _) => hmac_token(key, &v.encode_key()).to_vec(),
14730            (_, Value::Int64(x)) => ope_token_i64(key, *x).to_vec(),
14731            (_, Value::Float64(x)) => ope_token_f64(key, *x).to_vec(),
14732            _ => hmac_token(key, &v.encode_key()).to_vec(),
14733        };
14734        Some(Value::Bytes(token))
14735    }
14736
14737    /// Encoded index key for a `Value`, tokenized for HMAC-eq columns.
14738    fn index_lookup_key(&self, column_id: u16, v: &Value) -> Vec<u8> {
14739        self.index_lookup_key_bytes(column_id, &v.encode_key())
14740    }
14741
14742    /// Tokenize an already-encoded lookup key (equality queries pass the
14743    /// encoded search value; HMAC-eq columns wrap it under the column key).
14744    fn index_lookup_key_bytes(&self, column_id: u16, encoded: &[u8]) -> Vec<u8> {
14745        {
14746            use crate::encryption::{hmac_token, SCHEME_HMAC_EQ};
14747            if let Some((key, scheme)) = self.column_keys.get(&column_id) {
14748                if *scheme == SCHEME_HMAC_EQ {
14749                    return hmac_token(key, encoded).to_vec();
14750                }
14751            }
14752        }
14753        let _ = column_id;
14754        encoded.to_vec()
14755    }
14756}
14757
14758fn native_int64_strictly_increasing(col: &columnar::NativeColumn, n: usize) -> bool {
14759    let columnar::NativeColumn::Int64 { data, validity } = col else {
14760        return false;
14761    };
14762    if data.len() < n || !columnar::all_non_null(validity, n) {
14763        return false;
14764    }
14765    data.iter()
14766        .take(n)
14767        .zip(data.iter().skip(1))
14768        .all(|(a, b)| a < b)
14769}
14770
14771/// Exact aggregate of a column's page stats into a min/max/null_count triple
14772/// (Phase 7.1). Only meaningful when the owning table is insert-only, which
14773/// [`Table::exact_column_stats`] gates on.
14774#[derive(Debug, Clone)]
14775pub struct ColumnStat {
14776    pub min: Option<Value>,
14777    pub max: Option<Value>,
14778    pub null_count: u64,
14779}
14780
14781/// A supported native aggregate (Phase 7.2).
14782#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14783pub enum NativeAgg {
14784    Count,
14785    Sum,
14786    Min,
14787    Max,
14788    Avg,
14789}
14790
14791/// The typed result of a [`NativeAgg`] over a column.
14792#[derive(Debug, Clone, PartialEq)]
14793pub enum NativeAggResult {
14794    Count(u64),
14795    Int(i64),
14796    Float(f64),
14797    /// No non-null inputs (SUM/MIN/MAX/AVG over zero rows ⇒ SQL NULL).
14798    Null,
14799}
14800
14801/// A supported approximate aggregate over the reservoir sample (Phase 8.2).
14802#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14803pub enum ApproxAgg {
14804    Count,
14805    Sum,
14806    Avg,
14807}
14808
14809/// Point estimate with a normal-theory confidence interval from the reservoir
14810/// sample (Phase 8.2). `ci_low`/`ci_high` bracket `point` at the requested
14811/// z-score; the interval has zero width when the sample equals the whole table.
14812#[derive(Debug, Clone)]
14813pub struct ApproxResult {
14814    /// Point estimate of the aggregate.
14815    pub point: f64,
14816    /// Lower bound (`point − z·SE`).
14817    pub ci_low: f64,
14818    /// Upper bound (`point + z·SE`).
14819    pub ci_high: f64,
14820    /// Live population size (the table's `count()`).
14821    pub n_population: u64,
14822    /// Live rows in the sample (`≤` reservoir capacity).
14823    pub n_sample_live: usize,
14824    /// Sampled rows passing the WHERE predicate.
14825    pub n_passing: usize,
14826}
14827
14828/// A mergeable running aggregate state (Phase 8.3). Two states over disjoint
14829/// row sets `merge` into the state over their union, so a cached analytical
14830/// aggregate can be updated by merging in only the delta (newly inserted rows)
14831/// instead of a full recompute.
14832#[derive(Debug, Clone, PartialEq)]
14833pub enum AggState {
14834    /// `COUNT(*)` or `COUNT(col)` over `n` matching rows.
14835    Count(u64),
14836    /// Int64 `SUM`: running `i128` sum + non-null count.
14837    SumI {
14838        sum: i128,
14839        count: u64,
14840    },
14841    /// Float64 `SUM`: running `f64` sum + non-null count.
14842    SumF {
14843        sum: f64,
14844        count: u64,
14845    },
14846    /// Int64 `AVG`: running `i128` sum + non-null count (avg = sum/count).
14847    AvgI {
14848        sum: i128,
14849        count: u64,
14850    },
14851    /// Float64 `AVG`: running `f64` sum + non-null count.
14852    AvgF {
14853        sum: f64,
14854        count: u64,
14855    },
14856    /// Int64 `MIN`/`MAX`.
14857    MinI(i64),
14858    MaxI(i64),
14859    /// Float64 `MIN`/`MAX`.
14860    MinF(f64),
14861    MaxF(f64),
14862    /// No matching rows observed yet.
14863    Empty,
14864}
14865
14866impl AggState {
14867    /// Combine two states over disjoint row sets into the state over the union.
14868    pub fn merge(self, other: AggState) -> AggState {
14869        use AggState::*;
14870        match (self, other) {
14871            (Empty, x) | (x, Empty) => x,
14872            (Count(a), Count(b)) => Count(a + b),
14873            (SumI { sum: sa, count: ca }, SumI { sum: sb, count: cb }) => SumI {
14874                sum: sa + sb,
14875                count: ca + cb,
14876            },
14877            (SumF { sum: sa, count: ca }, SumF { sum: sb, count: cb }) => SumF {
14878                sum: sa + sb,
14879                count: ca + cb,
14880            },
14881            (AvgI { sum: sa, count: ca }, AvgI { sum: sb, count: cb }) => AvgI {
14882                sum: sa + sb,
14883                count: ca + cb,
14884            },
14885            (AvgF { sum: sa, count: ca }, AvgF { sum: sb, count: cb }) => AvgF {
14886                sum: sa + sb,
14887                count: ca + cb,
14888            },
14889            (MinI(a), MinI(b)) => MinI(a.min(b)),
14890            (MaxI(a), MaxI(b)) => MaxI(a.max(b)),
14891            (MinF(a), MinF(b)) => MinF(a.min(b)),
14892            (MaxF(a), MaxF(b)) => MaxF(a.max(b)),
14893            _ => Empty, // mismatched kinds — shouldn't happen (same query)
14894        }
14895    }
14896
14897    /// The scalar point value (`f64`), or `None` when there were no inputs.
14898    pub fn point(&self) -> Option<f64> {
14899        match self {
14900            AggState::Count(n) => Some(*n as f64),
14901            AggState::SumI { sum, .. } => Some(*sum as f64),
14902            AggState::SumF { sum, .. } => Some(*sum),
14903            AggState::AvgI { sum, count } if *count > 0 => Some(*sum as f64 / *count as f64),
14904            AggState::AvgF { sum, count } if *count > 0 => Some(*sum / *count as f64),
14905            AggState::MinI(n) => Some(*n as f64),
14906            AggState::MaxI(n) => Some(*n as f64),
14907            AggState::MinF(n) => Some(*n),
14908            AggState::MaxF(n) => Some(*n),
14909            AggState::AvgI { .. } | AggState::AvgF { .. } | AggState::Empty => None,
14910        }
14911    }
14912
14913    /// Convert a vectorized [`NativeAggResult`] (from the cursor path) into a
14914    /// mergeable [`AggState`], so the incremental cache can be seeded from the
14915    /// fast cold path. `ty` is the column's type (`None` for COUNT(*)).
14916    pub fn from_native(result: NativeAggResult, agg: NativeAgg, ty: Option<TypeId>) -> Self {
14917        let is_float = matches!(ty, Some(TypeId::Float64));
14918        match (agg, result) {
14919            (NativeAgg::Count, NativeAggResult::Count(n)) => AggState::Count(n),
14920            (NativeAgg::Sum, NativeAggResult::Int(x)) => AggState::SumI {
14921                sum: x as i128,
14922                count: 1, // count unknown from NativeAggResult; use sentinel
14923            },
14924            (NativeAgg::Sum, NativeAggResult::Float(x)) => AggState::SumF { sum: x, count: 1 },
14925            (NativeAgg::Avg, NativeAggResult::Float(x)) => AggState::AvgF { sum: x, count: 1 },
14926            (NativeAgg::Min, NativeAggResult::Int(x)) => AggState::MinI(x),
14927            (NativeAgg::Max, NativeAggResult::Int(x)) => AggState::MaxI(x),
14928            (NativeAgg::Min, NativeAggResult::Float(x)) => AggState::MinF(x),
14929            (NativeAgg::Max, NativeAggResult::Float(x)) => AggState::MaxF(x),
14930            (NativeAgg::Count, _) => AggState::Empty,
14931            (_, NativeAggResult::Null) => AggState::Empty,
14932            _ => {
14933                let _ = is_float;
14934                AggState::Empty
14935            }
14936        }
14937    }
14938}
14939
14940/// A cached incremental aggregate (Phase 8.3): the mergeable state, the row-id
14941/// watermark it covers (rows `[0, watermark)`), and the snapshot epoch.
14942#[derive(Debug, Clone)]
14943pub struct CachedAgg {
14944    pub state: AggState,
14945    pub watermark: u64,
14946    pub epoch: u64,
14947}
14948
14949/// Outcome of [`Table::aggregate_incremental`].
14950#[derive(Debug, Clone)]
14951pub struct IncrementalAggResult {
14952    /// The aggregate state covering all rows at the current epoch.
14953    pub state: AggState,
14954    /// `true` when produced by merging only the delta (new rows); `false` when
14955    /// a full recompute was required (cold cache, deletes, or same epoch).
14956    pub incremental: bool,
14957    /// Rows processed in the delta pass (`0` for a full recompute).
14958    pub delta_rows: u64,
14959}
14960
14961/// Compute a mergeable [`AggState`] over `rows` that pass every per-row
14962/// `conditions` conjunct (and whose row id is in every pre-resolved
14963/// `index_sets`). Shared by the cold (full) and warm (delta) incremental paths.
14964fn agg_state_from_rows(
14965    rows: &[Row],
14966    conditions: &[crate::query::Condition],
14967    index_sets: &[RowIdSet],
14968    column: Option<u16>,
14969    agg: NativeAgg,
14970    schema: &Schema,
14971    control: Option<&crate::ExecutionControl>,
14972) -> Result<AggState> {
14973    let mut count: u64 = 0;
14974    let mut sum_i: i128 = 0;
14975    let mut sum_f: f64 = 0.0;
14976    let mut mn_i: i64 = i64::MAX;
14977    let mut mx_i: i64 = i64::MIN;
14978    let mut mn_f: f64 = f64::INFINITY;
14979    let mut mx_f: f64 = f64::NEG_INFINITY;
14980    let mut saw_int = false;
14981    let mut saw_float = false;
14982    for (index, r) in rows.iter().enumerate() {
14983        execution_checkpoint(control, index)?;
14984        if !conditions
14985            .iter()
14986            .all(|c| condition_matches_row(c, r, schema))
14987        {
14988            continue;
14989        }
14990        if !index_sets.iter().all(|s| s.contains(r.row_id.0)) {
14991            continue;
14992        }
14993        match agg {
14994            NativeAgg::Count => match column {
14995                // COUNT(*) counts every passing row.
14996                None => count += 1,
14997                // COUNT(col) excludes NULLs — explicit `Value::Null` and a column
14998                // absent from the row (schema evolution) are both NULL.
14999                Some(cid) => match r.columns.get(&cid) {
15000                    None | Some(Value::Null) => {}
15001                    Some(_) => count += 1,
15002                },
15003            },
15004            _ => match column.and_then(|cid| r.columns.get(&cid)) {
15005                Some(Value::Int64(n)) => {
15006                    count += 1;
15007                    sum_i += *n as i128;
15008                    mn_i = mn_i.min(*n);
15009                    mx_i = mx_i.max(*n);
15010                    saw_int = true;
15011                }
15012                Some(Value::Float64(f)) => {
15013                    count += 1;
15014                    sum_f += f;
15015                    mn_f = mn_f.min(*f);
15016                    mx_f = mx_f.max(*f);
15017                    saw_float = true;
15018                }
15019                _ => {}
15020            },
15021        }
15022    }
15023    Ok(match agg {
15024        NativeAgg::Count => {
15025            if count == 0 {
15026                AggState::Empty
15027            } else {
15028                AggState::Count(count)
15029            }
15030        }
15031        NativeAgg::Sum => {
15032            if count == 0 {
15033                AggState::Empty
15034            } else if saw_int {
15035                AggState::SumI { sum: sum_i, count }
15036            } else {
15037                AggState::SumF { sum: sum_f, count }
15038            }
15039        }
15040        NativeAgg::Avg => {
15041            if count == 0 {
15042                AggState::Empty
15043            } else if saw_int {
15044                AggState::AvgI { sum: sum_i, count }
15045            } else {
15046                AggState::AvgF { sum: sum_f, count }
15047            }
15048        }
15049        NativeAgg::Min => {
15050            if !saw_int && !saw_float {
15051                AggState::Empty
15052            } else if saw_int {
15053                AggState::MinI(mn_i)
15054            } else {
15055                AggState::MinF(mn_f)
15056            }
15057        }
15058        NativeAgg::Max => {
15059            if !saw_int && !saw_float {
15060                AggState::Empty
15061            } else if saw_int {
15062                AggState::MaxI(mx_i)
15063            } else {
15064                AggState::MaxF(mx_f)
15065            }
15066        }
15067    })
15068}
15069
15070/// Evaluate an index-served [`Condition`] exactly against a materialized row.
15071/// `Ann`/`SparseMatch` (index-defined) always pass here; callers test those via a
15072/// pre-resolved row-id set.
15073fn condition_matches_row(c: &crate::query::Condition, row: &Row, schema: &Schema) -> bool {
15074    use crate::query::Condition;
15075    match c {
15076        Condition::Pk(key) => match schema.primary_key() {
15077            Some(pk) => row
15078                .columns
15079                .get(&pk.id)
15080                .map(|v| v.encode_key() == *key)
15081                .unwrap_or(false),
15082            None => false,
15083        },
15084        Condition::BitmapEq { column_id, value } => row
15085            .columns
15086            .get(column_id)
15087            .map(|v| v.encode_key() == *value)
15088            .unwrap_or(false),
15089        Condition::BitmapIn { column_id, values } => {
15090            let key = row.columns.get(column_id).map(|v| v.encode_key());
15091            match key {
15092                Some(k) => values.contains(&k),
15093                None => false,
15094            }
15095        }
15096        Condition::BytesPrefix { column_id, prefix } => row
15097            .columns
15098            .get(column_id)
15099            .map(|v| v.encode_key().starts_with(prefix))
15100            .unwrap_or(false),
15101        Condition::Range { column_id, lo, hi } => match row.columns.get(column_id) {
15102            Some(Value::Int64(n)) => *n >= *lo && *n <= *hi,
15103            _ => false,
15104        },
15105        Condition::RangeF64 {
15106            column_id,
15107            lo,
15108            lo_inclusive,
15109            hi,
15110            hi_inclusive,
15111        } => match row.columns.get(column_id) {
15112            Some(Value::Float64(n)) => {
15113                let lo_ok = if *lo_inclusive { *n >= *lo } else { *n > *lo };
15114                let hi_ok = if *hi_inclusive { *n <= *hi } else { *n < *hi };
15115                lo_ok && hi_ok
15116            }
15117            _ => false,
15118        },
15119        Condition::FmContains { column_id, pattern } => match row.columns.get(column_id) {
15120            Some(Value::Bytes(b)) => {
15121                !pattern.is_empty() && b.windows(pattern.len()).any(|w| w == &pattern[..])
15122            }
15123            _ => false,
15124        },
15125        Condition::FmContainsAll {
15126            column_id,
15127            patterns,
15128        } => match row.columns.get(column_id) {
15129            Some(Value::Bytes(b)) => patterns
15130                .iter()
15131                .all(|pat| !pat.is_empty() && b.windows(pat.len()).any(|w| w == &pat[..])),
15132            _ => false,
15133        },
15134        Condition::Ann { .. }
15135        | Condition::SparseMatch { .. }
15136        | Condition::MinHashSimilar { .. } => true,
15137        Condition::IsNull { column_id } => {
15138            matches!(row.columns.get(column_id), Some(Value::Null) | None)
15139        }
15140        Condition::IsNotNull { column_id } => {
15141            !matches!(row.columns.get(column_id), Some(Value::Null) | None)
15142        }
15143    }
15144}
15145
15146/// Coerce a cell to `f64` for Sum/Avg (Int64/Float64 only).
15147fn as_f64(v: Option<&Value>) -> Option<f64> {
15148    match v {
15149        Some(Value::Int64(n)) => Some(*n as f64),
15150        Some(Value::Float64(f)) => Some(*f),
15151        _ => None,
15152    }
15153}
15154
15155/// One-pass vectorized accumulation of `(non-null count, sum, min, max)` over an
15156/// Int64 column streamed through `cursor`. The inner loop over a contiguous
15157/// `&[i64]` autovectorizes (SIMD) for the all-non-null prefix.
15158fn accumulate_int(
15159    cursor: &mut dyn crate::cursor::Cursor,
15160    control: Option<&crate::ExecutionControl>,
15161) -> Result<(u64, i128, i64, i64)> {
15162    let mut count: u64 = 0;
15163    let mut sum: i128 = 0;
15164    let mut mn: i64 = i64::MAX;
15165    let mut mx: i64 = i64::MIN;
15166    while let Some(cols) = cursor.next_batch()? {
15167        execution_checkpoint(control, 0)?;
15168        if let Some(crate::columnar::NativeColumn::Int64 { data, validity }) = cols.first() {
15169            if crate::columnar::all_non_null(validity, data.len()) {
15170                // All-non-null: vectorized sum/min/max with no per-element branch.
15171                count += data.len() as u64;
15172                for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15173                    execution_checkpoint(control, chunk_index * 1024)?;
15174                    sum += chunk.iter().map(|&v| v as i128).sum::<i128>();
15175                    mn = mn.min(*chunk.iter().min().unwrap_or(&mn));
15176                    mx = mx.max(*chunk.iter().max().unwrap_or(&mx));
15177                }
15178            } else {
15179                for (i, &v) in data.iter().enumerate() {
15180                    execution_checkpoint(control, i)?;
15181                    if crate::columnar::validity_bit(validity, i) {
15182                        count += 1;
15183                        sum += v as i128;
15184                        mn = mn.min(v);
15185                        mx = mx.max(v);
15186                    }
15187                }
15188            }
15189        }
15190    }
15191    Ok((count, sum, mn, mx))
15192}
15193
15194/// f64 analogue of [`accumulate_int`].
15195fn accumulate_float(
15196    cursor: &mut dyn crate::cursor::Cursor,
15197    control: Option<&crate::ExecutionControl>,
15198) -> Result<(u64, f64, f64, f64)> {
15199    let mut count: u64 = 0;
15200    let mut sum: f64 = 0.0;
15201    let mut mn: f64 = f64::INFINITY;
15202    let mut mx: f64 = f64::NEG_INFINITY;
15203    while let Some(cols) = cursor.next_batch()? {
15204        execution_checkpoint(control, 0)?;
15205        if let Some(crate::columnar::NativeColumn::Float64 { data, validity }) = cols.first() {
15206            if crate::columnar::all_non_null(validity, data.len()) {
15207                count += data.len() as u64;
15208                for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15209                    execution_checkpoint(control, chunk_index * 1024)?;
15210                    sum += chunk.iter().sum::<f64>();
15211                    mn = mn.min(chunk.iter().copied().fold(f64::INFINITY, f64::min));
15212                    mx = mx.max(chunk.iter().copied().fold(f64::NEG_INFINITY, f64::max));
15213                }
15214            } else {
15215                for (i, &v) in data.iter().enumerate() {
15216                    execution_checkpoint(control, i)?;
15217                    if crate::columnar::validity_bit(validity, i) {
15218                        count += 1;
15219                        sum += v;
15220                        mn = mn.min(v);
15221                        mx = mx.max(v);
15222                    }
15223                }
15224            }
15225        }
15226    }
15227    Ok((count, sum, mn, mx))
15228}
15229
15230#[inline]
15231fn execution_checkpoint(control: Option<&crate::ExecutionControl>, index: usize) -> Result<()> {
15232    if index.is_multiple_of(256) {
15233        control
15234            .map(crate::ExecutionControl::checkpoint)
15235            .transpose()?;
15236    }
15237    Ok(())
15238}
15239
15240fn pack_int(agg: NativeAgg, count: u64, sum: i128, mn: i64, mx: i64) -> NativeAggResult {
15241    if count == 0 && !matches!(agg, NativeAgg::Count) {
15242        return NativeAggResult::Null;
15243    }
15244    match agg {
15245        NativeAgg::Count => NativeAggResult::Count(count),
15246        // i64 overflow on Sum ⇒ SQL NULL (DataFusion errors on overflow; null is
15247        // a safe, non-misleading fallback rather than a saturated wrong value).
15248        NativeAgg::Sum => match sum.try_into() {
15249            Ok(v) => NativeAggResult::Int(v),
15250            Err(_) => NativeAggResult::Null,
15251        },
15252        NativeAgg::Min => NativeAggResult::Int(mn),
15253        NativeAgg::Max => NativeAggResult::Int(mx),
15254        NativeAgg::Avg => NativeAggResult::Float((sum as f64) / (count as f64)),
15255    }
15256}
15257
15258fn pack_float(agg: NativeAgg, count: u64, sum: f64, mn: f64, mx: f64) -> NativeAggResult {
15259    if count == 0 && !matches!(agg, NativeAgg::Count) {
15260        return NativeAggResult::Null;
15261    }
15262    match agg {
15263        NativeAgg::Count => NativeAggResult::Count(count),
15264        NativeAgg::Sum => NativeAggResult::Float(sum),
15265        NativeAgg::Min => NativeAggResult::Float(mn),
15266        NativeAgg::Max => NativeAggResult::Float(mx),
15267        NativeAgg::Avg => NativeAggResult::Float(sum / (count as f64)),
15268    }
15269}
15270
15271/// Aggregate per-page `min`/`max`/`null_count` into a column-wide i64 triple.
15272/// Returns `None` if no page contributes a non-null min/max (all-null column).
15273fn agg_int(
15274    stats: &[crate::page::PageStat],
15275    decode: fn(Option<&[u8]>) -> Option<i64>,
15276) -> Option<(Option<i64>, Option<i64>, u64)> {
15277    let (mut mn, mut mx, mut nulls) = (i64::MAX, i64::MIN, 0u64);
15278    let mut any = false;
15279    for s in stats {
15280        if let Some(v) = decode(s.min.as_deref()) {
15281            mn = mn.min(v);
15282            any = true;
15283        }
15284        if let Some(v) = decode(s.max.as_deref()) {
15285            mx = mx.max(v);
15286            any = true;
15287        }
15288        nulls += s.null_count;
15289    }
15290    any.then_some((Some(mn), Some(mx), nulls))
15291}
15292
15293/// f64 analogue of [`agg_int`] (compares as f64, not as bit patterns).
15294fn agg_float(
15295    stats: &[crate::page::PageStat],
15296    decode: fn(Option<&[u8]>) -> Option<f64>,
15297) -> Option<(Option<f64>, Option<f64>, u64)> {
15298    let (mut mn, mut mx, mut nulls) = (f64::INFINITY, f64::NEG_INFINITY, 0u64);
15299    let mut any = false;
15300    for s in stats {
15301        if let Some(v) = decode(s.min.as_deref()) {
15302            mn = mn.min(v);
15303            any = true;
15304        }
15305        if let Some(v) = decode(s.max.as_deref()) {
15306            mx = mx.max(v);
15307            any = true;
15308        }
15309        nulls += s.null_count;
15310    }
15311    any.then_some((Some(mn), Some(mx), nulls))
15312}
15313
15314/// The four maintained secondary-index maps, keyed by column id.
15315type SecondaryIndexes = (
15316    HashMap<u16, BitmapIndex>,
15317    HashMap<u16, AnnIndex>,
15318    HashMap<u16, FmIndex>,
15319    HashMap<u16, SparseIndex>,
15320    HashMap<u16, MinHashIndex>,
15321);
15322
15323fn empty_indexes(schema: &Schema) -> SecondaryIndexes {
15324    let mut bitmap = HashMap::new();
15325    let mut ann = HashMap::new();
15326    let mut fm = HashMap::new();
15327    let mut sparse = HashMap::new();
15328    let mut minhash = HashMap::new();
15329    for idef in &schema.indexes {
15330        match idef.kind {
15331            IndexKind::Bitmap => {
15332                bitmap.insert(idef.column_id, BitmapIndex::new());
15333            }
15334            IndexKind::Ann => {
15335                let dim = schema
15336                    .columns
15337                    .iter()
15338                    .find(|c| c.id == idef.column_id)
15339                    .and_then(|c| match c.ty {
15340                        TypeId::Embedding { dim } => Some(dim as usize),
15341                        _ => None,
15342                    })
15343                    .unwrap_or(0);
15344                let options = idef.options.ann.clone().unwrap_or_default();
15345                ann.insert(
15346                    idef.column_id,
15347                    AnnIndex::with_full_options(
15348                        dim,
15349                        options.m,
15350                        options.ef_construction,
15351                        options.ef_search,
15352                        &options,
15353                    ),
15354                );
15355            }
15356            IndexKind::FmIndex => {
15357                fm.insert(idef.column_id, FmIndex::new());
15358            }
15359            IndexKind::Sparse => {
15360                sparse.insert(idef.column_id, SparseIndex::new());
15361            }
15362            IndexKind::MinHash => {
15363                let options = idef.options.minhash.clone().unwrap_or_default();
15364                minhash.insert(
15365                    idef.column_id,
15366                    MinHashIndex::with_options(options.permutations, options.bands),
15367                );
15368            }
15369            _ => {}
15370        }
15371    }
15372    (bitmap, ann, fm, sparse, minhash)
15373}
15374
15375const ALTER_COLUMN_PROTECTED_FLAGS: u32 = ColumnFlags::PRIMARY_KEY
15376    | ColumnFlags::AUTO_INCREMENT
15377    | ColumnFlags::ENCRYPTED
15378    | ColumnFlags::ENCRYPTED_INDEXABLE
15379    | ColumnFlags::EMBEDDING_BINARY_QUANTIZED;
15380
15381fn validate_alter_column_flags(old: ColumnFlags, new: ColumnFlags) -> Result<()> {
15382    if (old.bits() ^ new.bits()) & ALTER_COLUMN_PROTECTED_FLAGS != 0 {
15383        return Err(MongrelError::Schema(
15384            "ALTER COLUMN may only change NULLABLE; primary key, auto-increment, encryption, and embedding flags are immutable".into(),
15385        ));
15386    }
15387    Ok(())
15388}
15389
15390fn validate_alter_column_type(
15391    schema: &Schema,
15392    old: &ColumnDef,
15393    next: &ColumnDef,
15394    has_stored_versions: bool,
15395) -> Result<()> {
15396    if old.ty == next.ty {
15397        return Ok(());
15398    }
15399    if schema.indexes.iter().any(|i| i.column_id == old.id) {
15400        return Err(MongrelError::Schema(format!(
15401            "ALTER COLUMN TYPE is not supported for indexed column '{}'",
15402            old.name
15403        )));
15404    }
15405    if !has_stored_versions || storage_compatible_type_change(old.ty.clone(), next.ty.clone()) {
15406        return Ok(());
15407    }
15408    Err(MongrelError::Schema(format!(
15409        "ALTER COLUMN TYPE from {:?} to {:?} requires an empty column or a representation-compatible type",
15410        old.ty, next.ty
15411    )))
15412}
15413
15414fn storage_compatible_type_change(old: TypeId, new: TypeId) -> bool {
15415    matches!(
15416        (old, new),
15417        (TypeId::Int64, TypeId::TimestampNanos) | (TypeId::TimestampNanos, TypeId::Int64)
15418    )
15419}
15420
15421/// True when every row carries an `Int64` PK value and the sequence is
15422/// strictly increasing — no intra-batch duplicate is possible. The row-major
15423/// mirror of `native_int64_strictly_increasing` (the `bulk_pk_winner_indices`
15424/// fast path), used by `apply_put_rows_inner` to skip upsert probing for
15425/// append-style batches.
15426fn rows_pk_strictly_increasing(rows: &[Row], pk_id: u16) -> bool {
15427    let mut prev: Option<i64> = None;
15428    for r in rows {
15429        match r.columns.get(&pk_id) {
15430            Some(Value::Int64(v)) => {
15431                if prev.is_some_and(|p| p >= *v) {
15432                    return false;
15433                }
15434                prev = Some(*v);
15435            }
15436            _ => return false,
15437        }
15438    }
15439    true
15440}
15441
15442#[allow(clippy::too_many_arguments)]
15443fn index_into(
15444    schema: &Schema,
15445    row: &Row,
15446    hot: &mut HotIndex,
15447    bitmap: &mut HashMap<u16, BitmapIndex>,
15448    ann: &mut HashMap<u16, AnnIndex>,
15449    fm: &mut HashMap<u16, FmIndex>,
15450    sparse: &mut HashMap<u16, SparseIndex>,
15451    minhash: &mut HashMap<u16, MinHashIndex>,
15452) {
15453    for idef in &schema.indexes {
15454        let Some(val) = row.columns.get(&idef.column_id) else {
15455            continue;
15456        };
15457        match idef.kind {
15458            IndexKind::Bitmap => {
15459                if let Some(b) = bitmap.get_mut(&idef.column_id) {
15460                    b.insert(val.encode_key(), row.row_id);
15461                }
15462            }
15463            IndexKind::Ann => {
15464                if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15465                    if let Some(meta) = val.generated_embedding_metadata() {
15466                        // P1.5-T3: pending/failed generated vectors stay out of ANN.
15467                        if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15468                            continue;
15469                        }
15470                        if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15471                            .is_err()
15472                        {
15473                            continue;
15474                        }
15475                    }
15476                    a.insert_validated(v, row.row_id);
15477                }
15478            }
15479            IndexKind::FmIndex => {
15480                if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15481                    f.insert(b.clone(), row.row_id);
15482                }
15483            }
15484            IndexKind::Sparse => {
15485                if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15486                    // A sparse vector is stored as a bincode'd `Vec<(u32, f32)>`
15487                    // in a Bytes column (SPLADE weights in, retrieval out).
15488                    if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15489                        s.insert(&terms, row.row_id);
15490                    }
15491                }
15492            }
15493            IndexKind::MinHash => {
15494                if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15495                    // The set is a JSON array (the Kit's `set_similarity` shape);
15496                    // tokenize + hash its members into the MinHash signature.
15497                    let tokens = crate::index::token_hashes_from_bytes(b);
15498                    mh.insert(&tokens, row.row_id);
15499                }
15500            }
15501            _ => {}
15502        }
15503    }
15504    if let Some(pk_col) = schema.primary_key() {
15505        if let Some(pk_val) = row.columns.get(&pk_col.id) {
15506            hot.insert(pk_val.encode_key(), row.row_id);
15507        }
15508    }
15509}
15510
15511/// Index a row into a single specific index (used for partial indexes where
15512/// only matching indexes should receive the row).
15513#[allow(clippy::too_many_arguments)]
15514fn index_into_single(
15515    idef: &IndexDef,
15516    _schema: &Schema,
15517    row: &Row,
15518    _hot: &mut HotIndex,
15519    bitmap: &mut HashMap<u16, BitmapIndex>,
15520    ann: &mut HashMap<u16, AnnIndex>,
15521    fm: &mut HashMap<u16, FmIndex>,
15522    sparse: &mut HashMap<u16, SparseIndex>,
15523    minhash: &mut HashMap<u16, MinHashIndex>,
15524) {
15525    let Some(val) = row.columns.get(&idef.column_id) else {
15526        return;
15527    };
15528    match idef.kind {
15529        IndexKind::Bitmap => {
15530            if let Some(b) = bitmap.get_mut(&idef.column_id) {
15531                b.insert(val.encode_key(), row.row_id);
15532            }
15533        }
15534        IndexKind::Ann => {
15535            if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15536                if let Some(meta) = val.generated_embedding_metadata() {
15537                    // P1.5-T3: pending/failed generated vectors stay out of ANN.
15538                    if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15539                        return;
15540                    }
15541                    if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15542                        .is_err()
15543                    {
15544                        return;
15545                    }
15546                }
15547                a.insert_validated(v, row.row_id);
15548            }
15549        }
15550        IndexKind::FmIndex => {
15551            if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15552                f.insert(b.clone(), row.row_id);
15553            }
15554        }
15555        IndexKind::Sparse => {
15556            if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15557                if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15558                    s.insert(&terms, row.row_id);
15559                }
15560            }
15561        }
15562        IndexKind::MinHash => {
15563            if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15564                let tokens = crate::index::token_hashes_from_bytes(b);
15565                mh.insert(&tokens, row.row_id);
15566            }
15567        }
15568        _ => {}
15569    }
15570}
15571
15572/// Evaluate a partial-index predicate against a row. Supports the most common
15573/// patterns: `"column IS NOT NULL"` and `"column IS NULL"`. More complex
15574/// expressions require a full SQL evaluator in core (future work); the
15575/// predicate string is stored verbatim and this function provides a pragmatic
15576/// subset. Returns `true` if the row should be indexed.
15577fn eval_partial_predicate(
15578    pred: &str,
15579    columns_map: &HashMap<u16, &Value>,
15580    name_to_id: &HashMap<&str, u16>,
15581) -> bool {
15582    let lower = pred.trim().to_ascii_lowercase();
15583    // Pattern: "column_name IS NOT NULL"
15584    if let Some(rest) = lower.strip_suffix(" is not null") {
15585        let col_name = rest.trim();
15586        if let Some(col_id) = name_to_id.get(col_name) {
15587            return columns_map
15588                .get(col_id)
15589                .is_some_and(|v| !matches!(v, Value::Null));
15590        }
15591    }
15592    // Pattern: "column_name IS NULL"
15593    if let Some(rest) = lower.strip_suffix(" is null") {
15594        let col_name = rest.trim();
15595        if let Some(col_id) = name_to_id.get(col_name) {
15596            return columns_map
15597                .get(col_id)
15598                .is_none_or(|v| matches!(v, Value::Null));
15599        }
15600    }
15601    // Unknown predicate syntax: index the row (conservative — better to
15602    // over-index than to miss rows).
15603    true
15604}
15605
15606/// Per-element index key for the typed bulk-index path (Phase 14.2): mirrors
15607/// `index_into` on a `tokenized_for_indexes(row)` — encodes the element the way
15608/// [`Value::encode_key`] would, then applies the column's
15609/// `ENCRYPTED_INDEXABLE` tokenization (HMAC-eq / OPE) so bitmap/HOT keys match
15610/// what the incremental path stores. Returns `None` for null slots.
15611#[allow(dead_code)]
15612fn bulk_index_key(
15613    column_keys: &HashMap<u16, ([u8; 32], u8)>,
15614    column_id: u16,
15615    ty: TypeId,
15616    col: &columnar::NativeColumn,
15617    i: usize,
15618) -> Option<Vec<u8>> {
15619    let encoded = columnar::encode_key_native(ty, col, i)?;
15620    {
15621        use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
15622        if let Some((key, scheme)) = column_keys.get(&column_id) {
15623            return Some(match (*scheme, col) {
15624                (SCHEME_HMAC_EQ, _) => hmac_token(key, &encoded).to_vec(),
15625                (_, columnar::NativeColumn::Int64 { data, .. }) => {
15626                    ope_token_i64(key, data[i]).to_vec()
15627                }
15628                (_, columnar::NativeColumn::Float64 { data, .. }) => {
15629                    ope_token_f64(key, data[i]).to_vec()
15630                }
15631                _ => hmac_token(key, &encoded).to_vec(),
15632            });
15633        }
15634    }
15635    Some(encoded)
15636}
15637
15638pub(crate) fn write_schema(dir: &Path, schema: &Schema) -> Result<()> {
15639    write_schema_with_after(dir, schema, || {})
15640}
15641
15642pub(crate) fn write_schema_durable(
15643    root: &crate::durable_file::DurableRoot,
15644    schema: &Schema,
15645) -> Result<()> {
15646    write_schema_durable_with_after(root, schema, || {})
15647}
15648
15649fn write_schema_with_after<F>(dir: &Path, schema: &Schema, after_publish: F) -> Result<()>
15650where
15651    F: FnOnce(),
15652{
15653    let json = serde_json::to_string_pretty(schema)
15654        .map_err(|e| MongrelError::Schema(format!("encode schema: {e}")))?;
15655    crate::durable_file::write_atomic_with_after(
15656        &dir.join(SCHEMA_FILENAME),
15657        json.as_bytes(),
15658        after_publish,
15659    )?;
15660    Ok(())
15661}
15662
15663fn write_schema_durable_with_after<F>(
15664    root: &crate::durable_file::DurableRoot,
15665    schema: &Schema,
15666    after_publish: F,
15667) -> Result<()>
15668where
15669    F: FnOnce(),
15670{
15671    let json = serde_json::to_string_pretty(schema)
15672        .map_err(|error| MongrelError::Schema(format!("encode schema: {error}")))?;
15673    root.write_atomic_with_after(SCHEMA_FILENAME, json.as_bytes(), after_publish)?;
15674    Ok(())
15675}
15676
15677fn checkpoint_current_schema(table: &mut Table) -> Result<()> {
15678    let mut schema_published = false;
15679    let schema_result = match table._root_guard.as_deref() {
15680        Some(root) => write_schema_durable_with_after(root, &table.schema, || {
15681            schema_published = true;
15682        }),
15683        None => write_schema_with_after(&table.dir, &table.schema, || {
15684            schema_published = true;
15685        }),
15686    };
15687    if schema_result.is_err() && !schema_published {
15688        return schema_result;
15689    }
15690    match table.persist_manifest(table.current_epoch()) {
15691        Ok(()) => Ok(()),
15692        Err(manifest_error) => Err(match schema_result {
15693            Ok(()) => manifest_error,
15694            Err(schema_error) => MongrelError::Other(format!(
15695                "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
15696            )),
15697        }),
15698    }
15699}
15700
15701fn read_schema(dir: &Path) -> Result<Schema> {
15702    let file = crate::durable_file::open_regular_nofollow(&dir.join(SCHEMA_FILENAME))?;
15703    read_schema_file(file)
15704}
15705
15706fn read_schema_file(file: std::fs::File) -> Result<Schema> {
15707    const MAX_SCHEMA_BYTES: u64 = 16 * 1024 * 1024;
15708    use std::io::Read;
15709
15710    let length = file.metadata()?.len();
15711    if length > MAX_SCHEMA_BYTES {
15712        return Err(MongrelError::ResourceLimitExceeded {
15713            resource: "schema bytes",
15714            requested: usize::try_from(length).unwrap_or(usize::MAX),
15715            limit: MAX_SCHEMA_BYTES as usize,
15716        });
15717    }
15718    let mut bytes = Vec::with_capacity(length as usize);
15719    file.take(MAX_SCHEMA_BYTES + 1).read_to_end(&mut bytes)?;
15720    if bytes.len() as u64 != length {
15721        return Err(MongrelError::Schema(
15722            "schema length changed while reading".into(),
15723        ));
15724    }
15725    serde_json::from_slice(&bytes).map_err(|e| MongrelError::Schema(format!("decode schema: {e}")))
15726}
15727
15728fn preflight_standalone_open(
15729    dir: &Path,
15730    runs_root: Option<&crate::durable_file::DurableRoot>,
15731    idx_root: Option<&crate::durable_file::DurableRoot>,
15732    manifest: &Manifest,
15733    schema: &Schema,
15734    records: &[crate::wal::Record],
15735    kek: Option<Arc<Kek>>,
15736) -> Result<()> {
15737    crate::wal::validate_shared_transaction_framing(records)?;
15738    if manifest.schema_id > schema.schema_id
15739        || manifest.flushed_epoch > manifest.current_epoch
15740        || manifest.global_idx_epoch > manifest.current_epoch
15741        || manifest.next_row_id == u64::MAX
15742        || manifest.auto_inc_next < 0
15743        || manifest.auto_inc_next == i64::MAX
15744        || (schema.auto_increment_column().is_none() && manifest.auto_inc_next != 0)
15745    {
15746        return Err(MongrelError::InvalidArgument(
15747            "manifest counters or schema identity are invalid".into(),
15748        ));
15749    }
15750    let mut run_ids = HashSet::new();
15751    let mut maximum_row_id = None::<u64>;
15752    for run in &manifest.runs {
15753        if run.run_id >= u64::MAX as u128
15754            || !run_ids.insert(run.run_id)
15755            || run.epoch_created > manifest.current_epoch
15756        {
15757            return Err(MongrelError::InvalidArgument(
15758                "manifest contains an invalid or duplicate active run".into(),
15759            ));
15760        }
15761        let mut reader = match runs_root {
15762            Some(root) => RunReader::open_file(
15763                root.open_regular(format!("r-{}.sr", run.run_id as u64))?,
15764                schema.clone(),
15765                kek.clone(),
15766            )?,
15767            None => RunReader::open(
15768                dir.join(RUNS_DIR)
15769                    .join(format!("r-{}.sr", run.run_id as u64)),
15770                schema.clone(),
15771                kek.clone(),
15772            )?,
15773        };
15774        let header = reader.header();
15775        if header.run_id != run.run_id
15776            || header.level != run.level
15777            || header.row_count != run.row_count
15778            || !header.is_uniform_epoch() && header.epoch_created != run.epoch_created
15779            || header.is_uniform_epoch() && header.epoch_created != 0
15780            || header.schema_id > schema.schema_id
15781        {
15782            return Err(MongrelError::InvalidArgument(format!(
15783                "run {} differs from its manifest",
15784                run.run_id
15785            )));
15786        }
15787        if header.row_count != 0 {
15788            maximum_row_id = Some(
15789                maximum_row_id.map_or(header.max_row_id, |value| value.max(header.max_row_id)),
15790            );
15791        }
15792        reader.validate_all_pages()?;
15793    }
15794    if maximum_row_id.is_some_and(|maximum| manifest.next_row_id <= maximum) {
15795        return Err(MongrelError::InvalidArgument(
15796            "manifest next_row_id does not advance beyond persisted rows".into(),
15797        ));
15798    }
15799    for run in &manifest.retiring {
15800        if run.run_id >= u64::MAX as u128
15801            || run.retire_epoch > manifest.current_epoch
15802            || !run_ids.insert(run.run_id)
15803        {
15804            return Err(MongrelError::InvalidArgument(
15805                "manifest contains an invalid or duplicate retired run".into(),
15806            ));
15807        }
15808    }
15809    let idx_dek = kek.as_ref().map(|key| key.derive_idx_key());
15810    match idx_root {
15811        Some(root) => {
15812            global_idx::read_root(root, manifest.table_id, schema, idx_dek.as_deref())?;
15813        }
15814        None => {
15815            global_idx::read(dir, manifest.table_id, schema, idx_dek.as_deref())?;
15816        }
15817    }
15818
15819    let committed = records
15820        .iter()
15821        .filter_map(|record| match record.op {
15822            Op::TxnCommit { epoch, .. } => Some((record.txn_id, epoch)),
15823            _ => None,
15824        })
15825        .collect::<HashMap<_, _>>();
15826    for record in records {
15827        let Some(&_commit_epoch) = committed.get(&record.txn_id) else {
15828            continue;
15829        };
15830        match &record.op {
15831            Op::Put { table_id, rows } => {
15832                if *table_id != manifest.table_id {
15833                    return Err(MongrelError::CorruptWal {
15834                        offset: record.seq.0,
15835                        reason: format!(
15836                            "private WAL record references table {table_id}, expected {}",
15837                            manifest.table_id
15838                        ),
15839                    });
15840                }
15841                let rows: Vec<Row> =
15842                    bincode::deserialize(rows).map_err(|error| MongrelError::CorruptWal {
15843                        offset: record.seq.0,
15844                        reason: format!("committed Put payload could not be decoded: {error}"),
15845                    })?;
15846                for row in rows {
15847                    if row.deleted || row.row_id.0 == u64::MAX {
15848                        return Err(MongrelError::CorruptWal {
15849                            offset: record.seq.0,
15850                            reason: "committed Put contains an invalid row identity".into(),
15851                        });
15852                    }
15853                    let cells = row.columns.into_iter().collect::<Vec<_>>();
15854                    schema
15855                        .validate_values(&cells)
15856                        .map_err(|error| MongrelError::CorruptWal {
15857                            offset: record.seq.0,
15858                            reason: format!("committed Put violates table schema: {error}"),
15859                        })?;
15860                    if schema.auto_increment_column().is_some_and(|column| {
15861                        matches!(
15862                            cells.iter().find(|(id, _)| *id == column.id),
15863                            Some((_, Value::Int64(value))) if *value == i64::MAX
15864                        )
15865                    }) {
15866                        return Err(MongrelError::CorruptWal {
15867                            offset: record.seq.0,
15868                            reason: "committed Put exhausts AUTO_INCREMENT".into(),
15869                        });
15870                    }
15871                }
15872            }
15873            Op::Delete { table_id, .. } | Op::TruncateTable { table_id }
15874                if *table_id != manifest.table_id =>
15875            {
15876                return Err(MongrelError::CorruptWal {
15877                    offset: record.seq.0,
15878                    reason: format!(
15879                        "private WAL record references table {table_id}, expected {}",
15880                        manifest.table_id
15881                    ),
15882                });
15883            }
15884            Op::TxnCommit { added_runs, .. } if !added_runs.is_empty() => {
15885                return Err(MongrelError::CorruptWal {
15886                    offset: record.seq.0,
15887                    reason: "private WAL contains shared spilled-run metadata".into(),
15888                });
15889            }
15890            _ => {}
15891        }
15892    }
15893    Ok(())
15894}
15895
15896fn next_wal_segment(wal_dir: &Path) -> Result<PathBuf> {
15897    Ok(wal_dir.join(format!("seg-{:06}.wal", next_wal_number(wal_dir)?)))
15898}
15899
15900fn wal_segment_number(path: &Path) -> Option<u64> {
15901    path.file_stem()
15902        .and_then(|stem| stem.to_str())
15903        .and_then(|stem| stem.strip_prefix("seg-"))
15904        .and_then(|number| number.parse().ok())
15905}
15906
15907fn latest_wal_segment(wal_dir: &Path) -> Result<Option<PathBuf>> {
15908    let n = list_wal_numbers(wal_dir)?;
15909    Ok(n.map(|max| wal_dir.join(format!("seg-{max:06}.wal"))))
15910}
15911
15912fn next_wal_number(wal_dir: &Path) -> Result<u32> {
15913    list_wal_numbers(wal_dir)?
15914        .map(|maximum| {
15915            maximum
15916                .checked_add(1)
15917                .ok_or_else(|| MongrelError::Full("WAL segment namespace exhausted".into()))
15918        })
15919        .unwrap_or(Ok(0))
15920}
15921
15922fn list_wal_numbers(wal_dir: &Path) -> Result<Option<u32>> {
15923    let mut max_n = None;
15924    let entries = match std::fs::read_dir(wal_dir) {
15925        Ok(entries) => entries,
15926        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
15927        Err(error) => return Err(error.into()),
15928    };
15929    for entry in entries {
15930        let entry = entry?;
15931        let fname = entry.file_name();
15932        let Some(s) = fname.to_str() else {
15933            continue;
15934        };
15935        let Some(stripped) = s.strip_prefix("seg-") else {
15936            continue;
15937        };
15938        let Some(number) = stripped.strip_suffix(".wal") else {
15939            return Err(MongrelError::CorruptWal {
15940                offset: 0,
15941                reason: format!("malformed WAL segment name {s:?}"),
15942            });
15943        };
15944        let n = number
15945            .parse::<u32>()
15946            .map_err(|_| MongrelError::CorruptWal {
15947                offset: 0,
15948                reason: format!("malformed WAL segment name {s:?}"),
15949            })?;
15950        if s != format!("seg-{n:06}.wal") || !entry.file_type()?.is_file() {
15951            return Err(MongrelError::CorruptWal {
15952                offset: n as u64,
15953                reason: format!("noncanonical or nonregular WAL segment {s:?}"),
15954            });
15955        }
15956        max_n = Some(max_n.map(|m: u32| m.max(n)).unwrap_or(n));
15957    }
15958    Ok(max_n)
15959}
15960
15961// =========================================================================
15962// REM-001: full HLC authority across multi-run merge paths.
15963//
15964// These tests are the canonical inversion fixture from spec §6.1 / §9:
15965//
15966//   Run A:  epoch=low    HLC=high   payload="newer-by-HLC"
15967//   Run B:  epoch=high   HLC=low    payload="older-by-HLC"
15968//   Snapshot: epoch=10   HLC=600
15969//   Expected winner: "newer-by-HLC"
15970//
15971// Before the fix, every affected path stored `Option<(Epoch, ...)>` and
15972// picked the cross-run winner by `epoch > best_epoch`. An epoch-only fold
15973// selects Run B (high epoch) over Run A (low epoch), even though the HLC
15974// watermark is above both rows' stamps and HLC is the authority.
15975//
15976// The fix threads `commit_ts` through every cross-run fold via
15977// `crate::epoch::VersionStamp`; the run APIs return metadata-preserving
15978// `VersionedColumnValue` / `VersionVisibility` structs so the engine merge
15979// can compare candidates by full version stamp instead of epoch alone.
15980//
15981// The tests live inside this module so they can exercise private helpers
15982// (`values_for_rids_at`, `eligible_candidate_ids`, `rebuild_indexes_from_runs`).
15983// =========================================================================
15984
15985#[cfg(test)]
15986mod rem001_multi_run_hlc_authority {
15987    use super::*;
15988    use crate::epoch::{Epoch, Snapshot, VersionStamp};
15989    use crate::memtable::{Row, Value};
15990    use crate::query::{Condition, Query};
15991    use crate::schema::{ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
15992    use mongreldb_types::hlc::HlcTimestamp;
15993    use tempfile::tempdir;
15994
15995    fn hlc(physical_micros: u64) -> HlcTimestamp {
15996        HlcTimestamp {
15997            physical_micros,
15998            logical: 0,
15999            node_tiebreaker: 1,
16000        }
16001    }
16002
16003    fn pk_schema() -> Schema {
16004        Schema {
16005            schema_id: 1,
16006            columns: vec![
16007                ColumnDef {
16008                    id: 1,
16009                    name: "id".into(),
16010                    ty: TypeId::Int64,
16011                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16012                    default_value: None,
16013                    embedding_source: None,
16014                },
16015                ColumnDef {
16016                    id: 2,
16017                    name: "name".into(),
16018                    ty: TypeId::Bytes,
16019                    flags: ColumnFlags::empty(),
16020                    default_value: None,
16021                    embedding_source: None,
16022                },
16023            ],
16024            indexes: Vec::new(),
16025            colocation: vec![],
16026            constraints: Default::default(),
16027            clustered: false,
16028        }
16029    }
16030
16031    fn pk_schema_with_bitmap() -> Schema {
16032        Schema {
16033            schema_id: 1,
16034            columns: vec![
16035                ColumnDef {
16036                    id: 1,
16037                    name: "id".into(),
16038                    ty: TypeId::Int64,
16039                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16040                    default_value: None,
16041                    embedding_source: None,
16042                },
16043                ColumnDef {
16044                    id: 2,
16045                    name: "name".into(),
16046                    ty: TypeId::Bytes,
16047                    flags: ColumnFlags::empty(),
16048                    default_value: None,
16049                    embedding_source: None,
16050                },
16051            ],
16052            // Bitmap index on `name` so we can verify BitmapEq membership
16053            // reflects the HLC-winning run after the index rebuild.
16054            indexes: vec![IndexDef {
16055                name: "name_bitmap".into(),
16056                column_id: 2,
16057                kind: IndexKind::Bitmap,
16058                predicate: None,
16059                options: Default::default(),
16060            }],
16061            colocation: vec![],
16062            constraints: Default::default(),
16063            clustered: false,
16064        }
16065    }
16066
16067    fn encode_put(table_id: u64, row: &Row) -> Vec<u8> {
16068        use crate::database::StagedTxnWrite;
16069        bincode::serialize(&StagedTxnWrite::Put {
16070            table_id,
16071            rows: bincode::serialize(&vec![row.clone()]).expect("encode row"),
16072        })
16073        .expect("encode payload")
16074    }
16075
16076    /// Build the canonical two-run inversion:
16077    ///
16078    /// 1. apply the HLC-newer row first (lower committed_epoch because the
16079    ///    commit happens before any other write);
16080    /// 2. force-flush → `Run A` with `(epoch=1, HLC=500, payload="newer-by-HLC")`;
16081    /// 3. apply the HLC-older row second (higher committed_epoch because the
16082    ///    commit advances `epoch.visible()`);
16083    /// 4. force-flush → `Run B` with `(epoch=2, HLC=400, payload="older-by-HLC")`.
16084    ///
16085    /// After both flushes the table owns two immutable `.sr` files; Run A
16086    /// holds the HLC-newer payload, Run B holds the HLC-older payload, and
16087    /// Run B has the higher epoch because it was written later. Epoch-only
16088    /// cross-run folding picks Run B; HLC authority picks Run A.
16089    fn build_inverted_database(dir: &std::path::Path, schema: Schema) -> crate::Database {
16090        let db = crate::Database::create(dir).unwrap();
16091        db.create_table("t", schema).unwrap();
16092        let table_id = db.table_id("t").unwrap();
16093        let rid = RowId(7);
16094
16095        let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16096            .with_column(1, Value::Int64(7))
16097            .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()));
16098        let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16099            .with_column(1, Value::Int64(7))
16100            .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()));
16101
16102        db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16103            .expect("first apply");
16104        {
16105            let table = db.table("t").unwrap();
16106            table.lock().force_flush().expect("flush run A");
16107        }
16108
16109        db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16110            .expect("second apply");
16111        {
16112            let table = db.table("t").unwrap();
16113            table.lock().force_flush().expect("flush run B");
16114        }
16115
16116        db
16117    }
16118
16119    /// TTL fixture: HLC-newer row carries a far-future `ttl_ts`; HLC-older
16120    /// row carries a far-past `ttl_ts`. The TTL eligibility path must read
16121    /// the timestamp from the HLC-newer run (live), not from the HLC-older
16122    /// run (expired), and admit the rid.
16123    fn build_inverted_ttl_database(dir: &std::path::Path) -> crate::Database {
16124        let db = crate::Database::create(dir).unwrap();
16125        db.create_table("t", ttl_schema()).unwrap();
16126        let table_id = db.table_id("t").unwrap();
16127        let rid = RowId(7);
16128        let read_time_ns: i64 = 1_000_000_000;
16129        let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16130            .with_column(1, Value::Int64(7))
16131            .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()))
16132            .with_column(3, Value::Int64(read_time_ns + 60 * 1_000_000_000));
16133        let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16134            .with_column(1, Value::Int64(7))
16135            .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()))
16136            .with_column(3, Value::Int64(read_time_ns - 60 * 1_000_000_000));
16137
16138        db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16139            .expect("first apply");
16140        {
16141            let table = db.table("t").unwrap();
16142            table.lock().force_flush().expect("flush run A");
16143        }
16144        db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16145            .expect("second apply");
16146        {
16147            let table = db.table("t").unwrap();
16148            table.lock().force_flush().expect("flush run B");
16149        }
16150
16151        db
16152    }
16153
16154    fn ttl_schema() -> Schema {
16155        Schema {
16156            schema_id: 1,
16157            columns: vec![
16158                ColumnDef {
16159                    id: 1,
16160                    name: "id".into(),
16161                    ty: TypeId::Int64,
16162                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16163                    default_value: None,
16164                    embedding_source: None,
16165                },
16166                ColumnDef {
16167                    id: 2,
16168                    name: "name".into(),
16169                    ty: TypeId::Bytes,
16170                    flags: ColumnFlags::empty(),
16171                    default_value: None,
16172                    embedding_source: None,
16173                },
16174                ColumnDef {
16175                    id: 3,
16176                    name: "ttl_ts".into(),
16177                    ty: TypeId::Int64,
16178                    flags: ColumnFlags::empty(),
16179                    default_value: None,
16180                    embedding_source: None,
16181                },
16182            ],
16183            indexes: Vec::new(),
16184            colocation: vec![],
16185            constraints: Default::default(),
16186            clustered: false,
16187        }
16188    }
16189
16190    #[test]
16191    fn multi_run_rows_for_rids_uses_hlc_winner_when_epoch_is_inverted() {
16192        let dir = tempdir().unwrap();
16193        let db = build_inverted_database(dir.path(), pk_schema());
16194        let table = db.table("t").unwrap();
16195        let table = table.lock();
16196        // HLC-pinned snapshot at HLC=600 — both rows are visible, the
16197        // HLC-newer (Run A) must win. An epoch-only fold would silently
16198        // return Run B's "older-by-HLC" payload because its epoch=2 > 1.
16199        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16200        let rows = table
16201            .rows_for_rids(&[7], snap)
16202            .expect("rows_for_rids across two runs");
16203        assert_eq!(rows.len(), 1, "one row materialised across two runs");
16204        assert_eq!(
16205            rows[0].columns.get(&2),
16206            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16207            "multi-run rows_for_rids must honor HLC authority"
16208        );
16209    }
16210
16211    #[test]
16212    fn multi_run_projected_column_uses_hlc_winner_when_epoch_is_inverted() {
16213        let dir = tempdir().unwrap();
16214        let db = build_inverted_database(dir.path(), pk_schema());
16215        let table = db.table("t").unwrap();
16216        let table = table.lock();
16217        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16218        let projected = table
16219            .values_for_rids_at(&[7], 2, snap, i64::MAX)
16220            .expect("values_for_rids_at across two runs");
16221        assert_eq!(projected.len(), 1);
16222        assert_eq!(
16223            projected[0].1,
16224            Value::Bytes(b"newer-by-HLC".to_vec()),
16225            "multi-run projection must pick the HLC-newer column"
16226        );
16227    }
16228
16229    #[test]
16230    fn ann_candidate_eligibility_uses_hlc_winner_across_runs() {
16231        let dir = tempdir().unwrap();
16232        let db = build_inverted_database(dir.path(), pk_schema());
16233        let table = db.table("t").unwrap();
16234        let table = table.lock();
16235        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16236        // ANN/Sparse/MinHash all funnel through `eligible_candidate_ids`.
16237        // The HLC-newer row must survive the visibility fold.
16238        let eligible = table
16239            .eligible_candidate_ids(&[RowId(7)], 2, snap, None)
16240            .expect("eligibility across runs");
16241        assert!(
16242            eligible.contains(&RowId(7)),
16243            "HLC-newer rid must remain eligible across runs"
16244        );
16245    }
16246
16247    #[test]
16248    fn ttl_inverted_run_is_admitted_via_values_for_rids_at() {
16249        let dir = tempdir().unwrap();
16250        let db = build_inverted_ttl_database(dir.path());
16251        let table = db.table("t").unwrap();
16252        let table = table.lock();
16253        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16254        let now_ns: i64 = 1_000_000_000;
16255        // HLC-newer row's ttl_ts = now+60s (live); HLC-older row's ttl_ts =
16256        // now-60s (expired). The TTL eligibility path must read the
16257        // timestamp from the HLC-newer run (live) and surface the rid.
16258        let projected = table
16259            .values_for_rids_at(&[7], 2, snap, now_ns)
16260            .expect("ttl-aware projection");
16261        assert_eq!(projected.len(), 1, "TTL must admit the HLC-newer row");
16262        assert_eq!(
16263            projected[0].1,
16264            Value::Bytes(b"newer-by-HLC".to_vec()),
16265            "TTL must be read from the HLC-newer run; older run's timestamp is expired"
16266        );
16267    }
16268
16269    #[test]
16270    fn hot_candidate_inspection_uses_full_snapshot_for_run_versions() {
16271        // The HOT-fallback inspection path. `inspect_row_at` is invoked via
16272        // `Table::get` for rid-resolved lookups (the same merge logic
16273        // applies); the test exercises the production read path and asserts
16274        // the HLC-newer payload wins across runs.
16275        let dir = tempdir().unwrap();
16276        let db = build_inverted_database(dir.path(), pk_schema());
16277        let table = db.table("t").unwrap();
16278        let table = table.lock();
16279        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16280        let row = table
16281            .get(RowId(7), snap)
16282            .expect("Table::get across two runs");
16283        assert_eq!(
16284            row.columns.get(&2),
16285            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16286            "Table::get must surface the HLC-newer winner"
16287        );
16288    }
16289
16290    #[test]
16291    fn learned_range_rebuild_indexes_only_hlc_visible_winners() {
16292        // The learned-range rebuild path (`build_learned_ranges_inner`) is
16293        // only exercised when the table has exactly one run; we therefore
16294        // exercise the more general `rebuild_indexes_from_runs` path, which
16295        // performs the global merge. After rebuild the projected column for
16296        // rid=7 must come from the HLC-newer run even though Run B was
16297        // iterated last.
16298        let dir = tempdir().unwrap();
16299        let db = build_inverted_database(dir.path(), pk_schema());
16300        let handle = db.table("t").unwrap();
16301        let mut table = handle.lock();
16302        table.rebuild_indexes_from_runs().expect("rebuild");
16303        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16304        let rows = table
16305            .rows_for_rids(&[7], snap)
16306            .expect("post-rebuild rows_for_rids");
16307        assert_eq!(rows.len(), 1);
16308        assert_eq!(
16309            rows[0].columns.get(&2),
16310            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16311            "post-rebuild row must be the HLC-newer winner"
16312        );
16313    }
16314
16315    #[test]
16316    fn rebuild_indexes_uses_global_hlc_winners_not_run_iteration_order() {
16317        // REM-001 §7.6: after `rebuild_indexes` the primary-key lookup and
16318        // the Bitmap index membership must both reflect the HLC-winning run,
16319        // not whichever run was iterated last.
16320        //
16321        // Close + reopen preservation of the HLC-newer winner is covered by
16322        // `sorted_run_hlc_visibility::reopen_from_disk_preserves_hlc_visibility`
16323        // (and by the merged `pk_equality_fallback` path through `Table::get`).
16324        // Re-running it on top of `rebuild_indexes` would require writing two
16325        // `Op::Put` records for the same rid across two WAL segments, which
16326        // trips the recovery-time duplicate-row-id guard — that guard is
16327        // orthogonal to REM-001 and would mask the actual fix we want to
16328        // exercise here.
16329        let dir = tempdir().unwrap();
16330        let db = build_inverted_database(dir.path(), pk_schema_with_bitmap());
16331        let handle = db.table("t").unwrap();
16332        let mut table = handle.lock();
16333        table.rebuild_indexes_from_runs().expect("rebuild");
16334        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16335        // 1. PK lookup resolves to the HLC winner.
16336        let row = table.get(RowId(7), snap).expect("post-rebuild Table::get");
16337        assert_eq!(
16338            row.columns.get(&2),
16339            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16340            "PK lookup must resolve to the HLC-newer winner"
16341        );
16342        // 2. Bitmap membership: name="newer-by-HLC" must contain rid=7
16343        //    and name="older-by-HLC" must NOT (the older version was
16344        //    suppressed by the global merge before indexing).
16345        let query_newer = Query::new().and(Condition::BitmapEq {
16346            column_id: 2,
16347            value: b"newer-by-HLC".to_vec(),
16348        });
16349        let rows_newer = table.query(&query_newer).expect("bitmap eq newer");
16350        let rids_newer: Vec<u64> = rows_newer.iter().map(|r| r.row_id.0).collect();
16351        assert!(
16352            rids_newer.contains(&7),
16353            "bitmap must include the HLC-newer value (got {rids_newer:?})"
16354        );
16355        let query_older = Query::new().and(Condition::BitmapEq {
16356            column_id: 2,
16357            value: b"older-by-HLC".to_vec(),
16358        });
16359        let rows_older = table.query(&query_older).expect("bitmap eq older");
16360        let rids_older: Vec<u64> = rows_older.iter().map(|r| r.row_id.0).collect();
16361        assert!(
16362            !rids_older.contains(&7),
16363            "bitmap must NOT include the HLC-older value (got {rids_older:?})"
16364        );
16365    }
16366
16367    #[test]
16368    fn version_stamp_is_newer_than_matches_snapshot_rule() {
16369        // Unit test for the new VersionStamp helper: HLC-newer wins despite
16370        // a smaller epoch; both-unstamped falls back to epoch.
16371        let early = hlc(100);
16372        let late = hlc(200);
16373        let newer = VersionStamp {
16374            epoch: Epoch(9),
16375            commit_ts: Some(late),
16376        };
16377        let older = VersionStamp {
16378            epoch: Epoch(50),
16379            commit_ts: Some(early),
16380        };
16381        assert!(newer.is_newer_than(older));
16382        assert!(!older.is_newer_than(newer));
16383        let a = VersionStamp {
16384            epoch: Epoch(5),
16385            commit_ts: None,
16386        };
16387        let b = VersionStamp {
16388            epoch: Epoch(4),
16389            commit_ts: None,
16390        };
16391        assert!(a.is_newer_than(b));
16392    }
16393}