1use 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 Memtable(RowId, Epoch, Cow<'a, Row>),
106 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 Self::Run(version) => version.commit_ts,
147 }
148 }
149}
150
151enum ControlledVisibleCursor<'a> {
152 Memory(std::vec::IntoIter<Row>),
154 MemoryStreaming {
158 active: std::vec::IntoIter<Row>,
159 rest: std::collections::btree_map::IntoValues<RowId, Row>,
160 batch_cap: usize,
161 #[allow(dead_code)]
163 peak_active: usize,
164 #[allow(dead_code)]
166 total: usize,
167 },
168 Memtable(MemtableVisibleVersionCursor<'a>),
172 MutableRun(MutableRunVisibleVersionCursor<'a>),
174 Run(Box<RunVisibleVersionCursor>),
175 #[cfg(test)]
176 Synthetic {
177 next: u64,
178 end: u64,
179 },
180}
181
182#[allow(dead_code)] const 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 #[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 #[allow(dead_code)] 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 #[allow(dead_code)] fn memtable_cursor(cursor: MemtableVisibleVersionCursor<'a>) -> Self {
235 Self {
236 cursor: ControlledVisibleCursor::Memtable(cursor),
237 current: None,
238 }
239 }
240
241 #[allow(dead_code)] 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 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 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); 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 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 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 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 #[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 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 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 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 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
733fn 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
798pub 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; pub(crate) const PAGE_CACHE_CAPACITY: u64 = 64 * 1024 * 1024; pub(crate) const DECODED_CACHE_CAPACITY: u64 = 64 * 1024 * 1024; const DEFAULT_MUTABLE_RUN_SPILL_BYTES: u64 = 8 * 1024 * 1024;
820
821#[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
850fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
873pub enum IndexBuildPolicy {
874 #[default]
876 Deferred,
877 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#[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
1007pub(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#[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 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 pub fn schema(&self) -> &Arc<Schema> {
1052 &self.schema
1053 }
1054
1055 pub fn base_runs(&self) -> &[RunRef] {
1057 &self.base_runs
1058 }
1059
1060 pub fn indexes(&self) -> &Arc<IndexGeneration> {
1062 &self.indexes
1063 }
1064
1065 pub fn visible_through(&self) -> Epoch {
1067 self.visible_through
1068 }
1069
1070 pub fn deltas(&self) -> &TableDeltas {
1074 &self.deltas
1075 }
1076}
1077
1078impl TableDeltas {
1079 pub fn approx_bytes(&self) -> u64 {
1082 self.memtable
1083 .approx_bytes()
1084 .saturating_add(self.mutable_run.approx_bytes())
1085 }
1086
1087 pub fn memtable_len(&self) -> usize {
1089 self.memtable.len()
1090 }
1091
1092 pub fn mutable_run_len(&self) -> usize {
1094 self.mutable_run.len()
1095 }
1096
1097 pub fn hot_len(&self) -> usize {
1099 self.hot.len()
1100 }
1101
1102 pub fn reverse_pk_len(&self) -> usize {
1104 self.pk_by_row.entries().len()
1105 }
1106}
1107
1108#[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 name: String,
1120 auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
1125 read_only: bool,
1128 durable_commit_failed: bool,
1132 wal: WalSink,
1133 memtable: Memtable,
1134 mutable_run: MutableRun,
1139 mutable_run_spill_bytes: u64,
1141 compaction_zstd_level: i32,
1144 allocator: RowIdAllocator,
1145 epoch: Arc<EpochAuthority>,
1146 data_generation: u64,
1149 schema: Schema,
1150 hot: HotIndex,
1151 kek: Option<Arc<Kek>>,
1154 column_keys: HashMap<u16, ([u8; 32], u8)>,
1158 run_refs: Vec<RunRef>,
1159 retiring: Vec<crate::manifest::RetiredRun>,
1162 next_run_id: u64,
1163 sync_byte_threshold: u64,
1164 current_txn_id: u64,
1169 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 learned_range: Arc<HashMap<u16, ColumnLearnedRange>>,
1181 pk_by_row: ReversePkMap,
1183 pinned: BTreeMap<Epoch, usize>,
1186 pub(crate) live_count: u64,
1189 reservoir: crate::reservoir::Reservoir,
1192 reservoir_complete: bool,
1200 had_deletes: bool,
1204 recent_delete_preimages: HashMap<Vec<u8>, Row>,
1209 run_row_id_ranges: HashMap<u128, (u64, u64)>,
1212 agg_cache: Arc<HashMap<u64, CachedAgg>>,
1216 global_idx_epoch: u64,
1220 indexes_complete: bool,
1225 index_build_policy: IndexBuildPolicy,
1227 pk_by_row_complete: bool,
1234 flushed_epoch: u64,
1237 page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
1240 snapshots: Arc<crate::retention::SnapshotRegistry>,
1243 commit_lock: Arc<parking_lot::Mutex<()>>,
1245 decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
1248 verified_runs: Arc<parking_lot::Mutex<std::collections::HashSet<u128>>>,
1258 result_cache: Arc<parking_lot::Mutex<ResultCache>>,
1267 wal_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1269 pending_delete_rids: roaring::RoaringBitmap,
1272 pending_put_cols: std::collections::HashSet<u16>,
1275 pending_rows: Vec<Row>,
1281 pending_rows_auto_inc: Vec<bool>,
1282 pending_dels: Vec<RowId>,
1285 pending_truncate: Option<Epoch>,
1289 auto_inc: Option<AutoIncState>,
1292 ttl: Option<TtlPolicy>,
1295 pins: Arc<crate::retention::PinRegistry>,
1302 published: Arc<ArcSwap<ReadGeneration>>,
1307 read_generation_pin: Option<Arc<crate::retention::PinGuard>>,
1312 pub(crate) lookup_metrics: LookupMetrics,
1317 run_lookup: RunLookupState,
1321}
1322
1323#[derive(Debug, Default, Clone)]
1331struct RunLookupState {
1332 directory: Option<std::sync::Arc<crate::run_lookup::RunLookupDirectory>>,
1333 fingerprint: u64,
1334 complete: bool,
1335}
1336
1337#[derive(Debug, Default)]
1338pub struct LookupMetrics {
1339 hot_lookup_hit: std::sync::atomic::AtomicU64,
1340 hot_lookup_fallback: std::sync::atomic::AtomicU64,
1341 hot_lookup_fallback_overlay_rows: std::sync::atomic::AtomicU64,
1342 hot_lookup_fallback_runs: std::sync::atomic::AtomicU64,
1343 result_cache_memory_hit: std::sync::atomic::AtomicU64,
1344 result_cache_disk_hit: std::sync::atomic::AtomicU64,
1345 result_cache_miss: std::sync::atomic::AtomicU64,
1346 result_cache_persistent_write_us: std::sync::atomic::AtomicU64,
1347 get_run_opened: std::sync::atomic::AtomicU64,
1349 get_run_skipped: std::sync::atomic::AtomicU64,
1350 pub(crate) directory_lookup_hit: std::sync::atomic::AtomicU64,
1352 pub(crate) directory_lookup_fallback: std::sync::atomic::AtomicU64,
1353 pub(crate) directory_incomplete: std::sync::atomic::AtomicU64,
1354 pub(crate) directory_run_readers_opened: std::sync::atomic::AtomicU64,
1355 pub(crate) directory_early_stop_total: std::sync::atomic::AtomicU64,
1356 pub(crate) directory_complete_miss_total: std::sync::atomic::AtomicU64,
1362 pub(crate) result_cache_persist_enqueued_total: std::sync::atomic::AtomicU64,
1364 pub(crate) result_cache_persist_coalesced_total: std::sync::atomic::AtomicU64,
1365 pub(crate) result_cache_persist_dropped_store_total: std::sync::atomic::AtomicU64,
1366 pub(crate) result_cache_persist_remove_total: std::sync::atomic::AtomicU64,
1367 pub(crate) result_cache_persist_stale_store_skipped_total: std::sync::atomic::AtomicU64,
1368 pub(crate) result_cache_persist_errors_total: std::sync::atomic::AtomicU64,
1369 pub(crate) result_cache_persist_shutdown_abandoned_total: std::sync::atomic::AtomicU64,
1370 pub(crate) result_cache_persist_queue_depth: std::sync::atomic::AtomicU64,
1371 pub(crate) hot_fallback_reasons: [std::sync::atomic::AtomicU64; 9],
1373 pub(crate) hot_fallback_overlay_versions_total: std::sync::atomic::AtomicU64,
1374 pub(crate) hot_fallback_runs_considered_total: std::sync::atomic::AtomicU64,
1375 pub(crate) hot_fallback_runs_opened_total: std::sync::atomic::AtomicU64,
1376 pub(crate) hot_fallback_pages_decoded_total: std::sync::atomic::AtomicU64,
1377 pub(crate) hot_fallback_rows_materialized_total: std::sync::atomic::AtomicU64,
1378 pub(crate) hot_lookup_duration_nanos: std::sync::atomic::AtomicU64,
1379 pub(crate) hot_fallback_duration_nanos: std::sync::atomic::AtomicU64,
1380 pub(crate) hot_mapping_rebuild_total: std::sync::atomic::AtomicU64,
1381 pub(crate) hot_checkpoint_rejected_total: std::sync::atomic::AtomicU64,
1382}
1383
1384impl Clone for LookupMetrics {
1385 fn clone(&self) -> Self {
1386 let mut hot_fallback_reasons = [
1387 std::sync::atomic::AtomicU64::new(0),
1388 std::sync::atomic::AtomicU64::new(0),
1389 std::sync::atomic::AtomicU64::new(0),
1390 std::sync::atomic::AtomicU64::new(0),
1391 std::sync::atomic::AtomicU64::new(0),
1392 std::sync::atomic::AtomicU64::new(0),
1393 std::sync::atomic::AtomicU64::new(0),
1394 std::sync::atomic::AtomicU64::new(0),
1395 std::sync::atomic::AtomicU64::new(0),
1396 ];
1397 for (dst, src) in hot_fallback_reasons
1398 .iter_mut()
1399 .zip(self.hot_fallback_reasons.iter())
1400 {
1401 dst.store(
1402 src.load(std::sync::atomic::Ordering::Relaxed),
1403 std::sync::atomic::Ordering::Relaxed,
1404 );
1405 }
1406 let copy_atomic = |src: &std::sync::atomic::AtomicU64| {
1407 std::sync::atomic::AtomicU64::new(src.load(std::sync::atomic::Ordering::Relaxed))
1408 };
1409 Self {
1410 hot_lookup_hit: copy_atomic(&self.hot_lookup_hit),
1411 hot_lookup_fallback: copy_atomic(&self.hot_lookup_fallback),
1412 hot_lookup_fallback_overlay_rows: copy_atomic(&self.hot_lookup_fallback_overlay_rows),
1413 hot_lookup_fallback_runs: copy_atomic(&self.hot_lookup_fallback_runs),
1414 result_cache_memory_hit: copy_atomic(&self.result_cache_memory_hit),
1415 result_cache_disk_hit: copy_atomic(&self.result_cache_disk_hit),
1416 result_cache_miss: copy_atomic(&self.result_cache_miss),
1417 result_cache_persistent_write_us: copy_atomic(&self.result_cache_persistent_write_us),
1418 get_run_opened: copy_atomic(&self.get_run_opened),
1419 get_run_skipped: copy_atomic(&self.get_run_skipped),
1420 directory_lookup_hit: copy_atomic(&self.directory_lookup_hit),
1421 directory_lookup_fallback: copy_atomic(&self.directory_lookup_fallback),
1422 directory_incomplete: copy_atomic(&self.directory_incomplete),
1423 directory_run_readers_opened: copy_atomic(&self.directory_run_readers_opened),
1424 directory_early_stop_total: copy_atomic(&self.directory_early_stop_total),
1425 directory_complete_miss_total: copy_atomic(&self.directory_complete_miss_total),
1426 result_cache_persist_enqueued_total: copy_atomic(
1427 &self.result_cache_persist_enqueued_total,
1428 ),
1429 result_cache_persist_coalesced_total: copy_atomic(
1430 &self.result_cache_persist_coalesced_total,
1431 ),
1432 result_cache_persist_dropped_store_total: copy_atomic(
1433 &self.result_cache_persist_dropped_store_total,
1434 ),
1435 result_cache_persist_remove_total: copy_atomic(&self.result_cache_persist_remove_total),
1436 result_cache_persist_stale_store_skipped_total: copy_atomic(
1437 &self.result_cache_persist_stale_store_skipped_total,
1438 ),
1439 result_cache_persist_errors_total: copy_atomic(&self.result_cache_persist_errors_total),
1440 result_cache_persist_shutdown_abandoned_total: copy_atomic(
1441 &self.result_cache_persist_shutdown_abandoned_total,
1442 ),
1443 result_cache_persist_queue_depth: copy_atomic(&self.result_cache_persist_queue_depth),
1444 hot_fallback_reasons,
1445 hot_fallback_overlay_versions_total: copy_atomic(
1446 &self.hot_fallback_overlay_versions_total,
1447 ),
1448 hot_fallback_runs_considered_total: copy_atomic(
1449 &self.hot_fallback_runs_considered_total,
1450 ),
1451 hot_fallback_runs_opened_total: copy_atomic(&self.hot_fallback_runs_opened_total),
1452 hot_fallback_pages_decoded_total: copy_atomic(&self.hot_fallback_pages_decoded_total),
1453 hot_fallback_rows_materialized_total: copy_atomic(
1454 &self.hot_fallback_rows_materialized_total,
1455 ),
1456 hot_lookup_duration_nanos: copy_atomic(&self.hot_lookup_duration_nanos),
1457 hot_fallback_duration_nanos: copy_atomic(&self.hot_fallback_duration_nanos),
1458 hot_mapping_rebuild_total: copy_atomic(&self.hot_mapping_rebuild_total),
1459 hot_checkpoint_rejected_total: copy_atomic(&self.hot_checkpoint_rejected_total),
1460 }
1461 }
1462}
1463
1464impl LookupMetrics {
1465 fn snapshot(&self) -> LookupMetricsSnapshot {
1466 LookupMetricsSnapshot {
1467 hot_lookup_hit: self
1468 .hot_lookup_hit
1469 .load(std::sync::atomic::Ordering::Relaxed),
1470 hot_lookup_fallback: self
1471 .hot_lookup_fallback
1472 .load(std::sync::atomic::Ordering::Relaxed),
1473 hot_lookup_fallback_overlay_rows: self
1474 .hot_lookup_fallback_overlay_rows
1475 .load(std::sync::atomic::Ordering::Relaxed),
1476 hot_lookup_fallback_runs: self
1477 .hot_lookup_fallback_runs
1478 .load(std::sync::atomic::Ordering::Relaxed),
1479 result_cache_memory_hit: self
1480 .result_cache_memory_hit
1481 .load(std::sync::atomic::Ordering::Relaxed),
1482 result_cache_disk_hit: self
1483 .result_cache_disk_hit
1484 .load(std::sync::atomic::Ordering::Relaxed),
1485 result_cache_miss: self
1486 .result_cache_miss
1487 .load(std::sync::atomic::Ordering::Relaxed),
1488 result_cache_persistent_write_us: self
1489 .result_cache_persistent_write_us
1490 .load(std::sync::atomic::Ordering::Relaxed),
1491 get_run_opened: self
1492 .get_run_opened
1493 .load(std::sync::atomic::Ordering::Relaxed),
1494 get_run_skipped: self
1495 .get_run_skipped
1496 .load(std::sync::atomic::Ordering::Relaxed),
1497 directory_lookup_hit: self
1498 .directory_lookup_hit
1499 .load(std::sync::atomic::Ordering::Relaxed),
1500 directory_lookup_fallback: self
1501 .directory_lookup_fallback
1502 .load(std::sync::atomic::Ordering::Relaxed),
1503 directory_incomplete: self
1504 .directory_incomplete
1505 .load(std::sync::atomic::Ordering::Relaxed),
1506 directory_run_readers_opened: self
1507 .directory_run_readers_opened
1508 .load(std::sync::atomic::Ordering::Relaxed),
1509 directory_early_stop_total: self
1510 .directory_early_stop_total
1511 .load(std::sync::atomic::Ordering::Relaxed),
1512 directory_complete_miss_total: self
1513 .directory_complete_miss_total
1514 .load(std::sync::atomic::Ordering::Relaxed),
1515 result_cache_persist_enqueued_total: self
1516 .result_cache_persist_enqueued_total
1517 .load(std::sync::atomic::Ordering::Relaxed),
1518 result_cache_persist_coalesced_total: self
1519 .result_cache_persist_coalesced_total
1520 .load(std::sync::atomic::Ordering::Relaxed),
1521 result_cache_persist_dropped_store_total: self
1522 .result_cache_persist_dropped_store_total
1523 .load(std::sync::atomic::Ordering::Relaxed),
1524 result_cache_persist_remove_total: self
1525 .result_cache_persist_remove_total
1526 .load(std::sync::atomic::Ordering::Relaxed),
1527 result_cache_persist_stale_store_skipped_total: self
1528 .result_cache_persist_stale_store_skipped_total
1529 .load(std::sync::atomic::Ordering::Relaxed),
1530 result_cache_persist_errors_total: self
1531 .result_cache_persist_errors_total
1532 .load(std::sync::atomic::Ordering::Relaxed),
1533 result_cache_persist_shutdown_abandoned_total: self
1534 .result_cache_persist_shutdown_abandoned_total
1535 .load(std::sync::atomic::Ordering::Relaxed),
1536 result_cache_persist_queue_depth: self
1537 .result_cache_persist_queue_depth
1538 .load(std::sync::atomic::Ordering::Relaxed),
1539 result_cache_persist_unavailable_total: 0,
1543 result_cache_persist_skipped_total: 0,
1544 result_cache_worker_spawn_failures_total: 0,
1545 result_cache_worker_shutdown_total: 0,
1546 hot_fallback_reasons: [
1547 self.hot_fallback_reasons[0].load(std::sync::atomic::Ordering::Relaxed),
1548 self.hot_fallback_reasons[1].load(std::sync::atomic::Ordering::Relaxed),
1549 self.hot_fallback_reasons[2].load(std::sync::atomic::Ordering::Relaxed),
1550 self.hot_fallback_reasons[3].load(std::sync::atomic::Ordering::Relaxed),
1551 self.hot_fallback_reasons[4].load(std::sync::atomic::Ordering::Relaxed),
1552 self.hot_fallback_reasons[5].load(std::sync::atomic::Ordering::Relaxed),
1553 self.hot_fallback_reasons[6].load(std::sync::atomic::Ordering::Relaxed),
1554 self.hot_fallback_reasons[7].load(std::sync::atomic::Ordering::Relaxed),
1555 self.hot_fallback_reasons[8].load(std::sync::atomic::Ordering::Relaxed),
1556 ],
1557 hot_fallback_overlay_versions_total: self
1558 .hot_fallback_overlay_versions_total
1559 .load(std::sync::atomic::Ordering::Relaxed),
1560 hot_fallback_runs_considered_total: self
1561 .hot_fallback_runs_considered_total
1562 .load(std::sync::atomic::Ordering::Relaxed),
1563 hot_fallback_runs_opened_total: self
1564 .hot_fallback_runs_opened_total
1565 .load(std::sync::atomic::Ordering::Relaxed),
1566 hot_fallback_pages_decoded_total: self
1567 .hot_fallback_pages_decoded_total
1568 .load(std::sync::atomic::Ordering::Relaxed),
1569 hot_fallback_rows_materialized_total: self
1570 .hot_fallback_rows_materialized_total
1571 .load(std::sync::atomic::Ordering::Relaxed),
1572 hot_lookup_duration_nanos: self
1573 .hot_lookup_duration_nanos
1574 .load(std::sync::atomic::Ordering::Relaxed),
1575 hot_fallback_duration_nanos: self
1576 .hot_fallback_duration_nanos
1577 .load(std::sync::atomic::Ordering::Relaxed),
1578 hot_mapping_rebuild_total: self
1579 .hot_mapping_rebuild_total
1580 .load(std::sync::atomic::Ordering::Relaxed),
1581 hot_checkpoint_rejected_total: self
1582 .hot_checkpoint_rejected_total
1583 .load(std::sync::atomic::Ordering::Relaxed),
1584 }
1585 }
1586}
1587
1588#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1591pub struct LookupMetricsSnapshot {
1592 pub hot_lookup_hit: u64,
1593 pub hot_lookup_fallback: u64,
1594 pub hot_lookup_fallback_overlay_rows: u64,
1595 pub hot_lookup_fallback_runs: u64,
1596 pub result_cache_memory_hit: u64,
1597 pub result_cache_disk_hit: u64,
1598 pub result_cache_miss: u64,
1599 pub result_cache_persistent_write_us: u64,
1600 pub get_run_opened: u64,
1601 pub get_run_skipped: u64,
1602 pub directory_lookup_hit: u64,
1604 pub directory_lookup_fallback: u64,
1605 pub directory_incomplete: u64,
1606 pub directory_run_readers_opened: u64,
1607 pub directory_early_stop_total: u64,
1608 pub directory_complete_miss_total: u64,
1609 pub result_cache_persist_enqueued_total: u64,
1611 pub result_cache_persist_coalesced_total: u64,
1612 pub result_cache_persist_dropped_store_total: u64,
1613 pub result_cache_persist_remove_total: u64,
1614 pub result_cache_persist_stale_store_skipped_total: u64,
1615 pub result_cache_persist_errors_total: u64,
1616 pub result_cache_persist_shutdown_abandoned_total: u64,
1617 pub result_cache_persist_queue_depth: u64,
1618 pub result_cache_persist_unavailable_total: u64,
1622 pub result_cache_persist_skipped_total: u64,
1625 pub result_cache_worker_spawn_failures_total: u64,
1627 pub result_cache_worker_shutdown_total: u64,
1629 pub hot_fallback_reasons: [u64; 9],
1631 pub hot_fallback_overlay_versions_total: u64,
1632 pub hot_fallback_runs_considered_total: u64,
1633 pub hot_fallback_runs_opened_total: u64,
1634 pub hot_fallback_pages_decoded_total: u64,
1635 pub hot_fallback_rows_materialized_total: u64,
1636 pub hot_lookup_duration_nanos: u64,
1637 pub hot_fallback_duration_nanos: u64,
1638 pub hot_mapping_rebuild_total: u64,
1639 pub hot_checkpoint_rejected_total: u64,
1640}
1641
1642pub fn hot_fallback_reason_index(r: crate::trace::HotFallbackReason) -> usize {
1645 match r {
1646 crate::trace::HotFallbackReason::MissingMapping => 0,
1647 crate::trace::HotFallbackReason::StaleRowId => 1,
1648 crate::trace::HotFallbackReason::InvisibleAtSnapshot => 2,
1649 crate::trace::HotFallbackReason::HistoricalSnapshot => 3,
1650 crate::trace::HotFallbackReason::Tombstone => 4,
1651 crate::trace::HotFallbackReason::TtlExpired => 5,
1652 crate::trace::HotFallbackReason::PrimaryKeyMismatch => 6,
1653 crate::trace::HotFallbackReason::IndexIncomplete => 7,
1654 crate::trace::HotFallbackReason::CheckpointRejected => 8,
1655 }
1656}
1657
1658const _: () = {
1665 const fn assert_sync<T: ?Sized + Sync>() {}
1666 assert_sync::<Table>();
1667};
1668
1669#[derive(Clone)]
1675enum CachedData {
1676 Rows(Arc<Vec<Row>>),
1677 Columns(Arc<Vec<(u16, columnar::NativeColumn)>>),
1678}
1679
1680impl CachedData {
1681 fn approx_bytes(&self) -> u64 {
1682 match self {
1683 CachedData::Rows(r) => r.iter().map(|r| r.estimated_bytes()).sum::<u64>(),
1684 CachedData::Columns(c) => c
1685 .iter()
1686 .map(|(_, c)| c.approx_bytes())
1687 .sum::<u64>()
1688 .saturating_add(c.len() as u64 * 16),
1689 }
1690 }
1691}
1692
1693struct CachedEntry {
1697 data: CachedData,
1698 footprint: roaring::RoaringBitmap,
1699 condition_cols: Vec<u16>,
1700}
1701
1702impl CachedEntry {
1703 fn clone_for_persist(&self) -> Self {
1709 Self {
1710 data: self.data.clone(),
1711 footprint: self.footprint.clone(),
1712 condition_cols: self.condition_cols.clone(),
1713 }
1714 }
1715}
1716
1717struct ResultCache {
1730 entries: std::collections::HashMap<u64, CachedEntry>,
1731 order: BTreeSet<(u64, u64)>,
1732 generations: HashMap<u64, u64>,
1733 next_generation: u64,
1734 condition_index: HashMap<u16, HashSet<u64>>,
1737 empty_footprint_entries: HashSet<u64>,
1740 bytes: u64,
1741 max_bytes: u64,
1742 dir: Option<std::path::PathBuf>,
1743 #[allow(dead_code)]
1744 cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
1745 memory_hit: std::sync::atomic::AtomicU64,
1749 disk_hit: std::sync::atomic::AtomicU64,
1750 miss: std::sync::atomic::AtomicU64,
1751 persistent_write_us: std::sync::atomic::AtomicU64,
1752 persist_min_bytes: u64,
1757 persistence: PersistentPublicationState,
1764 worker_handle: Option<std::thread::JoinHandle<()>>,
1767 completion_rx: Option<std::sync::mpsc::Receiver<()>>,
1772 cache_payload_cipher: Option<std::sync::Arc<crate::encryption::AesCipher>>,
1776 persist_unavailable_total: std::sync::atomic::AtomicU64,
1780 persist_skipped_total: std::sync::atomic::AtomicU64,
1782 worker_spawn_failures_total: std::sync::atomic::AtomicU64,
1784 worker_shutdown_total: std::sync::atomic::AtomicU64,
1786}
1787
1788#[derive(serde::Serialize, serde::Deserialize)]
1790struct SerializedEntry {
1791 condition_cols: Vec<u16>,
1792 footprint_bits: Vec<u32>,
1793 data: SerializedData,
1794}
1795
1796#[derive(serde::Serialize, serde::Deserialize)]
1797enum SerializedData {
1798 Rows(Vec<Row>),
1799 Columns(Vec<(u16, columnar::NativeColumn)>),
1800}
1801
1802#[derive(serde::Serialize)]
1803struct SerializedEntryRef<'a> {
1804 condition_cols: &'a [u16],
1805 footprint_bits: Vec<u32>,
1806 data: SerializedDataRef<'a>,
1807}
1808
1809#[derive(serde::Serialize)]
1810enum SerializedDataRef<'a> {
1811 Rows(&'a [Row]),
1812 Columns(&'a [(u16, columnar::NativeColumn)]),
1813}
1814
1815impl<'a> SerializedEntryRef<'a> {
1816 fn from_entry(entry: &'a CachedEntry) -> Self {
1817 let footprint_bits: Vec<u32> = entry.footprint.iter().collect();
1818 let data = match &entry.data {
1819 CachedData::Rows(rows) => SerializedDataRef::Rows(rows.as_slice()),
1820 CachedData::Columns(columns) => SerializedDataRef::Columns(columns.as_slice()),
1821 };
1822 Self {
1823 condition_cols: &entry.condition_cols,
1824 footprint_bits,
1825 data,
1826 }
1827 }
1828}
1829
1830impl SerializedEntry {
1831 fn into_entry(self) -> Option<CachedEntry> {
1832 let footprint: roaring::RoaringBitmap = self.footprint_bits.into_iter().collect();
1833 let data = match self.data {
1834 SerializedData::Rows(r) => CachedData::Rows(Arc::new(r)),
1835 SerializedData::Columns(c) => {
1836 if !c.iter().all(|(_, col)| col.validate()) {
1839 return None;
1840 }
1841 CachedData::Columns(Arc::new(c))
1842 }
1843 };
1844 Some(CachedEntry {
1845 data,
1846 footprint,
1847 condition_cols: self.condition_cols,
1848 })
1849 }
1850}
1851
1852impl ResultCache {
1853 const DEFAULT_MAX_BYTES: u64 = 256 * 1024 * 1024;
1854
1855 fn new() -> Self {
1856 Self::with_max_bytes(Self::DEFAULT_MAX_BYTES)
1857 }
1858
1859 fn with_max_bytes(max_bytes: u64) -> Self {
1860 Self {
1861 entries: std::collections::HashMap::new(),
1862 order: BTreeSet::new(),
1863 generations: HashMap::new(),
1864 next_generation: 0,
1865 condition_index: HashMap::new(),
1866 empty_footprint_entries: HashSet::new(),
1867 bytes: 0,
1868 max_bytes,
1869 dir: None,
1870 cache_dek: None,
1871 memory_hit: std::sync::atomic::AtomicU64::new(0),
1872 disk_hit: std::sync::atomic::AtomicU64::new(0),
1873 miss: std::sync::atomic::AtomicU64::new(0),
1874 persistent_write_us: std::sync::atomic::AtomicU64::new(0),
1875 persist_min_bytes: 4 * 1024,
1878 persistence: PersistentPublicationState::Disabled(
1879 PersistenceDisabledReason::NoDirectory,
1880 ),
1881 worker_handle: None,
1882 completion_rx: None,
1883 cache_payload_cipher: None,
1884 persist_unavailable_total: std::sync::atomic::AtomicU64::new(0),
1885 persist_skipped_total: std::sync::atomic::AtomicU64::new(0),
1886 worker_spawn_failures_total: std::sync::atomic::AtomicU64::new(0),
1887 worker_shutdown_total: std::sync::atomic::AtomicU64::new(0),
1888 }
1889 }
1890
1891 fn with_dir(mut self, dir: std::path::PathBuf) -> Self {
1892 let _ = std::fs::create_dir_all(&dir);
1893 self.dir = Some(dir);
1894 if matches!(
1895 self.persistence,
1896 PersistentPublicationState::Disabled(PersistenceDisabledReason::NoDirectory)
1897 ) {
1898 self.persistence =
1899 PersistentPublicationState::Disabled(PersistenceDisabledReason::QueueUnavailable);
1900 }
1901 self
1902 }
1903
1904 fn with_cache_dek(mut self, dek: Option<Zeroizing<[u8; DEK_LEN]>>) -> Self {
1905 self.cache_dek = dek.clone();
1911 if let Some(dek) = dek {
1912 if let Ok(cipher) = crate::encryption::AesCipher::new(&dek[..]) {
1913 self.cache_payload_cipher = Some(std::sync::Arc::new(cipher));
1914 }
1915 }
1916 self
1917 }
1918
1919 fn install_persistent_writer(
1924 &mut self,
1925 writer: std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
1926 worker_handle: std::thread::JoinHandle<()>,
1927 completion_rx: std::sync::mpsc::Receiver<()>,
1928 ) {
1929 self.persistence = PersistentPublicationState::Async(writer);
1930 self.worker_handle = Some(worker_handle);
1931 self.completion_rx = Some(completion_rx);
1932 }
1933
1934 fn note_worker_spawn_failure(&mut self) {
1939 self.worker_spawn_failures_total
1940 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1941 self.persist_unavailable_total
1942 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1943 self.persistence =
1944 PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerSpawnFailed);
1945 }
1946
1947 fn take_persistent_worker(&mut self) -> Option<std::thread::JoinHandle<()>> {
1950 self.worker_handle.take()
1951 }
1952
1953 fn take_persistent_completion(&mut self) -> Option<std::sync::mpsc::Receiver<()>> {
1956 self.completion_rx.take()
1957 }
1958
1959 fn persistent_writer(
1962 &self,
1963 ) -> Option<&std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>> {
1964 match &self.persistence {
1965 PersistentPublicationState::Async(writer) => Some(writer),
1966 PersistentPublicationState::Disabled(_) => None,
1967 }
1968 }
1969
1970 fn disk_path(&self, key: u64) -> Option<std::path::PathBuf> {
1971 self.dir.as_ref().map(|d| d.join(format!("{key:016x}.bin")))
1972 }
1973
1974 fn persist_entry_synchronously_for_maintenance(
1986 &self,
1987 context: PersistContext,
1988 entry: &CachedEntry,
1989 ) {
1990 let Some(path) = self.disk_path(context.key) else {
1991 return;
1992 };
1993 let serialized = match bincode::serialize(&SerializedEntryRef::from_entry(entry)) {
1994 Ok(s) => s,
1995 Err(_) => return,
1996 };
1997 let bytes = match crate::result_cache::encode_persisted_entry(
1998 context,
1999 &serialized,
2000 self.cache_payload_cipher.as_deref(),
2001 ) {
2002 Ok(b) => b,
2003 Err(_) => return,
2004 };
2005 let tmp = path.with_extension("tmp");
2006 use std::io::Write;
2007 let write = || -> std::io::Result<()> {
2008 let mut f = std::fs::File::create(&tmp)?;
2009 f.write_all(&bytes)?;
2010 f.flush()?;
2011 f.sync_all()?;
2012 Ok(())
2013 };
2014 if write().is_err() {
2015 let _ = std::fs::remove_file(&tmp);
2016 return;
2017 }
2018 if std::fs::rename(&tmp, &path).is_err() {
2019 let _ = std::fs::remove_file(&tmp);
2020 return;
2021 }
2022 if let Ok(dir) = std::fs::File::open(self.dir.as_ref().expect("dir set").clone()) {
2023 let _ = dir.sync_all();
2024 }
2025 }
2026
2027 fn load_from_disk(&self, key: u64, identity: PersistentCacheIdentity) -> Option<CachedEntry> {
2033 let path = self.disk_path(key)?;
2034 let bytes = std::fs::read(&path).ok()?;
2035 if bytes.len() < FRAME_MAGIC.len() || bytes[..FRAME_MAGIC.len()] != FRAME_MAGIC {
2039 let _ = std::fs::remove_file(&path);
2040 return None;
2041 }
2042 let plaintext = match crate::result_cache::decode_persisted_entry(
2043 identity,
2044 key,
2045 &bytes,
2046 self.cache_payload_cipher.as_deref(),
2047 ) {
2048 Ok(p) => p,
2049 Err(_) => {
2050 let _ = std::fs::remove_file(&path);
2051 return None;
2052 }
2053 };
2054 let serialized: SerializedEntry = match bincode::deserialize(&plaintext) {
2055 Ok(s) => s,
2056 Err(_) => {
2057 let _ = std::fs::remove_file(&path);
2058 return None;
2059 }
2060 };
2061 serialized.into_entry()
2062 }
2063
2064 fn remove_from_disk(&self, key: u64) {
2066 if let Some(path) = self.disk_path(key) {
2067 let _ = std::fs::remove_file(&path);
2068 }
2069 }
2070
2071 fn load_persistent(&mut self, identity: PersistentCacheIdentity) {
2075 let Some(dir) = self.dir.as_ref().cloned() else {
2076 return;
2077 };
2078 let entries = match std::fs::read_dir(&dir) {
2079 Ok(e) => e,
2080 Err(_) => return,
2081 };
2082 for entry in entries.flatten() {
2083 let path = entry.path();
2084 if path.extension().and_then(|e| e.to_str()) == Some("tmp") {
2086 let _ = std::fs::remove_file(&path);
2087 continue;
2088 }
2089 if path.extension().and_then(|e| e.to_str()) != Some("bin") {
2090 continue;
2091 }
2092 let stem = match path.file_stem().and_then(|s| s.to_str()) {
2093 Some(s) => s,
2094 None => continue,
2095 };
2096 let key = match u64::from_str_radix(stem, 16) {
2097 Ok(k) => k,
2098 Err(_) => continue,
2099 };
2100 if let Some(entry) = self.load_from_disk(key, identity) {
2104 self.bytes = self.bytes.saturating_add(entry.data.approx_bytes());
2105 self.index_entry(key, &entry);
2106 self.entries.insert(key, entry);
2107 self.touch(key);
2108 }
2109 }
2110 self.evict();
2111 }
2112
2113 fn set_max_bytes(&mut self, max_bytes: u64) {
2114 self.max_bytes = max_bytes;
2115 self.evict();
2116 }
2117
2118 fn touch(&mut self, key: u64) {
2121 if !self.entries.contains_key(&key) {
2122 return;
2123 }
2124 if let Some(previous) = self.generations.remove(&key) {
2125 self.order.remove(&(previous, key));
2126 }
2127 let generation = self.allocate_generation();
2128 self.generations.insert(key, generation);
2129 self.order.insert((generation, key));
2130 }
2131
2132 fn untrack(&mut self, key: u64) {
2133 if let Some(generation) = self.generations.remove(&key) {
2134 self.order.remove(&(generation, key));
2135 }
2136 }
2137
2138 fn index_entry(&mut self, key: u64, entry: &CachedEntry) {
2139 for column in &entry.condition_cols {
2140 self.condition_index.entry(*column).or_default().insert(key);
2141 }
2142 if entry.footprint.is_empty() {
2143 self.empty_footprint_entries.insert(key);
2144 }
2145 }
2146
2147 fn unindex_entry(&mut self, key: u64, entry: &CachedEntry) {
2148 for column in &entry.condition_cols {
2149 let remove_column = self.condition_index.get_mut(column).is_some_and(|keys| {
2150 keys.remove(&key);
2151 keys.is_empty()
2152 });
2153 if remove_column {
2154 self.condition_index.remove(column);
2155 }
2156 }
2157 if entry.footprint.is_empty() {
2158 self.empty_footprint_entries.remove(&key);
2159 }
2160 }
2161
2162 fn allocate_generation(&mut self) -> u64 {
2163 if self.next_generation == u64::MAX {
2164 self.rebase_generations();
2165 }
2166 let generation = self.next_generation;
2167 self.next_generation += 1;
2168 generation
2169 }
2170
2171 fn rebase_generations(&mut self) {
2172 let ordered = std::mem::take(&mut self.order);
2173 self.generations.clear();
2174 for (generation, (_, key)) in ordered.into_iter().enumerate() {
2175 let generation = generation as u64;
2176 self.generations.insert(key, generation);
2177 self.order.insert((generation, key));
2178 }
2179 self.next_generation = self.order.len() as u64;
2180 }
2181
2182 fn get_rows(&mut self, key: u64, identity: PersistentCacheIdentity) -> Option<Arc<Vec<Row>>> {
2183 let res = self.entries.get(&key).and_then(|e| match &e.data {
2184 CachedData::Rows(r) => Some(r.clone()),
2185 CachedData::Columns(_) => None,
2186 });
2187 if res.is_some() {
2188 self.touch(key);
2189 self.memory_hit
2190 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2191 return res;
2192 }
2193 if let Some(entry) = self.load_from_disk(key, identity) {
2195 let res = match &entry.data {
2196 CachedData::Rows(r) => Some(r.clone()),
2197 CachedData::Columns(_) => None,
2198 };
2199 if res.is_some() {
2200 let approx = entry.data.approx_bytes();
2201 self.bytes = self.bytes.saturating_add(approx);
2202 self.index_entry(key, &entry);
2203 self.entries.insert(key, entry);
2204 self.touch(key);
2205 self.evict();
2206 self.disk_hit
2207 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2208 return res;
2209 }
2210 }
2211 self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2212 None
2213 }
2214
2215 fn get_columns(
2216 &mut self,
2217 key: u64,
2218 identity: PersistentCacheIdentity,
2219 ) -> Option<Arc<Vec<(u16, columnar::NativeColumn)>>> {
2220 let res = self.entries.get(&key).and_then(|e| match &e.data {
2221 CachedData::Columns(c) => Some(c.clone()),
2222 CachedData::Rows(_) => None,
2223 });
2224 if res.is_some() {
2225 self.touch(key);
2226 self.memory_hit
2227 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2228 return res;
2229 }
2230 if let Some(entry) = self.load_from_disk(key, identity) {
2232 let res = match &entry.data {
2233 CachedData::Columns(c) => Some(c.clone()),
2234 CachedData::Rows(_) => None,
2235 };
2236 if res.is_some() {
2237 let approx = entry.data.approx_bytes();
2238 self.bytes = self.bytes.saturating_add(approx);
2239 self.index_entry(key, &entry);
2240 self.entries.insert(key, entry);
2241 self.touch(key);
2242 self.evict();
2243 self.disk_hit
2244 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2245 return res;
2246 }
2247 }
2248 self.miss.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2249 None
2250 }
2251
2252 fn insert(&mut self, key: u64, entry: CachedEntry) {
2257 let approx = entry.data.approx_bytes();
2258 if let Some(previous) = self.entries.remove(&key) {
2259 self.bytes = self.bytes.saturating_sub(previous.data.approx_bytes());
2260 self.unindex_entry(key, &previous);
2261 self.untrack(key);
2262 }
2263 self.bytes = self.bytes.saturating_add(approx);
2264 self.index_entry(key, &entry);
2265 self.entries.insert(key, entry);
2266 self.touch(key);
2267 self.evict();
2268 }
2269
2270 fn persist_entry(&self, context: PersistContext, entry: &CachedEntry) {
2276 let approx = entry.data.approx_bytes();
2277 if self.dir.is_none() {
2278 return;
2279 }
2280 if self.persist_min_bytes > 0 && approx < self.persist_min_bytes {
2281 return;
2282 }
2283 match &self.persistence {
2284 PersistentPublicationState::Async(writer) => {
2285 let entry_clone = entry.clone_for_persist();
2289 let payload_factory: Box<dyn FnOnce() -> Option<Vec<u8>> + Send + 'static> =
2290 Box::new(move || {
2291 bincode::serialize(&SerializedEntryRef::from_entry(&entry_clone)).ok()
2292 });
2293 let persistable = crate::result_cache::PersistableEntry {
2294 key: context.key,
2295 table_id: context.identity.table_id,
2296 schema_id: context.identity.schema_id,
2297 run_generation: context.identity.logical_generation,
2298 entry_generation: context.entry_generation,
2299 bytes: approx as usize,
2300 payload_factory,
2301 };
2302 let write_start = std::time::Instant::now();
2303 writer.enqueue_store(persistable);
2304 let write_us = write_start.elapsed().as_micros() as u64;
2305 self.persistent_write_us
2306 .fetch_add(write_us, std::sync::atomic::Ordering::Relaxed);
2307 }
2308 PersistentPublicationState::Disabled(reason) => {
2309 self.persist_skipped_total
2314 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2315 crate::trace::QueryTrace::record(|trace| {
2316 trace.result_cache_persist_skipped = true;
2317 trace.result_cache_persist_skip_reason = Some(reason.label());
2318 });
2319 }
2320 }
2321 }
2322
2323 fn allocate_persist_generation(&mut self, key: u64) -> u64 {
2328 if let Some(writer) = self.persistent_writer() {
2329 let _ = key; writer.bump_persist_generation(key)
2333 } else {
2334 0
2335 }
2336 }
2337
2338 fn enqueue_persist_remove(&self, key: u64) {
2341 if let Some(writer) = self.persistent_writer() {
2342 writer.enqueue_remove(key);
2343 }
2344 }
2345
2346 fn enqueue_persist_clear(&self) {
2353 if let Some(writer) = self.persistent_writer() {
2354 writer.enqueue_clear();
2355 }
2356 }
2357
2358 fn flush_persistent_cache(&self, deadline: std::time::Duration) -> u64 {
2364 let Some(writer) = self.persistent_writer() else {
2365 return 0;
2366 };
2367 let start = std::time::Instant::now();
2368 loop {
2369 let depth = writer.queue_depth() as u64;
2370 let in_flight = writer.writes_in_flight();
2376 if depth == 0 && in_flight == 0 {
2377 return 0;
2378 }
2379 if start.elapsed() >= deadline {
2380 return depth;
2381 }
2382 std::thread::sleep(std::time::Duration::from_millis(2));
2383 }
2384 }
2385
2386 fn shutdown_persistent_cache(&mut self, deadline: std::time::Duration) {
2396 let start = Instant::now();
2397 if let Some(writer) = self.persistent_writer() {
2399 loop {
2400 if writer.queue_depth() == 0 {
2401 break;
2402 }
2403 if start.elapsed() >= deadline {
2404 break;
2405 }
2406 std::thread::sleep(std::time::Duration::from_millis(2));
2407 }
2408 }
2409 let writer = self.persistent_writer().cloned();
2413 if let Some(writer) = writer.as_ref() {
2414 writer.shutdown();
2415 let _ = writer.drain_all_as_abandoned();
2416 }
2417 let mut completion = self.take_persistent_completion();
2424 let completed = if let (Some(rx), Some(_writer)) = (completion.as_mut(), writer.as_ref()) {
2425 let elapsed = start.elapsed();
2426 let remaining = deadline.saturating_sub(elapsed);
2427 crate::result_cache::recv_completion_with_timeout(rx, remaining)
2428 } else {
2429 true
2430 };
2431 if completed {
2432 if let Some(handle) = self.take_persistent_worker() {
2433 let _ = handle.join();
2434 }
2435 drop(completion.take());
2437 } else {
2438 if let Some(writer) = writer.as_ref() {
2442 writer.record_outcome(DrainOutcome::Abandoned);
2443 }
2444 self.take_persistent_worker(); }
2446 if matches!(self.persistence, PersistentPublicationState::Async(_)) {
2450 self.worker_shutdown_total
2451 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2452 self.persist_unavailable_total
2453 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2454 self.persistence =
2455 PersistentPublicationState::Disabled(PersistenceDisabledReason::WorkerShutdown);
2456 }
2457 }
2458
2459 pub(crate) fn set_persist_min_bytes(&mut self, min: u64) {
2463 self.persist_min_bytes = min;
2464 }
2465
2466 #[cfg(test)]
2468 fn would_persist(&self, approx: u64) -> bool {
2469 self.dir.is_some() && (self.persist_min_bytes == 0 || approx >= self.persist_min_bytes)
2470 }
2471
2472 fn cache_counters(&self) -> (u64, u64, u64, u64) {
2475 (
2476 self.memory_hit.load(std::sync::atomic::Ordering::Relaxed),
2477 self.disk_hit.load(std::sync::atomic::Ordering::Relaxed),
2478 self.miss.load(std::sync::atomic::Ordering::Relaxed),
2479 self.persistent_write_us
2480 .load(std::sync::atomic::Ordering::Relaxed),
2481 )
2482 }
2483
2484 fn publication_counters(&self) -> (u64, u64, u64, u64) {
2488 (
2489 self.persist_unavailable_total
2490 .load(std::sync::atomic::Ordering::Relaxed),
2491 self.persist_skipped_total
2492 .load(std::sync::atomic::Ordering::Relaxed),
2493 self.worker_spawn_failures_total
2494 .load(std::sync::atomic::Ordering::Relaxed),
2495 self.worker_shutdown_total
2496 .load(std::sync::atomic::Ordering::Relaxed),
2497 )
2498 }
2499
2500 fn persist_snapshot(&self) -> Option<LookupMetricsSnapshot> {
2503 self.persistent_writer().map(|w| w.persist_snapshot())
2504 }
2505
2506 fn invalidate(
2515 &mut self,
2516 delete_rids: &roaring::RoaringBitmap,
2517 put_cols: &std::collections::HashSet<u16>,
2518 ) {
2519 if self.entries.is_empty() {
2520 return;
2521 }
2522 let has_deletes = !delete_rids.is_empty();
2523 let mut to_remove = HashSet::new();
2524
2525 for column in put_cols {
2529 if let Some(keys) = self.condition_index.get(column) {
2530 to_remove.extend(keys.iter().copied());
2531 }
2532 }
2533
2534 if has_deletes {
2535 to_remove.extend(self.empty_footprint_entries.iter().copied());
2539 for (&key, entry) in &self.entries {
2540 if !to_remove.contains(&key)
2541 && !entry.footprint.is_empty()
2542 && entry.footprint.intersection_len(delete_rids) > 0
2543 {
2544 to_remove.insert(key);
2545 }
2546 }
2547 }
2548
2549 for key in to_remove {
2550 if let Some(entry) = self.entries.remove(&key) {
2551 self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2552 self.unindex_entry(key, &entry);
2553 }
2554 if self.persistent_writer().is_some() {
2559 self.enqueue_persist_remove(key);
2560 } else {
2561 self.remove_from_disk(key);
2562 }
2563 self.untrack(key);
2564 }
2565 }
2566
2567 fn clear(&mut self) {
2568 if self.dir.is_some() {
2572 if self.persistent_writer().is_some() {
2573 self.enqueue_persist_clear();
2574 } else if let Some(dir) = &self.dir {
2575 if let Ok(entries) = std::fs::read_dir(dir) {
2576 for entry in entries.flatten() {
2577 let path = entry.path();
2578 if path.extension().and_then(|e| e.to_str()) == Some("bin") {
2579 let _ = std::fs::remove_file(&path);
2580 }
2581 }
2582 }
2583 }
2584 }
2585 self.entries.clear();
2586 self.order.clear();
2587 self.generations.clear();
2588 self.next_generation = 0;
2589 self.condition_index.clear();
2590 self.empty_footprint_entries.clear();
2591 self.bytes = 0;
2592 }
2593
2594 fn evict(&mut self) {
2595 while self.bytes > self.max_bytes {
2596 let Some((_, key)) = self.order.pop_first() else {
2597 break;
2598 };
2599 self.generations.remove(&key);
2600 if let Some(entry) = self.entries.remove(&key) {
2601 self.bytes = self.bytes.saturating_sub(entry.data.approx_bytes());
2602 self.unindex_entry(key, &entry);
2603 }
2611 }
2612 }
2613}
2614
2615fn spawn_persistent_cache_worker(
2623 dir: std::path::PathBuf,
2624 cache_dek: Option<Zeroizing<[u8; DEK_LEN]>>,
2625 metrics: LookupMetrics,
2626) -> std::io::Result<(
2627 std::sync::Arc<crate::result_cache::PersistentResultCacheWriter>,
2628 std::thread::JoinHandle<()>,
2629 std::sync::mpsc::Receiver<()>,
2630)> {
2631 use crate::result_cache::{
2632 spawn_persistent_cache_worker as spawn, RealPersistentCacheIo, StalenessGuard,
2633 WorkerConfig, WriterStalenessGuard,
2634 };
2635 if PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.get()) {
2639 return Err(std::io::Error::other(
2640 "persistent-cache worker spawn failure forced by test seam",
2641 ));
2642 }
2643 let io: std::sync::Arc<dyn crate::result_cache::PersistentCacheIo> =
2644 std::sync::Arc::new(RealPersistentCacheIo::new(dir)?);
2645 let cipher = match cache_dek {
2646 Some(dek) => {
2647 let cipher = crate::encryption::AesCipher::new(&dek[..])
2648 .map_err(|e| std::io::Error::other(format!("aes: {e}")))?;
2649 Some(std::sync::Arc::new(cipher))
2650 }
2651 None => None,
2652 };
2653 let writer = std::sync::Arc::new(crate::result_cache::PersistentResultCacheWriter::new(
2654 metrics,
2655 crate::result_cache::WriterLimits::default(),
2656 ));
2657 let staleness: std::sync::Arc<dyn StalenessGuard> =
2658 std::sync::Arc::new(WriterStalenessGuard::new(writer.clone()));
2659 let (completion_tx, completion_rx) = std::sync::mpsc::channel();
2660 let config = WorkerConfig {
2661 writer: writer.clone(),
2662 io,
2663 cipher,
2664 staleness,
2665 max_staleness_retries: 8,
2666 completion: Some(completion_tx),
2667 };
2668 let handle = spawn(config);
2669 Ok((writer, handle, completion_rx))
2670}
2671
2672thread_local! {
2673 static PERSISTENT_WORKER_SPAWN_FAILURE: std::cell::Cell<bool> =
2680 const { std::cell::Cell::new(false) };
2681}
2682
2683#[cfg(test)]
2684mod result_cache_lru_tests {
2685 use super::*;
2686
2687 fn row_entry(row_id: u64) -> CachedEntry {
2688 CachedEntry {
2689 data: CachedData::Rows(Arc::new(vec![Row::new(RowId(row_id), Epoch(1))])),
2690 footprint: std::iter::once(row_id as u32).collect(),
2691 condition_cols: vec![1],
2692 }
2693 }
2694
2695 #[test]
2696 fn hits_update_recency_without_growing_an_order_queue() {
2697 let mut cache = ResultCache::with_max_bytes(u64::MAX);
2698 let identity = PersistentCacheIdentity {
2699 table_id: 0,
2700 schema_id: 0,
2701 logical_generation: 0,
2702 };
2703 cache.insert(1, row_entry(1));
2704 cache.insert(2, row_entry(2));
2705 assert_eq!(cache.order.len(), cache.entries.len());
2706
2707 for _ in 0..1_000 {
2708 assert!(cache.get_rows(1, identity).is_some());
2709 }
2710
2711 assert_eq!(cache.order.len(), cache.entries.len());
2712 assert_eq!(cache.order.first().map(|(_, key)| *key), Some(2));
2713
2714 let one_entry = cache.entries[&1].data.approx_bytes();
2715 cache.set_max_bytes(one_entry);
2716 assert!(cache.entries.contains_key(&1));
2717 assert!(!cache.entries.contains_key(&2));
2718 assert_eq!(cache.order.len(), cache.entries.len());
2719 }
2720
2721 #[test]
2722 fn tiny_entries_skip_persistent_tier_by_default() {
2723 let dir = tempfile::tempdir().unwrap();
2724 let mut cache = ResultCache::with_max_bytes(u64::MAX).with_dir(dir.path().to_path_buf());
2725 let tiny = row_entry(1).data.approx_bytes();
2726 assert!(
2727 tiny < 4 * 1024,
2728 "row_entry fixture must be below default 4KiB threshold"
2729 );
2730 assert!(
2731 !cache.would_persist(tiny),
2732 "tiny entry must not force synchronous disk publish"
2733 );
2734 assert!(
2735 cache.would_persist(8 * 1024),
2736 "large entry must still persist when dir is set"
2737 );
2738 cache.set_persist_min_bytes(0);
2739 assert!(
2740 cache.would_persist(tiny),
2741 "persist_min_bytes=0 restores always-persist policy"
2742 );
2743 }
2744
2745 #[test]
2746 fn insert_invalidation_uses_the_condition_reverse_index() {
2747 let mut cache = ResultCache::with_max_bytes(u64::MAX);
2748 let mut first = row_entry(1);
2749 first.condition_cols = vec![1];
2750 let mut second = row_entry(2);
2751 second.condition_cols = vec![2];
2752 cache.insert(1, first);
2753 cache.insert(2, second);
2754
2755 let put_cols = std::iter::once(1_u16).collect();
2756 cache.invalidate(&roaring::RoaringBitmap::new(), &put_cols);
2757
2758 assert!(!cache.entries.contains_key(&1));
2759 assert!(cache.entries.contains_key(&2));
2760 assert!(!cache
2761 .condition_index
2762 .get(&1)
2763 .is_some_and(|keys| keys.contains(&1)));
2764 assert!(cache
2765 .condition_index
2766 .get(&2)
2767 .is_some_and(|keys| keys.contains(&2)));
2768 assert_eq!(cache.order.len(), cache.entries.len());
2769 }
2770
2771 #[test]
2772 fn delete_invalidation_preserves_known_and_unknown_footprint_semantics() {
2773 let mut cache = ResultCache::with_max_bytes(u64::MAX);
2774 cache.insert(1, row_entry(1));
2775 cache.insert(2, row_entry(2));
2776 let mut unknown = row_entry(3);
2777 unknown.footprint.clear();
2778 cache.insert(3, unknown);
2779
2780 let delete_rids: roaring::RoaringBitmap = std::iter::once(1_u32).collect();
2781 cache.invalidate(&delete_rids, &HashSet::new());
2782
2783 assert!(!cache.entries.contains_key(&1));
2784 assert!(cache.entries.contains_key(&2));
2785 assert!(!cache.entries.contains_key(&3));
2786 assert!(cache.empty_footprint_entries.is_empty());
2787 assert_eq!(cache.order.len(), cache.entries.len());
2788 }
2789
2790 #[test]
2791 fn borrowed_persistence_encoding_matches_the_existing_owned_format() {
2792 let entry = row_entry(7);
2793 let borrowed = bincode::serialize(&SerializedEntryRef::from_entry(&entry)).unwrap();
2794 let owned = bincode::serialize(&SerializedEntry {
2795 condition_cols: entry.condition_cols.clone(),
2796 footprint_bits: entry.footprint.iter().collect(),
2797 data: match &entry.data {
2798 CachedData::Rows(rows) => SerializedData::Rows((**rows).clone()),
2799 CachedData::Columns(columns) => SerializedData::Columns((**columns).clone()),
2800 },
2801 })
2802 .unwrap();
2803 assert_eq!(borrowed, owned);
2804 }
2805}
2806
2807type DekaOpt = Option<Zeroizing<[u8; DEK_LEN]>>;
2814
2815fn derive_subkeys(kek: Option<&Kek>, _table_id: u64) -> (DekaOpt, DekaOpt) {
2816 let _ = kek;
2817 {
2818 if let Some(k) = kek {
2819 return (
2820 Some(k.derive_table_wal_key(_table_id)),
2821 Some(k.derive_cache_key()),
2822 );
2823 }
2824 }
2825 (None, None)
2826}
2827
2828fn read_table_encryption_salt_root(
2829 root: &crate::durable_file::DurableRoot,
2830) -> Result<[u8; crate::encryption::SALT_LEN]> {
2831 use std::io::Read;
2832
2833 let mut file = root
2834 .open_regular(Path::new(META_DIR).join(KEYS_FILENAME))
2835 .map_err(|error| MongrelError::NotFound(format!("encryption salt file: {error}")))?;
2836 let length = file.metadata()?.len();
2837 if length != crate::encryption::SALT_LEN as u64 {
2838 return Err(MongrelError::InvalidArgument(format!(
2839 "salt file is {length} bytes, expected {}",
2840 crate::encryption::SALT_LEN
2841 )));
2842 }
2843 let mut salt = [0_u8; crate::encryption::SALT_LEN];
2844 file.read_exact(&mut salt)?;
2845 Ok(salt)
2846}
2847
2848fn make_cipher(dek: &Zeroizing<[u8; DEK_LEN]>) -> Box<dyn crate::encryption::Cipher> {
2850 Box::new(crate::encryption::AesCipher::new(&dek[..]).expect("DEK is 32 bytes"))
2851}
2852
2853fn build_column_keys(kek: Option<&Kek>, schema: &Schema) -> HashMap<u16, ([u8; 32], u8)> {
2854 let Some(kek) = kek else {
2855 return HashMap::new();
2856 };
2857 {
2858 use crate::encryption::{SCHEME_HMAC_EQ, SCHEME_OPE_RANGE};
2859 schema
2860 .columns
2861 .iter()
2862 .filter(|c| c.flags.contains(ColumnFlags::ENCRYPTED_INDEXABLE))
2863 .map(|c| {
2864 let scheme = if schema
2865 .indexes
2866 .iter()
2867 .any(|i| i.column_id == c.id && i.kind == IndexKind::LearnedRange)
2868 {
2869 SCHEME_OPE_RANGE
2870 } else {
2871 SCHEME_HMAC_EQ
2872 };
2873 let key: [u8; 32] = *kek.derive_column_key(c.id);
2874 (c.id, (key, scheme))
2875 })
2876 .collect()
2877 }
2878}
2879
2880pub(crate) struct SharedCtx {
2885 pub root_guard: Option<Arc<crate::durable_file::DurableRoot>>,
2886 pub epoch: Arc<EpochAuthority>,
2887 pub page_cache: Arc<crate::cache::Sharded<crate::cache::PageCache>>,
2888 pub decoded_cache: Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>,
2889 pub snapshots: Arc<crate::retention::SnapshotRegistry>,
2890 pub kek: Option<Arc<Kek>>,
2891 pub commit_lock: Arc<parking_lot::Mutex<()>>,
2897 pub shared: Option<SharedWalCtx>,
2901 pub table_name: Option<String>,
2904 pub auth: Option<Arc<dyn crate::auth_state::TableAuthChecker>>,
2907 pub read_only: bool,
2909}
2910
2911#[derive(Clone)]
2917pub(crate) struct SharedWalCtx {
2918 pub wal: Arc<parking_lot::Mutex<SharedWal>>,
2919 pub group: Arc<GroupCommit>,
2920 pub poisoned: Arc<AtomicBool>,
2921 pub txn_ids: Arc<parking_lot::Mutex<u64>>,
2922 pub change_wake: tokio::sync::broadcast::Sender<()>,
2923 pub lifecycle: Arc<crate::core::LifecycleController>,
2926 pub hlc: Arc<mongreldb_types::hlc::HlcClock>,
2928}
2929
2930enum WalSink {
2933 Private(Wal),
2934 Shared(SharedWalCtx),
2935 ReadOnly,
2936}
2937
2938impl Clone for WalSink {
2939 fn clone(&self) -> Self {
2940 match self {
2941 Self::Shared(shared) => Self::Shared(shared.clone()),
2942 Self::Private(_) | Self::ReadOnly => Self::ReadOnly,
2943 }
2944 }
2945}
2946
2947impl SharedCtx {
2948 pub(crate) fn new(kek: Option<Arc<Kek>>, cache_dir: Option<PathBuf>) -> Self {
2952 let n_shards = if cache_dir.is_some() {
2956 1
2957 } else {
2958 crate::cache::CACHE_SHARDS
2959 };
2960 let per_shard = PAGE_CACHE_CAPACITY / n_shards as u64;
2961 let page_cache = if let Some(d) = cache_dir {
2962 Arc::new(crate::cache::Sharded::new(1, || {
2963 crate::cache::PageCache::new(PAGE_CACHE_CAPACITY).with_persistence(d.clone())
2964 }))
2965 } else {
2966 Arc::new(crate::cache::Sharded::new(n_shards, || {
2967 crate::cache::PageCache::new(per_shard)
2968 }))
2969 };
2970 let decoded_per_shard = DECODED_CACHE_CAPACITY / crate::cache::CACHE_SHARDS as u64;
2971 let decoded_cache = Arc::new(crate::cache::Sharded::new(
2972 crate::cache::CACHE_SHARDS,
2973 || crate::cache::DecodedPageCache::new(decoded_per_shard),
2974 ));
2975 Self {
2976 root_guard: None,
2977 epoch: Arc::new(EpochAuthority::new(0)),
2978 page_cache,
2979 decoded_cache,
2980 snapshots: Arc::new(crate::retention::SnapshotRegistry::new()),
2981 kek,
2982 commit_lock: Arc::new(parking_lot::Mutex::new(())),
2983 shared: None,
2984 table_name: None,
2985 auth: None,
2986 read_only: false,
2987 }
2988 }
2989}
2990
2991fn condition_cost_rank(c: &crate::query::Condition) -> u8 {
2995 use crate::query::Condition;
2996 match c {
2997 Condition::Pk(_)
2999 | Condition::BitmapEq { .. }
3000 | Condition::BitmapIn { .. }
3001 | Condition::BytesPrefix { .. }
3002 | Condition::IsNull { .. }
3003 | Condition::IsNotNull { .. } => 0,
3004 Condition::Range { .. } | Condition::RangeF64 { .. } | Condition::MinHashSimilar { .. } => {
3006 1
3007 }
3008 Condition::FmContains { .. }
3010 | Condition::FmContainsAll { .. }
3011 | Condition::Ann { .. }
3012 | Condition::SparseMatch { .. } => 2,
3013 }
3014}
3015
3016impl Table {
3017 pub(crate) fn build_secondary_index_artifact<F>(
3023 &self,
3024 definition: &IndexDef,
3025 rows: &[Row],
3026 mut checkpoint: F,
3027 ) -> Result<SecondaryIndexArtifact>
3028 where
3029 F: FnMut(usize, usize) -> Result<()>,
3030 {
3031 let mut build_schema = self.schema.clone();
3032 build_schema.indexes = vec![definition.clone()];
3033 let (mut bitmap, mut ann, mut fm, mut sparse, mut minhash) = empty_indexes(&build_schema);
3034 let name_to_id: HashMap<&str, u16> = self
3035 .schema
3036 .columns
3037 .iter()
3038 .map(|column| (column.name.as_str(), column.id))
3039 .collect();
3040 let mut hot = HotIndex::new();
3041 let mut accepted = Vec::with_capacity(rows.len());
3042
3043 for (offset, row) in rows.iter().enumerate() {
3044 checkpoint(offset, rows.len())?;
3045 if row.deleted {
3046 continue;
3047 }
3048 if let Some(predicate) = &definition.predicate {
3049 let columns: HashMap<u16, &Value> =
3050 row.columns.iter().map(|(id, value)| (*id, value)).collect();
3051 if !eval_partial_predicate(predicate, &columns, &name_to_id) {
3052 continue;
3053 }
3054 }
3055 accepted.push(row);
3056 if definition.kind == IndexKind::LearnedRange {
3057 continue;
3058 }
3059 let effective = if self.column_keys.is_empty() {
3060 row.clone()
3061 } else {
3062 self.tokenized_for_indexes(row)
3063 };
3064 if definition.kind == IndexKind::Ann {
3065 if let (Some(index), Some(vector)) = (
3066 ann.get_mut(&definition.column_id),
3067 effective
3068 .columns
3069 .get(&definition.column_id)
3070 .and_then(Value::as_embedding),
3071 ) {
3072 index.insert_validated_with_checkpoint(vector, effective.row_id, || {
3073 checkpoint(offset, rows.len())
3074 })?;
3075 }
3076 } else {
3077 index_into_single(
3078 definition,
3079 &build_schema,
3080 &effective,
3081 &mut hot,
3082 &mut bitmap,
3083 &mut ann,
3084 &mut fm,
3085 &mut sparse,
3086 &mut minhash,
3087 );
3088 }
3089 }
3090 checkpoint(rows.len(), rows.len())?;
3091
3092 if let Some(index) = ann.get_mut(&definition.column_id) {
3093 index.seal_with_checkpoint(|| checkpoint(rows.len(), rows.len()))?;
3094 }
3095
3096 let column_id = definition.column_id;
3097 match definition.kind {
3098 IndexKind::Bitmap => bitmap
3099 .remove(&column_id)
3100 .map(|index| SecondaryIndexArtifact::Bitmap(column_id, index)),
3101 IndexKind::Ann => ann
3102 .remove(&column_id)
3103 .map(|index| SecondaryIndexArtifact::Ann(column_id, Box::new(index))),
3104 IndexKind::FmIndex => fm
3105 .remove(&column_id)
3106 .map(|index| SecondaryIndexArtifact::Fm(column_id, Box::new(index))),
3107 IndexKind::Sparse => sparse
3108 .remove(&column_id)
3109 .map(|index| SecondaryIndexArtifact::Sparse(column_id, index)),
3110 IndexKind::MinHash => minhash
3111 .remove(&column_id)
3112 .map(|index| SecondaryIndexArtifact::MinHash(column_id, index)),
3113 IndexKind::LearnedRange => {
3114 let epsilon = definition
3115 .options
3116 .learned_range
3117 .as_ref()
3118 .map(|options| options.epsilon)
3119 .unwrap_or(16);
3120 let column = self
3121 .schema
3122 .columns
3123 .iter()
3124 .find(|column| column.id == column_id)
3125 .ok_or_else(|| {
3126 MongrelError::Schema(format!(
3127 "index {} references unknown column {column_id}",
3128 definition.name
3129 ))
3130 })?;
3131 let index = match column.ty {
3132 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
3133 let pairs: Vec<_> = accepted
3134 .iter()
3135 .filter_map(|row| match row.columns.get(&column_id) {
3136 Some(Value::Int64(value)) if !row.deleted => {
3137 Some((*value, row.row_id.0))
3138 }
3139 _ => None,
3140 })
3141 .collect();
3142 ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon)
3143 }
3144 TypeId::Float32 | TypeId::Float64 => {
3145 let pairs: Vec<_> = accepted
3146 .iter()
3147 .filter_map(|row| match row.columns.get(&column_id) {
3148 Some(Value::Float64(value)) if !row.deleted => {
3149 Some((*value, row.row_id.0))
3150 }
3151 _ => None,
3152 })
3153 .collect();
3154 ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon)
3155 }
3156 ref ty => {
3157 return Err(MongrelError::Schema(format!(
3158 "LearnedRange index {} does not support {ty:?}",
3159 definition.name
3160 )));
3161 }
3162 };
3163 Some(SecondaryIndexArtifact::LearnedRange(column_id, index))
3164 }
3165 }
3166 .ok_or_else(|| {
3167 MongrelError::Other(format!(
3168 "failed to construct hidden index {}",
3169 definition.name
3170 ))
3171 })
3172 }
3173
3174 pub fn create(dir: impl AsRef<Path>, schema: Schema, table_id: u64) -> Result<Self> {
3175 let dir = dir.as_ref().to_path_buf();
3176 std::fs::create_dir_all(&dir)?;
3179 let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3180 let pinned = root.io_path()?;
3181 let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3182 ctx.root_guard = Some(root.clone());
3183 let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3184 root.finalize_deferred_sync_shallow()?;
3190 Ok(table)
3191 }
3192
3193 pub fn create_encrypted(
3204 dir: impl AsRef<Path>,
3205 schema: Schema,
3206 table_id: u64,
3207 passphrase: &str,
3208 ) -> Result<Self> {
3209 let dir = dir.as_ref().to_path_buf();
3210 std::fs::create_dir_all(&dir)?;
3211 let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3212 root.create_directory_all(META_DIR)?;
3213 let salt = crate::encryption::random_salt()?;
3214 root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3215 let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3216 let pinned = root.io_path()?;
3217 let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3218 ctx.root_guard = Some(root.clone());
3219 let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3220 root.finalize_deferred_sync()?;
3221 Ok(table)
3222 }
3223
3224 pub fn create_with_key(
3229 dir: impl AsRef<Path>,
3230 schema: Schema,
3231 table_id: u64,
3232 key: &[u8],
3233 ) -> Result<Self> {
3234 let dir = dir.as_ref().to_path_buf();
3235 std::fs::create_dir_all(&dir)?;
3236 let root = Arc::new(crate::durable_file::DurableRoot::open_deferred(&dir)?);
3237 root.create_directory_all(META_DIR)?;
3238 let salt = crate::encryption::random_salt()?;
3239 root.write_atomic(Path::new(META_DIR).join(KEYS_FILENAME), &salt)?;
3240 let kek: Arc<Kek> = Arc::new(Kek::from_raw_key(key, &salt)?);
3241 let pinned = root.io_path()?;
3242 let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3243 ctx.root_guard = Some(root.clone());
3244 let table = Self::create_in(&pinned, schema, table_id, ctx)?;
3245 root.finalize_deferred_sync()?;
3246 Ok(table)
3247 }
3248
3249 pub fn open_with_key(dir: impl AsRef<Path>, key: &[u8]) -> Result<Self> {
3251 let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3252 let salt = read_table_encryption_salt_root(&root)?;
3253 let kek = Arc::new(Kek::from_raw_key(key, &salt)?);
3254 let pinned = root.io_path()?;
3255 let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3256 ctx.root_guard = Some(root);
3257 Self::open_in(&pinned, ctx)
3258 }
3259
3260 pub(crate) fn create_in(
3261 dir: impl AsRef<Path>,
3262 schema: Schema,
3263 table_id: u64,
3264 ctx: SharedCtx,
3265 ) -> Result<Self> {
3266 schema.validate_auto_increment()?;
3267 schema.validate_defaults()?;
3268 schema.validate_ai()?;
3269 for index in &schema.indexes {
3270 index.validate_options()?;
3271 }
3272 let dir = dir.as_ref().to_path_buf();
3273 let runs_root = match ctx.root_guard.as_ref() {
3274 Some(root) => Some(Arc::new(root.create_directory_all_pinned(RUNS_DIR)?)),
3275 None => {
3276 crate::durable_file::create_directory_all(&dir)?;
3277 crate::durable_file::create_directory_all(&dir.join(RUNS_DIR))?;
3278 None
3279 }
3280 };
3281 match ctx.root_guard.as_deref() {
3282 Some(root) => write_schema_durable(root, &schema)?,
3283 None => write_schema(&dir, &schema)?,
3284 }
3285 let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), table_id);
3286 let (wal, current_txn_id) = match ctx.shared.clone() {
3289 Some(s) => (WalSink::Shared(s), 0),
3290 None => {
3291 let pinned_wal_root = match ctx.root_guard.as_deref() {
3292 Some(root) => Some(root.create_directory_all_pinned(WAL_DIR)?),
3293 None => None,
3294 };
3295 let wal_dir = if let Some(root) = pinned_wal_root.as_ref() {
3296 root.io_path()?
3297 } else {
3298 let wal_dir = dir.join(WAL_DIR);
3299 std::fs::create_dir_all(&wal_dir)?;
3300 wal_dir
3301 };
3302 let mut w = match (pinned_wal_root.as_ref(), wal_dek.as_ref()) {
3303 (Some(root), Some(dk)) => {
3304 Wal::create_in_root(root, 0, Epoch(0), Some(make_cipher(dk)))?
3305 }
3306 (Some(root), None) => Wal::create_in_root(root, 0, Epoch(0), None)?,
3307 (None, Some(dk)) => Wal::create_with_cipher(
3308 wal_dir.join("seg-000000.wal"),
3309 Epoch(0),
3310 Some(make_cipher(dk)),
3311 0,
3312 )?,
3313 (None, None) => Wal::create(wal_dir.join("seg-000000.wal"), Epoch(0))?,
3314 };
3315 w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3316 (WalSink::Private(w), 1)
3317 }
3318 };
3319 let mut manifest = Manifest::new(table_id, schema.schema_id);
3320 let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3325 match ctx.root_guard.as_deref() {
3326 Some(root) => manifest::write_durable(root, &mut manifest, manifest_meta_dek.as_ref())?,
3327 None => manifest::write_atomic(&dir, &mut manifest, manifest_meta_dek.as_ref())?,
3328 }
3329 let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&schema);
3330 let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3331 let auto_inc = resolve_auto_inc(&schema);
3332 let rcache_dir = dir.join(RCACHE_DIR);
3333 let initial_view = ReadGeneration::empty(&schema);
3334 Ok(Self {
3335 dir,
3336 _root_guard: ctx.root_guard,
3337 runs_root,
3338 idx_root: None,
3339 table_id,
3340 name: ctx.table_name.unwrap_or_default(),
3341 auth: ctx.auth,
3342 read_only: ctx.read_only,
3343 durable_commit_failed: false,
3344 wal,
3345 memtable: Memtable::new(),
3346 mutable_run: MutableRun::new(),
3347 mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3348 compaction_zstd_level: 3,
3349 allocator: RowIdAllocator::new(0),
3350 epoch: ctx.epoch,
3351 data_generation: 0,
3352 schema,
3353 hot: HotIndex::new(),
3354 kek: ctx.kek,
3355 column_keys,
3356 run_refs: Vec::new(),
3357 retiring: Vec::new(),
3358 next_run_id: 1,
3359 sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3360 current_txn_id,
3361 pending_private_mutations: false,
3362 bitmap,
3363 ann,
3364 fm,
3365 sparse,
3366 minhash,
3367 learned_range: Arc::new(HashMap::new()),
3368 pk_by_row: ReversePkMap::new(),
3369 pinned: BTreeMap::new(),
3370 live_count: 0,
3371 reservoir: crate::reservoir::Reservoir::default(),
3372 reservoir_complete: true,
3373 had_deletes: false,
3374 recent_delete_preimages: HashMap::new(),
3375 run_row_id_ranges: HashMap::new(),
3376 agg_cache: Arc::new(HashMap::new()),
3377 global_idx_epoch: 0,
3378 indexes_complete: true,
3379 index_build_policy: IndexBuildPolicy::default(),
3380 pk_by_row_complete: false,
3381 flushed_epoch: 0,
3382 page_cache: ctx.page_cache,
3383 decoded_cache: ctx.decoded_cache,
3384 verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3385 snapshots: ctx.snapshots,
3386 commit_lock: ctx.commit_lock,
3387 result_cache: {
3394 let cache = ResultCache::new()
3395 .with_dir(rcache_dir.clone())
3396 .with_cache_dek(cache_dek.clone());
3397 let metrics = Arc::new(LookupMetrics::default());
3401 let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3402 match spawn_persistent_cache_worker(
3403 rcache_dir.clone(),
3404 cache_dek.clone(),
3405 (*metrics).clone(),
3406 ) {
3407 Ok((writer, handle, completion_rx)) => {
3408 cache_arc
3409 .lock()
3410 .install_persistent_writer(writer, handle, completion_rx);
3411 }
3412 Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3413 }
3414 cache_arc
3415 },
3416 pending_delete_rids: roaring::RoaringBitmap::new(),
3417 pending_put_cols: std::collections::HashSet::new(),
3418 pending_rows: Vec::new(),
3419 pending_rows_auto_inc: Vec::new(),
3420 pending_dels: Vec::new(),
3421 pending_truncate: None,
3422 wal_dek,
3423 auto_inc,
3424 ttl: None,
3425 pins: Arc::new(crate::retention::PinRegistry::new()),
3426 published: Arc::new(ArcSwap::from_pointee(initial_view)),
3427 read_generation_pin: None,
3428 lookup_metrics: LookupMetrics::default(),
3429 run_lookup: RunLookupState::default(),
3430 })
3431 }
3432
3433 pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
3437 let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3438 let pinned = root.io_path()?;
3439 let mut ctx = SharedCtx::new(None, Some(pinned.join(CACHE_DIR)));
3440 ctx.root_guard = Some(root);
3441 Self::open_in(&pinned, ctx)
3442 }
3443
3444 pub fn open_encrypted(dir: impl AsRef<Path>, passphrase: &str) -> Result<Self> {
3447 let root = Arc::new(crate::durable_file::DurableRoot::open(dir.as_ref())?);
3448 let salt = read_table_encryption_salt_root(&root)?;
3449 let kek: Arc<Kek> = Arc::new(Kek::derive(passphrase, &salt)?);
3450 let pinned = root.io_path()?;
3451 let mut ctx = SharedCtx::new(Some(kek), Some(pinned.join(CACHE_DIR)));
3452 ctx.root_guard = Some(root);
3453 let t = Self::open_in(&pinned, ctx)?;
3454 Ok(t)
3455 }
3456
3457 pub(crate) fn open_in(dir: impl AsRef<Path>, ctx: SharedCtx) -> Result<Self> {
3458 let dir = dir.as_ref().to_path_buf();
3459 let manifest_meta_dek = crate::encryption::meta_dek_for(ctx.kek.as_deref());
3460 let mut manifest = match ctx.root_guard.as_ref() {
3461 Some(root) => manifest::read_durable(root, "", manifest_meta_dek.as_ref())?,
3462 None => manifest::read(&dir, manifest_meta_dek.as_ref())?,
3463 };
3464 let schema: Schema = match ctx.root_guard.as_ref() {
3465 Some(root) => read_schema_file(root.open_regular(SCHEMA_FILENAME)?)?,
3466 None => read_schema(&dir)?,
3467 };
3468 let schema_manifest_repair = manifest.schema_id < schema.schema_id;
3474 let runs_root = match ctx.root_guard.as_ref() {
3475 Some(root) => Some(Arc::new(root.open_directory(RUNS_DIR)?)),
3476 None => None,
3477 };
3478 let idx_root = match ctx.root_guard.as_ref() {
3479 Some(root) => match root.open_directory(global_idx::IDX_DIR) {
3480 Ok(root) => Some(Arc::new(root)),
3481 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
3482 Err(error) => return Err(error.into()),
3483 },
3484 None => None,
3485 };
3486 schema.validate_auto_increment()?;
3487 schema.validate_defaults()?;
3488 schema.validate_ai()?;
3489 for index in &schema.indexes {
3490 index.validate_options()?;
3491 }
3492 let replay_epoch = Epoch(manifest.current_epoch);
3493 let (wal_dek, cache_dek) = derive_subkeys(ctx.kek.as_deref(), manifest.table_id);
3494 let private_replayed = if ctx.shared.is_none() {
3495 match latest_wal_segment(&dir.join(WAL_DIR))? {
3496 Some(path) => {
3497 let cipher = wal_dek.as_ref().map(|dk| make_cipher(dk));
3498 crate::wal::replay_with_cipher(path, cipher)?
3499 }
3500 None => Vec::new(),
3501 }
3502 } else {
3503 Vec::new()
3504 };
3505 if ctx.shared.is_none() {
3506 preflight_standalone_open(
3507 &dir,
3508 runs_root.as_deref(),
3509 idx_root.as_deref(),
3510 &manifest,
3511 &schema,
3512 &private_replayed,
3513 ctx.kek.clone(),
3514 )?;
3515 }
3516 let next_run_id = derive_next_run_id(
3517 &dir,
3518 runs_root.as_deref(),
3519 &manifest.runs,
3520 &manifest.retiring,
3521 )?;
3522 let (wal, replayed, current_txn_id) = match ctx.shared.clone() {
3526 Some(s) => (WalSink::Shared(s), Vec::new(), 0),
3527 None => {
3528 let replayed = private_replayed;
3529 let wal_dir = dir.join(WAL_DIR);
3535 crate::durable_file::create_directory_all(&wal_dir)?;
3536 let segment = next_wal_segment(&wal_dir)?;
3537 let segment_no = wal_segment_number(&segment).unwrap_or(0);
3538 let temporary = wal_dir.join(format!(
3539 ".recovery-{}-{}-{segment_no:06}.tmp",
3540 std::process::id(),
3541 std::time::SystemTime::now()
3542 .duration_since(std::time::UNIX_EPOCH)
3543 .unwrap_or_default()
3544 .as_nanos()
3545 ));
3546 let mut w = Wal::create_with_cipher(
3547 &temporary,
3548 replay_epoch,
3549 wal_dek.as_ref().map(|dk| make_cipher(dk)),
3550 segment_no,
3551 )?;
3552 for record in &replayed {
3553 w.append_txn(record.txn_id, record.op.clone())?;
3554 }
3555 let mut w = w.publish_as(segment)?;
3556 w.set_sync_byte_threshold(DEFAULT_SYNC_BYTE_THRESHOLD);
3557 let next_txn_id = replayed
3558 .iter()
3559 .map(|record| record.txn_id)
3560 .filter(|txn_id| *txn_id != crate::wal::SYSTEM_TXN_ID)
3561 .max()
3562 .map(|txn_id| txn_id.checked_add(1).unwrap_or(0))
3563 .unwrap_or(1);
3564 (WalSink::Private(w), replayed, next_txn_id)
3565 }
3566 };
3567
3568 let mut memtable = Memtable::new();
3569 let mut allocator = RowIdAllocator::new(manifest.next_row_id);
3570 let persisted_epoch = manifest.current_epoch;
3571 let mut auto_inc = resolve_auto_inc(&schema).map(|mut s| {
3578 s.next = manifest.auto_inc_next;
3579 s.seeded = manifest.auto_inc_next > 0;
3580 s
3581 });
3582
3583 let mut staged_puts: HashMap<u64, Vec<Row>> = HashMap::new();
3590 let mut staged_deletes: HashMap<u64, Vec<RowId>> = HashMap::new();
3591 let mut staged_truncates: std::collections::HashSet<u64> = std::collections::HashSet::new();
3592 let mut replayed_puts: std::collections::BTreeMap<Epoch, Vec<Row>> =
3593 std::collections::BTreeMap::new();
3594 let mut replayed_deletes: Vec<(RowId, Epoch)> = Vec::new();
3595 let mut recovered_epoch = manifest.current_epoch;
3596 let mut recovered_manifest_dirty = schema_manifest_repair;
3597 let mut saw_delete = false;
3598 for record in replayed {
3599 let txn_id = record.txn_id;
3600 match record.op {
3601 Op::Put { rows, .. } => {
3602 let rows: Vec<Row> = bincode::deserialize(&rows)?;
3603 for row in &rows {
3604 allocator.advance_to(row.row_id)?;
3605 if let Some(ai) = auto_inc.as_mut() {
3606 if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
3607 let next = n.checked_add(1).ok_or_else(|| {
3608 MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
3609 })?;
3610 if next > ai.next {
3611 ai.next = next;
3612 }
3613 }
3614 }
3615 }
3616 staged_puts.entry(txn_id).or_default().extend(rows);
3617 }
3618 Op::Delete { row_ids, .. } => {
3619 staged_deletes.entry(txn_id).or_default().extend(row_ids);
3620 }
3621 Op::TxnCommit { epoch, .. } => {
3622 let commit_epoch = Epoch(epoch);
3623 recovered_epoch = recovered_epoch.max(epoch);
3624 if staged_truncates.remove(&txn_id) && commit_epoch.0 > manifest.flushed_epoch {
3625 memtable = Memtable::new();
3626 replayed_puts.clear();
3627 replayed_deletes.clear();
3628 manifest.runs.clear();
3629 manifest.retiring.clear();
3630 manifest.live_count = 0;
3631 manifest.global_idx_epoch = 0;
3632 manifest.current_epoch = manifest.current_epoch.max(epoch);
3633 recovered_manifest_dirty = true;
3634 saw_delete = true;
3635 }
3636 if let Some(puts) = staged_puts.remove(&txn_id) {
3637 if commit_epoch.0 > manifest.flushed_epoch {
3638 for row in &puts {
3639 memtable.upsert(row.clone());
3640 }
3641 replayed_puts.entry(commit_epoch).or_default().extend(puts);
3642 }
3643 }
3644 if let Some(dels) = staged_deletes.remove(&txn_id) {
3645 saw_delete = true;
3646 if commit_epoch.0 > manifest.flushed_epoch {
3647 for rid in dels {
3648 memtable.tombstone(rid, commit_epoch);
3649 replayed_deletes.push((rid, commit_epoch));
3650 }
3651 }
3652 }
3653 }
3654 Op::TxnAbort => {
3655 staged_puts.remove(&txn_id);
3656 staged_deletes.remove(&txn_id);
3657 staged_truncates.remove(&txn_id);
3658 }
3659 Op::TruncateTable { .. } => {
3660 staged_puts.remove(&txn_id);
3661 staged_deletes.remove(&txn_id);
3662 staged_truncates.insert(txn_id);
3663 }
3664 Op::ExternalTableState { .. }
3665 | Op::Flush { .. }
3666 | Op::Ddl(_)
3667 | Op::BeforeImage { .. }
3668 | Op::CommitTimestamp { .. }
3669 | Op::SpilledRows { .. } => {}
3670 }
3671 }
3672
3673 let rcache_dir = dir.join(RCACHE_DIR);
3674 let column_keys = build_column_keys(ctx.kek.as_deref(), &schema);
3675 let initial_view = ReadGeneration::empty(&schema);
3676 let mut db = Self {
3677 dir,
3678 _root_guard: ctx.root_guard,
3679 runs_root,
3680 idx_root,
3681 table_id: manifest.table_id,
3682 name: ctx.table_name.unwrap_or_default(),
3683 auth: ctx.auth,
3684 read_only: ctx.read_only,
3685 durable_commit_failed: false,
3686 wal,
3687 memtable,
3688 mutable_run: MutableRun::new(),
3689 mutable_run_spill_bytes: DEFAULT_MUTABLE_RUN_SPILL_BYTES,
3690 compaction_zstd_level: 3,
3691 allocator,
3692 epoch: ctx.epoch,
3693 data_generation: persisted_epoch,
3694 schema,
3695 hot: HotIndex::new(),
3696 kek: ctx.kek,
3697 column_keys,
3698 run_refs: manifest.runs.clone(),
3699 retiring: manifest.retiring.clone(),
3700 next_run_id,
3701 sync_byte_threshold: DEFAULT_SYNC_BYTE_THRESHOLD,
3702 current_txn_id,
3703 pending_private_mutations: false,
3704 bitmap: HashMap::new(),
3705 ann: HashMap::new(),
3706 fm: HashMap::new(),
3707 sparse: HashMap::new(),
3708 minhash: HashMap::new(),
3709 learned_range: Arc::new(HashMap::new()),
3710 pk_by_row: ReversePkMap::new(),
3711 pinned: BTreeMap::new(),
3712 live_count: manifest.live_count,
3713 reservoir: crate::reservoir::Reservoir::default(),
3714 reservoir_complete: false,
3715 had_deletes: saw_delete
3716 || manifest.runs.iter().map(|run| run.row_count).sum::<u64>()
3717 != manifest.live_count,
3718 recent_delete_preimages: HashMap::new(),
3719 run_row_id_ranges: HashMap::new(),
3720 agg_cache: Arc::new(HashMap::new()),
3721 global_idx_epoch: manifest.global_idx_epoch,
3722 indexes_complete: true,
3723 index_build_policy: IndexBuildPolicy::default(),
3724 pk_by_row_complete: false,
3725 flushed_epoch: manifest.flushed_epoch,
3726 page_cache: ctx.page_cache,
3727 decoded_cache: ctx.decoded_cache,
3728 verified_runs: Arc::new(parking_lot::Mutex::new(std::collections::HashSet::new())),
3729 snapshots: ctx.snapshots,
3730 commit_lock: ctx.commit_lock,
3731 result_cache: {
3732 let cache = ResultCache::new()
3733 .with_dir(rcache_dir.clone())
3734 .with_cache_dek(cache_dek.clone());
3735 let metrics = LookupMetrics::default();
3736 let cache_arc = Arc::new(parking_lot::Mutex::new(cache));
3737 match spawn_persistent_cache_worker(rcache_dir.clone(), cache_dek.clone(), metrics)
3738 {
3739 Ok((writer, handle, completion_rx)) => {
3740 cache_arc
3741 .lock()
3742 .install_persistent_writer(writer, handle, completion_rx);
3743 }
3744 Err(_) => cache_arc.lock().note_worker_spawn_failure(),
3748 }
3749 cache_arc
3750 },
3751 pending_delete_rids: roaring::RoaringBitmap::new(),
3752 pending_put_cols: std::collections::HashSet::new(),
3753 pending_rows: Vec::new(),
3754 pending_rows_auto_inc: Vec::new(),
3755 pending_dels: Vec::new(),
3756 pending_truncate: None,
3757 wal_dek,
3758 auto_inc,
3759 ttl: manifest.ttl,
3760 pins: Arc::new(crate::retention::PinRegistry::new()),
3761 published: Arc::new(ArcSwap::from_pointee(initial_view)),
3762 read_generation_pin: None,
3763 lookup_metrics: LookupMetrics::default(),
3764 run_lookup: RunLookupState::default(),
3765 };
3766
3767 db.epoch.advance_recovered(Epoch(recovered_epoch));
3770
3771 let checkpoint = match db.idx_root.as_deref() {
3776 Some(root) => {
3777 global_idx::read_root(root, db.table_id, &db.schema, db.idx_dek().as_deref())?
3778 }
3779 None => global_idx::read(&db.dir, db.table_id, &db.schema, db.idx_dek().as_deref())?,
3780 };
3781 let checkpoint_valid = checkpoint.as_ref().is_some_and(|c| {
3782 c.epoch_built == manifest.global_idx_epoch
3783 && manifest.global_idx_epoch > 0
3784 && manifest
3785 .runs
3786 .iter()
3787 .all(|r| r.epoch_created <= manifest.global_idx_epoch)
3788 });
3789 if let Some(loaded) = checkpoint {
3790 if checkpoint_valid {
3791 db.hot = loaded.hot;
3792 db.bitmap = loaded.bitmap;
3793 db.ann = loaded.ann;
3794 db.fm = loaded.fm;
3795 db.sparse = loaded.sparse;
3796 db.minhash = loaded.minhash;
3797 db.learned_range = Arc::new(loaded.learned_range);
3798 let (bitmap0, ann0, fm0, sparse0, minhash0) = empty_indexes(&db.schema);
3803 for (cid, idx) in bitmap0 {
3804 db.bitmap.entry(cid).or_insert(idx);
3805 }
3806 for (cid, idx) in ann0 {
3807 db.ann.entry(cid).or_insert(idx);
3808 }
3809 for (cid, idx) in fm0 {
3810 db.fm.entry(cid).or_insert(idx);
3811 }
3812 for (cid, idx) in sparse0 {
3813 db.sparse.entry(cid).or_insert(idx);
3814 }
3815 for (cid, idx) in minhash0 {
3816 db.minhash.entry(cid).or_insert(idx);
3817 }
3818 }
3821 }
3822 if !checkpoint_valid {
3823 let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&db.schema);
3824 db.bitmap = bitmap;
3825 db.ann = ann;
3826 db.fm = fm;
3827 db.sparse = sparse;
3828 db.minhash = minhash;
3829 db.rebuild_indexes_from_runs()?;
3830 db.build_learned_ranges()?;
3831 }
3832
3833 for (epoch, group) in replayed_puts {
3840 let (losers, winner_pks) = db.partition_pk_winners(&group);
3841 for (key, &row_id) in &winner_pks {
3842 if let Some(old_rid) = db.hot.get(key) {
3843 if old_rid != row_id {
3844 db.tombstone_row(old_rid, epoch, None, false);
3845 }
3846 }
3847 }
3848 for &loser_rid in &losers {
3849 db.tombstone_row(loser_rid, epoch, None, false);
3850 }
3851 for (key, row_id) in winner_pks {
3852 db.insert_hot_pk(key, row_id);
3853 }
3854 if db.schema.primary_key().is_none() {
3855 for r in &group {
3856 db.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
3857 }
3858 }
3859 if checkpoint_valid {
3860 for r in &group {
3861 if !losers.contains(&r.row_id) {
3862 db.index_row(r);
3863 }
3864 }
3865 }
3866 }
3867 for (rid, epoch) in &replayed_deletes {
3871 db.remove_hot_for_row(*rid, *epoch);
3872 }
3873
3874 if recovered_manifest_dirty {
3875 let rows = db.visible_rows(Snapshot::unbounded())?;
3876 db.live_count = rows.len() as u64;
3877 db.persist_manifest(Epoch(recovered_epoch))?;
3878 }
3879
3880 let identity = crate::result_cache::PersistentCacheIdentity {
3887 table_id: db.table_id,
3888 schema_id: db.schema.schema_id,
3889 logical_generation: db.epoch.visible().0,
3890 };
3891 db.result_cache.lock().load_persistent(identity);
3892 db.refresh_run_row_id_ranges();
3894 db.load_run_lookup_directory();
3899 Ok(db)
3900 }
3901
3902 fn load_run_lookup_directory(&mut self) {
3907 let active_runs = self.run_refs.clone();
3908 let schema_id = self.schema.schema_id;
3909 let run_generation = active_runs.len() as u64;
3910 let index_generation = self.global_idx_epoch;
3911 let fingerprint = crate::run_lookup::compute_fingerprint(
3912 &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
3913 schema_id,
3914 index_generation,
3915 run_generation,
3916 crate::run_lookup::DIRECTORY_FORMAT_VERSION,
3917 );
3918 let runs_dir = match self.runs_root.as_deref() {
3920 Some(root) => match root.io_path() {
3921 Ok(p) => p,
3922 Err(_) => self.dir.join(RUNS_DIR),
3923 },
3924 None => self.dir.join(RUNS_DIR),
3925 };
3926 match crate::run_lookup::RunLookupDirectory::read_checkpoint_sharded(&runs_dir, fingerprint)
3927 {
3928 Ok(dir) => {
3929 self.run_lookup = RunLookupState {
3930 directory: Some(std::sync::Arc::new(dir)),
3931 fingerprint,
3932 complete: true,
3933 };
3934 }
3935 Err(error) => {
3936 self.lookup_metrics
3937 .directory_incomplete
3938 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3939 self.lookup_metrics
3940 .directory_lookup_fallback
3941 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3942 self.run_lookup = RunLookupState {
3943 directory: None,
3944 fingerprint,
3945 complete: false,
3946 };
3947 let _ = error;
3951 }
3952 }
3953 }
3954
3955 fn ensure_reservoir_complete(&mut self) -> Result<()> {
3961 if self.reservoir_complete {
3962 return Ok(());
3963 }
3964 self.rebuild_reservoir()?;
3965 self.reservoir_complete = true;
3966 Ok(())
3967 }
3968
3969 fn rebuild_reservoir(&mut self) -> Result<()> {
3972 let snap = self.snapshot();
3973 let rows = self.visible_rows(snap)?;
3974 self.reservoir.reset();
3975 for r in rows {
3976 self.reservoir.offer(r.row_id.0);
3977 }
3978 Ok(())
3979 }
3980
3981 pub fn rebuild_indexes(&mut self) -> Result<()> {
3985 self.rebuild_indexes_from_runs_inner(None)
3986 }
3987
3988 pub fn __force_hot_map_for_test(&mut self, pk_bytes: &[u8], row_id: RowId) {
3999 self.hot.insert(pk_bytes.to_vec(), row_id);
4000 }
4001
4002 pub fn hot_for_test_remove(&mut self, pk_bytes: &[u8]) {
4005 self.hot.remove(pk_bytes);
4006 }
4007
4008 pub fn set_indexes_incomplete_for_test(&mut self) {
4011 self.indexes_complete = false;
4012 }
4013
4014 pub fn bump_hot_checkpoint_rejected_for_test(&self) {
4018 self.lookup_metrics
4019 .hot_checkpoint_rejected_total
4020 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4021 }
4022
4023 pub fn __install_run_for_test(&mut self, rows: &[Row]) -> Result<u128> {
4030 let mut rows = rows.to_vec();
4031 rows.sort_by_key(|r| (r.row_id, r.committed_epoch));
4032 let epoch = rows
4033 .iter()
4034 .map(|r| r.committed_epoch)
4035 .max()
4036 .unwrap_or(Epoch::ZERO);
4037 let run_id = self.alloc_run_id()?;
4038 let path = self.run_path(run_id);
4039 if let Some(parent) = path.parent() {
4040 std::fs::create_dir_all(parent)
4041 .map_err(|e| MongrelError::Other(format!("create runs dir: {e}")))?;
4042 }
4043 let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
4044 if let Some(kek) = &self.kek {
4045 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
4046 }
4047 let header = match self.create_run_file(run_id)? {
4048 Some(file) => writer.write_file(file, &rows)?,
4049 None => writer.write(&path, &rows)?,
4050 };
4051 self.run_refs.push(RunRef {
4052 run_id: run_id as u128,
4053 level: 0,
4054 epoch_created: epoch.0,
4055 row_count: header.row_count,
4056 });
4057 self.run_row_id_ranges
4058 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
4059 Ok(run_id as u128)
4060 }
4061
4062 pub fn __rebuild_run_lookup_for_test(&mut self) -> Result<()> {
4067 self.publish_run_lookup_directory()
4068 }
4069
4070 pub fn __set_run_lookup_complete_for_test(&mut self, complete: bool) {
4077 self.run_lookup.complete = complete;
4078 }
4079
4080 pub(crate) fn rebuild_indexes_from_runs(&mut self) -> Result<()> {
4081 self.rebuild_indexes_from_runs_inner(None)
4082 }
4083
4084 fn pk_equality_fallback(
4111 &self,
4112 pk_column_id: u16,
4113 lookup: &[u8],
4114 snapshot: Snapshot,
4115 ) -> Result<(RowIdSet, crate::trace::HotFallbackReason)> {
4116 let mut tombstone_hit = false;
4117 let mut overlay_versions = 0u64;
4118 let now_nanos = unix_nanos_now();
4119 for row in self.memtable.visible_versions_at(snapshot) {
4121 overlay_versions += 1;
4122 self.lookup_metrics
4123 .hot_lookup_fallback_overlay_rows
4124 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4125 if row.deleted {
4126 tombstone_hit = true;
4127 continue;
4128 }
4129 if self.row_expired_at(&row, now_nanos) {
4130 continue;
4131 }
4132 if let Some(pk_val) = row.columns.get(&pk_column_id) {
4133 if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4134 self.lookup_metrics
4135 .hot_fallback_overlay_versions_total
4136 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4137 return Ok((
4138 RowIdSet::one(row.row_id.0),
4139 crate::trace::HotFallbackReason::MissingMapping,
4140 ));
4141 }
4142 }
4143 }
4144 for row in self.mutable_run.visible_versions_at(snapshot) {
4145 overlay_versions += 1;
4146 self.lookup_metrics
4147 .hot_lookup_fallback_overlay_rows
4148 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4149 if row.deleted {
4150 tombstone_hit = true;
4151 continue;
4152 }
4153 if self.row_expired_at(&row, now_nanos) {
4154 continue;
4155 }
4156 if let Some(pk_val) = row.columns.get(&pk_column_id) {
4157 if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4158 self.lookup_metrics
4159 .hot_fallback_overlay_versions_total
4160 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4161 return Ok((
4162 RowIdSet::one(row.row_id.0),
4163 crate::trace::HotFallbackReason::MissingMapping,
4164 ));
4165 }
4166 }
4167 }
4168 if lookup.len() == 8 {
4171 if let Ok(arr) = <[u8; 8]>::try_from(lookup) {
4172 let n = i64::from_be_bytes(arr);
4173 let result = self.range_scan_i64(pk_column_id, n, n, snapshot)?;
4174 self.lookup_metrics
4175 .hot_lookup_fallback_runs
4176 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4177 self.lookup_metrics
4181 .hot_fallback_runs_considered_total
4182 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4183 self.lookup_metrics
4184 .hot_fallback_overlay_versions_total
4185 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4186 let reason = if result.is_empty() {
4187 if tombstone_hit {
4188 crate::trace::HotFallbackReason::Tombstone
4189 } else {
4190 crate::trace::HotFallbackReason::MissingMapping
4191 }
4192 } else {
4193 crate::trace::HotFallbackReason::MissingMapping
4194 };
4195 return Ok((result, reason));
4196 }
4197 }
4198 let mut found: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
4201 let overlay = self.overlay_rid_set(snapshot);
4202 let mut runs_considered = 0u64;
4203 for rr in &self.run_refs {
4204 runs_considered += 1;
4205 self.lookup_metrics
4206 .hot_lookup_fallback_runs
4207 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4208 let mut reader = self.open_reader(rr.run_id)?;
4209 for row in reader.visible_versions_at(snapshot)? {
4210 if overlay.contains(&row.row_id.0) || row.deleted {
4211 if row.deleted {
4212 tombstone_hit = true;
4213 }
4214 continue;
4215 }
4216 if self.row_expired_at(&row, now_nanos) {
4217 continue;
4218 }
4219 if let Some(pk_val) = row.columns.get(&pk_column_id) {
4220 if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4221 found.insert(row.row_id.0);
4222 }
4223 }
4224 }
4225 }
4226 let reason = if tombstone_hit {
4227 crate::trace::HotFallbackReason::Tombstone
4228 } else {
4229 crate::trace::HotFallbackReason::MissingMapping
4232 };
4233 self.lookup_metrics
4234 .hot_fallback_overlay_versions_total
4235 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4236 self.lookup_metrics
4237 .hot_fallback_runs_considered_total
4238 .fetch_add(runs_considered, std::sync::atomic::Ordering::Relaxed);
4239 Ok((RowIdSet::from_unsorted(found.into_iter().collect()), reason))
4240 }
4241
4242 fn record_hot_fallback_reason(&self, reason: crate::trace::HotFallbackReason) {
4246 let idx = hot_fallback_reason_index(reason);
4247 self.lookup_metrics.hot_fallback_reasons[idx]
4248 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4249 self.lookup_metrics
4250 .hot_lookup_fallback
4251 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4252 crate::trace::QueryTrace::record(|t| {
4253 t.hot_lookup_attempted = true;
4254 t.hot_lookup_hit = false;
4255 t.hot_fallback_reason = Some(reason.as_str());
4256 });
4257 }
4258
4259 fn rebuild_indexes_from_runs_inner(
4260 &mut self,
4261 control: Option<&crate::ExecutionControl>,
4262 ) -> Result<()> {
4263 let _index_build_pin = Arc::clone(self.pin_registry()).pin(
4266 crate::retention::PinSource::OnlineIndexBuild,
4267 self.current_epoch(),
4268 );
4269 self.hot = HotIndex::new();
4270 self.pk_by_row.clear();
4271 let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
4272 self.bitmap = bitmap;
4273 self.ann = ann;
4274 self.fm = fm;
4275 self.sparse = sparse;
4276 self.minhash = minhash;
4277 let snapshot = Snapshot::unbounded();
4300 let ttl_now = unix_nanos_now();
4301 let mut scanned = 0_usize;
4302 let mut winners: HashMap<RowId, (VersionStamp, Row)> = HashMap::new();
4303 let fold =
4304 |row: Row, winners: &mut HashMap<RowId, (VersionStamp, Row)>, scanned: &mut usize| {
4305 *scanned += 1;
4306 let stamp = VersionStamp {
4307 epoch: row.committed_epoch,
4308 commit_ts: row.commit_ts,
4309 };
4310 winners
4311 .entry(row.row_id)
4312 .and_modify(|entry| {
4313 if stamp.is_newer_than(entry.0) {
4314 *entry = (stamp, row.clone());
4315 }
4316 })
4317 .or_insert((stamp, row));
4318 };
4319 for rr in self.run_refs.clone() {
4320 if let Some(control) = control {
4321 control.checkpoint()?;
4322 }
4323 let mut reader = self.open_reader(rr.run_id)?;
4324 for row in reader.visible_versions_at(snapshot)? {
4325 if scanned.is_multiple_of(256) {
4326 if let Some(control) = control {
4327 control.checkpoint()?;
4328 }
4329 }
4330 fold(row, &mut winners, &mut scanned);
4334 }
4335 }
4336 for (index, row) in self
4337 .memtable
4338 .visible_versions_at(snapshot)
4339 .into_iter()
4340 .enumerate()
4341 {
4342 if index & 255 == 0 {
4343 if let Some(control) = control {
4344 control.checkpoint()?;
4345 }
4346 }
4347 fold(row, &mut winners, &mut scanned);
4348 }
4349 for (index, row) in self
4350 .mutable_run
4351 .visible_versions_at(snapshot)
4352 .into_iter()
4353 .enumerate()
4354 {
4355 if index & 255 == 0 {
4356 if let Some(control) = control {
4357 control.checkpoint()?;
4358 }
4359 }
4360 fold(row, &mut winners, &mut scanned);
4361 }
4362 let any_predicate = self
4367 .schema
4368 .indexes
4369 .iter()
4370 .any(|idx| idx.predicate.is_some());
4371 let name_to_id: HashMap<&str, u16> = self
4372 .schema
4373 .columns
4374 .iter()
4375 .map(|c| (c.name.as_str(), c.id))
4376 .collect();
4377 for (_rid, (stamp, row)) in winners.drain() {
4378 if row.deleted {
4379 let _ = stamp;
4382 continue;
4383 }
4384 let tok_row = self.tokenized_for_indexes(&row);
4387 if !any_predicate {
4388 index_into(
4389 &self.schema,
4390 &tok_row,
4391 &mut self.hot,
4392 &mut self.bitmap,
4393 &mut self.ann,
4394 &mut self.fm,
4395 &mut self.sparse,
4396 &mut self.minhash,
4397 );
4398 continue;
4399 }
4400 if let Some(pk_col) = self.schema.primary_key() {
4401 if let Some(pk_val) = tok_row.columns.get(&pk_col.id) {
4402 self.hot.insert(pk_val.encode_key(), tok_row.row_id);
4403 }
4404 }
4405 let columns_map: HashMap<u16, &Value> =
4406 row.columns.iter().map(|(k, v)| (*k, v)).collect();
4407 for idef in &self.schema.indexes {
4408 if let Some(pred) = &idef.predicate {
4409 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4410 continue;
4411 }
4412 }
4413 index_into_single(
4414 idef,
4415 &self.schema,
4416 &tok_row,
4417 &mut self.hot,
4418 &mut self.bitmap,
4419 &mut self.ann,
4420 &mut self.fm,
4421 &mut self.sparse,
4422 &mut self.minhash,
4423 );
4424 }
4425 }
4426 let pin_epochs = self.active_pin_epochs_for_rebuild();
4436 if !pin_epochs.is_empty() {
4437 let current_snap = Snapshot::at(Epoch(u64::MAX));
4438 let mut historical: HashMap<RowId, Row> = HashMap::new();
4439 for pin_epoch in pin_epochs {
4440 if let Some(control) = control {
4441 control.checkpoint()?;
4442 }
4443 let pin_snap = Snapshot::at(pin_epoch);
4444 for rr in self.run_refs.clone() {
4445 if let Some(control) = control {
4446 control.checkpoint()?;
4447 }
4448 let mut reader = self.open_reader(rr.run_id)?;
4449 for row in reader.visible_rows(pin_epoch)? {
4450 if row.deleted || self.row_expired_at(&row, ttl_now) {
4451 continue;
4452 }
4453 if historical.contains_key(&row.row_id) {
4454 continue;
4455 }
4456 if self.get(row.row_id, current_snap).is_none() {
4457 historical.insert(row.row_id, row);
4458 }
4459 }
4460 }
4461 for row in self
4462 .mutable_run
4463 .visible_versions_at(pin_snap)
4464 .into_iter()
4465 .chain(self.memtable.visible_versions_at(pin_snap))
4466 {
4467 if row.deleted || self.row_expired_at(&row, ttl_now) {
4468 continue;
4469 }
4470 if historical.contains_key(&row.row_id) {
4471 continue;
4472 }
4473 if self.get(row.row_id, current_snap).is_none() {
4474 historical.insert(row.row_id, row);
4475 }
4476 }
4477 }
4478 for row in historical.into_values() {
4479 self.index_secondary_membership_only(&row);
4480 }
4481 }
4482 self.recent_delete_preimages.clear();
4483 self.refresh_pk_by_row_from_hot();
4484 Ok(())
4485 }
4486
4487 fn index_secondary_membership_only(&mut self, row: &Row) {
4492 if row.deleted {
4493 return;
4494 }
4495 self.index_bitmap_membership_only(row);
4496 let effective = if self.column_keys.is_empty() {
4497 None
4498 } else {
4499 Some(self.tokenized_for_indexes(row))
4500 };
4501 let source = effective.as_ref().unwrap_or(row);
4502 let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4503 let name_to_id: HashMap<&str, u16> = self
4504 .schema
4505 .columns
4506 .iter()
4507 .map(|c| (c.name.as_str(), c.id))
4508 .collect();
4509 for idef in &self.schema.indexes {
4510 if idef.kind == crate::schema::IndexKind::Bitmap {
4511 continue;
4512 }
4513 if let Some(pred) = &idef.predicate {
4514 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4515 continue;
4516 }
4517 }
4518 index_into_single(
4519 idef,
4520 &self.schema,
4521 source,
4522 &mut self.hot,
4523 &mut self.bitmap,
4524 &mut self.ann,
4525 &mut self.fm,
4526 &mut self.sparse,
4527 &mut self.minhash,
4528 );
4529 }
4530 }
4531
4532 fn index_bitmap_membership_only(&mut self, row: &Row) {
4535 if row.deleted {
4536 return;
4537 }
4538 let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4539 let name_to_id: HashMap<&str, u16> = self
4540 .schema
4541 .columns
4542 .iter()
4543 .map(|c| (c.name.as_str(), c.id))
4544 .collect();
4545 for idef in &self.schema.indexes {
4546 if idef.kind != crate::schema::IndexKind::Bitmap {
4547 continue;
4548 }
4549 if let Some(pred) = &idef.predicate {
4550 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4551 continue;
4552 }
4553 }
4554 if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
4555 if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
4556 b.insert(key, row.row_id);
4557 }
4558 }
4559 }
4560 }
4561
4562 fn refresh_pk_by_row_from_hot(&mut self) {
4563 self.pk_by_row_complete = true;
4564 if self.schema.primary_key().is_none() {
4565 self.pk_by_row.clear();
4566 return;
4567 }
4568 self.pk_by_row = ReversePkMap::from_entries(
4574 self.hot
4575 .entries()
4576 .into_iter()
4577 .map(|(key, row_id)| (row_id, key)),
4578 );
4579 }
4580
4581 fn insert_hot_pk(&mut self, key: Vec<u8>, row_id: RowId) {
4582 if self.schema.primary_key().is_some() {
4583 self.pk_by_row.insert(row_id, key.clone());
4584 }
4585 self.hot.insert(key, row_id);
4586 }
4587
4588 pub(crate) fn build_learned_ranges(&mut self) -> Result<()> {
4592 self.build_learned_ranges_inner(None)
4593 }
4594
4595 fn build_learned_ranges_inner(
4596 &mut self,
4597 control: Option<&crate::ExecutionControl>,
4598 ) -> Result<()> {
4599 self.learned_range = Arc::new(HashMap::new());
4600 if self.run_refs.len() != 1 {
4601 return Ok(());
4602 }
4603 let cols: Vec<(u16, usize)> = self
4604 .schema
4605 .indexes
4606 .iter()
4607 .filter(|i| i.kind == IndexKind::LearnedRange)
4608 .map(|i| {
4609 (
4610 i.column_id,
4611 i.options
4612 .learned_range
4613 .as_ref()
4614 .map(|options| options.epsilon)
4615 .unwrap_or(16),
4616 )
4617 })
4618 .collect();
4619 if cols.is_empty() {
4620 return Ok(());
4621 }
4622 let snapshot = Snapshot::unbounded();
4633 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
4634 let (visible_positions, visible_rids) = reader.visible_positions_with_rids_at(snapshot)?;
4635 let row_ids: Vec<u64> = visible_rids.iter().map(|r| *r as u64).collect();
4636 for (column_index, (cid, epsilon)) in cols.into_iter().enumerate() {
4637 if column_index % 256 == 0 {
4638 if let Some(control) = control {
4639 control.checkpoint()?;
4640 }
4641 }
4642 let ty = self
4643 .schema
4644 .columns
4645 .iter()
4646 .find(|c| c.id == cid)
4647 .map(|c| c.ty.clone())
4648 .unwrap_or(TypeId::Int64);
4649 match ty {
4650 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
4651 if let columnar::NativeColumn::Int64 { data, .. } = reader.column_native(cid)? {
4652 let pairs: Vec<(i64, u64)> = visible_positions
4653 .iter()
4654 .zip(row_ids.iter())
4655 .map(|(&p, &r)| (data[p], r))
4656 .collect();
4657 Arc::make_mut(&mut self.learned_range).insert(
4658 cid,
4659 ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon),
4660 );
4661 }
4662 }
4663 TypeId::Float64 => {
4664 if let columnar::NativeColumn::Float64 { data, .. } =
4665 reader.column_native(cid)?
4666 {
4667 let pairs: Vec<(f64, u64)> = visible_positions
4668 .iter()
4669 .zip(row_ids.iter())
4670 .map(|(&p, &r)| (data[p], r))
4671 .collect();
4672 Arc::make_mut(&mut self.learned_range).insert(
4673 cid,
4674 ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon),
4675 );
4676 }
4677 }
4678 _ => {}
4679 }
4680 }
4681 Ok(())
4682 }
4683
4684 pub fn ensure_indexes_complete(&mut self) -> Result<()> {
4691 if self.indexes_complete {
4692 crate::trace::QueryTrace::record(|t| {
4693 t.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4694 });
4695 return Ok(());
4696 }
4697 crate::trace::QueryTrace::record(|t| {
4698 t.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4699 });
4700 self.rebuild_indexes_from_runs()?;
4701 self.build_learned_ranges()?;
4702 self.indexes_complete = true;
4703 let epoch = self.current_epoch();
4704 self.checkpoint_indexes(epoch);
4705 Ok(())
4706 }
4707
4708 #[doc(hidden)]
4711 pub fn ensure_indexes_complete_controlled<F>(
4712 &mut self,
4713 control: &crate::ExecutionControl,
4714 before_publish: F,
4715 ) -> Result<bool>
4716 where
4717 F: FnOnce() -> bool,
4718 {
4719 self.ensure_indexes_complete_controlled_with_receipt(control, before_publish)
4720 .map(|(changed, _)| changed)
4721 }
4722
4723 #[doc(hidden)]
4726 pub fn ensure_indexes_complete_controlled_with_receipt<F>(
4727 &mut self,
4728 control: &crate::ExecutionControl,
4729 before_publish: F,
4730 ) -> Result<(bool, Option<MaintenanceReceipt>)>
4731 where
4732 F: FnOnce() -> bool,
4733 {
4734 if self.indexes_complete {
4735 crate::trace::QueryTrace::record(|trace| {
4736 trace.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4737 });
4738 return Ok((false, None));
4739 }
4740 crate::trace::QueryTrace::record(|trace| {
4741 trace.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4742 });
4743 control.checkpoint()?;
4744 let maintenance_epoch = self.current_epoch();
4745 self.rebuild_indexes_from_runs_inner(Some(control))?;
4746 self.build_learned_ranges_inner(Some(control))?;
4747 control.checkpoint()?;
4748 if !before_publish() {
4749 return Err(MongrelError::Cancelled);
4750 }
4751 self.indexes_complete = true;
4752 self.checkpoint_indexes(maintenance_epoch);
4753 Ok((
4754 true,
4755 Some(MaintenanceReceipt {
4756 epoch: maintenance_epoch,
4757 }),
4758 ))
4759 }
4760
4761 fn pending_epoch(&self) -> Epoch {
4762 Epoch(self.epoch.visible().0 + 1)
4763 }
4764
4765 fn is_shared(&self) -> bool {
4768 matches!(self.wal, WalSink::Shared(_))
4769 }
4770
4771 fn ensure_txn_id(&mut self) -> Result<u64> {
4775 if self.current_txn_id == 0 {
4776 let id = match &self.wal {
4777 WalSink::Shared(s) => crate::txn::allocate_txn_id(&s.txn_ids)?,
4778 WalSink::Private(_) => {
4779 return Err(MongrelError::Full(
4780 "standalone transaction id namespace exhausted".into(),
4781 ))
4782 }
4783 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4784 };
4785 self.current_txn_id = id;
4786 }
4787 Ok(self.current_txn_id)
4788 }
4789
4790 fn wal_append_data(&mut self, op: Op) -> Result<()> {
4793 self.ensure_writable()?;
4794 let txn_id = self.ensure_txn_id()?;
4795 let table_id = self.table_id;
4796 match &mut self.wal {
4797 WalSink::Private(w) => {
4798 w.append_txn(txn_id, op)?;
4799 self.pending_private_mutations = true;
4800 }
4801 WalSink::Shared(s) => {
4802 s.wal.lock().append(txn_id, table_id, op)?;
4803 }
4804 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4805 }
4806 Ok(())
4807 }
4808
4809 fn ensure_writable(&self) -> Result<()> {
4810 if self.read_only || matches!(self.wal, WalSink::ReadOnly) {
4811 return Err(MongrelError::ReadOnlyReplica);
4812 }
4813 if self.durable_commit_failed {
4814 return Err(MongrelError::Other(
4815 "table poisoned by post-commit failure; reopen required".into(),
4816 ));
4817 }
4818 Ok(())
4819 }
4820
4821 fn require(&self, perm: crate::auth_state::RequiredPermission) -> Result<()> {
4832 match &self.auth {
4833 Some(checker) => checker.check(&self.name, perm),
4834 None => Ok(()),
4835 }
4836 }
4837 pub fn require_select(&self) -> Result<()> {
4842 self.require(crate::auth_state::RequiredPermission::Select)
4843 }
4844 fn require_insert(&self) -> Result<()> {
4845 self.require(crate::auth_state::RequiredPermission::Insert)
4846 }
4847 #[allow(dead_code)]
4851 fn require_update(&self) -> Result<()> {
4852 self.require(crate::auth_state::RequiredPermission::Update)
4853 }
4854 fn require_delete(&self) -> Result<()> {
4855 self.require(crate::auth_state::RequiredPermission::Delete)
4856 }
4857
4858 pub fn put(&mut self, columns: Vec<(u16, Value)>) -> Result<RowId> {
4861 self.require_insert()?;
4862 Ok(self.put_returning(columns)?.0)
4863 }
4864
4865 pub fn put_returning(
4870 &mut self,
4871 mut columns: Vec<(u16, Value)>,
4872 ) -> Result<(RowId, Option<i64>)> {
4873 self.require_insert()?;
4874 let assigned = self.fill_auto_inc(&mut columns)?;
4875 self.apply_defaults(&mut columns)?;
4876 self.schema.validate_values(&columns)?;
4877 let row_id = if self.schema.clustered {
4882 self.derive_clustered_row_id(&columns)?
4883 } else {
4884 self.allocator.alloc()?
4885 };
4886 let epoch = self.pending_epoch();
4887 let mut row = Row::new(row_id, epoch);
4888 for (col_id, val) in columns {
4889 row.columns.insert(col_id, val);
4890 }
4891 self.commit_rows(vec![row], assigned.is_some())?;
4892 Ok((row_id, assigned))
4893 }
4894
4895 pub fn put_batch(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Vec<RowId>> {
4898 self.require_insert()?;
4899 Ok(self
4900 .put_batch_returning(batch)?
4901 .into_iter()
4902 .map(|(r, _)| r)
4903 .collect())
4904 }
4905
4906 pub fn put_batch_returning(
4909 &mut self,
4910 batch: Vec<Vec<(u16, Value)>>,
4911 ) -> Result<Vec<(RowId, Option<i64>)>> {
4912 let mut filled: Vec<FilledAutoIncRow> = Vec::with_capacity(batch.len());
4913 for mut cols in batch {
4914 let assigned = self.fill_auto_inc(&mut cols)?;
4915 self.apply_defaults(&mut cols)?;
4916 filled.push((cols, assigned));
4917 }
4918 for (cols, _) in &filled {
4919 self.schema.validate_values(cols)?;
4920 }
4921 let epoch = self.pending_epoch();
4922 let mut rows = Vec::with_capacity(filled.len());
4923 let mut ids = Vec::with_capacity(filled.len());
4924 let first_row_id = if self.schema.clustered {
4925 None
4926 } else {
4927 let count = u64::try_from(filled.len())
4928 .map_err(|_| MongrelError::Full("row-id allocation request is too large".into()))?;
4929 Some(self.allocator.alloc_range(count)?.0)
4930 };
4931 for (row_index, (cols, assigned)) in filled.into_iter().enumerate() {
4932 let row_id = match first_row_id {
4933 Some(first) => RowId(first + row_index as u64),
4934 None => self.derive_clustered_row_id(&cols)?,
4935 };
4936 let mut row = Row::new(row_id, epoch);
4937 for (c, v) in cols {
4938 row.columns.insert(c, v);
4939 }
4940 ids.push((row_id, assigned));
4941 rows.push(row);
4942 }
4943 let all_auto_generated = ids.iter().all(|(_, assigned)| assigned.is_some());
4944 self.commit_rows(rows, all_auto_generated)?;
4945 Ok(ids)
4946 }
4947
4948 pub fn fill_auto_inc(&mut self, columns: &mut Vec<(u16, Value)>) -> Result<Option<i64>> {
4954 self.ensure_writable()?;
4955 let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
4956 return Ok(None);
4957 };
4958 let pos = columns.iter().position(|(c, _)| *c == cid);
4959 let assigned = match pos {
4960 Some(i) => match &columns[i].1 {
4961 Value::Null => {
4962 let next = self.alloc_auto_inc_value()?;
4963 columns[i].1 = Value::Int64(next);
4964 Some(next)
4965 }
4966 Value::Int64(n) => {
4967 self.advance_auto_inc_past(*n)?;
4968 None
4969 }
4970 other => {
4971 return Err(MongrelError::InvalidArgument(format!(
4972 "AUTO_INCREMENT column {cid} must be Int64 or NULL, got {:?}",
4973 other
4974 )))
4975 }
4976 },
4977 None => {
4978 let next = self.alloc_auto_inc_value()?;
4979 columns.push((cid, Value::Int64(next)));
4980 Some(next)
4981 }
4982 };
4983 Ok(assigned)
4984 }
4985
4986 pub fn apply_defaults(&self, columns: &mut Vec<(u16, Value)>) -> Result<()> {
4992 for col in &self.schema.columns {
4993 let Some(expr) = &col.default_value else {
4994 continue;
4995 };
4996 if col.flags.contains(ColumnFlags::AUTO_INCREMENT) {
4998 continue;
4999 }
5000 let pos = columns.iter().position(|(c, _)| *c == col.id);
5001 let needs_default = match pos {
5002 None => true,
5003 Some(i) => matches!(columns[i].1, Value::Null),
5004 };
5005 if !needs_default {
5006 continue;
5007 }
5008 let v = match expr {
5009 crate::schema::DefaultExpr::Static(v) => v.clone(),
5010 crate::schema::DefaultExpr::Now => Value::Bytes(iso_now_bytes()),
5011 crate::schema::DefaultExpr::Uuid => {
5012 let mut buf = [0u8; 16];
5013 getrandom::fill(&mut buf)
5014 .map_err(|e| MongrelError::Other(format!("UUID generation failed: {e}")))?;
5015 Value::Uuid(buf)
5016 }
5017 };
5018 match pos {
5019 None => columns.push((col.id, v)),
5020 Some(i) => columns[i].1 = v,
5021 }
5022 }
5023 Ok(())
5024 }
5025
5026 fn alloc_auto_inc_value(&mut self) -> Result<i64> {
5028 self.ensure_auto_inc_seeded()?;
5029 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5031 let v = ai.next;
5032 ai.next = ai
5033 .next
5034 .checked_add(1)
5035 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5036 Ok(v)
5037 }
5038
5039 fn advance_auto_inc_past(&mut self, used: i64) -> Result<()> {
5042 self.ensure_auto_inc_seeded()?;
5043 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5044 let floor = used
5045 .checked_add(1)
5046 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5047 .max(1);
5048 if ai.next < floor {
5049 ai.next = floor;
5050 }
5051 Ok(())
5052 }
5053
5054 fn ensure_auto_inc_seeded(&mut self) -> Result<()> {
5059 let needs_seed = match self.auto_inc {
5060 Some(ai) => !ai.seeded,
5061 None => return Ok(()),
5062 };
5063 if !needs_seed {
5064 return Ok(());
5065 }
5066 if self.seed_empty_auto_inc() {
5067 return Ok(());
5068 }
5069 let cid = self
5070 .auto_inc
5071 .as_ref()
5072 .expect("auto-inc column present")
5073 .column_id;
5074 let max = self.scan_max_int64(cid)?;
5075 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5076 let floor = max
5077 .checked_add(1)
5078 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5079 .max(1);
5080 if ai.next < floor {
5081 ai.next = floor;
5082 }
5083 ai.seeded = true;
5084 Ok(())
5085 }
5086
5087 fn alloc_auto_inc_range(&mut self, n: usize) -> Result<Option<i64>> {
5088 if n == 0 || self.auto_inc.is_none() {
5089 return Ok(None);
5090 }
5091 self.ensure_auto_inc_seeded()?;
5092 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5093 let start = ai.next;
5094 let count = i64::try_from(n)
5095 .map_err(|_| MongrelError::Full("AUTO_INCREMENT range is too large".into()))?;
5096 ai.next = ai
5097 .next
5098 .checked_add(count)
5099 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5100 Ok(Some(start))
5101 }
5102
5103 fn scan_max_int64(&mut self, column_id: u16) -> Result<i64> {
5107 let mut max: i64 = 0;
5108 for r in self.memtable.visible_versions_at(Snapshot::unbounded()) {
5109 if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5110 if *n > max {
5111 max = *n;
5112 }
5113 }
5114 }
5115 for r in self.mutable_run.visible_versions(Epoch(u64::MAX)) {
5116 if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5117 if *n > max {
5118 max = *n;
5119 }
5120 }
5121 }
5122 for rr in self.run_refs.clone() {
5123 let reader = self.open_reader(rr.run_id)?;
5124 if let Some(stats) = reader.column_page_stats(column_id) {
5125 for s in stats {
5126 if let Some(n) = crate::sorted_run::be_i64(s.max.as_deref()) {
5127 if n > max {
5128 max = n;
5129 }
5130 }
5131 }
5132 } else if reader.has_column(column_id) {
5133 if let columnar::NativeColumn::Int64 { data, validity } =
5134 reader.column_native_shared(column_id)?
5135 {
5136 for (i, n) in data.iter().enumerate() {
5137 if (validity.is_empty() || columnar::validity_bit(&validity, i)) && *n > max
5138 {
5139 max = *n;
5140 }
5141 }
5142 }
5143 }
5144 }
5145 Ok(max)
5146 }
5147
5148 fn seed_empty_auto_inc(&mut self) -> bool {
5149 let Some(ai) = self.auto_inc.as_mut() else {
5150 return false;
5151 };
5152 if ai.seeded || self.live_count != 0 {
5153 return false;
5154 }
5155 if ai.next < 1 {
5156 ai.next = 1;
5157 }
5158 ai.seeded = true;
5159 true
5160 }
5161
5162 fn advance_auto_inc_from_native_columns(
5163 &mut self,
5164 columns: &[(u16, columnar::NativeColumn)],
5165 n: usize,
5166 live_before: u64,
5167 ) -> Result<()> {
5168 let Some(ai) = self.auto_inc.as_mut() else {
5169 return Ok(());
5170 };
5171 let Some((_, col)) = columns.iter().find(|(cid, _)| *cid == ai.column_id) else {
5172 return Ok(());
5173 };
5174 let columnar::NativeColumn::Int64 { data, validity } = col else {
5175 return Err(MongrelError::InvalidArgument(format!(
5176 "AUTO_INCREMENT column {} must be Int64",
5177 ai.column_id
5178 )));
5179 };
5180 let max = if native_int64_strictly_increasing(col, n) {
5181 data.get(n.saturating_sub(1)).copied()
5182 } else {
5183 data.iter()
5184 .take(n)
5185 .enumerate()
5186 .filter_map(|(i, v)| {
5187 if validity.is_empty() || columnar::validity_bit(validity, i) {
5188 Some(*v)
5189 } else {
5190 None
5191 }
5192 })
5193 .max()
5194 };
5195 if let Some(max) = max {
5196 let floor = max
5197 .checked_add(1)
5198 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5199 .max(1);
5200 if ai.next < floor {
5201 ai.next = floor;
5202 }
5203 if ai.seeded || live_before == 0 {
5204 ai.seeded = true;
5205 }
5206 }
5207 Ok(())
5208 }
5209
5210 fn fill_auto_inc_native_columns(
5211 &mut self,
5212 columns: &mut Vec<(u16, columnar::NativeColumn)>,
5213 n: usize,
5214 ) -> Result<()> {
5215 let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
5216 return Ok(());
5217 };
5218 let Some(pos) = columns.iter().position(|(id, _)| *id == cid) else {
5219 if let Some(start) = self.alloc_auto_inc_range(n)? {
5220 columns.push((
5221 cid,
5222 columnar::NativeColumn::Int64 {
5223 data: (start..start.saturating_add(n as i64)).collect(),
5224 validity: vec![0xFF; n.div_ceil(8)],
5225 },
5226 ));
5227 }
5228 return Ok(());
5229 };
5230
5231 let columnar::NativeColumn::Int64 { data, validity } = &mut columns[pos].1 else {
5232 return Err(MongrelError::InvalidArgument(format!(
5233 "AUTO_INCREMENT column {cid} must be Int64"
5234 )));
5235 };
5236 if data.len() < n {
5237 return Err(MongrelError::InvalidArgument(format!(
5238 "AUTO_INCREMENT column {cid} has {} rows, expected {n}",
5239 data.len()
5240 )));
5241 }
5242 if columnar::all_non_null(validity, n) {
5243 return Ok(());
5244 }
5245 if validity.iter().all(|b| *b == 0) {
5246 if let Some(start) = self.alloc_auto_inc_range(n)? {
5247 for (i, slot) in data.iter_mut().take(n).enumerate() {
5248 *slot = start.saturating_add(i as i64);
5249 }
5250 *validity = vec![0xFF; n.div_ceil(8)];
5251 }
5252 return Ok(());
5253 }
5254
5255 let new_validity = vec![0xFF; data.len().div_ceil(8)];
5256 for (i, slot) in data.iter_mut().enumerate().take(n) {
5257 if columnar::validity_bit(validity, i) {
5258 self.advance_auto_inc_past(*slot)?;
5259 } else {
5260 *slot = self.alloc_auto_inc_value()?;
5261 }
5262 }
5263 *validity = new_validity;
5264 Ok(())
5265 }
5266
5267 pub fn reserve_auto_inc(&mut self) -> Result<Option<i64>> {
5281 self.ensure_writable()?;
5282 if self.auto_inc.is_none() {
5283 return Ok(None);
5284 }
5285 Ok(Some(self.alloc_auto_inc_value()?))
5286 }
5287
5288 fn commit_rows(&mut self, rows: Vec<Row>, auto_inc_generated: bool) -> Result<()> {
5294 let payload = bincode::serialize(&rows)?;
5295 self.wal_append_data(Op::Put {
5296 table_id: self.table_id,
5297 rows: payload,
5298 })?;
5299 if self.is_shared() {
5300 self.pending_rows_auto_inc
5301 .extend(std::iter::repeat_n(auto_inc_generated, rows.len()));
5302 self.pending_rows.extend(rows);
5303 } else {
5304 self.apply_put_rows_inner(rows, !auto_inc_generated)?;
5305 }
5306 Ok(())
5307 }
5308
5309 pub(crate) fn prepare_durable_publish(&mut self) -> Result<()> {
5312 self.ensure_indexes_complete()
5313 }
5314
5315 pub(crate) fn prepare_durable_publish_controlled(
5316 &mut self,
5317 control: &crate::ExecutionControl,
5318 ) -> Result<()> {
5319 self.ensure_indexes_complete_controlled(control, || true)?;
5320 Ok(())
5321 }
5322
5323 pub(crate) fn apply_put_rows_prepared(&mut self, rows: Vec<Row>) {
5324 self.apply_put_rows_inner_prepared(rows, true);
5325 }
5326
5327 fn apply_put_rows_inner(&mut self, rows: Vec<Row>, check_existing_pk: bool) -> Result<()> {
5328 if check_existing_pk {
5329 self.ensure_indexes_complete()?;
5330 }
5331 self.apply_put_rows_inner_prepared(rows, check_existing_pk);
5332 Ok(())
5333 }
5334
5335 fn apply_put_rows_inner_prepared(&mut self, rows: Vec<Row>, check_existing_pk: bool) {
5339 if rows.len() == 1 {
5343 let row = rows.into_iter().next().expect("len checked");
5344 self.apply_put_row_single(row, check_existing_pk);
5345 return;
5346 }
5347 let pk_id = self.schema.primary_key().map(|c| c.id);
5364 let probe = match pk_id {
5365 Some(pid) => {
5366 check_existing_pk
5367 && !(self.hot.is_empty() && rows_pk_strictly_increasing(&rows, pid))
5368 }
5369 None => false,
5370 };
5371 let maintain_pk_by_row = pk_id.is_some() && self.pk_by_row_complete;
5374 for r in rows {
5375 for &cid in r.columns.keys() {
5376 self.pending_put_cols.insert(cid);
5377 }
5378 let mut replaced_image: Option<Row> = None;
5379 match pk_id {
5380 Some(pid) if probe || maintain_pk_by_row => {
5381 if let Some(pk_val) = r.columns.get(&pid) {
5382 let key = self.index_lookup_key(pid, pk_val);
5383 if probe {
5384 if let Some(old) = self.recent_delete_preimages.remove(&key) {
5393 replaced_image = Some(old);
5394 if let Some(old_rid) = self.hot.get(&key) {
5395 if old_rid != r.row_id {
5396 self.tombstone_row(
5397 old_rid,
5398 r.committed_epoch,
5399 r.commit_ts,
5400 true,
5401 );
5402 }
5403 }
5404 } else if let Some(old_rid) = self.hot.get(&key) {
5405 if old_rid != r.row_id {
5406 replaced_image = self.get(old_rid, self.snapshot());
5407 self.tombstone_row(
5408 old_rid,
5409 r.committed_epoch,
5410 r.commit_ts,
5411 true,
5412 );
5413 }
5414 }
5415 }
5416 if maintain_pk_by_row {
5417 self.pk_by_row.insert(r.row_id, key);
5418 }
5419 }
5420 }
5421 Some(_) => {}
5422 None => {
5423 self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5424 }
5425 }
5426 if let Some(old) = replaced_image {
5427 self.maintain_indexes_on_pk_replace(&old, &r);
5428 } else {
5429 self.index_row(&r);
5430 }
5431 self.reservoir.offer(r.row_id.0);
5432 self.memtable.upsert(r);
5433 self.live_count = self.live_count.saturating_add(1);
5436 }
5437 self.data_generation = self.data_generation.wrapping_add(1);
5438 }
5439
5440 fn apply_put_row_single(&mut self, row: Row, check_existing_pk: bool) {
5450 for &cid in row.columns.keys() {
5451 self.pending_put_cols.insert(cid);
5452 }
5453 let epoch = row.committed_epoch;
5454 let mut replaced_image: Option<Row> = None;
5455 if let Some(pk_col) = self.schema.primary_key() {
5456 let pk_id = pk_col.id;
5457 if let Some(pk_val) = row.columns.get(&pk_id) {
5458 let maintain_pk_by_row = self.pk_by_row_complete;
5462 if check_existing_pk || maintain_pk_by_row {
5463 let key = self.index_lookup_key(pk_id, pk_val);
5464 if check_existing_pk {
5465 if let Some(old) = self.recent_delete_preimages.remove(&key) {
5474 replaced_image = Some(old);
5475 if let Some(old_rid) = self.hot.get(&key) {
5476 if old_rid != row.row_id {
5477 self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5478 }
5479 }
5480 } else if let Some(old_rid) = self.hot.get(&key) {
5481 if old_rid != row.row_id {
5482 replaced_image = self.get(old_rid, self.snapshot());
5486 self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5487 }
5488 }
5489 }
5490 if maintain_pk_by_row {
5491 self.pk_by_row.insert(row.row_id, key);
5492 }
5493 }
5494 }
5495 } else {
5496 self.hot
5497 .insert(row.row_id.0.to_be_bytes().to_vec(), row.row_id);
5498 }
5499 if let Some(old) = replaced_image {
5500 self.maintain_indexes_on_pk_replace(&old, &row);
5501 } else {
5502 self.index_row(&row);
5503 }
5504 self.reservoir.offer(row.row_id.0);
5505 self.memtable.upsert(row);
5506 self.live_count = self.live_count.saturating_add(1);
5507 self.data_generation = self.data_generation.wrapping_add(1);
5508 }
5509
5510 fn maintain_indexes_on_pk_replace(&mut self, old: &Row, new: &Row) {
5513 let has_partial = self
5514 .schema
5515 .indexes
5516 .iter()
5517 .any(|idx| idx.predicate.is_some());
5518 if has_partial {
5519 self.unindex_bitmap_membership(old);
5523 self.index_row(new);
5524 return;
5525 }
5526
5527 crate::index::maintain_bitmap_secondary_on_replace(
5528 &self.schema,
5529 &mut self.bitmap,
5530 old,
5531 new,
5532 );
5533 self.index_row_non_bitmap(new);
5534 }
5535
5536 fn index_row_non_bitmap(&mut self, row: &Row) {
5539 if row.deleted {
5540 return;
5541 }
5542 let effective = if self.column_keys.is_empty() {
5543 None
5544 } else {
5545 Some(self.tokenized_for_indexes(row))
5546 };
5547 let source = effective.as_ref().unwrap_or(row);
5548 for idef in &self.schema.indexes {
5549 if idef.kind == crate::schema::IndexKind::Bitmap {
5550 continue;
5551 }
5552 index_into_single(
5553 idef,
5554 &self.schema,
5555 source,
5556 &mut self.hot,
5557 &mut self.bitmap,
5558 &mut self.ann,
5559 &mut self.fm,
5560 &mut self.sparse,
5561 &mut self.minhash,
5562 );
5563 }
5564 if let Some(pk_col) = self.schema.primary_key() {
5565 if let Some(pk_val) = source.columns.get(&pk_col.id) {
5566 let key = if self.column_keys.is_empty() {
5567 pk_val.encode_key()
5568 } else {
5569 self.index_lookup_key(pk_col.id, pk_val)
5570 };
5571 self.hot.insert(key, source.row_id);
5572 }
5573 }
5574 }
5575
5576 pub(crate) fn alloc_row_id(&mut self) -> Result<RowId> {
5579 self.allocator.alloc()
5580 }
5581
5582 fn derive_clustered_row_id(&self, columns: &[(u16, Value)]) -> Result<RowId> {
5588 let pk = self.schema.primary_key().ok_or_else(|| {
5589 MongrelError::Schema("clustered table requires a single-column primary key".into())
5590 })?;
5591 let pk_val = columns
5592 .iter()
5593 .find(|(id, _)| *id == pk.id)
5594 .map(|(_, v)| v)
5595 .ok_or_else(|| {
5596 MongrelError::Schema(format!(
5597 "clustered table missing primary key column {} ({})",
5598 pk.id, pk.name
5599 ))
5600 })?;
5601 Ok(clustered_row_id(pk_val))
5602 }
5603
5604 pub(crate) fn apply_run_metadata_prepared(&mut self, rows: &[Row]) -> Result<()> {
5612 if rows.iter().any(|row| row.row_id.0 >= u64::MAX - 1) {
5613 return Err(MongrelError::Full("row-id namespace exhausted".into()));
5614 }
5615 let n = rows.len();
5616 for r in rows {
5617 for &cid in r.columns.keys() {
5618 self.pending_put_cols.insert(cid);
5619 }
5620 }
5621 let (losers, winner_pks) = self.partition_pk_winners(rows);
5622 let epoch = rows.first().map(|r| r.committed_epoch).unwrap_or(Epoch(0));
5623 let group_ts = rows.first().and_then(|r| r.commit_ts);
5625 for (key, &row_id) in &winner_pks {
5626 if let Some(old_rid) = self.hot.get(key) {
5627 if old_rid != row_id {
5628 self.tombstone_row(old_rid, epoch, group_ts, true);
5629 }
5630 }
5631 }
5632 for &loser_rid in &losers {
5635 self.tombstone_row(loser_rid, epoch, group_ts, false);
5636 }
5637 for (key, row_id) in winner_pks {
5639 self.insert_hot_pk(key, row_id);
5640 }
5641 if self.schema.primary_key().is_none() {
5642 for r in rows {
5643 self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5644 }
5645 }
5646 for r in rows {
5647 self.allocator.advance_to(r.row_id)?;
5648 if !losers.contains(&r.row_id) {
5649 self.index_row(r);
5650 }
5651 }
5652 for r in rows {
5653 if !losers.contains(&r.row_id) {
5654 self.reservoir.offer(r.row_id.0);
5655 }
5656 }
5657 self.live_count = self.live_count.saturating_add((n - losers.len()) as u64);
5658 self.data_generation = self.data_generation.wrapping_add(1);
5659 Ok(())
5660 }
5661
5662 pub(crate) fn recover_apply(
5667 &mut self,
5668 rows: Vec<Row>,
5669 deletes: Vec<(RowId, Epoch)>,
5670 ) -> Result<()> {
5671 let mut by_epoch: std::collections::BTreeMap<Epoch, Vec<Row>> =
5675 std::collections::BTreeMap::new();
5676 for row in rows {
5677 if row.row_id.0 >= u64::MAX - 1 {
5678 return Err(MongrelError::Full("row-id namespace exhausted".into()));
5679 }
5680 self.allocator.advance_to(row.row_id)?;
5681 if let Some(ai) = self.auto_inc.as_mut() {
5686 if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
5687 let next = n.checked_add(1).ok_or_else(|| {
5688 MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
5689 })?;
5690 if next > ai.next {
5691 ai.next = next;
5692 }
5693 }
5694 }
5695 by_epoch.entry(row.committed_epoch).or_default().push(row);
5696 }
5697 for (epoch, group) in by_epoch {
5698 let (losers, winner_pks) = self.partition_pk_winners(&group);
5699 let group_ts = group.first().and_then(|r| r.commit_ts);
5701 for (key, &row_id) in &winner_pks {
5702 if let Some(old_rid) = self.hot.get(key) {
5703 if old_rid != row_id {
5704 self.tombstone_row(old_rid, epoch, group_ts, false);
5705 }
5706 }
5707 }
5708 for (key, row_id) in winner_pks {
5709 self.insert_hot_pk(key, row_id);
5710 }
5711 if self.schema.primary_key().is_none() {
5712 for r in &group {
5713 self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5714 }
5715 }
5716 for r in &group {
5717 if !losers.contains(&r.row_id) {
5718 self.memtable.upsert(r.clone());
5719 self.index_row(r);
5720 }
5721 }
5722 }
5723 for (rid, epoch) in deletes {
5724 self.memtable.tombstone(rid, epoch);
5725 self.remove_hot_for_row(rid, epoch);
5726 }
5727 self.reservoir_complete = false;
5730 Ok(())
5731 }
5732
5733 pub(crate) fn flushed_epoch(&self) -> u64 {
5735 self.flushed_epoch
5736 }
5737
5738 pub(crate) fn set_flushed_epoch(&mut self, epoch: Epoch) {
5739 self.flushed_epoch = self.flushed_epoch.max(epoch.0);
5740 }
5741
5742 pub(crate) fn validate_cells_not_null(&self, cells: &[(u16, Value)]) -> Result<()> {
5744 self.schema.validate_values(cells)
5745 }
5746
5747 fn validate_columns_not_null(
5751 &self,
5752 columns: &[(u16, columnar::NativeColumn)],
5753 n: usize,
5754 ) -> Result<()> {
5755 let by_id: HashMap<u16, &columnar::NativeColumn> =
5756 columns.iter().map(|(id, c)| (*id, c)).collect();
5757 for col in &self.schema.columns {
5758 if !col.flags.contains(ColumnFlags::NULLABLE) {
5759 match by_id.get(&col.id) {
5760 None => {
5761 return Err(MongrelError::InvalidArgument(format!(
5762 "column '{}' ({}) is NOT NULL but was omitted from the bulk load",
5763 col.name, col.id
5764 )));
5765 }
5766 Some(c) => {
5767 if c.null_count(n) != 0 {
5768 return Err(MongrelError::InvalidArgument(format!(
5769 "column '{}' ({}) is NOT NULL but the bulk load contains nulls",
5770 col.name, col.id
5771 )));
5772 }
5773 }
5774 }
5775 }
5776 if let TypeId::Enum { variants } = &col.ty {
5777 let Some(columnar::NativeColumn::Bytes { .. }) = by_id.get(&col.id).copied() else {
5778 if by_id.contains_key(&col.id) {
5779 return Err(MongrelError::InvalidArgument(format!(
5780 "column '{}' ({}) enum requires a bytes column",
5781 col.name, col.id
5782 )));
5783 }
5784 continue;
5785 };
5786 for index in 0..n {
5787 let Some(value) = columnar::native_bytes_at(by_id[&col.id], index) else {
5788 continue;
5789 };
5790 if !variants.iter().any(|variant| variant.as_bytes() == value) {
5791 return Err(MongrelError::InvalidArgument(format!(
5792 "column '{}' ({}) enum value {:?} is not one of {:?}",
5793 col.name,
5794 col.id,
5795 String::from_utf8_lossy(value),
5796 variants
5797 )));
5798 }
5799 }
5800 }
5801 }
5802 Ok(())
5803 }
5804
5805 fn bulk_pk_winner_indices(
5810 &self,
5811 columns: &[(u16, columnar::NativeColumn)],
5812 n: usize,
5813 ) -> Option<Vec<usize>> {
5814 let pk_col = self.schema.primary_key()?;
5815 let pk_id = pk_col.id;
5816 let pk_ty = pk_col.ty.clone();
5817 let by_id: HashMap<u16, &columnar::NativeColumn> =
5818 columns.iter().map(|(id, c)| (*id, c)).collect();
5819 let pk_native = by_id.get(&pk_id)?;
5820 if native_int64_strictly_increasing(pk_native, n) {
5821 return None;
5822 }
5823 let mut last: HashMap<Vec<u8>, usize> = HashMap::new();
5825 let mut null_pk_rows: Vec<usize> = Vec::new();
5826 for i in 0..n {
5827 match bulk_index_key(&self.column_keys, pk_id, pk_ty.clone(), pk_native, i) {
5828 Some(key) => {
5829 last.insert(key, i);
5830 }
5831 None => null_pk_rows.push(i),
5832 }
5833 }
5834 let mut winners: HashSet<usize> = last.values().copied().collect();
5835 for i in null_pk_rows {
5836 winners.insert(i);
5837 }
5838 Some((0..n).filter(|i| winners.contains(i)).collect())
5839 }
5840
5841 pub fn delete(&mut self, row_id: RowId) -> Result<()> {
5843 self.require_delete()?;
5844 let epoch = self.pending_epoch();
5845 self.wal_append_data(Op::Delete {
5846 table_id: self.table_id,
5847 row_ids: vec![row_id],
5848 })?;
5849 if self.is_shared() {
5850 self.pending_dels.push(row_id);
5851 } else {
5852 self.apply_delete(row_id, epoch);
5853 }
5854 Ok(())
5855 }
5856
5857 pub fn delete_returning(&mut self, row_id: RowId) -> Result<Option<OwnedRow>> {
5858 let pre = self.get(row_id, self.snapshot());
5859 self.delete(row_id)?;
5860 Ok(pre.map(|row| {
5861 let mut columns: Vec<_> = row.columns.into_iter().collect();
5862 columns.sort_by_key(|(id, _)| *id);
5863 OwnedRow { columns }
5864 }))
5865 }
5866
5867 pub fn truncate(&mut self) -> Result<()> {
5869 self.require_delete()?;
5870 let epoch = self.pending_epoch();
5871 self.wal_append_data(Op::TruncateTable {
5872 table_id: self.table_id,
5873 })?;
5874 self.pending_rows.clear();
5875 self.pending_rows_auto_inc.clear();
5876 self.pending_dels.clear();
5877 self.pending_truncate = Some(epoch);
5878 Ok(())
5879 }
5880
5881 pub(crate) fn apply_truncate(&mut self, _epoch: Epoch) {
5883 self.run_refs.clear();
5888 self.retiring.clear();
5889 self.memtable = Memtable::new();
5890 self.mutable_run = MutableRun::new();
5891 self.hot = HotIndex::new();
5892 let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
5893 self.bitmap = bitmap;
5894 self.ann = ann;
5895 self.fm = fm;
5896 self.sparse = sparse;
5897 self.minhash = minhash;
5898 self.learned_range = Arc::new(HashMap::new());
5899 self.pk_by_row.clear();
5900 self.pk_by_row_complete = false;
5901 self.live_count = 0;
5902 self.reservoir = crate::reservoir::Reservoir::default();
5903 self.reservoir_complete = true;
5904 self.had_deletes = true;
5905 self.agg_cache = Arc::new(HashMap::new());
5906 self.global_idx_epoch = 0;
5907 self.indexes_complete = true;
5908 self.pending_delete_rids.clear();
5909 self.pending_put_cols.clear();
5910 self.pending_rows.clear();
5911 self.pending_rows_auto_inc.clear();
5912 self.pending_dels.clear();
5913 self.clear_result_cache();
5914 self.invalidate_index_checkpoint();
5915 self.data_generation = self.data_generation.wrapping_add(1);
5916 }
5917
5918 pub(crate) fn apply_delete(&mut self, row_id: RowId, epoch: Epoch) {
5921 self.apply_delete_at(row_id, epoch, None);
5922 }
5923
5924 pub(crate) fn apply_delete_at(
5926 &mut self,
5927 row_id: RowId,
5928 epoch: Epoch,
5929 commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
5930 ) {
5931 let preimage = self.get(row_id, self.snapshot());
5941 if let Some(row) = preimage {
5942 if let Some(pk_col) = self.schema.primary_key() {
5943 if let Some(pk_val) = row.columns.get(&pk_col.id) {
5944 let key = self.index_lookup_key(pk_col.id, pk_val);
5945 self.recent_delete_preimages.insert(key, row);
5946 }
5947 }
5948 }
5949 self.tombstone_row(row_id, epoch, commit_ts, true);
5950 self.data_generation = self.data_generation.wrapping_add(1);
5951 }
5952
5953 fn unindex_bitmap_membership(&mut self, row: &Row) {
5958 if row.deleted {
5959 return;
5960 }
5961 for idef in &self.schema.indexes {
5962 if idef.kind != crate::schema::IndexKind::Bitmap {
5963 continue;
5964 }
5965 if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
5966 if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
5967 b.remove(&key, row.row_id);
5968 }
5969 }
5970 }
5971 }
5972
5973 fn union_bitmap_point_i64(
5977 &self,
5978 set: &mut RowIdSet,
5979 column_id: u16,
5980 value: i64,
5981 snapshot: Snapshot,
5982 ) {
5983 let Some(b) = self.bitmap.get(&column_id) else {
5984 return;
5985 };
5986 let encoded = Value::Int64(value).encode_key();
5987 let lookup = self.index_lookup_key_bytes(column_id, &encoded);
5988 for rid in b.get(&lookup).iter() {
5989 set.insert(u64::from(rid));
5990 }
5991 set.remove_many(self.overlay_tombstoned_rids(snapshot));
5995 self.range_scan_overlay_i64(set, column_id, value, value, snapshot);
5996 }
5997
5998 fn tombstone_row(
6012 &mut self,
6013 row_id: RowId,
6014 epoch: Epoch,
6015 commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
6016 adjust_live_count: bool,
6017 ) {
6018 let prev_was_live = if adjust_live_count {
6019 match self.memtable.get_version(row_id, epoch) {
6020 Some((_, prev)) => !prev.deleted,
6021 None => true,
6022 }
6023 } else {
6024 false
6025 };
6026 let tombstone = Row {
6027 row_id,
6028 committed_epoch: epoch,
6029 columns: std::collections::HashMap::new(),
6030 deleted: true,
6031 commit_ts,
6032 };
6033 self.memtable.upsert(tombstone);
6034 self.pk_by_row.remove(&row_id);
6035 if prev_was_live {
6036 self.live_count = self.live_count.saturating_sub(1);
6037 }
6038 self.pending_delete_rids.insert(row_id.0 as u32);
6040 self.had_deletes = true;
6043 self.agg_cache = Arc::new(HashMap::new());
6044 }
6045
6046 fn remove_hot_for_row(&mut self, row_id: RowId, epoch: Epoch) {
6050 let Some(pk_col) = self.schema.primary_key() else {
6051 return;
6052 };
6053 if self.pk_by_row_complete {
6056 if let Some(key) = self.pk_by_row.remove(&row_id) {
6057 if self.hot.get(&key) == Some(row_id) {
6058 self.hot.remove(&key);
6059 }
6060 }
6061 return;
6062 }
6063 let lookup_epoch = Epoch(epoch.0.saturating_sub(1));
6082 if self.indexes_complete {
6083 let pk_val = self
6084 .memtable
6085 .get_version(row_id, lookup_epoch)
6086 .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6087 .or_else(|| {
6088 self.mutable_run
6089 .get_version(row_id, lookup_epoch)
6090 .filter(|(_, r)| !r.deleted)
6091 .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6092 })
6093 .or_else(|| {
6094 self.run_refs.iter().find_map(|rr| {
6095 let mut reader = self.open_reader(rr.run_id).ok()?;
6096 let (_, deleted, val) = reader
6097 .get_version_column(row_id, lookup_epoch, pk_col.id)
6098 .ok()??;
6099 if deleted {
6100 return None;
6101 }
6102 val
6103 })
6104 });
6105 if let Some(pk_val) = pk_val {
6106 let key = self.index_lookup_key(pk_col.id, &pk_val);
6107 if self.hot.get(&key) == Some(row_id) {
6108 self.hot.remove(&key);
6109 }
6110 return;
6111 }
6112 }
6113 self.refresh_pk_by_row_from_hot();
6118 if let Some(key) = self.pk_by_row.remove(&row_id) {
6119 if self.hot.get(&key) == Some(row_id) {
6120 self.hot.remove(&key);
6121 }
6122 }
6123 }
6124
6125 fn partition_pk_winners(
6130 &self,
6131 rows: &[Row],
6132 ) -> (
6133 std::collections::HashSet<RowId>,
6134 std::collections::HashMap<Vec<u8>, RowId>,
6135 ) {
6136 let mut losers = std::collections::HashSet::new();
6137 let Some(pk_col) = self.schema.primary_key() else {
6138 return (losers, std::collections::HashMap::new());
6139 };
6140 let pk_id = pk_col.id;
6141 let mut winners: std::collections::HashMap<Vec<u8>, RowId> =
6142 std::collections::HashMap::new();
6143 for r in rows {
6144 let Some(pk_val) = r.columns.get(&pk_id) else {
6145 continue;
6146 };
6147 let key = self.index_lookup_key(pk_id, pk_val);
6148 if let Some(&old_rid) = winners.get(&key) {
6149 losers.insert(old_rid);
6150 }
6151 winners.insert(key, r.row_id);
6152 }
6153 (losers, winners)
6154 }
6155
6156 fn index_row(&mut self, row: &Row) {
6157 if row.deleted {
6158 return;
6159 }
6160 let any_predicate = self
6168 .schema
6169 .indexes
6170 .iter()
6171 .any(|idx| idx.predicate.is_some());
6172 if any_predicate {
6173 let columns_map: HashMap<u16, &Value> =
6174 row.columns.iter().map(|(k, v)| (*k, v)).collect();
6175 let name_to_id: HashMap<&str, u16> = self
6176 .schema
6177 .columns
6178 .iter()
6179 .map(|c| (c.name.as_str(), c.id))
6180 .collect();
6181 for idx in &self.schema.indexes {
6182 if let Some(pred) = &idx.predicate {
6183 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
6184 continue; }
6186 }
6187 index_into_single(
6189 idx,
6190 &self.schema,
6191 row,
6192 &mut self.hot,
6193 &mut self.bitmap,
6194 &mut self.ann,
6195 &mut self.fm,
6196 &mut self.sparse,
6197 &mut self.minhash,
6198 );
6199 }
6200 return;
6201 }
6202 if self.column_keys.is_empty() {
6206 index_into(
6207 &self.schema,
6208 row,
6209 &mut self.hot,
6210 &mut self.bitmap,
6211 &mut self.ann,
6212 &mut self.fm,
6213 &mut self.sparse,
6214 &mut self.minhash,
6215 );
6216 return;
6217 }
6218 let effective_row = self.tokenized_for_indexes(row);
6219 index_into(
6220 &self.schema,
6221 &effective_row,
6222 &mut self.hot,
6223 &mut self.bitmap,
6224 &mut self.ann,
6225 &mut self.fm,
6226 &mut self.sparse,
6227 &mut self.minhash,
6228 );
6229 }
6230
6231 fn tokenized_for_indexes(&self, row: &Row) -> Row {
6237 if self.column_keys.is_empty() {
6238 return row.clone();
6239 }
6240 {
6241 use crate::encryption::SCHEME_HMAC_EQ;
6242 let mut tok = row.clone();
6243 for (&cid, &(_, scheme)) in &self.column_keys {
6244 if scheme != SCHEME_HMAC_EQ {
6245 continue;
6246 }
6247 if let Some(v) = tok.columns.get(&cid).cloned() {
6248 if let Some(t) = self.tokenize_value(cid, &v) {
6249 tok.columns.insert(cid, t);
6250 }
6251 }
6252 }
6253 tok
6254 }
6255 }
6256
6257 pub fn commit(&mut self) -> Result<Epoch> {
6262 self.commit_inner(None)
6263 }
6264
6265 #[doc(hidden)]
6268 pub fn commit_controlled<F>(
6269 &mut self,
6270 control: &crate::ExecutionControl,
6271 mut before_commit: F,
6272 ) -> Result<Epoch>
6273 where
6274 F: FnMut() -> Result<()>,
6275 {
6276 self.commit_inner(Some((control, &mut before_commit)))
6277 }
6278
6279 fn commit_inner(
6280 &mut self,
6281 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6282 ) -> Result<Epoch> {
6283 self.ensure_writable()?;
6284 if !self.has_pending_mutations() {
6285 if self.current_txn_id == 0 && matches!(&self.wal, WalSink::Private(_)) {
6286 return Err(MongrelError::Full(
6287 "standalone transaction id namespace exhausted".into(),
6288 ));
6289 }
6290 return Ok(self.epoch.visible());
6291 }
6292 self.commit_new_epoch_inner(controlled)
6293 }
6294
6295 fn commit_new_epoch(&mut self) -> Result<Epoch> {
6299 self.commit_new_epoch_inner(None)
6300 }
6301
6302 fn commit_new_epoch_inner(
6303 &mut self,
6304 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6305 ) -> Result<Epoch> {
6306 self.ensure_writable()?;
6307 if self.is_shared() {
6308 self.commit_shared(controlled)
6309 } else {
6310 self.commit_private(controlled)
6311 }
6312 }
6313
6314 fn commit_private(
6316 &mut self,
6317 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6318 ) -> Result<Epoch> {
6319 let commit_lock = Arc::clone(&self.commit_lock);
6323 let _g = commit_lock.lock();
6324 let txn_id = self.ensure_txn_id()?;
6327 if let Some((control, before_commit)) = controlled {
6328 control.checkpoint()?;
6329 before_commit()?;
6330 }
6331 let new_epoch = self.epoch.bump_assigned();
6332 let epoch_authority = Arc::clone(&self.epoch);
6333 let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6334 let wal_result = match &mut self.wal {
6338 WalSink::Private(w) => w
6339 .append_txn(
6340 txn_id,
6341 Op::TxnCommit {
6342 epoch: new_epoch.0,
6343 added_runs: Vec::new(),
6344 },
6345 )
6346 .and_then(|_| w.sync()),
6347 WalSink::Shared(_) => unreachable!("commit_private on a shared sink"),
6348 WalSink::ReadOnly => Err(MongrelError::ReadOnlyReplica),
6349 };
6350 if let Err(error) = wal_result {
6351 self.durable_commit_failed = true;
6352 return Err(MongrelError::CommitOutcomeUnknown {
6353 epoch: new_epoch.0,
6354 message: error.to_string(),
6355 });
6356 }
6357 if let Some(epoch) = self.pending_truncate.take() {
6360 self.apply_truncate(epoch);
6361 }
6362 self.invalidate_pending_cache();
6363 let publish_result = self.persist_manifest(new_epoch);
6364 self.epoch.publish_in_order(new_epoch);
6368 epoch_guard.disarm();
6369 if let Err(error) = publish_result {
6370 self.durable_commit_failed = true;
6371 return Err(MongrelError::DurableCommit {
6372 epoch: new_epoch.0,
6373 message: error.to_string(),
6374 });
6375 }
6376 self.current_txn_id = txn_id.checked_add(1).unwrap_or(0);
6377 self.pending_private_mutations = false;
6378 self.data_generation = self.data_generation.wrapping_add(1);
6379 Ok(new_epoch)
6380 }
6381
6382 fn commit_shared(
6388 &mut self,
6389 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6390 ) -> Result<Epoch> {
6391 use std::sync::atomic::Ordering;
6392 let s = match &self.wal {
6393 WalSink::Shared(s) => s.clone(),
6394 WalSink::Private(_) => unreachable!("commit_shared on a private sink"),
6395 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6396 };
6397 if s.poisoned.load(Ordering::Relaxed) {
6398 return Err(MongrelError::Other(
6399 "database poisoned by fsync error".into(),
6400 ));
6401 }
6402 let commit_lock = Arc::clone(&self.commit_lock);
6409 let _g = commit_lock.lock();
6410 if !self.pending_rows.is_empty() {
6411 match controlled.as_ref() {
6412 Some((control, _)) => self.prepare_durable_publish_controlled(control)?,
6413 None => self.prepare_durable_publish()?,
6414 }
6415 }
6416 let txn_id = self.ensure_txn_id()?;
6419 let mut wal = s.wal.lock();
6420 if let Some((control, before_commit)) = controlled {
6421 control.checkpoint()?;
6422 before_commit()?;
6423 }
6424 let new_epoch = self.epoch.bump_assigned();
6425 let epoch_authority = Arc::clone(&self.epoch);
6426 let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6427 let commit_ts = s.hlc.now().map_err(|skew| {
6430 MongrelError::Other(format!(
6431 "clock skew rejected commit timestamp allocation: {skew}"
6432 ))
6433 })?;
6434 let commit_seq = match wal.append_commit_at(
6435 txn_id,
6436 new_epoch,
6437 &[],
6438 commit_ts.physical_micros.saturating_mul(1_000),
6439 ) {
6440 Ok(commit_seq) => commit_seq,
6441 Err(error) => {
6442 s.poisoned.store(true, Ordering::Relaxed);
6443 s.lifecycle.poison();
6444 return Err(MongrelError::CommitOutcomeUnknown {
6445 epoch: new_epoch.0,
6446 message: error.to_string(),
6447 });
6448 }
6449 };
6450 drop(wal);
6451 if let Err(error) = s.group.await_durable(&s.wal, commit_seq) {
6452 s.poisoned.store(true, Ordering::Relaxed);
6453 s.lifecycle.poison();
6454 return Err(MongrelError::CommitOutcomeUnknown {
6455 epoch: new_epoch.0,
6456 message: error.to_string(),
6457 });
6458 }
6459
6460 if self.pending_truncate.take().is_some() {
6463 self.apply_truncate(new_epoch);
6464 }
6465 let mut rows = std::mem::take(&mut self.pending_rows);
6466 if !rows.is_empty() {
6467 for r in &mut rows {
6468 r.committed_epoch = new_epoch;
6469 r.commit_ts = Some(commit_ts);
6470 }
6471 let auto_inc_flags = std::mem::take(&mut self.pending_rows_auto_inc);
6472 let all_auto_generated =
6473 auto_inc_flags.len() == rows.len() && auto_inc_flags.iter().all(|b| *b);
6474 self.apply_put_rows_inner_prepared(rows, !all_auto_generated);
6475 } else {
6476 self.pending_rows_auto_inc.clear();
6477 }
6478 let dels = std::mem::take(&mut self.pending_dels);
6479 for rid in dels {
6480 self.apply_delete_at(rid, new_epoch, Some(commit_ts));
6481 }
6482
6483 self.invalidate_pending_cache();
6484 let publish_result = self.persist_manifest(new_epoch);
6485 self.epoch.publish_in_order(new_epoch);
6486 epoch_guard.disarm();
6487 let _ = s.change_wake.send(());
6488 if let Err(error) = publish_result {
6489 self.durable_commit_failed = true;
6490 s.poisoned.store(true, Ordering::Relaxed);
6491 s.lifecycle.poison();
6492 return Err(MongrelError::DurableCommit {
6493 epoch: new_epoch.0,
6494 message: error.to_string(),
6495 });
6496 }
6497 self.current_txn_id = 0;
6499 self.data_generation = self.data_generation.wrapping_add(1);
6500 Ok(new_epoch)
6501 }
6502
6503 pub fn flush(&mut self) -> Result<Epoch> {
6511 self.flush_with_outcome().map(|(epoch, _)| epoch)
6512 }
6513
6514 pub fn flush_with_outcome(&mut self) -> Result<(Epoch, bool)> {
6516 self.flush_with_outcome_inner(None)
6517 }
6518
6519 #[doc(hidden)]
6522 pub fn flush_with_outcome_controlled<F>(
6523 &mut self,
6524 control: &crate::ExecutionControl,
6525 mut before_commit: F,
6526 ) -> Result<(Epoch, bool)>
6527 where
6528 F: FnMut() -> Result<()>,
6529 {
6530 self.flush_with_outcome_inner(Some((control, &mut before_commit)))
6531 }
6532
6533 fn flush_with_outcome_inner(
6534 &mut self,
6535 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6536 ) -> Result<(Epoch, bool)> {
6537 match controlled.as_ref() {
6538 Some((control, _)) => {
6539 self.ensure_indexes_complete_controlled(control, || true)?;
6540 }
6541 None => self.ensure_indexes_complete()?,
6542 }
6543 let committed = self.has_pending_mutations();
6544 let epoch = self.commit_inner(controlled)?;
6545 let finish: Result<(Epoch, bool)> = (|| {
6546 let rows = self.memtable.drain_sorted();
6547 if !rows.is_empty() {
6548 self.mutable_run.insert_many(rows);
6549 }
6550 if self.mutable_run.approx_bytes() >= self.mutable_run_spill_bytes {
6551 self.spill_mutable_run(epoch)?;
6552 self.mark_flushed(epoch)?;
6556 self.persist_manifest(epoch)?;
6557 self.build_learned_ranges()?;
6558 self.checkpoint_indexes(epoch);
6561 let _ = self.publish_run_lookup_directory();
6566 }
6567 Ok((epoch, committed))
6570 })();
6571 let outcome = match finish {
6572 Err(error) if committed => Err(MongrelError::DurableCommit {
6573 epoch: epoch.0,
6574 message: error.to_string(),
6575 }),
6576 result => result,
6577 };
6578 if outcome.is_ok() {
6579 let _ = self.publish_read_generation();
6585 }
6586 outcome
6587 }
6588
6589 pub(crate) fn has_pending_mutations(&self) -> bool {
6590 self.pending_private_mutations
6591 || !self.pending_rows.is_empty()
6592 || !self.pending_dels.is_empty()
6593 || self.pending_truncate.is_some()
6594 }
6595
6596 pub fn has_pending_writes(&self) -> bool {
6597 self.has_pending_mutations()
6598 }
6599
6600 pub fn force_flush(&mut self) -> Result<Epoch> {
6609 let saved = self.mutable_run_spill_bytes;
6610 self.mutable_run_spill_bytes = 1;
6611 let result = self.flush();
6612 self.mutable_run_spill_bytes = saved;
6613 result
6614 }
6615
6616 pub fn close(&mut self) -> Result<()> {
6623 if self.memtable_len() > 0 || self.mutable_run_len() > 0 {
6624 self.force_flush()?;
6625 }
6626 self.result_cache
6632 .lock()
6633 .shutdown_persistent_cache(std::time::Duration::from_secs(5));
6634 Ok(())
6635 }
6636
6637 pub(crate) fn wal_is_read_only(&self) -> bool {
6647 matches!(self.wal, WalSink::ReadOnly)
6648 }
6649
6650 pub(crate) fn drain_committed_memtable_rows(&mut self, epoch: Epoch) {
6656 if self.memtable_len() == 0 {
6657 return;
6658 }
6659 let rows = self.memtable.drain_sorted();
6660 let mut pending = Vec::new();
6661 let mut committed = Vec::new();
6662 for row in rows {
6663 if row.committed_epoch > epoch {
6664 pending.push(row);
6665 } else {
6666 committed.push(row);
6667 }
6668 }
6669 if !committed.is_empty() {
6670 self.mutable_run.insert_many(committed);
6671 }
6672 for row in pending {
6673 self.memtable.upsert(row);
6674 }
6675 }
6676
6677 pub(crate) fn mark_flushed(&mut self, epoch: Epoch) -> Result<()> {
6678 let op = Op::Flush {
6679 table_id: self.table_id,
6680 flushed_epoch: epoch.0,
6681 };
6682 match &mut self.wal {
6683 WalSink::Private(w) => {
6684 w.append_system(op)?;
6685 w.sync()?;
6686 }
6687 WalSink::Shared(s) => {
6688 s.wal.lock().append_system(op)?;
6693 }
6694 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6695 }
6696 self.flushed_epoch = epoch.0;
6697 if matches!(self.wal, WalSink::Private(_)) {
6698 self.rotate_wal(epoch)?;
6699 }
6700 Ok(())
6701 }
6702
6703 fn spill_mutable_run(&mut self, epoch: Epoch) -> Result<()> {
6707 if self.mutable_run.is_empty() {
6708 return Ok(());
6709 }
6710 let run_id = self.alloc_run_id()?;
6711 let rows = self.mutable_run.drain_sorted();
6712 if rows.is_empty() {
6713 return Ok(());
6714 }
6715 let path = self.run_path(run_id);
6716 let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
6717 if let Some(kek) = &self.kek {
6718 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6719 }
6720 let header = match self.create_run_file(run_id)? {
6721 Some(file) => writer.write_file(file, &rows)?,
6722 None => writer.write(&path, &rows)?,
6723 };
6724 self.run_refs.push(RunRef {
6725 run_id: run_id as u128,
6726 level: 0,
6727 epoch_created: epoch.0,
6728 row_count: header.row_count,
6729 });
6730 self.run_row_id_ranges
6731 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6732 Ok(())
6733 }
6734
6735 pub fn set_mutable_run_spill_bytes(&mut self, bytes: u64) {
6739 self.mutable_run_spill_bytes = bytes.max(1);
6740 }
6741
6742 pub fn set_compaction_zstd_level(&mut self, level: i32) {
6746 self.compaction_zstd_level = level;
6747 }
6748
6749 pub fn set_result_cache_max_bytes(&mut self, max_bytes: u64) {
6753 self.result_cache.lock().set_max_bytes(max_bytes);
6754 }
6755
6756 pub fn flush_persistent_cache(&self, deadline_ms: u64) -> u64 {
6761 self.result_cache
6762 .lock()
6763 .flush_persistent_cache(std::time::Duration::from_millis(deadline_ms))
6764 }
6765
6766 pub fn shutdown_persistent_cache(&mut self, deadline_ms: u64) {
6771 self.result_cache
6772 .lock()
6773 .shutdown_persistent_cache(std::time::Duration::from_millis(deadline_ms));
6774 }
6775
6776 #[doc(hidden)]
6781 pub fn _set_persist_min_bytes_for_test(&mut self, min: u64) {
6782 self.result_cache.lock().set_persist_min_bytes(min);
6783 }
6784
6785 #[doc(hidden)]
6792 pub fn _force_persistent_worker_spawn_failure_for_test(enabled: bool) {
6793 PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.set(enabled));
6794 }
6795
6796 #[doc(hidden)]
6803 pub fn _persist_cached_entry_synchronously_for_maintenance(
6804 &mut self,
6805 q: &crate::query::Query,
6806 ) -> bool {
6807 let key = crate::query::canonical_query_key(&q.conditions, None, 0)
6808 ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
6809 ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
6810 let identity = PersistentCacheIdentity {
6811 table_id: self.table_id(),
6812 schema_id: self.schema.schema_id,
6813 logical_generation: self.current_epoch().0,
6814 };
6815 let mut cache = self.result_cache.lock();
6816 let Some(entry) = cache.entries.get(&key).map(|e| e.clone_for_persist()) else {
6817 return false;
6818 };
6819 let entry_generation = cache.allocate_persist_generation(key);
6820 let context = PersistContext {
6821 identity,
6822 key,
6823 entry_generation,
6824 };
6825 cache.persist_entry_synchronously_for_maintenance(context, &entry);
6826 true
6827 }
6828
6829 pub(crate) fn clear_result_cache(&mut self) {
6833 self.result_cache.lock().clear();
6834 }
6835
6836 pub fn mutable_run_len(&self) -> usize {
6838 self.mutable_run.len()
6839 }
6840
6841 pub(crate) fn drain_mutable_run(&mut self) -> Vec<Row> {
6844 self.mutable_run.drain_sorted()
6845 }
6846
6847 pub(crate) fn snapshot_mutable_run(&self) -> Vec<Row> {
6849 let mut snapshot = self.mutable_run.clone();
6850 snapshot.drain_sorted()
6851 }
6852
6853 pub fn bulk_load(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Epoch> {
6858 self.ensure_writable()?;
6859 let n = batch.len();
6860 if n == 0 {
6861 return Ok(self.current_epoch());
6862 }
6863 for row in &batch {
6864 self.schema.validate_values(row)?;
6865 }
6866 let epoch = self.commit_new_epoch()?;
6867 let live_before = self.live_count;
6868 self.spill_mutable_run(epoch)?;
6872 let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
6873 && self.indexes_complete
6874 && self.run_refs.is_empty()
6875 && self.memtable.is_empty()
6876 && self.mutable_run.is_empty();
6877 let mut user_columns: Vec<(u16, columnar::NativeColumn)> = {
6883 use rayon::prelude::*;
6884 self.schema
6885 .columns
6886 .par_iter()
6887 .map(|cdef| {
6888 (
6889 cdef.id,
6890 columnar::rows_to_native(cdef.ty.clone(), &batch, cdef.id),
6891 )
6892 })
6893 .collect::<Vec<_>>()
6894 };
6895 drop(batch);
6896 self.fill_auto_inc_native_columns(&mut user_columns, n)?;
6901 self.validate_columns_not_null(&user_columns, n)?;
6902 let winner_idx = self
6903 .bulk_pk_winner_indices(&user_columns, n)
6904 .filter(|idx| idx.len() != n);
6905 let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
6906 match winner_idx.as_deref() {
6907 Some(idx) => {
6908 let compacted = user_columns
6909 .iter()
6910 .map(|(id, c)| (*id, c.gather(idx)))
6911 .collect();
6912 (compacted, idx.len())
6913 }
6914 None => (std::mem::take(&mut user_columns), n),
6915 };
6916 self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
6917 let first = self.allocator.alloc_range(write_n as u64)?.0;
6918 for rid in first..first + write_n as u64 {
6919 self.reservoir.offer(rid);
6920 }
6921 let run_id = self.alloc_run_id()?;
6922 let path = self.run_path(run_id);
6923 let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0)
6924 .clean(true)
6925 .with_lz4()
6926 .with_native_endian();
6927 if let Some(kek) = &self.kek {
6928 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6929 }
6930 let header = match self.create_run_file(run_id)? {
6931 Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
6932 None => writer.write_native(&path, &write_columns, write_n, first)?,
6933 };
6934 self.run_refs.push(RunRef {
6935 run_id: run_id as u128,
6936 level: 0,
6937 epoch_created: epoch.0,
6938 row_count: header.row_count,
6939 });
6940 self.run_row_id_ranges
6941 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6942 self.live_count = self.live_count.saturating_add(write_n as u64);
6943 if eager_index_build {
6944 let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
6945 self.index_columns_bulk(&write_columns, &row_ids);
6946 self.indexes_complete = true;
6947 self.build_learned_ranges()?;
6948 } else {
6949 self.indexes_complete = false;
6950 }
6951 self.mark_flushed(epoch)?;
6952 self.persist_manifest(epoch)?;
6953 if eager_index_build {
6954 self.checkpoint_indexes(epoch);
6955 }
6956 self.clear_result_cache();
6957 Ok(epoch)
6958 }
6959
6960 fn rotate_wal(&mut self, epoch: Epoch) -> Result<()> {
6963 let segment = next_wal_segment(&self.dir.join(WAL_DIR))?;
6964 let cipher = self.wal_dek.as_ref().map(|dk| make_cipher(dk));
6965 let segment_no = segment
6968 .file_stem()
6969 .and_then(|s| s.to_str())
6970 .and_then(|s| s.strip_prefix("seg-"))
6971 .and_then(|s| s.parse::<u64>().ok())
6972 .unwrap_or(0);
6973 let mut wal = Wal::create_with_cipher(segment, epoch, cipher, segment_no)?;
6974 wal.set_sync_byte_threshold(self.sync_byte_threshold);
6975 wal.sync()?;
6976 self.wal = WalSink::Private(wal);
6977 Ok(())
6978 }
6979
6980 pub(crate) fn invalidate_pending_cache(&mut self) {
6985 self.result_cache
6986 .lock()
6987 .invalidate(&self.pending_delete_rids, &self.pending_put_cols);
6988 self.pending_delete_rids.clear();
6989 self.pending_put_cols.clear();
6990 }
6991
6992 pub(crate) fn persist_manifest(&self, epoch: Epoch) -> Result<()> {
6993 let mut m = Manifest::new(self.table_id, self.schema.schema_id);
6994 m.current_epoch = epoch.0;
6995 m.next_row_id = self.allocator.current().0;
6996 m.runs = self.run_refs.clone();
6997 m.live_count = self.live_count;
6998 m.global_idx_epoch = self.global_idx_epoch;
6999 m.flushed_epoch = self.flushed_epoch;
7000 m.retiring = self.retiring.clone();
7001 m.auto_inc_next = match self.auto_inc {
7005 Some(ai) if ai.seeded => ai.next,
7006 _ => 0,
7007 };
7008 m.ttl = self.ttl;
7009 let meta_dek = self.manifest_meta_dek();
7010 match self._root_guard.as_deref() {
7011 Some(root) => manifest::write_durable(root, &mut m, meta_dek.as_ref())?,
7012 None => manifest::write_atomic(&self.dir, &mut m, meta_dek.as_ref())?,
7013 }
7014 Ok(())
7015 }
7016
7017 pub(crate) fn publish_run_lookup_directory(&mut self) -> Result<()> {
7024 mongreldb_fault::inject("manifest.publication")
7028 .map_err(|e| MongrelError::Other(format!("manifest.publication fault: {e}")))?;
7029 let active_runs = self.run_refs.clone();
7030 let schema_id = self.schema.schema_id;
7031 let index_generation = self.global_idx_epoch;
7032 let run_generation = active_runs.len() as u64;
7033 let fingerprint = crate::run_lookup::compute_fingerprint(
7034 &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
7035 schema_id,
7036 index_generation,
7037 run_generation,
7038 crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7039 );
7040 let dir = match crate::run_lookup::RunLookupDirectory::rebuild_from_runs(&active_runs, self)
7041 {
7042 Ok(d) => d,
7043 Err(error) => {
7044 self.run_lookup.complete = false;
7047 self.lookup_metrics
7048 .directory_incomplete
7049 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7050 return Err(error);
7051 }
7052 };
7053 let mut dir = dir;
7057 dir.set_fingerprint(fingerprint);
7058 let runs_dir = match self.runs_root.as_deref() {
7059 Some(root) => match root.io_path() {
7060 Ok(p) => p,
7061 Err(_) => self.dir.join(RUNS_DIR),
7062 },
7063 None => self.dir.join(RUNS_DIR),
7064 };
7065 mongreldb_fault::inject("directory.temp_write")
7068 .map_err(|e| MongrelError::Other(format!("directory.temp_write fault: {e}")))?;
7069 let publish =
7070 dir.write_checkpoint_sharded(&runs_dir, crate::run_lookup::DEFAULT_SHARD_BYTES);
7071 mongreldb_fault::inject("directory.sync")
7072 .map_err(|e| MongrelError::Other(format!("directory.sync fault: {e}")))?;
7073 mongreldb_fault::inject("directory.rename")
7074 .map_err(|e| MongrelError::Other(format!("directory.rename fault: {e}")))?;
7075 if let Err(error) = publish {
7076 self.run_lookup = RunLookupState {
7079 directory: None,
7080 fingerprint,
7081 complete: false,
7082 };
7083 self.lookup_metrics
7084 .directory_incomplete
7085 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7086 self.lookup_metrics
7087 .directory_lookup_fallback
7088 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7089 return Err(error.into());
7090 }
7091 self.run_lookup = RunLookupState {
7092 directory: Some(std::sync::Arc::new(dir)),
7093 fingerprint,
7094 complete: true,
7095 };
7096 Ok(())
7097 }
7098
7099 pub(crate) fn plan_recovered_metadata(&mut self) -> Result<RecoveryMetadataPlan> {
7100 let rows = self.visible_rows_at_time(Snapshot::unbounded(), i64::MIN)?;
7104 let live_count = u64::try_from(rows.len())
7105 .map_err(|_| MongrelError::Full("table live-row count exceeds u64".into()))?;
7106 let auto_inc = match self.auto_inc {
7107 Some(mut state) => {
7108 let maximum = self.scan_max_int64(state.column_id)?;
7109 let after_maximum = maximum.checked_add(1).ok_or_else(|| {
7110 MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
7111 })?;
7112 state.next = state.next.max(after_maximum).max(1);
7113 state.seeded = true;
7114 Some(state)
7115 }
7116 None => None,
7117 };
7118 Ok(RecoveryMetadataPlan {
7119 live_count,
7120 auto_inc,
7121 changed: live_count != self.live_count
7122 || auto_inc.is_some_and(|planned| {
7123 self.auto_inc.is_none_or(|current| {
7124 current.next != planned.next || current.seeded != planned.seeded
7125 })
7126 }),
7127 })
7128 }
7129
7130 pub(crate) fn apply_recovered_metadata(
7131 &mut self,
7132 plan: RecoveryMetadataPlan,
7133 epoch: Epoch,
7134 ) -> Result<()> {
7135 if !plan.changed {
7136 return Ok(());
7137 }
7138 self.live_count = plan.live_count;
7139 self.auto_inc = plan.auto_inc;
7140 self.persist_manifest(epoch)
7141 }
7142
7143 pub(crate) fn checkpoint_indexes(&mut self, epoch: Epoch) {
7149 if !self.indexes_complete {
7152 return;
7153 }
7154 if epoch.0 > self.flushed_epoch {
7162 return;
7163 }
7164 if crate::catalog::inject_hook("index.publish.before").is_err() {
7167 return;
7168 }
7169 if self.idx_root.is_none() {
7170 if let Some(root) = self._root_guard.as_ref() {
7171 let Ok(idx_root) = root.create_directory_all_pinned(global_idx::IDX_DIR) else {
7172 return;
7173 };
7174 self.idx_root = Some(Arc::new(idx_root));
7175 }
7176 }
7177 let snap = global_idx::IndexSnapshot {
7178 hot: &self.hot,
7179 bitmap: &self.bitmap,
7180 ann: &self.ann,
7181 fm: &self.fm,
7182 sparse: &self.sparse,
7183 minhash: &self.minhash,
7184 learned_range: &self.learned_range,
7185 };
7186 let idx_dek = self.idx_dek();
7188 let written = match self.idx_root.as_deref() {
7189 Some(root) => global_idx::write_atomic_root(
7190 root,
7191 self.table_id,
7192 epoch.0,
7193 snap,
7194 idx_dek.as_deref(),
7195 ),
7196 None => global_idx::write_atomic(
7197 &self.dir,
7198 self.table_id,
7199 epoch.0,
7200 snap,
7201 idx_dek.as_deref(),
7202 ),
7203 };
7204 if written.is_ok() {
7205 self.global_idx_epoch = epoch.0;
7206 let _ = self.persist_manifest(epoch);
7207 let _ = crate::catalog::inject_hook("index.publish.after");
7209 }
7210 }
7211
7212 pub(crate) fn invalidate_index_checkpoint(&mut self) {
7215 self.global_idx_epoch = 0;
7216 if let Some(root) = self.idx_root.as_deref() {
7217 let _ = root.remove_file(global_idx::IDX_FILENAME);
7218 } else {
7219 global_idx::remove(&self.dir);
7220 }
7221 let _ = self.persist_manifest(self.epoch.visible());
7222 }
7223
7224 pub(crate) fn prepare_indexes_for_run_replacement(&mut self) {
7229 self.indexes_complete = false;
7230 self.global_idx_epoch = 0;
7231 if let Some(root) = self.idx_root.as_deref() {
7232 let _ = root.remove_file(global_idx::IDX_FILENAME);
7233 } else {
7234 global_idx::remove(&self.dir);
7235 }
7236 }
7237
7238 pub(crate) fn finish_indexes_for_run_replacement(&mut self) {
7239 self.indexes_complete = true;
7240 }
7241
7242 pub(crate) fn poison_after_maintenance_publish_failure(&mut self) {
7248 self.durable_commit_failed = true;
7249 if let WalSink::Shared(shared) = &self.wal {
7250 shared
7251 .poisoned
7252 .store(true, std::sync::atomic::Ordering::Relaxed);
7253 }
7254 }
7255
7256 pub(crate) fn mark_unavailable_after_quarantine(&mut self) {
7260 self.durable_commit_failed = true;
7261 }
7262
7263 pub fn get(&self, row_id: RowId, snapshot: Snapshot) -> Option<Row> {
7288 let mut best: Option<Row> = None;
7289 fn consider(best: &mut Option<Row>, row: Row, snapshot: Snapshot) {
7292 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7293 return;
7294 }
7295 if best.as_ref().is_none_or(|current| {
7296 Snapshot::version_is_newer(
7297 row.committed_epoch,
7298 row.commit_ts,
7299 current.committed_epoch,
7300 current.commit_ts,
7301 )
7302 }) {
7303 *best = Some(row);
7304 }
7305 }
7306 if let Some((_, row)) = self.memtable.get_version_at(row_id, snapshot) {
7307 consider(&mut best, row, snapshot);
7308 }
7309 if let Some((_, row)) = self.mutable_run.get_version_at(row_id, snapshot) {
7310 consider(&mut best, row, snapshot);
7311 }
7312 let decision = if self.run_lookup.complete {
7316 let active_ids: Vec<u128> = self.run_refs.iter().map(|r| r.run_id).collect();
7321 let expected_fp = crate::run_lookup::compute_fingerprint(
7322 &active_ids,
7323 self.schema.schema_id,
7324 self.global_idx_epoch,
7325 active_ids.len() as u64,
7326 crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7327 );
7328 if self.run_lookup.fingerprint == expected_fp {
7329 match self.run_lookup.directory.as_ref() {
7330 Some(dir) => dir.decide(row_id),
7331 None => crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale,
7332 }
7333 } else {
7334 self.lookup_metrics
7335 .directory_lookup_fallback
7336 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7337 crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7338 }
7339 } else {
7340 self.lookup_metrics
7341 .directory_lookup_fallback
7342 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7343 crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7344 };
7345 match decision {
7346 crate::run_lookup::DirectoryLookupDecision::CompleteMiss => {
7347 self.lookup_metrics
7352 .directory_lookup_hit
7353 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7354 self.lookup_metrics
7355 .directory_complete_miss_total
7356 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7357 }
7358 crate::run_lookup::DirectoryLookupDecision::Candidates(mut locators) => {
7359 locators.sort_by(|a, b| {
7366 if snapshot.uses_hlc_authority() {
7367 b.max_hlc
7368 .cmp(&a.max_hlc)
7369 .then_with(|| b.max_epoch.cmp(&a.max_epoch))
7370 } else {
7371 b.max_epoch
7372 .cmp(&a.max_epoch)
7373 .then_with(|| b.max_hlc.cmp(&a.max_hlc))
7374 }
7375 });
7376 let mut opened: std::collections::HashSet<u128> = std::collections::HashSet::new();
7382 let mut early_stopped: u64 = 0;
7383 for locator in &locators {
7384 let stamp = best
7387 .as_ref()
7388 .map(|current| crate::run_lookup::VersionStamp {
7389 epoch: current.committed_epoch,
7390 hlc: current.commit_ts,
7391 });
7392 if let Some(s) = stamp {
7393 if !locator.can_contain_version_newer_than(s, snapshot) {
7394 early_stopped += 1;
7395 continue;
7396 }
7397 }
7398 if locator.is_impossible_for(snapshot) {
7399 continue;
7400 }
7401 if !opened.insert(locator.run_id) {
7402 continue;
7403 }
7404 self.lookup_metrics
7405 .directory_run_readers_opened
7406 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7407 self.lookup_metrics
7408 .get_run_opened
7409 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7410 let Ok(mut reader) = self.open_reader(locator.run_id) else {
7411 continue;
7412 };
7413 let Ok(Some((_, row))) = reader.get_version_at(row_id, snapshot) else {
7416 continue;
7417 };
7418 consider(&mut best, row, snapshot);
7419 }
7420 if early_stopped > 0 {
7421 self.lookup_metrics
7422 .directory_early_stop_total
7423 .fetch_add(early_stopped, std::sync::atomic::Ordering::Relaxed);
7424 }
7425 self.lookup_metrics
7426 .directory_lookup_hit
7427 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7428 }
7429 crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale => {
7430 for rr in &self.run_refs {
7432 if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
7436 if row_id.0 < min_rid || row_id.0 > max_rid {
7437 self.lookup_metrics
7438 .get_run_skipped
7439 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7440 continue;
7441 }
7442 }
7443 self.lookup_metrics
7444 .get_run_opened
7445 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7446 let Ok(mut reader) = self.open_reader(rr.run_id) else {
7447 continue;
7448 };
7449 let Ok(Some((_, row))) = reader.get_version_at(row_id, snapshot) else {
7452 continue;
7453 };
7454 consider(&mut best, row, snapshot);
7455 }
7456 }
7457 }
7458 let now_nanos = unix_nanos_now();
7459 match best {
7460 Some(r) if r.deleted || self.row_expired_at(&r, now_nanos) => None,
7461 Some(r) => Some(r),
7462 None => None,
7463 }
7464 }
7465
7466 pub fn visible_rows(&self, snapshot: Snapshot) -> Result<Vec<Row>> {
7470 self.visible_rows_at_time(snapshot, unix_nanos_now())
7471 }
7472
7473 #[doc(hidden)]
7476 pub fn visible_rows_controlled(
7477 &self,
7478 snapshot: Snapshot,
7479 control: &crate::ExecutionControl,
7480 ) -> Result<Vec<Row>> {
7481 let mut out = Vec::new();
7482 self.for_each_visible_row_controlled(snapshot, control, |row| {
7483 out.push(row);
7484 Ok(())
7485 })?;
7486 Ok(out)
7487 }
7488
7489 #[doc(hidden)]
7492 pub fn for_each_visible_row_controlled<F>(
7493 &self,
7494 snapshot: Snapshot,
7495 control: &crate::ExecutionControl,
7496 mut visit: F,
7497 ) -> Result<()>
7498 where
7499 F: FnMut(Row) -> Result<()>,
7500 {
7501 let setup_start = std::time::Instant::now();
7508 let mut versions_examined: u64 = 0;
7509 let mut rows_emitted: u64 = 0;
7510 let mut checkpoints: u64 = 0;
7511 let mut first_row_recorded = false;
7512 let mut sources: Vec<ControlledVisibleSource<'_>> =
7513 Vec::with_capacity(self.run_refs.len() + 2);
7514 control.checkpoint()?;
7515 checkpoints += 1;
7516 if !self.memtable.is_empty() {
7519 sources.push(ControlledVisibleSource::memtable_cursor(
7520 self.memtable.newest_visible_iter(&snapshot),
7521 ));
7522 }
7523 control.checkpoint()?;
7524 checkpoints += 1;
7525 if !self.mutable_run.is_empty() {
7526 sources.push(ControlledVisibleSource::mutable_run_cursor(
7527 self.mutable_run.newest_visible_iter(&snapshot),
7528 ));
7529 }
7530 for run in &self.run_refs {
7531 control.checkpoint()?;
7532 checkpoints += 1;
7533 let reader = self.open_reader(run.run_id)?;
7534 sources.push(ControlledVisibleSource::run(
7535 reader.into_visible_version_cursor_at(snapshot)?,
7536 ));
7537 }
7538 let first_row_start = setup_start;
7541 let _setup_us = setup_start.elapsed().as_micros() as u64;
7542 let now_nanos = unix_nanos_now();
7543 let mut first_row_us: u64 = 0;
7544 let result = merge_controlled_visible_sources(
7545 &mut sources,
7546 control,
7547 |row| self.row_expired_at(row, now_nanos),
7548 |row| {
7549 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7550 return Ok(());
7551 }
7552 versions_examined += 1;
7553 if !first_row_recorded {
7554 first_row_us = first_row_start.elapsed().as_micros() as u64;
7555 first_row_recorded = true;
7556 }
7557 rows_emitted += 1;
7558 visit(row)
7559 },
7560 );
7561 let time_to_first_row_us = if first_row_recorded { first_row_us } else { 0 };
7562 crate::trace::QueryTrace::record(|t| {
7563 t.controlled_scan_versions_examined = t
7564 .controlled_scan_versions_examined
7565 .saturating_add(versions_examined as usize);
7566 t.controlled_scan_rows_emitted = t
7567 .controlled_scan_rows_emitted
7568 .saturating_add(rows_emitted as usize);
7569 t.controlled_scan_checkpoints = t
7570 .controlled_scan_checkpoints
7571 .saturating_add(checkpoints as usize);
7572 t.controlled_scan_time_to_first_row_us = t
7573 .controlled_scan_time_to_first_row_us
7574 .saturating_add(time_to_first_row_us);
7575 t.controlled_scan_setup_time_us =
7576 t.controlled_scan_setup_time_us.saturating_add(_setup_us);
7577 });
7578 result
7579 }
7580
7581 #[doc(hidden)]
7582 pub fn visible_rows_at_time(&self, snapshot: Snapshot, now_nanos: i64) -> Result<Vec<Row>> {
7583 let mut best: HashMap<u64, Row> = HashMap::new();
7584 let mut fold = |row: Row| {
7585 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7586 return;
7587 }
7588 best.entry(row.row_id.0)
7589 .and_modify(|existing| {
7590 if Snapshot::version_is_newer(
7591 row.committed_epoch,
7592 row.commit_ts,
7593 existing.committed_epoch,
7594 existing.commit_ts,
7595 ) {
7596 *existing = row.clone();
7597 }
7598 })
7599 .or_insert(row);
7600 };
7601 for row in self.memtable.visible_versions_at(snapshot) {
7602 fold(row);
7603 }
7604 for row in self.mutable_run.visible_versions_at(snapshot) {
7605 fold(row);
7606 }
7607 for rr in &self.run_refs {
7608 let mut reader = self.open_reader(rr.run_id)?;
7609 for row in reader.visible_versions_at(snapshot)? {
7611 fold(row);
7612 }
7613 }
7614 let mut out: Vec<Row> = best
7615 .into_values()
7616 .filter_map(|r| {
7617 if r.deleted || self.row_expired_at(&r, now_nanos) {
7618 None
7619 } else {
7620 Some(r)
7621 }
7622 })
7623 .collect();
7624 out.sort_by_key(|r| r.row_id);
7625 Ok(out)
7626 }
7627
7628 pub fn visible_columns(&self, snapshot: Snapshot) -> Result<Vec<(u16, Vec<Value>)>> {
7635 if self.ttl.is_none()
7636 && self.memtable.is_empty()
7637 && self.mutable_run.is_empty()
7638 && self.run_refs.len() == 1
7639 {
7640 let rr = self.run_refs[0].clone();
7641 let mut reader = self.open_reader(rr.run_id)?;
7642 let idxs = reader.visible_indices_at(snapshot)?;
7643 let mut cols = Vec::with_capacity(self.schema.columns.len());
7644 for cdef in &self.schema.columns {
7645 cols.push((cdef.id, reader.gather_column(cdef.id, &idxs)?));
7646 }
7647 return Ok(cols);
7648 }
7649 let rows = self.visible_rows(snapshot)?;
7651 let mut cols: Vec<(u16, Vec<Value>)> = self
7652 .schema
7653 .columns
7654 .iter()
7655 .map(|c| (c.id, Vec::with_capacity(rows.len())))
7656 .collect();
7657 for r in &rows {
7658 for (cid, vec) in cols.iter_mut() {
7659 vec.push(r.columns.get(cid).cloned().unwrap_or(Value::Null));
7660 }
7661 }
7662 Ok(cols)
7663 }
7664
7665 pub fn lookup_pk(&self, key: &[u8]) -> Option<RowId> {
7667 let row_id = self.hot.get(key)?;
7668 if self.ttl.is_none() || self.get(row_id, Snapshot::unbounded()).is_some() {
7669 Some(row_id)
7670 } else {
7671 None
7672 }
7673 }
7674
7675 pub fn lookup_metrics_snapshot(&self) -> LookupMetricsSnapshot {
7679 let mut snap = self.lookup_metrics.snapshot();
7680 let cache = self.result_cache.lock();
7681 let (mem, disk, miss, write_us) = cache.cache_counters();
7682 snap.result_cache_memory_hit = mem;
7683 snap.result_cache_disk_hit = disk;
7684 snap.result_cache_miss = miss;
7685 snap.result_cache_persistent_write_us = write_us;
7686 let (unavailable, skipped, spawn_failures, worker_shutdowns) = cache.publication_counters();
7688 snap.result_cache_persist_unavailable_total = unavailable;
7689 snap.result_cache_persist_skipped_total = skipped;
7690 snap.result_cache_worker_spawn_failures_total = spawn_failures;
7691 snap.result_cache_worker_shutdown_total = worker_shutdowns;
7692 if let Some(writer_snap) = cache.persist_snapshot() {
7695 snap.result_cache_persist_enqueued_total =
7696 writer_snap.result_cache_persist_enqueued_total;
7697 snap.result_cache_persist_coalesced_total =
7698 writer_snap.result_cache_persist_coalesced_total;
7699 snap.result_cache_persist_dropped_store_total =
7700 writer_snap.result_cache_persist_dropped_store_total;
7701 snap.result_cache_persist_remove_total = writer_snap.result_cache_persist_remove_total;
7702 snap.result_cache_persist_stale_store_skipped_total =
7703 writer_snap.result_cache_persist_stale_store_skipped_total;
7704 snap.result_cache_persist_errors_total = writer_snap.result_cache_persist_errors_total;
7705 snap.result_cache_persist_shutdown_abandoned_total =
7706 writer_snap.result_cache_persist_shutdown_abandoned_total;
7707 snap.result_cache_persist_queue_depth = writer_snap.result_cache_persist_queue_depth;
7708 }
7709 snap
7710 }
7711
7712 pub fn query(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
7717 self.query_at_with_allowed(q, self.snapshot(), None)
7718 }
7719
7720 pub fn query_controlled(
7723 &mut self,
7724 q: &crate::query::Query,
7725 control: &crate::ExecutionControl,
7726 ) -> Result<Vec<Row>> {
7727 self.query_at_with_allowed_controlled(q, self.snapshot(), None, control)
7728 }
7729
7730 pub fn query_at_with_allowed(
7733 &mut self,
7734 q: &crate::query::Query,
7735 snapshot: Snapshot,
7736 allowed: Option<&std::collections::HashSet<RowId>>,
7737 ) -> Result<Vec<Row>> {
7738 self.query_at_with_allowed_after(q, snapshot, allowed, None)
7739 }
7740
7741 #[doc(hidden)]
7742 pub fn query_at_with_allowed_controlled(
7743 &mut self,
7744 q: &crate::query::Query,
7745 snapshot: Snapshot,
7746 allowed: Option<&std::collections::HashSet<RowId>>,
7747 control: &crate::ExecutionControl,
7748 ) -> Result<Vec<Row>> {
7749 self.require_select()?;
7750 self.ensure_indexes_complete_controlled(control, || true)?;
7751 self.validate_native_query(q)?;
7752 self.query_conditions_at(
7753 &q.conditions,
7754 snapshot,
7755 allowed,
7756 q.limit,
7757 q.offset,
7758 None,
7759 unix_nanos_now(),
7760 Some(control),
7761 )
7762 }
7763
7764 #[doc(hidden)]
7765 pub fn query_at_with_allowed_after(
7766 &mut self,
7767 q: &crate::query::Query,
7768 snapshot: Snapshot,
7769 allowed: Option<&std::collections::HashSet<RowId>>,
7770 after_row_id: Option<RowId>,
7771 ) -> Result<Vec<Row>> {
7772 self.query_at_with_allowed_after_at_time(
7773 q,
7774 snapshot,
7775 allowed,
7776 after_row_id,
7777 unix_nanos_now(),
7778 )
7779 }
7780
7781 #[doc(hidden)]
7782 pub fn query_at_with_allowed_after_at_time(
7783 &mut self,
7784 q: &crate::query::Query,
7785 snapshot: Snapshot,
7786 allowed: Option<&std::collections::HashSet<RowId>>,
7787 after_row_id: Option<RowId>,
7788 query_time_nanos: i64,
7789 ) -> Result<Vec<Row>> {
7790 self.require_select()?;
7791 self.ensure_indexes_complete()?;
7792 self.validate_native_query(q)?;
7793 self.query_conditions_at(
7794 &q.conditions,
7795 snapshot,
7796 allowed,
7797 q.limit,
7798 q.offset,
7799 after_row_id,
7800 query_time_nanos,
7801 None,
7802 )
7803 }
7804
7805 fn validate_native_query(&self, q: &crate::query::Query) -> Result<()> {
7806 if q.conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7807 return Err(MongrelError::InvalidArgument(format!(
7808 "query exceeds {} conditions",
7809 crate::query::MAX_HARD_CONDITIONS
7810 )));
7811 }
7812 if let Some(limit) = q.limit {
7813 if limit == 0 || limit > crate::query::MAX_FINAL_LIMIT {
7814 return Err(MongrelError::InvalidArgument(format!(
7815 "query limit must be between 1 and {}",
7816 crate::query::MAX_FINAL_LIMIT
7817 )));
7818 }
7819 }
7820 if q.offset > crate::query::MAX_QUERY_OFFSET {
7821 return Err(MongrelError::InvalidArgument(format!(
7822 "query offset exceeds {}",
7823 crate::query::MAX_QUERY_OFFSET
7824 )));
7825 }
7826 Ok(())
7827 }
7828
7829 #[doc(hidden)]
7832 pub fn query_all_at(
7833 &mut self,
7834 conditions: &[crate::query::Condition],
7835 snapshot: Snapshot,
7836 ) -> Result<Vec<Row>> {
7837 self.require_select()?;
7838 self.ensure_indexes_complete()?;
7839 if conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7840 return Err(MongrelError::InvalidArgument(format!(
7841 "query exceeds {} conditions",
7842 crate::query::MAX_HARD_CONDITIONS
7843 )));
7844 }
7845 self.query_conditions_at(
7846 conditions,
7847 snapshot,
7848 None,
7849 None,
7850 0,
7851 None,
7852 unix_nanos_now(),
7853 None,
7854 )
7855 }
7856
7857 #[allow(clippy::too_many_arguments)]
7858 fn query_conditions_at(
7859 &self,
7860 conditions: &[crate::query::Condition],
7861 snapshot: Snapshot,
7862 allowed: Option<&std::collections::HashSet<RowId>>,
7863 limit: Option<usize>,
7864 offset: usize,
7865 after_row_id: Option<RowId>,
7866 query_time_nanos: i64,
7867 control: Option<&crate::ExecutionControl>,
7868 ) -> Result<Vec<Row>> {
7869 control
7870 .map(crate::ExecutionControl::checkpoint)
7871 .transpose()?;
7872 crate::trace::QueryTrace::record(|t| {
7873 t.run_count = self.run_refs.len();
7874 t.memtable_rows = self.memtable.len();
7875 t.mutable_run_rows = self.mutable_run.len();
7876 });
7877 if conditions.is_empty() {
7881 crate::trace::QueryTrace::record(|t| {
7882 t.scan_mode = crate::trace::ScanMode::Materialized;
7883 t.row_materialized = true;
7884 });
7885 let mut rows = match control {
7886 Some(control) => self.visible_rows_controlled(snapshot, control)?,
7887 None => self.visible_rows_at_time(snapshot, query_time_nanos)?,
7888 };
7889 if let Some(allowed) = allowed {
7890 let mut filtered = Vec::with_capacity(rows.len());
7891 for (index, row) in rows.into_iter().enumerate() {
7892 if index & 255 == 0 {
7893 control
7894 .map(crate::ExecutionControl::checkpoint)
7895 .transpose()?;
7896 }
7897 if allowed.contains(&row.row_id) {
7898 filtered.push(row);
7899 }
7900 }
7901 rows = filtered;
7902 }
7903 if let Some(after_row_id) = after_row_id {
7904 rows.retain(|row| row.row_id > after_row_id);
7905 }
7906 rows.drain(..offset.min(rows.len()));
7907 if let Some(limit) = limit {
7908 rows.truncate(limit);
7909 }
7910 return Ok(rows);
7911 }
7912 crate::trace::QueryTrace::record(|t| {
7913 t.conditions_pushed = conditions.len();
7914 t.scan_mode = crate::trace::ScanMode::Materialized;
7915 t.row_materialized = true;
7916 });
7917 let mut ordered: Vec<&crate::query::Condition> = conditions.iter().collect();
7924 ordered.sort_by_key(|c| condition_cost_rank(c));
7925 let mut sets: Vec<RowIdSet> = Vec::with_capacity(ordered.len());
7926 for c in &ordered {
7927 control
7928 .map(crate::ExecutionControl::checkpoint)
7929 .transpose()?;
7930 let s = self.resolve_condition_with_allowed(c, snapshot, allowed)?;
7931 let empty = s.is_empty();
7932 sets.push(s);
7933 if empty {
7934 break;
7935 }
7936 }
7937 let mut rids = RowIdSet::intersect_many(sets).into_sorted_vec();
7938 if let Some(allowed) = allowed {
7939 rids.retain(|row_id| allowed.contains(&RowId(*row_id)));
7940 }
7941 if let Some(after_row_id) = after_row_id {
7942 let first = rids.partition_point(|row_id| *row_id <= after_row_id.0);
7943 rids.drain(..first);
7944 }
7945 rids.drain(..offset.min(rids.len()));
7946 if let Some(limit) = limit {
7947 rids.truncate(limit);
7948 }
7949 control
7950 .map(crate::ExecutionControl::checkpoint)
7951 .transpose()?;
7952 self.rows_for_rids_at_time(&rids, snapshot, query_time_nanos, control)
7953 }
7954
7955 pub fn retrieve(
7957 &mut self,
7958 retriever: &crate::query::Retriever,
7959 ) -> Result<Vec<crate::query::RetrieverHit>> {
7960 self.retrieve_with_allowed(retriever, None)
7961 }
7962
7963 pub fn retrieve_at(
7964 &mut self,
7965 retriever: &crate::query::Retriever,
7966 snapshot: Snapshot,
7967 allowed: Option<&std::collections::HashSet<RowId>>,
7968 ) -> Result<Vec<crate::query::RetrieverHit>> {
7969 self.retrieve_at_with_allowed(retriever, snapshot, allowed)
7970 }
7971
7972 pub fn retrieve_with_allowed(
7975 &mut self,
7976 retriever: &crate::query::Retriever,
7977 allowed: Option<&std::collections::HashSet<RowId>>,
7978 ) -> Result<Vec<crate::query::RetrieverHit>> {
7979 self.retrieve_at_with_allowed(retriever, self.snapshot(), allowed)
7980 }
7981
7982 pub fn retrieve_at_with_allowed(
7983 &mut self,
7984 retriever: &crate::query::Retriever,
7985 snapshot: Snapshot,
7986 allowed: Option<&std::collections::HashSet<RowId>>,
7987 ) -> Result<Vec<crate::query::RetrieverHit>> {
7988 self.retrieve_at_with_allowed_and_context(retriever, snapshot, allowed, None)
7989 }
7990
7991 pub fn retrieve_at_with_allowed_and_context(
7992 &mut self,
7993 retriever: &crate::query::Retriever,
7994 snapshot: Snapshot,
7995 allowed: Option<&std::collections::HashSet<RowId>>,
7996 context: Option<&crate::query::AiExecutionContext>,
7997 ) -> Result<Vec<crate::query::RetrieverHit>> {
7998 self.require_select()?;
7999 self.ensure_indexes_complete()?;
8000 self.validate_retriever(retriever)?;
8001 self.retrieve_filtered(retriever, snapshot, None, allowed, None, context)
8002 }
8003
8004 pub fn retrieve_at_with_candidate_authorization_and_context(
8005 &mut self,
8006 retriever: &crate::query::Retriever,
8007 snapshot: Snapshot,
8008 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8009 context: Option<&crate::query::AiExecutionContext>,
8010 ) -> Result<Vec<crate::query::RetrieverHit>> {
8011 self.require_select()?;
8012 self.ensure_indexes_complete()?;
8013 self.retrieve_at_with_candidate_authorization_on_generation(
8014 retriever,
8015 snapshot,
8016 authorization,
8017 context,
8018 )
8019 }
8020
8021 #[doc(hidden)]
8022 pub fn retrieve_at_with_candidate_authorization_on_generation(
8023 &self,
8024 retriever: &crate::query::Retriever,
8025 snapshot: Snapshot,
8026 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8027 context: Option<&crate::query::AiExecutionContext>,
8028 ) -> Result<Vec<crate::query::RetrieverHit>> {
8029 self.require_select()?;
8030 self.validate_retriever(retriever)?;
8031 self.retrieve_filtered(retriever, snapshot, None, None, authorization, context)
8032 }
8033
8034 fn validate_retriever(&self, retriever: &crate::query::Retriever) -> Result<()> {
8035 use crate::query::{Retriever, MAX_RETRIEVER_K, MAX_SET_MEMBERS, MAX_SPARSE_TERMS};
8036 let (column_id, k) = match retriever {
8037 Retriever::Ann {
8038 column_id,
8039 query,
8040 k,
8041 } => {
8042 let index = self.ann.get(column_id).ok_or_else(|| {
8043 MongrelError::InvalidArgument(format!("column {column_id} has no ANN index"))
8044 })?;
8045 if query.len() != index.dim() {
8046 return Err(MongrelError::InvalidArgument(format!(
8047 "ANN query dimension must be {}, got {}",
8048 index.dim(),
8049 query.len()
8050 )));
8051 }
8052 if query.iter().any(|value| !value.is_finite()) {
8053 return Err(MongrelError::InvalidArgument(
8054 "ANN query values must be finite".into(),
8055 ));
8056 }
8057 (*column_id, *k)
8058 }
8059 Retriever::Sparse {
8060 column_id,
8061 query,
8062 k,
8063 } => {
8064 if !self.sparse.contains_key(column_id) {
8065 return Err(MongrelError::InvalidArgument(format!(
8066 "column {column_id} has no Sparse index"
8067 )));
8068 }
8069 if query.is_empty() || query.iter().any(|(_, weight)| !weight.is_finite()) {
8070 return Err(MongrelError::InvalidArgument(
8071 "Sparse query must be non-empty with finite weights".into(),
8072 ));
8073 }
8074 if query.len() > MAX_SPARSE_TERMS {
8075 return Err(MongrelError::InvalidArgument(format!(
8076 "Sparse query exceeds {MAX_SPARSE_TERMS} terms"
8077 )));
8078 }
8079 (*column_id, *k)
8080 }
8081 Retriever::MinHash {
8082 column_id,
8083 members,
8084 k,
8085 } => {
8086 if !self.minhash.contains_key(column_id) {
8087 return Err(MongrelError::InvalidArgument(format!(
8088 "column {column_id} has no MinHash index"
8089 )));
8090 }
8091 if members.is_empty() {
8092 return Err(MongrelError::InvalidArgument(
8093 "MinHash members must not be empty".into(),
8094 ));
8095 }
8096 if members.len() > MAX_SET_MEMBERS {
8097 return Err(MongrelError::InvalidArgument(format!(
8098 "MinHash query exceeds {MAX_SET_MEMBERS} members"
8099 )));
8100 }
8101 let mut total_bytes = 0usize;
8102 for member in members {
8103 let bytes = member.encoded_len();
8104 if bytes > crate::query::MAX_SET_MEMBER_BYTES {
8105 return Err(MongrelError::InvalidArgument(format!(
8106 "MinHash member exceeds {} bytes",
8107 crate::query::MAX_SET_MEMBER_BYTES
8108 )));
8109 }
8110 total_bytes = total_bytes.checked_add(bytes).ok_or_else(|| {
8111 MongrelError::InvalidArgument("MinHash input size overflow".into())
8112 })?;
8113 }
8114 if total_bytes > crate::query::MAX_SET_INPUT_BYTES {
8115 return Err(MongrelError::InvalidArgument(format!(
8116 "MinHash input exceeds {} bytes",
8117 crate::query::MAX_SET_INPUT_BYTES
8118 )));
8119 }
8120 (*column_id, *k)
8121 }
8122 };
8123 if k == 0 {
8124 return Err(MongrelError::InvalidArgument(
8125 "retriever k must be > 0".into(),
8126 ));
8127 }
8128 if k > MAX_RETRIEVER_K {
8129 return Err(MongrelError::InvalidArgument(format!(
8130 "retriever k exceeds {MAX_RETRIEVER_K}"
8131 )));
8132 }
8133 debug_assert!(self
8134 .schema
8135 .columns
8136 .iter()
8137 .any(|column| column.id == column_id));
8138 Ok(())
8139 }
8140
8141 fn validate_condition(&self, condition: &crate::query::Condition) -> Result<()> {
8142 use crate::query::Condition;
8143 match condition {
8144 Condition::Ann {
8145 column_id,
8146 query,
8147 k,
8148 } => self.validate_retriever(&crate::query::Retriever::Ann {
8149 column_id: *column_id,
8150 query: query.clone(),
8151 k: *k,
8152 }),
8153 Condition::SparseMatch {
8154 column_id,
8155 query,
8156 k,
8157 } => self.validate_retriever(&crate::query::Retriever::Sparse {
8158 column_id: *column_id,
8159 query: query.clone(),
8160 k: *k,
8161 }),
8162 Condition::MinHashSimilar {
8163 column_id,
8164 query,
8165 k,
8166 } => {
8167 if !self.minhash.contains_key(column_id) {
8168 return Err(MongrelError::InvalidArgument(format!(
8169 "column {column_id} has no MinHash index"
8170 )));
8171 }
8172 if query.is_empty() || *k == 0 {
8173 return Err(MongrelError::InvalidArgument(
8174 "MinHash query must be non-empty and k must be > 0".into(),
8175 ));
8176 }
8177 if query.len() > crate::query::MAX_SET_MEMBERS || *k > crate::query::MAX_RETRIEVER_K
8178 {
8179 return Err(MongrelError::InvalidArgument(format!(
8180 "MinHash query must have <= {} members and k <= {}",
8181 crate::query::MAX_SET_MEMBERS,
8182 crate::query::MAX_RETRIEVER_K
8183 )));
8184 }
8185 Ok(())
8186 }
8187 Condition::BitmapIn { values, .. } if values.len() > crate::query::MAX_SET_MEMBERS => {
8188 Err(MongrelError::InvalidArgument(format!(
8189 "bitmap IN exceeds {} values",
8190 crate::query::MAX_SET_MEMBERS
8191 )))
8192 }
8193 Condition::FmContainsAll { patterns, .. }
8194 if patterns.len() > crate::query::MAX_HARD_CONDITIONS =>
8195 {
8196 Err(MongrelError::InvalidArgument(format!(
8197 "FM query exceeds {} patterns",
8198 crate::query::MAX_HARD_CONDITIONS
8199 )))
8200 }
8201 _ => Ok(()),
8202 }
8203 }
8204
8205 fn retrieve_filtered(
8206 &self,
8207 retriever: &crate::query::Retriever,
8208 snapshot: Snapshot,
8209 hard_filter: Option<&RowIdSet>,
8210 allowed: Option<&std::collections::HashSet<RowId>>,
8211 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8212 context: Option<&crate::query::AiExecutionContext>,
8213 ) -> Result<Vec<crate::query::RetrieverHit>> {
8214 use crate::query::{Retriever, RetrieverHit, RetrieverScore};
8215 let started = std::time::Instant::now();
8216 let scored: Vec<(RowId, RetrieverScore)> = match retriever {
8217 Retriever::Ann {
8218 column_id,
8219 query,
8220 k,
8221 } => {
8222 let Some(index) = self.ann.get(column_id) else {
8223 return Ok(Vec::new());
8224 };
8225 let cap = ann_candidate_cap(index.len(), context);
8226 crate::trace::QueryTrace::record(|trace| trace.candidate_cap = cap);
8227 if cap == 0 {
8228 return Ok(Vec::new());
8229 }
8230 let mut breadth = (*k).max(1).min(cap);
8231 let mut eligibility = std::collections::HashMap::new();
8232 let mut raw_candidates_total: usize = 0;
8237 let mut visibility_rejected_total: usize = 0;
8238 let mut authorization_rejected_total: usize = 0;
8239 let mut candidate_cap_hit_final = false;
8240 let mut filtered = loop {
8241 let mut seen = std::collections::HashSet::new();
8242 if let Some(context) = context {
8243 context.checkpoint()?;
8244 }
8245 let raw = index.search_with_context(query, breadth, context)?;
8246 crate::trace::QueryTrace::record(|trace| {
8247 trace.raw_candidates = raw.len();
8248 let unique = raw
8249 .iter()
8250 .map(|(row_id, _)| *row_id)
8251 .collect::<std::collections::HashSet<_>>()
8252 .len();
8253 trace.unique_candidates = unique;
8254 trace.duplicate_candidates = raw.len().saturating_sub(unique);
8255 trace.authorization_rejected = raw
8256 .iter()
8257 .filter(|(row_id, _)| {
8258 allowed.is_some_and(|allowed| !allowed.contains(row_id))
8259 })
8260 .count();
8261 trace.hard_filter_rejected = raw
8262 .iter()
8263 .filter(|(row_id, _)| {
8264 hard_filter.is_some_and(|filter| !filter.contains(row_id.0))
8265 })
8266 .count();
8267 });
8268 raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8269 let unchecked: Vec<_> = raw
8270 .iter()
8271 .map(|(row_id, _)| *row_id)
8272 .filter(|row_id| !eligibility.contains_key(row_id))
8273 .filter(|row_id| {
8274 hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8275 && allowed.is_none_or(|allowed| allowed.contains(row_id))
8276 })
8277 .collect();
8278 let eligible = self.eligible_and_authorized_candidate_ids(
8279 &unchecked,
8280 *column_id,
8281 snapshot,
8282 candidate_authorization,
8283 context,
8284 )?;
8285 for row_id in &unchecked {
8286 eligibility.insert(*row_id, eligible.contains(row_id));
8287 }
8288 let new_visibility_or_auth_rejected = unchecked
8291 .iter()
8292 .filter(|row_id| !eligible.contains(row_id))
8293 .count();
8294 let mut new_auth_rejected = 0usize;
8299 if let Some(authorization) = candidate_authorization {
8300 if authorization.security.rls_enabled(authorization.table)
8301 && !authorization.principal.is_admin
8302 {
8303 new_auth_rejected = new_visibility_or_auth_rejected;
8309 }
8310 }
8311 let new_visibility_rejected =
8312 new_visibility_or_auth_rejected.saturating_sub(new_auth_rejected);
8313 visibility_rejected_total =
8314 visibility_rejected_total.saturating_add(new_visibility_rejected);
8315 authorization_rejected_total =
8316 authorization_rejected_total.saturating_add(new_auth_rejected);
8317 let filtered: Vec<_> = raw
8318 .into_iter()
8319 .filter(|(row_id, _)| {
8320 seen.insert(*row_id)
8321 && eligibility.get(row_id).copied().unwrap_or(false)
8322 })
8323 .map(|(row_id, score)| {
8324 let score = match score {
8325 crate::index::AnnDistance::Hamming(d) => {
8326 RetrieverScore::AnnHammingDistance(d)
8327 }
8328 crate::index::AnnDistance::Cosine(d) => {
8329 RetrieverScore::AnnCosineDistance(d)
8330 }
8331 };
8332 (row_id, score)
8333 })
8334 .collect();
8335 if filtered.len() >= *k || breadth >= cap {
8336 if filtered.len() < *k && index.len() > cap && breadth >= cap {
8337 crate::trace::QueryTrace::record(|trace| {
8338 trace.ann_candidate_cap_hit = true;
8339 trace.candidate_cap_hit = true;
8340 });
8341 candidate_cap_hit_final = true;
8342 }
8343 break filtered;
8344 }
8345 breadth = breadth.saturating_mul(2).min(cap);
8346 };
8347 let final_hits = filtered.len();
8350 let index_len = index.len();
8351 crate::trace::QueryTrace::record(|trace| {
8352 trace.candidate_cap = cap;
8353 trace.candidate_cap_hit = candidate_cap_hit_final;
8354 trace.ann_candidate_cap_hit = candidate_cap_hit_final;
8355 trace.raw_candidates =
8356 trace.raw_candidates.saturating_add(raw_candidates_total);
8357 trace.visibility_rejected = trace
8358 .visibility_rejected
8359 .saturating_add(visibility_rejected_total);
8360 trace.authorization_rejected = trace
8361 .authorization_rejected
8362 .saturating_add(authorization_rejected_total);
8363 trace.final_hits = trace.final_hits.saturating_add(final_hits);
8364 let _ = index_len;
8367 });
8368 filtered.truncate(*k);
8369 filtered
8370 }
8371 Retriever::Sparse {
8372 column_id,
8373 query,
8374 k,
8375 } => self
8376 .sparse
8377 .get(column_id)
8378 .map(|index| -> Result<Vec<_>> {
8379 let mut breadth = (*k).max(1);
8380 let mut eligibility = std::collections::HashMap::new();
8381 let mut raw_candidates_total: usize = 0;
8384 let mut visibility_rejected_total: usize = 0;
8385 let mut authorization_rejected_total: usize = 0;
8386 let filtered = loop {
8387 if let Some(context) = context {
8388 context.checkpoint()?;
8389 }
8390 let raw = index.search_with_context(query, breadth, context)?;
8391 raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8392 authorization_rejected_total = authorization_rejected_total.saturating_add(
8393 raw.iter()
8394 .filter(|(row_id, _)| {
8395 allowed.is_some_and(|allowed| !allowed.contains(row_id))
8396 })
8397 .count(),
8398 );
8399 let unchecked: Vec<_> = raw
8400 .iter()
8401 .map(|(row_id, _)| *row_id)
8402 .filter(|row_id| !eligibility.contains_key(row_id))
8403 .filter(|row_id| {
8404 hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8405 && allowed.is_none_or(|allowed| allowed.contains(row_id))
8406 })
8407 .collect();
8408 let eligible = self.eligible_and_authorized_candidate_ids(
8409 &unchecked,
8410 *column_id,
8411 snapshot,
8412 candidate_authorization,
8413 context,
8414 )?;
8415 visibility_rejected_total = visibility_rejected_total.saturating_add(
8416 unchecked
8417 .iter()
8418 .filter(|row_id| !eligible.contains(row_id))
8419 .count(),
8420 );
8421 for row_id in unchecked {
8422 eligibility.insert(row_id, eligible.contains(&row_id));
8423 }
8424 let filtered: Vec<_> = raw
8425 .iter()
8426 .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8427 .take(*k)
8428 .map(|(row_id, score)| {
8429 (*row_id, RetrieverScore::SparseDotProduct(*score))
8430 })
8431 .collect();
8432 if filtered.len() >= *k || raw.len() < breadth {
8433 break filtered;
8434 }
8435 let next = breadth.saturating_mul(2);
8436 if next == breadth {
8437 break filtered;
8438 }
8439 breadth = next;
8440 };
8441 crate::trace::QueryTrace::record(|trace| {
8442 trace.raw_candidates =
8443 trace.raw_candidates.saturating_add(raw_candidates_total);
8444 trace.visibility_rejected = trace
8445 .visibility_rejected
8446 .saturating_add(visibility_rejected_total);
8447 trace.authorization_rejected = trace
8448 .authorization_rejected
8449 .saturating_add(authorization_rejected_total);
8450 });
8451 Ok(filtered)
8452 })
8453 .transpose()?
8454 .unwrap_or_default(),
8455 Retriever::MinHash {
8456 column_id,
8457 members,
8458 k,
8459 } => self
8460 .minhash
8461 .get(column_id)
8462 .map(|index| -> Result<Vec<_>> {
8463 let mut hashes = Vec::with_capacity(members.len());
8464 for member in members {
8465 if let Some(context) = context {
8466 context.consume(crate::query::work_units(
8467 member.encoded_len(),
8468 crate::query::PARSE_WORK_QUANTUM,
8469 ))?;
8470 }
8471 hashes.push(member.hash_v1());
8472 }
8473 let mut breadth = (*k).max(1);
8474 let mut eligibility = std::collections::HashMap::new();
8475 let mut raw_candidates_total: usize = 0;
8476 let mut visibility_rejected_total: usize = 0;
8477 let mut authorization_rejected_total: usize = 0;
8478 let filtered = loop {
8479 if let Some(context) = context {
8480 context.checkpoint()?;
8481 }
8482 let raw = index.search_with_context(&hashes, breadth, context)?;
8483 raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8484 authorization_rejected_total = authorization_rejected_total.saturating_add(
8485 raw.iter()
8486 .filter(|(row_id, _)| {
8487 allowed.is_some_and(|allowed| !allowed.contains(row_id))
8488 })
8489 .count(),
8490 );
8491 let unchecked: Vec<_> = raw
8492 .iter()
8493 .map(|(row_id, _)| *row_id)
8494 .filter(|row_id| !eligibility.contains_key(row_id))
8495 .filter(|row_id| {
8496 hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8497 && allowed.is_none_or(|allowed| allowed.contains(row_id))
8498 })
8499 .collect();
8500 let eligible = self.eligible_and_authorized_candidate_ids(
8501 &unchecked,
8502 *column_id,
8503 snapshot,
8504 candidate_authorization,
8505 context,
8506 )?;
8507 visibility_rejected_total = visibility_rejected_total.saturating_add(
8508 unchecked
8509 .iter()
8510 .filter(|row_id| !eligible.contains(row_id))
8511 .count(),
8512 );
8513 for row_id in unchecked {
8514 eligibility.insert(row_id, eligible.contains(&row_id));
8515 }
8516 let filtered: Vec<_> = raw
8517 .iter()
8518 .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8519 .take(*k)
8520 .map(|(row_id, score)| {
8521 (*row_id, RetrieverScore::MinHashEstimatedJaccard(*score))
8522 })
8523 .collect();
8524 if filtered.len() >= *k || raw.len() < breadth {
8525 break filtered;
8526 }
8527 let next = breadth.saturating_mul(2);
8528 if next == breadth {
8529 break filtered;
8530 }
8531 breadth = next;
8532 };
8533 crate::trace::QueryTrace::record(|trace| {
8534 trace.raw_candidates =
8535 trace.raw_candidates.saturating_add(raw_candidates_total);
8536 trace.visibility_rejected = trace
8537 .visibility_rejected
8538 .saturating_add(visibility_rejected_total);
8539 trace.authorization_rejected = trace
8540 .authorization_rejected
8541 .saturating_add(authorization_rejected_total);
8542 });
8543 Ok(filtered)
8544 })
8545 .transpose()?
8546 .unwrap_or_default(),
8547 };
8548 let requested_k = match retriever {
8549 Retriever::Ann { k, .. }
8550 | Retriever::Sparse { k, .. }
8551 | Retriever::MinHash { k, .. } => *k,
8552 };
8553 crate::trace::QueryTrace::record(|trace| {
8554 trace.final_hits = scored.len();
8555 if scored.len() < requested_k {
8556 trace.underfill_reason = Some(if trace.candidate_cap_hit {
8557 "candidate_cap"
8558 } else {
8559 "eligible_candidates_exhausted"
8560 });
8561 }
8562 });
8563 let elapsed = started.elapsed().as_nanos() as u64;
8564 crate::trace::QueryTrace::record(|trace| {
8565 match retriever {
8566 Retriever::Ann { .. } => {
8567 trace.ann_candidate_nanos = trace.ann_candidate_nanos.saturating_add(elapsed);
8568 if let Retriever::Ann { column_id, .. } = retriever {
8569 if let Some(index) = self.ann.get(column_id) {
8570 trace.ann_algorithm = Some(index.algorithm());
8571 trace.ann_quantization = Some(index.quantization());
8572 trace.ann_backend = Some(index.backend_name());
8573 }
8574 }
8575 }
8576 Retriever::Sparse { .. } => {
8577 trace.sparse_candidate_nanos =
8578 trace.sparse_candidate_nanos.saturating_add(elapsed)
8579 }
8580 Retriever::MinHash { .. } => {
8581 trace.minhash_candidate_nanos =
8582 trace.minhash_candidate_nanos.saturating_add(elapsed)
8583 }
8584 }
8585 trace.candidate_count = trace.candidate_count.saturating_add(scored.len());
8586 });
8587 Ok(scored
8588 .into_iter()
8589 .enumerate()
8590 .map(|(rank, (row_id, score))| RetrieverHit {
8591 row_id,
8592 rank: rank + 1,
8593 score,
8594 })
8595 .collect())
8596 }
8597
8598 fn eligible_candidate_ids(
8599 &self,
8600 candidates: &[RowId],
8601 _column_id: u16,
8602 snapshot: Snapshot,
8603 context: Option<&crate::query::AiExecutionContext>,
8604 ) -> Result<std::collections::HashSet<RowId>> {
8605 let lookup_snapshot = snapshot;
8617 let mut readers: Vec<_> = self
8618 .run_refs
8619 .iter()
8620 .map(|run| self.open_reader(run.run_id))
8621 .collect::<Result<_>>()?;
8622 let now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8623 let mut eligible = std::collections::HashSet::with_capacity(candidates.len());
8624 for &row_id in candidates {
8625 if let Some(context) = context {
8626 context.consume(1)?;
8627 }
8628 let mem = self.memtable.get_version_at(row_id, lookup_snapshot);
8629 let mutable = self.mutable_run.get_version_at(row_id, lookup_snapshot);
8630 let overlay = match (mem, mutable) {
8631 (Some(left), Some(right)) => Some(
8632 if Snapshot::version_is_newer(
8633 left.1.committed_epoch,
8634 left.1.commit_ts,
8635 right.1.committed_epoch,
8636 right.1.commit_ts,
8637 ) {
8638 left
8639 } else {
8640 right
8641 },
8642 ),
8643 (Some(value), None) | (None, Some(value)) => Some(value),
8644 (None, None) => None,
8645 };
8646 if let Some((_, row)) = overlay {
8647 if !row.deleted && !self.row_expired_at(&row, now) {
8648 eligible.insert(row_id);
8649 }
8650 continue;
8651 }
8652 let mut best: Option<(crate::sorted_run::VersionVisibility, usize)> = None;
8658 for (index, reader) in readers.iter_mut().enumerate() {
8659 if let Some(visibility) =
8660 reader.get_version_visibility_full_at(row_id, lookup_snapshot)?
8661 {
8662 if best
8663 .as_ref()
8664 .map(|(current, _)| visibility.stamp.is_newer_than(current.stamp))
8665 .unwrap_or(true)
8666 {
8667 best = Some((visibility, index));
8668 }
8669 }
8670 }
8671 let Some((visibility, reader_index)) = best else {
8672 continue;
8673 };
8674 if visibility.deleted {
8675 continue;
8676 }
8677 if let Some(ttl) = self.ttl {
8678 if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
8679 row_id,
8680 lookup_snapshot,
8681 ttl.column_id,
8682 )? {
8683 if let Some(Value::Int64(timestamp)) = ttl_value.value {
8684 if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
8685 continue;
8686 }
8687 }
8688 }
8689 }
8690 eligible.insert(row_id);
8691 }
8692 Ok(eligible)
8693 }
8694
8695 fn eligible_and_authorized_candidate_ids(
8696 &self,
8697 candidates: &[RowId],
8698 column_id: u16,
8699 snapshot: Snapshot,
8700 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8701 context: Option<&crate::query::AiExecutionContext>,
8702 ) -> Result<std::collections::HashSet<RowId>> {
8703 let eligible = self.eligible_candidate_ids(candidates, column_id, snapshot, context)?;
8704 let Some(authorization) = authorization else {
8705 return Ok(eligible);
8706 };
8707 let candidates: Vec<_> = eligible.into_iter().collect();
8708 self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, context)
8709 }
8710
8711 fn policy_allowed_candidate_ids(
8712 &self,
8713 candidates: &[RowId],
8714 snapshot: Snapshot,
8715 authorization: &crate::security::CandidateAuthorization<'_>,
8716 context: Option<&crate::query::AiExecutionContext>,
8717 ) -> Result<std::collections::HashSet<RowId>> {
8718 let started = std::time::Instant::now();
8719 if candidates.is_empty()
8720 || authorization.principal.is_admin
8721 || !authorization.security.rls_enabled(authorization.table)
8722 {
8723 return Ok(candidates.iter().copied().collect());
8724 }
8725 if let Some(context) = context {
8726 context.checkpoint()?;
8727 }
8728 let row_ids: Vec<_> = candidates.iter().map(|row_id| row_id.0).collect();
8729 let mut rows: std::collections::HashMap<RowId, Row> = candidates
8730 .iter()
8731 .map(|row_id| {
8732 (
8733 *row_id,
8734 Row {
8735 row_id: *row_id,
8736 committed_epoch: snapshot.epoch,
8737 columns: std::collections::HashMap::new(),
8738 deleted: false,
8739 commit_ts: None,
8740 },
8741 )
8742 })
8743 .collect();
8744 let columns = authorization
8745 .security
8746 .select_policy_columns(authorization.table, authorization.principal);
8747 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8748 let mut decoded = 0usize;
8749 for column_id in &columns {
8750 if let Some(context) = context {
8751 context.checkpoint()?;
8752 }
8753 for (row_id, value) in self.values_for_rids_batch_at_with_context(
8754 &row_ids, *column_id, snapshot, query_now, context,
8755 )? {
8756 if let Some(row) = rows.get_mut(&row_id) {
8757 row.columns.insert(*column_id, value);
8758 decoded = decoded.saturating_add(1);
8759 }
8760 }
8761 }
8762 if let Some(context) = context {
8763 context.consume(candidates.len().saturating_add(decoded))?;
8764 }
8765 let allowed = rows
8766 .into_values()
8767 .filter_map(|row| {
8768 authorization
8769 .security
8770 .row_allowed(
8771 authorization.table,
8772 crate::security::PolicyCommand::Select,
8773 &row,
8774 authorization.principal,
8775 false,
8776 )
8777 .then_some(row.row_id)
8778 })
8779 .collect();
8780 crate::trace::QueryTrace::record(|trace| {
8781 trace.rls_rows_evaluated = trace.rls_rows_evaluated.saturating_add(candidates.len());
8782 trace.rls_policy_columns_decoded =
8783 trace.rls_policy_columns_decoded.saturating_add(decoded);
8784 trace.authorization_nanos = trace
8785 .authorization_nanos
8786 .saturating_add(started.elapsed().as_nanos() as u64);
8787 });
8788 Ok(allowed)
8789 }
8790
8791 pub fn search(
8793 &mut self,
8794 request: &crate::query::SearchRequest,
8795 ) -> Result<Vec<crate::query::SearchHit>> {
8796 self.search_with_allowed(request, None)
8797 }
8798
8799 pub fn search_at(
8800 &mut self,
8801 request: &crate::query::SearchRequest,
8802 snapshot: Snapshot,
8803 authorized: Option<&std::collections::HashSet<RowId>>,
8804 ) -> Result<Vec<crate::query::SearchHit>> {
8805 self.search_at_with_allowed(request, snapshot, authorized)
8806 }
8807
8808 pub fn search_with_allowed(
8809 &mut self,
8810 request: &crate::query::SearchRequest,
8811 authorized: Option<&std::collections::HashSet<RowId>>,
8812 ) -> Result<Vec<crate::query::SearchHit>> {
8813 self.search_at_with_allowed(request, self.snapshot(), authorized)
8814 }
8815
8816 pub fn search_at_with_allowed(
8817 &mut self,
8818 request: &crate::query::SearchRequest,
8819 snapshot: Snapshot,
8820 authorized: Option<&std::collections::HashSet<RowId>>,
8821 ) -> Result<Vec<crate::query::SearchHit>> {
8822 self.search_at_with_allowed_and_context(request, snapshot, authorized, None)
8823 }
8824
8825 pub fn search_at_with_allowed_and_context(
8826 &mut self,
8827 request: &crate::query::SearchRequest,
8828 snapshot: Snapshot,
8829 authorized: Option<&std::collections::HashSet<RowId>>,
8830 context: Option<&crate::query::AiExecutionContext>,
8831 ) -> Result<Vec<crate::query::SearchHit>> {
8832 self.ensure_indexes_complete()?;
8833 self.search_at_with_filters_and_context(request, snapshot, authorized, None, context, None)
8834 }
8835
8836 pub fn search_at_with_candidate_authorization_and_context(
8837 &mut self,
8838 request: &crate::query::SearchRequest,
8839 snapshot: Snapshot,
8840 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8841 context: Option<&crate::query::AiExecutionContext>,
8842 ) -> Result<Vec<crate::query::SearchHit>> {
8843 self.ensure_indexes_complete()?;
8844 self.search_at_with_filters_and_context(
8845 request,
8846 snapshot,
8847 None,
8848 authorization,
8849 context,
8850 None,
8851 )
8852 }
8853
8854 #[doc(hidden)]
8855 pub fn search_at_with_candidate_authorization_on_generation(
8856 &self,
8857 request: &crate::query::SearchRequest,
8858 snapshot: Snapshot,
8859 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8860 context: Option<&crate::query::AiExecutionContext>,
8861 ) -> Result<Vec<crate::query::SearchHit>> {
8862 self.search_at_with_filters_and_context(
8863 request,
8864 snapshot,
8865 None,
8866 authorization,
8867 context,
8868 None,
8869 )
8870 }
8871
8872 #[doc(hidden)]
8873 pub fn search_at_with_candidate_authorization_on_generation_after(
8874 &self,
8875 request: &crate::query::SearchRequest,
8876 snapshot: Snapshot,
8877 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8878 context: Option<&crate::query::AiExecutionContext>,
8879 after: Option<crate::query::SearchAfter>,
8880 ) -> Result<Vec<crate::query::SearchHit>> {
8881 self.search_at_with_filters_and_context(
8882 request,
8883 snapshot,
8884 None,
8885 authorization,
8886 context,
8887 after,
8888 )
8889 }
8890
8891 fn search_at_with_filters_and_context(
8892 &self,
8893 request: &crate::query::SearchRequest,
8894 snapshot: Snapshot,
8895 authorized: Option<&std::collections::HashSet<RowId>>,
8896 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8897 context: Option<&crate::query::AiExecutionContext>,
8898 after: Option<crate::query::SearchAfter>,
8899 ) -> Result<Vec<crate::query::SearchHit>> {
8900 use crate::query::{
8901 ComponentScore, Condition, Fusion, SearchHit, MAX_FINAL_LIMIT, MAX_HARD_CONDITIONS,
8902 MAX_PROJECTION_COLUMNS, MAX_RETRIEVERS, MAX_RETRIEVER_WEIGHT,
8903 };
8904 let total_started = std::time::Instant::now();
8905 let rank_offset = after.map_or(0, |after| after.returned_count);
8906 self.require_select()?;
8907 if request.limit == 0 {
8908 return Err(MongrelError::InvalidArgument(
8909 "search limit must be > 0".into(),
8910 ));
8911 }
8912 if request.limit > MAX_FINAL_LIMIT {
8913 return Err(MongrelError::InvalidArgument(format!(
8914 "search limit exceeds {MAX_FINAL_LIMIT}"
8915 )));
8916 }
8917 if after.is_some_and(|cursor| !cursor.final_score.is_finite()) {
8918 return Err(MongrelError::InvalidArgument(
8919 "search-after score must be finite".into(),
8920 ));
8921 }
8922 if request.retrievers.is_empty() {
8923 return Err(MongrelError::InvalidArgument(
8924 "search requires at least one retriever".into(),
8925 ));
8926 }
8927 if request.retrievers.len() > MAX_RETRIEVERS {
8928 return Err(MongrelError::InvalidArgument(format!(
8929 "search exceeds {MAX_RETRIEVERS} retrievers"
8930 )));
8931 }
8932 if request.must.len() > MAX_HARD_CONDITIONS {
8933 return Err(MongrelError::InvalidArgument(format!(
8934 "search exceeds {MAX_HARD_CONDITIONS} hard conditions"
8935 )));
8936 }
8937 for condition in &request.must {
8938 self.validate_condition(condition)?;
8939 }
8940 if request.must.iter().any(|condition| {
8941 matches!(
8942 condition,
8943 Condition::Ann { .. }
8944 | Condition::SparseMatch { .. }
8945 | Condition::MinHashSimilar { .. }
8946 )
8947 }) {
8948 return Err(MongrelError::InvalidArgument(
8949 "ranked ANN, Sparse, and MinHash conditions must be retrievers, not must filters"
8950 .into(),
8951 ));
8952 }
8953 let mut names = std::collections::HashSet::new();
8954 for named in &request.retrievers {
8955 if named.name.is_empty()
8956 || named.name.len() > crate::query::MAX_RETRIEVER_NAME_BYTES
8957 || !names.insert(named.name.as_str())
8958 {
8959 return Err(MongrelError::InvalidArgument(format!(
8960 "retriever names must be non-empty, unique, and at most {} UTF-8 bytes",
8961 crate::query::MAX_RETRIEVER_NAME_BYTES
8962 )));
8963 }
8964 if !named.weight.is_finite()
8965 || named.weight < 0.0
8966 || named.weight > MAX_RETRIEVER_WEIGHT
8967 {
8968 return Err(MongrelError::InvalidArgument(format!(
8969 "retriever weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
8970 )));
8971 }
8972 self.validate_retriever(&named.retriever)?;
8973 }
8974 let projection = request
8975 .projection
8976 .clone()
8977 .unwrap_or_else(|| self.schema.columns.iter().map(|column| column.id).collect());
8978 if projection.len() > MAX_PROJECTION_COLUMNS {
8979 return Err(MongrelError::InvalidArgument(format!(
8980 "projection exceeds {MAX_PROJECTION_COLUMNS} columns"
8981 )));
8982 }
8983 for column_id in &projection {
8984 if !self
8985 .schema
8986 .columns
8987 .iter()
8988 .any(|column| column.id == *column_id)
8989 {
8990 return Err(MongrelError::ColumnNotFound(column_id.to_string()));
8991 }
8992 }
8993 if let Some(crate::query::Rerank::ExactVector {
8994 embedding_column,
8995 query,
8996 candidate_limit,
8997 weight,
8998 ..
8999 }) = &request.rerank
9000 {
9001 if *candidate_limit < request.limit || *candidate_limit > crate::query::MAX_RETRIEVER_K
9002 {
9003 return Err(MongrelError::InvalidArgument(format!(
9004 "rerank candidate_limit must be between search limit and {}",
9005 crate::query::MAX_RETRIEVER_K
9006 )));
9007 }
9008 if !weight.is_finite() || *weight < 0.0 || *weight > MAX_RETRIEVER_WEIGHT {
9009 return Err(MongrelError::InvalidArgument(format!(
9010 "rerank weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
9011 )));
9012 }
9013 let column = self
9014 .schema
9015 .columns
9016 .iter()
9017 .find(|column| column.id == *embedding_column)
9018 .ok_or_else(|| MongrelError::ColumnNotFound(embedding_column.to_string()))?;
9019 let crate::schema::TypeId::Embedding { dim } = column.ty else {
9020 return Err(MongrelError::InvalidArgument(format!(
9021 "rerank column {embedding_column} is not an embedding"
9022 )));
9023 };
9024 if query.len() != dim as usize || query.iter().any(|value| !value.is_finite()) {
9025 return Err(MongrelError::InvalidArgument(format!(
9026 "rerank query must contain {dim} finite values"
9027 )));
9028 }
9029 }
9030
9031 let hard_filter_started = std::time::Instant::now();
9032 let hard_filter = if request.must.is_empty() {
9033 None
9034 } else {
9035 let mut sets = Vec::with_capacity(request.must.len());
9036 for condition in &request.must {
9037 if let Some(context) = context {
9038 context.checkpoint()?;
9039 }
9040 sets.push(self.resolve_condition(condition, snapshot)?);
9041 }
9042 Some(RowIdSet::intersect_many(sets))
9043 };
9044 crate::trace::QueryTrace::record(|trace| {
9045 trace.hard_filter_nanos = trace
9046 .hard_filter_nanos
9047 .saturating_add(hard_filter_started.elapsed().as_nanos() as u64);
9048 });
9049 if hard_filter.as_ref().is_some_and(RowIdSet::is_empty) {
9050 return Ok(Vec::new());
9051 }
9052
9053 let constant = match request.fusion {
9054 Fusion::ReciprocalRank { constant } => constant,
9055 };
9056 let mut retrievers: Vec<_> = request.retrievers.iter().collect();
9057 retrievers.sort_by(|a, b| a.name.cmp(&b.name));
9058 let mut fusion_nanos = 0u64;
9059 let mut fused: std::collections::HashMap<RowId, (f64, Vec<ComponentScore>)> =
9060 std::collections::HashMap::new();
9061 for named in retrievers {
9062 if named.weight == 0.0 {
9063 continue;
9064 }
9065 if let Some(context) = context {
9066 context.checkpoint()?;
9067 }
9068 let hits = self.retrieve_filtered(
9069 &named.retriever,
9070 snapshot,
9071 hard_filter.as_ref(),
9072 authorized,
9073 candidate_authorization,
9074 context,
9075 )?;
9076 let retriever_name: std::sync::Arc<str> = named.name.as_str().into();
9077 let fusion_started = std::time::Instant::now();
9078 for hit in hits {
9079 if let Some(context) = context {
9080 context.consume(1)?;
9081 }
9082 let contribution = named.weight / (constant as f64 + hit.rank as f64);
9083 if !contribution.is_finite() {
9084 return Err(MongrelError::InvalidArgument(
9085 "retriever contribution must be finite".into(),
9086 ));
9087 }
9088 let max_fused_candidates = context.map_or(
9089 crate::query::MAX_FUSED_CANDIDATES,
9090 crate::query::AiExecutionContext::max_fused_candidates,
9091 );
9092 if !fused.contains_key(&hit.row_id) && fused.len() >= max_fused_candidates {
9093 return Err(MongrelError::WorkBudgetExceeded);
9094 }
9095 let entry = fused.entry(hit.row_id).or_default();
9096 entry.0 += contribution;
9097 if !entry.0.is_finite() {
9098 return Err(MongrelError::InvalidArgument(
9099 "fused score must be finite".into(),
9100 ));
9101 }
9102 entry.1.push(ComponentScore {
9103 retriever_name: retriever_name.clone(),
9104 rank: hit.rank,
9105 raw_score: hit.score,
9106 contribution,
9107 });
9108 }
9109 fusion_nanos = fusion_nanos.saturating_add(fusion_started.elapsed().as_nanos() as u64);
9110 }
9111 let union_size = fused.len();
9112 let mut ranked: Vec<_> = fused
9113 .into_iter()
9114 .map(|(row_id, (fused_score, components))| {
9115 (row_id, fused_score, components, None, fused_score)
9116 })
9117 .collect();
9118 let order = |(a_row, _, _, _, a_score): &(
9119 RowId,
9120 f64,
9121 Vec<ComponentScore>,
9122 Option<f32>,
9123 f64,
9124 ),
9125 (b_row, _, _, _, b_score): &(
9126 RowId,
9127 f64,
9128 Vec<ComponentScore>,
9129 Option<f32>,
9130 f64,
9131 )| { b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row)) };
9132 if let Some(crate::query::Rerank::ExactVector {
9133 embedding_column,
9134 query,
9135 metric,
9136 candidate_limit,
9137 weight,
9138 }) = &request.rerank
9139 {
9140 let fused_order = |(a_row, a_score, ..): &(
9141 RowId,
9142 f64,
9143 Vec<ComponentScore>,
9144 Option<f32>,
9145 f64,
9146 ),
9147 (b_row, b_score, ..): &(
9148 RowId,
9149 f64,
9150 Vec<ComponentScore>,
9151 Option<f32>,
9152 f64,
9153 )| {
9154 b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row))
9155 };
9156 let selection_started = std::time::Instant::now();
9157 if let Some(context) = context {
9158 context.consume(ranked.len())?;
9159 }
9160 if ranked.len() > *candidate_limit {
9161 let (_, _, _) = ranked.select_nth_unstable_by(*candidate_limit, fused_order);
9162 ranked.truncate(*candidate_limit);
9163 }
9164 ranked.sort_by(fused_order);
9165 fusion_nanos =
9166 fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9167 let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9168 if let Some(context) = context {
9169 context.consume(row_ids.len())?;
9170 }
9171 let query_now =
9172 context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9173 let gather_started = std::time::Instant::now();
9174 let vectors = self.values_for_rids_batch_at_with_context(
9175 &row_ids,
9176 *embedding_column,
9177 snapshot,
9178 query_now,
9179 context,
9180 )?;
9181 let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9182 let vector_work =
9183 crate::query::work_units(query.len(), crate::query::VECTOR_WORK_QUANTUM);
9184 let query_norm = if matches!(metric, crate::query::VectorMetric::Cosine) {
9185 if let Some(context) = context {
9186 context.consume(vector_work)?;
9187 }
9188 query
9189 .iter()
9190 .map(|value| f64::from(*value).powi(2))
9191 .sum::<f64>()
9192 .sqrt()
9193 } else {
9194 0.0
9195 };
9196 let score_started = std::time::Instant::now();
9197 let mut scores = std::collections::HashMap::with_capacity(vectors.len());
9198 for (row_id, value) in vectors {
9199 if let Some(meta) = value.generated_embedding_metadata() {
9200 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9201 continue;
9202 }
9203 }
9204 let Some(vector) = value.as_embedding() else {
9205 continue;
9206 };
9207 let score = match metric {
9208 crate::query::VectorMetric::DotProduct => {
9209 if let Some(context) = context {
9210 context.consume(vector_work)?;
9211 }
9212 query
9213 .iter()
9214 .zip(vector)
9215 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9216 .sum::<f64>()
9217 }
9218 crate::query::VectorMetric::Cosine => {
9219 if let Some(context) = context {
9220 context.consume(vector_work.saturating_mul(2))?;
9221 }
9222 let dot = query
9223 .iter()
9224 .zip(vector)
9225 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9226 .sum::<f64>();
9227 let norm = vector
9228 .iter()
9229 .map(|value| f64::from(*value).powi(2))
9230 .sum::<f64>()
9231 .sqrt();
9232 if query_norm == 0.0 || norm == 0.0 {
9233 0.0
9234 } else {
9235 dot / (query_norm * norm)
9236 }
9237 }
9238 crate::query::VectorMetric::Euclidean => {
9239 if let Some(context) = context {
9240 context.consume(vector_work)?;
9241 }
9242 query
9243 .iter()
9244 .zip(vector)
9245 .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9246 .sum::<f64>()
9247 .sqrt()
9248 }
9249 };
9250 if !score.is_finite() {
9251 return Err(MongrelError::InvalidArgument(
9252 "exact rerank score must be finite".into(),
9253 ));
9254 }
9255 scores.insert(row_id, score as f32);
9256 }
9257 let mut reranked = Vec::with_capacity(ranked.len());
9258 for (row_id, fused_score, components, _, _) in ranked.drain(..) {
9259 let Some(score) = scores.get(&row_id).copied() else {
9260 continue;
9261 };
9262 let ordering_score = match metric {
9263 crate::query::VectorMetric::Euclidean => -f64::from(score),
9264 crate::query::VectorMetric::Cosine | crate::query::VectorMetric::DotProduct => {
9265 f64::from(score)
9266 }
9267 };
9268 let final_score = fused_score + *weight * ordering_score;
9269 if !final_score.is_finite() {
9270 return Err(MongrelError::InvalidArgument(
9271 "final rerank score must be finite".into(),
9272 ));
9273 }
9274 reranked.push((row_id, fused_score, components, Some(score), final_score));
9275 }
9276 ranked = reranked;
9277 ranked.sort_by(order);
9278 crate::trace::QueryTrace::record(|trace| {
9279 trace.exact_vector_gather_nanos =
9280 trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9281 trace.exact_vector_score_nanos = trace
9282 .exact_vector_score_nanos
9283 .saturating_add(score_started.elapsed().as_nanos() as u64);
9284 });
9285 }
9286 if let Some(after) = after {
9287 ranked.retain(|(row_id, _, _, _, final_score)| {
9288 final_score.total_cmp(&after.final_score).is_lt()
9289 || (final_score.total_cmp(&after.final_score).is_eq() && *row_id > after.row_id)
9290 });
9291 }
9292 let projection_started = std::time::Instant::now();
9293 let sentinel = projection
9294 .first()
9295 .copied()
9296 .or_else(|| self.schema.columns.first().map(|column| column.id));
9297 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9298 let mut out = Vec::with_capacity(request.limit.min(ranked.len()));
9299 let mut projection_rows = 0usize;
9300 let mut projection_cells = 0usize;
9301 while out.len() < request.limit && !ranked.is_empty() {
9302 if let Some(context) = context {
9303 context.checkpoint()?;
9304 context.consume(ranked.len())?;
9305 }
9306 let needed = request.limit - out.len();
9307 let window_size = ranked
9308 .len()
9309 .min(needed.saturating_mul(2).max(needed.saturating_add(8)));
9310 let selection_started = std::time::Instant::now();
9311 let mut remainder = if ranked.len() > window_size {
9312 let (_, _, _) = ranked.select_nth_unstable_by(window_size, order);
9313 ranked.split_off(window_size)
9314 } else {
9315 Vec::new()
9316 };
9317 ranked.sort_by(order);
9318 fusion_nanos =
9319 fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9320 let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9321 let gathered_columns = projection.len().max(usize::from(sentinel.is_some()));
9322 if let Some(context) = context {
9323 context.consume(row_ids.len().saturating_mul(gathered_columns))?;
9324 }
9325 projection_rows = projection_rows.saturating_add(row_ids.len());
9326 projection_cells =
9327 projection_cells.saturating_add(row_ids.len().saturating_mul(gathered_columns));
9328 let mut cells: std::collections::HashMap<RowId, std::collections::HashMap<u16, Value>> =
9329 std::collections::HashMap::new();
9330 if let Some(column_id) = sentinel {
9331 for (row_id, value) in self.values_for_rids_batch_at_with_context(
9332 &row_ids, column_id, snapshot, query_now, context,
9333 )? {
9334 cells.entry(row_id).or_default().insert(column_id, value);
9335 }
9336 }
9337 for &column_id in &projection {
9338 if Some(column_id) == sentinel {
9339 continue;
9340 }
9341 for (row_id, value) in self.values_for_rids_batch_at_with_context(
9342 &row_ids, column_id, snapshot, query_now, context,
9343 )? {
9344 cells.entry(row_id).or_default().insert(column_id, value);
9345 }
9346 }
9347 for (row_id, fused_score, mut components, exact_rerank_score, final_score) in
9348 ranked.drain(..)
9349 {
9350 let Some(row_cells) = cells.remove(&row_id) else {
9351 continue;
9352 };
9353 components.sort_by(|a, b| a.retriever_name.cmp(&b.retriever_name));
9354 let final_rank = rank_offset.saturating_add(out.len()).saturating_add(1);
9355 out.push(SearchHit {
9356 row_id,
9357 cells: projection
9358 .iter()
9359 .filter_map(|column_id| {
9360 row_cells
9361 .get(column_id)
9362 .cloned()
9363 .map(|value| (*column_id, value))
9364 })
9365 .collect(),
9366 components,
9367 fused_score,
9368 exact_rerank_score,
9369 final_score,
9370 final_rank,
9371 });
9372 if out.len() == request.limit {
9373 break;
9374 }
9375 }
9376 ranked.append(&mut remainder);
9377 }
9378 crate::trace::QueryTrace::record(|trace| {
9379 trace.union_size = union_size;
9380 trace.fusion_nanos = trace.fusion_nanos.saturating_add(fusion_nanos);
9381 trace.projection_nanos = trace
9382 .projection_nanos
9383 .saturating_add(projection_started.elapsed().as_nanos() as u64);
9384 trace.total_nanos = trace
9385 .total_nanos
9386 .saturating_add(total_started.elapsed().as_nanos() as u64);
9387 trace.projection_rows = trace.projection_rows.saturating_add(projection_rows);
9388 trace.projection_cells = trace.projection_cells.saturating_add(projection_cells);
9389 if let Some(context) = context {
9390 trace.work_consumed = trace.work_consumed.saturating_add(context.consumed_work());
9391 }
9392 });
9393 Ok(out)
9394 }
9395
9396 pub fn set_similarity(
9399 &mut self,
9400 request: &crate::query::SetSimilarityRequest,
9401 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9402 self.set_similarity_with_allowed(request, None)
9403 }
9404
9405 pub fn set_similarity_at(
9406 &mut self,
9407 request: &crate::query::SetSimilarityRequest,
9408 snapshot: Snapshot,
9409 allowed: Option<&std::collections::HashSet<RowId>>,
9410 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9411 self.set_similarity_explained_at(request, snapshot, allowed)
9412 .map(|(hits, _)| hits)
9413 }
9414
9415 pub fn ann_rerank(
9417 &mut self,
9418 request: &crate::query::AnnRerankRequest,
9419 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9420 self.ann_rerank_with_allowed(request, None)
9421 }
9422
9423 pub fn ann_rerank_with_allowed(
9424 &mut self,
9425 request: &crate::query::AnnRerankRequest,
9426 allowed: Option<&std::collections::HashSet<RowId>>,
9427 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9428 self.ann_rerank_at(request, self.snapshot(), allowed)
9429 }
9430
9431 pub fn ann_rerank_at(
9432 &mut self,
9433 request: &crate::query::AnnRerankRequest,
9434 snapshot: Snapshot,
9435 allowed: Option<&std::collections::HashSet<RowId>>,
9436 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9437 self.ann_rerank_at_with_context(request, snapshot, allowed, None)
9438 }
9439
9440 pub fn ann_rerank_at_with_context(
9441 &mut self,
9442 request: &crate::query::AnnRerankRequest,
9443 snapshot: Snapshot,
9444 allowed: Option<&std::collections::HashSet<RowId>>,
9445 context: Option<&crate::query::AiExecutionContext>,
9446 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9447 self.ensure_indexes_complete()?;
9448 self.ann_rerank_at_with_filters_and_context(request, snapshot, allowed, None, context)
9449 }
9450
9451 pub fn ann_rerank_at_with_candidate_authorization_and_context(
9452 &mut self,
9453 request: &crate::query::AnnRerankRequest,
9454 snapshot: Snapshot,
9455 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9456 context: Option<&crate::query::AiExecutionContext>,
9457 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9458 self.ensure_indexes_complete()?;
9459 self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9460 }
9461
9462 #[doc(hidden)]
9463 pub fn ann_rerank_at_with_candidate_authorization_on_generation(
9464 &self,
9465 request: &crate::query::AnnRerankRequest,
9466 snapshot: Snapshot,
9467 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9468 context: Option<&crate::query::AiExecutionContext>,
9469 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9470 self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9471 }
9472
9473 fn ann_rerank_at_with_filters_and_context(
9474 &self,
9475 request: &crate::query::AnnRerankRequest,
9476 snapshot: Snapshot,
9477 allowed: Option<&std::collections::HashSet<RowId>>,
9478 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9479 context: Option<&crate::query::AiExecutionContext>,
9480 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9481 use crate::query::{
9482 AnnCandidateDistance, AnnRerankHit, Retriever, RetrieverScore, VectorMetric,
9483 MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9484 };
9485 if request.candidate_k == 0 || request.limit == 0 {
9486 return Err(MongrelError::InvalidArgument(
9487 "candidate_k and limit must be > 0".into(),
9488 ));
9489 }
9490 if request.candidate_k > MAX_RETRIEVER_K || request.limit > MAX_FINAL_LIMIT {
9491 return Err(MongrelError::InvalidArgument(format!(
9492 "candidate_k must be <= {MAX_RETRIEVER_K} and limit <= {MAX_FINAL_LIMIT}"
9493 )));
9494 }
9495 let retriever = Retriever::Ann {
9496 column_id: request.column_id,
9497 query: request.query.clone(),
9498 k: request.candidate_k,
9499 };
9500 self.require_select()?;
9501 self.validate_retriever(&retriever)?;
9502 let hits = self.retrieve_filtered(
9503 &retriever,
9504 snapshot,
9505 None,
9506 allowed,
9507 candidate_authorization,
9508 context,
9509 )?;
9510 let distances: std::collections::HashMap<_, _> = hits
9511 .iter()
9512 .filter_map(|hit| match hit.score {
9513 RetrieverScore::AnnHammingDistance(distance) => {
9514 Some((hit.row_id, AnnCandidateDistance::Hamming(distance)))
9515 }
9516 RetrieverScore::AnnCosineDistance(distance) => {
9517 Some((hit.row_id, AnnCandidateDistance::Cosine(distance)))
9518 }
9519 _ => None,
9520 })
9521 .collect();
9522 let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9523 if let Some(context) = context {
9524 context.consume(row_ids.len())?;
9525 }
9526 let gather_started = std::time::Instant::now();
9527 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9528 let values = self.values_for_rids_batch_at_with_context(
9529 &row_ids,
9530 request.column_id,
9531 snapshot,
9532 query_now,
9533 context,
9534 )?;
9535 let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9536 let score_started = std::time::Instant::now();
9537 let vector_work =
9538 crate::query::work_units(request.query.len(), crate::query::VECTOR_WORK_QUANTUM);
9539 let query_norm = if matches!(request.metric, VectorMetric::Cosine) {
9540 if let Some(context) = context {
9541 context.consume(vector_work)?;
9542 }
9543 request
9544 .query
9545 .iter()
9546 .map(|value| f64::from(*value).powi(2))
9547 .sum::<f64>()
9548 .sqrt()
9549 } else {
9550 0.0
9551 };
9552 let mut reranked = Vec::with_capacity(values.len().min(request.limit));
9553 for (row_id, value) in values {
9554 if let Some(meta) = value.generated_embedding_metadata() {
9555 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9556 continue;
9557 }
9558 }
9559 let Some(vector) = value.as_embedding() else {
9560 continue;
9561 };
9562 let exact_score = match request.metric {
9563 VectorMetric::DotProduct => {
9564 if let Some(context) = context {
9565 context.consume(vector_work)?;
9566 }
9567 request
9568 .query
9569 .iter()
9570 .zip(vector)
9571 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9572 .sum::<f64>()
9573 }
9574 VectorMetric::Cosine => {
9575 if let Some(context) = context {
9576 context.consume(vector_work.saturating_mul(2))?;
9577 }
9578 let dot = request
9579 .query
9580 .iter()
9581 .zip(vector)
9582 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9583 .sum::<f64>();
9584 let norm = vector
9585 .iter()
9586 .map(|value| f64::from(*value).powi(2))
9587 .sum::<f64>()
9588 .sqrt();
9589 if query_norm == 0.0 || norm == 0.0 {
9590 0.0
9591 } else {
9592 dot / (query_norm * norm)
9593 }
9594 }
9595 VectorMetric::Euclidean => {
9596 if let Some(context) = context {
9597 context.consume(vector_work)?;
9598 }
9599 request
9600 .query
9601 .iter()
9602 .zip(vector)
9603 .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9604 .sum::<f64>()
9605 .sqrt()
9606 }
9607 };
9608 let exact_score = exact_score as f32;
9609 if !exact_score.is_finite() {
9610 return Err(MongrelError::InvalidArgument(
9611 "exact ANN score must be finite".into(),
9612 ));
9613 }
9614 let Some(candidate_distance) = distances.get(&row_id).copied() else {
9615 continue;
9616 };
9617 reranked.push(AnnRerankHit {
9618 row_id,
9619 candidate_distance,
9620 exact_score,
9621 });
9622 }
9623 reranked.sort_by(|left, right| {
9624 let score = match request.metric {
9625 VectorMetric::Euclidean => left.exact_score.total_cmp(&right.exact_score),
9626 VectorMetric::Cosine | VectorMetric::DotProduct => {
9627 right.exact_score.total_cmp(&left.exact_score)
9628 }
9629 };
9630 score.then_with(|| left.row_id.cmp(&right.row_id))
9631 });
9632 reranked.truncate(request.limit);
9633 crate::trace::QueryTrace::record(|trace| {
9634 trace.exact_vector_gather_nanos =
9635 trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9636 trace.exact_vector_score_nanos = trace
9637 .exact_vector_score_nanos
9638 .saturating_add(score_started.elapsed().as_nanos() as u64);
9639 });
9640 Ok(reranked)
9641 }
9642
9643 pub fn set_similarity_with_allowed(
9644 &mut self,
9645 request: &crate::query::SetSimilarityRequest,
9646 allowed: Option<&std::collections::HashSet<RowId>>,
9647 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9648 self.set_similarity_explained_at(request, self.snapshot(), allowed)
9649 .map(|(hits, _)| hits)
9650 }
9651
9652 pub fn set_similarity_explained(
9653 &mut self,
9654 request: &crate::query::SetSimilarityRequest,
9655 ) -> Result<(
9656 Vec<crate::query::SetSimilarityHit>,
9657 crate::query::SetSimilarityTrace,
9658 )> {
9659 self.set_similarity_explained_at(request, self.snapshot(), None)
9660 }
9661
9662 fn set_similarity_explained_at(
9663 &mut self,
9664 request: &crate::query::SetSimilarityRequest,
9665 snapshot: Snapshot,
9666 allowed: Option<&std::collections::HashSet<RowId>>,
9667 ) -> Result<(
9668 Vec<crate::query::SetSimilarityHit>,
9669 crate::query::SetSimilarityTrace,
9670 )> {
9671 self.ensure_indexes_complete()?;
9672 self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, None)
9673 }
9674
9675 pub fn set_similarity_at_with_context(
9676 &mut self,
9677 request: &crate::query::SetSimilarityRequest,
9678 snapshot: Snapshot,
9679 allowed: Option<&std::collections::HashSet<RowId>>,
9680 context: Option<&crate::query::AiExecutionContext>,
9681 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9682 self.ensure_indexes_complete()?;
9683 self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, context)
9684 .map(|(hits, _)| hits)
9685 }
9686
9687 pub fn set_similarity_at_with_candidate_authorization_and_context(
9688 &mut self,
9689 request: &crate::query::SetSimilarityRequest,
9690 snapshot: Snapshot,
9691 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9692 context: Option<&crate::query::AiExecutionContext>,
9693 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9694 self.ensure_indexes_complete()?;
9695 self.set_similarity_explained_at_with_context(
9696 request,
9697 snapshot,
9698 None,
9699 authorization,
9700 context,
9701 )
9702 .map(|(hits, _)| hits)
9703 }
9704
9705 #[doc(hidden)]
9706 pub fn set_similarity_at_with_candidate_authorization_on_generation(
9707 &self,
9708 request: &crate::query::SetSimilarityRequest,
9709 snapshot: Snapshot,
9710 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9711 context: Option<&crate::query::AiExecutionContext>,
9712 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9713 self.set_similarity_explained_at_with_context(
9714 request,
9715 snapshot,
9716 None,
9717 authorization,
9718 context,
9719 )
9720 .map(|(hits, _)| hits)
9721 }
9722
9723 fn set_similarity_explained_at_with_context(
9724 &self,
9725 request: &crate::query::SetSimilarityRequest,
9726 snapshot: Snapshot,
9727 allowed: Option<&std::collections::HashSet<RowId>>,
9728 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9729 context: Option<&crate::query::AiExecutionContext>,
9730 ) -> Result<(
9731 Vec<crate::query::SetSimilarityHit>,
9732 crate::query::SetSimilarityTrace,
9733 )> {
9734 use crate::query::{
9735 Retriever, RetrieverScore, SetSimilarityHit, MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9736 MAX_SET_MEMBERS,
9737 };
9738 let mut trace = crate::query::SetSimilarityTrace::default();
9739 if request.members.is_empty() {
9740 return Ok((Vec::new(), trace));
9741 }
9742 if request.candidate_k == 0 || request.limit == 0 {
9743 return Err(MongrelError::InvalidArgument(
9744 "candidate_k and limit must be > 0".into(),
9745 ));
9746 }
9747 if request.candidate_k > MAX_RETRIEVER_K
9748 || request.limit > MAX_FINAL_LIMIT
9749 || request.members.len() > MAX_SET_MEMBERS
9750 {
9751 return Err(MongrelError::InvalidArgument(format!(
9752 "candidate_k must be <= {MAX_RETRIEVER_K}, limit <= {MAX_FINAL_LIMIT}, and members <= {MAX_SET_MEMBERS}"
9753 )));
9754 }
9755 if !request.min_jaccard.is_finite() || !(0.0..=1.0).contains(&request.min_jaccard) {
9756 return Err(MongrelError::InvalidArgument(
9757 "min_jaccard must be finite and between 0 and 1".into(),
9758 ));
9759 }
9760 let started = std::time::Instant::now();
9761 let retriever = Retriever::MinHash {
9762 column_id: request.column_id,
9763 members: request.members.clone(),
9764 k: request.candidate_k,
9765 };
9766 self.require_select()?;
9767 self.validate_retriever(&retriever)?;
9768 let hits = self.retrieve_filtered(
9769 &retriever,
9770 snapshot,
9771 None,
9772 allowed,
9773 candidate_authorization,
9774 context,
9775 )?;
9776 trace.candidate_generation_us = started.elapsed().as_micros() as u64;
9777 trace.candidate_count = hits.len();
9778 let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9779 if let Some(context) = context {
9780 context.consume(row_ids.len())?;
9781 }
9782 let started = std::time::Instant::now();
9783 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9784 let values = self.values_for_rids_batch_at_with_context(
9785 &row_ids,
9786 request.column_id,
9787 snapshot,
9788 query_now,
9789 context,
9790 )?;
9791 trace.gather_us = started.elapsed().as_micros() as u64;
9792 if let Some(context) = context {
9793 context.consume(request.members.len())?;
9794 }
9795 let query: std::collections::HashSet<_> = request.members.iter().cloned().collect();
9796 let estimates: std::collections::HashMap<_, _> = hits
9797 .into_iter()
9798 .filter_map(|hit| match hit.score {
9799 RetrieverScore::MinHashEstimatedJaccard(score) => Some((hit.row_id, score)),
9800 _ => None,
9801 })
9802 .collect();
9803 let started = std::time::Instant::now();
9804 let mut parsed = Vec::with_capacity(values.len());
9805 for (row_id, value) in values {
9806 let Value::Bytes(bytes) = value else {
9807 continue;
9808 };
9809 if let Some(context) = context {
9810 context.consume(crate::query::work_units(
9811 bytes.len(),
9812 crate::query::PARSE_WORK_QUANTUM,
9813 ))?;
9814 }
9815 let Ok(serde_json::Value::Array(members)) = serde_json::from_slice(&bytes) else {
9816 continue;
9817 };
9818 if let Some(context) = context {
9819 context.consume(members.len())?;
9820 }
9821 let stored = members
9822 .into_iter()
9823 .filter_map(|member| match member {
9824 serde_json::Value::String(value) => {
9825 Some(crate::query::SetMember::String(value))
9826 }
9827 serde_json::Value::Number(value) => {
9828 Some(crate::query::SetMember::Number(value))
9829 }
9830 serde_json::Value::Bool(value) => Some(crate::query::SetMember::Boolean(value)),
9831 _ => None,
9832 })
9833 .collect::<std::collections::HashSet<_>>();
9834 parsed.push((row_id, stored));
9835 }
9836 trace.parse_us = started.elapsed().as_micros() as u64;
9837 trace.verified_count = parsed.len();
9838 let started = std::time::Instant::now();
9839 let mut exact = Vec::new();
9840 for (row_id, stored) in parsed {
9841 if let Some(context) = context {
9842 context.consume(query.len().saturating_add(stored.len()))?;
9843 }
9844 let union = query.union(&stored).count();
9845 let score = if union == 0 {
9846 1.0
9847 } else {
9848 query.intersection(&stored).count() as f32 / union as f32
9849 };
9850 if score >= request.min_jaccard {
9851 exact.push(SetSimilarityHit {
9852 row_id,
9853 estimated_jaccard: estimates.get(&row_id).copied().unwrap_or_default(),
9854 exact_jaccard: score,
9855 });
9856 }
9857 }
9858 exact.sort_by(|a, b| {
9859 b.exact_jaccard
9860 .total_cmp(&a.exact_jaccard)
9861 .then_with(|| a.row_id.cmp(&b.row_id))
9862 });
9863 exact.truncate(request.limit);
9864 trace.score_us = started.elapsed().as_micros() as u64;
9865 crate::trace::QueryTrace::record(|query_trace| {
9866 query_trace.exact_set_gather_nanos = query_trace
9867 .exact_set_gather_nanos
9868 .saturating_add(trace.gather_us.saturating_mul(1_000));
9869 query_trace.exact_set_parse_nanos = query_trace
9870 .exact_set_parse_nanos
9871 .saturating_add(trace.parse_us.saturating_mul(1_000));
9872 query_trace.exact_set_score_nanos = query_trace
9873 .exact_set_score_nanos
9874 .saturating_add(trace.score_us.saturating_mul(1_000));
9875 });
9876 Ok((exact, trace))
9877 }
9878
9879 fn values_for_rids_batch_at(
9881 &self,
9882 row_ids: &[u64],
9883 column_id: u16,
9884 snapshot: Snapshot,
9885 now: i64,
9886 ) -> Result<Vec<(RowId, Value)>> {
9887 if self.ttl.is_none()
9888 && self.memtable.is_empty()
9889 && self.mutable_run.is_empty()
9890 && self.run_refs.len() == 1
9891 {
9892 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
9893 if row_ids.len().saturating_mul(24) < reader.row_count() {
9898 let mut values = Vec::with_capacity(row_ids.len());
9899 for &raw_row_id in row_ids {
9900 let row_id = RowId(raw_row_id);
9901 if let Some((_, false, Some(value))) =
9902 reader.get_version_column_at(row_id, snapshot, column_id)?
9903 {
9904 values.push((row_id, value));
9905 }
9906 }
9907 return Ok(values);
9908 }
9909 let (positions, visible_row_ids) = reader.visible_positions_with_rids_at(snapshot)?;
9910 let requested: Vec<(RowId, usize)> = row_ids
9911 .iter()
9912 .filter_map(|raw| {
9913 visible_row_ids
9914 .binary_search(&(*raw as i64))
9915 .ok()
9916 .map(|index| (RowId(*raw), positions[index]))
9917 })
9918 .collect();
9919 let values = reader.gather_column(
9920 column_id,
9921 &requested
9922 .iter()
9923 .map(|(_, position)| *position)
9924 .collect::<Vec<_>>(),
9925 )?;
9926 return Ok(requested
9927 .into_iter()
9928 .zip(values)
9929 .map(|((row_id, _), value)| (row_id, value))
9930 .collect());
9931 }
9932 self.values_for_rids_at(row_ids, column_id, snapshot, now)
9933 }
9934
9935 fn values_for_rids_batch_at_with_context(
9936 &self,
9937 row_ids: &[u64],
9938 column_id: u16,
9939 snapshot: Snapshot,
9940 now: i64,
9941 context: Option<&crate::query::AiExecutionContext>,
9942 ) -> Result<Vec<(RowId, Value)>> {
9943 let Some(context) = context else {
9944 return self.values_for_rids_batch_at(row_ids, column_id, snapshot, now);
9945 };
9946 let mut values = Vec::with_capacity(row_ids.len());
9947 for chunk in row_ids.chunks(256) {
9948 context.checkpoint()?;
9949 values.extend(self.values_for_rids_batch_at(chunk, column_id, snapshot, now)?);
9950 }
9951 Ok(values)
9952 }
9953
9954 fn values_for_rids_at(
9956 &self,
9957 row_ids: &[u64],
9958 column_id: u16,
9959 snapshot: Snapshot,
9960 now: i64,
9961 ) -> Result<Vec<(RowId, Value)>> {
9962 let mut readers: Vec<_> = self
9963 .run_refs
9964 .iter()
9965 .map(|run| self.open_reader(run.run_id))
9966 .collect::<Result<_>>()?;
9967 let mut out = Vec::with_capacity(row_ids.len());
9968 for &raw_row_id in row_ids {
9969 let row_id = RowId(raw_row_id);
9970 let mem = self.memtable.get_version_at(row_id, snapshot);
9971 let mutable = self.mutable_run.get_version_at(row_id, snapshot);
9972 let overlay = match (mem, mutable) {
9973 (Some((_, a)), Some((_, b))) => Some(
9974 if Snapshot::version_is_newer(
9975 a.committed_epoch,
9976 a.commit_ts,
9977 b.committed_epoch,
9978 b.commit_ts,
9979 ) {
9980 a
9981 } else {
9982 b
9983 },
9984 ),
9985 (Some((_, value)), None) | (None, Some((_, value))) => Some(value),
9986 (None, None) => None,
9987 };
9988 if let Some(row) = overlay {
9989 if !row.deleted && !self.row_expired_at(&row, now) {
9990 if let Some(value) = row.columns.get(&column_id) {
9991 out.push((row_id, value.clone()));
9992 }
9993 }
9994 continue;
9995 }
9996
9997 let mut best: Option<(crate::sorted_run::VersionedColumnValue, usize)> = None;
10002 for (index, reader) in readers.iter_mut().enumerate() {
10003 if let Some(versioned) =
10004 reader.get_version_column_full_at(row_id, snapshot, column_id)?
10005 {
10006 if best
10007 .as_ref()
10008 .map(|(current, _)| versioned.stamp.is_newer_than(current.stamp))
10009 .unwrap_or(true)
10010 {
10011 best = Some((versioned, index));
10012 }
10013 }
10014 }
10015 let Some((candidate, reader_index)) = best else {
10016 continue;
10017 };
10018 if candidate.deleted {
10019 continue;
10020 }
10021 let Some(value) = candidate.value.clone() else {
10022 continue;
10023 };
10024 if let Some(ttl) = self.ttl {
10025 if ttl.column_id != column_id {
10026 if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
10027 row_id,
10028 snapshot,
10029 ttl.column_id,
10030 )? {
10031 if let Some(Value::Int64(timestamp)) = ttl_value.value {
10032 if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10033 continue;
10034 }
10035 }
10036 }
10037 } else if let Value::Int64(timestamp) = &value {
10038 if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
10039 continue;
10040 }
10041 }
10042 }
10043 out.push((row_id, value));
10044 }
10045 Ok(out)
10046 }
10047
10048 pub fn rows_for_rids(&self, rids: &[u64], snapshot: Snapshot) -> Result<Vec<Row>> {
10053 self.rows_for_rids_at_time(rids, snapshot, unix_nanos_now(), None)
10054 }
10055
10056 pub fn rows_for_rids_with_context(
10057 &self,
10058 rids: &[u64],
10059 snapshot: Snapshot,
10060 context: &crate::query::AiExecutionContext,
10061 ) -> Result<Vec<Row>> {
10062 context.consume(rids.len().saturating_mul(self.schema.columns.len()))?;
10063 self.rows_for_rids_at_time(rids, snapshot, context.query_time_nanos(), None)
10064 }
10065
10066 fn rows_for_rids_at_time(
10067 &self,
10068 rids: &[u64],
10069 snapshot: Snapshot,
10070 ttl_now: i64,
10071 control: Option<&crate::ExecutionControl>,
10072 ) -> Result<Vec<Row>> {
10073 use std::collections::HashMap;
10074 let mut rows = Vec::with_capacity(rids.len());
10075 let tier_size = self.memtable.len() + self.mutable_run.len();
10090 let mut overlay: HashMap<u64, Row> = HashMap::with_capacity(rids.len());
10091 if rids.len().saturating_mul(24) < tier_size {
10092 for &rid in rids {
10093 if overlay.len() & 255 == 0 {
10094 control
10095 .map(crate::ExecutionControl::checkpoint)
10096 .transpose()?;
10097 }
10098 let mem = self.memtable.get_version_at(RowId(rid), snapshot);
10099 let mrun = self.mutable_run.get_version_at(RowId(rid), snapshot);
10100 let newest = match (mem, mrun) {
10101 (Some((_, mr)), Some((_, rr))) => Some(
10102 if Snapshot::version_is_newer(
10103 mr.committed_epoch,
10104 mr.commit_ts,
10105 rr.committed_epoch,
10106 rr.commit_ts,
10107 ) {
10108 mr
10109 } else {
10110 rr
10111 },
10112 ),
10113 (Some((_, mr)), None) => Some(mr),
10114 (None, Some((_, rr))) => Some(rr),
10115 (None, None) => None,
10116 };
10117 if let Some(row) = newest {
10118 overlay.insert(rid, row);
10119 }
10120 }
10121 } else {
10122 let fold_newest = |row: Row, overlay: &mut HashMap<u64, Row>| {
10123 overlay
10124 .entry(row.row_id.0)
10125 .and_modify(|e| {
10126 if Snapshot::version_is_newer(
10127 row.committed_epoch,
10128 row.commit_ts,
10129 e.committed_epoch,
10130 e.commit_ts,
10131 ) {
10132 *e = row.clone();
10133 }
10134 })
10135 .or_insert(row);
10136 };
10137 for (index, row) in self
10138 .memtable
10139 .visible_versions_at(snapshot)
10140 .into_iter()
10141 .enumerate()
10142 {
10143 if index & 255 == 0 {
10144 control
10145 .map(crate::ExecutionControl::checkpoint)
10146 .transpose()?;
10147 }
10148 fold_newest(row, &mut overlay);
10149 }
10150 for (index, row) in self
10151 .mutable_run
10152 .visible_versions_at(snapshot)
10153 .into_iter()
10154 .enumerate()
10155 {
10156 if index & 255 == 0 {
10157 control
10158 .map(crate::ExecutionControl::checkpoint)
10159 .transpose()?;
10160 }
10161 fold_newest(row, &mut overlay);
10162 }
10163 }
10164 if self.run_refs.len() == 1 {
10165 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
10166 if rids.len().saturating_mul(24) < reader.row_count() {
10174 for (index, &rid) in rids.iter().enumerate() {
10175 if index & 255 == 0 {
10176 control
10177 .map(crate::ExecutionControl::checkpoint)
10178 .transpose()?;
10179 }
10180 if let Some(r) = overlay.get(&rid) {
10181 if !r.deleted {
10182 rows.push(r.clone());
10183 }
10184 continue;
10185 }
10186 if let Some((_, row)) = reader.get_version_at(RowId(rid), snapshot)? {
10187 if !row.deleted {
10188 rows.push(row);
10189 }
10190 }
10191 }
10192 rows.retain(|row| !self.row_expired_at(row, ttl_now));
10193 return Ok(rows);
10194 }
10195 let (positions, vis_rids) = reader.visible_positions_with_rids_at(snapshot)?;
10204 enum Src {
10207 Overlay,
10208 Run,
10209 }
10210 let mut plan: Vec<Src> = Vec::with_capacity(rids.len());
10211 let mut fetch: Vec<usize> = Vec::with_capacity(rids.len());
10212 for (index, rid) in rids.iter().enumerate() {
10213 if index & 255 == 0 {
10214 control
10215 .map(crate::ExecutionControl::checkpoint)
10216 .transpose()?;
10217 }
10218 if overlay.contains_key(rid) {
10219 plan.push(Src::Overlay);
10220 continue;
10221 }
10222 match vis_rids.binary_search(&(*rid as i64)) {
10223 Ok(i) => {
10224 plan.push(Src::Run);
10225 fetch.push(positions[i]);
10226 }
10227 Err(_) => { }
10228 }
10229 }
10230 let fetched = reader.materialize_batch(&fetch)?;
10231 let mut fetched_iter = fetched.into_iter();
10232 for (index, (rid, src)) in rids.iter().zip(plan).enumerate() {
10233 if index & 255 == 0 {
10234 control
10235 .map(crate::ExecutionControl::checkpoint)
10236 .transpose()?;
10237 }
10238 match src {
10239 Src::Overlay => {
10240 if let Some(r) = overlay.get(rid) {
10241 if !r.deleted {
10242 rows.push(r.clone());
10243 }
10244 }
10245 }
10246 Src::Run => {
10247 if let Some(row) = fetched_iter.next() {
10248 if !row.deleted {
10249 rows.push(row);
10250 }
10251 }
10252 }
10253 }
10254 }
10255 rows.retain(|row| !self.row_expired_at(row, ttl_now));
10256 return Ok(rows);
10257 }
10258 let mut readers: Vec<_> = self
10262 .run_refs
10263 .iter()
10264 .map(|rr| self.open_reader(rr.run_id))
10265 .collect::<Result<Vec<_>>>()?;
10266 for (index, rid) in rids.iter().enumerate() {
10267 if index & 255 == 0 {
10268 control
10269 .map(crate::ExecutionControl::checkpoint)
10270 .transpose()?;
10271 }
10272 if let Some(r) = overlay.get(rid) {
10273 if !r.deleted {
10274 rows.push(r.clone());
10275 }
10276 continue;
10277 }
10278 let mut best: Option<(VersionStamp, Row)> = None;
10283 for reader in readers.iter_mut() {
10284 if let Ok(Some((stamp, row))) = reader.get_version_stamp_at(RowId(*rid), snapshot) {
10285 if best
10286 .as_ref()
10287 .map(|(current, _)| stamp.is_newer_than(*current))
10288 .unwrap_or(true)
10289 {
10290 best = Some((stamp, row));
10291 }
10292 }
10293 }
10294 if let Some((_, r)) = best {
10295 if !r.deleted {
10296 rows.push(r);
10297 }
10298 }
10299 }
10300 rows.retain(|row| !self.row_expired_at(row, ttl_now));
10301 Ok(rows)
10302 }
10303
10304 pub fn indexes_complete(&self) -> bool {
10314 self.indexes_complete
10315 }
10316
10317 pub fn index_build_policy(&self) -> IndexBuildPolicy {
10319 self.index_build_policy
10320 }
10321
10322 pub fn set_index_build_policy(&mut self, policy: IndexBuildPolicy) {
10326 self.index_build_policy = policy;
10327 }
10328
10329 pub fn broadcast_join_values(&self, column_id: u16, pk_db: &Table) -> Option<Vec<Vec<u8>>> {
10334 if !self.indexes_complete {
10338 return None;
10339 }
10340 let b = self.bitmap.get(&column_id)?;
10341 let result: Vec<Vec<u8>> = b
10342 .keys()
10343 .into_iter()
10344 .filter(|k| pk_db.hot.get(k.as_slice()).is_some())
10345 .collect();
10346 Some(result)
10347 }
10348
10349 pub fn fk_join_row_ids(
10350 &self,
10351 fk_column_id: u16,
10352 pk_values: &[Vec<u8>],
10353 fk_conditions: &[crate::query::Condition],
10354 snapshot: Snapshot,
10355 ) -> Result<Vec<u64>> {
10356 let Some(b) = self.bitmap.get(&fk_column_id) else {
10357 return Ok(Vec::new());
10358 };
10359 let mut join_set = {
10360 let mut acc = roaring::RoaringBitmap::new();
10361 for v in pk_values {
10362 acc |= b.get(v);
10363 }
10364 RowIdSet::from_roaring(acc)
10365 };
10366 if !fk_conditions.is_empty() {
10367 let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10368 sets.push(join_set);
10369 for c in fk_conditions {
10370 sets.push(self.resolve_condition(c, snapshot)?);
10371 }
10372 join_set = RowIdSet::intersect_many(sets);
10373 }
10374 Ok(join_set.into_sorted_vec())
10375 }
10376
10377 pub fn fk_join_count(
10383 &self,
10384 fk_column_id: u16,
10385 pk_values: &[Vec<u8>],
10386 fk_conditions: &[crate::query::Condition],
10387 snapshot: Snapshot,
10388 ) -> Result<u64> {
10389 let Some(b) = self.bitmap.get(&fk_column_id) else {
10390 return Ok(0);
10391 };
10392 let mut acc = roaring::RoaringBitmap::new();
10393 for v in pk_values {
10394 acc |= b.get(v);
10395 }
10396 if fk_conditions.is_empty() {
10397 return Ok(acc.len());
10398 }
10399 let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10400 sets.push(RowIdSet::from_roaring(acc));
10401 for c in fk_conditions {
10402 sets.push(self.resolve_condition(c, snapshot)?);
10403 }
10404 Ok(RowIdSet::intersect_many(sets).len() as u64)
10405 }
10406
10407 fn inspect_row_at(&self, rid: RowId, snapshot: Snapshot) -> Option<crate::memtable::Row> {
10412 let mut best: Option<crate::memtable::Row> = None;
10413 let mut consider = |row: crate::memtable::Row| {
10414 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
10415 return;
10416 }
10417 if best.as_ref().is_none_or(|current| {
10418 Snapshot::version_is_newer(
10419 row.committed_epoch,
10420 row.commit_ts,
10421 current.committed_epoch,
10422 current.commit_ts,
10423 )
10424 }) {
10425 best = Some(row);
10426 }
10427 };
10428 if let Some((_, row)) = self.memtable.get_version_at(rid, snapshot) {
10429 consider(row);
10430 }
10431 if let Some((_, row)) = self.mutable_run.get_version_at(rid, snapshot) {
10432 consider(row);
10433 }
10434 for rr in &self.run_refs {
10435 if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
10436 if rid.0 < min_rid || rid.0 > max_rid {
10437 continue;
10438 }
10439 }
10440 let Ok(mut reader) = self.open_reader(rr.run_id) else {
10441 continue;
10442 };
10443 let Ok(Some((_stamp, row))) = reader.get_version_stamp_at(rid, snapshot) else {
10447 continue;
10448 };
10449 consider(row);
10450 }
10451 best
10452 }
10453
10454 fn resolve_pk_with_hot_fallback(
10455 &self,
10456 pk_column_id: u16,
10457 lookup: &[u8],
10458 snapshot: Snapshot,
10459 ) -> Result<RowIdSet> {
10460 let snapshot = if self.is_shared()
10473 || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10474 || snapshot.epoch.0 != self.epoch.visible().0
10475 {
10476 snapshot
10477 } else {
10478 Snapshot::at(self.pending_epoch())
10479 };
10480 if !self.indexes_complete {
10484 let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10485 self.record_hot_fallback_reason(crate::trace::HotFallbackReason::IndexIncomplete);
10486 return Ok(result);
10487 }
10488 let mapped = self.hot.get(lookup);
10491 let Some(r) = mapped else {
10492 let (result, reason) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10493 self.record_hot_fallback_reason(reason);
10494 return Ok(result);
10495 };
10496 if snapshot.epoch < self.current_epoch() {
10501 self.record_hot_fallback_reason(crate::trace::HotFallbackReason::HistoricalSnapshot);
10502 let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10503 return Ok(result);
10504 }
10505 let materialized = self.inspect_row_at(r, snapshot);
10509 let now_nanos = unix_nanos_now();
10510 let inspection = crate::trace::inspect_hot_candidate(
10511 materialized.as_ref(),
10512 snapshot,
10513 self.ttl,
10514 now_nanos,
10515 pk_column_id,
10516 lookup,
10517 |row| {
10518 let pk_value = row.columns.get(&pk_column_id);
10519 pk_value
10520 .map(|v| self.index_lookup_key(pk_column_id, v))
10521 .unwrap_or_default()
10522 },
10523 );
10524 match inspection {
10525 crate::trace::HotCandidateInspection::Hit(row) => {
10526 self.lookup_metrics
10527 .hot_lookup_hit
10528 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10529 crate::trace::QueryTrace::record(|t| {
10530 t.hot_lookup_attempted = true;
10531 t.hot_lookup_hit = true;
10532 });
10533 Ok(RowIdSet::one(row.row_id.0))
10534 }
10535 failure => {
10536 let reason = match &failure {
10537 crate::trace::HotCandidateInspection::Hit(_) => unreachable!(),
10538 crate::trace::HotCandidateInspection::MissingRow => {
10539 crate::trace::HotFallbackReason::Tombstone
10544 }
10545 crate::trace::HotCandidateInspection::Invisible => {
10546 crate::trace::HotFallbackReason::InvisibleAtSnapshot
10547 }
10548 crate::trace::HotCandidateInspection::Tombstone => {
10549 crate::trace::HotFallbackReason::Tombstone
10550 }
10551 crate::trace::HotCandidateInspection::TtlExpired => {
10552 crate::trace::HotFallbackReason::TtlExpired
10553 }
10554 crate::trace::HotCandidateInspection::PrimaryKeyMismatch { .. } => {
10555 crate::trace::HotFallbackReason::PrimaryKeyMismatch
10556 }
10557 };
10558 let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10564 self.record_hot_fallback_reason(reason);
10565 Ok(result)
10566 }
10567 }
10568 }
10569
10570 fn resolve_condition(
10575 &self,
10576 c: &crate::query::Condition,
10577 snapshot: Snapshot,
10578 ) -> Result<RowIdSet> {
10579 self.resolve_condition_with_allowed(c, snapshot, None)
10580 }
10581
10582 fn resolve_condition_with_allowed(
10583 &self,
10584 c: &crate::query::Condition,
10585 snapshot: Snapshot,
10586 allowed: Option<&std::collections::HashSet<RowId>>,
10587 ) -> Result<RowIdSet> {
10588 use crate::query::Condition;
10589 self.validate_condition(c)?;
10590 Ok(match c {
10591 Condition::Pk(key) => {
10592 let lookup = self
10593 .schema
10594 .primary_key()
10595 .map(|pk| self.index_lookup_key_bytes(pk.id, key))
10596 .unwrap_or_else(|| key.clone());
10597 if let Some(pk_col) = self.schema.primary_key() {
10598 return self.resolve_pk_with_hot_fallback(pk_col.id, &lookup, snapshot);
10599 }
10600 RowIdSet::empty()
10604 }
10605 Condition::BitmapEq { column_id, value } => {
10606 let lookup = self.index_lookup_key_bytes(*column_id, value);
10607 self.bitmap
10608 .get(column_id)
10609 .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
10610 .unwrap_or_else(RowIdSet::empty)
10611 }
10612 Condition::BitmapIn { column_id, values } => {
10613 let bm = self.bitmap.get(column_id);
10614 let mut acc = roaring::RoaringBitmap::new();
10615 if let Some(b) = bm {
10616 for v in values {
10617 let lookup = self.index_lookup_key_bytes(*column_id, v);
10618 acc |= b.get(&lookup);
10619 }
10620 }
10621 RowIdSet::from_roaring(acc)
10622 }
10623 Condition::BytesPrefix { column_id, prefix } => {
10624 if let Some(b) = self.bitmap.get(column_id) {
10629 let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
10630 let mut acc = roaring::RoaringBitmap::new();
10631 for key in b.keys() {
10632 if key.starts_with(&lookup_prefix) {
10633 acc |= b.get(&key);
10634 }
10635 }
10636 RowIdSet::from_roaring(acc)
10637 } else {
10638 RowIdSet::empty()
10639 }
10640 }
10641 Condition::FmContains { column_id, pattern } => self
10642 .fm
10643 .get(column_id)
10644 .map(|f| {
10645 RowIdSet::from_unsorted(f.locate(pattern).into_iter().map(|r| r.0).collect())
10646 })
10647 .unwrap_or_else(RowIdSet::empty),
10648 Condition::FmContainsAll {
10649 column_id,
10650 patterns,
10651 } => {
10652 if let Some(f) = self.fm.get(column_id) {
10655 let sets: Vec<RowIdSet> = patterns
10656 .iter()
10657 .map(|pat| {
10658 RowIdSet::from_unsorted(
10659 f.locate(pat).into_iter().map(|r| r.0).collect(),
10660 )
10661 })
10662 .collect();
10663 RowIdSet::intersect_many(sets)
10664 } else {
10665 RowIdSet::empty()
10666 }
10667 }
10668 Condition::Ann {
10669 column_id,
10670 query,
10671 k,
10672 } => RowIdSet::from_unsorted(
10673 self.retrieve_filtered(
10674 &crate::query::Retriever::Ann {
10675 column_id: *column_id,
10676 query: query.clone(),
10677 k: *k,
10678 },
10679 snapshot,
10680 None,
10681 allowed,
10682 None,
10683 None,
10684 )?
10685 .into_iter()
10686 .map(|hit| hit.row_id.0)
10687 .collect(),
10688 ),
10689 Condition::SparseMatch {
10690 column_id,
10691 query,
10692 k,
10693 } => RowIdSet::from_unsorted(
10694 self.retrieve_filtered(
10695 &crate::query::Retriever::Sparse {
10696 column_id: *column_id,
10697 query: query.clone(),
10698 k: *k,
10699 },
10700 snapshot,
10701 None,
10702 allowed,
10703 None,
10704 None,
10705 )?
10706 .into_iter()
10707 .map(|hit| hit.row_id.0)
10708 .collect(),
10709 ),
10710 Condition::MinHashSimilar {
10711 column_id,
10712 query,
10713 k,
10714 } => match self.minhash.get(column_id) {
10715 Some(index) => {
10716 let candidates = index.candidate_row_ids(query);
10717 let eligible =
10718 self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
10719 RowIdSet::from_unsorted(
10720 index
10721 .search_filtered(query, *k, |row_id| {
10722 eligible.contains(&row_id)
10723 && allowed.is_none_or(|allowed| allowed.contains(&row_id))
10724 })
10725 .into_iter()
10726 .map(|(row_id, _)| row_id.0)
10727 .collect(),
10728 )
10729 }
10730 None => RowIdSet::empty(),
10731 },
10732 Condition::Range { column_id, lo, hi } => {
10733 let mut set = if let Some(li) = self.learned_range.get(column_id) {
10752 if self.run_refs.len() == 1 {
10753 RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
10756 } else {
10757 let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10765 if lo == hi {
10766 self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10767 }
10768 return Ok(multi);
10769 }
10770 } else if self.run_refs.len() == 1 {
10771 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10772 r.range_row_id_set_i64(*column_id, *lo, *hi)?
10773 } else {
10774 let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10777 if lo == hi {
10778 self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10779 }
10780 return Ok(multi);
10781 };
10782 if self.learned_range.get(column_id).is_none() && self.run_refs.len() == 1 {
10783 let candidates: Vec<RowId> =
10784 set.into_sorted_vec().into_iter().map(RowId).collect();
10785 set = RowIdSet::from_unsorted(
10786 self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?
10787 .into_iter()
10788 .map(|row_id| row_id.0)
10789 .collect(),
10790 );
10791 }
10792 set.remove_many(self.overlay_rid_set(snapshot));
10793 self.range_scan_overlay_i64(&mut set, *column_id, *lo, *hi, snapshot);
10794 if lo == hi {
10795 self.union_bitmap_point_i64(&mut set, *column_id, *lo, snapshot);
10796 }
10797 RowIdSet::from_unsorted(
10798 set.into_sorted_vec()
10799 .into_iter()
10800 .filter(|row_id| self.get(RowId(*row_id), snapshot).is_some())
10801 .collect(),
10802 )
10803 }
10804 Condition::RangeF64 {
10805 column_id,
10806 lo,
10807 lo_inclusive,
10808 hi,
10809 hi_inclusive,
10810 } => {
10811 let mut set = if let Some(li) = self.learned_range.get(column_id) {
10814 RowIdSet::from_unsorted(
10815 li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
10816 .into_iter()
10817 .collect(),
10818 )
10819 } else if self.run_refs.len() == 1 {
10820 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10821 r.range_row_id_set_f64(*column_id, *lo, *lo_inclusive, *hi, *hi_inclusive)?
10822 } else {
10823 return self.range_scan_f64(
10824 *column_id,
10825 *lo,
10826 *lo_inclusive,
10827 *hi,
10828 *hi_inclusive,
10829 snapshot,
10830 );
10831 };
10832 set.remove_many(self.overlay_rid_set(snapshot));
10833 self.range_scan_overlay_f64(
10834 &mut set,
10835 *column_id,
10836 *lo,
10837 *lo_inclusive,
10838 *hi,
10839 *hi_inclusive,
10840 snapshot,
10841 );
10842 set
10843 }
10844 Condition::IsNull { column_id } => {
10845 let mut set = if self.run_refs.len() == 1 {
10846 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10847 r.null_row_id_set(*column_id, true)?
10848 } else {
10849 return self.null_scan(*column_id, true, snapshot);
10850 };
10851 set.remove_many(self.overlay_rid_set(snapshot));
10852 self.null_scan_overlay(&mut set, *column_id, true, snapshot);
10853 set
10854 }
10855 Condition::IsNotNull { column_id } => {
10856 let mut set = if self.run_refs.len() == 1 {
10857 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10858 r.null_row_id_set(*column_id, false)?
10859 } else {
10860 return self.null_scan(*column_id, false, snapshot);
10861 };
10862 set.remove_many(self.overlay_rid_set(snapshot));
10863 self.null_scan_overlay(&mut set, *column_id, false, snapshot);
10864 set
10865 }
10866 })
10867 }
10868
10869 fn range_scan_i64(
10877 &self,
10878 column_id: u16,
10879 lo: i64,
10880 hi: i64,
10881 snapshot: Snapshot,
10882 ) -> Result<RowIdSet> {
10883 let mut row_ids = Vec::new();
10884 let mut tomb_rids: HashSet<u64> = HashSet::new();
10891 let overlay_rids = self.overlay_rid_set(snapshot);
10892 for rr in &self.run_refs {
10893 let mut reader = self.open_reader(rr.run_id)?;
10894 let matched = reader.range_row_ids_visible_i64_at(column_id, lo, hi, snapshot)?;
10895 for rid in matched {
10896 if !overlay_rids.contains(&rid) {
10897 row_ids.push(rid);
10898 }
10899 }
10900 for rid in reader.tombstoned_row_ids_at(snapshot)? {
10901 tomb_rids.insert(rid);
10902 }
10903 }
10904 let overlay_tombstone_snapshot = if self.is_shared()
10911 || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10912 || snapshot.epoch.0 != self.epoch.visible().0
10913 {
10914 snapshot
10915 } else {
10916 Snapshot::at(self.pending_epoch())
10917 };
10918 for row in self
10919 .memtable
10920 .visible_versions_at(overlay_tombstone_snapshot)
10921 .into_iter()
10922 .chain(
10923 self.mutable_run
10924 .visible_versions_at(overlay_tombstone_snapshot),
10925 )
10926 {
10927 if row.deleted {
10928 tomb_rids.insert(row.row_id.0);
10929 }
10930 }
10931 let mut s = RowIdSet::from_unsorted(row_ids);
10932 s.remove_many(tomb_rids);
10933 let candidates: Vec<RowId> = s.into_sorted_vec().into_iter().map(RowId).collect();
10934 let eligible = self.eligible_candidate_ids(&candidates, column_id, snapshot, None)?;
10935 let mut s = RowIdSet::from_unsorted(eligible.into_iter().map(|row_id| row_id.0).collect());
10936 self.range_scan_overlay_i64(&mut s, column_id, lo, hi, snapshot);
10937 Ok(s)
10938 }
10939
10940 fn range_scan_f64(
10943 &self,
10944 column_id: u16,
10945 lo: f64,
10946 lo_inclusive: bool,
10947 hi: f64,
10948 hi_inclusive: bool,
10949 snapshot: Snapshot,
10950 ) -> Result<RowIdSet> {
10951 let mut row_ids = Vec::new();
10952 let overlay_rids = self.overlay_rid_set(snapshot);
10953 for rr in &self.run_refs {
10954 let mut reader = self.open_reader(rr.run_id)?;
10955 let matched = reader.range_row_ids_visible_f64_at(
10956 column_id,
10957 lo,
10958 lo_inclusive,
10959 hi,
10960 hi_inclusive,
10961 snapshot,
10962 )?;
10963 for rid in matched {
10964 if !overlay_rids.contains(&rid) {
10965 row_ids.push(rid);
10966 }
10967 }
10968 }
10969 let mut s = RowIdSet::from_unsorted(row_ids);
10970 self.range_scan_overlay_f64(
10971 &mut s,
10972 column_id,
10973 lo,
10974 lo_inclusive,
10975 hi,
10976 hi_inclusive,
10977 snapshot,
10978 );
10979 Ok(s)
10980 }
10981
10982 fn overlay_rid_set(&self, snapshot: Snapshot) -> HashSet<u64> {
10984 let mut s = HashSet::new();
10985 for row in self.memtable.visible_versions_at(snapshot) {
10986 s.insert(row.row_id.0);
10987 }
10988 for row in self.mutable_run.visible_versions_at(snapshot) {
10989 s.insert(row.row_id.0);
10990 }
10991 s
10992 }
10993
10994 fn range_scan_overlay_i64(
10995 &self,
10996 s: &mut RowIdSet,
10997 column_id: u16,
10998 lo: i64,
10999 hi: i64,
11000 snapshot: Snapshot,
11001 ) {
11002 let mut newest: HashMap<u64, Row> = HashMap::new();
11009 for r in self.mutable_run.visible_versions_at(snapshot) {
11010 newest.insert(r.row_id.0, r);
11011 }
11012 for r in self.memtable.visible_versions_at(snapshot) {
11013 newest
11014 .entry(r.row_id.0)
11015 .and_modify(|cur| {
11016 if Snapshot::version_is_newer(
11017 r.committed_epoch,
11018 r.commit_ts,
11019 cur.committed_epoch,
11020 cur.commit_ts,
11021 ) {
11022 *cur = r.clone();
11023 }
11024 })
11025 .or_insert(r);
11026 }
11027 for row in newest.values() {
11028 if !row.deleted {
11029 if let Some(Value::Int64(v)) = row.columns.get(&column_id) {
11030 if *v >= lo && *v <= hi && !self.row_expired_at(row, unix_nanos_now()) {
11031 s.insert(row.row_id.0);
11032 }
11033 }
11034 }
11035 }
11036 }
11037
11038 #[allow(clippy::too_many_arguments)]
11039 fn range_scan_overlay_f64(
11040 &self,
11041 s: &mut RowIdSet,
11042 column_id: u16,
11043 lo: f64,
11044 lo_inclusive: bool,
11045 hi: f64,
11046 hi_inclusive: bool,
11047 snapshot: Snapshot,
11048 ) {
11049 let mut newest: HashMap<u64, Row> = HashMap::new();
11052 for r in self.mutable_run.visible_versions_at(snapshot) {
11053 newest.insert(r.row_id.0, r);
11054 }
11055 for r in self.memtable.visible_versions_at(snapshot) {
11056 newest
11057 .entry(r.row_id.0)
11058 .and_modify(|cur| {
11059 if Snapshot::version_is_newer(
11060 r.committed_epoch,
11061 r.commit_ts,
11062 cur.committed_epoch,
11063 cur.commit_ts,
11064 ) {
11065 *cur = r.clone();
11066 }
11067 })
11068 .or_insert(r);
11069 }
11070 for row in newest.values() {
11071 if !row.deleted {
11072 if let Some(Value::Float64(v)) = row.columns.get(&column_id) {
11073 let ok_lo = if lo_inclusive { *v >= lo } else { *v > lo };
11074 let ok_hi = if hi_inclusive { *v <= hi } else { *v < hi };
11075 if ok_lo && ok_hi && !self.row_expired_at(row, unix_nanos_now()) {
11076 s.insert(row.row_id.0);
11077 }
11078 }
11079 }
11080 }
11081 }
11082
11083 fn null_scan(&self, column_id: u16, want_nulls: bool, snapshot: Snapshot) -> Result<RowIdSet> {
11086 let mut row_ids = Vec::new();
11087 let overlay_rids = self.overlay_rid_set(snapshot);
11088 for rr in &self.run_refs {
11089 let mut reader = self.open_reader(rr.run_id)?;
11090 let matched = reader.null_row_ids_visible_at(column_id, want_nulls, snapshot)?;
11091 for rid in matched {
11092 if !overlay_rids.contains(&rid) {
11093 row_ids.push(rid);
11094 }
11095 }
11096 }
11097 let mut s = RowIdSet::from_unsorted(row_ids);
11098 self.null_scan_overlay(&mut s, column_id, want_nulls, snapshot);
11099 Ok(s)
11100 }
11101
11102 fn null_scan_overlay(
11106 &self,
11107 s: &mut RowIdSet,
11108 column_id: u16,
11109 want_nulls: bool,
11110 snapshot: Snapshot,
11111 ) {
11112 let mut newest: HashMap<u64, Row> = HashMap::new();
11113 for r in self.mutable_run.visible_versions_at(snapshot) {
11114 newest.insert(r.row_id.0, r);
11115 }
11116 for r in self.memtable.visible_versions_at(snapshot) {
11117 newest
11118 .entry(r.row_id.0)
11119 .and_modify(|cur| {
11120 if Snapshot::version_is_newer(
11121 r.committed_epoch,
11122 r.commit_ts,
11123 cur.committed_epoch,
11124 cur.commit_ts,
11125 ) {
11126 *cur = r.clone();
11127 }
11128 })
11129 .or_insert(r);
11130 }
11131 for row in newest.values() {
11132 if row.deleted {
11133 continue;
11134 }
11135 let is_null = !row.columns.contains_key(&column_id)
11136 || matches!(row.columns.get(&column_id), Some(Value::Null) | None);
11137 if is_null == want_nulls {
11138 s.insert(row.row_id.0);
11139 }
11140 }
11141 }
11142
11143 pub fn snapshot(&self) -> Snapshot {
11144 let epoch = self.epoch.visible();
11145 match &self.wal {
11149 WalSink::Shared(shared) => match shared.hlc.now() {
11150 Ok(commit_ts) => Snapshot::at_hlc(epoch, commit_ts),
11151 Err(_) => Snapshot::at_hlc(epoch, mongreldb_types::hlc::HlcTimestamp::MAX),
11153 },
11154 WalSink::Private(_) | WalSink::ReadOnly => Snapshot::at(epoch),
11155 }
11156 }
11157
11158 pub fn data_generation(&self) -> u64 {
11160 self.data_generation
11161 }
11162
11163 pub(crate) fn bump_data_generation(&mut self) {
11164 self.data_generation = self.data_generation.wrapping_add(1);
11165 }
11166
11167 pub fn table_id(&self) -> u64 {
11169 self.table_id
11170 }
11171
11172 fn seal_generations(&mut self) {
11178 self.memtable.seal();
11179 self.mutable_run.seal();
11180 self.hot.seal();
11181 for index in self.bitmap.values_mut() {
11182 index.seal();
11183 }
11184 for index in self.ann.values_mut() {
11185 index.seal();
11186 }
11187 for index in self.fm.values_mut() {
11188 index.seal();
11189 }
11190 for index in self.sparse.values_mut() {
11191 index.seal();
11192 }
11193 for index in self.minhash.values_mut() {
11194 index.seal();
11195 }
11196 self.pk_by_row.seal();
11197 }
11198
11199 fn capture_read_generation(&self) -> ReadGeneration {
11204 let visible_through = self.current_epoch();
11205 ReadGeneration {
11206 schema: Arc::new(self.schema.clone()),
11207 base_runs: Arc::new(self.run_refs.clone()),
11208 deltas: TableDeltas {
11209 memtable: self.memtable.clone(),
11210 mutable_run: self.mutable_run.clone(),
11211 hot: self.hot.clone(),
11212 pk_by_row: self.pk_by_row.clone(),
11213 },
11214 indexes: Arc::new(IndexGeneration::capture(
11215 &self.bitmap,
11216 &self.learned_range,
11217 &self.fm,
11218 &self.ann,
11219 &self.sparse,
11220 &self.minhash,
11221 visible_through,
11222 match &self.wal {
11224 WalSink::Shared(shared) => shared
11225 .hlc
11226 .now()
11227 .unwrap_or(mongreldb_types::hlc::HlcTimestamp::MAX),
11228 _ => mongreldb_types::hlc::HlcTimestamp::MAX,
11229 },
11230 )),
11231 visible_through,
11232 }
11233 }
11234
11235 pub fn publish_read_generation(&mut self) -> Result<Arc<ReadGeneration>> {
11240 self.ensure_indexes_complete()?;
11241 self.seal_generations();
11242 let view = Arc::new(self.capture_read_generation());
11243 self.published.store(Arc::clone(&view));
11244 Ok(view)
11245 }
11246
11247 pub fn published_read_generation(&self) -> Arc<ReadGeneration> {
11253 self.published.load_full()
11254 }
11255
11256 pub fn pin_registry(&self) -> &Arc<crate::retention::PinRegistry> {
11258 &self.pins
11259 }
11260
11261 pub fn version_gc_floor(&self) -> Epoch {
11266 self.min_active_snapshot()
11267 .unwrap_or_else(|| self.current_epoch())
11268 }
11269
11270 pub fn version_pins_report(&self) -> crate::retention::PinsReport {
11277 let mut report = self.pins.report();
11278 let transaction_floor = [
11279 self.pinned.keys().next().copied(),
11280 self.snapshots.min_pinned(),
11281 ]
11282 .into_iter()
11283 .flatten()
11284 .min();
11285 if let Some(epoch) = transaction_floor {
11286 report.record_projection(crate::retention::PinSource::TransactionSnapshot, epoch);
11287 }
11288 if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11289 report.record_projection(crate::retention::PinSource::HistoryRetention, floor);
11290 }
11291 report
11292 }
11293
11294 pub(crate) fn clone_read_generation(&mut self) -> Result<Self> {
11295 self.publish_read_generation()?;
11296 let mut generation = self.clone();
11297 generation.read_only = true;
11298 generation.wal = WalSink::ReadOnly;
11299 generation.pending_delete_rids.clear();
11300 generation.pending_put_cols.clear();
11301 generation.pending_rows.clear();
11302 generation.pending_rows_auto_inc.clear();
11303 generation.pending_dels.clear();
11304 generation.pending_truncate = None;
11305 generation.agg_cache = Arc::new(HashMap::new());
11306 generation.published = Arc::new(ArcSwap::new(self.published.load_full()));
11309 generation.read_generation_pin = Some(Arc::new(self.pins.pin(
11312 crate::retention::PinSource::ReadGeneration,
11313 self.current_epoch(),
11314 )));
11315 Ok(generation)
11316 }
11317
11318 pub(crate) fn estimated_clone_bytes(&self) -> u64 {
11319 (std::mem::size_of::<Self>() as u64)
11320 .saturating_add(self.memtable.approx_bytes())
11321 .saturating_add(self.mutable_run.approx_bytes())
11322 .saturating_add(self.live_count.saturating_mul(64))
11323 }
11324
11325 pub fn pin_snapshot(&mut self) -> Snapshot {
11332 let snap = self.snapshot();
11333 *self.pinned.entry(snap.epoch).or_insert(0) += 1;
11334 snap
11335 }
11336
11337 fn active_pin_epochs_for_rebuild(&self) -> Vec<Epoch> {
11349 let mut set = BTreeSet::new();
11350 for epoch in self.pinned.keys().copied() {
11351 set.insert(epoch);
11352 }
11353 for epoch in self.snapshots.live_pinned_epochs() {
11354 set.insert(epoch);
11355 }
11356 for epoch in self.pins.live_pin_epochs() {
11357 set.insert(epoch);
11358 }
11359 if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11360 set.insert(floor);
11361 }
11362 set.into_iter().collect()
11363 }
11364
11365 pub fn hlc_gc_floor(
11375 &self,
11376 mut project_epoch: impl FnMut(Epoch) -> Option<mongreldb_types::hlc::HlcTimestamp>,
11377 ) -> crate::epoch::GcFloor {
11378 let mut project = |epoch: Option<Epoch>| -> mongreldb_types::hlc::HlcTimestamp {
11379 epoch
11380 .and_then(&mut project_epoch)
11381 .filter(|ts| *ts != mongreldb_types::hlc::HlcTimestamp::ZERO)
11382 .unwrap_or(mongreldb_types::hlc::HlcTimestamp::ZERO)
11383 };
11384 let transaction = [
11385 self.pinned.keys().next().copied(),
11386 self.snapshots.min_pinned(),
11387 ]
11388 .into_iter()
11389 .flatten()
11390 .min();
11391 let history = self.snapshots.history_floor(self.current_epoch());
11392 crate::epoch::GcFloor {
11393 transaction_snapshot: project(transaction),
11394 history_retention: project(history),
11395 backup_pitr: project(
11396 self.pins
11397 .oldest_for(crate::retention::PinSource::BackupPitr),
11398 ),
11399 replication: project(
11400 self.pins
11401 .oldest_for(crate::retention::PinSource::Replication),
11402 ),
11403 read_generation: project(
11404 self.pins
11405 .oldest_for(crate::retention::PinSource::ReadGeneration),
11406 ),
11407 online_index_build: project(
11408 self.pins
11409 .oldest_for(crate::retention::PinSource::OnlineIndexBuild),
11410 ),
11411 }
11412 }
11413
11414 pub fn unpin_snapshot(&mut self, snap: Snapshot) {
11416 if let Some(count) = self.pinned.get_mut(&snap.epoch) {
11417 *count -= 1;
11418 if *count == 0 {
11419 self.pinned.remove(&snap.epoch);
11420 }
11421 }
11422 }
11423
11424 pub(crate) fn min_active_snapshot(&self) -> Option<Epoch> {
11436 let local = self.pinned.keys().next().copied();
11437 let global = self.snapshots.min_pinned();
11438 let history = self.snapshots.history_floor(self.current_epoch());
11439 let pinned = self.pins.oldest_pinned();
11440 [local, global, history, pinned].into_iter().flatten().min()
11441 }
11442
11443 pub fn set_ttl(&mut self, column_name: &str, duration_nanos: u64) -> Result<()> {
11447 self.ensure_writable()?;
11448 let policy = self.prepare_ttl_policy(column_name, duration_nanos)?;
11449 self.apply_ttl_policy_at(Some(policy), self.current_epoch())
11450 }
11451
11452 pub fn clear_ttl(&mut self) -> Result<()> {
11453 self.ensure_writable()?;
11454 self.apply_ttl_policy_at(None, self.current_epoch())
11455 }
11456
11457 pub fn ttl(&self) -> Option<TtlPolicy> {
11458 self.ttl
11459 }
11460
11461 pub(crate) fn prepare_ttl_policy(
11462 &self,
11463 column_name: &str,
11464 duration_nanos: u64,
11465 ) -> Result<TtlPolicy> {
11466 if duration_nanos == 0 || duration_nanos > i64::MAX as u64 {
11467 return Err(MongrelError::InvalidArgument(
11468 "TTL duration must be between 1 and i64::MAX nanoseconds".into(),
11469 ));
11470 }
11471 let column = self
11472 .schema
11473 .columns
11474 .iter()
11475 .find(|column| column.name == column_name)
11476 .ok_or_else(|| MongrelError::Schema(format!("unknown TTL column {column_name}")))?;
11477 if column.ty != TypeId::TimestampNanos {
11478 return Err(MongrelError::Schema(format!(
11479 "TTL column {column_name} must be TimestampNanos, is {:?}",
11480 column.ty
11481 )));
11482 }
11483 Ok(TtlPolicy {
11484 column_id: column.id,
11485 duration_nanos,
11486 })
11487 }
11488
11489 pub(crate) fn apply_ttl_policy_at(
11490 &mut self,
11491 policy: Option<TtlPolicy>,
11492 epoch: Epoch,
11493 ) -> Result<()> {
11494 if let Some(policy) = policy {
11495 let column = self
11496 .schema
11497 .columns
11498 .iter()
11499 .find(|column| column.id == policy.column_id)
11500 .ok_or_else(|| {
11501 MongrelError::Schema(format!("unknown TTL column id {}", policy.column_id))
11502 })?;
11503 if column.ty != TypeId::TimestampNanos
11504 || policy.duration_nanos == 0
11505 || policy.duration_nanos > i64::MAX as u64
11506 {
11507 return Err(MongrelError::Schema("invalid TTL policy".into()));
11508 }
11509 }
11510 self.ttl = policy;
11511 self.agg_cache = Arc::new(HashMap::new());
11512 self.clear_result_cache();
11513 let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
11514 self.persist_manifest(epoch)
11515 }
11516
11517 pub(crate) fn row_expired_at(&self, row: &Row, now_nanos: i64) -> bool {
11518 let Some(policy) = self.ttl else {
11519 return false;
11520 };
11521 let Some(Value::Int64(timestamp)) = row.columns.get(&policy.column_id) else {
11522 return false;
11523 };
11524 timestamp.saturating_add(policy.duration_nanos as i64) <= now_nanos
11525 }
11526
11527 pub fn current_epoch(&self) -> Epoch {
11528 self.epoch.visible()
11529 }
11530
11531 pub fn memtable_len(&self) -> usize {
11532 self.memtable.len()
11533 }
11534
11535 pub fn count(&self) -> u64 {
11538 if self.ttl.is_none()
11539 && self.pending_put_cols.is_empty()
11540 && self.pending_delete_rids.is_empty()
11541 && self.pending_rows.is_empty()
11542 && self.pending_dels.is_empty()
11543 && self.pending_truncate.is_none()
11544 {
11545 self.live_count
11546 } else {
11547 self.visible_rows(self.snapshot())
11548 .map(|rows| rows.len() as u64)
11549 .unwrap_or(self.live_count)
11550 }
11551 }
11552
11553 pub fn count_conditions(
11557 &mut self,
11558 conditions: &[crate::query::Condition],
11559 snapshot: Snapshot,
11560 ) -> Result<Option<u64>> {
11561 use crate::query::Condition;
11562 if self.ttl.is_some() {
11563 if conditions.is_empty() {
11564 return Ok(Some(self.visible_rows(snapshot)?.len() as u64));
11565 }
11566 let mut sets = Vec::with_capacity(conditions.len());
11567 for condition in conditions {
11568 sets.push(self.resolve_condition(condition, snapshot)?);
11569 }
11570 let survivors = RowIdSet::intersect_many(sets);
11571 let rows = self.visible_rows(snapshot)?;
11572 return Ok(Some(
11573 rows.into_iter()
11574 .filter(|row| survivors.contains(row.row_id.0))
11575 .count() as u64,
11576 ));
11577 }
11578 if conditions.is_empty() {
11579 return Ok(Some(self.count()));
11580 }
11581 let served = |c: &Condition| {
11582 matches!(
11583 c,
11584 Condition::Pk(_)
11585 | Condition::BitmapEq { .. }
11586 | Condition::BitmapIn { .. }
11587 | Condition::BytesPrefix { .. }
11588 | Condition::FmContains { .. }
11589 | Condition::FmContainsAll { .. }
11590 | Condition::Ann { .. }
11591 | Condition::Range { .. }
11592 | Condition::RangeF64 { .. }
11593 | Condition::SparseMatch { .. }
11594 | Condition::MinHashSimilar { .. }
11595 | Condition::IsNull { .. }
11596 | Condition::IsNotNull { .. }
11597 )
11598 };
11599 if !conditions.iter().all(served) {
11600 return Ok(None);
11601 }
11602 self.ensure_indexes_complete()?;
11603 if !self.pending_put_cols.is_empty()
11604 || !self.pending_delete_rids.is_empty()
11605 || !self.pending_rows.is_empty()
11606 || !self.pending_dels.is_empty()
11607 || self.pending_truncate.is_some()
11608 {
11609 let mut sets = Vec::with_capacity(conditions.len());
11610 for condition in conditions {
11611 sets.push(self.resolve_condition(condition, snapshot)?);
11612 }
11613 let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
11614 return Ok(Some(self.rows_for_rids(&rids, snapshot)?.len() as u64));
11615 }
11616 let mut sets = Vec::with_capacity(conditions.len());
11617 for condition in conditions {
11618 sets.push(self.resolve_condition(condition, snapshot)?);
11619 }
11620 let rids = RowIdSet::intersect_many(sets);
11621 if self.had_deletes || !self.memtable.is_empty() || !self.mutable_run.is_empty() {
11629 let sorted = rids.into_sorted_vec();
11630 let count = self.rows_for_rids(&sorted, snapshot)?.len() as u64;
11631 crate::trace::QueryTrace::record(|t| {
11632 t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11633 t.survivor_count = Some(count as usize);
11634 t.conditions_pushed = conditions.len();
11635 });
11636 return Ok(Some(count));
11637 }
11638 let count = rids.len() as u64;
11639 crate::trace::QueryTrace::record(|t| {
11640 t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11641 t.survivor_count = Some(count as usize);
11642 t.conditions_pushed = conditions.len();
11643 });
11644 Ok(Some(count))
11645 }
11646
11647 fn overlay_tombstoned_rids(&self, snapshot: Snapshot) -> Vec<u64> {
11653 let mut out = Vec::new();
11654 for row in self.memtable.visible_versions_at(snapshot) {
11655 if row.deleted {
11656 out.push(row.row_id.0);
11657 }
11658 }
11659 for row in self.mutable_run.visible_versions_at(snapshot) {
11660 if row.deleted {
11661 out.push(row.row_id.0);
11662 }
11663 }
11664 out
11665 }
11666
11667 pub fn bulk_load_columns(
11676 &mut self,
11677 user_columns: Vec<(u16, columnar::NativeColumn)>,
11678 ) -> Result<Epoch> {
11679 self.bulk_load_columns_with(user_columns, 3, false, true)
11680 }
11681
11682 pub fn bulk_load_fast(
11689 &mut self,
11690 user_columns: Vec<(u16, columnar::NativeColumn)>,
11691 ) -> Result<Epoch> {
11692 self.bulk_load_columns_with(user_columns, -1, true, false)
11693 }
11694
11695 fn bulk_load_columns_with(
11696 &mut self,
11697 mut user_columns: Vec<(u16, columnar::NativeColumn)>,
11698 zstd_level: i32,
11699 force_plain: bool,
11700 lz4: bool,
11701 ) -> Result<Epoch> {
11702 self.ensure_writable()?;
11703 let n = user_columns.first().map(|(_, c)| c.len()).unwrap_or(0);
11704 if n == 0 {
11705 return Ok(self.current_epoch());
11706 }
11707 let epoch = self.commit_new_epoch()?;
11708 let live_before = self.live_count;
11709 self.spill_mutable_run(epoch)?;
11711 let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
11712 && self.indexes_complete
11713 && self.run_refs.is_empty()
11714 && self.memtable.is_empty()
11715 && self.mutable_run.is_empty();
11716 self.fill_auto_inc_native_columns(&mut user_columns, n)?;
11719 self.validate_columns_not_null(&user_columns, n)?;
11720 let winner_idx = self
11721 .bulk_pk_winner_indices(&user_columns, n)
11722 .filter(|idx| idx.len() != n);
11723 let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
11724 match winner_idx.as_deref() {
11725 Some(idx) => {
11726 let compacted = user_columns
11727 .iter()
11728 .map(|(id, c)| (*id, c.gather(idx)))
11729 .collect();
11730 (compacted, idx.len())
11731 }
11732 None => (user_columns, n),
11733 };
11734 self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
11735 let first = self.allocator.alloc_range(write_n as u64)?.0;
11736 for rid in first..first + write_n as u64 {
11737 self.reservoir.offer(rid);
11738 }
11739 let run_id = self.alloc_run_id()?;
11740 let path = self.run_path(run_id);
11741 let mut writer =
11742 RunWriter::new(&self.schema, run_id as u128, epoch, 0).with_native_endian();
11743 if force_plain {
11744 writer = writer.with_plain();
11745 } else if lz4 {
11746 writer = writer.with_lz4();
11749 } else {
11750 writer = writer.with_zstd_level(zstd_level);
11751 }
11752 if let Some(kek) = &self.kek {
11753 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
11754 }
11755 let header = match self.create_run_file(run_id)? {
11756 Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
11757 None => writer.write_native(&path, &write_columns, write_n, first)?,
11758 };
11759 self.run_refs.push(RunRef {
11760 run_id: run_id as u128,
11761 level: 0,
11762 epoch_created: epoch.0,
11763 row_count: header.row_count,
11764 });
11765 self.run_row_id_ranges
11766 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
11767 self.live_count = self.live_count.saturating_add(write_n as u64);
11768 if eager_index_build {
11769 let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
11770 self.index_columns_bulk(&write_columns, &row_ids);
11771 self.indexes_complete = true;
11772 self.build_learned_ranges()?;
11773 } else {
11774 self.indexes_complete = false;
11778 }
11779 self.mark_flushed(epoch)?;
11780 self.persist_manifest(epoch)?;
11781 if eager_index_build {
11782 self.checkpoint_indexes(epoch);
11783 }
11784 self.clear_result_cache();
11785 self.data_generation = self.data_generation.wrapping_add(1);
11786 Ok(epoch)
11787 }
11788
11789 fn index_columns_bulk(&mut self, columns: &[(u16, columnar::NativeColumn)], row_ids: &[u64]) {
11807 let n = row_ids.len();
11808 if n == 0 {
11809 return;
11810 }
11811 let by_id: std::collections::HashMap<u16, &columnar::NativeColumn> =
11812 columns.iter().map(|(id, c)| (*id, c)).collect();
11813 let ty_of: std::collections::HashMap<u16, TypeId> = self
11814 .schema
11815 .columns
11816 .iter()
11817 .map(|c| (c.id, c.ty.clone()))
11818 .collect();
11819 let pk_id = self.schema.primary_key().map(|c| c.id);
11820
11821 for (i, &rid) in row_ids.iter().enumerate() {
11822 let row_id = RowId(rid);
11823 if let Some(pid) = pk_id {
11824 if let Some(col) = by_id.get(&pid) {
11825 let ty = ty_of.get(&pid).cloned().unwrap_or(TypeId::Int64);
11826 if let Some(key) = bulk_index_key(&self.column_keys, pid, ty, col, i) {
11827 self.insert_hot_pk(key, row_id);
11828 }
11829 }
11830 }
11831 for idef in &self.schema.indexes {
11832 let Some(col) = by_id.get(&idef.column_id) else {
11833 continue;
11834 };
11835 let ty = ty_of.get(&idef.column_id).cloned().unwrap_or(TypeId::Int64);
11836 match idef.kind {
11837 IndexKind::Bitmap => {
11838 if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
11839 if let Some(key) =
11840 bulk_index_key(&self.column_keys, idef.column_id, ty, col, i)
11841 {
11842 b.insert(key, row_id);
11843 }
11844 }
11845 }
11846 IndexKind::FmIndex => {
11847 if let Some(f) = self.fm.get_mut(&idef.column_id) {
11848 if let Some(bytes) = columnar::native_bytes_at(col, i) {
11849 f.insert(bytes.to_vec(), row_id);
11850 }
11851 }
11852 }
11853 IndexKind::Sparse => {
11854 if let Some(s) = self.sparse.get_mut(&idef.column_id) {
11855 if let Some(bytes) = columnar::native_bytes_at(col, i) {
11856 if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(bytes) {
11857 s.insert(&terms, row_id);
11858 }
11859 }
11860 }
11861 }
11862 IndexKind::MinHash => {
11863 if let Some(mh) = self.minhash.get_mut(&idef.column_id) {
11864 if let Some(bytes) = columnar::native_bytes_at(col, i) {
11865 let tokens = crate::index::token_hashes_from_bytes(bytes);
11866 mh.insert(&tokens, row_id);
11867 }
11868 }
11869 }
11870 _ => {}
11871 }
11872 }
11873 }
11874 }
11875
11876 pub fn visible_columns_native(
11881 &self,
11882 snapshot: Snapshot,
11883 projection: Option<&[u16]>,
11884 ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11885 self.visible_columns_native_inner(snapshot, projection, None)
11886 }
11887
11888 pub fn visible_columns_native_with_control(
11889 &self,
11890 snapshot: Snapshot,
11891 projection: Option<&[u16]>,
11892 control: &crate::ExecutionControl,
11893 ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11894 self.visible_columns_native_inner(snapshot, projection, Some(control))
11895 }
11896
11897 fn visible_columns_native_inner(
11898 &self,
11899 snapshot: Snapshot,
11900 projection: Option<&[u16]>,
11901 control: Option<&crate::ExecutionControl>,
11902 ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11903 execution_checkpoint(control, 0)?;
11904 let wanted: Vec<u16> = match projection {
11905 Some(p) => p.to_vec(),
11906 None => self.schema.columns.iter().map(|c| c.id).collect(),
11907 };
11908 if self.ttl.is_none()
11909 && self.memtable.is_empty()
11910 && self.mutable_run.is_empty()
11911 && self.run_refs.len() == 1
11912 {
11913 let rr = self.run_refs[0].clone();
11914 let mut reader = self.open_reader(rr.run_id)?;
11915 let idxs = reader.visible_indices_native_at(snapshot)?;
11916 execution_checkpoint(control, 0)?;
11917 let all_visible = idxs.len() == reader.row_count();
11918 if reader.has_mmap() && control.is_none() {
11924 use rayon::prelude::*;
11925 let valid: Vec<u16> = wanted
11928 .iter()
11929 .filter(|cid| self.schema.columns.iter().any(|c| c.id == **cid))
11930 .copied()
11931 .collect();
11932 let decoded: Vec<(u16, columnar::NativeColumn)> = valid
11934 .par_iter()
11935 .filter_map(|cid| {
11936 reader
11937 .column_native_shared(*cid)
11938 .ok()
11939 .map(|col| (*cid, col))
11940 })
11941 .collect();
11942 let cols = decoded
11943 .into_iter()
11944 .map(|(id, col)| (id, if all_visible { col } else { col.gather(&idxs) }))
11945 .collect();
11946 return Ok(cols);
11947 }
11948 let mut cols = Vec::with_capacity(wanted.len());
11949 for (index, cid) in wanted.iter().enumerate() {
11950 execution_checkpoint(control, index)?;
11951 let cdef = match self.schema.columns.iter().find(|c| c.id == *cid) {
11952 Some(c) => c,
11953 None => continue,
11954 };
11955 let col = reader.column_native(cdef.id)?;
11956 cols.push((cdef.id, if all_visible { col } else { col.gather(&idxs) }));
11957 }
11958 return Ok(cols);
11959 }
11960 let vcols = self.visible_columns(snapshot)?;
11961 execution_checkpoint(control, 0)?;
11962 let want_set: std::collections::HashSet<u16> = wanted.iter().copied().collect();
11963 let out: Vec<(u16, columnar::NativeColumn)> = vcols
11964 .into_iter()
11965 .filter(|(id, _)| want_set.contains(id))
11966 .map(|(id, vals)| {
11967 let ty = self
11968 .schema
11969 .columns
11970 .iter()
11971 .find(|c| c.id == id)
11972 .map(|c| c.ty.clone())
11973 .unwrap_or(TypeId::Bytes);
11974 (id, columnar::values_to_native(ty, &vals))
11975 })
11976 .collect();
11977 Ok(out)
11978 }
11979
11980 pub fn run_count(&self) -> usize {
11981 self.run_refs.len()
11982 }
11983
11984 pub fn memtable_is_empty(&self) -> bool {
11986 self.memtable.is_empty()
11987 }
11988
11989 pub fn page_cache_stats(&self) -> crate::cache::CacheStats {
11993 self.page_cache.stats()
11994 }
11995
11996 pub fn reset_page_cache_stats(&self) {
11998 self.page_cache.reset_stats();
11999 }
12000
12001 pub fn run_ids(&self) -> Vec<u128> {
12004 self.run_refs.iter().map(|r| r.run_id).collect()
12005 }
12006
12007 pub fn single_run_is_clean(&self) -> bool {
12011 if self.ttl.is_some() || self.run_refs.len() != 1 {
12012 return false;
12013 }
12014 self.open_reader(self.run_refs[0].run_id)
12015 .map(|r| r.is_clean())
12016 .unwrap_or(false)
12017 }
12018
12019 fn resolve_footprint(
12026 &self,
12027 conditions: &[crate::query::Condition],
12028 snapshot: Snapshot,
12029 ) -> roaring::RoaringBitmap {
12030 if !self.memtable.is_empty() || !self.mutable_run.is_empty() {
12031 return roaring::RoaringBitmap::new();
12032 }
12033 if self.run_refs.is_empty() {
12034 return roaring::RoaringBitmap::new();
12035 }
12036 if self.run_refs.len() == 1 {
12038 if let Ok(mut reader) = self.open_reader(self.run_refs[0].run_id) {
12039 if let Ok(rids) = self.resolve_survivor_rids(conditions, &mut reader, snapshot) {
12040 return rids.to_roaring_lossy();
12041 }
12042 }
12043 }
12044 roaring::RoaringBitmap::new()
12045 }
12046
12047 pub fn query_columns_native_cached(
12058 &mut self,
12059 conditions: &[crate::query::Condition],
12060 projection: Option<&[u16]>,
12061 snapshot: Snapshot,
12062 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12063 self.query_columns_native_cached_inner(conditions, projection, snapshot, None)
12064 }
12065
12066 pub fn query_columns_native_cached_with_control(
12067 &mut self,
12068 conditions: &[crate::query::Condition],
12069 projection: Option<&[u16]>,
12070 snapshot: Snapshot,
12071 control: &crate::ExecutionControl,
12072 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12073 self.query_columns_native_cached_inner(conditions, projection, snapshot, Some(control))
12074 }
12075
12076 fn query_columns_native_cached_inner(
12077 &mut self,
12078 conditions: &[crate::query::Condition],
12079 projection: Option<&[u16]>,
12080 snapshot: Snapshot,
12081 control: Option<&crate::ExecutionControl>,
12082 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12083 execution_checkpoint(control, 0)?;
12084 if self.ttl.is_some() {
12087 return self.query_columns_native_inner(conditions, projection, snapshot, control);
12088 }
12089 if conditions.is_empty() {
12090 return self.query_columns_native_inner(conditions, projection, snapshot, control);
12091 }
12092 let key = crate::query::canonical_query_key(conditions, projection, snapshot.epoch.0);
12096 let identity = PersistentCacheIdentity {
12097 table_id: self.table_id(),
12098 schema_id: self.schema.schema_id,
12099 logical_generation: self.current_epoch().0,
12100 };
12101 if let Some(hit) = self.result_cache.lock().get_columns(key, identity) {
12102 crate::trace::QueryTrace::record(|t| {
12103 t.result_cache_hit = true;
12104 t.scan_mode = crate::trace::ScanMode::NativePushdown;
12105 });
12106 return Ok(Some((*hit).clone()));
12107 }
12108 let res = self.query_columns_native_inner(conditions, projection, snapshot, control)?;
12109 execution_checkpoint(control, 0)?;
12110 if let Some(cols) = &res {
12111 let footprint = self.resolve_footprint(conditions, snapshot);
12112 let condition_cols = crate::query::condition_columns(conditions);
12113 execution_checkpoint(control, 0)?;
12114 let entry = CachedEntry {
12115 data: CachedData::Columns(Arc::new(cols.clone())),
12116 footprint,
12117 condition_cols,
12118 };
12119 let mut cache = self.result_cache.lock();
12125 let entry_generation = cache.allocate_persist_generation(key);
12126 let context = PersistContext {
12127 identity,
12128 key,
12129 entry_generation,
12130 };
12131 cache.persist_entry(context, &entry);
12132 cache.insert(key, entry);
12133 }
12134 Ok(res)
12135 }
12136
12137 pub fn query_cached(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
12142 if self.ttl.is_some() {
12143 return self.query(q);
12144 }
12145 if q.conditions.is_empty() {
12146 return self.query(q);
12147 }
12148 let key = crate::query::canonical_query_key(&q.conditions, None, 0)
12149 ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
12150 ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
12151 let identity = PersistentCacheIdentity {
12152 table_id: self.table_id(),
12153 schema_id: self.schema.schema_id,
12154 logical_generation: self.current_epoch().0,
12155 };
12156 if let Some(hit) = self.result_cache.lock().get_rows(key, identity) {
12157 crate::trace::QueryTrace::record(|t| {
12158 t.result_cache_hit = true;
12159 t.scan_mode = crate::trace::ScanMode::Materialized;
12160 });
12161 return Ok((*hit).clone());
12162 }
12163 let rows = self.query(q)?;
12164 let footprint = rows.iter().map(|r| r.row_id.0 as u32).collect();
12165 let condition_cols = crate::query::condition_columns(&q.conditions);
12166 let entry = CachedEntry {
12167 data: CachedData::Rows(Arc::new(rows.clone())),
12168 footprint,
12169 condition_cols,
12170 };
12171 let mut cache = self.result_cache.lock();
12176 let entry_generation = cache.allocate_persist_generation(key);
12177 let context = PersistContext {
12178 identity,
12179 key,
12180 entry_generation,
12181 };
12182 cache.persist_entry(context, &entry);
12183 cache.insert(key, entry);
12184 Ok(rows)
12185 }
12186
12187 #[allow(clippy::type_complexity)]
12202 pub fn query_columns_native_traced(
12203 &mut self,
12204 conditions: &[crate::query::Condition],
12205 projection: Option<&[u16]>,
12206 snapshot: Snapshot,
12207 ) -> Result<(
12208 Option<Vec<(u16, columnar::NativeColumn)>>,
12209 crate::trace::QueryTrace,
12210 )> {
12211 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12212 self.query_columns_native(conditions, projection, snapshot)
12213 });
12214 Ok((result?, trace))
12215 }
12216
12217 #[allow(clippy::type_complexity)]
12220 pub fn query_columns_native_cached_traced(
12221 &mut self,
12222 conditions: &[crate::query::Condition],
12223 projection: Option<&[u16]>,
12224 snapshot: Snapshot,
12225 ) -> Result<(
12226 Option<Vec<(u16, columnar::NativeColumn)>>,
12227 crate::trace::QueryTrace,
12228 )> {
12229 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12230 self.query_columns_native_cached(conditions, projection, snapshot)
12231 });
12232 Ok((result?, trace))
12233 }
12234
12235 pub fn native_page_cursor_traced(
12237 &self,
12238 snapshot: Snapshot,
12239 projection: Vec<(u16, TypeId)>,
12240 conditions: &[crate::query::Condition],
12241 ) -> Result<(Option<NativePageCursor>, crate::trace::QueryTrace)> {
12242 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12243 self.native_page_cursor(snapshot, projection, conditions)
12244 });
12245 Ok((result?, trace))
12246 }
12247
12248 pub fn native_multi_run_cursor_traced(
12250 &self,
12251 snapshot: Snapshot,
12252 projection: Vec<(u16, TypeId)>,
12253 conditions: &[crate::query::Condition],
12254 ) -> Result<(
12255 Option<crate::cursor::MultiRunCursor>,
12256 crate::trace::QueryTrace,
12257 )> {
12258 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12259 self.native_multi_run_cursor(snapshot, projection, conditions)
12260 });
12261 Ok((result?, trace))
12262 }
12263
12264 pub fn count_conditions_traced(
12266 &mut self,
12267 conditions: &[crate::query::Condition],
12268 snapshot: Snapshot,
12269 ) -> Result<(Option<u64>, crate::trace::QueryTrace)> {
12270 let (result, trace) =
12271 crate::trace::QueryTrace::capture(|| self.count_conditions(conditions, snapshot));
12272 Ok((result?, trace))
12273 }
12274
12275 pub fn query_traced(
12277 &mut self,
12278 q: &crate::query::Query,
12279 ) -> Result<(Vec<Row>, crate::trace::QueryTrace)> {
12280 let (result, trace) = crate::trace::QueryTrace::capture(|| self.query(q));
12281 Ok((result?, trace))
12282 }
12283
12284 pub fn query_columns_native(
12289 &mut self,
12290 conditions: &[crate::query::Condition],
12291 projection: Option<&[u16]>,
12292 snapshot: Snapshot,
12293 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12294 self.query_columns_native_inner(conditions, projection, snapshot, None)
12295 }
12296
12297 pub fn query_columns_native_with_control(
12298 &mut self,
12299 conditions: &[crate::query::Condition],
12300 projection: Option<&[u16]>,
12301 snapshot: Snapshot,
12302 control: &crate::ExecutionControl,
12303 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12304 self.query_columns_native_inner(conditions, projection, snapshot, Some(control))
12305 }
12306
12307 fn query_columns_native_inner(
12308 &mut self,
12309 conditions: &[crate::query::Condition],
12310 projection: Option<&[u16]>,
12311 snapshot: Snapshot,
12312 control: Option<&crate::ExecutionControl>,
12313 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12314 use crate::query::Condition;
12315 execution_checkpoint(control, 0)?;
12316 if self.ttl.is_some() {
12319 return Ok(None);
12320 }
12321 if conditions.is_empty() {
12322 return Ok(None);
12323 }
12324 self.ensure_indexes_complete()?;
12325
12326 let served = |c: &Condition| {
12331 matches!(
12332 c,
12333 Condition::Pk(_)
12334 | Condition::BitmapEq { .. }
12335 | Condition::BitmapIn { .. }
12336 | Condition::BytesPrefix { .. }
12337 | Condition::FmContains { .. }
12338 | Condition::FmContainsAll { .. }
12339 | Condition::Ann { .. }
12340 | Condition::Range { .. }
12341 | Condition::RangeF64 { .. }
12342 | Condition::SparseMatch { .. }
12343 | Condition::MinHashSimilar { .. }
12344 | Condition::IsNull { .. }
12345 | Condition::IsNotNull { .. }
12346 )
12347 };
12348 if !conditions.iter().all(served) {
12349 return Ok(None);
12350 }
12351 let fast_path =
12352 self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
12353 crate::trace::QueryTrace::record(|t| {
12354 t.run_count = self.run_refs.len();
12355 t.memtable_rows = self.memtable.len();
12356 t.mutable_run_rows = self.mutable_run.len();
12357 t.conditions_pushed = conditions.len();
12358 t.learned_range_used = conditions.iter().any(|c| match c {
12359 Condition::Range { column_id, .. } | Condition::RangeF64 { column_id, .. } => {
12360 self.learned_range.contains_key(column_id)
12361 }
12362 _ => false,
12363 });
12364 });
12365 let col_ids: Vec<u16> = projection
12367 .map(|p| p.to_vec())
12368 .unwrap_or_else(|| self.schema.columns.iter().map(|c| c.id).collect());
12369 let proj_pairs: Vec<(u16, TypeId)> = col_ids
12370 .iter()
12371 .map(|&cid| {
12372 let ty = self
12373 .schema
12374 .columns
12375 .iter()
12376 .find(|c| c.id == cid)
12377 .map(|c| c.ty.clone())
12378 .unwrap_or(TypeId::Bytes);
12379 (cid, ty)
12380 })
12381 .collect();
12382
12383 if fast_path {
12389 let needs_column = conditions.iter().any(|c| match c {
12392 Condition::Range { column_id, .. } => !self.learned_range.contains_key(column_id),
12393 Condition::RangeF64 { column_id, .. } => {
12394 !self.learned_range.contains_key(column_id)
12395 }
12396 _ => false,
12397 });
12398 let mut reader_opt: Option<RunReader> = if needs_column {
12399 Some(self.open_reader(self.run_refs[0].run_id)?)
12400 } else {
12401 None
12402 };
12403 let mut sets: Vec<RowIdSet> = Vec::new();
12404 for (index, c) in conditions.iter().enumerate() {
12405 execution_checkpoint(control, index)?;
12406 let s = match c {
12407 Condition::Range { column_id, lo, hi }
12408 if !self.learned_range.contains_key(column_id) =>
12409 {
12410 if reader_opt.is_none() {
12411 reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12412 }
12413 reader_opt
12414 .as_mut()
12415 .expect("reader opened for range")
12416 .range_row_id_set_i64(*column_id, *lo, *hi)?
12417 }
12418 Condition::RangeF64 {
12419 column_id,
12420 lo,
12421 lo_inclusive,
12422 hi,
12423 hi_inclusive,
12424 } if !self.learned_range.contains_key(column_id) => {
12425 if reader_opt.is_none() {
12426 reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12427 }
12428 reader_opt
12429 .as_mut()
12430 .expect("reader opened for range")
12431 .range_row_id_set_f64(
12432 *column_id,
12433 *lo,
12434 *lo_inclusive,
12435 *hi,
12436 *hi_inclusive,
12437 )?
12438 }
12439 _ => self.resolve_condition(c, snapshot)?,
12440 };
12441 sets.push(s);
12442 }
12443 let candidates = RowIdSet::intersect_many(sets);
12444 crate::trace::QueryTrace::record(|t| {
12445 t.survivor_count = Some(candidates.len());
12446 });
12447 if candidates.is_empty() {
12448 let cols: Vec<(u16, columnar::NativeColumn)> = col_ids
12449 .iter()
12450 .map(|&id| {
12451 (
12452 id,
12453 columnar::null_native(
12454 proj_pairs
12455 .iter()
12456 .find(|(c, _)| c == &id)
12457 .map(|(_, t)| t.clone())
12458 .unwrap_or(TypeId::Bytes),
12459 0,
12460 ),
12461 )
12462 })
12463 .collect();
12464 return Ok(Some(cols));
12465 }
12466 let mut reader = match reader_opt.take() {
12467 Some(r) => r,
12468 None => self.open_reader(self.run_refs[0].run_id)?,
12469 };
12470 let candidate_ids = candidates.into_sorted_vec();
12471 let (positions, fast_rid) = if let Some(positions) =
12472 reader.positions_for_row_ids_fast(&candidate_ids)
12473 {
12474 (positions, true)
12475 } else {
12476 let col = reader.column_native(crate::sorted_run::SYS_ROW_ID)?;
12477 match col {
12478 columnar::NativeColumn::Int64 { data, .. } => {
12479 let mut p = Vec::with_capacity(candidate_ids.len());
12480 for (index, rid) in candidate_ids.iter().enumerate() {
12481 execution_checkpoint(control, index)?;
12482 if let Ok(position) = data.binary_search(&(*rid as i64)) {
12483 p.push(position);
12484 }
12485 }
12486 p.sort_unstable();
12487 (p, false)
12488 }
12489 _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
12490 }
12491 };
12492 crate::trace::QueryTrace::record(|t| {
12493 t.scan_mode = crate::trace::ScanMode::NativePushdown;
12494 t.fast_row_id_map = fast_rid;
12495 });
12496 let mut cols = Vec::with_capacity(col_ids.len());
12497 for (index, cid) in col_ids.iter().enumerate() {
12498 execution_checkpoint(control, index)?;
12499 let col = reader.column_native(*cid)?;
12500 cols.push((*cid, col.gather(&positions)));
12501 }
12502 return Ok(Some(cols));
12503 }
12504
12505 if !self.run_refs.is_empty() {
12518 use crate::cursor::{
12519 drain_cursor_to_columns, drain_cursor_to_columns_with_control, Cursor,
12520 };
12521 let remaining: usize;
12522 let mut cursor: Box<dyn crate::cursor::Cursor> = if self.run_refs.len() == 1 {
12523 let c = self
12524 .native_page_cursor(snapshot, proj_pairs.clone(), conditions)?
12525 .expect("single-run cursor should build when run_refs.len() == 1");
12526 remaining = c.remaining_rows();
12527 Box::new(c)
12528 } else {
12529 let c = self
12530 .native_multi_run_cursor(snapshot, proj_pairs.clone(), conditions)?
12531 .expect("multi-run cursor should build when run_refs.len() >= 1");
12532 remaining = c.remaining_rows();
12533 Box::new(c)
12534 };
12535 crate::trace::QueryTrace::record(|t| {
12536 if t.survivor_count.is_none() {
12537 t.survivor_count = Some(remaining);
12538 }
12539 });
12540 let cols = match control {
12541 Some(control) => {
12542 drain_cursor_to_columns_with_control(cursor.as_mut(), &proj_pairs, control)?
12543 }
12544 None => drain_cursor_to_columns(cursor.as_mut(), &proj_pairs)?,
12545 };
12546 return Ok(Some(cols));
12547 }
12548
12549 crate::trace::QueryTrace::record(|t| {
12554 t.scan_mode = crate::trace::ScanMode::Materialized;
12555 t.row_materialized = true;
12556 });
12557 let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12558 for (index, c) in conditions.iter().enumerate() {
12559 execution_checkpoint(control, index)?;
12560 sets.push(self.resolve_condition(c, snapshot)?);
12561 }
12562 let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
12563 let rows = self.rows_for_rids(&rids, snapshot)?;
12564 let mut cols: Vec<(u16, columnar::NativeColumn)> = Vec::with_capacity(col_ids.len());
12565 for (index, (cid, ty)) in proj_pairs.iter().enumerate() {
12566 execution_checkpoint(control, index)?;
12567 let vals: Vec<Value> = rows
12568 .iter()
12569 .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
12570 .collect();
12571 cols.push((*cid, columnar::values_to_native(ty.clone(), &vals)));
12572 }
12573 Ok(Some(cols))
12574 }
12575
12576 pub fn native_page_cursor(
12591 &self,
12592 snapshot: Snapshot,
12593 projection: Vec<(u16, TypeId)>,
12594 conditions: &[crate::query::Condition],
12595 ) -> Result<Option<NativePageCursor>> {
12596 use crate::cursor::build_page_plans;
12597 if self.ttl.is_some() {
12598 return Ok(None);
12599 }
12600 if !conditions.is_empty() && !self.indexes_complete {
12603 return Ok(None);
12604 }
12605 if self.run_refs.len() != 1 {
12606 return Ok(None);
12607 }
12608 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
12609 let (positions, rids) = reader.visible_positions_with_rids_at(snapshot)?;
12610
12611 let overlay_rids: HashSet<u64> = {
12614 let mut s = HashSet::new();
12615 for row in self.memtable.visible_versions_at(snapshot) {
12616 s.insert(row.row_id.0);
12617 }
12618 for row in self.mutable_run.visible_versions_at(snapshot) {
12619 s.insert(row.row_id.0);
12620 }
12621 s
12622 };
12623
12624 let survivors = if conditions.is_empty() {
12628 None
12629 } else {
12630 Some(self.resolve_survivor_rids(conditions, &mut reader, snapshot)?)
12631 };
12632
12633 let run_survivors: Option<RowIdSet> = if overlay_rids.is_empty() {
12640 survivors.clone()
12641 } else if let Some(s) = &survivors {
12642 let mut run_set = s.clone();
12643 run_set.remove_many(overlay_rids.iter().copied());
12644 Some(run_set)
12645 } else {
12646 Some(RowIdSet::from_unsorted(
12647 rids.iter()
12648 .map(|&r| r as u64)
12649 .filter(|r| !overlay_rids.contains(r))
12650 .collect(),
12651 ))
12652 };
12653
12654 let overlay_rows = if overlay_rids.is_empty() {
12655 Vec::new()
12656 } else {
12657 let bound = Self::overlay_materialization_bound(conditions, &survivors);
12658 self.overlay_visible_rows(snapshot, bound)
12659 };
12660
12661 let plans = if positions.is_empty() {
12663 Vec::new()
12664 } else {
12665 let page_rows = reader.page_row_counts(crate::sorted_run::SYS_ROW_ID)?;
12666 build_page_plans(&positions, &rids, &page_rows, run_survivors.as_ref())
12667 };
12668
12669 let overlay = if overlay_rows.is_empty() {
12671 None
12672 } else {
12673 let filtered =
12674 self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12675 if filtered.is_empty() {
12676 None
12677 } else {
12678 Some(self.materialize_overlay(&filtered, &projection))
12679 }
12680 };
12681
12682 let overlay_row_count = overlay
12683 .as_ref()
12684 .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12685 .unwrap_or(0);
12686 crate::trace::QueryTrace::record(|t| {
12687 t.scan_mode = crate::trace::ScanMode::NativePageCursor;
12688 t.run_count = self.run_refs.len();
12689 t.memtable_rows = self.memtable.len();
12690 t.mutable_run_rows = self.mutable_run.len();
12691 t.overlay_rows = overlay_row_count;
12692 t.conditions_pushed = conditions.len();
12693 t.pages_decoded = plans
12694 .iter()
12695 .map(|p| p.positions.len())
12696 .sum::<usize>()
12697 .min(1);
12698 });
12699
12700 Ok(Some(NativePageCursor::new_with_overlay(
12701 reader, projection, plans, overlay,
12702 )))
12703 }
12704 #[allow(clippy::type_complexity)]
12714 pub fn native_multi_run_cursor(
12715 &self,
12716 snapshot: Snapshot,
12717 projection: Vec<(u16, TypeId)>,
12718 conditions: &[crate::query::Condition],
12719 ) -> Result<Option<crate::cursor::MultiRunCursor>> {
12720 use crate::cursor::{MultiRunCursor, RunStream};
12721 use crate::sorted_run::SYS_ROW_ID;
12722 use std::collections::{BinaryHeap, HashMap, HashSet};
12723 if self.ttl.is_some() {
12724 return Ok(None);
12725 }
12726 if !conditions.is_empty() && !self.indexes_complete {
12729 return Ok(None);
12730 }
12731 if self.run_refs.is_empty() {
12732 return Ok(None);
12733 }
12734
12735 let mut run_meta: Vec<(
12737 RunReader,
12738 Vec<i64>,
12739 Vec<i64>,
12740 Vec<u8>,
12741 Option<Vec<Option<HlcTimestamp>>>,
12742 Vec<usize>,
12743 )> = Vec::with_capacity(self.run_refs.len());
12744 for rr in &self.run_refs {
12745 let mut reader = self.open_reader(rr.run_id)?;
12746 let (rids, eps, del) = reader.system_columns_native()?;
12747 let page_rows = reader.page_row_counts(SYS_ROW_ID)?;
12748 let commit_ts: Option<Vec<Option<HlcTimestamp>>> =
12749 if reader.has_column(crate::sorted_run::SYS_COMMIT_TS) {
12750 let col = reader.column_native(crate::sorted_run::SYS_COMMIT_TS)?;
12751 Some(
12752 (0..rids.len())
12753 .map(|i| {
12754 crate::sorted_run::decode_commit_ts_value(col.value_at(i).as_ref())
12755 })
12756 .collect(),
12757 )
12758 } else {
12759 None
12760 };
12761 run_meta.push((reader, rids, eps, del, commit_ts, page_rows));
12762 }
12763
12764 let mut best: HashMap<u64, (Epoch, Option<HlcTimestamp>, usize, usize, bool)> =
12770 HashMap::new();
12771 for (run_idx, (_, rids, eps, del, commit_ts, _)) in run_meta.iter().enumerate() {
12772 for i in 0..rids.len() {
12773 let rid = rids[i] as u64;
12774 let e = Epoch(eps[i] as u64);
12775 let ts = commit_ts.as_ref().and_then(|v| v.get(i).copied().flatten());
12776 if !snapshot.observes_row(e, ts) {
12777 continue;
12778 }
12779 let is_del = del[i] != 0;
12780 best.entry(rid)
12781 .and_modify(|cur| {
12782 if Snapshot::version_is_newer(e, ts, cur.0, cur.1) {
12783 *cur = (e, ts, run_idx, i, is_del);
12784 }
12785 })
12786 .or_insert((e, ts, run_idx, i, is_del));
12787 }
12788 }
12789
12790 let overlay_rids: HashSet<u64> = {
12792 let mut s = HashSet::new();
12793 for row in self.memtable.visible_versions_at(snapshot) {
12794 s.insert(row.row_id.0);
12795 }
12796 for row in self.mutable_run.visible_versions_at(snapshot) {
12797 s.insert(row.row_id.0);
12798 }
12799 s
12800 };
12801
12802 let survivors: Option<RowIdSet> = if conditions.is_empty() {
12804 None
12805 } else {
12806 let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12807 for c in conditions {
12808 sets.push(self.resolve_condition(c, snapshot)?);
12809 }
12810 Some(RowIdSet::intersect_many(sets))
12811 };
12812
12813 let mut per_run: Vec<Vec<(u64, usize)>> = vec![Vec::new(); run_meta.len()];
12817 for (rid, (_, _, run_idx, pos, deleted)) in &best {
12818 if *deleted {
12819 continue;
12820 }
12821 if overlay_rids.contains(rid) {
12822 continue;
12823 }
12824 if let Some(s) = &survivors {
12825 if !s.contains(*rid) {
12826 continue;
12827 }
12828 }
12829 per_run[*run_idx].push((*rid, *pos));
12830 }
12831 for v in per_run.iter_mut() {
12832 v.sort_unstable_by_key(|&(rid, _)| rid);
12833 }
12834
12835 let mut streams = Vec::with_capacity(run_meta.len());
12837 let mut heap: BinaryHeap<std::cmp::Reverse<(u64, usize)>> = BinaryHeap::new();
12838 let mut total = 0usize;
12839 for (run_idx, (reader, _, _, _, _, page_rows)) in run_meta.into_iter().enumerate() {
12840 let mut starts = Vec::with_capacity(page_rows.len());
12841 let mut acc = 0usize;
12842 for &r in &page_rows {
12843 starts.push(acc);
12844 acc += r;
12845 }
12846 let mut survivors_vec: Vec<(u64, usize, usize)> =
12847 Vec::with_capacity(per_run[run_idx].len());
12848 for &(rid, pos) in &per_run[run_idx] {
12849 let page_seq = match starts.partition_point(|&s| s <= pos) {
12850 0 => continue,
12851 p => p - 1,
12852 };
12853 let within = pos - starts[page_seq];
12854 survivors_vec.push((rid, page_seq, within));
12855 }
12856 total += survivors_vec.len();
12857 if let Some(&(rid, _, _)) = survivors_vec.first() {
12858 heap.push(std::cmp::Reverse((rid, run_idx)));
12859 }
12860 streams.push(RunStream::new(reader, survivors_vec, page_rows));
12861 }
12862
12863 let overlay_rows = if overlay_rids.is_empty() {
12865 Vec::new()
12866 } else {
12867 let bound = Self::overlay_materialization_bound(conditions, &survivors);
12868 self.overlay_visible_rows(snapshot, bound)
12869 };
12870 let overlay = if overlay_rows.is_empty() {
12871 None
12872 } else {
12873 let filtered =
12874 self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12875 if filtered.is_empty() {
12876 None
12877 } else {
12878 Some(self.materialize_overlay(&filtered, &projection))
12879 }
12880 };
12881
12882 let overlay_row_count = overlay
12883 .as_ref()
12884 .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12885 .unwrap_or(0);
12886 crate::trace::QueryTrace::record(|t| {
12887 t.scan_mode = crate::trace::ScanMode::MultiRunCursor;
12888 t.run_count = self.run_refs.len();
12889 t.memtable_rows = self.memtable.len();
12890 t.mutable_run_rows = self.mutable_run.len();
12891 t.overlay_rows = overlay_row_count;
12892 t.conditions_pushed = conditions.len();
12893 t.survivor_count = Some(total);
12894 });
12895
12896 Ok(Some(MultiRunCursor::new(
12897 streams, projection, heap, total, overlay,
12898 )))
12899 }
12900
12901 fn overlay_materialization_bound<'a>(
12913 conditions: &[crate::query::Condition],
12914 survivors: &'a Option<RowIdSet>,
12915 ) -> Option<&'a RowIdSet> {
12916 use crate::query::Condition;
12917 let has_range = conditions
12918 .iter()
12919 .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12920 if has_range {
12921 None
12922 } else {
12923 survivors.as_ref()
12924 }
12925 }
12926
12927 fn overlay_visible_rows(&self, snapshot: Snapshot, bound: Option<&RowIdSet>) -> Vec<Row> {
12939 let mut best: HashMap<u64, (Epoch, Row)> = HashMap::new();
12940 let mut fold = |row: Row| {
12941 if let Some(b) = bound {
12942 if !b.contains(row.row_id.0) {
12943 return;
12944 }
12945 }
12946 best.entry(row.row_id.0)
12947 .and_modify(|(be, br)| {
12948 if row.committed_epoch > *be {
12949 *be = row.committed_epoch;
12950 *br = row.clone();
12951 }
12952 })
12953 .or_insert_with(|| (row.committed_epoch, row));
12954 };
12955 for row in self.memtable.visible_versions_at(snapshot) {
12956 fold(row);
12957 }
12958 for row in self.mutable_run.visible_versions_at(snapshot) {
12959 fold(row);
12960 }
12961 let mut out: Vec<Row> = best
12962 .into_values()
12963 .filter_map(|(_, r)| if r.deleted { None } else { Some(r) })
12964 .collect();
12965 out.sort_by_key(|r| r.row_id);
12966 out
12967 }
12968
12969 fn filter_overlay_rows(
12977 &self,
12978 rows: Vec<Row>,
12979 conditions: &[crate::query::Condition],
12980 survivors: Option<&RowIdSet>,
12981 snapshot: Snapshot,
12982 ) -> Result<Vec<Row>> {
12983 if conditions.is_empty() {
12984 return Ok(rows);
12985 }
12986 use crate::query::Condition;
12987 let all_index_served = !conditions
12991 .iter()
12992 .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12993 if all_index_served {
12994 return Ok(rows
12995 .into_iter()
12996 .filter(|r| survivors.is_none_or(|s| s.contains(r.row_id.0)))
12997 .collect());
12998 }
12999 let mut per_cond_sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
13002 for c in conditions {
13003 let s = match c {
13004 Condition::Range { .. } | Condition::RangeF64 { .. } => RowIdSet::empty(),
13005 _ => self.resolve_condition(c, snapshot)?,
13006 };
13007 per_cond_sets.push(s);
13008 }
13009 Ok(rows
13010 .into_iter()
13011 .filter(|row| {
13012 conditions.iter().enumerate().all(|(i, c)| match c {
13013 Condition::Range { column_id, lo, hi } => {
13014 matches!(row.columns.get(column_id), Some(Value::Int64(v)) if *v >= *lo && *v <= *hi)
13015 }
13016 Condition::RangeF64 { column_id, lo, lo_inclusive, hi, hi_inclusive } => {
13017 match row.columns.get(column_id) {
13018 Some(Value::Float64(v)) => {
13019 let lo_ok = if *lo_inclusive { *v >= *lo } else { *v > *lo };
13020 let hi_ok = if *hi_inclusive { *v <= *hi } else { *v < *hi };
13021 lo_ok && hi_ok
13022 }
13023 _ => false,
13024 }
13025 }
13026 _ => per_cond_sets[i].contains(row.row_id.0),
13027 })
13028 })
13029 .collect())
13030 }
13031
13032 fn materialize_overlay(
13035 &self,
13036 rows: &[Row],
13037 projection: &[(u16, TypeId)],
13038 ) -> Vec<columnar::NativeColumn> {
13039 if projection.is_empty() {
13040 return vec![columnar::null_native(TypeId::Int64, rows.len())];
13041 }
13042 let mut cols = Vec::with_capacity(projection.len());
13043 for (cid, ty) in projection {
13044 let vals: Vec<Value> = rows
13045 .iter()
13046 .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
13047 .collect();
13048 cols.push(columnar::values_to_native(ty.clone(), &vals));
13049 }
13050 cols
13051 }
13052
13053 fn resolve_survivor_rids(
13058 &self,
13059 conditions: &[crate::query::Condition],
13060 reader: &mut RunReader,
13061 snapshot: Snapshot,
13062 ) -> Result<RowIdSet> {
13063 use crate::query::Condition;
13064 let mut sets: Vec<RowIdSet> = Vec::new();
13065 for c in conditions {
13066 self.validate_condition(c)?;
13067 let s: RowIdSet = match c {
13068 Condition::Pk(key) => {
13069 let lookup = self
13070 .schema
13071 .primary_key()
13072 .map(|pk| self.index_lookup_key_bytes(pk.id, key))
13073 .unwrap_or_else(|| key.clone());
13074 self.hot
13075 .get(&lookup)
13076 .map(|r| RowIdSet::one(r.0))
13077 .unwrap_or_else(RowIdSet::empty)
13078 }
13079 Condition::BitmapEq { column_id, value } => {
13080 let lookup = self.index_lookup_key_bytes(*column_id, value);
13081 self.bitmap
13082 .get(column_id)
13083 .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
13084 .unwrap_or_else(RowIdSet::empty)
13085 }
13086 Condition::BitmapIn { column_id, values } => {
13087 let bm = self.bitmap.get(column_id);
13088 let mut acc = roaring::RoaringBitmap::new();
13089 if let Some(b) = bm {
13090 for v in values {
13091 let lookup = self.index_lookup_key_bytes(*column_id, v);
13092 acc |= b.get(&lookup);
13093 }
13094 }
13095 RowIdSet::from_roaring(acc)
13096 }
13097 Condition::BytesPrefix { column_id, prefix } => {
13098 if let Some(b) = self.bitmap.get(column_id) {
13099 let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
13100 let mut acc = roaring::RoaringBitmap::new();
13101 for key in b.keys() {
13102 if key.starts_with(&lookup_prefix) {
13103 acc |= b.get(&key);
13104 }
13105 }
13106 RowIdSet::from_roaring(acc)
13107 } else {
13108 RowIdSet::empty()
13109 }
13110 }
13111 Condition::FmContains { column_id, pattern } => self
13112 .fm
13113 .get(column_id)
13114 .map(|f| {
13115 RowIdSet::from_unsorted(
13116 f.locate(pattern).into_iter().map(|r| r.0).collect(),
13117 )
13118 })
13119 .unwrap_or_else(RowIdSet::empty),
13120 Condition::FmContainsAll {
13121 column_id,
13122 patterns,
13123 } => {
13124 if let Some(f) = self.fm.get(column_id) {
13125 let sets: Vec<RowIdSet> = patterns
13126 .iter()
13127 .map(|pat| {
13128 RowIdSet::from_unsorted(
13129 f.locate(pat).into_iter().map(|r| r.0).collect(),
13130 )
13131 })
13132 .collect();
13133 RowIdSet::intersect_many(sets)
13134 } else {
13135 RowIdSet::empty()
13136 }
13137 }
13138 Condition::Ann {
13139 column_id,
13140 query,
13141 k,
13142 } => RowIdSet::from_unsorted(
13143 self.retrieve_filtered(
13144 &crate::query::Retriever::Ann {
13145 column_id: *column_id,
13146 query: query.clone(),
13147 k: *k,
13148 },
13149 snapshot,
13150 None,
13151 None,
13152 None,
13153 None,
13154 )?
13155 .into_iter()
13156 .map(|hit| hit.row_id.0)
13157 .collect(),
13158 ),
13159 Condition::SparseMatch {
13160 column_id,
13161 query,
13162 k,
13163 } => RowIdSet::from_unsorted(
13164 self.retrieve_filtered(
13165 &crate::query::Retriever::Sparse {
13166 column_id: *column_id,
13167 query: query.clone(),
13168 k: *k,
13169 },
13170 snapshot,
13171 None,
13172 None,
13173 None,
13174 None,
13175 )?
13176 .into_iter()
13177 .map(|hit| hit.row_id.0)
13178 .collect(),
13179 ),
13180 Condition::MinHashSimilar {
13181 column_id,
13182 query,
13183 k,
13184 } => match self.minhash.get(column_id) {
13185 Some(index) => {
13186 let candidates = index.candidate_row_ids(query);
13187 let eligible =
13188 self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
13189 RowIdSet::from_unsorted(
13190 index
13191 .search_filtered(query, *k, |row_id| eligible.contains(&row_id))
13192 .into_iter()
13193 .map(|(row_id, _)| row_id.0)
13194 .collect(),
13195 )
13196 }
13197 None => RowIdSet::empty(),
13198 },
13199 Condition::Range { column_id, lo, hi } => {
13200 if let Some(li) = self.learned_range.get(column_id) {
13201 RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
13202 } else {
13203 reader.range_row_id_set_i64(*column_id, *lo, *hi)?
13204 }
13205 }
13206 Condition::RangeF64 {
13207 column_id,
13208 lo,
13209 lo_inclusive,
13210 hi,
13211 hi_inclusive,
13212 } => {
13213 if let Some(li) = self.learned_range.get(column_id) {
13214 RowIdSet::from_unsorted(
13215 li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
13216 .into_iter()
13217 .collect(),
13218 )
13219 } else {
13220 reader.range_row_id_set_f64(
13221 *column_id,
13222 *lo,
13223 *lo_inclusive,
13224 *hi,
13225 *hi_inclusive,
13226 )?
13227 }
13228 }
13229 Condition::IsNull { column_id } => reader.null_row_id_set(*column_id, true)?,
13230 Condition::IsNotNull { column_id } => reader.null_row_id_set(*column_id, false)?,
13231 };
13232 sets.push(s);
13233 }
13234 Ok(RowIdSet::intersect_many(sets))
13235 }
13236
13237 pub fn scan_cursor(
13258 &self,
13259 snapshot: Snapshot,
13260 projection: Vec<(u16, TypeId)>,
13261 conditions: &[crate::query::Condition],
13262 ) -> Result<Option<Box<dyn crate::cursor::Cursor>>> {
13263 if self.ttl.is_some() {
13264 return Ok(None);
13265 }
13266 if !conditions.is_empty() && !self.indexes_complete {
13272 return Ok(None);
13273 }
13274 if self.run_refs.len() == 1 {
13275 Ok(self
13276 .native_page_cursor(snapshot, projection, conditions)?
13277 .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13278 } else {
13279 Ok(self
13280 .native_multi_run_cursor(snapshot, projection, conditions)?
13281 .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13282 }
13283 }
13284
13285 pub fn aggregate_native(
13299 &self,
13300 snapshot: Snapshot,
13301 column: Option<u16>,
13302 conditions: &[crate::query::Condition],
13303 agg: NativeAgg,
13304 ) -> Result<Option<NativeAggResult>> {
13305 self.aggregate_native_inner(snapshot, column, conditions, agg, None)
13306 }
13307
13308 pub fn aggregate_native_with_control(
13309 &self,
13310 snapshot: Snapshot,
13311 column: Option<u16>,
13312 conditions: &[crate::query::Condition],
13313 agg: NativeAgg,
13314 control: &crate::ExecutionControl,
13315 ) -> Result<Option<NativeAggResult>> {
13316 self.aggregate_native_inner(snapshot, column, conditions, agg, Some(control))
13317 }
13318
13319 fn aggregate_native_inner(
13320 &self,
13321 snapshot: Snapshot,
13322 column: Option<u16>,
13323 conditions: &[crate::query::Condition],
13324 agg: NativeAgg,
13325 control: Option<&crate::ExecutionControl>,
13326 ) -> Result<Option<NativeAggResult>> {
13327 execution_checkpoint(control, 0)?;
13328 if self.ttl.is_some() {
13329 return Ok(None);
13330 }
13331 if self.run_refs.len() == 1 && conditions.is_empty() {
13333 if let Some(res) = self.aggregate_from_stats(snapshot, column, agg)? {
13334 return Ok(Some(res));
13335 }
13336 }
13337 if matches!(agg, NativeAgg::Count) && column.is_none() {
13341 if let Some(c) = self.scan_cursor(snapshot, Vec::new(), conditions)? {
13342 return Ok(Some(NativeAggResult::Count(c.remaining_rows() as u64)));
13343 }
13344 let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13345 return Ok(Some(NativeAggResult::Count(rows.len() as u64)));
13346 }
13347 let cid = match column {
13350 Some(c) => c,
13351 None => return Ok(None),
13352 };
13353 let ty = self.column_type(cid);
13354 if let Some(mut cursor) = self.scan_cursor(snapshot, vec![(cid, ty.clone())], conditions)? {
13355 execution_checkpoint(control, 0)?;
13356 return match ty {
13357 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13358 let (count, sum, mn, mx) = accumulate_int(cursor.as_mut(), control)?;
13359 Ok(Some(pack_int(agg, count, sum, mn, mx)))
13360 }
13361 TypeId::Float64 => {
13362 let (count, sum, mn, mx) = accumulate_float(cursor.as_mut(), control)?;
13363 Ok(Some(pack_float(agg, count, sum, mn, mx)))
13364 }
13365 _ => Ok(None),
13366 };
13367 }
13368 let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13370 execution_checkpoint(control, 0)?;
13371 match ty {
13372 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13373 let mut count = 0u64;
13374 let mut sum = 0i128;
13375 let mut mn = i64::MAX;
13376 let mut mx = i64::MIN;
13377 for row in &rows {
13378 if let Some(Value::Int64(v)) = row.columns.get(&cid) {
13379 count += 1;
13380 sum += i128::from(*v);
13381 mn = mn.min(*v);
13382 mx = mx.max(*v);
13383 }
13384 }
13385 Ok(Some(pack_int(agg, count, sum, mn, mx)))
13386 }
13387 TypeId::Float64 => {
13388 let mut count = 0u64;
13389 let mut sum = 0.0f64;
13390 let mut mn = f64::INFINITY;
13391 let mut mx = f64::NEG_INFINITY;
13392 for row in &rows {
13393 if let Some(Value::Float64(v)) = row.columns.get(&cid) {
13394 count += 1;
13395 sum += *v;
13396 mn = mn.min(*v);
13397 mx = mx.max(*v);
13398 }
13399 }
13400 Ok(Some(pack_float(agg, count, sum, mn, mx)))
13401 }
13402 _ => Ok(None),
13403 }
13404 }
13405
13406 fn visible_rows_filtered(
13408 &self,
13409 snapshot: Snapshot,
13410 conditions: &[crate::query::Condition],
13411 control: Option<&crate::ExecutionControl>,
13412 ) -> Result<Vec<Row>> {
13413 let rows = if let Some(control) = control {
13414 self.visible_rows_controlled(snapshot, control)?
13415 } else {
13416 self.visible_rows(snapshot)?
13417 };
13418 if conditions.is_empty() {
13419 return Ok(rows);
13420 }
13421 Ok(rows
13422 .into_iter()
13423 .filter(|row| {
13424 conditions
13425 .iter()
13426 .all(|cond| condition_matches_row(cond, row, &self.schema))
13427 })
13428 .collect())
13429 }
13430
13431 fn aggregate_from_stats(
13439 &self,
13440 snapshot: Snapshot,
13441 column: Option<u16>,
13442 agg: NativeAgg,
13443 ) -> Result<Option<NativeAggResult>> {
13444 let cid = match (agg, column) {
13445 (NativeAgg::Count | NativeAgg::Min | NativeAgg::Max, Some(c)) => c,
13446 _ => return Ok(None), };
13448 let Some(stats) = self.exact_column_stats(snapshot, &[cid])? else {
13449 return Ok(None);
13450 };
13451 let Some(cs) = stats.get(&cid) else {
13452 return Ok(None);
13453 };
13454 match agg {
13455 NativeAgg::Count => Ok(Some(NativeAggResult::Count(
13457 self.live_count.saturating_sub(cs.null_count),
13458 ))),
13459 NativeAgg::Min | NativeAgg::Max => {
13460 let bound = if agg == NativeAgg::Min {
13461 &cs.min
13462 } else {
13463 &cs.max
13464 };
13465 match bound {
13466 Some(Value::Int64(x)) => Ok(Some(NativeAggResult::Int(*x))),
13467 Some(Value::Float64(x)) => Ok(Some(NativeAggResult::Float(*x))),
13468 Some(_) => Ok(None), None if cs.null_count >= self.live_count => Ok(Some(NativeAggResult::Null)),
13473 None => Ok(None),
13474 }
13475 }
13476 _ => Ok(None),
13477 }
13478 }
13479
13480 pub fn count_distinct_from_bitmap(&mut self, column_id: u16) -> Result<Option<u64>> {
13489 if self.ttl.is_some() {
13490 return Ok(None);
13491 }
13492 if !(self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1) {
13493 return Ok(None);
13494 }
13495 self.ensure_indexes_complete()?;
13498 let reader = self.open_reader(self.run_refs[0].run_id)?;
13499 if self.live_count != reader.row_count() as u64 {
13500 return Ok(None);
13501 }
13502 let Some(bm) = self.bitmap.get(&column_id) else {
13503 return Ok(None); };
13505 let mut distinct = bm.value_count() as u64;
13506 if !bm.get(&Value::Null.encode_key()).is_empty() {
13509 distinct = distinct.saturating_sub(1);
13510 }
13511 Ok(Some(distinct))
13512 }
13513
13514 pub fn aggregate_incremental(
13526 &mut self,
13527 cache_key: u64,
13528 conditions: &[crate::query::Condition],
13529 column: Option<u16>,
13530 agg: NativeAgg,
13531 ) -> Result<IncrementalAggResult> {
13532 self.aggregate_incremental_inner(cache_key, conditions, column, agg, None)
13533 }
13534
13535 pub fn aggregate_incremental_with_control(
13536 &mut self,
13537 cache_key: u64,
13538 conditions: &[crate::query::Condition],
13539 column: Option<u16>,
13540 agg: NativeAgg,
13541 control: &crate::ExecutionControl,
13542 ) -> Result<IncrementalAggResult> {
13543 self.aggregate_incremental_inner(cache_key, conditions, column, agg, Some(control))
13544 }
13545
13546 fn aggregate_incremental_inner(
13547 &mut self,
13548 cache_key: u64,
13549 conditions: &[crate::query::Condition],
13550 column: Option<u16>,
13551 agg: NativeAgg,
13552 control: Option<&crate::ExecutionControl>,
13553 ) -> Result<IncrementalAggResult> {
13554 execution_checkpoint(control, 0)?;
13555 let snap = self.snapshot();
13556 let cur_wm = self.allocator.current().0;
13557 let cur_epoch = snap.epoch.0;
13558 let incremental_ok = self.ttl.is_none()
13565 && !self.had_deletes
13566 && self.memtable.is_empty()
13567 && self.mutable_run.is_empty();
13568
13569 if incremental_ok {
13572 if let Some(cached) = self.agg_cache.get(&cache_key).cloned() {
13573 if cached.epoch == cur_epoch {
13574 return Ok(IncrementalAggResult {
13575 state: cached.state,
13576 incremental: true,
13577 delta_rows: 0,
13578 });
13579 }
13580 if cached.epoch < cur_epoch && cached.watermark <= cur_wm {
13581 let delta_len = cur_wm.saturating_sub(cached.watermark) as usize;
13582 let mut delta_rids = Vec::with_capacity(delta_len);
13583 for (index, row_id) in (cached.watermark..cur_wm).enumerate() {
13584 execution_checkpoint(control, index)?;
13585 delta_rids.push(row_id);
13586 }
13587 let delta_rows = self.rows_for_rids(&delta_rids, snap)?;
13588 execution_checkpoint(control, 0)?;
13589 let index_sets = self.resolve_index_conditions(conditions, snap)?;
13590 let delta_state = agg_state_from_rows(
13591 &delta_rows,
13592 conditions,
13593 &index_sets,
13594 column,
13595 agg,
13596 &self.schema,
13597 control,
13598 )?;
13599 let merged = cached.state.merge(delta_state);
13600 let delta_n = delta_rids.len() as u64;
13601 Arc::make_mut(&mut self.agg_cache).insert(
13602 cache_key,
13603 CachedAgg {
13604 state: merged.clone(),
13605 watermark: cur_wm,
13606 epoch: cur_epoch,
13607 },
13608 );
13609 return Ok(IncrementalAggResult {
13610 state: merged,
13611 incremental: true,
13612 delta_rows: delta_n,
13613 });
13614 }
13615 }
13616 }
13617
13618 let cursor_ok =
13623 self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
13624 let state = if cursor_ok && agg != NativeAgg::Avg {
13625 match self.aggregate_native_inner(snap, column, conditions, agg, control)? {
13626 Some(result) => {
13627 AggState::from_native(result, agg, column.map(|c| self.column_type(c)))
13628 }
13629 None => self.agg_state_full_scan(conditions, column, agg, snap, control)?,
13630 }
13631 } else {
13632 self.agg_state_full_scan(conditions, column, agg, snap, control)?
13633 };
13634 if incremental_ok {
13636 Arc::make_mut(&mut self.agg_cache).insert(
13637 cache_key,
13638 CachedAgg {
13639 state: state.clone(),
13640 watermark: cur_wm,
13641 epoch: cur_epoch,
13642 },
13643 );
13644 }
13645 Ok(IncrementalAggResult {
13646 state,
13647 incremental: false,
13648 delta_rows: 0,
13649 })
13650 }
13651
13652 fn agg_state_full_scan(
13655 &self,
13656 conditions: &[crate::query::Condition],
13657 column: Option<u16>,
13658 agg: NativeAgg,
13659 snap: Snapshot,
13660 control: Option<&crate::ExecutionControl>,
13661 ) -> Result<AggState> {
13662 execution_checkpoint(control, 0)?;
13663 let rows = self.visible_rows(snap)?;
13664 execution_checkpoint(control, 0)?;
13665 let index_sets = self.resolve_index_conditions(conditions, snap)?;
13666 agg_state_from_rows(
13667 &rows,
13668 conditions,
13669 &index_sets,
13670 column,
13671 agg,
13672 &self.schema,
13673 control,
13674 )
13675 }
13676
13677 fn resolve_index_conditions(
13680 &self,
13681 conditions: &[crate::query::Condition],
13682 snapshot: Snapshot,
13683 ) -> Result<Vec<RowIdSet>> {
13684 use crate::query::Condition;
13685 let mut sets = Vec::new();
13686 for c in conditions {
13687 if matches!(
13688 c,
13689 Condition::Ann { .. }
13690 | Condition::SparseMatch { .. }
13691 | Condition::MinHashSimilar { .. }
13692 ) {
13693 sets.push(self.resolve_condition(c, snapshot)?);
13694 }
13695 }
13696 Ok(sets)
13697 }
13698
13699 fn column_type(&self, cid: u16) -> TypeId {
13700 self.schema
13701 .columns
13702 .iter()
13703 .find(|c| c.id == cid)
13704 .map(|c| c.ty.clone())
13705 .unwrap_or(TypeId::Bytes)
13706 }
13707
13708 pub fn approx_aggregate(
13717 &mut self,
13718 conditions: &[crate::query::Condition],
13719 column: Option<u16>,
13720 agg: ApproxAgg,
13721 z: f64,
13722 ) -> Result<Option<ApproxResult>> {
13723 self.approx_aggregate_with_candidate_authorization(conditions, column, agg, z, None)
13724 }
13725
13726 pub fn approx_aggregate_with_candidate_authorization(
13729 &mut self,
13730 conditions: &[crate::query::Condition],
13731 column: Option<u16>,
13732 agg: ApproxAgg,
13733 z: f64,
13734 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
13735 ) -> Result<Option<ApproxResult>> {
13736 use crate::query::Condition;
13737 self.ensure_reservoir_complete()?;
13738 let mut snapshot = self.snapshot();
13743 let n_pop = self.count();
13744 let sample_rids: Vec<u64> = self.reservoir.row_ids().to_vec();
13745 if sample_rids.is_empty() {
13746 return Ok(None);
13747 }
13748 let mut live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13750 if live_sample.is_empty() {
13751 snapshot = Snapshot::unbounded();
13752 live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13753 }
13754 let s = live_sample.len();
13755 if s == 0 {
13756 return Ok(None);
13757 }
13758 let authorized = authorization
13759 .map(|authorization| {
13760 let candidates = live_sample.iter().map(|row| row.row_id).collect::<Vec<_>>();
13761 self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, None)
13762 })
13763 .transpose()?;
13764
13765 let mut index_sets: Vec<RowIdSet> = Vec::new();
13768 for c in conditions {
13769 if matches!(
13770 c,
13771 Condition::Ann { .. }
13772 | Condition::SparseMatch { .. }
13773 | Condition::MinHashSimilar { .. }
13774 ) {
13775 index_sets.push(self.resolve_condition(c, snapshot)?);
13776 }
13777 }
13778
13779 let cid = match (agg, column) {
13781 (ApproxAgg::Count, _) => None,
13782 (_, Some(c)) => Some(c),
13783 _ => return Ok(None),
13784 };
13785 let mut passing_vals: Vec<f64> = Vec::with_capacity(s);
13786 for r in &live_sample {
13787 if authorized
13788 .as_ref()
13789 .is_some_and(|authorized| !authorized.contains(&r.row_id))
13790 {
13791 continue;
13792 }
13793 if !conditions
13795 .iter()
13796 .all(|c| condition_matches_row(c, r, &self.schema))
13797 {
13798 continue;
13799 }
13800 if !index_sets.iter().all(|set| set.contains(r.row_id.0)) {
13802 continue;
13803 }
13804 if let Some(cid) = cid {
13805 let mut cells = r
13806 .columns
13807 .get(&cid)
13808 .cloned()
13809 .map(|value| vec![(cid, value)])
13810 .unwrap_or_default();
13811 if let Some(authorization) = authorization {
13812 authorization.security.apply_masks_to_cells(
13813 authorization.table,
13814 &mut cells,
13815 authorization.principal,
13816 );
13817 }
13818 if let Some(v) = as_f64(cells.first().map(|(_, value)| value)) {
13819 passing_vals.push(v);
13820 } } else {
13822 passing_vals.push(0.0); }
13824 }
13825 let m = passing_vals.len();
13826
13827 let (point, half) = match agg {
13828 ApproxAgg::Count => {
13829 let p = m as f64 / s as f64;
13831 let point = n_pop as f64 * p;
13832 let var = if s > 1 {
13833 n_pop as f64 * n_pop as f64 * p * (1.0 - p) / s as f64
13834 * (1.0 - s as f64 / n_pop as f64).max(0.0)
13835 } else {
13836 0.0
13837 };
13838 (point, z * var.sqrt())
13839 }
13840 ApproxAgg::Sum => {
13841 let y: Vec<f64> = live_sample
13843 .iter()
13844 .map(|r| {
13845 let passes_row = authorized
13846 .as_ref()
13847 .is_none_or(|authorized| authorized.contains(&r.row_id))
13848 && conditions
13849 .iter()
13850 .all(|c| condition_matches_row(c, r, &self.schema))
13851 && index_sets.iter().all(|set| set.contains(r.row_id.0));
13852 if passes_row {
13853 cid.and_then(|cid| {
13854 let mut cells = r
13855 .columns
13856 .get(&cid)
13857 .cloned()
13858 .map(|value| vec![(cid, value)])
13859 .unwrap_or_default();
13860 if let Some(authorization) = authorization {
13861 authorization.security.apply_masks_to_cells(
13862 authorization.table,
13863 &mut cells,
13864 authorization.principal,
13865 );
13866 }
13867 as_f64(cells.first().map(|(_, value)| value))
13868 })
13869 .unwrap_or(0.0)
13870 } else {
13871 0.0
13872 }
13873 })
13874 .collect();
13875 let mean_y = y.iter().sum::<f64>() / s as f64;
13876 let point = n_pop as f64 * mean_y;
13877 let var = if s > 1 {
13878 let ss: f64 = y.iter().map(|v| (v - mean_y).powi(2)).sum();
13879 let var_y = ss / (s - 1) as f64;
13880 n_pop as f64 * n_pop as f64 * var_y / s as f64
13881 * (1.0 - s as f64 / n_pop as f64).max(0.0)
13882 } else {
13883 0.0
13884 };
13885 (point, z * var.sqrt())
13886 }
13887 ApproxAgg::Avg => {
13888 if m == 0 {
13889 return Ok(Some(ApproxResult {
13890 point: 0.0,
13891 ci_low: 0.0,
13892 ci_high: 0.0,
13893 n_population: n_pop,
13894 n_sample_live: s,
13895 n_passing: 0,
13896 }));
13897 }
13898 let mean = passing_vals.iter().sum::<f64>() / m as f64;
13899 let half = if m > 1 {
13900 let ss: f64 = passing_vals.iter().map(|v| (v - mean).powi(2)).sum();
13901 let sd = (ss / (m - 1) as f64).sqrt();
13902 let fpc = (1.0 - s as f64 / n_pop as f64).max(0.0);
13903 z * sd / (m as f64).sqrt() * fpc.sqrt()
13904 } else {
13905 0.0
13906 };
13907 (mean, half)
13908 }
13909 };
13910
13911 Ok(Some(ApproxResult {
13912 point,
13913 ci_low: point - half,
13914 ci_high: point + half,
13915 n_population: n_pop,
13916 n_sample_live: s,
13917 n_passing: m,
13918 }))
13919 }
13920
13921 pub fn exact_column_stats(
13929 &self,
13930 _snapshot: Snapshot,
13931 projection: &[u16],
13932 ) -> Result<Option<HashMap<u16, ColumnStat>>> {
13933 if self.ttl.is_some()
13934 || !(self.memtable.is_empty()
13935 && self.mutable_run.is_empty()
13936 && self.run_refs.len() == 1)
13937 {
13938 return Ok(None);
13939 }
13940 let reader = self.open_reader(self.run_refs[0].run_id)?;
13941 if self.live_count != reader.row_count() as u64 {
13942 return Ok(None);
13943 }
13944 let mut out = HashMap::new();
13945 for &cid in projection {
13946 let cdef = match self.schema.columns.iter().find(|c| c.id == cid) {
13947 Some(c) => c,
13948 None => continue,
13949 };
13950 let Some(stats) = reader.column_page_stats(cid) else {
13952 out.insert(
13953 cid,
13954 ColumnStat {
13955 min: None,
13956 max: None,
13957 null_count: self.live_count,
13958 },
13959 );
13960 continue;
13961 };
13962 let stat = match cdef.ty {
13963 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13964 agg_int(stats, crate::sorted_run::be_i64).map(|(mn, mx, n)| ColumnStat {
13965 min: mn.map(Value::Int64),
13966 max: mx.map(Value::Int64),
13967 null_count: n,
13968 })
13969 }
13970 TypeId::Float64 => {
13971 agg_float(stats, crate::sorted_run::be_f64).map(|(mn, mx, n)| ColumnStat {
13972 min: mn.map(Value::Float64),
13973 max: mx.map(Value::Float64),
13974 null_count: n,
13975 })
13976 }
13977 _ => None,
13978 };
13979 if let Some(s) = stat {
13980 out.insert(cid, s);
13981 }
13982 }
13983 Ok(Some(out))
13984 }
13985
13986 pub fn dir(&self) -> &Path {
13987 &self.dir
13988 }
13989
13990 pub fn schema(&self) -> &Schema {
13991 &self.schema
13992 }
13993
13994 pub fn ann_index(&self, column_id: u16) -> Option<&crate::index::AnnIndex> {
13995 self.ann.get(&column_id)
13996 }
13997
13998 pub fn ann_index_mut(&mut self, column_id: u16) -> Option<&mut crate::index::AnnIndex> {
13999 self.ann.get_mut(&column_id)
14000 }
14001
14002 pub(crate) fn set_catalog_name(&mut self, name: String) {
14003 self.name = name;
14004 }
14005
14006 pub(crate) fn prepare_alter_column(
14007 &mut self,
14008 column_name: &str,
14009 change: &AlterColumn,
14010 ) -> Result<(ColumnDef, Option<Schema>)> {
14011 if !self.pending_rows.is_empty() || !self.pending_dels.is_empty() {
14012 return Err(MongrelError::InvalidArgument(
14013 "ALTER COLUMN requires committing staged writes first".into(),
14014 ));
14015 }
14016 let old = self
14017 .schema
14018 .columns
14019 .iter()
14020 .find(|c| c.name == column_name)
14021 .cloned()
14022 .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14023 let mut next = old.clone();
14024
14025 if let Some(name) = &change.name {
14026 let trimmed = name.trim();
14027 if trimmed.is_empty() {
14028 return Err(MongrelError::InvalidArgument(
14029 "ALTER COLUMN name must not be empty".into(),
14030 ));
14031 }
14032 if trimmed != old.name && self.schema.columns.iter().any(|c| c.name == trimmed) {
14033 return Err(MongrelError::Schema(format!(
14034 "column {trimmed} already exists"
14035 )));
14036 }
14037 next.name = trimmed.to_string();
14038 }
14039
14040 if let Some(ty) = &change.ty {
14041 next.ty = ty.clone();
14042 }
14043 if let Some(flags) = change.flags {
14044 validate_alter_column_flags(old.flags, flags)?;
14045 next.flags = flags;
14046 }
14047
14048 if let Some(default_change) = &change.default_value {
14049 next.default_value = default_change.clone();
14050 }
14051 if let Some(source_change) = &change.embedding_source {
14052 next.embedding_source = source_change.clone();
14053 }
14054
14055 validate_alter_column_type(&self.schema, &old, &next, self.has_stored_versions())?;
14056 if old.flags.contains(ColumnFlags::NULLABLE)
14057 && !next.flags.contains(ColumnFlags::NULLABLE)
14058 && self.column_has_nulls(old.id)?
14059 {
14060 return Err(MongrelError::InvalidArgument(format!(
14061 "column '{}' contains NULL values",
14062 old.name
14063 )));
14064 }
14065 if next == old {
14066 return Ok((next, None));
14067 }
14068 let mut schema = self.schema.clone();
14069 let index = schema
14070 .columns
14071 .iter()
14072 .position(|column| column.id == next.id)
14073 .ok_or_else(|| MongrelError::Schema(format!("unknown column {}", next.id)))?;
14074 schema.columns[index] = next.clone();
14075 schema.schema_id = schema
14076 .schema_id
14077 .checked_add(1)
14078 .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14079 schema.validate_auto_increment()?;
14080 schema.validate_defaults()?;
14081 Ok((next, Some(schema)))
14082 }
14083
14084 pub(crate) fn apply_altered_schema_prepared(&mut self, schema: Schema) {
14085 self.schema = schema;
14086 self.auto_inc = resolve_auto_inc(&self.schema);
14087 self.column_keys = build_column_keys(self.kek.as_deref(), &self.schema);
14088 self.clear_result_cache();
14089 let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
14090 }
14091
14092 pub(crate) fn publish_index_schema_change(
14096 &mut self,
14097 schema: Schema,
14098 artifact: SecondaryIndexArtifact,
14099 ) -> Result<()> {
14100 self.apply_altered_schema_prepared(schema);
14101 self.prune_index_maps_to_schema();
14102 match artifact {
14103 SecondaryIndexArtifact::Bitmap(column_id, index) => {
14104 self.bitmap.insert(column_id, index);
14105 }
14106 SecondaryIndexArtifact::LearnedRange(column_id, index) => {
14107 Arc::make_mut(&mut self.learned_range).insert(column_id, index);
14108 }
14109 SecondaryIndexArtifact::Fm(column_id, index) => {
14110 self.fm.insert(column_id, *index);
14111 }
14112 SecondaryIndexArtifact::Ann(column_id, index) => {
14113 self.ann.insert(column_id, *index);
14114 }
14115 SecondaryIndexArtifact::Sparse(column_id, index) => {
14116 self.sparse.insert(column_id, index);
14117 }
14118 SecondaryIndexArtifact::MinHash(column_id, index) => {
14119 self.minhash.insert(column_id, index);
14120 }
14121 }
14122 self.indexes_complete = true;
14123 self.seal_generations();
14124 let view = Arc::new(self.capture_read_generation());
14125 self.published.store(Arc::clone(&view));
14126 checkpoint_current_schema(self)?;
14127 self.invalidate_index_checkpoint();
14130 Ok(())
14131 }
14132
14133 pub(crate) fn publish_index_drop(&mut self, schema: Schema) -> Result<()> {
14139 self.apply_altered_schema_prepared(schema);
14140 self.prune_index_maps_to_schema();
14141 self.indexes_complete = true;
14142 self.seal_generations();
14143 let view = Arc::new(self.capture_read_generation());
14144 self.published.store(Arc::clone(&view));
14145 checkpoint_current_schema(self)?;
14146 self.invalidate_index_checkpoint();
14148 Ok(())
14149 }
14150
14151 fn prune_index_maps_to_schema(&mut self) {
14152 let keep_bitmap: std::collections::HashSet<u16> = self
14153 .schema
14154 .indexes
14155 .iter()
14156 .filter(|index| index.kind == IndexKind::Bitmap)
14157 .map(|index| index.column_id)
14158 .collect();
14159 let keep_ann: std::collections::HashSet<u16> = self
14160 .schema
14161 .indexes
14162 .iter()
14163 .filter(|index| index.kind == IndexKind::Ann)
14164 .map(|index| index.column_id)
14165 .collect();
14166 let keep_fm: std::collections::HashSet<u16> = self
14167 .schema
14168 .indexes
14169 .iter()
14170 .filter(|index| index.kind == IndexKind::FmIndex)
14171 .map(|index| index.column_id)
14172 .collect();
14173 let keep_sparse: std::collections::HashSet<u16> = self
14174 .schema
14175 .indexes
14176 .iter()
14177 .filter(|index| index.kind == IndexKind::Sparse)
14178 .map(|index| index.column_id)
14179 .collect();
14180 let keep_minhash: std::collections::HashSet<u16> = self
14181 .schema
14182 .indexes
14183 .iter()
14184 .filter(|index| index.kind == IndexKind::MinHash)
14185 .map(|index| index.column_id)
14186 .collect();
14187 let keep_learned: std::collections::HashSet<u16> = self
14188 .schema
14189 .indexes
14190 .iter()
14191 .filter(|index| index.kind == IndexKind::LearnedRange)
14192 .map(|index| index.column_id)
14193 .collect();
14194 self.bitmap
14195 .retain(|column_id, _| keep_bitmap.contains(column_id));
14196 self.ann.retain(|column_id, _| keep_ann.contains(column_id));
14197 self.fm.retain(|column_id, _| keep_fm.contains(column_id));
14198 self.sparse
14199 .retain(|column_id, _| keep_sparse.contains(column_id));
14200 self.minhash
14201 .retain(|column_id, _| keep_minhash.contains(column_id));
14202 {
14203 let learned = Arc::make_mut(&mut self.learned_range);
14204 learned.retain(|column_id, _| keep_learned.contains(column_id));
14205 }
14206 }
14207
14208 pub(crate) fn checkpoint_altered_schema(&mut self) -> Result<()> {
14209 checkpoint_current_schema(self)
14210 }
14211
14212 pub fn alter_column(&mut self, column_name: &str, change: AlterColumn) -> Result<ColumnDef> {
14213 self.ensure_writable()?;
14214 let previous_schema = self.schema.clone();
14215 let (column, schema) = self.prepare_alter_column(column_name, &change)?;
14216 if let Some(schema) = schema {
14217 self.apply_altered_schema_prepared(schema);
14218 self.checkpoint_standalone_schema_change(previous_schema)?;
14219 }
14220 Ok(column)
14221 }
14222
14223 fn column_has_nulls(&mut self, column_id: u16) -> Result<bool> {
14224 if self.live_count == 0 {
14225 return Ok(false);
14226 }
14227 let snap = self.snapshot();
14228 let columns = self.visible_columns_native(snap, Some(&[column_id]))?;
14229 Ok(columns
14230 .first()
14231 .map(|(_, col)| col.null_count(col.len()) != 0)
14232 .unwrap_or(true))
14233 }
14234
14235 fn has_stored_versions(&self) -> bool {
14236 !self.memtable.is_empty()
14237 || !self.mutable_run.is_empty()
14238 || self.run_refs.iter().any(|r| r.row_count > 0)
14239 || !self.retiring.is_empty()
14240 }
14241
14242 pub fn add_column(
14247 &mut self,
14248 name: &str,
14249 ty: TypeId,
14250 flags: ColumnFlags,
14251 default_value: Option<crate::schema::DefaultExpr>,
14252 ) -> Result<u16> {
14253 self.add_column_with_id(name, ty, flags, default_value, None)
14254 }
14255
14256 pub fn add_column_with_id(
14257 &mut self,
14258 name: &str,
14259 ty: TypeId,
14260 flags: ColumnFlags,
14261 default_value: Option<crate::schema::DefaultExpr>,
14262 requested_id: Option<u16>,
14263 ) -> Result<u16> {
14264 self.ensure_writable()?;
14265 let previous_schema = self.schema.clone();
14266 let (column, schema) =
14267 self.prepare_add_column(name, ty, flags, default_value, requested_id)?;
14268 self.apply_altered_schema_prepared(schema);
14269 self.checkpoint_standalone_schema_change(previous_schema)?;
14270 Ok(column.id)
14271 }
14272
14273 pub(crate) fn prepare_add_column(
14274 &mut self,
14275 name: &str,
14276 ty: TypeId,
14277 flags: ColumnFlags,
14278 default_value: Option<crate::schema::DefaultExpr>,
14279 requested_id: Option<u16>,
14280 ) -> Result<(ColumnDef, Schema)> {
14281 self.ensure_writable()?;
14282 if self.schema.columns.iter().any(|c| c.name == name) {
14283 return Err(MongrelError::Schema(format!(
14284 "column {name} already exists"
14285 )));
14286 }
14287 let id = if let Some(id) = requested_id.filter(|id| *id != 0) {
14288 if self.schema.columns.iter().any(|c| c.id == id) {
14289 return Err(MongrelError::Schema(format!(
14290 "column id {id} already exists"
14291 )));
14292 }
14293 id
14294 } else {
14295 self.schema
14296 .columns
14297 .iter()
14298 .map(|c| c.id)
14299 .max()
14300 .unwrap_or(0)
14301 .checked_add(1)
14302 .ok_or_else(|| MongrelError::Schema("column id space exhausted".into()))?
14303 };
14304 let column = ColumnDef {
14305 id,
14306 name: name.to_string(),
14307 ty,
14308 flags,
14309 default_value,
14310 embedding_source: None,
14311 };
14312 let mut next_schema = self.schema.clone();
14313 next_schema.columns.push(column.clone());
14314 next_schema.schema_id = next_schema
14315 .schema_id
14316 .checked_add(1)
14317 .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14318 next_schema.validate_auto_increment()?;
14319 next_schema.validate_defaults()?;
14320 Ok((column, next_schema))
14321 }
14322
14323 pub fn add_learned_range_index(&mut self, column_name: &str) -> Result<()> {
14332 self.ensure_writable()?;
14333 let cid = self
14334 .schema
14335 .columns
14336 .iter()
14337 .find(|c| c.name == column_name)
14338 .map(|c| c.id)
14339 .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14340 let ty = self
14341 .schema
14342 .columns
14343 .iter()
14344 .find(|c| c.id == cid)
14345 .map(|c| c.ty.clone())
14346 .unwrap_or(TypeId::Int64);
14347 if !matches!(
14348 ty,
14349 TypeId::Int64 | TypeId::Float64 | TypeId::TimestampNanos | TypeId::Date32
14350 ) {
14351 return Err(MongrelError::Schema(format!(
14352 "LearnedRange requires a numeric column; {column_name} is {ty:?}"
14353 )));
14354 }
14355 if self
14356 .schema
14357 .indexes
14358 .iter()
14359 .any(|i| i.column_id == cid && i.kind == IndexKind::LearnedRange)
14360 {
14361 return Ok(()); }
14363 let previous_schema = self.schema.clone();
14364 let previous_learned_range = Arc::clone(&self.learned_range);
14365 let mut next_schema = previous_schema.clone();
14366 next_schema.indexes.push(IndexDef {
14367 name: format!("{}_learned_range", column_name),
14368 column_id: cid,
14369 kind: IndexKind::LearnedRange,
14370 predicate: None,
14371 options: Default::default(),
14372 });
14373 next_schema.schema_id = next_schema
14374 .schema_id
14375 .checked_add(1)
14376 .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14377 self.apply_altered_schema_prepared(next_schema);
14378 if let Err(error) = self.build_learned_ranges() {
14379 self.apply_altered_schema_prepared(previous_schema);
14380 self.learned_range = previous_learned_range;
14381 return Err(error);
14382 }
14383 if let Err(error) = self.checkpoint_standalone_schema_change(previous_schema) {
14384 if !matches!(
14385 &error,
14386 MongrelError::DurableCommit { .. } | MongrelError::CommitOutcomeUnknown { .. }
14387 ) {
14388 self.learned_range = previous_learned_range;
14389 }
14390 return Err(error);
14391 }
14392 Ok(())
14393 }
14394
14395 fn checkpoint_standalone_schema_change(&mut self, previous_schema: Schema) -> Result<()> {
14396 let mut schema_published = false;
14397 let schema_result = match self._root_guard.as_deref() {
14398 Some(root) => write_schema_durable_with_after(root, &self.schema, || {
14399 schema_published = true;
14400 }),
14401 None => write_schema_with_after(&self.dir, &self.schema, || {
14402 schema_published = true;
14403 }),
14404 };
14405 if schema_result.is_err() && !schema_published {
14406 self.apply_altered_schema_prepared(previous_schema);
14407 return schema_result;
14408 }
14409
14410 let manifest_result = self.persist_manifest(self.current_epoch());
14411 match (schema_result, manifest_result) {
14412 (_, Ok(())) => Ok(()),
14413 (Ok(()), Err(error)) => {
14414 self.poison_after_maintenance_publish_failure();
14415 Err(MongrelError::DurableCommit {
14416 epoch: self.current_epoch().0,
14417 message: format!(
14418 "schema is durable but matching manifest publication failed: {error}"
14419 ),
14420 })
14421 }
14422 (Err(schema_error), Err(manifest_error)) => {
14423 self.poison_after_maintenance_publish_failure();
14424 Err(MongrelError::CommitOutcomeUnknown {
14425 epoch: self.current_epoch().0,
14426 message: format!(
14427 "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
14428 ),
14429 })
14430 }
14431 }
14432 }
14433
14434 pub fn set_sync_byte_threshold(&mut self, threshold: u64) {
14437 self.sync_byte_threshold = threshold;
14438 if let WalSink::Private(w) = &mut self.wal {
14439 w.set_sync_byte_threshold(threshold);
14440 }
14441 }
14442
14443 pub fn page_cache_flush(&self) {
14447 self.page_cache.flush_to_disk();
14448 }
14449
14450 pub fn page_cache_len(&self) -> usize {
14452 self.page_cache.len()
14453 }
14454
14455 pub fn decoded_cache_len(&self) -> usize {
14458 self.decoded_cache.len()
14459 }
14460
14461 pub fn drain_memtable_sorted(&mut self) -> Vec<Row> {
14464 self.memtable.drain_sorted()
14465 }
14466
14467 pub(crate) fn run_path(&self, run_id: u64) -> PathBuf {
14468 self.runs_dir().join(format!("r-{run_id}.sr"))
14469 }
14470
14471 pub(crate) fn create_run_file(&self, run_id: u64) -> Result<Option<std::fs::File>> {
14472 match self.runs_root.as_deref() {
14473 Some(root) => Ok(Some(root.create_regular_new(format!("r-{run_id}.sr"))?)),
14474 None => Ok(None),
14475 }
14476 }
14477
14478 pub(crate) fn create_run_entry(&self, name: &Path) -> Result<Option<std::fs::File>> {
14479 match self.runs_root.as_deref() {
14480 Some(root) => Ok(Some(root.create_regular_new(name)?)),
14481 None => Ok(None),
14482 }
14483 }
14484
14485 pub(crate) fn remove_run_entry(&self, name: &Path) -> Result<()> {
14486 match self.runs_root.as_deref() {
14487 Some(root) => match root.remove_file(name) {
14488 Ok(()) => Ok(()),
14489 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14490 Err(error) => Err(error.into()),
14491 },
14492 None => match std::fs::remove_file(self.runs_dir().join(name)) {
14493 Ok(()) => Ok(()),
14494 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14495 Err(error) => Err(error.into()),
14496 },
14497 }
14498 }
14499
14500 pub(crate) fn publish_run_entry(&self, source: &Path, destination: &Path) -> Result<()> {
14501 match self.runs_root.as_deref() {
14502 Some(root) => root
14503 .rename_file_new(source, destination)
14504 .map_err(Into::into),
14505 None => crate::durable_file::rename(
14506 &self.runs_dir().join(source),
14507 &self.runs_dir().join(destination),
14508 )
14509 .map_err(Into::into),
14510 }
14511 }
14512
14513 pub(crate) fn active_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14514 self.run_refs.iter().map(|run| run.run_id)
14515 }
14516
14517 pub(crate) fn table_dir(&self) -> &Path {
14518 &self.dir
14519 }
14520
14521 pub(crate) fn schema_ref(&self) -> &crate::schema::Schema {
14522 &self.schema
14523 }
14524
14525 pub(crate) fn alloc_run_id(&mut self) -> Result<u64> {
14526 let id = self.next_run_id;
14527 self.next_run_id = self
14528 .next_run_id
14529 .checked_add(1)
14530 .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))?;
14531 Ok(id)
14532 }
14533
14534 pub(crate) fn link_run(&mut self, run_ref: crate::manifest::RunRef) {
14535 self.run_refs.push(run_ref);
14536 }
14537
14538 pub(crate) fn retire_run(&mut self, run_id: u128, retire_epoch: u64) {
14548 self.retiring.push(crate::manifest::RetiredRun {
14549 run_id,
14550 retire_epoch,
14551 });
14552 }
14553
14554 pub(crate) fn reap_retiring(
14558 &mut self,
14559 min_active: Epoch,
14560 backup_pinned: &std::collections::HashSet<u128>,
14561 ) -> Result<usize> {
14562 if self.retiring.is_empty() {
14563 return Ok(0);
14564 }
14565 let mut reaped = 0;
14566 let mut kept: Vec<crate::manifest::RetiredRun> = Vec::new();
14567 for r in std::mem::take(&mut self.retiring) {
14573 if min_active.0 >= r.retire_epoch && !backup_pinned.contains(&r.run_id) {
14574 let _ = self.remove_run_entry(Path::new(&format!("r-{}.sr", r.run_id)));
14575 reaped += 1;
14576 } else {
14577 kept.push(r);
14578 }
14579 }
14580 self.retiring = kept;
14581 if reaped > 0 {
14582 self.persist_manifest(self.current_epoch())?;
14583 }
14584 Ok(reaped)
14585 }
14586
14587 pub(crate) fn has_reapable_retiring(
14588 &self,
14589 min_active: Epoch,
14590 backup_pinned: &std::collections::HashSet<u128>,
14591 ) -> bool {
14592 self.retiring
14593 .iter()
14594 .any(|run| min_active.0 >= run.retire_epoch && !backup_pinned.contains(&run.run_id))
14595 }
14596
14597 pub(crate) fn recover_spilled_run(&mut self, run_ref: crate::manifest::RunRef) -> bool {
14598 if self.run_refs.iter().any(|r| r.run_id == run_ref.run_id) {
14599 return false;
14600 }
14601 self.live_count = self.live_count.saturating_add(run_ref.row_count);
14602 self.run_refs.push(run_ref);
14603 self.indexes_complete = false;
14604 true
14605 }
14606
14607 pub(crate) fn kek_ref(&self) -> Option<&Arc<Kek>> {
14608 self.kek.as_ref()
14609 }
14610
14611 pub(crate) fn open_reader(&self, run_id: u128) -> Result<RunReader> {
14612 let mut reader = match self.runs_root.as_deref() {
14613 Some(root) => RunReader::open_file_with_cache(
14614 root.open_regular(format!("r-{run_id}.sr"))?,
14615 self.schema.clone(),
14616 self.kek.clone(),
14617 Some(self.page_cache.clone()),
14618 Some(self.decoded_cache.clone()),
14619 self.table_id,
14620 Some(&self.verified_runs),
14621 None,
14622 )?,
14623 None => RunReader::open_with_cache(
14624 self.dir.join(RUNS_DIR).join(format!("r-{run_id}.sr")),
14625 self.schema.clone(),
14626 self.kek.clone(),
14627 Some(self.page_cache.clone()),
14628 Some(self.decoded_cache.clone()),
14629 self.table_id,
14630 Some(&self.verified_runs),
14631 )?,
14632 };
14633 if let Some(rr) = self.run_refs.iter().find(|r| r.run_id == run_id) {
14637 reader.set_uniform_epoch(Epoch(rr.epoch_created));
14638 }
14639 Ok(reader)
14640 }
14641
14642 pub(crate) fn run_refs(&self) -> &[RunRef] {
14643 &self.run_refs
14644 }
14645
14646 pub(crate) fn retiring_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14647 self.retiring.iter().map(|run| run.run_id)
14648 }
14649
14650 pub(crate) fn runs_dir(&self) -> PathBuf {
14651 self.runs_root
14652 .as_deref()
14653 .and_then(|root| root.io_path().ok())
14654 .unwrap_or_else(|| self.dir.join(RUNS_DIR))
14655 }
14656
14657 pub(crate) fn wal_dir(&self) -> PathBuf {
14658 self.dir.join(WAL_DIR)
14659 }
14660
14661 pub(crate) fn set_run_refs(&mut self, refs: Vec<RunRef>) {
14662 self.run_refs = refs;
14663 self.refresh_run_row_id_ranges();
14664 }
14665
14666 pub(crate) fn run_row_id_range(&self, run_id: u128) -> Option<(u64, u64)> {
14670 self.run_row_id_ranges.get(&run_id).copied()
14671 }
14672
14673 pub(crate) fn refresh_run_row_id_ranges(&mut self) {
14676 let mut ranges = HashMap::with_capacity(self.run_refs.len());
14677 for rr in &self.run_refs {
14678 if let Ok(reader) = self.open_reader(rr.run_id) {
14679 let h = reader.header();
14680 ranges.insert(rr.run_id, (h.min_row_id, h.max_row_id));
14681 }
14682 }
14683 self.run_row_id_ranges = ranges;
14684 }
14685
14686 pub(crate) fn compaction_zstd_level(&self) -> i32 {
14687 self.compaction_zstd_level
14688 }
14689
14690 pub(crate) fn kek(&self) -> Option<Arc<Kek>> {
14691 self.kek.clone()
14692 }
14693
14694 fn idx_dek(&self) -> Option<Zeroizing<[u8; DEK_LEN]>> {
14698 self.kek.as_ref().map(|k| k.derive_idx_key())
14699 }
14700
14701 fn manifest_meta_dek(&self) -> Option<[u8; DEK_LEN]> {
14705 self.kek.as_ref().map(|k| *k.derive_meta_key())
14706 }
14707
14708 pub(crate) fn indexable_column_specs(&self) -> Vec<(u16, u8)> {
14711 self.column_keys
14712 .iter()
14713 .map(|(&id, &(_, scheme))| (id, scheme))
14714 .collect()
14715 }
14716
14717 fn tokenize_value(&self, column_id: u16, v: &Value) -> Option<Value> {
14722 self.tokenize_value_enc(column_id, v)
14723 }
14724
14725 fn tokenize_value_enc(&self, column_id: u16, v: &Value) -> Option<Value> {
14726 use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
14727 let (key, scheme) = self.column_keys.get(&column_id)?;
14728 let token: Vec<u8> = match (*scheme, v) {
14729 (SCHEME_HMAC_EQ, _) => hmac_token(key, &v.encode_key()).to_vec(),
14730 (_, Value::Int64(x)) => ope_token_i64(key, *x).to_vec(),
14731 (_, Value::Float64(x)) => ope_token_f64(key, *x).to_vec(),
14732 _ => hmac_token(key, &v.encode_key()).to_vec(),
14733 };
14734 Some(Value::Bytes(token))
14735 }
14736
14737 fn index_lookup_key(&self, column_id: u16, v: &Value) -> Vec<u8> {
14739 self.index_lookup_key_bytes(column_id, &v.encode_key())
14740 }
14741
14742 fn index_lookup_key_bytes(&self, column_id: u16, encoded: &[u8]) -> Vec<u8> {
14745 {
14746 use crate::encryption::{hmac_token, SCHEME_HMAC_EQ};
14747 if let Some((key, scheme)) = self.column_keys.get(&column_id) {
14748 if *scheme == SCHEME_HMAC_EQ {
14749 return hmac_token(key, encoded).to_vec();
14750 }
14751 }
14752 }
14753 let _ = column_id;
14754 encoded.to_vec()
14755 }
14756}
14757
14758fn native_int64_strictly_increasing(col: &columnar::NativeColumn, n: usize) -> bool {
14759 let columnar::NativeColumn::Int64 { data, validity } = col else {
14760 return false;
14761 };
14762 if data.len() < n || !columnar::all_non_null(validity, n) {
14763 return false;
14764 }
14765 data.iter()
14766 .take(n)
14767 .zip(data.iter().skip(1))
14768 .all(|(a, b)| a < b)
14769}
14770
14771#[derive(Debug, Clone)]
14775pub struct ColumnStat {
14776 pub min: Option<Value>,
14777 pub max: Option<Value>,
14778 pub null_count: u64,
14779}
14780
14781#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14783pub enum NativeAgg {
14784 Count,
14785 Sum,
14786 Min,
14787 Max,
14788 Avg,
14789}
14790
14791#[derive(Debug, Clone, PartialEq)]
14793pub enum NativeAggResult {
14794 Count(u64),
14795 Int(i64),
14796 Float(f64),
14797 Null,
14799}
14800
14801#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14803pub enum ApproxAgg {
14804 Count,
14805 Sum,
14806 Avg,
14807}
14808
14809#[derive(Debug, Clone)]
14813pub struct ApproxResult {
14814 pub point: f64,
14816 pub ci_low: f64,
14818 pub ci_high: f64,
14820 pub n_population: u64,
14822 pub n_sample_live: usize,
14824 pub n_passing: usize,
14826}
14827
14828#[derive(Debug, Clone, PartialEq)]
14833pub enum AggState {
14834 Count(u64),
14836 SumI {
14838 sum: i128,
14839 count: u64,
14840 },
14841 SumF {
14843 sum: f64,
14844 count: u64,
14845 },
14846 AvgI {
14848 sum: i128,
14849 count: u64,
14850 },
14851 AvgF {
14853 sum: f64,
14854 count: u64,
14855 },
14856 MinI(i64),
14858 MaxI(i64),
14859 MinF(f64),
14861 MaxF(f64),
14862 Empty,
14864}
14865
14866impl AggState {
14867 pub fn merge(self, other: AggState) -> AggState {
14869 use AggState::*;
14870 match (self, other) {
14871 (Empty, x) | (x, Empty) => x,
14872 (Count(a), Count(b)) => Count(a + b),
14873 (SumI { sum: sa, count: ca }, SumI { sum: sb, count: cb }) => SumI {
14874 sum: sa + sb,
14875 count: ca + cb,
14876 },
14877 (SumF { sum: sa, count: ca }, SumF { sum: sb, count: cb }) => SumF {
14878 sum: sa + sb,
14879 count: ca + cb,
14880 },
14881 (AvgI { sum: sa, count: ca }, AvgI { sum: sb, count: cb }) => AvgI {
14882 sum: sa + sb,
14883 count: ca + cb,
14884 },
14885 (AvgF { sum: sa, count: ca }, AvgF { sum: sb, count: cb }) => AvgF {
14886 sum: sa + sb,
14887 count: ca + cb,
14888 },
14889 (MinI(a), MinI(b)) => MinI(a.min(b)),
14890 (MaxI(a), MaxI(b)) => MaxI(a.max(b)),
14891 (MinF(a), MinF(b)) => MinF(a.min(b)),
14892 (MaxF(a), MaxF(b)) => MaxF(a.max(b)),
14893 _ => Empty, }
14895 }
14896
14897 pub fn point(&self) -> Option<f64> {
14899 match self {
14900 AggState::Count(n) => Some(*n as f64),
14901 AggState::SumI { sum, .. } => Some(*sum as f64),
14902 AggState::SumF { sum, .. } => Some(*sum),
14903 AggState::AvgI { sum, count } if *count > 0 => Some(*sum as f64 / *count as f64),
14904 AggState::AvgF { sum, count } if *count > 0 => Some(*sum / *count as f64),
14905 AggState::MinI(n) => Some(*n as f64),
14906 AggState::MaxI(n) => Some(*n as f64),
14907 AggState::MinF(n) => Some(*n),
14908 AggState::MaxF(n) => Some(*n),
14909 AggState::AvgI { .. } | AggState::AvgF { .. } | AggState::Empty => None,
14910 }
14911 }
14912
14913 pub fn from_native(result: NativeAggResult, agg: NativeAgg, ty: Option<TypeId>) -> Self {
14917 let is_float = matches!(ty, Some(TypeId::Float64));
14918 match (agg, result) {
14919 (NativeAgg::Count, NativeAggResult::Count(n)) => AggState::Count(n),
14920 (NativeAgg::Sum, NativeAggResult::Int(x)) => AggState::SumI {
14921 sum: x as i128,
14922 count: 1, },
14924 (NativeAgg::Sum, NativeAggResult::Float(x)) => AggState::SumF { sum: x, count: 1 },
14925 (NativeAgg::Avg, NativeAggResult::Float(x)) => AggState::AvgF { sum: x, count: 1 },
14926 (NativeAgg::Min, NativeAggResult::Int(x)) => AggState::MinI(x),
14927 (NativeAgg::Max, NativeAggResult::Int(x)) => AggState::MaxI(x),
14928 (NativeAgg::Min, NativeAggResult::Float(x)) => AggState::MinF(x),
14929 (NativeAgg::Max, NativeAggResult::Float(x)) => AggState::MaxF(x),
14930 (NativeAgg::Count, _) => AggState::Empty,
14931 (_, NativeAggResult::Null) => AggState::Empty,
14932 _ => {
14933 let _ = is_float;
14934 AggState::Empty
14935 }
14936 }
14937 }
14938}
14939
14940#[derive(Debug, Clone)]
14943pub struct CachedAgg {
14944 pub state: AggState,
14945 pub watermark: u64,
14946 pub epoch: u64,
14947}
14948
14949#[derive(Debug, Clone)]
14951pub struct IncrementalAggResult {
14952 pub state: AggState,
14954 pub incremental: bool,
14957 pub delta_rows: u64,
14959}
14960
14961fn agg_state_from_rows(
14965 rows: &[Row],
14966 conditions: &[crate::query::Condition],
14967 index_sets: &[RowIdSet],
14968 column: Option<u16>,
14969 agg: NativeAgg,
14970 schema: &Schema,
14971 control: Option<&crate::ExecutionControl>,
14972) -> Result<AggState> {
14973 let mut count: u64 = 0;
14974 let mut sum_i: i128 = 0;
14975 let mut sum_f: f64 = 0.0;
14976 let mut mn_i: i64 = i64::MAX;
14977 let mut mx_i: i64 = i64::MIN;
14978 let mut mn_f: f64 = f64::INFINITY;
14979 let mut mx_f: f64 = f64::NEG_INFINITY;
14980 let mut saw_int = false;
14981 let mut saw_float = false;
14982 for (index, r) in rows.iter().enumerate() {
14983 execution_checkpoint(control, index)?;
14984 if !conditions
14985 .iter()
14986 .all(|c| condition_matches_row(c, r, schema))
14987 {
14988 continue;
14989 }
14990 if !index_sets.iter().all(|s| s.contains(r.row_id.0)) {
14991 continue;
14992 }
14993 match agg {
14994 NativeAgg::Count => match column {
14995 None => count += 1,
14997 Some(cid) => match r.columns.get(&cid) {
15000 None | Some(Value::Null) => {}
15001 Some(_) => count += 1,
15002 },
15003 },
15004 _ => match column.and_then(|cid| r.columns.get(&cid)) {
15005 Some(Value::Int64(n)) => {
15006 count += 1;
15007 sum_i += *n as i128;
15008 mn_i = mn_i.min(*n);
15009 mx_i = mx_i.max(*n);
15010 saw_int = true;
15011 }
15012 Some(Value::Float64(f)) => {
15013 count += 1;
15014 sum_f += f;
15015 mn_f = mn_f.min(*f);
15016 mx_f = mx_f.max(*f);
15017 saw_float = true;
15018 }
15019 _ => {}
15020 },
15021 }
15022 }
15023 Ok(match agg {
15024 NativeAgg::Count => {
15025 if count == 0 {
15026 AggState::Empty
15027 } else {
15028 AggState::Count(count)
15029 }
15030 }
15031 NativeAgg::Sum => {
15032 if count == 0 {
15033 AggState::Empty
15034 } else if saw_int {
15035 AggState::SumI { sum: sum_i, count }
15036 } else {
15037 AggState::SumF { sum: sum_f, count }
15038 }
15039 }
15040 NativeAgg::Avg => {
15041 if count == 0 {
15042 AggState::Empty
15043 } else if saw_int {
15044 AggState::AvgI { sum: sum_i, count }
15045 } else {
15046 AggState::AvgF { sum: sum_f, count }
15047 }
15048 }
15049 NativeAgg::Min => {
15050 if !saw_int && !saw_float {
15051 AggState::Empty
15052 } else if saw_int {
15053 AggState::MinI(mn_i)
15054 } else {
15055 AggState::MinF(mn_f)
15056 }
15057 }
15058 NativeAgg::Max => {
15059 if !saw_int && !saw_float {
15060 AggState::Empty
15061 } else if saw_int {
15062 AggState::MaxI(mx_i)
15063 } else {
15064 AggState::MaxF(mx_f)
15065 }
15066 }
15067 })
15068}
15069
15070fn condition_matches_row(c: &crate::query::Condition, row: &Row, schema: &Schema) -> bool {
15074 use crate::query::Condition;
15075 match c {
15076 Condition::Pk(key) => match schema.primary_key() {
15077 Some(pk) => row
15078 .columns
15079 .get(&pk.id)
15080 .map(|v| v.encode_key() == *key)
15081 .unwrap_or(false),
15082 None => false,
15083 },
15084 Condition::BitmapEq { column_id, value } => row
15085 .columns
15086 .get(column_id)
15087 .map(|v| v.encode_key() == *value)
15088 .unwrap_or(false),
15089 Condition::BitmapIn { column_id, values } => {
15090 let key = row.columns.get(column_id).map(|v| v.encode_key());
15091 match key {
15092 Some(k) => values.contains(&k),
15093 None => false,
15094 }
15095 }
15096 Condition::BytesPrefix { column_id, prefix } => row
15097 .columns
15098 .get(column_id)
15099 .map(|v| v.encode_key().starts_with(prefix))
15100 .unwrap_or(false),
15101 Condition::Range { column_id, lo, hi } => match row.columns.get(column_id) {
15102 Some(Value::Int64(n)) => *n >= *lo && *n <= *hi,
15103 _ => false,
15104 },
15105 Condition::RangeF64 {
15106 column_id,
15107 lo,
15108 lo_inclusive,
15109 hi,
15110 hi_inclusive,
15111 } => match row.columns.get(column_id) {
15112 Some(Value::Float64(n)) => {
15113 let lo_ok = if *lo_inclusive { *n >= *lo } else { *n > *lo };
15114 let hi_ok = if *hi_inclusive { *n <= *hi } else { *n < *hi };
15115 lo_ok && hi_ok
15116 }
15117 _ => false,
15118 },
15119 Condition::FmContains { column_id, pattern } => match row.columns.get(column_id) {
15120 Some(Value::Bytes(b)) => {
15121 !pattern.is_empty() && b.windows(pattern.len()).any(|w| w == &pattern[..])
15122 }
15123 _ => false,
15124 },
15125 Condition::FmContainsAll {
15126 column_id,
15127 patterns,
15128 } => match row.columns.get(column_id) {
15129 Some(Value::Bytes(b)) => patterns
15130 .iter()
15131 .all(|pat| !pat.is_empty() && b.windows(pat.len()).any(|w| w == &pat[..])),
15132 _ => false,
15133 },
15134 Condition::Ann { .. }
15135 | Condition::SparseMatch { .. }
15136 | Condition::MinHashSimilar { .. } => true,
15137 Condition::IsNull { column_id } => {
15138 matches!(row.columns.get(column_id), Some(Value::Null) | None)
15139 }
15140 Condition::IsNotNull { column_id } => {
15141 !matches!(row.columns.get(column_id), Some(Value::Null) | None)
15142 }
15143 }
15144}
15145
15146fn as_f64(v: Option<&Value>) -> Option<f64> {
15148 match v {
15149 Some(Value::Int64(n)) => Some(*n as f64),
15150 Some(Value::Float64(f)) => Some(*f),
15151 _ => None,
15152 }
15153}
15154
15155fn accumulate_int(
15159 cursor: &mut dyn crate::cursor::Cursor,
15160 control: Option<&crate::ExecutionControl>,
15161) -> Result<(u64, i128, i64, i64)> {
15162 let mut count: u64 = 0;
15163 let mut sum: i128 = 0;
15164 let mut mn: i64 = i64::MAX;
15165 let mut mx: i64 = i64::MIN;
15166 while let Some(cols) = cursor.next_batch()? {
15167 execution_checkpoint(control, 0)?;
15168 if let Some(crate::columnar::NativeColumn::Int64 { data, validity }) = cols.first() {
15169 if crate::columnar::all_non_null(validity, data.len()) {
15170 count += data.len() as u64;
15172 for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15173 execution_checkpoint(control, chunk_index * 1024)?;
15174 sum += chunk.iter().map(|&v| v as i128).sum::<i128>();
15175 mn = mn.min(*chunk.iter().min().unwrap_or(&mn));
15176 mx = mx.max(*chunk.iter().max().unwrap_or(&mx));
15177 }
15178 } else {
15179 for (i, &v) in data.iter().enumerate() {
15180 execution_checkpoint(control, i)?;
15181 if crate::columnar::validity_bit(validity, i) {
15182 count += 1;
15183 sum += v as i128;
15184 mn = mn.min(v);
15185 mx = mx.max(v);
15186 }
15187 }
15188 }
15189 }
15190 }
15191 Ok((count, sum, mn, mx))
15192}
15193
15194fn accumulate_float(
15196 cursor: &mut dyn crate::cursor::Cursor,
15197 control: Option<&crate::ExecutionControl>,
15198) -> Result<(u64, f64, f64, f64)> {
15199 let mut count: u64 = 0;
15200 let mut sum: f64 = 0.0;
15201 let mut mn: f64 = f64::INFINITY;
15202 let mut mx: f64 = f64::NEG_INFINITY;
15203 while let Some(cols) = cursor.next_batch()? {
15204 execution_checkpoint(control, 0)?;
15205 if let Some(crate::columnar::NativeColumn::Float64 { data, validity }) = cols.first() {
15206 if crate::columnar::all_non_null(validity, data.len()) {
15207 count += data.len() as u64;
15208 for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15209 execution_checkpoint(control, chunk_index * 1024)?;
15210 sum += chunk.iter().sum::<f64>();
15211 mn = mn.min(chunk.iter().copied().fold(f64::INFINITY, f64::min));
15212 mx = mx.max(chunk.iter().copied().fold(f64::NEG_INFINITY, f64::max));
15213 }
15214 } else {
15215 for (i, &v) in data.iter().enumerate() {
15216 execution_checkpoint(control, i)?;
15217 if crate::columnar::validity_bit(validity, i) {
15218 count += 1;
15219 sum += v;
15220 mn = mn.min(v);
15221 mx = mx.max(v);
15222 }
15223 }
15224 }
15225 }
15226 }
15227 Ok((count, sum, mn, mx))
15228}
15229
15230#[inline]
15231fn execution_checkpoint(control: Option<&crate::ExecutionControl>, index: usize) -> Result<()> {
15232 if index.is_multiple_of(256) {
15233 control
15234 .map(crate::ExecutionControl::checkpoint)
15235 .transpose()?;
15236 }
15237 Ok(())
15238}
15239
15240fn pack_int(agg: NativeAgg, count: u64, sum: i128, mn: i64, mx: i64) -> NativeAggResult {
15241 if count == 0 && !matches!(agg, NativeAgg::Count) {
15242 return NativeAggResult::Null;
15243 }
15244 match agg {
15245 NativeAgg::Count => NativeAggResult::Count(count),
15246 NativeAgg::Sum => match sum.try_into() {
15249 Ok(v) => NativeAggResult::Int(v),
15250 Err(_) => NativeAggResult::Null,
15251 },
15252 NativeAgg::Min => NativeAggResult::Int(mn),
15253 NativeAgg::Max => NativeAggResult::Int(mx),
15254 NativeAgg::Avg => NativeAggResult::Float((sum as f64) / (count as f64)),
15255 }
15256}
15257
15258fn pack_float(agg: NativeAgg, count: u64, sum: f64, mn: f64, mx: f64) -> NativeAggResult {
15259 if count == 0 && !matches!(agg, NativeAgg::Count) {
15260 return NativeAggResult::Null;
15261 }
15262 match agg {
15263 NativeAgg::Count => NativeAggResult::Count(count),
15264 NativeAgg::Sum => NativeAggResult::Float(sum),
15265 NativeAgg::Min => NativeAggResult::Float(mn),
15266 NativeAgg::Max => NativeAggResult::Float(mx),
15267 NativeAgg::Avg => NativeAggResult::Float(sum / (count as f64)),
15268 }
15269}
15270
15271fn agg_int(
15274 stats: &[crate::page::PageStat],
15275 decode: fn(Option<&[u8]>) -> Option<i64>,
15276) -> Option<(Option<i64>, Option<i64>, u64)> {
15277 let (mut mn, mut mx, mut nulls) = (i64::MAX, i64::MIN, 0u64);
15278 let mut any = false;
15279 for s in stats {
15280 if let Some(v) = decode(s.min.as_deref()) {
15281 mn = mn.min(v);
15282 any = true;
15283 }
15284 if let Some(v) = decode(s.max.as_deref()) {
15285 mx = mx.max(v);
15286 any = true;
15287 }
15288 nulls += s.null_count;
15289 }
15290 any.then_some((Some(mn), Some(mx), nulls))
15291}
15292
15293fn agg_float(
15295 stats: &[crate::page::PageStat],
15296 decode: fn(Option<&[u8]>) -> Option<f64>,
15297) -> Option<(Option<f64>, Option<f64>, u64)> {
15298 let (mut mn, mut mx, mut nulls) = (f64::INFINITY, f64::NEG_INFINITY, 0u64);
15299 let mut any = false;
15300 for s in stats {
15301 if let Some(v) = decode(s.min.as_deref()) {
15302 mn = mn.min(v);
15303 any = true;
15304 }
15305 if let Some(v) = decode(s.max.as_deref()) {
15306 mx = mx.max(v);
15307 any = true;
15308 }
15309 nulls += s.null_count;
15310 }
15311 any.then_some((Some(mn), Some(mx), nulls))
15312}
15313
15314type SecondaryIndexes = (
15316 HashMap<u16, BitmapIndex>,
15317 HashMap<u16, AnnIndex>,
15318 HashMap<u16, FmIndex>,
15319 HashMap<u16, SparseIndex>,
15320 HashMap<u16, MinHashIndex>,
15321);
15322
15323fn empty_indexes(schema: &Schema) -> SecondaryIndexes {
15324 let mut bitmap = HashMap::new();
15325 let mut ann = HashMap::new();
15326 let mut fm = HashMap::new();
15327 let mut sparse = HashMap::new();
15328 let mut minhash = HashMap::new();
15329 for idef in &schema.indexes {
15330 match idef.kind {
15331 IndexKind::Bitmap => {
15332 bitmap.insert(idef.column_id, BitmapIndex::new());
15333 }
15334 IndexKind::Ann => {
15335 let dim = schema
15336 .columns
15337 .iter()
15338 .find(|c| c.id == idef.column_id)
15339 .and_then(|c| match c.ty {
15340 TypeId::Embedding { dim } => Some(dim as usize),
15341 _ => None,
15342 })
15343 .unwrap_or(0);
15344 let options = idef.options.ann.clone().unwrap_or_default();
15345 ann.insert(
15346 idef.column_id,
15347 AnnIndex::with_full_options(
15348 dim,
15349 options.m,
15350 options.ef_construction,
15351 options.ef_search,
15352 &options,
15353 ),
15354 );
15355 }
15356 IndexKind::FmIndex => {
15357 fm.insert(idef.column_id, FmIndex::new());
15358 }
15359 IndexKind::Sparse => {
15360 sparse.insert(idef.column_id, SparseIndex::new());
15361 }
15362 IndexKind::MinHash => {
15363 let options = idef.options.minhash.clone().unwrap_or_default();
15364 minhash.insert(
15365 idef.column_id,
15366 MinHashIndex::with_options(options.permutations, options.bands),
15367 );
15368 }
15369 _ => {}
15370 }
15371 }
15372 (bitmap, ann, fm, sparse, minhash)
15373}
15374
15375const ALTER_COLUMN_PROTECTED_FLAGS: u32 = ColumnFlags::PRIMARY_KEY
15376 | ColumnFlags::AUTO_INCREMENT
15377 | ColumnFlags::ENCRYPTED
15378 | ColumnFlags::ENCRYPTED_INDEXABLE
15379 | ColumnFlags::EMBEDDING_BINARY_QUANTIZED;
15380
15381fn validate_alter_column_flags(old: ColumnFlags, new: ColumnFlags) -> Result<()> {
15382 if (old.bits() ^ new.bits()) & ALTER_COLUMN_PROTECTED_FLAGS != 0 {
15383 return Err(MongrelError::Schema(
15384 "ALTER COLUMN may only change NULLABLE; primary key, auto-increment, encryption, and embedding flags are immutable".into(),
15385 ));
15386 }
15387 Ok(())
15388}
15389
15390fn validate_alter_column_type(
15391 schema: &Schema,
15392 old: &ColumnDef,
15393 next: &ColumnDef,
15394 has_stored_versions: bool,
15395) -> Result<()> {
15396 if old.ty == next.ty {
15397 return Ok(());
15398 }
15399 if schema.indexes.iter().any(|i| i.column_id == old.id) {
15400 return Err(MongrelError::Schema(format!(
15401 "ALTER COLUMN TYPE is not supported for indexed column '{}'",
15402 old.name
15403 )));
15404 }
15405 if !has_stored_versions || storage_compatible_type_change(old.ty.clone(), next.ty.clone()) {
15406 return Ok(());
15407 }
15408 Err(MongrelError::Schema(format!(
15409 "ALTER COLUMN TYPE from {:?} to {:?} requires an empty column or a representation-compatible type",
15410 old.ty, next.ty
15411 )))
15412}
15413
15414fn storage_compatible_type_change(old: TypeId, new: TypeId) -> bool {
15415 matches!(
15416 (old, new),
15417 (TypeId::Int64, TypeId::TimestampNanos) | (TypeId::TimestampNanos, TypeId::Int64)
15418 )
15419}
15420
15421fn rows_pk_strictly_increasing(rows: &[Row], pk_id: u16) -> bool {
15427 let mut prev: Option<i64> = None;
15428 for r in rows {
15429 match r.columns.get(&pk_id) {
15430 Some(Value::Int64(v)) => {
15431 if prev.is_some_and(|p| p >= *v) {
15432 return false;
15433 }
15434 prev = Some(*v);
15435 }
15436 _ => return false,
15437 }
15438 }
15439 true
15440}
15441
15442#[allow(clippy::too_many_arguments)]
15443fn index_into(
15444 schema: &Schema,
15445 row: &Row,
15446 hot: &mut HotIndex,
15447 bitmap: &mut HashMap<u16, BitmapIndex>,
15448 ann: &mut HashMap<u16, AnnIndex>,
15449 fm: &mut HashMap<u16, FmIndex>,
15450 sparse: &mut HashMap<u16, SparseIndex>,
15451 minhash: &mut HashMap<u16, MinHashIndex>,
15452) {
15453 for idef in &schema.indexes {
15454 let Some(val) = row.columns.get(&idef.column_id) else {
15455 continue;
15456 };
15457 match idef.kind {
15458 IndexKind::Bitmap => {
15459 if let Some(b) = bitmap.get_mut(&idef.column_id) {
15460 b.insert(val.encode_key(), row.row_id);
15461 }
15462 }
15463 IndexKind::Ann => {
15464 if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15465 if let Some(meta) = val.generated_embedding_metadata() {
15466 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15468 continue;
15469 }
15470 if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15471 .is_err()
15472 {
15473 continue;
15474 }
15475 }
15476 a.insert_validated(v, row.row_id);
15477 }
15478 }
15479 IndexKind::FmIndex => {
15480 if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15481 f.insert(b.clone(), row.row_id);
15482 }
15483 }
15484 IndexKind::Sparse => {
15485 if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15486 if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15489 s.insert(&terms, row.row_id);
15490 }
15491 }
15492 }
15493 IndexKind::MinHash => {
15494 if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15495 let tokens = crate::index::token_hashes_from_bytes(b);
15498 mh.insert(&tokens, row.row_id);
15499 }
15500 }
15501 _ => {}
15502 }
15503 }
15504 if let Some(pk_col) = schema.primary_key() {
15505 if let Some(pk_val) = row.columns.get(&pk_col.id) {
15506 hot.insert(pk_val.encode_key(), row.row_id);
15507 }
15508 }
15509}
15510
15511#[allow(clippy::too_many_arguments)]
15514fn index_into_single(
15515 idef: &IndexDef,
15516 _schema: &Schema,
15517 row: &Row,
15518 _hot: &mut HotIndex,
15519 bitmap: &mut HashMap<u16, BitmapIndex>,
15520 ann: &mut HashMap<u16, AnnIndex>,
15521 fm: &mut HashMap<u16, FmIndex>,
15522 sparse: &mut HashMap<u16, SparseIndex>,
15523 minhash: &mut HashMap<u16, MinHashIndex>,
15524) {
15525 let Some(val) = row.columns.get(&idef.column_id) else {
15526 return;
15527 };
15528 match idef.kind {
15529 IndexKind::Bitmap => {
15530 if let Some(b) = bitmap.get_mut(&idef.column_id) {
15531 b.insert(val.encode_key(), row.row_id);
15532 }
15533 }
15534 IndexKind::Ann => {
15535 if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15536 if let Some(meta) = val.generated_embedding_metadata() {
15537 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15539 return;
15540 }
15541 if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15542 .is_err()
15543 {
15544 return;
15545 }
15546 }
15547 a.insert_validated(v, row.row_id);
15548 }
15549 }
15550 IndexKind::FmIndex => {
15551 if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15552 f.insert(b.clone(), row.row_id);
15553 }
15554 }
15555 IndexKind::Sparse => {
15556 if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15557 if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15558 s.insert(&terms, row.row_id);
15559 }
15560 }
15561 }
15562 IndexKind::MinHash => {
15563 if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15564 let tokens = crate::index::token_hashes_from_bytes(b);
15565 mh.insert(&tokens, row.row_id);
15566 }
15567 }
15568 _ => {}
15569 }
15570}
15571
15572fn eval_partial_predicate(
15578 pred: &str,
15579 columns_map: &HashMap<u16, &Value>,
15580 name_to_id: &HashMap<&str, u16>,
15581) -> bool {
15582 let lower = pred.trim().to_ascii_lowercase();
15583 if let Some(rest) = lower.strip_suffix(" is not null") {
15585 let col_name = rest.trim();
15586 if let Some(col_id) = name_to_id.get(col_name) {
15587 return columns_map
15588 .get(col_id)
15589 .is_some_and(|v| !matches!(v, Value::Null));
15590 }
15591 }
15592 if let Some(rest) = lower.strip_suffix(" is null") {
15594 let col_name = rest.trim();
15595 if let Some(col_id) = name_to_id.get(col_name) {
15596 return columns_map
15597 .get(col_id)
15598 .is_none_or(|v| matches!(v, Value::Null));
15599 }
15600 }
15601 true
15604}
15605
15606#[allow(dead_code)]
15612fn bulk_index_key(
15613 column_keys: &HashMap<u16, ([u8; 32], u8)>,
15614 column_id: u16,
15615 ty: TypeId,
15616 col: &columnar::NativeColumn,
15617 i: usize,
15618) -> Option<Vec<u8>> {
15619 let encoded = columnar::encode_key_native(ty, col, i)?;
15620 {
15621 use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
15622 if let Some((key, scheme)) = column_keys.get(&column_id) {
15623 return Some(match (*scheme, col) {
15624 (SCHEME_HMAC_EQ, _) => hmac_token(key, &encoded).to_vec(),
15625 (_, columnar::NativeColumn::Int64 { data, .. }) => {
15626 ope_token_i64(key, data[i]).to_vec()
15627 }
15628 (_, columnar::NativeColumn::Float64 { data, .. }) => {
15629 ope_token_f64(key, data[i]).to_vec()
15630 }
15631 _ => hmac_token(key, &encoded).to_vec(),
15632 });
15633 }
15634 }
15635 Some(encoded)
15636}
15637
15638pub(crate) fn write_schema(dir: &Path, schema: &Schema) -> Result<()> {
15639 write_schema_with_after(dir, schema, || {})
15640}
15641
15642pub(crate) fn write_schema_durable(
15643 root: &crate::durable_file::DurableRoot,
15644 schema: &Schema,
15645) -> Result<()> {
15646 write_schema_durable_with_after(root, schema, || {})
15647}
15648
15649fn write_schema_with_after<F>(dir: &Path, schema: &Schema, after_publish: F) -> Result<()>
15650where
15651 F: FnOnce(),
15652{
15653 let json = serde_json::to_string_pretty(schema)
15654 .map_err(|e| MongrelError::Schema(format!("encode schema: {e}")))?;
15655 crate::durable_file::write_atomic_with_after(
15656 &dir.join(SCHEMA_FILENAME),
15657 json.as_bytes(),
15658 after_publish,
15659 )?;
15660 Ok(())
15661}
15662
15663fn write_schema_durable_with_after<F>(
15664 root: &crate::durable_file::DurableRoot,
15665 schema: &Schema,
15666 after_publish: F,
15667) -> Result<()>
15668where
15669 F: FnOnce(),
15670{
15671 let json = serde_json::to_string_pretty(schema)
15672 .map_err(|error| MongrelError::Schema(format!("encode schema: {error}")))?;
15673 root.write_atomic_with_after(SCHEMA_FILENAME, json.as_bytes(), after_publish)?;
15674 Ok(())
15675}
15676
15677fn checkpoint_current_schema(table: &mut Table) -> Result<()> {
15678 let mut schema_published = false;
15679 let schema_result = match table._root_guard.as_deref() {
15680 Some(root) => write_schema_durable_with_after(root, &table.schema, || {
15681 schema_published = true;
15682 }),
15683 None => write_schema_with_after(&table.dir, &table.schema, || {
15684 schema_published = true;
15685 }),
15686 };
15687 if schema_result.is_err() && !schema_published {
15688 return schema_result;
15689 }
15690 match table.persist_manifest(table.current_epoch()) {
15691 Ok(()) => Ok(()),
15692 Err(manifest_error) => Err(match schema_result {
15693 Ok(()) => manifest_error,
15694 Err(schema_error) => MongrelError::Other(format!(
15695 "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
15696 )),
15697 }),
15698 }
15699}
15700
15701fn read_schema(dir: &Path) -> Result<Schema> {
15702 let file = crate::durable_file::open_regular_nofollow(&dir.join(SCHEMA_FILENAME))?;
15703 read_schema_file(file)
15704}
15705
15706fn read_schema_file(file: std::fs::File) -> Result<Schema> {
15707 const MAX_SCHEMA_BYTES: u64 = 16 * 1024 * 1024;
15708 use std::io::Read;
15709
15710 let length = file.metadata()?.len();
15711 if length > MAX_SCHEMA_BYTES {
15712 return Err(MongrelError::ResourceLimitExceeded {
15713 resource: "schema bytes",
15714 requested: usize::try_from(length).unwrap_or(usize::MAX),
15715 limit: MAX_SCHEMA_BYTES as usize,
15716 });
15717 }
15718 let mut bytes = Vec::with_capacity(length as usize);
15719 file.take(MAX_SCHEMA_BYTES + 1).read_to_end(&mut bytes)?;
15720 if bytes.len() as u64 != length {
15721 return Err(MongrelError::Schema(
15722 "schema length changed while reading".into(),
15723 ));
15724 }
15725 serde_json::from_slice(&bytes).map_err(|e| MongrelError::Schema(format!("decode schema: {e}")))
15726}
15727
15728fn preflight_standalone_open(
15729 dir: &Path,
15730 runs_root: Option<&crate::durable_file::DurableRoot>,
15731 idx_root: Option<&crate::durable_file::DurableRoot>,
15732 manifest: &Manifest,
15733 schema: &Schema,
15734 records: &[crate::wal::Record],
15735 kek: Option<Arc<Kek>>,
15736) -> Result<()> {
15737 crate::wal::validate_shared_transaction_framing(records)?;
15738 if manifest.schema_id > schema.schema_id
15739 || manifest.flushed_epoch > manifest.current_epoch
15740 || manifest.global_idx_epoch > manifest.current_epoch
15741 || manifest.next_row_id == u64::MAX
15742 || manifest.auto_inc_next < 0
15743 || manifest.auto_inc_next == i64::MAX
15744 || (schema.auto_increment_column().is_none() && manifest.auto_inc_next != 0)
15745 {
15746 return Err(MongrelError::InvalidArgument(
15747 "manifest counters or schema identity are invalid".into(),
15748 ));
15749 }
15750 let mut run_ids = HashSet::new();
15751 let mut maximum_row_id = None::<u64>;
15752 for run in &manifest.runs {
15753 if run.run_id >= u64::MAX as u128
15754 || !run_ids.insert(run.run_id)
15755 || run.epoch_created > manifest.current_epoch
15756 {
15757 return Err(MongrelError::InvalidArgument(
15758 "manifest contains an invalid or duplicate active run".into(),
15759 ));
15760 }
15761 let mut reader = match runs_root {
15762 Some(root) => RunReader::open_file(
15763 root.open_regular(format!("r-{}.sr", run.run_id as u64))?,
15764 schema.clone(),
15765 kek.clone(),
15766 )?,
15767 None => RunReader::open(
15768 dir.join(RUNS_DIR)
15769 .join(format!("r-{}.sr", run.run_id as u64)),
15770 schema.clone(),
15771 kek.clone(),
15772 )?,
15773 };
15774 let header = reader.header();
15775 if header.run_id != run.run_id
15776 || header.level != run.level
15777 || header.row_count != run.row_count
15778 || !header.is_uniform_epoch() && header.epoch_created != run.epoch_created
15779 || header.is_uniform_epoch() && header.epoch_created != 0
15780 || header.schema_id > schema.schema_id
15781 {
15782 return Err(MongrelError::InvalidArgument(format!(
15783 "run {} differs from its manifest",
15784 run.run_id
15785 )));
15786 }
15787 if header.row_count != 0 {
15788 maximum_row_id = Some(
15789 maximum_row_id.map_or(header.max_row_id, |value| value.max(header.max_row_id)),
15790 );
15791 }
15792 reader.validate_all_pages()?;
15793 }
15794 if maximum_row_id.is_some_and(|maximum| manifest.next_row_id <= maximum) {
15795 return Err(MongrelError::InvalidArgument(
15796 "manifest next_row_id does not advance beyond persisted rows".into(),
15797 ));
15798 }
15799 for run in &manifest.retiring {
15800 if run.run_id >= u64::MAX as u128
15801 || run.retire_epoch > manifest.current_epoch
15802 || !run_ids.insert(run.run_id)
15803 {
15804 return Err(MongrelError::InvalidArgument(
15805 "manifest contains an invalid or duplicate retired run".into(),
15806 ));
15807 }
15808 }
15809 let idx_dek = kek.as_ref().map(|key| key.derive_idx_key());
15810 match idx_root {
15811 Some(root) => {
15812 global_idx::read_root(root, manifest.table_id, schema, idx_dek.as_deref())?;
15813 }
15814 None => {
15815 global_idx::read(dir, manifest.table_id, schema, idx_dek.as_deref())?;
15816 }
15817 }
15818
15819 let committed = records
15820 .iter()
15821 .filter_map(|record| match record.op {
15822 Op::TxnCommit { epoch, .. } => Some((record.txn_id, epoch)),
15823 _ => None,
15824 })
15825 .collect::<HashMap<_, _>>();
15826 for record in records {
15827 let Some(&_commit_epoch) = committed.get(&record.txn_id) else {
15828 continue;
15829 };
15830 match &record.op {
15831 Op::Put { table_id, rows } => {
15832 if *table_id != manifest.table_id {
15833 return Err(MongrelError::CorruptWal {
15834 offset: record.seq.0,
15835 reason: format!(
15836 "private WAL record references table {table_id}, expected {}",
15837 manifest.table_id
15838 ),
15839 });
15840 }
15841 let rows: Vec<Row> =
15842 bincode::deserialize(rows).map_err(|error| MongrelError::CorruptWal {
15843 offset: record.seq.0,
15844 reason: format!("committed Put payload could not be decoded: {error}"),
15845 })?;
15846 for row in rows {
15847 if row.deleted || row.row_id.0 == u64::MAX {
15848 return Err(MongrelError::CorruptWal {
15849 offset: record.seq.0,
15850 reason: "committed Put contains an invalid row identity".into(),
15851 });
15852 }
15853 let cells = row.columns.into_iter().collect::<Vec<_>>();
15854 schema
15855 .validate_values(&cells)
15856 .map_err(|error| MongrelError::CorruptWal {
15857 offset: record.seq.0,
15858 reason: format!("committed Put violates table schema: {error}"),
15859 })?;
15860 if schema.auto_increment_column().is_some_and(|column| {
15861 matches!(
15862 cells.iter().find(|(id, _)| *id == column.id),
15863 Some((_, Value::Int64(value))) if *value == i64::MAX
15864 )
15865 }) {
15866 return Err(MongrelError::CorruptWal {
15867 offset: record.seq.0,
15868 reason: "committed Put exhausts AUTO_INCREMENT".into(),
15869 });
15870 }
15871 }
15872 }
15873 Op::Delete { table_id, .. } | Op::TruncateTable { table_id }
15874 if *table_id != manifest.table_id =>
15875 {
15876 return Err(MongrelError::CorruptWal {
15877 offset: record.seq.0,
15878 reason: format!(
15879 "private WAL record references table {table_id}, expected {}",
15880 manifest.table_id
15881 ),
15882 });
15883 }
15884 Op::TxnCommit { added_runs, .. } if !added_runs.is_empty() => {
15885 return Err(MongrelError::CorruptWal {
15886 offset: record.seq.0,
15887 reason: "private WAL contains shared spilled-run metadata".into(),
15888 });
15889 }
15890 _ => {}
15891 }
15892 }
15893 Ok(())
15894}
15895
15896fn next_wal_segment(wal_dir: &Path) -> Result<PathBuf> {
15897 Ok(wal_dir.join(format!("seg-{:06}.wal", next_wal_number(wal_dir)?)))
15898}
15899
15900fn wal_segment_number(path: &Path) -> Option<u64> {
15901 path.file_stem()
15902 .and_then(|stem| stem.to_str())
15903 .and_then(|stem| stem.strip_prefix("seg-"))
15904 .and_then(|number| number.parse().ok())
15905}
15906
15907fn latest_wal_segment(wal_dir: &Path) -> Result<Option<PathBuf>> {
15908 let n = list_wal_numbers(wal_dir)?;
15909 Ok(n.map(|max| wal_dir.join(format!("seg-{max:06}.wal"))))
15910}
15911
15912fn next_wal_number(wal_dir: &Path) -> Result<u32> {
15913 list_wal_numbers(wal_dir)?
15914 .map(|maximum| {
15915 maximum
15916 .checked_add(1)
15917 .ok_or_else(|| MongrelError::Full("WAL segment namespace exhausted".into()))
15918 })
15919 .unwrap_or(Ok(0))
15920}
15921
15922fn list_wal_numbers(wal_dir: &Path) -> Result<Option<u32>> {
15923 let mut max_n = None;
15924 let entries = match std::fs::read_dir(wal_dir) {
15925 Ok(entries) => entries,
15926 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
15927 Err(error) => return Err(error.into()),
15928 };
15929 for entry in entries {
15930 let entry = entry?;
15931 let fname = entry.file_name();
15932 let Some(s) = fname.to_str() else {
15933 continue;
15934 };
15935 let Some(stripped) = s.strip_prefix("seg-") else {
15936 continue;
15937 };
15938 let Some(number) = stripped.strip_suffix(".wal") else {
15939 return Err(MongrelError::CorruptWal {
15940 offset: 0,
15941 reason: format!("malformed WAL segment name {s:?}"),
15942 });
15943 };
15944 let n = number
15945 .parse::<u32>()
15946 .map_err(|_| MongrelError::CorruptWal {
15947 offset: 0,
15948 reason: format!("malformed WAL segment name {s:?}"),
15949 })?;
15950 if s != format!("seg-{n:06}.wal") || !entry.file_type()?.is_file() {
15951 return Err(MongrelError::CorruptWal {
15952 offset: n as u64,
15953 reason: format!("noncanonical or nonregular WAL segment {s:?}"),
15954 });
15955 }
15956 max_n = Some(max_n.map(|m: u32| m.max(n)).unwrap_or(n));
15957 }
15958 Ok(max_n)
15959}
15960
15961#[cfg(test)]
15986mod rem001_multi_run_hlc_authority {
15987 use super::*;
15988 use crate::epoch::{Epoch, Snapshot, VersionStamp};
15989 use crate::memtable::{Row, Value};
15990 use crate::query::{Condition, Query};
15991 use crate::schema::{ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
15992 use mongreldb_types::hlc::HlcTimestamp;
15993 use tempfile::tempdir;
15994
15995 fn hlc(physical_micros: u64) -> HlcTimestamp {
15996 HlcTimestamp {
15997 physical_micros,
15998 logical: 0,
15999 node_tiebreaker: 1,
16000 }
16001 }
16002
16003 fn pk_schema() -> Schema {
16004 Schema {
16005 schema_id: 1,
16006 columns: vec![
16007 ColumnDef {
16008 id: 1,
16009 name: "id".into(),
16010 ty: TypeId::Int64,
16011 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16012 default_value: None,
16013 embedding_source: None,
16014 },
16015 ColumnDef {
16016 id: 2,
16017 name: "name".into(),
16018 ty: TypeId::Bytes,
16019 flags: ColumnFlags::empty(),
16020 default_value: None,
16021 embedding_source: None,
16022 },
16023 ],
16024 indexes: Vec::new(),
16025 colocation: vec![],
16026 constraints: Default::default(),
16027 clustered: false,
16028 }
16029 }
16030
16031 fn pk_schema_with_bitmap() -> Schema {
16032 Schema {
16033 schema_id: 1,
16034 columns: vec![
16035 ColumnDef {
16036 id: 1,
16037 name: "id".into(),
16038 ty: TypeId::Int64,
16039 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16040 default_value: None,
16041 embedding_source: None,
16042 },
16043 ColumnDef {
16044 id: 2,
16045 name: "name".into(),
16046 ty: TypeId::Bytes,
16047 flags: ColumnFlags::empty(),
16048 default_value: None,
16049 embedding_source: None,
16050 },
16051 ],
16052 indexes: vec![IndexDef {
16055 name: "name_bitmap".into(),
16056 column_id: 2,
16057 kind: IndexKind::Bitmap,
16058 predicate: None,
16059 options: Default::default(),
16060 }],
16061 colocation: vec![],
16062 constraints: Default::default(),
16063 clustered: false,
16064 }
16065 }
16066
16067 fn encode_put(table_id: u64, row: &Row) -> Vec<u8> {
16068 use crate::database::StagedTxnWrite;
16069 bincode::serialize(&StagedTxnWrite::Put {
16070 table_id,
16071 rows: bincode::serialize(&vec![row.clone()]).expect("encode row"),
16072 })
16073 .expect("encode payload")
16074 }
16075
16076 fn build_inverted_database(dir: &std::path::Path, schema: Schema) -> crate::Database {
16090 let db = crate::Database::create(dir).unwrap();
16091 db.create_table("t", schema).unwrap();
16092 let table_id = db.table_id("t").unwrap();
16093 let rid = RowId(7);
16094
16095 let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16096 .with_column(1, Value::Int64(7))
16097 .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()));
16098 let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16099 .with_column(1, Value::Int64(7))
16100 .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()));
16101
16102 db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16103 .expect("first apply");
16104 {
16105 let table = db.table("t").unwrap();
16106 table.lock().force_flush().expect("flush run A");
16107 }
16108
16109 db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16110 .expect("second apply");
16111 {
16112 let table = db.table("t").unwrap();
16113 table.lock().force_flush().expect("flush run B");
16114 }
16115
16116 db
16117 }
16118
16119 fn build_inverted_ttl_database(dir: &std::path::Path) -> crate::Database {
16124 let db = crate::Database::create(dir).unwrap();
16125 db.create_table("t", ttl_schema()).unwrap();
16126 let table_id = db.table_id("t").unwrap();
16127 let rid = RowId(7);
16128 let read_time_ns: i64 = 1_000_000_000;
16129 let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16130 .with_column(1, Value::Int64(7))
16131 .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()))
16132 .with_column(3, Value::Int64(read_time_ns + 60 * 1_000_000_000));
16133 let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16134 .with_column(1, Value::Int64(7))
16135 .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()))
16136 .with_column(3, Value::Int64(read_time_ns - 60 * 1_000_000_000));
16137
16138 db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16139 .expect("first apply");
16140 {
16141 let table = db.table("t").unwrap();
16142 table.lock().force_flush().expect("flush run A");
16143 }
16144 db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16145 .expect("second apply");
16146 {
16147 let table = db.table("t").unwrap();
16148 table.lock().force_flush().expect("flush run B");
16149 }
16150
16151 db
16152 }
16153
16154 fn ttl_schema() -> Schema {
16155 Schema {
16156 schema_id: 1,
16157 columns: vec![
16158 ColumnDef {
16159 id: 1,
16160 name: "id".into(),
16161 ty: TypeId::Int64,
16162 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16163 default_value: None,
16164 embedding_source: None,
16165 },
16166 ColumnDef {
16167 id: 2,
16168 name: "name".into(),
16169 ty: TypeId::Bytes,
16170 flags: ColumnFlags::empty(),
16171 default_value: None,
16172 embedding_source: None,
16173 },
16174 ColumnDef {
16175 id: 3,
16176 name: "ttl_ts".into(),
16177 ty: TypeId::Int64,
16178 flags: ColumnFlags::empty(),
16179 default_value: None,
16180 embedding_source: None,
16181 },
16182 ],
16183 indexes: Vec::new(),
16184 colocation: vec![],
16185 constraints: Default::default(),
16186 clustered: false,
16187 }
16188 }
16189
16190 #[test]
16191 fn multi_run_rows_for_rids_uses_hlc_winner_when_epoch_is_inverted() {
16192 let dir = tempdir().unwrap();
16193 let db = build_inverted_database(dir.path(), pk_schema());
16194 let table = db.table("t").unwrap();
16195 let table = table.lock();
16196 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16200 let rows = table
16201 .rows_for_rids(&[7], snap)
16202 .expect("rows_for_rids across two runs");
16203 assert_eq!(rows.len(), 1, "one row materialised across two runs");
16204 assert_eq!(
16205 rows[0].columns.get(&2),
16206 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16207 "multi-run rows_for_rids must honor HLC authority"
16208 );
16209 }
16210
16211 #[test]
16212 fn multi_run_projected_column_uses_hlc_winner_when_epoch_is_inverted() {
16213 let dir = tempdir().unwrap();
16214 let db = build_inverted_database(dir.path(), pk_schema());
16215 let table = db.table("t").unwrap();
16216 let table = table.lock();
16217 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16218 let projected = table
16219 .values_for_rids_at(&[7], 2, snap, i64::MAX)
16220 .expect("values_for_rids_at across two runs");
16221 assert_eq!(projected.len(), 1);
16222 assert_eq!(
16223 projected[0].1,
16224 Value::Bytes(b"newer-by-HLC".to_vec()),
16225 "multi-run projection must pick the HLC-newer column"
16226 );
16227 }
16228
16229 #[test]
16230 fn ann_candidate_eligibility_uses_hlc_winner_across_runs() {
16231 let dir = tempdir().unwrap();
16232 let db = build_inverted_database(dir.path(), pk_schema());
16233 let table = db.table("t").unwrap();
16234 let table = table.lock();
16235 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16236 let eligible = table
16239 .eligible_candidate_ids(&[RowId(7)], 2, snap, None)
16240 .expect("eligibility across runs");
16241 assert!(
16242 eligible.contains(&RowId(7)),
16243 "HLC-newer rid must remain eligible across runs"
16244 );
16245 }
16246
16247 #[test]
16248 fn ttl_inverted_run_is_admitted_via_values_for_rids_at() {
16249 let dir = tempdir().unwrap();
16250 let db = build_inverted_ttl_database(dir.path());
16251 let table = db.table("t").unwrap();
16252 let table = table.lock();
16253 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16254 let now_ns: i64 = 1_000_000_000;
16255 let projected = table
16259 .values_for_rids_at(&[7], 2, snap, now_ns)
16260 .expect("ttl-aware projection");
16261 assert_eq!(projected.len(), 1, "TTL must admit the HLC-newer row");
16262 assert_eq!(
16263 projected[0].1,
16264 Value::Bytes(b"newer-by-HLC".to_vec()),
16265 "TTL must be read from the HLC-newer run; older run's timestamp is expired"
16266 );
16267 }
16268
16269 #[test]
16270 fn hot_candidate_inspection_uses_full_snapshot_for_run_versions() {
16271 let dir = tempdir().unwrap();
16276 let db = build_inverted_database(dir.path(), pk_schema());
16277 let table = db.table("t").unwrap();
16278 let table = table.lock();
16279 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16280 let row = table
16281 .get(RowId(7), snap)
16282 .expect("Table::get across two runs");
16283 assert_eq!(
16284 row.columns.get(&2),
16285 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16286 "Table::get must surface the HLC-newer winner"
16287 );
16288 }
16289
16290 #[test]
16291 fn learned_range_rebuild_indexes_only_hlc_visible_winners() {
16292 let dir = tempdir().unwrap();
16299 let db = build_inverted_database(dir.path(), pk_schema());
16300 let handle = db.table("t").unwrap();
16301 let mut table = handle.lock();
16302 table.rebuild_indexes_from_runs().expect("rebuild");
16303 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16304 let rows = table
16305 .rows_for_rids(&[7], snap)
16306 .expect("post-rebuild rows_for_rids");
16307 assert_eq!(rows.len(), 1);
16308 assert_eq!(
16309 rows[0].columns.get(&2),
16310 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16311 "post-rebuild row must be the HLC-newer winner"
16312 );
16313 }
16314
16315 #[test]
16316 fn rebuild_indexes_uses_global_hlc_winners_not_run_iteration_order() {
16317 let dir = tempdir().unwrap();
16330 let db = build_inverted_database(dir.path(), pk_schema_with_bitmap());
16331 let handle = db.table("t").unwrap();
16332 let mut table = handle.lock();
16333 table.rebuild_indexes_from_runs().expect("rebuild");
16334 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16335 let row = table.get(RowId(7), snap).expect("post-rebuild Table::get");
16337 assert_eq!(
16338 row.columns.get(&2),
16339 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16340 "PK lookup must resolve to the HLC-newer winner"
16341 );
16342 let query_newer = Query::new().and(Condition::BitmapEq {
16346 column_id: 2,
16347 value: b"newer-by-HLC".to_vec(),
16348 });
16349 let rows_newer = table.query(&query_newer).expect("bitmap eq newer");
16350 let rids_newer: Vec<u64> = rows_newer.iter().map(|r| r.row_id.0).collect();
16351 assert!(
16352 rids_newer.contains(&7),
16353 "bitmap must include the HLC-newer value (got {rids_newer:?})"
16354 );
16355 let query_older = Query::new().and(Condition::BitmapEq {
16356 column_id: 2,
16357 value: b"older-by-HLC".to_vec(),
16358 });
16359 let rows_older = table.query(&query_older).expect("bitmap eq older");
16360 let rids_older: Vec<u64> = rows_older.iter().map(|r| r.row_id.0).collect();
16361 assert!(
16362 !rids_older.contains(&7),
16363 "bitmap must NOT include the HLC-older value (got {rids_older:?})"
16364 );
16365 }
16366
16367 #[test]
16368 fn version_stamp_is_newer_than_matches_snapshot_rule() {
16369 let early = hlc(100);
16372 let late = hlc(200);
16373 let newer = VersionStamp {
16374 epoch: Epoch(9),
16375 commit_ts: Some(late),
16376 };
16377 let older = VersionStamp {
16378 epoch: Epoch(50),
16379 commit_ts: Some(early),
16380 };
16381 assert!(newer.is_newer_than(older));
16382 assert!(!older.is_newer_than(newer));
16383 let a = VersionStamp {
16384 epoch: Epoch(5),
16385 commit_ts: None,
16386 };
16387 let b = VersionStamp {
16388 epoch: Epoch(4),
16389 commit_ts: None,
16390 };
16391 assert!(a.is_newer_than(b));
16392 }
16393}