Skip to main content

mongreldb_core/
engine.rs

1//! The engine tying the write and read paths together.
2//!
3//! Sub-ms writes: [`Table::put`] appends to the WAL **without fsyncing**, upserts
4//! the Bε-tree memtable, and updates the in-memory HOT index + secondary
5//! indexes. A batch-driven [`Table::commit`] does the group `fsync` and bumps the
6//! epoch. [`Table::flush`] commits, drains the memtable into an immutable sorted
7//! run, and rotates the WAL. Reads merge versions across the live memtable and
8//! all sorted runs ([`Table::get`], [`Table::visible_rows`]).
9
10use crate::columnar;
11use crate::cursor::NativePageCursor;
12use crate::encryption::Kek;
13use crate::encryption::DEK_LEN;
14use crate::epoch::{Epoch, EpochAuthority, EpochGuard, MaintenanceReceipt, Snapshot, VersionStamp};
15use crate::global_idx;
16use crate::index::{
17    AnnIndex, BitmapIndex, ColumnLearnedRange, FmIndex, HotIndex, IndexGeneration, MinHashIndex,
18    SparseIndex,
19};
20use crate::manifest::{self, Manifest, RunRef, TtlPolicy};
21use crate::memtable::{Memtable, MemtableVisibleVersionCursor, Row, Value};
22use crate::mutable_run::{MutableRun, MutableRunVisibleVersionCursor};
23use crate::result_cache::{
24    DrainOutcome, PersistContext, PersistenceDisabledReason, PersistentCacheIdentity,
25    PersistentPublicationState, FRAME_MAGIC,
26};
27use crate::row_id_set::RowIdSet;
28use crate::rowid::{RowId, RowIdAllocator};
29use crate::schema::{AlterColumn, ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
30use crate::sorted_run::{RunReader, RunVisibleVersion, RunVisibleVersionCursor, RunWriter};
31use crate::txn::{GroupCommit, OwnedRow};
32use crate::wal::{Op, SharedWal, Wal};
33use crate::{MongrelError, Result};
34use arc_swap::ArcSwap;
35use mongreldb_types::hlc::HlcTimestamp;
36use std::borrow::Cow;
37use std::cmp::Reverse;
38use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet};
39use std::path::{Path, PathBuf};
40use std::sync::atomic::AtomicBool;
41use std::sync::Arc;
42use std::time::Instant;
43use zeroize::Zeroizing;
44
45pub const WAL_DIR: &str = "_wal";
46pub const RUNS_DIR: &str = "_runs";
47pub const CACHE_DIR: &str = "_cache";
48pub const META_DIR: &str = "_meta";
49pub const RCACHE_DIR: &str = "_rcache";
50pub const KEYS_FILENAME: &str = "keys";
51pub const SCHEMA_FILENAME: &str = "schema.json";
52
53fn derive_next_run_id(
54    dir: &Path,
55    runs_root: Option<&crate::durable_file::DurableRoot>,
56    active: &[RunRef],
57    retiring: &[crate::manifest::RetiredRun],
58) -> Result<u64> {
59    let mut maximum = 0_u64;
60    for run_id in active
61        .iter()
62        .map(|run| run.run_id)
63        .chain(retiring.iter().map(|run| run.run_id))
64    {
65        let run_id = u64::try_from(run_id)
66            .map_err(|_| MongrelError::Full("run-id namespace exhausted".into()))?;
67        maximum = maximum.max(run_id);
68    }
69    let names = match runs_root {
70        Some(root) => root.list_regular_files(".")?,
71        None => std::fs::read_dir(dir.join(RUNS_DIR))?
72            .map(|entry| entry.map(|entry| entry.file_name()))
73            .collect::<std::io::Result<Vec<_>>>()?,
74    };
75    for name in names {
76        let Some(name) = name.to_str() else {
77            continue;
78        };
79        let Some(digits) = name
80            .strip_prefix("r-")
81            .and_then(|name| name.strip_suffix(".sr"))
82        else {
83            continue;
84        };
85        let Ok(run_id) = digits.parse::<u64>() else {
86            continue;
87        };
88        if name == format!("r-{run_id}.sr") {
89            maximum = maximum.max(run_id);
90        }
91    }
92    maximum
93        .checked_add(1)
94        .map(|next| next.max(1))
95        .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))
96}
97
98enum ControlledVisibleCandidate<'a> {
99    Memory(Row),
100    /// Newest-visible overlay row borrowed from the streaming memtable cursor.
101    /// The cursor yields `Cow<'a, Row>` (borrowed for leaf and buffered-upsert
102    /// rows, owned for buffer tombstones that have to be synthesized on the
103    /// fly); this carries the lifetime parameter so the borrowing variant
104    /// stays zero-copy.
105    Memtable(RowId, Epoch, Cow<'a, Row>),
106    /// Newest-visible overlay row borrowed from the streaming mutable-run cursor.
107    MutableRun(RowId, Epoch, &'a Row),
108    Run(RunVisibleVersion),
109}
110
111impl<'a> ControlledVisibleCandidate<'a> {
112    fn row_id(&self) -> RowId {
113        match self {
114            Self::Memory(row) => row.row_id,
115            Self::Memtable(rid, _, _) => *rid,
116            Self::MutableRun(rid, _, _) => *rid,
117            Self::Run(version) => version.row_id,
118        }
119    }
120
121    fn committed_epoch(&self) -> Epoch {
122        match self {
123            Self::Memory(row) => row.committed_epoch,
124            Self::Memtable(_, epoch, _) => *epoch,
125            Self::MutableRun(_, epoch, _) => *epoch,
126            Self::Run(version) => version.committed_epoch,
127        }
128    }
129
130    fn deleted(&self) -> bool {
131        match self {
132            Self::Memory(row) => row.deleted,
133            Self::Memtable(_, _, row) => row.deleted,
134            Self::MutableRun(_, _, row) => row.deleted,
135            Self::Run(version) => version.deleted,
136        }
137    }
138
139    fn commit_ts(&self) -> Option<mongreldb_types::hlc::HlcTimestamp> {
140        match self {
141            Self::Memory(row) => row.commit_ts,
142            Self::Memtable(_, _, row) => row.commit_ts,
143            Self::MutableRun(_, _, row) => row.commit_ts,
144            // Run candidates carry SYS_COMMIT_TS when the cursor loaded it;
145            // legacy runs without the column leave this None (epoch fallback).
146            Self::Run(version) => version.commit_ts,
147        }
148    }
149}
150
151enum ControlledVisibleCursor<'a> {
152    /// Newest-visible overlay rows, ordered by RowId (full source already small).
153    Memory(std::vec::IntoIter<Row>),
154    /// Batch-bounded overlay drain of a `BTreeMap` of newest-per-rid rows.
155    /// Only `batch_cap` rows live in the active merge buffer at once; the
156    /// remainder stays in the ordered map iterator (no full intermediate `Vec`).
157    MemoryStreaming {
158        active: std::vec::IntoIter<Row>,
159        rest: std::collections::btree_map::IntoValues<RowId, Row>,
160        batch_cap: usize,
161        /// Peak active-buffer length observed (for structural tests).
162        #[allow(dead_code)]
163        peak_active: usize,
164        /// Total rows that will be yielded (map size at construction).
165        #[allow(dead_code)]
166        total: usize,
167    },
168    /// Streaming cursor over the memtable's newest-visible versions. Yields
169    /// `(RowId, Epoch, &Row)` triples borrowing from the underlying memtable
170    /// storage — no per-row clone and no full materialisation.
171    Memtable(MemtableVisibleVersionCursor<'a>),
172    /// Streaming cursor over the mutable run's newest-visible versions.
173    MutableRun(MutableRunVisibleVersionCursor<'a>),
174    Run(Box<RunVisibleVersionCursor>),
175    #[cfg(test)]
176    Synthetic {
177        next: u64,
178        end: u64,
179    },
180}
181
182/// Default batch size for controlled hot-tier sources (memtable / mutable run).
183#[allow(dead_code)] // PR D follow-up: switch hot-tier path to the streaming cursor
184const CONTROLLED_HOT_BATCH: usize = 256;
185
186struct ControlledVisibleSource<'a> {
187    cursor: ControlledVisibleCursor<'a>,
188    current: Option<ControlledVisibleCandidate<'a>>,
189}
190
191impl<'a> ControlledVisibleSource<'a> {
192    /// Test/helper: wrap a pre-built row list (small fixtures only).
193    #[cfg(test)]
194    fn memory(rows: Vec<Row>) -> Self {
195        Self {
196            cursor: ControlledVisibleCursor::Memory(rows.into_iter()),
197            current: None,
198        }
199    }
200
201    /// Stream newest-visible hot-tier rows from an ordered map without first
202    /// collecting a full intermediate `Vec`. Only `CONTROLLED_HOT_BATCH` rows
203    /// occupy the active merge buffer at a time.
204    #[allow(dead_code)] // kept for the legacy map-based callers; new path uses the streaming cursor
205    fn memory_from_map(map: BTreeMap<RowId, Row>) -> Self {
206        let total = map.len();
207        let mut values = map.into_values();
208        if total > CONTROLLED_HOT_BATCH {
209            let active: Vec<Row> = values.by_ref().take(CONTROLLED_HOT_BATCH).collect();
210            let peak = active.len();
211            Self {
212                cursor: ControlledVisibleCursor::MemoryStreaming {
213                    active: active.into_iter(),
214                    rest: values,
215                    batch_cap: CONTROLLED_HOT_BATCH,
216                    peak_active: peak,
217                    total,
218                },
219                current: None,
220            }
221        } else {
222            let active: Vec<Row> = values.collect();
223            Self {
224                cursor: ControlledVisibleCursor::Memory(active.into_iter()),
225                current: None,
226            }
227        }
228    }
229
230    /// Wrap a streaming memtable cursor — preferred hot-tier path when the
231    /// memtable carries visible rows. Avoids the full `BTreeMap` materialisation
232    /// that the `memory_from_map` fallback performs.
233    #[allow(dead_code)] // wired in once the hot tier switches to streaming
234    fn memtable_cursor(cursor: MemtableVisibleVersionCursor<'a>) -> Self {
235        Self {
236            cursor: ControlledVisibleCursor::Memtable(cursor),
237            current: None,
238        }
239    }
240
241    /// Wrap a streaming mutable-run cursor — preferred hot-tier path when the
242    /// mutable run carries visible rows. Avoids the full `BTreeMap` clone that
243    /// the `memory_from_map` fallback performs.
244    #[allow(dead_code)] // wired in once the hot tier switches to streaming
245    fn mutable_run_cursor(cursor: MutableRunVisibleVersionCursor<'a>) -> Self {
246        Self {
247            cursor: ControlledVisibleCursor::MutableRun(cursor),
248            current: None,
249        }
250    }
251
252    fn run(cursor: RunVisibleVersionCursor) -> Self {
253        Self {
254            cursor: ControlledVisibleCursor::Run(Box::new(cursor)),
255            current: None,
256        }
257    }
258
259    #[cfg(test)]
260    fn synthetic(end: u64) -> Self {
261        Self {
262            cursor: ControlledVisibleCursor::Synthetic { next: 1, end },
263            current: None,
264        }
265    }
266
267    fn advance(&mut self, control: &crate::ExecutionControl) -> Result<()> {
268        self.current = match &mut self.cursor {
269            ControlledVisibleCursor::Memory(rows) => {
270                rows.next().map(ControlledVisibleCandidate::Memory)
271            }
272            ControlledVisibleCursor::MemoryStreaming {
273                active,
274                rest,
275                batch_cap,
276                peak_active,
277                total: _,
278            } => {
279                if let Some(row) = active.next() {
280                    Some(ControlledVisibleCandidate::Memory(row))
281                } else {
282                    control.checkpoint()?;
283                    let next_batch: Vec<Row> = rest.by_ref().take(*batch_cap).collect();
284                    if next_batch.is_empty() {
285                        None
286                    } else {
287                        *peak_active = (*peak_active).max(next_batch.len());
288                        *active = next_batch.into_iter();
289                        active.next().map(ControlledVisibleCandidate::Memory)
290                    }
291                }
292            }
293            ControlledVisibleCursor::Memtable(iter) => {
294                let prev_peak = iter.peak_examined;
295                // REM-C: the memtable cursor (and the lazy Bε-tree cursors
296                // beneath it) observe cooperative cancellation during
297                // traversal and large same-row gathers.
298                let next = iter
299                    .next_controlled(control)?
300                    .map(|(rid, epoch, row)| ControlledVisibleCandidate::Memtable(rid, epoch, row));
301                if let Some(peak) = iter.peak_examined.checked_sub(prev_peak) {
302                    crate::trace::QueryTrace::record(|t| {
303                        t.controlled_scan_peak_same_row_versions = t
304                            .controlled_scan_peak_same_row_versions
305                            .saturating_add(peak);
306                    });
307                }
308                next
309            }
310            ControlledVisibleCursor::MutableRun(iter) => {
311                let prev_peak = iter.peak_examined;
312                let next = iter.next().map(|(rid, epoch, row)| {
313                    ControlledVisibleCandidate::MutableRun(rid, epoch, row)
314                });
315                if let Some(peak) = iter.peak_examined.checked_sub(prev_peak) {
316                    crate::trace::QueryTrace::record(|t| {
317                        t.controlled_scan_peak_same_row_versions = t
318                            .controlled_scan_peak_same_row_versions
319                            .saturating_add(peak);
320                    });
321                }
322                next
323            }
324            ControlledVisibleCursor::Run(cursor) => cursor
325                .next_visible_version(control)?
326                .map(ControlledVisibleCandidate::Run),
327            #[cfg(test)]
328            ControlledVisibleCursor::Synthetic { next, end } => {
329                if *next > *end {
330                    None
331                } else {
332                    let row = Row::new(RowId(*next), Epoch(1));
333                    *next += 1;
334                    Some(ControlledVisibleCandidate::Memory(row))
335                }
336            }
337        };
338        Ok(())
339    }
340
341    fn pop(&mut self, control: &crate::ExecutionControl) -> Result<ControlledVisibleCandidate<'a>> {
342        let current = self.current.take().ok_or_else(|| {
343            MongrelError::Other("controlled visible source was not primed".into())
344        })?;
345        self.advance(control)?;
346        Ok(current)
347    }
348
349    fn materialize(
350        &mut self,
351        candidate: ControlledVisibleCandidate<'a>,
352        control: &crate::ExecutionControl,
353    ) -> Result<Row> {
354        match candidate {
355            ControlledVisibleCandidate::Memory(row) => Ok(row),
356            ControlledVisibleCandidate::Memtable(_, _, row) => Ok(row.into_owned()),
357            ControlledVisibleCandidate::MutableRun(_, _, row) => Ok(row.clone()),
358            ControlledVisibleCandidate::Run(version) => match &mut self.cursor {
359                ControlledVisibleCursor::Run(cursor) => cursor.materialize(version, control),
360                _ => Err(MongrelError::Other(
361                    "run candidate escaped its controlled cursor".into(),
362                )),
363            },
364        }
365    }
366
367    #[cfg(test)]
368    fn is_streaming_memory(&self) -> bool {
369        matches!(self.cursor, ControlledVisibleCursor::MemoryStreaming { .. })
370    }
371
372    #[cfg(test)]
373    fn streaming_peak_active(&self) -> Option<usize> {
374        match &self.cursor {
375            ControlledVisibleCursor::MemoryStreaming { peak_active, .. } => Some(*peak_active),
376            _ => None,
377        }
378    }
379
380    #[cfg(test)]
381    fn streaming_total(&self) -> Option<usize> {
382        match &self.cursor {
383            ControlledVisibleCursor::MemoryStreaming { total, .. } => Some(*total),
384            _ => None,
385        }
386    }
387}
388
389fn merge_controlled_visible_sources<'a>(
390    sources: &mut [ControlledVisibleSource<'a>],
391    control: &crate::ExecutionControl,
392    mut expired: impl FnMut(&Row) -> bool,
393    mut visit: impl FnMut(Row) -> Result<()>,
394) -> Result<()> {
395    let mut heap = BinaryHeap::new();
396    for (source_index, source) in sources.iter_mut().enumerate() {
397        source.advance(control)?;
398        if let Some(candidate) = &source.current {
399            heap.push(Reverse((candidate.row_id(), source_index)));
400        }
401    }
402    let mut merged = 0_usize;
403    let mut peak_buffer_rows: usize = heap.len();
404    let mut peak_same_row_versions: usize = 0;
405    let mut cancel_started: Option<std::time::Instant> = None;
406    while let Some(Reverse((row_id, source_index))) = heap.pop() {
407        if merged.is_multiple_of(256) {
408            control.checkpoint()?;
409        }
410        merged += 1;
411        let mut best_source = source_index;
412        let mut best = sources[source_index].pop(control)?;
413        if let Some(next) = &sources[source_index].current {
414            heap.push(Reverse((next.row_id(), source_index)));
415        }
416        let mut same_row_versions: usize = 1;
417        while heap
418            .peek()
419            .is_some_and(|Reverse((candidate, _))| *candidate == row_id)
420        {
421            control.checkpoint()?;
422            let Some(Reverse((_, source_index))) = heap.pop() else {
423                break;
424            };
425            let candidate = sources[source_index].pop(control)?;
426            same_row_versions += 1;
427            // HLC-authoritative: when both candidates carry HLC, the higher
428            // HLC wins regardless of local epoch. Falls back to epoch when
429            // either side lacks HLC (legacy / sorted-run path).
430            if Snapshot::version_is_newer(
431                candidate.committed_epoch(),
432                candidate.commit_ts(),
433                best.committed_epoch(),
434                best.commit_ts(),
435            ) {
436                best = candidate;
437                best_source = source_index;
438            }
439            if let Some(next) = &sources[source_index].current {
440                heap.push(Reverse((next.row_id(), source_index)));
441            }
442        }
443        peak_same_row_versions = peak_same_row_versions.max(same_row_versions);
444        peak_buffer_rows = peak_buffer_rows.max(heap.len());
445        if best.deleted() {
446            continue;
447        }
448        let row = sources[best_source].materialize(best, control)?;
449        if !expired(&row) {
450            visit(row)?;
451        }
452        if cancel_started.is_none() && control.is_cancelled() {
453            cancel_started = Some(std::time::Instant::now());
454        }
455    }
456    crate::trace::QueryTrace::record(|t| {
457        t.controlled_scan_source_refills = t.controlled_scan_source_refills.saturating_add(0); // source refills are counted by each cursor's own advance()
458        t.controlled_scan_peak_source_buffer_rows = t
459            .controlled_scan_peak_source_buffer_rows
460            .saturating_add(peak_buffer_rows);
461        t.controlled_scan_peak_same_row_versions = t
462            .controlled_scan_peak_same_row_versions
463            .saturating_add(peak_same_row_versions);
464    });
465    control.checkpoint()?;
466    Ok(())
467}
468
469#[cfg(test)]
470mod controlled_visible_cursor_tests {
471    use super::*;
472
473    #[test]
474    fn streams_more_than_one_million_rows_without_a_source_cap() {
475        let control = crate::ExecutionControl::new(None);
476        let mut sources = vec![ControlledVisibleSource::synthetic(1_000_001)];
477        let mut count = 0_u64;
478        let mut last = 0_u64;
479        merge_controlled_visible_sources(
480            &mut sources,
481            &control,
482            |_| false,
483            |row| {
484                count += 1;
485                assert!(row.row_id.0 > last);
486                last = row.row_id.0;
487                Ok(())
488            },
489        )
490        .unwrap();
491        assert_eq!(count, 1_000_001);
492        assert_eq!(last, 1_000_001);
493    }
494
495    #[test]
496    fn merge_orders_rows_and_honors_newest_tombstones() {
497        let control = crate::ExecutionControl::new(None);
498        let older = vec![
499            Row::new(RowId(1), Epoch(1)),
500            Row::new(RowId(2), Epoch(1)).with_column(1, Value::Int64(20)),
501            Row::new(RowId(4), Epoch(1)),
502        ];
503        let mut deleted = Row::new(RowId(1), Epoch(2));
504        deleted.deleted = true;
505        let newer = vec![
506            deleted,
507            Row::new(RowId(2), Epoch(2)).with_column(1, Value::Int64(22)),
508            Row::new(RowId(3), Epoch(2)),
509        ];
510        let mut sources = vec![
511            ControlledVisibleSource::memory(older),
512            ControlledVisibleSource::memory(newer),
513        ];
514        let mut rows = Vec::new();
515        merge_controlled_visible_sources(
516            &mut sources,
517            &control,
518            |_| false,
519            |row| {
520                rows.push(row);
521                Ok(())
522            },
523        )
524        .unwrap();
525        assert_eq!(
526            rows.iter().map(|row| row.row_id.0).collect::<Vec<_>>(),
527            vec![2, 3, 4]
528        );
529        assert_eq!(rows[0].columns.get(&1), Some(&Value::Int64(22)));
530    }
531
532    #[test]
533    fn controlled_merge_uses_hlc_authority_when_epochs_inverted() {
534        use mongreldb_types::hlc::HlcTimestamp;
535        let hlc_old = HlcTimestamp {
536            physical_micros: 100,
537            logical: 0,
538            node_tiebreaker: 1,
539        };
540        let hlc_new = HlcTimestamp {
541            physical_micros: 200,
542            logical: 0,
543            node_tiebreaker: 1,
544        };
545        // Source A: high epoch, OLD HLC. Source B: low epoch, NEW HLC.
546        // HLC authority should pick B; legacy epoch-only pick would pick A.
547        let a =
548            vec![Row::new_with_hlc(RowId(1), Epoch(50), hlc_old).with_column(1, Value::Int64(999))];
549        let b =
550            vec![Row::new_with_hlc(RowId(1), Epoch(1), hlc_new).with_column(1, Value::Int64(11))];
551        let control = crate::ExecutionControl::new(None);
552        let mut sources = vec![
553            ControlledVisibleSource::memory(a),
554            ControlledVisibleSource::memory(b),
555        ];
556        let mut rows = Vec::new();
557        merge_controlled_visible_sources(
558            &mut sources,
559            &control,
560            |_| false,
561            |row| {
562                rows.push(row);
563                Ok(())
564            },
565        )
566        .unwrap();
567        assert_eq!(rows.len(), 1);
568        assert_eq!(rows[0].row_id.0, 1);
569        // HLC-newer (source B, value 11) must win despite Epoch(50) on source A.
570        assert_eq!(rows[0].columns.get(&1), Some(&Value::Int64(11)));
571        assert_eq!(rows[0].commit_ts, Some(hlc_new));
572    }
573
574    #[test]
575    fn controlled_merge_epoch_wins_when_one_side_lacks_hlc() {
576        use mongreldb_types::hlc::HlcTimestamp;
577        let hlc_old = HlcTimestamp {
578            physical_micros: 100,
579            logical: 0,
580            node_tiebreaker: 1,
581        };
582        // Source A: HLC-stamped, higher epoch. Source B: no HLC, lower epoch.
583        // Legacy path: epoch wins -> A is newer.
584        let a =
585            vec![Row::new_with_hlc(RowId(1), Epoch(10), hlc_old).with_column(1, Value::Int64(10))];
586        let b = vec![Row::new(RowId(1), Epoch(5)).with_column(1, Value::Int64(5))];
587        let control = crate::ExecutionControl::new(None);
588        let mut sources = vec![
589            ControlledVisibleSource::memory(a),
590            ControlledVisibleSource::memory(b),
591        ];
592        let mut rows = Vec::new();
593        merge_controlled_visible_sources(
594            &mut sources,
595            &control,
596            |_| false,
597            |row| {
598                rows.push(row);
599                Ok(())
600            },
601        )
602        .unwrap();
603        assert_eq!(rows.len(), 1);
604        assert_eq!(rows[0].columns.get(&1), Some(&Value::Int64(10)));
605    }
606
607    /// Memory (low epoch, high HLC) vs Run (high epoch, low HLC) must pick the
608    /// HLC-newer memory version when the run candidate carries SYS_COMMIT_TS.
609    #[test]
610    fn controlled_merge_memory_vs_run_uses_hlc_when_run_stamped() {
611        use crate::sorted_run::{RunReader, RunWriter};
612        use mongreldb_types::hlc::HlcTimestamp;
613        use tempfile::tempdir;
614
615        let hlc_old = HlcTimestamp {
616            physical_micros: 100,
617            logical: 0,
618            node_tiebreaker: 1,
619        };
620        let hlc_new = HlcTimestamp {
621            physical_micros: 200,
622            logical: 0,
623            node_tiebreaker: 1,
624        };
625        let schema = Schema {
626            schema_id: 1,
627            columns: vec![ColumnDef {
628                id: 1,
629                name: "v".into(),
630                ty: TypeId::Int64,
631                flags: ColumnFlags::empty(),
632                default_value: None,
633                embedding_source: None,
634            }],
635            indexes: vec![],
636            colocation: vec![],
637            constraints: Default::default(),
638            clustered: false,
639        };
640        let dir = tempdir().unwrap();
641        let path = dir.path().join("r-hlc.sr");
642        // High epoch, OLD HLC on disk.
643        let run_rows =
644            vec![Row::new_with_hlc(RowId(1), Epoch(50), hlc_old).with_column(1, Value::Int64(999))];
645        RunWriter::new(&schema, 1, Epoch(50), 0)
646            .write(&path, &run_rows)
647            .unwrap();
648        let reader = RunReader::open(&path, schema, None).unwrap();
649        assert!(reader.has_column(crate::sorted_run::SYS_COMMIT_TS));
650
651        // Low epoch, NEW HLC in memory.
652        let mem =
653            vec![Row::new_with_hlc(RowId(1), Epoch(1), hlc_new).with_column(1, Value::Int64(11))];
654        let control = crate::ExecutionControl::new(None);
655        let mut sources = vec![
656            ControlledVisibleSource::memory(mem),
657            ControlledVisibleSource::run(
658                reader.into_visible_version_cursor(Epoch(u64::MAX)).unwrap(),
659            ),
660        ];
661        let mut rows = Vec::new();
662        merge_controlled_visible_sources(
663            &mut sources,
664            &control,
665            |_| false,
666            |row| {
667                rows.push(row);
668                Ok(())
669            },
670        )
671        .unwrap();
672        assert_eq!(rows.len(), 1);
673        assert_eq!(
674            rows[0].columns.get(&1),
675            Some(&Value::Int64(11)),
676            "HLC-newer memory version must beat epoch-newer run"
677        );
678        assert_eq!(rows[0].commit_ts, Some(hlc_new));
679    }
680
681    #[test]
682    fn controlled_memory_source_streams_large_overlays_without_full_active_vec() {
683        let mut map = BTreeMap::new();
684        for i in 1..=500u64 {
685            map.insert(
686                RowId(i),
687                Row::new(RowId(i), Epoch(1)).with_column(1, Value::Int64(i as i64)),
688            );
689        }
690        let source = ControlledVisibleSource::memory_from_map(map);
691        assert!(
692            source.is_streaming_memory(),
693            "overlays larger than CONTROLLED_HOT_BATCH must use streaming cursor"
694        );
695        assert_eq!(source.streaming_total(), Some(500));
696        // Active buffer is capped — never holds the full 500-row set at once.
697        assert!(
698            source.streaming_peak_active().unwrap_or(usize::MAX) <= CONTROLLED_HOT_BATCH,
699            "peak active buffer must be <= CONTROLLED_HOT_BATCH"
700        );
701
702        // Drain fully and re-check peak never exceeds the batch cap.
703        let control = crate::ExecutionControl::new(None);
704        let mut sources = vec![ControlledVisibleSource::memory_from_map({
705            let mut m = BTreeMap::new();
706            for i in 1..=500u64 {
707                m.insert(
708                    RowId(i),
709                    Row::new(RowId(i), Epoch(1)).with_column(1, Value::Int64(i as i64)),
710                );
711            }
712            m
713        })];
714        let mut n = 0usize;
715        merge_controlled_visible_sources(
716            &mut sources,
717            &control,
718            |_| false,
719            |_| {
720                n += 1;
721                Ok(())
722            },
723        )
724        .unwrap();
725        assert_eq!(n, 500);
726        assert!(
727            sources[0].streaming_peak_active().unwrap_or(0) <= CONTROLLED_HOT_BATCH,
728            "after full drain peak active still <= batch cap"
729        );
730    }
731}
732
733/// Current UTC time as an ISO-8601 string in bytes (e.g. `b"2024-07-07T14:30:00Z"`).
734/// Used by `DefaultExpr::Now` at stage time.
735fn iso_now_bytes() -> Vec<u8> {
736    let secs = std::time::SystemTime::now()
737        .duration_since(std::time::UNIX_EPOCH)
738        .map(|d| d.as_secs() as i64)
739        .unwrap_or(0);
740    let days = secs.div_euclid(86_400);
741    let rem = secs.rem_euclid(86_400);
742    let (hour, minute, second) = (rem / 3600, (rem % 3600) / 60, rem % 60);
743    let (year, month, day) = civil_from_days(days);
744    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z").into_bytes()
745}
746
747pub(crate) fn unix_nanos_now() -> i64 {
748    std::time::SystemTime::now()
749        .duration_since(std::time::UNIX_EPOCH)
750        .map(|d| d.as_nanos().min(i64::MAX as u128) as i64)
751        .unwrap_or(0)
752}
753
754fn ann_candidate_cap(
755    index_len: usize,
756    context: Option<&crate::query::AiExecutionContext>,
757) -> usize {
758    index_len
759        .min(crate::query::MAX_RAW_INDEX_CANDIDATES)
760        .min(context.map_or(
761            crate::query::MAX_RAW_INDEX_CANDIDATES,
762            crate::query::AiExecutionContext::max_fused_candidates,
763        ))
764}
765
766#[cfg(test)]
767mod ann_candidate_cap_tests {
768    use super::*;
769
770    #[test]
771    fn raw_and_request_candidate_ceilings_are_both_hard_bounds() {
772        assert_eq!(
773            ann_candidate_cap(crate::query::MAX_RAW_INDEX_CANDIDATES + 1, None),
774            crate::query::MAX_RAW_INDEX_CANDIDATES,
775        );
776        let context = crate::query::AiExecutionContext::with_limits(
777            std::time::Duration::from_secs(1),
778            usize::MAX,
779            17,
780        );
781        assert_eq!(ann_candidate_cap(1_000_000, Some(&context)), 17);
782    }
783}
784
785fn civil_from_days(z: i64) -> (i64, u32, u32) {
786    let z = z + 719_468;
787    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
788    let doe = z - era * 146_097;
789    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
790    let y = yoe + era * 400;
791    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
792    let mp = (5 * doy + 2) / 153;
793    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
794    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
795    (if m <= 2 { y + 1 } else { y }, m, d)
796}
797
798/// Derives the stable physical row id used by clustered (`WITHOUT ROWID`)
799/// tables from the encoded primary-key value.
800///
801/// Replicated tablet bootstrap uses this helper when it constructs the same
802/// logical row on every replica without going through the user transaction
803/// staging path.
804pub fn clustered_row_id(primary_key: &Value) -> RowId {
805    let mut hash: u64 = 0xcbf29ce484222325;
806    for byte in primary_key.encode_key() {
807        hash ^= u64::from(byte);
808        hash = hash.wrapping_mul(0x100000001b3);
809    }
810    RowId(hash.max(1))
811}
812
813const DEFAULT_SYNC_BYTE_THRESHOLD: u64 = 0; // manual commit only (pure group commit)
814pub(crate) const PAGE_CACHE_CAPACITY: u64 = 64 * 1024 * 1024; // 64 MiB shared page cache
815pub(crate) const DECODED_CACHE_CAPACITY: u64 = 64 * 1024 * 1024; // 64 MiB shared decoded-page cache (Phase 15.4)
816/// Default byte watermark at which the PMA mutable-run tier spills to an
817/// immutable `.sr` sorted run (Phase 11.1). Coalesces many small flushes into
818/// one larger run so the read path merges fewer readers.
819const DEFAULT_MUTABLE_RUN_SPILL_BYTES: u64 = 8 * 1024 * 1024;
820
821/// Engine-managed `AUTO_INCREMENT` counter state for a table (present iff the
822/// schema declares an `AUTO_INCREMENT` primary key).
823///
824/// `next` is the next value to hand out (1-based, monotonic, never reused). It
825/// is `0` while *unseeded* — the counter has never been advanced (fresh table or
826/// a legacy manifest predating `auto_inc_next`). When `seeded` is `false` the
827/// first allocation scans `max(PK)` over all visible rows so the counter never
828/// collides with pre-existing rows; a value of `0` after seeding never happens
829/// (ids are never 0). The manifest persists `next` only when `seeded`, so a
830/// reopen that reads `auto_inc_next > 0` is authoritative.
831///
832/// `seeded == false` but `next > 0` is a transient recovery-only state: WAL
833/// replay may bump `next` past replayed ids without marking it seeded, so the
834/// scan still runs to cover rows that were already flushed to sorted runs.
835#[derive(Clone, Copy, Debug)]
836struct AutoIncState {
837    column_id: u16,
838    next: i64,
839    seeded: bool,
840}
841
842pub(crate) struct RecoveryMetadataPlan {
843    live_count: u64,
844    auto_inc: Option<AutoIncState>,
845    changed: bool,
846}
847
848type FilledAutoIncRow = (Vec<(u16, Value)>, Option<i64>);
849
850/// Resolve the auto-increment column (if any) from a schema into initial
851/// counter state. Always called after [`crate::schema::Schema::validate_auto_increment`].
852fn resolve_auto_inc(schema: &Schema) -> Option<AutoIncState> {
853    schema.auto_increment_column().map(|c| AutoIncState {
854        column_id: c.id,
855        next: 0,
856        seeded: false,
857    })
858}
859
860/// When a bulk load (`bulk_load` / `bulk_load_columns` / `bulk_load_fast`)
861/// builds the live in-memory indexes.
862///
863/// The engine is correct under either policy: with [`Self::Deferred`] the
864/// indexes are rebuilt lazily by the first `query`/`flush` (Phase 14.7,
865/// `ensure_indexes_complete`), with [`Self::Eager`] they are built — and
866/// checkpointed to `_idx/global.idx` — inside the bulk load itself. The trade
867/// is *where* the build cost lands: `Deferred` keeps the ingest critical path
868/// minimal (write the run, persist the manifest, return); `Eager` gives
869/// predictable first-query latency at the price of a slower load. Serving
870/// deployments that load then immediately serve point queries (e.g. a warm
871/// daemon) may prefer `Eager`; batch/ETL ingest wants `Deferred`.
872#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
873pub enum IndexBuildPolicy {
874    /// Defer index building to the first query/flush — fastest ingest (default).
875    #[default]
876    Deferred,
877    /// Build and checkpoint indexes inside the bulk load — fastest first query.
878    Eager,
879}
880
881#[derive(Clone)]
882struct ReversePkSegment {
883    values: HashMap<RowId, Vec<u8>>,
884    removed: HashSet<RowId>,
885}
886
887#[derive(Clone)]
888struct ReversePkMap {
889    frozen: Arc<Vec<Arc<ReversePkSegment>>>,
890    active: ReversePkSegment,
891}
892
893impl ReversePkMap {
894    fn new() -> Self {
895        Self {
896            frozen: Arc::new(Vec::new()),
897            active: ReversePkSegment {
898                values: HashMap::new(),
899                removed: HashSet::new(),
900            },
901        }
902    }
903
904    fn from_entries(entries: impl IntoIterator<Item = (RowId, Vec<u8>)>) -> Self {
905        let mut map = Self::new();
906        map.active.values.extend(entries);
907        map
908    }
909
910    fn insert(&mut self, row_id: RowId, key: Vec<u8>) {
911        self.active.removed.remove(&row_id);
912        self.active.values.insert(row_id, key);
913    }
914
915    fn get(&self, row_id: &RowId) -> Option<&Vec<u8>> {
916        if let Some(key) = self.active.values.get(row_id) {
917            return Some(key);
918        }
919        if self.active.removed.contains(row_id) {
920            return None;
921        }
922        for segment in self.frozen.iter().rev() {
923            if let Some(key) = segment.values.get(row_id) {
924                return Some(key);
925            }
926            if segment.removed.contains(row_id) {
927                return None;
928            }
929        }
930        None
931    }
932
933    fn remove(&mut self, row_id: &RowId) -> Option<Vec<u8>> {
934        let previous = self.get(row_id).cloned();
935        self.active.values.remove(row_id);
936        self.active.removed.insert(*row_id);
937        previous
938    }
939
940    fn clear(&mut self) {
941        *self = Self::new();
942    }
943
944    fn entries(&self) -> HashMap<RowId, Vec<u8>> {
945        let mut entries = HashMap::new();
946        for segment in self
947            .frozen
948            .iter()
949            .map(Arc::as_ref)
950            .chain(std::iter::once(&self.active))
951        {
952            for row_id in &segment.removed {
953                entries.remove(row_id);
954            }
955            entries.extend(
956                segment
957                    .values
958                    .iter()
959                    .map(|(row_id, key)| (*row_id, key.clone())),
960            );
961        }
962        entries
963    }
964
965    fn seal(&mut self) {
966        if self.active.values.is_empty() && self.active.removed.is_empty() {
967            return;
968        }
969        let active = std::mem::replace(
970            &mut self.active,
971            ReversePkSegment {
972                values: HashMap::new(),
973                removed: HashSet::new(),
974            },
975        );
976        Arc::make_mut(&mut self.frozen).push(Arc::new(active));
977        if self.frozen.len() >= crate::MAX_READ_GENERATION_LAYERS {
978            self.frozen = Arc::new(vec![Arc::new(ReversePkSegment {
979                values: self.entries(),
980                removed: HashSet::new(),
981            })]);
982        }
983    }
984}
985
986/// S1C-001: an immutable, atomically-published table read view — the
987/// engine-layer counterpart of `database::TableReadGeneration`. Readers pin
988/// an `Arc<ReadGeneration>`; writers publish a replacement with a single
989/// `ArcSwap` store ([`Table::publish_read_generation`]) after sealing their
990/// active deltas, so no write ever clones the complete table/index set
991/// merely because readers exist: every captured piece is either an `Arc`
992/// share of immutable frozen layers or a small metadata copy.
993///
994/// `visible_through` is the engine's commit-epoch watermark (the spec's
995/// `HlcTimestamp` maps onto it at the commit-log layer): the view reflects
996/// every commit whose epoch is `<= visible_through`, and later writes are
997/// invisible through it even though they mutate the publishing [`Table`].
998#[derive(Clone)]
999pub struct ReadGeneration {
1000    schema: Arc<Schema>,
1001    base_runs: Arc<Vec<RunRef>>,
1002    deltas: TableDeltas,
1003    indexes: Arc<IndexGeneration>,
1004    visible_through: Epoch,
1005}
1006
1007/// One fully-built secondary index staged outside the publication barrier.
1008/// The variant carries only the target index. Unrelated live indexes remain
1009/// structurally shared when this artifact is installed.
1010pub(crate) enum SecondaryIndexArtifact {
1011    Bitmap(u16, BitmapIndex),
1012    LearnedRange(u16, ColumnLearnedRange),
1013    Fm(u16, Box<FmIndex>),
1014    Ann(u16, Box<AnnIndex>),
1015    Sparse(u16, SparseIndex),
1016    MinHash(u16, MinHashIndex),
1017}
1018
1019/// The sealed in-memory deltas captured with a [`ReadGeneration`]: memtable,
1020/// mutable-run tier, HOT primary-key index, and the reverse primary-key map.
1021/// Each is a post-seal clone — frozen layers are `Arc`-shared with the
1022/// writer, the active delta is empty — so capturing copies no row data, and
1023/// pinning the view keeps exactly the frozen layers it captured alive.
1024#[derive(Clone)]
1025pub struct TableDeltas {
1026    memtable: Memtable,
1027    mutable_run: MutableRun,
1028    hot: HotIndex,
1029    pk_by_row: ReversePkMap,
1030}
1031
1032impl ReadGeneration {
1033    /// An empty view over `schema`, used to seed the published cell before
1034    /// the first [`Table::publish_read_generation`].
1035    fn empty(schema: &Schema) -> Self {
1036        Self {
1037            schema: Arc::new(schema.clone()),
1038            base_runs: Arc::new(Vec::new()),
1039            deltas: TableDeltas {
1040                memtable: Memtable::new(),
1041                mutable_run: MutableRun::new(),
1042                hot: HotIndex::new(),
1043                pk_by_row: ReversePkMap::new(),
1044            },
1045            indexes: Arc::new(IndexGeneration::default()),
1046            visible_through: Epoch(0),
1047        }
1048    }
1049
1050    /// Table schema as of this generation.
1051    pub fn schema(&self) -> &Arc<Schema> {
1052        &self.schema
1053    }
1054
1055    /// Immutable base sorted runs (`r-*.sr`) visible in this generation.
1056    pub fn base_runs(&self) -> &[RunRef] {
1057        &self.base_runs
1058    }
1059
1060    /// The published index generation (all six families).
1061    pub fn indexes(&self) -> &Arc<IndexGeneration> {
1062        &self.indexes
1063    }
1064
1065    /// Highest commit epoch reflected in this view.
1066    pub fn visible_through(&self) -> Epoch {
1067        self.visible_through
1068    }
1069
1070    /// The sealed in-memory deltas captured with this view. The view owns an
1071    /// `Arc` share of every frozen layer, so the layers stay alive (and
1072    /// unchanged) for as long as the view is pinned.
1073    pub fn deltas(&self) -> &TableDeltas {
1074        &self.deltas
1075    }
1076}
1077
1078impl TableDeltas {
1079    /// Approximate heap bytes held by the captured memtable and mutable-run
1080    /// frozen deltas (diagnostics).
1081    pub fn approx_bytes(&self) -> u64 {
1082        self.memtable
1083            .approx_bytes()
1084            .saturating_add(self.mutable_run.approx_bytes())
1085    }
1086
1087    /// Row versions held in the captured memtable layers.
1088    pub fn memtable_len(&self) -> usize {
1089        self.memtable.len()
1090    }
1091
1092    /// Row versions held in the captured mutable-run layers.
1093    pub fn mutable_run_len(&self) -> usize {
1094        self.mutable_run.len()
1095    }
1096
1097    /// Primary-key entries held in the captured HOT index layers.
1098    pub fn hot_len(&self) -> usize {
1099        self.hot.len()
1100    }
1101
1102    /// Reverse primary-key entries captured for HOT cleanup on deletes.
1103    pub fn reverse_pk_len(&self) -> usize {
1104        self.pk_by_row.entries().len()
1105    }
1106}
1107
1108/// An open MongrelDB table.
1109#[derive(Clone)]
1110pub struct Table {
1111    dir: PathBuf,
1112    _root_guard: Option<Arc<crate::durable_file::DurableRoot>>,
1113    runs_root: Option<Arc<crate::durable_file::DurableRoot>>,
1114    idx_root: Option<Arc<crate::durable_file::DurableRoot>>,
1115    table_id: u64,
1116    /// The table's catalog name, set at mount time. Used by the auth
1117    /// enforcement layer to check `Select`/`Insert`/`Update`/`Delete`
1118    /// permissions against this specific table.
1119    name: String,
1120    /// Optional auth checker for per-operation enforcement. `None` on
1121    /// credentialless databases (the default); `Some` when the database has
1122    /// `require_auth = true`. The checker is shared (via `Arc`) so it sees
1123    /// live updates to the principal and the `require_auth` flag.
1124    auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
1125    /// Logical writes are forbidden when this table belongs to a replication
1126    /// follower. Replication itself appends through the database WAL API.
1127    read_only: bool,
1128    /// A WAL commit reached durable storage but its live publication failed.
1129    /// Reads may continue for diagnostics, but writes require a clean reopen so
1130    /// recovery can rebuild one coherent runtime state from the durable WAL.
1131    durable_commit_failed: bool,
1132    wal: WalSink,
1133    memtable: Memtable,
1134    /// PMA-backed mutable-run LSM tier (Phase 11.1). A flush drains the
1135    /// memtable into this in-memory sorted tier instead of immediately writing
1136    /// a `.sr` run; once it crosses `mutable_run_spill_bytes` it spills to an
1137    /// immutable run. Purely in-memory — rebuilt from WAL replay on reopen.
1138    mutable_run: MutableRun,
1139    /// Byte watermark controlling when `mutable_run` spills to a sorted run.
1140    mutable_run_spill_bytes: u64,
1141    /// Zstd compression level for compaction output (Phase 18.1: default 3;
1142    /// higher = better ratio but slower compaction).
1143    compaction_zstd_level: i32,
1144    allocator: RowIdAllocator,
1145    epoch: Arc<EpochAuthority>,
1146    /// Table-local content generation used by authorization caches. Unlike the
1147    /// shared MVCC epoch, unrelated table commits do not change this value.
1148    data_generation: u64,
1149    schema: Schema,
1150    hot: HotIndex,
1151    /// Table Key-Encryption Key (Argon2id+HKDF from the passphrase). Each run
1152    /// stores a fresh DEK wrapped by this KEK (see §7). `None` when plaintext.
1153    kek: Option<Arc<Kek>>,
1154    /// Per-column indexable-encryption keys + scheme (Phase 10.2) for every
1155    /// ENCRYPTED_INDEXABLE column, derived deterministically from the KEK so
1156    /// tokens are identical across runs. Empty when the table is plaintext.
1157    column_keys: HashMap<u16, ([u8; 32], u8)>,
1158    run_refs: Vec<RunRef>,
1159    /// Runs superseded by compaction, kept on disk for snapshot retention until
1160    /// `gc()` reaps them (spec §6.4). Persisted in the manifest (`retiring`).
1161    retiring: Vec<crate::manifest::RetiredRun>,
1162    next_run_id: u64,
1163    sync_byte_threshold: u64,
1164    /// Next transaction id to assign to a single-table auto-commit txn
1165    /// (`put`/`delete` then `commit`). 0 is reserved for [`wal::SYSTEM_TXN_ID`].
1166    /// The Database transaction layer (P2.5) assigns these globally; the
1167    /// single-table path uses this local counter.
1168    current_txn_id: u64,
1169    /// True after a standalone table appends a private-WAL mutation and until
1170    /// `commit_private` has durably sealed and published that transaction.
1171    /// Mounted tables use `pending_rows` / `pending_dels` instead.
1172    pending_private_mutations: bool,
1173    bitmap: HashMap<u16, BitmapIndex>,
1174    ann: HashMap<u16, AnnIndex>,
1175    fm: HashMap<u16, FmIndex>,
1176    sparse: HashMap<u16, SparseIndex>,
1177    minhash: HashMap<u16, MinHashIndex>,
1178    /// Per-column learned (PGM) range indexes for `IndexKind::LearnedRange`
1179    /// columns, built from the single sorted run.
1180    learned_range: Arc<HashMap<u16, ColumnLearnedRange>>,
1181    /// Reverse primary-key map for HOT cleanup on row-id deletes.
1182    pk_by_row: ReversePkMap,
1183    /// Refcounted pinned read snapshots (epoch → count); compaction must not GC
1184    /// versions an active snapshot still needs.
1185    pinned: BTreeMap<Epoch, usize>,
1186    /// Live (non-deleted) row count — maintained incrementally for O(1)
1187    /// `Table::count()` without a scan.
1188    pub(crate) live_count: u64,
1189    /// Uniform reservoir sample of row ids for approximate analytics
1190    /// (Phase 8.2). Maintained incrementally on insert; repopulated on open.
1191    reservoir: crate::reservoir::Reservoir,
1192    /// False when `reservoir` needs a full rebuild from `visible_rows` before
1193    /// [`Table::approx_aggregate`] can trust it (same lazy pattern as
1194    /// [`Table::ensure_indexes_complete`]). Open and WAL-replay leave this
1195    /// false instead of eagerly materializing every row — a full-table scan
1196    /// no plain insert/update/delete needs — and the first approximate-
1197    /// aggregate call pays the rebuild, after which `.offer()` calls maintain
1198    /// it incrementally.
1199    reservoir_complete: bool,
1200    /// True once any row has been deleted. The incremental aggregate cache
1201    /// (Phase 8.3) is only valid for append-only tables, so a single delete
1202    /// permanently disables incremental maintenance for this table.
1203    had_deletes: bool,
1204    /// Pre-images of pure deletes keyed by encoded PK, retained so a subsequent
1205    /// Kit-style delete+put (new rid, same PK) can re-point Bitmap secondaries
1206    /// via [`Self::maintain_indexes_on_pk_replace`] even though HOT no longer
1207    /// maps the PK. Cleared on successful re-point or index rebuild.
1208    recent_delete_preimages: HashMap<Vec<u8>, Row>,
1209    /// In-memory min/max RowId per run for O(1) skip in [`Self::get`]. Populated
1210    /// from run headers on open/spill; not a manifest field (avoids format bump).
1211    run_row_id_ranges: HashMap<u128, (u64, u64)>,
1212    /// Incremental aggregate cache (Phase 8.3): caller-supplied key → the
1213    /// mergeable aggregate state, the row-id watermark it covers, and the
1214    /// epoch. A re-query after more inserts processes only the delta and merges.
1215    agg_cache: Arc<HashMap<u64, CachedAgg>>,
1216    /// The manifest epoch the on-disk `_idx/global.idx` checkpoint covers (0 if
1217    /// there is no checkpoint). Updated by [`Table::checkpoint_indexes`]; persisted
1218    /// in the manifest so reopen loads the checkpoint instead of rebuilding.
1219    global_idx_epoch: u64,
1220    /// False when the live in-memory indexes are known to be incomplete (e.g.
1221    /// after [`Table::bulk_load_columns`], which bypasses per-row indexing). A
1222    /// flush in that state must NOT checkpoint; reopen rebuilds complete indexes
1223    /// from the runs and resets this to true.
1224    indexes_complete: bool,
1225    /// Where bulk loads put the index-build cost (see [`IndexBuildPolicy`]).
1226    index_build_policy: IndexBuildPolicy,
1227    /// False when `pk_by_row` may be missing entries for rows present in
1228    /// `hot`. Fresh tables start false and puts skip the reverse map — pure
1229    /// ingest never pays for it. The first delete that needs it rebuilds it
1230    /// from `hot` (the same lazy pattern as `ensure_indexes_complete`), after
1231    /// which puts maintain it incrementally so a delete-active workload pays
1232    /// the build exactly once.
1233    pk_by_row_complete: bool,
1234    /// Highest epoch whose data is durable in a sorted run (spec §7.1). Recovery
1235    /// skips replaying WAL records whose commit epoch is `<= flushed_epoch`.
1236    flushed_epoch: u64,
1237    /// Shared, MVCC content-addressed page cache (Phase 9.2). Fed by every
1238    /// `RunReader::read_page` so all readers share raw (decrypted) page bytes.
1239    page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
1240    /// Global snapshot-retention registry shared across all tables in a
1241    /// `Database`. Single-table direct opens get a private one.
1242    snapshots: Arc<crate::retention::SnapshotRegistry>,
1243    /// Cross-table commit serializer (see [`SharedCtx::commit_lock`]).
1244    commit_lock: Arc<parking_lot::Mutex<()>>,
1245    /// Shared decoded-page cache (Phase 15.4): the post-decompress/decrypt typed
1246    /// page, so repeat scans skip decode. Keyed by `(run_id, column_id, page)`.
1247    decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
1248    /// `run_id`s whose on-disk footer checksum has already been verified by a
1249    /// `RunReader` construction in this process. `.sr` runs are immutable once
1250    /// written, so re-hashing an already-verified run's full body on every
1251    /// repeat `open_reader` call (every query, every `remove_hot_for_row`) is
1252    /// pure waste for a warm/long-lived handle — this cache lets
1253    /// `read_header_cached` skip straight to the cheap header+footer-magic
1254    /// check after the first open. Scoped per-`Table` (not shared via
1255    /// `SharedCtx`) since `run_id` is only unique within one table's own
1256    /// manifest.
1257    verified_runs: Arc<parking_lot::Mutex<std::collections::HashSet<u128>>>,
1258    /// Open sorted-run readers keyed by run id. Runs are immutable once
1259    /// written, so a point lookup must not reopen and remap the `.sr` on
1260    /// every row. Drop the entry before deleting that file (Windows will not
1261    /// remove a mapped file).
1262    run_readers: Arc<parking_lot::Mutex<HashMap<u128, RunReader>>>,
1263    /// Table-level result cache (Phase 19.1): `canonical_query_key(conditions,
1264    /// projection, epoch)` → the survivor columns as typed `NativeColumn`s. Shared
1265    /// by the native `Condition` API and (via `query_cached`) the tool-call path,
1266    /// which previously had no caching (only the SQL `MongrelSession` cache did).
1267    /// Hardening (c): epoch is no longer in the key; instead, a `commit()`
1268    /// invalidates only entries whose footprint or condition-columns intersect
1269    /// the committed mutations, tracked in `pending_delete_rids` and
1270    /// `pending_put_cols`.
1271    result_cache: Arc<parking_lot::Mutex<ResultCache>>,
1272    /// WAL DEK (for frame-level encryption). None for plaintext tables.
1273    wal_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1274    /// RowIds deleted since the last `commit()` — used by fine-grained cache
1275    /// invalidation to check footprint intersection.
1276    pending_delete_rids: roaring::RoaringBitmap,
1277    /// Column IDs touched by `put`/`put_batch` since the last `commit()` — used
1278    /// by conservative insert-newly-matches invalidation.
1279    pending_put_cols: std::collections::HashSet<u16>,
1280    /// B1/B2: rows staged by `put`/`put_batch` on a mounted (shared-WAL) table
1281    /// but not yet applied to the memtable. They are re-stamped to the real
1282    /// assigned epoch in `commit` (never a speculative `visible+1`), so a
1283    /// concurrent reader can never observe them before their commit epoch.
1284    /// Always empty on a standalone (private-WAL) table, which applies inline.
1285    pending_rows: Vec<Row>,
1286    pending_rows_auto_inc: Vec<bool>,
1287    /// B1/B2: tombstones staged on a mounted table, applied at the assigned
1288    /// epoch in `commit` (mirror of `pending_rows`).
1289    pending_dels: Vec<RowId>,
1290    /// B1/B2: truncate staged on a mounted table, applied at the assigned epoch
1291    /// in `commit`; standalone tables also defer the physical clear until after
1292    /// the private WAL is fsynced.
1293    pending_truncate: Option<Epoch>,
1294    /// Engine-managed `AUTO_INCREMENT` counter (`None` for tables without an
1295    /// auto-increment primary key). See [`AutoIncState`].
1296    auto_inc: Option<AutoIncState>,
1297    /// Manifest-backed timestamp retention policy. Its wall-clock cutoff is
1298    /// evaluated once per read/compaction operation, never cached by epoch.
1299    ttl: Option<TtlPolicy>,
1300    /// Unified version-retention pin registry (S1C-004). Read generations
1301    /// register [`crate::retention::PinSource::ReadGeneration`] pins here;
1302    /// backup/PITR, replication, and online-index-build wiring from the
1303    /// `Database` layer is a follow-up (they can share this registry via
1304    /// [`Table::pin_registry`]). Compaction and version GC consult it through
1305    /// [`Table::min_active_snapshot`].
1306    pins: Arc<crate::retention::PinRegistry>,
1307    /// The atomically-published immutable read view (S1C-001). Writers store
1308    /// a replacement after sealing their active deltas; readers pin the
1309    /// loaded `Arc`. Read-generation clones get their own frozen cell so a
1310    /// later writer publish can never mutate a pinned generation's view.
1311    published: Arc<ArcSwap<ReadGeneration>>,
1312    /// The [`crate::retention::PinGuard`] keeping this generation's epoch
1313    /// retained. `None` on writer tables; `Some` on clones produced by
1314    /// [`Table::clone_read_generation`], released when the generation drops.
1315    /// Shared behind an `Arc` so cloning a generation shares one pin.
1316    read_generation_pin: Option<Arc<crate::retention::PinGuard>>,
1317    /// Lookup observability counters. HOT hits are the fast-path expectation;
1318    /// any fallback in a healthy workload is a regression to investigate.
1319    /// Each clone of `Table` (e.g. `clone_read_generation`) gets its own
1320    /// counters — readers and writers typically share via `Arc<Table>`.
1321    pub(crate) lookup_metrics: LookupMetrics,
1322    /// Per-table row-to-run lookup directory state (spec §1.2 / §8.4). Derived
1323    /// data only — open must not fail when the checkpoint is missing or stale
1324    /// (the existing range-scan fallback stays the safety net).
1325    run_lookup: RunLookupState,
1326    active_run_fingerprint: u64,
1327}
1328
1329/// Per-table row-to-run lookup directory state (Issue 4 / spec §8.4).
1330///
1331/// The directory is *derived* state and never authoritative for correctness.
1332/// `complete == true` means the in-memory `directory` is consistent with the
1333/// active run set; `false` means the open path found a missing / corrupt /
1334/// stale checkpoint and the read path should fall back to range scans until
1335/// a rebuild finishes (or a fresh publish lands).
1336#[derive(Debug, Default, Clone)]
1337struct RunLookupState {
1338    directory: Option<std::sync::Arc<crate::run_lookup::RunLookupDirectory>>,
1339    fingerprint: u64,
1340    complete: bool,
1341}
1342
1343#[derive(Debug, Default)]
1344pub struct LookupMetrics {
1345    hot_lookup_hit: std::sync::atomic::AtomicU64,
1346    hot_lookup_fallback: std::sync::atomic::AtomicU64,
1347    hot_lookup_fallback_overlay_rows: std::sync::atomic::AtomicU64,
1348    hot_lookup_fallback_runs: std::sync::atomic::AtomicU64,
1349    result_cache_memory_hit: std::sync::atomic::AtomicU64,
1350    result_cache_disk_hit: std::sync::atomic::AtomicU64,
1351    result_cache_miss: std::sync::atomic::AtomicU64,
1352    result_cache_persistent_write_us: std::sync::atomic::AtomicU64,
1353    /// Point-get run probes: opened vs skipped via `run_row_id_ranges`.
1354    get_run_opened: std::sync::atomic::AtomicU64,
1355    get_run_skipped: std::sync::atomic::AtomicU64,
1356    // ---- TODO §1: point-lookup directory counters ----
1357    pub(crate) directory_lookup_hit: std::sync::atomic::AtomicU64,
1358    pub(crate) directory_lookup_fallback: std::sync::atomic::AtomicU64,
1359    pub(crate) directory_incomplete: std::sync::atomic::AtomicU64,
1360    pub(crate) directory_run_readers_opened: std::sync::atomic::AtomicU64,
1361    pub(crate) directory_early_stop_total: std::sync::atomic::AtomicU64,
1362    /// REM-004: directory returned an empty complete lookup for a row (no
1363    /// postings at all). Distinct from `directory_lookup_fallback`, which
1364    /// records only `UnavailableOrStale` (no usable directory). Incremented
1365    /// alongside `directory_lookup_hit` because the directory itself was
1366    /// usable; the answer just happened to be "no immutable runs".
1367    pub(crate) directory_complete_miss_total: std::sync::atomic::AtomicU64,
1368    // ---- TODO §2: persistent result cache async counters ----
1369    pub(crate) result_cache_persist_enqueued_total: std::sync::atomic::AtomicU64,
1370    pub(crate) result_cache_persist_coalesced_total: std::sync::atomic::AtomicU64,
1371    pub(crate) result_cache_persist_dropped_store_total: std::sync::atomic::AtomicU64,
1372    pub(crate) result_cache_persist_remove_total: std::sync::atomic::AtomicU64,
1373    pub(crate) result_cache_persist_stale_store_skipped_total: std::sync::atomic::AtomicU64,
1374    pub(crate) result_cache_persist_errors_total: std::sync::atomic::AtomicU64,
1375    pub(crate) result_cache_persist_shutdown_abandoned_total: std::sync::atomic::AtomicU64,
1376    pub(crate) result_cache_persist_queue_depth: std::sync::atomic::AtomicU64,
1377    // ---- TODO §5: HOT fallback per-reason counters ----
1378    pub(crate) hot_fallback_reasons: [std::sync::atomic::AtomicU64; 9],
1379    pub(crate) hot_fallback_overlay_versions_total: std::sync::atomic::AtomicU64,
1380    pub(crate) hot_fallback_runs_considered_total: std::sync::atomic::AtomicU64,
1381    pub(crate) hot_fallback_runs_opened_total: std::sync::atomic::AtomicU64,
1382    pub(crate) hot_fallback_pages_decoded_total: std::sync::atomic::AtomicU64,
1383    pub(crate) hot_fallback_rows_materialized_total: std::sync::atomic::AtomicU64,
1384    pub(crate) hot_lookup_duration_nanos: std::sync::atomic::AtomicU64,
1385    pub(crate) hot_fallback_duration_nanos: std::sync::atomic::AtomicU64,
1386    pub(crate) hot_mapping_rebuild_total: std::sync::atomic::AtomicU64,
1387    pub(crate) hot_checkpoint_rejected_total: std::sync::atomic::AtomicU64,
1388}
1389
1390impl Clone for LookupMetrics {
1391    fn clone(&self) -> Self {
1392        let mut hot_fallback_reasons = [
1393            std::sync::atomic::AtomicU64::new(0),
1394            std::sync::atomic::AtomicU64::new(0),
1395            std::sync::atomic::AtomicU64::new(0),
1396            std::sync::atomic::AtomicU64::new(0),
1397            std::sync::atomic::AtomicU64::new(0),
1398            std::sync::atomic::AtomicU64::new(0),
1399            std::sync::atomic::AtomicU64::new(0),
1400            std::sync::atomic::AtomicU64::new(0),
1401            std::sync::atomic::AtomicU64::new(0),
1402        ];
1403        for (dst, src) in hot_fallback_reasons
1404            .iter_mut()
1405            .zip(self.hot_fallback_reasons.iter())
1406        {
1407            dst.store(
1408                src.load(std::sync::atomic::Ordering::Relaxed),
1409                std::sync::atomic::Ordering::Relaxed,
1410            );
1411        }
1412        let copy_atomic = |src: &std::sync::atomic::AtomicU64| {
1413            std::sync::atomic::AtomicU64::new(src.load(std::sync::atomic::Ordering::Relaxed))
1414        };
1415        Self {
1416            hot_lookup_hit: copy_atomic(&self.hot_lookup_hit),
1417            hot_lookup_fallback: copy_atomic(&self.hot_lookup_fallback),
1418            hot_lookup_fallback_overlay_rows: copy_atomic(&self.hot_lookup_fallback_overlay_rows),
1419            hot_lookup_fallback_runs: copy_atomic(&self.hot_lookup_fallback_runs),
1420            result_cache_memory_hit: copy_atomic(&self.result_cache_memory_hit),
1421            result_cache_disk_hit: copy_atomic(&self.result_cache_disk_hit),
1422            result_cache_miss: copy_atomic(&self.result_cache_miss),
1423            result_cache_persistent_write_us: copy_atomic(&self.result_cache_persistent_write_us),
1424            get_run_opened: copy_atomic(&self.get_run_opened),
1425            get_run_skipped: copy_atomic(&self.get_run_skipped),
1426            directory_lookup_hit: copy_atomic(&self.directory_lookup_hit),
1427            directory_lookup_fallback: copy_atomic(&self.directory_lookup_fallback),
1428            directory_incomplete: copy_atomic(&self.directory_incomplete),
1429            directory_run_readers_opened: copy_atomic(&self.directory_run_readers_opened),
1430            directory_early_stop_total: copy_atomic(&self.directory_early_stop_total),
1431            directory_complete_miss_total: copy_atomic(&self.directory_complete_miss_total),
1432            result_cache_persist_enqueued_total: copy_atomic(
1433                &self.result_cache_persist_enqueued_total,
1434            ),
1435            result_cache_persist_coalesced_total: copy_atomic(
1436                &self.result_cache_persist_coalesced_total,
1437            ),
1438            result_cache_persist_dropped_store_total: copy_atomic(
1439                &self.result_cache_persist_dropped_store_total,
1440            ),
1441            result_cache_persist_remove_total: copy_atomic(&self.result_cache_persist_remove_total),
1442            result_cache_persist_stale_store_skipped_total: copy_atomic(
1443                &self.result_cache_persist_stale_store_skipped_total,
1444            ),
1445            result_cache_persist_errors_total: copy_atomic(&self.result_cache_persist_errors_total),
1446            result_cache_persist_shutdown_abandoned_total: copy_atomic(
1447                &self.result_cache_persist_shutdown_abandoned_total,
1448            ),
1449            result_cache_persist_queue_depth: copy_atomic(&self.result_cache_persist_queue_depth),
1450            hot_fallback_reasons,
1451            hot_fallback_overlay_versions_total: copy_atomic(
1452                &self.hot_fallback_overlay_versions_total,
1453            ),
1454            hot_fallback_runs_considered_total: copy_atomic(
1455                &self.hot_fallback_runs_considered_total,
1456            ),
1457            hot_fallback_runs_opened_total: copy_atomic(&self.hot_fallback_runs_opened_total),
1458            hot_fallback_pages_decoded_total: copy_atomic(&self.hot_fallback_pages_decoded_total),
1459            hot_fallback_rows_materialized_total: copy_atomic(
1460                &self.hot_fallback_rows_materialized_total,
1461            ),
1462            hot_lookup_duration_nanos: copy_atomic(&self.hot_lookup_duration_nanos),
1463            hot_fallback_duration_nanos: copy_atomic(&self.hot_fallback_duration_nanos),
1464            hot_mapping_rebuild_total: copy_atomic(&self.hot_mapping_rebuild_total),
1465            hot_checkpoint_rejected_total: copy_atomic(&self.hot_checkpoint_rejected_total),
1466        }
1467    }
1468}
1469
1470impl LookupMetrics {
1471    fn snapshot(&self) -> LookupMetricsSnapshot {
1472        LookupMetricsSnapshot {
1473            hot_lookup_hit: self
1474                .hot_lookup_hit
1475                .load(std::sync::atomic::Ordering::Relaxed),
1476            hot_lookup_fallback: self
1477                .hot_lookup_fallback
1478                .load(std::sync::atomic::Ordering::Relaxed),
1479            hot_lookup_fallback_overlay_rows: self
1480                .hot_lookup_fallback_overlay_rows
1481                .load(std::sync::atomic::Ordering::Relaxed),
1482            hot_lookup_fallback_runs: self
1483                .hot_lookup_fallback_runs
1484                .load(std::sync::atomic::Ordering::Relaxed),
1485            result_cache_memory_hit: self
1486                .result_cache_memory_hit
1487                .load(std::sync::atomic::Ordering::Relaxed),
1488            result_cache_disk_hit: self
1489                .result_cache_disk_hit
1490                .load(std::sync::atomic::Ordering::Relaxed),
1491            result_cache_miss: self
1492                .result_cache_miss
1493                .load(std::sync::atomic::Ordering::Relaxed),
1494            result_cache_persistent_write_us: self
1495                .result_cache_persistent_write_us
1496                .load(std::sync::atomic::Ordering::Relaxed),
1497            get_run_opened: self
1498                .get_run_opened
1499                .load(std::sync::atomic::Ordering::Relaxed),
1500            get_run_skipped: self
1501                .get_run_skipped
1502                .load(std::sync::atomic::Ordering::Relaxed),
1503            directory_lookup_hit: self
1504                .directory_lookup_hit
1505                .load(std::sync::atomic::Ordering::Relaxed),
1506            directory_lookup_fallback: self
1507                .directory_lookup_fallback
1508                .load(std::sync::atomic::Ordering::Relaxed),
1509            directory_incomplete: self
1510                .directory_incomplete
1511                .load(std::sync::atomic::Ordering::Relaxed),
1512            directory_run_readers_opened: self
1513                .directory_run_readers_opened
1514                .load(std::sync::atomic::Ordering::Relaxed),
1515            directory_early_stop_total: self
1516                .directory_early_stop_total
1517                .load(std::sync::atomic::Ordering::Relaxed),
1518            directory_complete_miss_total: self
1519                .directory_complete_miss_total
1520                .load(std::sync::atomic::Ordering::Relaxed),
1521            result_cache_persist_enqueued_total: self
1522                .result_cache_persist_enqueued_total
1523                .load(std::sync::atomic::Ordering::Relaxed),
1524            result_cache_persist_coalesced_total: self
1525                .result_cache_persist_coalesced_total
1526                .load(std::sync::atomic::Ordering::Relaxed),
1527            result_cache_persist_dropped_store_total: self
1528                .result_cache_persist_dropped_store_total
1529                .load(std::sync::atomic::Ordering::Relaxed),
1530            result_cache_persist_remove_total: self
1531                .result_cache_persist_remove_total
1532                .load(std::sync::atomic::Ordering::Relaxed),
1533            result_cache_persist_stale_store_skipped_total: self
1534                .result_cache_persist_stale_store_skipped_total
1535                .load(std::sync::atomic::Ordering::Relaxed),
1536            result_cache_persist_errors_total: self
1537                .result_cache_persist_errors_total
1538                .load(std::sync::atomic::Ordering::Relaxed),
1539            result_cache_persist_shutdown_abandoned_total: self
1540                .result_cache_persist_shutdown_abandoned_total
1541                .load(std::sync::atomic::Ordering::Relaxed),
1542            result_cache_persist_queue_depth: self
1543                .result_cache_persist_queue_depth
1544                .load(std::sync::atomic::Ordering::Relaxed),
1545            // REM-D §8.7: publication-availability counters live on the
1546            // `ResultCache` itself (not on the writer's metrics), so they
1547            // are filled in by `Table::lookup_metrics_snapshot`.
1548            result_cache_persist_unavailable_total: 0,
1549            result_cache_persist_skipped_total: 0,
1550            result_cache_worker_spawn_failures_total: 0,
1551            result_cache_worker_shutdown_total: 0,
1552            hot_fallback_reasons: [
1553                self.hot_fallback_reasons[0].load(std::sync::atomic::Ordering::Relaxed),
1554                self.hot_fallback_reasons[1].load(std::sync::atomic::Ordering::Relaxed),
1555                self.hot_fallback_reasons[2].load(std::sync::atomic::Ordering::Relaxed),
1556                self.hot_fallback_reasons[3].load(std::sync::atomic::Ordering::Relaxed),
1557                self.hot_fallback_reasons[4].load(std::sync::atomic::Ordering::Relaxed),
1558                self.hot_fallback_reasons[5].load(std::sync::atomic::Ordering::Relaxed),
1559                self.hot_fallback_reasons[6].load(std::sync::atomic::Ordering::Relaxed),
1560                self.hot_fallback_reasons[7].load(std::sync::atomic::Ordering::Relaxed),
1561                self.hot_fallback_reasons[8].load(std::sync::atomic::Ordering::Relaxed),
1562            ],
1563            hot_fallback_overlay_versions_total: self
1564                .hot_fallback_overlay_versions_total
1565                .load(std::sync::atomic::Ordering::Relaxed),
1566            hot_fallback_runs_considered_total: self
1567                .hot_fallback_runs_considered_total
1568                .load(std::sync::atomic::Ordering::Relaxed),
1569            hot_fallback_runs_opened_total: self
1570                .hot_fallback_runs_opened_total
1571                .load(std::sync::atomic::Ordering::Relaxed),
1572            hot_fallback_pages_decoded_total: self
1573                .hot_fallback_pages_decoded_total
1574                .load(std::sync::atomic::Ordering::Relaxed),
1575            hot_fallback_rows_materialized_total: self
1576                .hot_fallback_rows_materialized_total
1577                .load(std::sync::atomic::Ordering::Relaxed),
1578            hot_lookup_duration_nanos: self
1579                .hot_lookup_duration_nanos
1580                .load(std::sync::atomic::Ordering::Relaxed),
1581            hot_fallback_duration_nanos: self
1582                .hot_fallback_duration_nanos
1583                .load(std::sync::atomic::Ordering::Relaxed),
1584            hot_mapping_rebuild_total: self
1585                .hot_mapping_rebuild_total
1586                .load(std::sync::atomic::Ordering::Relaxed),
1587            hot_checkpoint_rejected_total: self
1588                .hot_checkpoint_rejected_total
1589                .load(std::sync::atomic::Ordering::Relaxed),
1590        }
1591    }
1592}
1593
1594/// Point-in-time copy of [`LookupMetrics`]. Returned from
1595/// [`Table::lookup_metrics_snapshot`] for `/metrics` exposure or test assertions.
1596#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1597pub struct LookupMetricsSnapshot {
1598    pub hot_lookup_hit: u64,
1599    pub hot_lookup_fallback: u64,
1600    pub hot_lookup_fallback_overlay_rows: u64,
1601    pub hot_lookup_fallback_runs: u64,
1602    pub result_cache_memory_hit: u64,
1603    pub result_cache_disk_hit: u64,
1604    pub result_cache_miss: u64,
1605    pub result_cache_persistent_write_us: u64,
1606    pub get_run_opened: u64,
1607    pub get_run_skipped: u64,
1608    // ---- TODO §1 ----
1609    pub directory_lookup_hit: u64,
1610    pub directory_lookup_fallback: u64,
1611    pub directory_incomplete: u64,
1612    pub directory_run_readers_opened: u64,
1613    pub directory_early_stop_total: u64,
1614    pub directory_complete_miss_total: u64,
1615    // ---- TODO §2 ----
1616    pub result_cache_persist_enqueued_total: u64,
1617    pub result_cache_persist_coalesced_total: u64,
1618    pub result_cache_persist_dropped_store_total: u64,
1619    pub result_cache_persist_remove_total: u64,
1620    pub result_cache_persist_stale_store_skipped_total: u64,
1621    pub result_cache_persist_errors_total: u64,
1622    pub result_cache_persist_shutdown_abandoned_total: u64,
1623    pub result_cache_persist_queue_depth: u64,
1624    // ---- REM-D §8.7: publication-availability counters ----
1625    /// Number of times persistent publication transitioned to unavailable
1626    /// (worker spawn failure, worker shutdown, queue unavailable).
1627    pub result_cache_persist_unavailable_total: u64,
1628    /// Number of query-path persist operations skipped because publication
1629    /// was unavailable (the in-memory entry is kept; nothing hits disk).
1630    pub result_cache_persist_skipped_total: u64,
1631    /// Number of background-worker spawn / I/O-setup failures.
1632    pub result_cache_worker_spawn_failures_total: u64,
1633    /// Number of background-worker shutdowns while the cache was live.
1634    pub result_cache_worker_shutdown_total: u64,
1635    // ---- TODO §5 ----
1636    pub hot_fallback_reasons: [u64; 9],
1637    pub hot_fallback_overlay_versions_total: u64,
1638    pub hot_fallback_runs_considered_total: u64,
1639    pub hot_fallback_runs_opened_total: u64,
1640    pub hot_fallback_pages_decoded_total: u64,
1641    pub hot_fallback_rows_materialized_total: u64,
1642    pub hot_lookup_duration_nanos: u64,
1643    pub hot_fallback_duration_nanos: u64,
1644    pub hot_mapping_rebuild_total: u64,
1645    pub hot_checkpoint_rejected_total: u64,
1646}
1647
1648/// Reason label for one HOT fallback. The integer index is the position in
1649/// `LookupMetrics::hot_fallback_reasons` and MUST stay stable across releases.
1650pub fn hot_fallback_reason_index(r: crate::trace::HotFallbackReason) -> usize {
1651    match r {
1652        crate::trace::HotFallbackReason::MissingMapping => 0,
1653        crate::trace::HotFallbackReason::StaleRowId => 1,
1654        crate::trace::HotFallbackReason::InvisibleAtSnapshot => 2,
1655        crate::trace::HotFallbackReason::HistoricalSnapshot => 3,
1656        crate::trace::HotFallbackReason::Tombstone => 4,
1657        crate::trace::HotFallbackReason::TtlExpired => 5,
1658        crate::trace::HotFallbackReason::PrimaryKeyMismatch => 6,
1659        crate::trace::HotFallbackReason::IndexIncomplete => 7,
1660        crate::trace::HotFallbackReason::CheckpointRejected => 8,
1661    }
1662}
1663
1664// `Table` is `Sync`: every field is either plain data, an `Arc`, a `Vec`/`HashMap`
1665// of `Sync` data, or a thread-safe interior-mutability cell (`parking_lot::Mutex`,
1666// `crossbeam`/`epoch` Arc-shared caches). The only `RefCell`-based type was
1667// `FmIndex` (lazy rebuild of the BWT), which now uses a `Mutex`, so a `&Table`
1668// can be safely shared across read threads (concurrent mutation still requires
1669// the caller's `Mutex<Table>`).
1670const _: () = {
1671    const fn assert_sync<T: ?Sized + Sync>() {}
1672    assert_sync::<Table>();
1673};
1674
1675/// A cached query result — either survivor `Row`s (the tool-call/`query` path)
1676/// or typed survivor columns (the pushdown/`query_columns_native` path). One
1677/// canonical key maps to exactly one variant (a `query` with no projection vs a
1678/// `query_columns_native` with a specific projection produce different keys), so
1679/// there is no representation collision.
1680#[derive(Clone)]
1681enum CachedData {
1682    Rows(Arc<Vec<Row>>),
1683    Columns(Arc<Vec<(u16, columnar::NativeColumn)>>),
1684}
1685
1686impl CachedData {
1687    fn approx_bytes(&self) -> u64 {
1688        match self {
1689            CachedData::Rows(r) => r.iter().map(|r| r.estimated_bytes()).sum::<u64>(),
1690            CachedData::Columns(c) => c
1691                .iter()
1692                .map(|(_, c)| c.approx_bytes())
1693                .sum::<u64>()
1694                .saturating_add(c.len() as u64 * 16),
1695        }
1696    }
1697}
1698
1699/// A cached entry carrying the survivor `RowId` **footprint** (for precise
1700/// delete-based invalidation) and the condition column IDs (for conservative
1701/// insert-based invalidation). Hardening (c).
1702struct CachedEntry {
1703    data: CachedData,
1704    footprint: roaring::RoaringBitmap,
1705    condition_cols: Vec<u16>,
1706}
1707
1708impl CachedEntry {
1709    /// Cheap clone for handing to the persistent-cache worker. The `data`
1710    /// is `Arc`-shared (no row/column copy); only the `condition_cols`
1711    /// vector and the `footprint` bitmap are duplicated. The latter two are
1712    /// small relative to the cached payload, so this is fine on the query
1713    /// path.
1714    fn clone_for_persist(&self) -> Self {
1715        Self {
1716            data: self.data.clone(),
1717            footprint: self.footprint.clone(),
1718            condition_cols: self.condition_cols.clone(),
1719        }
1720    }
1721}
1722
1723/// Size-bounded **access-order LRU** result cache (Phase 19.1 + hardening (a)).
1724/// Every `get_*` assigns a new recency generation; eviction removes the lowest
1725/// generation (least-recently-used) — a true LRU, not FIFO.
1726///
1727/// Hardening (b): an optional on-disk persistent tier (`dir = Some(_)`). On a
1728/// memory miss, the cache tries disk before falling through to re-resolution.
1729/// On `insert`, the caller publishes the entry through `persist_entry`, which
1730/// enqueues the atomic write (temp + fsync + rename) onto the background
1731/// worker — never synchronously on the query thread (REM-D §8.5). On
1732/// `invalidate`/`clear`, the matching disk files are deleted. On
1733/// `Table::open`, existing disk entries are pre-loaded so fine-grained invalidation
1734/// resumes across restart.
1735struct ResultCache {
1736    entries: std::collections::HashMap<u64, CachedEntry>,
1737    order: BTreeSet<(u64, u64)>,
1738    generations: HashMap<u64, u64>,
1739    next_generation: u64,
1740    /// Reverse index for conservative insert invalidation. Its size is bounded
1741    /// by cached query-condition metadata, not by survivor rows.
1742    condition_index: HashMap<u16, HashSet<u64>>,
1743    /// Entries whose row footprint could not be resolved. Any delete must
1744    /// conservatively invalidate these entries.
1745    empty_footprint_entries: HashSet<u64>,
1746    bytes: u64,
1747    max_bytes: u64,
1748    dir: Option<std::path::PathBuf>,
1749    #[allow(dead_code)]
1750    cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1751    /// Cache hit/miss counters (memory vs disk tier) + persistent-write latency.
1752    /// Independent of `LookupMetrics` on the parent `Table` — the cache may be
1753    /// queried by paths that don't pass through the table's Pk arm.
1754    memory_hit: std::sync::atomic::AtomicU64,
1755    disk_hit: std::sync::atomic::AtomicU64,
1756    miss: std::sync::atomic::AtomicU64,
1757    persistent_write_us: std::sync::atomic::AtomicU64,
1758    /// Minimum entry size (approx bytes) before the persistent tier is written.
1759    /// Tiny one-row results stay memory-only so a warm miss is not forced to
1760    /// pay atomic filesystem publish. 0 disables the threshold (always persist
1761    /// when `dir` is set). Default: 4 KiB.
1762    persist_min_bytes: u64,
1763    /// Explicit persistent-publication state (REM-D §8.6). `Async` once the
1764    /// table has been wired to a background worker (`install_persistent_writer`);
1765    /// `Disabled(reason)` before then, after a spawn failure, or after worker
1766    /// shutdown. The query path never performs synchronous disk publication:
1767    /// when the state is `Disabled`, `persist_entry` keeps the in-memory entry,
1768    /// skips publication, and increments the skip metric.
1769    persistence: PersistentPublicationState,
1770    /// Worker join handle, kept on the cache so `shutdown_persistent_cache`
1771    /// can wait for drain to finish.
1772    worker_handle: Option<std::thread::JoinHandle<()>>,
1773    /// Completion-signal receiver. The worker sends `()` on this channel
1774    /// immediately before exiting. `shutdown_persistent_cache(deadline)`
1775    /// uses `recv_timeout(remaining_deadline)` so it can return by its
1776    /// advertised deadline even if the worker is blocked in filesystem I/O.
1777    completion_rx: Option<std::sync::mpsc::Receiver<()>>,
1778    /// Optional DEK for cache payload encryption (binary, not a `Zeroizing`
1779    /// wrapper). Stored separately from the cache writer so the same cipher
1780    /// can be reused for both async and sync encode/decode paths.
1781    cache_payload_cipher: Option<std::sync::Arc<crate::encryption::AesCipher>>,
1782    // ---- REM-D §8.7: publication-availability counters ----
1783    /// Transitions of `persistence` to a `Disabled` state while the cache
1784    /// was expected to publish.
1785    persist_unavailable_total: std::sync::atomic::AtomicU64,
1786    /// Query-path persist operations skipped because publication was disabled.
1787    persist_skipped_total: std::sync::atomic::AtomicU64,
1788    /// Worker spawn / I/O-setup failures observed at wiring time.
1789    worker_spawn_failures_total: std::sync::atomic::AtomicU64,
1790    /// Worker shutdowns observed while the cache was live.
1791    worker_shutdown_total: std::sync::atomic::AtomicU64,
1792}
1793
1794/// Serialised form of a [`CachedEntry`] for the persistent on-disk tier (b).
1795#[derive(serde::Serialize, serde::Deserialize)]
1796struct SerializedEntry {
1797    condition_cols: Vec<u16>,
1798    footprint_bits: Vec<u32>,
1799    data: SerializedData,
1800}
1801
1802#[derive(serde::Serialize, serde::Deserialize)]
1803enum SerializedData {
1804    Rows(Vec<Row>),
1805    Columns(Vec<(u16, columnar::NativeColumn)>),
1806}
1807
1808#[derive(serde::Serialize)]
1809struct SerializedEntryRef<'a> {
1810    condition_cols: &'a [u16],
1811    footprint_bits: Vec<u32>,
1812    data: SerializedDataRef<'a>,
1813}
1814
1815#[derive(serde::Serialize)]
1816enum SerializedDataRef<'a> {
1817    Rows(&'a [Row]),
1818    Columns(&'a [(u16, columnar::NativeColumn)]),
1819}
1820
1821impl<'a> SerializedEntryRef<'a> {
1822    fn from_entry(entry: &'a CachedEntry) -> Self {
1823        let footprint_bits: Vec<u32> = entry.footprint.iter().collect();
1824        let data = match &entry.data {
1825            CachedData::Rows(rows) => SerializedDataRef::Rows(rows.as_slice()),
1826            CachedData::Columns(columns) => SerializedDataRef::Columns(columns.as_slice()),
1827        };
1828        Self {
1829            condition_cols: &entry.condition_cols,
1830            footprint_bits,
1831            data,
1832        }
1833    }
1834}
1835
1836impl SerializedEntry {
1837    fn into_entry(self) -> Option<CachedEntry> {
1838        let footprint: roaring::RoaringBitmap = self.footprint_bits.into_iter().collect();
1839        let data = match self.data {
1840            SerializedData::Rows(r) => CachedData::Rows(Arc::new(r)),
1841            SerializedData::Columns(c) => {
1842                // Validate deserialized columns (hardening (b)): reject corrupt
1843                // data instead of panicking on access.
1844                if !c.iter().all(|(_, col)| col.validate()) {
1845                    return None;
1846                }
1847                CachedData::Columns(Arc::new(c))
1848            }
1849        };
1850        Some(CachedEntry {
1851            data,
1852            footprint,
1853            condition_cols: self.condition_cols,
1854        })
1855    }
1856}
1857
1858impl ResultCache {
1859    const DEFAULT_MAX_BYTES: u64 = 256 * 1024 * 1024;
1860
1861    fn new() -> Self {
1862        Self::with_max_bytes(Self::DEFAULT_MAX_BYTES)
1863    }
1864
1865    fn with_max_bytes(max_bytes: u64) -> Self {
1866        Self {
1867            entries: std::collections::HashMap::new(),
1868            order: BTreeSet::new(),
1869            generations: HashMap::new(),
1870            next_generation: 0,
1871            condition_index: HashMap::new(),
1872            empty_footprint_entries: HashSet::new(),
1873            bytes: 0,
1874            max_bytes,
1875            dir: None,
1876            cache_dek: None,
1877            memory_hit: std::sync::atomic::AtomicU64::new(0),
1878            disk_hit: std::sync::atomic::AtomicU64::new(0),
1879            miss: std::sync::atomic::AtomicU64::new(0),
1880            persistent_write_us: std::sync::atomic::AtomicU64::new(0),
1881            // Skip synchronous disk publish for tiny results (one-row point
1882            // queries). Larger analytical results still hit the durable tier.
1883            persist_min_bytes: 4 * 1024,
1884            persistence: PersistentPublicationState::Disabled(
1885                PersistenceDisabledReason::NoDirectory,
1886            ),
1887            worker_handle: None,
1888            completion_rx: None,
1889            cache_payload_cipher: None,
1890            persist_unavailable_total: std::sync::atomic::AtomicU64::new(0),
1891            persist_skipped_total: std::sync::atomic::AtomicU64::new(0),
1892            worker_spawn_failures_total: std::sync::atomic::AtomicU64::new(0),
1893            worker_shutdown_total: std::sync::atomic::AtomicU64::new(0),
1894        }
1895    }
1896
1897    fn with_dir(mut self, dir: std::path::PathBuf) -> Self {
1898        let _ = std::fs::create_dir_all(&dir);
1899        self.dir = Some(dir);
1900        if matches!(
1901            self.persistence,
1902            PersistentPublicationState::Disabled(PersistenceDisabledReason::NoDirectory)
1903        ) {
1904            self.persistence =
1905                PersistentPublicationState::Disabled(PersistenceDisabledReason::QueueUnavailable);
1906        }
1907        self
1908    }
1909
1910    fn with_cache_dek(mut self, dek: Option<Zeroizing<[u8; DEK_LEN]>>) -> Self {
1911        // Build a single cipher for both async and sync paths. The cipher is
1912        // a thin wrapper around the AES key, so creating it twice (once for
1913        // the cache, once for the worker's own copy) is cheap. We keep the
1914        // raw DEK for backward compatibility with `encrypt_cache` /
1915        // `decrypt_cache`; new code paths should use `cache_payload_cipher`.
1916        self.cache_dek = dek.clone();
1917        if let Some(dek) = dek {
1918            if let Ok(cipher) = crate::encryption::AesCipher::new(&dek[..]) {
1919                self.cache_payload_cipher = Some(std::sync::Arc::new(cipher));
1920            }
1921        }
1922        self
1923    }
1924
1925    /// Install a background writer and its worker. The writer drains the
1926    /// pending-op queue and publishes through the supplied I/O backend.
1927    /// `flush_persistent_cache(deadline)` and `shutdown_persistent_cache(deadline)`
1928    /// rely on the writer being installed.
1929    fn install_persistent_writer(
1930        &mut self,
1931        writer: std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
1932        worker_handle: std::thread::JoinHandle<()>,
1933        completion_rx: std::sync::mpsc::Receiver<()>,
1934    ) {
1935        self.persistence = PersistentPublicationState::Async(writer);
1936        self.worker_handle = Some(worker_handle);
1937        self.completion_rx = Some(completion_rx);
1938    }
1939
1940    /// Record that the background worker (or its I/O setup) failed to start.
1941    /// Publication transitions to `Disabled(WorkerSpawnFailed)`; subsequent
1942    /// query-path persists are skipped with a metric instead of falling back
1943    /// to synchronous query-thread I/O (REM-D §8.5).
1944    fn note_worker_spawn_failure(&mut self) {
1945        self.worker_spawn_failures_total
1946            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1947        self.persist_unavailable_total
1948            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1949        self.persistence =
1950            PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerSpawnFailed);
1951    }
1952
1953    /// Take the worker handle so the caller can join it after shutdown.
1954    /// Returns `None` if no writer is installed.
1955    fn take_persistent_worker(&mut self) -> Option<std::thread::JoinHandle<()>> {
1956        self.worker_handle.take()
1957    }
1958
1959    /// Take the completion-signal receiver so the caller can wait on a
1960    /// bounded deadline. Returns `None` if no writer is installed.
1961    fn take_persistent_completion(&mut self) -> Option<std::sync::mpsc::Receiver<()>> {
1962        self.completion_rx.take()
1963    }
1964
1965    /// Borrow the writer (when installed). Used by `flush_persistent_cache` /
1966    /// `shutdown_persistent_cache` to wait for the queue to drain.
1967    fn persistent_writer(
1968        &self,
1969    ) -> Option<&std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>> {
1970        match &self.persistence {
1971            PersistentPublicationState::Async(writer) => Some(writer),
1972            PersistentPublicationState::Disabled(_) => None,
1973        }
1974    }
1975
1976    fn disk_path(&self, key: u64) -> Option<std::path::PathBuf> {
1977        self.dir.as_ref().map(|d| d.join(format!("{key:016x}.bin")))
1978    }
1979
1980    /// Persist `entry` to the on-disk tier **synchronously** using the MLCP
1981    /// frame format (REM-002). The encoding is shared with the async worker —
1982    /// both paths produce the same frame layout, identity validation, and
1983    /// payload encryption. Best-effort: silently ignores I/O errors (the
1984    /// in-memory cache is authoritative; the cache is disposable —
1985    /// missing/stale files fall through to re-resolution).
1986    ///
1987    /// Maintenance-only entry point (REM-D §8.6): migration tools, explicit
1988    /// administrative flushes, and focused format-parity tests. Never called
1989    /// from `query_cached` / `query_columns_native_cached` — the query path
1990    /// uses [`ResultCache::persist_entry`], which never blocks on disk I/O.
1991    fn persist_entry_synchronously_for_maintenance(
1992        &self,
1993        context: PersistContext,
1994        entry: &CachedEntry,
1995    ) {
1996        let Some(path) = self.disk_path(context.key) else {
1997            return;
1998        };
1999        let serialized = match bincode::serialize(&SerializedEntryRef::from_entry(entry)) {
2000            Ok(s) => s,
2001            Err(_) => return,
2002        };
2003        let bytes = match crate::result_cache::encode_persisted_entry(
2004            context,
2005            &serialized,
2006            self.cache_payload_cipher.as_deref(),
2007        ) {
2008            Ok(b) => b,
2009            Err(_) => return,
2010        };
2011        let tmp = path.with_extension("tmp");
2012        use std::io::Write;
2013        let write = || -> std::io::Result<()> {
2014            let mut f = std::fs::File::create(&tmp)?;
2015            f.write_all(&bytes)?;
2016            f.flush()?;
2017            f.sync_all()?;
2018            Ok(())
2019        };
2020        if write().is_err() {
2021            let _ = std::fs::remove_file(&tmp);
2022            return;
2023        }
2024        if std::fs::rename(&tmp, &path).is_err() {
2025            let _ = std::fs::remove_file(&tmp);
2026            return;
2027        }
2028        if let Ok(dir) = std::fs::File::open(self.dir.as_ref().expect("dir set").clone()) {
2029            let _ = dir.sync_all();
2030        }
2031    }
2032
2033    /// Try loading `key` from disk. Returns `None` on miss or error.
2034    /// Decodes the MLCP frame, validates table / schema / key / generation /
2035    /// format version / CRC, decrypts the payload, and bincode-deserializes
2036    /// the entry. Legacy unframed files (anything that does not start with
2037    /// the MLCP magic) are deleted as a safe migration (REM-002 §18.5).
2038    fn load_from_disk(&self, key: u64, identity: PersistentCacheIdentity) -> Option<CachedEntry> {
2039        let path = self.disk_path(key)?;
2040        let bytes = std::fs::read(&path).ok()?;
2041        // Legacy migration: drop unframed files instead of trying to
2042        // bincode-deserialize a raw entry. The cache is disposable — a
2043        // recompute is cheaper than a fragile backward-compat shim.
2044        if bytes.len() < FRAME_MAGIC.len() || bytes[..FRAME_MAGIC.len()] != FRAME_MAGIC {
2045            let _ = std::fs::remove_file(&path);
2046            return None;
2047        }
2048        let plaintext = match crate::result_cache::decode_persisted_entry(
2049            identity,
2050            key,
2051            &bytes,
2052            self.cache_payload_cipher.as_deref(),
2053        ) {
2054            Ok(p) => p,
2055            Err(_) => {
2056                let _ = std::fs::remove_file(&path);
2057                return None;
2058            }
2059        };
2060        let serialized: SerializedEntry = match bincode::deserialize(&plaintext) {
2061            Ok(s) => s,
2062            Err(_) => {
2063                let _ = std::fs::remove_file(&path);
2064                return None;
2065            }
2066        };
2067        serialized.into_entry()
2068    }
2069
2070    /// Delete the on-disk file for `key` if it exists. Best-effort.
2071    fn remove_from_disk(&self, key: u64) {
2072        if let Some(path) = self.disk_path(key) {
2073            let _ = std::fs::remove_file(&path);
2074        }
2075    }
2076
2077    /// Scan the cache directory and pre-load all entries into memory. Called
2078    /// once on `Table::open`. Best-effort: corrupt / unframed / wrong-identity
2079    /// files are deleted and the corresponding entry is treated as a miss.
2080    fn load_persistent(&mut self, identity: PersistentCacheIdentity) {
2081        let Some(dir) = self.dir.as_ref().cloned() else {
2082            return;
2083        };
2084        let entries = match std::fs::read_dir(&dir) {
2085            Ok(e) => e,
2086            Err(_) => return,
2087        };
2088        for entry in entries.flatten() {
2089            let path = entry.path();
2090            // Clean up orphan .tmp files from crashed atomic-write calls.
2091            if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
2092                let _ = std::fs::remove_file(&path);
2093                continue;
2094            }
2095            if path.extension().and_then(|e| e.to_str()) != Some("bin") {
2096                continue;
2097            }
2098            let stem = match path.file_stem().and_then(|s| s.to_str()) {
2099                Some(s) => s,
2100                None => continue,
2101            };
2102            let key = match u64::from_str_radix(stem, 16) {
2103                Ok(k) => k,
2104                Err(_) => continue,
2105            };
2106            // Reuse `load_from_disk` so the legacy / corruption / identity
2107            // rejection path is consistent across the per-key load and the
2108            // bulk preload. The function deletes bad files itself.
2109            if let Some(entry) = self.load_from_disk(key, identity) {
2110                self.bytes = self.bytes.saturating_add(entry.data.approx_bytes());
2111                self.index_entry(key, &entry);
2112                self.entries.insert(key, entry);
2113                self.touch(key);
2114            }
2115        }
2116        self.evict();
2117    }
2118
2119    fn set_max_bytes(&mut self, max_bytes: u64) {
2120        self.max_bytes = max_bytes;
2121        self.evict();
2122    }
2123
2124    /// Promote `key` to most-recently-used position without scanning every
2125    /// cache entry. The generation-ordered set provides exact LRU in O(log n).
2126    fn touch(&mut self, key: u64) {
2127        if !self.entries.contains_key(&key) {
2128            return;
2129        }
2130        if let Some(previous) = self.generations.remove(&key) {
2131            self.order.remove(&(previous, key));
2132        }
2133        let generation = self.allocate_generation();
2134        self.generations.insert(key, generation);
2135        self.order.insert((generation, key));
2136    }
2137
2138    fn untrack(&mut self, key: u64) {
2139        if let Some(generation) = self.generations.remove(&key) {
2140            self.order.remove(&(generation, key));
2141        }
2142    }
2143
2144    fn index_entry(&mut self, key: u64, entry: &CachedEntry) {
2145        for column in &entry.condition_cols {
2146            self.condition_index.entry(*column).or_default().insert(key);
2147        }
2148        if entry.footprint.is_empty() {
2149            self.empty_footprint_entries.insert(key);
2150        }
2151    }
2152
2153    fn unindex_entry(&mut self, key: u64, entry: &CachedEntry) {
2154        for column in &entry.condition_cols {
2155            let remove_column = self.condition_index.get_mut(column).is_some_and(|keys| {
2156                keys.remove(&key);
2157                keys.is_empty()
2158            });
2159            if remove_column {
2160                self.condition_index.remove(column);
2161            }
2162        }
2163        if entry.footprint.is_empty() {
2164            self.empty_footprint_entries.remove(&key);
2165        }
2166    }
2167
2168    fn allocate_generation(&mut self) -> u64 {
2169        if self.next_generation == u64::MAX {
2170            self.rebase_generations();
2171        }
2172        let generation = self.next_generation;
2173        self.next_generation += 1;
2174        generation
2175    }
2176
2177    fn rebase_generations(&mut self) {
2178        let ordered = std::mem::take(&mut self.order);
2179        self.generations.clear();
2180        for (generation, (_, key)) in ordered.into_iter().enumerate() {
2181            let generation = generation as u64;
2182            self.generations.insert(key, generation);
2183            self.order.insert((generation, key));
2184        }
2185        self.next_generation = self.order.len() as u64;
2186    }
2187
2188    fn get_rows(&mut self, key: u64, identity: PersistentCacheIdentity) -> Option<Arc<Vec<Row>>> {
2189        let res = self.entries.get(&key).and_then(|e| match &e.data {
2190            CachedData::Rows(r) => Some(r.clone()),
2191            CachedData::Columns(_) => None,
2192        });
2193        if res.is_some() {
2194            self.touch(key);
2195            self.memory_hit
2196                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2197            return res;
2198        }
2199        // Memory miss → try the persistent tier (b).
2200        if let Some(entry) = self.load_from_disk(key, identity) {
2201            let res = match &entry.data {
2202                CachedData::Rows(r) => Some(r.clone()),
2203                CachedData::Columns(_) => None,
2204            };
2205            if res.is_some() {
2206                let approx = entry.data.approx_bytes();
2207                self.bytes = self.bytes.saturating_add(approx);
2208                self.index_entry(key, &entry);
2209                self.entries.insert(key, entry);
2210                self.touch(key);
2211                self.evict();
2212                self.disk_hit
2213                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2214                return res;
2215            }
2216        }
2217        self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2218        None
2219    }
2220
2221    fn get_columns(
2222        &mut self,
2223        key: u64,
2224        identity: PersistentCacheIdentity,
2225    ) -> Option<Arc<Vec<(u16, columnar::NativeColumn)>>> {
2226        let res = self.entries.get(&key).and_then(|e| match &e.data {
2227            CachedData::Columns(c) => Some(c.clone()),
2228            CachedData::Rows(_) => None,
2229        });
2230        if res.is_some() {
2231            self.touch(key);
2232            self.memory_hit
2233                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2234            return res;
2235        }
2236        // Memory miss → try the persistent tier (b).
2237        if let Some(entry) = self.load_from_disk(key, identity) {
2238            let res = match &entry.data {
2239                CachedData::Columns(c) => Some(c.clone()),
2240                CachedData::Rows(_) => None,
2241            };
2242            if res.is_some() {
2243                let approx = entry.data.approx_bytes();
2244                self.bytes = self.bytes.saturating_add(approx);
2245                self.index_entry(key, &entry);
2246                self.entries.insert(key, entry);
2247                self.touch(key);
2248                self.evict();
2249                self.disk_hit
2250                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2251                return res;
2252            }
2253        }
2254        self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2255        None
2256    }
2257
2258    /// In-memory insert only. Persistent publication is the caller's job —
2259    /// they call `persist_entry(context, &entry)` (or the legacy
2260    /// `enqueue_persist` for the async path) before this method so the on-
2261    /// disk frame and the in-memory copy can never diverge.
2262    fn insert(&mut self, key: u64, entry: CachedEntry) {
2263        let approx = entry.data.approx_bytes();
2264        if let Some(previous) = self.entries.remove(&key) {
2265            self.bytes = self.bytes.saturating_sub(previous.data.approx_bytes());
2266            self.unindex_entry(key, &previous);
2267            self.untrack(key);
2268        }
2269        self.bytes = self.bytes.saturating_add(approx);
2270        self.index_entry(key, &entry);
2271        self.entries.insert(key, entry);
2272        self.touch(key);
2273        self.evict();
2274    }
2275
2276    /// Persist `entry` using the MLCP frame format (REM-002 §18.3). When
2277    /// the async writer is installed the op is enqueued; when publication is
2278    /// unavailable the entry stays in the in-memory tier and the skip is
2279    /// counted (REM-D §8.5). The query thread never performs disk I/O here.
2280    /// No-op when the entry is below the persistence threshold.
2281    fn persist_entry(&self, context: PersistContext, entry: &CachedEntry) {
2282        let approx = entry.data.approx_bytes();
2283        if self.dir.is_none() {
2284            return;
2285        }
2286        if self.persist_min_bytes > 0 && approx < self.persist_min_bytes {
2287            return;
2288        }
2289        match &self.persistence {
2290            PersistentPublicationState::Async(writer) => {
2291                // Async path: enqueue a `PersistableEntry`. The worker calls
2292                // the same `encode_persisted_entry` helper so the on-disk
2293                // format is byte-for-byte identical to the sync path.
2294                let entry_clone = entry.clone_for_persist();
2295                let payload_factory: Box<dyn FnOnce() -> Option<Vec<u8>> + Send + 'static> =
2296                    Box::new(move || {
2297                        bincode::serialize(&SerializedEntryRef::from_entry(&entry_clone)).ok()
2298                    });
2299                let persistable = crate::result_cache::PersistableEntry {
2300                    key: context.key,
2301                    table_id: context.identity.table_id,
2302                    schema_id: context.identity.schema_id,
2303                    run_generation: context.identity.logical_generation,
2304                    entry_generation: context.entry_generation,
2305                    bytes: approx as usize,
2306                    payload_factory,
2307                };
2308                let write_start = std::time::Instant::now();
2309                writer.enqueue_store(persistable);
2310                let write_us = write_start.elapsed().as_micros() as u64;
2311                self.persistent_write_us
2312                    .fetch_add(write_us, std::sync::atomic::Ordering::Relaxed);
2313            }
2314            PersistentPublicationState::Disabled(reason) => {
2315                // Publication unavailable: keep the in-memory entry, skip the
2316                // persistent write, and make the skip observable (REM-D
2317                // §8.5). The persistent cache is disposable optimization
2318                // state; the next miss simply recomputes.
2319                self.persist_skipped_total
2320                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2321                crate::trace::QueryTrace::record(|trace| {
2322                    trace.result_cache_persist_skipped = true;
2323                    trace.result_cache_persist_skip_reason = Some(reason.label());
2324                });
2325            }
2326        }
2327    }
2328
2329    /// Allocate a fresh per-key entry generation. The generation is what
2330    /// the worker compares against the writer's queue to decide whether a
2331    /// store is still current. A newer invalidation that arrives after the
2332    /// generation was issued supersedes the queued store.
2333    fn allocate_persist_generation(&mut self, key: u64) -> u64 {
2334        if let Some(writer) = self.persistent_writer() {
2335            // Bump the global per-key generation on the writer so a
2336            // subsequent store for the same key is observed as fresh.
2337            let _ = key; // the writer tracks per-key generations internally
2338            writer.bump_persist_generation(key)
2339        } else {
2340            0
2341        }
2342    }
2343
2344    /// Enqueue a `Remove` to the background writer. No-op when no writer is
2345    /// installed.
2346    fn enqueue_persist_remove(&self, key: u64) {
2347        if let Some(writer) = self.persistent_writer() {
2348            writer.enqueue_remove(key);
2349        }
2350    }
2351
2352    /// Enqueue a `Clear` to the background writer. No-op when no writer is
2353    /// installed. Bumping the writer's `clear_generation` is the
2354    /// "shutdown generation" required by REM-002 §18.6 — any in-flight
2355    /// write that re-checks staleness right before publish is then
2356    /// observed as stale and dropped instead of becoming a late durable
2357    /// entry.
2358    fn enqueue_persist_clear(&self) {
2359        if let Some(writer) = self.persistent_writer() {
2360            writer.enqueue_clear();
2361        }
2362    }
2363
2364    /// Drain the writer's queue synchronously until empty or `deadline`
2365    /// expires. The caller invokes this on `Database::close` or before a
2366    /// checkpoint; the worker keeps running and the queue depth is checked
2367    /// between drains. Returns the queue depth at the moment of the call
2368    /// return.
2369    fn flush_persistent_cache(&self, deadline: std::time::Duration) -> u64 {
2370        let Some(writer) = self.persistent_writer() else {
2371            return 0;
2372        };
2373        let start = std::time::Instant::now();
2374        loop {
2375            let depth = writer.queue_depth() as u64;
2376            // Wait until the queue is empty AND no dequeued op is unfinished.
2377            // The worker counts an op as in flight from the moment it leaves
2378            // the queue, including the staleness check before I/O. Observing
2379            // both counters at zero means the directory rename has finished,
2380            // not merely that the op was popped.
2381            let in_flight = writer.writes_in_flight();
2382            if depth == 0 && in_flight == 0 {
2383                return 0;
2384            }
2385            if start.elapsed() >= deadline {
2386                return depth;
2387            }
2388            std::thread::sleep(std::time::Duration::from_millis(2));
2389        }
2390    }
2391
2392    /// Shut the writer down. The worker drains remaining ops until the
2393    /// queue is empty or `deadline` expires; any ops still queued are
2394    /// counted as abandoned. The completion signal is waited on with the
2395    /// *remaining* deadline (REM-002 §18.6) — if it does not arrive in
2396    /// time, the timeout counter is bumped and the worker is detached
2397    /// (its `Arc`-shared state keeps it safe to outlive this method).
2398    /// Publication transitions to `Disabled(WorkerShutdown)` so subsequent
2399    /// `persist_entry` calls skip persistent publication with a metric
2400    /// instead of falling back to synchronous query-thread I/O (REM-D §8.5).
2401    fn shutdown_persistent_cache(&mut self, deadline: std::time::Duration) {
2402        let start = Instant::now();
2403        // Phase 1: wait for the queue to drain or the deadline to expire.
2404        if let Some(writer) = self.persistent_writer() {
2405            loop {
2406                if writer.queue_depth() == 0 {
2407                    break;
2408                }
2409                if start.elapsed() >= deadline {
2410                    break;
2411                }
2412                std::thread::sleep(std::time::Duration::from_millis(2));
2413            }
2414        }
2415        // Phase 2: mark the writer closed. `enqueue_clear` advances the
2416        // global clear_generation so the worker's final staleness check
2417        // (right before publish) aborts any late in-flight write.
2418        let writer = self.persistent_writer().cloned();
2419        if let Some(writer) = writer.as_ref() {
2420            writer.shutdown();
2421            let _ = writer.drain_all_as_abandoned();
2422        }
2423        // Phase 3: wait for the completion signal with the *remaining*
2424        // deadline. `JoinHandle::join` has no timed variant, so we use
2425        // the channel as the deadline-bounded wait point. If the worker
2426        // is blocked in filesystem I/O, the recv returns Err on timeout
2427        // and we detach the handle (state is `Arc`-shared, so the worker
2428        // can still complete safely).
2429        let mut completion = self.take_persistent_completion();
2430        let completed = if let (Some(rx), Some(_writer)) = (completion.as_mut(), writer.as_ref()) {
2431            let elapsed = start.elapsed();
2432            let remaining = deadline.saturating_sub(elapsed);
2433            crate::result_cache::recv_completion_with_timeout(rx, remaining)
2434        } else {
2435            true
2436        };
2437        if completed {
2438            if let Some(handle) = self.take_persistent_worker() {
2439                let _ = handle.join();
2440            }
2441            // Drain any signal we did not consume.
2442            drop(completion.take());
2443        } else {
2444            // Timeout: bump the abandoned counter and detach the handle.
2445            // The worker is still running and may eventually finish; the
2446            // in-flight I/O either completes or fails on its own.
2447            if let Some(writer) = writer.as_ref() {
2448                writer.record_outcome(DrainOutcome::Abandoned);
2449            }
2450            self.take_persistent_worker(); // drop the handle, do not join
2451        }
2452        // Transition publication to `Disabled(WorkerShutdown)`: subsequent
2453        // inserts keep their in-memory entry and skip persistent publication
2454        // (REM-D §8.5). The transition and the shutdown are both counted.
2455        if matches!(self.persistence, PersistentPublicationState::Async(_)) {
2456            self.worker_shutdown_total
2457                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2458            self.persist_unavailable_total
2459                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2460            self.persistence =
2461                PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerShutdown);
2462        }
2463    }
2464
2465    /// Set the minimum entry size (approx bytes) before the persistent tier
2466    /// is written. 0 always persists. Exposed as a `pub(crate)` so the test
2467    /// seam on `Table` can drive sub-4KiB fixtures through the on-disk path.
2468    pub(crate) fn set_persist_min_bytes(&mut self, min: u64) {
2469        self.persist_min_bytes = min;
2470    }
2471
2472    /// True when the last insert of an entry of size `approx` would hit disk.
2473    #[cfg(test)]
2474    fn would_persist(&self, approx: u64) -> bool {
2475        self.dir.is_some() && (self.persist_min_bytes == 0 || approx >= self.persist_min_bytes)
2476    }
2477
2478    /// Read the per-tier counters. Returned as `(memory_hit, disk_hit, miss,
2479    /// persistent_write_us)` so callers can roll them into their own snapshot.
2480    fn cache_counters(&self) -> (u64, u64, u64, u64) {
2481        (
2482            self.memory_hit.load(std::sync::atomic::Ordering::Relaxed),
2483            self.disk_hit.load(std::sync::atomic::Ordering::Relaxed),
2484            self.miss.load(std::sync::atomic::Ordering::Relaxed),
2485            self.persistent_write_us
2486                .load(std::sync::atomic::Ordering::Relaxed),
2487        )
2488    }
2489
2490    /// Read the REM-D §8.7 publication-availability counters. Returned as
2491    /// `(persist_unavailable_total, persist_skipped_total,
2492    /// worker_spawn_failures_total, worker_shutdown_total)`.
2493    fn publication_counters(&self) -> (u64, u64, u64, u64) {
2494        (
2495            self.persist_unavailable_total
2496                .load(std::sync::atomic::Ordering::Relaxed),
2497            self.persist_skipped_total
2498                .load(std::sync::atomic::Ordering::Relaxed),
2499            self.worker_spawn_failures_total
2500                .load(std::sync::atomic::Ordering::Relaxed),
2501            self.worker_shutdown_total
2502                .load(std::sync::atomic::Ordering::Relaxed),
2503        )
2504    }
2505
2506    /// Snapshot of the writer's persist counters. `None` when no writer is
2507    /// installed (publication disabled).
2508    fn persist_snapshot(&self) -> Option<LookupMetricsSnapshot> {
2509        self.persistent_writer().map(|w| w.persist_snapshot())
2510    }
2511
2512    /// Fine-grained invalidation (hardening (c)). Drop only entries that are
2513    /// actually affected by the committed mutations:
2514    /// - **Delete path**: if `delete_rids` intersects an entry's footprint, a
2515    ///   survivor was deleted → stale. If the footprint is empty (multi-run or
2516    ///   non-empty memtable — we couldn't resolve it), **any** delete
2517    ///   conservatively invalidates the entry (correctness over precision).
2518    /// - **Insert path**: if `put_cols` intersects an entry's `condition_cols`,
2519    ///   a newly-inserted row might match the query → conservatively stale.
2520    fn invalidate(
2521        &mut self,
2522        delete_rids: &roaring::RoaringBitmap,
2523        put_cols: &std::collections::HashSet<u16>,
2524    ) {
2525        if self.entries.is_empty() {
2526            return;
2527        }
2528        let has_deletes = !delete_rids.is_empty();
2529        let mut to_remove = HashSet::new();
2530
2531        // Inserts/updates are the common mutation path. Resolve affected cache
2532        // keys directly from the condition-column reverse index instead of
2533        // scanning every cached result on every commit.
2534        for column in put_cols {
2535            if let Some(keys) = self.condition_index.get(column) {
2536                to_remove.extend(keys.iter().copied());
2537            }
2538        }
2539
2540        if has_deletes {
2541            // Entries with an unknown footprint are conservatively stale after
2542            // any delete. Known footprints still require a bitmap intersection;
2543            // this scan is paid only by delete commits, not every insert.
2544            to_remove.extend(self.empty_footprint_entries.iter().copied());
2545            for (&key, entry) in &self.entries {
2546                if !to_remove.contains(&key)
2547                    && !entry.footprint.is_empty()
2548                    && entry.footprint.intersection_len(delete_rids) > 0
2549                {
2550                    to_remove.insert(key);
2551                }
2552            }
2553        }
2554
2555        for key in to_remove {
2556            if let Some(entry) = self.entries.remove(&key) {
2557                self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2558                self.unindex_entry(key, &entry);
2559            }
2560            // When a background writer is installed, the on-disk file is
2561            // removed asynchronously by the worker; otherwise, fall back to
2562            // the legacy synchronous `remove_from_disk` so early test paths
2563            // (which build a `ResultCache` directly) keep working.
2564            if self.persistent_writer().is_some() {
2565                self.enqueue_persist_remove(key);
2566            } else {
2567                self.remove_from_disk(key);
2568            }
2569            self.untrack(key);
2570        }
2571    }
2572
2573    fn clear(&mut self) {
2574        // Delete all persistent files (b). When a background writer is
2575        // installed, the on-disk files are removed asynchronously by the
2576        // worker; otherwise, fall back to the legacy synchronous scan.
2577        if self.dir.is_some() {
2578            if self.persistent_writer().is_some() {
2579                self.enqueue_persist_clear();
2580            } else if let Some(dir) = &self.dir {
2581                if let Ok(entries) = std::fs::read_dir(dir) {
2582                    for entry in entries.flatten() {
2583                        let path = entry.path();
2584                        if path.extension().and_then(|e| e.to_str()) == Some("bin") {
2585                            let _ = std::fs::remove_file(&path);
2586                        }
2587                    }
2588                }
2589            }
2590        }
2591        self.entries.clear();
2592        self.order.clear();
2593        self.generations.clear();
2594        self.next_generation = 0;
2595        self.condition_index.clear();
2596        self.empty_footprint_entries.clear();
2597        self.bytes = 0;
2598    }
2599
2600    fn evict(&mut self) {
2601        while self.bytes > self.max_bytes {
2602            let Some((_, key)) = self.order.pop_first() else {
2603                break;
2604            };
2605            self.generations.remove(&key);
2606            if let Some(entry) = self.entries.remove(&key) {
2607                self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2608                self.unindex_entry(key, &entry);
2609                // The on-disk file is left in place. The persistent
2610                // loader validates the frame's `logical_generation` on
2611                // every load (REM-002 §18.4), so a stale file from a
2612                // pre-commit epoch is rejected as `GenerationMismatch` and
2613                // deleted on read. Deleting the file at eviction time
2614                // would defeat the "memory eviction → disk hit" path
2615                // exercised by the production tests.
2616            }
2617        }
2618    }
2619}
2620
2621/// Set up the persistent-publication writer for a fresh `ResultCache`. The
2622/// returned tuple is `(writer, worker_join_handle, completion_receiver)`;
2623/// pass `writer` and `worker_join_handle` to
2624/// [`ResultCache::install_persistent_writer`], and the `completion_receiver`
2625/// to the cache so `shutdown_persistent_cache(deadline)` can wait on a
2626/// bounded deadline. The caller is responsible for joining the worker on
2627/// `shutdown_persistent_cache(deadline)`.
2628fn spawn_persistent_cache_worker(
2629    dir: std::path::PathBuf,
2630    cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
2631    metrics: LookupMetrics,
2632) -> std::io::Result<(
2633    std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
2634    std::thread::JoinHandle<()>,
2635    std::sync::mpsc::Receiver<()>,
2636)> {
2637    use crate::result_cache::{
2638        spawn_persistent_cache_worker as spawn, RealPersistentCacheIo, StalenessGuard,
2639        WorkerConfig, WriterStalenessGuard,
2640    };
2641    // Test seam (REM-D §8.8): force worker startup failure through the real
2642    // `Table::create` / `Table::open` wiring. Thread-local so parallel tests
2643    // in the same process are unaffected.
2644    if PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.get()) {
2645        return Err(std::io::Error::other(
2646            "persistent-cache worker spawn failure forced by test seam",
2647        ));
2648    }
2649    let io: std::sync::Arc<dyn crate::result_cache::PersistentCacheIo> =
2650        std::sync::Arc::new(RealPersistentCacheIo::new(dir)?);
2651    let cipher = match cache_dek {
2652        Some(dek) => {
2653            let cipher = crate::encryption::AesCipher::new(&dek[..])
2654                .map_err(|e| std::io::Error::other(format!("aes: {e}")))?;
2655            Some(std::sync::Arc::new(cipher))
2656        }
2657        None => None,
2658    };
2659    let writer = std::sync::Arc::new(crate::result_cache::PersistentResultCacheWriter::new(
2660        metrics,
2661        crate::result_cache::WriterLimits::default(),
2662    ));
2663    let staleness: std::sync::Arc<dyn StalenessGuard> =
2664        std::sync::Arc::new(WriterStalenessGuard::new(writer.clone()));
2665    let (completion_tx, completion_rx) = std::sync::mpsc::channel();
2666    let config = WorkerConfig {
2667        writer: writer.clone(),
2668        io,
2669        cipher,
2670        staleness,
2671        max_staleness_retries: 8,
2672        completion: Some(completion_tx),
2673    };
2674    let handle = spawn(config);
2675    Ok((writer, handle, completion_rx))
2676}
2677
2678thread_local! {
2679    /// Thread-local test seam (REM-D §8.8): when set,
2680    /// [`spawn_persistent_cache_worker`] fails deterministically so tests can
2681    /// exercise the "worker startup failure" path through the real
2682    /// `Table::create` / `Table::open` wiring. Thread-local so concurrently
2683    /// running tests are unaffected. Reset by
2684    /// [`Table::_force_persistent_worker_spawn_failure_for_test`].
2685    static PERSISTENT_WORKER_SPAWN_FAILURE: std::cell::Cell<bool> =
2686        const { std::cell::Cell::new(false) };
2687}
2688
2689#[cfg(test)]
2690mod result_cache_lru_tests {
2691    use super::*;
2692
2693    fn row_entry(row_id: u64) -> CachedEntry {
2694        CachedEntry {
2695            data: CachedData::Rows(Arc::new(vec![Row::new(RowId(row_id), Epoch(1))])),
2696            footprint: std::iter::once(row_id as u32).collect(),
2697            condition_cols: vec![1],
2698        }
2699    }
2700
2701    #[test]
2702    fn hits_update_recency_without_growing_an_order_queue() {
2703        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2704        let identity = PersistentCacheIdentity {
2705            table_id: 0,
2706            schema_id: 0,
2707            logical_generation: 0,
2708        };
2709        cache.insert(1, row_entry(1));
2710        cache.insert(2, row_entry(2));
2711        assert_eq!(cache.order.len(), cache.entries.len());
2712
2713        for _ in 0..1_000 {
2714            assert!(cache.get_rows(1, identity).is_some());
2715        }
2716
2717        assert_eq!(cache.order.len(), cache.entries.len());
2718        assert_eq!(cache.order.first().map(|(_, key)| *key), Some(2));
2719
2720        let one_entry = cache.entries[&1].data.approx_bytes();
2721        cache.set_max_bytes(one_entry);
2722        assert!(cache.entries.contains_key(&1));
2723        assert!(!cache.entries.contains_key(&2));
2724        assert_eq!(cache.order.len(), cache.entries.len());
2725    }
2726
2727    #[test]
2728    fn tiny_entries_skip_persistent_tier_by_default() {
2729        let dir = tempfile::tempdir().unwrap();
2730        let mut cache = ResultCache::with_max_bytes(u64::MAX).with_dir(dir.path().to_path_buf());
2731        let tiny = row_entry(1).data.approx_bytes();
2732        assert!(
2733            tiny < 4 * 1024,
2734            "row_entry fixture must be below default 4KiB threshold"
2735        );
2736        assert!(
2737            !cache.would_persist(tiny),
2738            "tiny entry must not force synchronous disk publish"
2739        );
2740        assert!(
2741            cache.would_persist(8 * 1024),
2742            "large entry must still persist when dir is set"
2743        );
2744        cache.set_persist_min_bytes(0);
2745        assert!(
2746            cache.would_persist(tiny),
2747            "persist_min_bytes=0 restores always-persist policy"
2748        );
2749    }
2750
2751    #[test]
2752    fn insert_invalidation_uses_the_condition_reverse_index() {
2753        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2754        let mut first = row_entry(1);
2755        first.condition_cols = vec![1];
2756        let mut second = row_entry(2);
2757        second.condition_cols = vec![2];
2758        cache.insert(1, first);
2759        cache.insert(2, second);
2760
2761        let put_cols = std::iter::once(1_u16).collect();
2762        cache.invalidate(&roaring::RoaringBitmap::new(), &put_cols);
2763
2764        assert!(!cache.entries.contains_key(&1));
2765        assert!(cache.entries.contains_key(&2));
2766        assert!(!cache
2767            .condition_index
2768            .get(&1)
2769            .is_some_and(|keys| keys.contains(&1)));
2770        assert!(cache
2771            .condition_index
2772            .get(&2)
2773            .is_some_and(|keys| keys.contains(&2)));
2774        assert_eq!(cache.order.len(), cache.entries.len());
2775    }
2776
2777    #[test]
2778    fn delete_invalidation_preserves_known_and_unknown_footprint_semantics() {
2779        let mut cache = ResultCache::with_max_bytes(u64::MAX);
2780        cache.insert(1, row_entry(1));
2781        cache.insert(2, row_entry(2));
2782        let mut unknown = row_entry(3);
2783        unknown.footprint.clear();
2784        cache.insert(3, unknown);
2785
2786        let delete_rids: roaring::RoaringBitmap = std::iter::once(1_u32).collect();
2787        cache.invalidate(&delete_rids, &HashSet::new());
2788
2789        assert!(!cache.entries.contains_key(&1));
2790        assert!(cache.entries.contains_key(&2));
2791        assert!(!cache.entries.contains_key(&3));
2792        assert!(cache.empty_footprint_entries.is_empty());
2793        assert_eq!(cache.order.len(), cache.entries.len());
2794    }
2795
2796    #[test]
2797    fn borrowed_persistence_encoding_matches_the_existing_owned_format() {
2798        let entry = row_entry(7);
2799        let borrowed = bincode::serialize(&SerializedEntryRef::from_entry(&entry)).unwrap();
2800        let owned = bincode::serialize(&SerializedEntry {
2801            condition_cols: entry.condition_cols.clone(),
2802            footprint_bits: entry.footprint.iter().collect(),
2803            data: match &entry.data {
2804                CachedData::Rows(rows) => SerializedData::Rows((**rows).clone()),
2805                CachedData::Columns(columns) => SerializedData::Columns((**columns).clone()),
2806            },
2807        })
2808        .unwrap();
2809        assert_eq!(borrowed, owned);
2810    }
2811}
2812
2813/// Derive per-column indexable-encryption keys (Phase 10.2) for every
2814/// ENCRYPTED_INDEXABLE column from the KEK. Scheme is `OPE_RANGE` if the column
2815/// has a `LearnedRange` index, else `HMAC_EQ` (equality). Keys are derived
2816/// deterministically from the KEK so tokens are stable across runs. Empty when
2817/// the table is plaintext (no KEK).
2818/// Derive WAL and cache DEKs from the KEK (None when no encryption).
2819type DekaOpt = Option<Zeroizing<[u8; DEK_LEN]>>;
2820
2821fn derive_subkeys(kek: Option<&Kek>, _table_id: u64) -> (DekaOpt, DekaOpt) {
2822    let _ = kek;
2823    {
2824        if let Some(k) = kek {
2825            return (
2826                Some(k.derive_table_wal_key(_table_id)),
2827                Some(k.derive_cache_key()),
2828            );
2829        }
2830    }
2831    (None, None)
2832}
2833
2834fn read_table_encryption_salt_root(
2835    root: &crate::durable_file::DurableRoot,
2836) -> Result<[u8; crate::encryption::SALT_LEN]> {
2837    use std::io::Read;
2838
2839    let mut file = root
2840        .open_regular(Path::new(META_DIR).join(KEYS_FILENAME))
2841        .map_err(|error| MongrelError::NotFound(format!("encryption salt file: {error}")))?;
2842    let length = file.metadata()?.len();
2843    if length != crate::encryption::SALT_LEN as u64 {
2844        return Err(MongrelError::InvalidArgument(format!(
2845            "salt file is {length} bytes, expected {}",
2846            crate::encryption::SALT_LEN
2847        )));
2848    }
2849    let mut salt = [0_u8; crate::encryption::SALT_LEN];
2850    file.read_exact(&mut salt)?;
2851    Ok(salt)
2852}
2853
2854/// Create a boxed cipher from a DEK.
2855fn make_cipher(dek: &Zeroizing<[u8; DEK_LEN]>) -> Box<dyn crate::encryption::Cipher> {
2856    Box::new(crate::encryption::AesCipher::new(&dek[..]).expect("DEK is 32 bytes"))
2857}
2858
2859fn build_column_keys(kek: Option<&Kek>, schema: &Schema) -> HashMap<u16, ([u8; 32], u8)> {
2860    let Some(kek) = kek else {
2861        return HashMap::new();
2862    };
2863    {
2864        use crate::encryption::{SCHEME_HMAC_EQ, SCHEME_OPE_RANGE};
2865        schema
2866            .columns
2867            .iter()
2868            .filter(|c| c.flags.contains(ColumnFlags::ENCRYPTED_INDEXABLE))
2869            .map(|c| {
2870                let scheme = if schema
2871                    .indexes
2872                    .iter()
2873                    .any(|i| i.column_id == c.id && i.kind == IndexKind::LearnedRange)
2874                {
2875                    SCHEME_OPE_RANGE
2876                } else {
2877                    SCHEME_HMAC_EQ
2878                };
2879                let key: [u8; 32] = *kek.derive_column_key(c.id);
2880                (c.id, (key, scheme))
2881            })
2882            .collect()
2883    }
2884}
2885
2886/// Shared services injected into every `Table` owned by a `Database`: one epoch
2887/// authority (single commit clock), one raw-page cache, one decoded-page cache,
2888/// one snapshot-retention registry, and the DB-wide KEK. A directly-opened
2889/// single table builds a private `SharedCtx` of its own.
2890pub(crate) struct SharedCtx {
2891    pub root_guard: Option<Arc<crate::durable_file::DurableRoot>>,
2892    pub epoch: Arc<EpochAuthority>,
2893    pub page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
2894    pub decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
2895    pub snapshots: Arc<crate::retention::SnapshotRegistry>,
2896    pub kek: Option<Arc<Kek>>,
2897    /// Serializes the commit critical section across all tables sharing this
2898    /// context so the dual-counter's in-order-publish invariant holds: the
2899    /// assigned ticket is reserved, the WAL fsynced, the manifest persisted,
2900    /// and `visible` published as one atomic unit. P3 replaces this with the
2901    /// bounded validate-first sequencer + group commit (overlapping fsync).
2902    pub commit_lock: Arc<parking_lot::Mutex<()>>,
2903    /// B1: when `Some`, the table is mounted in a `Database` and routes every
2904    /// write through the one shared WAL (no private `_wal/` dir is created).
2905    /// `None` for a directly-opened standalone table, which keeps a private WAL.
2906    pub shared: Option<SharedWalCtx>,
2907    /// The table's catalog name (for auth enforcement). `None` on standalone
2908    /// direct-open tables that have no catalog entry.
2909    pub table_name: Option<String>,
2910    /// Auth checker for per-operation enforcement. `None` on credentialless
2911    /// databases; cloned from the `Database`'s `auth_state` wrapper.
2912    pub auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
2913    /// Whether logical writes must be rejected for a replica database.
2914    pub read_only: bool,
2915}
2916
2917/// Handles a mounted table needs to write to the database's single shared WAL
2918/// (B1): the WAL itself, the group-commit coordinator + poison flag (so a
2919/// single-table commit honors the same durability/§9.3e semantics as a cross-
2920/// table txn), and the shared txn-id allocator (so auto-commit ids never alias
2921/// cross-table ones in the merged log).
2922#[derive(Clone)]
2923pub(crate) struct SharedWalCtx {
2924    pub wal: Arc<parking_lot::Mutex<SharedWal>>,
2925    pub group: Arc<GroupCommit>,
2926    pub poisoned: Arc<AtomicBool>,
2927    pub txn_ids: Arc<parking_lot::Mutex<u64>>,
2928    pub change_wake: tokio::sync::broadcast::Sender<()>,
2929    /// S1A-004: the owning core's lifecycle, poisoned at every fsync-error
2930    /// site so the whole core rejects later operations.
2931    pub lifecycle: Arc<crate::core::LifecycleController>,
2932    /// Database HLC clock used to stamp single-table commit row versions (P0.5).
2933    pub hlc: Arc<mongreldb_types::hlc::HlcClock>,
2934}
2935
2936/// Where a table's WAL records go. A standalone table owns a `Private` WAL; a
2937/// `Database`-mounted table writes to the one `Shared` WAL (B1).
2938enum WalSink {
2939    Private(Wal),
2940    Shared(SharedWalCtx),
2941    ReadOnly,
2942}
2943
2944impl Clone for WalSink {
2945    fn clone(&self) -> Self {
2946        match self {
2947            Self::Shared(shared) => Self::Shared(shared.clone()),
2948            Self::Private(_) | Self::ReadOnly => Self::ReadOnly,
2949        }
2950    }
2951}
2952
2953impl SharedCtx {
2954    /// Build a fresh private (standalone) context. `cache_dir = Some(_)` enables
2955    /// on-disk page cache persistence (single-table direct open); `None` keeps
2956    /// it in-memory (shared across tables in a `Database`).
2957    pub(crate) fn new(kek: Option<Arc<Kek>>, cache_dir: Option<PathBuf>) -> Self {
2958        // §5.8: shard the caches to reduce lock contention under parallel
2959        // rayon scans. The persistent (single-table) path uses 1 shard (no
2960        // contention) so its on-disk load/spill stays simple.
2961        let n_shards = if cache_dir.is_some() {
2962            1
2963        } else {
2964            crate::cache::CACHE_SHARDS
2965        };
2966        let per_shard = PAGE_CACHE_CAPACITY / n_shards as u64;
2967        let page_cache = if let Some(d) = cache_dir {
2968            Arc::new(crate::cache::Sharded::new(1, || {
2969                crate::cache::PageCache::new(PAGE_CACHE_CAPACITY).with_persistence(d.clone())
2970            }))
2971        } else {
2972            Arc::new(crate::cache::Sharded::new(n_shards, || {
2973                crate::cache::PageCache::new(per_shard)
2974            }))
2975        };
2976        let decoded_per_shard = DECODED_CACHE_CAPACITY / crate::cache::CACHE_SHARDS as u64;
2977        let decoded_cache = Arc::new(crate::cache::Sharded::new(
2978            crate::cache::CACHE_SHARDS,
2979            || crate::cache::DecodedPageCache::new(decoded_per_shard),
2980        ));
2981        Self {
2982            root_guard: None,
2983            epoch: Arc::new(EpochAuthority::new(0)),
2984            page_cache,
2985            decoded_cache,
2986            snapshots: Arc::new(crate::retention::SnapshotRegistry::new()),
2987            kek,
2988            commit_lock: Arc::new(parking_lot::Mutex::new(())),
2989            shared: None,
2990            table_name: None,
2991            auth: None,
2992            read_only: false,
2993        }
2994    }
2995}
2996
2997/// §5.5: estimated per-condition resolution cost for cheap-first conjunction
2998/// ordering. Lower is resolved first so a selective O(1) index lookup can
2999/// short-circuit an expensive range/FM/vector scan.
3000fn condition_cost_rank(c: &crate::query::Condition) -> u8 {
3001    use crate::query::Condition;
3002    match c {
3003        // O(1) index lookups — resolve first.
3004        Condition::Pk(_)
3005        | Condition::BitmapEq { .. }
3006        | Condition::BitmapIn { .. }
3007        | Condition::BytesPrefix { .. }
3008        | Condition::IsNull { .. }
3009        | Condition::IsNotNull { .. } => 0,
3010        // Page-pruned scan or LSH candidate lookup.
3011        Condition::Range { .. } | Condition::RangeF64 { .. } | Condition::MinHashSimilar { .. } => {
3012            1
3013        }
3014        // FM locate / vector scans — most expensive, resolve last.
3015        Condition::FmContains { .. }
3016        | Condition::FmContainsAll { .. }
3017        | Condition::Ann { .. }
3018        | Condition::SparseMatch { .. } => 2,
3019    }
3020}
3021
3022impl Table {
3023    /// Build one hidden secondary index from authoritative visible rows.
3024    /// Callers run this against a pinned read generation, outside the final
3025    /// publication barrier. `checkpoint` supplies cooperative cancellation,
3026    /// resource checks, and progress reporting without coupling the engine to
3027    /// the jobs framework.
3028    pub(crate) fn build_secondary_index_artifact<F>(
3029        &self,
3030        definition: &IndexDef,
3031        rows: &[Row],
3032        mut checkpoint: F,
3033    ) -> Result<SecondaryIndexArtifact>
3034    where
3035        F: FnMut(usize, usize) -> Result<()>,
3036    {
3037        let mut build_schema = self.schema.clone();
3038        build_schema.indexes = vec![definition.clone()];
3039        let (mut bitmap, mut ann, mut fm, mut sparse, mut minhash) = empty_indexes(&build_schema);
3040        let name_to_id: HashMap<&str, u16> = self
3041            .schema
3042            .columns
3043            .iter()
3044            .map(|column| (column.name.as_str(), column.id))
3045            .collect();
3046        let mut hot = HotIndex::new();
3047        let mut accepted = Vec::with_capacity(rows.len());
3048
3049        for (offset, row) in rows.iter().enumerate() {
3050            checkpoint(offset, rows.len())?;
3051            if row.deleted {
3052                continue;
3053            }
3054            if let Some(predicate) = &definition.predicate {
3055                let columns: HashMap<u16, &Value> =
3056                    row.columns.iter().map(|(id, value)| (*id, value)).collect();
3057                if !eval_partial_predicate(predicate, &columns, &name_to_id) {
3058                    continue;
3059                }
3060            }
3061            accepted.push(row);
3062            if definition.kind == IndexKind::LearnedRange {
3063                continue;
3064            }
3065            let effective = if self.column_keys.is_empty() {
3066                row.clone()
3067            } else {
3068                self.tokenized_for_indexes(row)
3069            };
3070            if definition.kind == IndexKind::Ann {
3071                if let (Some(index), Some(vector)) = (
3072                    ann.get_mut(&definition.column_id),
3073                    effective
3074                        .columns
3075                        .get(&definition.column_id)
3076                        .and_then(Value::as_embedding),
3077                ) {
3078                    index.insert_validated_with_checkpoint(vector, effective.row_id, || {
3079                        checkpoint(offset, rows.len())
3080                    })?;
3081                }
3082            } else {
3083                index_into_single(
3084                    definition,
3085                    &build_schema,
3086                    &effective,
3087                    &mut hot,
3088                    &mut bitmap,
3089                    &mut ann,
3090                    &mut fm,
3091                    &mut sparse,
3092                    &mut minhash,
3093                );
3094            }
3095        }
3096        checkpoint(rows.len(), rows.len())?;
3097
3098        if let Some(index) = ann.get_mut(&definition.column_id) {
3099            index.seal_with_checkpoint(|| checkpoint(rows.len(), rows.len()))?;
3100        }
3101
3102        let column_id = definition.column_id;
3103        match definition.kind {
3104            IndexKind::Bitmap => bitmap
3105                .remove(&column_id)
3106                .map(|index| SecondaryIndexArtifact::Bitmap(column_id, index)),
3107            IndexKind::Ann => ann
3108                .remove(&column_id)
3109                .map(|index| SecondaryIndexArtifact::Ann(column_id, Box::new(index))),
3110            IndexKind::FmIndex => fm
3111                .remove(&column_id)
3112                .map(|index| SecondaryIndexArtifact::Fm(column_id, Box::new(index))),
3113            IndexKind::Sparse => sparse
3114                .remove(&column_id)
3115                .map(|index| SecondaryIndexArtifact::Sparse(column_id, index)),
3116            IndexKind::MinHash => minhash
3117                .remove(&column_id)
3118                .map(|index| SecondaryIndexArtifact::MinHash(column_id, index)),
3119            IndexKind::LearnedRange => {
3120                let epsilon = definition
3121                    .options
3122                    .learned_range
3123                    .as_ref()
3124                    .map(|options| options.epsilon)
3125                    .unwrap_or(16);
3126                let column = self
3127                    .schema
3128                    .columns
3129                    .iter()
3130                    .find(|column| column.id == column_id)
3131                    .ok_or_else(|| {
3132                        MongrelError::Schema(format!(
3133                            "index {} references unknown column {column_id}",
3134                            definition.name
3135                        ))
3136                    })?;
3137                let index = match column.ty {
3138                    TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
3139                        let pairs: Vec<_> = accepted
3140                            .iter()
3141                            .filter_map(|row| match row.columns.get(&column_id) {
3142                                Some(Value::Int64(value)) if !row.deleted => {
3143                                    Some((*value, row.row_id.0))
3144                                }
3145                                _ => None,
3146                            })
3147                            .collect();
3148                        ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon)
3149                    }
3150                    TypeId::Float32 | TypeId::Float64 => {
3151                        let pairs: Vec<_> = accepted
3152                            .iter()
3153                            .filter_map(|row| match row.columns.get(&column_id) {
3154                                Some(Value::Float64(value)) if !row.deleted => {
3155                                    Some((*value, row.row_id.0))
3156                                }
3157                                _ => None,
3158                            })
3159                            .collect();
3160                        ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon)
3161                    }
3162                    ref ty => {
3163                        return Err(MongrelError::Schema(format!(
3164                            "LearnedRange index {} does not support {ty:?}",
3165                            definition.name
3166                        )));
3167                    }
3168                };
3169                Some(SecondaryIndexArtifact::LearnedRange(column_id, index))
3170            }
3171        }
3172        .ok_or_else(|| {
3173            MongrelError::Other(format!(
3174                "failed to construct hidden index {}",
3175                definition.name
3176            ))
3177        })
3178    }
3179
3180    pub fn create(dir: impl AsRef<Path>, schema: Schema, table_id: u64) -> Result<Self> {
3181        let dir = dir.as_ref().to_path_buf();
3182        // Use std::fs (no eager parent-fsync) — the deferred root's finalize
3183        // pass makes the entry durable at the end of create.
3184        std::fs::create_dir_all(&dir)?;
3185        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3186        let pinned = root.io_path()?;
3187        let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3188        ctx.root_guard = Some(root.clone());
3189        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3190        // Shallow finalize: root-level files (schema, manifest) are
3191        // data-durable, root + immediate subdirs are entry-durable. Files
3192        // inside `_wal/` and `_runs/` rely on the first commit/flush (same
3193        // contract as the pre-hardening path). Encrypted tables use the full
3194        // recursive `finalize_deferred_sync` via `create_encrypted`.
3195        root.finalize_deferred_sync_shallow()?;
3196        Ok(table)
3197    }
3198
3199    /// Create a new encrypted table, deriving the table Key-Encryption Key
3200    /// (KEK) from `passphrase` via Argon2id + HKDF (§7). A fresh random salt is
3201    /// generated and persisted under `_meta/keys` so the same passphrase
3202    /// recreates the KEK on reopen. Each run gets its own wrapped DEK.
3203    ///
3204    /// **Scope (§7):** encryption is *page-granular* — only sorted-run page
3205    /// payloads are encrypted. The live WAL (`_wal/`) holds rows as plaintext
3206    /// between `put` and `flush`; call `flush()` (which rotates the WAL) before
3207    /// treating sensitive data as fully at-rest-protected. Full WAL encryption
3208    /// is deferred.
3209    pub fn create_encrypted(
3210        dir: impl AsRef<Path>,
3211        schema: Schema,
3212        table_id: u64,
3213        passphrase: &str,
3214    ) -> Result<Self> {
3215        let dir = dir.as_ref().to_path_buf();
3216        std::fs::create_dir_all(&dir)?;
3217        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3218        root.create_directory_all(META_DIR)?;
3219        let salt = crate::encryption::random_salt()?;
3220        root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3221        let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3222        let pinned = root.io_path()?;
3223        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3224        ctx.root_guard = Some(root.clone());
3225        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3226        root.finalize_deferred_sync()?;
3227        Ok(table)
3228    }
3229
3230    /// Create a new encrypted table using a raw key (e.g. from a key file)
3231    /// instead of a passphrase. Skips Argon2id — the key must already be
3232    /// high-entropy (>= 32 bytes of random data). ~0.1ms vs ~50ms for the
3233    /// passphrase path.
3234    pub fn create_with_key(
3235        dir: impl AsRef<Path>,
3236        schema: Schema,
3237        table_id: u64,
3238        key: &[u8],
3239    ) -> Result<Self> {
3240        let dir = dir.as_ref().to_path_buf();
3241        std::fs::create_dir_all(&dir)?;
3242        let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3243        root.create_directory_all(META_DIR)?;
3244        let salt = crate::encryption::random_salt()?;
3245        root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3246        let kek: Arc<Kek> = Arc::new(Kek::from_raw_key(key, &salt)?);
3247        let pinned = root.io_path()?;
3248        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3249        ctx.root_guard = Some(root.clone());
3250        let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3251        root.finalize_deferred_sync()?;
3252        Ok(table)
3253    }
3254
3255    /// Open an existing encrypted table using a raw key.
3256    pub fn open_with_key(dir: impl AsRef<Path>, key: &[u8]) -> Result<Self> {
3257        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3258        let salt = read_table_encryption_salt_root(&root)?;
3259        let kek = Arc::new(Kek::from_raw_key(key, &salt)?);
3260        let pinned = root.io_path()?;
3261        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3262        ctx.root_guard = Some(root);
3263        Self::open_in(&pinned, ctx)
3264    }
3265
3266    pub(crate) fn create_in(
3267        dir: impl AsRef<Path>,
3268        schema: Schema,
3269        table_id: u64,
3270        ctx: SharedCtx,
3271    ) -> Result<Self> {
3272        schema.validate_auto_increment()?;
3273        schema.validate_defaults()?;
3274        schema.validate_ai()?;
3275        for index in &schema.indexes {
3276            index.validate_options()?;
3277        }
3278        let dir = dir.as_ref().to_path_buf();
3279        let runs_root = match ctx.root_guard.as_ref() {
3280            Some(root) => Some(Arc::new(root.create_directory_all_pinned(RUNS_DIR)?)),
3281            None => {
3282                crate::durable_file::create_directory_all(&dir)?;
3283                crate::durable_file::create_directory_all(&dir.join(RUNS_DIR))?;
3284                None
3285            }
3286        };
3287        match ctx.root_guard.as_deref() {
3288            Some(root) => write_schema_durable(root, &schema)?,
3289            None => write_schema(&dir, &schema)?,
3290        }
3291        let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), table_id);
3292        // B1: a mounted table routes writes through the shared WAL and never
3293        // creates its own `_wal/` dir. A standalone table owns a private WAL.
3294        let (wal, current_txn_id) = match ctx.shared.clone() {
3295            Some(s) => (WalSink::Shared(s), 0),
3296            None => {
3297                let pinned_wal_root = match ctx.root_guard.as_deref() {
3298                    Some(root) => Some(root.create_directory_all_pinned(WAL_DIR)?),
3299                    None => None,
3300                };
3301                let wal_dir = if let Some(root) = pinned_wal_root.as_ref() {
3302                    root.io_path()?
3303                } else {
3304                    let wal_dir = dir.join(WAL_DIR);
3305                    std::fs::create_dir_all(&wal_dir)?;
3306                    wal_dir
3307                };
3308                let mut w = match (pinned_wal_root.as_ref(), wal_dek.as_ref()) {
3309                    (Some(root), Some(dk)) => {
3310                        Wal::create_in_root(root, 0, Epoch(0), Some(make_cipher(dk)))?
3311                    }
3312                    (Some(root), None) => Wal::create_in_root(root, 0, Epoch(0), None)?,
3313                    (None, Some(dk)) => Wal::create_with_cipher(
3314                        wal_dir.join("seg-000000.wal"),
3315                        Epoch(0),
3316                        Some(make_cipher(dk)),
3317                        0,
3318                    )?,
3319                    (None, None) => Wal::create(wal_dir.join("seg-000000.wal"), Epoch(0))?,
3320                };
3321                w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3322                (WalSink::Private(w), 1)
3323            }
3324        };
3325        let mut manifest = Manifest::new(table_id, schema.schema_id);
3326        // Seal the create-time manifest with the meta DEK so an encrypted table
3327        // reopens even if no write/flush ever re-persists it (otherwise the
3328        // reopen's encrypted manifest read fails to authenticate a plaintext
3329        // blob — see `manifest_meta_dek`).
3330        let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3331        match ctx.root_guard.as_deref() {
3332            Some(root) => manifest::write_durable(root, &mut manifest, manifest_meta_dek.as_ref())?,
3333            None => manifest::write_atomic(&dir, &mut manifest, manifest_meta_dek.as_ref())?,
3334        }
3335        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&schema);
3336        let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3337        let auto_inc = resolve_auto_inc(&schema);
3338        let rcache_dir = dir.join(RCACHE_DIR);
3339        let initial_view = ReadGeneration::empty(&schema);
3340        Ok(Self {
3341            dir,
3342            _root_guard: ctx.root_guard,
3343            runs_root,
3344            idx_root: None,
3345            table_id,
3346            name: ctx.table_name.unwrap_or_default(),
3347            auth: ctx.auth,
3348            read_only: ctx.read_only,
3349            durable_commit_failed: false,
3350            wal,
3351            memtable: Memtable::new(),
3352            mutable_run: MutableRun::new(),
3353            mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3354            compaction_zstd_level: 3,
3355            allocator: RowIdAllocator::new(0),
3356            epoch: ctx.epoch,
3357            data_generation: 0,
3358            schema,
3359            hot: HotIndex::new(),
3360            kek: ctx.kek,
3361            column_keys,
3362            run_refs: Vec::new(),
3363            retiring: Vec::new(),
3364            next_run_id: 1,
3365            sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3366            current_txn_id,
3367            pending_private_mutations: false,
3368            bitmap,
3369            ann,
3370            fm,
3371            sparse,
3372            minhash,
3373            learned_range: Arc::new(HashMap::new()),
3374            pk_by_row: ReversePkMap::new(),
3375            pinned: BTreeMap::new(),
3376            live_count: 0,
3377            reservoir: crate::reservoir::Reservoir::default(),
3378            reservoir_complete: true,
3379            had_deletes: false,
3380            recent_delete_preimages: HashMap::new(),
3381            run_row_id_ranges: HashMap::new(),
3382            agg_cache: Arc::new(HashMap::new()),
3383            global_idx_epoch: 0,
3384            indexes_complete: true,
3385            index_build_policy: IndexBuildPolicy::default(),
3386            pk_by_row_complete: false,
3387            flushed_epoch: 0,
3388            page_cache: ctx.page_cache,
3389            decoded_cache: ctx.decoded_cache,
3390            verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3391            run_readers: Arc::new(parking_lot::Mutex::new(HashMap::new())),
3392            snapshots: ctx.snapshots,
3393            commit_lock: ctx.commit_lock,
3394            // Build the persistent-cache result cache. We attempt to spawn a
3395            // background writer; if that fails (e.g. the OS won't let us
3396            // create the temp file), publication is marked
3397            // `Disabled(WorkerSpawnFailed)` — the table still opens and
3398            // query-path persists are skipped with a metric, never performed
3399            // synchronously on the query thread (REM-D §8.5).
3400            result_cache: {
3401                let cache = ResultCache::new()
3402                    .with_dir(rcache_dir.clone())
3403                    .with_cache_dek(cache_dek.clone());
3404                // Reuse a per-table `LookupMetrics` so the writer's
3405                // enqueue/coalesce/drop counters are visible through
3406                // `Table::lookup_metrics_snapshot`.
3407                let metrics = Arc::new(LookupMetrics::default());
3408                let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3409                match spawn_persistent_cache_worker(
3410                    rcache_dir.clone(),
3411                    cache_dek.clone(),
3412                    (*metrics).clone(),
3413                ) {
3414                    Ok((writer, handle, completion_rx)) => {
3415                        cache_arc
3416                            .lock()
3417                            .install_persistent_writer(writer, handle, completion_rx);
3418                    }
3419                    Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3420                }
3421                cache_arc
3422            },
3423            pending_delete_rids: roaring::RoaringBitmap::new(),
3424            pending_put_cols: std::collections::HashSet::new(),
3425            pending_rows: Vec::new(),
3426            pending_rows_auto_inc: Vec::new(),
3427            pending_dels: Vec::new(),
3428            pending_truncate: None,
3429            wal_dek,
3430            auto_inc,
3431            ttl: None,
3432            pins: Arc::new(crate::retention::PinRegistry::new()),
3433            published: Arc::new(ArcSwap::from_pointee(initial_view)),
3434            read_generation_pin: None,
3435            lookup_metrics: LookupMetrics::default(),
3436            run_lookup: RunLookupState::default(),
3437            active_run_fingerprint: 0,
3438        })
3439    }
3440
3441    /// Open an existing table: load the manifest, replay the active WAL segment
3442    /// into the memtable, and rebuild the HOT + secondary indexes from the runs
3443    /// and replayed rows.
3444    pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
3445        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3446        let pinned = root.io_path()?;
3447        let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3448        ctx.root_guard = Some(root);
3449        Self::open_in(&pinned, ctx)
3450    }
3451
3452    /// Open an existing encrypted table. `passphrase` must match the one used at
3453    /// create time (combined with the persisted salt to re-derive the KEK).
3454    pub fn open_encrypted(dir: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
3455        let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3456        let salt = read_table_encryption_salt_root(&root)?;
3457        let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3458        let pinned = root.io_path()?;
3459        let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3460        ctx.root_guard = Some(root);
3461        let t = Self::open_in(&pinned, ctx)?;
3462        Ok(t)
3463    }
3464
3465    pub(crate) fn open_in(dir: impl AsRef<Path>, ctx: SharedCtx) -> Result<Self> {
3466        let dir = dir.as_ref().to_path_buf();
3467        let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3468        let mut manifest = match ctx.root_guard.as_ref() {
3469            Some(root) => manifest::read_durable(root, "", manifest_meta_dek.as_ref())?,
3470            None => manifest::read(&dir, manifest_meta_dek.as_ref())?,
3471        };
3472        let schema: Schema = match ctx.root_guard.as_ref() {
3473            Some(root) => read_schema_file(root.open_regular(SCHEMA_FILENAME)?)?,
3474            None => read_schema(&dir)?,
3475        };
3476        // A standalone schema change publishes the schema before its matching
3477        // manifest. If the process dies in that narrow window, the newer,
3478        // fully validated schema is authoritative and the manifest identity is
3479        // repaired only after the rest of open has passed preflight. A manifest
3480        // claiming a schema newer than the durable schema remains corruption.
3481        let schema_manifest_repair = manifest.schema_id < schema.schema_id;
3482        let runs_root = match ctx.root_guard.as_ref() {
3483            Some(root) => Some(Arc::new(root.open_directory(RUNS_DIR)?)),
3484            None => None,
3485        };
3486        let idx_root = match ctx.root_guard.as_ref() {
3487            Some(root) => match root.open_directory(global_idx::IDX_DIR) {
3488                Ok(root) => Some(Arc::new(root)),
3489                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
3490                Err(error) => return Err(error.into()),
3491            },
3492            None => None,
3493        };
3494        schema.validate_auto_increment()?;
3495        schema.validate_defaults()?;
3496        schema.validate_ai()?;
3497        for index in &schema.indexes {
3498            index.validate_options()?;
3499        }
3500        let replay_epoch = Epoch(manifest.current_epoch);
3501        let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), manifest.table_id);
3502        let private_replayed = if ctx.shared.is_none() {
3503            match latest_wal_segment(&dir.join(WAL_DIR))? {
3504                Some(path) => {
3505                    let cipher = wal_dek.as_ref().map(|dk| make_cipher(dk));
3506                    crate::wal::replay_with_cipher(path, cipher)?
3507                }
3508                None => Vec::new(),
3509            }
3510        } else {
3511            Vec::new()
3512        };
3513        if ctx.shared.is_none() {
3514            preflight_standalone_open(
3515                &dir,
3516                runs_root.as_deref(),
3517                idx_root.as_deref(),
3518                &manifest,
3519                &schema,
3520                &private_replayed,
3521                ctx.kek.clone(),
3522            )?;
3523        }
3524        let next_run_id = derive_next_run_id(
3525            &dir,
3526            runs_root.as_deref(),
3527            &manifest.runs,
3528            &manifest.retiring,
3529        )?;
3530        // B1: a mounted table has no private WAL — its committed records live in
3531        // the shared WAL and are replayed by `Database::recover_shared_wal`. A
3532        // standalone table replays + reopens its own `_wal/` segment here.
3533        let (wal, replayed, current_txn_id) = match ctx.shared.clone() {
3534            Some(s) => (WalSink::Shared(s), Vec::new(), 0),
3535            None => {
3536                let replayed = private_replayed;
3537                // Never truncate the only durable recovery source. Re-encode
3538                // every valid frame into a synced staging segment, then publish
3539                // it atomically under the next segment number. A crash before
3540                // publication leaves the old segment authoritative; a crash
3541                // afterward finds the complete replacement as the latest WAL.
3542                let wal_dir = dir.join(WAL_DIR);
3543                crate::durable_file::create_directory_all(&wal_dir)?;
3544                let segment = next_wal_segment(&wal_dir)?;
3545                let segment_no = wal_segment_number(&segment).unwrap_or(0);
3546                let temporary = wal_dir.join(format!(
3547                    ".recovery-{}-{}-{segment_no:06}.tmp",
3548                    std::process::id(),
3549                    std::time::SystemTime::now()
3550                        .duration_since(std::time::UNIX_EPOCH)
3551                        .unwrap_or_default()
3552                        .as_nanos()
3553                ));
3554                let mut w = Wal::create_with_cipher(
3555                    &temporary,
3556                    replay_epoch,
3557                    wal_dek.as_ref().map(|dk| make_cipher(dk)),
3558                    segment_no,
3559                )?;
3560                for record in &replayed {
3561                    w.append_txn(record.txn_id, record.op.clone())?;
3562                }
3563                let mut w = w.publish_as(segment)?;
3564                w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3565                let next_txn_id = replayed
3566                    .iter()
3567                    .map(|record| record.txn_id)
3568                    .filter(|txn_id| *txn_id != crate::wal::SYSTEM_TXN_ID)
3569                    .max()
3570                    .map(|txn_id| txn_id.checked_add(1).unwrap_or(0))
3571                    .unwrap_or(1);
3572                (WalSink::Private(w), replayed, next_txn_id)
3573            }
3574        };
3575
3576        let mut memtable = Memtable::new();
3577        let mut allocator = RowIdAllocator::new(manifest.next_row_id);
3578        let persisted_epoch = manifest.current_epoch;
3579        // Seed the auto-increment counter from the manifest. `auto_inc_next == 0`
3580        // means unseeded (fresh table, or a legacy manifest migrated forward) —
3581        // the first allocation scans `max(PK)` to avoid colliding with existing
3582        // rows. WAL replay (below) and `recover_apply` additionally bump `next`
3583        // past replayed ids without marking it seeded, so the scan still covers
3584        // any rows that were already flushed to sorted runs.
3585        let mut auto_inc = resolve_auto_inc(&schema).map(|mut s| {
3586            s.next = manifest.auto_inc_next;
3587            s.seeded = manifest.auto_inc_next > 0;
3588            s
3589        });
3590
3591        // 1. Replay is two-phase and TxnCommit-gated: data records (Put/Delete)
3592        //    are staged per `txn_id` and only applied when a durable
3593        //    `TxnCommit{epoch}` for that txn is seen. Uncommitted / aborted /
3594        //    torn-tail txns are discarded. Indexing happens AFTER loading any
3595        //    checkpoint / run data (below) so the newer replayed versions
3596        //    overwrite the older run versions in the HOT index.
3597        let mut staged_puts: HashMap<u64, Vec<Row>> = HashMap::new();
3598        let mut staged_deletes: HashMap<u64, Vec<RowId>> = HashMap::new();
3599        let mut staged_truncates: std::collections::HashSet<u64> = std::collections::HashSet::new();
3600        let mut replayed_puts: std::collections::BTreeMap<Epoch, Vec<Row>> =
3601            std::collections::BTreeMap::new();
3602        let mut replayed_deletes: Vec<(RowId, Epoch)> = Vec::new();
3603        let mut recovered_epoch = manifest.current_epoch;
3604        let mut recovered_manifest_dirty = schema_manifest_repair;
3605        let mut saw_delete = false;
3606        for record in replayed {
3607            let txn_id = record.txn_id;
3608            match record.op {
3609                Op::Put { rows, .. } => {
3610                    let rows: Vec<Row> = bincode::deserialize(&rows)?;
3611                    for row in &rows {
3612                        allocator.advance_to(row.row_id)?;
3613                        if let Some(ai) = auto_inc.as_mut() {
3614                            if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
3615                                let next = n.checked_add(1).ok_or_else(|| {
3616                                    MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
3617                                })?;
3618                                if next > ai.next {
3619                                    ai.next = next;
3620                                }
3621                            }
3622                        }
3623                    }
3624                    staged_puts.entry(txn_id).or_default().extend(rows);
3625                }
3626                Op::Delete { row_ids, .. } => {
3627                    staged_deletes.entry(txn_id).or_default().extend(row_ids);
3628                }
3629                Op::TxnCommit { epoch, .. } => {
3630                    let commit_epoch = Epoch(epoch);
3631                    recovered_epoch = recovered_epoch.max(epoch);
3632                    if staged_truncates.remove(&txn_id) && commit_epoch.0 > manifest.flushed_epoch {
3633                        memtable = Memtable::new();
3634                        replayed_puts.clear();
3635                        replayed_deletes.clear();
3636                        manifest.runs.clear();
3637                        manifest.retiring.clear();
3638                        manifest.live_count = 0;
3639                        manifest.global_idx_epoch = 0;
3640                        manifest.current_epoch = manifest.current_epoch.max(epoch);
3641                        recovered_manifest_dirty = true;
3642                        saw_delete = true;
3643                    }
3644                    if let Some(puts) = staged_puts.remove(&txn_id) {
3645                        if commit_epoch.0 > manifest.flushed_epoch {
3646                            for row in &puts {
3647                                memtable.upsert(row.clone());
3648                            }
3649                            replayed_puts.entry(commit_epoch).or_default().extend(puts);
3650                        }
3651                    }
3652                    if let Some(dels) = staged_deletes.remove(&txn_id) {
3653                        saw_delete = true;
3654                        if commit_epoch.0 > manifest.flushed_epoch {
3655                            for rid in dels {
3656                                memtable.tombstone(rid, commit_epoch);
3657                                replayed_deletes.push((rid, commit_epoch));
3658                            }
3659                        }
3660                    }
3661                }
3662                Op::TxnAbort => {
3663                    staged_puts.remove(&txn_id);
3664                    staged_deletes.remove(&txn_id);
3665                    staged_truncates.remove(&txn_id);
3666                }
3667                Op::TruncateTable { .. } => {
3668                    staged_puts.remove(&txn_id);
3669                    staged_deletes.remove(&txn_id);
3670                    staged_truncates.insert(txn_id);
3671                }
3672                Op::ExternalTableState { .. }
3673                | Op::Flush { .. }
3674                | Op::Ddl(_)
3675                | Op::BeforeImage { .. }
3676                | Op::CommitTimestamp { .. }
3677                | Op::SpilledRows { .. } => {}
3678            }
3679        }
3680
3681        let rcache_dir = dir.join(RCACHE_DIR);
3682        let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3683        let initial_view = ReadGeneration::empty(&schema);
3684        let mut db = Self {
3685            dir,
3686            _root_guard: ctx.root_guard,
3687            runs_root,
3688            idx_root,
3689            table_id: manifest.table_id,
3690            name: ctx.table_name.unwrap_or_default(),
3691            auth: ctx.auth,
3692            read_only: ctx.read_only,
3693            durable_commit_failed: false,
3694            wal,
3695            memtable,
3696            mutable_run: MutableRun::new(),
3697            mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3698            compaction_zstd_level: 3,
3699            allocator,
3700            epoch: ctx.epoch,
3701            data_generation: persisted_epoch,
3702            schema,
3703            hot: HotIndex::new(),
3704            kek: ctx.kek,
3705            column_keys,
3706            run_refs: manifest.runs.clone(),
3707            retiring: manifest.retiring.clone(),
3708            next_run_id,
3709            sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3710            current_txn_id,
3711            pending_private_mutations: false,
3712            bitmap: HashMap::new(),
3713            ann: HashMap::new(),
3714            fm: HashMap::new(),
3715            sparse: HashMap::new(),
3716            minhash: HashMap::new(),
3717            learned_range: Arc::new(HashMap::new()),
3718            pk_by_row: ReversePkMap::new(),
3719            pinned: BTreeMap::new(),
3720            live_count: manifest.live_count,
3721            reservoir: crate::reservoir::Reservoir::default(),
3722            reservoir_complete: false,
3723            had_deletes: saw_delete
3724                || manifest.runs.iter().map(|run| run.row_count).sum::<u64>()
3725                    != manifest.live_count,
3726            recent_delete_preimages: HashMap::new(),
3727            run_row_id_ranges: HashMap::new(),
3728            agg_cache: Arc::new(HashMap::new()),
3729            global_idx_epoch: manifest.global_idx_epoch,
3730            indexes_complete: true,
3731            index_build_policy: IndexBuildPolicy::default(),
3732            pk_by_row_complete: false,
3733            flushed_epoch: manifest.flushed_epoch,
3734            page_cache: ctx.page_cache,
3735            decoded_cache: ctx.decoded_cache,
3736            verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3737            run_readers: Arc::new(parking_lot::Mutex::new(HashMap::new())),
3738            snapshots: ctx.snapshots,
3739            commit_lock: ctx.commit_lock,
3740            result_cache: {
3741                let cache = ResultCache::new()
3742                    .with_dir(rcache_dir.clone())
3743                    .with_cache_dek(cache_dek.clone());
3744                let metrics = LookupMetrics::default();
3745                let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3746                match spawn_persistent_cache_worker(rcache_dir.clone(), cache_dek.clone(), metrics)
3747                {
3748                    Ok((writer, handle, completion_rx)) => {
3749                        cache_arc
3750                            .lock()
3751                            .install_persistent_writer(writer, handle, completion_rx);
3752                    }
3753                    // Spawn / I/O-setup failure: publication is disabled and
3754                    // query-path persists are skipped with a metric (REM-D
3755                    // §8.5) — never a synchronous query-thread write.
3756                    Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3757                }
3758                cache_arc
3759            },
3760            pending_delete_rids: roaring::RoaringBitmap::new(),
3761            pending_put_cols: std::collections::HashSet::new(),
3762            pending_rows: Vec::new(),
3763            pending_rows_auto_inc: Vec::new(),
3764            pending_dels: Vec::new(),
3765            pending_truncate: None,
3766            wal_dek,
3767            auto_inc,
3768            ttl: manifest.ttl,
3769            pins: Arc::new(crate::retention::PinRegistry::new()),
3770            published: Arc::new(ArcSwap::from_pointee(initial_view)),
3771            read_generation_pin: None,
3772            lookup_metrics: LookupMetrics::default(),
3773            run_lookup: RunLookupState::default(),
3774            active_run_fingerprint: 0,
3775        };
3776
3777        // Advance the (possibly shared) epoch authority to this table's manifest
3778        // epoch so rebuild/index reads below observe the recovered watermark.
3779        db.epoch.advance_recovered(Epoch(recovered_epoch));
3780
3781        // 2. Fast path: load the persisted global-index checkpoint (Phase 9.1).
3782        //    Valid only when its embedded epoch matches the manifest-endorsed
3783        //    `global_idx_epoch` and every run was created at or before it, so the
3784        //    checkpoint covers all run data. Otherwise rebuild from the runs.
3785        let checkpoint = match db.idx_root.as_deref() {
3786            Some(root) => {
3787                global_idx::read_root(root, db.table_id, &db.schema, db.idx_dek().as_deref())?
3788            }
3789            None => global_idx::read(&db.dir, db.table_id, &db.schema, db.idx_dek().as_deref())?,
3790        };
3791        let checkpoint_valid = checkpoint.as_ref().is_some_and(|c| {
3792            c.epoch_built == manifest.global_idx_epoch
3793                && manifest.global_idx_epoch > 0
3794                && manifest
3795                    .runs
3796                    .iter()
3797                    .all(|r| r.epoch_created <= manifest.global_idx_epoch)
3798        });
3799        if let Some(loaded) = checkpoint {
3800            if checkpoint_valid {
3801                db.hot = loaded.hot;
3802                db.bitmap = loaded.bitmap;
3803                db.ann = loaded.ann;
3804                db.fm = loaded.fm;
3805                db.sparse = loaded.sparse;
3806                db.minhash = loaded.minhash;
3807                db.learned_range = Arc::new(loaded.learned_range);
3808                // Checkpoints omit empty secondary indexes (e.g. ANN with no
3809                // vectors yet). Re-seed any schema-declared maps that were
3810                // skipped so retrievers like ANN do not fail with "has no
3811                // ANN index" after reopen.
3812                let (bitmap0, ann0, fm0, sparse0, minhash0) = empty_indexes(&db.schema);
3813                for (cid, idx) in bitmap0 {
3814                    db.bitmap.entry(cid).or_insert(idx);
3815                }
3816                for (cid, idx) in ann0 {
3817                    db.ann.entry(cid).or_insert(idx);
3818                }
3819                for (cid, idx) in fm0 {
3820                    db.fm.entry(cid).or_insert(idx);
3821                }
3822                for (cid, idx) in sparse0 {
3823                    db.sparse.entry(cid).or_insert(idx);
3824                }
3825                for (cid, idx) in minhash0 {
3826                    db.minhash.entry(cid).or_insert(idx);
3827                }
3828                // `pk_by_row` stays lazy (`pk_by_row_complete == false`): the
3829                // first delete rebuilds it from the loaded HOT.
3830            }
3831        }
3832        if !checkpoint_valid {
3833            let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&db.schema);
3834            db.bitmap = bitmap;
3835            db.ann = ann;
3836            db.fm = fm;
3837            db.sparse = sparse;
3838            db.minhash = minhash;
3839            db.rebuild_indexes_from_runs()?;
3840            db.build_learned_ranges()?;
3841        }
3842
3843        // 3. Replay overlay: PK winner/loser tombstone maintenance always
3844        //    runs (rebuild is per-RowId and does not apply same-PK replace
3845        //    tombstones). Index the replayed rows only when the checkpoint
3846        //    was loaded — a full rebuild already folded the memtable, which
3847        //    already contains these rows. Re-inserting would double Sparse
3848        //    scores and duplicate ANN nodes.
3849        for (epoch, group) in replayed_puts {
3850            let (losers, winner_pks) = db.partition_pk_winners(&group);
3851            for (key, &row_id) in &winner_pks {
3852                if let Some(old_rid) = db.hot.get(key) {
3853                    if old_rid != row_id {
3854                        db.tombstone_row(old_rid, epoch, None, false);
3855                    }
3856                }
3857            }
3858            for &loser_rid in &losers {
3859                db.tombstone_row(loser_rid, epoch, None, false);
3860            }
3861            for (key, row_id) in winner_pks {
3862                db.insert_hot_pk(key, row_id);
3863            }
3864            if db.schema.primary_key().is_none() {
3865                for r in &group {
3866                    db.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
3867                }
3868            }
3869            if checkpoint_valid {
3870                for r in &group {
3871                    if !losers.contains(&r.row_id) {
3872                        db.index_row(r);
3873                    }
3874                }
3875            }
3876        }
3877        // Apply replayed deletes after the puts: a delete targets a specific row
3878        // id and only removes the HOT entry if it still points to that id, so a
3879        // newer upsert for the same PK is not accidentally erased.
3880        for (rid, epoch) in &replayed_deletes {
3881            db.remove_hot_for_row(*rid, *epoch);
3882        }
3883
3884        if recovered_manifest_dirty {
3885            let rows = db.visible_rows(Snapshot::unbounded())?;
3886            db.live_count = rows.len() as u64;
3887            db.persist_manifest(Epoch(recovered_epoch))?;
3888        }
3889
3890        // The reservoir stays lazy (`reservoir_complete == false`, set above):
3891        // rebuilding it means materializing every visible row, which no plain
3892        // open/insert/update/delete needs. `ensure_reservoir_complete` pays
3893        // that cost on the first `approx_aggregate` call instead.
3894        // Load the persistent result-cache tier (hardening (b)) so fine-grained
3895        // invalidation resumes across restart.
3896        let identity = crate::result_cache::PersistentCacheIdentity {
3897            table_id: db.table_id,
3898            schema_id: db.schema.schema_id,
3899            logical_generation: db.epoch.visible().0,
3900        };
3901        db.result_cache.lock().load_persistent(identity);
3902        // Populate RowId range directory so point get can skip irrelevant runs.
3903        db.refresh_run_row_id_ranges();
3904        // Issue 4 / spec §8.4 step 3 — try to install the row-to-run lookup
3905        // directory from the sharded checkpoint. Failure is non-fatal: the
3906        // open succeeds, the read path falls back to range scans, and the
3907        // next flush/compaction rebuilds + publishes a fresh directory.
3908        db.load_run_lookup_directory();
3909        Ok(db)
3910    }
3911
3912    fn refresh_active_run_fingerprint(&mut self) {
3913        let active_ids: Vec<u128> = self.run_refs.iter().map(|r| r.run_id).collect();
3914        self.active_run_fingerprint = crate::run_lookup::compute_fingerprint(
3915            &active_ids,
3916            self.schema.schema_id,
3917            self.global_idx_epoch,
3918            active_ids.len() as u64,
3919            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
3920        );
3921    }
3922
3923    /// Best-effort load of the run-lookup directory on open. Tries the
3924    /// sharded checkpoint first; if it's missing, corrupt, or stale, the
3925    /// in-memory state is left in `complete = false` and the existing
3926    /// range-scan fallback stays the read path's safety net.
3927    fn load_run_lookup_directory(&mut self) {
3928        let active_runs = self.run_refs.clone();
3929        let schema_id = self.schema.schema_id;
3930        let run_generation = active_runs.len() as u64;
3931        let index_generation = self.global_idx_epoch;
3932        let fingerprint = crate::run_lookup::compute_fingerprint(
3933            &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
3934            schema_id,
3935            index_generation,
3936            run_generation,
3937            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
3938        );
3939        self.active_run_fingerprint = fingerprint;
3940        // Build a candidate from the sharded checkpoint in `_runs/`.
3941        let runs_dir = match self.runs_root.as_deref() {
3942            Some(root) => match root.io_path() {
3943                Ok(p) => p,
3944                Err(_) => self.dir.join(RUNS_DIR),
3945            },
3946            None => self.dir.join(RUNS_DIR),
3947        };
3948        match crate::run_lookup::RunLookupDirectory::read_checkpoint_sharded(&runs_dir, fingerprint)
3949        {
3950            Ok(dir) => {
3951                self.run_lookup = RunLookupState {
3952                    directory: Some(std::sync::Arc::new(dir)),
3953                    fingerprint,
3954                    complete: true,
3955                };
3956            }
3957            Err(error) => {
3958                self.lookup_metrics
3959                    .directory_incomplete
3960                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3961                self.lookup_metrics
3962                    .directory_lookup_fallback
3963                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3964                self.run_lookup = RunLookupState {
3965                    directory: None,
3966                    fingerprint,
3967                    complete: false,
3968                };
3969                // Trace the load failure so smoke tests catch silent fallbacks
3970                // during the closure audit. The error kind is enough; full
3971                // path is preserved by the trace.
3972                let _ = error;
3973            }
3974        }
3975    }
3976
3977    /// Rebuild `reservoir` from every visible row if it isn't already
3978    /// complete (lazy — same pattern as [`Self::ensure_indexes_complete`]).
3979    /// Open and WAL replay leave the reservoir stale rather than eagerly
3980    /// paying a full-table scan; this pays it once, on the first
3981    /// [`Self::approx_aggregate`] call.
3982    fn ensure_reservoir_complete(&mut self) -> Result<()> {
3983        if self.reservoir_complete {
3984            return Ok(());
3985        }
3986        self.rebuild_reservoir()?;
3987        self.reservoir_complete = true;
3988        Ok(())
3989    }
3990
3991    /// Repopulate the reservoir sample from all visible rows (used on open so a
3992    /// reopened table has an analytics sample without further inserts).
3993    fn rebuild_reservoir(&mut self) -> Result<()> {
3994        let snap = self.snapshot();
3995        let rows = self.visible_rows(snap)?;
3996        self.reservoir.reset();
3997        for r in rows {
3998            self.reservoir.offer(r.row_id.0);
3999        }
4000        Ok(())
4001    }
4002
4003    /// Rebuild HOT + every secondary index from durable runs, the mutable run,
4004    /// and the memtable. Safe to call online; used by recovery tooling and the
4005    /// public [`crate::Database::rebuild_indexes`] path after index desync.
4006    pub fn rebuild_indexes(&mut self) -> Result<()> {
4007        self.rebuild_indexes_from_runs_inner(None)
4008    }
4009
4010    /// Test-only fault-injection seam: install an arbitrary HOT mapping.
4011    ///
4012    /// Bypasses the per-row index maintenance path so regression tests for the
4013    /// HOT fallback (issue 2) can deliberately corrupt the HOT map and assert
4014    /// that the [`Self::resolve_pk_with_hot_fallback`] path still returns the
4015    /// correct, scanned row instead of the mismatched mapped one.
4016    ///
4017    /// Always public so integration tests in `tests/` can reach it; the
4018    /// `__` prefix + the explicit "for_test" name is the convention used
4019    /// elsewhere in the codebase to discourage production callers.
4020    pub fn __force_hot_map_for_test(&mut self, pk_bytes: &[u8], row_id: RowId) {
4021        self.hot.insert(pk_bytes.to_vec(), row_id);
4022    }
4023
4024    /// Test-only helper: drop a single HOT mapping so a test can simulate
4025    /// the missing-mapping fallback path without tearing down the table.
4026    pub fn hot_for_test_remove(&mut self, pk_bytes: &[u8]) {
4027        self.hot.remove(pk_bytes);
4028    }
4029
4030    /// Test-only helper: force the `indexes_complete` flag to `false` so a
4031    /// test can drive the `IndexIncomplete` branch of the fallback path.
4032    pub fn set_indexes_incomplete_for_test(&mut self) {
4033        self.indexes_complete = false;
4034    }
4035
4036    /// Test-only helper: bump the `hot_checkpoint_rejected_total` counter by
4037    /// one so a test can drive the `CheckpointRejected` path. The counter
4038    /// is `pub(crate)` so the helper bumps it directly.
4039    pub fn bump_hot_checkpoint_rejected_for_test(&self) {
4040        self.lookup_metrics
4041            .hot_checkpoint_rejected_total
4042            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4043    }
4044
4045    /// Test-only seam: write `rows` as a synthetic immutable run and link it
4046    /// into the active run set so point-directory tests can control exact
4047    /// (epoch, HLC) stamps and run topology — the public write path stamps
4048    /// every commit with `hlc.now()`, so neither is injectable otherwise.
4049    /// Rows are sorted by `(RowId, epoch)` before writing (sorted-run layout
4050    /// requires ascending `RowId`); returns the allocated run id.
4051    pub fn __install_run_for_test(&mut self, rows: &[Row]) -> Result<u128> {
4052        let mut rows = rows.to_vec();
4053        rows.sort_by_key(|r| (r.row_id, r.committed_epoch));
4054        let epoch = rows
4055            .iter()
4056            .map(|r| r.committed_epoch)
4057            .max()
4058            .unwrap_or(Epoch::ZERO);
4059        let run_id = self.alloc_run_id()?;
4060        let path = self.run_path(run_id);
4061        if let Some(parent) = path.parent() {
4062            std::fs::create_dir_all(parent)
4063                .map_err(|e| MongrelError::Other(format!("create runs dir: {e}")))?;
4064        }
4065        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
4066        if let Some(kek) = &self.kek {
4067            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
4068        }
4069        let header = match self.create_run_file(run_id)? {
4070            Some(file) => writer.write_file(file, &rows)?,
4071            None => writer.write(&path, &rows)?,
4072        };
4073        self.run_refs.push(RunRef {
4074            run_id: run_id as u128,
4075            level: 0,
4076            epoch_created: epoch.0,
4077            row_count: header.row_count,
4078        });
4079        self.refresh_active_run_fingerprint();
4080        self.run_row_id_ranges
4081            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
4082        Ok(run_id as u128)
4083    }
4084
4085    /// Test-only seam: rebuild and publish the run-lookup directory over the
4086    /// current active run set so directory-assisted `Table::get` tests can
4087    /// drive the synthetic topologies installed via
4088    /// [`Self::__install_run_for_test`].
4089    pub fn __rebuild_run_lookup_for_test(&mut self) -> Result<()> {
4090        self.publish_run_lookup_directory()
4091    }
4092
4093    /// Test-only seam: toggle the directory-assisted point-lookup path. With
4094    /// `complete == false`, `Table::get` takes the `UnavailableOrStale`
4095    /// branch and opens every active run — the forced full-run oracle the
4096    /// point-directory correctness tests compare against. The installed
4097    /// directory is kept, so `complete == true` restores the
4098    /// directory-assisted path.
4099    pub fn __set_run_lookup_complete_for_test(&mut self, complete: bool) {
4100        self.run_lookup.complete = complete;
4101    }
4102
4103    pub(crate) fn rebuild_indexes_from_runs(&mut self) -> Result<()> {
4104        self.rebuild_indexes_from_runs_inner(None)
4105    }
4106
4107    /// Scan overlay + runs for a live row whose PK encode matches `lookup`.
4108    /// Used when the HOT map misses a key that may still exist on disk.
4109    ///
4110    /// Returns `(result, reason)`. The caller in `resolve_condition_with_allowed`
4111    /// is the sole authority for `record_hot_fallback_reason` so that the HOT
4112    /// hit branch (which already recorded e.g. `HistoricalSnapshot`) does not
4113    /// double-bookkeep when it delegates the actual scan here. The returned
4114    /// reason is always set:
4115    ///   - tombstone observed at `snapshot` -> `Tombstone`
4116    ///   - live row found on disk              -> `MissingMapping`
4117    ///   - nothing found                       -> `MissingMapping` (a genuine
4118    ///     miss is still a HOT-fallback event for observability).
4119    ///
4120    /// Correctness contract:
4121    ///   - obeys the full `Snapshot` (epoch + HLC) through `visible_*`
4122    ///     iterators and `range_scan_i64`;
4123    ///   - ignores deleted rows in the overlay and durable runs;
4124    ///   - ignores TTL-expired rows via [`Self::row_expired_at`];
4125    ///   - compares the **materialized** PK against the requested encoded
4126    ///     key (post-HMAC tokenization) so that HMAC-eq columns and bytes
4127    ///     PKs both produce exact matches;
4128    ///   - dedups the resulting `RowId` set so a row referenced from
4129    ///     multiple paths (overlay + run, multi-run) is reported once;
4130    ///   - works across the memtable, mutable-run, and every sorted run;
4131    ///   - preserves historical snapshots — pinned-snapshot readers see the
4132    ///     historical row, not the latest.
4133    fn pk_equality_fallback(
4134        &self,
4135        pk_column_id: u16,
4136        lookup: &[u8],
4137        snapshot: Snapshot,
4138    ) -> Result<(RowIdSet, crate::trace::HotFallbackReason)> {
4139        let mut tombstone_hit = false;
4140        let mut overlay_versions = 0u64;
4141        let now_nanos = unix_nanos_now();
4142        // Overlay first (newest versions).
4143        for row in self.memtable.visible_versions_at(snapshot) {
4144            overlay_versions += 1;
4145            self.lookup_metrics
4146                .hot_lookup_fallback_overlay_rows
4147                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4148            if row.deleted {
4149                tombstone_hit = true;
4150                continue;
4151            }
4152            if self.row_expired_at(&row, now_nanos) {
4153                continue;
4154            }
4155            if let Some(pk_val) = row.columns.get(&pk_column_id) {
4156                if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4157                    self.lookup_metrics
4158                        .hot_fallback_overlay_versions_total
4159                        .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4160                    return Ok((
4161                        RowIdSet::one(row.row_id.0),
4162                        crate::trace::HotFallbackReason::MissingMapping,
4163                    ));
4164                }
4165            }
4166        }
4167        for row in self.mutable_run.visible_versions_at(snapshot) {
4168            overlay_versions += 1;
4169            self.lookup_metrics
4170                .hot_lookup_fallback_overlay_rows
4171                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4172            if row.deleted {
4173                tombstone_hit = true;
4174                continue;
4175            }
4176            if self.row_expired_at(&row, now_nanos) {
4177                continue;
4178            }
4179            if let Some(pk_val) = row.columns.get(&pk_column_id) {
4180                if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4181                    self.lookup_metrics
4182                        .hot_fallback_overlay_versions_total
4183                        .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4184                    return Ok((
4185                        RowIdSet::one(row.row_id.0),
4186                        crate::trace::HotFallbackReason::MissingMapping,
4187                    ));
4188                }
4189            }
4190        }
4191        // Durable runs: prefer int64 point range when the encoded key is 8
4192        // bytes of big-endian i64 (the common Kit PK shape).
4193        if lookup.len() == 8 {
4194            if let Ok(arr) = <[u8; 8]>::try_from(lookup) {
4195                let n = i64::from_be_bytes(arr);
4196                let result = self.range_scan_i64(pk_column_id, n, n, snapshot)?;
4197                self.lookup_metrics
4198                    .hot_lookup_fallback_runs
4199                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4200                // Count this as a considered run for the lookup-metrics
4201                // invariant (every HOT fallback must record exactly one reason
4202                // and advance the run accounting by at least one).
4203                self.lookup_metrics
4204                    .hot_fallback_runs_considered_total
4205                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4206                self.lookup_metrics
4207                    .hot_fallback_overlay_versions_total
4208                    .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4209                let reason = if result.is_empty() {
4210                    if tombstone_hit {
4211                        crate::trace::HotFallbackReason::Tombstone
4212                    } else {
4213                        crate::trace::HotFallbackReason::MissingMapping
4214                    }
4215                } else {
4216                    crate::trace::HotFallbackReason::MissingMapping
4217                };
4218                return Ok((result, reason));
4219            }
4220        }
4221        // Bytes / other PK types: linear visible scan of runs is expensive but
4222        // correctness-first for rare HOT misses.
4223        let mut found: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
4224        let overlay = self.overlay_rid_set(snapshot);
4225        let mut runs_considered = 0u64;
4226        for rr in &self.run_refs {
4227            runs_considered += 1;
4228            self.lookup_metrics
4229                .hot_lookup_fallback_runs
4230                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4231            let mut reader = self.open_reader(rr.run_id)?;
4232            for row in reader.visible_versions_at(snapshot)? {
4233                if overlay.contains(&row.row_id.0) || row.deleted {
4234                    if row.deleted {
4235                        tombstone_hit = true;
4236                    }
4237                    continue;
4238                }
4239                if self.row_expired_at(&row, now_nanos) {
4240                    continue;
4241                }
4242                if let Some(pk_val) = row.columns.get(&pk_column_id) {
4243                    if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4244                        found.insert(row.row_id.0);
4245                    }
4246                }
4247            }
4248        }
4249        let reason = if tombstone_hit {
4250            crate::trace::HotFallbackReason::Tombstone
4251        } else {
4252            // Found or not: the HOT entry was missing, so this is a mapping
4253            // miss regardless of whether the row exists on disk.
4254            crate::trace::HotFallbackReason::MissingMapping
4255        };
4256        self.lookup_metrics
4257            .hot_fallback_overlay_versions_total
4258            .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4259        self.lookup_metrics
4260            .hot_fallback_runs_considered_total
4261            .fetch_add(runs_considered, std::sync::atomic::Ordering::Relaxed);
4262        Ok((RowIdSet::from_unsorted(found.into_iter().collect()), reason))
4263    }
4264
4265    /// TODO §5.1/§5.2 — record a HOT fallback reason. Increments the
4266    /// per-reason counter, the global `hot_lookup_fallback` total, the
4267    /// per-query trace, and the active-call duration bucket.
4268    fn record_hot_fallback_reason(&self, reason: crate::trace::HotFallbackReason) {
4269        let idx = hot_fallback_reason_index(reason);
4270        self.lookup_metrics.hot_fallback_reasons[idx]
4271            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4272        self.lookup_metrics
4273            .hot_lookup_fallback
4274            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4275        crate::trace::QueryTrace::record(|t| {
4276            t.hot_lookup_attempted = true;
4277            t.hot_lookup_hit = false;
4278            t.hot_fallback_reason = Some(reason.as_str());
4279        });
4280    }
4281
4282    fn rebuild_indexes_from_runs_inner(
4283        &mut self,
4284        control: Option<&crate::ExecutionControl>,
4285    ) -> Result<()> {
4286        // S1C-004: online index rebuild pins the current visible epoch so
4287        // version GC cannot reclaim rows while the rebuild scans them.
4288        let _index_build_pin = Arc::clone(self.pin_registry()).pin(
4289            crate::retention::PinSource::OnlineIndexBuild,
4290            self.current_epoch(),
4291        );
4292        self.hot = HotIndex::new();
4293        self.pk_by_row.clear();
4294        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
4295        self.bitmap = bitmap;
4296        self.ann = ann;
4297        self.fm = fm;
4298        self.sparse = sparse;
4299        self.minhash = minhash;
4300        // REM-001: rebuild the current-state index from a *globally merged*
4301        // candidate set rather than indexing each run's visible versions in
4302        // iteration order. For every RowId we collect the candidate from each
4303        // run + the overlay tiers, select the winner using full version
4304        // authority (HLC when both sides are stamped), and index the winner
4305        // exactly once. Tombstones drop the entry entirely. Physical run
4306        // order is no longer a substitute for HLC authority.
4307        //
4308        // TTL-expired rows ARE indexed (HOT and every secondary), matching
4309        // what incremental maintenance would have produced had the rows been
4310        // written after the rebuild: expiry is a query-time eligibility
4311        // filter ([`Self::row_expired_at`]), not an index-content rule.
4312        // Skipping them here would lose the HOT entry a later same-PK put
4313        // needs to tombstone the old row, and would strand the row's
4314        // secondary postings if the TTL policy is ever cleared or relaxed —
4315        // both observed as stale rows resurfacing after `clear_ttl`.
4316        //
4317        // Visibility spans every epoch — a row just upserted in the memtable
4318        // lives at `pending_epoch = visible + 1` (no commit yet) so a snapshot
4319        // pinned at `visible` would silently hide it. Use [`Snapshot::unbounded`]
4320        // so the fold observes every durable row, regardless of whether the
4321        // caller has committed since the upsert.
4322        let snapshot = Snapshot::unbounded();
4323        let ttl_now = unix_nanos_now();
4324        let mut scanned = 0_usize;
4325        let mut winners: HashMap<RowId, (VersionStamp, Row)> = HashMap::new();
4326        let fold =
4327            |row: Row, winners: &mut HashMap<RowId, (VersionStamp, Row)>, scanned: &mut usize| {
4328                *scanned += 1;
4329                let stamp = VersionStamp {
4330                    epoch: row.committed_epoch,
4331                    commit_ts: row.commit_ts,
4332                };
4333                winners
4334                    .entry(row.row_id)
4335                    .and_modify(|entry| {
4336                        if stamp.is_newer_than(entry.0) {
4337                            *entry = (stamp, row.clone());
4338                        }
4339                    })
4340                    .or_insert((stamp, row));
4341            };
4342        for rr in self.run_refs.clone() {
4343            if let Some(control) = control {
4344                control.checkpoint()?;
4345            }
4346            let mut reader = self.open_reader(rr.run_id)?;
4347            for row in reader.visible_versions_at(snapshot)? {
4348                if scanned.is_multiple_of(256) {
4349                    if let Some(control) = control {
4350                        control.checkpoint()?;
4351                    }
4352                }
4353                // Tombstones are still folded: a tombstone's stamp may beat a
4354                // older live row's stamp and clear the entry; folding both
4355                // lets the merge decide the final state per RowId.
4356                fold(row, &mut winners, &mut scanned);
4357            }
4358        }
4359        for (index, row) in self
4360            .memtable
4361            .visible_versions_at(snapshot)
4362            .into_iter()
4363            .enumerate()
4364        {
4365            if index & 255 == 0 {
4366                if let Some(control) = control {
4367                    control.checkpoint()?;
4368                }
4369            }
4370            fold(row, &mut winners, &mut scanned);
4371        }
4372        for (index, row) in self
4373            .mutable_run
4374            .visible_versions_at(snapshot)
4375            .into_iter()
4376            .enumerate()
4377        {
4378            if index & 255 == 0 {
4379                if let Some(control) = control {
4380                    control.checkpoint()?;
4381                }
4382            }
4383            fold(row, &mut winners, &mut scanned);
4384        }
4385        // Partial-index predicates filter the rebuild the same way they
4386        // filter incremental puts (`index_row`): a winner row enters only
4387        // the indexes whose predicate it matches. The HOT map is the
4388        // primary-key map, not a partial index, and is always populated.
4389        let any_predicate = self
4390            .schema
4391            .indexes
4392            .iter()
4393            .any(|idx| idx.predicate.is_some());
4394        let name_to_id: HashMap<&str, u16> = self
4395            .schema
4396            .columns
4397            .iter()
4398            .map(|c| (c.name.as_str(), c.id))
4399            .collect();
4400        for (_rid, (stamp, row)) in winners.drain() {
4401            if row.deleted {
4402                // Tombstone: nothing to index. Anything that was about to be
4403                // promoted under this rid is suppressed by the merge above.
4404                let _ = stamp;
4405                continue;
4406            }
4407            // See the rebuild comment above: TTL-expired winners are indexed
4408            // on purpose; expiry is applied at query time.
4409            let tok_row = self.tokenized_for_indexes(&row);
4410            if !any_predicate {
4411                index_into(
4412                    &self.schema,
4413                    &tok_row,
4414                    &mut self.hot,
4415                    &mut self.bitmap,
4416                    &mut self.ann,
4417                    &mut self.fm,
4418                    &mut self.sparse,
4419                    &mut self.minhash,
4420                );
4421                continue;
4422            }
4423            if let Some(pk_col) = self.schema.primary_key() {
4424                if let Some(pk_val) = tok_row.columns.get(&pk_col.id) {
4425                    self.hot.insert(pk_val.encode_key(), tok_row.row_id);
4426                }
4427            }
4428            let columns_map: HashMap<u16, &Value> =
4429                row.columns.iter().map(|(k, v)| (*k, v)).collect();
4430            for idef in &self.schema.indexes {
4431                if let Some(pred) = &idef.predicate {
4432                    if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4433                        continue;
4434                    }
4435                }
4436                index_into_single(
4437                    idef,
4438                    &self.schema,
4439                    &tok_row,
4440                    &mut self.hot,
4441                    &mut self.bitmap,
4442                    &mut self.ann,
4443                    &mut self.fm,
4444                    &mut self.sparse,
4445                    &mut self.minhash,
4446                );
4447            }
4448        }
4449        // Pin-aware historical discovery for EVERY active pin source that
4450        // compact honors via min_active_snapshot — local pin_snapshot pins,
4451        // Database SnapshotRegistry pins, PinRegistry (backup/replication/
4452        // read-generation/…), and history_floor. Winner-takes-all at the
4453        // unbounded snapshot drops rows only pinned readers still need;
4454        // restore those rows into every secondary (not just Bitmap) so
4455        // retrieve_at / BitmapEq / FmContains still answer at the pin.
4456        // Dedup by RowId: Sparse/MinHash/ANN insert is additive, and the
4457        // same historical rid can be visible at more than one pin epoch.
4458        let pin_epochs = self.active_pin_epochs_for_rebuild();
4459        if !pin_epochs.is_empty() {
4460            let current_snap = Snapshot::at(Epoch(u64::MAX));
4461            let mut historical: HashMap<RowId, Row> = HashMap::new();
4462            for pin_epoch in pin_epochs {
4463                if let Some(control) = control {
4464                    control.checkpoint()?;
4465                }
4466                let pin_snap = Snapshot::at(pin_epoch);
4467                for rr in self.run_refs.clone() {
4468                    if let Some(control) = control {
4469                        control.checkpoint()?;
4470                    }
4471                    let mut reader = self.open_reader(rr.run_id)?;
4472                    for row in reader.visible_rows(pin_epoch)? {
4473                        if row.deleted || self.row_expired_at(&row, ttl_now) {
4474                            continue;
4475                        }
4476                        if historical.contains_key(&row.row_id) {
4477                            continue;
4478                        }
4479                        if self.get(row.row_id, current_snap).is_none() {
4480                            historical.insert(row.row_id, row);
4481                        }
4482                    }
4483                }
4484                for row in self
4485                    .mutable_run
4486                    .visible_versions_at(pin_snap)
4487                    .into_iter()
4488                    .chain(self.memtable.visible_versions_at(pin_snap))
4489                {
4490                    if row.deleted || self.row_expired_at(&row, ttl_now) {
4491                        continue;
4492                    }
4493                    if historical.contains_key(&row.row_id) {
4494                        continue;
4495                    }
4496                    if self.get(row.row_id, current_snap).is_none() {
4497                        historical.insert(row.row_id, row);
4498                    }
4499                }
4500            }
4501            for row in historical.into_values() {
4502                self.index_secondary_membership_only(&row);
4503            }
4504        }
4505        self.recent_delete_preimages.clear();
4506        self.refresh_pk_by_row_from_hot();
4507        Ok(())
4508    }
4509
4510    /// Index every secondary for `row` without touching HOT. Used to restore
4511    /// pin-needed discovery / retrieval keys after a live-only rebuild.
4512    /// Bitmap keeps the HMAC-aware `bitmap_key_for_column` path; other kinds
4513    /// go through `index_into_single` so Sparse/MinHash/ANN/FM match put.
4514    fn index_secondary_membership_only(&mut self, row: &Row) {
4515        if row.deleted {
4516            return;
4517        }
4518        self.index_bitmap_membership_only(row);
4519        let effective = if self.column_keys.is_empty() {
4520            None
4521        } else {
4522            Some(self.tokenized_for_indexes(row))
4523        };
4524        let source = effective.as_ref().unwrap_or(row);
4525        let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4526        let name_to_id: HashMap<&str, u16> = self
4527            .schema
4528            .columns
4529            .iter()
4530            .map(|c| (c.name.as_str(), c.id))
4531            .collect();
4532        for idef in &self.schema.indexes {
4533            if idef.kind == crate::schema::IndexKind::Bitmap {
4534                continue;
4535            }
4536            if let Some(pred) = &idef.predicate {
4537                if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4538                    continue;
4539                }
4540            }
4541            index_into_single(
4542                idef,
4543                &self.schema,
4544                source,
4545                &mut self.hot,
4546                &mut self.bitmap,
4547                &mut self.ann,
4548                &mut self.fm,
4549                &mut self.sparse,
4550                &mut self.minhash,
4551            );
4552        }
4553    }
4554
4555    /// Index Bitmap secondaries for `row` without touching HOT / ANN / etc.
4556    /// Used to restore pin-needed discovery keys after a live-only rebuild.
4557    fn index_bitmap_membership_only(&mut self, row: &Row) {
4558        if row.deleted {
4559            return;
4560        }
4561        let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4562        let name_to_id: HashMap<&str, u16> = self
4563            .schema
4564            .columns
4565            .iter()
4566            .map(|c| (c.name.as_str(), c.id))
4567            .collect();
4568        for idef in &self.schema.indexes {
4569            if idef.kind != crate::schema::IndexKind::Bitmap {
4570                continue;
4571            }
4572            if let Some(pred) = &idef.predicate {
4573                if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4574                    continue;
4575                }
4576            }
4577            if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
4578                if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
4579                    b.insert(key, row.row_id);
4580                }
4581            }
4582        }
4583    }
4584
4585    fn refresh_pk_by_row_from_hot(&mut self) {
4586        self.pk_by_row_complete = true;
4587        if self.schema.primary_key().is_none() {
4588            self.pk_by_row.clear();
4589            return;
4590        }
4591        // `.collect()` drives `HashMap`'s bulk-build `FromIterator` (reserves
4592        // once from the exact-size iterator), instead of growing-and-rehashing
4593        // through a one-at-a-time `insert()` loop — same fix as
4594        // `HotIndex::from_entries`, same hot path (first delete after a put
4595        // streak rebuilds this from the full HOT index).
4596        self.pk_by_row = ReversePkMap::from_entries(
4597            self.hot
4598                .entries()
4599                .into_iter()
4600                .map(|(key, row_id)| (row_id, key)),
4601        );
4602    }
4603
4604    fn insert_hot_pk(&mut self, key: Vec<u8>, row_id: RowId) {
4605        if self.schema.primary_key().is_some() {
4606            self.pk_by_row.insert(row_id, key.clone());
4607        }
4608        self.hot.insert(key, row_id);
4609    }
4610
4611    /// (Re)build per-column learned (PGM) range indexes for `LearnedRange`
4612    /// columns from the single sorted run. Serves `Condition::Range` sub-linearly
4613    /// on the fast path; no-op when there isn't exactly one run.
4614    pub(crate) fn build_learned_ranges(&mut self) -> Result<()> {
4615        self.build_learned_ranges_inner(None)
4616    }
4617
4618    fn build_learned_ranges_inner(
4619        &mut self,
4620        control: Option<&crate::ExecutionControl>,
4621    ) -> Result<()> {
4622        self.learned_range = Arc::new(HashMap::new());
4623        if self.run_refs.len() != 1 {
4624            return Ok(());
4625        }
4626        let cols: Vec<(u16, usize)> = self
4627            .schema
4628            .indexes
4629            .iter()
4630            .filter(|i| i.kind == IndexKind::LearnedRange)
4631            .map(|i| {
4632                (
4633                    i.column_id,
4634                    i.options
4635                        .learned_range
4636                        .as_ref()
4637                        .map(|options| options.epsilon)
4638                        .unwrap_or(16),
4639                )
4640            })
4641            .collect();
4642        if cols.is_empty() {
4643            return Ok(());
4644        }
4645        // Build the PGM from the newest *visible* (non-tombstoned, snapshot-
4646        // eligible) row per RowId. The run's raw column pages also hold prior
4647        // versions and tombstones (deletes are physical, not logical); feeding
4648        // those into the PGM would surface stale rids from `ColumnLearnedRange::
4649        // range` that the engine's overlay merge cannot strip — a leaked
4650        // tombstone is a wrong hit (tested by `churn_oracle_learned_range`).
4651        // REM-001: route through the full-Snapshot visibility API so HLC-pinned
4652        // tables pick the HLC-newer winner across run versions instead of the
4653        // higher-epoch legacy fallback. Same `unbounded` rationale as the
4654        // rebuild — every durable run row must be eligible for the PGM input.
4655        let snapshot = Snapshot::unbounded();
4656        let mut reader = self.open_reader(self.run_refs[0].run_id)?;
4657        let (visible_positions, visible_rids) = reader.visible_positions_with_rids_at(snapshot)?;
4658        let row_ids: Vec<u64> = visible_rids.iter().map(|r| *r as u64).collect();
4659        for (column_index, (cid, epsilon)) in cols.into_iter().enumerate() {
4660            if column_index % 256 == 0 {
4661                if let Some(control) = control {
4662                    control.checkpoint()?;
4663                }
4664            }
4665            let ty = self
4666                .schema
4667                .columns
4668                .iter()
4669                .find(|c| c.id == cid)
4670                .map(|c| c.ty.clone())
4671                .unwrap_or(TypeId::Int64);
4672            match ty {
4673                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
4674                    if let columnar::NativeColumn::Int64 { data, .. } = reader.column_native(cid)? {
4675                        let pairs: Vec<(i64, u64)> = visible_positions
4676                            .iter()
4677                            .zip(row_ids.iter())
4678                            .map(|(&p, &r)| (data[p], r))
4679                            .collect();
4680                        Arc::make_mut(&mut self.learned_range).insert(
4681                            cid,
4682                            ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon),
4683                        );
4684                    }
4685                }
4686                TypeId::Float64 => {
4687                    if let columnar::NativeColumn::Float64 { data, .. } =
4688                        reader.column_native(cid)?
4689                    {
4690                        let pairs: Vec<(f64, u64)> = visible_positions
4691                            .iter()
4692                            .zip(row_ids.iter())
4693                            .map(|(&p, &r)| (data[p], r))
4694                            .collect();
4695                        Arc::make_mut(&mut self.learned_range).insert(
4696                            cid,
4697                            ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon),
4698                        );
4699                    }
4700                }
4701                _ => {}
4702            }
4703        }
4704        Ok(())
4705    }
4706
4707    /// Phase 14.7: if the live indexes are known incomplete (after a bulk
4708    /// ingest that deferred index building — see [`IndexBuildPolicy`]),
4709    /// rebuild them from the runs now. Called lazily by `query` /
4710    /// `query_columns_native` / `flush`; public so external index consumers
4711    /// (SQL scans, joins, PK point lookups on a shared handle) can pay the
4712    /// one-time build before reading a `&self` index view.
4713    pub fn ensure_indexes_complete(&mut self) -> Result<()> {
4714        if self.indexes_complete {
4715            crate::trace::QueryTrace::record(|t| {
4716                t.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4717            });
4718            return Ok(());
4719        }
4720        crate::trace::QueryTrace::record(|t| {
4721            t.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4722        });
4723        self.rebuild_indexes_from_runs()?;
4724        self.build_learned_ranges()?;
4725        self.indexes_complete = true;
4726        let epoch = self.current_epoch();
4727        self.checkpoint_indexes(epoch);
4728        Ok(())
4729    }
4730
4731    /// Rebuild derived indexes cooperatively, publishing their checkpoint only
4732    /// after `before_publish` succeeds.
4733    #[doc(hidden)]
4734    pub fn ensure_indexes_complete_controlled<F>(
4735        &mut self,
4736        control: &crate::ExecutionControl,
4737        before_publish: F,
4738    ) -> Result<bool>
4739    where
4740        F: FnOnce() -> bool,
4741    {
4742        self.ensure_indexes_complete_controlled_with_receipt(control, before_publish)
4743            .map(|(changed, _)| changed)
4744    }
4745
4746    /// Rebuild derived indexes cooperatively and return the exact table
4747    /// snapshot used by the rebuild. No receipt is returned for a no-op.
4748    #[doc(hidden)]
4749    pub fn ensure_indexes_complete_controlled_with_receipt<F>(
4750        &mut self,
4751        control: &crate::ExecutionControl,
4752        before_publish: F,
4753    ) -> Result<(bool, Option<MaintenanceReceipt>)>
4754    where
4755        F: FnOnce() -> bool,
4756    {
4757        if self.indexes_complete {
4758            crate::trace::QueryTrace::record(|trace| {
4759                trace.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4760            });
4761            return Ok((false, None));
4762        }
4763        crate::trace::QueryTrace::record(|trace| {
4764            trace.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4765        });
4766        control.checkpoint()?;
4767        let maintenance_epoch = self.current_epoch();
4768        self.rebuild_indexes_from_runs_inner(Some(control))?;
4769        self.build_learned_ranges_inner(Some(control))?;
4770        control.checkpoint()?;
4771        if !before_publish() {
4772            return Err(MongrelError::Cancelled);
4773        }
4774        self.indexes_complete = true;
4775        self.checkpoint_indexes(maintenance_epoch);
4776        Ok((
4777            true,
4778            Some(MaintenanceReceipt {
4779                epoch: maintenance_epoch,
4780            }),
4781        ))
4782    }
4783
4784    fn pending_epoch(&self) -> Epoch {
4785        Epoch(self.epoch.visible().0 + 1)
4786    }
4787
4788    /// True when this table is mounted in a `Database` (writes route through the
4789    /// shared WAL).
4790    fn is_shared(&self) -> bool {
4791        matches!(self.wal, WalSink::Shared(_))
4792    }
4793
4794    /// Return the current auto-commit txn id, allocating a fresh one from the
4795    /// shared allocator on a mounted table when a new span starts (sentinel 0).
4796    /// A standalone table uses its private monotonic counter (never 0).
4797    fn ensure_txn_id(&mut self) -> Result<u64> {
4798        if self.current_txn_id == 0 {
4799            let id = match &self.wal {
4800                WalSink::Shared(s) => crate::txn::allocate_txn_id(&s.txn_ids)?,
4801                WalSink::Private(_) => {
4802                    return Err(MongrelError::Full(
4803                        "standalone transaction id namespace exhausted".into(),
4804                    ))
4805                }
4806                WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4807            };
4808            self.current_txn_id = id;
4809        }
4810        Ok(self.current_txn_id)
4811    }
4812
4813    /// Append a data record (`Put`/`Delete`) for the current auto-commit txn to
4814    /// whichever WAL backs this table.
4815    fn wal_append_data(&mut self, op: Op) -> Result<()> {
4816        self.ensure_writable()?;
4817        let txn_id = self.ensure_txn_id()?;
4818        let table_id = self.table_id;
4819        match &mut self.wal {
4820            WalSink::Private(w) => {
4821                w.append_txn(txn_id, op)?;
4822                self.pending_private_mutations = true;
4823            }
4824            WalSink::Shared(s) => {
4825                s.wal.lock().append(txn_id, table_id, op)?;
4826            }
4827            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4828        }
4829        Ok(())
4830    }
4831
4832    fn ensure_writable(&self) -> Result<()> {
4833        if self.read_only || matches!(self.wal, WalSink::ReadOnly) {
4834            return Err(MongrelError::ReadOnlyReplica);
4835        }
4836        if self.durable_commit_failed {
4837            return Err(MongrelError::Other(
4838                "table poisoned by post-commit failure; reopen required".into(),
4839            ));
4840        }
4841        Ok(())
4842    }
4843
4844    /// Upsert a row. Allocates a [`RowId`], appends a (non-fsynced) WAL record,
4845    /// and updates the memtable + indexes. Returns the new row id. Durability
4846    /// arrives at the next [`Table::commit`] (or [`Table::flush`]).
4847    ///
4848    /// For an `AUTO_INCREMENT` primary key, omit the column (or pass
4849    /// Auth enforcement helpers. Each delegates to the optional
4850    /// [`TableAuthChecker`] (set at mount time from the `Database`'s auth
4851    /// state). On a credentialless database (`auth = None`), these are
4852    /// no-ops. The `name` field provides the table name for the permission
4853    /// check without needing a reference back to `Database`.
4854    fn require(&self, perm: crate::auth_state::RequiredPermission) -> Result<()> {
4855        match &self.auth {
4856            Some(checker) => checker.check(&self.name, perm),
4857            None => Ok(()),
4858        }
4859    }
4860    /// Check `Select` permission on this table. Public so that read entry
4861    /// points that don't go through `Table::query` (e.g. `MongrelProvider::scan`,
4862    /// `Table::count`) can enforce before reading. On a credentialless database
4863    /// this is a no-op.
4864    pub fn require_select(&self) -> Result<()> {
4865        self.require(crate::auth_state::RequiredPermission::Select)
4866    }
4867    fn require_insert(&self) -> Result<()> {
4868        self.require(crate::auth_state::RequiredPermission::Insert)
4869    }
4870    /// Currently unused on `Table` directly (updates go through `Transaction`),
4871    /// but kept for API completeness — the four `require_*` helpers mirror the
4872    /// four table-level permission kinds.
4873    #[allow(dead_code)]
4874    fn require_update(&self) -> Result<()> {
4875        self.require(crate::auth_state::RequiredPermission::Update)
4876    }
4877    fn require_delete(&self) -> Result<()> {
4878        self.require(crate::auth_state::RequiredPermission::Delete)
4879    }
4880
4881    /// [`Value::Null`]) and the engine assigns the next counter value; use
4882    /// [`Table::put_returning`] to learn that assigned value.
4883    pub fn put(&mut self, columns: Vec<(u16, Value)>) -> Result<RowId> {
4884        self.require_insert()?;
4885        Ok(self.put_returning(columns)?.0)
4886    }
4887
4888    /// Like [`Table::put`] but also returns the engine-assigned `AUTO_INCREMENT`
4889    /// value (`Some` only when the column was omitted/null and the engine filled
4890    /// it; `None` when the table has no auto-increment column or the caller
4891    /// supplied an explicit value).
4892    pub fn put_returning(
4893        &mut self,
4894        mut columns: Vec<(u16, Value)>,
4895    ) -> Result<(RowId, Option<i64>)> {
4896        self.require_insert()?;
4897        let assigned = self.fill_auto_inc(&mut columns)?;
4898        self.apply_defaults(&mut columns)?;
4899        self.schema.validate_values(&columns)?;
4900        // For clustered (WITHOUT ROWID) tables, derive RowId deterministically
4901        // from the PK value so the same PK always maps to the same row (no
4902        // allocator waste, idempotent upserts). For standard tables, use the
4903        // monotonic allocator.
4904        let row_id = if self.schema.clustered {
4905            self.derive_clustered_row_id(&columns)?
4906        } else {
4907            self.allocator.alloc()?
4908        };
4909        let epoch = self.pending_epoch();
4910        let mut row = Row::new(row_id, epoch);
4911        for (col_id, val) in columns {
4912            row.columns.insert(col_id, val);
4913        }
4914        self.commit_rows(vec![row], assigned.is_some())?;
4915        Ok((row_id, assigned))
4916    }
4917
4918    /// Bulk upsert: many rows under a single WAL record + one index pass. Far
4919    /// cheaper than `put` in a loop for batch ingest.
4920    pub fn put_batch(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Vec<RowId>> {
4921        self.require_insert()?;
4922        Ok(self
4923            .put_batch_returning(batch)?
4924            .into_iter()
4925            .map(|(r, _)| r)
4926            .collect())
4927    }
4928
4929    /// Like [`Table::put_batch`] but each entry is paired with the engine-
4930    /// assigned `AUTO_INCREMENT` value (`Some` only when filled by the engine).
4931    pub fn put_batch_returning(
4932        &mut self,
4933        batch: Vec<Vec<(u16, Value)>>,
4934    ) -> Result<Vec<(RowId, Option<i64>)>> {
4935        let mut filled: Vec<FilledAutoIncRow> = Vec::with_capacity(batch.len());
4936        for mut cols in batch {
4937            let assigned = self.fill_auto_inc(&mut cols)?;
4938            self.apply_defaults(&mut cols)?;
4939            filled.push((cols, assigned));
4940        }
4941        for (cols, _) in &filled {
4942            self.schema.validate_values(cols)?;
4943        }
4944        let epoch = self.pending_epoch();
4945        let mut rows = Vec::with_capacity(filled.len());
4946        let mut ids = Vec::with_capacity(filled.len());
4947        let first_row_id = if self.schema.clustered {
4948            None
4949        } else {
4950            let count = u64::try_from(filled.len())
4951                .map_err(|_| MongrelError::Full("row-id allocation request is too large".into()))?;
4952            Some(self.allocator.alloc_range(count)?.0)
4953        };
4954        for (row_index, (cols, assigned)) in filled.into_iter().enumerate() {
4955            let row_id = match first_row_id {
4956                Some(first) => RowId(first + row_index as u64),
4957                None => self.derive_clustered_row_id(&cols)?,
4958            };
4959            let mut row = Row::new(row_id, epoch);
4960            for (c, v) in cols {
4961                row.columns.insert(c, v);
4962            }
4963            ids.push((row_id, assigned));
4964            rows.push(row);
4965        }
4966        let all_auto_generated = ids.iter().all(|(_, assigned)| assigned.is_some());
4967        self.commit_rows(rows, all_auto_generated)?;
4968        Ok(ids)
4969    }
4970
4971    /// Fill the `AUTO_INCREMENT` column for an upcoming row. When the column is
4972    /// omitted or [`Value::Null`] the next counter value is allocated and the
4973    /// cell is appended/replaced in `columns`; an explicit `Int64` is honored
4974    /// and advances the counter past it. Returns `Some(value)` when the engine
4975    /// allocated (so the caller can surface it), `None` otherwise.
4976    pub fn fill_auto_inc(&mut self, columns: &mut Vec<(u16, Value)>) -> Result<Option<i64>> {
4977        self.ensure_writable()?;
4978        let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
4979            return Ok(None);
4980        };
4981        let pos = columns.iter().position(|(c, _)| *c == cid);
4982        let assigned = match pos {
4983            Some(i) => match &columns[i].1 {
4984                Value::Null => {
4985                    let next = self.alloc_auto_inc_value()?;
4986                    columns[i].1 = Value::Int64(next);
4987                    Some(next)
4988                }
4989                Value::Int64(n) => {
4990                    self.advance_auto_inc_past(*n)?;
4991                    None
4992                }
4993                other => {
4994                    return Err(MongrelError::InvalidArgument(format!(
4995                        "AUTO_INCREMENT column {cid} must be Int64 or NULL, got {:?}",
4996                        other
4997                    )))
4998                }
4999            },
5000            None => {
5001                let next = self.alloc_auto_inc_value()?;
5002                columns.push((cid, Value::Int64(next)));
5003                Some(next)
5004            }
5005        };
5006        Ok(assigned)
5007    }
5008
5009    /// Apply column default expressions to `columns` at stage time (before
5010    /// NOT NULL validation). For each column carrying a `default_value`, if the
5011    /// column is omitted or explicitly `Null`, the default is applied. Explicit
5012    /// values are never overridden. Called after [`fill_auto_inc`](Self::fill_auto_inc)
5013    /// and before `validate_not_null`.
5014    pub fn apply_defaults(&self, columns: &mut Vec<(u16, Value)>) -> Result<()> {
5015        for col in &self.schema.columns {
5016            let Some(expr) = &col.default_value else {
5017                continue;
5018            };
5019            // Skip AUTO_INCREMENT columns — handled by fill_auto_inc.
5020            if col.flags.contains(ColumnFlags::AUTO_INCREMENT) {
5021                continue;
5022            }
5023            let pos = columns.iter().position(|(c, _)| *c == col.id);
5024            let needs_default = match pos {
5025                None => true,
5026                Some(i) => matches!(columns[i].1, Value::Null),
5027            };
5028            if !needs_default {
5029                continue;
5030            }
5031            let v = match expr {
5032                crate::schema::DefaultExpr::Static(v) => v.clone(),
5033                crate::schema::DefaultExpr::Now => Value::Bytes(iso_now_bytes()),
5034                crate::schema::DefaultExpr::Uuid => {
5035                    let mut buf = [0u8; 16];
5036                    getrandom::fill(&mut buf)
5037                        .map_err(|e| MongrelError::Other(format!("UUID generation failed: {e}")))?;
5038                    Value::Uuid(buf)
5039                }
5040            };
5041            match pos {
5042                None => columns.push((col.id, v)),
5043                Some(i) => columns[i].1 = v,
5044            }
5045        }
5046        Ok(())
5047    }
5048
5049    /// Allocate the next identity value, seeding the counter first if needed.
5050    fn alloc_auto_inc_value(&mut self) -> Result<i64> {
5051        self.ensure_auto_inc_seeded()?;
5052        // Borrow checker: re-read after the mutable `ensure` call returns.
5053        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5054        let v = ai.next;
5055        ai.next = ai
5056            .next
5057            .checked_add(1)
5058            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5059        Ok(v)
5060    }
5061
5062    /// Advance the counter past an explicit id, seeding first if needed so a
5063    /// pre-existing higher id elsewhere is never ignored.
5064    fn advance_auto_inc_past(&mut self, used: i64) -> Result<()> {
5065        self.ensure_auto_inc_seeded()?;
5066        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5067        let floor = used
5068            .checked_add(1)
5069            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5070            .max(1);
5071        if ai.next < floor {
5072            ai.next = floor;
5073        }
5074        Ok(())
5075    }
5076
5077    /// Seed the counter on first use by scanning `max(PK)` over all visible
5078    /// rows, so an upgraded table (legacy client-assigned ids, or a manifest
5079    /// migrated from `auto_inc_next == 0`) never hands out a colliding id.
5080    /// Idempotent: a no-op once seeded.
5081    fn ensure_auto_inc_seeded(&mut self) -> Result<()> {
5082        let needs_seed = match self.auto_inc {
5083            Some(ai) => !ai.seeded,
5084            None => return Ok(()),
5085        };
5086        if !needs_seed {
5087            return Ok(());
5088        }
5089        if self.seed_empty_auto_inc() {
5090            return Ok(());
5091        }
5092        let cid = self
5093            .auto_inc
5094            .as_ref()
5095            .expect("auto-inc column present")
5096            .column_id;
5097        let max = self.scan_max_int64(cid)?;
5098        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5099        let floor = max
5100            .checked_add(1)
5101            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5102            .max(1);
5103        if ai.next < floor {
5104            ai.next = floor;
5105        }
5106        ai.seeded = true;
5107        Ok(())
5108    }
5109
5110    fn alloc_auto_inc_range(&mut self, n: usize) -> Result<Option<i64>> {
5111        if n == 0 || self.auto_inc.is_none() {
5112            return Ok(None);
5113        }
5114        self.ensure_auto_inc_seeded()?;
5115        let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5116        let start = ai.next;
5117        let count = i64::try_from(n)
5118            .map_err(|_| MongrelError::Full("AUTO_INCREMENT range is too large".into()))?;
5119        ai.next = ai
5120            .next
5121            .checked_add(count)
5122            .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5123        Ok(Some(start))
5124    }
5125
5126    /// One-time `max(Int64 column)` over all MVCC-visible rows. Used to seed the
5127    /// auto-increment counter. Runs at most once per table (the manifest then
5128    /// checkpoints the seeded counter).
5129    fn scan_max_int64(&mut self, column_id: u16) -> Result<i64> {
5130        let mut max: i64 = 0;
5131        for r in self.memtable.visible_versions_at(Snapshot::unbounded()) {
5132            if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5133                if *n > max {
5134                    max = *n;
5135                }
5136            }
5137        }
5138        for r in self.mutable_run.visible_versions(Epoch(u64::MAX)) {
5139            if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5140                if *n > max {
5141                    max = *n;
5142                }
5143            }
5144        }
5145        for rr in self.run_refs.clone() {
5146            let reader = self.open_reader(rr.run_id)?;
5147            if let Some(stats) = reader.column_page_stats(column_id) {
5148                for s in stats {
5149                    if let Some(n) = crate::sorted_run::be_i64(s.max.as_deref()) {
5150                        if n > max {
5151                            max = n;
5152                        }
5153                    }
5154                }
5155            } else if reader.has_column(column_id) {
5156                if let columnar::NativeColumn::Int64 { data, validity } =
5157                    reader.column_native_shared(column_id)?
5158                {
5159                    for (i, n) in data.iter().enumerate() {
5160                        if (validity.is_empty() || columnar::validity_bit(&validity, i)) && *n > max
5161                        {
5162                            max = *n;
5163                        }
5164                    }
5165                }
5166            }
5167        }
5168        Ok(max)
5169    }
5170
5171    fn seed_empty_auto_inc(&mut self) -> bool {
5172        let Some(ai) = self.auto_inc.as_mut() else {
5173            return false;
5174        };
5175        if ai.seeded || self.live_count != 0 {
5176            return false;
5177        }
5178        if ai.next < 1 {
5179            ai.next = 1;
5180        }
5181        ai.seeded = true;
5182        true
5183    }
5184
5185    fn advance_auto_inc_from_native_columns(
5186        &mut self,
5187        columns: &[(u16, columnar::NativeColumn)],
5188        n: usize,
5189        live_before: u64,
5190    ) -> Result<()> {
5191        let Some(ai) = self.auto_inc.as_mut() else {
5192            return Ok(());
5193        };
5194        let Some((_, col)) = columns.iter().find(|(cid, _)| *cid == ai.column_id) else {
5195            return Ok(());
5196        };
5197        let columnar::NativeColumn::Int64 { data, validity } = col else {
5198            return Err(MongrelError::InvalidArgument(format!(
5199                "AUTO_INCREMENT column {} must be Int64",
5200                ai.column_id
5201            )));
5202        };
5203        let max = if native_int64_strictly_increasing(col, n) {
5204            data.get(n.saturating_sub(1)).copied()
5205        } else {
5206            data.iter()
5207                .take(n)
5208                .enumerate()
5209                .filter_map(|(i, v)| {
5210                    if validity.is_empty() || columnar::validity_bit(validity, i) {
5211                        Some(*v)
5212                    } else {
5213                        None
5214                    }
5215                })
5216                .max()
5217        };
5218        if let Some(max) = max {
5219            let floor = max
5220                .checked_add(1)
5221                .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5222                .max(1);
5223            if ai.next < floor {
5224                ai.next = floor;
5225            }
5226            if ai.seeded || live_before == 0 {
5227                ai.seeded = true;
5228            }
5229        }
5230        Ok(())
5231    }
5232
5233    fn fill_auto_inc_native_columns(
5234        &mut self,
5235        columns: &mut Vec<(u16, columnar::NativeColumn)>,
5236        n: usize,
5237    ) -> Result<()> {
5238        let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
5239            return Ok(());
5240        };
5241        let Some(pos) = columns.iter().position(|(id, _)| *id == cid) else {
5242            if let Some(start) = self.alloc_auto_inc_range(n)? {
5243                columns.push((
5244                    cid,
5245                    columnar::NativeColumn::Int64 {
5246                        data: (start..start.saturating_add(n as i64)).collect(),
5247                        validity: vec![0xFF; n.div_ceil(8)],
5248                    },
5249                ));
5250            }
5251            return Ok(());
5252        };
5253
5254        let columnar::NativeColumn::Int64 { data, validity } = &mut columns[pos].1 else {
5255            return Err(MongrelError::InvalidArgument(format!(
5256                "AUTO_INCREMENT column {cid} must be Int64"
5257            )));
5258        };
5259        if data.len() < n {
5260            return Err(MongrelError::InvalidArgument(format!(
5261                "AUTO_INCREMENT column {cid} has {} rows, expected {n}",
5262                data.len()
5263            )));
5264        }
5265        if columnar::all_non_null(validity, n) {
5266            return Ok(());
5267        }
5268        if validity.iter().all(|b| *b == 0) {
5269            if let Some(start) = self.alloc_auto_inc_range(n)? {
5270                for (i, slot) in data.iter_mut().take(n).enumerate() {
5271                    *slot = start.saturating_add(i as i64);
5272                }
5273                *validity = vec![0xFF; n.div_ceil(8)];
5274            }
5275            return Ok(());
5276        }
5277
5278        let new_validity = vec![0xFF; data.len().div_ceil(8)];
5279        for (i, slot) in data.iter_mut().enumerate().take(n) {
5280            if columnar::validity_bit(validity, i) {
5281                self.advance_auto_inc_past(*slot)?;
5282            } else {
5283                *slot = self.alloc_auto_inc_value()?;
5284            }
5285        }
5286        *validity = new_validity;
5287        Ok(())
5288    }
5289
5290    /// Reserve (but do not insert) the next `AUTO_INCREMENT` value, advancing
5291    /// the in-memory counter. Returns `None` when the table has no
5292    /// auto-increment column.
5293    ///
5294    /// This is the escape hatch for callers that stage the row with an explicit
5295    /// id inside a cross-table [`crate::Transaction`] — where the engine cannot
5296    /// fill the column on the `put` path (the row id + cells are only assembled
5297    /// at commit). Unlike the old Kit `__kit_sequences` sequence row, the
5298    /// reservation is a pure in-memory counter bump: no hot row, no second
5299    /// commit. It becomes durable when a row carrying the reserved id commits
5300    /// (the counter is checkpointed to the manifest in the same commit); an
5301    /// aborted reservation simply leaves a gap, which the never-reuse rule
5302    /// permits.
5303    pub fn reserve_auto_inc(&mut self) -> Result<Option<i64>> {
5304        self.ensure_writable()?;
5305        if self.auto_inc.is_none() {
5306            return Ok(None);
5307        }
5308        Ok(Some(self.alloc_auto_inc_value()?))
5309    }
5310
5311    /// Append `rows` under one WAL record. On a standalone table they are folded
5312    /// into the memtable + indexes immediately (single clock — no speculative-
5313    /// epoch hazard). On a mounted table (B1/B2) they are staged in
5314    /// `pending_rows` and applied at the real assigned epoch in `commit`, so a
5315    /// concurrent reader can never see them before their commit epoch.
5316    fn commit_rows(&mut self, rows: Vec<Row>, auto_inc_generated: bool) -> Result<()> {
5317        let payload = bincode::serialize(&rows)?;
5318        self.wal_append_data(Op::Put {
5319            table_id: self.table_id,
5320            rows: payload,
5321        })?;
5322        if self.is_shared() {
5323            self.pending_rows_auto_inc
5324                .extend(std::iter::repeat_n(auto_inc_generated, rows.len()));
5325            self.pending_rows.extend(rows);
5326        } else {
5327            self.apply_put_rows_inner(rows, !auto_inc_generated)?;
5328        }
5329        Ok(())
5330    }
5331
5332    /// Complete every fallible read/index preparation before a WAL commit can
5333    /// become durable. After this succeeds, row application is in-memory only.
5334    pub(crate) fn prepare_durable_publish(&mut self) -> Result<()> {
5335        self.ensure_indexes_complete()
5336    }
5337
5338    pub(crate) fn prepare_durable_publish_controlled(
5339        &mut self,
5340        control: &crate::ExecutionControl,
5341    ) -> Result<()> {
5342        self.ensure_indexes_complete_controlled(control, || true)?;
5343        Ok(())
5344    }
5345
5346    pub(crate) fn apply_put_rows_prepared(&mut self, rows: Vec<Row>) {
5347        self.apply_put_rows_inner_prepared(rows, true);
5348    }
5349
5350    fn apply_put_rows_inner(&mut self, rows: Vec<Row>, check_existing_pk: bool) -> Result<()> {
5351        if check_existing_pk {
5352            self.ensure_indexes_complete()?;
5353        }
5354        self.apply_put_rows_inner_prepared(rows, check_existing_pk);
5355        Ok(())
5356    }
5357
5358    /// Apply rows after [`Self::ensure_indexes_complete`] has succeeded. Every
5359    /// operation below is in-memory and infallible, so durable publication can
5360    /// never stop halfway through a batch on an I/O error.
5361    fn apply_put_rows_inner_prepared(&mut self, rows: Vec<Row>, check_existing_pk: bool) {
5362        // Single-row puts — the hot operational path — cannot contain an
5363        // intra-batch duplicate, so the winner/loser partition maps are pure
5364        // overhead. Same semantics as the batch path below with `losers = ∅`.
5365        if rows.len() == 1 {
5366            let row = rows.into_iter().next().expect("len checked");
5367            self.apply_put_row_single(row, check_existing_pk);
5368            return;
5369        }
5370        // One pass per row: track mutated columns, tombstone the previous
5371        // owner of the row's PK, index (which places the HOT entry), sample,
5372        // and materialize. Each row is applied completely — including its
5373        // memtable upsert — before the next row processes, so "the last row
5374        // wins" falls out naturally for an intra-batch duplicate PK: the
5375        // earlier row is already materialized and gets tombstoned like any
5376        // other displaced owner (same visible state as pre-partitioning the
5377        // batch into winners and losers, without materializing a winner map
5378        // over the whole batch).
5379        //
5380        // Upsert probing is skipped entirely when no PK owner can be
5381        // displaced: `check_existing_pk == false` means every PK is a fresh
5382        // engine-assigned AUTO_INCREMENT value; an empty HOT index plus
5383        // strictly-increasing batch PKs (the append-style batch, mirroring
5384        // `bulk_pk_winner_indices`' fast path) rules out both pre-existing
5385        // owners and intra-batch duplicates.
5386        let pk_id = self.schema.primary_key().map(|c| c.id);
5387        let probe = match pk_id {
5388            Some(pid) => {
5389                check_existing_pk
5390                    && !(self.hot.is_empty() && rows_pk_strictly_increasing(&rows, pid))
5391            }
5392            None => false,
5393        };
5394        // The PK reverse map is maintained inline only once a delete has built
5395        // it (`pk_by_row_complete`); ingest-only tables never pay for it.
5396        let maintain_pk_by_row = pk_id.is_some() && self.pk_by_row_complete;
5397        for r in rows {
5398            for &cid in r.columns.keys() {
5399                self.pending_put_cols.insert(cid);
5400            }
5401            let mut replaced_image: Option<Row> = None;
5402            match pk_id {
5403                Some(pid) if probe || maintain_pk_by_row => {
5404                    if let Some(pk_val) = r.columns.get(&pid) {
5405                        let key = self.index_lookup_key(pid, pk_val);
5406                        if probe {
5407                            // Prefer `recent_delete_preimages` (Kit
5408                            // delete+put: the pre-image is needed to drive
5409                            // Bitmap delta maintenance). Fall back to the
5410                            // stale HOT entry when the preimage was cleared
5411                            // (e.g., after a rebuild). `apply_delete_at`
5412                            // preserves the HOT entry so the stale-entry
5413                            // branch is the common one for a same-PK Kit
5414                            // delete+put.
5415                            if let Some(old) = self.recent_delete_preimages.remove(&key) {
5416                                replaced_image = Some(old);
5417                                if let Some(old_rid) = self.hot.get(&key) {
5418                                    if old_rid != r.row_id {
5419                                        self.tombstone_row(
5420                                            old_rid,
5421                                            r.committed_epoch,
5422                                            r.commit_ts,
5423                                            true,
5424                                        );
5425                                    }
5426                                }
5427                            } else if let Some(old_rid) = self.hot.get(&key) {
5428                                if old_rid != r.row_id {
5429                                    replaced_image = self.get(old_rid, self.snapshot());
5430                                    self.tombstone_row(
5431                                        old_rid,
5432                                        r.committed_epoch,
5433                                        r.commit_ts,
5434                                        true,
5435                                    );
5436                                }
5437                            }
5438                        }
5439                        if maintain_pk_by_row {
5440                            self.pk_by_row.insert(r.row_id, key);
5441                        }
5442                    }
5443                }
5444                Some(_) => {}
5445                None => {
5446                    self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5447                }
5448            }
5449            if let Some(old) = replaced_image {
5450                self.maintain_indexes_on_pk_replace(&old, &r);
5451            } else {
5452                self.index_row(&r);
5453            }
5454            self.reservoir.offer(r.row_id.0);
5455            self.memtable.upsert(r);
5456            // Count as each row lands so a later duplicate's tombstone
5457            // decrement (in `tombstone_row`) sees an up-to-date value.
5458            self.live_count = self.live_count.saturating_add(1);
5459        }
5460        self.data_generation = self.data_generation.wrapping_add(1);
5461    }
5462
5463    /// One-row specialization of [`Table::apply_put_rows_inner`]: identical
5464    /// upsert semantics (tombstone the previous PK owner, insert into HOT,
5465    /// index, sample, materialize) without the per-batch winner/loser maps.
5466    ///
5467    /// When a same-PK put replaces an older live row (the product update path
5468    /// after delete+put normalize, or a direct upsert), Bitmap secondary indexes
5469    /// are maintained via [`crate::index::maintain_bitmap_secondary_on_replace`]
5470    /// so unchanged equality keys only re-point row ids and changed keys move —
5471    /// rather than leaving tombstoned row ids permanently in the bitmaps.
5472    fn apply_put_row_single(&mut self, row: Row, check_existing_pk: bool) {
5473        for &cid in row.columns.keys() {
5474            self.pending_put_cols.insert(cid);
5475        }
5476        let epoch = row.committed_epoch;
5477        let mut replaced_image: Option<Row> = None;
5478        if let Some(pk_col) = self.schema.primary_key() {
5479            let pk_id = pk_col.id;
5480            if let Some(pk_val) = row.columns.get(&pk_id) {
5481                // `index_row` / HOT-only path below writes the HOT entry. The
5482                // reverse map is maintained inline only once a delete has built
5483                // it; ingest-only tables never pay for it.
5484                let maintain_pk_by_row = self.pk_by_row_complete;
5485                if check_existing_pk || maintain_pk_by_row {
5486                    let key = self.index_lookup_key(pk_id, pk_val);
5487                    if check_existing_pk {
5488                        // Prefer `recent_delete_preimages` (Kit delete+put:
5489                        // the pre-image is needed to drive Bitmap delta
5490                        // maintenance). Fall back to the stale HOT entry for
5491                        // cases where `recent_delete_preimages` was cleared
5492                        // (e.g., after a rebuild) but HOT still maps to the
5493                        // old rid. `apply_delete_at` preserves the HOT entry
5494                        // so the stale-entry branch is the common one for a
5495                        // same-PK Kit delete+put.
5496                        if let Some(old) = self.recent_delete_preimages.remove(&key) {
5497                            replaced_image = Some(old);
5498                            if let Some(old_rid) = self.hot.get(&key) {
5499                                if old_rid != row.row_id {
5500                                    self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5501                                }
5502                            }
5503                        } else if let Some(old_rid) = self.hot.get(&key) {
5504                            if old_rid != row.row_id {
5505                                // Capture the pre-image while it is still live so
5506                                // secondary-index delta maintenance can drop the
5507                                // old row-id from Bitmap keys.
5508                                replaced_image = self.get(old_rid, self.snapshot());
5509                                self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5510                            }
5511                        }
5512                    }
5513                    if maintain_pk_by_row {
5514                        self.pk_by_row.insert(row.row_id, key);
5515                    }
5516                }
5517            }
5518        } else {
5519            self.hot
5520                .insert(row.row_id.0.to_be_bytes().to_vec(), row.row_id);
5521        }
5522        if let Some(old) = replaced_image {
5523            self.maintain_indexes_on_pk_replace(&old, &row);
5524        } else {
5525            self.index_row(&row);
5526        }
5527        self.reservoir.offer(row.row_id.0);
5528        self.memtable.upsert(row);
5529        self.live_count = self.live_count.saturating_add(1);
5530        self.data_generation = self.data_generation.wrapping_add(1);
5531    }
5532
5533    /// PK-replace index maintenance: Bitmap secondaries via delta plan; other
5534    /// secondary kinds + HOT via the existing full path for those families.
5535    fn maintain_indexes_on_pk_replace(&mut self, old: &Row, new: &Row) {
5536        let has_partial = self
5537            .schema
5538            .indexes
5539            .iter()
5540            .any(|idx| idx.predicate.is_some());
5541        if has_partial {
5542            // Partial predicates make selective unindex subtle; drop old Bitmap
5543            // memberships then full-index the new image (still cleans tombstone
5544            // pollution for Bitmap keys on the replace path only).
5545            self.unindex_bitmap_membership(old);
5546            self.index_row(new);
5547            return;
5548        }
5549
5550        crate::index::maintain_bitmap_secondary_on_replace(
5551            &self.schema,
5552            &mut self.bitmap,
5553            old,
5554            new,
5555        );
5556        self.index_row_non_bitmap(new);
5557    }
5558
5559    /// Index HOT + every non-Bitmap secondary for `row`. Bitmap secondaries are
5560    /// assumed already maintained by a delta plan on the replace path.
5561    fn index_row_non_bitmap(&mut self, row: &Row) {
5562        if row.deleted {
5563            return;
5564        }
5565        let effective = if self.column_keys.is_empty() {
5566            None
5567        } else {
5568            Some(self.tokenized_for_indexes(row))
5569        };
5570        let source = effective.as_ref().unwrap_or(row);
5571        for idef in &self.schema.indexes {
5572            if idef.kind == crate::schema::IndexKind::Bitmap {
5573                continue;
5574            }
5575            index_into_single(
5576                idef,
5577                &self.schema,
5578                source,
5579                &mut self.hot,
5580                &mut self.bitmap,
5581                &mut self.ann,
5582                &mut self.fm,
5583                &mut self.sparse,
5584                &mut self.minhash,
5585            );
5586        }
5587        if let Some(pk_col) = self.schema.primary_key() {
5588            if let Some(pk_val) = source.columns.get(&pk_col.id) {
5589                let key = if self.column_keys.is_empty() {
5590                    pk_val.encode_key()
5591                } else {
5592                    self.index_lookup_key(pk_col.id, pk_val)
5593                };
5594                self.hot.insert(key, source.row_id);
5595            }
5596        }
5597    }
5598
5599    /// Allocate a fresh row id (advancing the table's allocator). Used by the
5600    /// cross-table `Transaction` to assign ids before sealing a row.
5601    pub(crate) fn alloc_row_id(&mut self) -> Result<RowId> {
5602        self.allocator.alloc()
5603    }
5604
5605    /// For clustered (WITHOUT ROWID) tables: derive a deterministic `RowId`
5606    /// from the primary-key value so the same PK always maps to the same row.
5607    /// Uses a stable hash of the PK's `encode_key()` bytes, cast to `u64`.
5608    /// This gives WITHOUT ROWID tables idempotent upsert semantics (same PK →
5609    /// same RowId, no allocator waste) without changing the storage format.
5610    fn derive_clustered_row_id(&self, columns: &[(u16, Value)]) -> Result<RowId> {
5611        let pk = self.schema.primary_key().ok_or_else(|| {
5612            MongrelError::Schema("clustered table requires a single-column primary key".into())
5613        })?;
5614        let pk_val = columns
5615            .iter()
5616            .find(|(id, _)| *id == pk.id)
5617            .map(|(_, v)| v)
5618            .ok_or_else(|| {
5619                MongrelError::Schema(format!(
5620                    "clustered table missing primary key column {} ({})",
5621                    pk.id, pk.name
5622                ))
5623            })?;
5624        Ok(clustered_row_id(pk_val))
5625    }
5626
5627    /// Apply the metadata for rows that were spilled to a linked uniform-epoch
5628    /// run (P3.4): update the HOT + secondary indexes, the reservoir, the
5629    /// allocator high-water mark, and `live_count` — but **do NOT** insert the
5630    /// rows into the memtable. The rows are served from the linked run (which the
5631    /// scan/merge path reads at the run's commit epoch), so materializing them in
5632    /// the memtable too would defeat the point of spilling (peak memory stays
5633    /// bounded). Caller must have linked the run before reads can resolve indexes.
5634    pub(crate) fn apply_run_metadata_prepared(&mut self, rows: &[Row]) -> Result<()> {
5635        if rows.iter().any(|row| row.row_id.0 >= u64::MAX - 1) {
5636            return Err(MongrelError::Full("row-id namespace exhausted".into()));
5637        }
5638        let n = rows.len();
5639        for r in rows {
5640            for &cid in r.columns.keys() {
5641                self.pending_put_cols.insert(cid);
5642            }
5643        }
5644        let (losers, winner_pks) = self.partition_pk_winners(rows);
5645        let epoch = rows.first().map(|r| r.committed_epoch).unwrap_or(Epoch(0));
5646        // Tombstone pre-existing rows that conflict with winners.
5647        let group_ts = rows.first().and_then(|r| r.commit_ts);
5648        for (key, &row_id) in &winner_pks {
5649            if let Some(old_rid) = self.hot.get(key) {
5650                if old_rid != row_id {
5651                    self.tombstone_row(old_rid, epoch, group_ts, true);
5652                }
5653            }
5654        }
5655        // Hide duplicate-PK rows inside this uniform-epoch run by tombstoning
5656        // their row ids in the memtable overlay (the overlay wins over the run).
5657        for &loser_rid in &losers {
5658            self.tombstone_row(loser_rid, epoch, group_ts, false);
5659        }
5660        // Insert the winners into HOT.
5661        for (key, row_id) in winner_pks {
5662            self.insert_hot_pk(key, row_id);
5663        }
5664        if self.schema.primary_key().is_none() {
5665            for r in rows {
5666                self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5667            }
5668        }
5669        for r in rows {
5670            self.allocator.advance_to(r.row_id)?;
5671            if !losers.contains(&r.row_id) {
5672                self.index_row(r);
5673            }
5674        }
5675        for r in rows {
5676            if !losers.contains(&r.row_id) {
5677                self.reservoir.offer(r.row_id.0);
5678            }
5679        }
5680        self.live_count = self.live_count.saturating_add((n - losers.len()) as u64);
5681        self.data_generation = self.data_generation.wrapping_add(1);
5682        Ok(())
5683    }
5684
5685    /// Apply already-committed puts + tombstones during shared-WAL recovery
5686    /// (spec §15 pass 2). Advances the allocator, upserts/tombstones the
5687    /// memtable, and indexes the rows — but does NOT touch `live_count` (the
5688    /// manifest is authoritative) and does NOT append to the WAL.
5689    pub(crate) fn recover_apply(
5690        &mut self,
5691        rows: Vec<Row>,
5692        deletes: Vec<(RowId, Epoch)>,
5693    ) -> Result<()> {
5694        // Rows from different transactions have different epochs and can be
5695        // upserted sequentially. Rows inside one transaction share an epoch, so
5696        // duplicate PKs within that transaction must keep only the last winner.
5697        let mut by_epoch: std::collections::BTreeMap<Epoch, Vec<Row>> =
5698            std::collections::BTreeMap::new();
5699        for row in rows {
5700            if row.row_id.0 >= u64::MAX - 1 {
5701                return Err(MongrelError::Full("row-id namespace exhausted".into()));
5702            }
5703            self.allocator.advance_to(row.row_id)?;
5704            // Mirror the row-id advance for the AUTO_INCREMENT counter: WAL
5705            // replay must not hand out an id a recovered row already claimed.
5706            // `seeded` is intentionally left untouched so a still-unseeded
5707            // counter still scans `max(PK)` to cover already-flushed rows.
5708            if let Some(ai) = self.auto_inc.as_mut() {
5709                if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
5710                    let next = n.checked_add(1).ok_or_else(|| {
5711                        MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
5712                    })?;
5713                    if next > ai.next {
5714                        ai.next = next;
5715                    }
5716                }
5717            }
5718            by_epoch.entry(row.committed_epoch).or_default().push(row);
5719        }
5720        for (epoch, group) in by_epoch {
5721            let (losers, winner_pks) = self.partition_pk_winners(&group);
5722            // Tombstone pre-existing PK owners.
5723            let group_ts = group.first().and_then(|r| r.commit_ts);
5724            for (key, &row_id) in &winner_pks {
5725                if let Some(old_rid) = self.hot.get(key) {
5726                    if old_rid != row_id {
5727                        self.tombstone_row(old_rid, epoch, group_ts, false);
5728                    }
5729                }
5730            }
5731            for (key, row_id) in winner_pks {
5732                self.insert_hot_pk(key, row_id);
5733            }
5734            if self.schema.primary_key().is_none() {
5735                for r in &group {
5736                    self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5737                }
5738            }
5739            for r in &group {
5740                if !losers.contains(&r.row_id) {
5741                    self.memtable.upsert(r.clone());
5742                    self.index_row(r);
5743                }
5744            }
5745        }
5746        for (rid, epoch) in deletes {
5747            self.memtable.tombstone(rid, epoch);
5748            self.remove_hot_for_row(rid, epoch);
5749        }
5750        // Reservoir stays lazy — see `ensure_reservoir_complete` — rather than
5751        // eagerly materializing every row on every WAL-replay batch.
5752        self.reservoir_complete = false;
5753        Ok(())
5754    }
5755
5756    /// Highest epoch whose data is durable in a sorted run (spec §7.1).
5757    pub(crate) fn flushed_epoch(&self) -> u64 {
5758        self.flushed_epoch
5759    }
5760
5761    pub(crate) fn set_flushed_epoch(&mut self, epoch: Epoch) {
5762        self.flushed_epoch = self.flushed_epoch.max(epoch.0);
5763    }
5764
5765    /// Validate that `cells` satisfy the schema's NOT NULL constraints.
5766    pub(crate) fn validate_cells_not_null(&self, cells: &[(u16, Value)]) -> Result<()> {
5767        self.schema.validate_values(cells)
5768    }
5769
5770    /// Column-major NOT NULL validation for the bulk-load paths. Every schema
5771    /// column that is not marked NULLABLE must be present in `columns` and have
5772    /// no null validity bits over its first `n` rows.
5773    fn validate_columns_not_null(
5774        &self,
5775        columns: &[(u16, columnar::NativeColumn)],
5776        n: usize,
5777    ) -> Result<()> {
5778        let by_id: HashMap<u16, &columnar::NativeColumn> =
5779            columns.iter().map(|(id, c)| (*id, c)).collect();
5780        for col in &self.schema.columns {
5781            if !col.flags.contains(ColumnFlags::NULLABLE) {
5782                match by_id.get(&col.id) {
5783                    None => {
5784                        return Err(MongrelError::InvalidArgument(format!(
5785                            "column '{}' ({}) is NOT NULL but was omitted from the bulk load",
5786                            col.name, col.id
5787                        )));
5788                    }
5789                    Some(c) => {
5790                        if c.null_count(n) != 0 {
5791                            return Err(MongrelError::InvalidArgument(format!(
5792                                "column '{}' ({}) is NOT NULL but the bulk load contains nulls",
5793                                col.name, col.id
5794                            )));
5795                        }
5796                    }
5797                }
5798            }
5799            if let TypeId::Enum { variants } = &col.ty {
5800                let Some(columnar::NativeColumn::Bytes { .. }) = by_id.get(&col.id).copied() else {
5801                    if by_id.contains_key(&col.id) {
5802                        return Err(MongrelError::InvalidArgument(format!(
5803                            "column '{}' ({}) enum requires a bytes column",
5804                            col.name, col.id
5805                        )));
5806                    }
5807                    continue;
5808                };
5809                for index in 0..n {
5810                    let Some(value) = columnar::native_bytes_at(by_id[&col.id], index) else {
5811                        continue;
5812                    };
5813                    if !variants.iter().any(|variant| variant.as_bytes() == value) {
5814                        return Err(MongrelError::InvalidArgument(format!(
5815                            "column '{}' ({}) enum value {:?} is not one of {:?}",
5816                            col.name,
5817                            col.id,
5818                            String::from_utf8_lossy(value),
5819                            variants
5820                        )));
5821                    }
5822                }
5823            }
5824        }
5825        Ok(())
5826    }
5827
5828    /// For a bulk-loaded batch, compute the row indices that survive primary-
5829    /// key upsert: for each PK value the last occurrence wins, earlier
5830    /// duplicates are dropped. Rows with a null PK value are always kept. Returns
5831    /// `None` when there is no primary key or no compaction is needed.
5832    fn bulk_pk_winner_indices(
5833        &self,
5834        columns: &[(u16, columnar::NativeColumn)],
5835        n: usize,
5836    ) -> Option<Vec<usize>> {
5837        let pk_col = self.schema.primary_key()?;
5838        let pk_id = pk_col.id;
5839        let pk_ty = pk_col.ty.clone();
5840        let by_id: HashMap<u16, &columnar::NativeColumn> =
5841            columns.iter().map(|(id, c)| (*id, c)).collect();
5842        let pk_native = by_id.get(&pk_id)?;
5843        if native_int64_strictly_increasing(pk_native, n) {
5844            return None;
5845        }
5846        // key -> index of the last row that carried that PK value.
5847        let mut last: HashMap<Vec<u8>, usize> = HashMap::new();
5848        let mut null_pk_rows: Vec<usize> = Vec::new();
5849        for i in 0..n {
5850            match bulk_index_key(&self.column_keys, pk_id, pk_ty.clone(), pk_native, i) {
5851                Some(key) => {
5852                    last.insert(key, i);
5853                }
5854                None => null_pk_rows.push(i),
5855            }
5856        }
5857        let mut winners: HashSet<usize> = last.values().copied().collect();
5858        for i in null_pk_rows {
5859            winners.insert(i);
5860        }
5861        Some((0..n).filter(|i| winners.contains(i)).collect())
5862    }
5863
5864    /// Logically delete `row_id` (effective at the next commit).
5865    pub fn delete(&mut self, row_id: RowId) -> Result<()> {
5866        self.require_delete()?;
5867        let epoch = self.pending_epoch();
5868        self.wal_append_data(Op::Delete {
5869            table_id: self.table_id,
5870            row_ids: vec![row_id],
5871        })?;
5872        if self.is_shared() {
5873            self.pending_dels.push(row_id);
5874        } else {
5875            self.apply_delete(row_id, epoch);
5876        }
5877        Ok(())
5878    }
5879
5880    pub fn delete_returning(&mut self, row_id: RowId) -> Result<Option<OwnedRow>> {
5881        let pre = self.get(row_id, self.snapshot());
5882        self.delete(row_id)?;
5883        Ok(pre.map(|row| {
5884            let mut columns: Vec<_> = row.columns.into_iter().collect();
5885            columns.sort_by_key(|(id, _)| *id);
5886            OwnedRow { columns }
5887        }))
5888    }
5889
5890    /// Durably remove every row in the table once the current write span commits.
5891    pub fn truncate(&mut self) -> Result<()> {
5892        self.require_delete()?;
5893        let epoch = self.pending_epoch();
5894        self.wal_append_data(Op::TruncateTable {
5895            table_id: self.table_id,
5896        })?;
5897        self.pending_rows.clear();
5898        self.pending_rows_auto_inc.clear();
5899        self.pending_dels.clear();
5900        self.pending_truncate = Some(epoch);
5901        Ok(())
5902    }
5903
5904    /// Apply an already-durable truncate without appending to the WAL.
5905    pub(crate) fn apply_truncate(&mut self, _epoch: Epoch) {
5906        // Unlink active topology in the next manifest before removing any run
5907        // file. A crash before that manifest is durable must still be able to
5908        // open the old manifest and replay the durable truncate from WAL.
5909        // Unreferenced files are safe orphans and `gc()` removes them later.
5910        self.run_refs.clear();
5911        self.retiring.clear();
5912        self.memtable = Memtable::new();
5913        self.mutable_run = MutableRun::new();
5914        self.hot = HotIndex::new();
5915        let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
5916        self.bitmap = bitmap;
5917        self.ann = ann;
5918        self.fm = fm;
5919        self.sparse = sparse;
5920        self.minhash = minhash;
5921        self.learned_range = Arc::new(HashMap::new());
5922        self.pk_by_row.clear();
5923        self.pk_by_row_complete = false;
5924        self.live_count = 0;
5925        self.reservoir = crate::reservoir::Reservoir::default();
5926        self.reservoir_complete = true;
5927        self.had_deletes = true;
5928        self.agg_cache = Arc::new(HashMap::new());
5929        self.global_idx_epoch = 0;
5930        self.refresh_active_run_fingerprint();
5931        self.indexes_complete = true;
5932        self.pending_delete_rids.clear();
5933        self.pending_put_cols.clear();
5934        self.pending_rows.clear();
5935        self.pending_rows_auto_inc.clear();
5936        self.pending_dels.clear();
5937        self.clear_result_cache();
5938        self.invalidate_index_checkpoint();
5939        self.data_generation = self.data_generation.wrapping_add(1);
5940    }
5941
5942    /// Apply a tombstone (already-durable on the WAL) at `epoch` without
5943    /// appending to the per-table WAL. Used by the cross-table `Transaction`.
5944    pub(crate) fn apply_delete(&mut self, row_id: RowId, epoch: Epoch) {
5945        self.apply_delete_at(row_id, epoch, None);
5946    }
5947
5948    /// Apply a tombstone stamped with an optional HLC commit timestamp (P0.5).
5949    pub(crate) fn apply_delete_at(
5950        &mut self,
5951        row_id: RowId,
5952        epoch: Epoch,
5953        commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
5954    ) {
5955        // Capture pre-image before the tombstone lands so (1) Kit delete+put
5956        // can re-point Bitmap keys via `recent_delete_preimages` (the subsequent
5957        // put finds a stale HOT entry, and `index_row` reads the preimage from
5958        // `recent_delete_preimages` to drive delta maintenance), and (2) the
5959        // HOT entry is preserved so a `Condition::Pk` lookup can observe the
5960        // tombstone via `self.get(r, snap) == None` and record
5961        // `HotFallbackReason::Tombstone` (and so a pinned-snapshot lookup
5962        // records `HistoricalSnapshot` on the HOT-hit branch instead of
5963        // degrading to `MissingMapping` on the HOT-miss branch).
5964        let preimage = self.get(row_id, self.snapshot());
5965        if let Some(row) = preimage {
5966            if let Some(pk_col) = self.schema.primary_key() {
5967                if let Some(pk_val) = row.columns.get(&pk_col.id) {
5968                    let key = self.index_lookup_key(pk_col.id, pk_val);
5969                    self.recent_delete_preimages.insert(key, row);
5970                }
5971            }
5972        }
5973        self.tombstone_row(row_id, epoch, commit_ts, true);
5974        self.data_generation = self.data_generation.wrapping_add(1);
5975    }
5976
5977    /// Drop this row's membership from every Bitmap secondary (best-effort).
5978    /// Used on replace / partial-predicate paths that must re-point equality
5979    /// keys; pure deletes keep membership so historical snapshots can still
5980    /// discover the rid via BitmapEq (see [`Self::apply_delete_at`]).
5981    fn unindex_bitmap_membership(&mut self, row: &Row) {
5982        if row.deleted {
5983            return;
5984        }
5985        for idef in &self.schema.indexes {
5986            if idef.kind != crate::schema::IndexKind::Bitmap {
5987                continue;
5988            }
5989            if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
5990                if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
5991                    b.remove(&key, row.row_id);
5992                }
5993            }
5994        }
5995    }
5996
5997    /// Union Bitmap membership for a point (`lo == hi`) int64 range query into
5998    /// `set`, then re-merge overlay so pure-memtable rows still win. No-op when
5999    /// the column has no Bitmap index.
6000    fn union_bitmap_point_i64(
6001        &self,
6002        set: &mut RowIdSet,
6003        column_id: u16,
6004        value: i64,
6005        snapshot: Snapshot,
6006    ) {
6007        let Some(b) = self.bitmap.get(&column_id) else {
6008            return;
6009        };
6010        let encoded = Value::Int64(value).encode_key();
6011        let lookup = self.index_lookup_key_bytes(column_id, &encoded);
6012        for rid in b.get(&lookup).iter() {
6013            set.insert(u64::from(rid));
6014        }
6015        // Drop rids whose newest overlay version is a tombstone (append-only
6016        // leftovers). Live overlay versions for this value are re-inserted by
6017        // the overlay range scan.
6018        set.remove_many(self.overlay_tombstoned_rids(snapshot));
6019        self.range_scan_overlay_i64(set, column_id, value, value, snapshot);
6020    }
6021
6022    /// Tombstone `row_id` at `epoch`. When `adjust_live_count` is true the
6023    /// table's `live_count` is decremented (used on the live write path); during
6024    /// recovery the manifest is authoritative so the flag is false.
6025    ///
6026    /// `live_count` is decremented only when the prior visible version of
6027    /// `row_id` was a live row. A prior tombstone (either from earlier in this
6028    /// commit or from a previous commit) means the live-count adjustment has
6029    /// already happened — the cross-table `Transaction` path can call
6030    /// `tombstone_row` on the same rid twice in one commit (Delete + the
6031    /// Put's stale HOT tombstone), and standalone callers can hit the same
6032    /// rid twice across commits. Without this guard `live_count` drifts
6033    /// negative (saturating to 0) and `Table::count()` returns a value below
6034    /// the true live-row count.
6035    fn tombstone_row(
6036        &mut self,
6037        row_id: RowId,
6038        epoch: Epoch,
6039        commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
6040        adjust_live_count: bool,
6041    ) {
6042        let prev_was_live = if adjust_live_count {
6043            match self.memtable.get_version(row_id, epoch) {
6044                Some((_, prev)) => !prev.deleted,
6045                None => true,
6046            }
6047        } else {
6048            false
6049        };
6050        let tombstone = Row {
6051            row_id,
6052            committed_epoch: epoch,
6053            columns: std::collections::HashMap::new(),
6054            deleted: true,
6055            commit_ts,
6056        };
6057        self.memtable.upsert(tombstone);
6058        self.pk_by_row.remove(&row_id);
6059        if prev_was_live {
6060            self.live_count = self.live_count.saturating_sub(1);
6061        }
6062        // Track for fine-grained cache invalidation (c).
6063        self.pending_delete_rids.insert(row_id.0 as u32);
6064        // A delete makes the incremental aggregate cache (row-id watermark
6065        // delta) unsafe — permanently disable it for this table.
6066        self.had_deletes = true;
6067        self.agg_cache = Arc::new(HashMap::new());
6068    }
6069
6070    /// If `row_id` has a primary-key value and the HOT index currently maps
6071    /// that PK to this row id, remove the entry. Keeps the PK→RowId mapping
6072    /// consistent after deletes and before upserts.
6073    fn remove_hot_for_row(&mut self, row_id: RowId, epoch: Epoch) {
6074        let Some(pk_col) = self.schema.primary_key() else {
6075            return;
6076        };
6077        // Warm path: a prior delete in this process already paid the
6078        // reverse-map rebuild below, so it's kept up to date — O(1).
6079        if self.pk_by_row_complete {
6080            if let Some(key) = self.pk_by_row.remove(&row_id) {
6081                if self.hot.get(&key) == Some(row_id) {
6082                    self.hot.remove(&key);
6083                }
6084            }
6085            return;
6086        }
6087        // Cold path (the common case: a short-lived process — CLI,
6088        // NAPI-per-call — that deletes once and exits): derive the PK
6089        // straight from the row's own pre-delete version via a targeted
6090        // get_version lookup (memtable -> mutable_run -> runs, the same
6091        // page-pruned lookup `Table::get` uses) instead of paying
6092        // `refresh_pk_by_row_from_hot`'s O(table-size) rebuild for a single
6093        // delete. `pk_by_row` is deliberately left incomplete here — same
6094        // "puts leave the reverse map stale" tradeoff, extended to this path.
6095        //
6096        // Look up at `epoch - 1`, not `epoch`: on the live-delete call site
6097        // this delete's own tombstone hasn't landed yet either way, but on
6098        // the WAL-replay call sites (`recover_apply`, `open_in`) the
6099        // memtable tombstone for this exact row/epoch is already applied
6100        // before this runs. Querying `epoch` would see that tombstone
6101        // (empty columns) and fall through to the full rebuild every time a
6102        // replayed delete exists; `epoch - 1` is still >= any real prior
6103        // version's committed_epoch (epochs are unique and monotonic), so it
6104        // finds the same pre-delete row either way.
6105        let lookup_epoch = Epoch(epoch.0.saturating_sub(1));
6106        if self.indexes_complete {
6107            let pk_val = self
6108                .memtable
6109                .get_version(row_id, lookup_epoch)
6110                .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6111                .or_else(|| {
6112                    self.mutable_run
6113                        .get_version(row_id, lookup_epoch)
6114                        .filter(|(_, r)| !r.deleted)
6115                        .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6116                })
6117                .or_else(|| {
6118                    self.run_refs.iter().find_map(|rr| {
6119                        let mut reader = self.open_reader(rr.run_id).ok()?;
6120                        let (_, deleted, val) = reader
6121                            .get_version_column(row_id, lookup_epoch, pk_col.id)
6122                            .ok()??;
6123                        if deleted {
6124                            return None;
6125                        }
6126                        val
6127                    })
6128                });
6129            if let Some(pk_val) = pk_val {
6130                let key = self.index_lookup_key(pk_col.id, &pk_val);
6131                if self.hot.get(&key) == Some(row_id) {
6132                    self.hot.remove(&key);
6133                }
6134                return;
6135            }
6136        }
6137        // Fallback: full reverse-map rebuild, guaranteed correct. Reached
6138        // when indexes aren't complete yet, or the row was already gone by
6139        // the time this ran (e.g. already tombstoned in an overlay ahead of
6140        // this HOT cleanup, as `rebuild_indexes_from_runs` does).
6141        self.refresh_pk_by_row_from_hot();
6142        if let Some(key) = self.pk_by_row.remove(&row_id) {
6143            if self.hot.get(&key) == Some(row_id) {
6144                self.hot.remove(&key);
6145            }
6146        }
6147    }
6148
6149    /// For a batch of rows that share the same commit epoch, decide which rows
6150    /// win for each primary-key value. Returns the set of "loser" row ids that
6151    /// must be skipped/overwritten, and a map from PK lookup key to the winning
6152    /// row id. Rows without a PK value are always winners.
6153    fn partition_pk_winners(
6154        &self,
6155        rows: &[Row],
6156    ) -> (
6157        std::collections::HashSet<RowId>,
6158        std::collections::HashMap<Vec<u8>, RowId>,
6159    ) {
6160        let mut losers = std::collections::HashSet::new();
6161        let Some(pk_col) = self.schema.primary_key() else {
6162            return (losers, std::collections::HashMap::new());
6163        };
6164        let pk_id = pk_col.id;
6165        let mut winners: std::collections::HashMap<Vec<u8>, RowId> =
6166            std::collections::HashMap::new();
6167        for r in rows {
6168            let Some(pk_val) = r.columns.get(&pk_id) else {
6169                continue;
6170            };
6171            let key = self.index_lookup_key(pk_id, pk_val);
6172            if let Some(&old_rid) = winners.get(&key) {
6173                losers.insert(old_rid);
6174            }
6175            winners.insert(key, r.row_id);
6176        }
6177        (losers, winners)
6178    }
6179
6180    fn index_row(&mut self, row: &Row) {
6181        if row.deleted {
6182            return;
6183        }
6184        // Partial index filtering: skip rows that don't match any index's
6185        // predicate. The predicate is a SQL WHERE clause string evaluated
6186        // against the row's column values. For now, we support a simple
6187        // "column_name IS NOT NULL" and "column_name = value" syntax that
6188        // covers the common partial-index patterns (e.g. WHERE deleted_at
6189        // IS NULL). More complex predicates require a full expression
6190        // evaluator in core (future work).
6191        let any_predicate = self
6192            .schema
6193            .indexes
6194            .iter()
6195            .any(|idx| idx.predicate.is_some());
6196        if any_predicate {
6197            let columns_map: HashMap<u16, &Value> =
6198                row.columns.iter().map(|(k, v)| (*k, v)).collect();
6199            let name_to_id: HashMap<&str, u16> = self
6200                .schema
6201                .columns
6202                .iter()
6203                .map(|c| (c.name.as_str(), c.id))
6204                .collect();
6205            for idx in &self.schema.indexes {
6206                if let Some(pred) = &idx.predicate {
6207                    if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
6208                        continue; // skip this index for this row
6209                    }
6210                }
6211                // Index the row into this specific index only.
6212                index_into_single(
6213                    idx,
6214                    &self.schema,
6215                    row,
6216                    &mut self.hot,
6217                    &mut self.bitmap,
6218                    &mut self.ann,
6219                    &mut self.fm,
6220                    &mut self.sparse,
6221                    &mut self.minhash,
6222                );
6223            }
6224            return;
6225        }
6226        // Plaintext tables index the row as-is; only ENCRYPTED_INDEXABLE
6227        // columns need the tokenized copy (`tokenized_for_indexes` clones the
6228        // whole row, which would tax every put on unencrypted tables).
6229        if self.column_keys.is_empty() {
6230            index_into(
6231                &self.schema,
6232                row,
6233                &mut self.hot,
6234                &mut self.bitmap,
6235                &mut self.ann,
6236                &mut self.fm,
6237                &mut self.sparse,
6238                &mut self.minhash,
6239            );
6240            return;
6241        }
6242        let effective_row = self.tokenized_for_indexes(row);
6243        index_into(
6244            &self.schema,
6245            &effective_row,
6246            &mut self.hot,
6247            &mut self.bitmap,
6248            &mut self.ann,
6249            &mut self.fm,
6250            &mut self.sparse,
6251            &mut self.minhash,
6252        );
6253    }
6254
6255    /// Produce the row view that indexes should see. For ENCRYPTED_INDEXABLE
6256    /// equality (HMAC-eq) columns the plaintext value is replaced by its token,
6257    /// so the bitmap/HOT indexes store tokens. OPE-range columns keep their raw
6258    /// value (their range index is rebuilt from runs over plaintext). Plaintext
6259    /// tables return the row unchanged.
6260    fn tokenized_for_indexes(&self, row: &Row) -> Row {
6261        if self.column_keys.is_empty() {
6262            return row.clone();
6263        }
6264        {
6265            use crate::encryption::SCHEME_HMAC_EQ;
6266            let mut tok = row.clone();
6267            for (&cid, &(_, scheme)) in &self.column_keys {
6268                if scheme != SCHEME_HMAC_EQ {
6269                    continue;
6270                }
6271                if let Some(v) = tok.columns.get(&cid).cloned() {
6272                    if let Some(t) = self.tokenize_value(cid, &v) {
6273                        tok.columns.insert(cid, t);
6274                    }
6275                }
6276            }
6277            tok
6278        }
6279    }
6280
6281    /// Group-commit: make all pending writes durable, advance the epoch so they
6282    /// become visible, and persist the manifest. Dispatches on the WAL sink: a
6283    /// standalone table fsyncs its private WAL; a mounted table seals into the
6284    /// shared WAL and defers the fsync to the group-commit coordinator (B1).
6285    pub fn commit(&mut self) -> Result<Epoch> {
6286        self.commit_inner(None)
6287    }
6288
6289    /// Prepare a pending commit cooperatively, then invoke `before_commit`
6290    /// immediately before the durable transaction marker is appended.
6291    #[doc(hidden)]
6292    pub fn commit_controlled<F>(
6293        &mut self,
6294        control: &crate::ExecutionControl,
6295        mut before_commit: F,
6296    ) -> Result<Epoch>
6297    where
6298        F: FnMut() -> Result<()>,
6299    {
6300        self.commit_inner(Some((control, &mut before_commit)))
6301    }
6302
6303    fn commit_inner(
6304        &mut self,
6305        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6306    ) -> Result<Epoch> {
6307        self.ensure_writable()?;
6308        if !self.has_pending_mutations() {
6309            if self.current_txn_id == 0 && matches!(&self.wal, WalSink::Private(_)) {
6310                return Err(MongrelError::Full(
6311                    "standalone transaction id namespace exhausted".into(),
6312                ));
6313            }
6314            return Ok(self.epoch.visible());
6315        }
6316        self.commit_new_epoch_inner(controlled)
6317    }
6318
6319    /// Seal a real logical write at a fresh epoch. Bulk-load paths publish
6320    /// their run directly rather than staging rows in the WAL, so they call
6321    /// this after proving the input is non-empty.
6322    fn commit_new_epoch(&mut self) -> Result<Epoch> {
6323        self.commit_new_epoch_inner(None)
6324    }
6325
6326    fn commit_new_epoch_inner(
6327        &mut self,
6328        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6329    ) -> Result<Epoch> {
6330        self.ensure_writable()?;
6331        if self.is_shared() {
6332            self.commit_shared(controlled)
6333        } else {
6334            self.commit_private(controlled)
6335        }
6336    }
6337
6338    /// Standalone commit: fsync the private WAL under the commit lock.
6339    fn commit_private(
6340        &mut self,
6341        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6342    ) -> Result<Epoch> {
6343        // Serialize the assign→fsync→publish critical section across all tables
6344        // sharing the epoch authority so `visible` is published strictly in
6345        // assigned order (the dual-counter invariant).
6346        let commit_lock = Arc::clone(&self.commit_lock);
6347        let _g = commit_lock.lock();
6348        // Validate the private transaction namespace before allocating an
6349        // epoch or appending any terminal WAL record.
6350        let txn_id = self.ensure_txn_id()?;
6351        if let Some((control, before_commit)) = controlled {
6352            control.checkpoint()?;
6353            before_commit()?;
6354        }
6355        let new_epoch = self.epoch.bump_assigned();
6356        let epoch_authority = Arc::clone(&self.epoch);
6357        let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6358        // Seal the staged records under a TxnCommit marker carrying the commit
6359        // epoch, then a single group fsync. Recovery applies only records whose
6360        // txn has a durable TxnCommit (uncommitted/torn tails are discarded).
6361        let wal_result = match &mut self.wal {
6362            WalSink::Private(w) => w
6363                .append_txn(
6364                    txn_id,
6365                    Op::TxnCommit {
6366                        epoch: new_epoch.0,
6367                        added_runs: Vec::new(),
6368                    },
6369                )
6370                .and_then(|_| w.sync()),
6371            WalSink::Shared(_) => unreachable!("commit_private on a shared sink"),
6372            WalSink::ReadOnly => Err(MongrelError::ReadOnlyReplica),
6373        };
6374        if let Err(error) = wal_result {
6375            self.durable_commit_failed = true;
6376            return Err(MongrelError::CommitOutcomeUnknown {
6377                epoch: new_epoch.0,
6378                message: error.to_string(),
6379            });
6380        }
6381        // The commit marker is durable. Resolve the assigned epoch even when a
6382        // live publish/checkpoint step fails, and report the exact outcome.
6383        if let Some(epoch) = self.pending_truncate.take() {
6384            self.apply_truncate(epoch);
6385        }
6386        self.invalidate_pending_cache();
6387        let publish_result = self.persist_manifest(new_epoch);
6388        // Publish through the shared in-order gate so a `Table::commit` can never
6389        // advance the watermark past an in-flight cross-table transaction's
6390        // lower assigned epoch whose writes are not yet applied (spec §9.3e).
6391        self.epoch.publish_in_order(new_epoch);
6392        epoch_guard.disarm();
6393        if let Err(error) = publish_result {
6394            self.durable_commit_failed = true;
6395            return Err(MongrelError::DurableCommit {
6396                epoch: new_epoch.0,
6397                message: error.to_string(),
6398            });
6399        }
6400        self.current_txn_id = txn_id.checked_add(1).unwrap_or(0);
6401        self.pending_private_mutations = false;
6402        self.data_generation = self.data_generation.wrapping_add(1);
6403        Ok(new_epoch)
6404    }
6405
6406    /// Mounted commit (B1/B2): mirror the cross-table sequencer. Seal a
6407    /// `TxnCommit` into the shared WAL under the WAL lock (assigning the epoch in
6408    /// WAL-append order), make it durable via the group-commit coordinator (one
6409    /// leader fsync for the whole batch), then apply the staged rows at the
6410    /// assigned epoch and publish in order. Honors the shared poison flag.
6411    fn commit_shared(
6412        &mut self,
6413        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6414    ) -> Result<Epoch> {
6415        use std::sync::atomic::Ordering;
6416        let s = match &self.wal {
6417            WalSink::Shared(s) => s.clone(),
6418            WalSink::Private(_) => unreachable!("commit_shared on a private sink"),
6419            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6420        };
6421        if s.poisoned.load(Ordering::Relaxed) {
6422            return Err(MongrelError::Other(
6423                "database poisoned by fsync error".into(),
6424            ));
6425        }
6426        // Serialize the whole single-table commit critical section (assign →
6427        // durable → publish) under the shared commit lock so concurrent
6428        // `Table::commit`s publish strictly in assigned order and each returns
6429        // only once its epoch is visible (read-your-writes after commit). The
6430        // fsync still defers to the group-commit coordinator, which can batch a
6431        // held commit with concurrent cross-table `transaction()` committers.
6432        let commit_lock = Arc::clone(&self.commit_lock);
6433        let _g = commit_lock.lock();
6434        if !self.pending_rows.is_empty() {
6435            match controlled.as_ref() {
6436                Some((control, _)) => self.prepare_durable_publish_controlled(control)?,
6437                None => self.prepare_durable_publish()?,
6438            }
6439        }
6440        // Always seal a txn (allocating an id if this span had no writes) so the
6441        // epoch advances monotonically like the standalone path.
6442        let txn_id = self.ensure_txn_id()?;
6443        let mut wal = s.wal.lock();
6444        if let Some((control, before_commit)) = controlled {
6445            control.checkpoint()?;
6446            before_commit()?;
6447        }
6448        let new_epoch = self.epoch.bump_assigned();
6449        let epoch_authority = Arc::clone(&self.epoch);
6450        let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6451        // P0.5: stamp every row version with the database HLC so visibility is
6452        // HLC-authoritative on the single-table commit path too.
6453        let commit_ts = s.hlc.now().map_err(|skew| {
6454            MongrelError::Other(format!(
6455                "clock skew rejected commit timestamp allocation: {skew}"
6456            ))
6457        })?;
6458        let commit_seq = match wal.append_commit_at(
6459            txn_id,
6460            new_epoch,
6461            &[],
6462            commit_ts.physical_micros.saturating_mul(1_000),
6463        ) {
6464            Ok(commit_seq) => commit_seq,
6465            Err(error) => {
6466                s.poisoned.store(true, Ordering::Relaxed);
6467                s.lifecycle.poison();
6468                return Err(MongrelError::CommitOutcomeUnknown {
6469                    epoch: new_epoch.0,
6470                    message: error.to_string(),
6471                });
6472            }
6473        };
6474        drop(wal);
6475        if let Err(error) = s.group.await_durable(&s.wal, commit_seq) {
6476            s.poisoned.store(true, Ordering::Relaxed);
6477            s.lifecycle.poison();
6478            return Err(MongrelError::CommitOutcomeUnknown {
6479                epoch: new_epoch.0,
6480                message: error.to_string(),
6481            });
6482        }
6483
6484        // Apply staged state after durability, but never lose the durable
6485        // outcome if a live apply or manifest checkpoint fails.
6486        if self.pending_truncate.take().is_some() {
6487            self.apply_truncate(new_epoch);
6488        }
6489        let mut rows = std::mem::take(&mut self.pending_rows);
6490        if !rows.is_empty() {
6491            for r in &mut rows {
6492                r.committed_epoch = new_epoch;
6493                r.commit_ts = Some(commit_ts);
6494            }
6495            let auto_inc_flags = std::mem::take(&mut self.pending_rows_auto_inc);
6496            let all_auto_generated =
6497                auto_inc_flags.len() == rows.len() && auto_inc_flags.iter().all(|b| *b);
6498            self.apply_put_rows_inner_prepared(rows, !all_auto_generated);
6499        } else {
6500            self.pending_rows_auto_inc.clear();
6501        }
6502        let dels = std::mem::take(&mut self.pending_dels);
6503        for rid in dels {
6504            self.apply_delete_at(rid, new_epoch, Some(commit_ts));
6505        }
6506
6507        self.invalidate_pending_cache();
6508        let publish_result = self.persist_manifest(new_epoch);
6509        self.epoch.publish_in_order(new_epoch);
6510        epoch_guard.disarm();
6511        let _ = s.change_wake.send(());
6512        if let Err(error) = publish_result {
6513            self.durable_commit_failed = true;
6514            s.poisoned.store(true, Ordering::Relaxed);
6515            s.lifecycle.poison();
6516            return Err(MongrelError::DurableCommit {
6517                epoch: new_epoch.0,
6518                message: error.to_string(),
6519            });
6520        }
6521        // Next auto-commit span allocates a fresh shared txn id.
6522        self.current_txn_id = 0;
6523        self.data_generation = self.data_generation.wrapping_add(1);
6524        Ok(new_epoch)
6525    }
6526
6527    /// Commit, then drain the memtable into the mutable-run LSM tier (Phase
6528    /// 11.1). The tier absorbs flushes in place and only spills to an immutable
6529    /// `.sr` sorted run once it crosses the spill watermark — coalescing many
6530    /// small flushes into fewer, larger runs. While the tier holds un-spilled
6531    /// data the WAL is **not** rotated: the Flush marker / WAL rotation is
6532    /// deferred until the data is durably in a run, so crash recovery replays
6533    /// those rows back into the memtable (the tier rebuilds from replay).
6534    pub fn flush(&mut self) -> Result<Epoch> {
6535        self.flush_with_outcome().map(|(epoch, _)| epoch)
6536    }
6537
6538    /// Flush and report whether this call published pending logical mutations.
6539    pub fn flush_with_outcome(&mut self) -> Result<(Epoch, bool)> {
6540        self.flush_with_outcome_inner(None)
6541    }
6542
6543    /// Cooperatively prepare a flush, entering the commit fence immediately
6544    /// before its transaction marker can become durable.
6545    #[doc(hidden)]
6546    pub fn flush_with_outcome_controlled<F>(
6547        &mut self,
6548        control: &crate::ExecutionControl,
6549        mut before_commit: F,
6550    ) -> Result<(Epoch, bool)>
6551    where
6552        F: FnMut() -> Result<()>,
6553    {
6554        self.flush_with_outcome_inner(Some((control, &mut before_commit)))
6555    }
6556
6557    fn flush_with_outcome_inner(
6558        &mut self,
6559        controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6560    ) -> Result<(Epoch, bool)> {
6561        match controlled.as_ref() {
6562            Some((control, _)) => {
6563                self.ensure_indexes_complete_controlled(control, || true)?;
6564            }
6565            None => self.ensure_indexes_complete()?,
6566        }
6567        let committed = self.has_pending_mutations();
6568        let epoch = self.commit_inner(controlled)?;
6569        let finish: Result<(Epoch, bool)> = (|| {
6570            let rows = self.memtable.drain_sorted();
6571            if !rows.is_empty() {
6572                self.mutable_run.insert_many(rows);
6573            }
6574            if self.mutable_run.approx_bytes() >= self.mutable_run_spill_bytes {
6575                self.spill_mutable_run(epoch)?;
6576                // The tier is now empty and its data is durably in a run → safe to
6577                // mark the WAL flushed (and, for a private WAL, rotate to a fresh
6578                // segment so the flushed records aren't replayed).
6579                self.mark_flushed(epoch)?;
6580                self.persist_manifest(epoch)?;
6581                self.build_learned_ranges()?;
6582                // Memtable is drained and runs are stable → checkpoint the indexes so
6583                // the next open skips the full run scan (Phase 9.1).
6584                self.checkpoint_indexes(epoch);
6585                // Issue 4: rebuild + publish the run-lookup directory so the
6586                // next open fast-paths point lookups. Failure is non-fatal —
6587                // the manifest is already durable so the table reopens and
6588                // rebuilds the directory lazily.
6589                let _ = self.publish_run_lookup_directory();
6590            }
6591            // else: data coalesced in the in-memory tier; the WAL still covers it
6592            // and the manifest epoch was already persisted by `commit`.
6593            Ok((epoch, committed))
6594        })();
6595        let outcome = match finish {
6596            Err(error) if committed => Err(MongrelError::DurableCommit {
6597                epoch: epoch.0,
6598                message: error.to_string(),
6599            }),
6600            result => result,
6601        };
6602        if outcome.is_ok() {
6603            // S1C-001: the base changed (the memtable drained into the
6604            // mutable-run tier and may have spilled to a new run) — publish a
6605            // fresh immutable view for generation readers. Indexes were
6606            // ensured complete above, so publishing cannot fail; if it ever
6607            // did, the previous (still valid) view stays published.
6608            let _ = self.publish_read_generation();
6609        }
6610        outcome
6611    }
6612
6613    pub(crate) fn has_pending_mutations(&self) -> bool {
6614        self.pending_private_mutations
6615            || !self.pending_rows.is_empty()
6616            || !self.pending_dels.is_empty()
6617            || self.pending_truncate.is_some()
6618    }
6619
6620    pub fn has_pending_writes(&self) -> bool {
6621        self.has_pending_mutations()
6622    }
6623
6624    /// Force a full flush to a `.sr` sorted run regardless of the spill
6625    /// threshold. Temporarily lowers `mutable_run_spill_bytes` to 1 so the
6626    /// threshold check in [`Self::flush`] always fires. Used by
6627    /// [`Self::close`] and the Kit's flush-on-close path (§4.4) so a
6628    /// short-lived process (CLI, one-shot script) leaves all pending writes
6629    /// durable in a run — keeping WAL segment count bounded across repeated
6630    /// invocations. Best-effort: errors are propagated but the threshold is
6631    /// always restored.
6632    pub fn force_flush(&mut self) -> Result<Epoch> {
6633        let saved = self.mutable_run_spill_bytes;
6634        self.mutable_run_spill_bytes = 1;
6635        let result = self.flush();
6636        self.mutable_run_spill_bytes = saved;
6637        result
6638    }
6639
6640    /// Best-effort close: force-flush any pending writes to a sorted run so
6641    /// the WAL segments can be reaped on the next open. Never panics — a
6642    /// flush error is logged and returned but the threshold is always
6643    /// restored. Call this as the last action before a short-lived process
6644    /// exits (CLI, one-shot script). Not needed for the daemon (its
6645    /// background auto-compactor handles run management). (§4.4)
6646    pub fn close(&mut self) -> Result<()> {
6647        if self.memtable_len() > 0 || self.mutable_run_len() > 0 {
6648            self.force_flush()?;
6649        }
6650        // Drain the persistent result cache: best-effort, deadline-bounded
6651        // shutdown of the background writer. Closing the table should not
6652        // block forever; ops still queued at the deadline are abandoned
6653        // (counted on the writer's `result_cache_persist_shutdown_abandoned_total`
6654        // metric) but the queue lock is released.
6655        self.result_cache
6656            .lock()
6657            .shutdown_persistent_cache(std::time::Duration::from_secs(5));
6658        Ok(())
6659    }
6660
6661    /// Mark `epoch` as flushed: append a `Flush` marker to the WAL, advance
6662    /// `flushed_epoch`, and — for a private WAL only — rotate to a fresh segment
6663    /// so the now-durable-in-a-run records are not replayed. A mounted table's
6664    /// shared WAL is never rotated per-table; recovery skips its already-flushed
6665    /// records via the manifest `flushed_epoch` gate, and segment GC (B3c) reaps
6666    /// them once every table has flushed past them.
6667    /// True when this table has no WAL replay gate to advance (read-only
6668    /// replica sink). Compaction consults this before advancing
6669    /// `flushed_epoch`.
6670    pub(crate) fn wal_is_read_only(&self) -> bool {
6671        matches!(self.wal, WalSink::ReadOnly)
6672    }
6673
6674    /// Move committed memtable rows (committed at or below `epoch`) into the
6675    /// mutable run, leaving pending, uncommitted rows (which sit at
6676    /// `pending_epoch = visible + 1`) in the memtable. Compaction calls this
6677    /// before snapshotting the merge input so publishing can advance the WAL
6678    /// replay gate without stranding committed rows outside the runs.
6679    pub(crate) fn drain_committed_memtable_rows(&mut self, epoch: Epoch) {
6680        if self.memtable_len() == 0 {
6681            return;
6682        }
6683        let rows = self.memtable.drain_sorted();
6684        let mut pending = Vec::new();
6685        let mut committed = Vec::new();
6686        for row in rows {
6687            if row.committed_epoch > epoch {
6688                pending.push(row);
6689            } else {
6690                committed.push(row);
6691            }
6692        }
6693        if !committed.is_empty() {
6694            self.mutable_run.insert_many(committed);
6695        }
6696        for row in pending {
6697            self.memtable.upsert(row);
6698        }
6699    }
6700
6701    pub(crate) fn mark_flushed(&mut self, epoch: Epoch) -> Result<()> {
6702        let op = Op::Flush {
6703            table_id: self.table_id,
6704            flushed_epoch: epoch.0,
6705        };
6706        match &mut self.wal {
6707            WalSink::Private(w) => {
6708                w.append_system(op)?;
6709                w.sync()?;
6710            }
6711            WalSink::Shared(s) => {
6712                // Informational in the shared log (recovery gates on the manifest
6713                // `flushed_epoch`); not separately fsynced — the run + manifest
6714                // are the durability point and the underlying rows were already
6715                // fsynced at their commit.
6716                s.wal.lock().append_system(op)?;
6717            }
6718            WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6719        }
6720        self.flushed_epoch = epoch.0;
6721        if matches!(self.wal, WalSink::Private(_)) {
6722            self.rotate_wal(epoch)?;
6723        }
6724        Ok(())
6725    }
6726
6727    /// Spill the mutable-run tier to a new immutable level-0 sorted run. The
6728    /// caller owns the Flush-marker / WAL-rotation / manifest steps (only valid
6729    /// once all in-flight data is in runs). No-op when the tier is empty.
6730    fn spill_mutable_run(&mut self, epoch: Epoch) -> Result<()> {
6731        if self.mutable_run.is_empty() {
6732            return Ok(());
6733        }
6734        let run_id = self.alloc_run_id()?;
6735        let rows = self.mutable_run.drain_sorted();
6736        if rows.is_empty() {
6737            return Ok(());
6738        }
6739        let path = self.run_path(run_id);
6740        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
6741        if let Some(kek) = &self.kek {
6742            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6743        }
6744        let header = match self.create_run_file(run_id)? {
6745            Some(file) => writer.write_file(file, &rows)?,
6746            None => writer.write(&path, &rows)?,
6747        };
6748        self.run_refs.push(RunRef {
6749            run_id: run_id as u128,
6750            level: 0,
6751            epoch_created: epoch.0,
6752            row_count: header.row_count,
6753        });
6754        self.refresh_active_run_fingerprint();
6755        self.run_row_id_ranges
6756            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6757        Ok(())
6758    }
6759
6760    /// Tune the mutable-run spill watermark (bytes). A smaller threshold spills
6761    /// sooner (more, smaller runs — closer to the pre-Phase-11.1 behavior); a
6762    /// larger one coalesces more flushes in memory.
6763    pub fn set_mutable_run_spill_bytes(&mut self, bytes: u64) {
6764        self.mutable_run_spill_bytes = bytes.max(1);
6765    }
6766
6767    /// Set the zstd compression level for compaction output (Phase 18.1).
6768    /// Default 3; higher values give better compression ratio at the cost of
6769    /// slower compaction.
6770    pub fn set_compaction_zstd_level(&mut self, level: i32) {
6771        self.compaction_zstd_level = level;
6772    }
6773
6774    /// Set the result-cache byte budget (Phase 19.1 hardening (a)). Entries are
6775    /// evicted in access-order LRU past this limit. Takes effect immediately
6776    /// (may evict entries if the new limit is smaller than the current footprint).
6777    pub fn set_result_cache_max_bytes(&mut self, max_bytes: u64) {
6778        self.result_cache.lock().set_max_bytes(max_bytes);
6779    }
6780
6781    /// Wait for the persistent-cache writer to drain the pending queue, up
6782    /// to `deadline_ms` milliseconds. Returns the queue depth observed at
6783    /// the moment of the return (0 if fully drained). Tests use this to
6784    /// observe on-disk state without sleeping.
6785    pub fn flush_persistent_cache(&self, deadline_ms: u64) -> u64 {
6786        self.result_cache
6787            .lock()
6788            .flush_persistent_cache(std::time::Duration::from_millis(deadline_ms))
6789    }
6790
6791    /// Shut down the persistent-cache writer, draining pending ops until
6792    /// either the queue is empty or `deadline_ms` milliseconds have passed.
6793    /// The worker thread is joined on return. Tests and `Database::close`
6794    /// use this.
6795    pub fn shutdown_persistent_cache(&mut self, deadline_ms: u64) {
6796        self.result_cache
6797            .lock()
6798            .shutdown_persistent_cache(std::time::Duration::from_millis(deadline_ms));
6799    }
6800
6801    /// Test-only: set the minimum cache entry size (approx bytes) below
6802    /// which the persistent tier is skipped. A value of `0` always
6803    /// publishes to disk. Used by the REM-002 production tests so small
6804    /// fixtures can exercise the on-disk path without 4 KiB of data.
6805    #[doc(hidden)]
6806    pub fn _set_persist_min_bytes_for_test(&mut self, min: u64) {
6807        self.result_cache.lock().set_persist_min_bytes(min);
6808    }
6809
6810    /// Test seam (REM-D §8.8): when `enabled`, the next
6811    /// `Table::create` / `Table::open` on **this thread** fails its
6812    /// persistent-cache worker spawn and marks publication
6813    /// `Disabled(WorkerSpawnFailed)`. Thread-local, so concurrently running
6814    /// tests are unaffected. Callers should reset it with
6815    /// `_force_persistent_worker_spawn_failure_for_test(false)` after use.
6816    #[doc(hidden)]
6817    pub fn _force_persistent_worker_spawn_failure_for_test(enabled: bool) {
6818        PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.set(enabled));
6819    }
6820
6821    /// Explicit administrative flush (REM-D §8.6): synchronously persist the
6822    /// in-memory cached entry for `q` through the maintenance path
6823    /// (`persist_entry_synchronously_for_maintenance`), even when the
6824    /// background writer is unavailable. Returns `true` when an in-memory
6825    /// entry existed and a frame write was attempted. Never used by the
6826    /// query path; intended for migration tools and format-parity tests.
6827    #[doc(hidden)]
6828    pub fn _persist_cached_entry_synchronously_for_maintenance(
6829        &mut self,
6830        q: &crate::query::Query,
6831    ) -> bool {
6832        let key = crate::query::canonical_query_key(&q.conditions, None, 0)
6833            ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
6834            ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
6835        let identity = PersistentCacheIdentity {
6836            table_id: self.table_id(),
6837            schema_id: self.schema.schema_id,
6838            logical_generation: self.current_epoch().0,
6839        };
6840        let mut cache = self.result_cache.lock();
6841        let Some(entry) = cache.entries.get(&key).map(|e| e.clone_for_persist()) else {
6842            return false;
6843        };
6844        let entry_generation = cache.allocate_persist_generation(key);
6845        let context = PersistContext {
6846            identity,
6847            key,
6848            entry_generation,
6849        };
6850        cache.persist_entry_synchronously_for_maintenance(context, &entry);
6851        true
6852    }
6853
6854    /// Drop every cached result (used by compaction, schema evolution, and bulk
6855    /// load — paths that change run layout or data without going through the
6856    /// fine-grained `pending_*` tracking).
6857    pub(crate) fn clear_result_cache(&mut self) {
6858        self.result_cache.lock().clear();
6859    }
6860
6861    /// Number of versions currently held in the mutable-run tier.
6862    pub fn mutable_run_len(&self) -> usize {
6863        self.mutable_run.len()
6864    }
6865
6866    /// Drain every version from the mutable-run tier (ascending `(RowId,
6867    /// Epoch)` order). Used by compaction to fold the tier into its merge.
6868    pub(crate) fn drain_mutable_run(&mut self) -> Vec<Row> {
6869        self.mutable_run.drain_sorted()
6870    }
6871
6872    /// Snapshot the mutable-run tier without changing live table state.
6873    pub(crate) fn snapshot_mutable_run(&self) -> Vec<Row> {
6874        let mut snapshot = self.mutable_run.clone();
6875        snapshot.drain_sorted()
6876    }
6877
6878    /// Bulk-load: write `batch` directly to a new sorted run, bypassing the WAL
6879    /// and the memtable entirely (no per-row bincode, no skip-list inserts). The
6880    /// run + a rotated WAL + the manifest are fsynced once — the fast ingest
6881    /// path for large analytical loads. Indexes are still maintained.
6882    pub fn bulk_load(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Epoch> {
6883        self.ensure_writable()?;
6884        let n = batch.len();
6885        if n == 0 {
6886            return Ok(self.current_epoch());
6887        }
6888        for row in &batch {
6889            self.schema.validate_values(row)?;
6890        }
6891        let epoch = self.commit_new_epoch()?;
6892        let live_before = self.live_count;
6893        // Spill any pending mutable-run data first: bulk_load writes a Flush
6894        // marker + rotates the WAL below, which is only safe once all in-flight
6895        // data is durably in a run.
6896        self.spill_mutable_run(epoch)?;
6897        let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
6898            && self.indexes_complete
6899            && self.run_refs.is_empty()
6900            && self.memtable.is_empty()
6901            && self.mutable_run.is_empty();
6902        // Phase 14.7: route the legacy Value API through the same parallel
6903        // encode + typed batch-index path as `bulk_load_columns`. Transpose the
6904        // row-major sparse batch → column-major typed columns (in parallel),
6905        // then `write_native` + `index_columns_bulk`, instead of per-row
6906        // `Row { HashMap }` + `index_into` + the sequential `Value` writer.
6907        let mut user_columns: Vec<(u16, columnar::NativeColumn)> = {
6908            use rayon::prelude::*;
6909            self.schema
6910                .columns
6911                .par_iter()
6912                .map(|cdef| {
6913                    (
6914                        cdef.id,
6915                        columnar::rows_to_native(cdef.ty.clone(), &batch, cdef.id),
6916                    )
6917                })
6918                .collect::<Vec<_>>()
6919        };
6920        drop(batch);
6921        // Enforce NOT NULL constraints and primary-key upsert semantics before
6922        // any row id is allocated or bytes hit the run file. Losers of a
6923        // duplicate primary key are dropped from the encoded run entirely so
6924        // the dedup survives reopen (no ephemeral memtable tombstone).
6925        self.fill_auto_inc_native_columns(&mut user_columns, n)?;
6926        self.validate_columns_not_null(&user_columns, n)?;
6927        let winner_idx = self
6928            .bulk_pk_winner_indices(&user_columns, n)
6929            .filter(|idx| idx.len() != n);
6930        let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
6931            match winner_idx.as_deref() {
6932                Some(idx) => {
6933                    let compacted = user_columns
6934                        .iter()
6935                        .map(|(id, c)| (*id, c.gather(idx)))
6936                        .collect();
6937                    (compacted, idx.len())
6938                }
6939                None => (std::mem::take(&mut user_columns), n),
6940            };
6941        self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
6942        let first = self.allocator.alloc_range(write_n as u64)?.0;
6943        for rid in first..first + write_n as u64 {
6944            self.reservoir.offer(rid);
6945        }
6946        let run_id = self.alloc_run_id()?;
6947        let path = self.run_path(run_id);
6948        let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0)
6949            .clean(true)
6950            .with_lz4()
6951            .with_native_endian();
6952        if let Some(kek) = &self.kek {
6953            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6954        }
6955        let header = match self.create_run_file(run_id)? {
6956            Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
6957            None => writer.write_native(&path, &write_columns, write_n, first)?,
6958        };
6959        self.run_refs.push(RunRef {
6960            run_id: run_id as u128,
6961            level: 0,
6962            epoch_created: epoch.0,
6963            row_count: header.row_count,
6964        });
6965        self.refresh_active_run_fingerprint();
6966        self.run_row_id_ranges
6967            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6968        self.live_count = self.live_count.saturating_add(write_n as u64);
6969        if eager_index_build {
6970            let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
6971            self.index_columns_bulk(&write_columns, &row_ids);
6972            self.indexes_complete = true;
6973            self.build_learned_ranges()?;
6974        } else {
6975            self.indexes_complete = false;
6976        }
6977        self.mark_flushed(epoch)?;
6978        self.persist_manifest(epoch)?;
6979        if eager_index_build {
6980            self.checkpoint_indexes(epoch);
6981        }
6982        self.clear_result_cache();
6983        Ok(epoch)
6984    }
6985
6986    /// Rotate the private WAL to a fresh segment. Only valid for a standalone
6987    /// table — a mounted table never rotates the shared WAL per-table.
6988    fn rotate_wal(&mut self, epoch: Epoch) -> Result<()> {
6989        let segment = next_wal_segment(&self.dir.join(WAL_DIR))?;
6990        let cipher = self.wal_dek.as_ref().map(|dk| make_cipher(dk));
6991        // The segment number (from the filename) namespaces nonces under the
6992        // constant WAL DEK — pass it through to the writer.
6993        let segment_no = segment
6994            .file_stem()
6995            .and_then(|s| s.to_str())
6996            .and_then(|s| s.strip_prefix("seg-"))
6997            .and_then(|s| s.parse::<u64>().ok())
6998            .unwrap_or(0);
6999        let mut wal = Wal::create_with_cipher(segment, epoch, cipher, segment_no)?;
7000        wal.set_sync_byte_threshold(self.sync_byte_threshold);
7001        wal.sync()?;
7002        self.wal = WalSink::Private(wal);
7003        Ok(())
7004    }
7005
7006    /// Fine-grained result-cache invalidation (hardening (c)): drop only
7007    /// entries whose footprint intersects a deleted RowId or whose
7008    /// condition-columns intersect a mutated column, then clear the pending
7009    /// sets. Called by `commit` and the cross-table transaction path.
7010    pub(crate) fn invalidate_pending_cache(&mut self) {
7011        self.result_cache
7012            .lock()
7013            .invalidate(&self.pending_delete_rids, &self.pending_put_cols);
7014        self.pending_delete_rids.clear();
7015        self.pending_put_cols.clear();
7016    }
7017
7018    pub(crate) fn persist_manifest(&self, epoch: Epoch) -> Result<()> {
7019        let mut m = Manifest::new(self.table_id, self.schema.schema_id);
7020        m.current_epoch = epoch.0;
7021        m.next_row_id = self.allocator.current().0;
7022        m.runs = self.run_refs.clone();
7023        m.live_count = self.live_count;
7024        m.global_idx_epoch = self.global_idx_epoch;
7025        m.flushed_epoch = self.flushed_epoch;
7026        m.retiring = self.retiring.clone();
7027        // Persist the authoritative counter only when seeded; otherwise write 0
7028        // so the next open still scans `max(PK)` on first use (an unseeded
7029        // lower bound from WAL replay is not safe to trust across a flush).
7030        m.auto_inc_next = match self.auto_inc {
7031            Some(ai) if ai.seeded => ai.next,
7032            _ => 0,
7033        };
7034        m.ttl = self.ttl;
7035        let meta_dek = self.manifest_meta_dek();
7036        match self._root_guard.as_deref() {
7037            Some(root) => manifest::write_durable(root, &mut m, meta_dek.as_ref())?,
7038            None => manifest::write_atomic(&self.dir, &mut m, meta_dek.as_ref())?,
7039        }
7040        Ok(())
7041    }
7042
7043    /// Rebuild the row-to-run lookup directory from the active run set and
7044    /// publish it as a sharded checkpoint in `_runs/`. Failure is non-fatal:
7045    /// the manifest is the authoritative source, the next open falls back to
7046    /// the range-scan path, and a subsequent flush rebuilds + republishes.
7047    /// Returns the resulting directory state so callers can keep the
7048    /// in-memory state in sync.
7049    pub(crate) fn publish_run_lookup_directory(&mut self) -> Result<()> {
7050        // Fire the `manifest.publication` fault hook so tests can simulate a
7051        // crash after the manifest is durable but before the directory
7052        // checkpoint lands.
7053        mongreldb_fault::inject("manifest.publication")
7054            .map_err(|e| MongrelError::Other(format!("manifest.publication fault: {e}")))?;
7055        let active_runs = self.run_refs.clone();
7056        let schema_id = self.schema.schema_id;
7057        let index_generation = self.global_idx_epoch;
7058        let run_generation = active_runs.len() as u64;
7059        let fingerprint = crate::run_lookup::compute_fingerprint(
7060            &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
7061            schema_id,
7062            index_generation,
7063            run_generation,
7064            crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7065        );
7066        self.active_run_fingerprint = fingerprint;
7067        let dir = match crate::run_lookup::RunLookupDirectory::rebuild_from_runs(&active_runs, self)
7068        {
7069            Ok(d) => d,
7070            Err(error) => {
7071                // Failure to rebuild is non-fatal: the manifest is durable
7072                // and the next open will retry.
7073                self.run_lookup.complete = false;
7074                self.lookup_metrics
7075                    .directory_incomplete
7076                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7077                return Err(error);
7078            }
7079        };
7080        // Stamp the fingerprint on the in-memory directory before publishing
7081        // so the on-disk shards carry the exact value the open path will
7082        // compare against.
7083        let mut dir = dir;
7084        dir.set_fingerprint(fingerprint);
7085        let runs_dir = match self.runs_root.as_deref() {
7086            Some(root) => match root.io_path() {
7087                Ok(p) => p,
7088                Err(_) => self.dir.join(RUNS_DIR),
7089            },
7090            None => self.dir.join(RUNS_DIR),
7091        };
7092        // Best-effort fault hook so tests can intercept the temp-write + rename
7093        // boundary.
7094        mongreldb_fault::inject("directory.temp_write")
7095            .map_err(|e| MongrelError::Other(format!("directory.temp_write fault: {e}")))?;
7096        let publish =
7097            dir.write_checkpoint_sharded(&runs_dir, crate::run_lookup::DEFAULT_SHARD_BYTES);
7098        mongreldb_fault::inject("directory.sync")
7099            .map_err(|e| MongrelError::Other(format!("directory.sync fault: {e}")))?;
7100        mongreldb_fault::inject("directory.rename")
7101            .map_err(|e| MongrelError::Other(format!("directory.rename fault: {e}")))?;
7102        if let Err(error) = publish {
7103            // The manifest is still durable; mark the directory incomplete
7104            // and let the next open rebuild lazily.
7105            self.run_lookup = RunLookupState {
7106                directory: None,
7107                fingerprint,
7108                complete: false,
7109            };
7110            self.lookup_metrics
7111                .directory_incomplete
7112                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7113            self.lookup_metrics
7114                .directory_lookup_fallback
7115                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7116            return Err(error.into());
7117        }
7118        self.run_lookup = RunLookupState {
7119            directory: Some(std::sync::Arc::new(dir)),
7120            fingerprint,
7121            complete: true,
7122        };
7123        Ok(())
7124    }
7125
7126    pub(crate) fn plan_recovered_metadata(&mut self) -> Result<RecoveryMetadataPlan> {
7127        // `live_count` tracks logical tombstones, not wall-clock TTL expiry.
7128        // Use a time before every representable timestamp so TTL cannot hide a
7129        // row while rebuilding authoritative manifest metadata.
7130        let rows = self.visible_rows_at_time(Snapshot::unbounded(), i64::MIN)?;
7131        let live_count = u64::try_from(rows.len())
7132            .map_err(|_| MongrelError::Full("table live-row count exceeds u64".into()))?;
7133        let auto_inc = match self.auto_inc {
7134            Some(mut state) => {
7135                let maximum = self.scan_max_int64(state.column_id)?;
7136                let after_maximum = maximum.checked_add(1).ok_or_else(|| {
7137                    MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
7138                })?;
7139                state.next = state.next.max(after_maximum).max(1);
7140                state.seeded = true;
7141                Some(state)
7142            }
7143            None => None,
7144        };
7145        Ok(RecoveryMetadataPlan {
7146            live_count,
7147            auto_inc,
7148            changed: live_count != self.live_count
7149                || auto_inc.is_some_and(|planned| {
7150                    self.auto_inc.is_none_or(|current| {
7151                        current.next != planned.next || current.seeded != planned.seeded
7152                    })
7153                }),
7154        })
7155    }
7156
7157    pub(crate) fn apply_recovered_metadata(
7158        &mut self,
7159        plan: RecoveryMetadataPlan,
7160        epoch: Epoch,
7161    ) -> Result<()> {
7162        if !plan.changed {
7163            return Ok(());
7164        }
7165        self.live_count = plan.live_count;
7166        self.auto_inc = plan.auto_inc;
7167        self.persist_manifest(epoch)
7168    }
7169
7170    /// Checkpoint the in-memory secondary indexes to `_idx/global.idx` and stamp
7171    /// the manifest's `global_idx_epoch` (Phase 9.1). Call after the runs are
7172    /// stable and the memtable is drained (flush/bulk-load/compact) so the
7173    /// checkpoint exactly matches the run data; subsequent [`Table::open`] loads it
7174    /// directly instead of scanning every run.
7175    pub(crate) fn checkpoint_indexes(&mut self, epoch: Epoch) {
7176        // Never persist an incomplete index set (e.g. after bulk_load_columns,
7177        // which bypasses per-row indexing) — reopen rebuilds from the runs.
7178        if !self.indexes_complete {
7179            return;
7180        }
7181        // The reopen replay gate is the manifest's `flushed_epoch`: every
7182        // commit past it is re-applied (and re-indexed) from the WAL on open.
7183        // The live index maps also cover committed-but-unflushed rows
7184        // (memtable / mutable-run content), so a checkpoint stamped past
7185        // `flushed_epoch` would make replay double-index those rows (Sparse
7186        // dot-product scores double-count; ANN graphs gain duplicate nodes).
7187        // Only persist an image whose content is fully behind the gate.
7188        if epoch.0 > self.flushed_epoch {
7189            return;
7190        }
7191        // FND-006: a fired fault behaves like a failed checkpoint — the write
7192        // is best-effort and the next open simply rebuilds from the runs.
7193        if crate::catalog::inject_hook("index.publish.before").is_err() {
7194            return;
7195        }
7196        if self.idx_root.is_none() {
7197            if let Some(root) = self._root_guard.as_ref() {
7198                let Ok(idx_root) = root.create_directory_all_pinned(global_idx::IDX_DIR) else {
7199                    return;
7200                };
7201                self.idx_root = Some(Arc::new(idx_root));
7202            }
7203        }
7204        let snap = global_idx::IndexSnapshot {
7205            hot: &self.hot,
7206            bitmap: &self.bitmap,
7207            ann: &self.ann,
7208            fm: &self.fm,
7209            sparse: &self.sparse,
7210            minhash: &self.minhash,
7211            learned_range: &self.learned_range,
7212        };
7213        // Best-effort: a failed checkpoint just means the next open rebuilds.
7214        let idx_dek = self.idx_dek();
7215        let written = match self.idx_root.as_deref() {
7216            Some(root) => global_idx::write_atomic_root(
7217                root,
7218                self.table_id,
7219                epoch.0,
7220                snap,
7221                idx_dek.as_deref(),
7222            ),
7223            None => global_idx::write_atomic(
7224                &self.dir,
7225                self.table_id,
7226                epoch.0,
7227                snap,
7228                idx_dek.as_deref(),
7229            ),
7230        };
7231        if written.is_ok() {
7232            self.global_idx_epoch = epoch.0;
7233            self.refresh_active_run_fingerprint();
7234            let _ = self.persist_manifest(epoch);
7235            // FND-006: the index generation is published.
7236            let _ = crate::catalog::inject_hook("index.publish.after");
7237        }
7238    }
7239
7240    /// Drop any on-disk index checkpoint so the next open rebuilds from runs
7241    /// (used when the live indexes are known stale, e.g. compaction to empty).
7242    pub(crate) fn invalidate_index_checkpoint(&mut self) {
7243        self.global_idx_epoch = 0;
7244        self.refresh_active_run_fingerprint();
7245        if let Some(root) = self.idx_root.as_deref() {
7246            let _ = root.remove_file(global_idx::IDX_FILENAME);
7247        } else {
7248            global_idx::remove(&self.dir);
7249        }
7250        let _ = self.persist_manifest(self.epoch.visible());
7251    }
7252
7253    /// Prepare for replacing every run without publishing a second manifest.
7254    /// The caller persists the replacement topology after this returns.  An
7255    /// older checkpoint may remain on disk if deletion fails, but a manifest
7256    /// with `global_idx_epoch = 0` will never endorse it on reopen.
7257    pub(crate) fn prepare_indexes_for_run_replacement(&mut self) {
7258        self.indexes_complete = false;
7259        self.global_idx_epoch = 0;
7260        self.refresh_active_run_fingerprint();
7261        if let Some(root) = self.idx_root.as_deref() {
7262            let _ = root.remove_file(global_idx::IDX_FILENAME);
7263        } else {
7264            global_idx::remove(&self.dir);
7265        }
7266    }
7267
7268    pub(crate) fn finish_indexes_for_run_replacement(&mut self) {
7269        self.indexes_complete = true;
7270    }
7271
7272    /// A maintenance operation changed live run topology and could not prove
7273    /// the matching manifest publication.  Fail closed until recovery rebuilds
7274    /// one coherent view from durable state.  Mounted tables also poison their
7275    /// owning database so GC, DDL, and transactions cannot continue around the
7276    /// uncertain topology.
7277    pub(crate) fn poison_after_maintenance_publish_failure(&mut self) {
7278        self.durable_commit_failed = true;
7279        if let WalSink::Shared(shared) = &self.wal {
7280            shared
7281                .poisoned
7282                .store(true, std::sync::atomic::Ordering::Relaxed);
7283        }
7284    }
7285
7286    /// Invalidate a stale handle after DOCTOR has durably dropped its catalog
7287    /// entry. Other tables remain usable, but this handle must never append new
7288    /// writes for the quarantined table id.
7289    pub(crate) fn mark_unavailable_after_quarantine(&mut self) {
7290        self.durable_commit_failed = true;
7291    }
7292
7293    /// Read the row at `row_id` visible to `snapshot`, merging the newest
7294    /// version across the memtable, mutable-run tier, and all sorted runs.
7295    ///
7296    /// In-memory tiers use full-[`Snapshot`] HLC visibility (P0.5-T3). Sorted
7297    /// runs restore optional [`crate::sorted_run::SYS_COMMIT_TS`] when present
7298    /// and fall back to epoch-only for legacy runs; candidates are filtered
7299    /// with [`Snapshot::observes_row`] so HLC-stamped versions never win under
7300    /// an epoch-only pin.
7301    ///
7302    /// When the run-lookup directory is complete, the read path consults it
7303    /// to open only the runs whose locators may contain a visible version for
7304    /// this `row_id`. The existing range-scan path stays the safety net when
7305    /// the directory is missing or stale.
7306    ///
7307    /// REM-004: the directory consultation returns one of three explicit
7308    /// decisions ([`crate::run_lookup::DirectoryLookupDecision`]):
7309    ///
7310    /// - [`CompleteMiss`](crate::run_lookup::DirectoryLookupDecision::CompleteMiss) —
7311    ///   authoritative "no immutable run hosts this row"; open zero readers.
7312    /// - [`Candidates`](crate::run_lookup::DirectoryLookupDecision::Candidates) —
7313    ///   walk locators with the conservative filter plus a safe early-stop
7314    ///   proof ([`crate::run_lookup::RunLocator::can_contain_version_newer_than`]).
7315    /// - [`UnavailableOrStale`](crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale) —
7316    ///   fall back to the existing per-run range filter.
7317    pub fn get(&self, row_id: RowId, snapshot: Snapshot) -> Option<Row> {
7318        let mut best: Option<Row> = None;
7319        // `consider` is a free function (not a closure) so the caller can
7320        // also inspect `best` between iterations without colliding borrows.
7321        fn consider(best: &mut Option<Row>, row: Row, snapshot: Snapshot) {
7322            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7323                return;
7324            }
7325            if best.as_ref().is_none_or(|current| {
7326                Snapshot::version_is_newer(
7327                    row.committed_epoch,
7328                    row.commit_ts,
7329                    current.committed_epoch,
7330                    current.commit_ts,
7331                )
7332            }) {
7333                *best = Some(row);
7334            }
7335        }
7336        if let Some((_, row)) = self.memtable.get_version_at(row_id, snapshot) {
7337            consider(&mut best, row, snapshot);
7338        }
7339        if let Some((_, row)) = self.mutable_run.get_version_at(row_id, snapshot) {
7340            consider(&mut best, row, snapshot);
7341        }
7342        // Decide which runs to open. The directory is consulted only when it
7343        // is marked complete AND the active run set is non-empty; otherwise
7344        // we fall back to the per-run range filter below.
7345        let decision = if self.run_lookup.complete {
7346            // Defensive: verify the in-memory directory's fingerprint against
7347            // the active fingerprint refreshed whenever the topology changes.
7348            if self.run_lookup.fingerprint == self.active_run_fingerprint {
7349                match self.run_lookup.directory.as_ref() {
7350                    Some(dir) => dir.decide(row_id),
7351                    None => crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale,
7352                }
7353            } else {
7354                self.lookup_metrics
7355                    .directory_lookup_fallback
7356                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7357                crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7358            }
7359        } else {
7360            self.lookup_metrics
7361                .directory_lookup_fallback
7362                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7363            crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7364        };
7365        match decision {
7366            crate::run_lookup::DirectoryLookupDecision::CompleteMiss => {
7367                // REM-004: a complete directory miss is authoritative — the
7368                // memtable + mutable-run tiers have already been searched,
7369                // so no immutable run can host a visible version. Skip the
7370                // range scan and return whatever the in-memory tiers said.
7371                self.lookup_metrics
7372                    .directory_lookup_hit
7373                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7374                self.lookup_metrics
7375                    .directory_complete_miss_total
7376                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7377            }
7378            crate::run_lookup::DirectoryLookupDecision::Candidates(list) => {
7379                // Snapshot-aware candidate ordering (REM-B §6.13): an
7380                // HLC-authoritative snapshot considers fully stamped
7381                // locators by newest possible visible HLC first; an
7382                // epoch-only snapshot stays epoch-first. Ordering is a
7383                // performance hint only — early-stop correctness never
7384                // depends on it.
7385                let mut locators = std::borrow::Cow::Borrowed(list.locators.as_slice());
7386                if locators.len() > 1 {
7387                    locators.to_mut().sort_by(|a, b| {
7388                        if snapshot.uses_hlc_authority() {
7389                            b.max_hlc
7390                                .cmp(&a.max_hlc)
7391                                .then_with(|| b.max_epoch.cmp(&a.max_epoch))
7392                        } else {
7393                            b.max_epoch
7394                                .cmp(&a.max_epoch)
7395                                .then_with(|| b.max_hlc.cmp(&a.max_hlc))
7396                        }
7397                    });
7398                }
7399                // Apply the conservative snapshot filter and the safe
7400                // early-stop proof — locators that provably cannot contain a
7401                // visible version, or whose maximum visible version is
7402                // provably ≤ the current winner, are skipped. The remainder
7403                // is opened in newest-first order.
7404                let mut opened: std::collections::HashSet<u128> = std::collections::HashSet::new();
7405                let mut early_stopped: u64 = 0;
7406                for locator in locators.iter() {
7407                    // REM-004 early-stop: once we have a winner, skip
7408                    // locators that provably cannot beat it.
7409                    let stamp = best
7410                        .as_ref()
7411                        .map(|current| crate::run_lookup::VersionStamp {
7412                            epoch: current.committed_epoch,
7413                            hlc: current.commit_ts,
7414                        });
7415                    if let Some(s) = stamp {
7416                        if !locator.can_contain_version_newer_than(s, snapshot) {
7417                            early_stopped += 1;
7418                            continue;
7419                        }
7420                    }
7421                    if locator.is_impossible_for(snapshot) {
7422                        continue;
7423                    }
7424                    if locators.len() > 1 && !opened.insert(locator.run_id) {
7425                        continue;
7426                    }
7427                    self.lookup_metrics
7428                        .directory_run_readers_opened
7429                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7430                    self.lookup_metrics
7431                        .get_run_opened
7432                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7433                    let Ok(Ok(Some((_, row)))) = self.with_run_reader(locator.run_id, |reader| {
7434                        reader.get_version_at(row_id, snapshot)
7435                    }) else {
7436                        continue;
7437                    };
7438                    consider(&mut best, row, snapshot);
7439                }
7440                if early_stopped > 0 {
7441                    self.lookup_metrics
7442                        .directory_early_stop_total
7443                        .fetch_add(early_stopped, std::sync::atomic::Ordering::Relaxed);
7444                }
7445                self.lookup_metrics
7446                    .directory_lookup_hit
7447                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7448            }
7449            crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale => {
7450                // Exact directory miss OR no directory: range-scan fallback.
7451                for rr in &self.run_refs {
7452                    // Skip runs whose RowId range cannot contain this key
7453                    // (populated from run headers on open/spill). Missing
7454                    // range falls through.
7455                    if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
7456                        if row_id.0 < min_rid || row_id.0 > max_rid {
7457                            self.lookup_metrics
7458                                .get_run_skipped
7459                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7460                            continue;
7461                        }
7462                    }
7463                    self.lookup_metrics
7464                        .get_run_opened
7465                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7466                    let Ok(Ok(Some((_, row)))) = self.with_run_reader(rr.run_id, |reader| {
7467                        reader.get_version_at(row_id, snapshot)
7468                    }) else {
7469                        continue;
7470                    };
7471                    consider(&mut best, row, snapshot);
7472                }
7473            }
7474        }
7475        let now_nanos = unix_nanos_now();
7476        match best {
7477            Some(r) if r.deleted || self.row_expired_at(&r, now_nanos) => None,
7478            Some(r) => Some(r),
7479            None => None,
7480        }
7481    }
7482
7483    /// All rows visible at `snapshot` (newest version per `RowId`, tombstones
7484    /// dropped), merged across the memtable, the mutable-run tier, and all
7485    /// runs. Ascending `RowId`.
7486    pub fn visible_rows(&self, snapshot: Snapshot) -> Result<Vec<Row>> {
7487        self.visible_rows_at_time(snapshot, unix_nanos_now())
7488    }
7489
7490    /// Materialize visible rows with cooperative checkpoints while merging
7491    /// page-bounded, already ordered tier cursors.
7492    #[doc(hidden)]
7493    pub fn visible_rows_controlled(
7494        &self,
7495        snapshot: Snapshot,
7496        control: &crate::ExecutionControl,
7497    ) -> Result<Vec<Row>> {
7498        let mut out = Vec::new();
7499        self.for_each_visible_row_controlled(snapshot, control, |row| {
7500            out.push(row);
7501            Ok(())
7502        })?;
7503        Ok(out)
7504    }
7505
7506    /// Visit visible rows in row-id order with a k-way merge over ordered tier
7507    /// cursors. No full-table merge map or row-id sort is constructed.
7508    #[doc(hidden)]
7509    pub fn for_each_visible_row_controlled<F>(
7510        &self,
7511        snapshot: Snapshot,
7512        control: &crate::ExecutionControl,
7513        mut visit: F,
7514    ) -> Result<()>
7515    where
7516        F: FnMut(Row) -> Result<()>,
7517    {
7518        // TODO §3: trace metrics for the controlled-scan path. The fields are
7519        // populated on the streaming path; today (memory_from_map +
7520        // into_visible_version_cursor) the buffer is still bounded, so the
7521        // counts are the right shape even if some are zero on this impl.
7522        // `versions_examined` is incremented inside the visitor closure so
7523        // cancellation is observed within the bounded buffer.
7524        let setup_start = std::time::Instant::now();
7525        let mut versions_examined: u64 = 0;
7526        let mut rows_emitted: u64 = 0;
7527        let mut checkpoints: u64 = 0;
7528        let mut first_row_recorded = false;
7529        let mut sources: Vec<ControlledVisibleSource<'_>> =
7530            Vec::with_capacity(self.run_refs.len() + 2);
7531        control.checkpoint()?;
7532        checkpoints += 1;
7533        // Hot-tier sources use borrowing cursors: only the current version
7534        // group is retained, so setup does not scale with the live row count.
7535        if !self.memtable.is_empty() {
7536            sources.push(ControlledVisibleSource::memtable_cursor(
7537                self.memtable.newest_visible_iter(&snapshot),
7538            ));
7539        }
7540        control.checkpoint()?;
7541        checkpoints += 1;
7542        if !self.mutable_run.is_empty() {
7543            sources.push(ControlledVisibleSource::mutable_run_cursor(
7544                self.mutable_run.newest_visible_iter(&snapshot),
7545            ));
7546        }
7547        for run in &self.run_refs {
7548            control.checkpoint()?;
7549            checkpoints += 1;
7550            let reader = self.open_reader(run.run_id)?;
7551            sources.push(ControlledVisibleSource::run(
7552                reader.into_visible_version_cursor_at(snapshot)?,
7553            ));
7554        }
7555        // Time-to-first-row includes source construction; setup_us captures
7556        // the construction cost separately.
7557        let first_row_start = setup_start;
7558        let _setup_us = setup_start.elapsed().as_micros() as u64;
7559        let now_nanos = unix_nanos_now();
7560        let mut first_row_us: u64 = 0;
7561        let result = merge_controlled_visible_sources(
7562            &mut sources,
7563            control,
7564            |row| self.row_expired_at(row, now_nanos),
7565            |row| {
7566                if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7567                    return Ok(());
7568                }
7569                versions_examined += 1;
7570                if !first_row_recorded {
7571                    first_row_us = first_row_start.elapsed().as_micros() as u64;
7572                    first_row_recorded = true;
7573                }
7574                rows_emitted += 1;
7575                visit(row)
7576            },
7577        );
7578        let time_to_first_row_us = if first_row_recorded { first_row_us } else { 0 };
7579        crate::trace::QueryTrace::record(|t| {
7580            t.controlled_scan_versions_examined = t
7581                .controlled_scan_versions_examined
7582                .saturating_add(versions_examined as usize);
7583            t.controlled_scan_rows_emitted = t
7584                .controlled_scan_rows_emitted
7585                .saturating_add(rows_emitted as usize);
7586            t.controlled_scan_checkpoints = t
7587                .controlled_scan_checkpoints
7588                .saturating_add(checkpoints as usize);
7589            t.controlled_scan_time_to_first_row_us = t
7590                .controlled_scan_time_to_first_row_us
7591                .saturating_add(time_to_first_row_us);
7592            t.controlled_scan_setup_time_us =
7593                t.controlled_scan_setup_time_us.saturating_add(_setup_us);
7594        });
7595        result
7596    }
7597
7598    #[doc(hidden)]
7599    pub fn visible_rows_at_time(&self, snapshot: Snapshot, now_nanos: i64) -> Result<Vec<Row>> {
7600        let mut best: HashMap<u64, Row> = HashMap::new();
7601        let mut fold = |row: Row| {
7602            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7603                return;
7604            }
7605            best.entry(row.row_id.0)
7606                .and_modify(|existing| {
7607                    if Snapshot::version_is_newer(
7608                        row.committed_epoch,
7609                        row.commit_ts,
7610                        existing.committed_epoch,
7611                        existing.commit_ts,
7612                    ) {
7613                        *existing = row.clone();
7614                    }
7615                })
7616                .or_insert(row);
7617        };
7618        for row in self.memtable.visible_versions_at(snapshot) {
7619            fold(row);
7620        }
7621        for row in self.mutable_run.visible_versions_at(snapshot) {
7622            fold(row);
7623        }
7624        for rr in &self.run_refs {
7625            let mut reader = self.open_reader(rr.run_id)?;
7626            // P0.5-T3: optional SYS_COMMIT_TS restored when present on the run.
7627            for row in reader.visible_versions_at(snapshot)? {
7628                fold(row);
7629            }
7630        }
7631        let mut out: Vec<Row> = best
7632            .into_values()
7633            .filter_map(|r| {
7634                if r.deleted || self.row_expired_at(&r, now_nanos) {
7635                    None
7636                } else {
7637                    Some(r)
7638                }
7639            })
7640            .collect();
7641        out.sort_by_key(|r| r.row_id);
7642        Ok(out)
7643    }
7644
7645    /// Visible data as columns (column_id → values) rather than rows — the
7646    /// vectorized scan path. Fast path: when the memtable is empty and there is
7647    /// exactly one run (the common post-flush analytical case), it computes the
7648    /// visible index set once and gathers each column, with **no per-row
7649    /// `HashMap`/`Row` materialization**. Falls back to [`Self::visible_rows`]
7650    /// pivoted to columns when the memtable is live or runs overlap.
7651    pub fn visible_columns(&self, snapshot: Snapshot) -> Result<Vec<(u16, Vec<Value>)>> {
7652        if self.ttl.is_none()
7653            && self.memtable.is_empty()
7654            && self.mutable_run.is_empty()
7655            && self.run_refs.len() == 1
7656        {
7657            let rr = self.run_refs[0].clone();
7658            let mut reader = self.open_reader(rr.run_id)?;
7659            let idxs = reader.visible_indices_at(snapshot)?;
7660            let mut cols = Vec::with_capacity(self.schema.columns.len());
7661            for cdef in &self.schema.columns {
7662                cols.push((cdef.id, reader.gather_column(cdef.id, &idxs)?));
7663            }
7664            return Ok(cols);
7665        }
7666        // Fallback: row merge, then pivot to columns.
7667        let rows = self.visible_rows(snapshot)?;
7668        let mut cols: Vec<(u16, Vec<Value>)> = self
7669            .schema
7670            .columns
7671            .iter()
7672            .map(|c| (c.id, Vec::with_capacity(rows.len())))
7673            .collect();
7674        for r in &rows {
7675            for (cid, vec) in cols.iter_mut() {
7676                vec.push(r.columns.get(cid).cloned().unwrap_or(Value::Null));
7677            }
7678        }
7679        Ok(cols)
7680    }
7681
7682    /// Resolve a primary-key value to a row id (latest version).
7683    pub fn lookup_pk(&self, key: &[u8]) -> Option<RowId> {
7684        let row_id = self.hot.get(key)?;
7685        if self.ttl.is_none() || self.get(row_id, Snapshot::unbounded()).is_some() {
7686            Some(row_id)
7687        } else {
7688            None
7689        }
7690    }
7691
7692    /// Snapshot of lookup + result-cache counters. Point-in-time copy suitable
7693    /// for `/metrics` exposition or test assertions. Cache counts come from the
7694    /// [`ResultCache`] mutex; HOT counts come from the in-table atomics.
7695    pub fn lookup_metrics_snapshot(&self) -> LookupMetricsSnapshot {
7696        let mut snap = self.lookup_metrics.snapshot();
7697        let cache = self.result_cache.lock();
7698        let (mem, disk, miss, write_us) = cache.cache_counters();
7699        snap.result_cache_memory_hit = mem;
7700        snap.result_cache_disk_hit = disk;
7701        snap.result_cache_miss = miss;
7702        snap.result_cache_persistent_write_us = write_us;
7703        // REM-D §8.7: publication-availability counters live on the cache.
7704        let (unavailable, skipped, spawn_failures, worker_shutdowns) = cache.publication_counters();
7705        snap.result_cache_persist_unavailable_total = unavailable;
7706        snap.result_cache_persist_skipped_total = skipped;
7707        snap.result_cache_worker_spawn_failures_total = spawn_failures;
7708        snap.result_cache_worker_shutdown_total = worker_shutdowns;
7709        // Merge the writer's persist counters so tests and observability
7710        // surfaces see the full picture.
7711        if let Some(writer_snap) = cache.persist_snapshot() {
7712            snap.result_cache_persist_enqueued_total =
7713                writer_snap.result_cache_persist_enqueued_total;
7714            snap.result_cache_persist_coalesced_total =
7715                writer_snap.result_cache_persist_coalesced_total;
7716            snap.result_cache_persist_dropped_store_total =
7717                writer_snap.result_cache_persist_dropped_store_total;
7718            snap.result_cache_persist_remove_total = writer_snap.result_cache_persist_remove_total;
7719            snap.result_cache_persist_stale_store_skipped_total =
7720                writer_snap.result_cache_persist_stale_store_skipped_total;
7721            snap.result_cache_persist_errors_total = writer_snap.result_cache_persist_errors_total;
7722            snap.result_cache_persist_shutdown_abandoned_total =
7723                writer_snap.result_cache_persist_shutdown_abandoned_total;
7724            snap.result_cache_persist_queue_depth = writer_snap.result_cache_persist_queue_depth;
7725        }
7726        snap
7727    }
7728
7729    /// Run a conjunctive query over the shared row-id space: each condition
7730    /// yields a candidate row-id set, the sets are intersected, and the
7731    /// survivors are materialized at the current snapshot. This is the AI-native
7732    /// "compose primitives" surface (`semsearch ∩ fm_contains ∩ cat_in`).
7733    pub fn query(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
7734        self.query_at_with_allowed(q, self.snapshot(), None)
7735    }
7736
7737    /// Run a native conjunctive query with cooperative cancellation through
7738    /// index resolution, scans, filtering, and row materialization.
7739    pub fn query_controlled(
7740        &mut self,
7741        q: &crate::query::Query,
7742        control: &crate::ExecutionControl,
7743    ) -> Result<Vec<Row>> {
7744        self.query_at_with_allowed_controlled(q, self.snapshot(), None, control)
7745    }
7746
7747    /// Execute a conjunctive query at one snapshot, applying authorization
7748    /// before ranked ANN, Sparse, and MinHash top-k selection.
7749    pub fn query_at_with_allowed(
7750        &mut self,
7751        q: &crate::query::Query,
7752        snapshot: Snapshot,
7753        allowed: Option<&std::collections::HashSet<RowId>>,
7754    ) -> Result<Vec<Row>> {
7755        self.query_at_with_allowed_after(q, snapshot, allowed, None)
7756    }
7757
7758    #[doc(hidden)]
7759    pub fn query_at_with_allowed_controlled(
7760        &mut self,
7761        q: &crate::query::Query,
7762        snapshot: Snapshot,
7763        allowed: Option<&std::collections::HashSet<RowId>>,
7764        control: &crate::ExecutionControl,
7765    ) -> Result<Vec<Row>> {
7766        self.require_select()?;
7767        self.ensure_indexes_complete_controlled(control, || true)?;
7768        self.validate_native_query(q)?;
7769        self.query_conditions_at(
7770            &q.conditions,
7771            snapshot,
7772            allowed,
7773            q.limit,
7774            q.offset,
7775            None,
7776            unix_nanos_now(),
7777            Some(control),
7778        )
7779    }
7780
7781    #[doc(hidden)]
7782    pub fn query_at_with_allowed_after(
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    ) -> Result<Vec<Row>> {
7789        self.query_at_with_allowed_after_at_time(
7790            q,
7791            snapshot,
7792            allowed,
7793            after_row_id,
7794            unix_nanos_now(),
7795        )
7796    }
7797
7798    #[doc(hidden)]
7799    pub fn query_at_with_allowed_after_at_time(
7800        &mut self,
7801        q: &crate::query::Query,
7802        snapshot: Snapshot,
7803        allowed: Option<&std::collections::HashSet<RowId>>,
7804        after_row_id: Option<RowId>,
7805        query_time_nanos: i64,
7806    ) -> Result<Vec<Row>> {
7807        self.require_select()?;
7808        self.ensure_indexes_complete()?;
7809        self.validate_native_query(q)?;
7810        self.query_conditions_at(
7811            &q.conditions,
7812            snapshot,
7813            allowed,
7814            q.limit,
7815            q.offset,
7816            after_row_id,
7817            query_time_nanos,
7818            None,
7819        )
7820    }
7821
7822    fn validate_native_query(&self, q: &crate::query::Query) -> Result<()> {
7823        if q.conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7824            return Err(MongrelError::InvalidArgument(format!(
7825                "query exceeds {} conditions",
7826                crate::query::MAX_HARD_CONDITIONS
7827            )));
7828        }
7829        if let Some(limit) = q.limit {
7830            if limit == 0 || limit > crate::query::MAX_FINAL_LIMIT {
7831                return Err(MongrelError::InvalidArgument(format!(
7832                    "query limit must be between 1 and {}",
7833                    crate::query::MAX_FINAL_LIMIT
7834                )));
7835            }
7836        }
7837        if q.offset > crate::query::MAX_QUERY_OFFSET {
7838            return Err(MongrelError::InvalidArgument(format!(
7839                "query offset exceeds {}",
7840                crate::query::MAX_QUERY_OFFSET
7841            )));
7842        }
7843        Ok(())
7844    }
7845
7846    /// Unbounded internal SQL join helper. Public request surfaces must use
7847    /// [`Self::query_at_with_allowed`] and its result ceiling.
7848    #[doc(hidden)]
7849    pub fn query_all_at(
7850        &mut self,
7851        conditions: &[crate::query::Condition],
7852        snapshot: Snapshot,
7853    ) -> Result<Vec<Row>> {
7854        self.require_select()?;
7855        self.ensure_indexes_complete()?;
7856        if conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7857            return Err(MongrelError::InvalidArgument(format!(
7858                "query exceeds {} conditions",
7859                crate::query::MAX_HARD_CONDITIONS
7860            )));
7861        }
7862        self.query_conditions_at(
7863            conditions,
7864            snapshot,
7865            None,
7866            None,
7867            0,
7868            None,
7869            unix_nanos_now(),
7870            None,
7871        )
7872    }
7873
7874    #[allow(clippy::too_many_arguments)]
7875    fn query_conditions_at(
7876        &self,
7877        conditions: &[crate::query::Condition],
7878        snapshot: Snapshot,
7879        allowed: Option<&std::collections::HashSet<RowId>>,
7880        limit: Option<usize>,
7881        offset: usize,
7882        after_row_id: Option<RowId>,
7883        query_time_nanos: i64,
7884        control: Option<&crate::ExecutionControl>,
7885    ) -> Result<Vec<Row>> {
7886        control
7887            .map(crate::ExecutionControl::checkpoint)
7888            .transpose()?;
7889        crate::trace::QueryTrace::record(|t| {
7890            t.run_count = self.run_refs.len();
7891            t.memtable_rows = self.memtable.len();
7892            t.mutable_run_rows = self.mutable_run.len();
7893        });
7894        // A conjunction with no predicates matches every visible row (the
7895        // documented "Empty ⇒ all rows" contract); `intersect_sets` of zero
7896        // sets would otherwise wrongly yield the empty set.
7897        if conditions.is_empty() {
7898            crate::trace::QueryTrace::record(|t| {
7899                t.scan_mode = crate::trace::ScanMode::Materialized;
7900                t.row_materialized = true;
7901            });
7902            let mut rows = match control {
7903                Some(control) => self.visible_rows_controlled(snapshot, control)?,
7904                None => self.visible_rows_at_time(snapshot, query_time_nanos)?,
7905            };
7906            if let Some(allowed) = allowed {
7907                let mut filtered = Vec::with_capacity(rows.len());
7908                for (index, row) in rows.into_iter().enumerate() {
7909                    if index & 255 == 0 {
7910                        control
7911                            .map(crate::ExecutionControl::checkpoint)
7912                            .transpose()?;
7913                    }
7914                    if allowed.contains(&row.row_id) {
7915                        filtered.push(row);
7916                    }
7917                }
7918                rows = filtered;
7919            }
7920            if let Some(after_row_id) = after_row_id {
7921                rows.retain(|row| row.row_id > after_row_id);
7922            }
7923            rows.drain(..offset.min(rows.len()));
7924            if let Some(limit) = limit {
7925                rows.truncate(limit);
7926            }
7927            return Ok(rows);
7928        }
7929        crate::trace::QueryTrace::record(|t| {
7930            t.conditions_pushed = conditions.len();
7931            t.scan_mode = crate::trace::ScanMode::Materialized;
7932            t.row_materialized = true;
7933        });
7934        // §5.5: resolve conditions CHEAP-FIRST and early-exit the moment a
7935        // condition yields an empty survivor set. Previously every condition
7936        // (including an expensive range/FM page scan) was resolved before
7937        // `intersect_many` noticed an empty set; now a selective bitmap/PK that
7938        // eliminates all rows short-circuits the rest. Correctness is unchanged
7939        // (intersection with an empty set is empty either way).
7940        let mut ordered: Vec<&crate::query::Condition> = conditions.iter().collect();
7941        ordered.sort_by_key(|c| condition_cost_rank(c));
7942        let mut sets: Vec<RowIdSet> = Vec::with_capacity(ordered.len());
7943        for c in &ordered {
7944            control
7945                .map(crate::ExecutionControl::checkpoint)
7946                .transpose()?;
7947            let s = self.resolve_condition_with_allowed(c, snapshot, allowed)?;
7948            let empty = s.is_empty();
7949            sets.push(s);
7950            if empty {
7951                break;
7952            }
7953        }
7954        let mut rids = RowIdSet::intersect_many(sets).into_sorted_vec();
7955        if let Some(allowed) = allowed {
7956            rids.retain(|row_id| allowed.contains(&RowId(*row_id)));
7957        }
7958        if let Some(after_row_id) = after_row_id {
7959            let first = rids.partition_point(|row_id| *row_id <= after_row_id.0);
7960            rids.drain(..first);
7961        }
7962        rids.drain(..offset.min(rids.len()));
7963        if let Some(limit) = limit {
7964            rids.truncate(limit);
7965        }
7966        control
7967            .map(crate::ExecutionControl::checkpoint)
7968            .transpose()?;
7969        self.rows_for_rids_at_time(&rids, snapshot, query_time_nanos, control)
7970    }
7971
7972    /// Return an index's ordered candidates without discarding scores.
7973    pub fn retrieve(
7974        &mut self,
7975        retriever: &crate::query::Retriever,
7976    ) -> Result<Vec<crate::query::RetrieverHit>> {
7977        self.retrieve_with_allowed(retriever, None)
7978    }
7979
7980    pub fn retrieve_at(
7981        &mut self,
7982        retriever: &crate::query::Retriever,
7983        snapshot: Snapshot,
7984        allowed: Option<&std::collections::HashSet<RowId>>,
7985    ) -> Result<Vec<crate::query::RetrieverHit>> {
7986        self.retrieve_at_with_allowed(retriever, snapshot, allowed)
7987    }
7988
7989    /// Scored retrieval restricted to caller-authorized row IDs. Core MVCC,
7990    /// tombstone, and TTL eligibility is always applied before ranking.
7991    pub fn retrieve_with_allowed(
7992        &mut self,
7993        retriever: &crate::query::Retriever,
7994        allowed: Option<&std::collections::HashSet<RowId>>,
7995    ) -> Result<Vec<crate::query::RetrieverHit>> {
7996        self.retrieve_at_with_allowed(retriever, self.snapshot(), allowed)
7997    }
7998
7999    pub fn retrieve_at_with_allowed(
8000        &mut self,
8001        retriever: &crate::query::Retriever,
8002        snapshot: Snapshot,
8003        allowed: Option<&std::collections::HashSet<RowId>>,
8004    ) -> Result<Vec<crate::query::RetrieverHit>> {
8005        self.retrieve_at_with_allowed_and_context(retriever, snapshot, allowed, None)
8006    }
8007
8008    pub fn retrieve_at_with_allowed_and_context(
8009        &mut self,
8010        retriever: &crate::query::Retriever,
8011        snapshot: Snapshot,
8012        allowed: Option<&std::collections::HashSet<RowId>>,
8013        context: Option<&crate::query::AiExecutionContext>,
8014    ) -> Result<Vec<crate::query::RetrieverHit>> {
8015        self.require_select()?;
8016        self.ensure_indexes_complete()?;
8017        self.validate_retriever(retriever)?;
8018        self.retrieve_filtered(retriever, snapshot, None, allowed, None, context)
8019    }
8020
8021    pub fn retrieve_at_with_candidate_authorization_and_context(
8022        &mut self,
8023        retriever: &crate::query::Retriever,
8024        snapshot: Snapshot,
8025        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8026        context: Option<&crate::query::AiExecutionContext>,
8027    ) -> Result<Vec<crate::query::RetrieverHit>> {
8028        self.require_select()?;
8029        self.ensure_indexes_complete()?;
8030        self.retrieve_at_with_candidate_authorization_on_generation(
8031            retriever,
8032            snapshot,
8033            authorization,
8034            context,
8035        )
8036    }
8037
8038    #[doc(hidden)]
8039    pub fn retrieve_at_with_candidate_authorization_on_generation(
8040        &self,
8041        retriever: &crate::query::Retriever,
8042        snapshot: Snapshot,
8043        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8044        context: Option<&crate::query::AiExecutionContext>,
8045    ) -> Result<Vec<crate::query::RetrieverHit>> {
8046        self.require_select()?;
8047        self.validate_retriever(retriever)?;
8048        self.retrieve_filtered(retriever, snapshot, None, None, authorization, context)
8049    }
8050
8051    fn validate_retriever(&self, retriever: &crate::query::Retriever) -> Result<()> {
8052        use crate::query::{Retriever, MAX_RETRIEVER_K, MAX_SET_MEMBERS, MAX_SPARSE_TERMS};
8053        let (column_id, k) = match retriever {
8054            Retriever::Ann {
8055                column_id,
8056                query,
8057                k,
8058            } => {
8059                let index = self.ann.get(column_id).ok_or_else(|| {
8060                    MongrelError::InvalidArgument(format!("column {column_id} has no ANN index"))
8061                })?;
8062                if query.len() != index.dim() {
8063                    return Err(MongrelError::InvalidArgument(format!(
8064                        "ANN query dimension must be {}, got {}",
8065                        index.dim(),
8066                        query.len()
8067                    )));
8068                }
8069                if query.iter().any(|value| !value.is_finite()) {
8070                    return Err(MongrelError::InvalidArgument(
8071                        "ANN query values must be finite".into(),
8072                    ));
8073                }
8074                (*column_id, *k)
8075            }
8076            Retriever::Sparse {
8077                column_id,
8078                query,
8079                k,
8080            } => {
8081                if !self.sparse.contains_key(column_id) {
8082                    return Err(MongrelError::InvalidArgument(format!(
8083                        "column {column_id} has no Sparse index"
8084                    )));
8085                }
8086                if query.is_empty() || query.iter().any(|(_, weight)| !weight.is_finite()) {
8087                    return Err(MongrelError::InvalidArgument(
8088                        "Sparse query must be non-empty with finite weights".into(),
8089                    ));
8090                }
8091                if query.len() > MAX_SPARSE_TERMS {
8092                    return Err(MongrelError::InvalidArgument(format!(
8093                        "Sparse query exceeds {MAX_SPARSE_TERMS} terms"
8094                    )));
8095                }
8096                (*column_id, *k)
8097            }
8098            Retriever::MinHash {
8099                column_id,
8100                members,
8101                k,
8102            } => {
8103                if !self.minhash.contains_key(column_id) {
8104                    return Err(MongrelError::InvalidArgument(format!(
8105                        "column {column_id} has no MinHash index"
8106                    )));
8107                }
8108                if members.is_empty() {
8109                    return Err(MongrelError::InvalidArgument(
8110                        "MinHash members must not be empty".into(),
8111                    ));
8112                }
8113                if members.len() > MAX_SET_MEMBERS {
8114                    return Err(MongrelError::InvalidArgument(format!(
8115                        "MinHash query exceeds {MAX_SET_MEMBERS} members"
8116                    )));
8117                }
8118                let mut total_bytes = 0usize;
8119                for member in members {
8120                    let bytes = member.encoded_len();
8121                    if bytes > crate::query::MAX_SET_MEMBER_BYTES {
8122                        return Err(MongrelError::InvalidArgument(format!(
8123                            "MinHash member exceeds {} bytes",
8124                            crate::query::MAX_SET_MEMBER_BYTES
8125                        )));
8126                    }
8127                    total_bytes = total_bytes.checked_add(bytes).ok_or_else(|| {
8128                        MongrelError::InvalidArgument("MinHash input size overflow".into())
8129                    })?;
8130                }
8131                if total_bytes > crate::query::MAX_SET_INPUT_BYTES {
8132                    return Err(MongrelError::InvalidArgument(format!(
8133                        "MinHash input exceeds {} bytes",
8134                        crate::query::MAX_SET_INPUT_BYTES
8135                    )));
8136                }
8137                (*column_id, *k)
8138            }
8139        };
8140        if k == 0 {
8141            return Err(MongrelError::InvalidArgument(
8142                "retriever k must be > 0".into(),
8143            ));
8144        }
8145        if k > MAX_RETRIEVER_K {
8146            return Err(MongrelError::InvalidArgument(format!(
8147                "retriever k exceeds {MAX_RETRIEVER_K}"
8148            )));
8149        }
8150        debug_assert!(self
8151            .schema
8152            .columns
8153            .iter()
8154            .any(|column| column.id == column_id));
8155        Ok(())
8156    }
8157
8158    fn validate_condition(&self, condition: &crate::query::Condition) -> Result<()> {
8159        use crate::query::Condition;
8160        match condition {
8161            Condition::Ann {
8162                column_id,
8163                query,
8164                k,
8165            } => self.validate_retriever(&crate::query::Retriever::Ann {
8166                column_id: *column_id,
8167                query: query.clone(),
8168                k: *k,
8169            }),
8170            Condition::SparseMatch {
8171                column_id,
8172                query,
8173                k,
8174            } => self.validate_retriever(&crate::query::Retriever::Sparse {
8175                column_id: *column_id,
8176                query: query.clone(),
8177                k: *k,
8178            }),
8179            Condition::MinHashSimilar {
8180                column_id,
8181                query,
8182                k,
8183            } => {
8184                if !self.minhash.contains_key(column_id) {
8185                    return Err(MongrelError::InvalidArgument(format!(
8186                        "column {column_id} has no MinHash index"
8187                    )));
8188                }
8189                if query.is_empty() || *k == 0 {
8190                    return Err(MongrelError::InvalidArgument(
8191                        "MinHash query must be non-empty and k must be > 0".into(),
8192                    ));
8193                }
8194                if query.len() > crate::query::MAX_SET_MEMBERS || *k > crate::query::MAX_RETRIEVER_K
8195                {
8196                    return Err(MongrelError::InvalidArgument(format!(
8197                        "MinHash query must have <= {} members and k <= {}",
8198                        crate::query::MAX_SET_MEMBERS,
8199                        crate::query::MAX_RETRIEVER_K
8200                    )));
8201                }
8202                Ok(())
8203            }
8204            Condition::BitmapIn { values, .. } if values.len() > crate::query::MAX_SET_MEMBERS => {
8205                Err(MongrelError::InvalidArgument(format!(
8206                    "bitmap IN exceeds {} values",
8207                    crate::query::MAX_SET_MEMBERS
8208                )))
8209            }
8210            Condition::FmContainsAll { patterns, .. }
8211                if patterns.len() > crate::query::MAX_HARD_CONDITIONS =>
8212            {
8213                Err(MongrelError::InvalidArgument(format!(
8214                    "FM query exceeds {} patterns",
8215                    crate::query::MAX_HARD_CONDITIONS
8216                )))
8217            }
8218            _ => Ok(()),
8219        }
8220    }
8221
8222    fn retrieve_filtered(
8223        &self,
8224        retriever: &crate::query::Retriever,
8225        snapshot: Snapshot,
8226        hard_filter: Option<&RowIdSet>,
8227        allowed: Option<&std::collections::HashSet<RowId>>,
8228        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8229        context: Option<&crate::query::AiExecutionContext>,
8230    ) -> Result<Vec<crate::query::RetrieverHit>> {
8231        use crate::query::{Retriever, RetrieverHit, RetrieverScore};
8232        let started = std::time::Instant::now();
8233        let scored: Vec<(RowId, RetrieverScore)> = match retriever {
8234            Retriever::Ann {
8235                column_id,
8236                query,
8237                k,
8238            } => {
8239                let Some(index) = self.ann.get(column_id) else {
8240                    return Ok(Vec::new());
8241                };
8242                let cap = ann_candidate_cap(index.len(), context);
8243                crate::trace::QueryTrace::record(|trace| trace.candidate_cap = cap);
8244                if cap == 0 {
8245                    return Ok(Vec::new());
8246                }
8247                let mut breadth = (*k).max(1).min(cap);
8248                let mut eligibility = std::collections::HashMap::new();
8249                // Cumulative trace counters across widening iterations
8250                // (spec §7.5: raw / visibility / authorization rejection
8251                // accounting; the candidate cap and `candidate_cap_hit`
8252                // are written when the loop terminates).
8253                let mut raw_candidates_total: usize = 0;
8254                let mut visibility_rejected_total: usize = 0;
8255                let mut authorization_rejected_total: usize = 0;
8256                let mut candidate_cap_hit_final = false;
8257                let mut filtered = loop {
8258                    let mut seen = std::collections::HashSet::new();
8259                    if let Some(context) = context {
8260                        context.checkpoint()?;
8261                    }
8262                    let raw = index.search_with_context(query, breadth, context)?;
8263                    crate::trace::QueryTrace::record(|trace| {
8264                        trace.raw_candidates = raw.len();
8265                        let unique = raw
8266                            .iter()
8267                            .map(|(row_id, _)| *row_id)
8268                            .collect::<std::collections::HashSet<_>>()
8269                            .len();
8270                        trace.unique_candidates = unique;
8271                        trace.duplicate_candidates = raw.len().saturating_sub(unique);
8272                        trace.authorization_rejected = raw
8273                            .iter()
8274                            .filter(|(row_id, _)| {
8275                                allowed.is_some_and(|allowed| !allowed.contains(row_id))
8276                            })
8277                            .count();
8278                        trace.hard_filter_rejected = raw
8279                            .iter()
8280                            .filter(|(row_id, _)| {
8281                                hard_filter.is_some_and(|filter| !filter.contains(row_id.0))
8282                            })
8283                            .count();
8284                    });
8285                    raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8286                    let unchecked: Vec<_> = raw
8287                        .iter()
8288                        .map(|(row_id, _)| *row_id)
8289                        .filter(|row_id| !eligibility.contains_key(row_id))
8290                        .filter(|row_id| {
8291                            hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8292                                && allowed.is_none_or(|allowed| allowed.contains(row_id))
8293                        })
8294                        .collect();
8295                    let eligible = self.eligible_and_authorized_candidate_ids(
8296                        &unchecked,
8297                        *column_id,
8298                        snapshot,
8299                        candidate_authorization,
8300                        context,
8301                    )?;
8302                    for row_id in &unchecked {
8303                        eligibility.insert(*row_id, eligible.contains(row_id));
8304                    }
8305                    // Account for newly rejected rows: anything not in
8306                    // `eligible` (visibility or tombstone/TTL or authorization).
8307                    let new_visibility_or_auth_rejected = unchecked
8308                        .iter()
8309                        .filter(|row_id| !eligible.contains(row_id))
8310                        .count();
8311                    // Distinguish visibility vs authorization rejections for
8312                    // the trace. Authorization rejections are rows that pass
8313                    // visibility but fail the candidate-authorization check;
8314                    // visibility rejections are the remainder.
8315                    let mut new_auth_rejected = 0usize;
8316                    if let Some(authorization) = candidate_authorization {
8317                        if authorization.security.rls_enabled(authorization.table)
8318                            && !authorization.principal.is_admin
8319                        {
8320                            // Re-eligibility-check only the auth layer to
8321                            // count how many were dropped at authorization
8322                            // specifically (eligible already merged auth
8323                            // into its result; treat non-eligible as
8324                            // auth-rejected when RLS is on).
8325                            new_auth_rejected = new_visibility_or_auth_rejected;
8326                        }
8327                    }
8328                    let new_visibility_rejected =
8329                        new_visibility_or_auth_rejected.saturating_sub(new_auth_rejected);
8330                    visibility_rejected_total =
8331                        visibility_rejected_total.saturating_add(new_visibility_rejected);
8332                    authorization_rejected_total =
8333                        authorization_rejected_total.saturating_add(new_auth_rejected);
8334                    let filtered: Vec<_> = raw
8335                        .into_iter()
8336                        .filter(|(row_id, _)| {
8337                            seen.insert(*row_id)
8338                                && eligibility.get(row_id).copied().unwrap_or(false)
8339                        })
8340                        .map(|(row_id, score)| {
8341                            let score = match score {
8342                                crate::index::AnnDistance::Hamming(d) => {
8343                                    RetrieverScore::AnnHammingDistance(d)
8344                                }
8345                                crate::index::AnnDistance::Cosine(d) => {
8346                                    RetrieverScore::AnnCosineDistance(d)
8347                                }
8348                            };
8349                            (row_id, score)
8350                        })
8351                        .collect();
8352                    if filtered.len() >= *k || breadth >= cap {
8353                        if filtered.len() < *k && index.len() > cap && breadth >= cap {
8354                            crate::trace::QueryTrace::record(|trace| {
8355                                trace.ann_candidate_cap_hit = true;
8356                                trace.candidate_cap_hit = true;
8357                            });
8358                            candidate_cap_hit_final = true;
8359                        }
8360                        break filtered;
8361                    }
8362                    breadth = breadth.saturating_mul(2).min(cap);
8363                };
8364                // Final trace write for ANN: candidate cap, cap-hit flag,
8365                // cumulative raw / rejection counts, and final hit count.
8366                let final_hits = filtered.len();
8367                let index_len = index.len();
8368                crate::trace::QueryTrace::record(|trace| {
8369                    trace.candidate_cap = cap;
8370                    trace.candidate_cap_hit = candidate_cap_hit_final;
8371                    trace.ann_candidate_cap_hit = candidate_cap_hit_final;
8372                    trace.raw_candidates =
8373                        trace.raw_candidates.saturating_add(raw_candidates_total);
8374                    trace.visibility_rejected = trace
8375                        .visibility_rejected
8376                        .saturating_add(visibility_rejected_total);
8377                    trace.authorization_rejected = trace
8378                        .authorization_rejected
8379                        .saturating_add(authorization_rejected_total);
8380                    trace.final_hits = trace.final_hits.saturating_add(final_hits);
8381                    // Suppress the unused warning on index_len — it is a
8382                    // useful diagnostic when paired with `candidate_cap_hit`.
8383                    let _ = index_len;
8384                });
8385                filtered.truncate(*k);
8386                filtered
8387            }
8388            Retriever::Sparse {
8389                column_id,
8390                query,
8391                k,
8392            } => self
8393                .sparse
8394                .get(column_id)
8395                .map(|index| -> Result<Vec<_>> {
8396                    let mut breadth = (*k).max(1);
8397                    let mut eligibility = std::collections::HashMap::new();
8398                    // Cumulative trace counters across widening iterations
8399                    // (same §7.5 accounting as the ANN branch above).
8400                    let mut raw_candidates_total: usize = 0;
8401                    let mut visibility_rejected_total: usize = 0;
8402                    let mut authorization_rejected_total: usize = 0;
8403                    let filtered = loop {
8404                        if let Some(context) = context {
8405                            context.checkpoint()?;
8406                        }
8407                        let raw = index.search_with_context(query, breadth, context)?;
8408                        raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8409                        authorization_rejected_total = authorization_rejected_total.saturating_add(
8410                            raw.iter()
8411                                .filter(|(row_id, _)| {
8412                                    allowed.is_some_and(|allowed| !allowed.contains(row_id))
8413                                })
8414                                .count(),
8415                        );
8416                        let unchecked: Vec<_> = raw
8417                            .iter()
8418                            .map(|(row_id, _)| *row_id)
8419                            .filter(|row_id| !eligibility.contains_key(row_id))
8420                            .filter(|row_id| {
8421                                hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8422                                    && allowed.is_none_or(|allowed| allowed.contains(row_id))
8423                            })
8424                            .collect();
8425                        let eligible = self.eligible_and_authorized_candidate_ids(
8426                            &unchecked,
8427                            *column_id,
8428                            snapshot,
8429                            candidate_authorization,
8430                            context,
8431                        )?;
8432                        visibility_rejected_total = visibility_rejected_total.saturating_add(
8433                            unchecked
8434                                .iter()
8435                                .filter(|row_id| !eligible.contains(row_id))
8436                                .count(),
8437                        );
8438                        for row_id in unchecked {
8439                            eligibility.insert(row_id, eligible.contains(&row_id));
8440                        }
8441                        let filtered: Vec<_> = raw
8442                            .iter()
8443                            .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8444                            .take(*k)
8445                            .map(|(row_id, score)| {
8446                                (*row_id, RetrieverScore::SparseDotProduct(*score))
8447                            })
8448                            .collect();
8449                        if filtered.len() >= *k || raw.len() < breadth {
8450                            break filtered;
8451                        }
8452                        let next = breadth.saturating_mul(2);
8453                        if next == breadth {
8454                            break filtered;
8455                        }
8456                        breadth = next;
8457                    };
8458                    crate::trace::QueryTrace::record(|trace| {
8459                        trace.raw_candidates =
8460                            trace.raw_candidates.saturating_add(raw_candidates_total);
8461                        trace.visibility_rejected = trace
8462                            .visibility_rejected
8463                            .saturating_add(visibility_rejected_total);
8464                        trace.authorization_rejected = trace
8465                            .authorization_rejected
8466                            .saturating_add(authorization_rejected_total);
8467                    });
8468                    Ok(filtered)
8469                })
8470                .transpose()?
8471                .unwrap_or_default(),
8472            Retriever::MinHash {
8473                column_id,
8474                members,
8475                k,
8476            } => self
8477                .minhash
8478                .get(column_id)
8479                .map(|index| -> Result<Vec<_>> {
8480                    let mut hashes = Vec::with_capacity(members.len());
8481                    for member in members {
8482                        if let Some(context) = context {
8483                            context.consume(crate::query::work_units(
8484                                member.encoded_len(),
8485                                crate::query::PARSE_WORK_QUANTUM,
8486                            ))?;
8487                        }
8488                        hashes.push(member.hash_v1());
8489                    }
8490                    let mut breadth = (*k).max(1);
8491                    let mut eligibility = std::collections::HashMap::new();
8492                    let mut raw_candidates_total: usize = 0;
8493                    let mut visibility_rejected_total: usize = 0;
8494                    let mut authorization_rejected_total: usize = 0;
8495                    let filtered = loop {
8496                        if let Some(context) = context {
8497                            context.checkpoint()?;
8498                        }
8499                        let raw = index.search_with_context(&hashes, breadth, context)?;
8500                        raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8501                        authorization_rejected_total = authorization_rejected_total.saturating_add(
8502                            raw.iter()
8503                                .filter(|(row_id, _)| {
8504                                    allowed.is_some_and(|allowed| !allowed.contains(row_id))
8505                                })
8506                                .count(),
8507                        );
8508                        let unchecked: Vec<_> = raw
8509                            .iter()
8510                            .map(|(row_id, _)| *row_id)
8511                            .filter(|row_id| !eligibility.contains_key(row_id))
8512                            .filter(|row_id| {
8513                                hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8514                                    && allowed.is_none_or(|allowed| allowed.contains(row_id))
8515                            })
8516                            .collect();
8517                        let eligible = self.eligible_and_authorized_candidate_ids(
8518                            &unchecked,
8519                            *column_id,
8520                            snapshot,
8521                            candidate_authorization,
8522                            context,
8523                        )?;
8524                        visibility_rejected_total = visibility_rejected_total.saturating_add(
8525                            unchecked
8526                                .iter()
8527                                .filter(|row_id| !eligible.contains(row_id))
8528                                .count(),
8529                        );
8530                        for row_id in unchecked {
8531                            eligibility.insert(row_id, eligible.contains(&row_id));
8532                        }
8533                        let filtered: Vec<_> = raw
8534                            .iter()
8535                            .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8536                            .take(*k)
8537                            .map(|(row_id, score)| {
8538                                (*row_id, RetrieverScore::MinHashEstimatedJaccard(*score))
8539                            })
8540                            .collect();
8541                        if filtered.len() >= *k || raw.len() < breadth {
8542                            break filtered;
8543                        }
8544                        let next = breadth.saturating_mul(2);
8545                        if next == breadth {
8546                            break filtered;
8547                        }
8548                        breadth = next;
8549                    };
8550                    crate::trace::QueryTrace::record(|trace| {
8551                        trace.raw_candidates =
8552                            trace.raw_candidates.saturating_add(raw_candidates_total);
8553                        trace.visibility_rejected = trace
8554                            .visibility_rejected
8555                            .saturating_add(visibility_rejected_total);
8556                        trace.authorization_rejected = trace
8557                            .authorization_rejected
8558                            .saturating_add(authorization_rejected_total);
8559                    });
8560                    Ok(filtered)
8561                })
8562                .transpose()?
8563                .unwrap_or_default(),
8564        };
8565        let requested_k = match retriever {
8566            Retriever::Ann { k, .. }
8567            | Retriever::Sparse { k, .. }
8568            | Retriever::MinHash { k, .. } => *k,
8569        };
8570        crate::trace::QueryTrace::record(|trace| {
8571            trace.final_hits = scored.len();
8572            if scored.len() < requested_k {
8573                trace.underfill_reason = Some(if trace.candidate_cap_hit {
8574                    "candidate_cap"
8575                } else {
8576                    "eligible_candidates_exhausted"
8577                });
8578            }
8579        });
8580        let elapsed = started.elapsed().as_nanos() as u64;
8581        crate::trace::QueryTrace::record(|trace| {
8582            match retriever {
8583                Retriever::Ann { .. } => {
8584                    trace.ann_candidate_nanos = trace.ann_candidate_nanos.saturating_add(elapsed);
8585                    if let Retriever::Ann { column_id, .. } = retriever {
8586                        if let Some(index) = self.ann.get(column_id) {
8587                            trace.ann_algorithm = Some(index.algorithm());
8588                            trace.ann_quantization = Some(index.quantization());
8589                            trace.ann_backend = Some(index.backend_name());
8590                        }
8591                    }
8592                }
8593                Retriever::Sparse { .. } => {
8594                    trace.sparse_candidate_nanos =
8595                        trace.sparse_candidate_nanos.saturating_add(elapsed)
8596                }
8597                Retriever::MinHash { .. } => {
8598                    trace.minhash_candidate_nanos =
8599                        trace.minhash_candidate_nanos.saturating_add(elapsed)
8600                }
8601            }
8602            trace.candidate_count = trace.candidate_count.saturating_add(scored.len());
8603        });
8604        Ok(scored
8605            .into_iter()
8606            .enumerate()
8607            .map(|(rank, (row_id, score))| RetrieverHit {
8608                row_id,
8609                rank: rank + 1,
8610                score,
8611            })
8612            .collect())
8613    }
8614
8615    fn eligible_candidate_ids(
8616        &self,
8617        candidates: &[RowId],
8618        _column_id: u16,
8619        snapshot: Snapshot,
8620        context: Option<&crate::query::AiExecutionContext>,
8621    ) -> Result<std::collections::HashSet<RowId>> {
8622        // Candidate eligibility is a pure snapshot read — the same
8623        // visibility rule point lookups (`get`) use. The in-flight
8624        // private-WAL batch lands in the memtable at `pending_epoch =
8625        // visible + 1` (puts and matching tombstones), above every reader
8626        // snapshot, so the un-advanced snapshot already hides it. Unlike
8627        // `resolve_pk_with_hot_fallback`, retrievers must NOT advance to
8628        // `pending_epoch`: an uncommitted row whose embedding is the exact
8629        // query match would outrank every committed row and leak into the
8630        // hits (see tests/retriever_uncommitted.rs). Committed versions
8631        // remain eligible under the caller snapshot, including HLC-stamped
8632        // winners admitted by `observes_row` (REM-001).
8633        let lookup_snapshot = snapshot;
8634        let mut readers: Vec<_> = self
8635            .run_refs
8636            .iter()
8637            .map(|run| self.open_reader(run.run_id))
8638            .collect::<Result<_>>()?;
8639        let now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8640        let mut eligible = std::collections::HashSet::with_capacity(candidates.len());
8641        for &row_id in candidates {
8642            if let Some(context) = context {
8643                context.consume(1)?;
8644            }
8645            let mem = self.memtable.get_version_at(row_id, lookup_snapshot);
8646            let mutable = self.mutable_run.get_version_at(row_id, lookup_snapshot);
8647            let overlay = match (mem, mutable) {
8648                (Some(left), Some(right)) => Some(
8649                    if Snapshot::version_is_newer(
8650                        left.1.committed_epoch,
8651                        left.1.commit_ts,
8652                        right.1.committed_epoch,
8653                        right.1.commit_ts,
8654                    ) {
8655                        left
8656                    } else {
8657                        right
8658                    },
8659                ),
8660                (Some(value), None) | (None, Some(value)) => Some(value),
8661                (None, None) => None,
8662            };
8663            if let Some((_, row)) = overlay {
8664                if !row.deleted && !self.row_expired_at(&row, now) {
8665                    eligible.insert(row_id);
8666                }
8667                continue;
8668            }
8669            // REM-001: keep the full version stamp across runs so the eligibility fold
8670            // honors HLC authority when candidates are stamped. The legacy
8671            // `(epoch, deleted, reader_index)` tuple dropped `commit_ts` and
8672            // could admit a stale high-epoch row over an HLC-newer low-epoch
8673            // candidate.
8674            let mut best: Option<(crate::sorted_run::VersionVisibility, usize)> = None;
8675            for (index, reader) in readers.iter_mut().enumerate() {
8676                if let Some(visibility) =
8677                    reader.get_version_visibility_full_at(row_id, lookup_snapshot)?
8678                {
8679                    if best
8680                        .as_ref()
8681                        .map(|(current, _)| visibility.stamp.is_newer_than(current.stamp))
8682                        .unwrap_or(true)
8683                    {
8684                        best = Some((visibility, index));
8685                    }
8686                }
8687            }
8688            let Some((visibility, reader_index)) = best else {
8689                continue;
8690            };
8691            if visibility.deleted {
8692                continue;
8693            }
8694            if let Some(ttl) = self.ttl {
8695                if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
8696                    row_id,
8697                    lookup_snapshot,
8698                    ttl.column_id,
8699                )? {
8700                    if let Some(Value::Int64(timestamp)) = ttl_value.value {
8701                        if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
8702                            continue;
8703                        }
8704                    }
8705                }
8706            }
8707            eligible.insert(row_id);
8708        }
8709        Ok(eligible)
8710    }
8711
8712    fn eligible_and_authorized_candidate_ids(
8713        &self,
8714        candidates: &[RowId],
8715        column_id: u16,
8716        snapshot: Snapshot,
8717        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8718        context: Option<&crate::query::AiExecutionContext>,
8719    ) -> Result<std::collections::HashSet<RowId>> {
8720        let eligible = self.eligible_candidate_ids(candidates, column_id, snapshot, context)?;
8721        let Some(authorization) = authorization else {
8722            return Ok(eligible);
8723        };
8724        let candidates: Vec<_> = eligible.into_iter().collect();
8725        self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, context)
8726    }
8727
8728    fn policy_allowed_candidate_ids(
8729        &self,
8730        candidates: &[RowId],
8731        snapshot: Snapshot,
8732        authorization: &crate::security::CandidateAuthorization<'_>,
8733        context: Option<&crate::query::AiExecutionContext>,
8734    ) -> Result<std::collections::HashSet<RowId>> {
8735        let started = std::time::Instant::now();
8736        if candidates.is_empty()
8737            || authorization.principal.is_admin
8738            || !authorization.security.rls_enabled(authorization.table)
8739        {
8740            return Ok(candidates.iter().copied().collect());
8741        }
8742        if let Some(context) = context {
8743            context.checkpoint()?;
8744        }
8745        let row_ids: Vec<_> = candidates.iter().map(|row_id| row_id.0).collect();
8746        let mut rows: std::collections::HashMap<RowId, Row> = candidates
8747            .iter()
8748            .map(|row_id| {
8749                (
8750                    *row_id,
8751                    Row {
8752                        row_id: *row_id,
8753                        committed_epoch: snapshot.epoch,
8754                        columns: std::collections::HashMap::new(),
8755                        deleted: false,
8756                        commit_ts: None,
8757                    },
8758                )
8759            })
8760            .collect();
8761        let columns = authorization
8762            .security
8763            .select_policy_columns(authorization.table, authorization.principal);
8764        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8765        let mut decoded = 0usize;
8766        for column_id in &columns {
8767            if let Some(context) = context {
8768                context.checkpoint()?;
8769            }
8770            for (row_id, value) in self.values_for_rids_batch_at_with_context(
8771                &row_ids, *column_id, snapshot, query_now, context,
8772            )? {
8773                if let Some(row) = rows.get_mut(&row_id) {
8774                    row.columns.insert(*column_id, value);
8775                    decoded = decoded.saturating_add(1);
8776                }
8777            }
8778        }
8779        if let Some(context) = context {
8780            context.consume(candidates.len().saturating_add(decoded))?;
8781        }
8782        let allowed = rows
8783            .into_values()
8784            .filter_map(|row| {
8785                authorization
8786                    .security
8787                    .row_allowed(
8788                        authorization.table,
8789                        crate::security::PolicyCommand::Select,
8790                        &row,
8791                        authorization.principal,
8792                        false,
8793                    )
8794                    .then_some(row.row_id)
8795            })
8796            .collect();
8797        crate::trace::QueryTrace::record(|trace| {
8798            trace.rls_rows_evaluated = trace.rls_rows_evaluated.saturating_add(candidates.len());
8799            trace.rls_policy_columns_decoded =
8800                trace.rls_policy_columns_decoded.saturating_add(decoded);
8801            trace.authorization_nanos = trace
8802                .authorization_nanos
8803                .saturating_add(started.elapsed().as_nanos() as u64);
8804        });
8805        Ok(allowed)
8806    }
8807
8808    /// Filter-aware union and reciprocal-rank fusion over scored retrievers.
8809    pub fn search(
8810        &mut self,
8811        request: &crate::query::SearchRequest,
8812    ) -> Result<Vec<crate::query::SearchHit>> {
8813        self.search_with_allowed(request, None)
8814    }
8815
8816    pub fn search_at(
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(request, snapshot, authorized)
8823    }
8824
8825    pub fn search_with_allowed(
8826        &mut self,
8827        request: &crate::query::SearchRequest,
8828        authorized: Option<&std::collections::HashSet<RowId>>,
8829    ) -> Result<Vec<crate::query::SearchHit>> {
8830        self.search_at_with_allowed(request, self.snapshot(), authorized)
8831    }
8832
8833    pub fn search_at_with_allowed(
8834        &mut self,
8835        request: &crate::query::SearchRequest,
8836        snapshot: Snapshot,
8837        authorized: Option<&std::collections::HashSet<RowId>>,
8838    ) -> Result<Vec<crate::query::SearchHit>> {
8839        self.search_at_with_allowed_and_context(request, snapshot, authorized, None)
8840    }
8841
8842    pub fn search_at_with_allowed_and_context(
8843        &mut self,
8844        request: &crate::query::SearchRequest,
8845        snapshot: Snapshot,
8846        authorized: Option<&std::collections::HashSet<RowId>>,
8847        context: Option<&crate::query::AiExecutionContext>,
8848    ) -> Result<Vec<crate::query::SearchHit>> {
8849        self.ensure_indexes_complete()?;
8850        self.search_at_with_filters_and_context(request, snapshot, authorized, None, context, None)
8851    }
8852
8853    pub fn search_at_with_candidate_authorization_and_context(
8854        &mut self,
8855        request: &crate::query::SearchRequest,
8856        snapshot: Snapshot,
8857        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8858        context: Option<&crate::query::AiExecutionContext>,
8859    ) -> Result<Vec<crate::query::SearchHit>> {
8860        self.ensure_indexes_complete()?;
8861        self.search_at_with_filters_and_context(
8862            request,
8863            snapshot,
8864            None,
8865            authorization,
8866            context,
8867            None,
8868        )
8869    }
8870
8871    #[doc(hidden)]
8872    pub fn search_at_with_candidate_authorization_on_generation(
8873        &self,
8874        request: &crate::query::SearchRequest,
8875        snapshot: Snapshot,
8876        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8877        context: Option<&crate::query::AiExecutionContext>,
8878    ) -> Result<Vec<crate::query::SearchHit>> {
8879        self.search_at_with_filters_and_context(
8880            request,
8881            snapshot,
8882            None,
8883            authorization,
8884            context,
8885            None,
8886        )
8887    }
8888
8889    #[doc(hidden)]
8890    pub fn search_at_with_candidate_authorization_on_generation_after(
8891        &self,
8892        request: &crate::query::SearchRequest,
8893        snapshot: Snapshot,
8894        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8895        context: Option<&crate::query::AiExecutionContext>,
8896        after: Option<crate::query::SearchAfter>,
8897    ) -> Result<Vec<crate::query::SearchHit>> {
8898        self.search_at_with_filters_and_context(
8899            request,
8900            snapshot,
8901            None,
8902            authorization,
8903            context,
8904            after,
8905        )
8906    }
8907
8908    fn search_at_with_filters_and_context(
8909        &self,
8910        request: &crate::query::SearchRequest,
8911        snapshot: Snapshot,
8912        authorized: Option<&std::collections::HashSet<RowId>>,
8913        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8914        context: Option<&crate::query::AiExecutionContext>,
8915        after: Option<crate::query::SearchAfter>,
8916    ) -> Result<Vec<crate::query::SearchHit>> {
8917        use crate::query::{
8918            ComponentScore, Condition, Fusion, SearchHit, MAX_FINAL_LIMIT, MAX_HARD_CONDITIONS,
8919            MAX_PROJECTION_COLUMNS, MAX_RETRIEVERS, MAX_RETRIEVER_WEIGHT,
8920        };
8921        let total_started = std::time::Instant::now();
8922        let rank_offset = after.map_or(0, |after| after.returned_count);
8923        self.require_select()?;
8924        if request.limit == 0 {
8925            return Err(MongrelError::InvalidArgument(
8926                "search limit must be > 0".into(),
8927            ));
8928        }
8929        if request.limit > MAX_FINAL_LIMIT {
8930            return Err(MongrelError::InvalidArgument(format!(
8931                "search limit exceeds {MAX_FINAL_LIMIT}"
8932            )));
8933        }
8934        if after.is_some_and(|cursor| !cursor.final_score.is_finite()) {
8935            return Err(MongrelError::InvalidArgument(
8936                "search-after score must be finite".into(),
8937            ));
8938        }
8939        if request.retrievers.is_empty() {
8940            return Err(MongrelError::InvalidArgument(
8941                "search requires at least one retriever".into(),
8942            ));
8943        }
8944        if request.retrievers.len() > MAX_RETRIEVERS {
8945            return Err(MongrelError::InvalidArgument(format!(
8946                "search exceeds {MAX_RETRIEVERS} retrievers"
8947            )));
8948        }
8949        if request.must.len() > MAX_HARD_CONDITIONS {
8950            return Err(MongrelError::InvalidArgument(format!(
8951                "search exceeds {MAX_HARD_CONDITIONS} hard conditions"
8952            )));
8953        }
8954        for condition in &request.must {
8955            self.validate_condition(condition)?;
8956        }
8957        if request.must.iter().any(|condition| {
8958            matches!(
8959                condition,
8960                Condition::Ann { .. }
8961                    | Condition::SparseMatch { .. }
8962                    | Condition::MinHashSimilar { .. }
8963            )
8964        }) {
8965            return Err(MongrelError::InvalidArgument(
8966                "ranked ANN, Sparse, and MinHash conditions must be retrievers, not must filters"
8967                    .into(),
8968            ));
8969        }
8970        let mut names = std::collections::HashSet::new();
8971        for named in &request.retrievers {
8972            if named.name.is_empty()
8973                || named.name.len() > crate::query::MAX_RETRIEVER_NAME_BYTES
8974                || !names.insert(named.name.as_str())
8975            {
8976                return Err(MongrelError::InvalidArgument(format!(
8977                    "retriever names must be non-empty, unique, and at most {} UTF-8 bytes",
8978                    crate::query::MAX_RETRIEVER_NAME_BYTES
8979                )));
8980            }
8981            if !named.weight.is_finite()
8982                || named.weight < 0.0
8983                || named.weight > MAX_RETRIEVER_WEIGHT
8984            {
8985                return Err(MongrelError::InvalidArgument(format!(
8986                    "retriever weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
8987                )));
8988            }
8989            self.validate_retriever(&named.retriever)?;
8990        }
8991        let projection = request
8992            .projection
8993            .clone()
8994            .unwrap_or_else(|| self.schema.columns.iter().map(|column| column.id).collect());
8995        if projection.len() > MAX_PROJECTION_COLUMNS {
8996            return Err(MongrelError::InvalidArgument(format!(
8997                "projection exceeds {MAX_PROJECTION_COLUMNS} columns"
8998            )));
8999        }
9000        for column_id in &projection {
9001            if !self
9002                .schema
9003                .columns
9004                .iter()
9005                .any(|column| column.id == *column_id)
9006            {
9007                return Err(MongrelError::ColumnNotFound(column_id.to_string()));
9008            }
9009        }
9010        if let Some(crate::query::Rerank::ExactVector {
9011            embedding_column,
9012            query,
9013            candidate_limit,
9014            weight,
9015            ..
9016        }) = &request.rerank
9017        {
9018            if *candidate_limit < request.limit || *candidate_limit > crate::query::MAX_RETRIEVER_K
9019            {
9020                return Err(MongrelError::InvalidArgument(format!(
9021                    "rerank candidate_limit must be between search limit and {}",
9022                    crate::query::MAX_RETRIEVER_K
9023                )));
9024            }
9025            if !weight.is_finite() || *weight < 0.0 || *weight > MAX_RETRIEVER_WEIGHT {
9026                return Err(MongrelError::InvalidArgument(format!(
9027                    "rerank weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
9028                )));
9029            }
9030            let column = self
9031                .schema
9032                .columns
9033                .iter()
9034                .find(|column| column.id == *embedding_column)
9035                .ok_or_else(|| MongrelError::ColumnNotFound(embedding_column.to_string()))?;
9036            let crate::schema::TypeId::Embedding { dim } = column.ty else {
9037                return Err(MongrelError::InvalidArgument(format!(
9038                    "rerank column {embedding_column} is not an embedding"
9039                )));
9040            };
9041            if query.len() != dim as usize || query.iter().any(|value| !value.is_finite()) {
9042                return Err(MongrelError::InvalidArgument(format!(
9043                    "rerank query must contain {dim} finite values"
9044                )));
9045            }
9046        }
9047
9048        let hard_filter_started = std::time::Instant::now();
9049        let hard_filter = if request.must.is_empty() {
9050            None
9051        } else {
9052            let mut sets = Vec::with_capacity(request.must.len());
9053            for condition in &request.must {
9054                if let Some(context) = context {
9055                    context.checkpoint()?;
9056                }
9057                sets.push(self.resolve_condition(condition, snapshot)?);
9058            }
9059            Some(RowIdSet::intersect_many(sets))
9060        };
9061        crate::trace::QueryTrace::record(|trace| {
9062            trace.hard_filter_nanos = trace
9063                .hard_filter_nanos
9064                .saturating_add(hard_filter_started.elapsed().as_nanos() as u64);
9065        });
9066        if hard_filter.as_ref().is_some_and(RowIdSet::is_empty) {
9067            return Ok(Vec::new());
9068        }
9069
9070        let constant = match request.fusion {
9071            Fusion::ReciprocalRank { constant } => constant,
9072        };
9073        let mut retrievers: Vec<_> = request.retrievers.iter().collect();
9074        retrievers.sort_by(|a, b| a.name.cmp(&b.name));
9075        let mut fusion_nanos = 0u64;
9076        let mut fused: std::collections::HashMap<RowId, (f64, Vec<ComponentScore>)> =
9077            std::collections::HashMap::new();
9078        for named in retrievers {
9079            if named.weight == 0.0 {
9080                continue;
9081            }
9082            if let Some(context) = context {
9083                context.checkpoint()?;
9084            }
9085            let hits = self.retrieve_filtered(
9086                &named.retriever,
9087                snapshot,
9088                hard_filter.as_ref(),
9089                authorized,
9090                candidate_authorization,
9091                context,
9092            )?;
9093            let retriever_name: std::sync::Arc<str> = named.name.as_str().into();
9094            let fusion_started = std::time::Instant::now();
9095            for hit in hits {
9096                if let Some(context) = context {
9097                    context.consume(1)?;
9098                }
9099                let contribution = named.weight / (constant as f64 + hit.rank as f64);
9100                if !contribution.is_finite() {
9101                    return Err(MongrelError::InvalidArgument(
9102                        "retriever contribution must be finite".into(),
9103                    ));
9104                }
9105                let max_fused_candidates = context.map_or(
9106                    crate::query::MAX_FUSED_CANDIDATES,
9107                    crate::query::AiExecutionContext::max_fused_candidates,
9108                );
9109                if !fused.contains_key(&hit.row_id) && fused.len() >= max_fused_candidates {
9110                    return Err(MongrelError::WorkBudgetExceeded);
9111                }
9112                let entry = fused.entry(hit.row_id).or_default();
9113                entry.0 += contribution;
9114                if !entry.0.is_finite() {
9115                    return Err(MongrelError::InvalidArgument(
9116                        "fused score must be finite".into(),
9117                    ));
9118                }
9119                entry.1.push(ComponentScore {
9120                    retriever_name: retriever_name.clone(),
9121                    rank: hit.rank,
9122                    raw_score: hit.score,
9123                    contribution,
9124                });
9125            }
9126            fusion_nanos = fusion_nanos.saturating_add(fusion_started.elapsed().as_nanos() as u64);
9127        }
9128        let union_size = fused.len();
9129        let mut ranked: Vec<_> = fused
9130            .into_iter()
9131            .map(|(row_id, (fused_score, components))| {
9132                (row_id, fused_score, components, None, fused_score)
9133            })
9134            .collect();
9135        let order = |(a_row, _, _, _, a_score): &(
9136            RowId,
9137            f64,
9138            Vec<ComponentScore>,
9139            Option<f32>,
9140            f64,
9141        ),
9142                     (b_row, _, _, _, b_score): &(
9143            RowId,
9144            f64,
9145            Vec<ComponentScore>,
9146            Option<f32>,
9147            f64,
9148        )| { b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row)) };
9149        if let Some(crate::query::Rerank::ExactVector {
9150            embedding_column,
9151            query,
9152            metric,
9153            candidate_limit,
9154            weight,
9155        }) = &request.rerank
9156        {
9157            let fused_order = |(a_row, a_score, ..): &(
9158                RowId,
9159                f64,
9160                Vec<ComponentScore>,
9161                Option<f32>,
9162                f64,
9163            ),
9164                               (b_row, b_score, ..): &(
9165                RowId,
9166                f64,
9167                Vec<ComponentScore>,
9168                Option<f32>,
9169                f64,
9170            )| {
9171                b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row))
9172            };
9173            let selection_started = std::time::Instant::now();
9174            if let Some(context) = context {
9175                context.consume(ranked.len())?;
9176            }
9177            if ranked.len() > *candidate_limit {
9178                let (_, _, _) = ranked.select_nth_unstable_by(*candidate_limit, fused_order);
9179                ranked.truncate(*candidate_limit);
9180            }
9181            ranked.sort_by(fused_order);
9182            fusion_nanos =
9183                fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9184            let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9185            if let Some(context) = context {
9186                context.consume(row_ids.len())?;
9187            }
9188            let query_now =
9189                context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9190            let gather_started = std::time::Instant::now();
9191            let vectors = self.values_for_rids_batch_at_with_context(
9192                &row_ids,
9193                *embedding_column,
9194                snapshot,
9195                query_now,
9196                context,
9197            )?;
9198            let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9199            let vector_work =
9200                crate::query::work_units(query.len(), crate::query::VECTOR_WORK_QUANTUM);
9201            let query_norm = if matches!(metric, crate::query::VectorMetric::Cosine) {
9202                if let Some(context) = context {
9203                    context.consume(vector_work)?;
9204                }
9205                query
9206                    .iter()
9207                    .map(|value| f64::from(*value).powi(2))
9208                    .sum::<f64>()
9209                    .sqrt()
9210            } else {
9211                0.0
9212            };
9213            let score_started = std::time::Instant::now();
9214            let mut scores = std::collections::HashMap::with_capacity(vectors.len());
9215            for (row_id, value) in vectors {
9216                if let Some(meta) = value.generated_embedding_metadata() {
9217                    if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9218                        continue;
9219                    }
9220                }
9221                let Some(vector) = value.as_embedding() else {
9222                    continue;
9223                };
9224                let score = match metric {
9225                    crate::query::VectorMetric::DotProduct => {
9226                        if let Some(context) = context {
9227                            context.consume(vector_work)?;
9228                        }
9229                        query
9230                            .iter()
9231                            .zip(vector)
9232                            .map(|(left, right)| f64::from(*left) * f64::from(*right))
9233                            .sum::<f64>()
9234                    }
9235                    crate::query::VectorMetric::Cosine => {
9236                        if let Some(context) = context {
9237                            context.consume(vector_work.saturating_mul(2))?;
9238                        }
9239                        let dot = query
9240                            .iter()
9241                            .zip(vector)
9242                            .map(|(left, right)| f64::from(*left) * f64::from(*right))
9243                            .sum::<f64>();
9244                        let norm = vector
9245                            .iter()
9246                            .map(|value| f64::from(*value).powi(2))
9247                            .sum::<f64>()
9248                            .sqrt();
9249                        if query_norm == 0.0 || norm == 0.0 {
9250                            0.0
9251                        } else {
9252                            dot / (query_norm * norm)
9253                        }
9254                    }
9255                    crate::query::VectorMetric::Euclidean => {
9256                        if let Some(context) = context {
9257                            context.consume(vector_work)?;
9258                        }
9259                        query
9260                            .iter()
9261                            .zip(vector)
9262                            .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9263                            .sum::<f64>()
9264                            .sqrt()
9265                    }
9266                };
9267                if !score.is_finite() {
9268                    return Err(MongrelError::InvalidArgument(
9269                        "exact rerank score must be finite".into(),
9270                    ));
9271                }
9272                scores.insert(row_id, score as f32);
9273            }
9274            let mut reranked = Vec::with_capacity(ranked.len());
9275            for (row_id, fused_score, components, _, _) in ranked.drain(..) {
9276                let Some(score) = scores.get(&row_id).copied() else {
9277                    continue;
9278                };
9279                let ordering_score = match metric {
9280                    crate::query::VectorMetric::Euclidean => -f64::from(score),
9281                    crate::query::VectorMetric::Cosine | crate::query::VectorMetric::DotProduct => {
9282                        f64::from(score)
9283                    }
9284                };
9285                let final_score = fused_score + *weight * ordering_score;
9286                if !final_score.is_finite() {
9287                    return Err(MongrelError::InvalidArgument(
9288                        "final rerank score must be finite".into(),
9289                    ));
9290                }
9291                reranked.push((row_id, fused_score, components, Some(score), final_score));
9292            }
9293            ranked = reranked;
9294            ranked.sort_by(order);
9295            crate::trace::QueryTrace::record(|trace| {
9296                trace.exact_vector_gather_nanos =
9297                    trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9298                trace.exact_vector_score_nanos = trace
9299                    .exact_vector_score_nanos
9300                    .saturating_add(score_started.elapsed().as_nanos() as u64);
9301            });
9302        }
9303        if let Some(after) = after {
9304            ranked.retain(|(row_id, _, _, _, final_score)| {
9305                final_score.total_cmp(&after.final_score).is_lt()
9306                    || (final_score.total_cmp(&after.final_score).is_eq() && *row_id > after.row_id)
9307            });
9308        }
9309        let projection_started = std::time::Instant::now();
9310        let sentinel = projection
9311            .first()
9312            .copied()
9313            .or_else(|| self.schema.columns.first().map(|column| column.id));
9314        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9315        let mut out = Vec::with_capacity(request.limit.min(ranked.len()));
9316        let mut projection_rows = 0usize;
9317        let mut projection_cells = 0usize;
9318        while out.len() < request.limit && !ranked.is_empty() {
9319            if let Some(context) = context {
9320                context.checkpoint()?;
9321                context.consume(ranked.len())?;
9322            }
9323            let needed = request.limit - out.len();
9324            let window_size = ranked
9325                .len()
9326                .min(needed.saturating_mul(2).max(needed.saturating_add(8)));
9327            let selection_started = std::time::Instant::now();
9328            let mut remainder = if ranked.len() > window_size {
9329                let (_, _, _) = ranked.select_nth_unstable_by(window_size, order);
9330                ranked.split_off(window_size)
9331            } else {
9332                Vec::new()
9333            };
9334            ranked.sort_by(order);
9335            fusion_nanos =
9336                fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9337            let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9338            let gathered_columns = projection.len().max(usize::from(sentinel.is_some()));
9339            if let Some(context) = context {
9340                context.consume(row_ids.len().saturating_mul(gathered_columns))?;
9341            }
9342            projection_rows = projection_rows.saturating_add(row_ids.len());
9343            projection_cells =
9344                projection_cells.saturating_add(row_ids.len().saturating_mul(gathered_columns));
9345            let mut cells: std::collections::HashMap<RowId, std::collections::HashMap<u16, Value>> =
9346                std::collections::HashMap::new();
9347            if let Some(column_id) = sentinel {
9348                for (row_id, value) in self.values_for_rids_batch_at_with_context(
9349                    &row_ids, column_id, snapshot, query_now, context,
9350                )? {
9351                    cells.entry(row_id).or_default().insert(column_id, value);
9352                }
9353            }
9354            for &column_id in &projection {
9355                if Some(column_id) == sentinel {
9356                    continue;
9357                }
9358                for (row_id, value) in self.values_for_rids_batch_at_with_context(
9359                    &row_ids, column_id, snapshot, query_now, context,
9360                )? {
9361                    cells.entry(row_id).or_default().insert(column_id, value);
9362                }
9363            }
9364            for (row_id, fused_score, mut components, exact_rerank_score, final_score) in
9365                ranked.drain(..)
9366            {
9367                let Some(row_cells) = cells.remove(&row_id) else {
9368                    continue;
9369                };
9370                components.sort_by(|a, b| a.retriever_name.cmp(&b.retriever_name));
9371                let final_rank = rank_offset.saturating_add(out.len()).saturating_add(1);
9372                out.push(SearchHit {
9373                    row_id,
9374                    cells: projection
9375                        .iter()
9376                        .filter_map(|column_id| {
9377                            row_cells
9378                                .get(column_id)
9379                                .cloned()
9380                                .map(|value| (*column_id, value))
9381                        })
9382                        .collect(),
9383                    components,
9384                    fused_score,
9385                    exact_rerank_score,
9386                    final_score,
9387                    final_rank,
9388                });
9389                if out.len() == request.limit {
9390                    break;
9391                }
9392            }
9393            ranked.append(&mut remainder);
9394        }
9395        crate::trace::QueryTrace::record(|trace| {
9396            trace.union_size = union_size;
9397            trace.fusion_nanos = trace.fusion_nanos.saturating_add(fusion_nanos);
9398            trace.projection_nanos = trace
9399                .projection_nanos
9400                .saturating_add(projection_started.elapsed().as_nanos() as u64);
9401            trace.total_nanos = trace
9402                .total_nanos
9403                .saturating_add(total_started.elapsed().as_nanos() as u64);
9404            trace.projection_rows = trace.projection_rows.saturating_add(projection_rows);
9405            trace.projection_cells = trace.projection_cells.saturating_add(projection_cells);
9406            if let Some(context) = context {
9407                trace.work_consumed = trace.work_consumed.saturating_add(context.consumed_work());
9408            }
9409        });
9410        Ok(out)
9411    }
9412
9413    /// MinHash candidate generation followed by exact Jaccard verification.
9414    /// An empty query set returns no hits.
9415    pub fn set_similarity(
9416        &mut self,
9417        request: &crate::query::SetSimilarityRequest,
9418    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9419        self.set_similarity_with_allowed(request, None)
9420    }
9421
9422    pub fn set_similarity_at(
9423        &mut self,
9424        request: &crate::query::SetSimilarityRequest,
9425        snapshot: Snapshot,
9426        allowed: Option<&std::collections::HashSet<RowId>>,
9427    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9428        self.set_similarity_explained_at(request, snapshot, allowed)
9429            .map(|(hits, _)| hits)
9430    }
9431
9432    /// Binary ANN candidate generation followed by exact float-vector reranking.
9433    pub fn ann_rerank(
9434        &mut self,
9435        request: &crate::query::AnnRerankRequest,
9436    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9437        self.ann_rerank_with_allowed(request, None)
9438    }
9439
9440    pub fn ann_rerank_with_allowed(
9441        &mut self,
9442        request: &crate::query::AnnRerankRequest,
9443        allowed: Option<&std::collections::HashSet<RowId>>,
9444    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9445        self.ann_rerank_at(request, self.snapshot(), allowed)
9446    }
9447
9448    pub fn ann_rerank_at(
9449        &mut self,
9450        request: &crate::query::AnnRerankRequest,
9451        snapshot: Snapshot,
9452        allowed: Option<&std::collections::HashSet<RowId>>,
9453    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9454        self.ann_rerank_at_with_context(request, snapshot, allowed, None)
9455    }
9456
9457    pub fn ann_rerank_at_with_context(
9458        &mut self,
9459        request: &crate::query::AnnRerankRequest,
9460        snapshot: Snapshot,
9461        allowed: Option<&std::collections::HashSet<RowId>>,
9462        context: Option<&crate::query::AiExecutionContext>,
9463    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9464        self.ensure_indexes_complete()?;
9465        self.ann_rerank_at_with_filters_and_context(request, snapshot, allowed, None, context)
9466    }
9467
9468    pub fn ann_rerank_at_with_candidate_authorization_and_context(
9469        &mut self,
9470        request: &crate::query::AnnRerankRequest,
9471        snapshot: Snapshot,
9472        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9473        context: Option<&crate::query::AiExecutionContext>,
9474    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9475        self.ensure_indexes_complete()?;
9476        self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9477    }
9478
9479    #[doc(hidden)]
9480    pub fn ann_rerank_at_with_candidate_authorization_on_generation(
9481        &self,
9482        request: &crate::query::AnnRerankRequest,
9483        snapshot: Snapshot,
9484        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9485        context: Option<&crate::query::AiExecutionContext>,
9486    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9487        self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9488    }
9489
9490    fn ann_rerank_at_with_filters_and_context(
9491        &self,
9492        request: &crate::query::AnnRerankRequest,
9493        snapshot: Snapshot,
9494        allowed: Option<&std::collections::HashSet<RowId>>,
9495        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9496        context: Option<&crate::query::AiExecutionContext>,
9497    ) -> Result<Vec<crate::query::AnnRerankHit>> {
9498        use crate::query::{
9499            AnnCandidateDistance, AnnRerankHit, Retriever, RetrieverScore, VectorMetric,
9500            MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9501        };
9502        if request.candidate_k == 0 || request.limit == 0 {
9503            return Err(MongrelError::InvalidArgument(
9504                "candidate_k and limit must be > 0".into(),
9505            ));
9506        }
9507        if request.candidate_k > MAX_RETRIEVER_K || request.limit > MAX_FINAL_LIMIT {
9508            return Err(MongrelError::InvalidArgument(format!(
9509                "candidate_k must be <= {MAX_RETRIEVER_K} and limit <= {MAX_FINAL_LIMIT}"
9510            )));
9511        }
9512        let retriever = Retriever::Ann {
9513            column_id: request.column_id,
9514            query: request.query.clone(),
9515            k: request.candidate_k,
9516        };
9517        self.require_select()?;
9518        self.validate_retriever(&retriever)?;
9519        let hits = self.retrieve_filtered(
9520            &retriever,
9521            snapshot,
9522            None,
9523            allowed,
9524            candidate_authorization,
9525            context,
9526        )?;
9527        let distances: std::collections::HashMap<_, _> = hits
9528            .iter()
9529            .filter_map(|hit| match hit.score {
9530                RetrieverScore::AnnHammingDistance(distance) => {
9531                    Some((hit.row_id, AnnCandidateDistance::Hamming(distance)))
9532                }
9533                RetrieverScore::AnnCosineDistance(distance) => {
9534                    Some((hit.row_id, AnnCandidateDistance::Cosine(distance)))
9535                }
9536                _ => None,
9537            })
9538            .collect();
9539        let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9540        if let Some(context) = context {
9541            context.consume(row_ids.len())?;
9542        }
9543        let gather_started = std::time::Instant::now();
9544        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9545        let values = self.values_for_rids_batch_at_with_context(
9546            &row_ids,
9547            request.column_id,
9548            snapshot,
9549            query_now,
9550            context,
9551        )?;
9552        let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9553        let score_started = std::time::Instant::now();
9554        let vector_work =
9555            crate::query::work_units(request.query.len(), crate::query::VECTOR_WORK_QUANTUM);
9556        let query_norm = if matches!(request.metric, VectorMetric::Cosine) {
9557            if let Some(context) = context {
9558                context.consume(vector_work)?;
9559            }
9560            request
9561                .query
9562                .iter()
9563                .map(|value| f64::from(*value).powi(2))
9564                .sum::<f64>()
9565                .sqrt()
9566        } else {
9567            0.0
9568        };
9569        let mut reranked = Vec::with_capacity(values.len().min(request.limit));
9570        for (row_id, value) in values {
9571            if let Some(meta) = value.generated_embedding_metadata() {
9572                if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9573                    continue;
9574                }
9575            }
9576            let Some(vector) = value.as_embedding() else {
9577                continue;
9578            };
9579            let exact_score = match request.metric {
9580                VectorMetric::DotProduct => {
9581                    if let Some(context) = context {
9582                        context.consume(vector_work)?;
9583                    }
9584                    request
9585                        .query
9586                        .iter()
9587                        .zip(vector)
9588                        .map(|(left, right)| f64::from(*left) * f64::from(*right))
9589                        .sum::<f64>()
9590                }
9591                VectorMetric::Cosine => {
9592                    if let Some(context) = context {
9593                        context.consume(vector_work.saturating_mul(2))?;
9594                    }
9595                    let dot = request
9596                        .query
9597                        .iter()
9598                        .zip(vector)
9599                        .map(|(left, right)| f64::from(*left) * f64::from(*right))
9600                        .sum::<f64>();
9601                    let norm = vector
9602                        .iter()
9603                        .map(|value| f64::from(*value).powi(2))
9604                        .sum::<f64>()
9605                        .sqrt();
9606                    if query_norm == 0.0 || norm == 0.0 {
9607                        0.0
9608                    } else {
9609                        dot / (query_norm * norm)
9610                    }
9611                }
9612                VectorMetric::Euclidean => {
9613                    if let Some(context) = context {
9614                        context.consume(vector_work)?;
9615                    }
9616                    request
9617                        .query
9618                        .iter()
9619                        .zip(vector)
9620                        .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9621                        .sum::<f64>()
9622                        .sqrt()
9623                }
9624            };
9625            let exact_score = exact_score as f32;
9626            if !exact_score.is_finite() {
9627                return Err(MongrelError::InvalidArgument(
9628                    "exact ANN score must be finite".into(),
9629                ));
9630            }
9631            let Some(candidate_distance) = distances.get(&row_id).copied() else {
9632                continue;
9633            };
9634            reranked.push(AnnRerankHit {
9635                row_id,
9636                candidate_distance,
9637                exact_score,
9638            });
9639        }
9640        reranked.sort_by(|left, right| {
9641            let score = match request.metric {
9642                VectorMetric::Euclidean => left.exact_score.total_cmp(&right.exact_score),
9643                VectorMetric::Cosine | VectorMetric::DotProduct => {
9644                    right.exact_score.total_cmp(&left.exact_score)
9645                }
9646            };
9647            score.then_with(|| left.row_id.cmp(&right.row_id))
9648        });
9649        reranked.truncate(request.limit);
9650        crate::trace::QueryTrace::record(|trace| {
9651            trace.exact_vector_gather_nanos =
9652                trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9653            trace.exact_vector_score_nanos = trace
9654                .exact_vector_score_nanos
9655                .saturating_add(score_started.elapsed().as_nanos() as u64);
9656        });
9657        Ok(reranked)
9658    }
9659
9660    pub fn set_similarity_with_allowed(
9661        &mut self,
9662        request: &crate::query::SetSimilarityRequest,
9663        allowed: Option<&std::collections::HashSet<RowId>>,
9664    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9665        self.set_similarity_explained_at(request, self.snapshot(), allowed)
9666            .map(|(hits, _)| hits)
9667    }
9668
9669    pub fn set_similarity_explained(
9670        &mut self,
9671        request: &crate::query::SetSimilarityRequest,
9672    ) -> Result<(
9673        Vec<crate::query::SetSimilarityHit>,
9674        crate::query::SetSimilarityTrace,
9675    )> {
9676        self.set_similarity_explained_at(request, self.snapshot(), None)
9677    }
9678
9679    fn set_similarity_explained_at(
9680        &mut self,
9681        request: &crate::query::SetSimilarityRequest,
9682        snapshot: Snapshot,
9683        allowed: Option<&std::collections::HashSet<RowId>>,
9684    ) -> Result<(
9685        Vec<crate::query::SetSimilarityHit>,
9686        crate::query::SetSimilarityTrace,
9687    )> {
9688        self.ensure_indexes_complete()?;
9689        self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, None)
9690    }
9691
9692    pub fn set_similarity_at_with_context(
9693        &mut self,
9694        request: &crate::query::SetSimilarityRequest,
9695        snapshot: Snapshot,
9696        allowed: Option<&std::collections::HashSet<RowId>>,
9697        context: Option<&crate::query::AiExecutionContext>,
9698    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9699        self.ensure_indexes_complete()?;
9700        self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, context)
9701            .map(|(hits, _)| hits)
9702    }
9703
9704    pub fn set_similarity_at_with_candidate_authorization_and_context(
9705        &mut self,
9706        request: &crate::query::SetSimilarityRequest,
9707        snapshot: Snapshot,
9708        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9709        context: Option<&crate::query::AiExecutionContext>,
9710    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9711        self.ensure_indexes_complete()?;
9712        self.set_similarity_explained_at_with_context(
9713            request,
9714            snapshot,
9715            None,
9716            authorization,
9717            context,
9718        )
9719        .map(|(hits, _)| hits)
9720    }
9721
9722    #[doc(hidden)]
9723    pub fn set_similarity_at_with_candidate_authorization_on_generation(
9724        &self,
9725        request: &crate::query::SetSimilarityRequest,
9726        snapshot: Snapshot,
9727        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9728        context: Option<&crate::query::AiExecutionContext>,
9729    ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9730        self.set_similarity_explained_at_with_context(
9731            request,
9732            snapshot,
9733            None,
9734            authorization,
9735            context,
9736        )
9737        .map(|(hits, _)| hits)
9738    }
9739
9740    fn set_similarity_explained_at_with_context(
9741        &self,
9742        request: &crate::query::SetSimilarityRequest,
9743        snapshot: Snapshot,
9744        allowed: Option<&std::collections::HashSet<RowId>>,
9745        candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9746        context: Option<&crate::query::AiExecutionContext>,
9747    ) -> Result<(
9748        Vec<crate::query::SetSimilarityHit>,
9749        crate::query::SetSimilarityTrace,
9750    )> {
9751        use crate::query::{
9752            Retriever, RetrieverScore, SetSimilarityHit, MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9753            MAX_SET_MEMBERS,
9754        };
9755        let mut trace = crate::query::SetSimilarityTrace::default();
9756        if request.members.is_empty() {
9757            return Ok((Vec::new(), trace));
9758        }
9759        if request.candidate_k == 0 || request.limit == 0 {
9760            return Err(MongrelError::InvalidArgument(
9761                "candidate_k and limit must be > 0".into(),
9762            ));
9763        }
9764        if request.candidate_k > MAX_RETRIEVER_K
9765            || request.limit > MAX_FINAL_LIMIT
9766            || request.members.len() > MAX_SET_MEMBERS
9767        {
9768            return Err(MongrelError::InvalidArgument(format!(
9769                "candidate_k must be <= {MAX_RETRIEVER_K}, limit <= {MAX_FINAL_LIMIT}, and members <= {MAX_SET_MEMBERS}"
9770            )));
9771        }
9772        if !request.min_jaccard.is_finite() || !(0.0..=1.0).contains(&request.min_jaccard) {
9773            return Err(MongrelError::InvalidArgument(
9774                "min_jaccard must be finite and between 0 and 1".into(),
9775            ));
9776        }
9777        let started = std::time::Instant::now();
9778        let retriever = Retriever::MinHash {
9779            column_id: request.column_id,
9780            members: request.members.clone(),
9781            k: request.candidate_k,
9782        };
9783        self.require_select()?;
9784        self.validate_retriever(&retriever)?;
9785        let hits = self.retrieve_filtered(
9786            &retriever,
9787            snapshot,
9788            None,
9789            allowed,
9790            candidate_authorization,
9791            context,
9792        )?;
9793        trace.candidate_generation_us = started.elapsed().as_micros() as u64;
9794        trace.candidate_count = hits.len();
9795        let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9796        if let Some(context) = context {
9797            context.consume(row_ids.len())?;
9798        }
9799        let started = std::time::Instant::now();
9800        let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9801        let values = self.values_for_rids_batch_at_with_context(
9802            &row_ids,
9803            request.column_id,
9804            snapshot,
9805            query_now,
9806            context,
9807        )?;
9808        trace.gather_us = started.elapsed().as_micros() as u64;
9809        if let Some(context) = context {
9810            context.consume(request.members.len())?;
9811        }
9812        let query: std::collections::HashSet<_> = request.members.iter().cloned().collect();
9813        let estimates: std::collections::HashMap<_, _> = hits
9814            .into_iter()
9815            .filter_map(|hit| match hit.score {
9816                RetrieverScore::MinHashEstimatedJaccard(score) => Some((hit.row_id, score)),
9817                _ => None,
9818            })
9819            .collect();
9820        let started = std::time::Instant::now();
9821        let mut parsed = Vec::with_capacity(values.len());
9822        for (row_id, value) in values {
9823            let Value::Bytes(bytes) = value else {
9824                continue;
9825            };
9826            if let Some(context) = context {
9827                context.consume(crate::query::work_units(
9828                    bytes.len(),
9829                    crate::query::PARSE_WORK_QUANTUM,
9830                ))?;
9831            }
9832            let Ok(serde_json::Value::Array(members)) = serde_json::from_slice(&bytes) else {
9833                continue;
9834            };
9835            if let Some(context) = context {
9836                context.consume(members.len())?;
9837            }
9838            let stored = members
9839                .into_iter()
9840                .filter_map(|member| match member {
9841                    serde_json::Value::String(value) => {
9842                        Some(crate::query::SetMember::String(value))
9843                    }
9844                    serde_json::Value::Number(value) => {
9845                        Some(crate::query::SetMember::Number(value))
9846                    }
9847                    serde_json::Value::Bool(value) => Some(crate::query::SetMember::Boolean(value)),
9848                    _ => None,
9849                })
9850                .collect::<std::collections::HashSet<_>>();
9851            parsed.push((row_id, stored));
9852        }
9853        trace.parse_us = started.elapsed().as_micros() as u64;
9854        trace.verified_count = parsed.len();
9855        let started = std::time::Instant::now();
9856        let mut exact = Vec::new();
9857        for (row_id, stored) in parsed {
9858            if let Some(context) = context {
9859                context.consume(query.len().saturating_add(stored.len()))?;
9860            }
9861            let union = query.union(&stored).count();
9862            let score = if union == 0 {
9863                1.0
9864            } else {
9865                query.intersection(&stored).count() as f32 / union as f32
9866            };
9867            if score >= request.min_jaccard {
9868                exact.push(SetSimilarityHit {
9869                    row_id,
9870                    estimated_jaccard: estimates.get(&row_id).copied().unwrap_or_default(),
9871                    exact_jaccard: score,
9872                });
9873            }
9874        }
9875        exact.sort_by(|a, b| {
9876            b.exact_jaccard
9877                .total_cmp(&a.exact_jaccard)
9878                .then_with(|| a.row_id.cmp(&b.row_id))
9879        });
9880        exact.truncate(request.limit);
9881        trace.score_us = started.elapsed().as_micros() as u64;
9882        crate::trace::QueryTrace::record(|query_trace| {
9883            query_trace.exact_set_gather_nanos = query_trace
9884                .exact_set_gather_nanos
9885                .saturating_add(trace.gather_us.saturating_mul(1_000));
9886            query_trace.exact_set_parse_nanos = query_trace
9887                .exact_set_parse_nanos
9888                .saturating_add(trace.parse_us.saturating_mul(1_000));
9889            query_trace.exact_set_score_nanos = query_trace
9890                .exact_set_score_nanos
9891                .saturating_add(trace.score_us.saturating_mul(1_000));
9892        });
9893        Ok((exact, trace))
9894    }
9895
9896    /// Fetch one column for visible row ids without decoding unrelated columns.
9897    fn values_for_rids_batch_at(
9898        &self,
9899        row_ids: &[u64],
9900        column_id: u16,
9901        snapshot: Snapshot,
9902        now: i64,
9903    ) -> Result<Vec<(RowId, Value)>> {
9904        if self.ttl.is_none()
9905            && self.memtable.is_empty()
9906            && self.mutable_run.is_empty()
9907            && self.run_refs.len() == 1
9908        {
9909            let mut reader = self.open_reader(self.run_refs[0].run_id)?;
9910            // Small projections should not decode and scan the run's entire
9911            // row-id column. Resolve each requested row through the page-pruned
9912            // point path until a full visibility pass becomes cheaper. Keep
9913            // this crossover aligned with `rows_for_rids_at_time`.
9914            if row_ids.len().saturating_mul(24) < reader.row_count() {
9915                let mut values = Vec::with_capacity(row_ids.len());
9916                for &raw_row_id in row_ids {
9917                    let row_id = RowId(raw_row_id);
9918                    if let Some((_, false, Some(value))) =
9919                        reader.get_version_column_at(row_id, snapshot, column_id)?
9920                    {
9921                        values.push((row_id, value));
9922                    }
9923                }
9924                return Ok(values);
9925            }
9926            let (positions, visible_row_ids) = reader.visible_positions_with_rids_at(snapshot)?;
9927            let requested: Vec<(RowId, usize)> = row_ids
9928                .iter()
9929                .filter_map(|raw| {
9930                    visible_row_ids
9931                        .binary_search(&(*raw as i64))
9932                        .ok()
9933                        .map(|index| (RowId(*raw), positions[index]))
9934                })
9935                .collect();
9936            let values = reader.gather_column(
9937                column_id,
9938                &requested
9939                    .iter()
9940                    .map(|(_, position)| *position)
9941                    .collect::<Vec<_>>(),
9942            )?;
9943            return Ok(requested
9944                .into_iter()
9945                .zip(values)
9946                .map(|((row_id, _), value)| (row_id, value))
9947                .collect());
9948        }
9949        self.values_for_rids_at(row_ids, column_id, snapshot, now)
9950    }
9951
9952    fn values_for_rids_batch_at_with_context(
9953        &self,
9954        row_ids: &[u64],
9955        column_id: u16,
9956        snapshot: Snapshot,
9957        now: i64,
9958        context: Option<&crate::query::AiExecutionContext>,
9959    ) -> Result<Vec<(RowId, Value)>> {
9960        let Some(context) = context else {
9961            return self.values_for_rids_batch_at(row_ids, column_id, snapshot, now);
9962        };
9963        let mut values = Vec::with_capacity(row_ids.len());
9964        for chunk in row_ids.chunks(256) {
9965            context.checkpoint()?;
9966            values.extend(self.values_for_rids_batch_at(chunk, column_id, snapshot, now)?);
9967        }
9968        Ok(values)
9969    }
9970
9971    /// Fetch one column for visible row ids without decoding unrelated columns.
9972    fn values_for_rids_at(
9973        &self,
9974        row_ids: &[u64],
9975        column_id: u16,
9976        snapshot: Snapshot,
9977        now: i64,
9978    ) -> Result<Vec<(RowId, Value)>> {
9979        let mut readers: Vec<_> = self
9980            .run_refs
9981            .iter()
9982            .map(|run| self.open_reader(run.run_id))
9983            .collect::<Result<_>>()?;
9984        let mut out = Vec::with_capacity(row_ids.len());
9985        for &raw_row_id in row_ids {
9986            let row_id = RowId(raw_row_id);
9987            let mem = self.memtable.get_version_at(row_id, snapshot);
9988            let mutable = self.mutable_run.get_version_at(row_id, snapshot);
9989            let overlay = match (mem, mutable) {
9990                (Some((_, a)), Some((_, b))) => Some(
9991                    if Snapshot::version_is_newer(
9992                        a.committed_epoch,
9993                        a.commit_ts,
9994                        b.committed_epoch,
9995                        b.commit_ts,
9996                    ) {
9997                        a
9998                    } else {
9999                        b
10000                    },
10001                ),
10002                (Some((_, value)), None) | (None, Some((_, value))) => Some(value),
10003                (None, None) => None,
10004            };
10005            if let Some(row) = overlay {
10006                if !row.deleted && !self.row_expired_at(&row, now) {
10007                    if let Some(value) = row.columns.get(&column_id) {
10008                        out.push((row_id, value.clone()));
10009                    }
10010                }
10011                continue;
10012            }
10013
10014            // REM-001: keep `commit_ts` on the cross-run candidate so the winner is
10015            // selected under full HLC authority instead of the legacy epoch-only
10016            // tuple. The metadata-preserving `get_version_column_full_at`
10017            // returns a `VersionedColumnValue` (stamp, deleted, value).
10018            let mut best: Option<(crate::sorted_run::VersionedColumnValue, usize)> = None;
10019            for (index, reader) in readers.iter_mut().enumerate() {
10020                if let Some(versioned) =
10021                    reader.get_version_column_full_at(row_id, snapshot, column_id)?
10022                {
10023                    if best
10024                        .as_ref()
10025                        .map(|(current, _)| versioned.stamp.is_newer_than(current.stamp))
10026                        .unwrap_or(true)
10027                    {
10028                        best = Some((versioned, index));
10029                    }
10030                }
10031            }
10032            let Some((candidate, reader_index)) = best else {
10033                continue;
10034            };
10035            if candidate.deleted {
10036                continue;
10037            }
10038            let Some(value) = candidate.value.clone() else {
10039                continue;
10040            };
10041            if let Some(ttl) = self.ttl {
10042                if ttl.column_id != column_id {
10043                    if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
10044                        row_id,
10045                        snapshot,
10046                        ttl.column_id,
10047                    )? {
10048                        if let Some(Value::Int64(timestamp)) = ttl_value.value {
10049                            if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10050                                continue;
10051                            }
10052                        }
10053                    }
10054                } else if let Value::Int64(timestamp) = &value {
10055                    if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10056                        continue;
10057                    }
10058                }
10059            }
10060            out.push((row_id, value));
10061        }
10062        Ok(out)
10063    }
10064
10065    /// Materialize the MVCC-visible, non-deleted rows for `rids` at `snapshot`,
10066    /// preserving the input order. Rows whose newest visible version is a
10067    /// tombstone, or that no longer exist, are omitted. Shared by index-served
10068    /// [`query`] and the Phase 8.1 FK-join path.
10069    pub fn rows_for_rids(&self, rids: &[u64], snapshot: Snapshot) -> Result<Vec<Row>> {
10070        self.rows_for_rids_at_time(rids, snapshot, unix_nanos_now(), None)
10071    }
10072
10073    pub fn rows_for_rids_with_context(
10074        &self,
10075        rids: &[u64],
10076        snapshot: Snapshot,
10077        context: &crate::query::AiExecutionContext,
10078    ) -> Result<Vec<Row>> {
10079        context.consume(rids.len().saturating_mul(self.schema.columns.len()))?;
10080        self.rows_for_rids_at_time(rids, snapshot, context.query_time_nanos(), None)
10081    }
10082
10083    fn rows_for_rids_at_time(
10084        &self,
10085        rids: &[u64],
10086        snapshot: Snapshot,
10087        ttl_now: i64,
10088        control: Option<&crate::ExecutionControl>,
10089    ) -> Result<Vec<Row>> {
10090        use std::collections::HashMap;
10091        let mut rows = Vec::with_capacity(rids.len());
10092        // Overlay (memtable + mutable-run) newest visible version per rid —
10093        // these shadow any stale version stored in a run. Prefer HLC order via
10094        // version_is_newer when stamps are present (P0.5-T3).
10095        //
10096        // `rids` is already index-resolved (the caller's condition set), so it
10097        // is normally tiny relative to the memtable/mutable-run tiers — a
10098        // single-row PK/unique check feeding insert/update/delete resolves to
10099        // 0 or 1 rid. Materializing every version in both tiers (the old
10100        // behavior) cost O(tier size) regardless, which meant an unrelated
10101        // full-table-sized scan (plus the drop cost of the resulting map) on
10102        // every point lookup once the table grew large. Below the crossover,
10103        // a direct per-rid probe (`get_version_at`) wins; once `rids` approaches
10104        // tier size, one linear materializing pass beats `rids.len()` separate
10105        // probes, so fall back to it.
10106        let tier_size = self.memtable.len() + self.mutable_run.len();
10107        let mut overlay: HashMap<u64, Row> = HashMap::with_capacity(rids.len());
10108        if rids.len().saturating_mul(24) < tier_size {
10109            for &rid in rids {
10110                if overlay.len() & 255 == 0 {
10111                    control
10112                        .map(crate::ExecutionControl::checkpoint)
10113                        .transpose()?;
10114                }
10115                let mem = self.memtable.get_version_at(RowId(rid), snapshot);
10116                let mrun = self.mutable_run.get_version_at(RowId(rid), snapshot);
10117                let newest = match (mem, mrun) {
10118                    (Some((_, mr)), Some((_, rr))) => Some(
10119                        if Snapshot::version_is_newer(
10120                            mr.committed_epoch,
10121                            mr.commit_ts,
10122                            rr.committed_epoch,
10123                            rr.commit_ts,
10124                        ) {
10125                            mr
10126                        } else {
10127                            rr
10128                        },
10129                    ),
10130                    (Some((_, mr)), None) => Some(mr),
10131                    (None, Some((_, rr))) => Some(rr),
10132                    (None, None) => None,
10133                };
10134                if let Some(row) = newest {
10135                    overlay.insert(rid, row);
10136                }
10137            }
10138        } else {
10139            let fold_newest = |row: Row, overlay: &mut HashMap<u64, Row>| {
10140                overlay
10141                    .entry(row.row_id.0)
10142                    .and_modify(|e| {
10143                        if Snapshot::version_is_newer(
10144                            row.committed_epoch,
10145                            row.commit_ts,
10146                            e.committed_epoch,
10147                            e.commit_ts,
10148                        ) {
10149                            *e = row.clone();
10150                        }
10151                    })
10152                    .or_insert(row);
10153            };
10154            for (index, row) in self
10155                .memtable
10156                .visible_versions_at(snapshot)
10157                .into_iter()
10158                .enumerate()
10159            {
10160                if index & 255 == 0 {
10161                    control
10162                        .map(crate::ExecutionControl::checkpoint)
10163                        .transpose()?;
10164                }
10165                fold_newest(row, &mut overlay);
10166            }
10167            for (index, row) in self
10168                .mutable_run
10169                .visible_versions_at(snapshot)
10170                .into_iter()
10171                .enumerate()
10172            {
10173                if index & 255 == 0 {
10174                    control
10175                        .map(crate::ExecutionControl::checkpoint)
10176                        .transpose()?;
10177                }
10178                fold_newest(row, &mut overlay);
10179            }
10180        }
10181        if self.run_refs.len() == 1 {
10182            let mut reader = self.open_reader(self.run_refs[0].run_id)?;
10183            // Same crossover as the overlay above: `visible_positions_with_rids`
10184            // decodes/scans the run's *entire* row-id column regardless of
10185            // `rids.len()`, so a point lookup (0 or 1 rid, the common
10186            // insert/update/delete case) paid an O(run size) tax for a single
10187            // row. Below the crossover, `get_version`'s page-pruned lookup
10188            // (`SYS_ROW_ID` pages carry exact row-id bounds) resolves each rid
10189            // by decoding only its page, no whole-column decode.
10190            if rids.len().saturating_mul(24) < reader.row_count() {
10191                for (index, &rid) in rids.iter().enumerate() {
10192                    if index & 255 == 0 {
10193                        control
10194                            .map(crate::ExecutionControl::checkpoint)
10195                            .transpose()?;
10196                    }
10197                    if let Some(r) = overlay.get(&rid) {
10198                        if !r.deleted {
10199                            rows.push(r.clone());
10200                        }
10201                        continue;
10202                    }
10203                    if let Some((_, row)) = reader.get_version_at(RowId(rid), snapshot)? {
10204                        if !row.deleted {
10205                            rows.push(row);
10206                        }
10207                    }
10208                }
10209                rows.retain(|row| !self.row_expired_at(row, ttl_now));
10210                return Ok(rows);
10211            }
10212            // Phase 16.3b: decode the system columns ONCE (via the clean-run-
10213            // shortcut visibility pass) and binary-search each requested rid,
10214            // instead of `get_version`-per-rid which re-decoded + cloned the
10215            // full system columns on every call (the ~350 ms native-query tax).
10216            // Phase 16.3b finish: batch the survivor positions into ONE
10217            // `materialize_batch` call so user columns are decoded once each via
10218            // the typed, page-cached path (not a per-rid `Vec<Value>` decode +
10219            // `.cloned()`).
10220            let (positions, vis_rids) = reader.visible_positions_with_rids_at(snapshot)?;
10221            // First pass: classify each input rid (overlay / run position /
10222            // not-found), recording the run positions to fetch in input order.
10223            enum Src {
10224                Overlay,
10225                Run,
10226            }
10227            let mut plan: Vec<Src> = Vec::with_capacity(rids.len());
10228            let mut fetch: Vec<usize> = Vec::with_capacity(rids.len());
10229            for (index, rid) in rids.iter().enumerate() {
10230                if index & 255 == 0 {
10231                    control
10232                        .map(crate::ExecutionControl::checkpoint)
10233                        .transpose()?;
10234                }
10235                if overlay.contains_key(rid) {
10236                    plan.push(Src::Overlay);
10237                    continue;
10238                }
10239                match vis_rids.binary_search(&(*rid as i64)) {
10240                    Ok(i) => {
10241                        plan.push(Src::Run);
10242                        fetch.push(positions[i]);
10243                    }
10244                    Err(_) => { /* not found — omitted from output */ }
10245                }
10246            }
10247            let fetched = reader.materialize_batch(&fetch)?;
10248            let mut fetched_iter = fetched.into_iter();
10249            for (index, (rid, src)) in rids.iter().zip(plan).enumerate() {
10250                if index & 255 == 0 {
10251                    control
10252                        .map(crate::ExecutionControl::checkpoint)
10253                        .transpose()?;
10254                }
10255                match src {
10256                    Src::Overlay => {
10257                        if let Some(r) = overlay.get(rid) {
10258                            if !r.deleted {
10259                                rows.push(r.clone());
10260                            }
10261                        }
10262                    }
10263                    Src::Run => {
10264                        if let Some(row) = fetched_iter.next() {
10265                            if !row.deleted {
10266                                rows.push(row);
10267                            }
10268                        }
10269                    }
10270                }
10271            }
10272            rows.retain(|row| !self.row_expired_at(row, ttl_now));
10273            return Ok(rows);
10274        }
10275        // Multi-run: one reader per run; newest visible version across all runs
10276        // + the overlay. (Per-rid `get_version` here is unavoidable without a
10277        // cross-run merge, but multi-run is the uncommon cold case.)
10278        let mut readers: Vec<_> = self
10279            .run_refs
10280            .iter()
10281            .map(|rr| self.open_reader(rr.run_id))
10282            .collect::<Result<Vec<_>>>()?;
10283        for (index, rid) in rids.iter().enumerate() {
10284            if index & 255 == 0 {
10285                control
10286                    .map(crate::ExecutionControl::checkpoint)
10287                    .transpose()?;
10288            }
10289            if let Some(r) = overlay.get(rid) {
10290                if !r.deleted {
10291                    rows.push(r.clone());
10292                }
10293                continue;
10294            }
10295            // REM-001: keep the full VersionStamp so the cross-run fold uses HLC
10296            // authority when both candidates are stamped (the legacy
10297            // `(epoch, _)` tuple discarded `commit_ts` and let a higher-epoch
10298            // run silently outrank an HLC-newer run).
10299            let mut best: Option<(VersionStamp, Row)> = None;
10300            for reader in readers.iter_mut() {
10301                if let Ok(Some((stamp, row))) = reader.get_version_stamp_at(RowId(*rid), snapshot) {
10302                    if best
10303                        .as_ref()
10304                        .map(|(current, _)| stamp.is_newer_than(*current))
10305                        .unwrap_or(true)
10306                    {
10307                        best = Some((stamp, row));
10308                    }
10309                }
10310            }
10311            if let Some((_, r)) = best {
10312                if !r.deleted {
10313                    rows.push(r);
10314                }
10315            }
10316        }
10317        rows.retain(|row| !self.row_expired_at(row, ttl_now));
10318        Ok(rows)
10319    }
10320
10321    /// Resolve the referencing (FK) side of a primary-key ↔ foreign-key join as
10322    /// a row-id set (Phase 8.1): union the roaring-bitmap entries of
10323    /// `fk_column_id` for every value in `pk_values` — the surviving
10324    /// primary-key values — then intersect with `fk_conditions`, i.e. any
10325    /// FK-side predicates (`ann_search ∩ fm_contains`, bitmap equality, range,
10326    /// …). Returns the survivor row-ids ascending. Requires a bitmap index on
10327    /// `fk_column_id`; returns an empty set when there is none.
10328    /// Whether live indexes are complete (Phase 14.7 + 17.2: the broadcast
10329    /// join path checks this before using the HOT index).
10330    pub fn indexes_complete(&self) -> bool {
10331        self.indexes_complete
10332    }
10333
10334    /// Where bulk loads put the index-build cost (see [`IndexBuildPolicy`]).
10335    pub fn index_build_policy(&self) -> IndexBuildPolicy {
10336        self.index_build_policy
10337    }
10338
10339    /// Set the bulk-load index-build policy. Takes effect on the next
10340    /// `bulk_load` / `bulk_load_columns` / `bulk_load_fast`; never changes
10341    /// already-built indexes.
10342    pub fn set_index_build_policy(&mut self, policy: IndexBuildPolicy) {
10343        self.index_build_policy = policy;
10344    }
10345
10346    /// Phase 17.2: broadcast join — return the distinct values in this table's
10347    /// bitmap index for `column_id` that also exist as a key in `pk_db`'s HOT
10348    /// index. Avoids loading the entire PK table when the FK column has low
10349    /// cardinality. Returns `None` if no bitmap index exists for the column.
10350    pub fn broadcast_join_values(&self, column_id: u16, pk_db: &Table) -> Option<Vec<Vec<u8>>> {
10351        // A deferred bulk load leaves the bitmap unbuilt — its (empty) key set
10352        // would silently produce an empty join. Decline; the caller falls back
10353        // to the PK-side query path, which completes indexes lazily.
10354        if !self.indexes_complete {
10355            return None;
10356        }
10357        let b = self.bitmap.get(&column_id)?;
10358        let result: Vec<Vec<u8>> = b
10359            .keys()
10360            .into_iter()
10361            .filter(|k| pk_db.hot.get(k.as_slice()).is_some())
10362            .collect();
10363        Some(result)
10364    }
10365
10366    pub fn fk_join_row_ids(
10367        &self,
10368        fk_column_id: u16,
10369        pk_values: &[Vec<u8>],
10370        fk_conditions: &[crate::query::Condition],
10371        snapshot: Snapshot,
10372    ) -> Result<Vec<u64>> {
10373        let Some(b) = self.bitmap.get(&fk_column_id) else {
10374            return Ok(Vec::new());
10375        };
10376        let mut join_set = {
10377            let mut acc = roaring::RoaringBitmap::new();
10378            for v in pk_values {
10379                acc |= b.get(v);
10380            }
10381            RowIdSet::from_roaring(acc)
10382        };
10383        if !fk_conditions.is_empty() {
10384            let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10385            sets.push(join_set);
10386            for c in fk_conditions {
10387                sets.push(self.resolve_condition(c, snapshot)?);
10388            }
10389            join_set = RowIdSet::intersect_many(sets);
10390        }
10391        Ok(join_set.into_sorted_vec())
10392    }
10393
10394    /// Like [`fk_join_row_ids`] but returns only the **cardinality** of the FK
10395    /// survivor set — without materializing or sorting it. For a bare
10396    /// `COUNT(*)` join with no FK-side filter this is O(1) on the bitmap union
10397    /// (Phase 17.4): the prior path built a `HashSet<u64>` + `Vec<u64>` +
10398    /// `sort_unstable` over up to N rows only to read `.len()`.
10399    pub fn fk_join_count(
10400        &self,
10401        fk_column_id: u16,
10402        pk_values: &[Vec<u8>],
10403        fk_conditions: &[crate::query::Condition],
10404        snapshot: Snapshot,
10405    ) -> Result<u64> {
10406        let Some(b) = self.bitmap.get(&fk_column_id) else {
10407            return Ok(0);
10408        };
10409        let mut acc = roaring::RoaringBitmap::new();
10410        for v in pk_values {
10411            acc |= b.get(v);
10412        }
10413        if fk_conditions.is_empty() {
10414            return Ok(acc.len());
10415        }
10416        let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10417        sets.push(RowIdSet::from_roaring(acc));
10418        for c in fk_conditions {
10419            sets.push(self.resolve_condition(c, snapshot)?);
10420        }
10421        Ok(RowIdSet::intersect_many(sets).len() as u64)
10422    }
10423
10424    /// Inspect the row at `rid` directly — without going through
10425    /// [`Self::get`] (which collapses tombstones and TTL-expired rows into
10426    /// `None`). Used by [`Self::resolve_pk_with_hot_fallback`] so the
10427    /// fallback reason can distinguish Tombstone from TtlExpired.
10428    fn inspect_row_at(&self, rid: RowId, snapshot: Snapshot) -> Option<crate::memtable::Row> {
10429        let mut best: Option<crate::memtable::Row> = None;
10430        let mut consider = |row: crate::memtable::Row| {
10431            if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
10432                return;
10433            }
10434            if best.as_ref().is_none_or(|current| {
10435                Snapshot::version_is_newer(
10436                    row.committed_epoch,
10437                    row.commit_ts,
10438                    current.committed_epoch,
10439                    current.commit_ts,
10440                )
10441            }) {
10442                best = Some(row);
10443            }
10444        };
10445        if let Some((_, row)) = self.memtable.get_version_at(rid, snapshot) {
10446            consider(row);
10447        }
10448        if let Some((_, row)) = self.mutable_run.get_version_at(rid, snapshot) {
10449            consider(row);
10450        }
10451        for rr in &self.run_refs {
10452            if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
10453                if rid.0 < min_rid || rid.0 > max_rid {
10454                    continue;
10455                }
10456            }
10457            let Ok(mut reader) = self.open_reader(rr.run_id) else {
10458                continue;
10459            };
10460            // REM-001: route through the full-Snapshot run API so HLC-stamped
10461            // row versions are admitted by `observes_row` and recency selection
10462            // uses `commit_ts` instead of discarding it at the epoch boundary.
10463            let Ok(Some((_stamp, row))) = reader.get_version_stamp_at(rid, snapshot) else {
10464                continue;
10465            };
10466            consider(row);
10467        }
10468        best
10469    }
10470
10471    fn resolve_pk_with_hot_fallback(
10472        &self,
10473        pk_column_id: u16,
10474        lookup: &[u8],
10475        snapshot: Snapshot,
10476    ) -> Result<RowIdSet> {
10477        // Private WAL: the in-flight batch lands in the memtable at
10478        // `pending_epoch = visible + 1` (puts and matching tombstones). A
10479        // caller snapshot pinned at the *current* visible epoch predates
10480        // every pending write, so a PK lookup would resolve a just-replaced
10481        // PK to the stale pre-image (or resurrect a just-deleted row).
10482        // Advance to `pending_epoch` and let the batch participate — the
10483        // same read-your-writes rule as `eligible_candidate_ids` and
10484        // `range_scan_i64`. A strictly *historical* pinned snapshot is
10485        // honored as-is: the pending batch is uncommitted and must stay
10486        // invisible to it. Shared WAL tables keep the original snapshot
10487        // because their pending rows live in `pending_rows` and haven't
10488        // been materialised into the memtable yet.
10489        let snapshot = if self.is_shared()
10490            || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10491            || snapshot.epoch.0 != self.epoch.visible().0
10492        {
10493            snapshot
10494        } else {
10495            Snapshot::at(self.pending_epoch())
10496        };
10497        // Indexes incomplete: record `IndexIncomplete` and run the scanner
10498        // directly. The HOT map may be stale or absent, but the scanner's
10499        // result is still correct because it reads durable runs.
10500        if !self.indexes_complete {
10501            let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10502            self.record_hot_fallback_reason(crate::trace::HotFallbackReason::IndexIncomplete);
10503            return Ok(result);
10504        }
10505        // Step 1 — HOT hit attempt. Look up the mapped `RowId`; if absent,
10506        // delegate straight to the scanner (which classifies the reason).
10507        let mapped = self.hot.get(lookup);
10508        let Some(r) = mapped else {
10509            let (result, reason) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10510            self.record_hot_fallback_reason(reason);
10511            return Ok(result);
10512        };
10513        // Step 2 — historical snapshot: the HOT map is keyed on the latest
10514        // RowId, not the historical one. The historical branch records its
10515        // own reason and runs the scanner; the inner scanner is suppressed
10516        // from recording a second reason (see `pk_equality_fallback`).
10517        if snapshot.epoch < self.current_epoch() {
10518            self.record_hot_fallback_reason(crate::trace::HotFallbackReason::HistoricalSnapshot);
10519            let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10520            return Ok(result);
10521        }
10522        // Step 3 — materialize the mapped candidate and classify it.
10523        // `inspect_row_at` does not collapse TTL-expired rows into `None`,
10524        // so the inspection can distinguish Tombstone from TtlExpired.
10525        let materialized = self.inspect_row_at(r, snapshot);
10526        let now_nanos = unix_nanos_now();
10527        let inspection = crate::trace::inspect_hot_candidate(
10528            materialized.as_ref(),
10529            snapshot,
10530            self.ttl,
10531            now_nanos,
10532            pk_column_id,
10533            lookup,
10534            |row| {
10535                let pk_value = row.columns.get(&pk_column_id);
10536                pk_value
10537                    .map(|v| self.index_lookup_key(pk_column_id, v))
10538                    .unwrap_or_default()
10539            },
10540        );
10541        match inspection {
10542            crate::trace::HotCandidateInspection::Hit(row) => {
10543                self.lookup_metrics
10544                    .hot_lookup_hit
10545                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10546                crate::trace::QueryTrace::record(|t| {
10547                    t.hot_lookup_attempted = true;
10548                    t.hot_lookup_hit = true;
10549                });
10550                Ok(RowIdSet::one(row.row_id.0))
10551            }
10552            failure => {
10553                let reason = match &failure {
10554                    crate::trace::HotCandidateInspection::Hit(_) => unreachable!(),
10555                    crate::trace::HotCandidateInspection::MissingRow => {
10556                        // `inspect_row_at` could not find any version at this
10557                        // RowId. The HOT map pointed at a `RowId` that does
10558                        // not exist; the closest label is Tombstone (the row
10559                        // used to be there and is now gone).
10560                        crate::trace::HotFallbackReason::Tombstone
10561                    }
10562                    crate::trace::HotCandidateInspection::Invisible => {
10563                        crate::trace::HotFallbackReason::InvisibleAtSnapshot
10564                    }
10565                    crate::trace::HotCandidateInspection::Tombstone => {
10566                        crate::trace::HotFallbackReason::Tombstone
10567                    }
10568                    crate::trace::HotCandidateInspection::TtlExpired => {
10569                        crate::trace::HotFallbackReason::TtlExpired
10570                    }
10571                    crate::trace::HotCandidateInspection::PrimaryKeyMismatch { .. } => {
10572                        crate::trace::HotFallbackReason::PrimaryKeyMismatch
10573                    }
10574                };
10575                // The HOT map may have a stale RowId; the inner scanner is
10576                // the only source of the verified RowIdSet. Suppress the
10577                // inner `record_hot_fallback_reason` call by passing
10578                // `snapshot` unchanged — the historical/PK-mismatch branches
10579                // already short-circuit before re-recording.
10580                let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10581                self.record_hot_fallback_reason(reason);
10582                Ok(result)
10583            }
10584        }
10585    }
10586
10587    /// Resolve a single condition to its row-id set. Index-served conditions use
10588    /// the in-memory indexes; `Range`/`RangeF64` prefer the learned (PGM) index
10589    /// or the reader's page-index-skipping path on the single-run fast path, and
10590    /// only fall back to a `visible_rows` scan off the fast path (multi-run).
10591    fn resolve_condition(
10592        &self,
10593        c: &crate::query::Condition,
10594        snapshot: Snapshot,
10595    ) -> Result<RowIdSet> {
10596        self.resolve_condition_with_allowed(c, snapshot, None)
10597    }
10598
10599    fn resolve_condition_with_allowed(
10600        &self,
10601        c: &crate::query::Condition,
10602        snapshot: Snapshot,
10603        allowed: Option<&std::collections::HashSet<RowId>>,
10604    ) -> Result<RowIdSet> {
10605        use crate::query::Condition;
10606        self.validate_condition(c)?;
10607        Ok(match c {
10608            Condition::Pk(key) => {
10609                let lookup = self
10610                    .schema
10611                    .primary_key()
10612                    .map(|pk| self.index_lookup_key_bytes(pk.id, key))
10613                    .unwrap_or_else(|| key.clone());
10614                if let Some(pk_col) = self.schema.primary_key() {
10615                    return self.resolve_pk_with_hot_fallback(pk_col.id, &lookup, snapshot);
10616                }
10617                // No primary key column — HOT is meaningless. Match the
10618                // legacy behavior: every PK condition collapses to an empty
10619                // set.
10620                RowIdSet::empty()
10621            }
10622            Condition::BitmapEq { column_id, value } => {
10623                let lookup = self.index_lookup_key_bytes(*column_id, value);
10624                self.bitmap
10625                    .get(column_id)
10626                    .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
10627                    .unwrap_or_else(RowIdSet::empty)
10628            }
10629            Condition::BitmapIn { column_id, values } => {
10630                let bm = self.bitmap.get(column_id);
10631                let mut acc = roaring::RoaringBitmap::new();
10632                if let Some(b) = bm {
10633                    for v in values {
10634                        let lookup = self.index_lookup_key_bytes(*column_id, v);
10635                        acc |= b.get(&lookup);
10636                    }
10637                }
10638                RowIdSet::from_roaring(acc)
10639            }
10640            Condition::BytesPrefix { column_id, prefix } => {
10641                // §5.6: enumerate bitmap keys sharing the prefix for an exact
10642                // prefix match (anchored `LIKE 'prefix%'`), tighter than the
10643                // FM substring superset. The caller only emits this when the
10644                // column has a bitmap index.
10645                if let Some(b) = self.bitmap.get(column_id) {
10646                    let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
10647                    let mut acc = roaring::RoaringBitmap::new();
10648                    for key in b.keys() {
10649                        if key.starts_with(&lookup_prefix) {
10650                            acc |= b.get(&key);
10651                        }
10652                    }
10653                    RowIdSet::from_roaring(acc)
10654                } else {
10655                    RowIdSet::empty()
10656                }
10657            }
10658            Condition::FmContains { column_id, pattern } => self
10659                .fm
10660                .get(column_id)
10661                .map(|f| {
10662                    RowIdSet::from_unsorted(f.locate(pattern).into_iter().map(|r| r.0).collect())
10663                })
10664                .unwrap_or_else(RowIdSet::empty),
10665            Condition::FmContainsAll {
10666                column_id,
10667                patterns,
10668            } => {
10669                // Multi-segment intersection (Priority 12): resolve each segment
10670                // via FM and intersect — much tighter than the single longest.
10671                if let Some(f) = self.fm.get(column_id) {
10672                    let sets: Vec<RowIdSet> = patterns
10673                        .iter()
10674                        .map(|pat| {
10675                            RowIdSet::from_unsorted(
10676                                f.locate(pat).into_iter().map(|r| r.0).collect(),
10677                            )
10678                        })
10679                        .collect();
10680                    RowIdSet::intersect_many(sets)
10681                } else {
10682                    RowIdSet::empty()
10683                }
10684            }
10685            Condition::Ann {
10686                column_id,
10687                query,
10688                k,
10689            } => RowIdSet::from_unsorted(
10690                self.retrieve_filtered(
10691                    &crate::query::Retriever::Ann {
10692                        column_id: *column_id,
10693                        query: query.clone(),
10694                        k: *k,
10695                    },
10696                    snapshot,
10697                    None,
10698                    allowed,
10699                    None,
10700                    None,
10701                )?
10702                .into_iter()
10703                .map(|hit| hit.row_id.0)
10704                .collect(),
10705            ),
10706            Condition::SparseMatch {
10707                column_id,
10708                query,
10709                k,
10710            } => RowIdSet::from_unsorted(
10711                self.retrieve_filtered(
10712                    &crate::query::Retriever::Sparse {
10713                        column_id: *column_id,
10714                        query: query.clone(),
10715                        k: *k,
10716                    },
10717                    snapshot,
10718                    None,
10719                    allowed,
10720                    None,
10721                    None,
10722                )?
10723                .into_iter()
10724                .map(|hit| hit.row_id.0)
10725                .collect(),
10726            ),
10727            Condition::MinHashSimilar {
10728                column_id,
10729                query,
10730                k,
10731            } => match self.minhash.get(column_id) {
10732                Some(index) => {
10733                    let candidates = index.candidate_row_ids(query);
10734                    let eligible =
10735                        self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
10736                    RowIdSet::from_unsorted(
10737                        index
10738                            .search_filtered(query, *k, |row_id| {
10739                                eligible.contains(&row_id)
10740                                    && allowed.is_none_or(|allowed| allowed.contains(&row_id))
10741                            })
10742                            .into_iter()
10743                            .map(|(row_id, _)| row_id.0)
10744                            .collect(),
10745                    )
10746                }
10747                None => RowIdSet::empty(),
10748            },
10749            Condition::Range { column_id, lo, hi } => {
10750                // Build the candidate set from the durable tier — the learned
10751                // index (built from sorted runs) or a single page-pruned run —
10752                // then merge the memtable/mutable-run overlay. An overlay row
10753                // supersedes its run version (it may have been updated out of
10754                // range or deleted), so overlay rids are dropped from the run
10755                // set and re-evaluated from the overlay directly. Without this
10756                // merge, rows still in the memtable are invisible to a ranged
10757                // read whenever a LearnedRange index is present.
10758                //
10759                // Point equality (`lo == hi`) additionally unions the Bitmap
10760                // secondary when one exists on this column. The TypeScript Kit
10761                // always pushes int64 `eq()` as RangeInt (not BitmapEq / Pk),
10762                // so product listing-by-FK would never hit the Bitmap that
10763                // `maintain_bitmap_secondary_on_replace` keeps correct after
10764                // updates. Dual-sourcing Range + Bitmap closes that gap: a
10765                // desynced run/LearnedRange plan can no longer hide a live row
10766                // that still has a correct Bitmap membership (and vice versa
10767                // the overlay merge still covers pure-memtable puts).
10768                let mut set = if let Some(li) = self.learned_range.get(column_id) {
10769                    if self.run_refs.len() == 1 {
10770                        // Single-run: learned_range was built from this run and
10771                        // excludes tombstones, so it's MVCC-correct.
10772                        RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
10773                    } else {
10774                        // Multi-run: learned_range only covers run_refs[0]; a
10775                        // tombstone in a later run wouldn't strip its alive
10776                        // preimage rid from the PGM, and the overlay merge
10777                        // (memtable + mutable_run) is empty after a spill, so a
10778                        // leaked rid would surface as a wrong hit. Fall through
10779                        // to the MVCC-aware multi-run path so deletes land in
10780                        // any run are honored.
10781                        let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10782                        if lo == hi {
10783                            self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10784                        }
10785                        return Ok(multi);
10786                    }
10787                } else if self.run_refs.len() == 1 {
10788                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10789                    r.range_row_id_set_i64(*column_id, *lo, *hi)?
10790                } else {
10791                    // Multi-run / no learned index: full range_scan already
10792                    // merges overlay; union Bitmap for point queries below.
10793                    let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10794                    if lo == hi {
10795                        self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10796                    }
10797                    return Ok(multi);
10798                };
10799                if self.learned_range.get(column_id).is_none() && self.run_refs.len() == 1 {
10800                    let candidates: Vec<RowId> =
10801                        set.into_sorted_vec().into_iter().map(RowId).collect();
10802                    set = RowIdSet::from_unsorted(
10803                        self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?
10804                            .into_iter()
10805                            .map(|row_id| row_id.0)
10806                            .collect(),
10807                    );
10808                }
10809                set.remove_many(self.overlay_rid_set(snapshot));
10810                self.range_scan_overlay_i64(&mut set, *column_id, *lo, *hi, snapshot);
10811                if lo == hi {
10812                    self.union_bitmap_point_i64(&mut set, *column_id, *lo, snapshot);
10813                }
10814                RowIdSet::from_unsorted(
10815                    set.into_sorted_vec()
10816                        .into_iter()
10817                        .filter(|row_id| self.get(RowId(*row_id), snapshot).is_some())
10818                        .collect(),
10819                )
10820            }
10821            Condition::RangeF64 {
10822                column_id,
10823                lo,
10824                lo_inclusive,
10825                hi,
10826                hi_inclusive,
10827            } => {
10828                // See the `Range` arm: merge the overlay over the durable
10829                // candidate set so memtable/mutable-run rows are visible.
10830                let mut set = if let Some(li) = self.learned_range.get(column_id) {
10831                    RowIdSet::from_unsorted(
10832                        li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
10833                            .into_iter()
10834                            .collect(),
10835                    )
10836                } else if self.run_refs.len() == 1 {
10837                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10838                    r.range_row_id_set_f64(*column_id, *lo, *lo_inclusive, *hi, *hi_inclusive)?
10839                } else {
10840                    return self.range_scan_f64(
10841                        *column_id,
10842                        *lo,
10843                        *lo_inclusive,
10844                        *hi,
10845                        *hi_inclusive,
10846                        snapshot,
10847                    );
10848                };
10849                set.remove_many(self.overlay_rid_set(snapshot));
10850                self.range_scan_overlay_f64(
10851                    &mut set,
10852                    *column_id,
10853                    *lo,
10854                    *lo_inclusive,
10855                    *hi,
10856                    *hi_inclusive,
10857                    snapshot,
10858                );
10859                set
10860            }
10861            Condition::IsNull { column_id } => {
10862                let mut set = if self.run_refs.len() == 1 {
10863                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10864                    r.null_row_id_set(*column_id, true)?
10865                } else {
10866                    return self.null_scan(*column_id, true, snapshot);
10867                };
10868                set.remove_many(self.overlay_rid_set(snapshot));
10869                self.null_scan_overlay(&mut set, *column_id, true, snapshot);
10870                set
10871            }
10872            Condition::IsNotNull { column_id } => {
10873                let mut set = if self.run_refs.len() == 1 {
10874                    let mut r = self.open_reader(self.run_refs[0].run_id)?;
10875                    r.null_row_id_set(*column_id, false)?
10876                } else {
10877                    return self.null_scan(*column_id, false, snapshot);
10878                };
10879                set.remove_many(self.overlay_rid_set(snapshot));
10880                self.null_scan_overlay(&mut set, *column_id, false, snapshot);
10881                set
10882            }
10883        })
10884    }
10885
10886    /// Vectorized range scan for Int64 columns (Phase 13.2 / 16.3). Resolves the
10887    /// survivor set via the reader's **page-pruned** path — pages whose `[min,max]`
10888    /// excludes `[lo,hi]` are never decoded — restricted to MVCC-visible rows.
10889    /// This is layout-independent: correct under any memtable / multi-run state,
10890    /// so it is always safe to call (no "single clean run" gate). Overlay rows
10891    /// (memtable / mutable-run) are excluded from the run portion and checked
10892    /// directly via [`Self::range_scan_overlay_i64`].
10893    fn range_scan_i64(
10894        &self,
10895        column_id: u16,
10896        lo: i64,
10897        hi: i64,
10898        snapshot: Snapshot,
10899    ) -> Result<RowIdSet> {
10900        let mut row_ids = Vec::new();
10901        // Collect per-run tombstones whose newest visible version is a
10902        // tombstone: they must strip any alive preimage rid that landed in
10903        // an older run from the survivor set. Without this, a delete-after-
10904        // put whose tombstone lands in a newer run can't override the
10905        // preimage that `range_row_ids_visible_i64` happily returned for the
10906        // older run — the model filters them out, the engine must too.
10907        let mut tomb_rids: HashSet<u64> = HashSet::new();
10908        let overlay_rids = self.overlay_rid_set(snapshot);
10909        for rr in &self.run_refs {
10910            let mut reader = self.open_reader(rr.run_id)?;
10911            let matched = reader.range_row_ids_visible_i64_at(column_id, lo, hi, snapshot)?;
10912            for rid in matched {
10913                if !overlay_rids.contains(&rid) {
10914                    row_ids.push(rid);
10915                }
10916            }
10917            for rid in reader.tombstoned_row_ids_at(snapshot)? {
10918                tomb_rids.insert(rid);
10919            }
10920        }
10921        // Overlay tombstones strip matching run preimages. Collect them
10922        // under the same read-your-writes rule as
10923        // `eligible_candidate_ids`: a snapshot pinned at the current
10924        // visible epoch advances over the in-flight batch; a strictly
10925        // historical pinned snapshot must NOT see pending (uncommitted)
10926        // tombstones.
10927        let overlay_tombstone_snapshot = if self.is_shared()
10928            || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10929            || snapshot.epoch.0 != self.epoch.visible().0
10930        {
10931            snapshot
10932        } else {
10933            Snapshot::at(self.pending_epoch())
10934        };
10935        for row in self
10936            .memtable
10937            .visible_versions_at(overlay_tombstone_snapshot)
10938            .into_iter()
10939            .chain(
10940                self.mutable_run
10941                    .visible_versions_at(overlay_tombstone_snapshot),
10942            )
10943        {
10944            if row.deleted {
10945                tomb_rids.insert(row.row_id.0);
10946            }
10947        }
10948        let mut s = RowIdSet::from_unsorted(row_ids);
10949        s.remove_many(tomb_rids);
10950        let candidates: Vec<RowId> = s.into_sorted_vec().into_iter().map(RowId).collect();
10951        let eligible = self.eligible_candidate_ids(&candidates, column_id, snapshot, None)?;
10952        let mut s = RowIdSet::from_unsorted(eligible.into_iter().map(|row_id| row_id.0).collect());
10953        self.range_scan_overlay_i64(&mut s, column_id, lo, hi, snapshot);
10954        Ok(s)
10955    }
10956
10957    /// Float64 analogue of [`Self::range_scan_i64`] with per-bound inclusivity
10958    /// (Phase 13.2 / 16.3).
10959    fn range_scan_f64(
10960        &self,
10961        column_id: u16,
10962        lo: f64,
10963        lo_inclusive: bool,
10964        hi: f64,
10965        hi_inclusive: bool,
10966        snapshot: Snapshot,
10967    ) -> Result<RowIdSet> {
10968        let mut row_ids = Vec::new();
10969        let overlay_rids = self.overlay_rid_set(snapshot);
10970        for rr in &self.run_refs {
10971            let mut reader = self.open_reader(rr.run_id)?;
10972            let matched = reader.range_row_ids_visible_f64_at(
10973                column_id,
10974                lo,
10975                lo_inclusive,
10976                hi,
10977                hi_inclusive,
10978                snapshot,
10979            )?;
10980            for rid in matched {
10981                if !overlay_rids.contains(&rid) {
10982                    row_ids.push(rid);
10983                }
10984            }
10985        }
10986        let mut s = RowIdSet::from_unsorted(row_ids);
10987        self.range_scan_overlay_f64(
10988            &mut s,
10989            column_id,
10990            lo,
10991            lo_inclusive,
10992            hi,
10993            hi_inclusive,
10994            snapshot,
10995        );
10996        Ok(s)
10997    }
10998
10999    /// Collect the set of row-ids visible in the memtable / mutable-run overlay.
11000    fn overlay_rid_set(&self, snapshot: Snapshot) -> HashSet<u64> {
11001        let mut s = HashSet::new();
11002        for row in self.memtable.visible_versions_at(snapshot) {
11003            s.insert(row.row_id.0);
11004        }
11005        for row in self.mutable_run.visible_versions_at(snapshot) {
11006            s.insert(row.row_id.0);
11007        }
11008        s
11009    }
11010
11011    fn range_scan_overlay_i64(
11012        &self,
11013        s: &mut RowIdSet,
11014        column_id: u16,
11015        lo: i64,
11016        hi: i64,
11017        snapshot: Snapshot,
11018    ) {
11019        // Collapse both overlay tiers to the newest visible version per row id
11020        // (HLC-aware when stamped; P0.5-T3) before range-checking, so a stale
11021        // in-range mutable-run version cannot shadow a newer out-of-range
11022        // memtable version of the same row.
11023        // Both tiers already applied version_is_newer within themselves; when
11024        // both report a rid, prefer the HLC-newer of the two.
11025        let mut newest: HashMap<u64, Row> = HashMap::new();
11026        for r in self.mutable_run.visible_versions_at(snapshot) {
11027            newest.insert(r.row_id.0, r);
11028        }
11029        for r in self.memtable.visible_versions_at(snapshot) {
11030            newest
11031                .entry(r.row_id.0)
11032                .and_modify(|cur| {
11033                    if Snapshot::version_is_newer(
11034                        r.committed_epoch,
11035                        r.commit_ts,
11036                        cur.committed_epoch,
11037                        cur.commit_ts,
11038                    ) {
11039                        *cur = r.clone();
11040                    }
11041                })
11042                .or_insert(r);
11043        }
11044        for row in newest.values() {
11045            if !row.deleted {
11046                if let Some(Value::Int64(v)) = row.columns.get(&column_id) {
11047                    if *v >= lo && *v <= hi && !self.row_expired_at(row, unix_nanos_now()) {
11048                        s.insert(row.row_id.0);
11049                    }
11050                }
11051            }
11052        }
11053    }
11054
11055    #[allow(clippy::too_many_arguments)]
11056    fn range_scan_overlay_f64(
11057        &self,
11058        s: &mut RowIdSet,
11059        column_id: u16,
11060        lo: f64,
11061        lo_inclusive: bool,
11062        hi: f64,
11063        hi_inclusive: bool,
11064        snapshot: Snapshot,
11065    ) {
11066        // See `range_scan_overlay_i64`: dedup to the newest version per row id
11067        // across the memtable + mutable run before range-checking.
11068        let mut newest: HashMap<u64, Row> = HashMap::new();
11069        for r in self.mutable_run.visible_versions_at(snapshot) {
11070            newest.insert(r.row_id.0, r);
11071        }
11072        for r in self.memtable.visible_versions_at(snapshot) {
11073            newest
11074                .entry(r.row_id.0)
11075                .and_modify(|cur| {
11076                    if Snapshot::version_is_newer(
11077                        r.committed_epoch,
11078                        r.commit_ts,
11079                        cur.committed_epoch,
11080                        cur.commit_ts,
11081                    ) {
11082                        *cur = r.clone();
11083                    }
11084                })
11085                .or_insert(r);
11086        }
11087        for row in newest.values() {
11088            if !row.deleted {
11089                if let Some(Value::Float64(v)) = row.columns.get(&column_id) {
11090                    let ok_lo = if lo_inclusive { *v >= lo } else { *v > lo };
11091                    let ok_hi = if hi_inclusive { *v <= hi } else { *v < hi };
11092                    if ok_lo && ok_hi && !self.row_expired_at(row, unix_nanos_now()) {
11093                        s.insert(row.row_id.0);
11094                    }
11095                }
11096            }
11097        }
11098    }
11099
11100    /// Multi-run fallback for `IS NULL` / `IS NOT NULL`. Calls each run's
11101    /// MVCC-aware null scan and merges with the overlay.
11102    fn null_scan(&self, column_id: u16, want_nulls: bool, snapshot: Snapshot) -> Result<RowIdSet> {
11103        let mut row_ids = Vec::new();
11104        let overlay_rids = self.overlay_rid_set(snapshot);
11105        for rr in &self.run_refs {
11106            let mut reader = self.open_reader(rr.run_id)?;
11107            let matched = reader.null_row_ids_visible_at(column_id, want_nulls, snapshot)?;
11108            for rid in matched {
11109                if !overlay_rids.contains(&rid) {
11110                    row_ids.push(rid);
11111                }
11112            }
11113        }
11114        let mut s = RowIdSet::from_unsorted(row_ids);
11115        self.null_scan_overlay(&mut s, column_id, want_nulls, snapshot);
11116        Ok(s)
11117    }
11118
11119    /// Merge overlay rows for `IS NULL` / `IS NOT NULL`. An overlay row
11120    /// supersedes its run version, so overlay rids are removed from the run
11121    /// set and re-evaluated from the overlay values directly.
11122    fn null_scan_overlay(
11123        &self,
11124        s: &mut RowIdSet,
11125        column_id: u16,
11126        want_nulls: bool,
11127        snapshot: Snapshot,
11128    ) {
11129        let mut newest: HashMap<u64, Row> = HashMap::new();
11130        for r in self.mutable_run.visible_versions_at(snapshot) {
11131            newest.insert(r.row_id.0, r);
11132        }
11133        for r in self.memtable.visible_versions_at(snapshot) {
11134            newest
11135                .entry(r.row_id.0)
11136                .and_modify(|cur| {
11137                    if Snapshot::version_is_newer(
11138                        r.committed_epoch,
11139                        r.commit_ts,
11140                        cur.committed_epoch,
11141                        cur.commit_ts,
11142                    ) {
11143                        *cur = r.clone();
11144                    }
11145                })
11146                .or_insert(r);
11147        }
11148        for row in newest.values() {
11149            if row.deleted {
11150                continue;
11151            }
11152            let is_null = !row.columns.contains_key(&column_id)
11153                || matches!(row.columns.get(&column_id), Some(Value::Null) | None);
11154            if is_null == want_nulls {
11155                s.insert(row.row_id.0);
11156            }
11157        }
11158    }
11159
11160    pub fn snapshot(&self) -> Snapshot {
11161        let epoch = self.epoch.visible();
11162        // P0.5: mounted tables pin the shared HLC so HLC-stamped row versions
11163        // remain visible under at_hlc. Standalone private-WAL tables fall back
11164        // to epoch-only (private commits do not stamp HLC today).
11165        match &self.wal {
11166            WalSink::Shared(shared) => match shared.hlc.now() {
11167                Ok(commit_ts) => Snapshot::at_hlc(epoch, commit_ts),
11168                // Clock skew must not hide committed HLC rows from product reads.
11169                Err(_) => Snapshot::at_hlc(epoch, mongreldb_types::hlc::HlcTimestamp::MAX),
11170            },
11171            WalSink::Private(_) | WalSink::ReadOnly => Snapshot::at(epoch),
11172        }
11173    }
11174
11175    /// Generation of this table's row contents for table-local caches.
11176    pub fn data_generation(&self) -> u64 {
11177        self.data_generation
11178    }
11179
11180    pub(crate) fn bump_data_generation(&mut self) {
11181        self.data_generation = self.data_generation.wrapping_add(1);
11182    }
11183
11184    /// Stable catalog table id for this mounted table.
11185    pub fn table_id(&self) -> u64 {
11186        self.table_id
11187    }
11188
11189    /// Seal every active delta (memtable, mutable-run tier, HOT, reverse-PK
11190    /// map, and every secondary index) so the current state can be captured
11191    /// as an immutable generation. Sealing moves the active delta behind the
11192    /// shared frozen `Arc` without copying row data; the writer keeps
11193    /// appending to a fresh, empty active delta (S1C-001).
11194    fn seal_generations(&mut self) {
11195        self.memtable.seal();
11196        self.mutable_run.seal();
11197        self.hot.seal();
11198        for index in self.bitmap.values_mut() {
11199            index.seal();
11200        }
11201        for index in self.ann.values_mut() {
11202            index.seal();
11203        }
11204        for index in self.fm.values_mut() {
11205            index.seal();
11206        }
11207        for index in self.sparse.values_mut() {
11208            index.seal();
11209        }
11210        for index in self.minhash.values_mut() {
11211            index.seal();
11212        }
11213        self.pk_by_row.seal();
11214    }
11215
11216    /// Capture the current (freshly sealed) state as an immutable
11217    /// [`ReadGeneration`]. Cheap by construction: frozen layers are
11218    /// `Arc`-shared, schema/run-refs are small metadata copies, and every
11219    /// active delta is empty post-seal.
11220    fn capture_read_generation(&self) -> ReadGeneration {
11221        let visible_through = self.current_epoch();
11222        ReadGeneration {
11223            schema: Arc::new(self.schema.clone()),
11224            base_runs: Arc::new(self.run_refs.clone()),
11225            deltas: TableDeltas {
11226                memtable: self.memtable.clone(),
11227                mutable_run: self.mutable_run.clone(),
11228                hot: self.hot.clone(),
11229                pk_by_row: self.pk_by_row.clone(),
11230            },
11231            indexes: Arc::new(IndexGeneration::capture(
11232                &self.bitmap,
11233                &self.learned_range,
11234                &self.fm,
11235                &self.ann,
11236                &self.sparse,
11237                &self.minhash,
11238                visible_through,
11239                // P0.5-T5: authoritative HLC readiness watermark.
11240                match &self.wal {
11241                    WalSink::Shared(shared) => shared
11242                        .hlc
11243                        .now()
11244                        .unwrap_or(mongreldb_types::hlc::HlcTimestamp::MAX),
11245                    _ => mongreldb_types::hlc::HlcTimestamp::MAX,
11246                },
11247            )),
11248            visible_through,
11249        }
11250    }
11251
11252    /// Seal the active deltas and atomically publish a replacement
11253    /// [`ReadGeneration`] (S1C-001/S1C-002). The publish is a single
11254    /// `ArcSwap` store: readers that pinned the previous `Arc` keep their
11255    /// stable view, new readers see this one. Returns the published view.
11256    pub fn publish_read_generation(&mut self) -> Result<Arc<ReadGeneration>> {
11257        self.ensure_indexes_complete()?;
11258        self.seal_generations();
11259        let view = Arc::new(self.capture_read_generation());
11260        self.published.store(Arc::clone(&view));
11261        Ok(view)
11262    }
11263
11264    /// The most recently published immutable read view. Pinning the returned
11265    /// `Arc` keeps its structurally-shared frozen layers alive. The view is
11266    /// seeded empty at open/create and refreshed by
11267    /// [`Table::publish_read_generation`], [`Table::flush`], and read-
11268    /// generation creation.
11269    pub fn published_read_generation(&self) -> Arc<ReadGeneration> {
11270        self.published.load_full()
11271    }
11272
11273    /// The table's unified version-retention pin registry (S1C-004).
11274    pub fn pin_registry(&self) -> &Arc<crate::retention::PinRegistry> {
11275        &self.pins
11276    }
11277
11278    /// S1C-004: the epoch floor for version reclamation — a version may be
11279    /// reclaimed only when older than every pin source. Equals
11280    /// [`Table::min_active_snapshot`], or the current visible epoch when
11281    /// nothing is pinned (nothing older than the floor can still be needed).
11282    pub fn version_gc_floor(&self) -> Epoch {
11283        self.min_active_snapshot()
11284            .unwrap_or_else(|| self.current_epoch())
11285    }
11286
11287    /// S1C-004 diagnostics: every active version-retention pin source.
11288    /// Registered pins (read generations, and later backup/PITR, replication,
11289    /// online index builds) come from the [`crate::retention::PinRegistry`];
11290    /// the oldest transaction snapshot (local pins plus the shared
11291    /// [`crate::retention::SnapshotRegistry`]) and the configured history
11292    /// window are projected into the report so all six sources are visible.
11293    pub fn version_pins_report(&self) -> crate::retention::PinsReport {
11294        let mut report = self.pins.report();
11295        let transaction_floor = [
11296            self.pinned.keys().next().copied(),
11297            self.snapshots.min_pinned(),
11298        ]
11299        .into_iter()
11300        .flatten()
11301        .min();
11302        if let Some(epoch) = transaction_floor {
11303            report.record_projection(crate::retention::PinSource::TransactionSnapshot, epoch);
11304        }
11305        if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11306            report.record_projection(crate::retention::PinSource::HistoryRetention, floor);
11307        }
11308        report
11309    }
11310
11311    pub(crate) fn clone_read_generation(&mut self) -> Result<Self> {
11312        self.publish_read_generation()?;
11313        let mut generation = self.clone();
11314        generation.read_only = true;
11315        generation.wal = WalSink::ReadOnly;
11316        generation.pending_delete_rids.clear();
11317        generation.pending_put_cols.clear();
11318        generation.pending_rows.clear();
11319        generation.pending_rows_auto_inc.clear();
11320        generation.pending_dels.clear();
11321        generation.pending_truncate = None;
11322        generation.agg_cache = Arc::new(HashMap::new());
11323        // The pinned generation keeps the view published at its birth, not
11324        // the writer's live cell: later publishes must not mutate it.
11325        generation.published = Arc::new(ArcSwap::new(self.published.load_full()));
11326        // S1C-004: the generation pins its birth epoch until it drops, so
11327        // version GC can never reclaim versions it still reads.
11328        generation.read_generation_pin = Some(Arc::new(self.pins.pin(
11329            crate::retention::PinSource::ReadGeneration,
11330            self.current_epoch(),
11331        )));
11332        Ok(generation)
11333    }
11334
11335    pub(crate) fn estimated_clone_bytes(&self) -> u64 {
11336        (std::mem::size_of::<Self>() as u64)
11337            .saturating_add(self.memtable.approx_bytes())
11338            .saturating_add(self.mutable_run.approx_bytes())
11339            .saturating_add(self.live_count.saturating_mul(64))
11340    }
11341
11342    /// Pin the current read snapshot; compaction will preserve the versions it
11343    /// needs until [`Table::unpin_snapshot`] is called.
11344    ///
11345    /// Mounted (shared-WAL) tables pin HLC via [`Snapshot::at_hlc`] so HLC is
11346    /// the cluster-wide authority. Standalone private-WAL tables remain
11347    /// epoch-only until they stamp HLC on commit.
11348    pub fn pin_snapshot(&mut self) -> Snapshot {
11349        let snap = self.snapshot();
11350        *self.pinned.entry(snap.epoch).or_insert(0) += 1;
11351        snap
11352    }
11353
11354    /// Every epoch that pin-aware index rebuild must restore secondary
11355    /// discovery / retrieval for — the full set of reader/retention pins that
11356    /// [`Self::min_active_snapshot`] folds into compaction GC, not just the
11357    /// oldest and not just the standalone `pin_snapshot` map.
11358    ///
11359    /// Sources (union, ascending, deduped):
11360    /// - local `self.pinned` ([`Self::pin_snapshot`])
11361    /// - [`crate::retention::SnapshotRegistry`] live pins (`Database::snapshot`)
11362    /// - [`crate::retention::PinRegistry`] live pins (backup/PITR, replication,
11363    ///   read-generation, online-index-build, …)
11364    /// - history-retention floor when configured
11365    fn active_pin_epochs_for_rebuild(&self) -> Vec<Epoch> {
11366        let mut set = BTreeSet::new();
11367        for epoch in self.pinned.keys().copied() {
11368            set.insert(epoch);
11369        }
11370        for epoch in self.snapshots.live_pinned_epochs() {
11371            set.insert(epoch);
11372        }
11373        for epoch in self.pins.live_pin_epochs() {
11374            set.insert(epoch);
11375        }
11376        if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11377            set.insert(floor);
11378        }
11379        set.into_iter().collect()
11380    }
11381
11382    /// P0.5-T6: report the HLC GC floor as named pin sources.
11383    ///
11384    /// Epoch pins that cannot yet be projected to a durable HLC report
11385    /// [`HlcTimestamp::ZERO`](mongreldb_types::hlc::HlcTimestamp::ZERO). Physical
11386    /// reclamation still consults the epoch floor ([`Self::version_gc_floor`]).
11387    ///
11388    /// `project_epoch` maps a local pin epoch to an HLC (typically
11389    /// [`crate::Database::commit_ts_for_epoch`]); return `None` / `ZERO` when
11390    /// the epoch has no durable stamp.
11391    pub fn hlc_gc_floor(
11392        &self,
11393        mut project_epoch: impl FnMut(Epoch) -> Option<mongreldb_types::hlc::HlcTimestamp>,
11394    ) -> crate::epoch::GcFloor {
11395        let mut project = |epoch: Option<Epoch>| -> mongreldb_types::hlc::HlcTimestamp {
11396            epoch
11397                .and_then(&mut project_epoch)
11398                .filter(|ts| *ts != mongreldb_types::hlc::HlcTimestamp::ZERO)
11399                .unwrap_or(mongreldb_types::hlc::HlcTimestamp::ZERO)
11400        };
11401        let transaction = [
11402            self.pinned.keys().next().copied(),
11403            self.snapshots.min_pinned(),
11404        ]
11405        .into_iter()
11406        .flatten()
11407        .min();
11408        let history = self.snapshots.history_floor(self.current_epoch());
11409        crate::epoch::GcFloor {
11410            transaction_snapshot: project(transaction),
11411            history_retention: project(history),
11412            backup_pitr: project(
11413                self.pins
11414                    .oldest_for(crate::retention::PinSource::BackupPitr),
11415            ),
11416            replication: project(
11417                self.pins
11418                    .oldest_for(crate::retention::PinSource::Replication),
11419            ),
11420            read_generation: project(
11421                self.pins
11422                    .oldest_for(crate::retention::PinSource::ReadGeneration),
11423            ),
11424            online_index_build: project(
11425                self.pins
11426                    .oldest_for(crate::retention::PinSource::OnlineIndexBuild),
11427            ),
11428        }
11429    }
11430
11431    /// Release a pinned snapshot.
11432    pub fn unpin_snapshot(&mut self, snap: Snapshot) {
11433        if let Some(count) = self.pinned.get_mut(&snap.epoch) {
11434            *count -= 1;
11435            if *count == 0 {
11436                self.pinned.remove(&snap.epoch);
11437            }
11438        }
11439    }
11440
11441    /// Oldest pinned snapshot epoch, or `None` if no snapshot is active.
11442    /// Lowest snapshot epoch that compaction must preserve a version for, or
11443    /// `None` when no reader is pinned anywhere. Considers BOTH the single-table
11444    /// local pin set (`self.pinned`, used by the standalone `pin_snapshot` API)
11445    /// AND the shared `Database` snapshot registry (`db.snapshot()` readers) —
11446    /// otherwise a multi-table reader's version could be dropped by a compaction
11447    /// triggered on its table (the registry-gated reaper would then keep the
11448    /// old run *files*, but readers only scan the merged run, so the version
11449    /// would still be lost). Also folds in the unified [`crate::retention::PinRegistry`]
11450    /// (S1C-004): backup/PITR, replication, cursor/read-generation, and
11451    /// online-index-build pins all gate version reclamation here.
11452    pub(crate) fn min_active_snapshot(&self) -> Option<Epoch> {
11453        let local = self.pinned.keys().next().copied();
11454        let global = self.snapshots.min_pinned();
11455        let history = self.snapshots.history_floor(self.current_epoch());
11456        let pinned = self.pins.oldest_pinned();
11457        [local, global, history, pinned].into_iter().flatten().min()
11458    }
11459
11460    /// Configure timestamp-column retention on a standalone table. Mounted
11461    /// databases should use [`crate::Database::set_table_ttl`] so the DDL is
11462    /// WAL-replicated.
11463    pub fn set_ttl(&mut self, column_name: &str, duration_nanos: u64) -> Result<()> {
11464        self.ensure_writable()?;
11465        let policy = self.prepare_ttl_policy(column_name, duration_nanos)?;
11466        self.apply_ttl_policy_at(Some(policy), self.current_epoch())
11467    }
11468
11469    pub fn clear_ttl(&mut self) -> Result<()> {
11470        self.ensure_writable()?;
11471        self.apply_ttl_policy_at(None, self.current_epoch())
11472    }
11473
11474    pub fn ttl(&self) -> Option<TtlPolicy> {
11475        self.ttl
11476    }
11477
11478    pub(crate) fn prepare_ttl_policy(
11479        &self,
11480        column_name: &str,
11481        duration_nanos: u64,
11482    ) -> Result<TtlPolicy> {
11483        if duration_nanos == 0 || duration_nanos > i64::MAX as u64 {
11484            return Err(MongrelError::InvalidArgument(
11485                "TTL duration must be between 1 and i64::MAX nanoseconds".into(),
11486            ));
11487        }
11488        let column = self
11489            .schema
11490            .columns
11491            .iter()
11492            .find(|column| column.name == column_name)
11493            .ok_or_else(|| MongrelError::Schema(format!("unknown TTL column {column_name}")))?;
11494        if column.ty != TypeId::TimestampNanos {
11495            return Err(MongrelError::Schema(format!(
11496                "TTL column {column_name} must be TimestampNanos, is {:?}",
11497                column.ty
11498            )));
11499        }
11500        Ok(TtlPolicy {
11501            column_id: column.id,
11502            duration_nanos,
11503        })
11504    }
11505
11506    pub(crate) fn apply_ttl_policy_at(
11507        &mut self,
11508        policy: Option<TtlPolicy>,
11509        epoch: Epoch,
11510    ) -> Result<()> {
11511        if let Some(policy) = policy {
11512            let column = self
11513                .schema
11514                .columns
11515                .iter()
11516                .find(|column| column.id == policy.column_id)
11517                .ok_or_else(|| {
11518                    MongrelError::Schema(format!("unknown TTL column id {}", policy.column_id))
11519                })?;
11520            if column.ty != TypeId::TimestampNanos
11521                || policy.duration_nanos == 0
11522                || policy.duration_nanos > i64::MAX as u64
11523            {
11524                return Err(MongrelError::Schema("invalid TTL policy".into()));
11525            }
11526        }
11527        self.ttl = policy;
11528        self.agg_cache = Arc::new(HashMap::new());
11529        self.clear_result_cache();
11530        let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
11531        self.persist_manifest(epoch)
11532    }
11533
11534    pub(crate) fn row_expired_at(&self, row: &Row, now_nanos: i64) -> bool {
11535        let Some(policy) = self.ttl else {
11536            return false;
11537        };
11538        let Some(Value::Int64(timestamp)) = row.columns.get(&policy.column_id) else {
11539            return false;
11540        };
11541        timestamp.saturating_add(policy.duration_nanos as i64) <= now_nanos
11542    }
11543
11544    pub fn current_epoch(&self) -> Epoch {
11545        self.epoch.visible()
11546    }
11547
11548    pub fn memtable_len(&self) -> usize {
11549        self.memtable.len()
11550    }
11551
11552    /// Live row count. O(1) without TTL; TTL tables scan because wall-clock
11553    /// expiry can change without a commit epoch.
11554    pub fn count(&self) -> u64 {
11555        if self.ttl.is_none()
11556            && self.pending_put_cols.is_empty()
11557            && self.pending_delete_rids.is_empty()
11558            && self.pending_rows.is_empty()
11559            && self.pending_dels.is_empty()
11560            && self.pending_truncate.is_none()
11561        {
11562            self.live_count
11563        } else {
11564            self.visible_rows(self.snapshot())
11565                .map(|rows| rows.len() as u64)
11566                .unwrap_or(self.live_count)
11567        }
11568    }
11569
11570    /// Count rows matching an index-backed conjunctive predicate without
11571    /// materializing projected columns. Returns `None` when a condition cannot
11572    /// be served by the native predicate resolver.
11573    pub fn count_conditions(
11574        &mut self,
11575        conditions: &[crate::query::Condition],
11576        snapshot: Snapshot,
11577    ) -> Result<Option<u64>> {
11578        use crate::query::Condition;
11579        if self.ttl.is_some() {
11580            if conditions.is_empty() {
11581                return Ok(Some(self.visible_rows(snapshot)?.len() as u64));
11582            }
11583            let mut sets = Vec::with_capacity(conditions.len());
11584            for condition in conditions {
11585                sets.push(self.resolve_condition(condition, snapshot)?);
11586            }
11587            let survivors = RowIdSet::intersect_many(sets);
11588            let rows = self.visible_rows(snapshot)?;
11589            return Ok(Some(
11590                rows.into_iter()
11591                    .filter(|row| survivors.contains(row.row_id.0))
11592                    .count() as u64,
11593            ));
11594        }
11595        if conditions.is_empty() {
11596            return Ok(Some(self.count()));
11597        }
11598        let served = |c: &Condition| {
11599            matches!(
11600                c,
11601                Condition::Pk(_)
11602                    | Condition::BitmapEq { .. }
11603                    | Condition::BitmapIn { .. }
11604                    | Condition::BytesPrefix { .. }
11605                    | Condition::FmContains { .. }
11606                    | Condition::FmContainsAll { .. }
11607                    | Condition::Ann { .. }
11608                    | Condition::Range { .. }
11609                    | Condition::RangeF64 { .. }
11610                    | Condition::SparseMatch { .. }
11611                    | Condition::MinHashSimilar { .. }
11612                    | Condition::IsNull { .. }
11613                    | Condition::IsNotNull { .. }
11614            )
11615        };
11616        if !conditions.iter().all(served) {
11617            return Ok(None);
11618        }
11619        self.ensure_indexes_complete()?;
11620        if !self.pending_put_cols.is_empty()
11621            || !self.pending_delete_rids.is_empty()
11622            || !self.pending_rows.is_empty()
11623            || !self.pending_dels.is_empty()
11624            || self.pending_truncate.is_some()
11625        {
11626            let mut sets = Vec::with_capacity(conditions.len());
11627            for condition in conditions {
11628                sets.push(self.resolve_condition(condition, snapshot)?);
11629            }
11630            let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
11631            return Ok(Some(self.rows_for_rids(&rids, snapshot)?.len() as u64));
11632        }
11633        let mut sets = Vec::with_capacity(conditions.len());
11634        for condition in conditions {
11635            sets.push(self.resolve_condition(condition, snapshot)?);
11636        }
11637        let rids = RowIdSet::intersect_many(sets);
11638        // §5.1: secondary indexes are append-only across pure deletes, so
11639        // tombstoned rids linger under equality keys until a pin-aware rebuild
11640        // / compaction. Materialize paths already filter via MVCC. The count
11641        // path must not trust raw index cardinality whenever deletes have ever
11642        // happened (including after flush/spill emptied the overlay and after
11643        // reopen of a checkpoint that still carries stale memberships).
11644        // `had_deletes` is reconstructed on open from run_count vs live_count.
11645        if self.had_deletes || !self.memtable.is_empty() || !self.mutable_run.is_empty() {
11646            let sorted = rids.into_sorted_vec();
11647            let count = self.rows_for_rids(&sorted, snapshot)?.len() as u64;
11648            crate::trace::QueryTrace::record(|t| {
11649                t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11650                t.survivor_count = Some(count as usize);
11651                t.conditions_pushed = conditions.len();
11652            });
11653            return Ok(Some(count));
11654        }
11655        let count = rids.len() as u64;
11656        crate::trace::QueryTrace::record(|t| {
11657            t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11658            t.survivor_count = Some(count as usize);
11659            t.conditions_pushed = conditions.len();
11660        });
11661        Ok(Some(count))
11662    }
11663
11664    /// Row-ids whose newest visible overlay version is a tombstone. Used to
11665    /// prune stale entries left behind by the append-only in-memory indexes
11666    /// (see point dual-source / overlay merge). Tombstones may also live in
11667    /// sorted runs after flush; callers that need full correctness use
11668    /// materialize (`rows_for_rids`) instead of this overlay-only set. (§5.1)
11669    fn overlay_tombstoned_rids(&self, snapshot: Snapshot) -> Vec<u64> {
11670        let mut out = Vec::new();
11671        for row in self.memtable.visible_versions_at(snapshot) {
11672            if row.deleted {
11673                out.push(row.row_id.0);
11674            }
11675        }
11676        for row in self.mutable_run.visible_versions_at(snapshot) {
11677            if row.deleted {
11678                out.push(row.row_id.0);
11679            }
11680        }
11681        out
11682    }
11683
11684    /// Bulk-load typed columns straight to a new run — the fast ingest path.
11685    /// Bypasses the WAL, the memtable, and the `Value` enum entirely; writes one
11686    /// compressed run (delta for sorted Int64, dictionary for low-card Bytes)
11687    /// with **LZ4** (Phase 15.3 — fast decode for scan-heavy analytical runs),
11688    /// rotates the WAL, and persists the manifest in a single fsync group.
11689    /// Index building follows [`Table::index_build_policy`]: deferred to the
11690    /// first query/flush by default, or bulk-built inline from the typed
11691    /// columns (Phase 14.2) under [`IndexBuildPolicy::Eager`].
11692    pub fn bulk_load_columns(
11693        &mut self,
11694        user_columns: Vec<(u16, columnar::NativeColumn)>,
11695    ) -> Result<Epoch> {
11696        self.bulk_load_columns_with(user_columns, 3, false, true)
11697    }
11698
11699    /// Maximal-throughput bulk ingest (Phase 14.4): skip zstd entirely and write
11700    /// raw `ALGO_PLAIN` pages. ~3–4× the encode throughput of
11701    /// [`Self::bulk_load_columns`] at ~3–4× the on-disk size — the right choice
11702    /// when ingest latency dominates and a background compaction will re-compress
11703    /// later. Indexing, WAL rotation, and the manifest are identical to
11704    /// [`Self::bulk_load_columns`].
11705    pub fn bulk_load_fast(
11706        &mut self,
11707        user_columns: Vec<(u16, columnar::NativeColumn)>,
11708    ) -> Result<Epoch> {
11709        self.bulk_load_columns_with(user_columns, -1, true, false)
11710    }
11711
11712    fn bulk_load_columns_with(
11713        &mut self,
11714        mut user_columns: Vec<(u16, columnar::NativeColumn)>,
11715        zstd_level: i32,
11716        force_plain: bool,
11717        lz4: bool,
11718    ) -> Result<Epoch> {
11719        self.ensure_writable()?;
11720        let n = user_columns.first().map(|(_, c)| c.len()).unwrap_or(0);
11721        if n == 0 {
11722            return Ok(self.current_epoch());
11723        }
11724        let epoch = self.commit_new_epoch()?;
11725        let live_before = self.live_count;
11726        // Spill pending mutable-run data before the Flush marker + WAL rotation.
11727        self.spill_mutable_run(epoch)?;
11728        let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
11729            && self.indexes_complete
11730            && self.run_refs.is_empty()
11731            && self.memtable.is_empty()
11732            && self.mutable_run.is_empty();
11733        // Enforce NOT NULL constraints and primary-key upsert semantics before
11734        // any row id is allocated or bytes hit the run file.
11735        self.fill_auto_inc_native_columns(&mut user_columns, n)?;
11736        self.validate_columns_not_null(&user_columns, n)?;
11737        let winner_idx = self
11738            .bulk_pk_winner_indices(&user_columns, n)
11739            .filter(|idx| idx.len() != n);
11740        let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
11741            match winner_idx.as_deref() {
11742                Some(idx) => {
11743                    let compacted = user_columns
11744                        .iter()
11745                        .map(|(id, c)| (*id, c.gather(idx)))
11746                        .collect();
11747                    (compacted, idx.len())
11748                }
11749                None => (user_columns, n),
11750            };
11751        self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
11752        let first = self.allocator.alloc_range(write_n as u64)?.0;
11753        for rid in first..first + write_n as u64 {
11754            self.reservoir.offer(rid);
11755        }
11756        let run_id = self.alloc_run_id()?;
11757        let path = self.run_path(run_id);
11758        let mut writer =
11759            RunWriter::new(&self.schema, run_id as u128, epoch, 0).with_native_endian();
11760        if force_plain {
11761            writer = writer.with_plain();
11762        } else if lz4 {
11763            // Phase 15.3: bulk-loaded analytical runs are scan-heavy, so encode
11764            // them with LZ4 (3–5× faster decode, ~10% worse ratio than zstd).
11765            writer = writer.with_lz4();
11766        } else {
11767            writer = writer.with_zstd_level(zstd_level);
11768        }
11769        if let Some(kek) = &self.kek {
11770            writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
11771        }
11772        let header = match self.create_run_file(run_id)? {
11773            Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
11774            None => writer.write_native(&path, &write_columns, write_n, first)?,
11775        };
11776        self.run_refs.push(RunRef {
11777            run_id: run_id as u128,
11778            level: 0,
11779            epoch_created: epoch.0,
11780            row_count: header.row_count,
11781        });
11782        self.refresh_active_run_fingerprint();
11783        self.run_row_id_ranges
11784            .insert(run_id as u128, (header.min_row_id, header.max_row_id));
11785        self.live_count = self.live_count.saturating_add(write_n as u64);
11786        if eager_index_build {
11787            let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
11788            self.index_columns_bulk(&write_columns, &row_ids);
11789            self.indexes_complete = true;
11790            self.build_learned_ranges()?;
11791        } else {
11792            // Phase 14.7: defer index building off the ingest critical path for
11793            // non-empty tables where cross-run PK/update semantics must be
11794            // reconstructed from durable state.
11795            self.indexes_complete = false;
11796        }
11797        self.mark_flushed(epoch)?;
11798        self.persist_manifest(epoch)?;
11799        if eager_index_build {
11800            self.checkpoint_indexes(epoch);
11801        }
11802        self.clear_result_cache();
11803        self.data_generation = self.data_generation.wrapping_add(1);
11804        Ok(epoch)
11805    }
11806
11807    /// Bulk-build the live in-memory indexes (HOT/bitmap/FM/sparse) straight
11808    /// from typed columns — the deferred batch-indexing path (Phase 14.2).
11809    ///
11810    /// Replaces the per-row `index_into` loop: no `Row`, no per-row
11811    /// `HashMap<u16, Value>`, no `Value` enum. Index keys are computed directly
11812    /// from the typed buffers via [`columnar::encode_key_native`], tokenized for
11813    /// `ENCRYPTED_INDEXABLE` columns the same way `index_into` on a tokenized
11814    /// row would. FM is appended dirty and rebuilt once on the next query; the
11815    /// others are populated in a single typed pass. Entries are merged into the
11816    /// existing indexes so this is correct under multi-run loads and partial
11817    /// reindexes.
11818    ///
11819    /// `row_ids[i]` is the `RowId` of element `i` of every column. ANN
11820    /// (`IndexKind::Ann`) is intentionally skipped: the native codec carries no
11821    /// embeddings, so an `Embedding` column can never reach this path (a native
11822    /// bulk load of an embedding schema fails at encode). LearnedRange is built
11823    /// separately from the runs by [`Self::build_learned_ranges`].
11824    fn index_columns_bulk(&mut self, columns: &[(u16, columnar::NativeColumn)], row_ids: &[u64]) {
11825        let n = row_ids.len();
11826        if n == 0 {
11827            return;
11828        }
11829        let by_id: std::collections::HashMap<u16, &columnar::NativeColumn> =
11830            columns.iter().map(|(id, c)| (*id, c)).collect();
11831        let ty_of: std::collections::HashMap<u16, TypeId> = self
11832            .schema
11833            .columns
11834            .iter()
11835            .map(|c| (c.id, c.ty.clone()))
11836            .collect();
11837        let pk_id = self.schema.primary_key().map(|c| c.id);
11838
11839        for (i, &rid) in row_ids.iter().enumerate() {
11840            let row_id = RowId(rid);
11841            if let Some(pid) = pk_id {
11842                if let Some(col) = by_id.get(&pid) {
11843                    let ty = ty_of.get(&pid).cloned().unwrap_or(TypeId::Int64);
11844                    if let Some(key) = bulk_index_key(&self.column_keys, pid, ty, col, i) {
11845                        self.insert_hot_pk(key, row_id);
11846                    }
11847                }
11848            }
11849            for idef in &self.schema.indexes {
11850                let Some(col) = by_id.get(&idef.column_id) else {
11851                    continue;
11852                };
11853                let ty = ty_of.get(&idef.column_id).cloned().unwrap_or(TypeId::Int64);
11854                match idef.kind {
11855                    IndexKind::Bitmap => {
11856                        if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
11857                            if let Some(key) =
11858                                bulk_index_key(&self.column_keys, idef.column_id, ty, col, i)
11859                            {
11860                                b.insert(key, row_id);
11861                            }
11862                        }
11863                    }
11864                    IndexKind::FmIndex => {
11865                        if let Some(f) = self.fm.get_mut(&idef.column_id) {
11866                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11867                                f.insert(bytes.to_vec(), row_id);
11868                            }
11869                        }
11870                    }
11871                    IndexKind::Sparse => {
11872                        if let Some(s) = self.sparse.get_mut(&idef.column_id) {
11873                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11874                                if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(bytes) {
11875                                    s.insert(&terms, row_id);
11876                                }
11877                            }
11878                        }
11879                    }
11880                    IndexKind::MinHash => {
11881                        if let Some(mh) = self.minhash.get_mut(&idef.column_id) {
11882                            if let Some(bytes) = columnar::native_bytes_at(col, i) {
11883                                let tokens = crate::index::token_hashes_from_bytes(bytes);
11884                                mh.insert(&tokens, row_id);
11885                            }
11886                        }
11887                    }
11888                    _ => {}
11889                }
11890            }
11891        }
11892    }
11893
11894    /// no `Value`). Fast path: empty memtable + single run decodes columns
11895    /// directly and gathers visible indices; falls back to the `Value` path
11896    /// pivoted to native columns otherwise. `projection` (a set of column ids)
11897    /// limits decoding to the requested columns — `None` ⇒ all user columns.
11898    pub fn visible_columns_native(
11899        &self,
11900        snapshot: Snapshot,
11901        projection: Option<&[u16]>,
11902    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11903        self.visible_columns_native_inner(snapshot, projection, None)
11904    }
11905
11906    pub fn visible_columns_native_with_control(
11907        &self,
11908        snapshot: Snapshot,
11909        projection: Option<&[u16]>,
11910        control: &crate::ExecutionControl,
11911    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11912        self.visible_columns_native_inner(snapshot, projection, Some(control))
11913    }
11914
11915    fn visible_columns_native_inner(
11916        &self,
11917        snapshot: Snapshot,
11918        projection: Option<&[u16]>,
11919        control: Option<&crate::ExecutionControl>,
11920    ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11921        execution_checkpoint(control, 0)?;
11922        let wanted: Vec<u16> = match projection {
11923            Some(p) => p.to_vec(),
11924            None => self.schema.columns.iter().map(|c| c.id).collect(),
11925        };
11926        if self.ttl.is_none()
11927            && self.memtable.is_empty()
11928            && self.mutable_run.is_empty()
11929            && self.run_refs.len() == 1
11930        {
11931            let rr = self.run_refs[0].clone();
11932            let mut reader = self.open_reader(rr.run_id)?;
11933            let idxs = reader.visible_indices_native_at(snapshot)?;
11934            execution_checkpoint(control, 0)?;
11935            let all_visible = idxs.len() == reader.row_count();
11936            // Phase 15.1: decode every requested column in parallel when the
11937            // reader is mmap-backed. Each column already parallel-decodes its
11938            // own pages, so a wide table saturates the pool via nested rayon
11939            // without oversubscribing (work-stealing handles it). Falls back to
11940            // the sequential `&mut` path when mmap is unavailable.
11941            if reader.has_mmap() && control.is_none() {
11942                use rayon::prelude::*;
11943                // Pre-resolve the requested ids that exist in the schema (don't
11944                // capture `self` inside the rayon closure).
11945                let valid: Vec<u16> = wanted
11946                    .iter()
11947                    .filter(|cid| self.schema.columns.iter().any(|c| c.id == **cid))
11948                    .copied()
11949                    .collect();
11950                // Decode concurrently; `collect` preserves `valid` order.
11951                let decoded: Vec<(u16, columnar::NativeColumn)> = valid
11952                    .par_iter()
11953                    .filter_map(|cid| {
11954                        reader
11955                            .column_native_shared(*cid)
11956                            .ok()
11957                            .map(|col| (*cid, col))
11958                    })
11959                    .collect();
11960                let cols = decoded
11961                    .into_iter()
11962                    .map(|(id, col)| (id, if all_visible { col } else { col.gather(&idxs) }))
11963                    .collect();
11964                return Ok(cols);
11965            }
11966            let mut cols = Vec::with_capacity(wanted.len());
11967            for (index, cid) in wanted.iter().enumerate() {
11968                execution_checkpoint(control, index)?;
11969                let cdef = match self.schema.columns.iter().find(|c| c.id == *cid) {
11970                    Some(c) => c,
11971                    None => continue,
11972                };
11973                let col = reader.column_native(cdef.id)?;
11974                cols.push((cdef.id, if all_visible { col } else { col.gather(&idxs) }));
11975            }
11976            return Ok(cols);
11977        }
11978        let vcols = self.visible_columns(snapshot)?;
11979        execution_checkpoint(control, 0)?;
11980        let want_set: std::collections::HashSet<u16> = wanted.iter().copied().collect();
11981        let out: Vec<(u16, columnar::NativeColumn)> = vcols
11982            .into_iter()
11983            .filter(|(id, _)| want_set.contains(id))
11984            .map(|(id, vals)| {
11985                let ty = self
11986                    .schema
11987                    .columns
11988                    .iter()
11989                    .find(|c| c.id == id)
11990                    .map(|c| c.ty.clone())
11991                    .unwrap_or(TypeId::Bytes);
11992                (id, columnar::values_to_native(ty, &vals))
11993            })
11994            .collect();
11995        Ok(out)
11996    }
11997
11998    pub fn run_count(&self) -> usize {
11999        self.run_refs.len()
12000    }
12001
12002    /// Whether the memtable is empty (no unflushed puts).
12003    pub fn memtable_is_empty(&self) -> bool {
12004        self.memtable.is_empty()
12005    }
12006
12007    /// Cumulative raw-page-cache hit/miss counts (Priority 14: hit visibility).
12008    /// Useful for confirming a repeat scan is served from cache or measuring a
12009    /// query's locality after [`reset_page_cache_stats`](Self::reset_page_cache_stats).
12010    pub fn page_cache_stats(&self) -> crate::cache::CacheStats {
12011        self.page_cache.stats()
12012    }
12013
12014    /// Zero the raw-page-cache hit/miss counters.
12015    pub fn reset_page_cache_stats(&self) {
12016        self.page_cache.reset_stats();
12017    }
12018
12019    /// The run IDs in level order (Phase 15.5: used by the Arrow IPC shadow to
12020    /// key shadow files and detect stale shadows).
12021    pub fn run_ids(&self) -> Vec<u128> {
12022        self.run_refs.iter().map(|r| r.run_id).collect()
12023    }
12024
12025    /// Whether the single run (if exactly one) is clean — i.e. has
12026    /// `RUN_FLAG_CLEAN` set (Phase 15.5: the shadow is zero-copy only for clean
12027    /// runs).
12028    pub fn single_run_is_clean(&self) -> bool {
12029        if self.ttl.is_some() || self.run_refs.len() != 1 {
12030            return false;
12031        }
12032        self.open_reader(self.run_refs[0].run_id)
12033            .map(|r| r.is_clean())
12034            .unwrap_or(false)
12035    }
12036
12037    /// Best-effort resolve of the survivor RowId set for fine-grained cache
12038    /// invalidation (hardening (c)). On the single-run fast path, opens a reader
12039    /// and calls `resolve_survivor_rids`. On the multi-run/memtable path,
12040    /// returns an empty bitmap — conservative (condition_cols still catches
12041    /// column mutations, and deletes are caught by the epoch-free design falling
12042    /// through to the multi-run path which re-resolves).
12043    fn resolve_footprint(
12044        &self,
12045        conditions: &[crate::query::Condition],
12046        snapshot: Snapshot,
12047    ) -> roaring::RoaringBitmap {
12048        if !self.memtable.is_empty() || !self.mutable_run.is_empty() {
12049            return roaring::RoaringBitmap::new();
12050        }
12051        if self.run_refs.is_empty() {
12052            return roaring::RoaringBitmap::new();
12053        }
12054        // Try the single-run fast path.
12055        if self.run_refs.len() == 1 {
12056            if let Ok(mut reader) = self.open_reader(self.run_refs[0].run_id) {
12057                if let Ok(rids) = self.resolve_survivor_rids(conditions, &mut reader, snapshot) {
12058                    return rids.to_roaring_lossy();
12059                }
12060            }
12061        }
12062        roaring::RoaringBitmap::new()
12063    }
12064
12065    /// Phase 19.1 + hardening (c): a cached form of
12066    /// [`Table::query_columns_native`]. The cache key embeds the snapshot epoch
12067    /// so two queries at different pinned snapshots never share an entry;
12068    /// invalidation is fine-grained — a `commit()` drops only entries whose
12069    /// footprint intersects a deleted RowId or whose condition-columns intersect
12070    /// a mutated column. On a miss the underlying `query_columns_native` runs and
12071    /// the result is cached as typed `NativeColumn`s. Returns `None` exactly when
12072    /// the non-cached path would (conditions not pushdown-served). Strictly
12073    /// additive — callers wanting fresh results keep using
12074    /// `query_columns_native`.
12075    pub fn query_columns_native_cached(
12076        &mut self,
12077        conditions: &[crate::query::Condition],
12078        projection: Option<&[u16]>,
12079        snapshot: Snapshot,
12080    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12081        self.query_columns_native_cached_inner(conditions, projection, snapshot, None)
12082    }
12083
12084    pub fn query_columns_native_cached_with_control(
12085        &mut self,
12086        conditions: &[crate::query::Condition],
12087        projection: Option<&[u16]>,
12088        snapshot: Snapshot,
12089        control: &crate::ExecutionControl,
12090    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12091        self.query_columns_native_cached_inner(conditions, projection, snapshot, Some(control))
12092    }
12093
12094    fn query_columns_native_cached_inner(
12095        &mut self,
12096        conditions: &[crate::query::Condition],
12097        projection: Option<&[u16]>,
12098        snapshot: Snapshot,
12099        control: Option<&crate::ExecutionControl>,
12100    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12101        execution_checkpoint(control, 0)?;
12102        // Wall-clock expiry changes without an MVCC epoch, so an epoch-keyed
12103        // result can become stale while sitting in the cache.
12104        if self.ttl.is_some() {
12105            return self.query_columns_native_inner(conditions, projection, snapshot, control);
12106        }
12107        if conditions.is_empty() {
12108            return self.query_columns_native_inner(conditions, projection, snapshot, control);
12109        }
12110        // The snapshot epoch is part of the key so two queries with identical
12111        // conditions/projection but pinned at different snapshots never share a
12112        // cached result (MVCC isolation for the explicit-snapshot API).
12113        let key = crate::query::canonical_query_key(conditions, projection, snapshot.epoch.0);
12114        let identity = PersistentCacheIdentity {
12115            table_id: self.table_id(),
12116            schema_id: self.schema.schema_id,
12117            logical_generation: self.current_epoch().0,
12118        };
12119        if let Some(hit) = self.result_cache.lock().get_columns(key, identity) {
12120            crate::trace::QueryTrace::record(|t| {
12121                t.result_cache_hit = true;
12122                t.scan_mode = crate::trace::ScanMode::NativePushdown;
12123            });
12124            return Ok(Some((*hit).clone()));
12125        }
12126        let res = self.query_columns_native_inner(conditions, projection, snapshot, control)?;
12127        execution_checkpoint(control, 0)?;
12128        if let Some(cols) = &res {
12129            let footprint = self.resolve_footprint(conditions, snapshot);
12130            let condition_cols = crate::query::condition_columns(conditions);
12131            execution_checkpoint(control, 0)?;
12132            let entry = CachedEntry {
12133                data: CachedData::Columns(Arc::new(cols.clone())),
12134                footprint,
12135                condition_cols,
12136            };
12137            // Compute everything we need, then take the lock once. The
12138            // `ResultCache` lock is a non-reentrant `parking_lot::Mutex` so
12139            // `persist_entry` + `insert` must run in the same critical
12140            // section. `persist_entry` enqueues onto the background writer
12141            // or skips publication with a metric — never query-thread I/O.
12142            let mut cache = self.result_cache.lock();
12143            let entry_generation = cache.allocate_persist_generation(key);
12144            let context = PersistContext {
12145                identity,
12146                key,
12147                entry_generation,
12148            };
12149            cache.persist_entry(context, &entry);
12150            cache.insert(key, entry);
12151        }
12152        Ok(res)
12153    }
12154
12155    /// Phase 19.1 + hardening (c): a cached form of [`Table::query`]. The cache key
12156    /// is epoch-independent; invalidation is fine-grained (see
12157    /// [`Table::query_columns_native_cached`]). On a hit returns the cached rows (no
12158    /// re-resolve, no re-decode).
12159    pub fn query_cached(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
12160        if self.ttl.is_some() {
12161            return self.query(q);
12162        }
12163        if q.conditions.is_empty() {
12164            return self.query(q);
12165        }
12166        let key = crate::query::canonical_query_key(&q.conditions, None, 0)
12167            ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
12168            ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
12169        let identity = PersistentCacheIdentity {
12170            table_id: self.table_id(),
12171            schema_id: self.schema.schema_id,
12172            logical_generation: self.current_epoch().0,
12173        };
12174        if let Some(hit) = self.result_cache.lock().get_rows(key, identity) {
12175            crate::trace::QueryTrace::record(|t| {
12176                t.result_cache_hit = true;
12177                t.scan_mode = crate::trace::ScanMode::Materialized;
12178            });
12179            return Ok((*hit).clone());
12180        }
12181        let rows = self.query(q)?;
12182        let footprint = rows.iter().map(|r| r.row_id.0 as u32).collect();
12183        let condition_cols = crate::query::condition_columns(&q.conditions);
12184        let entry = CachedEntry {
12185            data: CachedData::Rows(Arc::new(rows.clone())),
12186            footprint,
12187            condition_cols,
12188        };
12189        // Take the lock once: persist_entry + insert must run atomically
12190        // because `ResultCache` uses a non-reentrant `parking_lot::Mutex`.
12191        // `persist_entry` enqueues onto the background writer or skips
12192        // publication with a metric — never query-thread I/O (REM-D §8.5).
12193        let mut cache = self.result_cache.lock();
12194        let entry_generation = cache.allocate_persist_generation(key);
12195        let context = PersistContext {
12196            identity,
12197            key,
12198            entry_generation,
12199        };
12200        cache.persist_entry(context, &entry);
12201        cache.insert(key, entry);
12202        Ok(rows)
12203    }
12204
12205    // -----------------------------------------------------------------------
12206    // Traced query wrappers (OPTIMIZATIONS.md Priority 0 / 16).
12207    //
12208    // Each `_traced` method runs its underlying query inside a
12209    // [`crate::trace::QueryTrace::capture`] scope and returns the result
12210    // alongside the captured path trace. The trace records which physical path
12211    // served the query (cursor / pushdown / materialized / count-shortcut),
12212    // whether indexes were rebuilt, whether the result cache hit, overlay size,
12213    // survivor count, and the fast row-id map usage. Recording is zero-cost
12214    // when no `_traced` method is on the call stack (the plain methods are
12215    // unchanged).
12216    // -----------------------------------------------------------------------
12217
12218    /// [`Self::query_columns_native`] with a captured [`crate::trace::QueryTrace`].
12219    #[allow(clippy::type_complexity)]
12220    pub fn query_columns_native_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(conditions, projection, snapshot)
12231        });
12232        Ok((result?, trace))
12233    }
12234
12235    /// [`Self::query_columns_native_cached`] with a captured
12236    /// [`crate::trace::QueryTrace`] (records result-cache hits too).
12237    #[allow(clippy::type_complexity)]
12238    pub fn query_columns_native_cached_traced(
12239        &mut self,
12240        conditions: &[crate::query::Condition],
12241        projection: Option<&[u16]>,
12242        snapshot: Snapshot,
12243    ) -> Result<(
12244        Option<Vec<(u16, columnar::NativeColumn)>>,
12245        crate::trace::QueryTrace,
12246    )> {
12247        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12248            self.query_columns_native_cached(conditions, projection, snapshot)
12249        });
12250        Ok((result?, trace))
12251    }
12252
12253    /// [`Self::native_page_cursor`] with a captured [`crate::trace::QueryTrace`].
12254    pub fn native_page_cursor_traced(
12255        &self,
12256        snapshot: Snapshot,
12257        projection: Vec<(u16, TypeId)>,
12258        conditions: &[crate::query::Condition],
12259    ) -> Result<(Option<NativePageCursor>, crate::trace::QueryTrace)> {
12260        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12261            self.native_page_cursor(snapshot, projection, conditions)
12262        });
12263        Ok((result?, trace))
12264    }
12265
12266    /// [`Self::native_multi_run_cursor`] with a captured [`crate::trace::QueryTrace`].
12267    pub fn native_multi_run_cursor_traced(
12268        &self,
12269        snapshot: Snapshot,
12270        projection: Vec<(u16, TypeId)>,
12271        conditions: &[crate::query::Condition],
12272    ) -> Result<(
12273        Option<crate::cursor::MultiRunCursor>,
12274        crate::trace::QueryTrace,
12275    )> {
12276        let (result, trace) = crate::trace::QueryTrace::capture(|| {
12277            self.native_multi_run_cursor(snapshot, projection, conditions)
12278        });
12279        Ok((result?, trace))
12280    }
12281
12282    /// [`Self::count_conditions`] with a captured [`crate::trace::QueryTrace`].
12283    pub fn count_conditions_traced(
12284        &mut self,
12285        conditions: &[crate::query::Condition],
12286        snapshot: Snapshot,
12287    ) -> Result<(Option<u64>, crate::trace::QueryTrace)> {
12288        let (result, trace) =
12289            crate::trace::QueryTrace::capture(|| self.count_conditions(conditions, snapshot));
12290        Ok((result?, trace))
12291    }
12292
12293    /// [`Self::query`] with a captured [`crate::trace::QueryTrace`].
12294    pub fn query_traced(
12295        &mut self,
12296        q: &crate::query::Query,
12297    ) -> Result<(Vec<Row>, crate::trace::QueryTrace)> {
12298        let (result, trace) = crate::trace::QueryTrace::capture(|| self.query(q));
12299        Ok((result?, trace))
12300    }
12301
12302    /// Predicate pushdown: resolve `conditions` via indexes to find the matching
12303    /// row-id set, then decode only those rows' columns — not the whole table.
12304    /// Returns `None` if the conditions can't be served by indexes (caller falls
12305    /// back to a full scan). This is the fast path for `WHERE col = 'value'`.
12306    pub fn query_columns_native(
12307        &mut self,
12308        conditions: &[crate::query::Condition],
12309        projection: Option<&[u16]>,
12310        snapshot: Snapshot,
12311    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12312        self.query_columns_native_inner(conditions, projection, snapshot, None)
12313    }
12314
12315    pub fn query_columns_native_with_control(
12316        &mut self,
12317        conditions: &[crate::query::Condition],
12318        projection: Option<&[u16]>,
12319        snapshot: Snapshot,
12320        control: &crate::ExecutionControl,
12321    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12322        self.query_columns_native_inner(conditions, projection, snapshot, Some(control))
12323    }
12324
12325    fn query_columns_native_inner(
12326        &mut self,
12327        conditions: &[crate::query::Condition],
12328        projection: Option<&[u16]>,
12329        snapshot: Snapshot,
12330        control: Option<&crate::ExecutionControl>,
12331    ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12332        use crate::query::Condition;
12333        execution_checkpoint(control, 0)?;
12334        // TTL reads use the materialized visibility path so the wall-clock
12335        // cutoff is captured once and applied to every storage tier.
12336        if self.ttl.is_some() {
12337            return Ok(None);
12338        }
12339        if conditions.is_empty() {
12340            return Ok(None);
12341        }
12342        self.ensure_indexes_complete()?;
12343
12344        // Only these conditions are pushdown-served. Range/RangeF64 need a
12345        // column read on the single-run fast path; off it they fall back to a
12346        // visible-rows scan via `resolve_condition` (still correct for any
12347        // layout, just not page-pruned).
12348        let served = |c: &Condition| {
12349            matches!(
12350                c,
12351                Condition::Pk(_)
12352                    | Condition::BitmapEq { .. }
12353                    | Condition::BitmapIn { .. }
12354                    | Condition::BytesPrefix { .. }
12355                    | Condition::FmContains { .. }
12356                    | Condition::FmContainsAll { .. }
12357                    | Condition::Ann { .. }
12358                    | Condition::Range { .. }
12359                    | Condition::RangeF64 { .. }
12360                    | Condition::SparseMatch { .. }
12361                    | Condition::MinHashSimilar { .. }
12362                    | Condition::IsNull { .. }
12363                    | Condition::IsNotNull { .. }
12364            )
12365        };
12366        if !conditions.iter().all(served) {
12367            return Ok(None);
12368        }
12369        let fast_path =
12370            self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
12371        crate::trace::QueryTrace::record(|t| {
12372            t.run_count = self.run_refs.len();
12373            t.memtable_rows = self.memtable.len();
12374            t.mutable_run_rows = self.mutable_run.len();
12375            t.conditions_pushed = conditions.len();
12376            t.learned_range_used = conditions.iter().any(|c| match c {
12377                Condition::Range { column_id, .. } | Condition::RangeF64 { column_id, .. } => {
12378                    self.learned_range.contains_key(column_id)
12379                }
12380                _ => false,
12381            });
12382        });
12383        // Build column list (projected or all user columns) + projection pairs.
12384        let col_ids: Vec<u16> = projection
12385            .map(|p| p.to_vec())
12386            .unwrap_or_else(|| self.schema.columns.iter().map(|c| c.id).collect());
12387        let proj_pairs: Vec<(u16, TypeId)> = col_ids
12388            .iter()
12389            .map(|&cid| {
12390                let ty = self
12391                    .schema
12392                    .columns
12393                    .iter()
12394                    .find(|c| c.id == cid)
12395                    .map(|c| c.ty.clone())
12396                    .unwrap_or(TypeId::Bytes);
12397                (cid, ty)
12398            })
12399            .collect();
12400
12401        // -----------------------------------------------------------------------
12402        // Fast path: single run, empty memtable/mutable-run → resolve survivors,
12403        // binary-search positions, gather only the projected columns from one
12404        // reader. This is the fastest pushdown path (no cursor overhead).
12405        // -----------------------------------------------------------------------
12406        if fast_path {
12407            // A Range/RangeF64 needs a column read *unless* its column has a
12408            // learned (PGM) range index, in which case it's served in-memory.
12409            let needs_column = conditions.iter().any(|c| match c {
12410                Condition::Range { column_id, .. } => !self.learned_range.contains_key(column_id),
12411                Condition::RangeF64 { column_id, .. } => {
12412                    !self.learned_range.contains_key(column_id)
12413                }
12414                _ => false,
12415            });
12416            let mut reader_opt: Option<RunReader> = if needs_column {
12417                Some(self.open_reader(self.run_refs[0].run_id)?)
12418            } else {
12419                None
12420            };
12421            let mut sets: Vec<RowIdSet> = Vec::new();
12422            for (index, c) in conditions.iter().enumerate() {
12423                execution_checkpoint(control, index)?;
12424                let s = match c {
12425                    Condition::Range { column_id, lo, hi }
12426                        if !self.learned_range.contains_key(column_id) =>
12427                    {
12428                        if reader_opt.is_none() {
12429                            reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12430                        }
12431                        reader_opt
12432                            .as_mut()
12433                            .expect("reader opened for range")
12434                            .range_row_id_set_i64(*column_id, *lo, *hi)?
12435                    }
12436                    Condition::RangeF64 {
12437                        column_id,
12438                        lo,
12439                        lo_inclusive,
12440                        hi,
12441                        hi_inclusive,
12442                    } if !self.learned_range.contains_key(column_id) => {
12443                        if reader_opt.is_none() {
12444                            reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12445                        }
12446                        reader_opt
12447                            .as_mut()
12448                            .expect("reader opened for range")
12449                            .range_row_id_set_f64(
12450                                *column_id,
12451                                *lo,
12452                                *lo_inclusive,
12453                                *hi,
12454                                *hi_inclusive,
12455                            )?
12456                    }
12457                    _ => self.resolve_condition(c, snapshot)?,
12458                };
12459                sets.push(s);
12460            }
12461            let candidates = RowIdSet::intersect_many(sets);
12462            crate::trace::QueryTrace::record(|t| {
12463                t.survivor_count = Some(candidates.len());
12464            });
12465            if candidates.is_empty() {
12466                let cols: Vec<(u16, columnar::NativeColumn)> = col_ids
12467                    .iter()
12468                    .map(|&id| {
12469                        (
12470                            id,
12471                            columnar::null_native(
12472                                proj_pairs
12473                                    .iter()
12474                                    .find(|(c, _)| c == &id)
12475                                    .map(|(_, t)| t.clone())
12476                                    .unwrap_or(TypeId::Bytes),
12477                                0,
12478                            ),
12479                        )
12480                    })
12481                    .collect();
12482                return Ok(Some(cols));
12483            }
12484            let mut reader = match reader_opt.take() {
12485                Some(r) => r,
12486                None => self.open_reader(self.run_refs[0].run_id)?,
12487            };
12488            let candidate_ids = candidates.into_sorted_vec();
12489            let (positions, fast_rid) = if let Some(positions) =
12490                reader.positions_for_row_ids_fast(&candidate_ids)
12491            {
12492                (positions, true)
12493            } else {
12494                let col = reader.column_native(crate::sorted_run::SYS_ROW_ID)?;
12495                match col {
12496                    columnar::NativeColumn::Int64 { data, .. } => {
12497                        let mut p = Vec::with_capacity(candidate_ids.len());
12498                        for (index, rid) in candidate_ids.iter().enumerate() {
12499                            execution_checkpoint(control, index)?;
12500                            if let Ok(position) = data.binary_search(&(*rid as i64)) {
12501                                p.push(position);
12502                            }
12503                        }
12504                        p.sort_unstable();
12505                        (p, false)
12506                    }
12507                    _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
12508                }
12509            };
12510            crate::trace::QueryTrace::record(|t| {
12511                t.scan_mode = crate::trace::ScanMode::NativePushdown;
12512                t.fast_row_id_map = fast_rid;
12513            });
12514            let mut cols = Vec::with_capacity(col_ids.len());
12515            for (index, cid) in col_ids.iter().enumerate() {
12516                execution_checkpoint(control, index)?;
12517                let col = reader.column_native(*cid)?;
12518                cols.push((*cid, col.gather(&positions)));
12519            }
12520            return Ok(Some(cols));
12521        }
12522
12523        // -----------------------------------------------------------------------
12524        // Non-fast path (multi-run / non-empty overlay). Route through the
12525        // columnar cursor (OPTIMIZATIONS.md Priority 1 + 4): the cursor builder
12526        // resolves MVCC, predicates, and overlay internally in batch, then
12527        // streams projected columns page-by-page. This avoids the per-rid
12528        // `rows_for_rids` `get_version`-across-all-runs cost that made multi-run
12529        // pushdown ~1000× slower than the single-run fast path.
12530        //
12531        // The cursor handles both single-run-with-overlay (`native_page_cursor`)
12532        // and multi-run (`native_multi_run_cursor`) layouts. The empty-table
12533        // (no runs, memtable-only) edge case falls through to `rows_for_rids`.
12534        // -----------------------------------------------------------------------
12535        if !self.run_refs.is_empty() {
12536            use crate::cursor::{
12537                drain_cursor_to_columns, drain_cursor_to_columns_with_control, Cursor,
12538            };
12539            let remaining: usize;
12540            let mut cursor: Box<dyn crate::cursor::Cursor> = if self.run_refs.len() == 1 {
12541                let c = self
12542                    .native_page_cursor(snapshot, proj_pairs.clone(), conditions)?
12543                    .expect("single-run cursor should build when run_refs.len() == 1");
12544                remaining = c.remaining_rows();
12545                Box::new(c)
12546            } else {
12547                let c = self
12548                    .native_multi_run_cursor(snapshot, proj_pairs.clone(), conditions)?
12549                    .expect("multi-run cursor should build when run_refs.len() >= 1");
12550                remaining = c.remaining_rows();
12551                Box::new(c)
12552            };
12553            crate::trace::QueryTrace::record(|t| {
12554                if t.survivor_count.is_none() {
12555                    t.survivor_count = Some(remaining);
12556                }
12557            });
12558            let cols = match control {
12559                Some(control) => {
12560                    drain_cursor_to_columns_with_control(cursor.as_mut(), &proj_pairs, control)?
12561                }
12562                None => drain_cursor_to_columns(cursor.as_mut(), &proj_pairs)?,
12563            };
12564            return Ok(Some(cols));
12565        }
12566
12567        // Empty-table fallback (no sorted runs, memtable/mutable-run only): the
12568        // cursor builders return `None` for `run_refs.is_empty()`, so resolve
12569        // from overlay indexes and materialize via `rows_for_rids`. This is the
12570        // rare edge case (fresh table with only `put`s, no `flush`/`bulk_load`).
12571        crate::trace::QueryTrace::record(|t| {
12572            t.scan_mode = crate::trace::ScanMode::Materialized;
12573            t.row_materialized = true;
12574        });
12575        let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12576        for (index, c) in conditions.iter().enumerate() {
12577            execution_checkpoint(control, index)?;
12578            sets.push(self.resolve_condition(c, snapshot)?);
12579        }
12580        let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
12581        let rows = self.rows_for_rids(&rids, snapshot)?;
12582        let mut cols: Vec<(u16, columnar::NativeColumn)> = Vec::with_capacity(col_ids.len());
12583        for (index, (cid, ty)) in proj_pairs.iter().enumerate() {
12584            execution_checkpoint(control, index)?;
12585            let vals: Vec<Value> = rows
12586                .iter()
12587                .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
12588                .collect();
12589            cols.push((*cid, columnar::values_to_native(ty.clone(), &vals)));
12590        }
12591        Ok(Some(cols))
12592    }
12593
12594    /// Build a lazy, page-aware [`NativePageCursor`] for the single-run fast
12595    /// path. MVCC visibility and predicate survivor resolution are settled up
12596    /// front (so they see the live indexes under the DB lock); the cursor then
12597    /// owns the reader and decodes only the projected columns of pages that
12598    /// contain survivors, lazily. This is the fused-predicate + page-skip +
12599    /// late-materialization scan.
12600    ///
12601    /// Phase 13.1: the memtable / mutable-run overlay is now handled. Rows with
12602    /// a newer version in the overlay are excluded from the run's page plans
12603    /// (their run version is stale); the overlay rows are pre-materialized and
12604    /// appended as a final batch via [`NativePageCursor::new_with_overlay`].
12605    ///
12606    /// Returns `None` only for multiple sorted runs; the caller falls back to
12607    /// the materialize-then-stream scan for that layout.
12608    pub fn native_page_cursor(
12609        &self,
12610        snapshot: Snapshot,
12611        projection: Vec<(u16, TypeId)>,
12612        conditions: &[crate::query::Condition],
12613    ) -> Result<Option<NativePageCursor>> {
12614        use crate::cursor::build_page_plans;
12615        if self.ttl.is_some() {
12616            return Ok(None);
12617        }
12618        // See `scan_cursor`: incomplete (deferred) indexes cannot resolve
12619        // conditions — signal "can't serve" instead of empty survivor sets.
12620        if !conditions.is_empty() && !self.indexes_complete {
12621            return Ok(None);
12622        }
12623        if self.run_refs.len() != 1 {
12624            return Ok(None);
12625        }
12626        let mut reader = self.open_reader(self.run_refs[0].run_id)?;
12627        let (positions, rids) = reader.visible_positions_with_rids_at(snapshot)?;
12628
12629        // Collect overlay rows from memtable + mutable_run (visible, newest
12630        // version per row). These shadow any stale version in the run.
12631        let overlay_rids: HashSet<u64> = {
12632            let mut s = HashSet::new();
12633            for row in self.memtable.visible_versions_at(snapshot) {
12634                s.insert(row.row_id.0);
12635            }
12636            for row in self.mutable_run.visible_versions_at(snapshot) {
12637                s.insert(row.row_id.0);
12638            }
12639            s
12640        };
12641
12642        // Resolve survivor rids via indexes (covers overlay rows for index-
12643        // served conditions: PK, bitmap, FM, ANN, sparse — all maintained on
12644        // every put).
12645        let survivors = if conditions.is_empty() {
12646            None
12647        } else {
12648            Some(self.resolve_survivor_rids(conditions, &mut reader, snapshot)?)
12649        };
12650
12651        // Exclude overlay rids from the run portion: their version in the run
12652        // is stale (updated/deleted in the overlay) or they don't exist in the
12653        // run (new inserts). When there are conditions, we remove overlay rids
12654        // from the survivor set. When there are no conditions, we synthesize a
12655        // survivor set = (all visible run rids) − (overlay rids) so the stale
12656        // run rows are pruned.
12657        let run_survivors: Option<RowIdSet> = if overlay_rids.is_empty() {
12658            survivors.clone()
12659        } else if let Some(s) = &survivors {
12660            let mut run_set = s.clone();
12661            run_set.remove_many(overlay_rids.iter().copied());
12662            Some(run_set)
12663        } else {
12664            Some(RowIdSet::from_unsorted(
12665                rids.iter()
12666                    .map(|&r| r as u64)
12667                    .filter(|r| !overlay_rids.contains(r))
12668                    .collect(),
12669            ))
12670        };
12671
12672        let overlay_rows = if overlay_rids.is_empty() {
12673            Vec::new()
12674        } else {
12675            let bound = Self::overlay_materialization_bound(conditions, &survivors);
12676            self.overlay_visible_rows(snapshot, bound)
12677        };
12678
12679        // Build page plans for the run portion.
12680        let plans = if positions.is_empty() {
12681            Vec::new()
12682        } else {
12683            let page_rows = reader.page_row_counts(crate::sorted_run::SYS_ROW_ID)?;
12684            build_page_plans(&positions, &rids, &page_rows, run_survivors.as_ref())
12685        };
12686
12687        // Filter and materialize the overlay.
12688        let overlay = if overlay_rows.is_empty() {
12689            None
12690        } else {
12691            let filtered =
12692                self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12693            if filtered.is_empty() {
12694                None
12695            } else {
12696                Some(self.materialize_overlay(&filtered, &projection))
12697            }
12698        };
12699
12700        let overlay_row_count = overlay
12701            .as_ref()
12702            .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12703            .unwrap_or(0);
12704        crate::trace::QueryTrace::record(|t| {
12705            t.scan_mode = crate::trace::ScanMode::NativePageCursor;
12706            t.run_count = self.run_refs.len();
12707            t.memtable_rows = self.memtable.len();
12708            t.mutable_run_rows = self.mutable_run.len();
12709            t.overlay_rows = overlay_row_count;
12710            t.conditions_pushed = conditions.len();
12711            t.pages_decoded = plans
12712                .iter()
12713                .map(|p| p.positions.len())
12714                .sum::<usize>()
12715                .min(1);
12716        });
12717
12718        Ok(Some(NativePageCursor::new_with_overlay(
12719            reader, projection, plans, overlay,
12720        )))
12721    }
12722    /// Generalizes [`Self::native_page_cursor`] (single-run) to arbitrary run
12723    /// counts via a k-way merge by `RowId`. Cross-run MVCC resolution (newest
12724    /// visible version per `RowId`) and predicate survivor resolution are settled
12725    /// up front from the cheap system columns + global indexes; the cursor then
12726    /// lazily decodes the projected data columns of just the pages that own
12727    /// survivors, each page at most once. The memtable / mutable-run overlay is
12728    /// materialized and yielded as a final batch (mirroring the single-run path).
12729    ///
12730    /// Returns `None` only when there are no runs at all (caller falls back).
12731    #[allow(clippy::type_complexity)]
12732    pub fn native_multi_run_cursor(
12733        &self,
12734        snapshot: Snapshot,
12735        projection: Vec<(u16, TypeId)>,
12736        conditions: &[crate::query::Condition],
12737    ) -> Result<Option<crate::cursor::MultiRunCursor>> {
12738        use crate::cursor::{MultiRunCursor, RunStream};
12739        use crate::sorted_run::SYS_ROW_ID;
12740        use std::collections::{BinaryHeap, HashMap, HashSet};
12741        if self.ttl.is_some() {
12742            return Ok(None);
12743        }
12744        // See `scan_cursor`: incomplete (deferred) indexes cannot resolve
12745        // conditions — signal "can't serve" instead of empty survivor sets.
12746        if !conditions.is_empty() && !self.indexes_complete {
12747            return Ok(None);
12748        }
12749        if self.run_refs.is_empty() {
12750            return Ok(None);
12751        }
12752
12753        // Open each run once; read its system columns + page layout.
12754        let mut run_meta: Vec<(
12755            RunReader,
12756            Vec<i64>,
12757            Vec<i64>,
12758            Vec<u8>,
12759            Option<Vec<Option<HlcTimestamp>>>,
12760            Vec<usize>,
12761        )> = Vec::with_capacity(self.run_refs.len());
12762        for rr in &self.run_refs {
12763            let mut reader = self.open_reader(rr.run_id)?;
12764            let (rids, eps, del) = reader.system_columns_native()?;
12765            let page_rows = reader.page_row_counts(SYS_ROW_ID)?;
12766            let commit_ts: Option<Vec<Option<HlcTimestamp>>> =
12767                if reader.has_column(crate::sorted_run::SYS_COMMIT_TS) {
12768                    let col = reader.column_native(crate::sorted_run::SYS_COMMIT_TS)?;
12769                    Some(
12770                        (0..rids.len())
12771                            .map(|i| {
12772                                crate::sorted_run::decode_commit_ts_value(col.value_at(i).as_ref())
12773                            })
12774                            .collect(),
12775                    )
12776                } else {
12777                    None
12778                };
12779            run_meta.push((reader, rids, eps, del, commit_ts, page_rows));
12780        }
12781
12782        // Global cross-run newest-version resolution: rid -> (epoch, run_idx,
12783        // position, deleted). Mirrors `visible_rows`, tracking which run owns
12784        // the newest MVCC-visible version. HLC stamps participate via
12785        // `Snapshot::observes_row` and `version_is_newer` so an HLC-pinned
12786        // snapshot surfaces the HLC-newer winner regardless of local epoch.
12787        let mut best: HashMap<u64, (Epoch, Option<HlcTimestamp>, usize, usize, bool)> =
12788            HashMap::new();
12789        for (run_idx, (_, rids, eps, del, commit_ts, _)) in run_meta.iter().enumerate() {
12790            for i in 0..rids.len() {
12791                let rid = rids[i] as u64;
12792                let e = Epoch(eps[i] as u64);
12793                let ts = commit_ts.as_ref().and_then(|v| v.get(i).copied().flatten());
12794                if !snapshot.observes_row(e, ts) {
12795                    continue;
12796                }
12797                let is_del = del[i] != 0;
12798                best.entry(rid)
12799                    .and_modify(|cur| {
12800                        if Snapshot::version_is_newer(e, ts, cur.0, cur.1) {
12801                            *cur = (e, ts, run_idx, i, is_del);
12802                        }
12803                    })
12804                    .or_insert((e, ts, run_idx, i, is_del));
12805            }
12806        }
12807
12808        // Overlay rids (memtable + mutable-run) shadow every run version.
12809        let overlay_rids: HashSet<u64> = {
12810            let mut s = HashSet::new();
12811            for row in self.memtable.visible_versions_at(snapshot) {
12812                s.insert(row.row_id.0);
12813            }
12814            for row in self.mutable_run.visible_versions_at(snapshot) {
12815                s.insert(row.row_id.0);
12816            }
12817            s
12818        };
12819
12820        // Predicate survivors (global, layout-independent).
12821        let survivors: Option<RowIdSet> = if conditions.is_empty() {
12822            None
12823        } else {
12824            let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12825            for c in conditions {
12826                sets.push(self.resolve_condition(c, snapshot)?);
12827            }
12828            Some(RowIdSet::intersect_many(sets))
12829        };
12830
12831        // Per-run owned survivors: (rid, position), ascending by rid. A row is
12832        // owned by the run holding its newest visible version, is not deleted,
12833        // is not shadowed by the overlay, and satisfies the predicate.
12834        let mut per_run: Vec<Vec<(u64, usize)>> = vec![Vec::new(); run_meta.len()];
12835        for (rid, (_, _, run_idx, pos, deleted)) in &best {
12836            if *deleted {
12837                continue;
12838            }
12839            if overlay_rids.contains(rid) {
12840                continue;
12841            }
12842            if let Some(s) = &survivors {
12843                if !s.contains(*rid) {
12844                    continue;
12845                }
12846            }
12847            per_run[*run_idx].push((*rid, *pos));
12848        }
12849        for v in per_run.iter_mut() {
12850            v.sort_unstable_by_key(|&(rid, _)| rid);
12851        }
12852
12853        // Build the merge streams: map each owned position to (page_seq, within).
12854        let mut streams = Vec::with_capacity(run_meta.len());
12855        let mut heap: BinaryHeap<std::cmp::Reverse<(u64, usize)>> = BinaryHeap::new();
12856        let mut total = 0usize;
12857        for (run_idx, (reader, _, _, _, _, page_rows)) in run_meta.into_iter().enumerate() {
12858            let mut starts = Vec::with_capacity(page_rows.len());
12859            let mut acc = 0usize;
12860            for &r in &page_rows {
12861                starts.push(acc);
12862                acc += r;
12863            }
12864            let mut survivors_vec: Vec<(u64, usize, usize)> =
12865                Vec::with_capacity(per_run[run_idx].len());
12866            for &(rid, pos) in &per_run[run_idx] {
12867                let page_seq = match starts.partition_point(|&s| s <= pos) {
12868                    0 => continue,
12869                    p => p - 1,
12870                };
12871                let within = pos - starts[page_seq];
12872                survivors_vec.push((rid, page_seq, within));
12873            }
12874            total += survivors_vec.len();
12875            if let Some(&(rid, _, _)) = survivors_vec.first() {
12876                heap.push(std::cmp::Reverse((rid, run_idx)));
12877            }
12878            streams.push(RunStream::new(reader, survivors_vec, page_rows));
12879        }
12880
12881        // Materialize the overlay (filtered + projected), yielded as the final batch.
12882        let overlay_rows = if overlay_rids.is_empty() {
12883            Vec::new()
12884        } else {
12885            let bound = Self::overlay_materialization_bound(conditions, &survivors);
12886            self.overlay_visible_rows(snapshot, bound)
12887        };
12888        let overlay = if overlay_rows.is_empty() {
12889            None
12890        } else {
12891            let filtered =
12892                self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12893            if filtered.is_empty() {
12894                None
12895            } else {
12896                Some(self.materialize_overlay(&filtered, &projection))
12897            }
12898        };
12899
12900        let overlay_row_count = overlay
12901            .as_ref()
12902            .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12903            .unwrap_or(0);
12904        crate::trace::QueryTrace::record(|t| {
12905            t.scan_mode = crate::trace::ScanMode::MultiRunCursor;
12906            t.run_count = self.run_refs.len();
12907            t.memtable_rows = self.memtable.len();
12908            t.mutable_run_rows = self.mutable_run.len();
12909            t.overlay_rows = overlay_row_count;
12910            t.conditions_pushed = conditions.len();
12911            t.survivor_count = Some(total);
12912        });
12913
12914        Ok(Some(MultiRunCursor::new(
12915            streams, projection, heap, total, overlay,
12916        )))
12917    }
12918
12919    /// Collect visible, non-deleted overlay rows from the memtable and mutable-
12920    /// run tier at `snapshot`. These are the rows whose data lives only in the
12921    /// in-memory buffers (not yet in a sorted run), or that shadow a stale
12922    /// version in the run.
12923    /// The survivor set that bounds overlay materialization (Priority 2), or
12924    /// `None` when overlay rows must be fully materialized — i.e. there is a
12925    /// `Range`/`RangeF64` residual, for which the index-served survivor set does
12926    /// not cover matching overlay rows (those are evaluated downstream). This
12927    /// mirrors the `all_index_served` branch of
12928    /// [`filter_overlay_rows`](Self::filter_overlay_rows), so bounding here is
12929    /// result-preserving.
12930    fn overlay_materialization_bound<'a>(
12931        conditions: &[crate::query::Condition],
12932        survivors: &'a Option<RowIdSet>,
12933    ) -> Option<&'a RowIdSet> {
12934        use crate::query::Condition;
12935        let has_range = conditions
12936            .iter()
12937            .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12938        if has_range {
12939            None
12940        } else {
12941            survivors.as_ref()
12942        }
12943    }
12944
12945    /// Materialize the visible overlay rows (memtable + mutable-run, newest
12946    /// version per row, non-deleted).
12947    ///
12948    /// Priority 2 (selective overlay probing): when `bound` is `Some`, only rows
12949    /// whose id is in it are materialized. The caller passes the index-resolved
12950    /// survivor set as `bound` exactly when every condition is index-served — in
12951    /// which case [`filter_overlay_rows`](Self::filter_overlay_rows) would discard
12952    /// any non-survivor overlay row anyway, so this prunes the materialization
12953    /// without changing the result. With a Range/RangeF64 residual the survivor
12954    /// set is incomplete for overlay rows, so the caller passes `None` (full
12955    /// materialization) and the range is re-evaluated downstream.
12956    fn overlay_visible_rows(&self, snapshot: Snapshot, bound: Option<&RowIdSet>) -> Vec<Row> {
12957        let mut best: HashMap<u64, (Epoch, Row)> = HashMap::new();
12958        let mut fold = |row: Row| {
12959            if let Some(b) = bound {
12960                if !b.contains(row.row_id.0) {
12961                    return;
12962                }
12963            }
12964            best.entry(row.row_id.0)
12965                .and_modify(|(be, br)| {
12966                    if row.committed_epoch > *be {
12967                        *be = row.committed_epoch;
12968                        *br = row.clone();
12969                    }
12970                })
12971                .or_insert_with(|| (row.committed_epoch, row));
12972        };
12973        for row in self.memtable.visible_versions_at(snapshot) {
12974            fold(row);
12975        }
12976        for row in self.mutable_run.visible_versions_at(snapshot) {
12977            fold(row);
12978        }
12979        let mut out: Vec<Row> = best
12980            .into_values()
12981            .filter_map(|(_, r)| if r.deleted { None } else { Some(r) })
12982            .collect();
12983        out.sort_by_key(|r| r.row_id);
12984        out
12985    }
12986
12987    /// Filter overlay rows against the conjunctive predicate. Range / RangeF64
12988    /// are evaluated directly (the reader-served survivor set misses overlay
12989    /// rows). All other conditions are index-served (indexes maintained on
12990    /// every `put`) so the intersected `survivors` set includes overlay rows
12991    /// that match — but ONLY when every condition is index-served. When there
12992    /// is a mix, we compute per-condition index sets for non-range conditions
12993    /// and evaluate range conditions directly, so the intersection is correct.
12994    fn filter_overlay_rows(
12995        &self,
12996        rows: Vec<Row>,
12997        conditions: &[crate::query::Condition],
12998        survivors: Option<&RowIdSet>,
12999        snapshot: Snapshot,
13000    ) -> Result<Vec<Row>> {
13001        if conditions.is_empty() {
13002            return Ok(rows);
13003        }
13004        use crate::query::Condition;
13005        // Determine whether every condition is index-served (survivors set is
13006        // then complete for overlay rows). If so, a simple membership check
13007        // suffices and is cheapest.
13008        let all_index_served = !conditions
13009            .iter()
13010            .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
13011        if all_index_served {
13012            return Ok(rows
13013                .into_iter()
13014                .filter(|r| survivors.is_none_or(|s| s.contains(r.row_id.0)))
13015                .collect());
13016        }
13017        // Mixed: compute per-condition index sets for non-range conditions, and
13018        // evaluate range conditions directly on column values.
13019        let mut per_cond_sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
13020        for c in conditions {
13021            let s = match c {
13022                Condition::Range { .. } | Condition::RangeF64 { .. } => RowIdSet::empty(),
13023                _ => self.resolve_condition(c, snapshot)?,
13024            };
13025            per_cond_sets.push(s);
13026        }
13027        Ok(rows
13028            .into_iter()
13029            .filter(|row| {
13030                conditions.iter().enumerate().all(|(i, c)| match c {
13031                    Condition::Range { column_id, lo, hi } => {
13032                        matches!(row.columns.get(column_id), Some(Value::Int64(v)) if *v >= *lo && *v <= *hi)
13033                    }
13034                    Condition::RangeF64 { column_id, lo, lo_inclusive, hi, hi_inclusive } => {
13035                        match row.columns.get(column_id) {
13036                            Some(Value::Float64(v)) => {
13037                                let lo_ok = if *lo_inclusive { *v >= *lo } else { *v > *lo };
13038                                let hi_ok = if *hi_inclusive { *v <= *hi } else { *v < *hi };
13039                                lo_ok && hi_ok
13040                            }
13041                            _ => false,
13042                        }
13043                    }
13044                    _ => per_cond_sets[i].contains(row.row_id.0),
13045                })
13046            })
13047            .collect())
13048    }
13049
13050    /// Materialize overlay rows into typed `NativeColumn`s for the cursor's
13051    /// final batch.
13052    fn materialize_overlay(
13053        &self,
13054        rows: &[Row],
13055        projection: &[(u16, TypeId)],
13056    ) -> Vec<columnar::NativeColumn> {
13057        if projection.is_empty() {
13058            return vec![columnar::null_native(TypeId::Int64, rows.len())];
13059        }
13060        let mut cols = Vec::with_capacity(projection.len());
13061        for (cid, ty) in projection {
13062            let vals: Vec<Value> = rows
13063                .iter()
13064                .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
13065                .collect();
13066            cols.push(columnar::values_to_native(ty.clone(), &vals));
13067        }
13068        cols
13069    }
13070
13071    /// Resolve a conjunctive predicate to its surviving `RowId` set on the
13072    /// single-run fast path: each condition becomes a `RowId` set via the
13073    /// in-memory indexes or the reader's page-pruned range scan, then they are
13074    /// intersected. Mirrors the resolution inside [`Self::query_columns_native`].
13075    fn resolve_survivor_rids(
13076        &self,
13077        conditions: &[crate::query::Condition],
13078        reader: &mut RunReader,
13079        snapshot: Snapshot,
13080    ) -> Result<RowIdSet> {
13081        use crate::query::Condition;
13082        let mut sets: Vec<RowIdSet> = Vec::new();
13083        for c in conditions {
13084            self.validate_condition(c)?;
13085            let s: RowIdSet = match c {
13086                Condition::Pk(key) => {
13087                    let lookup = self
13088                        .schema
13089                        .primary_key()
13090                        .map(|pk| self.index_lookup_key_bytes(pk.id, key))
13091                        .unwrap_or_else(|| key.clone());
13092                    self.hot
13093                        .get(&lookup)
13094                        .map(|r| RowIdSet::one(r.0))
13095                        .unwrap_or_else(RowIdSet::empty)
13096                }
13097                Condition::BitmapEq { column_id, value } => {
13098                    let lookup = self.index_lookup_key_bytes(*column_id, value);
13099                    self.bitmap
13100                        .get(column_id)
13101                        .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
13102                        .unwrap_or_else(RowIdSet::empty)
13103                }
13104                Condition::BitmapIn { column_id, values } => {
13105                    let bm = self.bitmap.get(column_id);
13106                    let mut acc = roaring::RoaringBitmap::new();
13107                    if let Some(b) = bm {
13108                        for v in values {
13109                            let lookup = self.index_lookup_key_bytes(*column_id, v);
13110                            acc |= b.get(&lookup);
13111                        }
13112                    }
13113                    RowIdSet::from_roaring(acc)
13114                }
13115                Condition::BytesPrefix { column_id, prefix } => {
13116                    if let Some(b) = self.bitmap.get(column_id) {
13117                        let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
13118                        let mut acc = roaring::RoaringBitmap::new();
13119                        for key in b.keys() {
13120                            if key.starts_with(&lookup_prefix) {
13121                                acc |= b.get(&key);
13122                            }
13123                        }
13124                        RowIdSet::from_roaring(acc)
13125                    } else {
13126                        RowIdSet::empty()
13127                    }
13128                }
13129                Condition::FmContains { column_id, pattern } => self
13130                    .fm
13131                    .get(column_id)
13132                    .map(|f| {
13133                        RowIdSet::from_unsorted(
13134                            f.locate(pattern).into_iter().map(|r| r.0).collect(),
13135                        )
13136                    })
13137                    .unwrap_or_else(RowIdSet::empty),
13138                Condition::FmContainsAll {
13139                    column_id,
13140                    patterns,
13141                } => {
13142                    if let Some(f) = self.fm.get(column_id) {
13143                        let sets: Vec<RowIdSet> = patterns
13144                            .iter()
13145                            .map(|pat| {
13146                                RowIdSet::from_unsorted(
13147                                    f.locate(pat).into_iter().map(|r| r.0).collect(),
13148                                )
13149                            })
13150                            .collect();
13151                        RowIdSet::intersect_many(sets)
13152                    } else {
13153                        RowIdSet::empty()
13154                    }
13155                }
13156                Condition::Ann {
13157                    column_id,
13158                    query,
13159                    k,
13160                } => RowIdSet::from_unsorted(
13161                    self.retrieve_filtered(
13162                        &crate::query::Retriever::Ann {
13163                            column_id: *column_id,
13164                            query: query.clone(),
13165                            k: *k,
13166                        },
13167                        snapshot,
13168                        None,
13169                        None,
13170                        None,
13171                        None,
13172                    )?
13173                    .into_iter()
13174                    .map(|hit| hit.row_id.0)
13175                    .collect(),
13176                ),
13177                Condition::SparseMatch {
13178                    column_id,
13179                    query,
13180                    k,
13181                } => RowIdSet::from_unsorted(
13182                    self.retrieve_filtered(
13183                        &crate::query::Retriever::Sparse {
13184                            column_id: *column_id,
13185                            query: query.clone(),
13186                            k: *k,
13187                        },
13188                        snapshot,
13189                        None,
13190                        None,
13191                        None,
13192                        None,
13193                    )?
13194                    .into_iter()
13195                    .map(|hit| hit.row_id.0)
13196                    .collect(),
13197                ),
13198                Condition::MinHashSimilar {
13199                    column_id,
13200                    query,
13201                    k,
13202                } => match self.minhash.get(column_id) {
13203                    Some(index) => {
13204                        let candidates = index.candidate_row_ids(query);
13205                        let eligible =
13206                            self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
13207                        RowIdSet::from_unsorted(
13208                            index
13209                                .search_filtered(query, *k, |row_id| eligible.contains(&row_id))
13210                                .into_iter()
13211                                .map(|(row_id, _)| row_id.0)
13212                                .collect(),
13213                        )
13214                    }
13215                    None => RowIdSet::empty(),
13216                },
13217                Condition::Range { column_id, lo, hi } => {
13218                    if let Some(li) = self.learned_range.get(column_id) {
13219                        RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
13220                    } else {
13221                        reader.range_row_id_set_i64(*column_id, *lo, *hi)?
13222                    }
13223                }
13224                Condition::RangeF64 {
13225                    column_id,
13226                    lo,
13227                    lo_inclusive,
13228                    hi,
13229                    hi_inclusive,
13230                } => {
13231                    if let Some(li) = self.learned_range.get(column_id) {
13232                        RowIdSet::from_unsorted(
13233                            li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
13234                                .into_iter()
13235                                .collect(),
13236                        )
13237                    } else {
13238                        reader.range_row_id_set_f64(
13239                            *column_id,
13240                            *lo,
13241                            *lo_inclusive,
13242                            *hi,
13243                            *hi_inclusive,
13244                        )?
13245                    }
13246                }
13247                Condition::IsNull { column_id } => reader.null_row_id_set(*column_id, true)?,
13248                Condition::IsNotNull { column_id } => reader.null_row_id_set(*column_id, false)?,
13249            };
13250            sets.push(s);
13251        }
13252        Ok(RowIdSet::intersect_many(sets))
13253    }
13254
13255    /// Native vectorized aggregate over a (possibly filtered) column on the
13256    /// single-run fast path (Phase 7.2). Resolves survivors via the same
13257    /// page-pruned cursor as the scan, then accumulates the aggregate in one
13258    /// pass over the typed buffer — no `Value`, no Arrow `RecordBatch`.
13259    ///
13260    /// `column` is `None` for `COUNT(*)`. Returns `Ok(None)` when the fast path
13261    /// does not apply (multi-run / non-empty memtable); the caller scans.
13262    /// Open the streaming [`Cursor`](crate::cursor::Cursor) matching the current
13263    /// run layout: the single-run page cursor when there is exactly one sorted
13264    /// run, otherwise the multi-run k-way merge cursor. Both fuse the predicate,
13265    /// skip non-surviving pages, and fold the memtable / mutable-run overlay, so
13266    /// callers stay columnar end-to-end and never materialize `Row`s. Returns
13267    /// `None` when no cursor applies (e.g. an overlay-only table with no sorted
13268    /// run), leaving the caller to fall back.
13269    ///
13270    /// This is the single source of truth for layout-aware cursor selection,
13271    /// shared by the column scan ([`Self::query_columns_native`] / the SQL
13272    /// provider) and the aggregate path ([`Self::aggregate_native`]). New
13273    /// streaming consumers should build on this rather than re-deciding the
13274    /// cursor by run count.
13275    pub fn scan_cursor(
13276        &self,
13277        snapshot: Snapshot,
13278        projection: Vec<(u16, TypeId)>,
13279        conditions: &[crate::query::Condition],
13280    ) -> Result<Option<Box<dyn crate::cursor::Cursor>>> {
13281        if self.ttl.is_some() {
13282            return Ok(None);
13283        }
13284        // A deferred bulk load leaves the live indexes unbuilt; resolving
13285        // conditions against them would return silently-empty survivor sets.
13286        // Signal "can't serve" so the caller falls back to a `&mut` path that
13287        // runs `ensure_indexes_complete`. (Condition-free scans don't touch
13288        // the indexes and stay served.)
13289        if !conditions.is_empty() && !self.indexes_complete {
13290            return Ok(None);
13291        }
13292        if self.run_refs.len() == 1 {
13293            Ok(self
13294                .native_page_cursor(snapshot, projection, conditions)?
13295                .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13296        } else {
13297            Ok(self
13298                .native_multi_run_cursor(snapshot, projection, conditions)?
13299                .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13300        }
13301    }
13302
13303    /// Native vectorized aggregate over a (possibly filtered) column, in one
13304    /// pass over the typed buffers — no `Value`, no Arrow batch. Layout-agnostic:
13305    /// survivors stream through [`Self::scan_cursor`] (single- or multi-run,
13306    /// overlay-folded), so the same path serves every sorted-run layout.
13307    ///
13308    /// `column` is `None` for `COUNT(*)`. Order of attempts:
13309    /// 1. Single clean run + no `WHERE` ⇒ `MIN`/`MAX`/`COUNT(col)` straight from
13310    ///    page `min`/`max`/`null_count` (no decode).
13311    /// 2. `COUNT(*)` ⇒ survivor cardinality from the cursor's page plans.
13312    /// 3. Otherwise accumulate the projected column over the cursor.
13313    ///
13314    /// Returns `Ok(None)` (caller scans) when no native path applies: an
13315    /// overlay-only table with no sorted run, or a non-numeric column.
13316    pub fn aggregate_native(
13317        &self,
13318        snapshot: Snapshot,
13319        column: Option<u16>,
13320        conditions: &[crate::query::Condition],
13321        agg: NativeAgg,
13322    ) -> Result<Option<NativeAggResult>> {
13323        self.aggregate_native_inner(snapshot, column, conditions, agg, None)
13324    }
13325
13326    pub fn aggregate_native_with_control(
13327        &self,
13328        snapshot: Snapshot,
13329        column: Option<u16>,
13330        conditions: &[crate::query::Condition],
13331        agg: NativeAgg,
13332        control: &crate::ExecutionControl,
13333    ) -> Result<Option<NativeAggResult>> {
13334        self.aggregate_native_inner(snapshot, column, conditions, agg, Some(control))
13335    }
13336
13337    fn aggregate_native_inner(
13338        &self,
13339        snapshot: Snapshot,
13340        column: Option<u16>,
13341        conditions: &[crate::query::Condition],
13342        agg: NativeAgg,
13343        control: Option<&crate::ExecutionControl>,
13344    ) -> Result<Option<NativeAggResult>> {
13345        execution_checkpoint(control, 0)?;
13346        if self.ttl.is_some() {
13347            return Ok(None);
13348        }
13349        // 1. Single clean run + no WHERE ⇒ MIN/MAX/COUNT(col) from page stats.
13350        if self.run_refs.len() == 1 && conditions.is_empty() {
13351            if let Some(res) = self.aggregate_from_stats(snapshot, column, agg)? {
13352                return Ok(Some(res));
13353            }
13354        }
13355        // 2. COUNT(*) ⇒ survivor count from the cursor's page plans, no decode.
13356        //    Overlay-only replicas (no sorted run yet) fall through to a
13357        //    visible-row scan so aggregate_native still serves correctly.
13358        if matches!(agg, NativeAgg::Count) && column.is_none() {
13359            if let Some(c) = self.scan_cursor(snapshot, Vec::new(), conditions)? {
13360                return Ok(Some(NativeAggResult::Count(c.remaining_rows() as u64)));
13361            }
13362            let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13363            return Ok(Some(NativeAggResult::Count(rows.len() as u64)));
13364        }
13365        // 3. Accumulate the projected column. COUNT(col) excludes nulls — the
13366        //    accumulator's count is the non-null count, which `pack_*` returns.
13367        let cid = match column {
13368            Some(c) => c,
13369            None => return Ok(None),
13370        };
13371        let ty = self.column_type(cid);
13372        if let Some(mut cursor) = self.scan_cursor(snapshot, vec![(cid, ty.clone())], conditions)? {
13373            execution_checkpoint(control, 0)?;
13374            return match ty {
13375                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13376                    let (count, sum, mn, mx) = accumulate_int(cursor.as_mut(), control)?;
13377                    Ok(Some(pack_int(agg, count, sum, mn, mx)))
13378                }
13379                TypeId::Float64 => {
13380                    let (count, sum, mn, mx) = accumulate_float(cursor.as_mut(), control)?;
13381                    Ok(Some(pack_float(agg, count, sum, mn, mx)))
13382                }
13383                _ => Ok(None),
13384            };
13385        }
13386        // Overlay-only / replica path: fold over visible rows in memory.
13387        let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13388        execution_checkpoint(control, 0)?;
13389        match ty {
13390            TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13391                let mut count = 0u64;
13392                let mut sum = 0i128;
13393                let mut mn = i64::MAX;
13394                let mut mx = i64::MIN;
13395                for row in &rows {
13396                    if let Some(Value::Int64(v)) = row.columns.get(&cid) {
13397                        count += 1;
13398                        sum += i128::from(*v);
13399                        mn = mn.min(*v);
13400                        mx = mx.max(*v);
13401                    }
13402                }
13403                Ok(Some(pack_int(agg, count, sum, mn, mx)))
13404            }
13405            TypeId::Float64 => {
13406                let mut count = 0u64;
13407                let mut sum = 0.0f64;
13408                let mut mn = f64::INFINITY;
13409                let mut mx = f64::NEG_INFINITY;
13410                for row in &rows {
13411                    if let Some(Value::Float64(v)) = row.columns.get(&cid) {
13412                        count += 1;
13413                        sum += *v;
13414                        mn = mn.min(*v);
13415                        mx = mx.max(*v);
13416                    }
13417                }
13418                Ok(Some(pack_float(agg, count, sum, mn, mx)))
13419            }
13420            _ => Ok(None),
13421        }
13422    }
13423
13424    /// Visible rows matching `conditions`, for overlay-only aggregate fallbacks.
13425    fn visible_rows_filtered(
13426        &self,
13427        snapshot: Snapshot,
13428        conditions: &[crate::query::Condition],
13429        control: Option<&crate::ExecutionControl>,
13430    ) -> Result<Vec<Row>> {
13431        let rows = if let Some(control) = control {
13432            self.visible_rows_controlled(snapshot, control)?
13433        } else {
13434            self.visible_rows(snapshot)?
13435        };
13436        if conditions.is_empty() {
13437            return Ok(rows);
13438        }
13439        Ok(rows
13440            .into_iter()
13441            .filter(|row| {
13442                conditions
13443                    .iter()
13444                    .all(|cond| condition_matches_row(cond, row, &self.schema))
13445            })
13446            .collect())
13447    }
13448
13449    /// Phase 7.1 metadata fast path: answer an unfiltered `MIN`/`MAX`/`COUNT(col)`
13450    /// straight from page `min`/`max`/`null_count` — no column decode. Returns
13451    /// `None` (caller decodes) for `COUNT(*)`/`SUM`/`AVG`, when exact stats are
13452    /// unavailable (multi-version run; [`Table::exact_column_stats`] gates this),
13453    /// or for a column whose stats omit `min`/`max` while it still holds values
13454    /// (e.g. an encrypted column) — returning `NULL` there would be a wrong
13455    /// answer, so we fall back to decoding.
13456    fn aggregate_from_stats(
13457        &self,
13458        snapshot: Snapshot,
13459        column: Option<u16>,
13460        agg: NativeAgg,
13461    ) -> Result<Option<NativeAggResult>> {
13462        let cid = match (agg, column) {
13463            (NativeAgg::Count | NativeAgg::Min | NativeAgg::Max, Some(c)) => c,
13464            _ => return Ok(None), // COUNT(*), SUM, AVG: not served from page stats
13465        };
13466        let Some(stats) = self.exact_column_stats(snapshot, &[cid])? else {
13467            return Ok(None);
13468        };
13469        let Some(cs) = stats.get(&cid) else {
13470            return Ok(None);
13471        };
13472        match agg {
13473            // COUNT(col) excludes NULLs: live rows minus the column's null count.
13474            NativeAgg::Count => Ok(Some(NativeAggResult::Count(
13475                self.live_count.saturating_sub(cs.null_count),
13476            ))),
13477            NativeAgg::Min | NativeAgg::Max => {
13478                let bound = if agg == NativeAgg::Min {
13479                    &cs.min
13480                } else {
13481                    &cs.max
13482                };
13483                match bound {
13484                    Some(Value::Int64(x)) => Ok(Some(NativeAggResult::Int(*x))),
13485                    Some(Value::Float64(x)) => Ok(Some(NativeAggResult::Float(*x))),
13486                    Some(_) => Ok(None), // unexpected stat type ⇒ decode
13487                    // No bound: a genuine SQL NULL only when the column is wholly
13488                    // null. Otherwise the stats are simply unavailable (encrypted),
13489                    // so decode for a correct answer.
13490                    None if cs.null_count >= self.live_count => Ok(Some(NativeAggResult::Null)),
13491                    None => Ok(None),
13492                }
13493            }
13494            _ => Ok(None),
13495        }
13496    }
13497
13498    /// Phase 7.1c: exact `COUNT(DISTINCT col)` from the bitmap index's partition
13499    /// cardinality — the number of distinct indexed values — with no scan. Each
13500    /// distinct value is one bitmap key; under the insert-only invariant (empty
13501    /// overlay, single run, `live_count == row_count`) every key has at least one
13502    /// live row, so the key count is exact. `NULL` is excluded from
13503    /// `COUNT(DISTINCT)`, so a null key (from an explicit `Value::Null` put) is
13504    /// discounted. Returns `None` (caller scans) without a bitmap index on the
13505    /// column or when the invariant does not hold.
13506    pub fn count_distinct_from_bitmap(&mut self, column_id: u16) -> Result<Option<u64>> {
13507        if self.ttl.is_some() {
13508            return Ok(None);
13509        }
13510        if !(self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1) {
13511            return Ok(None);
13512        }
13513        // A deferred bulk load leaves the bitmap unbuilt; complete it before
13514        // trusting its key count (same lazy contract as `query`/`flush`).
13515        self.ensure_indexes_complete()?;
13516        let reader = self.open_reader(self.run_refs[0].run_id)?;
13517        if self.live_count != reader.row_count() as u64 {
13518            return Ok(None);
13519        }
13520        let Some(bm) = self.bitmap.get(&column_id) else {
13521            return Ok(None); // no bitmap index ⇒ let the caller scan
13522        };
13523        let mut distinct = bm.value_count() as u64;
13524        // A null key (explicit `Value::Null`) is indexed but excluded from
13525        // COUNT(DISTINCT). (Schema-evolution-absent columns are never indexed.)
13526        if !bm.get(&Value::Null.encode_key()).is_empty() {
13527            distinct = distinct.saturating_sub(1);
13528        }
13529        Ok(Some(distinct))
13530    }
13531
13532    /// Incremental aggregate over the live table (Phase 8.3). For an append-only
13533    /// table, a warm cache entry (same `cache_key`) lets the result be refreshed
13534    /// by aggregating **only the newly inserted rows** (row-id watermark delta)
13535    /// and merging, instead of a full recompute. The caller supplies a stable
13536    /// `cache_key` (e.g. a hash of the SQL + projection); distinct queries must
13537    /// use distinct keys.
13538    ///
13539    /// Returns [`IncrementalAggResult`] with the merged state and whether the
13540    /// delta path was taken. A single `delete` (ever) disables the incremental
13541    /// path for the table, so correctness never relies on append-only behavior
13542    /// that deletes invalidate.
13543    pub fn aggregate_incremental(
13544        &mut self,
13545        cache_key: u64,
13546        conditions: &[crate::query::Condition],
13547        column: Option<u16>,
13548        agg: NativeAgg,
13549    ) -> Result<IncrementalAggResult> {
13550        self.aggregate_incremental_inner(cache_key, conditions, column, agg, None)
13551    }
13552
13553    pub fn aggregate_incremental_with_control(
13554        &mut self,
13555        cache_key: u64,
13556        conditions: &[crate::query::Condition],
13557        column: Option<u16>,
13558        agg: NativeAgg,
13559        control: &crate::ExecutionControl,
13560    ) -> Result<IncrementalAggResult> {
13561        self.aggregate_incremental_inner(cache_key, conditions, column, agg, Some(control))
13562    }
13563
13564    fn aggregate_incremental_inner(
13565        &mut self,
13566        cache_key: u64,
13567        conditions: &[crate::query::Condition],
13568        column: Option<u16>,
13569        agg: NativeAgg,
13570        control: Option<&crate::ExecutionControl>,
13571    ) -> Result<IncrementalAggResult> {
13572        execution_checkpoint(control, 0)?;
13573        let snap = self.snapshot();
13574        let cur_wm = self.allocator.current().0;
13575        let cur_epoch = snap.epoch.0;
13576        // The watermark equals the committed row count only when the memtable is
13577        // empty (every allocated row id is durably in a run). With pending
13578        // (uncommitted) writes the allocator is ahead of the visible set, so the
13579        // delta range would silently skip just-committed rows — disable the
13580        // incremental path entirely in that case. The mutable-run tier holding
13581        // un-spilled data also disables it (those rows aren't in a run yet).
13582        let incremental_ok = self.ttl.is_none()
13583            && !self.had_deletes
13584            && self.memtable.is_empty()
13585            && self.mutable_run.is_empty();
13586
13587        // Incremental path: append-only, no pending writes, warm cache, advanced
13588        // epoch.
13589        if incremental_ok {
13590            if let Some(cached) = self.agg_cache.get(&cache_key).cloned() {
13591                if cached.epoch == cur_epoch {
13592                    return Ok(IncrementalAggResult {
13593                        state: cached.state,
13594                        incremental: true,
13595                        delta_rows: 0,
13596                    });
13597                }
13598                if cached.epoch < cur_epoch && cached.watermark <= cur_wm {
13599                    let delta_len = cur_wm.saturating_sub(cached.watermark) as usize;
13600                    let mut delta_rids = Vec::with_capacity(delta_len);
13601                    for (index, row_id) in (cached.watermark..cur_wm).enumerate() {
13602                        execution_checkpoint(control, index)?;
13603                        delta_rids.push(row_id);
13604                    }
13605                    let delta_rows = self.rows_for_rids(&delta_rids, snap)?;
13606                    execution_checkpoint(control, 0)?;
13607                    let index_sets = self.resolve_index_conditions(conditions, snap)?;
13608                    let delta_state = agg_state_from_rows(
13609                        &delta_rows,
13610                        conditions,
13611                        &index_sets,
13612                        column,
13613                        agg,
13614                        &self.schema,
13615                        control,
13616                    )?;
13617                    let merged = cached.state.merge(delta_state);
13618                    let delta_n = delta_rids.len() as u64;
13619                    Arc::make_mut(&mut self.agg_cache).insert(
13620                        cache_key,
13621                        CachedAgg {
13622                            state: merged.clone(),
13623                            watermark: cur_wm,
13624                            epoch: cur_epoch,
13625                        },
13626                    );
13627                    return Ok(IncrementalAggResult {
13628                        state: merged,
13629                        incremental: true,
13630                        delta_rows: delta_n,
13631                    });
13632                }
13633            }
13634        }
13635
13636        // Cold path. For Count/Sum/Min/Max the fast vectorized cursor produces a
13637        // directly-seedable state; for Avg it returns only the mean (losing the
13638        // sum+count needed to merge a future delta), so Avg falls back to a
13639        // visible-rows scan that captures both.
13640        let cursor_ok =
13641            self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
13642        let state = if cursor_ok && agg != NativeAgg::Avg {
13643            match self.aggregate_native_inner(snap, column, conditions, agg, control)? {
13644                Some(result) => {
13645                    AggState::from_native(result, agg, column.map(|c| self.column_type(c)))
13646                }
13647                None => self.agg_state_full_scan(conditions, column, agg, snap, control)?,
13648            }
13649        } else {
13650            self.agg_state_full_scan(conditions, column, agg, snap, control)?
13651        };
13652        // Seed only when the watermark is meaningful (no pending writes).
13653        if incremental_ok {
13654            Arc::make_mut(&mut self.agg_cache).insert(
13655                cache_key,
13656                CachedAgg {
13657                    state: state.clone(),
13658                    watermark: cur_wm,
13659                    epoch: cur_epoch,
13660                },
13661            );
13662        }
13663        Ok(IncrementalAggResult {
13664            state,
13665            incremental: false,
13666            delta_rows: 0,
13667        })
13668    }
13669
13670    /// Full visible-rows scan → [`AggState`] (cold path; captures sum+count for
13671    /// correct Avg seeding).
13672    fn agg_state_full_scan(
13673        &self,
13674        conditions: &[crate::query::Condition],
13675        column: Option<u16>,
13676        agg: NativeAgg,
13677        snap: Snapshot,
13678        control: Option<&crate::ExecutionControl>,
13679    ) -> Result<AggState> {
13680        execution_checkpoint(control, 0)?;
13681        let rows = self.visible_rows(snap)?;
13682        execution_checkpoint(control, 0)?;
13683        let index_sets = self.resolve_index_conditions(conditions, snap)?;
13684        agg_state_from_rows(
13685            &rows,
13686            conditions,
13687            &index_sets,
13688            column,
13689            agg,
13690            &self.schema,
13691            control,
13692        )
13693    }
13694
13695    /// Resolve only the index-defined conditions (`Ann`/`SparseMatch`) to row-id
13696    /// sets for membership testing during row-wise aggregation.
13697    fn resolve_index_conditions(
13698        &self,
13699        conditions: &[crate::query::Condition],
13700        snapshot: Snapshot,
13701    ) -> Result<Vec<RowIdSet>> {
13702        use crate::query::Condition;
13703        let mut sets = Vec::new();
13704        for c in conditions {
13705            if matches!(
13706                c,
13707                Condition::Ann { .. }
13708                    | Condition::SparseMatch { .. }
13709                    | Condition::MinHashSimilar { .. }
13710            ) {
13711                sets.push(self.resolve_condition(c, snapshot)?);
13712            }
13713        }
13714        Ok(sets)
13715    }
13716
13717    fn column_type(&self, cid: u16) -> TypeId {
13718        self.schema
13719            .columns
13720            .iter()
13721            .find(|c| c.id == cid)
13722            .map(|c| c.ty.clone())
13723            .unwrap_or(TypeId::Bytes)
13724    }
13725
13726    /// Approximate `COUNT`/`SUM`/`AVG` over a filtered set, computed from the
13727    /// in-memory reservoir sample (Phase 8.2). Returns a point estimate plus a
13728    /// normal-theory confidence interval at the supplied z-score (1.96 ≈ 95 %).
13729    ///
13730    /// The WHERE predicates are evaluated **exactly** on each sampled row (so
13731    /// LIKE/FM and equality/range contribute no index bias); `Ann`/`SparseMatch`
13732    /// are index-defined and resolved once to a row-id set that sampled rows are
13733    /// tested against. `Ok(None)` when there is no usable sample.
13734    pub fn approx_aggregate(
13735        &mut self,
13736        conditions: &[crate::query::Condition],
13737        column: Option<u16>,
13738        agg: ApproxAgg,
13739        z: f64,
13740    ) -> Result<Option<ApproxResult>> {
13741        self.approx_aggregate_with_candidate_authorization(conditions, column, agg, z, None)
13742    }
13743
13744    /// Security-aware approximate aggregate. RLS is evaluated only for the
13745    /// reservoir candidates, and column masks are applied before aggregation.
13746    pub fn approx_aggregate_with_candidate_authorization(
13747        &mut self,
13748        conditions: &[crate::query::Condition],
13749        column: Option<u16>,
13750        agg: ApproxAgg,
13751        z: f64,
13752        authorization: Option<&crate::security::CandidateAuthorization<'_>>,
13753    ) -> Result<Option<ApproxResult>> {
13754        use crate::query::Condition;
13755        self.ensure_reservoir_complete()?;
13756        // Approx stats estimate the current live population. Prefer the table
13757        // snapshot, but if HLC dual-model visibility filters the entire
13758        // reservoir sample (epoch-only vs HLC-stamped), fall back to an
13759        // unbounded product snapshot so Count/Sum estimates remain available.
13760        let mut snapshot = self.snapshot();
13761        let n_pop = self.count();
13762        let sample_rids: Vec<u64> = self.reservoir.row_ids().to_vec();
13763        if sample_rids.is_empty() {
13764            return Ok(None);
13765        }
13766        // Materialize the live, non-deleted sampled rows.
13767        let mut live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13768        if live_sample.is_empty() {
13769            snapshot = Snapshot::unbounded();
13770            live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13771        }
13772        let s = live_sample.len();
13773        if s == 0 {
13774            return Ok(None);
13775        }
13776        let authorized = authorization
13777            .map(|authorization| {
13778                let candidates = live_sample.iter().map(|row| row.row_id).collect::<Vec<_>>();
13779                self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, None)
13780            })
13781            .transpose()?;
13782
13783        // Pre-resolve Ann/Sparse conditions (index-defined predicates) to row-id
13784        // sets; the per-row predicates below are evaluated exactly.
13785        let mut index_sets: Vec<RowIdSet> = Vec::new();
13786        for c in conditions {
13787            if matches!(
13788                c,
13789                Condition::Ann { .. }
13790                    | Condition::SparseMatch { .. }
13791                    | Condition::MinHashSimilar { .. }
13792            ) {
13793                index_sets.push(self.resolve_condition(c, snapshot)?);
13794            }
13795        }
13796
13797        // For Sum/Avg, gather the numeric column value of each passing row.
13798        let cid = match (agg, column) {
13799            (ApproxAgg::Count, _) => None,
13800            (_, Some(c)) => Some(c),
13801            _ => return Ok(None),
13802        };
13803        let mut passing_vals: Vec<f64> = Vec::with_capacity(s);
13804        for r in &live_sample {
13805            if authorized
13806                .as_ref()
13807                .is_some_and(|authorized| !authorized.contains(&r.row_id))
13808            {
13809                continue;
13810            }
13811            // Exact per-row predicate evaluation.
13812            if !conditions
13813                .iter()
13814                .all(|c| condition_matches_row(c, r, &self.schema))
13815            {
13816                continue;
13817            }
13818            // Ann/Sparse membership.
13819            if !index_sets.iter().all(|set| set.contains(r.row_id.0)) {
13820                continue;
13821            }
13822            if let Some(cid) = cid {
13823                let mut cells = r
13824                    .columns
13825                    .get(&cid)
13826                    .cloned()
13827                    .map(|value| vec![(cid, value)])
13828                    .unwrap_or_default();
13829                if let Some(authorization) = authorization {
13830                    authorization.security.apply_masks_to_cells(
13831                        authorization.table,
13832                        &mut cells,
13833                        authorization.principal,
13834                    );
13835                }
13836                if let Some(v) = as_f64(cells.first().map(|(_, value)| value)) {
13837                    passing_vals.push(v);
13838                } // nulls ⇒ excluded (matching SQL AVG/SUM null semantics)
13839            } else {
13840                passing_vals.push(0.0); // placeholder for COUNT
13841            }
13842        }
13843        let m = passing_vals.len();
13844
13845        let (point, half) = match agg {
13846            ApproxAgg::Count => {
13847                // Proportion estimate scaled to the population.
13848                let p = m as f64 / s as f64;
13849                let point = n_pop as f64 * p;
13850                let var = if s > 1 {
13851                    n_pop as f64 * n_pop as f64 * p * (1.0 - p) / s as f64
13852                        * (1.0 - s as f64 / n_pop as f64).max(0.0)
13853                } else {
13854                    0.0
13855                };
13856                (point, z * var.sqrt())
13857            }
13858            ApproxAgg::Sum => {
13859                // Horvitz–Thompson: each sampled row represents n_pop/s rows.
13860                let y: Vec<f64> = live_sample
13861                    .iter()
13862                    .map(|r| {
13863                        let passes_row = authorized
13864                            .as_ref()
13865                            .is_none_or(|authorized| authorized.contains(&r.row_id))
13866                            && conditions
13867                                .iter()
13868                                .all(|c| condition_matches_row(c, r, &self.schema))
13869                            && index_sets.iter().all(|set| set.contains(r.row_id.0));
13870                        if passes_row {
13871                            cid.and_then(|cid| {
13872                                let mut cells = r
13873                                    .columns
13874                                    .get(&cid)
13875                                    .cloned()
13876                                    .map(|value| vec![(cid, value)])
13877                                    .unwrap_or_default();
13878                                if let Some(authorization) = authorization {
13879                                    authorization.security.apply_masks_to_cells(
13880                                        authorization.table,
13881                                        &mut cells,
13882                                        authorization.principal,
13883                                    );
13884                                }
13885                                as_f64(cells.first().map(|(_, value)| value))
13886                            })
13887                            .unwrap_or(0.0)
13888                        } else {
13889                            0.0
13890                        }
13891                    })
13892                    .collect();
13893                let mean_y = y.iter().sum::<f64>() / s as f64;
13894                let point = n_pop as f64 * mean_y;
13895                let var = if s > 1 {
13896                    let ss: f64 = y.iter().map(|v| (v - mean_y).powi(2)).sum();
13897                    let var_y = ss / (s - 1) as f64;
13898                    n_pop as f64 * n_pop as f64 * var_y / s as f64
13899                        * (1.0 - s as f64 / n_pop as f64).max(0.0)
13900                } else {
13901                    0.0
13902                };
13903                (point, z * var.sqrt())
13904            }
13905            ApproxAgg::Avg => {
13906                if m == 0 {
13907                    return Ok(Some(ApproxResult {
13908                        point: 0.0,
13909                        ci_low: 0.0,
13910                        ci_high: 0.0,
13911                        n_population: n_pop,
13912                        n_sample_live: s,
13913                        n_passing: 0,
13914                    }));
13915                }
13916                let mean = passing_vals.iter().sum::<f64>() / m as f64;
13917                let half = if m > 1 {
13918                    let ss: f64 = passing_vals.iter().map(|v| (v - mean).powi(2)).sum();
13919                    let sd = (ss / (m - 1) as f64).sqrt();
13920                    let fpc = (1.0 - s as f64 / n_pop as f64).max(0.0);
13921                    z * sd / (m as f64).sqrt() * fpc.sqrt()
13922                } else {
13923                    0.0
13924                };
13925                (mean, half)
13926            }
13927        };
13928
13929        Ok(Some(ApproxResult {
13930            point,
13931            ci_low: point - half,
13932            ci_high: point + half,
13933            n_population: n_pop,
13934            n_sample_live: s,
13935            n_passing: m,
13936        }))
13937    }
13938
13939    /// Exact per-column statistics for the analytical aggregate fast path
13940    /// (Phase 7.1: `MIN`/`MAX`/`COUNT(col)` from page stats). Returns `None`
13941    /// unless the table is effectively insert-only at `snapshot` — empty
13942    /// memtable, a single sorted run, and `live_count == run.row_count()` — so
13943    /// the run's page `min`/`max`/`null_count` are exact (no tombstoned or
13944    /// superseded versions skew them). Under deletes/updates the caller falls
13945    /// back to scanning.
13946    pub fn exact_column_stats(
13947        &self,
13948        _snapshot: Snapshot,
13949        projection: &[u16],
13950    ) -> Result<Option<HashMap<u16, ColumnStat>>> {
13951        if self.ttl.is_some()
13952            || !(self.memtable.is_empty()
13953                && self.mutable_run.is_empty()
13954                && self.run_refs.len() == 1)
13955        {
13956            return Ok(None);
13957        }
13958        let reader = self.open_reader(self.run_refs[0].run_id)?;
13959        if self.live_count != reader.row_count() as u64 {
13960            return Ok(None);
13961        }
13962        let mut out = HashMap::new();
13963        for &cid in projection {
13964            let cdef = match self.schema.columns.iter().find(|c| c.id == cid) {
13965                Some(c) => c,
13966                None => continue,
13967            };
13968            // Absent column (schema evolution) ⇒ all rows null.
13969            let Some(stats) = reader.column_page_stats(cid) else {
13970                out.insert(
13971                    cid,
13972                    ColumnStat {
13973                        min: None,
13974                        max: None,
13975                        null_count: self.live_count,
13976                    },
13977                );
13978                continue;
13979            };
13980            let stat = match cdef.ty {
13981                TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13982                    agg_int(stats, crate::sorted_run::be_i64).map(|(mn, mx, n)| ColumnStat {
13983                        min: mn.map(Value::Int64),
13984                        max: mx.map(Value::Int64),
13985                        null_count: n,
13986                    })
13987                }
13988                TypeId::Float64 => {
13989                    agg_float(stats, crate::sorted_run::be_f64).map(|(mn, mx, n)| ColumnStat {
13990                        min: mn.map(Value::Float64),
13991                        max: mx.map(Value::Float64),
13992                        null_count: n,
13993                    })
13994                }
13995                _ => None,
13996            };
13997            if let Some(s) = stat {
13998                out.insert(cid, s);
13999            }
14000        }
14001        Ok(Some(out))
14002    }
14003
14004    pub fn dir(&self) -> &Path {
14005        &self.dir
14006    }
14007
14008    pub fn schema(&self) -> &Schema {
14009        &self.schema
14010    }
14011
14012    pub fn ann_index(&self, column_id: u16) -> Option<&crate::index::AnnIndex> {
14013        self.ann.get(&column_id)
14014    }
14015
14016    pub fn ann_index_mut(&mut self, column_id: u16) -> Option<&mut crate::index::AnnIndex> {
14017        self.ann.get_mut(&column_id)
14018    }
14019
14020    pub(crate) fn set_catalog_name(&mut self, name: String) {
14021        self.name = name;
14022    }
14023
14024    pub(crate) fn prepare_alter_column(
14025        &mut self,
14026        column_name: &str,
14027        change: &AlterColumn,
14028    ) -> Result<(ColumnDef, Option<Schema>)> {
14029        if !self.pending_rows.is_empty() || !self.pending_dels.is_empty() {
14030            return Err(MongrelError::InvalidArgument(
14031                "ALTER COLUMN requires committing staged writes first".into(),
14032            ));
14033        }
14034        let old = self
14035            .schema
14036            .columns
14037            .iter()
14038            .find(|c| c.name == column_name)
14039            .cloned()
14040            .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14041        let mut next = old.clone();
14042
14043        if let Some(name) = &change.name {
14044            let trimmed = name.trim();
14045            if trimmed.is_empty() {
14046                return Err(MongrelError::InvalidArgument(
14047                    "ALTER COLUMN name must not be empty".into(),
14048                ));
14049            }
14050            if trimmed != old.name && self.schema.columns.iter().any(|c| c.name == trimmed) {
14051                return Err(MongrelError::Schema(format!(
14052                    "column {trimmed} already exists"
14053                )));
14054            }
14055            next.name = trimmed.to_string();
14056        }
14057
14058        if let Some(ty) = &change.ty {
14059            next.ty = ty.clone();
14060        }
14061        if let Some(flags) = change.flags {
14062            validate_alter_column_flags(old.flags, flags)?;
14063            next.flags = flags;
14064        }
14065
14066        if let Some(default_change) = &change.default_value {
14067            next.default_value = default_change.clone();
14068        }
14069        if let Some(source_change) = &change.embedding_source {
14070            next.embedding_source = source_change.clone();
14071        }
14072
14073        validate_alter_column_type(&self.schema, &old, &next, self.has_stored_versions())?;
14074        if old.flags.contains(ColumnFlags::NULLABLE)
14075            && !next.flags.contains(ColumnFlags::NULLABLE)
14076            && self.column_has_nulls(old.id)?
14077        {
14078            return Err(MongrelError::InvalidArgument(format!(
14079                "column '{}' contains NULL values",
14080                old.name
14081            )));
14082        }
14083        if next == old {
14084            return Ok((next, None));
14085        }
14086        let mut schema = self.schema.clone();
14087        let index = schema
14088            .columns
14089            .iter()
14090            .position(|column| column.id == next.id)
14091            .ok_or_else(|| MongrelError::Schema(format!("unknown column {}", next.id)))?;
14092        schema.columns[index] = next.clone();
14093        schema.schema_id = schema
14094            .schema_id
14095            .checked_add(1)
14096            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14097        schema.validate_auto_increment()?;
14098        schema.validate_defaults()?;
14099        Ok((next, Some(schema)))
14100    }
14101
14102    pub(crate) fn apply_altered_schema_prepared(&mut self, schema: Schema) {
14103        self.schema = schema;
14104        self.auto_inc = resolve_auto_inc(&self.schema);
14105        self.column_keys = build_column_keys(self.kek.as_deref(), &self.schema);
14106        self.clear_result_cache();
14107        self.refresh_active_run_fingerprint();
14108        let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
14109    }
14110
14111    /// Publish one hidden index artifact with its prepared schema. Callers
14112    /// hold the final commit barrier and have already verified that
14113    /// `artifact` covers the table's exact current epoch.
14114    pub(crate) fn publish_index_schema_change(
14115        &mut self,
14116        schema: Schema,
14117        artifact: SecondaryIndexArtifact,
14118    ) -> Result<()> {
14119        self.apply_altered_schema_prepared(schema);
14120        self.prune_index_maps_to_schema();
14121        match artifact {
14122            SecondaryIndexArtifact::Bitmap(column_id, index) => {
14123                self.bitmap.insert(column_id, index);
14124            }
14125            SecondaryIndexArtifact::LearnedRange(column_id, index) => {
14126                Arc::make_mut(&mut self.learned_range).insert(column_id, index);
14127            }
14128            SecondaryIndexArtifact::Fm(column_id, index) => {
14129                self.fm.insert(column_id, *index);
14130            }
14131            SecondaryIndexArtifact::Ann(column_id, index) => {
14132                self.ann.insert(column_id, *index);
14133            }
14134            SecondaryIndexArtifact::Sparse(column_id, index) => {
14135                self.sparse.insert(column_id, index);
14136            }
14137            SecondaryIndexArtifact::MinHash(column_id, index) => {
14138                self.minhash.insert(column_id, index);
14139            }
14140        }
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        // The catalog + rows are authoritative. A later flush/checkpoint
14147        // persists this derived generation without extending the write fence.
14148        self.invalidate_index_checkpoint();
14149        Ok(())
14150    }
14151
14152    /// Drop one secondary index from the live maps without rewriting table
14153    /// rows. Installs `schema` (already missing the dropped index), prunes
14154    /// maps, publishes a new generation, and invalidates the derived
14155    /// global-index checkpoint so reopen rebuilds from the authoritative
14156    /// schema + rows.
14157    pub(crate) fn publish_index_drop(&mut self, schema: Schema) -> Result<()> {
14158        self.apply_altered_schema_prepared(schema);
14159        self.prune_index_maps_to_schema();
14160        self.indexes_complete = true;
14161        self.seal_generations();
14162        let view = Arc::new(self.capture_read_generation());
14163        self.published.store(Arc::clone(&view));
14164        checkpoint_current_schema(self)?;
14165        // Dropped-index maps no longer match any prior checkpoint image.
14166        self.invalidate_index_checkpoint();
14167        Ok(())
14168    }
14169
14170    fn prune_index_maps_to_schema(&mut self) {
14171        let keep_bitmap: std::collections::HashSet<u16> = self
14172            .schema
14173            .indexes
14174            .iter()
14175            .filter(|index| index.kind == IndexKind::Bitmap)
14176            .map(|index| index.column_id)
14177            .collect();
14178        let keep_ann: std::collections::HashSet<u16> = self
14179            .schema
14180            .indexes
14181            .iter()
14182            .filter(|index| index.kind == IndexKind::Ann)
14183            .map(|index| index.column_id)
14184            .collect();
14185        let keep_fm: std::collections::HashSet<u16> = self
14186            .schema
14187            .indexes
14188            .iter()
14189            .filter(|index| index.kind == IndexKind::FmIndex)
14190            .map(|index| index.column_id)
14191            .collect();
14192        let keep_sparse: std::collections::HashSet<u16> = self
14193            .schema
14194            .indexes
14195            .iter()
14196            .filter(|index| index.kind == IndexKind::Sparse)
14197            .map(|index| index.column_id)
14198            .collect();
14199        let keep_minhash: std::collections::HashSet<u16> = self
14200            .schema
14201            .indexes
14202            .iter()
14203            .filter(|index| index.kind == IndexKind::MinHash)
14204            .map(|index| index.column_id)
14205            .collect();
14206        let keep_learned: std::collections::HashSet<u16> = self
14207            .schema
14208            .indexes
14209            .iter()
14210            .filter(|index| index.kind == IndexKind::LearnedRange)
14211            .map(|index| index.column_id)
14212            .collect();
14213        self.bitmap
14214            .retain(|column_id, _| keep_bitmap.contains(column_id));
14215        self.ann.retain(|column_id, _| keep_ann.contains(column_id));
14216        self.fm.retain(|column_id, _| keep_fm.contains(column_id));
14217        self.sparse
14218            .retain(|column_id, _| keep_sparse.contains(column_id));
14219        self.minhash
14220            .retain(|column_id, _| keep_minhash.contains(column_id));
14221        {
14222            let learned = Arc::make_mut(&mut self.learned_range);
14223            learned.retain(|column_id, _| keep_learned.contains(column_id));
14224        }
14225    }
14226
14227    pub(crate) fn checkpoint_altered_schema(&mut self) -> Result<()> {
14228        checkpoint_current_schema(self)
14229    }
14230
14231    pub fn alter_column(&mut self, column_name: &str, change: AlterColumn) -> Result<ColumnDef> {
14232        self.ensure_writable()?;
14233        let previous_schema = self.schema.clone();
14234        let (column, schema) = self.prepare_alter_column(column_name, &change)?;
14235        if let Some(schema) = schema {
14236            self.apply_altered_schema_prepared(schema);
14237            self.checkpoint_standalone_schema_change(previous_schema)?;
14238        }
14239        Ok(column)
14240    }
14241
14242    fn column_has_nulls(&mut self, column_id: u16) -> Result<bool> {
14243        if self.live_count == 0 {
14244            return Ok(false);
14245        }
14246        let snap = self.snapshot();
14247        let columns = self.visible_columns_native(snap, Some(&[column_id]))?;
14248        Ok(columns
14249            .first()
14250            .map(|(_, col)| col.null_count(col.len()) != 0)
14251            .unwrap_or(true))
14252    }
14253
14254    fn has_stored_versions(&self) -> bool {
14255        !self.memtable.is_empty()
14256            || !self.mutable_run.is_empty()
14257            || self.run_refs.iter().any(|r| r.row_count > 0)
14258            || !self.retiring.is_empty()
14259    }
14260
14261    /// Add a column to the schema (schema evolution). Existing runs simply read
14262    /// back as null for the new column until re-written. Persists the new schema
14263    /// and manifest. The caller supplies the full [`ColumnFlags`] so migrations
14264    /// can add `PRIMARY KEY` / `AUTO_INCREMENT` columns correctly.
14265    pub fn add_column(
14266        &mut self,
14267        name: &str,
14268        ty: TypeId,
14269        flags: ColumnFlags,
14270        default_value: Option<crate::schema::DefaultExpr>,
14271    ) -> Result<u16> {
14272        self.add_column_with_id(name, ty, flags, default_value, None)
14273    }
14274
14275    pub fn add_column_with_id(
14276        &mut self,
14277        name: &str,
14278        ty: TypeId,
14279        flags: ColumnFlags,
14280        default_value: Option<crate::schema::DefaultExpr>,
14281        requested_id: Option<u16>,
14282    ) -> Result<u16> {
14283        self.ensure_writable()?;
14284        let previous_schema = self.schema.clone();
14285        let (column, schema) =
14286            self.prepare_add_column(name, ty, flags, default_value, requested_id)?;
14287        self.apply_altered_schema_prepared(schema);
14288        self.checkpoint_standalone_schema_change(previous_schema)?;
14289        Ok(column.id)
14290    }
14291
14292    pub(crate) fn prepare_add_column(
14293        &mut self,
14294        name: &str,
14295        ty: TypeId,
14296        flags: ColumnFlags,
14297        default_value: Option<crate::schema::DefaultExpr>,
14298        requested_id: Option<u16>,
14299    ) -> Result<(ColumnDef, Schema)> {
14300        self.ensure_writable()?;
14301        if self.schema.columns.iter().any(|c| c.name == name) {
14302            return Err(MongrelError::Schema(format!(
14303                "column {name} already exists"
14304            )));
14305        }
14306        let id = if let Some(id) = requested_id.filter(|id| *id != 0) {
14307            if self.schema.columns.iter().any(|c| c.id == id) {
14308                return Err(MongrelError::Schema(format!(
14309                    "column id {id} already exists"
14310                )));
14311            }
14312            id
14313        } else {
14314            self.schema
14315                .columns
14316                .iter()
14317                .map(|c| c.id)
14318                .max()
14319                .unwrap_or(0)
14320                .checked_add(1)
14321                .ok_or_else(|| MongrelError::Schema("column id space exhausted".into()))?
14322        };
14323        let column = ColumnDef {
14324            id,
14325            name: name.to_string(),
14326            ty,
14327            flags,
14328            default_value,
14329            embedding_source: None,
14330        };
14331        let mut next_schema = self.schema.clone();
14332        next_schema.columns.push(column.clone());
14333        next_schema.schema_id = next_schema
14334            .schema_id
14335            .checked_add(1)
14336            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14337        next_schema.validate_auto_increment()?;
14338        next_schema.validate_defaults()?;
14339        Ok((column, next_schema))
14340    }
14341
14342    /// Declare a `LearnedRange` (PGM) index on an existing numeric column and
14343    /// build it immediately from the current sorted run (Phase 13.3). After
14344    /// this, `Condition::Range` / `Condition::RangeF64` on that column resolve
14345    /// survivors sub-linearly (O(log segments + log ε)) instead of scanning the
14346    /// full column.
14347    ///
14348    /// Requires exactly one sorted run (call after `flush`). The index is
14349    /// rebuilt automatically on subsequent flushes.
14350    pub fn add_learned_range_index(&mut self, column_name: &str) -> Result<()> {
14351        self.ensure_writable()?;
14352        let cid = self
14353            .schema
14354            .columns
14355            .iter()
14356            .find(|c| c.name == column_name)
14357            .map(|c| c.id)
14358            .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14359        let ty = self
14360            .schema
14361            .columns
14362            .iter()
14363            .find(|c| c.id == cid)
14364            .map(|c| c.ty.clone())
14365            .unwrap_or(TypeId::Int64);
14366        if !matches!(
14367            ty,
14368            TypeId::Int64 | TypeId::Float64 | TypeId::TimestampNanos | TypeId::Date32
14369        ) {
14370            return Err(MongrelError::Schema(format!(
14371                "LearnedRange requires a numeric column; {column_name} is {ty:?}"
14372            )));
14373        }
14374        if self
14375            .schema
14376            .indexes
14377            .iter()
14378            .any(|i| i.column_id == cid && i.kind == IndexKind::LearnedRange)
14379        {
14380            return Ok(()); // already declared
14381        }
14382        let previous_schema = self.schema.clone();
14383        let previous_learned_range = Arc::clone(&self.learned_range);
14384        let mut next_schema = previous_schema.clone();
14385        next_schema.indexes.push(IndexDef {
14386            name: format!("{}_learned_range", column_name),
14387            column_id: cid,
14388            kind: IndexKind::LearnedRange,
14389            predicate: None,
14390            options: Default::default(),
14391        });
14392        next_schema.schema_id = next_schema
14393            .schema_id
14394            .checked_add(1)
14395            .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14396        self.apply_altered_schema_prepared(next_schema);
14397        if let Err(error) = self.build_learned_ranges() {
14398            self.apply_altered_schema_prepared(previous_schema);
14399            self.learned_range = previous_learned_range;
14400            return Err(error);
14401        }
14402        if let Err(error) = self.checkpoint_standalone_schema_change(previous_schema) {
14403            if !matches!(
14404                &error,
14405                MongrelError::DurableCommit { .. } | MongrelError::CommitOutcomeUnknown { .. }
14406            ) {
14407                self.learned_range = previous_learned_range;
14408            }
14409            return Err(error);
14410        }
14411        Ok(())
14412    }
14413
14414    fn checkpoint_standalone_schema_change(&mut self, previous_schema: Schema) -> Result<()> {
14415        let mut schema_published = false;
14416        let schema_result = match self._root_guard.as_deref() {
14417            Some(root) => write_schema_durable_with_after(root, &self.schema, || {
14418                schema_published = true;
14419            }),
14420            None => write_schema_with_after(&self.dir, &self.schema, || {
14421                schema_published = true;
14422            }),
14423        };
14424        if schema_result.is_err() && !schema_published {
14425            self.apply_altered_schema_prepared(previous_schema);
14426            return schema_result;
14427        }
14428
14429        let manifest_result = self.persist_manifest(self.current_epoch());
14430        match (schema_result, manifest_result) {
14431            (_, Ok(())) => Ok(()),
14432            (Ok(()), Err(error)) => {
14433                self.poison_after_maintenance_publish_failure();
14434                Err(MongrelError::DurableCommit {
14435                    epoch: self.current_epoch().0,
14436                    message: format!(
14437                        "schema is durable but matching manifest publication failed: {error}"
14438                    ),
14439                })
14440            }
14441            (Err(schema_error), Err(manifest_error)) => {
14442                self.poison_after_maintenance_publish_failure();
14443                Err(MongrelError::CommitOutcomeUnknown {
14444                    epoch: self.current_epoch().0,
14445                    message: format!(
14446                        "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
14447                    ),
14448                })
14449            }
14450        }
14451    }
14452
14453    /// Tuning knob for the WAL auto-sync threshold. A no-op on a mounted table
14454    /// (the shared WAL's durability is governed by the group-commit coordinator).
14455    pub fn set_sync_byte_threshold(&mut self, threshold: u64) {
14456        self.sync_byte_threshold = threshold;
14457        if let WalSink::Private(w) = &mut self.wal {
14458            w.set_sync_byte_threshold(threshold);
14459        }
14460    }
14461
14462    /// Flush all live page-cache entries to the persistent `_cache/` backing
14463    /// directory (best-effort). Useful before a clean shutdown so hot pages
14464    /// survive restart.
14465    pub fn page_cache_flush(&self) {
14466        self.page_cache.flush_to_disk();
14467    }
14468
14469    /// Number of entries currently in the shared page cache (diagnostic).
14470    pub fn page_cache_len(&self) -> usize {
14471        self.page_cache.len()
14472    }
14473
14474    /// Number of entries currently in the shared decoded-page cache (Phase
14475    /// 15.4 diagnostic).
14476    pub fn decoded_cache_len(&self) -> usize {
14477        self.decoded_cache.len()
14478    }
14479
14480    /// Drain the live memtable (prototype/testing helper used by the flush path
14481    /// demos). Prefer [`Table::flush`] for the durable path.
14482    pub fn drain_memtable_sorted(&mut self) -> Vec<Row> {
14483        self.memtable.drain_sorted()
14484    }
14485
14486    pub(crate) fn run_path(&self, run_id: u64) -> PathBuf {
14487        self.runs_dir().join(format!("r-{run_id}.sr"))
14488    }
14489
14490    pub(crate) fn create_run_file(&self, run_id: u64) -> Result<Option<std::fs::File>> {
14491        match self.runs_root.as_deref() {
14492            Some(root) => Ok(Some(root.create_regular_new(format!("r-{run_id}.sr"))?)),
14493            None => Ok(None),
14494        }
14495    }
14496
14497    pub(crate) fn create_run_entry(&self, name: &Path) -> Result<Option<std::fs::File>> {
14498        match self.runs_root.as_deref() {
14499            Some(root) => Ok(Some(root.create_regular_new(name)?)),
14500            None => Ok(None),
14501        }
14502    }
14503
14504    pub(crate) fn release_run_reader(&self, run_id: u128) {
14505        self.run_readers.lock().remove(&run_id);
14506    }
14507
14508    pub(crate) fn remove_run_entry(&self, name: &Path) -> Result<()> {
14509        if let Some(run_id) = Self::run_id_from_entry_name(name) {
14510            self.release_run_reader(run_id);
14511        }
14512        match self.runs_root.as_deref() {
14513            Some(root) => match root.remove_file(name) {
14514                Ok(()) => Ok(()),
14515                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14516                Err(error) => Err(error.into()),
14517            },
14518            None => match std::fs::remove_file(self.runs_dir().join(name)) {
14519                Ok(()) => Ok(()),
14520                Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14521                Err(error) => Err(error.into()),
14522            },
14523        }
14524    }
14525
14526    pub(crate) fn publish_run_entry(&self, source: &Path, destination: &Path) -> Result<()> {
14527        match self.runs_root.as_deref() {
14528            Some(root) => root
14529                .rename_file_new(source, destination)
14530                .map_err(Into::into),
14531            None => crate::durable_file::rename(
14532                &self.runs_dir().join(source),
14533                &self.runs_dir().join(destination),
14534            )
14535            .map_err(Into::into),
14536        }
14537    }
14538
14539    pub(crate) fn active_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14540        self.run_refs.iter().map(|run| run.run_id)
14541    }
14542
14543    pub(crate) fn table_dir(&self) -> &Path {
14544        &self.dir
14545    }
14546
14547    pub(crate) fn schema_ref(&self) -> &crate::schema::Schema {
14548        &self.schema
14549    }
14550
14551    pub(crate) fn alloc_run_id(&mut self) -> Result<u64> {
14552        let id = self.next_run_id;
14553        self.next_run_id = self
14554            .next_run_id
14555            .checked_add(1)
14556            .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))?;
14557        Ok(id)
14558    }
14559
14560    pub(crate) fn link_run(&mut self, run_ref: crate::manifest::RunRef) {
14561        self.run_refs.push(run_ref);
14562        self.refresh_active_run_fingerprint();
14563    }
14564
14565    /// Link a spilled run found during shared-WAL recovery (spec §8.5).
14566    /// **Idempotent**: if the run is already in the manifest (the publish phase
14567    /// persisted it before the crash, or this is a clean reopen with the
14568    /// `TxnCommit` still in the WAL) this is a no-op returning `false`, so the
14569    /// caller never double-links or double-counts. Otherwise — a crash *after*
14570    /// the commit fsync but *before* publish persisted the manifest — the run is
14571    /// Enqueue a compaction-superseded run for retention-gated deletion (spec
14572    /// §6.4). The file stays on disk until [`Self::reap_retiring`] removes it
14573    /// once `min_active_snapshot` has advanced past `retire_epoch`.
14574    pub(crate) fn retire_run(&mut self, run_id: u128, retire_epoch: u64) {
14575        self.retiring.push(crate::manifest::RetiredRun {
14576            run_id,
14577            retire_epoch,
14578        });
14579    }
14580
14581    /// Physically delete retired run files whose `retire_epoch` no pinned reader
14582    /// can still need (`min_active >= retire_epoch`), drop them from the queue,
14583    /// and persist the manifest if anything changed. Returns the count reaped.
14584    pub(crate) fn reap_retiring(
14585        &mut self,
14586        min_active: Epoch,
14587        backup_pinned: &std::collections::HashSet<u128>,
14588    ) -> Result<usize> {
14589        if self.retiring.is_empty() {
14590            return Ok(0);
14591        }
14592        let mut reaped = 0;
14593        let mut kept: Vec<crate::manifest::RetiredRun> = Vec::new();
14594        // Delete-then-persist is crash-idempotent: if we crash after unlinking
14595        // some files but before persisting, the manifest still lists them in
14596        // `retiring`; the next `reap_retiring` re-issues `remove_file` (the
14597        // error is ignored) and `check()` excludes `retiring` ids from orphan
14598        // detection, so the lingering entries are harmless until then.
14599        for r in std::mem::take(&mut self.retiring) {
14600            if min_active.0 >= r.retire_epoch && !backup_pinned.contains(&r.run_id) {
14601                let _ = self.remove_run_entry(Path::new(&format!("r-{}.sr", r.run_id)));
14602                reaped += 1;
14603            } else {
14604                kept.push(r);
14605            }
14606        }
14607        self.retiring = kept;
14608        if reaped > 0 {
14609            self.persist_manifest(self.current_epoch())?;
14610        }
14611        Ok(reaped)
14612    }
14613
14614    pub(crate) fn has_reapable_retiring(
14615        &self,
14616        min_active: Epoch,
14617        backup_pinned: &std::collections::HashSet<u128>,
14618    ) -> bool {
14619        self.retiring
14620            .iter()
14621            .any(|run| min_active.0 >= run.retire_epoch && !backup_pinned.contains(&run.run_id))
14622    }
14623
14624    pub(crate) fn recover_spilled_run(&mut self, run_ref: crate::manifest::RunRef) -> bool {
14625        if self.run_refs.iter().any(|r| r.run_id == run_ref.run_id) {
14626            return false;
14627        }
14628        self.live_count = self.live_count.saturating_add(run_ref.row_count);
14629        self.run_refs.push(run_ref);
14630        self.refresh_active_run_fingerprint();
14631        self.indexes_complete = false;
14632        true
14633    }
14634
14635    pub(crate) fn kek_ref(&self) -> Option<&Arc<Kek>> {
14636        self.kek.as_ref()
14637    }
14638
14639    /// Borrow the immutable reader for `run_id`, opening it once per table.
14640    fn with_run_reader<T>(
14641        &self,
14642        run_id: u128,
14643        body: impl FnOnce(&mut RunReader) -> T,
14644    ) -> Result<T> {
14645        let mut cache = self.run_readers.lock();
14646        if let Some(reader) = cache.get_mut(&run_id) {
14647            return Ok(body(reader));
14648        }
14649        drop(cache);
14650        let reader = self.open_reader(run_id)?;
14651        cache = self.run_readers.lock();
14652        // Keep the bounded warm set large enough for the 256-run scaling
14653        // contract; clearing it on every 65th run forces random point reads
14654        // to reopen readers continuously.
14655        if cache.len() >= 256 && !cache.contains_key(&run_id) {
14656            cache.clear();
14657        }
14658        Ok(body(cache.entry(run_id).or_insert(reader)))
14659    }
14660
14661    fn run_id_from_entry_name(name: &Path) -> Option<u128> {
14662        let file_name = name.file_name()?.to_str()?;
14663        file_name
14664            .strip_prefix("r-")?
14665            .strip_suffix(".sr")?
14666            .parse()
14667            .ok()
14668    }
14669
14670    pub(crate) fn open_reader(&self, run_id: u128) -> Result<RunReader> {
14671        let mut reader = match self.runs_root.as_deref() {
14672            Some(root) => RunReader::open_file_with_cache(
14673                root.open_regular(format!("r-{run_id}.sr"))?,
14674                self.schema.clone(),
14675                self.kek.clone(),
14676                Some(self.page_cache.clone()),
14677                Some(self.decoded_cache.clone()),
14678                self.table_id,
14679                Some(&self.verified_runs),
14680                None,
14681            )?,
14682            None => RunReader::open_with_cache(
14683                self.dir.join(RUNS_DIR).join(format!("r-{run_id}.sr")),
14684                self.schema.clone(),
14685                self.kek.clone(),
14686                Some(self.page_cache.clone()),
14687                Some(self.decoded_cache.clone()),
14688                self.table_id,
14689                Some(&self.verified_runs),
14690            )?,
14691        };
14692        // Overlay the real commit epoch for uniform-epoch (large-txn spill) runs:
14693        // their stored `_epoch` is a placeholder; the manifest RunRef carries the
14694        // assigned epoch. A no-op for ordinary runs.
14695        if let Some(rr) = self.run_refs.iter().find(|r| r.run_id == run_id) {
14696            reader.set_uniform_epoch(Epoch(rr.epoch_created));
14697        }
14698        Ok(reader)
14699    }
14700
14701    pub(crate) fn run_refs(&self) -> &[RunRef] {
14702        &self.run_refs
14703    }
14704
14705    pub(crate) fn retiring_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14706        self.retiring.iter().map(|run| run.run_id)
14707    }
14708
14709    pub(crate) fn runs_dir(&self) -> PathBuf {
14710        self.runs_root
14711            .as_deref()
14712            .and_then(|root| root.io_path().ok())
14713            .unwrap_or_else(|| self.dir.join(RUNS_DIR))
14714    }
14715
14716    pub(crate) fn wal_dir(&self) -> PathBuf {
14717        self.dir.join(WAL_DIR)
14718    }
14719
14720    pub(crate) fn set_run_refs(&mut self, refs: Vec<RunRef>) {
14721        self.run_refs = refs;
14722        self.refresh_active_run_fingerprint();
14723        self.refresh_run_row_id_ranges();
14724    }
14725
14726    /// `(min_row_id, max_row_id)` for the given run, when known. Used by
14727    /// compaction to enforce L1+ disjointness without re-opening every
14728    /// existing run header.
14729    pub(crate) fn run_row_id_range(&self, run_id: u128) -> Option<(u64, u64)> {
14730        self.run_row_id_ranges.get(&run_id).copied()
14731    }
14732
14733    /// Populate `run_row_id_ranges` from each run's on-disk header so
14734    /// [`Self::get`] can skip runs that cannot contain a given RowId.
14735    pub(crate) fn refresh_run_row_id_ranges(&mut self) {
14736        let mut ranges = HashMap::with_capacity(self.run_refs.len());
14737        for rr in &self.run_refs {
14738            if let Ok(reader) = self.open_reader(rr.run_id) {
14739                let h = reader.header();
14740                ranges.insert(rr.run_id, (h.min_row_id, h.max_row_id));
14741            }
14742        }
14743        self.run_row_id_ranges = ranges;
14744    }
14745
14746    pub(crate) fn compaction_zstd_level(&self) -> i32 {
14747        self.compaction_zstd_level
14748    }
14749
14750    pub(crate) fn kek(&self) -> Option<Arc<Kek>> {
14751        self.kek.clone()
14752    }
14753
14754    /// The index-checkpoint DEK (KEK-derived) for encrypted tables; `None` for
14755    /// plaintext tables. The checkpoint embeds index keys / PGM segment values
14756    /// derived from user data, so an encrypted table must encrypt it at rest.
14757    fn idx_dek(&self) -> Option<Zeroizing<[u8; DEK_LEN]>> {
14758        self.kek.as_ref().map(|k| k.derive_idx_key())
14759    }
14760
14761    /// Manifest (and other DB-wide metadata) meta DEK, derived from the KEK so
14762    /// the on-disk manifest is encrypted + authenticated at rest for encrypted
14763    /// tables. `None` for plaintext.
14764    fn manifest_meta_dek(&self) -> Option<[u8; DEK_LEN]> {
14765        self.kek.as_ref().map(|k| *k.derive_meta_key())
14766    }
14767
14768    /// `(column_id, scheme)` for every ENCRYPTED_INDEXABLE column — passed to
14769    /// the run writer so each run's descriptor records the column keys.
14770    pub(crate) fn indexable_column_specs(&self) -> Vec<(u16, u8)> {
14771        self.column_keys
14772            .iter()
14773            .map(|(&id, &(_, scheme))| (id, scheme))
14774            .collect()
14775    }
14776
14777    /// Tokenize a value for an ENCRYPTED_INDEXABLE column (HMAC-eq or OPE-range,
14778    /// per the column's scheme). Returns `None` for plaintext columns. Indexes
14779    /// over such columns store tokens, and queries tokenize literals the same
14780    /// way — so lookups never decrypt the stored (encrypted) page payloads.
14781    fn tokenize_value(&self, column_id: u16, v: &Value) -> Option<Value> {
14782        self.tokenize_value_enc(column_id, v)
14783    }
14784
14785    fn tokenize_value_enc(&self, column_id: u16, v: &Value) -> Option<Value> {
14786        use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
14787        let (key, scheme) = self.column_keys.get(&column_id)?;
14788        let token: Vec<u8> = match (*scheme, v) {
14789            (SCHEME_HMAC_EQ, _) => hmac_token(key, &v.encode_key()).to_vec(),
14790            (_, Value::Int64(x)) => ope_token_i64(key, *x).to_vec(),
14791            (_, Value::Float64(x)) => ope_token_f64(key, *x).to_vec(),
14792            _ => hmac_token(key, &v.encode_key()).to_vec(),
14793        };
14794        Some(Value::Bytes(token))
14795    }
14796
14797    /// Encoded index key for a `Value`, tokenized for HMAC-eq columns.
14798    fn index_lookup_key(&self, column_id: u16, v: &Value) -> Vec<u8> {
14799        self.index_lookup_key_bytes(column_id, &v.encode_key())
14800    }
14801
14802    /// Tokenize an already-encoded lookup key (equality queries pass the
14803    /// encoded search value; HMAC-eq columns wrap it under the column key).
14804    fn index_lookup_key_bytes(&self, column_id: u16, encoded: &[u8]) -> Vec<u8> {
14805        {
14806            use crate::encryption::{hmac_token, SCHEME_HMAC_EQ};
14807            if let Some((key, scheme)) = self.column_keys.get(&column_id) {
14808                if *scheme == SCHEME_HMAC_EQ {
14809                    return hmac_token(key, encoded).to_vec();
14810                }
14811            }
14812        }
14813        let _ = column_id;
14814        encoded.to_vec()
14815    }
14816}
14817
14818fn native_int64_strictly_increasing(col: &columnar::NativeColumn, n: usize) -> bool {
14819    let columnar::NativeColumn::Int64 { data, validity } = col else {
14820        return false;
14821    };
14822    if data.len() < n || !columnar::all_non_null(validity, n) {
14823        return false;
14824    }
14825    data.iter()
14826        .take(n)
14827        .zip(data.iter().skip(1))
14828        .all(|(a, b)| a < b)
14829}
14830
14831/// Exact aggregate of a column's page stats into a min/max/null_count triple
14832/// (Phase 7.1). Only meaningful when the owning table is insert-only, which
14833/// [`Table::exact_column_stats`] gates on.
14834#[derive(Debug, Clone)]
14835pub struct ColumnStat {
14836    pub min: Option<Value>,
14837    pub max: Option<Value>,
14838    pub null_count: u64,
14839}
14840
14841/// A supported native aggregate (Phase 7.2).
14842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14843pub enum NativeAgg {
14844    Count,
14845    Sum,
14846    Min,
14847    Max,
14848    Avg,
14849}
14850
14851/// The typed result of a [`NativeAgg`] over a column.
14852#[derive(Debug, Clone, PartialEq)]
14853pub enum NativeAggResult {
14854    Count(u64),
14855    Int(i64),
14856    Float(f64),
14857    /// No non-null inputs (SUM/MIN/MAX/AVG over zero rows ⇒ SQL NULL).
14858    Null,
14859}
14860
14861/// A supported approximate aggregate over the reservoir sample (Phase 8.2).
14862#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14863pub enum ApproxAgg {
14864    Count,
14865    Sum,
14866    Avg,
14867}
14868
14869/// Point estimate with a normal-theory confidence interval from the reservoir
14870/// sample (Phase 8.2). `ci_low`/`ci_high` bracket `point` at the requested
14871/// z-score; the interval has zero width when the sample equals the whole table.
14872#[derive(Debug, Clone)]
14873pub struct ApproxResult {
14874    /// Point estimate of the aggregate.
14875    pub point: f64,
14876    /// Lower bound (`point − z·SE`).
14877    pub ci_low: f64,
14878    /// Upper bound (`point + z·SE`).
14879    pub ci_high: f64,
14880    /// Live population size (the table's `count()`).
14881    pub n_population: u64,
14882    /// Live rows in the sample (`≤` reservoir capacity).
14883    pub n_sample_live: usize,
14884    /// Sampled rows passing the WHERE predicate.
14885    pub n_passing: usize,
14886}
14887
14888/// A mergeable running aggregate state (Phase 8.3). Two states over disjoint
14889/// row sets `merge` into the state over their union, so a cached analytical
14890/// aggregate can be updated by merging in only the delta (newly inserted rows)
14891/// instead of a full recompute.
14892#[derive(Debug, Clone, PartialEq)]
14893pub enum AggState {
14894    /// `COUNT(*)` or `COUNT(col)` over `n` matching rows.
14895    Count(u64),
14896    /// Int64 `SUM`: running `i128` sum + non-null count.
14897    SumI {
14898        sum: i128,
14899        count: u64,
14900    },
14901    /// Float64 `SUM`: running `f64` sum + non-null count.
14902    SumF {
14903        sum: f64,
14904        count: u64,
14905    },
14906    /// Int64 `AVG`: running `i128` sum + non-null count (avg = sum/count).
14907    AvgI {
14908        sum: i128,
14909        count: u64,
14910    },
14911    /// Float64 `AVG`: running `f64` sum + non-null count.
14912    AvgF {
14913        sum: f64,
14914        count: u64,
14915    },
14916    /// Int64 `MIN`/`MAX`.
14917    MinI(i64),
14918    MaxI(i64),
14919    /// Float64 `MIN`/`MAX`.
14920    MinF(f64),
14921    MaxF(f64),
14922    /// No matching rows observed yet.
14923    Empty,
14924}
14925
14926impl AggState {
14927    /// Combine two states over disjoint row sets into the state over the union.
14928    pub fn merge(self, other: AggState) -> AggState {
14929        use AggState::*;
14930        match (self, other) {
14931            (Empty, x) | (x, Empty) => x,
14932            (Count(a), Count(b)) => Count(a + b),
14933            (SumI { sum: sa, count: ca }, SumI { sum: sb, count: cb }) => SumI {
14934                sum: sa + sb,
14935                count: ca + cb,
14936            },
14937            (SumF { sum: sa, count: ca }, SumF { sum: sb, count: cb }) => SumF {
14938                sum: sa + sb,
14939                count: ca + cb,
14940            },
14941            (AvgI { sum: sa, count: ca }, AvgI { sum: sb, count: cb }) => AvgI {
14942                sum: sa + sb,
14943                count: ca + cb,
14944            },
14945            (AvgF { sum: sa, count: ca }, AvgF { sum: sb, count: cb }) => AvgF {
14946                sum: sa + sb,
14947                count: ca + cb,
14948            },
14949            (MinI(a), MinI(b)) => MinI(a.min(b)),
14950            (MaxI(a), MaxI(b)) => MaxI(a.max(b)),
14951            (MinF(a), MinF(b)) => MinF(a.min(b)),
14952            (MaxF(a), MaxF(b)) => MaxF(a.max(b)),
14953            _ => Empty, // mismatched kinds — shouldn't happen (same query)
14954        }
14955    }
14956
14957    /// The scalar point value (`f64`), or `None` when there were no inputs.
14958    pub fn point(&self) -> Option<f64> {
14959        match self {
14960            AggState::Count(n) => Some(*n as f64),
14961            AggState::SumI { sum, .. } => Some(*sum as f64),
14962            AggState::SumF { sum, .. } => Some(*sum),
14963            AggState::AvgI { sum, count } if *count > 0 => Some(*sum as f64 / *count as f64),
14964            AggState::AvgF { sum, count } if *count > 0 => Some(*sum / *count as f64),
14965            AggState::MinI(n) => Some(*n as f64),
14966            AggState::MaxI(n) => Some(*n as f64),
14967            AggState::MinF(n) => Some(*n),
14968            AggState::MaxF(n) => Some(*n),
14969            AggState::AvgI { .. } | AggState::AvgF { .. } | AggState::Empty => None,
14970        }
14971    }
14972
14973    /// Convert a vectorized [`NativeAggResult`] (from the cursor path) into a
14974    /// mergeable [`AggState`], so the incremental cache can be seeded from the
14975    /// fast cold path. `ty` is the column's type (`None` for COUNT(*)).
14976    pub fn from_native(result: NativeAggResult, agg: NativeAgg, ty: Option<TypeId>) -> Self {
14977        let is_float = matches!(ty, Some(TypeId::Float64));
14978        match (agg, result) {
14979            (NativeAgg::Count, NativeAggResult::Count(n)) => AggState::Count(n),
14980            (NativeAgg::Sum, NativeAggResult::Int(x)) => AggState::SumI {
14981                sum: x as i128,
14982                count: 1, // count unknown from NativeAggResult; use sentinel
14983            },
14984            (NativeAgg::Sum, NativeAggResult::Float(x)) => AggState::SumF { sum: x, count: 1 },
14985            (NativeAgg::Avg, NativeAggResult::Float(x)) => AggState::AvgF { sum: x, count: 1 },
14986            (NativeAgg::Min, NativeAggResult::Int(x)) => AggState::MinI(x),
14987            (NativeAgg::Max, NativeAggResult::Int(x)) => AggState::MaxI(x),
14988            (NativeAgg::Min, NativeAggResult::Float(x)) => AggState::MinF(x),
14989            (NativeAgg::Max, NativeAggResult::Float(x)) => AggState::MaxF(x),
14990            (NativeAgg::Count, _) => AggState::Empty,
14991            (_, NativeAggResult::Null) => AggState::Empty,
14992            _ => {
14993                let _ = is_float;
14994                AggState::Empty
14995            }
14996        }
14997    }
14998}
14999
15000/// A cached incremental aggregate (Phase 8.3): the mergeable state, the row-id
15001/// watermark it covers (rows `[0, watermark)`), and the snapshot epoch.
15002#[derive(Debug, Clone)]
15003pub struct CachedAgg {
15004    pub state: AggState,
15005    pub watermark: u64,
15006    pub epoch: u64,
15007}
15008
15009/// Outcome of [`Table::aggregate_incremental`].
15010#[derive(Debug, Clone)]
15011pub struct IncrementalAggResult {
15012    /// The aggregate state covering all rows at the current epoch.
15013    pub state: AggState,
15014    /// `true` when produced by merging only the delta (new rows); `false` when
15015    /// a full recompute was required (cold cache, deletes, or same epoch).
15016    pub incremental: bool,
15017    /// Rows processed in the delta pass (`0` for a full recompute).
15018    pub delta_rows: u64,
15019}
15020
15021/// Compute a mergeable [`AggState`] over `rows` that pass every per-row
15022/// `conditions` conjunct (and whose row id is in every pre-resolved
15023/// `index_sets`). Shared by the cold (full) and warm (delta) incremental paths.
15024fn agg_state_from_rows(
15025    rows: &[Row],
15026    conditions: &[crate::query::Condition],
15027    index_sets: &[RowIdSet],
15028    column: Option<u16>,
15029    agg: NativeAgg,
15030    schema: &Schema,
15031    control: Option<&crate::ExecutionControl>,
15032) -> Result<AggState> {
15033    let mut count: u64 = 0;
15034    let mut sum_i: i128 = 0;
15035    let mut sum_f: f64 = 0.0;
15036    let mut mn_i: i64 = i64::MAX;
15037    let mut mx_i: i64 = i64::MIN;
15038    let mut mn_f: f64 = f64::INFINITY;
15039    let mut mx_f: f64 = f64::NEG_INFINITY;
15040    let mut saw_int = false;
15041    let mut saw_float = false;
15042    for (index, r) in rows.iter().enumerate() {
15043        execution_checkpoint(control, index)?;
15044        if !conditions
15045            .iter()
15046            .all(|c| condition_matches_row(c, r, schema))
15047        {
15048            continue;
15049        }
15050        if !index_sets.iter().all(|s| s.contains(r.row_id.0)) {
15051            continue;
15052        }
15053        match agg {
15054            NativeAgg::Count => match column {
15055                // COUNT(*) counts every passing row.
15056                None => count += 1,
15057                // COUNT(col) excludes NULLs — explicit `Value::Null` and a column
15058                // absent from the row (schema evolution) are both NULL.
15059                Some(cid) => match r.columns.get(&cid) {
15060                    None | Some(Value::Null) => {}
15061                    Some(_) => count += 1,
15062                },
15063            },
15064            _ => match column.and_then(|cid| r.columns.get(&cid)) {
15065                Some(Value::Int64(n)) => {
15066                    count += 1;
15067                    sum_i += *n as i128;
15068                    mn_i = mn_i.min(*n);
15069                    mx_i = mx_i.max(*n);
15070                    saw_int = true;
15071                }
15072                Some(Value::Float64(f)) => {
15073                    count += 1;
15074                    sum_f += f;
15075                    mn_f = mn_f.min(*f);
15076                    mx_f = mx_f.max(*f);
15077                    saw_float = true;
15078                }
15079                _ => {}
15080            },
15081        }
15082    }
15083    Ok(match agg {
15084        NativeAgg::Count => {
15085            if count == 0 {
15086                AggState::Empty
15087            } else {
15088                AggState::Count(count)
15089            }
15090        }
15091        NativeAgg::Sum => {
15092            if count == 0 {
15093                AggState::Empty
15094            } else if saw_int {
15095                AggState::SumI { sum: sum_i, count }
15096            } else {
15097                AggState::SumF { sum: sum_f, count }
15098            }
15099        }
15100        NativeAgg::Avg => {
15101            if count == 0 {
15102                AggState::Empty
15103            } else if saw_int {
15104                AggState::AvgI { sum: sum_i, count }
15105            } else {
15106                AggState::AvgF { sum: sum_f, count }
15107            }
15108        }
15109        NativeAgg::Min => {
15110            if !saw_int && !saw_float {
15111                AggState::Empty
15112            } else if saw_int {
15113                AggState::MinI(mn_i)
15114            } else {
15115                AggState::MinF(mn_f)
15116            }
15117        }
15118        NativeAgg::Max => {
15119            if !saw_int && !saw_float {
15120                AggState::Empty
15121            } else if saw_int {
15122                AggState::MaxI(mx_i)
15123            } else {
15124                AggState::MaxF(mx_f)
15125            }
15126        }
15127    })
15128}
15129
15130/// Evaluate an index-served [`Condition`] exactly against a materialized row.
15131/// `Ann`/`SparseMatch` (index-defined) always pass here; callers test those via a
15132/// pre-resolved row-id set.
15133fn condition_matches_row(c: &crate::query::Condition, row: &Row, schema: &Schema) -> bool {
15134    use crate::query::Condition;
15135    match c {
15136        Condition::Pk(key) => match schema.primary_key() {
15137            Some(pk) => row
15138                .columns
15139                .get(&pk.id)
15140                .map(|v| v.encode_key() == *key)
15141                .unwrap_or(false),
15142            None => false,
15143        },
15144        Condition::BitmapEq { column_id, value } => row
15145            .columns
15146            .get(column_id)
15147            .map(|v| v.encode_key() == *value)
15148            .unwrap_or(false),
15149        Condition::BitmapIn { column_id, values } => {
15150            let key = row.columns.get(column_id).map(|v| v.encode_key());
15151            match key {
15152                Some(k) => values.contains(&k),
15153                None => false,
15154            }
15155        }
15156        Condition::BytesPrefix { column_id, prefix } => row
15157            .columns
15158            .get(column_id)
15159            .map(|v| v.encode_key().starts_with(prefix))
15160            .unwrap_or(false),
15161        Condition::Range { column_id, lo, hi } => match row.columns.get(column_id) {
15162            Some(Value::Int64(n)) => *n >= *lo && *n <= *hi,
15163            _ => false,
15164        },
15165        Condition::RangeF64 {
15166            column_id,
15167            lo,
15168            lo_inclusive,
15169            hi,
15170            hi_inclusive,
15171        } => match row.columns.get(column_id) {
15172            Some(Value::Float64(n)) => {
15173                let lo_ok = if *lo_inclusive { *n >= *lo } else { *n > *lo };
15174                let hi_ok = if *hi_inclusive { *n <= *hi } else { *n < *hi };
15175                lo_ok && hi_ok
15176            }
15177            _ => false,
15178        },
15179        Condition::FmContains { column_id, pattern } => match row.columns.get(column_id) {
15180            Some(Value::Bytes(b)) => {
15181                !pattern.is_empty() && b.windows(pattern.len()).any(|w| w == &pattern[..])
15182            }
15183            _ => false,
15184        },
15185        Condition::FmContainsAll {
15186            column_id,
15187            patterns,
15188        } => match row.columns.get(column_id) {
15189            Some(Value::Bytes(b)) => patterns
15190                .iter()
15191                .all(|pat| !pat.is_empty() && b.windows(pat.len()).any(|w| w == &pat[..])),
15192            _ => false,
15193        },
15194        Condition::Ann { .. }
15195        | Condition::SparseMatch { .. }
15196        | Condition::MinHashSimilar { .. } => true,
15197        Condition::IsNull { column_id } => {
15198            matches!(row.columns.get(column_id), Some(Value::Null) | None)
15199        }
15200        Condition::IsNotNull { column_id } => {
15201            !matches!(row.columns.get(column_id), Some(Value::Null) | None)
15202        }
15203    }
15204}
15205
15206/// Coerce a cell to `f64` for Sum/Avg (Int64/Float64 only).
15207fn as_f64(v: Option<&Value>) -> Option<f64> {
15208    match v {
15209        Some(Value::Int64(n)) => Some(*n as f64),
15210        Some(Value::Float64(f)) => Some(*f),
15211        _ => None,
15212    }
15213}
15214
15215/// One-pass vectorized accumulation of `(non-null count, sum, min, max)` over an
15216/// Int64 column streamed through `cursor`. The inner loop over a contiguous
15217/// `&[i64]` autovectorizes (SIMD) for the all-non-null prefix.
15218fn accumulate_int(
15219    cursor: &mut dyn crate::cursor::Cursor,
15220    control: Option<&crate::ExecutionControl>,
15221) -> Result<(u64, i128, i64, i64)> {
15222    let mut count: u64 = 0;
15223    let mut sum: i128 = 0;
15224    let mut mn: i64 = i64::MAX;
15225    let mut mx: i64 = i64::MIN;
15226    while let Some(cols) = cursor.next_batch()? {
15227        execution_checkpoint(control, 0)?;
15228        if let Some(crate::columnar::NativeColumn::Int64 { data, validity }) = cols.first() {
15229            if crate::columnar::all_non_null(validity, data.len()) {
15230                // All-non-null: vectorized sum/min/max with no per-element branch.
15231                count += data.len() as u64;
15232                for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15233                    execution_checkpoint(control, chunk_index * 1024)?;
15234                    sum += chunk.iter().map(|&v| v as i128).sum::<i128>();
15235                    mn = mn.min(*chunk.iter().min().unwrap_or(&mn));
15236                    mx = mx.max(*chunk.iter().max().unwrap_or(&mx));
15237                }
15238            } else {
15239                for (i, &v) in data.iter().enumerate() {
15240                    execution_checkpoint(control, i)?;
15241                    if crate::columnar::validity_bit(validity, i) {
15242                        count += 1;
15243                        sum += v as i128;
15244                        mn = mn.min(v);
15245                        mx = mx.max(v);
15246                    }
15247                }
15248            }
15249        }
15250    }
15251    Ok((count, sum, mn, mx))
15252}
15253
15254/// f64 analogue of [`accumulate_int`].
15255fn accumulate_float(
15256    cursor: &mut dyn crate::cursor::Cursor,
15257    control: Option<&crate::ExecutionControl>,
15258) -> Result<(u64, f64, f64, f64)> {
15259    let mut count: u64 = 0;
15260    let mut sum: f64 = 0.0;
15261    let mut mn: f64 = f64::INFINITY;
15262    let mut mx: f64 = f64::NEG_INFINITY;
15263    while let Some(cols) = cursor.next_batch()? {
15264        execution_checkpoint(control, 0)?;
15265        if let Some(crate::columnar::NativeColumn::Float64 { data, validity }) = cols.first() {
15266            if crate::columnar::all_non_null(validity, data.len()) {
15267                count += data.len() as u64;
15268                for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15269                    execution_checkpoint(control, chunk_index * 1024)?;
15270                    sum += chunk.iter().sum::<f64>();
15271                    mn = mn.min(chunk.iter().copied().fold(f64::INFINITY, f64::min));
15272                    mx = mx.max(chunk.iter().copied().fold(f64::NEG_INFINITY, f64::max));
15273                }
15274            } else {
15275                for (i, &v) in data.iter().enumerate() {
15276                    execution_checkpoint(control, i)?;
15277                    if crate::columnar::validity_bit(validity, i) {
15278                        count += 1;
15279                        sum += v;
15280                        mn = mn.min(v);
15281                        mx = mx.max(v);
15282                    }
15283                }
15284            }
15285        }
15286    }
15287    Ok((count, sum, mn, mx))
15288}
15289
15290#[inline]
15291fn execution_checkpoint(control: Option<&crate::ExecutionControl>, index: usize) -> Result<()> {
15292    if index.is_multiple_of(256) {
15293        control
15294            .map(crate::ExecutionControl::checkpoint)
15295            .transpose()?;
15296    }
15297    Ok(())
15298}
15299
15300fn pack_int(agg: NativeAgg, count: u64, sum: i128, mn: i64, mx: i64) -> NativeAggResult {
15301    if count == 0 && !matches!(agg, NativeAgg::Count) {
15302        return NativeAggResult::Null;
15303    }
15304    match agg {
15305        NativeAgg::Count => NativeAggResult::Count(count),
15306        // i64 overflow on Sum ⇒ SQL NULL (DataFusion errors on overflow; null is
15307        // a safe, non-misleading fallback rather than a saturated wrong value).
15308        NativeAgg::Sum => match sum.try_into() {
15309            Ok(v) => NativeAggResult::Int(v),
15310            Err(_) => NativeAggResult::Null,
15311        },
15312        NativeAgg::Min => NativeAggResult::Int(mn),
15313        NativeAgg::Max => NativeAggResult::Int(mx),
15314        NativeAgg::Avg => NativeAggResult::Float((sum as f64) / (count as f64)),
15315    }
15316}
15317
15318fn pack_float(agg: NativeAgg, count: u64, sum: f64, mn: f64, mx: f64) -> NativeAggResult {
15319    if count == 0 && !matches!(agg, NativeAgg::Count) {
15320        return NativeAggResult::Null;
15321    }
15322    match agg {
15323        NativeAgg::Count => NativeAggResult::Count(count),
15324        NativeAgg::Sum => NativeAggResult::Float(sum),
15325        NativeAgg::Min => NativeAggResult::Float(mn),
15326        NativeAgg::Max => NativeAggResult::Float(mx),
15327        NativeAgg::Avg => NativeAggResult::Float(sum / (count as f64)),
15328    }
15329}
15330
15331/// Aggregate per-page `min`/`max`/`null_count` into a column-wide i64 triple.
15332/// Returns `None` if no page contributes a non-null min/max (all-null column).
15333fn agg_int(
15334    stats: &[crate::page::PageStat],
15335    decode: fn(Option<&[u8]>) -> Option<i64>,
15336) -> Option<(Option<i64>, Option<i64>, u64)> {
15337    let (mut mn, mut mx, mut nulls) = (i64::MAX, i64::MIN, 0u64);
15338    let mut any = false;
15339    for s in stats {
15340        if let Some(v) = decode(s.min.as_deref()) {
15341            mn = mn.min(v);
15342            any = true;
15343        }
15344        if let Some(v) = decode(s.max.as_deref()) {
15345            mx = mx.max(v);
15346            any = true;
15347        }
15348        nulls += s.null_count;
15349    }
15350    any.then_some((Some(mn), Some(mx), nulls))
15351}
15352
15353/// f64 analogue of [`agg_int`] (compares as f64, not as bit patterns).
15354fn agg_float(
15355    stats: &[crate::page::PageStat],
15356    decode: fn(Option<&[u8]>) -> Option<f64>,
15357) -> Option<(Option<f64>, Option<f64>, u64)> {
15358    let (mut mn, mut mx, mut nulls) = (f64::INFINITY, f64::NEG_INFINITY, 0u64);
15359    let mut any = false;
15360    for s in stats {
15361        if let Some(v) = decode(s.min.as_deref()) {
15362            mn = mn.min(v);
15363            any = true;
15364        }
15365        if let Some(v) = decode(s.max.as_deref()) {
15366            mx = mx.max(v);
15367            any = true;
15368        }
15369        nulls += s.null_count;
15370    }
15371    any.then_some((Some(mn), Some(mx), nulls))
15372}
15373
15374/// The four maintained secondary-index maps, keyed by column id.
15375type SecondaryIndexes = (
15376    HashMap<u16, BitmapIndex>,
15377    HashMap<u16, AnnIndex>,
15378    HashMap<u16, FmIndex>,
15379    HashMap<u16, SparseIndex>,
15380    HashMap<u16, MinHashIndex>,
15381);
15382
15383fn empty_indexes(schema: &Schema) -> SecondaryIndexes {
15384    let mut bitmap = HashMap::new();
15385    let mut ann = HashMap::new();
15386    let mut fm = HashMap::new();
15387    let mut sparse = HashMap::new();
15388    let mut minhash = HashMap::new();
15389    for idef in &schema.indexes {
15390        match idef.kind {
15391            IndexKind::Bitmap => {
15392                bitmap.insert(idef.column_id, BitmapIndex::new());
15393            }
15394            IndexKind::Ann => {
15395                let dim = schema
15396                    .columns
15397                    .iter()
15398                    .find(|c| c.id == idef.column_id)
15399                    .and_then(|c| match c.ty {
15400                        TypeId::Embedding { dim } => Some(dim as usize),
15401                        _ => None,
15402                    })
15403                    .unwrap_or(0);
15404                let options = idef.options.ann.clone().unwrap_or_default();
15405                ann.insert(
15406                    idef.column_id,
15407                    AnnIndex::with_full_options(
15408                        dim,
15409                        options.m,
15410                        options.ef_construction,
15411                        options.ef_search,
15412                        &options,
15413                    ),
15414                );
15415            }
15416            IndexKind::FmIndex => {
15417                fm.insert(idef.column_id, FmIndex::new());
15418            }
15419            IndexKind::Sparse => {
15420                sparse.insert(idef.column_id, SparseIndex::new());
15421            }
15422            IndexKind::MinHash => {
15423                let options = idef.options.minhash.clone().unwrap_or_default();
15424                minhash.insert(
15425                    idef.column_id,
15426                    MinHashIndex::with_options(options.permutations, options.bands),
15427                );
15428            }
15429            _ => {}
15430        }
15431    }
15432    (bitmap, ann, fm, sparse, minhash)
15433}
15434
15435const ALTER_COLUMN_PROTECTED_FLAGS: u32 = ColumnFlags::PRIMARY_KEY
15436    | ColumnFlags::AUTO_INCREMENT
15437    | ColumnFlags::ENCRYPTED
15438    | ColumnFlags::ENCRYPTED_INDEXABLE
15439    | ColumnFlags::EMBEDDING_BINARY_QUANTIZED;
15440
15441fn validate_alter_column_flags(old: ColumnFlags, new: ColumnFlags) -> Result<()> {
15442    if (old.bits() ^ new.bits()) & ALTER_COLUMN_PROTECTED_FLAGS != 0 {
15443        return Err(MongrelError::Schema(
15444            "ALTER COLUMN may only change NULLABLE; primary key, auto-increment, encryption, and embedding flags are immutable".into(),
15445        ));
15446    }
15447    Ok(())
15448}
15449
15450fn validate_alter_column_type(
15451    schema: &Schema,
15452    old: &ColumnDef,
15453    next: &ColumnDef,
15454    has_stored_versions: bool,
15455) -> Result<()> {
15456    if old.ty == next.ty {
15457        return Ok(());
15458    }
15459    if schema.indexes.iter().any(|i| i.column_id == old.id) {
15460        return Err(MongrelError::Schema(format!(
15461            "ALTER COLUMN TYPE is not supported for indexed column '{}'",
15462            old.name
15463        )));
15464    }
15465    if !has_stored_versions || storage_compatible_type_change(old.ty.clone(), next.ty.clone()) {
15466        return Ok(());
15467    }
15468    Err(MongrelError::Schema(format!(
15469        "ALTER COLUMN TYPE from {:?} to {:?} requires an empty column or a representation-compatible type",
15470        old.ty, next.ty
15471    )))
15472}
15473
15474fn storage_compatible_type_change(old: TypeId, new: TypeId) -> bool {
15475    matches!(
15476        (old, new),
15477        (TypeId::Int64, TypeId::TimestampNanos) | (TypeId::TimestampNanos, TypeId::Int64)
15478    )
15479}
15480
15481/// True when every row carries an `Int64` PK value and the sequence is
15482/// strictly increasing — no intra-batch duplicate is possible. The row-major
15483/// mirror of `native_int64_strictly_increasing` (the `bulk_pk_winner_indices`
15484/// fast path), used by `apply_put_rows_inner` to skip upsert probing for
15485/// append-style batches.
15486fn rows_pk_strictly_increasing(rows: &[Row], pk_id: u16) -> bool {
15487    let mut prev: Option<i64> = None;
15488    for r in rows {
15489        match r.columns.get(&pk_id) {
15490            Some(Value::Int64(v)) => {
15491                if prev.is_some_and(|p| p >= *v) {
15492                    return false;
15493                }
15494                prev = Some(*v);
15495            }
15496            _ => return false,
15497        }
15498    }
15499    true
15500}
15501
15502#[allow(clippy::too_many_arguments)]
15503fn index_into(
15504    schema: &Schema,
15505    row: &Row,
15506    hot: &mut HotIndex,
15507    bitmap: &mut HashMap<u16, BitmapIndex>,
15508    ann: &mut HashMap<u16, AnnIndex>,
15509    fm: &mut HashMap<u16, FmIndex>,
15510    sparse: &mut HashMap<u16, SparseIndex>,
15511    minhash: &mut HashMap<u16, MinHashIndex>,
15512) {
15513    for idef in &schema.indexes {
15514        let Some(val) = row.columns.get(&idef.column_id) else {
15515            continue;
15516        };
15517        match idef.kind {
15518            IndexKind::Bitmap => {
15519                if let Some(b) = bitmap.get_mut(&idef.column_id) {
15520                    b.insert(val.encode_key(), row.row_id);
15521                }
15522            }
15523            IndexKind::Ann => {
15524                if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15525                    if let Some(meta) = val.generated_embedding_metadata() {
15526                        // P1.5-T3: pending/failed generated vectors stay out of ANN.
15527                        if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15528                            continue;
15529                        }
15530                        if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15531                            .is_err()
15532                        {
15533                            continue;
15534                        }
15535                    }
15536                    a.insert_validated(v, row.row_id);
15537                }
15538            }
15539            IndexKind::FmIndex => {
15540                if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15541                    f.insert(b.clone(), row.row_id);
15542                }
15543            }
15544            IndexKind::Sparse => {
15545                if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15546                    // A sparse vector is stored as a bincode'd `Vec<(u32, f32)>`
15547                    // in a Bytes column (SPLADE weights in, retrieval out).
15548                    if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15549                        s.insert(&terms, row.row_id);
15550                    }
15551                }
15552            }
15553            IndexKind::MinHash => {
15554                if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15555                    // The set is a JSON array (the Kit's `set_similarity` shape);
15556                    // tokenize + hash its members into the MinHash signature.
15557                    let tokens = crate::index::token_hashes_from_bytes(b);
15558                    mh.insert(&tokens, row.row_id);
15559                }
15560            }
15561            _ => {}
15562        }
15563    }
15564    if let Some(pk_col) = schema.primary_key() {
15565        if let Some(pk_val) = row.columns.get(&pk_col.id) {
15566            hot.insert(pk_val.encode_key(), row.row_id);
15567        }
15568    }
15569}
15570
15571/// Index a row into a single specific index (used for partial indexes where
15572/// only matching indexes should receive the row).
15573#[allow(clippy::too_many_arguments)]
15574fn index_into_single(
15575    idef: &IndexDef,
15576    _schema: &Schema,
15577    row: &Row,
15578    _hot: &mut HotIndex,
15579    bitmap: &mut HashMap<u16, BitmapIndex>,
15580    ann: &mut HashMap<u16, AnnIndex>,
15581    fm: &mut HashMap<u16, FmIndex>,
15582    sparse: &mut HashMap<u16, SparseIndex>,
15583    minhash: &mut HashMap<u16, MinHashIndex>,
15584) {
15585    let Some(val) = row.columns.get(&idef.column_id) else {
15586        return;
15587    };
15588    match idef.kind {
15589        IndexKind::Bitmap => {
15590            if let Some(b) = bitmap.get_mut(&idef.column_id) {
15591                b.insert(val.encode_key(), row.row_id);
15592            }
15593        }
15594        IndexKind::Ann => {
15595            if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15596                if let Some(meta) = val.generated_embedding_metadata() {
15597                    // P1.5-T3: pending/failed generated vectors stay out of ANN.
15598                    if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15599                        return;
15600                    }
15601                    if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15602                        .is_err()
15603                    {
15604                        return;
15605                    }
15606                }
15607                a.insert_validated(v, row.row_id);
15608            }
15609        }
15610        IndexKind::FmIndex => {
15611            if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15612                f.insert(b.clone(), row.row_id);
15613            }
15614        }
15615        IndexKind::Sparse => {
15616            if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15617                if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15618                    s.insert(&terms, row.row_id);
15619                }
15620            }
15621        }
15622        IndexKind::MinHash => {
15623            if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15624                let tokens = crate::index::token_hashes_from_bytes(b);
15625                mh.insert(&tokens, row.row_id);
15626            }
15627        }
15628        _ => {}
15629    }
15630}
15631
15632/// Evaluate a partial-index predicate against a row. Supports the most common
15633/// patterns: `"column IS NOT NULL"` and `"column IS NULL"`. More complex
15634/// expressions require a full SQL evaluator in core (future work); the
15635/// predicate string is stored verbatim and this function provides a pragmatic
15636/// subset. Returns `true` if the row should be indexed.
15637fn eval_partial_predicate(
15638    pred: &str,
15639    columns_map: &HashMap<u16, &Value>,
15640    name_to_id: &HashMap<&str, u16>,
15641) -> bool {
15642    let lower = pred.trim().to_ascii_lowercase();
15643    // Pattern: "column_name IS NOT NULL"
15644    if let Some(rest) = lower.strip_suffix(" is not null") {
15645        let col_name = rest.trim();
15646        if let Some(col_id) = name_to_id.get(col_name) {
15647            return columns_map
15648                .get(col_id)
15649                .is_some_and(|v| !matches!(v, Value::Null));
15650        }
15651    }
15652    // Pattern: "column_name IS NULL"
15653    if let Some(rest) = lower.strip_suffix(" is null") {
15654        let col_name = rest.trim();
15655        if let Some(col_id) = name_to_id.get(col_name) {
15656            return columns_map
15657                .get(col_id)
15658                .is_none_or(|v| matches!(v, Value::Null));
15659        }
15660    }
15661    // Unknown predicate syntax: index the row (conservative — better to
15662    // over-index than to miss rows).
15663    true
15664}
15665
15666/// Per-element index key for the typed bulk-index path (Phase 14.2): mirrors
15667/// `index_into` on a `tokenized_for_indexes(row)` — encodes the element the way
15668/// [`Value::encode_key`] would, then applies the column's
15669/// `ENCRYPTED_INDEXABLE` tokenization (HMAC-eq / OPE) so bitmap/HOT keys match
15670/// what the incremental path stores. Returns `None` for null slots.
15671#[allow(dead_code)]
15672fn bulk_index_key(
15673    column_keys: &HashMap<u16, ([u8; 32], u8)>,
15674    column_id: u16,
15675    ty: TypeId,
15676    col: &columnar::NativeColumn,
15677    i: usize,
15678) -> Option<Vec<u8>> {
15679    let encoded = columnar::encode_key_native(ty, col, i)?;
15680    {
15681        use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
15682        if let Some((key, scheme)) = column_keys.get(&column_id) {
15683            return Some(match (*scheme, col) {
15684                (SCHEME_HMAC_EQ, _) => hmac_token(key, &encoded).to_vec(),
15685                (_, columnar::NativeColumn::Int64 { data, .. }) => {
15686                    ope_token_i64(key, data[i]).to_vec()
15687                }
15688                (_, columnar::NativeColumn::Float64 { data, .. }) => {
15689                    ope_token_f64(key, data[i]).to_vec()
15690                }
15691                _ => hmac_token(key, &encoded).to_vec(),
15692            });
15693        }
15694    }
15695    Some(encoded)
15696}
15697
15698pub(crate) fn write_schema(dir: &Path, schema: &Schema) -> Result<()> {
15699    write_schema_with_after(dir, schema, || {})
15700}
15701
15702pub(crate) fn write_schema_durable(
15703    root: &crate::durable_file::DurableRoot,
15704    schema: &Schema,
15705) -> Result<()> {
15706    write_schema_durable_with_after(root, schema, || {})
15707}
15708
15709fn write_schema_with_after<F>(dir: &Path, schema: &Schema, after_publish: F) -> Result<()>
15710where
15711    F: FnOnce(),
15712{
15713    let json = serde_json::to_string_pretty(schema)
15714        .map_err(|e| MongrelError::Schema(format!("encode schema: {e}")))?;
15715    crate::durable_file::write_atomic_with_after(
15716        &dir.join(SCHEMA_FILENAME),
15717        json.as_bytes(),
15718        after_publish,
15719    )?;
15720    Ok(())
15721}
15722
15723fn write_schema_durable_with_after<F>(
15724    root: &crate::durable_file::DurableRoot,
15725    schema: &Schema,
15726    after_publish: F,
15727) -> Result<()>
15728where
15729    F: FnOnce(),
15730{
15731    let json = serde_json::to_string_pretty(schema)
15732        .map_err(|error| MongrelError::Schema(format!("encode schema: {error}")))?;
15733    root.write_atomic_with_after(SCHEMA_FILENAME, json.as_bytes(), after_publish)?;
15734    Ok(())
15735}
15736
15737fn checkpoint_current_schema(table: &mut Table) -> Result<()> {
15738    let mut schema_published = false;
15739    let schema_result = match table._root_guard.as_deref() {
15740        Some(root) => write_schema_durable_with_after(root, &table.schema, || {
15741            schema_published = true;
15742        }),
15743        None => write_schema_with_after(&table.dir, &table.schema, || {
15744            schema_published = true;
15745        }),
15746    };
15747    if schema_result.is_err() && !schema_published {
15748        return schema_result;
15749    }
15750    match table.persist_manifest(table.current_epoch()) {
15751        Ok(()) => Ok(()),
15752        Err(manifest_error) => Err(match schema_result {
15753            Ok(()) => manifest_error,
15754            Err(schema_error) => MongrelError::Other(format!(
15755                "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
15756            )),
15757        }),
15758    }
15759}
15760
15761fn read_schema(dir: &Path) -> Result<Schema> {
15762    let file = crate::durable_file::open_regular_nofollow(&dir.join(SCHEMA_FILENAME))?;
15763    read_schema_file(file)
15764}
15765
15766fn read_schema_file(file: std::fs::File) -> Result<Schema> {
15767    const MAX_SCHEMA_BYTES: u64 = 16 * 1024 * 1024;
15768    use std::io::Read;
15769
15770    let length = file.metadata()?.len();
15771    if length > MAX_SCHEMA_BYTES {
15772        return Err(MongrelError::ResourceLimitExceeded {
15773            resource: "schema bytes",
15774            requested: usize::try_from(length).unwrap_or(usize::MAX),
15775            limit: MAX_SCHEMA_BYTES as usize,
15776        });
15777    }
15778    let mut bytes = Vec::with_capacity(length as usize);
15779    file.take(MAX_SCHEMA_BYTES + 1).read_to_end(&mut bytes)?;
15780    if bytes.len() as u64 != length {
15781        return Err(MongrelError::Schema(
15782            "schema length changed while reading".into(),
15783        ));
15784    }
15785    serde_json::from_slice(&bytes).map_err(|e| MongrelError::Schema(format!("decode schema: {e}")))
15786}
15787
15788fn preflight_standalone_open(
15789    dir: &Path,
15790    runs_root: Option<&crate::durable_file::DurableRoot>,
15791    idx_root: Option<&crate::durable_file::DurableRoot>,
15792    manifest: &Manifest,
15793    schema: &Schema,
15794    records: &[crate::wal::Record],
15795    kek: Option<Arc<Kek>>,
15796) -> Result<()> {
15797    crate::wal::validate_shared_transaction_framing(records)?;
15798    if manifest.schema_id > schema.schema_id
15799        || manifest.flushed_epoch > manifest.current_epoch
15800        || manifest.global_idx_epoch > manifest.current_epoch
15801        || manifest.next_row_id == u64::MAX
15802        || manifest.auto_inc_next < 0
15803        || manifest.auto_inc_next == i64::MAX
15804        || (schema.auto_increment_column().is_none() && manifest.auto_inc_next != 0)
15805    {
15806        return Err(MongrelError::InvalidArgument(
15807            "manifest counters or schema identity are invalid".into(),
15808        ));
15809    }
15810    let mut run_ids = HashSet::new();
15811    let mut maximum_row_id = None::<u64>;
15812    for run in &manifest.runs {
15813        if run.run_id >= u64::MAX as u128
15814            || !run_ids.insert(run.run_id)
15815            || run.epoch_created > manifest.current_epoch
15816        {
15817            return Err(MongrelError::InvalidArgument(
15818                "manifest contains an invalid or duplicate active run".into(),
15819            ));
15820        }
15821        let mut reader = match runs_root {
15822            Some(root) => RunReader::open_file(
15823                root.open_regular(format!("r-{}.sr", run.run_id as u64))?,
15824                schema.clone(),
15825                kek.clone(),
15826            )?,
15827            None => RunReader::open(
15828                dir.join(RUNS_DIR)
15829                    .join(format!("r-{}.sr", run.run_id as u64)),
15830                schema.clone(),
15831                kek.clone(),
15832            )?,
15833        };
15834        let header = reader.header();
15835        if header.run_id != run.run_id
15836            || header.level != run.level
15837            || header.row_count != run.row_count
15838            || !header.is_uniform_epoch() && header.epoch_created != run.epoch_created
15839            || header.is_uniform_epoch() && header.epoch_created != 0
15840            || header.schema_id > schema.schema_id
15841        {
15842            return Err(MongrelError::InvalidArgument(format!(
15843                "run {} differs from its manifest",
15844                run.run_id
15845            )));
15846        }
15847        if header.row_count != 0 {
15848            maximum_row_id = Some(
15849                maximum_row_id.map_or(header.max_row_id, |value| value.max(header.max_row_id)),
15850            );
15851        }
15852        reader.validate_all_pages()?;
15853    }
15854    if maximum_row_id.is_some_and(|maximum| manifest.next_row_id <= maximum) {
15855        return Err(MongrelError::InvalidArgument(
15856            "manifest next_row_id does not advance beyond persisted rows".into(),
15857        ));
15858    }
15859    for run in &manifest.retiring {
15860        if run.run_id >= u64::MAX as u128
15861            || run.retire_epoch > manifest.current_epoch
15862            || !run_ids.insert(run.run_id)
15863        {
15864            return Err(MongrelError::InvalidArgument(
15865                "manifest contains an invalid or duplicate retired run".into(),
15866            ));
15867        }
15868    }
15869    let idx_dek = kek.as_ref().map(|key| key.derive_idx_key());
15870    match idx_root {
15871        Some(root) => {
15872            global_idx::read_root(root, manifest.table_id, schema, idx_dek.as_deref())?;
15873        }
15874        None => {
15875            global_idx::read(dir, manifest.table_id, schema, idx_dek.as_deref())?;
15876        }
15877    }
15878
15879    let committed = records
15880        .iter()
15881        .filter_map(|record| match record.op {
15882            Op::TxnCommit { epoch, .. } => Some((record.txn_id, epoch)),
15883            _ => None,
15884        })
15885        .collect::<HashMap<_, _>>();
15886    for record in records {
15887        let Some(&_commit_epoch) = committed.get(&record.txn_id) else {
15888            continue;
15889        };
15890        match &record.op {
15891            Op::Put { table_id, rows } => {
15892                if *table_id != manifest.table_id {
15893                    return Err(MongrelError::CorruptWal {
15894                        offset: record.seq.0,
15895                        reason: format!(
15896                            "private WAL record references table {table_id}, expected {}",
15897                            manifest.table_id
15898                        ),
15899                    });
15900                }
15901                let rows: Vec<Row> =
15902                    bincode::deserialize(rows).map_err(|error| MongrelError::CorruptWal {
15903                        offset: record.seq.0,
15904                        reason: format!("committed Put payload could not be decoded: {error}"),
15905                    })?;
15906                for row in rows {
15907                    if row.deleted || row.row_id.0 == u64::MAX {
15908                        return Err(MongrelError::CorruptWal {
15909                            offset: record.seq.0,
15910                            reason: "committed Put contains an invalid row identity".into(),
15911                        });
15912                    }
15913                    let cells = row.columns.into_iter().collect::<Vec<_>>();
15914                    schema
15915                        .validate_values(&cells)
15916                        .map_err(|error| MongrelError::CorruptWal {
15917                            offset: record.seq.0,
15918                            reason: format!("committed Put violates table schema: {error}"),
15919                        })?;
15920                    if schema.auto_increment_column().is_some_and(|column| {
15921                        matches!(
15922                            cells.iter().find(|(id, _)| *id == column.id),
15923                            Some((_, Value::Int64(value))) if *value == i64::MAX
15924                        )
15925                    }) {
15926                        return Err(MongrelError::CorruptWal {
15927                            offset: record.seq.0,
15928                            reason: "committed Put exhausts AUTO_INCREMENT".into(),
15929                        });
15930                    }
15931                }
15932            }
15933            Op::Delete { table_id, .. } | Op::TruncateTable { table_id }
15934                if *table_id != manifest.table_id =>
15935            {
15936                return Err(MongrelError::CorruptWal {
15937                    offset: record.seq.0,
15938                    reason: format!(
15939                        "private WAL record references table {table_id}, expected {}",
15940                        manifest.table_id
15941                    ),
15942                });
15943            }
15944            Op::TxnCommit { added_runs, .. } if !added_runs.is_empty() => {
15945                return Err(MongrelError::CorruptWal {
15946                    offset: record.seq.0,
15947                    reason: "private WAL contains shared spilled-run metadata".into(),
15948                });
15949            }
15950            _ => {}
15951        }
15952    }
15953    Ok(())
15954}
15955
15956fn next_wal_segment(wal_dir: &Path) -> Result<PathBuf> {
15957    Ok(wal_dir.join(format!("seg-{:06}.wal", next_wal_number(wal_dir)?)))
15958}
15959
15960fn wal_segment_number(path: &Path) -> Option<u64> {
15961    path.file_stem()
15962        .and_then(|stem| stem.to_str())
15963        .and_then(|stem| stem.strip_prefix("seg-"))
15964        .and_then(|number| number.parse().ok())
15965}
15966
15967fn latest_wal_segment(wal_dir: &Path) -> Result<Option<PathBuf>> {
15968    let n = list_wal_numbers(wal_dir)?;
15969    Ok(n.map(|max| wal_dir.join(format!("seg-{max:06}.wal"))))
15970}
15971
15972fn next_wal_number(wal_dir: &Path) -> Result<u32> {
15973    list_wal_numbers(wal_dir)?
15974        .map(|maximum| {
15975            maximum
15976                .checked_add(1)
15977                .ok_or_else(|| MongrelError::Full("WAL segment namespace exhausted".into()))
15978        })
15979        .unwrap_or(Ok(0))
15980}
15981
15982fn list_wal_numbers(wal_dir: &Path) -> Result<Option<u32>> {
15983    let mut max_n = None;
15984    let entries = match std::fs::read_dir(wal_dir) {
15985        Ok(entries) => entries,
15986        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
15987        Err(error) => return Err(error.into()),
15988    };
15989    for entry in entries {
15990        let entry = entry?;
15991        let fname = entry.file_name();
15992        let Some(s) = fname.to_str() else {
15993            continue;
15994        };
15995        let Some(stripped) = s.strip_prefix("seg-") else {
15996            continue;
15997        };
15998        let Some(number) = stripped.strip_suffix(".wal") else {
15999            return Err(MongrelError::CorruptWal {
16000                offset: 0,
16001                reason: format!("malformed WAL segment name {s:?}"),
16002            });
16003        };
16004        let n = number
16005            .parse::<u32>()
16006            .map_err(|_| MongrelError::CorruptWal {
16007                offset: 0,
16008                reason: format!("malformed WAL segment name {s:?}"),
16009            })?;
16010        if s != format!("seg-{n:06}.wal") || !entry.file_type()?.is_file() {
16011            return Err(MongrelError::CorruptWal {
16012                offset: n as u64,
16013                reason: format!("noncanonical or nonregular WAL segment {s:?}"),
16014            });
16015        }
16016        max_n = Some(max_n.map(|m: u32| m.max(n)).unwrap_or(n));
16017    }
16018    Ok(max_n)
16019}
16020
16021// =========================================================================
16022// REM-001: full HLC authority across multi-run merge paths.
16023//
16024// These tests are the canonical inversion fixture from spec §6.1 / §9:
16025//
16026//   Run A:  epoch=low    HLC=high   payload="newer-by-HLC"
16027//   Run B:  epoch=high   HLC=low    payload="older-by-HLC"
16028//   Snapshot: epoch=10   HLC=600
16029//   Expected winner: "newer-by-HLC"
16030//
16031// Before the fix, every affected path stored `Option<(Epoch, ...)>` and
16032// picked the cross-run winner by `epoch > best_epoch`. An epoch-only fold
16033// selects Run B (high epoch) over Run A (low epoch), even though the HLC
16034// watermark is above both rows' stamps and HLC is the authority.
16035//
16036// The fix threads `commit_ts` through every cross-run fold via
16037// `crate::epoch::VersionStamp`; the run APIs return metadata-preserving
16038// `VersionedColumnValue` / `VersionVisibility` structs so the engine merge
16039// can compare candidates by full version stamp instead of epoch alone.
16040//
16041// The tests live inside this module so they can exercise private helpers
16042// (`values_for_rids_at`, `eligible_candidate_ids`, `rebuild_indexes_from_runs`).
16043// =========================================================================
16044
16045#[cfg(test)]
16046mod rem001_multi_run_hlc_authority {
16047    use super::*;
16048    use crate::epoch::{Epoch, Snapshot, VersionStamp};
16049    use crate::memtable::{Row, Value};
16050    use crate::query::{Condition, Query};
16051    use crate::schema::{ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
16052    use mongreldb_types::hlc::HlcTimestamp;
16053    use tempfile::tempdir;
16054
16055    fn hlc(physical_micros: u64) -> HlcTimestamp {
16056        HlcTimestamp {
16057            physical_micros,
16058            logical: 0,
16059            node_tiebreaker: 1,
16060        }
16061    }
16062
16063    fn pk_schema() -> Schema {
16064        Schema {
16065            schema_id: 1,
16066            columns: vec![
16067                ColumnDef {
16068                    id: 1,
16069                    name: "id".into(),
16070                    ty: TypeId::Int64,
16071                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16072                    default_value: None,
16073                    embedding_source: None,
16074                },
16075                ColumnDef {
16076                    id: 2,
16077                    name: "name".into(),
16078                    ty: TypeId::Bytes,
16079                    flags: ColumnFlags::empty(),
16080                    default_value: None,
16081                    embedding_source: None,
16082                },
16083            ],
16084            indexes: Vec::new(),
16085            colocation: vec![],
16086            constraints: Default::default(),
16087            clustered: false,
16088        }
16089    }
16090
16091    fn pk_schema_with_bitmap() -> Schema {
16092        Schema {
16093            schema_id: 1,
16094            columns: vec![
16095                ColumnDef {
16096                    id: 1,
16097                    name: "id".into(),
16098                    ty: TypeId::Int64,
16099                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16100                    default_value: None,
16101                    embedding_source: None,
16102                },
16103                ColumnDef {
16104                    id: 2,
16105                    name: "name".into(),
16106                    ty: TypeId::Bytes,
16107                    flags: ColumnFlags::empty(),
16108                    default_value: None,
16109                    embedding_source: None,
16110                },
16111            ],
16112            // Bitmap index on `name` so we can verify BitmapEq membership
16113            // reflects the HLC-winning run after the index rebuild.
16114            indexes: vec![IndexDef {
16115                name: "name_bitmap".into(),
16116                column_id: 2,
16117                kind: IndexKind::Bitmap,
16118                predicate: None,
16119                options: Default::default(),
16120            }],
16121            colocation: vec![],
16122            constraints: Default::default(),
16123            clustered: false,
16124        }
16125    }
16126
16127    fn encode_put(table_id: u64, row: &Row) -> Vec<u8> {
16128        use crate::database::StagedTxnWrite;
16129        bincode::serialize(&StagedTxnWrite::Put {
16130            table_id,
16131            rows: bincode::serialize(&vec![row.clone()]).expect("encode row"),
16132        })
16133        .expect("encode payload")
16134    }
16135
16136    /// Build the canonical two-run inversion:
16137    ///
16138    /// 1. apply the HLC-newer row first (lower committed_epoch because the
16139    ///    commit happens before any other write);
16140    /// 2. force-flush → `Run A` with `(epoch=1, HLC=500, payload="newer-by-HLC")`;
16141    /// 3. apply the HLC-older row second (higher committed_epoch because the
16142    ///    commit advances `epoch.visible()`);
16143    /// 4. force-flush → `Run B` with `(epoch=2, HLC=400, payload="older-by-HLC")`.
16144    ///
16145    /// After both flushes the table owns two immutable `.sr` files; Run A
16146    /// holds the HLC-newer payload, Run B holds the HLC-older payload, and
16147    /// Run B has the higher epoch because it was written later. Epoch-only
16148    /// cross-run folding picks Run B; HLC authority picks Run A.
16149    fn build_inverted_database(dir: &std::path::Path, schema: Schema) -> crate::Database {
16150        let db = crate::Database::create(dir).unwrap();
16151        db.create_table("t", schema).unwrap();
16152        let table_id = db.table_id("t").unwrap();
16153        let rid = RowId(7);
16154
16155        let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16156            .with_column(1, Value::Int64(7))
16157            .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()));
16158        let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16159            .with_column(1, Value::Int64(7))
16160            .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()));
16161
16162        db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16163            .expect("first apply");
16164        {
16165            let table = db.table("t").unwrap();
16166            table.lock().force_flush().expect("flush run A");
16167        }
16168
16169        db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16170            .expect("second apply");
16171        {
16172            let table = db.table("t").unwrap();
16173            table.lock().force_flush().expect("flush run B");
16174        }
16175
16176        db
16177    }
16178
16179    /// TTL fixture: HLC-newer row carries a far-future `ttl_ts`; HLC-older
16180    /// row carries a far-past `ttl_ts`. The TTL eligibility path must read
16181    /// the timestamp from the HLC-newer run (live), not from the HLC-older
16182    /// run (expired), and admit the rid.
16183    fn build_inverted_ttl_database(dir: &std::path::Path) -> crate::Database {
16184        let db = crate::Database::create(dir).unwrap();
16185        db.create_table("t", ttl_schema()).unwrap();
16186        let table_id = db.table_id("t").unwrap();
16187        let rid = RowId(7);
16188        let read_time_ns: i64 = 1_000_000_000;
16189        let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16190            .with_column(1, Value::Int64(7))
16191            .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()))
16192            .with_column(3, Value::Int64(read_time_ns + 60 * 1_000_000_000));
16193        let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16194            .with_column(1, Value::Int64(7))
16195            .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()))
16196            .with_column(3, Value::Int64(read_time_ns - 60 * 1_000_000_000));
16197
16198        db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16199            .expect("first apply");
16200        {
16201            let table = db.table("t").unwrap();
16202            table.lock().force_flush().expect("flush run A");
16203        }
16204        db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16205            .expect("second apply");
16206        {
16207            let table = db.table("t").unwrap();
16208            table.lock().force_flush().expect("flush run B");
16209        }
16210
16211        db
16212    }
16213
16214    fn ttl_schema() -> Schema {
16215        Schema {
16216            schema_id: 1,
16217            columns: vec![
16218                ColumnDef {
16219                    id: 1,
16220                    name: "id".into(),
16221                    ty: TypeId::Int64,
16222                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16223                    default_value: None,
16224                    embedding_source: None,
16225                },
16226                ColumnDef {
16227                    id: 2,
16228                    name: "name".into(),
16229                    ty: TypeId::Bytes,
16230                    flags: ColumnFlags::empty(),
16231                    default_value: None,
16232                    embedding_source: None,
16233                },
16234                ColumnDef {
16235                    id: 3,
16236                    name: "ttl_ts".into(),
16237                    ty: TypeId::Int64,
16238                    flags: ColumnFlags::empty(),
16239                    default_value: None,
16240                    embedding_source: None,
16241                },
16242            ],
16243            indexes: Vec::new(),
16244            colocation: vec![],
16245            constraints: Default::default(),
16246            clustered: false,
16247        }
16248    }
16249
16250    #[test]
16251    fn multi_run_rows_for_rids_uses_hlc_winner_when_epoch_is_inverted() {
16252        let dir = tempdir().unwrap();
16253        let db = build_inverted_database(dir.path(), pk_schema());
16254        let table = db.table("t").unwrap();
16255        let table = table.lock();
16256        // HLC-pinned snapshot at HLC=600 — both rows are visible, the
16257        // HLC-newer (Run A) must win. An epoch-only fold would silently
16258        // return Run B's "older-by-HLC" payload because its epoch=2 > 1.
16259        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16260        let rows = table
16261            .rows_for_rids(&[7], snap)
16262            .expect("rows_for_rids across two runs");
16263        assert_eq!(rows.len(), 1, "one row materialised across two runs");
16264        assert_eq!(
16265            rows[0].columns.get(&2),
16266            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16267            "multi-run rows_for_rids must honor HLC authority"
16268        );
16269    }
16270
16271    #[test]
16272    fn multi_run_projected_column_uses_hlc_winner_when_epoch_is_inverted() {
16273        let dir = tempdir().unwrap();
16274        let db = build_inverted_database(dir.path(), pk_schema());
16275        let table = db.table("t").unwrap();
16276        let table = table.lock();
16277        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16278        let projected = table
16279            .values_for_rids_at(&[7], 2, snap, i64::MAX)
16280            .expect("values_for_rids_at across two runs");
16281        assert_eq!(projected.len(), 1);
16282        assert_eq!(
16283            projected[0].1,
16284            Value::Bytes(b"newer-by-HLC".to_vec()),
16285            "multi-run projection must pick the HLC-newer column"
16286        );
16287    }
16288
16289    #[test]
16290    fn ann_candidate_eligibility_uses_hlc_winner_across_runs() {
16291        let dir = tempdir().unwrap();
16292        let db = build_inverted_database(dir.path(), pk_schema());
16293        let table = db.table("t").unwrap();
16294        let table = table.lock();
16295        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16296        // ANN/Sparse/MinHash all funnel through `eligible_candidate_ids`.
16297        // The HLC-newer row must survive the visibility fold.
16298        let eligible = table
16299            .eligible_candidate_ids(&[RowId(7)], 2, snap, None)
16300            .expect("eligibility across runs");
16301        assert!(
16302            eligible.contains(&RowId(7)),
16303            "HLC-newer rid must remain eligible across runs"
16304        );
16305    }
16306
16307    #[test]
16308    fn ttl_inverted_run_is_admitted_via_values_for_rids_at() {
16309        let dir = tempdir().unwrap();
16310        let db = build_inverted_ttl_database(dir.path());
16311        let table = db.table("t").unwrap();
16312        let table = table.lock();
16313        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16314        let now_ns: i64 = 1_000_000_000;
16315        // HLC-newer row's ttl_ts = now+60s (live); HLC-older row's ttl_ts =
16316        // now-60s (expired). The TTL eligibility path must read the
16317        // timestamp from the HLC-newer run (live) and surface the rid.
16318        let projected = table
16319            .values_for_rids_at(&[7], 2, snap, now_ns)
16320            .expect("ttl-aware projection");
16321        assert_eq!(projected.len(), 1, "TTL must admit the HLC-newer row");
16322        assert_eq!(
16323            projected[0].1,
16324            Value::Bytes(b"newer-by-HLC".to_vec()),
16325            "TTL must be read from the HLC-newer run; older run's timestamp is expired"
16326        );
16327    }
16328
16329    #[test]
16330    fn hot_candidate_inspection_uses_full_snapshot_for_run_versions() {
16331        // The HOT-fallback inspection path. `inspect_row_at` is invoked via
16332        // `Table::get` for rid-resolved lookups (the same merge logic
16333        // applies); the test exercises the production read path and asserts
16334        // the HLC-newer payload wins across runs.
16335        let dir = tempdir().unwrap();
16336        let db = build_inverted_database(dir.path(), pk_schema());
16337        let table = db.table("t").unwrap();
16338        let table = table.lock();
16339        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16340        let row = table
16341            .get(RowId(7), snap)
16342            .expect("Table::get across two runs");
16343        assert_eq!(
16344            row.columns.get(&2),
16345            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16346            "Table::get must surface the HLC-newer winner"
16347        );
16348    }
16349
16350    #[test]
16351    fn learned_range_rebuild_indexes_only_hlc_visible_winners() {
16352        // The learned-range rebuild path (`build_learned_ranges_inner`) is
16353        // only exercised when the table has exactly one run; we therefore
16354        // exercise the more general `rebuild_indexes_from_runs` path, which
16355        // performs the global merge. After rebuild the projected column for
16356        // rid=7 must come from the HLC-newer run even though Run B was
16357        // iterated last.
16358        let dir = tempdir().unwrap();
16359        let db = build_inverted_database(dir.path(), pk_schema());
16360        let handle = db.table("t").unwrap();
16361        let mut table = handle.lock();
16362        table.rebuild_indexes_from_runs().expect("rebuild");
16363        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16364        let rows = table
16365            .rows_for_rids(&[7], snap)
16366            .expect("post-rebuild rows_for_rids");
16367        assert_eq!(rows.len(), 1);
16368        assert_eq!(
16369            rows[0].columns.get(&2),
16370            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16371            "post-rebuild row must be the HLC-newer winner"
16372        );
16373    }
16374
16375    #[test]
16376    fn rebuild_indexes_uses_global_hlc_winners_not_run_iteration_order() {
16377        // REM-001 §7.6: after `rebuild_indexes` the primary-key lookup and
16378        // the Bitmap index membership must both reflect the HLC-winning run,
16379        // not whichever run was iterated last.
16380        //
16381        // Close + reopen preservation of the HLC-newer winner is covered by
16382        // `sorted_run_hlc_visibility::reopen_from_disk_preserves_hlc_visibility`
16383        // (and by the merged `pk_equality_fallback` path through `Table::get`).
16384        // Re-running it on top of `rebuild_indexes` would require writing two
16385        // `Op::Put` records for the same rid across two WAL segments, which
16386        // trips the recovery-time duplicate-row-id guard — that guard is
16387        // orthogonal to REM-001 and would mask the actual fix we want to
16388        // exercise here.
16389        let dir = tempdir().unwrap();
16390        let db = build_inverted_database(dir.path(), pk_schema_with_bitmap());
16391        let handle = db.table("t").unwrap();
16392        let mut table = handle.lock();
16393        table.rebuild_indexes_from_runs().expect("rebuild");
16394        let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16395        // 1. PK lookup resolves to the HLC winner.
16396        let row = table.get(RowId(7), snap).expect("post-rebuild Table::get");
16397        assert_eq!(
16398            row.columns.get(&2),
16399            Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16400            "PK lookup must resolve to the HLC-newer winner"
16401        );
16402        // 2. Bitmap membership: name="newer-by-HLC" must contain rid=7
16403        //    and name="older-by-HLC" must NOT (the older version was
16404        //    suppressed by the global merge before indexing).
16405        let query_newer = Query::new().and(Condition::BitmapEq {
16406            column_id: 2,
16407            value: b"newer-by-HLC".to_vec(),
16408        });
16409        let rows_newer = table.query(&query_newer).expect("bitmap eq newer");
16410        let rids_newer: Vec<u64> = rows_newer.iter().map(|r| r.row_id.0).collect();
16411        assert!(
16412            rids_newer.contains(&7),
16413            "bitmap must include the HLC-newer value (got {rids_newer:?})"
16414        );
16415        let query_older = Query::new().and(Condition::BitmapEq {
16416            column_id: 2,
16417            value: b"older-by-HLC".to_vec(),
16418        });
16419        let rows_older = table.query(&query_older).expect("bitmap eq older");
16420        let rids_older: Vec<u64> = rows_older.iter().map(|r| r.row_id.0).collect();
16421        assert!(
16422            !rids_older.contains(&7),
16423            "bitmap must NOT include the HLC-older value (got {rids_older:?})"
16424        );
16425    }
16426
16427    #[test]
16428    fn version_stamp_is_newer_than_matches_snapshot_rule() {
16429        // Unit test for the new VersionStamp helper: HLC-newer wins despite
16430        // a smaller epoch; both-unstamped falls back to epoch.
16431        let early = hlc(100);
16432        let late = hlc(200);
16433        let newer = VersionStamp {
16434            epoch: Epoch(9),
16435            commit_ts: Some(late),
16436        };
16437        let older = VersionStamp {
16438            epoch: Epoch(50),
16439            commit_ts: Some(early),
16440        };
16441        assert!(newer.is_newer_than(older));
16442        assert!(!older.is_newer_than(newer));
16443        let a = VersionStamp {
16444            epoch: Epoch(5),
16445            commit_ts: None,
16446        };
16447        let b = VersionStamp {
16448            epoch: Epoch(4),
16449            commit_ts: None,
16450        };
16451        assert!(a.is_newer_than(b));
16452    }
16453}