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 {
3838 let (losers, winner_pks) = db.partition_pk_winners(&group);
3839 for (key, &row_id) in &winner_pks {
3840 if let Some(old_rid) = db.hot.get(key) {
3841 if old_rid != row_id {
3842 db.tombstone_row(old_rid, epoch, None, false);
3843 }
3844 }
3845 }
3846 for &loser_rid in &losers {
3847 db.tombstone_row(loser_rid, epoch, None, false);
3848 }
3849 for (key, row_id) in winner_pks {
3850 db.insert_hot_pk(key, row_id);
3851 }
3852 if db.schema.primary_key().is_none() {
3853 for r in &group {
3854 db.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
3855 }
3856 }
3857 for r in &group {
3858 if !losers.contains(&r.row_id) {
3859 db.index_row(r);
3860 }
3861 }
3862 }
3863 for (rid, epoch) in &replayed_deletes {
3867 db.remove_hot_for_row(*rid, *epoch);
3868 }
3869
3870 if recovered_manifest_dirty {
3871 let rows = db.visible_rows(Snapshot::unbounded())?;
3872 db.live_count = rows.len() as u64;
3873 db.persist_manifest(Epoch(recovered_epoch))?;
3874 }
3875
3876 let identity = crate::result_cache::PersistentCacheIdentity {
3883 table_id: db.table_id,
3884 schema_id: db.schema.schema_id,
3885 logical_generation: db.epoch.visible().0,
3886 };
3887 db.result_cache.lock().load_persistent(identity);
3888 db.refresh_run_row_id_ranges();
3890 db.load_run_lookup_directory();
3895 Ok(db)
3896 }
3897
3898 fn load_run_lookup_directory(&mut self) {
3903 let active_runs = self.run_refs.clone();
3904 let schema_id = self.schema.schema_id;
3905 let run_generation = active_runs.len() as u64;
3906 let index_generation = self.global_idx_epoch;
3907 let fingerprint = crate::run_lookup::compute_fingerprint(
3908 &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
3909 schema_id,
3910 index_generation,
3911 run_generation,
3912 crate::run_lookup::DIRECTORY_FORMAT_VERSION,
3913 );
3914 let runs_dir = match self.runs_root.as_deref() {
3916 Some(root) => match root.io_path() {
3917 Ok(p) => p,
3918 Err(_) => self.dir.join(RUNS_DIR),
3919 },
3920 None => self.dir.join(RUNS_DIR),
3921 };
3922 match crate::run_lookup::RunLookupDirectory::read_checkpoint_sharded(&runs_dir, fingerprint)
3923 {
3924 Ok(dir) => {
3925 self.run_lookup = RunLookupState {
3926 directory: Some(std::sync::Arc::new(dir)),
3927 fingerprint,
3928 complete: true,
3929 };
3930 }
3931 Err(error) => {
3932 self.lookup_metrics
3933 .directory_incomplete
3934 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3935 self.lookup_metrics
3936 .directory_lookup_fallback
3937 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3938 self.run_lookup = RunLookupState {
3939 directory: None,
3940 fingerprint,
3941 complete: false,
3942 };
3943 let _ = error;
3947 }
3948 }
3949 }
3950
3951 fn ensure_reservoir_complete(&mut self) -> Result<()> {
3957 if self.reservoir_complete {
3958 return Ok(());
3959 }
3960 self.rebuild_reservoir()?;
3961 self.reservoir_complete = true;
3962 Ok(())
3963 }
3964
3965 fn rebuild_reservoir(&mut self) -> Result<()> {
3968 let snap = self.snapshot();
3969 let rows = self.visible_rows(snap)?;
3970 self.reservoir.reset();
3971 for r in rows {
3972 self.reservoir.offer(r.row_id.0);
3973 }
3974 Ok(())
3975 }
3976
3977 pub fn rebuild_indexes(&mut self) -> Result<()> {
3981 self.rebuild_indexes_from_runs_inner(None)
3982 }
3983
3984 pub fn __force_hot_map_for_test(&mut self, pk_bytes: &[u8], row_id: RowId) {
3995 self.hot.insert(pk_bytes.to_vec(), row_id);
3996 }
3997
3998 pub fn hot_for_test_remove(&mut self, pk_bytes: &[u8]) {
4001 self.hot.remove(pk_bytes);
4002 }
4003
4004 pub fn set_indexes_incomplete_for_test(&mut self) {
4007 self.indexes_complete = false;
4008 }
4009
4010 pub fn bump_hot_checkpoint_rejected_for_test(&self) {
4014 self.lookup_metrics
4015 .hot_checkpoint_rejected_total
4016 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4017 }
4018
4019 pub fn __install_run_for_test(&mut self, rows: &[Row]) -> Result<u128> {
4026 let mut rows = rows.to_vec();
4027 rows.sort_by_key(|r| (r.row_id, r.committed_epoch));
4028 let epoch = rows
4029 .iter()
4030 .map(|r| r.committed_epoch)
4031 .max()
4032 .unwrap_or(Epoch::ZERO);
4033 let run_id = self.alloc_run_id()?;
4034 let path = self.run_path(run_id);
4035 if let Some(parent) = path.parent() {
4036 std::fs::create_dir_all(parent)
4037 .map_err(|e| MongrelError::Other(format!("create runs dir: {e}")))?;
4038 }
4039 let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
4040 if let Some(kek) = &self.kek {
4041 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
4042 }
4043 let header = match self.create_run_file(run_id)? {
4044 Some(file) => writer.write_file(file, &rows)?,
4045 None => writer.write(&path, &rows)?,
4046 };
4047 self.run_refs.push(RunRef {
4048 run_id: run_id as u128,
4049 level: 0,
4050 epoch_created: epoch.0,
4051 row_count: header.row_count,
4052 });
4053 self.run_row_id_ranges
4054 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
4055 Ok(run_id as u128)
4056 }
4057
4058 pub fn __rebuild_run_lookup_for_test(&mut self) -> Result<()> {
4063 self.publish_run_lookup_directory()
4064 }
4065
4066 pub fn __set_run_lookup_complete_for_test(&mut self, complete: bool) {
4073 self.run_lookup.complete = complete;
4074 }
4075
4076 pub(crate) fn rebuild_indexes_from_runs(&mut self) -> Result<()> {
4077 self.rebuild_indexes_from_runs_inner(None)
4078 }
4079
4080 fn pk_equality_fallback(
4107 &self,
4108 pk_column_id: u16,
4109 lookup: &[u8],
4110 snapshot: Snapshot,
4111 ) -> Result<(RowIdSet, crate::trace::HotFallbackReason)> {
4112 let mut tombstone_hit = false;
4113 let mut overlay_versions = 0u64;
4114 let now_nanos = unix_nanos_now();
4115 for row in self.memtable.visible_versions_at(snapshot) {
4117 overlay_versions += 1;
4118 self.lookup_metrics
4119 .hot_lookup_fallback_overlay_rows
4120 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4121 if row.deleted {
4122 tombstone_hit = true;
4123 continue;
4124 }
4125 if self.row_expired_at(&row, now_nanos) {
4126 continue;
4127 }
4128 if let Some(pk_val) = row.columns.get(&pk_column_id) {
4129 if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4130 self.lookup_metrics
4131 .hot_fallback_overlay_versions_total
4132 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4133 return Ok((
4134 RowIdSet::one(row.row_id.0),
4135 crate::trace::HotFallbackReason::MissingMapping,
4136 ));
4137 }
4138 }
4139 }
4140 for row in self.mutable_run.visible_versions_at(snapshot) {
4141 overlay_versions += 1;
4142 self.lookup_metrics
4143 .hot_lookup_fallback_overlay_rows
4144 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4145 if row.deleted {
4146 tombstone_hit = true;
4147 continue;
4148 }
4149 if self.row_expired_at(&row, now_nanos) {
4150 continue;
4151 }
4152 if let Some(pk_val) = row.columns.get(&pk_column_id) {
4153 if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4154 self.lookup_metrics
4155 .hot_fallback_overlay_versions_total
4156 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4157 return Ok((
4158 RowIdSet::one(row.row_id.0),
4159 crate::trace::HotFallbackReason::MissingMapping,
4160 ));
4161 }
4162 }
4163 }
4164 if lookup.len() == 8 {
4167 if let Ok(arr) = <[u8; 8]>::try_from(lookup) {
4168 let n = i64::from_be_bytes(arr);
4169 let result = self.range_scan_i64(pk_column_id, n, n, snapshot)?;
4170 self.lookup_metrics
4171 .hot_lookup_fallback_runs
4172 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4173 self.lookup_metrics
4177 .hot_fallback_runs_considered_total
4178 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4179 self.lookup_metrics
4180 .hot_fallback_overlay_versions_total
4181 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4182 let reason = if result.is_empty() {
4183 if tombstone_hit {
4184 crate::trace::HotFallbackReason::Tombstone
4185 } else {
4186 crate::trace::HotFallbackReason::MissingMapping
4187 }
4188 } else {
4189 crate::trace::HotFallbackReason::MissingMapping
4190 };
4191 return Ok((result, reason));
4192 }
4193 }
4194 let mut found: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new();
4197 let overlay = self.overlay_rid_set(snapshot);
4198 let mut runs_considered = 0u64;
4199 for rr in &self.run_refs {
4200 runs_considered += 1;
4201 self.lookup_metrics
4202 .hot_lookup_fallback_runs
4203 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4204 let mut reader = self.open_reader(rr.run_id)?;
4205 for row in reader.visible_versions_at(snapshot)? {
4206 if overlay.contains(&row.row_id.0) || row.deleted {
4207 if row.deleted {
4208 tombstone_hit = true;
4209 }
4210 continue;
4211 }
4212 if self.row_expired_at(&row, now_nanos) {
4213 continue;
4214 }
4215 if let Some(pk_val) = row.columns.get(&pk_column_id) {
4216 if self.index_lookup_key(pk_column_id, pk_val) == lookup {
4217 found.insert(row.row_id.0);
4218 }
4219 }
4220 }
4221 }
4222 let reason = if tombstone_hit {
4223 crate::trace::HotFallbackReason::Tombstone
4224 } else {
4225 crate::trace::HotFallbackReason::MissingMapping
4228 };
4229 self.lookup_metrics
4230 .hot_fallback_overlay_versions_total
4231 .fetch_add(overlay_versions, std::sync::atomic::Ordering::Relaxed);
4232 self.lookup_metrics
4233 .hot_fallback_runs_considered_total
4234 .fetch_add(runs_considered, std::sync::atomic::Ordering::Relaxed);
4235 Ok((RowIdSet::from_unsorted(found.into_iter().collect()), reason))
4236 }
4237
4238 fn record_hot_fallback_reason(&self, reason: crate::trace::HotFallbackReason) {
4242 let idx = hot_fallback_reason_index(reason);
4243 self.lookup_metrics.hot_fallback_reasons[idx]
4244 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4245 self.lookup_metrics
4246 .hot_lookup_fallback
4247 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4248 crate::trace::QueryTrace::record(|t| {
4249 t.hot_lookup_attempted = true;
4250 t.hot_lookup_hit = false;
4251 t.hot_fallback_reason = Some(reason.as_str());
4252 });
4253 }
4254
4255 fn rebuild_indexes_from_runs_inner(
4256 &mut self,
4257 control: Option<&crate::ExecutionControl>,
4258 ) -> Result<()> {
4259 let _index_build_pin = Arc::clone(self.pin_registry()).pin(
4262 crate::retention::PinSource::OnlineIndexBuild,
4263 self.current_epoch(),
4264 );
4265 self.hot = HotIndex::new();
4266 self.pk_by_row.clear();
4267 let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
4268 self.bitmap = bitmap;
4269 self.ann = ann;
4270 self.fm = fm;
4271 self.sparse = sparse;
4272 self.minhash = minhash;
4273 let snapshot = Snapshot::unbounded();
4296 let ttl_now = unix_nanos_now();
4297 let mut scanned = 0_usize;
4298 let mut winners: HashMap<RowId, (VersionStamp, Row)> = HashMap::new();
4299 let fold =
4300 |row: Row, winners: &mut HashMap<RowId, (VersionStamp, Row)>, scanned: &mut usize| {
4301 *scanned += 1;
4302 let stamp = VersionStamp {
4303 epoch: row.committed_epoch,
4304 commit_ts: row.commit_ts,
4305 };
4306 winners
4307 .entry(row.row_id)
4308 .and_modify(|entry| {
4309 if stamp.is_newer_than(entry.0) {
4310 *entry = (stamp, row.clone());
4311 }
4312 })
4313 .or_insert((stamp, row));
4314 };
4315 for rr in self.run_refs.clone() {
4316 if let Some(control) = control {
4317 control.checkpoint()?;
4318 }
4319 let mut reader = self.open_reader(rr.run_id)?;
4320 for row in reader.visible_versions_at(snapshot)? {
4321 if scanned.is_multiple_of(256) {
4322 if let Some(control) = control {
4323 control.checkpoint()?;
4324 }
4325 }
4326 fold(row, &mut winners, &mut scanned);
4330 }
4331 }
4332 for (index, row) in self
4333 .memtable
4334 .visible_versions_at(snapshot)
4335 .into_iter()
4336 .enumerate()
4337 {
4338 if index & 255 == 0 {
4339 if let Some(control) = control {
4340 control.checkpoint()?;
4341 }
4342 }
4343 fold(row, &mut winners, &mut scanned);
4344 }
4345 for (index, row) in self
4346 .mutable_run
4347 .visible_versions_at(snapshot)
4348 .into_iter()
4349 .enumerate()
4350 {
4351 if index & 255 == 0 {
4352 if let Some(control) = control {
4353 control.checkpoint()?;
4354 }
4355 }
4356 fold(row, &mut winners, &mut scanned);
4357 }
4358 let any_predicate = self
4363 .schema
4364 .indexes
4365 .iter()
4366 .any(|idx| idx.predicate.is_some());
4367 let name_to_id: HashMap<&str, u16> = self
4368 .schema
4369 .columns
4370 .iter()
4371 .map(|c| (c.name.as_str(), c.id))
4372 .collect();
4373 for (_rid, (stamp, row)) in winners.drain() {
4374 if row.deleted {
4375 let _ = stamp;
4378 continue;
4379 }
4380 let tok_row = self.tokenized_for_indexes(&row);
4383 if !any_predicate {
4384 index_into(
4385 &self.schema,
4386 &tok_row,
4387 &mut self.hot,
4388 &mut self.bitmap,
4389 &mut self.ann,
4390 &mut self.fm,
4391 &mut self.sparse,
4392 &mut self.minhash,
4393 );
4394 continue;
4395 }
4396 if let Some(pk_col) = self.schema.primary_key() {
4397 if let Some(pk_val) = tok_row.columns.get(&pk_col.id) {
4398 self.hot.insert(pk_val.encode_key(), tok_row.row_id);
4399 }
4400 }
4401 let columns_map: HashMap<u16, &Value> =
4402 row.columns.iter().map(|(k, v)| (*k, v)).collect();
4403 for idef in &self.schema.indexes {
4404 if let Some(pred) = &idef.predicate {
4405 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4406 continue;
4407 }
4408 }
4409 index_into_single(
4410 idef,
4411 &self.schema,
4412 &tok_row,
4413 &mut self.hot,
4414 &mut self.bitmap,
4415 &mut self.ann,
4416 &mut self.fm,
4417 &mut self.sparse,
4418 &mut self.minhash,
4419 );
4420 }
4421 }
4422 let pin_epochs = self.active_pin_epochs_for_rebuild();
4428 if !pin_epochs.is_empty() {
4429 let current_snap = Snapshot::at(Epoch(u64::MAX));
4430 for pin_epoch in pin_epochs {
4431 if let Some(control) = control {
4432 control.checkpoint()?;
4433 }
4434 let pin_snap = Snapshot::at(pin_epoch);
4435 for rr in self.run_refs.clone() {
4436 if let Some(control) = control {
4437 control.checkpoint()?;
4438 }
4439 let mut reader = self.open_reader(rr.run_id)?;
4440 for row in reader.visible_rows(pin_epoch)? {
4441 if row.deleted || self.row_expired_at(&row, ttl_now) {
4442 continue;
4443 }
4444 if self.get(row.row_id, current_snap).is_none() {
4445 self.index_bitmap_membership_only(&row);
4446 }
4447 }
4448 }
4449 for row in self
4450 .mutable_run
4451 .visible_versions_at(pin_snap)
4452 .into_iter()
4453 .chain(self.memtable.visible_versions_at(pin_snap))
4454 {
4455 if row.deleted || self.row_expired_at(&row, ttl_now) {
4456 continue;
4457 }
4458 if self.get(row.row_id, current_snap).is_none() {
4459 self.index_bitmap_membership_only(&row);
4460 }
4461 }
4462 }
4463 }
4464 self.recent_delete_preimages.clear();
4465 self.refresh_pk_by_row_from_hot();
4466 Ok(())
4467 }
4468
4469 fn index_bitmap_membership_only(&mut self, row: &Row) {
4472 if row.deleted {
4473 return;
4474 }
4475 let columns_map: HashMap<u16, &Value> = row.columns.iter().map(|(k, v)| (*k, v)).collect();
4476 let name_to_id: HashMap<&str, u16> = self
4477 .schema
4478 .columns
4479 .iter()
4480 .map(|c| (c.name.as_str(), c.id))
4481 .collect();
4482 for idef in &self.schema.indexes {
4483 if idef.kind != crate::schema::IndexKind::Bitmap {
4484 continue;
4485 }
4486 if let Some(pred) = &idef.predicate {
4487 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
4488 continue;
4489 }
4490 }
4491 if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
4492 if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
4493 b.insert(key, row.row_id);
4494 }
4495 }
4496 }
4497 }
4498
4499 fn refresh_pk_by_row_from_hot(&mut self) {
4500 self.pk_by_row_complete = true;
4501 if self.schema.primary_key().is_none() {
4502 self.pk_by_row.clear();
4503 return;
4504 }
4505 self.pk_by_row = ReversePkMap::from_entries(
4511 self.hot
4512 .entries()
4513 .into_iter()
4514 .map(|(key, row_id)| (row_id, key)),
4515 );
4516 }
4517
4518 fn insert_hot_pk(&mut self, key: Vec<u8>, row_id: RowId) {
4519 if self.schema.primary_key().is_some() {
4520 self.pk_by_row.insert(row_id, key.clone());
4521 }
4522 self.hot.insert(key, row_id);
4523 }
4524
4525 pub(crate) fn build_learned_ranges(&mut self) -> Result<()> {
4529 self.build_learned_ranges_inner(None)
4530 }
4531
4532 fn build_learned_ranges_inner(
4533 &mut self,
4534 control: Option<&crate::ExecutionControl>,
4535 ) -> Result<()> {
4536 self.learned_range = Arc::new(HashMap::new());
4537 if self.run_refs.len() != 1 {
4538 return Ok(());
4539 }
4540 let cols: Vec<(u16, usize)> = self
4541 .schema
4542 .indexes
4543 .iter()
4544 .filter(|i| i.kind == IndexKind::LearnedRange)
4545 .map(|i| {
4546 (
4547 i.column_id,
4548 i.options
4549 .learned_range
4550 .as_ref()
4551 .map(|options| options.epsilon)
4552 .unwrap_or(16),
4553 )
4554 })
4555 .collect();
4556 if cols.is_empty() {
4557 return Ok(());
4558 }
4559 let snapshot = Snapshot::unbounded();
4570 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
4571 let (visible_positions, visible_rids) = reader.visible_positions_with_rids_at(snapshot)?;
4572 let row_ids: Vec<u64> = visible_rids.iter().map(|r| *r as u64).collect();
4573 for (column_index, (cid, epsilon)) in cols.into_iter().enumerate() {
4574 if column_index % 256 == 0 {
4575 if let Some(control) = control {
4576 control.checkpoint()?;
4577 }
4578 }
4579 let ty = self
4580 .schema
4581 .columns
4582 .iter()
4583 .find(|c| c.id == cid)
4584 .map(|c| c.ty.clone())
4585 .unwrap_or(TypeId::Int64);
4586 match ty {
4587 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
4588 if let columnar::NativeColumn::Int64 { data, .. } = reader.column_native(cid)? {
4589 let pairs: Vec<(i64, u64)> = visible_positions
4590 .iter()
4591 .zip(row_ids.iter())
4592 .map(|(&p, &r)| (data[p], r))
4593 .collect();
4594 Arc::make_mut(&mut self.learned_range).insert(
4595 cid,
4596 ColumnLearnedRange::build_i64_with_epsilon(&pairs, epsilon),
4597 );
4598 }
4599 }
4600 TypeId::Float64 => {
4601 if let columnar::NativeColumn::Float64 { data, .. } =
4602 reader.column_native(cid)?
4603 {
4604 let pairs: Vec<(f64, u64)> = visible_positions
4605 .iter()
4606 .zip(row_ids.iter())
4607 .map(|(&p, &r)| (data[p], r))
4608 .collect();
4609 Arc::make_mut(&mut self.learned_range).insert(
4610 cid,
4611 ColumnLearnedRange::build_f64_with_epsilon(&pairs, epsilon),
4612 );
4613 }
4614 }
4615 _ => {}
4616 }
4617 }
4618 Ok(())
4619 }
4620
4621 pub fn ensure_indexes_complete(&mut self) -> Result<()> {
4628 if self.indexes_complete {
4629 crate::trace::QueryTrace::record(|t| {
4630 t.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4631 });
4632 return Ok(());
4633 }
4634 crate::trace::QueryTrace::record(|t| {
4635 t.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4636 });
4637 self.rebuild_indexes_from_runs()?;
4638 self.build_learned_ranges()?;
4639 self.indexes_complete = true;
4640 let epoch = self.current_epoch();
4641 self.checkpoint_indexes(epoch);
4642 Ok(())
4643 }
4644
4645 #[doc(hidden)]
4648 pub fn ensure_indexes_complete_controlled<F>(
4649 &mut self,
4650 control: &crate::ExecutionControl,
4651 before_publish: F,
4652 ) -> Result<bool>
4653 where
4654 F: FnOnce() -> bool,
4655 {
4656 self.ensure_indexes_complete_controlled_with_receipt(control, before_publish)
4657 .map(|(changed, _)| changed)
4658 }
4659
4660 #[doc(hidden)]
4663 pub fn ensure_indexes_complete_controlled_with_receipt<F>(
4664 &mut self,
4665 control: &crate::ExecutionControl,
4666 before_publish: F,
4667 ) -> Result<(bool, Option<MaintenanceReceipt>)>
4668 where
4669 F: FnOnce() -> bool,
4670 {
4671 if self.indexes_complete {
4672 crate::trace::QueryTrace::record(|trace| {
4673 trace.index_rebuild = crate::trace::IndexRebuild::AlreadyComplete;
4674 });
4675 return Ok((false, None));
4676 }
4677 crate::trace::QueryTrace::record(|trace| {
4678 trace.index_rebuild = crate::trace::IndexRebuild::Rebuilt;
4679 });
4680 control.checkpoint()?;
4681 let maintenance_epoch = self.current_epoch();
4682 self.rebuild_indexes_from_runs_inner(Some(control))?;
4683 self.build_learned_ranges_inner(Some(control))?;
4684 control.checkpoint()?;
4685 if !before_publish() {
4686 return Err(MongrelError::Cancelled);
4687 }
4688 self.indexes_complete = true;
4689 self.checkpoint_indexes(maintenance_epoch);
4690 Ok((
4691 true,
4692 Some(MaintenanceReceipt {
4693 epoch: maintenance_epoch,
4694 }),
4695 ))
4696 }
4697
4698 fn pending_epoch(&self) -> Epoch {
4699 Epoch(self.epoch.visible().0 + 1)
4700 }
4701
4702 fn is_shared(&self) -> bool {
4705 matches!(self.wal, WalSink::Shared(_))
4706 }
4707
4708 fn ensure_txn_id(&mut self) -> Result<u64> {
4712 if self.current_txn_id == 0 {
4713 let id = match &self.wal {
4714 WalSink::Shared(s) => crate::txn::allocate_txn_id(&s.txn_ids)?,
4715 WalSink::Private(_) => {
4716 return Err(MongrelError::Full(
4717 "standalone transaction id namespace exhausted".into(),
4718 ))
4719 }
4720 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4721 };
4722 self.current_txn_id = id;
4723 }
4724 Ok(self.current_txn_id)
4725 }
4726
4727 fn wal_append_data(&mut self, op: Op) -> Result<()> {
4730 self.ensure_writable()?;
4731 let txn_id = self.ensure_txn_id()?;
4732 let table_id = self.table_id;
4733 match &mut self.wal {
4734 WalSink::Private(w) => {
4735 w.append_txn(txn_id, op)?;
4736 self.pending_private_mutations = true;
4737 }
4738 WalSink::Shared(s) => {
4739 s.wal.lock().append(txn_id, table_id, op)?;
4740 }
4741 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
4742 }
4743 Ok(())
4744 }
4745
4746 fn ensure_writable(&self) -> Result<()> {
4747 if self.read_only || matches!(self.wal, WalSink::ReadOnly) {
4748 return Err(MongrelError::ReadOnlyReplica);
4749 }
4750 if self.durable_commit_failed {
4751 return Err(MongrelError::Other(
4752 "table poisoned by post-commit failure; reopen required".into(),
4753 ));
4754 }
4755 Ok(())
4756 }
4757
4758 fn require(&self, perm: crate::auth_state::RequiredPermission) -> Result<()> {
4769 match &self.auth {
4770 Some(checker) => checker.check(&self.name, perm),
4771 None => Ok(()),
4772 }
4773 }
4774 pub fn require_select(&self) -> Result<()> {
4779 self.require(crate::auth_state::RequiredPermission::Select)
4780 }
4781 fn require_insert(&self) -> Result<()> {
4782 self.require(crate::auth_state::RequiredPermission::Insert)
4783 }
4784 #[allow(dead_code)]
4788 fn require_update(&self) -> Result<()> {
4789 self.require(crate::auth_state::RequiredPermission::Update)
4790 }
4791 fn require_delete(&self) -> Result<()> {
4792 self.require(crate::auth_state::RequiredPermission::Delete)
4793 }
4794
4795 pub fn put(&mut self, columns: Vec<(u16, Value)>) -> Result<RowId> {
4798 self.require_insert()?;
4799 Ok(self.put_returning(columns)?.0)
4800 }
4801
4802 pub fn put_returning(
4807 &mut self,
4808 mut columns: Vec<(u16, Value)>,
4809 ) -> Result<(RowId, Option<i64>)> {
4810 self.require_insert()?;
4811 let assigned = self.fill_auto_inc(&mut columns)?;
4812 self.apply_defaults(&mut columns)?;
4813 self.schema.validate_values(&columns)?;
4814 let row_id = if self.schema.clustered {
4819 self.derive_clustered_row_id(&columns)?
4820 } else {
4821 self.allocator.alloc()?
4822 };
4823 let epoch = self.pending_epoch();
4824 let mut row = Row::new(row_id, epoch);
4825 for (col_id, val) in columns {
4826 row.columns.insert(col_id, val);
4827 }
4828 self.commit_rows(vec![row], assigned.is_some())?;
4829 Ok((row_id, assigned))
4830 }
4831
4832 pub fn put_batch(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Vec<RowId>> {
4835 self.require_insert()?;
4836 Ok(self
4837 .put_batch_returning(batch)?
4838 .into_iter()
4839 .map(|(r, _)| r)
4840 .collect())
4841 }
4842
4843 pub fn put_batch_returning(
4846 &mut self,
4847 batch: Vec<Vec<(u16, Value)>>,
4848 ) -> Result<Vec<(RowId, Option<i64>)>> {
4849 let mut filled: Vec<FilledAutoIncRow> = Vec::with_capacity(batch.len());
4850 for mut cols in batch {
4851 let assigned = self.fill_auto_inc(&mut cols)?;
4852 self.apply_defaults(&mut cols)?;
4853 filled.push((cols, assigned));
4854 }
4855 for (cols, _) in &filled {
4856 self.schema.validate_values(cols)?;
4857 }
4858 let epoch = self.pending_epoch();
4859 let mut rows = Vec::with_capacity(filled.len());
4860 let mut ids = Vec::with_capacity(filled.len());
4861 let first_row_id = if self.schema.clustered {
4862 None
4863 } else {
4864 let count = u64::try_from(filled.len())
4865 .map_err(|_| MongrelError::Full("row-id allocation request is too large".into()))?;
4866 Some(self.allocator.alloc_range(count)?.0)
4867 };
4868 for (row_index, (cols, assigned)) in filled.into_iter().enumerate() {
4869 let row_id = match first_row_id {
4870 Some(first) => RowId(first + row_index as u64),
4871 None => self.derive_clustered_row_id(&cols)?,
4872 };
4873 let mut row = Row::new(row_id, epoch);
4874 for (c, v) in cols {
4875 row.columns.insert(c, v);
4876 }
4877 ids.push((row_id, assigned));
4878 rows.push(row);
4879 }
4880 let all_auto_generated = ids.iter().all(|(_, assigned)| assigned.is_some());
4881 self.commit_rows(rows, all_auto_generated)?;
4882 Ok(ids)
4883 }
4884
4885 pub fn fill_auto_inc(&mut self, columns: &mut Vec<(u16, Value)>) -> Result<Option<i64>> {
4891 self.ensure_writable()?;
4892 let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
4893 return Ok(None);
4894 };
4895 let pos = columns.iter().position(|(c, _)| *c == cid);
4896 let assigned = match pos {
4897 Some(i) => match &columns[i].1 {
4898 Value::Null => {
4899 let next = self.alloc_auto_inc_value()?;
4900 columns[i].1 = Value::Int64(next);
4901 Some(next)
4902 }
4903 Value::Int64(n) => {
4904 self.advance_auto_inc_past(*n)?;
4905 None
4906 }
4907 other => {
4908 return Err(MongrelError::InvalidArgument(format!(
4909 "AUTO_INCREMENT column {cid} must be Int64 or NULL, got {:?}",
4910 other
4911 )))
4912 }
4913 },
4914 None => {
4915 let next = self.alloc_auto_inc_value()?;
4916 columns.push((cid, Value::Int64(next)));
4917 Some(next)
4918 }
4919 };
4920 Ok(assigned)
4921 }
4922
4923 pub fn apply_defaults(&self, columns: &mut Vec<(u16, Value)>) -> Result<()> {
4929 for col in &self.schema.columns {
4930 let Some(expr) = &col.default_value else {
4931 continue;
4932 };
4933 if col.flags.contains(ColumnFlags::AUTO_INCREMENT) {
4935 continue;
4936 }
4937 let pos = columns.iter().position(|(c, _)| *c == col.id);
4938 let needs_default = match pos {
4939 None => true,
4940 Some(i) => matches!(columns[i].1, Value::Null),
4941 };
4942 if !needs_default {
4943 continue;
4944 }
4945 let v = match expr {
4946 crate::schema::DefaultExpr::Static(v) => v.clone(),
4947 crate::schema::DefaultExpr::Now => Value::Bytes(iso_now_bytes()),
4948 crate::schema::DefaultExpr::Uuid => {
4949 let mut buf = [0u8; 16];
4950 getrandom::getrandom(&mut buf)
4951 .map_err(|e| MongrelError::Other(format!("UUID generation failed: {e}")))?;
4952 Value::Uuid(buf)
4953 }
4954 };
4955 match pos {
4956 None => columns.push((col.id, v)),
4957 Some(i) => columns[i].1 = v,
4958 }
4959 }
4960 Ok(())
4961 }
4962
4963 fn alloc_auto_inc_value(&mut self) -> Result<i64> {
4965 self.ensure_auto_inc_seeded()?;
4966 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
4968 let v = ai.next;
4969 ai.next = ai
4970 .next
4971 .checked_add(1)
4972 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
4973 Ok(v)
4974 }
4975
4976 fn advance_auto_inc_past(&mut self, used: i64) -> Result<()> {
4979 self.ensure_auto_inc_seeded()?;
4980 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
4981 let floor = used
4982 .checked_add(1)
4983 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
4984 .max(1);
4985 if ai.next < floor {
4986 ai.next = floor;
4987 }
4988 Ok(())
4989 }
4990
4991 fn ensure_auto_inc_seeded(&mut self) -> Result<()> {
4996 let needs_seed = match self.auto_inc {
4997 Some(ai) => !ai.seeded,
4998 None => return Ok(()),
4999 };
5000 if !needs_seed {
5001 return Ok(());
5002 }
5003 if self.seed_empty_auto_inc() {
5004 return Ok(());
5005 }
5006 let cid = self
5007 .auto_inc
5008 .as_ref()
5009 .expect("auto-inc column present")
5010 .column_id;
5011 let max = self.scan_max_int64(cid)?;
5012 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5013 let floor = max
5014 .checked_add(1)
5015 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5016 .max(1);
5017 if ai.next < floor {
5018 ai.next = floor;
5019 }
5020 ai.seeded = true;
5021 Ok(())
5022 }
5023
5024 fn alloc_auto_inc_range(&mut self, n: usize) -> Result<Option<i64>> {
5025 if n == 0 || self.auto_inc.is_none() {
5026 return Ok(None);
5027 }
5028 self.ensure_auto_inc_seeded()?;
5029 let ai = self.auto_inc.as_mut().expect("auto-inc column present");
5030 let start = ai.next;
5031 let count = i64::try_from(n)
5032 .map_err(|_| MongrelError::Full("AUTO_INCREMENT range is too large".into()))?;
5033 ai.next = ai
5034 .next
5035 .checked_add(count)
5036 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?;
5037 Ok(Some(start))
5038 }
5039
5040 fn scan_max_int64(&mut self, column_id: u16) -> Result<i64> {
5044 let mut max: i64 = 0;
5045 for r in self.memtable.visible_versions_at(Snapshot::unbounded()) {
5046 if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5047 if *n > max {
5048 max = *n;
5049 }
5050 }
5051 }
5052 for r in self.mutable_run.visible_versions(Epoch(u64::MAX)) {
5053 if let Some(Value::Int64(n)) = r.columns.get(&column_id) {
5054 if *n > max {
5055 max = *n;
5056 }
5057 }
5058 }
5059 for rr in self.run_refs.clone() {
5060 let reader = self.open_reader(rr.run_id)?;
5061 if let Some(stats) = reader.column_page_stats(column_id) {
5062 for s in stats {
5063 if let Some(n) = crate::sorted_run::be_i64(s.max.as_deref()) {
5064 if n > max {
5065 max = n;
5066 }
5067 }
5068 }
5069 } else if reader.has_column(column_id) {
5070 if let columnar::NativeColumn::Int64 { data, validity } =
5071 reader.column_native_shared(column_id)?
5072 {
5073 for (i, n) in data.iter().enumerate() {
5074 if (validity.is_empty() || columnar::validity_bit(&validity, i)) && *n > max
5075 {
5076 max = *n;
5077 }
5078 }
5079 }
5080 }
5081 }
5082 Ok(max)
5083 }
5084
5085 fn seed_empty_auto_inc(&mut self) -> bool {
5086 let Some(ai) = self.auto_inc.as_mut() else {
5087 return false;
5088 };
5089 if ai.seeded || self.live_count != 0 {
5090 return false;
5091 }
5092 if ai.next < 1 {
5093 ai.next = 1;
5094 }
5095 ai.seeded = true;
5096 true
5097 }
5098
5099 fn advance_auto_inc_from_native_columns(
5100 &mut self,
5101 columns: &[(u16, columnar::NativeColumn)],
5102 n: usize,
5103 live_before: u64,
5104 ) -> Result<()> {
5105 let Some(ai) = self.auto_inc.as_mut() else {
5106 return Ok(());
5107 };
5108 let Some((_, col)) = columns.iter().find(|(cid, _)| *cid == ai.column_id) else {
5109 return Ok(());
5110 };
5111 let columnar::NativeColumn::Int64 { data, validity } = col else {
5112 return Err(MongrelError::InvalidArgument(format!(
5113 "AUTO_INCREMENT column {} must be Int64",
5114 ai.column_id
5115 )));
5116 };
5117 let max = if native_int64_strictly_increasing(col, n) {
5118 data.get(n.saturating_sub(1)).copied()
5119 } else {
5120 data.iter()
5121 .take(n)
5122 .enumerate()
5123 .filter_map(|(i, v)| {
5124 if validity.is_empty() || columnar::validity_bit(validity, i) {
5125 Some(*v)
5126 } else {
5127 None
5128 }
5129 })
5130 .max()
5131 };
5132 if let Some(max) = max {
5133 let floor = max
5134 .checked_add(1)
5135 .ok_or_else(|| MongrelError::Full("AUTO_INCREMENT namespace exhausted".into()))?
5136 .max(1);
5137 if ai.next < floor {
5138 ai.next = floor;
5139 }
5140 if ai.seeded || live_before == 0 {
5141 ai.seeded = true;
5142 }
5143 }
5144 Ok(())
5145 }
5146
5147 fn fill_auto_inc_native_columns(
5148 &mut self,
5149 columns: &mut Vec<(u16, columnar::NativeColumn)>,
5150 n: usize,
5151 ) -> Result<()> {
5152 let Some(cid) = self.auto_inc.as_ref().map(|a| a.column_id) else {
5153 return Ok(());
5154 };
5155 let Some(pos) = columns.iter().position(|(id, _)| *id == cid) else {
5156 if let Some(start) = self.alloc_auto_inc_range(n)? {
5157 columns.push((
5158 cid,
5159 columnar::NativeColumn::Int64 {
5160 data: (start..start.saturating_add(n as i64)).collect(),
5161 validity: vec![0xFF; n.div_ceil(8)],
5162 },
5163 ));
5164 }
5165 return Ok(());
5166 };
5167
5168 let columnar::NativeColumn::Int64 { data, validity } = &mut columns[pos].1 else {
5169 return Err(MongrelError::InvalidArgument(format!(
5170 "AUTO_INCREMENT column {cid} must be Int64"
5171 )));
5172 };
5173 if data.len() < n {
5174 return Err(MongrelError::InvalidArgument(format!(
5175 "AUTO_INCREMENT column {cid} has {} rows, expected {n}",
5176 data.len()
5177 )));
5178 }
5179 if columnar::all_non_null(validity, n) {
5180 return Ok(());
5181 }
5182 if validity.iter().all(|b| *b == 0) {
5183 if let Some(start) = self.alloc_auto_inc_range(n)? {
5184 for (i, slot) in data.iter_mut().take(n).enumerate() {
5185 *slot = start.saturating_add(i as i64);
5186 }
5187 *validity = vec![0xFF; n.div_ceil(8)];
5188 }
5189 return Ok(());
5190 }
5191
5192 let new_validity = vec![0xFF; data.len().div_ceil(8)];
5193 for (i, slot) in data.iter_mut().enumerate().take(n) {
5194 if columnar::validity_bit(validity, i) {
5195 self.advance_auto_inc_past(*slot)?;
5196 } else {
5197 *slot = self.alloc_auto_inc_value()?;
5198 }
5199 }
5200 *validity = new_validity;
5201 Ok(())
5202 }
5203
5204 pub fn reserve_auto_inc(&mut self) -> Result<Option<i64>> {
5218 self.ensure_writable()?;
5219 if self.auto_inc.is_none() {
5220 return Ok(None);
5221 }
5222 Ok(Some(self.alloc_auto_inc_value()?))
5223 }
5224
5225 fn commit_rows(&mut self, rows: Vec<Row>, auto_inc_generated: bool) -> Result<()> {
5231 let payload = bincode::serialize(&rows)?;
5232 self.wal_append_data(Op::Put {
5233 table_id: self.table_id,
5234 rows: payload,
5235 })?;
5236 if self.is_shared() {
5237 self.pending_rows_auto_inc
5238 .extend(std::iter::repeat_n(auto_inc_generated, rows.len()));
5239 self.pending_rows.extend(rows);
5240 } else {
5241 self.apply_put_rows_inner(rows, !auto_inc_generated)?;
5242 }
5243 Ok(())
5244 }
5245
5246 pub(crate) fn prepare_durable_publish(&mut self) -> Result<()> {
5249 self.ensure_indexes_complete()
5250 }
5251
5252 pub(crate) fn prepare_durable_publish_controlled(
5253 &mut self,
5254 control: &crate::ExecutionControl,
5255 ) -> Result<()> {
5256 self.ensure_indexes_complete_controlled(control, || true)?;
5257 Ok(())
5258 }
5259
5260 pub(crate) fn apply_put_rows_prepared(&mut self, rows: Vec<Row>) {
5261 self.apply_put_rows_inner_prepared(rows, true);
5262 }
5263
5264 fn apply_put_rows_inner(&mut self, rows: Vec<Row>, check_existing_pk: bool) -> Result<()> {
5265 if check_existing_pk {
5266 self.ensure_indexes_complete()?;
5267 }
5268 self.apply_put_rows_inner_prepared(rows, check_existing_pk);
5269 Ok(())
5270 }
5271
5272 fn apply_put_rows_inner_prepared(&mut self, rows: Vec<Row>, check_existing_pk: bool) {
5276 if rows.len() == 1 {
5280 let row = rows.into_iter().next().expect("len checked");
5281 self.apply_put_row_single(row, check_existing_pk);
5282 return;
5283 }
5284 let pk_id = self.schema.primary_key().map(|c| c.id);
5301 let probe = match pk_id {
5302 Some(pid) => {
5303 check_existing_pk
5304 && !(self.hot.is_empty() && rows_pk_strictly_increasing(&rows, pid))
5305 }
5306 None => false,
5307 };
5308 let maintain_pk_by_row = pk_id.is_some() && self.pk_by_row_complete;
5311 for r in rows {
5312 for &cid in r.columns.keys() {
5313 self.pending_put_cols.insert(cid);
5314 }
5315 let mut replaced_image: Option<Row> = None;
5316 match pk_id {
5317 Some(pid) if probe || maintain_pk_by_row => {
5318 if let Some(pk_val) = r.columns.get(&pid) {
5319 let key = self.index_lookup_key(pid, pk_val);
5320 if probe {
5321 if let Some(old) = self.recent_delete_preimages.remove(&key) {
5330 replaced_image = Some(old);
5331 if let Some(old_rid) = self.hot.get(&key) {
5332 if old_rid != r.row_id {
5333 self.tombstone_row(
5334 old_rid,
5335 r.committed_epoch,
5336 r.commit_ts,
5337 true,
5338 );
5339 }
5340 }
5341 } else if let Some(old_rid) = self.hot.get(&key) {
5342 if old_rid != r.row_id {
5343 replaced_image = self.get(old_rid, self.snapshot());
5344 self.tombstone_row(
5345 old_rid,
5346 r.committed_epoch,
5347 r.commit_ts,
5348 true,
5349 );
5350 }
5351 }
5352 }
5353 if maintain_pk_by_row {
5354 self.pk_by_row.insert(r.row_id, key);
5355 }
5356 }
5357 }
5358 Some(_) => {}
5359 None => {
5360 self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5361 }
5362 }
5363 if let Some(old) = replaced_image {
5364 self.maintain_indexes_on_pk_replace(&old, &r);
5365 } else {
5366 self.index_row(&r);
5367 }
5368 self.reservoir.offer(r.row_id.0);
5369 self.memtable.upsert(r);
5370 self.live_count = self.live_count.saturating_add(1);
5373 }
5374 self.data_generation = self.data_generation.wrapping_add(1);
5375 }
5376
5377 fn apply_put_row_single(&mut self, row: Row, check_existing_pk: bool) {
5387 for &cid in row.columns.keys() {
5388 self.pending_put_cols.insert(cid);
5389 }
5390 let epoch = row.committed_epoch;
5391 let mut replaced_image: Option<Row> = None;
5392 if let Some(pk_col) = self.schema.primary_key() {
5393 let pk_id = pk_col.id;
5394 if let Some(pk_val) = row.columns.get(&pk_id) {
5395 let maintain_pk_by_row = self.pk_by_row_complete;
5399 if check_existing_pk || maintain_pk_by_row {
5400 let key = self.index_lookup_key(pk_id, pk_val);
5401 if check_existing_pk {
5402 if let Some(old) = self.recent_delete_preimages.remove(&key) {
5411 replaced_image = Some(old);
5412 if let Some(old_rid) = self.hot.get(&key) {
5413 if old_rid != row.row_id {
5414 self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5415 }
5416 }
5417 } else if let Some(old_rid) = self.hot.get(&key) {
5418 if old_rid != row.row_id {
5419 replaced_image = self.get(old_rid, self.snapshot());
5423 self.tombstone_row(old_rid, epoch, row.commit_ts, true);
5424 }
5425 }
5426 }
5427 if maintain_pk_by_row {
5428 self.pk_by_row.insert(row.row_id, key);
5429 }
5430 }
5431 }
5432 } else {
5433 self.hot
5434 .insert(row.row_id.0.to_be_bytes().to_vec(), row.row_id);
5435 }
5436 if let Some(old) = replaced_image {
5437 self.maintain_indexes_on_pk_replace(&old, &row);
5438 } else {
5439 self.index_row(&row);
5440 }
5441 self.reservoir.offer(row.row_id.0);
5442 self.memtable.upsert(row);
5443 self.live_count = self.live_count.saturating_add(1);
5444 self.data_generation = self.data_generation.wrapping_add(1);
5445 }
5446
5447 fn maintain_indexes_on_pk_replace(&mut self, old: &Row, new: &Row) {
5450 let has_partial = self
5451 .schema
5452 .indexes
5453 .iter()
5454 .any(|idx| idx.predicate.is_some());
5455 if has_partial {
5456 self.unindex_bitmap_membership(old);
5460 self.index_row(new);
5461 return;
5462 }
5463
5464 crate::index::maintain_bitmap_secondary_on_replace(
5465 &self.schema,
5466 &mut self.bitmap,
5467 old,
5468 new,
5469 );
5470 self.index_row_non_bitmap(new);
5471 }
5472
5473 fn index_row_non_bitmap(&mut self, row: &Row) {
5476 if row.deleted {
5477 return;
5478 }
5479 let effective = if self.column_keys.is_empty() {
5480 None
5481 } else {
5482 Some(self.tokenized_for_indexes(row))
5483 };
5484 let source = effective.as_ref().unwrap_or(row);
5485 for idef in &self.schema.indexes {
5486 if idef.kind == crate::schema::IndexKind::Bitmap {
5487 continue;
5488 }
5489 index_into_single(
5490 idef,
5491 &self.schema,
5492 source,
5493 &mut self.hot,
5494 &mut self.bitmap,
5495 &mut self.ann,
5496 &mut self.fm,
5497 &mut self.sparse,
5498 &mut self.minhash,
5499 );
5500 }
5501 if let Some(pk_col) = self.schema.primary_key() {
5502 if let Some(pk_val) = source.columns.get(&pk_col.id) {
5503 let key = if self.column_keys.is_empty() {
5504 pk_val.encode_key()
5505 } else {
5506 self.index_lookup_key(pk_col.id, pk_val)
5507 };
5508 self.hot.insert(key, source.row_id);
5509 }
5510 }
5511 }
5512
5513 pub(crate) fn alloc_row_id(&mut self) -> Result<RowId> {
5516 self.allocator.alloc()
5517 }
5518
5519 fn derive_clustered_row_id(&self, columns: &[(u16, Value)]) -> Result<RowId> {
5525 let pk = self.schema.primary_key().ok_or_else(|| {
5526 MongrelError::Schema("clustered table requires a single-column primary key".into())
5527 })?;
5528 let pk_val = columns
5529 .iter()
5530 .find(|(id, _)| *id == pk.id)
5531 .map(|(_, v)| v)
5532 .ok_or_else(|| {
5533 MongrelError::Schema(format!(
5534 "clustered table missing primary key column {} ({})",
5535 pk.id, pk.name
5536 ))
5537 })?;
5538 Ok(clustered_row_id(pk_val))
5539 }
5540
5541 pub(crate) fn apply_run_metadata_prepared(&mut self, rows: &[Row]) -> Result<()> {
5549 if rows.iter().any(|row| row.row_id.0 >= u64::MAX - 1) {
5550 return Err(MongrelError::Full("row-id namespace exhausted".into()));
5551 }
5552 let n = rows.len();
5553 for r in rows {
5554 for &cid in r.columns.keys() {
5555 self.pending_put_cols.insert(cid);
5556 }
5557 }
5558 let (losers, winner_pks) = self.partition_pk_winners(rows);
5559 let epoch = rows.first().map(|r| r.committed_epoch).unwrap_or(Epoch(0));
5560 let group_ts = rows.first().and_then(|r| r.commit_ts);
5562 for (key, &row_id) in &winner_pks {
5563 if let Some(old_rid) = self.hot.get(key) {
5564 if old_rid != row_id {
5565 self.tombstone_row(old_rid, epoch, group_ts, true);
5566 }
5567 }
5568 }
5569 for &loser_rid in &losers {
5572 self.tombstone_row(loser_rid, epoch, group_ts, false);
5573 }
5574 for (key, row_id) in winner_pks {
5576 self.insert_hot_pk(key, row_id);
5577 }
5578 if self.schema.primary_key().is_none() {
5579 for r in rows {
5580 self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5581 }
5582 }
5583 for r in rows {
5584 self.allocator.advance_to(r.row_id)?;
5585 if !losers.contains(&r.row_id) {
5586 self.index_row(r);
5587 }
5588 }
5589 for r in rows {
5590 if !losers.contains(&r.row_id) {
5591 self.reservoir.offer(r.row_id.0);
5592 }
5593 }
5594 self.live_count = self.live_count.saturating_add((n - losers.len()) as u64);
5595 self.data_generation = self.data_generation.wrapping_add(1);
5596 Ok(())
5597 }
5598
5599 pub(crate) fn recover_apply(
5604 &mut self,
5605 rows: Vec<Row>,
5606 deletes: Vec<(RowId, Epoch)>,
5607 ) -> Result<()> {
5608 let mut by_epoch: std::collections::BTreeMap<Epoch, Vec<Row>> =
5612 std::collections::BTreeMap::new();
5613 for row in rows {
5614 if row.row_id.0 >= u64::MAX - 1 {
5615 return Err(MongrelError::Full("row-id namespace exhausted".into()));
5616 }
5617 self.allocator.advance_to(row.row_id)?;
5618 if let Some(ai) = self.auto_inc.as_mut() {
5623 if let Some(Value::Int64(n)) = row.columns.get(&ai.column_id) {
5624 let next = n.checked_add(1).ok_or_else(|| {
5625 MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
5626 })?;
5627 if next > ai.next {
5628 ai.next = next;
5629 }
5630 }
5631 }
5632 by_epoch.entry(row.committed_epoch).or_default().push(row);
5633 }
5634 for (epoch, group) in by_epoch {
5635 let (losers, winner_pks) = self.partition_pk_winners(&group);
5636 let group_ts = group.first().and_then(|r| r.commit_ts);
5638 for (key, &row_id) in &winner_pks {
5639 if let Some(old_rid) = self.hot.get(key) {
5640 if old_rid != row_id {
5641 self.tombstone_row(old_rid, epoch, group_ts, false);
5642 }
5643 }
5644 }
5645 for (key, row_id) in winner_pks {
5646 self.insert_hot_pk(key, row_id);
5647 }
5648 if self.schema.primary_key().is_none() {
5649 for r in &group {
5650 self.hot.insert(r.row_id.0.to_be_bytes().to_vec(), r.row_id);
5651 }
5652 }
5653 for r in &group {
5654 if !losers.contains(&r.row_id) {
5655 self.memtable.upsert(r.clone());
5656 self.index_row(r);
5657 }
5658 }
5659 }
5660 for (rid, epoch) in deletes {
5661 self.memtable.tombstone(rid, epoch);
5662 self.remove_hot_for_row(rid, epoch);
5663 }
5664 self.reservoir_complete = false;
5667 Ok(())
5668 }
5669
5670 pub(crate) fn flushed_epoch(&self) -> u64 {
5672 self.flushed_epoch
5673 }
5674
5675 pub(crate) fn set_flushed_epoch(&mut self, epoch: Epoch) {
5676 self.flushed_epoch = self.flushed_epoch.max(epoch.0);
5677 }
5678
5679 pub(crate) fn validate_cells_not_null(&self, cells: &[(u16, Value)]) -> Result<()> {
5681 self.schema.validate_values(cells)
5682 }
5683
5684 fn validate_columns_not_null(
5688 &self,
5689 columns: &[(u16, columnar::NativeColumn)],
5690 n: usize,
5691 ) -> Result<()> {
5692 let by_id: HashMap<u16, &columnar::NativeColumn> =
5693 columns.iter().map(|(id, c)| (*id, c)).collect();
5694 for col in &self.schema.columns {
5695 if !col.flags.contains(ColumnFlags::NULLABLE) {
5696 match by_id.get(&col.id) {
5697 None => {
5698 return Err(MongrelError::InvalidArgument(format!(
5699 "column '{}' ({}) is NOT NULL but was omitted from the bulk load",
5700 col.name, col.id
5701 )));
5702 }
5703 Some(c) => {
5704 if c.null_count(n) != 0 {
5705 return Err(MongrelError::InvalidArgument(format!(
5706 "column '{}' ({}) is NOT NULL but the bulk load contains nulls",
5707 col.name, col.id
5708 )));
5709 }
5710 }
5711 }
5712 }
5713 if let TypeId::Enum { variants } = &col.ty {
5714 let Some(columnar::NativeColumn::Bytes { .. }) = by_id.get(&col.id).copied() else {
5715 if by_id.contains_key(&col.id) {
5716 return Err(MongrelError::InvalidArgument(format!(
5717 "column '{}' ({}) enum requires a bytes column",
5718 col.name, col.id
5719 )));
5720 }
5721 continue;
5722 };
5723 for index in 0..n {
5724 let Some(value) = columnar::native_bytes_at(by_id[&col.id], index) else {
5725 continue;
5726 };
5727 if !variants.iter().any(|variant| variant.as_bytes() == value) {
5728 return Err(MongrelError::InvalidArgument(format!(
5729 "column '{}' ({}) enum value {:?} is not one of {:?}",
5730 col.name,
5731 col.id,
5732 String::from_utf8_lossy(value),
5733 variants
5734 )));
5735 }
5736 }
5737 }
5738 }
5739 Ok(())
5740 }
5741
5742 fn bulk_pk_winner_indices(
5747 &self,
5748 columns: &[(u16, columnar::NativeColumn)],
5749 n: usize,
5750 ) -> Option<Vec<usize>> {
5751 let pk_col = self.schema.primary_key()?;
5752 let pk_id = pk_col.id;
5753 let pk_ty = pk_col.ty.clone();
5754 let by_id: HashMap<u16, &columnar::NativeColumn> =
5755 columns.iter().map(|(id, c)| (*id, c)).collect();
5756 let pk_native = by_id.get(&pk_id)?;
5757 if native_int64_strictly_increasing(pk_native, n) {
5758 return None;
5759 }
5760 let mut last: HashMap<Vec<u8>, usize> = HashMap::new();
5762 let mut null_pk_rows: Vec<usize> = Vec::new();
5763 for i in 0..n {
5764 match bulk_index_key(&self.column_keys, pk_id, pk_ty.clone(), pk_native, i) {
5765 Some(key) => {
5766 last.insert(key, i);
5767 }
5768 None => null_pk_rows.push(i),
5769 }
5770 }
5771 let mut winners: HashSet<usize> = last.values().copied().collect();
5772 for i in null_pk_rows {
5773 winners.insert(i);
5774 }
5775 Some((0..n).filter(|i| winners.contains(i)).collect())
5776 }
5777
5778 pub fn delete(&mut self, row_id: RowId) -> Result<()> {
5780 self.require_delete()?;
5781 let epoch = self.pending_epoch();
5782 self.wal_append_data(Op::Delete {
5783 table_id: self.table_id,
5784 row_ids: vec![row_id],
5785 })?;
5786 if self.is_shared() {
5787 self.pending_dels.push(row_id);
5788 } else {
5789 self.apply_delete(row_id, epoch);
5790 }
5791 Ok(())
5792 }
5793
5794 pub fn delete_returning(&mut self, row_id: RowId) -> Result<Option<OwnedRow>> {
5795 let pre = self.get(row_id, self.snapshot());
5796 self.delete(row_id)?;
5797 Ok(pre.map(|row| {
5798 let mut columns: Vec<_> = row.columns.into_iter().collect();
5799 columns.sort_by_key(|(id, _)| *id);
5800 OwnedRow { columns }
5801 }))
5802 }
5803
5804 pub fn truncate(&mut self) -> Result<()> {
5806 self.require_delete()?;
5807 let epoch = self.pending_epoch();
5808 self.wal_append_data(Op::TruncateTable {
5809 table_id: self.table_id,
5810 })?;
5811 self.pending_rows.clear();
5812 self.pending_rows_auto_inc.clear();
5813 self.pending_dels.clear();
5814 self.pending_truncate = Some(epoch);
5815 Ok(())
5816 }
5817
5818 pub(crate) fn apply_truncate(&mut self, _epoch: Epoch) {
5820 self.run_refs.clear();
5825 self.retiring.clear();
5826 self.memtable = Memtable::new();
5827 self.mutable_run = MutableRun::new();
5828 self.hot = HotIndex::new();
5829 let (bitmap, ann, fm, sparse, minhash) = empty_indexes(&self.schema);
5830 self.bitmap = bitmap;
5831 self.ann = ann;
5832 self.fm = fm;
5833 self.sparse = sparse;
5834 self.minhash = minhash;
5835 self.learned_range = Arc::new(HashMap::new());
5836 self.pk_by_row.clear();
5837 self.pk_by_row_complete = false;
5838 self.live_count = 0;
5839 self.reservoir = crate::reservoir::Reservoir::default();
5840 self.reservoir_complete = true;
5841 self.had_deletes = true;
5842 self.agg_cache = Arc::new(HashMap::new());
5843 self.global_idx_epoch = 0;
5844 self.indexes_complete = true;
5845 self.pending_delete_rids.clear();
5846 self.pending_put_cols.clear();
5847 self.pending_rows.clear();
5848 self.pending_rows_auto_inc.clear();
5849 self.pending_dels.clear();
5850 self.clear_result_cache();
5851 self.invalidate_index_checkpoint();
5852 self.data_generation = self.data_generation.wrapping_add(1);
5853 }
5854
5855 pub(crate) fn apply_delete(&mut self, row_id: RowId, epoch: Epoch) {
5858 self.apply_delete_at(row_id, epoch, None);
5859 }
5860
5861 pub(crate) fn apply_delete_at(
5863 &mut self,
5864 row_id: RowId,
5865 epoch: Epoch,
5866 commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
5867 ) {
5868 let preimage = self.get(row_id, self.snapshot());
5878 if let Some(row) = preimage {
5879 if let Some(pk_col) = self.schema.primary_key() {
5880 if let Some(pk_val) = row.columns.get(&pk_col.id) {
5881 let key = self.index_lookup_key(pk_col.id, pk_val);
5882 self.recent_delete_preimages.insert(key, row);
5883 }
5884 }
5885 }
5886 self.tombstone_row(row_id, epoch, commit_ts, true);
5887 self.data_generation = self.data_generation.wrapping_add(1);
5888 }
5889
5890 fn unindex_bitmap_membership(&mut self, row: &Row) {
5895 if row.deleted {
5896 return;
5897 }
5898 for idef in &self.schema.indexes {
5899 if idef.kind != crate::schema::IndexKind::Bitmap {
5900 continue;
5901 }
5902 if let Some(key) = crate::index::maintain::bitmap_key_for_column(row, idef.column_id) {
5903 if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
5904 b.remove(&key, row.row_id);
5905 }
5906 }
5907 }
5908 }
5909
5910 fn union_bitmap_point_i64(
5914 &self,
5915 set: &mut RowIdSet,
5916 column_id: u16,
5917 value: i64,
5918 snapshot: Snapshot,
5919 ) {
5920 let Some(b) = self.bitmap.get(&column_id) else {
5921 return;
5922 };
5923 let encoded = Value::Int64(value).encode_key();
5924 let lookup = self.index_lookup_key_bytes(column_id, &encoded);
5925 for rid in b.get(&lookup).iter() {
5926 set.insert(u64::from(rid));
5927 }
5928 set.remove_many(self.overlay_tombstoned_rids(snapshot));
5932 self.range_scan_overlay_i64(set, column_id, value, value, snapshot);
5933 }
5934
5935 fn tombstone_row(
5949 &mut self,
5950 row_id: RowId,
5951 epoch: Epoch,
5952 commit_ts: Option<mongreldb_types::hlc::HlcTimestamp>,
5953 adjust_live_count: bool,
5954 ) {
5955 let prev_was_live = if adjust_live_count {
5956 match self.memtable.get_version(row_id, epoch) {
5957 Some((_, prev)) => !prev.deleted,
5958 None => true,
5959 }
5960 } else {
5961 false
5962 };
5963 let tombstone = Row {
5964 row_id,
5965 committed_epoch: epoch,
5966 columns: std::collections::HashMap::new(),
5967 deleted: true,
5968 commit_ts,
5969 };
5970 self.memtable.upsert(tombstone);
5971 self.pk_by_row.remove(&row_id);
5972 if prev_was_live {
5973 self.live_count = self.live_count.saturating_sub(1);
5974 }
5975 self.pending_delete_rids.insert(row_id.0 as u32);
5977 self.had_deletes = true;
5980 self.agg_cache = Arc::new(HashMap::new());
5981 }
5982
5983 fn remove_hot_for_row(&mut self, row_id: RowId, epoch: Epoch) {
5987 let Some(pk_col) = self.schema.primary_key() else {
5988 return;
5989 };
5990 if self.pk_by_row_complete {
5993 if let Some(key) = self.pk_by_row.remove(&row_id) {
5994 if self.hot.get(&key) == Some(row_id) {
5995 self.hot.remove(&key);
5996 }
5997 }
5998 return;
5999 }
6000 let lookup_epoch = Epoch(epoch.0.saturating_sub(1));
6019 if self.indexes_complete {
6020 let pk_val = self
6021 .memtable
6022 .get_version(row_id, lookup_epoch)
6023 .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6024 .or_else(|| {
6025 self.mutable_run
6026 .get_version(row_id, lookup_epoch)
6027 .filter(|(_, r)| !r.deleted)
6028 .and_then(|(_, r)| r.columns.get(&pk_col.id).cloned())
6029 })
6030 .or_else(|| {
6031 self.run_refs.iter().find_map(|rr| {
6032 let mut reader = self.open_reader(rr.run_id).ok()?;
6033 let (_, deleted, val) = reader
6034 .get_version_column(row_id, lookup_epoch, pk_col.id)
6035 .ok()??;
6036 if deleted {
6037 return None;
6038 }
6039 val
6040 })
6041 });
6042 if let Some(pk_val) = pk_val {
6043 let key = self.index_lookup_key(pk_col.id, &pk_val);
6044 if self.hot.get(&key) == Some(row_id) {
6045 self.hot.remove(&key);
6046 }
6047 return;
6048 }
6049 }
6050 self.refresh_pk_by_row_from_hot();
6055 if let Some(key) = self.pk_by_row.remove(&row_id) {
6056 if self.hot.get(&key) == Some(row_id) {
6057 self.hot.remove(&key);
6058 }
6059 }
6060 }
6061
6062 fn partition_pk_winners(
6067 &self,
6068 rows: &[Row],
6069 ) -> (
6070 std::collections::HashSet<RowId>,
6071 std::collections::HashMap<Vec<u8>, RowId>,
6072 ) {
6073 let mut losers = std::collections::HashSet::new();
6074 let Some(pk_col) = self.schema.primary_key() else {
6075 return (losers, std::collections::HashMap::new());
6076 };
6077 let pk_id = pk_col.id;
6078 let mut winners: std::collections::HashMap<Vec<u8>, RowId> =
6079 std::collections::HashMap::new();
6080 for r in rows {
6081 let Some(pk_val) = r.columns.get(&pk_id) else {
6082 continue;
6083 };
6084 let key = self.index_lookup_key(pk_id, pk_val);
6085 if let Some(&old_rid) = winners.get(&key) {
6086 losers.insert(old_rid);
6087 }
6088 winners.insert(key, r.row_id);
6089 }
6090 (losers, winners)
6091 }
6092
6093 fn index_row(&mut self, row: &Row) {
6094 if row.deleted {
6095 return;
6096 }
6097 let any_predicate = self
6105 .schema
6106 .indexes
6107 .iter()
6108 .any(|idx| idx.predicate.is_some());
6109 if any_predicate {
6110 let columns_map: HashMap<u16, &Value> =
6111 row.columns.iter().map(|(k, v)| (*k, v)).collect();
6112 let name_to_id: HashMap<&str, u16> = self
6113 .schema
6114 .columns
6115 .iter()
6116 .map(|c| (c.name.as_str(), c.id))
6117 .collect();
6118 for idx in &self.schema.indexes {
6119 if let Some(pred) = &idx.predicate {
6120 if !eval_partial_predicate(pred, &columns_map, &name_to_id) {
6121 continue; }
6123 }
6124 index_into_single(
6126 idx,
6127 &self.schema,
6128 row,
6129 &mut self.hot,
6130 &mut self.bitmap,
6131 &mut self.ann,
6132 &mut self.fm,
6133 &mut self.sparse,
6134 &mut self.minhash,
6135 );
6136 }
6137 return;
6138 }
6139 if self.column_keys.is_empty() {
6143 index_into(
6144 &self.schema,
6145 row,
6146 &mut self.hot,
6147 &mut self.bitmap,
6148 &mut self.ann,
6149 &mut self.fm,
6150 &mut self.sparse,
6151 &mut self.minhash,
6152 );
6153 return;
6154 }
6155 let effective_row = self.tokenized_for_indexes(row);
6156 index_into(
6157 &self.schema,
6158 &effective_row,
6159 &mut self.hot,
6160 &mut self.bitmap,
6161 &mut self.ann,
6162 &mut self.fm,
6163 &mut self.sparse,
6164 &mut self.minhash,
6165 );
6166 }
6167
6168 fn tokenized_for_indexes(&self, row: &Row) -> Row {
6174 if self.column_keys.is_empty() {
6175 return row.clone();
6176 }
6177 {
6178 use crate::encryption::SCHEME_HMAC_EQ;
6179 let mut tok = row.clone();
6180 for (&cid, &(_, scheme)) in &self.column_keys {
6181 if scheme != SCHEME_HMAC_EQ {
6182 continue;
6183 }
6184 if let Some(v) = tok.columns.get(&cid).cloned() {
6185 if let Some(t) = self.tokenize_value(cid, &v) {
6186 tok.columns.insert(cid, t);
6187 }
6188 }
6189 }
6190 tok
6191 }
6192 }
6193
6194 pub fn commit(&mut self) -> Result<Epoch> {
6199 self.commit_inner(None)
6200 }
6201
6202 #[doc(hidden)]
6205 pub fn commit_controlled<F>(
6206 &mut self,
6207 control: &crate::ExecutionControl,
6208 mut before_commit: F,
6209 ) -> Result<Epoch>
6210 where
6211 F: FnMut() -> Result<()>,
6212 {
6213 self.commit_inner(Some((control, &mut before_commit)))
6214 }
6215
6216 fn commit_inner(
6217 &mut self,
6218 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6219 ) -> Result<Epoch> {
6220 self.ensure_writable()?;
6221 if !self.has_pending_mutations() {
6222 if self.current_txn_id == 0 && matches!(&self.wal, WalSink::Private(_)) {
6223 return Err(MongrelError::Full(
6224 "standalone transaction id namespace exhausted".into(),
6225 ));
6226 }
6227 return Ok(self.epoch.visible());
6228 }
6229 self.commit_new_epoch_inner(controlled)
6230 }
6231
6232 fn commit_new_epoch(&mut self) -> Result<Epoch> {
6236 self.commit_new_epoch_inner(None)
6237 }
6238
6239 fn commit_new_epoch_inner(
6240 &mut self,
6241 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6242 ) -> Result<Epoch> {
6243 self.ensure_writable()?;
6244 if self.is_shared() {
6245 self.commit_shared(controlled)
6246 } else {
6247 self.commit_private(controlled)
6248 }
6249 }
6250
6251 fn commit_private(
6253 &mut self,
6254 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6255 ) -> Result<Epoch> {
6256 let commit_lock = Arc::clone(&self.commit_lock);
6260 let _g = commit_lock.lock();
6261 let txn_id = self.ensure_txn_id()?;
6264 if let Some((control, before_commit)) = controlled {
6265 control.checkpoint()?;
6266 before_commit()?;
6267 }
6268 let new_epoch = self.epoch.bump_assigned();
6269 let epoch_authority = Arc::clone(&self.epoch);
6270 let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6271 let wal_result = match &mut self.wal {
6275 WalSink::Private(w) => w
6276 .append_txn(
6277 txn_id,
6278 Op::TxnCommit {
6279 epoch: new_epoch.0,
6280 added_runs: Vec::new(),
6281 },
6282 )
6283 .and_then(|_| w.sync()),
6284 WalSink::Shared(_) => unreachable!("commit_private on a shared sink"),
6285 WalSink::ReadOnly => Err(MongrelError::ReadOnlyReplica),
6286 };
6287 if let Err(error) = wal_result {
6288 self.durable_commit_failed = true;
6289 return Err(MongrelError::CommitOutcomeUnknown {
6290 epoch: new_epoch.0,
6291 message: error.to_string(),
6292 });
6293 }
6294 if let Some(epoch) = self.pending_truncate.take() {
6297 self.apply_truncate(epoch);
6298 }
6299 self.invalidate_pending_cache();
6300 let publish_result = self.persist_manifest(new_epoch);
6301 self.epoch.publish_in_order(new_epoch);
6305 epoch_guard.disarm();
6306 if let Err(error) = publish_result {
6307 self.durable_commit_failed = true;
6308 return Err(MongrelError::DurableCommit {
6309 epoch: new_epoch.0,
6310 message: error.to_string(),
6311 });
6312 }
6313 self.current_txn_id = txn_id.checked_add(1).unwrap_or(0);
6314 self.pending_private_mutations = false;
6315 self.data_generation = self.data_generation.wrapping_add(1);
6316 Ok(new_epoch)
6317 }
6318
6319 fn commit_shared(
6325 &mut self,
6326 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6327 ) -> Result<Epoch> {
6328 use std::sync::atomic::Ordering;
6329 let s = match &self.wal {
6330 WalSink::Shared(s) => s.clone(),
6331 WalSink::Private(_) => unreachable!("commit_shared on a private sink"),
6332 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6333 };
6334 if s.poisoned.load(Ordering::Relaxed) {
6335 return Err(MongrelError::Other(
6336 "database poisoned by fsync error".into(),
6337 ));
6338 }
6339 let commit_lock = Arc::clone(&self.commit_lock);
6346 let _g = commit_lock.lock();
6347 if !self.pending_rows.is_empty() {
6348 match controlled.as_ref() {
6349 Some((control, _)) => self.prepare_durable_publish_controlled(control)?,
6350 None => self.prepare_durable_publish()?,
6351 }
6352 }
6353 let txn_id = self.ensure_txn_id()?;
6356 let mut wal = s.wal.lock();
6357 if let Some((control, before_commit)) = controlled {
6358 control.checkpoint()?;
6359 before_commit()?;
6360 }
6361 let new_epoch = self.epoch.bump_assigned();
6362 let epoch_authority = Arc::clone(&self.epoch);
6363 let mut epoch_guard = EpochGuard::new(epoch_authority.as_ref(), new_epoch);
6364 let commit_ts = s.hlc.now().map_err(|skew| {
6367 MongrelError::Other(format!(
6368 "clock skew rejected commit timestamp allocation: {skew}"
6369 ))
6370 })?;
6371 let commit_seq = match wal.append_commit_at(
6372 txn_id,
6373 new_epoch,
6374 &[],
6375 commit_ts.physical_micros.saturating_mul(1_000),
6376 ) {
6377 Ok(commit_seq) => commit_seq,
6378 Err(error) => {
6379 s.poisoned.store(true, Ordering::Relaxed);
6380 s.lifecycle.poison();
6381 return Err(MongrelError::CommitOutcomeUnknown {
6382 epoch: new_epoch.0,
6383 message: error.to_string(),
6384 });
6385 }
6386 };
6387 drop(wal);
6388 if let Err(error) = s.group.await_durable(&s.wal, commit_seq) {
6389 s.poisoned.store(true, Ordering::Relaxed);
6390 s.lifecycle.poison();
6391 return Err(MongrelError::CommitOutcomeUnknown {
6392 epoch: new_epoch.0,
6393 message: error.to_string(),
6394 });
6395 }
6396
6397 if self.pending_truncate.take().is_some() {
6400 self.apply_truncate(new_epoch);
6401 }
6402 let mut rows = std::mem::take(&mut self.pending_rows);
6403 if !rows.is_empty() {
6404 for r in &mut rows {
6405 r.committed_epoch = new_epoch;
6406 r.commit_ts = Some(commit_ts);
6407 }
6408 let auto_inc_flags = std::mem::take(&mut self.pending_rows_auto_inc);
6409 let all_auto_generated =
6410 auto_inc_flags.len() == rows.len() && auto_inc_flags.iter().all(|b| *b);
6411 self.apply_put_rows_inner_prepared(rows, !all_auto_generated);
6412 } else {
6413 self.pending_rows_auto_inc.clear();
6414 }
6415 let dels = std::mem::take(&mut self.pending_dels);
6416 for rid in dels {
6417 self.apply_delete_at(rid, new_epoch, Some(commit_ts));
6418 }
6419
6420 self.invalidate_pending_cache();
6421 let publish_result = self.persist_manifest(new_epoch);
6422 self.epoch.publish_in_order(new_epoch);
6423 epoch_guard.disarm();
6424 let _ = s.change_wake.send(());
6425 if let Err(error) = publish_result {
6426 self.durable_commit_failed = true;
6427 s.poisoned.store(true, Ordering::Relaxed);
6428 s.lifecycle.poison();
6429 return Err(MongrelError::DurableCommit {
6430 epoch: new_epoch.0,
6431 message: error.to_string(),
6432 });
6433 }
6434 self.current_txn_id = 0;
6436 self.data_generation = self.data_generation.wrapping_add(1);
6437 Ok(new_epoch)
6438 }
6439
6440 pub fn flush(&mut self) -> Result<Epoch> {
6448 self.flush_with_outcome().map(|(epoch, _)| epoch)
6449 }
6450
6451 pub fn flush_with_outcome(&mut self) -> Result<(Epoch, bool)> {
6453 self.flush_with_outcome_inner(None)
6454 }
6455
6456 #[doc(hidden)]
6459 pub fn flush_with_outcome_controlled<F>(
6460 &mut self,
6461 control: &crate::ExecutionControl,
6462 mut before_commit: F,
6463 ) -> Result<(Epoch, bool)>
6464 where
6465 F: FnMut() -> Result<()>,
6466 {
6467 self.flush_with_outcome_inner(Some((control, &mut before_commit)))
6468 }
6469
6470 fn flush_with_outcome_inner(
6471 &mut self,
6472 controlled: Option<(&crate::ExecutionControl, &mut dyn FnMut() -> Result<()>)>,
6473 ) -> Result<(Epoch, bool)> {
6474 match controlled.as_ref() {
6475 Some((control, _)) => {
6476 self.ensure_indexes_complete_controlled(control, || true)?;
6477 }
6478 None => self.ensure_indexes_complete()?,
6479 }
6480 let committed = self.has_pending_mutations();
6481 let epoch = self.commit_inner(controlled)?;
6482 let finish: Result<(Epoch, bool)> = (|| {
6483 let rows = self.memtable.drain_sorted();
6484 if !rows.is_empty() {
6485 self.mutable_run.insert_many(rows);
6486 }
6487 if self.mutable_run.approx_bytes() >= self.mutable_run_spill_bytes {
6488 self.spill_mutable_run(epoch)?;
6489 self.mark_flushed(epoch)?;
6493 self.persist_manifest(epoch)?;
6494 self.build_learned_ranges()?;
6495 self.checkpoint_indexes(epoch);
6498 let _ = self.publish_run_lookup_directory();
6503 }
6504 Ok((epoch, committed))
6507 })();
6508 let outcome = match finish {
6509 Err(error) if committed => Err(MongrelError::DurableCommit {
6510 epoch: epoch.0,
6511 message: error.to_string(),
6512 }),
6513 result => result,
6514 };
6515 if outcome.is_ok() {
6516 let _ = self.publish_read_generation();
6522 }
6523 outcome
6524 }
6525
6526 pub(crate) fn has_pending_mutations(&self) -> bool {
6527 self.pending_private_mutations
6528 || !self.pending_rows.is_empty()
6529 || !self.pending_dels.is_empty()
6530 || self.pending_truncate.is_some()
6531 }
6532
6533 pub fn has_pending_writes(&self) -> bool {
6534 self.has_pending_mutations()
6535 }
6536
6537 pub fn force_flush(&mut self) -> Result<Epoch> {
6546 let saved = self.mutable_run_spill_bytes;
6547 self.mutable_run_spill_bytes = 1;
6548 let result = self.flush();
6549 self.mutable_run_spill_bytes = saved;
6550 result
6551 }
6552
6553 pub fn close(&mut self) -> Result<()> {
6560 if self.memtable_len() > 0 || self.mutable_run_len() > 0 {
6561 self.force_flush()?;
6562 }
6563 self.result_cache
6569 .lock()
6570 .shutdown_persistent_cache(std::time::Duration::from_secs(5));
6571 Ok(())
6572 }
6573
6574 pub(crate) fn wal_is_read_only(&self) -> bool {
6584 matches!(self.wal, WalSink::ReadOnly)
6585 }
6586
6587 pub(crate) fn drain_committed_memtable_rows(&mut self, epoch: Epoch) {
6593 if self.memtable_len() == 0 {
6594 return;
6595 }
6596 let rows = self.memtable.drain_sorted();
6597 let mut pending = Vec::new();
6598 let mut committed = Vec::new();
6599 for row in rows {
6600 if row.committed_epoch > epoch {
6601 pending.push(row);
6602 } else {
6603 committed.push(row);
6604 }
6605 }
6606 if !committed.is_empty() {
6607 self.mutable_run.insert_many(committed);
6608 }
6609 for row in pending {
6610 self.memtable.upsert(row);
6611 }
6612 }
6613
6614 pub(crate) fn mark_flushed(&mut self, epoch: Epoch) -> Result<()> {
6615 let op = Op::Flush {
6616 table_id: self.table_id,
6617 flushed_epoch: epoch.0,
6618 };
6619 match &mut self.wal {
6620 WalSink::Private(w) => {
6621 w.append_system(op)?;
6622 w.sync()?;
6623 }
6624 WalSink::Shared(s) => {
6625 s.wal.lock().append_system(op)?;
6630 }
6631 WalSink::ReadOnly => return Err(MongrelError::ReadOnlyReplica),
6632 }
6633 self.flushed_epoch = epoch.0;
6634 if matches!(self.wal, WalSink::Private(_)) {
6635 self.rotate_wal(epoch)?;
6636 }
6637 Ok(())
6638 }
6639
6640 fn spill_mutable_run(&mut self, epoch: Epoch) -> Result<()> {
6644 if self.mutable_run.is_empty() {
6645 return Ok(());
6646 }
6647 let run_id = self.alloc_run_id()?;
6648 let rows = self.mutable_run.drain_sorted();
6649 if rows.is_empty() {
6650 return Ok(());
6651 }
6652 let path = self.run_path(run_id);
6653 let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0);
6654 if let Some(kek) = &self.kek {
6655 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6656 }
6657 let header = match self.create_run_file(run_id)? {
6658 Some(file) => writer.write_file(file, &rows)?,
6659 None => writer.write(&path, &rows)?,
6660 };
6661 self.run_refs.push(RunRef {
6662 run_id: run_id as u128,
6663 level: 0,
6664 epoch_created: epoch.0,
6665 row_count: header.row_count,
6666 });
6667 self.run_row_id_ranges
6668 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6669 Ok(())
6670 }
6671
6672 pub fn set_mutable_run_spill_bytes(&mut self, bytes: u64) {
6676 self.mutable_run_spill_bytes = bytes.max(1);
6677 }
6678
6679 pub fn set_compaction_zstd_level(&mut self, level: i32) {
6683 self.compaction_zstd_level = level;
6684 }
6685
6686 pub fn set_result_cache_max_bytes(&mut self, max_bytes: u64) {
6690 self.result_cache.lock().set_max_bytes(max_bytes);
6691 }
6692
6693 pub fn flush_persistent_cache(&self, deadline_ms: u64) -> u64 {
6698 self.result_cache
6699 .lock()
6700 .flush_persistent_cache(std::time::Duration::from_millis(deadline_ms))
6701 }
6702
6703 pub fn shutdown_persistent_cache(&mut self, deadline_ms: u64) {
6708 self.result_cache
6709 .lock()
6710 .shutdown_persistent_cache(std::time::Duration::from_millis(deadline_ms));
6711 }
6712
6713 #[doc(hidden)]
6718 pub fn _set_persist_min_bytes_for_test(&mut self, min: u64) {
6719 self.result_cache.lock().set_persist_min_bytes(min);
6720 }
6721
6722 #[doc(hidden)]
6729 pub fn _force_persistent_worker_spawn_failure_for_test(enabled: bool) {
6730 PERSISTENT_WORKER_SPAWN_FAILURE.with(|flag| flag.set(enabled));
6731 }
6732
6733 #[doc(hidden)]
6740 pub fn _persist_cached_entry_synchronously_for_maintenance(
6741 &mut self,
6742 q: &crate::query::Query,
6743 ) -> bool {
6744 let key = crate::query::canonical_query_key(&q.conditions, None, 0)
6745 ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
6746 ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
6747 let identity = PersistentCacheIdentity {
6748 table_id: self.table_id(),
6749 schema_id: self.schema.schema_id,
6750 logical_generation: self.current_epoch().0,
6751 };
6752 let mut cache = self.result_cache.lock();
6753 let Some(entry) = cache.entries.get(&key).map(|e| e.clone_for_persist()) else {
6754 return false;
6755 };
6756 let entry_generation = cache.allocate_persist_generation(key);
6757 let context = PersistContext {
6758 identity,
6759 key,
6760 entry_generation,
6761 };
6762 cache.persist_entry_synchronously_for_maintenance(context, &entry);
6763 true
6764 }
6765
6766 pub(crate) fn clear_result_cache(&mut self) {
6770 self.result_cache.lock().clear();
6771 }
6772
6773 pub fn mutable_run_len(&self) -> usize {
6775 self.mutable_run.len()
6776 }
6777
6778 pub(crate) fn drain_mutable_run(&mut self) -> Vec<Row> {
6781 self.mutable_run.drain_sorted()
6782 }
6783
6784 pub(crate) fn snapshot_mutable_run(&self) -> Vec<Row> {
6786 let mut snapshot = self.mutable_run.clone();
6787 snapshot.drain_sorted()
6788 }
6789
6790 pub fn bulk_load(&mut self, batch: Vec<Vec<(u16, Value)>>) -> Result<Epoch> {
6795 self.ensure_writable()?;
6796 let n = batch.len();
6797 if n == 0 {
6798 return Ok(self.current_epoch());
6799 }
6800 for row in &batch {
6801 self.schema.validate_values(row)?;
6802 }
6803 let epoch = self.commit_new_epoch()?;
6804 let live_before = self.live_count;
6805 self.spill_mutable_run(epoch)?;
6809 let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
6810 && self.indexes_complete
6811 && self.run_refs.is_empty()
6812 && self.memtable.is_empty()
6813 && self.mutable_run.is_empty();
6814 let mut user_columns: Vec<(u16, columnar::NativeColumn)> = {
6820 use rayon::prelude::*;
6821 self.schema
6822 .columns
6823 .par_iter()
6824 .map(|cdef| {
6825 (
6826 cdef.id,
6827 columnar::rows_to_native(cdef.ty.clone(), &batch, cdef.id),
6828 )
6829 })
6830 .collect::<Vec<_>>()
6831 };
6832 drop(batch);
6833 self.fill_auto_inc_native_columns(&mut user_columns, n)?;
6838 self.validate_columns_not_null(&user_columns, n)?;
6839 let winner_idx = self
6840 .bulk_pk_winner_indices(&user_columns, n)
6841 .filter(|idx| idx.len() != n);
6842 let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
6843 match winner_idx.as_deref() {
6844 Some(idx) => {
6845 let compacted = user_columns
6846 .iter()
6847 .map(|(id, c)| (*id, c.gather(idx)))
6848 .collect();
6849 (compacted, idx.len())
6850 }
6851 None => (std::mem::take(&mut user_columns), n),
6852 };
6853 self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
6854 let first = self.allocator.alloc_range(write_n as u64)?.0;
6855 for rid in first..first + write_n as u64 {
6856 self.reservoir.offer(rid);
6857 }
6858 let run_id = self.alloc_run_id()?;
6859 let path = self.run_path(run_id);
6860 let mut writer = RunWriter::new(&self.schema, run_id as u128, epoch, 0)
6861 .clean(true)
6862 .with_lz4()
6863 .with_native_endian();
6864 if let Some(kek) = &self.kek {
6865 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
6866 }
6867 let header = match self.create_run_file(run_id)? {
6868 Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
6869 None => writer.write_native(&path, &write_columns, write_n, first)?,
6870 };
6871 self.run_refs.push(RunRef {
6872 run_id: run_id as u128,
6873 level: 0,
6874 epoch_created: epoch.0,
6875 row_count: header.row_count,
6876 });
6877 self.run_row_id_ranges
6878 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
6879 self.live_count = self.live_count.saturating_add(write_n as u64);
6880 if eager_index_build {
6881 let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
6882 self.index_columns_bulk(&write_columns, &row_ids);
6883 self.indexes_complete = true;
6884 self.build_learned_ranges()?;
6885 } else {
6886 self.indexes_complete = false;
6887 }
6888 self.mark_flushed(epoch)?;
6889 self.persist_manifest(epoch)?;
6890 if eager_index_build {
6891 self.checkpoint_indexes(epoch);
6892 }
6893 self.clear_result_cache();
6894 Ok(epoch)
6895 }
6896
6897 fn rotate_wal(&mut self, epoch: Epoch) -> Result<()> {
6900 let segment = next_wal_segment(&self.dir.join(WAL_DIR))?;
6901 let cipher = self.wal_dek.as_ref().map(|dk| make_cipher(dk));
6902 let segment_no = segment
6905 .file_stem()
6906 .and_then(|s| s.to_str())
6907 .and_then(|s| s.strip_prefix("seg-"))
6908 .and_then(|s| s.parse::<u64>().ok())
6909 .unwrap_or(0);
6910 let mut wal = Wal::create_with_cipher(segment, epoch, cipher, segment_no)?;
6911 wal.set_sync_byte_threshold(self.sync_byte_threshold);
6912 wal.sync()?;
6913 self.wal = WalSink::Private(wal);
6914 Ok(())
6915 }
6916
6917 pub(crate) fn invalidate_pending_cache(&mut self) {
6922 self.result_cache
6923 .lock()
6924 .invalidate(&self.pending_delete_rids, &self.pending_put_cols);
6925 self.pending_delete_rids.clear();
6926 self.pending_put_cols.clear();
6927 }
6928
6929 pub(crate) fn persist_manifest(&self, epoch: Epoch) -> Result<()> {
6930 let mut m = Manifest::new(self.table_id, self.schema.schema_id);
6931 m.current_epoch = epoch.0;
6932 m.next_row_id = self.allocator.current().0;
6933 m.runs = self.run_refs.clone();
6934 m.live_count = self.live_count;
6935 m.global_idx_epoch = self.global_idx_epoch;
6936 m.flushed_epoch = self.flushed_epoch;
6937 m.retiring = self.retiring.clone();
6938 m.auto_inc_next = match self.auto_inc {
6942 Some(ai) if ai.seeded => ai.next,
6943 _ => 0,
6944 };
6945 m.ttl = self.ttl;
6946 let meta_dek = self.manifest_meta_dek();
6947 match self._root_guard.as_deref() {
6948 Some(root) => manifest::write_durable(root, &mut m, meta_dek.as_ref())?,
6949 None => manifest::write_atomic(&self.dir, &mut m, meta_dek.as_ref())?,
6950 }
6951 Ok(())
6952 }
6953
6954 pub(crate) fn publish_run_lookup_directory(&mut self) -> Result<()> {
6961 mongreldb_fault::inject("manifest.publication")
6965 .map_err(|e| MongrelError::Other(format!("manifest.publication fault: {e}")))?;
6966 let active_runs = self.run_refs.clone();
6967 let schema_id = self.schema.schema_id;
6968 let index_generation = self.global_idx_epoch;
6969 let run_generation = active_runs.len() as u64;
6970 let fingerprint = crate::run_lookup::compute_fingerprint(
6971 &active_runs.iter().map(|r| r.run_id).collect::<Vec<_>>(),
6972 schema_id,
6973 index_generation,
6974 run_generation,
6975 crate::run_lookup::DIRECTORY_FORMAT_VERSION,
6976 );
6977 let dir = match crate::run_lookup::RunLookupDirectory::rebuild_from_runs(&active_runs, self)
6978 {
6979 Ok(d) => d,
6980 Err(error) => {
6981 self.run_lookup.complete = false;
6984 self.lookup_metrics
6985 .directory_incomplete
6986 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6987 return Err(error);
6988 }
6989 };
6990 let mut dir = dir;
6994 dir.set_fingerprint(fingerprint);
6995 let runs_dir = match self.runs_root.as_deref() {
6996 Some(root) => match root.io_path() {
6997 Ok(p) => p,
6998 Err(_) => self.dir.join(RUNS_DIR),
6999 },
7000 None => self.dir.join(RUNS_DIR),
7001 };
7002 mongreldb_fault::inject("directory.temp_write")
7005 .map_err(|e| MongrelError::Other(format!("directory.temp_write fault: {e}")))?;
7006 let publish =
7007 dir.write_checkpoint_sharded(&runs_dir, crate::run_lookup::DEFAULT_SHARD_BYTES);
7008 mongreldb_fault::inject("directory.sync")
7009 .map_err(|e| MongrelError::Other(format!("directory.sync fault: {e}")))?;
7010 mongreldb_fault::inject("directory.rename")
7011 .map_err(|e| MongrelError::Other(format!("directory.rename fault: {e}")))?;
7012 if let Err(error) = publish {
7013 self.run_lookup = RunLookupState {
7016 directory: None,
7017 fingerprint,
7018 complete: false,
7019 };
7020 self.lookup_metrics
7021 .directory_incomplete
7022 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7023 self.lookup_metrics
7024 .directory_lookup_fallback
7025 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7026 return Err(error.into());
7027 }
7028 self.run_lookup = RunLookupState {
7029 directory: Some(std::sync::Arc::new(dir)),
7030 fingerprint,
7031 complete: true,
7032 };
7033 Ok(())
7034 }
7035
7036 pub(crate) fn plan_recovered_metadata(&mut self) -> Result<RecoveryMetadataPlan> {
7037 let rows = self.visible_rows_at_time(Snapshot::unbounded(), i64::MIN)?;
7041 let live_count = u64::try_from(rows.len())
7042 .map_err(|_| MongrelError::Full("table live-row count exceeds u64".into()))?;
7043 let auto_inc = match self.auto_inc {
7044 Some(mut state) => {
7045 let maximum = self.scan_max_int64(state.column_id)?;
7046 let after_maximum = maximum.checked_add(1).ok_or_else(|| {
7047 MongrelError::Full("AUTO_INCREMENT namespace exhausted".into())
7048 })?;
7049 state.next = state.next.max(after_maximum).max(1);
7050 state.seeded = true;
7051 Some(state)
7052 }
7053 None => None,
7054 };
7055 Ok(RecoveryMetadataPlan {
7056 live_count,
7057 auto_inc,
7058 changed: live_count != self.live_count
7059 || auto_inc.is_some_and(|planned| {
7060 self.auto_inc.is_none_or(|current| {
7061 current.next != planned.next || current.seeded != planned.seeded
7062 })
7063 }),
7064 })
7065 }
7066
7067 pub(crate) fn apply_recovered_metadata(
7068 &mut self,
7069 plan: RecoveryMetadataPlan,
7070 epoch: Epoch,
7071 ) -> Result<()> {
7072 if !plan.changed {
7073 return Ok(());
7074 }
7075 self.live_count = plan.live_count;
7076 self.auto_inc = plan.auto_inc;
7077 self.persist_manifest(epoch)
7078 }
7079
7080 pub(crate) fn checkpoint_indexes(&mut self, epoch: Epoch) {
7086 if !self.indexes_complete {
7089 return;
7090 }
7091 if epoch.0 > self.flushed_epoch {
7099 return;
7100 }
7101 if crate::catalog::inject_hook("index.publish.before").is_err() {
7104 return;
7105 }
7106 if self.idx_root.is_none() {
7107 if let Some(root) = self._root_guard.as_ref() {
7108 let Ok(idx_root) = root.create_directory_all_pinned(global_idx::IDX_DIR) else {
7109 return;
7110 };
7111 self.idx_root = Some(Arc::new(idx_root));
7112 }
7113 }
7114 let snap = global_idx::IndexSnapshot {
7115 hot: &self.hot,
7116 bitmap: &self.bitmap,
7117 ann: &self.ann,
7118 fm: &self.fm,
7119 sparse: &self.sparse,
7120 minhash: &self.minhash,
7121 learned_range: &self.learned_range,
7122 };
7123 let idx_dek = self.idx_dek();
7125 let written = match self.idx_root.as_deref() {
7126 Some(root) => global_idx::write_atomic_root(
7127 root,
7128 self.table_id,
7129 epoch.0,
7130 snap,
7131 idx_dek.as_deref(),
7132 ),
7133 None => global_idx::write_atomic(
7134 &self.dir,
7135 self.table_id,
7136 epoch.0,
7137 snap,
7138 idx_dek.as_deref(),
7139 ),
7140 };
7141 if written.is_ok() {
7142 self.global_idx_epoch = epoch.0;
7143 let _ = self.persist_manifest(epoch);
7144 let _ = crate::catalog::inject_hook("index.publish.after");
7146 }
7147 }
7148
7149 pub(crate) fn invalidate_index_checkpoint(&mut self) {
7152 self.global_idx_epoch = 0;
7153 if let Some(root) = self.idx_root.as_deref() {
7154 let _ = root.remove_file(global_idx::IDX_FILENAME);
7155 } else {
7156 global_idx::remove(&self.dir);
7157 }
7158 let _ = self.persist_manifest(self.epoch.visible());
7159 }
7160
7161 pub(crate) fn prepare_indexes_for_run_replacement(&mut self) {
7166 self.indexes_complete = false;
7167 self.global_idx_epoch = 0;
7168 if let Some(root) = self.idx_root.as_deref() {
7169 let _ = root.remove_file(global_idx::IDX_FILENAME);
7170 } else {
7171 global_idx::remove(&self.dir);
7172 }
7173 }
7174
7175 pub(crate) fn finish_indexes_for_run_replacement(&mut self) {
7176 self.indexes_complete = true;
7177 }
7178
7179 pub(crate) fn poison_after_maintenance_publish_failure(&mut self) {
7185 self.durable_commit_failed = true;
7186 if let WalSink::Shared(shared) = &self.wal {
7187 shared
7188 .poisoned
7189 .store(true, std::sync::atomic::Ordering::Relaxed);
7190 }
7191 }
7192
7193 pub(crate) fn mark_unavailable_after_quarantine(&mut self) {
7197 self.durable_commit_failed = true;
7198 }
7199
7200 pub fn get(&self, row_id: RowId, snapshot: Snapshot) -> Option<Row> {
7225 let mut best: Option<Row> = None;
7226 fn consider(best: &mut Option<Row>, row: Row, snapshot: Snapshot) {
7229 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7230 return;
7231 }
7232 if best.as_ref().is_none_or(|current| {
7233 Snapshot::version_is_newer(
7234 row.committed_epoch,
7235 row.commit_ts,
7236 current.committed_epoch,
7237 current.commit_ts,
7238 )
7239 }) {
7240 *best = Some(row);
7241 }
7242 }
7243 if let Some((_, row)) = self.memtable.get_version_at(row_id, snapshot) {
7244 consider(&mut best, row, snapshot);
7245 }
7246 if let Some((_, row)) = self.mutable_run.get_version_at(row_id, snapshot) {
7247 consider(&mut best, row, snapshot);
7248 }
7249 let decision = if self.run_lookup.complete {
7253 let active_ids: Vec<u128> = self.run_refs.iter().map(|r| r.run_id).collect();
7258 let expected_fp = crate::run_lookup::compute_fingerprint(
7259 &active_ids,
7260 self.schema.schema_id,
7261 self.global_idx_epoch,
7262 active_ids.len() as u64,
7263 crate::run_lookup::DIRECTORY_FORMAT_VERSION,
7264 );
7265 if self.run_lookup.fingerprint == expected_fp {
7266 match self.run_lookup.directory.as_ref() {
7267 Some(dir) => dir.decide(row_id),
7268 None => crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale,
7269 }
7270 } else {
7271 self.lookup_metrics
7272 .directory_lookup_fallback
7273 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7274 crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7275 }
7276 } else {
7277 self.lookup_metrics
7278 .directory_lookup_fallback
7279 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7280 crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale
7281 };
7282 match decision {
7283 crate::run_lookup::DirectoryLookupDecision::CompleteMiss => {
7284 self.lookup_metrics
7289 .directory_lookup_hit
7290 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7291 self.lookup_metrics
7292 .directory_complete_miss_total
7293 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7294 }
7295 crate::run_lookup::DirectoryLookupDecision::Candidates(mut locators) => {
7296 locators.sort_by(|a, b| {
7303 if snapshot.uses_hlc_authority() {
7304 b.max_hlc
7305 .cmp(&a.max_hlc)
7306 .then_with(|| b.max_epoch.cmp(&a.max_epoch))
7307 } else {
7308 b.max_epoch
7309 .cmp(&a.max_epoch)
7310 .then_with(|| b.max_hlc.cmp(&a.max_hlc))
7311 }
7312 });
7313 let mut opened: std::collections::HashSet<u128> = std::collections::HashSet::new();
7319 let mut early_stopped: u64 = 0;
7320 for locator in &locators {
7321 let stamp = best
7324 .as_ref()
7325 .map(|current| crate::run_lookup::VersionStamp {
7326 epoch: current.committed_epoch,
7327 hlc: current.commit_ts,
7328 });
7329 if let Some(s) = stamp {
7330 if !locator.can_contain_version_newer_than(s, snapshot) {
7331 early_stopped += 1;
7332 continue;
7333 }
7334 }
7335 if locator.is_impossible_for(snapshot) {
7336 continue;
7337 }
7338 if !opened.insert(locator.run_id) {
7339 continue;
7340 }
7341 self.lookup_metrics
7342 .directory_run_readers_opened
7343 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7344 self.lookup_metrics
7345 .get_run_opened
7346 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7347 let Ok(mut reader) = self.open_reader(locator.run_id) else {
7348 continue;
7349 };
7350 let Ok(Some((_, row))) = reader.get_version_at(row_id, snapshot) else {
7353 continue;
7354 };
7355 consider(&mut best, row, snapshot);
7356 }
7357 if early_stopped > 0 {
7358 self.lookup_metrics
7359 .directory_early_stop_total
7360 .fetch_add(early_stopped, std::sync::atomic::Ordering::Relaxed);
7361 }
7362 self.lookup_metrics
7363 .directory_lookup_hit
7364 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7365 }
7366 crate::run_lookup::DirectoryLookupDecision::UnavailableOrStale => {
7367 for rr in &self.run_refs {
7369 if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
7373 if row_id.0 < min_rid || row_id.0 > max_rid {
7374 self.lookup_metrics
7375 .get_run_skipped
7376 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7377 continue;
7378 }
7379 }
7380 self.lookup_metrics
7381 .get_run_opened
7382 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7383 let Ok(mut reader) = self.open_reader(rr.run_id) else {
7384 continue;
7385 };
7386 let Ok(Some((_, row))) = reader.get_version_at(row_id, snapshot) else {
7389 continue;
7390 };
7391 consider(&mut best, row, snapshot);
7392 }
7393 }
7394 }
7395 let now_nanos = unix_nanos_now();
7396 match best {
7397 Some(r) if r.deleted || self.row_expired_at(&r, now_nanos) => None,
7398 Some(r) => Some(r),
7399 None => None,
7400 }
7401 }
7402
7403 pub fn visible_rows(&self, snapshot: Snapshot) -> Result<Vec<Row>> {
7407 self.visible_rows_at_time(snapshot, unix_nanos_now())
7408 }
7409
7410 #[doc(hidden)]
7413 pub fn visible_rows_controlled(
7414 &self,
7415 snapshot: Snapshot,
7416 control: &crate::ExecutionControl,
7417 ) -> Result<Vec<Row>> {
7418 let mut out = Vec::new();
7419 self.for_each_visible_row_controlled(snapshot, control, |row| {
7420 out.push(row);
7421 Ok(())
7422 })?;
7423 Ok(out)
7424 }
7425
7426 #[doc(hidden)]
7429 pub fn for_each_visible_row_controlled<F>(
7430 &self,
7431 snapshot: Snapshot,
7432 control: &crate::ExecutionControl,
7433 mut visit: F,
7434 ) -> Result<()>
7435 where
7436 F: FnMut(Row) -> Result<()>,
7437 {
7438 let setup_start = std::time::Instant::now();
7445 let mut versions_examined: u64 = 0;
7446 let mut rows_emitted: u64 = 0;
7447 let mut checkpoints: u64 = 0;
7448 let mut first_row_recorded = false;
7449 let mut sources: Vec<ControlledVisibleSource<'_>> =
7450 Vec::with_capacity(self.run_refs.len() + 2);
7451 control.checkpoint()?;
7452 checkpoints += 1;
7453 if !self.memtable.is_empty() {
7456 sources.push(ControlledVisibleSource::memtable_cursor(
7457 self.memtable.newest_visible_iter(&snapshot),
7458 ));
7459 }
7460 control.checkpoint()?;
7461 checkpoints += 1;
7462 if !self.mutable_run.is_empty() {
7463 sources.push(ControlledVisibleSource::mutable_run_cursor(
7464 self.mutable_run.newest_visible_iter(&snapshot),
7465 ));
7466 }
7467 for run in &self.run_refs {
7468 control.checkpoint()?;
7469 checkpoints += 1;
7470 let reader = self.open_reader(run.run_id)?;
7471 sources.push(ControlledVisibleSource::run(
7472 reader.into_visible_version_cursor_at(snapshot)?,
7473 ));
7474 }
7475 let first_row_start = setup_start;
7478 let _setup_us = setup_start.elapsed().as_micros() as u64;
7479 let now_nanos = unix_nanos_now();
7480 let mut first_row_us: u64 = 0;
7481 let result = merge_controlled_visible_sources(
7482 &mut sources,
7483 control,
7484 |row| self.row_expired_at(row, now_nanos),
7485 |row| {
7486 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7487 return Ok(());
7488 }
7489 versions_examined += 1;
7490 if !first_row_recorded {
7491 first_row_us = first_row_start.elapsed().as_micros() as u64;
7492 first_row_recorded = true;
7493 }
7494 rows_emitted += 1;
7495 visit(row)
7496 },
7497 );
7498 let time_to_first_row_us = if first_row_recorded { first_row_us } else { 0 };
7499 crate::trace::QueryTrace::record(|t| {
7500 t.controlled_scan_versions_examined = t
7501 .controlled_scan_versions_examined
7502 .saturating_add(versions_examined as usize);
7503 t.controlled_scan_rows_emitted = t
7504 .controlled_scan_rows_emitted
7505 .saturating_add(rows_emitted as usize);
7506 t.controlled_scan_checkpoints = t
7507 .controlled_scan_checkpoints
7508 .saturating_add(checkpoints as usize);
7509 t.controlled_scan_time_to_first_row_us = t
7510 .controlled_scan_time_to_first_row_us
7511 .saturating_add(time_to_first_row_us);
7512 t.controlled_scan_setup_time_us =
7513 t.controlled_scan_setup_time_us.saturating_add(_setup_us);
7514 });
7515 result
7516 }
7517
7518 #[doc(hidden)]
7519 pub fn visible_rows_at_time(&self, snapshot: Snapshot, now_nanos: i64) -> Result<Vec<Row>> {
7520 let mut best: HashMap<u64, Row> = HashMap::new();
7521 let mut fold = |row: Row| {
7522 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
7523 return;
7524 }
7525 best.entry(row.row_id.0)
7526 .and_modify(|existing| {
7527 if Snapshot::version_is_newer(
7528 row.committed_epoch,
7529 row.commit_ts,
7530 existing.committed_epoch,
7531 existing.commit_ts,
7532 ) {
7533 *existing = row.clone();
7534 }
7535 })
7536 .or_insert(row);
7537 };
7538 for row in self.memtable.visible_versions_at(snapshot) {
7539 fold(row);
7540 }
7541 for row in self.mutable_run.visible_versions_at(snapshot) {
7542 fold(row);
7543 }
7544 for rr in &self.run_refs {
7545 let mut reader = self.open_reader(rr.run_id)?;
7546 for row in reader.visible_versions_at(snapshot)? {
7548 fold(row);
7549 }
7550 }
7551 let mut out: Vec<Row> = best
7552 .into_values()
7553 .filter_map(|r| {
7554 if r.deleted || self.row_expired_at(&r, now_nanos) {
7555 None
7556 } else {
7557 Some(r)
7558 }
7559 })
7560 .collect();
7561 out.sort_by_key(|r| r.row_id);
7562 Ok(out)
7563 }
7564
7565 pub fn visible_columns(&self, snapshot: Snapshot) -> Result<Vec<(u16, Vec<Value>)>> {
7572 if self.ttl.is_none()
7573 && self.memtable.is_empty()
7574 && self.mutable_run.is_empty()
7575 && self.run_refs.len() == 1
7576 {
7577 let rr = self.run_refs[0].clone();
7578 let mut reader = self.open_reader(rr.run_id)?;
7579 let idxs = reader.visible_indices_at(snapshot)?;
7580 let mut cols = Vec::with_capacity(self.schema.columns.len());
7581 for cdef in &self.schema.columns {
7582 cols.push((cdef.id, reader.gather_column(cdef.id, &idxs)?));
7583 }
7584 return Ok(cols);
7585 }
7586 let rows = self.visible_rows(snapshot)?;
7588 let mut cols: Vec<(u16, Vec<Value>)> = self
7589 .schema
7590 .columns
7591 .iter()
7592 .map(|c| (c.id, Vec::with_capacity(rows.len())))
7593 .collect();
7594 for r in &rows {
7595 for (cid, vec) in cols.iter_mut() {
7596 vec.push(r.columns.get(cid).cloned().unwrap_or(Value::Null));
7597 }
7598 }
7599 Ok(cols)
7600 }
7601
7602 pub fn lookup_pk(&self, key: &[u8]) -> Option<RowId> {
7604 let row_id = self.hot.get(key)?;
7605 if self.ttl.is_none() || self.get(row_id, Snapshot::unbounded()).is_some() {
7606 Some(row_id)
7607 } else {
7608 None
7609 }
7610 }
7611
7612 pub fn lookup_metrics_snapshot(&self) -> LookupMetricsSnapshot {
7616 let mut snap = self.lookup_metrics.snapshot();
7617 let cache = self.result_cache.lock();
7618 let (mem, disk, miss, write_us) = cache.cache_counters();
7619 snap.result_cache_memory_hit = mem;
7620 snap.result_cache_disk_hit = disk;
7621 snap.result_cache_miss = miss;
7622 snap.result_cache_persistent_write_us = write_us;
7623 let (unavailable, skipped, spawn_failures, worker_shutdowns) = cache.publication_counters();
7625 snap.result_cache_persist_unavailable_total = unavailable;
7626 snap.result_cache_persist_skipped_total = skipped;
7627 snap.result_cache_worker_spawn_failures_total = spawn_failures;
7628 snap.result_cache_worker_shutdown_total = worker_shutdowns;
7629 if let Some(writer_snap) = cache.persist_snapshot() {
7632 snap.result_cache_persist_enqueued_total =
7633 writer_snap.result_cache_persist_enqueued_total;
7634 snap.result_cache_persist_coalesced_total =
7635 writer_snap.result_cache_persist_coalesced_total;
7636 snap.result_cache_persist_dropped_store_total =
7637 writer_snap.result_cache_persist_dropped_store_total;
7638 snap.result_cache_persist_remove_total = writer_snap.result_cache_persist_remove_total;
7639 snap.result_cache_persist_stale_store_skipped_total =
7640 writer_snap.result_cache_persist_stale_store_skipped_total;
7641 snap.result_cache_persist_errors_total = writer_snap.result_cache_persist_errors_total;
7642 snap.result_cache_persist_shutdown_abandoned_total =
7643 writer_snap.result_cache_persist_shutdown_abandoned_total;
7644 snap.result_cache_persist_queue_depth = writer_snap.result_cache_persist_queue_depth;
7645 }
7646 snap
7647 }
7648
7649 pub fn query(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
7654 self.query_at_with_allowed(q, self.snapshot(), None)
7655 }
7656
7657 pub fn query_controlled(
7660 &mut self,
7661 q: &crate::query::Query,
7662 control: &crate::ExecutionControl,
7663 ) -> Result<Vec<Row>> {
7664 self.query_at_with_allowed_controlled(q, self.snapshot(), None, control)
7665 }
7666
7667 pub fn query_at_with_allowed(
7670 &mut self,
7671 q: &crate::query::Query,
7672 snapshot: Snapshot,
7673 allowed: Option<&std::collections::HashSet<RowId>>,
7674 ) -> Result<Vec<Row>> {
7675 self.query_at_with_allowed_after(q, snapshot, allowed, None)
7676 }
7677
7678 #[doc(hidden)]
7679 pub fn query_at_with_allowed_controlled(
7680 &mut self,
7681 q: &crate::query::Query,
7682 snapshot: Snapshot,
7683 allowed: Option<&std::collections::HashSet<RowId>>,
7684 control: &crate::ExecutionControl,
7685 ) -> Result<Vec<Row>> {
7686 self.require_select()?;
7687 self.ensure_indexes_complete_controlled(control, || true)?;
7688 self.validate_native_query(q)?;
7689 self.query_conditions_at(
7690 &q.conditions,
7691 snapshot,
7692 allowed,
7693 q.limit,
7694 q.offset,
7695 None,
7696 unix_nanos_now(),
7697 Some(control),
7698 )
7699 }
7700
7701 #[doc(hidden)]
7702 pub fn query_at_with_allowed_after(
7703 &mut self,
7704 q: &crate::query::Query,
7705 snapshot: Snapshot,
7706 allowed: Option<&std::collections::HashSet<RowId>>,
7707 after_row_id: Option<RowId>,
7708 ) -> Result<Vec<Row>> {
7709 self.query_at_with_allowed_after_at_time(
7710 q,
7711 snapshot,
7712 allowed,
7713 after_row_id,
7714 unix_nanos_now(),
7715 )
7716 }
7717
7718 #[doc(hidden)]
7719 pub fn query_at_with_allowed_after_at_time(
7720 &mut self,
7721 q: &crate::query::Query,
7722 snapshot: Snapshot,
7723 allowed: Option<&std::collections::HashSet<RowId>>,
7724 after_row_id: Option<RowId>,
7725 query_time_nanos: i64,
7726 ) -> Result<Vec<Row>> {
7727 self.require_select()?;
7728 self.ensure_indexes_complete()?;
7729 self.validate_native_query(q)?;
7730 self.query_conditions_at(
7731 &q.conditions,
7732 snapshot,
7733 allowed,
7734 q.limit,
7735 q.offset,
7736 after_row_id,
7737 query_time_nanos,
7738 None,
7739 )
7740 }
7741
7742 fn validate_native_query(&self, q: &crate::query::Query) -> Result<()> {
7743 if q.conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7744 return Err(MongrelError::InvalidArgument(format!(
7745 "query exceeds {} conditions",
7746 crate::query::MAX_HARD_CONDITIONS
7747 )));
7748 }
7749 if let Some(limit) = q.limit {
7750 if limit == 0 || limit > crate::query::MAX_FINAL_LIMIT {
7751 return Err(MongrelError::InvalidArgument(format!(
7752 "query limit must be between 1 and {}",
7753 crate::query::MAX_FINAL_LIMIT
7754 )));
7755 }
7756 }
7757 if q.offset > crate::query::MAX_QUERY_OFFSET {
7758 return Err(MongrelError::InvalidArgument(format!(
7759 "query offset exceeds {}",
7760 crate::query::MAX_QUERY_OFFSET
7761 )));
7762 }
7763 Ok(())
7764 }
7765
7766 #[doc(hidden)]
7769 pub fn query_all_at(
7770 &mut self,
7771 conditions: &[crate::query::Condition],
7772 snapshot: Snapshot,
7773 ) -> Result<Vec<Row>> {
7774 self.require_select()?;
7775 self.ensure_indexes_complete()?;
7776 if conditions.len() > crate::query::MAX_HARD_CONDITIONS {
7777 return Err(MongrelError::InvalidArgument(format!(
7778 "query exceeds {} conditions",
7779 crate::query::MAX_HARD_CONDITIONS
7780 )));
7781 }
7782 self.query_conditions_at(
7783 conditions,
7784 snapshot,
7785 None,
7786 None,
7787 0,
7788 None,
7789 unix_nanos_now(),
7790 None,
7791 )
7792 }
7793
7794 #[allow(clippy::too_many_arguments)]
7795 fn query_conditions_at(
7796 &self,
7797 conditions: &[crate::query::Condition],
7798 snapshot: Snapshot,
7799 allowed: Option<&std::collections::HashSet<RowId>>,
7800 limit: Option<usize>,
7801 offset: usize,
7802 after_row_id: Option<RowId>,
7803 query_time_nanos: i64,
7804 control: Option<&crate::ExecutionControl>,
7805 ) -> Result<Vec<Row>> {
7806 control
7807 .map(crate::ExecutionControl::checkpoint)
7808 .transpose()?;
7809 crate::trace::QueryTrace::record(|t| {
7810 t.run_count = self.run_refs.len();
7811 t.memtable_rows = self.memtable.len();
7812 t.mutable_run_rows = self.mutable_run.len();
7813 });
7814 if conditions.is_empty() {
7818 crate::trace::QueryTrace::record(|t| {
7819 t.scan_mode = crate::trace::ScanMode::Materialized;
7820 t.row_materialized = true;
7821 });
7822 let mut rows = match control {
7823 Some(control) => self.visible_rows_controlled(snapshot, control)?,
7824 None => self.visible_rows_at_time(snapshot, query_time_nanos)?,
7825 };
7826 if let Some(allowed) = allowed {
7827 let mut filtered = Vec::with_capacity(rows.len());
7828 for (index, row) in rows.into_iter().enumerate() {
7829 if index & 255 == 0 {
7830 control
7831 .map(crate::ExecutionControl::checkpoint)
7832 .transpose()?;
7833 }
7834 if allowed.contains(&row.row_id) {
7835 filtered.push(row);
7836 }
7837 }
7838 rows = filtered;
7839 }
7840 if let Some(after_row_id) = after_row_id {
7841 rows.retain(|row| row.row_id > after_row_id);
7842 }
7843 rows.drain(..offset.min(rows.len()));
7844 if let Some(limit) = limit {
7845 rows.truncate(limit);
7846 }
7847 return Ok(rows);
7848 }
7849 crate::trace::QueryTrace::record(|t| {
7850 t.conditions_pushed = conditions.len();
7851 t.scan_mode = crate::trace::ScanMode::Materialized;
7852 t.row_materialized = true;
7853 });
7854 let mut ordered: Vec<&crate::query::Condition> = conditions.iter().collect();
7861 ordered.sort_by_key(|c| condition_cost_rank(c));
7862 let mut sets: Vec<RowIdSet> = Vec::with_capacity(ordered.len());
7863 for c in &ordered {
7864 control
7865 .map(crate::ExecutionControl::checkpoint)
7866 .transpose()?;
7867 let s = self.resolve_condition_with_allowed(c, snapshot, allowed)?;
7868 let empty = s.is_empty();
7869 sets.push(s);
7870 if empty {
7871 break;
7872 }
7873 }
7874 let mut rids = RowIdSet::intersect_many(sets).into_sorted_vec();
7875 if let Some(allowed) = allowed {
7876 rids.retain(|row_id| allowed.contains(&RowId(*row_id)));
7877 }
7878 if let Some(after_row_id) = after_row_id {
7879 let first = rids.partition_point(|row_id| *row_id <= after_row_id.0);
7880 rids.drain(..first);
7881 }
7882 rids.drain(..offset.min(rids.len()));
7883 if let Some(limit) = limit {
7884 rids.truncate(limit);
7885 }
7886 control
7887 .map(crate::ExecutionControl::checkpoint)
7888 .transpose()?;
7889 self.rows_for_rids_at_time(&rids, snapshot, query_time_nanos, control)
7890 }
7891
7892 pub fn retrieve(
7894 &mut self,
7895 retriever: &crate::query::Retriever,
7896 ) -> Result<Vec<crate::query::RetrieverHit>> {
7897 self.retrieve_with_allowed(retriever, None)
7898 }
7899
7900 pub fn retrieve_at(
7901 &mut self,
7902 retriever: &crate::query::Retriever,
7903 snapshot: Snapshot,
7904 allowed: Option<&std::collections::HashSet<RowId>>,
7905 ) -> Result<Vec<crate::query::RetrieverHit>> {
7906 self.retrieve_at_with_allowed(retriever, snapshot, allowed)
7907 }
7908
7909 pub fn retrieve_with_allowed(
7912 &mut self,
7913 retriever: &crate::query::Retriever,
7914 allowed: Option<&std::collections::HashSet<RowId>>,
7915 ) -> Result<Vec<crate::query::RetrieverHit>> {
7916 self.retrieve_at_with_allowed(retriever, self.snapshot(), allowed)
7917 }
7918
7919 pub fn retrieve_at_with_allowed(
7920 &mut self,
7921 retriever: &crate::query::Retriever,
7922 snapshot: Snapshot,
7923 allowed: Option<&std::collections::HashSet<RowId>>,
7924 ) -> Result<Vec<crate::query::RetrieverHit>> {
7925 self.retrieve_at_with_allowed_and_context(retriever, snapshot, allowed, None)
7926 }
7927
7928 pub fn retrieve_at_with_allowed_and_context(
7929 &mut self,
7930 retriever: &crate::query::Retriever,
7931 snapshot: Snapshot,
7932 allowed: Option<&std::collections::HashSet<RowId>>,
7933 context: Option<&crate::query::AiExecutionContext>,
7934 ) -> Result<Vec<crate::query::RetrieverHit>> {
7935 self.require_select()?;
7936 self.ensure_indexes_complete()?;
7937 self.validate_retriever(retriever)?;
7938 self.retrieve_filtered(retriever, snapshot, None, allowed, None, context)
7939 }
7940
7941 pub fn retrieve_at_with_candidate_authorization_and_context(
7942 &mut self,
7943 retriever: &crate::query::Retriever,
7944 snapshot: Snapshot,
7945 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
7946 context: Option<&crate::query::AiExecutionContext>,
7947 ) -> Result<Vec<crate::query::RetrieverHit>> {
7948 self.require_select()?;
7949 self.ensure_indexes_complete()?;
7950 self.retrieve_at_with_candidate_authorization_on_generation(
7951 retriever,
7952 snapshot,
7953 authorization,
7954 context,
7955 )
7956 }
7957
7958 #[doc(hidden)]
7959 pub fn retrieve_at_with_candidate_authorization_on_generation(
7960 &self,
7961 retriever: &crate::query::Retriever,
7962 snapshot: Snapshot,
7963 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
7964 context: Option<&crate::query::AiExecutionContext>,
7965 ) -> Result<Vec<crate::query::RetrieverHit>> {
7966 self.require_select()?;
7967 self.validate_retriever(retriever)?;
7968 self.retrieve_filtered(retriever, snapshot, None, None, authorization, context)
7969 }
7970
7971 fn validate_retriever(&self, retriever: &crate::query::Retriever) -> Result<()> {
7972 use crate::query::{Retriever, MAX_RETRIEVER_K, MAX_SET_MEMBERS, MAX_SPARSE_TERMS};
7973 let (column_id, k) = match retriever {
7974 Retriever::Ann {
7975 column_id,
7976 query,
7977 k,
7978 } => {
7979 let index = self.ann.get(column_id).ok_or_else(|| {
7980 MongrelError::InvalidArgument(format!("column {column_id} has no ANN index"))
7981 })?;
7982 if query.len() != index.dim() {
7983 return Err(MongrelError::InvalidArgument(format!(
7984 "ANN query dimension must be {}, got {}",
7985 index.dim(),
7986 query.len()
7987 )));
7988 }
7989 if query.iter().any(|value| !value.is_finite()) {
7990 return Err(MongrelError::InvalidArgument(
7991 "ANN query values must be finite".into(),
7992 ));
7993 }
7994 (*column_id, *k)
7995 }
7996 Retriever::Sparse {
7997 column_id,
7998 query,
7999 k,
8000 } => {
8001 if !self.sparse.contains_key(column_id) {
8002 return Err(MongrelError::InvalidArgument(format!(
8003 "column {column_id} has no Sparse index"
8004 )));
8005 }
8006 if query.is_empty() || query.iter().any(|(_, weight)| !weight.is_finite()) {
8007 return Err(MongrelError::InvalidArgument(
8008 "Sparse query must be non-empty with finite weights".into(),
8009 ));
8010 }
8011 if query.len() > MAX_SPARSE_TERMS {
8012 return Err(MongrelError::InvalidArgument(format!(
8013 "Sparse query exceeds {MAX_SPARSE_TERMS} terms"
8014 )));
8015 }
8016 (*column_id, *k)
8017 }
8018 Retriever::MinHash {
8019 column_id,
8020 members,
8021 k,
8022 } => {
8023 if !self.minhash.contains_key(column_id) {
8024 return Err(MongrelError::InvalidArgument(format!(
8025 "column {column_id} has no MinHash index"
8026 )));
8027 }
8028 if members.is_empty() {
8029 return Err(MongrelError::InvalidArgument(
8030 "MinHash members must not be empty".into(),
8031 ));
8032 }
8033 if members.len() > MAX_SET_MEMBERS {
8034 return Err(MongrelError::InvalidArgument(format!(
8035 "MinHash query exceeds {MAX_SET_MEMBERS} members"
8036 )));
8037 }
8038 let mut total_bytes = 0usize;
8039 for member in members {
8040 let bytes = member.encoded_len();
8041 if bytes > crate::query::MAX_SET_MEMBER_BYTES {
8042 return Err(MongrelError::InvalidArgument(format!(
8043 "MinHash member exceeds {} bytes",
8044 crate::query::MAX_SET_MEMBER_BYTES
8045 )));
8046 }
8047 total_bytes = total_bytes.checked_add(bytes).ok_or_else(|| {
8048 MongrelError::InvalidArgument("MinHash input size overflow".into())
8049 })?;
8050 }
8051 if total_bytes > crate::query::MAX_SET_INPUT_BYTES {
8052 return Err(MongrelError::InvalidArgument(format!(
8053 "MinHash input exceeds {} bytes",
8054 crate::query::MAX_SET_INPUT_BYTES
8055 )));
8056 }
8057 (*column_id, *k)
8058 }
8059 };
8060 if k == 0 {
8061 return Err(MongrelError::InvalidArgument(
8062 "retriever k must be > 0".into(),
8063 ));
8064 }
8065 if k > MAX_RETRIEVER_K {
8066 return Err(MongrelError::InvalidArgument(format!(
8067 "retriever k exceeds {MAX_RETRIEVER_K}"
8068 )));
8069 }
8070 debug_assert!(self
8071 .schema
8072 .columns
8073 .iter()
8074 .any(|column| column.id == column_id));
8075 Ok(())
8076 }
8077
8078 fn validate_condition(&self, condition: &crate::query::Condition) -> Result<()> {
8079 use crate::query::Condition;
8080 match condition {
8081 Condition::Ann {
8082 column_id,
8083 query,
8084 k,
8085 } => self.validate_retriever(&crate::query::Retriever::Ann {
8086 column_id: *column_id,
8087 query: query.clone(),
8088 k: *k,
8089 }),
8090 Condition::SparseMatch {
8091 column_id,
8092 query,
8093 k,
8094 } => self.validate_retriever(&crate::query::Retriever::Sparse {
8095 column_id: *column_id,
8096 query: query.clone(),
8097 k: *k,
8098 }),
8099 Condition::MinHashSimilar {
8100 column_id,
8101 query,
8102 k,
8103 } => {
8104 if !self.minhash.contains_key(column_id) {
8105 return Err(MongrelError::InvalidArgument(format!(
8106 "column {column_id} has no MinHash index"
8107 )));
8108 }
8109 if query.is_empty() || *k == 0 {
8110 return Err(MongrelError::InvalidArgument(
8111 "MinHash query must be non-empty and k must be > 0".into(),
8112 ));
8113 }
8114 if query.len() > crate::query::MAX_SET_MEMBERS || *k > crate::query::MAX_RETRIEVER_K
8115 {
8116 return Err(MongrelError::InvalidArgument(format!(
8117 "MinHash query must have <= {} members and k <= {}",
8118 crate::query::MAX_SET_MEMBERS,
8119 crate::query::MAX_RETRIEVER_K
8120 )));
8121 }
8122 Ok(())
8123 }
8124 Condition::BitmapIn { values, .. } if values.len() > crate::query::MAX_SET_MEMBERS => {
8125 Err(MongrelError::InvalidArgument(format!(
8126 "bitmap IN exceeds {} values",
8127 crate::query::MAX_SET_MEMBERS
8128 )))
8129 }
8130 Condition::FmContainsAll { patterns, .. }
8131 if patterns.len() > crate::query::MAX_HARD_CONDITIONS =>
8132 {
8133 Err(MongrelError::InvalidArgument(format!(
8134 "FM query exceeds {} patterns",
8135 crate::query::MAX_HARD_CONDITIONS
8136 )))
8137 }
8138 _ => Ok(()),
8139 }
8140 }
8141
8142 fn retrieve_filtered(
8143 &self,
8144 retriever: &crate::query::Retriever,
8145 snapshot: Snapshot,
8146 hard_filter: Option<&RowIdSet>,
8147 allowed: Option<&std::collections::HashSet<RowId>>,
8148 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8149 context: Option<&crate::query::AiExecutionContext>,
8150 ) -> Result<Vec<crate::query::RetrieverHit>> {
8151 use crate::query::{Retriever, RetrieverHit, RetrieverScore};
8152 let started = std::time::Instant::now();
8153 let scored: Vec<(RowId, RetrieverScore)> = match retriever {
8154 Retriever::Ann {
8155 column_id,
8156 query,
8157 k,
8158 } => {
8159 let Some(index) = self.ann.get(column_id) else {
8160 return Ok(Vec::new());
8161 };
8162 let cap = ann_candidate_cap(index.len(), context);
8163 crate::trace::QueryTrace::record(|trace| trace.candidate_cap = cap);
8164 if cap == 0 {
8165 return Ok(Vec::new());
8166 }
8167 let mut breadth = (*k).max(1).min(cap);
8168 let mut eligibility = std::collections::HashMap::new();
8169 let mut raw_candidates_total: usize = 0;
8174 let mut visibility_rejected_total: usize = 0;
8175 let mut authorization_rejected_total: usize = 0;
8176 let mut candidate_cap_hit_final = false;
8177 let mut filtered = loop {
8178 let mut seen = std::collections::HashSet::new();
8179 if let Some(context) = context {
8180 context.checkpoint()?;
8181 }
8182 let raw = index.search_with_context(query, breadth, context)?;
8183 crate::trace::QueryTrace::record(|trace| {
8184 trace.raw_candidates = raw.len();
8185 let unique = raw
8186 .iter()
8187 .map(|(row_id, _)| *row_id)
8188 .collect::<std::collections::HashSet<_>>()
8189 .len();
8190 trace.unique_candidates = unique;
8191 trace.duplicate_candidates = raw.len().saturating_sub(unique);
8192 trace.authorization_rejected = raw
8193 .iter()
8194 .filter(|(row_id, _)| {
8195 allowed.is_some_and(|allowed| !allowed.contains(row_id))
8196 })
8197 .count();
8198 trace.hard_filter_rejected = raw
8199 .iter()
8200 .filter(|(row_id, _)| {
8201 hard_filter.is_some_and(|filter| !filter.contains(row_id.0))
8202 })
8203 .count();
8204 });
8205 raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8206 let unchecked: Vec<_> = raw
8207 .iter()
8208 .map(|(row_id, _)| *row_id)
8209 .filter(|row_id| !eligibility.contains_key(row_id))
8210 .filter(|row_id| {
8211 hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8212 && allowed.is_none_or(|allowed| allowed.contains(row_id))
8213 })
8214 .collect();
8215 let eligible = self.eligible_and_authorized_candidate_ids(
8216 &unchecked,
8217 *column_id,
8218 snapshot,
8219 candidate_authorization,
8220 context,
8221 )?;
8222 for row_id in &unchecked {
8223 eligibility.insert(*row_id, eligible.contains(row_id));
8224 }
8225 let new_visibility_or_auth_rejected = unchecked
8228 .iter()
8229 .filter(|row_id| !eligible.contains(row_id))
8230 .count();
8231 let mut new_auth_rejected = 0usize;
8236 if let Some(authorization) = candidate_authorization {
8237 if authorization.security.rls_enabled(authorization.table)
8238 && !authorization.principal.is_admin
8239 {
8240 new_auth_rejected = new_visibility_or_auth_rejected;
8246 }
8247 }
8248 let new_visibility_rejected =
8249 new_visibility_or_auth_rejected.saturating_sub(new_auth_rejected);
8250 visibility_rejected_total =
8251 visibility_rejected_total.saturating_add(new_visibility_rejected);
8252 authorization_rejected_total =
8253 authorization_rejected_total.saturating_add(new_auth_rejected);
8254 let filtered: Vec<_> = raw
8255 .into_iter()
8256 .filter(|(row_id, _)| {
8257 seen.insert(*row_id)
8258 && eligibility.get(row_id).copied().unwrap_or(false)
8259 })
8260 .map(|(row_id, score)| {
8261 let score = match score {
8262 crate::index::AnnDistance::Hamming(d) => {
8263 RetrieverScore::AnnHammingDistance(d)
8264 }
8265 crate::index::AnnDistance::Cosine(d) => {
8266 RetrieverScore::AnnCosineDistance(d)
8267 }
8268 };
8269 (row_id, score)
8270 })
8271 .collect();
8272 if filtered.len() >= *k || breadth >= cap {
8273 if filtered.len() < *k && index.len() > cap && breadth >= cap {
8274 crate::trace::QueryTrace::record(|trace| {
8275 trace.ann_candidate_cap_hit = true;
8276 trace.candidate_cap_hit = true;
8277 });
8278 candidate_cap_hit_final = true;
8279 }
8280 break filtered;
8281 }
8282 breadth = breadth.saturating_mul(2).min(cap);
8283 };
8284 let final_hits = filtered.len();
8287 let index_len = index.len();
8288 crate::trace::QueryTrace::record(|trace| {
8289 trace.candidate_cap = cap;
8290 trace.candidate_cap_hit = candidate_cap_hit_final;
8291 trace.ann_candidate_cap_hit = candidate_cap_hit_final;
8292 trace.raw_candidates =
8293 trace.raw_candidates.saturating_add(raw_candidates_total);
8294 trace.visibility_rejected = trace
8295 .visibility_rejected
8296 .saturating_add(visibility_rejected_total);
8297 trace.authorization_rejected = trace
8298 .authorization_rejected
8299 .saturating_add(authorization_rejected_total);
8300 trace.final_hits = trace.final_hits.saturating_add(final_hits);
8301 let _ = index_len;
8304 });
8305 filtered.truncate(*k);
8306 filtered
8307 }
8308 Retriever::Sparse {
8309 column_id,
8310 query,
8311 k,
8312 } => self
8313 .sparse
8314 .get(column_id)
8315 .map(|index| -> Result<Vec<_>> {
8316 let mut breadth = (*k).max(1);
8317 let mut eligibility = std::collections::HashMap::new();
8318 let mut raw_candidates_total: usize = 0;
8321 let mut visibility_rejected_total: usize = 0;
8322 let mut authorization_rejected_total: usize = 0;
8323 let filtered = loop {
8324 if let Some(context) = context {
8325 context.checkpoint()?;
8326 }
8327 let raw = index.search_with_context(query, breadth, context)?;
8328 raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8329 authorization_rejected_total = authorization_rejected_total.saturating_add(
8330 raw.iter()
8331 .filter(|(row_id, _)| {
8332 allowed.is_some_and(|allowed| !allowed.contains(row_id))
8333 })
8334 .count(),
8335 );
8336 let unchecked: Vec<_> = raw
8337 .iter()
8338 .map(|(row_id, _)| *row_id)
8339 .filter(|row_id| !eligibility.contains_key(row_id))
8340 .filter(|row_id| {
8341 hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8342 && allowed.is_none_or(|allowed| allowed.contains(row_id))
8343 })
8344 .collect();
8345 let eligible = self.eligible_and_authorized_candidate_ids(
8346 &unchecked,
8347 *column_id,
8348 snapshot,
8349 candidate_authorization,
8350 context,
8351 )?;
8352 visibility_rejected_total = visibility_rejected_total.saturating_add(
8353 unchecked
8354 .iter()
8355 .filter(|row_id| !eligible.contains(row_id))
8356 .count(),
8357 );
8358 for row_id in unchecked {
8359 eligibility.insert(row_id, eligible.contains(&row_id));
8360 }
8361 let filtered: Vec<_> = raw
8362 .iter()
8363 .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8364 .take(*k)
8365 .map(|(row_id, score)| {
8366 (*row_id, RetrieverScore::SparseDotProduct(*score))
8367 })
8368 .collect();
8369 if filtered.len() >= *k || raw.len() < breadth {
8370 break filtered;
8371 }
8372 let next = breadth.saturating_mul(2);
8373 if next == breadth {
8374 break filtered;
8375 }
8376 breadth = next;
8377 };
8378 crate::trace::QueryTrace::record(|trace| {
8379 trace.raw_candidates =
8380 trace.raw_candidates.saturating_add(raw_candidates_total);
8381 trace.visibility_rejected = trace
8382 .visibility_rejected
8383 .saturating_add(visibility_rejected_total);
8384 trace.authorization_rejected = trace
8385 .authorization_rejected
8386 .saturating_add(authorization_rejected_total);
8387 });
8388 Ok(filtered)
8389 })
8390 .transpose()?
8391 .unwrap_or_default(),
8392 Retriever::MinHash {
8393 column_id,
8394 members,
8395 k,
8396 } => self
8397 .minhash
8398 .get(column_id)
8399 .map(|index| -> Result<Vec<_>> {
8400 let mut hashes = Vec::with_capacity(members.len());
8401 for member in members {
8402 if let Some(context) = context {
8403 context.consume(crate::query::work_units(
8404 member.encoded_len(),
8405 crate::query::PARSE_WORK_QUANTUM,
8406 ))?;
8407 }
8408 hashes.push(member.hash_v1());
8409 }
8410 let mut breadth = (*k).max(1);
8411 let mut eligibility = std::collections::HashMap::new();
8412 let mut raw_candidates_total: usize = 0;
8413 let mut visibility_rejected_total: usize = 0;
8414 let mut authorization_rejected_total: usize = 0;
8415 let filtered = loop {
8416 if let Some(context) = context {
8417 context.checkpoint()?;
8418 }
8419 let raw = index.search_with_context(&hashes, breadth, context)?;
8420 raw_candidates_total = raw_candidates_total.saturating_add(raw.len());
8421 authorization_rejected_total = authorization_rejected_total.saturating_add(
8422 raw.iter()
8423 .filter(|(row_id, _)| {
8424 allowed.is_some_and(|allowed| !allowed.contains(row_id))
8425 })
8426 .count(),
8427 );
8428 let unchecked: Vec<_> = raw
8429 .iter()
8430 .map(|(row_id, _)| *row_id)
8431 .filter(|row_id| !eligibility.contains_key(row_id))
8432 .filter(|row_id| {
8433 hard_filter.is_none_or(|filter| filter.contains(row_id.0))
8434 && allowed.is_none_or(|allowed| allowed.contains(row_id))
8435 })
8436 .collect();
8437 let eligible = self.eligible_and_authorized_candidate_ids(
8438 &unchecked,
8439 *column_id,
8440 snapshot,
8441 candidate_authorization,
8442 context,
8443 )?;
8444 visibility_rejected_total = visibility_rejected_total.saturating_add(
8445 unchecked
8446 .iter()
8447 .filter(|row_id| !eligible.contains(row_id))
8448 .count(),
8449 );
8450 for row_id in unchecked {
8451 eligibility.insert(row_id, eligible.contains(&row_id));
8452 }
8453 let filtered: Vec<_> = raw
8454 .iter()
8455 .filter(|(row_id, _)| eligibility.get(row_id).copied().unwrap_or(false))
8456 .take(*k)
8457 .map(|(row_id, score)| {
8458 (*row_id, RetrieverScore::MinHashEstimatedJaccard(*score))
8459 })
8460 .collect();
8461 if filtered.len() >= *k || raw.len() < breadth {
8462 break filtered;
8463 }
8464 let next = breadth.saturating_mul(2);
8465 if next == breadth {
8466 break filtered;
8467 }
8468 breadth = next;
8469 };
8470 crate::trace::QueryTrace::record(|trace| {
8471 trace.raw_candidates =
8472 trace.raw_candidates.saturating_add(raw_candidates_total);
8473 trace.visibility_rejected = trace
8474 .visibility_rejected
8475 .saturating_add(visibility_rejected_total);
8476 trace.authorization_rejected = trace
8477 .authorization_rejected
8478 .saturating_add(authorization_rejected_total);
8479 });
8480 Ok(filtered)
8481 })
8482 .transpose()?
8483 .unwrap_or_default(),
8484 };
8485 let requested_k = match retriever {
8486 Retriever::Ann { k, .. }
8487 | Retriever::Sparse { k, .. }
8488 | Retriever::MinHash { k, .. } => *k,
8489 };
8490 crate::trace::QueryTrace::record(|trace| {
8491 trace.final_hits = scored.len();
8492 if scored.len() < requested_k {
8493 trace.underfill_reason = Some(if trace.candidate_cap_hit {
8494 "candidate_cap"
8495 } else {
8496 "eligible_candidates_exhausted"
8497 });
8498 }
8499 });
8500 let elapsed = started.elapsed().as_nanos() as u64;
8501 crate::trace::QueryTrace::record(|trace| {
8502 match retriever {
8503 Retriever::Ann { .. } => {
8504 trace.ann_candidate_nanos = trace.ann_candidate_nanos.saturating_add(elapsed);
8505 if let Retriever::Ann { column_id, .. } = retriever {
8506 if let Some(index) = self.ann.get(column_id) {
8507 trace.ann_algorithm = Some(index.algorithm());
8508 trace.ann_quantization = Some(index.quantization());
8509 trace.ann_backend = Some(index.backend_name());
8510 }
8511 }
8512 }
8513 Retriever::Sparse { .. } => {
8514 trace.sparse_candidate_nanos =
8515 trace.sparse_candidate_nanos.saturating_add(elapsed)
8516 }
8517 Retriever::MinHash { .. } => {
8518 trace.minhash_candidate_nanos =
8519 trace.minhash_candidate_nanos.saturating_add(elapsed)
8520 }
8521 }
8522 trace.candidate_count = trace.candidate_count.saturating_add(scored.len());
8523 });
8524 Ok(scored
8525 .into_iter()
8526 .enumerate()
8527 .map(|(rank, (row_id, score))| RetrieverHit {
8528 row_id,
8529 rank: rank + 1,
8530 score,
8531 })
8532 .collect())
8533 }
8534
8535 fn eligible_candidate_ids(
8536 &self,
8537 candidates: &[RowId],
8538 _column_id: u16,
8539 snapshot: Snapshot,
8540 context: Option<&crate::query::AiExecutionContext>,
8541 ) -> Result<std::collections::HashSet<RowId>> {
8542 let lookup_snapshot = snapshot;
8554 let mut readers: Vec<_> = self
8555 .run_refs
8556 .iter()
8557 .map(|run| self.open_reader(run.run_id))
8558 .collect::<Result<_>>()?;
8559 let now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8560 let mut eligible = std::collections::HashSet::with_capacity(candidates.len());
8561 for &row_id in candidates {
8562 if let Some(context) = context {
8563 context.consume(1)?;
8564 }
8565 let mem = self.memtable.get_version_at(row_id, lookup_snapshot);
8566 let mutable = self.mutable_run.get_version_at(row_id, lookup_snapshot);
8567 let overlay = match (mem, mutable) {
8568 (Some(left), Some(right)) => Some(
8569 if Snapshot::version_is_newer(
8570 left.1.committed_epoch,
8571 left.1.commit_ts,
8572 right.1.committed_epoch,
8573 right.1.commit_ts,
8574 ) {
8575 left
8576 } else {
8577 right
8578 },
8579 ),
8580 (Some(value), None) | (None, Some(value)) => Some(value),
8581 (None, None) => None,
8582 };
8583 if let Some((_, row)) = overlay {
8584 if !row.deleted && !self.row_expired_at(&row, now) {
8585 eligible.insert(row_id);
8586 }
8587 continue;
8588 }
8589 let mut best: Option<(crate::sorted_run::VersionVisibility, usize)> = None;
8595 for (index, reader) in readers.iter_mut().enumerate() {
8596 if let Some(visibility) =
8597 reader.get_version_visibility_full_at(row_id, lookup_snapshot)?
8598 {
8599 if best
8600 .as_ref()
8601 .map(|(current, _)| visibility.stamp.is_newer_than(current.stamp))
8602 .unwrap_or(true)
8603 {
8604 best = Some((visibility, index));
8605 }
8606 }
8607 }
8608 let Some((visibility, reader_index)) = best else {
8609 continue;
8610 };
8611 if visibility.deleted {
8612 continue;
8613 }
8614 if let Some(ttl) = self.ttl {
8615 if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
8616 row_id,
8617 lookup_snapshot,
8618 ttl.column_id,
8619 )? {
8620 if let Some(Value::Int64(timestamp)) = ttl_value.value {
8621 if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
8622 continue;
8623 }
8624 }
8625 }
8626 }
8627 eligible.insert(row_id);
8628 }
8629 Ok(eligible)
8630 }
8631
8632 fn eligible_and_authorized_candidate_ids(
8633 &self,
8634 candidates: &[RowId],
8635 column_id: u16,
8636 snapshot: Snapshot,
8637 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8638 context: Option<&crate::query::AiExecutionContext>,
8639 ) -> Result<std::collections::HashSet<RowId>> {
8640 let eligible = self.eligible_candidate_ids(candidates, column_id, snapshot, context)?;
8641 let Some(authorization) = authorization else {
8642 return Ok(eligible);
8643 };
8644 let candidates: Vec<_> = eligible.into_iter().collect();
8645 self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, context)
8646 }
8647
8648 fn policy_allowed_candidate_ids(
8649 &self,
8650 candidates: &[RowId],
8651 snapshot: Snapshot,
8652 authorization: &crate::security::CandidateAuthorization<'_>,
8653 context: Option<&crate::query::AiExecutionContext>,
8654 ) -> Result<std::collections::HashSet<RowId>> {
8655 let started = std::time::Instant::now();
8656 if candidates.is_empty()
8657 || authorization.principal.is_admin
8658 || !authorization.security.rls_enabled(authorization.table)
8659 {
8660 return Ok(candidates.iter().copied().collect());
8661 }
8662 if let Some(context) = context {
8663 context.checkpoint()?;
8664 }
8665 let row_ids: Vec<_> = candidates.iter().map(|row_id| row_id.0).collect();
8666 let mut rows: std::collections::HashMap<RowId, Row> = candidates
8667 .iter()
8668 .map(|row_id| {
8669 (
8670 *row_id,
8671 Row {
8672 row_id: *row_id,
8673 committed_epoch: snapshot.epoch,
8674 columns: std::collections::HashMap::new(),
8675 deleted: false,
8676 commit_ts: None,
8677 },
8678 )
8679 })
8680 .collect();
8681 let columns = authorization
8682 .security
8683 .select_policy_columns(authorization.table, authorization.principal);
8684 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
8685 let mut decoded = 0usize;
8686 for column_id in &columns {
8687 if let Some(context) = context {
8688 context.checkpoint()?;
8689 }
8690 for (row_id, value) in self.values_for_rids_batch_at_with_context(
8691 &row_ids, *column_id, snapshot, query_now, context,
8692 )? {
8693 if let Some(row) = rows.get_mut(&row_id) {
8694 row.columns.insert(*column_id, value);
8695 decoded = decoded.saturating_add(1);
8696 }
8697 }
8698 }
8699 if let Some(context) = context {
8700 context.consume(candidates.len().saturating_add(decoded))?;
8701 }
8702 let allowed = rows
8703 .into_values()
8704 .filter_map(|row| {
8705 authorization
8706 .security
8707 .row_allowed(
8708 authorization.table,
8709 crate::security::PolicyCommand::Select,
8710 &row,
8711 authorization.principal,
8712 false,
8713 )
8714 .then_some(row.row_id)
8715 })
8716 .collect();
8717 crate::trace::QueryTrace::record(|trace| {
8718 trace.rls_rows_evaluated = trace.rls_rows_evaluated.saturating_add(candidates.len());
8719 trace.rls_policy_columns_decoded =
8720 trace.rls_policy_columns_decoded.saturating_add(decoded);
8721 trace.authorization_nanos = trace
8722 .authorization_nanos
8723 .saturating_add(started.elapsed().as_nanos() as u64);
8724 });
8725 Ok(allowed)
8726 }
8727
8728 pub fn search(
8730 &mut self,
8731 request: &crate::query::SearchRequest,
8732 ) -> Result<Vec<crate::query::SearchHit>> {
8733 self.search_with_allowed(request, None)
8734 }
8735
8736 pub fn search_at(
8737 &mut self,
8738 request: &crate::query::SearchRequest,
8739 snapshot: Snapshot,
8740 authorized: Option<&std::collections::HashSet<RowId>>,
8741 ) -> Result<Vec<crate::query::SearchHit>> {
8742 self.search_at_with_allowed(request, snapshot, authorized)
8743 }
8744
8745 pub fn search_with_allowed(
8746 &mut self,
8747 request: &crate::query::SearchRequest,
8748 authorized: Option<&std::collections::HashSet<RowId>>,
8749 ) -> Result<Vec<crate::query::SearchHit>> {
8750 self.search_at_with_allowed(request, self.snapshot(), authorized)
8751 }
8752
8753 pub fn search_at_with_allowed(
8754 &mut self,
8755 request: &crate::query::SearchRequest,
8756 snapshot: Snapshot,
8757 authorized: Option<&std::collections::HashSet<RowId>>,
8758 ) -> Result<Vec<crate::query::SearchHit>> {
8759 self.search_at_with_allowed_and_context(request, snapshot, authorized, None)
8760 }
8761
8762 pub fn search_at_with_allowed_and_context(
8763 &mut self,
8764 request: &crate::query::SearchRequest,
8765 snapshot: Snapshot,
8766 authorized: Option<&std::collections::HashSet<RowId>>,
8767 context: Option<&crate::query::AiExecutionContext>,
8768 ) -> Result<Vec<crate::query::SearchHit>> {
8769 self.ensure_indexes_complete()?;
8770 self.search_at_with_filters_and_context(request, snapshot, authorized, None, context, None)
8771 }
8772
8773 pub fn search_at_with_candidate_authorization_and_context(
8774 &mut self,
8775 request: &crate::query::SearchRequest,
8776 snapshot: Snapshot,
8777 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8778 context: Option<&crate::query::AiExecutionContext>,
8779 ) -> Result<Vec<crate::query::SearchHit>> {
8780 self.ensure_indexes_complete()?;
8781 self.search_at_with_filters_and_context(
8782 request,
8783 snapshot,
8784 None,
8785 authorization,
8786 context,
8787 None,
8788 )
8789 }
8790
8791 #[doc(hidden)]
8792 pub fn search_at_with_candidate_authorization_on_generation(
8793 &self,
8794 request: &crate::query::SearchRequest,
8795 snapshot: Snapshot,
8796 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8797 context: Option<&crate::query::AiExecutionContext>,
8798 ) -> Result<Vec<crate::query::SearchHit>> {
8799 self.search_at_with_filters_and_context(
8800 request,
8801 snapshot,
8802 None,
8803 authorization,
8804 context,
8805 None,
8806 )
8807 }
8808
8809 #[doc(hidden)]
8810 pub fn search_at_with_candidate_authorization_on_generation_after(
8811 &self,
8812 request: &crate::query::SearchRequest,
8813 snapshot: Snapshot,
8814 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8815 context: Option<&crate::query::AiExecutionContext>,
8816 after: Option<crate::query::SearchAfter>,
8817 ) -> Result<Vec<crate::query::SearchHit>> {
8818 self.search_at_with_filters_and_context(
8819 request,
8820 snapshot,
8821 None,
8822 authorization,
8823 context,
8824 after,
8825 )
8826 }
8827
8828 fn search_at_with_filters_and_context(
8829 &self,
8830 request: &crate::query::SearchRequest,
8831 snapshot: Snapshot,
8832 authorized: Option<&std::collections::HashSet<RowId>>,
8833 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
8834 context: Option<&crate::query::AiExecutionContext>,
8835 after: Option<crate::query::SearchAfter>,
8836 ) -> Result<Vec<crate::query::SearchHit>> {
8837 use crate::query::{
8838 ComponentScore, Condition, Fusion, SearchHit, MAX_FINAL_LIMIT, MAX_HARD_CONDITIONS,
8839 MAX_PROJECTION_COLUMNS, MAX_RETRIEVERS, MAX_RETRIEVER_WEIGHT,
8840 };
8841 let total_started = std::time::Instant::now();
8842 let rank_offset = after.map_or(0, |after| after.returned_count);
8843 self.require_select()?;
8844 if request.limit == 0 {
8845 return Err(MongrelError::InvalidArgument(
8846 "search limit must be > 0".into(),
8847 ));
8848 }
8849 if request.limit > MAX_FINAL_LIMIT {
8850 return Err(MongrelError::InvalidArgument(format!(
8851 "search limit exceeds {MAX_FINAL_LIMIT}"
8852 )));
8853 }
8854 if after.is_some_and(|cursor| !cursor.final_score.is_finite()) {
8855 return Err(MongrelError::InvalidArgument(
8856 "search-after score must be finite".into(),
8857 ));
8858 }
8859 if request.retrievers.is_empty() {
8860 return Err(MongrelError::InvalidArgument(
8861 "search requires at least one retriever".into(),
8862 ));
8863 }
8864 if request.retrievers.len() > MAX_RETRIEVERS {
8865 return Err(MongrelError::InvalidArgument(format!(
8866 "search exceeds {MAX_RETRIEVERS} retrievers"
8867 )));
8868 }
8869 if request.must.len() > MAX_HARD_CONDITIONS {
8870 return Err(MongrelError::InvalidArgument(format!(
8871 "search exceeds {MAX_HARD_CONDITIONS} hard conditions"
8872 )));
8873 }
8874 for condition in &request.must {
8875 self.validate_condition(condition)?;
8876 }
8877 if request.must.iter().any(|condition| {
8878 matches!(
8879 condition,
8880 Condition::Ann { .. }
8881 | Condition::SparseMatch { .. }
8882 | Condition::MinHashSimilar { .. }
8883 )
8884 }) {
8885 return Err(MongrelError::InvalidArgument(
8886 "ranked ANN, Sparse, and MinHash conditions must be retrievers, not must filters"
8887 .into(),
8888 ));
8889 }
8890 let mut names = std::collections::HashSet::new();
8891 for named in &request.retrievers {
8892 if named.name.is_empty()
8893 || named.name.len() > crate::query::MAX_RETRIEVER_NAME_BYTES
8894 || !names.insert(named.name.as_str())
8895 {
8896 return Err(MongrelError::InvalidArgument(format!(
8897 "retriever names must be non-empty, unique, and at most {} UTF-8 bytes",
8898 crate::query::MAX_RETRIEVER_NAME_BYTES
8899 )));
8900 }
8901 if !named.weight.is_finite()
8902 || named.weight < 0.0
8903 || named.weight > MAX_RETRIEVER_WEIGHT
8904 {
8905 return Err(MongrelError::InvalidArgument(format!(
8906 "retriever weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
8907 )));
8908 }
8909 self.validate_retriever(&named.retriever)?;
8910 }
8911 let projection = request
8912 .projection
8913 .clone()
8914 .unwrap_or_else(|| self.schema.columns.iter().map(|column| column.id).collect());
8915 if projection.len() > MAX_PROJECTION_COLUMNS {
8916 return Err(MongrelError::InvalidArgument(format!(
8917 "projection exceeds {MAX_PROJECTION_COLUMNS} columns"
8918 )));
8919 }
8920 for column_id in &projection {
8921 if !self
8922 .schema
8923 .columns
8924 .iter()
8925 .any(|column| column.id == *column_id)
8926 {
8927 return Err(MongrelError::ColumnNotFound(column_id.to_string()));
8928 }
8929 }
8930 if let Some(crate::query::Rerank::ExactVector {
8931 embedding_column,
8932 query,
8933 candidate_limit,
8934 weight,
8935 ..
8936 }) = &request.rerank
8937 {
8938 if *candidate_limit < request.limit || *candidate_limit > crate::query::MAX_RETRIEVER_K
8939 {
8940 return Err(MongrelError::InvalidArgument(format!(
8941 "rerank candidate_limit must be between search limit and {}",
8942 crate::query::MAX_RETRIEVER_K
8943 )));
8944 }
8945 if !weight.is_finite() || *weight < 0.0 || *weight > MAX_RETRIEVER_WEIGHT {
8946 return Err(MongrelError::InvalidArgument(format!(
8947 "rerank weight must be finite, non-negative, and <= {MAX_RETRIEVER_WEIGHT}"
8948 )));
8949 }
8950 let column = self
8951 .schema
8952 .columns
8953 .iter()
8954 .find(|column| column.id == *embedding_column)
8955 .ok_or_else(|| MongrelError::ColumnNotFound(embedding_column.to_string()))?;
8956 let crate::schema::TypeId::Embedding { dim } = column.ty else {
8957 return Err(MongrelError::InvalidArgument(format!(
8958 "rerank column {embedding_column} is not an embedding"
8959 )));
8960 };
8961 if query.len() != dim as usize || query.iter().any(|value| !value.is_finite()) {
8962 return Err(MongrelError::InvalidArgument(format!(
8963 "rerank query must contain {dim} finite values"
8964 )));
8965 }
8966 }
8967
8968 let hard_filter_started = std::time::Instant::now();
8969 let hard_filter = if request.must.is_empty() {
8970 None
8971 } else {
8972 let mut sets = Vec::with_capacity(request.must.len());
8973 for condition in &request.must {
8974 if let Some(context) = context {
8975 context.checkpoint()?;
8976 }
8977 sets.push(self.resolve_condition(condition, snapshot)?);
8978 }
8979 Some(RowIdSet::intersect_many(sets))
8980 };
8981 crate::trace::QueryTrace::record(|trace| {
8982 trace.hard_filter_nanos = trace
8983 .hard_filter_nanos
8984 .saturating_add(hard_filter_started.elapsed().as_nanos() as u64);
8985 });
8986 if hard_filter.as_ref().is_some_and(RowIdSet::is_empty) {
8987 return Ok(Vec::new());
8988 }
8989
8990 let constant = match request.fusion {
8991 Fusion::ReciprocalRank { constant } => constant,
8992 };
8993 let mut retrievers: Vec<_> = request.retrievers.iter().collect();
8994 retrievers.sort_by(|a, b| a.name.cmp(&b.name));
8995 let mut fusion_nanos = 0u64;
8996 let mut fused: std::collections::HashMap<RowId, (f64, Vec<ComponentScore>)> =
8997 std::collections::HashMap::new();
8998 for named in retrievers {
8999 if named.weight == 0.0 {
9000 continue;
9001 }
9002 if let Some(context) = context {
9003 context.checkpoint()?;
9004 }
9005 let hits = self.retrieve_filtered(
9006 &named.retriever,
9007 snapshot,
9008 hard_filter.as_ref(),
9009 authorized,
9010 candidate_authorization,
9011 context,
9012 )?;
9013 let retriever_name: std::sync::Arc<str> = named.name.as_str().into();
9014 let fusion_started = std::time::Instant::now();
9015 for hit in hits {
9016 if let Some(context) = context {
9017 context.consume(1)?;
9018 }
9019 let contribution = named.weight / (constant as f64 + hit.rank as f64);
9020 if !contribution.is_finite() {
9021 return Err(MongrelError::InvalidArgument(
9022 "retriever contribution must be finite".into(),
9023 ));
9024 }
9025 let max_fused_candidates = context.map_or(
9026 crate::query::MAX_FUSED_CANDIDATES,
9027 crate::query::AiExecutionContext::max_fused_candidates,
9028 );
9029 if !fused.contains_key(&hit.row_id) && fused.len() >= max_fused_candidates {
9030 return Err(MongrelError::WorkBudgetExceeded);
9031 }
9032 let entry = fused.entry(hit.row_id).or_default();
9033 entry.0 += contribution;
9034 if !entry.0.is_finite() {
9035 return Err(MongrelError::InvalidArgument(
9036 "fused score must be finite".into(),
9037 ));
9038 }
9039 entry.1.push(ComponentScore {
9040 retriever_name: retriever_name.clone(),
9041 rank: hit.rank,
9042 raw_score: hit.score,
9043 contribution,
9044 });
9045 }
9046 fusion_nanos = fusion_nanos.saturating_add(fusion_started.elapsed().as_nanos() as u64);
9047 }
9048 let union_size = fused.len();
9049 let mut ranked: Vec<_> = fused
9050 .into_iter()
9051 .map(|(row_id, (fused_score, components))| {
9052 (row_id, fused_score, components, None, fused_score)
9053 })
9054 .collect();
9055 let order = |(a_row, _, _, _, a_score): &(
9056 RowId,
9057 f64,
9058 Vec<ComponentScore>,
9059 Option<f32>,
9060 f64,
9061 ),
9062 (b_row, _, _, _, b_score): &(
9063 RowId,
9064 f64,
9065 Vec<ComponentScore>,
9066 Option<f32>,
9067 f64,
9068 )| { b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row)) };
9069 if let Some(crate::query::Rerank::ExactVector {
9070 embedding_column,
9071 query,
9072 metric,
9073 candidate_limit,
9074 weight,
9075 }) = &request.rerank
9076 {
9077 let fused_order = |(a_row, a_score, ..): &(
9078 RowId,
9079 f64,
9080 Vec<ComponentScore>,
9081 Option<f32>,
9082 f64,
9083 ),
9084 (b_row, b_score, ..): &(
9085 RowId,
9086 f64,
9087 Vec<ComponentScore>,
9088 Option<f32>,
9089 f64,
9090 )| {
9091 b_score.total_cmp(a_score).then_with(|| a_row.cmp(b_row))
9092 };
9093 let selection_started = std::time::Instant::now();
9094 if let Some(context) = context {
9095 context.consume(ranked.len())?;
9096 }
9097 if ranked.len() > *candidate_limit {
9098 let (_, _, _) = ranked.select_nth_unstable_by(*candidate_limit, fused_order);
9099 ranked.truncate(*candidate_limit);
9100 }
9101 ranked.sort_by(fused_order);
9102 fusion_nanos =
9103 fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9104 let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9105 if let Some(context) = context {
9106 context.consume(row_ids.len())?;
9107 }
9108 let query_now =
9109 context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9110 let gather_started = std::time::Instant::now();
9111 let vectors = self.values_for_rids_batch_at_with_context(
9112 &row_ids,
9113 *embedding_column,
9114 snapshot,
9115 query_now,
9116 context,
9117 )?;
9118 let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9119 let vector_work =
9120 crate::query::work_units(query.len(), crate::query::VECTOR_WORK_QUANTUM);
9121 let query_norm = if matches!(metric, crate::query::VectorMetric::Cosine) {
9122 if let Some(context) = context {
9123 context.consume(vector_work)?;
9124 }
9125 query
9126 .iter()
9127 .map(|value| f64::from(*value).powi(2))
9128 .sum::<f64>()
9129 .sqrt()
9130 } else {
9131 0.0
9132 };
9133 let score_started = std::time::Instant::now();
9134 let mut scores = std::collections::HashMap::with_capacity(vectors.len());
9135 for (row_id, value) in vectors {
9136 if let Some(meta) = value.generated_embedding_metadata() {
9137 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9138 continue;
9139 }
9140 }
9141 let Some(vector) = value.as_embedding() else {
9142 continue;
9143 };
9144 let score = match metric {
9145 crate::query::VectorMetric::DotProduct => {
9146 if let Some(context) = context {
9147 context.consume(vector_work)?;
9148 }
9149 query
9150 .iter()
9151 .zip(vector)
9152 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9153 .sum::<f64>()
9154 }
9155 crate::query::VectorMetric::Cosine => {
9156 if let Some(context) = context {
9157 context.consume(vector_work.saturating_mul(2))?;
9158 }
9159 let dot = query
9160 .iter()
9161 .zip(vector)
9162 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9163 .sum::<f64>();
9164 let norm = vector
9165 .iter()
9166 .map(|value| f64::from(*value).powi(2))
9167 .sum::<f64>()
9168 .sqrt();
9169 if query_norm == 0.0 || norm == 0.0 {
9170 0.0
9171 } else {
9172 dot / (query_norm * norm)
9173 }
9174 }
9175 crate::query::VectorMetric::Euclidean => {
9176 if let Some(context) = context {
9177 context.consume(vector_work)?;
9178 }
9179 query
9180 .iter()
9181 .zip(vector)
9182 .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9183 .sum::<f64>()
9184 .sqrt()
9185 }
9186 };
9187 if !score.is_finite() {
9188 return Err(MongrelError::InvalidArgument(
9189 "exact rerank score must be finite".into(),
9190 ));
9191 }
9192 scores.insert(row_id, score as f32);
9193 }
9194 let mut reranked = Vec::with_capacity(ranked.len());
9195 for (row_id, fused_score, components, _, _) in ranked.drain(..) {
9196 let Some(score) = scores.get(&row_id).copied() else {
9197 continue;
9198 };
9199 let ordering_score = match metric {
9200 crate::query::VectorMetric::Euclidean => -f64::from(score),
9201 crate::query::VectorMetric::Cosine | crate::query::VectorMetric::DotProduct => {
9202 f64::from(score)
9203 }
9204 };
9205 let final_score = fused_score + *weight * ordering_score;
9206 if !final_score.is_finite() {
9207 return Err(MongrelError::InvalidArgument(
9208 "final rerank score must be finite".into(),
9209 ));
9210 }
9211 reranked.push((row_id, fused_score, components, Some(score), final_score));
9212 }
9213 ranked = reranked;
9214 ranked.sort_by(order);
9215 crate::trace::QueryTrace::record(|trace| {
9216 trace.exact_vector_gather_nanos =
9217 trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9218 trace.exact_vector_score_nanos = trace
9219 .exact_vector_score_nanos
9220 .saturating_add(score_started.elapsed().as_nanos() as u64);
9221 });
9222 }
9223 if let Some(after) = after {
9224 ranked.retain(|(row_id, _, _, _, final_score)| {
9225 final_score.total_cmp(&after.final_score).is_lt()
9226 || (final_score.total_cmp(&after.final_score).is_eq() && *row_id > after.row_id)
9227 });
9228 }
9229 let projection_started = std::time::Instant::now();
9230 let sentinel = projection
9231 .first()
9232 .copied()
9233 .or_else(|| self.schema.columns.first().map(|column| column.id));
9234 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9235 let mut out = Vec::with_capacity(request.limit.min(ranked.len()));
9236 let mut projection_rows = 0usize;
9237 let mut projection_cells = 0usize;
9238 while out.len() < request.limit && !ranked.is_empty() {
9239 if let Some(context) = context {
9240 context.checkpoint()?;
9241 context.consume(ranked.len())?;
9242 }
9243 let needed = request.limit - out.len();
9244 let window_size = ranked
9245 .len()
9246 .min(needed.saturating_mul(2).max(needed.saturating_add(8)));
9247 let selection_started = std::time::Instant::now();
9248 let mut remainder = if ranked.len() > window_size {
9249 let (_, _, _) = ranked.select_nth_unstable_by(window_size, order);
9250 ranked.split_off(window_size)
9251 } else {
9252 Vec::new()
9253 };
9254 ranked.sort_by(order);
9255 fusion_nanos =
9256 fusion_nanos.saturating_add(selection_started.elapsed().as_nanos() as u64);
9257 let row_ids: Vec<_> = ranked.iter().map(|(row_id, ..)| row_id.0).collect();
9258 let gathered_columns = projection.len().max(usize::from(sentinel.is_some()));
9259 if let Some(context) = context {
9260 context.consume(row_ids.len().saturating_mul(gathered_columns))?;
9261 }
9262 projection_rows = projection_rows.saturating_add(row_ids.len());
9263 projection_cells =
9264 projection_cells.saturating_add(row_ids.len().saturating_mul(gathered_columns));
9265 let mut cells: std::collections::HashMap<RowId, std::collections::HashMap<u16, Value>> =
9266 std::collections::HashMap::new();
9267 if let Some(column_id) = sentinel {
9268 for (row_id, value) in self.values_for_rids_batch_at_with_context(
9269 &row_ids, column_id, snapshot, query_now, context,
9270 )? {
9271 cells.entry(row_id).or_default().insert(column_id, value);
9272 }
9273 }
9274 for &column_id in &projection {
9275 if Some(column_id) == sentinel {
9276 continue;
9277 }
9278 for (row_id, value) in self.values_for_rids_batch_at_with_context(
9279 &row_ids, column_id, snapshot, query_now, context,
9280 )? {
9281 cells.entry(row_id).or_default().insert(column_id, value);
9282 }
9283 }
9284 for (row_id, fused_score, mut components, exact_rerank_score, final_score) in
9285 ranked.drain(..)
9286 {
9287 let Some(row_cells) = cells.remove(&row_id) else {
9288 continue;
9289 };
9290 components.sort_by(|a, b| a.retriever_name.cmp(&b.retriever_name));
9291 let final_rank = rank_offset.saturating_add(out.len()).saturating_add(1);
9292 out.push(SearchHit {
9293 row_id,
9294 cells: projection
9295 .iter()
9296 .filter_map(|column_id| {
9297 row_cells
9298 .get(column_id)
9299 .cloned()
9300 .map(|value| (*column_id, value))
9301 })
9302 .collect(),
9303 components,
9304 fused_score,
9305 exact_rerank_score,
9306 final_score,
9307 final_rank,
9308 });
9309 if out.len() == request.limit {
9310 break;
9311 }
9312 }
9313 ranked.append(&mut remainder);
9314 }
9315 crate::trace::QueryTrace::record(|trace| {
9316 trace.union_size = union_size;
9317 trace.fusion_nanos = trace.fusion_nanos.saturating_add(fusion_nanos);
9318 trace.projection_nanos = trace
9319 .projection_nanos
9320 .saturating_add(projection_started.elapsed().as_nanos() as u64);
9321 trace.total_nanos = trace
9322 .total_nanos
9323 .saturating_add(total_started.elapsed().as_nanos() as u64);
9324 trace.projection_rows = trace.projection_rows.saturating_add(projection_rows);
9325 trace.projection_cells = trace.projection_cells.saturating_add(projection_cells);
9326 if let Some(context) = context {
9327 trace.work_consumed = trace.work_consumed.saturating_add(context.consumed_work());
9328 }
9329 });
9330 Ok(out)
9331 }
9332
9333 pub fn set_similarity(
9336 &mut self,
9337 request: &crate::query::SetSimilarityRequest,
9338 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9339 self.set_similarity_with_allowed(request, None)
9340 }
9341
9342 pub fn set_similarity_at(
9343 &mut self,
9344 request: &crate::query::SetSimilarityRequest,
9345 snapshot: Snapshot,
9346 allowed: Option<&std::collections::HashSet<RowId>>,
9347 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9348 self.set_similarity_explained_at(request, snapshot, allowed)
9349 .map(|(hits, _)| hits)
9350 }
9351
9352 pub fn ann_rerank(
9354 &mut self,
9355 request: &crate::query::AnnRerankRequest,
9356 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9357 self.ann_rerank_with_allowed(request, None)
9358 }
9359
9360 pub fn ann_rerank_with_allowed(
9361 &mut self,
9362 request: &crate::query::AnnRerankRequest,
9363 allowed: Option<&std::collections::HashSet<RowId>>,
9364 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9365 self.ann_rerank_at(request, self.snapshot(), allowed)
9366 }
9367
9368 pub fn ann_rerank_at(
9369 &mut self,
9370 request: &crate::query::AnnRerankRequest,
9371 snapshot: Snapshot,
9372 allowed: Option<&std::collections::HashSet<RowId>>,
9373 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9374 self.ann_rerank_at_with_context(request, snapshot, allowed, None)
9375 }
9376
9377 pub fn ann_rerank_at_with_context(
9378 &mut self,
9379 request: &crate::query::AnnRerankRequest,
9380 snapshot: Snapshot,
9381 allowed: Option<&std::collections::HashSet<RowId>>,
9382 context: Option<&crate::query::AiExecutionContext>,
9383 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9384 self.ensure_indexes_complete()?;
9385 self.ann_rerank_at_with_filters_and_context(request, snapshot, allowed, None, context)
9386 }
9387
9388 pub fn ann_rerank_at_with_candidate_authorization_and_context(
9389 &mut self,
9390 request: &crate::query::AnnRerankRequest,
9391 snapshot: Snapshot,
9392 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9393 context: Option<&crate::query::AiExecutionContext>,
9394 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9395 self.ensure_indexes_complete()?;
9396 self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9397 }
9398
9399 #[doc(hidden)]
9400 pub fn ann_rerank_at_with_candidate_authorization_on_generation(
9401 &self,
9402 request: &crate::query::AnnRerankRequest,
9403 snapshot: Snapshot,
9404 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9405 context: Option<&crate::query::AiExecutionContext>,
9406 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9407 self.ann_rerank_at_with_filters_and_context(request, snapshot, None, authorization, context)
9408 }
9409
9410 fn ann_rerank_at_with_filters_and_context(
9411 &self,
9412 request: &crate::query::AnnRerankRequest,
9413 snapshot: Snapshot,
9414 allowed: Option<&std::collections::HashSet<RowId>>,
9415 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9416 context: Option<&crate::query::AiExecutionContext>,
9417 ) -> Result<Vec<crate::query::AnnRerankHit>> {
9418 use crate::query::{
9419 AnnCandidateDistance, AnnRerankHit, Retriever, RetrieverScore, VectorMetric,
9420 MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9421 };
9422 if request.candidate_k == 0 || request.limit == 0 {
9423 return Err(MongrelError::InvalidArgument(
9424 "candidate_k and limit must be > 0".into(),
9425 ));
9426 }
9427 if request.candidate_k > MAX_RETRIEVER_K || request.limit > MAX_FINAL_LIMIT {
9428 return Err(MongrelError::InvalidArgument(format!(
9429 "candidate_k must be <= {MAX_RETRIEVER_K} and limit <= {MAX_FINAL_LIMIT}"
9430 )));
9431 }
9432 let retriever = Retriever::Ann {
9433 column_id: request.column_id,
9434 query: request.query.clone(),
9435 k: request.candidate_k,
9436 };
9437 self.require_select()?;
9438 self.validate_retriever(&retriever)?;
9439 let hits = self.retrieve_filtered(
9440 &retriever,
9441 snapshot,
9442 None,
9443 allowed,
9444 candidate_authorization,
9445 context,
9446 )?;
9447 let distances: std::collections::HashMap<_, _> = hits
9448 .iter()
9449 .filter_map(|hit| match hit.score {
9450 RetrieverScore::AnnHammingDistance(distance) => {
9451 Some((hit.row_id, AnnCandidateDistance::Hamming(distance)))
9452 }
9453 RetrieverScore::AnnCosineDistance(distance) => {
9454 Some((hit.row_id, AnnCandidateDistance::Cosine(distance)))
9455 }
9456 _ => None,
9457 })
9458 .collect();
9459 let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9460 if let Some(context) = context {
9461 context.consume(row_ids.len())?;
9462 }
9463 let gather_started = std::time::Instant::now();
9464 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9465 let values = self.values_for_rids_batch_at_with_context(
9466 &row_ids,
9467 request.column_id,
9468 snapshot,
9469 query_now,
9470 context,
9471 )?;
9472 let gather_nanos = gather_started.elapsed().as_nanos() as u64;
9473 let score_started = std::time::Instant::now();
9474 let vector_work =
9475 crate::query::work_units(request.query.len(), crate::query::VECTOR_WORK_QUANTUM);
9476 let query_norm = if matches!(request.metric, VectorMetric::Cosine) {
9477 if let Some(context) = context {
9478 context.consume(vector_work)?;
9479 }
9480 request
9481 .query
9482 .iter()
9483 .map(|value| f64::from(*value).powi(2))
9484 .sum::<f64>()
9485 .sqrt()
9486 } else {
9487 0.0
9488 };
9489 let mut reranked = Vec::with_capacity(values.len().min(request.limit));
9490 for (row_id, value) in values {
9491 if let Some(meta) = value.generated_embedding_metadata() {
9492 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
9493 continue;
9494 }
9495 }
9496 let Some(vector) = value.as_embedding() else {
9497 continue;
9498 };
9499 let exact_score = match request.metric {
9500 VectorMetric::DotProduct => {
9501 if let Some(context) = context {
9502 context.consume(vector_work)?;
9503 }
9504 request
9505 .query
9506 .iter()
9507 .zip(vector)
9508 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9509 .sum::<f64>()
9510 }
9511 VectorMetric::Cosine => {
9512 if let Some(context) = context {
9513 context.consume(vector_work.saturating_mul(2))?;
9514 }
9515 let dot = request
9516 .query
9517 .iter()
9518 .zip(vector)
9519 .map(|(left, right)| f64::from(*left) * f64::from(*right))
9520 .sum::<f64>();
9521 let norm = vector
9522 .iter()
9523 .map(|value| f64::from(*value).powi(2))
9524 .sum::<f64>()
9525 .sqrt();
9526 if query_norm == 0.0 || norm == 0.0 {
9527 0.0
9528 } else {
9529 dot / (query_norm * norm)
9530 }
9531 }
9532 VectorMetric::Euclidean => {
9533 if let Some(context) = context {
9534 context.consume(vector_work)?;
9535 }
9536 request
9537 .query
9538 .iter()
9539 .zip(vector)
9540 .map(|(left, right)| (f64::from(*left) - f64::from(*right)).powi(2))
9541 .sum::<f64>()
9542 .sqrt()
9543 }
9544 };
9545 let exact_score = exact_score as f32;
9546 if !exact_score.is_finite() {
9547 return Err(MongrelError::InvalidArgument(
9548 "exact ANN score must be finite".into(),
9549 ));
9550 }
9551 let Some(candidate_distance) = distances.get(&row_id).copied() else {
9552 continue;
9553 };
9554 reranked.push(AnnRerankHit {
9555 row_id,
9556 candidate_distance,
9557 exact_score,
9558 });
9559 }
9560 reranked.sort_by(|left, right| {
9561 let score = match request.metric {
9562 VectorMetric::Euclidean => left.exact_score.total_cmp(&right.exact_score),
9563 VectorMetric::Cosine | VectorMetric::DotProduct => {
9564 right.exact_score.total_cmp(&left.exact_score)
9565 }
9566 };
9567 score.then_with(|| left.row_id.cmp(&right.row_id))
9568 });
9569 reranked.truncate(request.limit);
9570 crate::trace::QueryTrace::record(|trace| {
9571 trace.exact_vector_gather_nanos =
9572 trace.exact_vector_gather_nanos.saturating_add(gather_nanos);
9573 trace.exact_vector_score_nanos = trace
9574 .exact_vector_score_nanos
9575 .saturating_add(score_started.elapsed().as_nanos() as u64);
9576 });
9577 Ok(reranked)
9578 }
9579
9580 pub fn set_similarity_with_allowed(
9581 &mut self,
9582 request: &crate::query::SetSimilarityRequest,
9583 allowed: Option<&std::collections::HashSet<RowId>>,
9584 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9585 self.set_similarity_explained_at(request, self.snapshot(), allowed)
9586 .map(|(hits, _)| hits)
9587 }
9588
9589 pub fn set_similarity_explained(
9590 &mut self,
9591 request: &crate::query::SetSimilarityRequest,
9592 ) -> Result<(
9593 Vec<crate::query::SetSimilarityHit>,
9594 crate::query::SetSimilarityTrace,
9595 )> {
9596 self.set_similarity_explained_at(request, self.snapshot(), None)
9597 }
9598
9599 fn set_similarity_explained_at(
9600 &mut self,
9601 request: &crate::query::SetSimilarityRequest,
9602 snapshot: Snapshot,
9603 allowed: Option<&std::collections::HashSet<RowId>>,
9604 ) -> Result<(
9605 Vec<crate::query::SetSimilarityHit>,
9606 crate::query::SetSimilarityTrace,
9607 )> {
9608 self.ensure_indexes_complete()?;
9609 self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, None)
9610 }
9611
9612 pub fn set_similarity_at_with_context(
9613 &mut self,
9614 request: &crate::query::SetSimilarityRequest,
9615 snapshot: Snapshot,
9616 allowed: Option<&std::collections::HashSet<RowId>>,
9617 context: Option<&crate::query::AiExecutionContext>,
9618 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9619 self.ensure_indexes_complete()?;
9620 self.set_similarity_explained_at_with_context(request, snapshot, allowed, None, context)
9621 .map(|(hits, _)| hits)
9622 }
9623
9624 pub fn set_similarity_at_with_candidate_authorization_and_context(
9625 &mut self,
9626 request: &crate::query::SetSimilarityRequest,
9627 snapshot: Snapshot,
9628 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9629 context: Option<&crate::query::AiExecutionContext>,
9630 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9631 self.ensure_indexes_complete()?;
9632 self.set_similarity_explained_at_with_context(
9633 request,
9634 snapshot,
9635 None,
9636 authorization,
9637 context,
9638 )
9639 .map(|(hits, _)| hits)
9640 }
9641
9642 #[doc(hidden)]
9643 pub fn set_similarity_at_with_candidate_authorization_on_generation(
9644 &self,
9645 request: &crate::query::SetSimilarityRequest,
9646 snapshot: Snapshot,
9647 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9648 context: Option<&crate::query::AiExecutionContext>,
9649 ) -> Result<Vec<crate::query::SetSimilarityHit>> {
9650 self.set_similarity_explained_at_with_context(
9651 request,
9652 snapshot,
9653 None,
9654 authorization,
9655 context,
9656 )
9657 .map(|(hits, _)| hits)
9658 }
9659
9660 fn set_similarity_explained_at_with_context(
9661 &self,
9662 request: &crate::query::SetSimilarityRequest,
9663 snapshot: Snapshot,
9664 allowed: Option<&std::collections::HashSet<RowId>>,
9665 candidate_authorization: Option<&crate::security::CandidateAuthorization<'_>>,
9666 context: Option<&crate::query::AiExecutionContext>,
9667 ) -> Result<(
9668 Vec<crate::query::SetSimilarityHit>,
9669 crate::query::SetSimilarityTrace,
9670 )> {
9671 use crate::query::{
9672 Retriever, RetrieverScore, SetSimilarityHit, MAX_FINAL_LIMIT, MAX_RETRIEVER_K,
9673 MAX_SET_MEMBERS,
9674 };
9675 let mut trace = crate::query::SetSimilarityTrace::default();
9676 if request.members.is_empty() {
9677 return Ok((Vec::new(), trace));
9678 }
9679 if request.candidate_k == 0 || request.limit == 0 {
9680 return Err(MongrelError::InvalidArgument(
9681 "candidate_k and limit must be > 0".into(),
9682 ));
9683 }
9684 if request.candidate_k > MAX_RETRIEVER_K
9685 || request.limit > MAX_FINAL_LIMIT
9686 || request.members.len() > MAX_SET_MEMBERS
9687 {
9688 return Err(MongrelError::InvalidArgument(format!(
9689 "candidate_k must be <= {MAX_RETRIEVER_K}, limit <= {MAX_FINAL_LIMIT}, and members <= {MAX_SET_MEMBERS}"
9690 )));
9691 }
9692 if !request.min_jaccard.is_finite() || !(0.0..=1.0).contains(&request.min_jaccard) {
9693 return Err(MongrelError::InvalidArgument(
9694 "min_jaccard must be finite and between 0 and 1".into(),
9695 ));
9696 }
9697 let started = std::time::Instant::now();
9698 let retriever = Retriever::MinHash {
9699 column_id: request.column_id,
9700 members: request.members.clone(),
9701 k: request.candidate_k,
9702 };
9703 self.require_select()?;
9704 self.validate_retriever(&retriever)?;
9705 let hits = self.retrieve_filtered(
9706 &retriever,
9707 snapshot,
9708 None,
9709 allowed,
9710 candidate_authorization,
9711 context,
9712 )?;
9713 trace.candidate_generation_us = started.elapsed().as_micros() as u64;
9714 trace.candidate_count = hits.len();
9715 let row_ids: Vec<_> = hits.iter().map(|hit| hit.row_id.0).collect();
9716 if let Some(context) = context {
9717 context.consume(row_ids.len())?;
9718 }
9719 let started = std::time::Instant::now();
9720 let query_now = context.map_or_else(unix_nanos_now, |context| context.query_time_nanos());
9721 let values = self.values_for_rids_batch_at_with_context(
9722 &row_ids,
9723 request.column_id,
9724 snapshot,
9725 query_now,
9726 context,
9727 )?;
9728 trace.gather_us = started.elapsed().as_micros() as u64;
9729 if let Some(context) = context {
9730 context.consume(request.members.len())?;
9731 }
9732 let query: std::collections::HashSet<_> = request.members.iter().cloned().collect();
9733 let estimates: std::collections::HashMap<_, _> = hits
9734 .into_iter()
9735 .filter_map(|hit| match hit.score {
9736 RetrieverScore::MinHashEstimatedJaccard(score) => Some((hit.row_id, score)),
9737 _ => None,
9738 })
9739 .collect();
9740 let started = std::time::Instant::now();
9741 let mut parsed = Vec::with_capacity(values.len());
9742 for (row_id, value) in values {
9743 let Value::Bytes(bytes) = value else {
9744 continue;
9745 };
9746 if let Some(context) = context {
9747 context.consume(crate::query::work_units(
9748 bytes.len(),
9749 crate::query::PARSE_WORK_QUANTUM,
9750 ))?;
9751 }
9752 let Ok(serde_json::Value::Array(members)) = serde_json::from_slice(&bytes) else {
9753 continue;
9754 };
9755 if let Some(context) = context {
9756 context.consume(members.len())?;
9757 }
9758 let stored = members
9759 .into_iter()
9760 .filter_map(|member| match member {
9761 serde_json::Value::String(value) => {
9762 Some(crate::query::SetMember::String(value))
9763 }
9764 serde_json::Value::Number(value) => {
9765 Some(crate::query::SetMember::Number(value))
9766 }
9767 serde_json::Value::Bool(value) => Some(crate::query::SetMember::Boolean(value)),
9768 _ => None,
9769 })
9770 .collect::<std::collections::HashSet<_>>();
9771 parsed.push((row_id, stored));
9772 }
9773 trace.parse_us = started.elapsed().as_micros() as u64;
9774 trace.verified_count = parsed.len();
9775 let started = std::time::Instant::now();
9776 let mut exact = Vec::new();
9777 for (row_id, stored) in parsed {
9778 if let Some(context) = context {
9779 context.consume(query.len().saturating_add(stored.len()))?;
9780 }
9781 let union = query.union(&stored).count();
9782 let score = if union == 0 {
9783 1.0
9784 } else {
9785 query.intersection(&stored).count() as f32 / union as f32
9786 };
9787 if score >= request.min_jaccard {
9788 exact.push(SetSimilarityHit {
9789 row_id,
9790 estimated_jaccard: estimates.get(&row_id).copied().unwrap_or_default(),
9791 exact_jaccard: score,
9792 });
9793 }
9794 }
9795 exact.sort_by(|a, b| {
9796 b.exact_jaccard
9797 .total_cmp(&a.exact_jaccard)
9798 .then_with(|| a.row_id.cmp(&b.row_id))
9799 });
9800 exact.truncate(request.limit);
9801 trace.score_us = started.elapsed().as_micros() as u64;
9802 crate::trace::QueryTrace::record(|query_trace| {
9803 query_trace.exact_set_gather_nanos = query_trace
9804 .exact_set_gather_nanos
9805 .saturating_add(trace.gather_us.saturating_mul(1_000));
9806 query_trace.exact_set_parse_nanos = query_trace
9807 .exact_set_parse_nanos
9808 .saturating_add(trace.parse_us.saturating_mul(1_000));
9809 query_trace.exact_set_score_nanos = query_trace
9810 .exact_set_score_nanos
9811 .saturating_add(trace.score_us.saturating_mul(1_000));
9812 });
9813 Ok((exact, trace))
9814 }
9815
9816 fn values_for_rids_batch_at(
9818 &self,
9819 row_ids: &[u64],
9820 column_id: u16,
9821 snapshot: Snapshot,
9822 now: i64,
9823 ) -> Result<Vec<(RowId, Value)>> {
9824 if self.ttl.is_none()
9825 && self.memtable.is_empty()
9826 && self.mutable_run.is_empty()
9827 && self.run_refs.len() == 1
9828 {
9829 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
9830 if row_ids.len().saturating_mul(24) < reader.row_count() {
9835 let mut values = Vec::with_capacity(row_ids.len());
9836 for &raw_row_id in row_ids {
9837 let row_id = RowId(raw_row_id);
9838 if let Some((_, false, Some(value))) =
9839 reader.get_version_column_at(row_id, snapshot, column_id)?
9840 {
9841 values.push((row_id, value));
9842 }
9843 }
9844 return Ok(values);
9845 }
9846 let (positions, visible_row_ids) = reader.visible_positions_with_rids_at(snapshot)?;
9847 let requested: Vec<(RowId, usize)> = row_ids
9848 .iter()
9849 .filter_map(|raw| {
9850 visible_row_ids
9851 .binary_search(&(*raw as i64))
9852 .ok()
9853 .map(|index| (RowId(*raw), positions[index]))
9854 })
9855 .collect();
9856 let values = reader.gather_column(
9857 column_id,
9858 &requested
9859 .iter()
9860 .map(|(_, position)| *position)
9861 .collect::<Vec<_>>(),
9862 )?;
9863 return Ok(requested
9864 .into_iter()
9865 .zip(values)
9866 .map(|((row_id, _), value)| (row_id, value))
9867 .collect());
9868 }
9869 self.values_for_rids_at(row_ids, column_id, snapshot, now)
9870 }
9871
9872 fn values_for_rids_batch_at_with_context(
9873 &self,
9874 row_ids: &[u64],
9875 column_id: u16,
9876 snapshot: Snapshot,
9877 now: i64,
9878 context: Option<&crate::query::AiExecutionContext>,
9879 ) -> Result<Vec<(RowId, Value)>> {
9880 let Some(context) = context else {
9881 return self.values_for_rids_batch_at(row_ids, column_id, snapshot, now);
9882 };
9883 let mut values = Vec::with_capacity(row_ids.len());
9884 for chunk in row_ids.chunks(256) {
9885 context.checkpoint()?;
9886 values.extend(self.values_for_rids_batch_at(chunk, column_id, snapshot, now)?);
9887 }
9888 Ok(values)
9889 }
9890
9891 fn values_for_rids_at(
9893 &self,
9894 row_ids: &[u64],
9895 column_id: u16,
9896 snapshot: Snapshot,
9897 now: i64,
9898 ) -> Result<Vec<(RowId, Value)>> {
9899 let mut readers: Vec<_> = self
9900 .run_refs
9901 .iter()
9902 .map(|run| self.open_reader(run.run_id))
9903 .collect::<Result<_>>()?;
9904 let mut out = Vec::with_capacity(row_ids.len());
9905 for &raw_row_id in row_ids {
9906 let row_id = RowId(raw_row_id);
9907 let mem = self.memtable.get_version_at(row_id, snapshot);
9908 let mutable = self.mutable_run.get_version_at(row_id, snapshot);
9909 let overlay = match (mem, mutable) {
9910 (Some((_, a)), Some((_, b))) => Some(
9911 if Snapshot::version_is_newer(
9912 a.committed_epoch,
9913 a.commit_ts,
9914 b.committed_epoch,
9915 b.commit_ts,
9916 ) {
9917 a
9918 } else {
9919 b
9920 },
9921 ),
9922 (Some((_, value)), None) | (None, Some((_, value))) => Some(value),
9923 (None, None) => None,
9924 };
9925 if let Some(row) = overlay {
9926 if !row.deleted && !self.row_expired_at(&row, now) {
9927 if let Some(value) = row.columns.get(&column_id) {
9928 out.push((row_id, value.clone()));
9929 }
9930 }
9931 continue;
9932 }
9933
9934 let mut best: Option<(crate::sorted_run::VersionedColumnValue, usize)> = None;
9939 for (index, reader) in readers.iter_mut().enumerate() {
9940 if let Some(versioned) =
9941 reader.get_version_column_full_at(row_id, snapshot, column_id)?
9942 {
9943 if best
9944 .as_ref()
9945 .map(|(current, _)| versioned.stamp.is_newer_than(current.stamp))
9946 .unwrap_or(true)
9947 {
9948 best = Some((versioned, index));
9949 }
9950 }
9951 }
9952 let Some((candidate, reader_index)) = best else {
9953 continue;
9954 };
9955 if candidate.deleted {
9956 continue;
9957 }
9958 let Some(value) = candidate.value.clone() else {
9959 continue;
9960 };
9961 if let Some(ttl) = self.ttl {
9962 if ttl.column_id != column_id {
9963 if let Some(ttl_value) = readers[reader_index].get_version_column_full_at(
9964 row_id,
9965 snapshot,
9966 ttl.column_id,
9967 )? {
9968 if let Some(Value::Int64(timestamp)) = ttl_value.value {
9969 if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
9970 continue;
9971 }
9972 }
9973 }
9974 } else if let Value::Int64(timestamp) = &value {
9975 if timestamp.saturating_add(ttl.duration_nanos as i64) <= now {
9976 continue;
9977 }
9978 }
9979 }
9980 out.push((row_id, value));
9981 }
9982 Ok(out)
9983 }
9984
9985 pub fn rows_for_rids(&self, rids: &[u64], snapshot: Snapshot) -> Result<Vec<Row>> {
9990 self.rows_for_rids_at_time(rids, snapshot, unix_nanos_now(), None)
9991 }
9992
9993 pub fn rows_for_rids_with_context(
9994 &self,
9995 rids: &[u64],
9996 snapshot: Snapshot,
9997 context: &crate::query::AiExecutionContext,
9998 ) -> Result<Vec<Row>> {
9999 context.consume(rids.len().saturating_mul(self.schema.columns.len()))?;
10000 self.rows_for_rids_at_time(rids, snapshot, context.query_time_nanos(), None)
10001 }
10002
10003 fn rows_for_rids_at_time(
10004 &self,
10005 rids: &[u64],
10006 snapshot: Snapshot,
10007 ttl_now: i64,
10008 control: Option<&crate::ExecutionControl>,
10009 ) -> Result<Vec<Row>> {
10010 use std::collections::HashMap;
10011 let mut rows = Vec::with_capacity(rids.len());
10012 let tier_size = self.memtable.len() + self.mutable_run.len();
10027 let mut overlay: HashMap<u64, Row> = HashMap::with_capacity(rids.len());
10028 if rids.len().saturating_mul(24) < tier_size {
10029 for &rid in rids {
10030 if overlay.len() & 255 == 0 {
10031 control
10032 .map(crate::ExecutionControl::checkpoint)
10033 .transpose()?;
10034 }
10035 let mem = self.memtable.get_version_at(RowId(rid), snapshot);
10036 let mrun = self.mutable_run.get_version_at(RowId(rid), snapshot);
10037 let newest = match (mem, mrun) {
10038 (Some((_, mr)), Some((_, rr))) => Some(
10039 if Snapshot::version_is_newer(
10040 mr.committed_epoch,
10041 mr.commit_ts,
10042 rr.committed_epoch,
10043 rr.commit_ts,
10044 ) {
10045 mr
10046 } else {
10047 rr
10048 },
10049 ),
10050 (Some((_, mr)), None) => Some(mr),
10051 (None, Some((_, rr))) => Some(rr),
10052 (None, None) => None,
10053 };
10054 if let Some(row) = newest {
10055 overlay.insert(rid, row);
10056 }
10057 }
10058 } else {
10059 let fold_newest = |row: Row, overlay: &mut HashMap<u64, Row>| {
10060 overlay
10061 .entry(row.row_id.0)
10062 .and_modify(|e| {
10063 if Snapshot::version_is_newer(
10064 row.committed_epoch,
10065 row.commit_ts,
10066 e.committed_epoch,
10067 e.commit_ts,
10068 ) {
10069 *e = row.clone();
10070 }
10071 })
10072 .or_insert(row);
10073 };
10074 for (index, row) in self
10075 .memtable
10076 .visible_versions_at(snapshot)
10077 .into_iter()
10078 .enumerate()
10079 {
10080 if index & 255 == 0 {
10081 control
10082 .map(crate::ExecutionControl::checkpoint)
10083 .transpose()?;
10084 }
10085 fold_newest(row, &mut overlay);
10086 }
10087 for (index, row) in self
10088 .mutable_run
10089 .visible_versions_at(snapshot)
10090 .into_iter()
10091 .enumerate()
10092 {
10093 if index & 255 == 0 {
10094 control
10095 .map(crate::ExecutionControl::checkpoint)
10096 .transpose()?;
10097 }
10098 fold_newest(row, &mut overlay);
10099 }
10100 }
10101 if self.run_refs.len() == 1 {
10102 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
10103 if rids.len().saturating_mul(24) < reader.row_count() {
10111 for (index, &rid) in rids.iter().enumerate() {
10112 if index & 255 == 0 {
10113 control
10114 .map(crate::ExecutionControl::checkpoint)
10115 .transpose()?;
10116 }
10117 if let Some(r) = overlay.get(&rid) {
10118 if !r.deleted {
10119 rows.push(r.clone());
10120 }
10121 continue;
10122 }
10123 if let Some((_, row)) = reader.get_version_at(RowId(rid), snapshot)? {
10124 if !row.deleted {
10125 rows.push(row);
10126 }
10127 }
10128 }
10129 rows.retain(|row| !self.row_expired_at(row, ttl_now));
10130 return Ok(rows);
10131 }
10132 let (positions, vis_rids) = reader.visible_positions_with_rids_at(snapshot)?;
10141 enum Src {
10144 Overlay,
10145 Run,
10146 }
10147 let mut plan: Vec<Src> = Vec::with_capacity(rids.len());
10148 let mut fetch: Vec<usize> = Vec::with_capacity(rids.len());
10149 for (index, rid) in rids.iter().enumerate() {
10150 if index & 255 == 0 {
10151 control
10152 .map(crate::ExecutionControl::checkpoint)
10153 .transpose()?;
10154 }
10155 if overlay.contains_key(rid) {
10156 plan.push(Src::Overlay);
10157 continue;
10158 }
10159 match vis_rids.binary_search(&(*rid as i64)) {
10160 Ok(i) => {
10161 plan.push(Src::Run);
10162 fetch.push(positions[i]);
10163 }
10164 Err(_) => { }
10165 }
10166 }
10167 let fetched = reader.materialize_batch(&fetch)?;
10168 let mut fetched_iter = fetched.into_iter();
10169 for (index, (rid, src)) in rids.iter().zip(plan).enumerate() {
10170 if index & 255 == 0 {
10171 control
10172 .map(crate::ExecutionControl::checkpoint)
10173 .transpose()?;
10174 }
10175 match src {
10176 Src::Overlay => {
10177 if let Some(r) = overlay.get(rid) {
10178 if !r.deleted {
10179 rows.push(r.clone());
10180 }
10181 }
10182 }
10183 Src::Run => {
10184 if let Some(row) = fetched_iter.next() {
10185 if !row.deleted {
10186 rows.push(row);
10187 }
10188 }
10189 }
10190 }
10191 }
10192 rows.retain(|row| !self.row_expired_at(row, ttl_now));
10193 return Ok(rows);
10194 }
10195 let mut readers: Vec<_> = self
10199 .run_refs
10200 .iter()
10201 .map(|rr| self.open_reader(rr.run_id))
10202 .collect::<Result<Vec<_>>>()?;
10203 for (index, rid) in rids.iter().enumerate() {
10204 if index & 255 == 0 {
10205 control
10206 .map(crate::ExecutionControl::checkpoint)
10207 .transpose()?;
10208 }
10209 if let Some(r) = overlay.get(rid) {
10210 if !r.deleted {
10211 rows.push(r.clone());
10212 }
10213 continue;
10214 }
10215 let mut best: Option<(VersionStamp, Row)> = None;
10220 for reader in readers.iter_mut() {
10221 if let Ok(Some((stamp, row))) = reader.get_version_stamp_at(RowId(*rid), snapshot) {
10222 if best
10223 .as_ref()
10224 .map(|(current, _)| stamp.is_newer_than(*current))
10225 .unwrap_or(true)
10226 {
10227 best = Some((stamp, row));
10228 }
10229 }
10230 }
10231 if let Some((_, r)) = best {
10232 if !r.deleted {
10233 rows.push(r);
10234 }
10235 }
10236 }
10237 rows.retain(|row| !self.row_expired_at(row, ttl_now));
10238 Ok(rows)
10239 }
10240
10241 pub fn indexes_complete(&self) -> bool {
10251 self.indexes_complete
10252 }
10253
10254 pub fn index_build_policy(&self) -> IndexBuildPolicy {
10256 self.index_build_policy
10257 }
10258
10259 pub fn set_index_build_policy(&mut self, policy: IndexBuildPolicy) {
10263 self.index_build_policy = policy;
10264 }
10265
10266 pub fn broadcast_join_values(&self, column_id: u16, pk_db: &Table) -> Option<Vec<Vec<u8>>> {
10271 if !self.indexes_complete {
10275 return None;
10276 }
10277 let b = self.bitmap.get(&column_id)?;
10278 let result: Vec<Vec<u8>> = b
10279 .keys()
10280 .into_iter()
10281 .filter(|k| pk_db.hot.get(k.as_slice()).is_some())
10282 .collect();
10283 Some(result)
10284 }
10285
10286 pub fn fk_join_row_ids(
10287 &self,
10288 fk_column_id: u16,
10289 pk_values: &[Vec<u8>],
10290 fk_conditions: &[crate::query::Condition],
10291 snapshot: Snapshot,
10292 ) -> Result<Vec<u64>> {
10293 let Some(b) = self.bitmap.get(&fk_column_id) else {
10294 return Ok(Vec::new());
10295 };
10296 let mut join_set = {
10297 let mut acc = roaring::RoaringBitmap::new();
10298 for v in pk_values {
10299 acc |= b.get(v);
10300 }
10301 RowIdSet::from_roaring(acc)
10302 };
10303 if !fk_conditions.is_empty() {
10304 let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10305 sets.push(join_set);
10306 for c in fk_conditions {
10307 sets.push(self.resolve_condition(c, snapshot)?);
10308 }
10309 join_set = RowIdSet::intersect_many(sets);
10310 }
10311 Ok(join_set.into_sorted_vec())
10312 }
10313
10314 pub fn fk_join_count(
10320 &self,
10321 fk_column_id: u16,
10322 pk_values: &[Vec<u8>],
10323 fk_conditions: &[crate::query::Condition],
10324 snapshot: Snapshot,
10325 ) -> Result<u64> {
10326 let Some(b) = self.bitmap.get(&fk_column_id) else {
10327 return Ok(0);
10328 };
10329 let mut acc = roaring::RoaringBitmap::new();
10330 for v in pk_values {
10331 acc |= b.get(v);
10332 }
10333 if fk_conditions.is_empty() {
10334 return Ok(acc.len());
10335 }
10336 let mut sets: Vec<RowIdSet> = Vec::with_capacity(fk_conditions.len() + 1);
10337 sets.push(RowIdSet::from_roaring(acc));
10338 for c in fk_conditions {
10339 sets.push(self.resolve_condition(c, snapshot)?);
10340 }
10341 Ok(RowIdSet::intersect_many(sets).len() as u64)
10342 }
10343
10344 fn inspect_row_at(&self, rid: RowId, snapshot: Snapshot) -> Option<crate::memtable::Row> {
10349 let mut best: Option<crate::memtable::Row> = None;
10350 let mut consider = |row: crate::memtable::Row| {
10351 if !snapshot.observes_row(row.committed_epoch, row.commit_ts) {
10352 return;
10353 }
10354 if best.as_ref().is_none_or(|current| {
10355 Snapshot::version_is_newer(
10356 row.committed_epoch,
10357 row.commit_ts,
10358 current.committed_epoch,
10359 current.commit_ts,
10360 )
10361 }) {
10362 best = Some(row);
10363 }
10364 };
10365 if let Some((_, row)) = self.memtable.get_version_at(rid, snapshot) {
10366 consider(row);
10367 }
10368 if let Some((_, row)) = self.mutable_run.get_version_at(rid, snapshot) {
10369 consider(row);
10370 }
10371 for rr in &self.run_refs {
10372 if let Some(&(min_rid, max_rid)) = self.run_row_id_ranges.get(&rr.run_id) {
10373 if rid.0 < min_rid || rid.0 > max_rid {
10374 continue;
10375 }
10376 }
10377 let Ok(mut reader) = self.open_reader(rr.run_id) else {
10378 continue;
10379 };
10380 let Ok(Some((_stamp, row))) = reader.get_version_stamp_at(rid, snapshot) else {
10384 continue;
10385 };
10386 consider(row);
10387 }
10388 best
10389 }
10390
10391 fn resolve_pk_with_hot_fallback(
10392 &self,
10393 pk_column_id: u16,
10394 lookup: &[u8],
10395 snapshot: Snapshot,
10396 ) -> Result<RowIdSet> {
10397 let snapshot = if self.is_shared()
10410 || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10411 || snapshot.epoch.0 != self.epoch.visible().0
10412 {
10413 snapshot
10414 } else {
10415 Snapshot::at(self.pending_epoch())
10416 };
10417 if !self.indexes_complete {
10421 let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10422 self.record_hot_fallback_reason(crate::trace::HotFallbackReason::IndexIncomplete);
10423 return Ok(result);
10424 }
10425 let mapped = self.hot.get(lookup);
10428 let Some(r) = mapped else {
10429 let (result, reason) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10430 self.record_hot_fallback_reason(reason);
10431 return Ok(result);
10432 };
10433 if snapshot.epoch < self.current_epoch() {
10438 self.record_hot_fallback_reason(crate::trace::HotFallbackReason::HistoricalSnapshot);
10439 let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10440 return Ok(result);
10441 }
10442 let materialized = self.inspect_row_at(r, snapshot);
10446 let now_nanos = unix_nanos_now();
10447 let inspection = crate::trace::inspect_hot_candidate(
10448 materialized.as_ref(),
10449 snapshot,
10450 self.ttl,
10451 now_nanos,
10452 pk_column_id,
10453 lookup,
10454 |row| {
10455 let pk_value = row.columns.get(&pk_column_id);
10456 pk_value
10457 .map(|v| self.index_lookup_key(pk_column_id, v))
10458 .unwrap_or_default()
10459 },
10460 );
10461 match inspection {
10462 crate::trace::HotCandidateInspection::Hit(row) => {
10463 self.lookup_metrics
10464 .hot_lookup_hit
10465 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10466 crate::trace::QueryTrace::record(|t| {
10467 t.hot_lookup_attempted = true;
10468 t.hot_lookup_hit = true;
10469 });
10470 Ok(RowIdSet::one(row.row_id.0))
10471 }
10472 failure => {
10473 let reason = match &failure {
10474 crate::trace::HotCandidateInspection::Hit(_) => unreachable!(),
10475 crate::trace::HotCandidateInspection::MissingRow => {
10476 crate::trace::HotFallbackReason::Tombstone
10481 }
10482 crate::trace::HotCandidateInspection::Invisible => {
10483 crate::trace::HotFallbackReason::InvisibleAtSnapshot
10484 }
10485 crate::trace::HotCandidateInspection::Tombstone => {
10486 crate::trace::HotFallbackReason::Tombstone
10487 }
10488 crate::trace::HotCandidateInspection::TtlExpired => {
10489 crate::trace::HotFallbackReason::TtlExpired
10490 }
10491 crate::trace::HotCandidateInspection::PrimaryKeyMismatch { .. } => {
10492 crate::trace::HotFallbackReason::PrimaryKeyMismatch
10493 }
10494 };
10495 let (result, _inner) = self.pk_equality_fallback(pk_column_id, lookup, snapshot)?;
10501 self.record_hot_fallback_reason(reason);
10502 Ok(result)
10503 }
10504 }
10505 }
10506
10507 fn resolve_condition(
10512 &self,
10513 c: &crate::query::Condition,
10514 snapshot: Snapshot,
10515 ) -> Result<RowIdSet> {
10516 self.resolve_condition_with_allowed(c, snapshot, None)
10517 }
10518
10519 fn resolve_condition_with_allowed(
10520 &self,
10521 c: &crate::query::Condition,
10522 snapshot: Snapshot,
10523 allowed: Option<&std::collections::HashSet<RowId>>,
10524 ) -> Result<RowIdSet> {
10525 use crate::query::Condition;
10526 self.validate_condition(c)?;
10527 Ok(match c {
10528 Condition::Pk(key) => {
10529 let lookup = self
10530 .schema
10531 .primary_key()
10532 .map(|pk| self.index_lookup_key_bytes(pk.id, key))
10533 .unwrap_or_else(|| key.clone());
10534 if let Some(pk_col) = self.schema.primary_key() {
10535 return self.resolve_pk_with_hot_fallback(pk_col.id, &lookup, snapshot);
10536 }
10537 RowIdSet::empty()
10541 }
10542 Condition::BitmapEq { column_id, value } => {
10543 let lookup = self.index_lookup_key_bytes(*column_id, value);
10544 self.bitmap
10545 .get(column_id)
10546 .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
10547 .unwrap_or_else(RowIdSet::empty)
10548 }
10549 Condition::BitmapIn { column_id, values } => {
10550 let bm = self.bitmap.get(column_id);
10551 let mut acc = roaring::RoaringBitmap::new();
10552 if let Some(b) = bm {
10553 for v in values {
10554 let lookup = self.index_lookup_key_bytes(*column_id, v);
10555 acc |= b.get(&lookup);
10556 }
10557 }
10558 RowIdSet::from_roaring(acc)
10559 }
10560 Condition::BytesPrefix { column_id, prefix } => {
10561 if let Some(b) = self.bitmap.get(column_id) {
10566 let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
10567 let mut acc = roaring::RoaringBitmap::new();
10568 for key in b.keys() {
10569 if key.starts_with(&lookup_prefix) {
10570 acc |= b.get(&key);
10571 }
10572 }
10573 RowIdSet::from_roaring(acc)
10574 } else {
10575 RowIdSet::empty()
10576 }
10577 }
10578 Condition::FmContains { column_id, pattern } => self
10579 .fm
10580 .get(column_id)
10581 .map(|f| {
10582 RowIdSet::from_unsorted(f.locate(pattern).into_iter().map(|r| r.0).collect())
10583 })
10584 .unwrap_or_else(RowIdSet::empty),
10585 Condition::FmContainsAll {
10586 column_id,
10587 patterns,
10588 } => {
10589 if let Some(f) = self.fm.get(column_id) {
10592 let sets: Vec<RowIdSet> = patterns
10593 .iter()
10594 .map(|pat| {
10595 RowIdSet::from_unsorted(
10596 f.locate(pat).into_iter().map(|r| r.0).collect(),
10597 )
10598 })
10599 .collect();
10600 RowIdSet::intersect_many(sets)
10601 } else {
10602 RowIdSet::empty()
10603 }
10604 }
10605 Condition::Ann {
10606 column_id,
10607 query,
10608 k,
10609 } => RowIdSet::from_unsorted(
10610 self.retrieve_filtered(
10611 &crate::query::Retriever::Ann {
10612 column_id: *column_id,
10613 query: query.clone(),
10614 k: *k,
10615 },
10616 snapshot,
10617 None,
10618 allowed,
10619 None,
10620 None,
10621 )?
10622 .into_iter()
10623 .map(|hit| hit.row_id.0)
10624 .collect(),
10625 ),
10626 Condition::SparseMatch {
10627 column_id,
10628 query,
10629 k,
10630 } => RowIdSet::from_unsorted(
10631 self.retrieve_filtered(
10632 &crate::query::Retriever::Sparse {
10633 column_id: *column_id,
10634 query: query.clone(),
10635 k: *k,
10636 },
10637 snapshot,
10638 None,
10639 allowed,
10640 None,
10641 None,
10642 )?
10643 .into_iter()
10644 .map(|hit| hit.row_id.0)
10645 .collect(),
10646 ),
10647 Condition::MinHashSimilar {
10648 column_id,
10649 query,
10650 k,
10651 } => match self.minhash.get(column_id) {
10652 Some(index) => {
10653 let candidates = index.candidate_row_ids(query);
10654 let eligible =
10655 self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
10656 RowIdSet::from_unsorted(
10657 index
10658 .search_filtered(query, *k, |row_id| {
10659 eligible.contains(&row_id)
10660 && allowed.is_none_or(|allowed| allowed.contains(&row_id))
10661 })
10662 .into_iter()
10663 .map(|(row_id, _)| row_id.0)
10664 .collect(),
10665 )
10666 }
10667 None => RowIdSet::empty(),
10668 },
10669 Condition::Range { column_id, lo, hi } => {
10670 let mut set = if let Some(li) = self.learned_range.get(column_id) {
10689 if self.run_refs.len() == 1 {
10690 RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
10693 } else {
10694 let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10702 if lo == hi {
10703 self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10704 }
10705 return Ok(multi);
10706 }
10707 } else if self.run_refs.len() == 1 {
10708 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10709 r.range_row_id_set_i64(*column_id, *lo, *hi)?
10710 } else {
10711 let mut multi = self.range_scan_i64(*column_id, *lo, *hi, snapshot)?;
10714 if lo == hi {
10715 self.union_bitmap_point_i64(&mut multi, *column_id, *lo, snapshot);
10716 }
10717 return Ok(multi);
10718 };
10719 if self.learned_range.get(column_id).is_none() && self.run_refs.len() == 1 {
10720 let candidates: Vec<RowId> =
10721 set.into_sorted_vec().into_iter().map(RowId).collect();
10722 set = RowIdSet::from_unsorted(
10723 self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?
10724 .into_iter()
10725 .map(|row_id| row_id.0)
10726 .collect(),
10727 );
10728 }
10729 set.remove_many(self.overlay_rid_set(snapshot));
10730 self.range_scan_overlay_i64(&mut set, *column_id, *lo, *hi, snapshot);
10731 if lo == hi {
10732 self.union_bitmap_point_i64(&mut set, *column_id, *lo, snapshot);
10733 }
10734 RowIdSet::from_unsorted(
10735 set.into_sorted_vec()
10736 .into_iter()
10737 .filter(|row_id| self.get(RowId(*row_id), snapshot).is_some())
10738 .collect(),
10739 )
10740 }
10741 Condition::RangeF64 {
10742 column_id,
10743 lo,
10744 lo_inclusive,
10745 hi,
10746 hi_inclusive,
10747 } => {
10748 let mut set = if let Some(li) = self.learned_range.get(column_id) {
10751 RowIdSet::from_unsorted(
10752 li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
10753 .into_iter()
10754 .collect(),
10755 )
10756 } else if self.run_refs.len() == 1 {
10757 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10758 r.range_row_id_set_f64(*column_id, *lo, *lo_inclusive, *hi, *hi_inclusive)?
10759 } else {
10760 return self.range_scan_f64(
10761 *column_id,
10762 *lo,
10763 *lo_inclusive,
10764 *hi,
10765 *hi_inclusive,
10766 snapshot,
10767 );
10768 };
10769 set.remove_many(self.overlay_rid_set(snapshot));
10770 self.range_scan_overlay_f64(
10771 &mut set,
10772 *column_id,
10773 *lo,
10774 *lo_inclusive,
10775 *hi,
10776 *hi_inclusive,
10777 snapshot,
10778 );
10779 set
10780 }
10781 Condition::IsNull { column_id } => {
10782 let mut set = if self.run_refs.len() == 1 {
10783 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10784 r.null_row_id_set(*column_id, true)?
10785 } else {
10786 return self.null_scan(*column_id, true, snapshot);
10787 };
10788 set.remove_many(self.overlay_rid_set(snapshot));
10789 self.null_scan_overlay(&mut set, *column_id, true, snapshot);
10790 set
10791 }
10792 Condition::IsNotNull { column_id } => {
10793 let mut set = if self.run_refs.len() == 1 {
10794 let mut r = self.open_reader(self.run_refs[0].run_id)?;
10795 r.null_row_id_set(*column_id, false)?
10796 } else {
10797 return self.null_scan(*column_id, false, snapshot);
10798 };
10799 set.remove_many(self.overlay_rid_set(snapshot));
10800 self.null_scan_overlay(&mut set, *column_id, false, snapshot);
10801 set
10802 }
10803 })
10804 }
10805
10806 fn range_scan_i64(
10814 &self,
10815 column_id: u16,
10816 lo: i64,
10817 hi: i64,
10818 snapshot: Snapshot,
10819 ) -> Result<RowIdSet> {
10820 let mut row_ids = Vec::new();
10821 let mut tomb_rids: HashSet<u64> = HashSet::new();
10828 let overlay_rids = self.overlay_rid_set(snapshot);
10829 for rr in &self.run_refs {
10830 let mut reader = self.open_reader(rr.run_id)?;
10831 let matched = reader.range_row_ids_visible_i64_at(column_id, lo, hi, snapshot)?;
10832 for rid in matched {
10833 if !overlay_rids.contains(&rid) {
10834 row_ids.push(rid);
10835 }
10836 }
10837 for rid in reader.tombstoned_row_ids_at(snapshot)? {
10838 tomb_rids.insert(rid);
10839 }
10840 }
10841 let overlay_tombstone_snapshot = if self.is_shared()
10848 || (self.pending_put_cols.is_empty() && self.pending_delete_rids.is_empty())
10849 || snapshot.epoch.0 != self.epoch.visible().0
10850 {
10851 snapshot
10852 } else {
10853 Snapshot::at(self.pending_epoch())
10854 };
10855 for row in self
10856 .memtable
10857 .visible_versions_at(overlay_tombstone_snapshot)
10858 .into_iter()
10859 .chain(
10860 self.mutable_run
10861 .visible_versions_at(overlay_tombstone_snapshot),
10862 )
10863 {
10864 if row.deleted {
10865 tomb_rids.insert(row.row_id.0);
10866 }
10867 }
10868 let mut s = RowIdSet::from_unsorted(row_ids);
10869 s.remove_many(tomb_rids);
10870 let candidates: Vec<RowId> = s.into_sorted_vec().into_iter().map(RowId).collect();
10871 let eligible = self.eligible_candidate_ids(&candidates, column_id, snapshot, None)?;
10872 let mut s = RowIdSet::from_unsorted(eligible.into_iter().map(|row_id| row_id.0).collect());
10873 self.range_scan_overlay_i64(&mut s, column_id, lo, hi, snapshot);
10874 Ok(s)
10875 }
10876
10877 fn range_scan_f64(
10880 &self,
10881 column_id: u16,
10882 lo: f64,
10883 lo_inclusive: bool,
10884 hi: f64,
10885 hi_inclusive: bool,
10886 snapshot: Snapshot,
10887 ) -> Result<RowIdSet> {
10888 let mut row_ids = Vec::new();
10889 let overlay_rids = self.overlay_rid_set(snapshot);
10890 for rr in &self.run_refs {
10891 let mut reader = self.open_reader(rr.run_id)?;
10892 let matched = reader.range_row_ids_visible_f64_at(
10893 column_id,
10894 lo,
10895 lo_inclusive,
10896 hi,
10897 hi_inclusive,
10898 snapshot,
10899 )?;
10900 for rid in matched {
10901 if !overlay_rids.contains(&rid) {
10902 row_ids.push(rid);
10903 }
10904 }
10905 }
10906 let mut s = RowIdSet::from_unsorted(row_ids);
10907 self.range_scan_overlay_f64(
10908 &mut s,
10909 column_id,
10910 lo,
10911 lo_inclusive,
10912 hi,
10913 hi_inclusive,
10914 snapshot,
10915 );
10916 Ok(s)
10917 }
10918
10919 fn overlay_rid_set(&self, snapshot: Snapshot) -> HashSet<u64> {
10921 let mut s = HashSet::new();
10922 for row in self.memtable.visible_versions_at(snapshot) {
10923 s.insert(row.row_id.0);
10924 }
10925 for row in self.mutable_run.visible_versions_at(snapshot) {
10926 s.insert(row.row_id.0);
10927 }
10928 s
10929 }
10930
10931 fn range_scan_overlay_i64(
10932 &self,
10933 s: &mut RowIdSet,
10934 column_id: u16,
10935 lo: i64,
10936 hi: i64,
10937 snapshot: Snapshot,
10938 ) {
10939 let mut newest: HashMap<u64, Row> = HashMap::new();
10946 for r in self.mutable_run.visible_versions_at(snapshot) {
10947 newest.insert(r.row_id.0, r);
10948 }
10949 for r in self.memtable.visible_versions_at(snapshot) {
10950 newest
10951 .entry(r.row_id.0)
10952 .and_modify(|cur| {
10953 if Snapshot::version_is_newer(
10954 r.committed_epoch,
10955 r.commit_ts,
10956 cur.committed_epoch,
10957 cur.commit_ts,
10958 ) {
10959 *cur = r.clone();
10960 }
10961 })
10962 .or_insert(r);
10963 }
10964 for row in newest.values() {
10965 if !row.deleted {
10966 if let Some(Value::Int64(v)) = row.columns.get(&column_id) {
10967 if *v >= lo && *v <= hi && !self.row_expired_at(row, unix_nanos_now()) {
10968 s.insert(row.row_id.0);
10969 }
10970 }
10971 }
10972 }
10973 }
10974
10975 #[allow(clippy::too_many_arguments)]
10976 fn range_scan_overlay_f64(
10977 &self,
10978 s: &mut RowIdSet,
10979 column_id: u16,
10980 lo: f64,
10981 lo_inclusive: bool,
10982 hi: f64,
10983 hi_inclusive: bool,
10984 snapshot: Snapshot,
10985 ) {
10986 let mut newest: HashMap<u64, Row> = HashMap::new();
10989 for r in self.mutable_run.visible_versions_at(snapshot) {
10990 newest.insert(r.row_id.0, r);
10991 }
10992 for r in self.memtable.visible_versions_at(snapshot) {
10993 newest
10994 .entry(r.row_id.0)
10995 .and_modify(|cur| {
10996 if Snapshot::version_is_newer(
10997 r.committed_epoch,
10998 r.commit_ts,
10999 cur.committed_epoch,
11000 cur.commit_ts,
11001 ) {
11002 *cur = r.clone();
11003 }
11004 })
11005 .or_insert(r);
11006 }
11007 for row in newest.values() {
11008 if !row.deleted {
11009 if let Some(Value::Float64(v)) = row.columns.get(&column_id) {
11010 let ok_lo = if lo_inclusive { *v >= lo } else { *v > lo };
11011 let ok_hi = if hi_inclusive { *v <= hi } else { *v < hi };
11012 if ok_lo && ok_hi && !self.row_expired_at(row, unix_nanos_now()) {
11013 s.insert(row.row_id.0);
11014 }
11015 }
11016 }
11017 }
11018 }
11019
11020 fn null_scan(&self, column_id: u16, want_nulls: bool, snapshot: Snapshot) -> Result<RowIdSet> {
11023 let mut row_ids = Vec::new();
11024 let overlay_rids = self.overlay_rid_set(snapshot);
11025 for rr in &self.run_refs {
11026 let mut reader = self.open_reader(rr.run_id)?;
11027 let matched = reader.null_row_ids_visible_at(column_id, want_nulls, snapshot)?;
11028 for rid in matched {
11029 if !overlay_rids.contains(&rid) {
11030 row_ids.push(rid);
11031 }
11032 }
11033 }
11034 let mut s = RowIdSet::from_unsorted(row_ids);
11035 self.null_scan_overlay(&mut s, column_id, want_nulls, snapshot);
11036 Ok(s)
11037 }
11038
11039 fn null_scan_overlay(
11043 &self,
11044 s: &mut RowIdSet,
11045 column_id: u16,
11046 want_nulls: bool,
11047 snapshot: Snapshot,
11048 ) {
11049 let mut newest: HashMap<u64, Row> = HashMap::new();
11050 for r in self.mutable_run.visible_versions_at(snapshot) {
11051 newest.insert(r.row_id.0, r);
11052 }
11053 for r in self.memtable.visible_versions_at(snapshot) {
11054 newest
11055 .entry(r.row_id.0)
11056 .and_modify(|cur| {
11057 if Snapshot::version_is_newer(
11058 r.committed_epoch,
11059 r.commit_ts,
11060 cur.committed_epoch,
11061 cur.commit_ts,
11062 ) {
11063 *cur = r.clone();
11064 }
11065 })
11066 .or_insert(r);
11067 }
11068 for row in newest.values() {
11069 if row.deleted {
11070 continue;
11071 }
11072 let is_null = !row.columns.contains_key(&column_id)
11073 || matches!(row.columns.get(&column_id), Some(Value::Null) | None);
11074 if is_null == want_nulls {
11075 s.insert(row.row_id.0);
11076 }
11077 }
11078 }
11079
11080 pub fn snapshot(&self) -> Snapshot {
11081 let epoch = self.epoch.visible();
11082 match &self.wal {
11086 WalSink::Shared(shared) => match shared.hlc.now() {
11087 Ok(commit_ts) => Snapshot::at_hlc(epoch, commit_ts),
11088 Err(_) => Snapshot::at_hlc(epoch, mongreldb_types::hlc::HlcTimestamp::MAX),
11090 },
11091 WalSink::Private(_) | WalSink::ReadOnly => Snapshot::at(epoch),
11092 }
11093 }
11094
11095 pub fn data_generation(&self) -> u64 {
11097 self.data_generation
11098 }
11099
11100 pub(crate) fn bump_data_generation(&mut self) {
11101 self.data_generation = self.data_generation.wrapping_add(1);
11102 }
11103
11104 pub fn table_id(&self) -> u64 {
11106 self.table_id
11107 }
11108
11109 fn seal_generations(&mut self) {
11115 self.memtable.seal();
11116 self.mutable_run.seal();
11117 self.hot.seal();
11118 for index in self.bitmap.values_mut() {
11119 index.seal();
11120 }
11121 for index in self.ann.values_mut() {
11122 index.seal();
11123 }
11124 for index in self.fm.values_mut() {
11125 index.seal();
11126 }
11127 for index in self.sparse.values_mut() {
11128 index.seal();
11129 }
11130 for index in self.minhash.values_mut() {
11131 index.seal();
11132 }
11133 self.pk_by_row.seal();
11134 }
11135
11136 fn capture_read_generation(&self) -> ReadGeneration {
11141 let visible_through = self.current_epoch();
11142 ReadGeneration {
11143 schema: Arc::new(self.schema.clone()),
11144 base_runs: Arc::new(self.run_refs.clone()),
11145 deltas: TableDeltas {
11146 memtable: self.memtable.clone(),
11147 mutable_run: self.mutable_run.clone(),
11148 hot: self.hot.clone(),
11149 pk_by_row: self.pk_by_row.clone(),
11150 },
11151 indexes: Arc::new(IndexGeneration::capture(
11152 &self.bitmap,
11153 &self.learned_range,
11154 &self.fm,
11155 &self.ann,
11156 &self.sparse,
11157 &self.minhash,
11158 visible_through,
11159 match &self.wal {
11161 WalSink::Shared(shared) => shared
11162 .hlc
11163 .now()
11164 .unwrap_or(mongreldb_types::hlc::HlcTimestamp::MAX),
11165 _ => mongreldb_types::hlc::HlcTimestamp::MAX,
11166 },
11167 )),
11168 visible_through,
11169 }
11170 }
11171
11172 pub fn publish_read_generation(&mut self) -> Result<Arc<ReadGeneration>> {
11177 self.ensure_indexes_complete()?;
11178 self.seal_generations();
11179 let view = Arc::new(self.capture_read_generation());
11180 self.published.store(Arc::clone(&view));
11181 Ok(view)
11182 }
11183
11184 pub fn published_read_generation(&self) -> Arc<ReadGeneration> {
11190 self.published.load_full()
11191 }
11192
11193 pub fn pin_registry(&self) -> &Arc<crate::retention::PinRegistry> {
11195 &self.pins
11196 }
11197
11198 pub fn version_gc_floor(&self) -> Epoch {
11203 self.min_active_snapshot()
11204 .unwrap_or_else(|| self.current_epoch())
11205 }
11206
11207 pub fn version_pins_report(&self) -> crate::retention::PinsReport {
11214 let mut report = self.pins.report();
11215 let transaction_floor = [
11216 self.pinned.keys().next().copied(),
11217 self.snapshots.min_pinned(),
11218 ]
11219 .into_iter()
11220 .flatten()
11221 .min();
11222 if let Some(epoch) = transaction_floor {
11223 report.record_projection(crate::retention::PinSource::TransactionSnapshot, epoch);
11224 }
11225 if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11226 report.record_projection(crate::retention::PinSource::HistoryRetention, floor);
11227 }
11228 report
11229 }
11230
11231 pub(crate) fn clone_read_generation(&mut self) -> Result<Self> {
11232 self.publish_read_generation()?;
11233 let mut generation = self.clone();
11234 generation.read_only = true;
11235 generation.wal = WalSink::ReadOnly;
11236 generation.pending_delete_rids.clear();
11237 generation.pending_put_cols.clear();
11238 generation.pending_rows.clear();
11239 generation.pending_rows_auto_inc.clear();
11240 generation.pending_dels.clear();
11241 generation.pending_truncate = None;
11242 generation.agg_cache = Arc::new(HashMap::new());
11243 generation.published = Arc::new(ArcSwap::new(self.published.load_full()));
11246 generation.read_generation_pin = Some(Arc::new(self.pins.pin(
11249 crate::retention::PinSource::ReadGeneration,
11250 self.current_epoch(),
11251 )));
11252 Ok(generation)
11253 }
11254
11255 pub(crate) fn estimated_clone_bytes(&self) -> u64 {
11256 (std::mem::size_of::<Self>() as u64)
11257 .saturating_add(self.memtable.approx_bytes())
11258 .saturating_add(self.mutable_run.approx_bytes())
11259 .saturating_add(self.live_count.saturating_mul(64))
11260 }
11261
11262 pub fn pin_snapshot(&mut self) -> Snapshot {
11269 let snap = self.snapshot();
11270 *self.pinned.entry(snap.epoch).or_insert(0) += 1;
11271 snap
11272 }
11273
11274 fn active_pin_epochs_for_rebuild(&self) -> Vec<Epoch> {
11286 let mut set = BTreeSet::new();
11287 for epoch in self.pinned.keys().copied() {
11288 set.insert(epoch);
11289 }
11290 for epoch in self.snapshots.live_pinned_epochs() {
11291 set.insert(epoch);
11292 }
11293 for epoch in self.pins.live_pin_epochs() {
11294 set.insert(epoch);
11295 }
11296 if let Some(floor) = self.snapshots.history_floor(self.current_epoch()) {
11297 set.insert(floor);
11298 }
11299 set.into_iter().collect()
11300 }
11301
11302 pub fn hlc_gc_floor(
11312 &self,
11313 mut project_epoch: impl FnMut(Epoch) -> Option<mongreldb_types::hlc::HlcTimestamp>,
11314 ) -> crate::epoch::GcFloor {
11315 let mut project = |epoch: Option<Epoch>| -> mongreldb_types::hlc::HlcTimestamp {
11316 epoch
11317 .and_then(&mut project_epoch)
11318 .filter(|ts| *ts != mongreldb_types::hlc::HlcTimestamp::ZERO)
11319 .unwrap_or(mongreldb_types::hlc::HlcTimestamp::ZERO)
11320 };
11321 let transaction = [
11322 self.pinned.keys().next().copied(),
11323 self.snapshots.min_pinned(),
11324 ]
11325 .into_iter()
11326 .flatten()
11327 .min();
11328 let history = self.snapshots.history_floor(self.current_epoch());
11329 crate::epoch::GcFloor {
11330 transaction_snapshot: project(transaction),
11331 history_retention: project(history),
11332 backup_pitr: project(
11333 self.pins
11334 .oldest_for(crate::retention::PinSource::BackupPitr),
11335 ),
11336 replication: project(
11337 self.pins
11338 .oldest_for(crate::retention::PinSource::Replication),
11339 ),
11340 read_generation: project(
11341 self.pins
11342 .oldest_for(crate::retention::PinSource::ReadGeneration),
11343 ),
11344 online_index_build: project(
11345 self.pins
11346 .oldest_for(crate::retention::PinSource::OnlineIndexBuild),
11347 ),
11348 }
11349 }
11350
11351 pub fn unpin_snapshot(&mut self, snap: Snapshot) {
11353 if let Some(count) = self.pinned.get_mut(&snap.epoch) {
11354 *count -= 1;
11355 if *count == 0 {
11356 self.pinned.remove(&snap.epoch);
11357 }
11358 }
11359 }
11360
11361 pub(crate) fn min_active_snapshot(&self) -> Option<Epoch> {
11373 let local = self.pinned.keys().next().copied();
11374 let global = self.snapshots.min_pinned();
11375 let history = self.snapshots.history_floor(self.current_epoch());
11376 let pinned = self.pins.oldest_pinned();
11377 [local, global, history, pinned].into_iter().flatten().min()
11378 }
11379
11380 pub fn set_ttl(&mut self, column_name: &str, duration_nanos: u64) -> Result<()> {
11384 self.ensure_writable()?;
11385 let policy = self.prepare_ttl_policy(column_name, duration_nanos)?;
11386 self.apply_ttl_policy_at(Some(policy), self.current_epoch())
11387 }
11388
11389 pub fn clear_ttl(&mut self) -> Result<()> {
11390 self.ensure_writable()?;
11391 self.apply_ttl_policy_at(None, self.current_epoch())
11392 }
11393
11394 pub fn ttl(&self) -> Option<TtlPolicy> {
11395 self.ttl
11396 }
11397
11398 pub(crate) fn prepare_ttl_policy(
11399 &self,
11400 column_name: &str,
11401 duration_nanos: u64,
11402 ) -> Result<TtlPolicy> {
11403 if duration_nanos == 0 || duration_nanos > i64::MAX as u64 {
11404 return Err(MongrelError::InvalidArgument(
11405 "TTL duration must be between 1 and i64::MAX nanoseconds".into(),
11406 ));
11407 }
11408 let column = self
11409 .schema
11410 .columns
11411 .iter()
11412 .find(|column| column.name == column_name)
11413 .ok_or_else(|| MongrelError::Schema(format!("unknown TTL column {column_name}")))?;
11414 if column.ty != TypeId::TimestampNanos {
11415 return Err(MongrelError::Schema(format!(
11416 "TTL column {column_name} must be TimestampNanos, is {:?}",
11417 column.ty
11418 )));
11419 }
11420 Ok(TtlPolicy {
11421 column_id: column.id,
11422 duration_nanos,
11423 })
11424 }
11425
11426 pub(crate) fn apply_ttl_policy_at(
11427 &mut self,
11428 policy: Option<TtlPolicy>,
11429 epoch: Epoch,
11430 ) -> Result<()> {
11431 if let Some(policy) = policy {
11432 let column = self
11433 .schema
11434 .columns
11435 .iter()
11436 .find(|column| column.id == policy.column_id)
11437 .ok_or_else(|| {
11438 MongrelError::Schema(format!("unknown TTL column id {}", policy.column_id))
11439 })?;
11440 if column.ty != TypeId::TimestampNanos
11441 || policy.duration_nanos == 0
11442 || policy.duration_nanos > i64::MAX as u64
11443 {
11444 return Err(MongrelError::Schema("invalid TTL policy".into()));
11445 }
11446 }
11447 self.ttl = policy;
11448 self.agg_cache = Arc::new(HashMap::new());
11449 self.clear_result_cache();
11450 let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
11451 self.persist_manifest(epoch)
11452 }
11453
11454 pub(crate) fn row_expired_at(&self, row: &Row, now_nanos: i64) -> bool {
11455 let Some(policy) = self.ttl else {
11456 return false;
11457 };
11458 let Some(Value::Int64(timestamp)) = row.columns.get(&policy.column_id) else {
11459 return false;
11460 };
11461 timestamp.saturating_add(policy.duration_nanos as i64) <= now_nanos
11462 }
11463
11464 pub fn current_epoch(&self) -> Epoch {
11465 self.epoch.visible()
11466 }
11467
11468 pub fn memtable_len(&self) -> usize {
11469 self.memtable.len()
11470 }
11471
11472 pub fn count(&self) -> u64 {
11475 if self.ttl.is_none()
11476 && self.pending_put_cols.is_empty()
11477 && self.pending_delete_rids.is_empty()
11478 && self.pending_rows.is_empty()
11479 && self.pending_dels.is_empty()
11480 && self.pending_truncate.is_none()
11481 {
11482 self.live_count
11483 } else {
11484 self.visible_rows(self.snapshot())
11485 .map(|rows| rows.len() as u64)
11486 .unwrap_or(self.live_count)
11487 }
11488 }
11489
11490 pub fn count_conditions(
11494 &mut self,
11495 conditions: &[crate::query::Condition],
11496 snapshot: Snapshot,
11497 ) -> Result<Option<u64>> {
11498 use crate::query::Condition;
11499 if self.ttl.is_some() {
11500 if conditions.is_empty() {
11501 return Ok(Some(self.visible_rows(snapshot)?.len() as u64));
11502 }
11503 let mut sets = Vec::with_capacity(conditions.len());
11504 for condition in conditions {
11505 sets.push(self.resolve_condition(condition, snapshot)?);
11506 }
11507 let survivors = RowIdSet::intersect_many(sets);
11508 let rows = self.visible_rows(snapshot)?;
11509 return Ok(Some(
11510 rows.into_iter()
11511 .filter(|row| survivors.contains(row.row_id.0))
11512 .count() as u64,
11513 ));
11514 }
11515 if conditions.is_empty() {
11516 return Ok(Some(self.count()));
11517 }
11518 let served = |c: &Condition| {
11519 matches!(
11520 c,
11521 Condition::Pk(_)
11522 | Condition::BitmapEq { .. }
11523 | Condition::BitmapIn { .. }
11524 | Condition::BytesPrefix { .. }
11525 | Condition::FmContains { .. }
11526 | Condition::FmContainsAll { .. }
11527 | Condition::Ann { .. }
11528 | Condition::Range { .. }
11529 | Condition::RangeF64 { .. }
11530 | Condition::SparseMatch { .. }
11531 | Condition::MinHashSimilar { .. }
11532 | Condition::IsNull { .. }
11533 | Condition::IsNotNull { .. }
11534 )
11535 };
11536 if !conditions.iter().all(served) {
11537 return Ok(None);
11538 }
11539 self.ensure_indexes_complete()?;
11540 if !self.pending_put_cols.is_empty()
11541 || !self.pending_delete_rids.is_empty()
11542 || !self.pending_rows.is_empty()
11543 || !self.pending_dels.is_empty()
11544 || self.pending_truncate.is_some()
11545 {
11546 let mut sets = Vec::with_capacity(conditions.len());
11547 for condition in conditions {
11548 sets.push(self.resolve_condition(condition, snapshot)?);
11549 }
11550 let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
11551 return Ok(Some(self.rows_for_rids(&rids, snapshot)?.len() as u64));
11552 }
11553 let mut sets = Vec::with_capacity(conditions.len());
11554 for condition in conditions {
11555 sets.push(self.resolve_condition(condition, snapshot)?);
11556 }
11557 let rids = RowIdSet::intersect_many(sets);
11558 if self.had_deletes || !self.memtable.is_empty() || !self.mutable_run.is_empty() {
11566 let sorted = rids.into_sorted_vec();
11567 let count = self.rows_for_rids(&sorted, snapshot)?.len() as u64;
11568 crate::trace::QueryTrace::record(|t| {
11569 t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11570 t.survivor_count = Some(count as usize);
11571 t.conditions_pushed = conditions.len();
11572 });
11573 return Ok(Some(count));
11574 }
11575 let count = rids.len() as u64;
11576 crate::trace::QueryTrace::record(|t| {
11577 t.scan_mode = crate::trace::ScanMode::CountSurvivors;
11578 t.survivor_count = Some(count as usize);
11579 t.conditions_pushed = conditions.len();
11580 });
11581 Ok(Some(count))
11582 }
11583
11584 fn overlay_tombstoned_rids(&self, snapshot: Snapshot) -> Vec<u64> {
11590 let mut out = Vec::new();
11591 for row in self.memtable.visible_versions_at(snapshot) {
11592 if row.deleted {
11593 out.push(row.row_id.0);
11594 }
11595 }
11596 for row in self.mutable_run.visible_versions_at(snapshot) {
11597 if row.deleted {
11598 out.push(row.row_id.0);
11599 }
11600 }
11601 out
11602 }
11603
11604 pub fn bulk_load_columns(
11613 &mut self,
11614 user_columns: Vec<(u16, columnar::NativeColumn)>,
11615 ) -> Result<Epoch> {
11616 self.bulk_load_columns_with(user_columns, 3, false, true)
11617 }
11618
11619 pub fn bulk_load_fast(
11626 &mut self,
11627 user_columns: Vec<(u16, columnar::NativeColumn)>,
11628 ) -> Result<Epoch> {
11629 self.bulk_load_columns_with(user_columns, -1, true, false)
11630 }
11631
11632 fn bulk_load_columns_with(
11633 &mut self,
11634 mut user_columns: Vec<(u16, columnar::NativeColumn)>,
11635 zstd_level: i32,
11636 force_plain: bool,
11637 lz4: bool,
11638 ) -> Result<Epoch> {
11639 self.ensure_writable()?;
11640 let n = user_columns.first().map(|(_, c)| c.len()).unwrap_or(0);
11641 if n == 0 {
11642 return Ok(self.current_epoch());
11643 }
11644 let epoch = self.commit_new_epoch()?;
11645 let live_before = self.live_count;
11646 self.spill_mutable_run(epoch)?;
11648 let eager_index_build = self.index_build_policy == IndexBuildPolicy::Eager
11649 && self.indexes_complete
11650 && self.run_refs.is_empty()
11651 && self.memtable.is_empty()
11652 && self.mutable_run.is_empty();
11653 self.fill_auto_inc_native_columns(&mut user_columns, n)?;
11656 self.validate_columns_not_null(&user_columns, n)?;
11657 let winner_idx = self
11658 .bulk_pk_winner_indices(&user_columns, n)
11659 .filter(|idx| idx.len() != n);
11660 let (write_columns, write_n): (Vec<(u16, columnar::NativeColumn)>, usize) =
11661 match winner_idx.as_deref() {
11662 Some(idx) => {
11663 let compacted = user_columns
11664 .iter()
11665 .map(|(id, c)| (*id, c.gather(idx)))
11666 .collect();
11667 (compacted, idx.len())
11668 }
11669 None => (user_columns, n),
11670 };
11671 self.advance_auto_inc_from_native_columns(&write_columns, write_n, live_before)?;
11672 let first = self.allocator.alloc_range(write_n as u64)?.0;
11673 for rid in first..first + write_n as u64 {
11674 self.reservoir.offer(rid);
11675 }
11676 let run_id = self.alloc_run_id()?;
11677 let path = self.run_path(run_id);
11678 let mut writer =
11679 RunWriter::new(&self.schema, run_id as u128, epoch, 0).with_native_endian();
11680 if force_plain {
11681 writer = writer.with_plain();
11682 } else if lz4 {
11683 writer = writer.with_lz4();
11686 } else {
11687 writer = writer.with_zstd_level(zstd_level);
11688 }
11689 if let Some(kek) = &self.kek {
11690 writer = writer.with_encryption(kek.as_ref(), self.indexable_column_specs());
11691 }
11692 let header = match self.create_run_file(run_id)? {
11693 Some(file) => writer.write_native_file(file, &write_columns, write_n, first)?,
11694 None => writer.write_native(&path, &write_columns, write_n, first)?,
11695 };
11696 self.run_refs.push(RunRef {
11697 run_id: run_id as u128,
11698 level: 0,
11699 epoch_created: epoch.0,
11700 row_count: header.row_count,
11701 });
11702 self.run_row_id_ranges
11703 .insert(run_id as u128, (header.min_row_id, header.max_row_id));
11704 self.live_count = self.live_count.saturating_add(write_n as u64);
11705 if eager_index_build {
11706 let row_ids: Vec<u64> = (first..first + write_n as u64).collect();
11707 self.index_columns_bulk(&write_columns, &row_ids);
11708 self.indexes_complete = true;
11709 self.build_learned_ranges()?;
11710 } else {
11711 self.indexes_complete = false;
11715 }
11716 self.mark_flushed(epoch)?;
11717 self.persist_manifest(epoch)?;
11718 if eager_index_build {
11719 self.checkpoint_indexes(epoch);
11720 }
11721 self.clear_result_cache();
11722 self.data_generation = self.data_generation.wrapping_add(1);
11723 Ok(epoch)
11724 }
11725
11726 fn index_columns_bulk(&mut self, columns: &[(u16, columnar::NativeColumn)], row_ids: &[u64]) {
11744 let n = row_ids.len();
11745 if n == 0 {
11746 return;
11747 }
11748 let by_id: std::collections::HashMap<u16, &columnar::NativeColumn> =
11749 columns.iter().map(|(id, c)| (*id, c)).collect();
11750 let ty_of: std::collections::HashMap<u16, TypeId> = self
11751 .schema
11752 .columns
11753 .iter()
11754 .map(|c| (c.id, c.ty.clone()))
11755 .collect();
11756 let pk_id = self.schema.primary_key().map(|c| c.id);
11757
11758 for (i, &rid) in row_ids.iter().enumerate() {
11759 let row_id = RowId(rid);
11760 if let Some(pid) = pk_id {
11761 if let Some(col) = by_id.get(&pid) {
11762 let ty = ty_of.get(&pid).cloned().unwrap_or(TypeId::Int64);
11763 if let Some(key) = bulk_index_key(&self.column_keys, pid, ty, col, i) {
11764 self.insert_hot_pk(key, row_id);
11765 }
11766 }
11767 }
11768 for idef in &self.schema.indexes {
11769 let Some(col) = by_id.get(&idef.column_id) else {
11770 continue;
11771 };
11772 let ty = ty_of.get(&idef.column_id).cloned().unwrap_or(TypeId::Int64);
11773 match idef.kind {
11774 IndexKind::Bitmap => {
11775 if let Some(b) = self.bitmap.get_mut(&idef.column_id) {
11776 if let Some(key) =
11777 bulk_index_key(&self.column_keys, idef.column_id, ty, col, i)
11778 {
11779 b.insert(key, row_id);
11780 }
11781 }
11782 }
11783 IndexKind::FmIndex => {
11784 if let Some(f) = self.fm.get_mut(&idef.column_id) {
11785 if let Some(bytes) = columnar::native_bytes_at(col, i) {
11786 f.insert(bytes.to_vec(), row_id);
11787 }
11788 }
11789 }
11790 IndexKind::Sparse => {
11791 if let Some(s) = self.sparse.get_mut(&idef.column_id) {
11792 if let Some(bytes) = columnar::native_bytes_at(col, i) {
11793 if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(bytes) {
11794 s.insert(&terms, row_id);
11795 }
11796 }
11797 }
11798 }
11799 IndexKind::MinHash => {
11800 if let Some(mh) = self.minhash.get_mut(&idef.column_id) {
11801 if let Some(bytes) = columnar::native_bytes_at(col, i) {
11802 let tokens = crate::index::token_hashes_from_bytes(bytes);
11803 mh.insert(&tokens, row_id);
11804 }
11805 }
11806 }
11807 _ => {}
11808 }
11809 }
11810 }
11811 }
11812
11813 pub fn visible_columns_native(
11818 &self,
11819 snapshot: Snapshot,
11820 projection: Option<&[u16]>,
11821 ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11822 self.visible_columns_native_inner(snapshot, projection, None)
11823 }
11824
11825 pub fn visible_columns_native_with_control(
11826 &self,
11827 snapshot: Snapshot,
11828 projection: Option<&[u16]>,
11829 control: &crate::ExecutionControl,
11830 ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11831 self.visible_columns_native_inner(snapshot, projection, Some(control))
11832 }
11833
11834 fn visible_columns_native_inner(
11835 &self,
11836 snapshot: Snapshot,
11837 projection: Option<&[u16]>,
11838 control: Option<&crate::ExecutionControl>,
11839 ) -> Result<Vec<(u16, columnar::NativeColumn)>> {
11840 execution_checkpoint(control, 0)?;
11841 let wanted: Vec<u16> = match projection {
11842 Some(p) => p.to_vec(),
11843 None => self.schema.columns.iter().map(|c| c.id).collect(),
11844 };
11845 if self.ttl.is_none()
11846 && self.memtable.is_empty()
11847 && self.mutable_run.is_empty()
11848 && self.run_refs.len() == 1
11849 {
11850 let rr = self.run_refs[0].clone();
11851 let mut reader = self.open_reader(rr.run_id)?;
11852 let idxs = reader.visible_indices_native_at(snapshot)?;
11853 execution_checkpoint(control, 0)?;
11854 let all_visible = idxs.len() == reader.row_count();
11855 if reader.has_mmap() && control.is_none() {
11861 use rayon::prelude::*;
11862 let valid: Vec<u16> = wanted
11865 .iter()
11866 .filter(|cid| self.schema.columns.iter().any(|c| c.id == **cid))
11867 .copied()
11868 .collect();
11869 let decoded: Vec<(u16, columnar::NativeColumn)> = valid
11871 .par_iter()
11872 .filter_map(|cid| {
11873 reader
11874 .column_native_shared(*cid)
11875 .ok()
11876 .map(|col| (*cid, col))
11877 })
11878 .collect();
11879 let cols = decoded
11880 .into_iter()
11881 .map(|(id, col)| (id, if all_visible { col } else { col.gather(&idxs) }))
11882 .collect();
11883 return Ok(cols);
11884 }
11885 let mut cols = Vec::with_capacity(wanted.len());
11886 for (index, cid) in wanted.iter().enumerate() {
11887 execution_checkpoint(control, index)?;
11888 let cdef = match self.schema.columns.iter().find(|c| c.id == *cid) {
11889 Some(c) => c,
11890 None => continue,
11891 };
11892 let col = reader.column_native(cdef.id)?;
11893 cols.push((cdef.id, if all_visible { col } else { col.gather(&idxs) }));
11894 }
11895 return Ok(cols);
11896 }
11897 let vcols = self.visible_columns(snapshot)?;
11898 execution_checkpoint(control, 0)?;
11899 let want_set: std::collections::HashSet<u16> = wanted.iter().copied().collect();
11900 let out: Vec<(u16, columnar::NativeColumn)> = vcols
11901 .into_iter()
11902 .filter(|(id, _)| want_set.contains(id))
11903 .map(|(id, vals)| {
11904 let ty = self
11905 .schema
11906 .columns
11907 .iter()
11908 .find(|c| c.id == id)
11909 .map(|c| c.ty.clone())
11910 .unwrap_or(TypeId::Bytes);
11911 (id, columnar::values_to_native(ty, &vals))
11912 })
11913 .collect();
11914 Ok(out)
11915 }
11916
11917 pub fn run_count(&self) -> usize {
11918 self.run_refs.len()
11919 }
11920
11921 pub fn memtable_is_empty(&self) -> bool {
11923 self.memtable.is_empty()
11924 }
11925
11926 pub fn page_cache_stats(&self) -> crate::cache::CacheStats {
11930 self.page_cache.stats()
11931 }
11932
11933 pub fn reset_page_cache_stats(&self) {
11935 self.page_cache.reset_stats();
11936 }
11937
11938 pub fn run_ids(&self) -> Vec<u128> {
11941 self.run_refs.iter().map(|r| r.run_id).collect()
11942 }
11943
11944 pub fn single_run_is_clean(&self) -> bool {
11948 if self.ttl.is_some() || self.run_refs.len() != 1 {
11949 return false;
11950 }
11951 self.open_reader(self.run_refs[0].run_id)
11952 .map(|r| r.is_clean())
11953 .unwrap_or(false)
11954 }
11955
11956 fn resolve_footprint(
11963 &self,
11964 conditions: &[crate::query::Condition],
11965 snapshot: Snapshot,
11966 ) -> roaring::RoaringBitmap {
11967 if !self.memtable.is_empty() || !self.mutable_run.is_empty() {
11968 return roaring::RoaringBitmap::new();
11969 }
11970 if self.run_refs.is_empty() {
11971 return roaring::RoaringBitmap::new();
11972 }
11973 if self.run_refs.len() == 1 {
11975 if let Ok(mut reader) = self.open_reader(self.run_refs[0].run_id) {
11976 if let Ok(rids) = self.resolve_survivor_rids(conditions, &mut reader, snapshot) {
11977 return rids.to_roaring_lossy();
11978 }
11979 }
11980 }
11981 roaring::RoaringBitmap::new()
11982 }
11983
11984 pub fn query_columns_native_cached(
11995 &mut self,
11996 conditions: &[crate::query::Condition],
11997 projection: Option<&[u16]>,
11998 snapshot: Snapshot,
11999 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12000 self.query_columns_native_cached_inner(conditions, projection, snapshot, None)
12001 }
12002
12003 pub fn query_columns_native_cached_with_control(
12004 &mut self,
12005 conditions: &[crate::query::Condition],
12006 projection: Option<&[u16]>,
12007 snapshot: Snapshot,
12008 control: &crate::ExecutionControl,
12009 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12010 self.query_columns_native_cached_inner(conditions, projection, snapshot, Some(control))
12011 }
12012
12013 fn query_columns_native_cached_inner(
12014 &mut self,
12015 conditions: &[crate::query::Condition],
12016 projection: Option<&[u16]>,
12017 snapshot: Snapshot,
12018 control: Option<&crate::ExecutionControl>,
12019 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12020 execution_checkpoint(control, 0)?;
12021 if self.ttl.is_some() {
12024 return self.query_columns_native_inner(conditions, projection, snapshot, control);
12025 }
12026 if conditions.is_empty() {
12027 return self.query_columns_native_inner(conditions, projection, snapshot, control);
12028 }
12029 let key = crate::query::canonical_query_key(conditions, projection, snapshot.epoch.0);
12033 let identity = PersistentCacheIdentity {
12034 table_id: self.table_id(),
12035 schema_id: self.schema.schema_id,
12036 logical_generation: self.current_epoch().0,
12037 };
12038 if let Some(hit) = self.result_cache.lock().get_columns(key, identity) {
12039 crate::trace::QueryTrace::record(|t| {
12040 t.result_cache_hit = true;
12041 t.scan_mode = crate::trace::ScanMode::NativePushdown;
12042 });
12043 return Ok(Some((*hit).clone()));
12044 }
12045 let res = self.query_columns_native_inner(conditions, projection, snapshot, control)?;
12046 execution_checkpoint(control, 0)?;
12047 if let Some(cols) = &res {
12048 let footprint = self.resolve_footprint(conditions, snapshot);
12049 let condition_cols = crate::query::condition_columns(conditions);
12050 execution_checkpoint(control, 0)?;
12051 let entry = CachedEntry {
12052 data: CachedData::Columns(Arc::new(cols.clone())),
12053 footprint,
12054 condition_cols,
12055 };
12056 let mut cache = self.result_cache.lock();
12062 let entry_generation = cache.allocate_persist_generation(key);
12063 let context = PersistContext {
12064 identity,
12065 key,
12066 entry_generation,
12067 };
12068 cache.persist_entry(context, &entry);
12069 cache.insert(key, entry);
12070 }
12071 Ok(res)
12072 }
12073
12074 pub fn query_cached(&mut self, q: &crate::query::Query) -> Result<Vec<Row>> {
12079 if self.ttl.is_some() {
12080 return self.query(q);
12081 }
12082 if q.conditions.is_empty() {
12083 return self.query(q);
12084 }
12085 let key = crate::query::canonical_query_key(&q.conditions, None, 0)
12086 ^ (q.limit.unwrap_or(usize::MAX) as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
12087 ^ (q.offset as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
12088 let identity = PersistentCacheIdentity {
12089 table_id: self.table_id(),
12090 schema_id: self.schema.schema_id,
12091 logical_generation: self.current_epoch().0,
12092 };
12093 if let Some(hit) = self.result_cache.lock().get_rows(key, identity) {
12094 crate::trace::QueryTrace::record(|t| {
12095 t.result_cache_hit = true;
12096 t.scan_mode = crate::trace::ScanMode::Materialized;
12097 });
12098 return Ok((*hit).clone());
12099 }
12100 let rows = self.query(q)?;
12101 let footprint = rows.iter().map(|r| r.row_id.0 as u32).collect();
12102 let condition_cols = crate::query::condition_columns(&q.conditions);
12103 let entry = CachedEntry {
12104 data: CachedData::Rows(Arc::new(rows.clone())),
12105 footprint,
12106 condition_cols,
12107 };
12108 let mut cache = self.result_cache.lock();
12113 let entry_generation = cache.allocate_persist_generation(key);
12114 let context = PersistContext {
12115 identity,
12116 key,
12117 entry_generation,
12118 };
12119 cache.persist_entry(context, &entry);
12120 cache.insert(key, entry);
12121 Ok(rows)
12122 }
12123
12124 #[allow(clippy::type_complexity)]
12139 pub fn query_columns_native_traced(
12140 &mut self,
12141 conditions: &[crate::query::Condition],
12142 projection: Option<&[u16]>,
12143 snapshot: Snapshot,
12144 ) -> Result<(
12145 Option<Vec<(u16, columnar::NativeColumn)>>,
12146 crate::trace::QueryTrace,
12147 )> {
12148 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12149 self.query_columns_native(conditions, projection, snapshot)
12150 });
12151 Ok((result?, trace))
12152 }
12153
12154 #[allow(clippy::type_complexity)]
12157 pub fn query_columns_native_cached_traced(
12158 &mut self,
12159 conditions: &[crate::query::Condition],
12160 projection: Option<&[u16]>,
12161 snapshot: Snapshot,
12162 ) -> Result<(
12163 Option<Vec<(u16, columnar::NativeColumn)>>,
12164 crate::trace::QueryTrace,
12165 )> {
12166 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12167 self.query_columns_native_cached(conditions, projection, snapshot)
12168 });
12169 Ok((result?, trace))
12170 }
12171
12172 pub fn native_page_cursor_traced(
12174 &self,
12175 snapshot: Snapshot,
12176 projection: Vec<(u16, TypeId)>,
12177 conditions: &[crate::query::Condition],
12178 ) -> Result<(Option<NativePageCursor>, crate::trace::QueryTrace)> {
12179 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12180 self.native_page_cursor(snapshot, projection, conditions)
12181 });
12182 Ok((result?, trace))
12183 }
12184
12185 pub fn native_multi_run_cursor_traced(
12187 &self,
12188 snapshot: Snapshot,
12189 projection: Vec<(u16, TypeId)>,
12190 conditions: &[crate::query::Condition],
12191 ) -> Result<(
12192 Option<crate::cursor::MultiRunCursor>,
12193 crate::trace::QueryTrace,
12194 )> {
12195 let (result, trace) = crate::trace::QueryTrace::capture(|| {
12196 self.native_multi_run_cursor(snapshot, projection, conditions)
12197 });
12198 Ok((result?, trace))
12199 }
12200
12201 pub fn count_conditions_traced(
12203 &mut self,
12204 conditions: &[crate::query::Condition],
12205 snapshot: Snapshot,
12206 ) -> Result<(Option<u64>, crate::trace::QueryTrace)> {
12207 let (result, trace) =
12208 crate::trace::QueryTrace::capture(|| self.count_conditions(conditions, snapshot));
12209 Ok((result?, trace))
12210 }
12211
12212 pub fn query_traced(
12214 &mut self,
12215 q: &crate::query::Query,
12216 ) -> Result<(Vec<Row>, crate::trace::QueryTrace)> {
12217 let (result, trace) = crate::trace::QueryTrace::capture(|| self.query(q));
12218 Ok((result?, trace))
12219 }
12220
12221 pub fn query_columns_native(
12226 &mut self,
12227 conditions: &[crate::query::Condition],
12228 projection: Option<&[u16]>,
12229 snapshot: Snapshot,
12230 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12231 self.query_columns_native_inner(conditions, projection, snapshot, None)
12232 }
12233
12234 pub fn query_columns_native_with_control(
12235 &mut self,
12236 conditions: &[crate::query::Condition],
12237 projection: Option<&[u16]>,
12238 snapshot: Snapshot,
12239 control: &crate::ExecutionControl,
12240 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12241 self.query_columns_native_inner(conditions, projection, snapshot, Some(control))
12242 }
12243
12244 fn query_columns_native_inner(
12245 &mut self,
12246 conditions: &[crate::query::Condition],
12247 projection: Option<&[u16]>,
12248 snapshot: Snapshot,
12249 control: Option<&crate::ExecutionControl>,
12250 ) -> Result<Option<Vec<(u16, columnar::NativeColumn)>>> {
12251 use crate::query::Condition;
12252 execution_checkpoint(control, 0)?;
12253 if self.ttl.is_some() {
12256 return Ok(None);
12257 }
12258 if conditions.is_empty() {
12259 return Ok(None);
12260 }
12261 self.ensure_indexes_complete()?;
12262
12263 let served = |c: &Condition| {
12268 matches!(
12269 c,
12270 Condition::Pk(_)
12271 | Condition::BitmapEq { .. }
12272 | Condition::BitmapIn { .. }
12273 | Condition::BytesPrefix { .. }
12274 | Condition::FmContains { .. }
12275 | Condition::FmContainsAll { .. }
12276 | Condition::Ann { .. }
12277 | Condition::Range { .. }
12278 | Condition::RangeF64 { .. }
12279 | Condition::SparseMatch { .. }
12280 | Condition::MinHashSimilar { .. }
12281 | Condition::IsNull { .. }
12282 | Condition::IsNotNull { .. }
12283 )
12284 };
12285 if !conditions.iter().all(served) {
12286 return Ok(None);
12287 }
12288 let fast_path =
12289 self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
12290 crate::trace::QueryTrace::record(|t| {
12291 t.run_count = self.run_refs.len();
12292 t.memtable_rows = self.memtable.len();
12293 t.mutable_run_rows = self.mutable_run.len();
12294 t.conditions_pushed = conditions.len();
12295 t.learned_range_used = conditions.iter().any(|c| match c {
12296 Condition::Range { column_id, .. } | Condition::RangeF64 { column_id, .. } => {
12297 self.learned_range.contains_key(column_id)
12298 }
12299 _ => false,
12300 });
12301 });
12302 let col_ids: Vec<u16> = projection
12304 .map(|p| p.to_vec())
12305 .unwrap_or_else(|| self.schema.columns.iter().map(|c| c.id).collect());
12306 let proj_pairs: Vec<(u16, TypeId)> = col_ids
12307 .iter()
12308 .map(|&cid| {
12309 let ty = self
12310 .schema
12311 .columns
12312 .iter()
12313 .find(|c| c.id == cid)
12314 .map(|c| c.ty.clone())
12315 .unwrap_or(TypeId::Bytes);
12316 (cid, ty)
12317 })
12318 .collect();
12319
12320 if fast_path {
12326 let needs_column = conditions.iter().any(|c| match c {
12329 Condition::Range { column_id, .. } => !self.learned_range.contains_key(column_id),
12330 Condition::RangeF64 { column_id, .. } => {
12331 !self.learned_range.contains_key(column_id)
12332 }
12333 _ => false,
12334 });
12335 let mut reader_opt: Option<RunReader> = if needs_column {
12336 Some(self.open_reader(self.run_refs[0].run_id)?)
12337 } else {
12338 None
12339 };
12340 let mut sets: Vec<RowIdSet> = Vec::new();
12341 for (index, c) in conditions.iter().enumerate() {
12342 execution_checkpoint(control, index)?;
12343 let s = match c {
12344 Condition::Range { column_id, lo, hi }
12345 if !self.learned_range.contains_key(column_id) =>
12346 {
12347 if reader_opt.is_none() {
12348 reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12349 }
12350 reader_opt
12351 .as_mut()
12352 .expect("reader opened for range")
12353 .range_row_id_set_i64(*column_id, *lo, *hi)?
12354 }
12355 Condition::RangeF64 {
12356 column_id,
12357 lo,
12358 lo_inclusive,
12359 hi,
12360 hi_inclusive,
12361 } if !self.learned_range.contains_key(column_id) => {
12362 if reader_opt.is_none() {
12363 reader_opt = Some(self.open_reader(self.run_refs[0].run_id)?);
12364 }
12365 reader_opt
12366 .as_mut()
12367 .expect("reader opened for range")
12368 .range_row_id_set_f64(
12369 *column_id,
12370 *lo,
12371 *lo_inclusive,
12372 *hi,
12373 *hi_inclusive,
12374 )?
12375 }
12376 _ => self.resolve_condition(c, snapshot)?,
12377 };
12378 sets.push(s);
12379 }
12380 let candidates = RowIdSet::intersect_many(sets);
12381 crate::trace::QueryTrace::record(|t| {
12382 t.survivor_count = Some(candidates.len());
12383 });
12384 if candidates.is_empty() {
12385 let cols: Vec<(u16, columnar::NativeColumn)> = col_ids
12386 .iter()
12387 .map(|&id| {
12388 (
12389 id,
12390 columnar::null_native(
12391 proj_pairs
12392 .iter()
12393 .find(|(c, _)| c == &id)
12394 .map(|(_, t)| t.clone())
12395 .unwrap_or(TypeId::Bytes),
12396 0,
12397 ),
12398 )
12399 })
12400 .collect();
12401 return Ok(Some(cols));
12402 }
12403 let mut reader = match reader_opt.take() {
12404 Some(r) => r,
12405 None => self.open_reader(self.run_refs[0].run_id)?,
12406 };
12407 let candidate_ids = candidates.into_sorted_vec();
12408 let (positions, fast_rid) = if let Some(positions) =
12409 reader.positions_for_row_ids_fast(&candidate_ids)
12410 {
12411 (positions, true)
12412 } else {
12413 let col = reader.column_native(crate::sorted_run::SYS_ROW_ID)?;
12414 match col {
12415 columnar::NativeColumn::Int64 { data, .. } => {
12416 let mut p = Vec::with_capacity(candidate_ids.len());
12417 for (index, rid) in candidate_ids.iter().enumerate() {
12418 execution_checkpoint(control, index)?;
12419 if let Ok(position) = data.binary_search(&(*rid as i64)) {
12420 p.push(position);
12421 }
12422 }
12423 p.sort_unstable();
12424 (p, false)
12425 }
12426 _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
12427 }
12428 };
12429 crate::trace::QueryTrace::record(|t| {
12430 t.scan_mode = crate::trace::ScanMode::NativePushdown;
12431 t.fast_row_id_map = fast_rid;
12432 });
12433 let mut cols = Vec::with_capacity(col_ids.len());
12434 for (index, cid) in col_ids.iter().enumerate() {
12435 execution_checkpoint(control, index)?;
12436 let col = reader.column_native(*cid)?;
12437 cols.push((*cid, col.gather(&positions)));
12438 }
12439 return Ok(Some(cols));
12440 }
12441
12442 if !self.run_refs.is_empty() {
12455 use crate::cursor::{
12456 drain_cursor_to_columns, drain_cursor_to_columns_with_control, Cursor,
12457 };
12458 let remaining: usize;
12459 let mut cursor: Box<dyn crate::cursor::Cursor> = if self.run_refs.len() == 1 {
12460 let c = self
12461 .native_page_cursor(snapshot, proj_pairs.clone(), conditions)?
12462 .expect("single-run cursor should build when run_refs.len() == 1");
12463 remaining = c.remaining_rows();
12464 Box::new(c)
12465 } else {
12466 let c = self
12467 .native_multi_run_cursor(snapshot, proj_pairs.clone(), conditions)?
12468 .expect("multi-run cursor should build when run_refs.len() >= 1");
12469 remaining = c.remaining_rows();
12470 Box::new(c)
12471 };
12472 crate::trace::QueryTrace::record(|t| {
12473 if t.survivor_count.is_none() {
12474 t.survivor_count = Some(remaining);
12475 }
12476 });
12477 let cols = match control {
12478 Some(control) => {
12479 drain_cursor_to_columns_with_control(cursor.as_mut(), &proj_pairs, control)?
12480 }
12481 None => drain_cursor_to_columns(cursor.as_mut(), &proj_pairs)?,
12482 };
12483 return Ok(Some(cols));
12484 }
12485
12486 crate::trace::QueryTrace::record(|t| {
12491 t.scan_mode = crate::trace::ScanMode::Materialized;
12492 t.row_materialized = true;
12493 });
12494 let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12495 for (index, c) in conditions.iter().enumerate() {
12496 execution_checkpoint(control, index)?;
12497 sets.push(self.resolve_condition(c, snapshot)?);
12498 }
12499 let rids = RowIdSet::intersect_many(sets).into_sorted_vec();
12500 let rows = self.rows_for_rids(&rids, snapshot)?;
12501 let mut cols: Vec<(u16, columnar::NativeColumn)> = Vec::with_capacity(col_ids.len());
12502 for (index, (cid, ty)) in proj_pairs.iter().enumerate() {
12503 execution_checkpoint(control, index)?;
12504 let vals: Vec<Value> = rows
12505 .iter()
12506 .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
12507 .collect();
12508 cols.push((*cid, columnar::values_to_native(ty.clone(), &vals)));
12509 }
12510 Ok(Some(cols))
12511 }
12512
12513 pub fn native_page_cursor(
12528 &self,
12529 snapshot: Snapshot,
12530 projection: Vec<(u16, TypeId)>,
12531 conditions: &[crate::query::Condition],
12532 ) -> Result<Option<NativePageCursor>> {
12533 use crate::cursor::build_page_plans;
12534 if self.ttl.is_some() {
12535 return Ok(None);
12536 }
12537 if !conditions.is_empty() && !self.indexes_complete {
12540 return Ok(None);
12541 }
12542 if self.run_refs.len() != 1 {
12543 return Ok(None);
12544 }
12545 let mut reader = self.open_reader(self.run_refs[0].run_id)?;
12546 let (positions, rids) = reader.visible_positions_with_rids_at(snapshot)?;
12547
12548 let overlay_rids: HashSet<u64> = {
12551 let mut s = HashSet::new();
12552 for row in self.memtable.visible_versions_at(snapshot) {
12553 s.insert(row.row_id.0);
12554 }
12555 for row in self.mutable_run.visible_versions_at(snapshot) {
12556 s.insert(row.row_id.0);
12557 }
12558 s
12559 };
12560
12561 let survivors = if conditions.is_empty() {
12565 None
12566 } else {
12567 Some(self.resolve_survivor_rids(conditions, &mut reader, snapshot)?)
12568 };
12569
12570 let run_survivors: Option<RowIdSet> = if overlay_rids.is_empty() {
12577 survivors.clone()
12578 } else if let Some(s) = &survivors {
12579 let mut run_set = s.clone();
12580 run_set.remove_many(overlay_rids.iter().copied());
12581 Some(run_set)
12582 } else {
12583 Some(RowIdSet::from_unsorted(
12584 rids.iter()
12585 .map(|&r| r as u64)
12586 .filter(|r| !overlay_rids.contains(r))
12587 .collect(),
12588 ))
12589 };
12590
12591 let overlay_rows = if overlay_rids.is_empty() {
12592 Vec::new()
12593 } else {
12594 let bound = Self::overlay_materialization_bound(conditions, &survivors);
12595 self.overlay_visible_rows(snapshot, bound)
12596 };
12597
12598 let plans = if positions.is_empty() {
12600 Vec::new()
12601 } else {
12602 let page_rows = reader.page_row_counts(crate::sorted_run::SYS_ROW_ID)?;
12603 build_page_plans(&positions, &rids, &page_rows, run_survivors.as_ref())
12604 };
12605
12606 let overlay = if overlay_rows.is_empty() {
12608 None
12609 } else {
12610 let filtered =
12611 self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12612 if filtered.is_empty() {
12613 None
12614 } else {
12615 Some(self.materialize_overlay(&filtered, &projection))
12616 }
12617 };
12618
12619 let overlay_row_count = overlay
12620 .as_ref()
12621 .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12622 .unwrap_or(0);
12623 crate::trace::QueryTrace::record(|t| {
12624 t.scan_mode = crate::trace::ScanMode::NativePageCursor;
12625 t.run_count = self.run_refs.len();
12626 t.memtable_rows = self.memtable.len();
12627 t.mutable_run_rows = self.mutable_run.len();
12628 t.overlay_rows = overlay_row_count;
12629 t.conditions_pushed = conditions.len();
12630 t.pages_decoded = plans
12631 .iter()
12632 .map(|p| p.positions.len())
12633 .sum::<usize>()
12634 .min(1);
12635 });
12636
12637 Ok(Some(NativePageCursor::new_with_overlay(
12638 reader, projection, plans, overlay,
12639 )))
12640 }
12641 #[allow(clippy::type_complexity)]
12651 pub fn native_multi_run_cursor(
12652 &self,
12653 snapshot: Snapshot,
12654 projection: Vec<(u16, TypeId)>,
12655 conditions: &[crate::query::Condition],
12656 ) -> Result<Option<crate::cursor::MultiRunCursor>> {
12657 use crate::cursor::{MultiRunCursor, RunStream};
12658 use crate::sorted_run::SYS_ROW_ID;
12659 use std::collections::{BinaryHeap, HashMap, HashSet};
12660 if self.ttl.is_some() {
12661 return Ok(None);
12662 }
12663 if !conditions.is_empty() && !self.indexes_complete {
12666 return Ok(None);
12667 }
12668 if self.run_refs.is_empty() {
12669 return Ok(None);
12670 }
12671
12672 let mut run_meta: Vec<(
12674 RunReader,
12675 Vec<i64>,
12676 Vec<i64>,
12677 Vec<u8>,
12678 Option<Vec<Option<HlcTimestamp>>>,
12679 Vec<usize>,
12680 )> = Vec::with_capacity(self.run_refs.len());
12681 for rr in &self.run_refs {
12682 let mut reader = self.open_reader(rr.run_id)?;
12683 let (rids, eps, del) = reader.system_columns_native()?;
12684 let page_rows = reader.page_row_counts(SYS_ROW_ID)?;
12685 let commit_ts: Option<Vec<Option<HlcTimestamp>>> =
12686 if reader.has_column(crate::sorted_run::SYS_COMMIT_TS) {
12687 let col = reader.column_native(crate::sorted_run::SYS_COMMIT_TS)?;
12688 Some(
12689 (0..rids.len())
12690 .map(|i| {
12691 crate::sorted_run::decode_commit_ts_value(col.value_at(i).as_ref())
12692 })
12693 .collect(),
12694 )
12695 } else {
12696 None
12697 };
12698 run_meta.push((reader, rids, eps, del, commit_ts, page_rows));
12699 }
12700
12701 let mut best: HashMap<u64, (Epoch, Option<HlcTimestamp>, usize, usize, bool)> =
12707 HashMap::new();
12708 for (run_idx, (_, rids, eps, del, commit_ts, _)) in run_meta.iter().enumerate() {
12709 for i in 0..rids.len() {
12710 let rid = rids[i] as u64;
12711 let e = Epoch(eps[i] as u64);
12712 let ts = commit_ts.as_ref().and_then(|v| v.get(i).copied().flatten());
12713 if !snapshot.observes_row(e, ts) {
12714 continue;
12715 }
12716 let is_del = del[i] != 0;
12717 best.entry(rid)
12718 .and_modify(|cur| {
12719 if Snapshot::version_is_newer(e, ts, cur.0, cur.1) {
12720 *cur = (e, ts, run_idx, i, is_del);
12721 }
12722 })
12723 .or_insert((e, ts, run_idx, i, is_del));
12724 }
12725 }
12726
12727 let overlay_rids: HashSet<u64> = {
12729 let mut s = HashSet::new();
12730 for row in self.memtable.visible_versions_at(snapshot) {
12731 s.insert(row.row_id.0);
12732 }
12733 for row in self.mutable_run.visible_versions_at(snapshot) {
12734 s.insert(row.row_id.0);
12735 }
12736 s
12737 };
12738
12739 let survivors: Option<RowIdSet> = if conditions.is_empty() {
12741 None
12742 } else {
12743 let mut sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12744 for c in conditions {
12745 sets.push(self.resolve_condition(c, snapshot)?);
12746 }
12747 Some(RowIdSet::intersect_many(sets))
12748 };
12749
12750 let mut per_run: Vec<Vec<(u64, usize)>> = vec![Vec::new(); run_meta.len()];
12754 for (rid, (_, _, run_idx, pos, deleted)) in &best {
12755 if *deleted {
12756 continue;
12757 }
12758 if overlay_rids.contains(rid) {
12759 continue;
12760 }
12761 if let Some(s) = &survivors {
12762 if !s.contains(*rid) {
12763 continue;
12764 }
12765 }
12766 per_run[*run_idx].push((*rid, *pos));
12767 }
12768 for v in per_run.iter_mut() {
12769 v.sort_unstable_by_key(|&(rid, _)| rid);
12770 }
12771
12772 let mut streams = Vec::with_capacity(run_meta.len());
12774 let mut heap: BinaryHeap<std::cmp::Reverse<(u64, usize)>> = BinaryHeap::new();
12775 let mut total = 0usize;
12776 for (run_idx, (reader, _, _, _, _, page_rows)) in run_meta.into_iter().enumerate() {
12777 let mut starts = Vec::with_capacity(page_rows.len());
12778 let mut acc = 0usize;
12779 for &r in &page_rows {
12780 starts.push(acc);
12781 acc += r;
12782 }
12783 let mut survivors_vec: Vec<(u64, usize, usize)> =
12784 Vec::with_capacity(per_run[run_idx].len());
12785 for &(rid, pos) in &per_run[run_idx] {
12786 let page_seq = match starts.partition_point(|&s| s <= pos) {
12787 0 => continue,
12788 p => p - 1,
12789 };
12790 let within = pos - starts[page_seq];
12791 survivors_vec.push((rid, page_seq, within));
12792 }
12793 total += survivors_vec.len();
12794 if let Some(&(rid, _, _)) = survivors_vec.first() {
12795 heap.push(std::cmp::Reverse((rid, run_idx)));
12796 }
12797 streams.push(RunStream::new(reader, survivors_vec, page_rows));
12798 }
12799
12800 let overlay_rows = if overlay_rids.is_empty() {
12802 Vec::new()
12803 } else {
12804 let bound = Self::overlay_materialization_bound(conditions, &survivors);
12805 self.overlay_visible_rows(snapshot, bound)
12806 };
12807 let overlay = if overlay_rows.is_empty() {
12808 None
12809 } else {
12810 let filtered =
12811 self.filter_overlay_rows(overlay_rows, conditions, survivors.as_ref(), snapshot)?;
12812 if filtered.is_empty() {
12813 None
12814 } else {
12815 Some(self.materialize_overlay(&filtered, &projection))
12816 }
12817 };
12818
12819 let overlay_row_count = overlay
12820 .as_ref()
12821 .map(|c| c.first().map(|c| c.len()).unwrap_or(0))
12822 .unwrap_or(0);
12823 crate::trace::QueryTrace::record(|t| {
12824 t.scan_mode = crate::trace::ScanMode::MultiRunCursor;
12825 t.run_count = self.run_refs.len();
12826 t.memtable_rows = self.memtable.len();
12827 t.mutable_run_rows = self.mutable_run.len();
12828 t.overlay_rows = overlay_row_count;
12829 t.conditions_pushed = conditions.len();
12830 t.survivor_count = Some(total);
12831 });
12832
12833 Ok(Some(MultiRunCursor::new(
12834 streams, projection, heap, total, overlay,
12835 )))
12836 }
12837
12838 fn overlay_materialization_bound<'a>(
12850 conditions: &[crate::query::Condition],
12851 survivors: &'a Option<RowIdSet>,
12852 ) -> Option<&'a RowIdSet> {
12853 use crate::query::Condition;
12854 let has_range = conditions
12855 .iter()
12856 .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12857 if has_range {
12858 None
12859 } else {
12860 survivors.as_ref()
12861 }
12862 }
12863
12864 fn overlay_visible_rows(&self, snapshot: Snapshot, bound: Option<&RowIdSet>) -> Vec<Row> {
12876 let mut best: HashMap<u64, (Epoch, Row)> = HashMap::new();
12877 let mut fold = |row: Row| {
12878 if let Some(b) = bound {
12879 if !b.contains(row.row_id.0) {
12880 return;
12881 }
12882 }
12883 best.entry(row.row_id.0)
12884 .and_modify(|(be, br)| {
12885 if row.committed_epoch > *be {
12886 *be = row.committed_epoch;
12887 *br = row.clone();
12888 }
12889 })
12890 .or_insert_with(|| (row.committed_epoch, row));
12891 };
12892 for row in self.memtable.visible_versions_at(snapshot) {
12893 fold(row);
12894 }
12895 for row in self.mutable_run.visible_versions_at(snapshot) {
12896 fold(row);
12897 }
12898 let mut out: Vec<Row> = best
12899 .into_values()
12900 .filter_map(|(_, r)| if r.deleted { None } else { Some(r) })
12901 .collect();
12902 out.sort_by_key(|r| r.row_id);
12903 out
12904 }
12905
12906 fn filter_overlay_rows(
12914 &self,
12915 rows: Vec<Row>,
12916 conditions: &[crate::query::Condition],
12917 survivors: Option<&RowIdSet>,
12918 snapshot: Snapshot,
12919 ) -> Result<Vec<Row>> {
12920 if conditions.is_empty() {
12921 return Ok(rows);
12922 }
12923 use crate::query::Condition;
12924 let all_index_served = !conditions
12928 .iter()
12929 .any(|c| matches!(c, Condition::Range { .. } | Condition::RangeF64 { .. }));
12930 if all_index_served {
12931 return Ok(rows
12932 .into_iter()
12933 .filter(|r| survivors.is_none_or(|s| s.contains(r.row_id.0)))
12934 .collect());
12935 }
12936 let mut per_cond_sets: Vec<RowIdSet> = Vec::with_capacity(conditions.len());
12939 for c in conditions {
12940 let s = match c {
12941 Condition::Range { .. } | Condition::RangeF64 { .. } => RowIdSet::empty(),
12942 _ => self.resolve_condition(c, snapshot)?,
12943 };
12944 per_cond_sets.push(s);
12945 }
12946 Ok(rows
12947 .into_iter()
12948 .filter(|row| {
12949 conditions.iter().enumerate().all(|(i, c)| match c {
12950 Condition::Range { column_id, lo, hi } => {
12951 matches!(row.columns.get(column_id), Some(Value::Int64(v)) if *v >= *lo && *v <= *hi)
12952 }
12953 Condition::RangeF64 { column_id, lo, lo_inclusive, hi, hi_inclusive } => {
12954 match row.columns.get(column_id) {
12955 Some(Value::Float64(v)) => {
12956 let lo_ok = if *lo_inclusive { *v >= *lo } else { *v > *lo };
12957 let hi_ok = if *hi_inclusive { *v <= *hi } else { *v < *hi };
12958 lo_ok && hi_ok
12959 }
12960 _ => false,
12961 }
12962 }
12963 _ => per_cond_sets[i].contains(row.row_id.0),
12964 })
12965 })
12966 .collect())
12967 }
12968
12969 fn materialize_overlay(
12972 &self,
12973 rows: &[Row],
12974 projection: &[(u16, TypeId)],
12975 ) -> Vec<columnar::NativeColumn> {
12976 if projection.is_empty() {
12977 return vec![columnar::null_native(TypeId::Int64, rows.len())];
12978 }
12979 let mut cols = Vec::with_capacity(projection.len());
12980 for (cid, ty) in projection {
12981 let vals: Vec<Value> = rows
12982 .iter()
12983 .map(|r| r.columns.get(cid).cloned().unwrap_or(Value::Null))
12984 .collect();
12985 cols.push(columnar::values_to_native(ty.clone(), &vals));
12986 }
12987 cols
12988 }
12989
12990 fn resolve_survivor_rids(
12995 &self,
12996 conditions: &[crate::query::Condition],
12997 reader: &mut RunReader,
12998 snapshot: Snapshot,
12999 ) -> Result<RowIdSet> {
13000 use crate::query::Condition;
13001 let mut sets: Vec<RowIdSet> = Vec::new();
13002 for c in conditions {
13003 self.validate_condition(c)?;
13004 let s: RowIdSet = match c {
13005 Condition::Pk(key) => {
13006 let lookup = self
13007 .schema
13008 .primary_key()
13009 .map(|pk| self.index_lookup_key_bytes(pk.id, key))
13010 .unwrap_or_else(|| key.clone());
13011 self.hot
13012 .get(&lookup)
13013 .map(|r| RowIdSet::one(r.0))
13014 .unwrap_or_else(RowIdSet::empty)
13015 }
13016 Condition::BitmapEq { column_id, value } => {
13017 let lookup = self.index_lookup_key_bytes(*column_id, value);
13018 self.bitmap
13019 .get(column_id)
13020 .map(|b| RowIdSet::from_roaring(b.get(&lookup)))
13021 .unwrap_or_else(RowIdSet::empty)
13022 }
13023 Condition::BitmapIn { column_id, values } => {
13024 let bm = self.bitmap.get(column_id);
13025 let mut acc = roaring::RoaringBitmap::new();
13026 if let Some(b) = bm {
13027 for v in values {
13028 let lookup = self.index_lookup_key_bytes(*column_id, v);
13029 acc |= b.get(&lookup);
13030 }
13031 }
13032 RowIdSet::from_roaring(acc)
13033 }
13034 Condition::BytesPrefix { column_id, prefix } => {
13035 if let Some(b) = self.bitmap.get(column_id) {
13036 let lookup_prefix = self.index_lookup_key_bytes(*column_id, prefix);
13037 let mut acc = roaring::RoaringBitmap::new();
13038 for key in b.keys() {
13039 if key.starts_with(&lookup_prefix) {
13040 acc |= b.get(&key);
13041 }
13042 }
13043 RowIdSet::from_roaring(acc)
13044 } else {
13045 RowIdSet::empty()
13046 }
13047 }
13048 Condition::FmContains { column_id, pattern } => self
13049 .fm
13050 .get(column_id)
13051 .map(|f| {
13052 RowIdSet::from_unsorted(
13053 f.locate(pattern).into_iter().map(|r| r.0).collect(),
13054 )
13055 })
13056 .unwrap_or_else(RowIdSet::empty),
13057 Condition::FmContainsAll {
13058 column_id,
13059 patterns,
13060 } => {
13061 if let Some(f) = self.fm.get(column_id) {
13062 let sets: Vec<RowIdSet> = patterns
13063 .iter()
13064 .map(|pat| {
13065 RowIdSet::from_unsorted(
13066 f.locate(pat).into_iter().map(|r| r.0).collect(),
13067 )
13068 })
13069 .collect();
13070 RowIdSet::intersect_many(sets)
13071 } else {
13072 RowIdSet::empty()
13073 }
13074 }
13075 Condition::Ann {
13076 column_id,
13077 query,
13078 k,
13079 } => RowIdSet::from_unsorted(
13080 self.retrieve_filtered(
13081 &crate::query::Retriever::Ann {
13082 column_id: *column_id,
13083 query: query.clone(),
13084 k: *k,
13085 },
13086 snapshot,
13087 None,
13088 None,
13089 None,
13090 None,
13091 )?
13092 .into_iter()
13093 .map(|hit| hit.row_id.0)
13094 .collect(),
13095 ),
13096 Condition::SparseMatch {
13097 column_id,
13098 query,
13099 k,
13100 } => RowIdSet::from_unsorted(
13101 self.retrieve_filtered(
13102 &crate::query::Retriever::Sparse {
13103 column_id: *column_id,
13104 query: query.clone(),
13105 k: *k,
13106 },
13107 snapshot,
13108 None,
13109 None,
13110 None,
13111 None,
13112 )?
13113 .into_iter()
13114 .map(|hit| hit.row_id.0)
13115 .collect(),
13116 ),
13117 Condition::MinHashSimilar {
13118 column_id,
13119 query,
13120 k,
13121 } => match self.minhash.get(column_id) {
13122 Some(index) => {
13123 let candidates = index.candidate_row_ids(query);
13124 let eligible =
13125 self.eligible_candidate_ids(&candidates, *column_id, snapshot, None)?;
13126 RowIdSet::from_unsorted(
13127 index
13128 .search_filtered(query, *k, |row_id| eligible.contains(&row_id))
13129 .into_iter()
13130 .map(|(row_id, _)| row_id.0)
13131 .collect(),
13132 )
13133 }
13134 None => RowIdSet::empty(),
13135 },
13136 Condition::Range { column_id, lo, hi } => {
13137 if let Some(li) = self.learned_range.get(column_id) {
13138 RowIdSet::from_unsorted(li.range(*lo, *hi).into_iter().collect())
13139 } else {
13140 reader.range_row_id_set_i64(*column_id, *lo, *hi)?
13141 }
13142 }
13143 Condition::RangeF64 {
13144 column_id,
13145 lo,
13146 lo_inclusive,
13147 hi,
13148 hi_inclusive,
13149 } => {
13150 if let Some(li) = self.learned_range.get(column_id) {
13151 RowIdSet::from_unsorted(
13152 li.range_f64(*lo, *lo_inclusive, *hi, *hi_inclusive)
13153 .into_iter()
13154 .collect(),
13155 )
13156 } else {
13157 reader.range_row_id_set_f64(
13158 *column_id,
13159 *lo,
13160 *lo_inclusive,
13161 *hi,
13162 *hi_inclusive,
13163 )?
13164 }
13165 }
13166 Condition::IsNull { column_id } => reader.null_row_id_set(*column_id, true)?,
13167 Condition::IsNotNull { column_id } => reader.null_row_id_set(*column_id, false)?,
13168 };
13169 sets.push(s);
13170 }
13171 Ok(RowIdSet::intersect_many(sets))
13172 }
13173
13174 pub fn scan_cursor(
13195 &self,
13196 snapshot: Snapshot,
13197 projection: Vec<(u16, TypeId)>,
13198 conditions: &[crate::query::Condition],
13199 ) -> Result<Option<Box<dyn crate::cursor::Cursor>>> {
13200 if self.ttl.is_some() {
13201 return Ok(None);
13202 }
13203 if !conditions.is_empty() && !self.indexes_complete {
13209 return Ok(None);
13210 }
13211 if self.run_refs.len() == 1 {
13212 Ok(self
13213 .native_page_cursor(snapshot, projection, conditions)?
13214 .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13215 } else {
13216 Ok(self
13217 .native_multi_run_cursor(snapshot, projection, conditions)?
13218 .map(|c| Box::new(c) as Box<dyn crate::cursor::Cursor>))
13219 }
13220 }
13221
13222 pub fn aggregate_native(
13236 &self,
13237 snapshot: Snapshot,
13238 column: Option<u16>,
13239 conditions: &[crate::query::Condition],
13240 agg: NativeAgg,
13241 ) -> Result<Option<NativeAggResult>> {
13242 self.aggregate_native_inner(snapshot, column, conditions, agg, None)
13243 }
13244
13245 pub fn aggregate_native_with_control(
13246 &self,
13247 snapshot: Snapshot,
13248 column: Option<u16>,
13249 conditions: &[crate::query::Condition],
13250 agg: NativeAgg,
13251 control: &crate::ExecutionControl,
13252 ) -> Result<Option<NativeAggResult>> {
13253 self.aggregate_native_inner(snapshot, column, conditions, agg, Some(control))
13254 }
13255
13256 fn aggregate_native_inner(
13257 &self,
13258 snapshot: Snapshot,
13259 column: Option<u16>,
13260 conditions: &[crate::query::Condition],
13261 agg: NativeAgg,
13262 control: Option<&crate::ExecutionControl>,
13263 ) -> Result<Option<NativeAggResult>> {
13264 execution_checkpoint(control, 0)?;
13265 if self.ttl.is_some() {
13266 return Ok(None);
13267 }
13268 if self.run_refs.len() == 1 && conditions.is_empty() {
13270 if let Some(res) = self.aggregate_from_stats(snapshot, column, agg)? {
13271 return Ok(Some(res));
13272 }
13273 }
13274 if matches!(agg, NativeAgg::Count) && column.is_none() {
13278 if let Some(c) = self.scan_cursor(snapshot, Vec::new(), conditions)? {
13279 return Ok(Some(NativeAggResult::Count(c.remaining_rows() as u64)));
13280 }
13281 let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13282 return Ok(Some(NativeAggResult::Count(rows.len() as u64)));
13283 }
13284 let cid = match column {
13287 Some(c) => c,
13288 None => return Ok(None),
13289 };
13290 let ty = self.column_type(cid);
13291 if let Some(mut cursor) = self.scan_cursor(snapshot, vec![(cid, ty.clone())], conditions)? {
13292 execution_checkpoint(control, 0)?;
13293 return match ty {
13294 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13295 let (count, sum, mn, mx) = accumulate_int(cursor.as_mut(), control)?;
13296 Ok(Some(pack_int(agg, count, sum, mn, mx)))
13297 }
13298 TypeId::Float64 => {
13299 let (count, sum, mn, mx) = accumulate_float(cursor.as_mut(), control)?;
13300 Ok(Some(pack_float(agg, count, sum, mn, mx)))
13301 }
13302 _ => Ok(None),
13303 };
13304 }
13305 let rows = self.visible_rows_filtered(snapshot, conditions, control)?;
13307 execution_checkpoint(control, 0)?;
13308 match ty {
13309 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13310 let mut count = 0u64;
13311 let mut sum = 0i128;
13312 let mut mn = i64::MAX;
13313 let mut mx = i64::MIN;
13314 for row in &rows {
13315 if let Some(Value::Int64(v)) = row.columns.get(&cid) {
13316 count += 1;
13317 sum += i128::from(*v);
13318 mn = mn.min(*v);
13319 mx = mx.max(*v);
13320 }
13321 }
13322 Ok(Some(pack_int(agg, count, sum, mn, mx)))
13323 }
13324 TypeId::Float64 => {
13325 let mut count = 0u64;
13326 let mut sum = 0.0f64;
13327 let mut mn = f64::INFINITY;
13328 let mut mx = f64::NEG_INFINITY;
13329 for row in &rows {
13330 if let Some(Value::Float64(v)) = row.columns.get(&cid) {
13331 count += 1;
13332 sum += *v;
13333 mn = mn.min(*v);
13334 mx = mx.max(*v);
13335 }
13336 }
13337 Ok(Some(pack_float(agg, count, sum, mn, mx)))
13338 }
13339 _ => Ok(None),
13340 }
13341 }
13342
13343 fn visible_rows_filtered(
13345 &self,
13346 snapshot: Snapshot,
13347 conditions: &[crate::query::Condition],
13348 control: Option<&crate::ExecutionControl>,
13349 ) -> Result<Vec<Row>> {
13350 let rows = if let Some(control) = control {
13351 self.visible_rows_controlled(snapshot, control)?
13352 } else {
13353 self.visible_rows(snapshot)?
13354 };
13355 if conditions.is_empty() {
13356 return Ok(rows);
13357 }
13358 Ok(rows
13359 .into_iter()
13360 .filter(|row| {
13361 conditions
13362 .iter()
13363 .all(|cond| condition_matches_row(cond, row, &self.schema))
13364 })
13365 .collect())
13366 }
13367
13368 fn aggregate_from_stats(
13376 &self,
13377 snapshot: Snapshot,
13378 column: Option<u16>,
13379 agg: NativeAgg,
13380 ) -> Result<Option<NativeAggResult>> {
13381 let cid = match (agg, column) {
13382 (NativeAgg::Count | NativeAgg::Min | NativeAgg::Max, Some(c)) => c,
13383 _ => return Ok(None), };
13385 let Some(stats) = self.exact_column_stats(snapshot, &[cid])? else {
13386 return Ok(None);
13387 };
13388 let Some(cs) = stats.get(&cid) else {
13389 return Ok(None);
13390 };
13391 match agg {
13392 NativeAgg::Count => Ok(Some(NativeAggResult::Count(
13394 self.live_count.saturating_sub(cs.null_count),
13395 ))),
13396 NativeAgg::Min | NativeAgg::Max => {
13397 let bound = if agg == NativeAgg::Min {
13398 &cs.min
13399 } else {
13400 &cs.max
13401 };
13402 match bound {
13403 Some(Value::Int64(x)) => Ok(Some(NativeAggResult::Int(*x))),
13404 Some(Value::Float64(x)) => Ok(Some(NativeAggResult::Float(*x))),
13405 Some(_) => Ok(None), None if cs.null_count >= self.live_count => Ok(Some(NativeAggResult::Null)),
13410 None => Ok(None),
13411 }
13412 }
13413 _ => Ok(None),
13414 }
13415 }
13416
13417 pub fn count_distinct_from_bitmap(&mut self, column_id: u16) -> Result<Option<u64>> {
13426 if self.ttl.is_some() {
13427 return Ok(None);
13428 }
13429 if !(self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1) {
13430 return Ok(None);
13431 }
13432 self.ensure_indexes_complete()?;
13435 let reader = self.open_reader(self.run_refs[0].run_id)?;
13436 if self.live_count != reader.row_count() as u64 {
13437 return Ok(None);
13438 }
13439 let Some(bm) = self.bitmap.get(&column_id) else {
13440 return Ok(None); };
13442 let mut distinct = bm.value_count() as u64;
13443 if !bm.get(&Value::Null.encode_key()).is_empty() {
13446 distinct = distinct.saturating_sub(1);
13447 }
13448 Ok(Some(distinct))
13449 }
13450
13451 pub fn aggregate_incremental(
13463 &mut self,
13464 cache_key: u64,
13465 conditions: &[crate::query::Condition],
13466 column: Option<u16>,
13467 agg: NativeAgg,
13468 ) -> Result<IncrementalAggResult> {
13469 self.aggregate_incremental_inner(cache_key, conditions, column, agg, None)
13470 }
13471
13472 pub fn aggregate_incremental_with_control(
13473 &mut self,
13474 cache_key: u64,
13475 conditions: &[crate::query::Condition],
13476 column: Option<u16>,
13477 agg: NativeAgg,
13478 control: &crate::ExecutionControl,
13479 ) -> Result<IncrementalAggResult> {
13480 self.aggregate_incremental_inner(cache_key, conditions, column, agg, Some(control))
13481 }
13482
13483 fn aggregate_incremental_inner(
13484 &mut self,
13485 cache_key: u64,
13486 conditions: &[crate::query::Condition],
13487 column: Option<u16>,
13488 agg: NativeAgg,
13489 control: Option<&crate::ExecutionControl>,
13490 ) -> Result<IncrementalAggResult> {
13491 execution_checkpoint(control, 0)?;
13492 let snap = self.snapshot();
13493 let cur_wm = self.allocator.current().0;
13494 let cur_epoch = snap.epoch.0;
13495 let incremental_ok = self.ttl.is_none()
13502 && !self.had_deletes
13503 && self.memtable.is_empty()
13504 && self.mutable_run.is_empty();
13505
13506 if incremental_ok {
13509 if let Some(cached) = self.agg_cache.get(&cache_key).cloned() {
13510 if cached.epoch == cur_epoch {
13511 return Ok(IncrementalAggResult {
13512 state: cached.state,
13513 incremental: true,
13514 delta_rows: 0,
13515 });
13516 }
13517 if cached.epoch < cur_epoch && cached.watermark <= cur_wm {
13518 let delta_len = cur_wm.saturating_sub(cached.watermark) as usize;
13519 let mut delta_rids = Vec::with_capacity(delta_len);
13520 for (index, row_id) in (cached.watermark..cur_wm).enumerate() {
13521 execution_checkpoint(control, index)?;
13522 delta_rids.push(row_id);
13523 }
13524 let delta_rows = self.rows_for_rids(&delta_rids, snap)?;
13525 execution_checkpoint(control, 0)?;
13526 let index_sets = self.resolve_index_conditions(conditions, snap)?;
13527 let delta_state = agg_state_from_rows(
13528 &delta_rows,
13529 conditions,
13530 &index_sets,
13531 column,
13532 agg,
13533 &self.schema,
13534 control,
13535 )?;
13536 let merged = cached.state.merge(delta_state);
13537 let delta_n = delta_rids.len() as u64;
13538 Arc::make_mut(&mut self.agg_cache).insert(
13539 cache_key,
13540 CachedAgg {
13541 state: merged.clone(),
13542 watermark: cur_wm,
13543 epoch: cur_epoch,
13544 },
13545 );
13546 return Ok(IncrementalAggResult {
13547 state: merged,
13548 incremental: true,
13549 delta_rows: delta_n,
13550 });
13551 }
13552 }
13553 }
13554
13555 let cursor_ok =
13560 self.memtable.is_empty() && self.mutable_run.is_empty() && self.run_refs.len() == 1;
13561 let state = if cursor_ok && agg != NativeAgg::Avg {
13562 match self.aggregate_native_inner(snap, column, conditions, agg, control)? {
13563 Some(result) => {
13564 AggState::from_native(result, agg, column.map(|c| self.column_type(c)))
13565 }
13566 None => self.agg_state_full_scan(conditions, column, agg, snap, control)?,
13567 }
13568 } else {
13569 self.agg_state_full_scan(conditions, column, agg, snap, control)?
13570 };
13571 if incremental_ok {
13573 Arc::make_mut(&mut self.agg_cache).insert(
13574 cache_key,
13575 CachedAgg {
13576 state: state.clone(),
13577 watermark: cur_wm,
13578 epoch: cur_epoch,
13579 },
13580 );
13581 }
13582 Ok(IncrementalAggResult {
13583 state,
13584 incremental: false,
13585 delta_rows: 0,
13586 })
13587 }
13588
13589 fn agg_state_full_scan(
13592 &self,
13593 conditions: &[crate::query::Condition],
13594 column: Option<u16>,
13595 agg: NativeAgg,
13596 snap: Snapshot,
13597 control: Option<&crate::ExecutionControl>,
13598 ) -> Result<AggState> {
13599 execution_checkpoint(control, 0)?;
13600 let rows = self.visible_rows(snap)?;
13601 execution_checkpoint(control, 0)?;
13602 let index_sets = self.resolve_index_conditions(conditions, snap)?;
13603 agg_state_from_rows(
13604 &rows,
13605 conditions,
13606 &index_sets,
13607 column,
13608 agg,
13609 &self.schema,
13610 control,
13611 )
13612 }
13613
13614 fn resolve_index_conditions(
13617 &self,
13618 conditions: &[crate::query::Condition],
13619 snapshot: Snapshot,
13620 ) -> Result<Vec<RowIdSet>> {
13621 use crate::query::Condition;
13622 let mut sets = Vec::new();
13623 for c in conditions {
13624 if matches!(
13625 c,
13626 Condition::Ann { .. }
13627 | Condition::SparseMatch { .. }
13628 | Condition::MinHashSimilar { .. }
13629 ) {
13630 sets.push(self.resolve_condition(c, snapshot)?);
13631 }
13632 }
13633 Ok(sets)
13634 }
13635
13636 fn column_type(&self, cid: u16) -> TypeId {
13637 self.schema
13638 .columns
13639 .iter()
13640 .find(|c| c.id == cid)
13641 .map(|c| c.ty.clone())
13642 .unwrap_or(TypeId::Bytes)
13643 }
13644
13645 pub fn approx_aggregate(
13654 &mut self,
13655 conditions: &[crate::query::Condition],
13656 column: Option<u16>,
13657 agg: ApproxAgg,
13658 z: f64,
13659 ) -> Result<Option<ApproxResult>> {
13660 self.approx_aggregate_with_candidate_authorization(conditions, column, agg, z, None)
13661 }
13662
13663 pub fn approx_aggregate_with_candidate_authorization(
13666 &mut self,
13667 conditions: &[crate::query::Condition],
13668 column: Option<u16>,
13669 agg: ApproxAgg,
13670 z: f64,
13671 authorization: Option<&crate::security::CandidateAuthorization<'_>>,
13672 ) -> Result<Option<ApproxResult>> {
13673 use crate::query::Condition;
13674 self.ensure_reservoir_complete()?;
13675 let mut snapshot = self.snapshot();
13680 let n_pop = self.count();
13681 let sample_rids: Vec<u64> = self.reservoir.row_ids().to_vec();
13682 if sample_rids.is_empty() {
13683 return Ok(None);
13684 }
13685 let mut live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13687 if live_sample.is_empty() {
13688 snapshot = Snapshot::unbounded();
13689 live_sample = self.rows_for_rids(&sample_rids, snapshot)?;
13690 }
13691 let s = live_sample.len();
13692 if s == 0 {
13693 return Ok(None);
13694 }
13695 let authorized = authorization
13696 .map(|authorization| {
13697 let candidates = live_sample.iter().map(|row| row.row_id).collect::<Vec<_>>();
13698 self.policy_allowed_candidate_ids(&candidates, snapshot, authorization, None)
13699 })
13700 .transpose()?;
13701
13702 let mut index_sets: Vec<RowIdSet> = Vec::new();
13705 for c in conditions {
13706 if matches!(
13707 c,
13708 Condition::Ann { .. }
13709 | Condition::SparseMatch { .. }
13710 | Condition::MinHashSimilar { .. }
13711 ) {
13712 index_sets.push(self.resolve_condition(c, snapshot)?);
13713 }
13714 }
13715
13716 let cid = match (agg, column) {
13718 (ApproxAgg::Count, _) => None,
13719 (_, Some(c)) => Some(c),
13720 _ => return Ok(None),
13721 };
13722 let mut passing_vals: Vec<f64> = Vec::with_capacity(s);
13723 for r in &live_sample {
13724 if authorized
13725 .as_ref()
13726 .is_some_and(|authorized| !authorized.contains(&r.row_id))
13727 {
13728 continue;
13729 }
13730 if !conditions
13732 .iter()
13733 .all(|c| condition_matches_row(c, r, &self.schema))
13734 {
13735 continue;
13736 }
13737 if !index_sets.iter().all(|set| set.contains(r.row_id.0)) {
13739 continue;
13740 }
13741 if let Some(cid) = cid {
13742 let mut cells = r
13743 .columns
13744 .get(&cid)
13745 .cloned()
13746 .map(|value| vec![(cid, value)])
13747 .unwrap_or_default();
13748 if let Some(authorization) = authorization {
13749 authorization.security.apply_masks_to_cells(
13750 authorization.table,
13751 &mut cells,
13752 authorization.principal,
13753 );
13754 }
13755 if let Some(v) = as_f64(cells.first().map(|(_, value)| value)) {
13756 passing_vals.push(v);
13757 } } else {
13759 passing_vals.push(0.0); }
13761 }
13762 let m = passing_vals.len();
13763
13764 let (point, half) = match agg {
13765 ApproxAgg::Count => {
13766 let p = m as f64 / s as f64;
13768 let point = n_pop as f64 * p;
13769 let var = if s > 1 {
13770 n_pop as f64 * n_pop as f64 * p * (1.0 - p) / s as f64
13771 * (1.0 - s as f64 / n_pop as f64).max(0.0)
13772 } else {
13773 0.0
13774 };
13775 (point, z * var.sqrt())
13776 }
13777 ApproxAgg::Sum => {
13778 let y: Vec<f64> = live_sample
13780 .iter()
13781 .map(|r| {
13782 let passes_row = authorized
13783 .as_ref()
13784 .is_none_or(|authorized| authorized.contains(&r.row_id))
13785 && conditions
13786 .iter()
13787 .all(|c| condition_matches_row(c, r, &self.schema))
13788 && index_sets.iter().all(|set| set.contains(r.row_id.0));
13789 if passes_row {
13790 cid.and_then(|cid| {
13791 let mut cells = r
13792 .columns
13793 .get(&cid)
13794 .cloned()
13795 .map(|value| vec![(cid, value)])
13796 .unwrap_or_default();
13797 if let Some(authorization) = authorization {
13798 authorization.security.apply_masks_to_cells(
13799 authorization.table,
13800 &mut cells,
13801 authorization.principal,
13802 );
13803 }
13804 as_f64(cells.first().map(|(_, value)| value))
13805 })
13806 .unwrap_or(0.0)
13807 } else {
13808 0.0
13809 }
13810 })
13811 .collect();
13812 let mean_y = y.iter().sum::<f64>() / s as f64;
13813 let point = n_pop as f64 * mean_y;
13814 let var = if s > 1 {
13815 let ss: f64 = y.iter().map(|v| (v - mean_y).powi(2)).sum();
13816 let var_y = ss / (s - 1) as f64;
13817 n_pop as f64 * n_pop as f64 * var_y / s as f64
13818 * (1.0 - s as f64 / n_pop as f64).max(0.0)
13819 } else {
13820 0.0
13821 };
13822 (point, z * var.sqrt())
13823 }
13824 ApproxAgg::Avg => {
13825 if m == 0 {
13826 return Ok(Some(ApproxResult {
13827 point: 0.0,
13828 ci_low: 0.0,
13829 ci_high: 0.0,
13830 n_population: n_pop,
13831 n_sample_live: s,
13832 n_passing: 0,
13833 }));
13834 }
13835 let mean = passing_vals.iter().sum::<f64>() / m as f64;
13836 let half = if m > 1 {
13837 let ss: f64 = passing_vals.iter().map(|v| (v - mean).powi(2)).sum();
13838 let sd = (ss / (m - 1) as f64).sqrt();
13839 let fpc = (1.0 - s as f64 / n_pop as f64).max(0.0);
13840 z * sd / (m as f64).sqrt() * fpc.sqrt()
13841 } else {
13842 0.0
13843 };
13844 (mean, half)
13845 }
13846 };
13847
13848 Ok(Some(ApproxResult {
13849 point,
13850 ci_low: point - half,
13851 ci_high: point + half,
13852 n_population: n_pop,
13853 n_sample_live: s,
13854 n_passing: m,
13855 }))
13856 }
13857
13858 pub fn exact_column_stats(
13866 &self,
13867 _snapshot: Snapshot,
13868 projection: &[u16],
13869 ) -> Result<Option<HashMap<u16, ColumnStat>>> {
13870 if self.ttl.is_some()
13871 || !(self.memtable.is_empty()
13872 && self.mutable_run.is_empty()
13873 && self.run_refs.len() == 1)
13874 {
13875 return Ok(None);
13876 }
13877 let reader = self.open_reader(self.run_refs[0].run_id)?;
13878 if self.live_count != reader.row_count() as u64 {
13879 return Ok(None);
13880 }
13881 let mut out = HashMap::new();
13882 for &cid in projection {
13883 let cdef = match self.schema.columns.iter().find(|c| c.id == cid) {
13884 Some(c) => c,
13885 None => continue,
13886 };
13887 let Some(stats) = reader.column_page_stats(cid) else {
13889 out.insert(
13890 cid,
13891 ColumnStat {
13892 min: None,
13893 max: None,
13894 null_count: self.live_count,
13895 },
13896 );
13897 continue;
13898 };
13899 let stat = match cdef.ty {
13900 TypeId::Int64 | TypeId::TimestampNanos | TypeId::Date32 => {
13901 agg_int(stats, crate::sorted_run::be_i64).map(|(mn, mx, n)| ColumnStat {
13902 min: mn.map(Value::Int64),
13903 max: mx.map(Value::Int64),
13904 null_count: n,
13905 })
13906 }
13907 TypeId::Float64 => {
13908 agg_float(stats, crate::sorted_run::be_f64).map(|(mn, mx, n)| ColumnStat {
13909 min: mn.map(Value::Float64),
13910 max: mx.map(Value::Float64),
13911 null_count: n,
13912 })
13913 }
13914 _ => None,
13915 };
13916 if let Some(s) = stat {
13917 out.insert(cid, s);
13918 }
13919 }
13920 Ok(Some(out))
13921 }
13922
13923 pub fn dir(&self) -> &Path {
13924 &self.dir
13925 }
13926
13927 pub fn schema(&self) -> &Schema {
13928 &self.schema
13929 }
13930
13931 pub fn ann_index(&self, column_id: u16) -> Option<&crate::index::AnnIndex> {
13932 self.ann.get(&column_id)
13933 }
13934
13935 pub fn ann_index_mut(&mut self, column_id: u16) -> Option<&mut crate::index::AnnIndex> {
13936 self.ann.get_mut(&column_id)
13937 }
13938
13939 pub(crate) fn set_catalog_name(&mut self, name: String) {
13940 self.name = name;
13941 }
13942
13943 pub(crate) fn prepare_alter_column(
13944 &mut self,
13945 column_name: &str,
13946 change: &AlterColumn,
13947 ) -> Result<(ColumnDef, Option<Schema>)> {
13948 if !self.pending_rows.is_empty() || !self.pending_dels.is_empty() {
13949 return Err(MongrelError::InvalidArgument(
13950 "ALTER COLUMN requires committing staged writes first".into(),
13951 ));
13952 }
13953 let old = self
13954 .schema
13955 .columns
13956 .iter()
13957 .find(|c| c.name == column_name)
13958 .cloned()
13959 .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
13960 let mut next = old.clone();
13961
13962 if let Some(name) = &change.name {
13963 let trimmed = name.trim();
13964 if trimmed.is_empty() {
13965 return Err(MongrelError::InvalidArgument(
13966 "ALTER COLUMN name must not be empty".into(),
13967 ));
13968 }
13969 if trimmed != old.name && self.schema.columns.iter().any(|c| c.name == trimmed) {
13970 return Err(MongrelError::Schema(format!(
13971 "column {trimmed} already exists"
13972 )));
13973 }
13974 next.name = trimmed.to_string();
13975 }
13976
13977 if let Some(ty) = &change.ty {
13978 next.ty = ty.clone();
13979 }
13980 if let Some(flags) = change.flags {
13981 validate_alter_column_flags(old.flags, flags)?;
13982 next.flags = flags;
13983 }
13984
13985 if let Some(default_change) = &change.default_value {
13986 next.default_value = default_change.clone();
13987 }
13988 if let Some(source_change) = &change.embedding_source {
13989 next.embedding_source = source_change.clone();
13990 }
13991
13992 validate_alter_column_type(&self.schema, &old, &next, self.has_stored_versions())?;
13993 if old.flags.contains(ColumnFlags::NULLABLE)
13994 && !next.flags.contains(ColumnFlags::NULLABLE)
13995 && self.column_has_nulls(old.id)?
13996 {
13997 return Err(MongrelError::InvalidArgument(format!(
13998 "column '{}' contains NULL values",
13999 old.name
14000 )));
14001 }
14002 if next == old {
14003 return Ok((next, None));
14004 }
14005 let mut schema = self.schema.clone();
14006 let index = schema
14007 .columns
14008 .iter()
14009 .position(|column| column.id == next.id)
14010 .ok_or_else(|| MongrelError::Schema(format!("unknown column {}", next.id)))?;
14011 schema.columns[index] = next.clone();
14012 schema.schema_id = schema
14013 .schema_id
14014 .checked_add(1)
14015 .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14016 schema.validate_auto_increment()?;
14017 schema.validate_defaults()?;
14018 Ok((next, Some(schema)))
14019 }
14020
14021 pub(crate) fn apply_altered_schema_prepared(&mut self, schema: Schema) {
14022 self.schema = schema;
14023 self.auto_inc = resolve_auto_inc(&self.schema);
14024 self.column_keys = build_column_keys(self.kek.as_deref(), &self.schema);
14025 self.clear_result_cache();
14026 let _ = std::fs::remove_dir_all(self.dir.join("_shadow"));
14027 }
14028
14029 pub(crate) fn publish_index_schema_change(
14033 &mut self,
14034 schema: Schema,
14035 artifact: SecondaryIndexArtifact,
14036 ) -> Result<()> {
14037 self.apply_altered_schema_prepared(schema);
14038 self.prune_index_maps_to_schema();
14039 match artifact {
14040 SecondaryIndexArtifact::Bitmap(column_id, index) => {
14041 self.bitmap.insert(column_id, index);
14042 }
14043 SecondaryIndexArtifact::LearnedRange(column_id, index) => {
14044 Arc::make_mut(&mut self.learned_range).insert(column_id, index);
14045 }
14046 SecondaryIndexArtifact::Fm(column_id, index) => {
14047 self.fm.insert(column_id, *index);
14048 }
14049 SecondaryIndexArtifact::Ann(column_id, index) => {
14050 self.ann.insert(column_id, *index);
14051 }
14052 SecondaryIndexArtifact::Sparse(column_id, index) => {
14053 self.sparse.insert(column_id, index);
14054 }
14055 SecondaryIndexArtifact::MinHash(column_id, index) => {
14056 self.minhash.insert(column_id, index);
14057 }
14058 }
14059 self.indexes_complete = true;
14060 self.seal_generations();
14061 let view = Arc::new(self.capture_read_generation());
14062 self.published.store(Arc::clone(&view));
14063 checkpoint_current_schema(self)?;
14064 self.invalidate_index_checkpoint();
14067 Ok(())
14068 }
14069
14070 pub(crate) fn publish_index_drop(&mut self, schema: Schema) -> Result<()> {
14076 self.apply_altered_schema_prepared(schema);
14077 self.prune_index_maps_to_schema();
14078 self.indexes_complete = true;
14079 self.seal_generations();
14080 let view = Arc::new(self.capture_read_generation());
14081 self.published.store(Arc::clone(&view));
14082 checkpoint_current_schema(self)?;
14083 self.invalidate_index_checkpoint();
14085 Ok(())
14086 }
14087
14088 fn prune_index_maps_to_schema(&mut self) {
14089 let keep_bitmap: std::collections::HashSet<u16> = self
14090 .schema
14091 .indexes
14092 .iter()
14093 .filter(|index| index.kind == IndexKind::Bitmap)
14094 .map(|index| index.column_id)
14095 .collect();
14096 let keep_ann: std::collections::HashSet<u16> = self
14097 .schema
14098 .indexes
14099 .iter()
14100 .filter(|index| index.kind == IndexKind::Ann)
14101 .map(|index| index.column_id)
14102 .collect();
14103 let keep_fm: std::collections::HashSet<u16> = self
14104 .schema
14105 .indexes
14106 .iter()
14107 .filter(|index| index.kind == IndexKind::FmIndex)
14108 .map(|index| index.column_id)
14109 .collect();
14110 let keep_sparse: std::collections::HashSet<u16> = self
14111 .schema
14112 .indexes
14113 .iter()
14114 .filter(|index| index.kind == IndexKind::Sparse)
14115 .map(|index| index.column_id)
14116 .collect();
14117 let keep_minhash: std::collections::HashSet<u16> = self
14118 .schema
14119 .indexes
14120 .iter()
14121 .filter(|index| index.kind == IndexKind::MinHash)
14122 .map(|index| index.column_id)
14123 .collect();
14124 let keep_learned: std::collections::HashSet<u16> = self
14125 .schema
14126 .indexes
14127 .iter()
14128 .filter(|index| index.kind == IndexKind::LearnedRange)
14129 .map(|index| index.column_id)
14130 .collect();
14131 self.bitmap
14132 .retain(|column_id, _| keep_bitmap.contains(column_id));
14133 self.ann.retain(|column_id, _| keep_ann.contains(column_id));
14134 self.fm.retain(|column_id, _| keep_fm.contains(column_id));
14135 self.sparse
14136 .retain(|column_id, _| keep_sparse.contains(column_id));
14137 self.minhash
14138 .retain(|column_id, _| keep_minhash.contains(column_id));
14139 {
14140 let learned = Arc::make_mut(&mut self.learned_range);
14141 learned.retain(|column_id, _| keep_learned.contains(column_id));
14142 }
14143 }
14144
14145 pub(crate) fn checkpoint_altered_schema(&mut self) -> Result<()> {
14146 checkpoint_current_schema(self)
14147 }
14148
14149 pub fn alter_column(&mut self, column_name: &str, change: AlterColumn) -> Result<ColumnDef> {
14150 self.ensure_writable()?;
14151 let previous_schema = self.schema.clone();
14152 let (column, schema) = self.prepare_alter_column(column_name, &change)?;
14153 if let Some(schema) = schema {
14154 self.apply_altered_schema_prepared(schema);
14155 self.checkpoint_standalone_schema_change(previous_schema)?;
14156 }
14157 Ok(column)
14158 }
14159
14160 fn column_has_nulls(&mut self, column_id: u16) -> Result<bool> {
14161 if self.live_count == 0 {
14162 return Ok(false);
14163 }
14164 let snap = self.snapshot();
14165 let columns = self.visible_columns_native(snap, Some(&[column_id]))?;
14166 Ok(columns
14167 .first()
14168 .map(|(_, col)| col.null_count(col.len()) != 0)
14169 .unwrap_or(true))
14170 }
14171
14172 fn has_stored_versions(&self) -> bool {
14173 !self.memtable.is_empty()
14174 || !self.mutable_run.is_empty()
14175 || self.run_refs.iter().any(|r| r.row_count > 0)
14176 || !self.retiring.is_empty()
14177 }
14178
14179 pub fn add_column(
14184 &mut self,
14185 name: &str,
14186 ty: TypeId,
14187 flags: ColumnFlags,
14188 default_value: Option<crate::schema::DefaultExpr>,
14189 ) -> Result<u16> {
14190 self.add_column_with_id(name, ty, flags, default_value, None)
14191 }
14192
14193 pub fn add_column_with_id(
14194 &mut self,
14195 name: &str,
14196 ty: TypeId,
14197 flags: ColumnFlags,
14198 default_value: Option<crate::schema::DefaultExpr>,
14199 requested_id: Option<u16>,
14200 ) -> Result<u16> {
14201 self.ensure_writable()?;
14202 let previous_schema = self.schema.clone();
14203 let (column, schema) =
14204 self.prepare_add_column(name, ty, flags, default_value, requested_id)?;
14205 self.apply_altered_schema_prepared(schema);
14206 self.checkpoint_standalone_schema_change(previous_schema)?;
14207 Ok(column.id)
14208 }
14209
14210 pub(crate) fn prepare_add_column(
14211 &mut self,
14212 name: &str,
14213 ty: TypeId,
14214 flags: ColumnFlags,
14215 default_value: Option<crate::schema::DefaultExpr>,
14216 requested_id: Option<u16>,
14217 ) -> Result<(ColumnDef, Schema)> {
14218 self.ensure_writable()?;
14219 if self.schema.columns.iter().any(|c| c.name == name) {
14220 return Err(MongrelError::Schema(format!(
14221 "column {name} already exists"
14222 )));
14223 }
14224 let id = if let Some(id) = requested_id.filter(|id| *id != 0) {
14225 if self.schema.columns.iter().any(|c| c.id == id) {
14226 return Err(MongrelError::Schema(format!(
14227 "column id {id} already exists"
14228 )));
14229 }
14230 id
14231 } else {
14232 self.schema
14233 .columns
14234 .iter()
14235 .map(|c| c.id)
14236 .max()
14237 .unwrap_or(0)
14238 .checked_add(1)
14239 .ok_or_else(|| MongrelError::Schema("column id space exhausted".into()))?
14240 };
14241 let column = ColumnDef {
14242 id,
14243 name: name.to_string(),
14244 ty,
14245 flags,
14246 default_value,
14247 embedding_source: None,
14248 };
14249 let mut next_schema = self.schema.clone();
14250 next_schema.columns.push(column.clone());
14251 next_schema.schema_id = next_schema
14252 .schema_id
14253 .checked_add(1)
14254 .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14255 next_schema.validate_auto_increment()?;
14256 next_schema.validate_defaults()?;
14257 Ok((column, next_schema))
14258 }
14259
14260 pub fn add_learned_range_index(&mut self, column_name: &str) -> Result<()> {
14269 self.ensure_writable()?;
14270 let cid = self
14271 .schema
14272 .columns
14273 .iter()
14274 .find(|c| c.name == column_name)
14275 .map(|c| c.id)
14276 .ok_or_else(|| MongrelError::Schema(format!("unknown column {column_name}")))?;
14277 let ty = self
14278 .schema
14279 .columns
14280 .iter()
14281 .find(|c| c.id == cid)
14282 .map(|c| c.ty.clone())
14283 .unwrap_or(TypeId::Int64);
14284 if !matches!(
14285 ty,
14286 TypeId::Int64 | TypeId::Float64 | TypeId::TimestampNanos | TypeId::Date32
14287 ) {
14288 return Err(MongrelError::Schema(format!(
14289 "LearnedRange requires a numeric column; {column_name} is {ty:?}"
14290 )));
14291 }
14292 if self
14293 .schema
14294 .indexes
14295 .iter()
14296 .any(|i| i.column_id == cid && i.kind == IndexKind::LearnedRange)
14297 {
14298 return Ok(()); }
14300 let previous_schema = self.schema.clone();
14301 let previous_learned_range = Arc::clone(&self.learned_range);
14302 let mut next_schema = previous_schema.clone();
14303 next_schema.indexes.push(IndexDef {
14304 name: format!("{}_learned_range", column_name),
14305 column_id: cid,
14306 kind: IndexKind::LearnedRange,
14307 predicate: None,
14308 options: Default::default(),
14309 });
14310 next_schema.schema_id = next_schema
14311 .schema_id
14312 .checked_add(1)
14313 .ok_or_else(|| MongrelError::Schema("schema id space exhausted".into()))?;
14314 self.apply_altered_schema_prepared(next_schema);
14315 if let Err(error) = self.build_learned_ranges() {
14316 self.apply_altered_schema_prepared(previous_schema);
14317 self.learned_range = previous_learned_range;
14318 return Err(error);
14319 }
14320 if let Err(error) = self.checkpoint_standalone_schema_change(previous_schema) {
14321 if !matches!(
14322 &error,
14323 MongrelError::DurableCommit { .. } | MongrelError::CommitOutcomeUnknown { .. }
14324 ) {
14325 self.learned_range = previous_learned_range;
14326 }
14327 return Err(error);
14328 }
14329 Ok(())
14330 }
14331
14332 fn checkpoint_standalone_schema_change(&mut self, previous_schema: Schema) -> Result<()> {
14333 let mut schema_published = false;
14334 let schema_result = match self._root_guard.as_deref() {
14335 Some(root) => write_schema_durable_with_after(root, &self.schema, || {
14336 schema_published = true;
14337 }),
14338 None => write_schema_with_after(&self.dir, &self.schema, || {
14339 schema_published = true;
14340 }),
14341 };
14342 if schema_result.is_err() && !schema_published {
14343 self.apply_altered_schema_prepared(previous_schema);
14344 return schema_result;
14345 }
14346
14347 let manifest_result = self.persist_manifest(self.current_epoch());
14348 match (schema_result, manifest_result) {
14349 (_, Ok(())) => Ok(()),
14350 (Ok(()), Err(error)) => {
14351 self.poison_after_maintenance_publish_failure();
14352 Err(MongrelError::DurableCommit {
14353 epoch: self.current_epoch().0,
14354 message: format!(
14355 "schema is durable but matching manifest publication failed: {error}"
14356 ),
14357 })
14358 }
14359 (Err(schema_error), Err(manifest_error)) => {
14360 self.poison_after_maintenance_publish_failure();
14361 Err(MongrelError::CommitOutcomeUnknown {
14362 epoch: self.current_epoch().0,
14363 message: format!(
14364 "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
14365 ),
14366 })
14367 }
14368 }
14369 }
14370
14371 pub fn set_sync_byte_threshold(&mut self, threshold: u64) {
14374 self.sync_byte_threshold = threshold;
14375 if let WalSink::Private(w) = &mut self.wal {
14376 w.set_sync_byte_threshold(threshold);
14377 }
14378 }
14379
14380 pub fn page_cache_flush(&self) {
14384 self.page_cache.flush_to_disk();
14385 }
14386
14387 pub fn page_cache_len(&self) -> usize {
14389 self.page_cache.len()
14390 }
14391
14392 pub fn decoded_cache_len(&self) -> usize {
14395 self.decoded_cache.len()
14396 }
14397
14398 pub fn drain_memtable_sorted(&mut self) -> Vec<Row> {
14401 self.memtable.drain_sorted()
14402 }
14403
14404 pub(crate) fn run_path(&self, run_id: u64) -> PathBuf {
14405 self.runs_dir().join(format!("r-{run_id}.sr"))
14406 }
14407
14408 pub(crate) fn create_run_file(&self, run_id: u64) -> Result<Option<std::fs::File>> {
14409 match self.runs_root.as_deref() {
14410 Some(root) => Ok(Some(root.create_regular_new(format!("r-{run_id}.sr"))?)),
14411 None => Ok(None),
14412 }
14413 }
14414
14415 pub(crate) fn create_run_entry(&self, name: &Path) -> Result<Option<std::fs::File>> {
14416 match self.runs_root.as_deref() {
14417 Some(root) => Ok(Some(root.create_regular_new(name)?)),
14418 None => Ok(None),
14419 }
14420 }
14421
14422 pub(crate) fn remove_run_entry(&self, name: &Path) -> Result<()> {
14423 match self.runs_root.as_deref() {
14424 Some(root) => match root.remove_file(name) {
14425 Ok(()) => Ok(()),
14426 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14427 Err(error) => Err(error.into()),
14428 },
14429 None => match std::fs::remove_file(self.runs_dir().join(name)) {
14430 Ok(()) => Ok(()),
14431 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
14432 Err(error) => Err(error.into()),
14433 },
14434 }
14435 }
14436
14437 pub(crate) fn publish_run_entry(&self, source: &Path, destination: &Path) -> Result<()> {
14438 match self.runs_root.as_deref() {
14439 Some(root) => root
14440 .rename_file_new(source, destination)
14441 .map_err(Into::into),
14442 None => crate::durable_file::rename(
14443 &self.runs_dir().join(source),
14444 &self.runs_dir().join(destination),
14445 )
14446 .map_err(Into::into),
14447 }
14448 }
14449
14450 pub(crate) fn active_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14451 self.run_refs.iter().map(|run| run.run_id)
14452 }
14453
14454 pub(crate) fn table_dir(&self) -> &Path {
14455 &self.dir
14456 }
14457
14458 pub(crate) fn schema_ref(&self) -> &crate::schema::Schema {
14459 &self.schema
14460 }
14461
14462 pub(crate) fn alloc_run_id(&mut self) -> Result<u64> {
14463 let id = self.next_run_id;
14464 self.next_run_id = self
14465 .next_run_id
14466 .checked_add(1)
14467 .ok_or_else(|| MongrelError::Full("run-id namespace exhausted".into()))?;
14468 Ok(id)
14469 }
14470
14471 pub(crate) fn link_run(&mut self, run_ref: crate::manifest::RunRef) {
14472 self.run_refs.push(run_ref);
14473 }
14474
14475 pub(crate) fn retire_run(&mut self, run_id: u128, retire_epoch: u64) {
14485 self.retiring.push(crate::manifest::RetiredRun {
14486 run_id,
14487 retire_epoch,
14488 });
14489 }
14490
14491 pub(crate) fn reap_retiring(
14495 &mut self,
14496 min_active: Epoch,
14497 backup_pinned: &std::collections::HashSet<u128>,
14498 ) -> Result<usize> {
14499 if self.retiring.is_empty() {
14500 return Ok(0);
14501 }
14502 let mut reaped = 0;
14503 let mut kept: Vec<crate::manifest::RetiredRun> = Vec::new();
14504 for r in std::mem::take(&mut self.retiring) {
14510 if min_active.0 >= r.retire_epoch && !backup_pinned.contains(&r.run_id) {
14511 let _ = self.remove_run_entry(Path::new(&format!("r-{}.sr", r.run_id)));
14512 reaped += 1;
14513 } else {
14514 kept.push(r);
14515 }
14516 }
14517 self.retiring = kept;
14518 if reaped > 0 {
14519 self.persist_manifest(self.current_epoch())?;
14520 }
14521 Ok(reaped)
14522 }
14523
14524 pub(crate) fn has_reapable_retiring(
14525 &self,
14526 min_active: Epoch,
14527 backup_pinned: &std::collections::HashSet<u128>,
14528 ) -> bool {
14529 self.retiring
14530 .iter()
14531 .any(|run| min_active.0 >= run.retire_epoch && !backup_pinned.contains(&run.run_id))
14532 }
14533
14534 pub(crate) fn recover_spilled_run(&mut self, run_ref: crate::manifest::RunRef) -> bool {
14535 if self.run_refs.iter().any(|r| r.run_id == run_ref.run_id) {
14536 return false;
14537 }
14538 self.live_count = self.live_count.saturating_add(run_ref.row_count);
14539 self.run_refs.push(run_ref);
14540 self.indexes_complete = false;
14541 true
14542 }
14543
14544 pub(crate) fn kek_ref(&self) -> Option<&Arc<Kek>> {
14545 self.kek.as_ref()
14546 }
14547
14548 pub(crate) fn open_reader(&self, run_id: u128) -> Result<RunReader> {
14549 let mut reader = match self.runs_root.as_deref() {
14550 Some(root) => RunReader::open_file_with_cache(
14551 root.open_regular(format!("r-{run_id}.sr"))?,
14552 self.schema.clone(),
14553 self.kek.clone(),
14554 Some(self.page_cache.clone()),
14555 Some(self.decoded_cache.clone()),
14556 self.table_id,
14557 Some(&self.verified_runs),
14558 None,
14559 )?,
14560 None => RunReader::open_with_cache(
14561 self.dir.join(RUNS_DIR).join(format!("r-{run_id}.sr")),
14562 self.schema.clone(),
14563 self.kek.clone(),
14564 Some(self.page_cache.clone()),
14565 Some(self.decoded_cache.clone()),
14566 self.table_id,
14567 Some(&self.verified_runs),
14568 )?,
14569 };
14570 if let Some(rr) = self.run_refs.iter().find(|r| r.run_id == run_id) {
14574 reader.set_uniform_epoch(Epoch(rr.epoch_created));
14575 }
14576 Ok(reader)
14577 }
14578
14579 pub(crate) fn run_refs(&self) -> &[RunRef] {
14580 &self.run_refs
14581 }
14582
14583 pub(crate) fn retiring_run_ids(&self) -> impl Iterator<Item = u128> + '_ {
14584 self.retiring.iter().map(|run| run.run_id)
14585 }
14586
14587 pub(crate) fn runs_dir(&self) -> PathBuf {
14588 self.runs_root
14589 .as_deref()
14590 .and_then(|root| root.io_path().ok())
14591 .unwrap_or_else(|| self.dir.join(RUNS_DIR))
14592 }
14593
14594 pub(crate) fn wal_dir(&self) -> PathBuf {
14595 self.dir.join(WAL_DIR)
14596 }
14597
14598 pub(crate) fn set_run_refs(&mut self, refs: Vec<RunRef>) {
14599 self.run_refs = refs;
14600 self.refresh_run_row_id_ranges();
14601 }
14602
14603 pub(crate) fn run_row_id_range(&self, run_id: u128) -> Option<(u64, u64)> {
14607 self.run_row_id_ranges.get(&run_id).copied()
14608 }
14609
14610 pub(crate) fn refresh_run_row_id_ranges(&mut self) {
14613 let mut ranges = HashMap::with_capacity(self.run_refs.len());
14614 for rr in &self.run_refs {
14615 if let Ok(reader) = self.open_reader(rr.run_id) {
14616 let h = reader.header();
14617 ranges.insert(rr.run_id, (h.min_row_id, h.max_row_id));
14618 }
14619 }
14620 self.run_row_id_ranges = ranges;
14621 }
14622
14623 pub(crate) fn compaction_zstd_level(&self) -> i32 {
14624 self.compaction_zstd_level
14625 }
14626
14627 pub(crate) fn kek(&self) -> Option<Arc<Kek>> {
14628 self.kek.clone()
14629 }
14630
14631 fn idx_dek(&self) -> Option<Zeroizing<[u8; DEK_LEN]>> {
14635 self.kek.as_ref().map(|k| k.derive_idx_key())
14636 }
14637
14638 fn manifest_meta_dek(&self) -> Option<[u8; DEK_LEN]> {
14642 self.kek.as_ref().map(|k| *k.derive_meta_key())
14643 }
14644
14645 pub(crate) fn indexable_column_specs(&self) -> Vec<(u16, u8)> {
14648 self.column_keys
14649 .iter()
14650 .map(|(&id, &(_, scheme))| (id, scheme))
14651 .collect()
14652 }
14653
14654 fn tokenize_value(&self, column_id: u16, v: &Value) -> Option<Value> {
14659 self.tokenize_value_enc(column_id, v)
14660 }
14661
14662 fn tokenize_value_enc(&self, column_id: u16, v: &Value) -> Option<Value> {
14663 use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
14664 let (key, scheme) = self.column_keys.get(&column_id)?;
14665 let token: Vec<u8> = match (*scheme, v) {
14666 (SCHEME_HMAC_EQ, _) => hmac_token(key, &v.encode_key()).to_vec(),
14667 (_, Value::Int64(x)) => ope_token_i64(key, *x).to_vec(),
14668 (_, Value::Float64(x)) => ope_token_f64(key, *x).to_vec(),
14669 _ => hmac_token(key, &v.encode_key()).to_vec(),
14670 };
14671 Some(Value::Bytes(token))
14672 }
14673
14674 fn index_lookup_key(&self, column_id: u16, v: &Value) -> Vec<u8> {
14676 self.index_lookup_key_bytes(column_id, &v.encode_key())
14677 }
14678
14679 fn index_lookup_key_bytes(&self, column_id: u16, encoded: &[u8]) -> Vec<u8> {
14682 {
14683 use crate::encryption::{hmac_token, SCHEME_HMAC_EQ};
14684 if let Some((key, scheme)) = self.column_keys.get(&column_id) {
14685 if *scheme == SCHEME_HMAC_EQ {
14686 return hmac_token(key, encoded).to_vec();
14687 }
14688 }
14689 }
14690 let _ = column_id;
14691 encoded.to_vec()
14692 }
14693}
14694
14695fn native_int64_strictly_increasing(col: &columnar::NativeColumn, n: usize) -> bool {
14696 let columnar::NativeColumn::Int64 { data, validity } = col else {
14697 return false;
14698 };
14699 if data.len() < n || !columnar::all_non_null(validity, n) {
14700 return false;
14701 }
14702 data.iter()
14703 .take(n)
14704 .zip(data.iter().skip(1))
14705 .all(|(a, b)| a < b)
14706}
14707
14708#[derive(Debug, Clone)]
14712pub struct ColumnStat {
14713 pub min: Option<Value>,
14714 pub max: Option<Value>,
14715 pub null_count: u64,
14716}
14717
14718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14720pub enum NativeAgg {
14721 Count,
14722 Sum,
14723 Min,
14724 Max,
14725 Avg,
14726}
14727
14728#[derive(Debug, Clone, PartialEq)]
14730pub enum NativeAggResult {
14731 Count(u64),
14732 Int(i64),
14733 Float(f64),
14734 Null,
14736}
14737
14738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14740pub enum ApproxAgg {
14741 Count,
14742 Sum,
14743 Avg,
14744}
14745
14746#[derive(Debug, Clone)]
14750pub struct ApproxResult {
14751 pub point: f64,
14753 pub ci_low: f64,
14755 pub ci_high: f64,
14757 pub n_population: u64,
14759 pub n_sample_live: usize,
14761 pub n_passing: usize,
14763}
14764
14765#[derive(Debug, Clone, PartialEq)]
14770pub enum AggState {
14771 Count(u64),
14773 SumI {
14775 sum: i128,
14776 count: u64,
14777 },
14778 SumF {
14780 sum: f64,
14781 count: u64,
14782 },
14783 AvgI {
14785 sum: i128,
14786 count: u64,
14787 },
14788 AvgF {
14790 sum: f64,
14791 count: u64,
14792 },
14793 MinI(i64),
14795 MaxI(i64),
14796 MinF(f64),
14798 MaxF(f64),
14799 Empty,
14801}
14802
14803impl AggState {
14804 pub fn merge(self, other: AggState) -> AggState {
14806 use AggState::*;
14807 match (self, other) {
14808 (Empty, x) | (x, Empty) => x,
14809 (Count(a), Count(b)) => Count(a + b),
14810 (SumI { sum: sa, count: ca }, SumI { sum: sb, count: cb }) => SumI {
14811 sum: sa + sb,
14812 count: ca + cb,
14813 },
14814 (SumF { sum: sa, count: ca }, SumF { sum: sb, count: cb }) => SumF {
14815 sum: sa + sb,
14816 count: ca + cb,
14817 },
14818 (AvgI { sum: sa, count: ca }, AvgI { sum: sb, count: cb }) => AvgI {
14819 sum: sa + sb,
14820 count: ca + cb,
14821 },
14822 (AvgF { sum: sa, count: ca }, AvgF { sum: sb, count: cb }) => AvgF {
14823 sum: sa + sb,
14824 count: ca + cb,
14825 },
14826 (MinI(a), MinI(b)) => MinI(a.min(b)),
14827 (MaxI(a), MaxI(b)) => MaxI(a.max(b)),
14828 (MinF(a), MinF(b)) => MinF(a.min(b)),
14829 (MaxF(a), MaxF(b)) => MaxF(a.max(b)),
14830 _ => Empty, }
14832 }
14833
14834 pub fn point(&self) -> Option<f64> {
14836 match self {
14837 AggState::Count(n) => Some(*n as f64),
14838 AggState::SumI { sum, .. } => Some(*sum as f64),
14839 AggState::SumF { sum, .. } => Some(*sum),
14840 AggState::AvgI { sum, count } if *count > 0 => Some(*sum as f64 / *count as f64),
14841 AggState::AvgF { sum, count } if *count > 0 => Some(*sum / *count as f64),
14842 AggState::MinI(n) => Some(*n as f64),
14843 AggState::MaxI(n) => Some(*n as f64),
14844 AggState::MinF(n) => Some(*n),
14845 AggState::MaxF(n) => Some(*n),
14846 AggState::AvgI { .. } | AggState::AvgF { .. } | AggState::Empty => None,
14847 }
14848 }
14849
14850 pub fn from_native(result: NativeAggResult, agg: NativeAgg, ty: Option<TypeId>) -> Self {
14854 let is_float = matches!(ty, Some(TypeId::Float64));
14855 match (agg, result) {
14856 (NativeAgg::Count, NativeAggResult::Count(n)) => AggState::Count(n),
14857 (NativeAgg::Sum, NativeAggResult::Int(x)) => AggState::SumI {
14858 sum: x as i128,
14859 count: 1, },
14861 (NativeAgg::Sum, NativeAggResult::Float(x)) => AggState::SumF { sum: x, count: 1 },
14862 (NativeAgg::Avg, NativeAggResult::Float(x)) => AggState::AvgF { sum: x, count: 1 },
14863 (NativeAgg::Min, NativeAggResult::Int(x)) => AggState::MinI(x),
14864 (NativeAgg::Max, NativeAggResult::Int(x)) => AggState::MaxI(x),
14865 (NativeAgg::Min, NativeAggResult::Float(x)) => AggState::MinF(x),
14866 (NativeAgg::Max, NativeAggResult::Float(x)) => AggState::MaxF(x),
14867 (NativeAgg::Count, _) => AggState::Empty,
14868 (_, NativeAggResult::Null) => AggState::Empty,
14869 _ => {
14870 let _ = is_float;
14871 AggState::Empty
14872 }
14873 }
14874 }
14875}
14876
14877#[derive(Debug, Clone)]
14880pub struct CachedAgg {
14881 pub state: AggState,
14882 pub watermark: u64,
14883 pub epoch: u64,
14884}
14885
14886#[derive(Debug, Clone)]
14888pub struct IncrementalAggResult {
14889 pub state: AggState,
14891 pub incremental: bool,
14894 pub delta_rows: u64,
14896}
14897
14898fn agg_state_from_rows(
14902 rows: &[Row],
14903 conditions: &[crate::query::Condition],
14904 index_sets: &[RowIdSet],
14905 column: Option<u16>,
14906 agg: NativeAgg,
14907 schema: &Schema,
14908 control: Option<&crate::ExecutionControl>,
14909) -> Result<AggState> {
14910 let mut count: u64 = 0;
14911 let mut sum_i: i128 = 0;
14912 let mut sum_f: f64 = 0.0;
14913 let mut mn_i: i64 = i64::MAX;
14914 let mut mx_i: i64 = i64::MIN;
14915 let mut mn_f: f64 = f64::INFINITY;
14916 let mut mx_f: f64 = f64::NEG_INFINITY;
14917 let mut saw_int = false;
14918 let mut saw_float = false;
14919 for (index, r) in rows.iter().enumerate() {
14920 execution_checkpoint(control, index)?;
14921 if !conditions
14922 .iter()
14923 .all(|c| condition_matches_row(c, r, schema))
14924 {
14925 continue;
14926 }
14927 if !index_sets.iter().all(|s| s.contains(r.row_id.0)) {
14928 continue;
14929 }
14930 match agg {
14931 NativeAgg::Count => match column {
14932 None => count += 1,
14934 Some(cid) => match r.columns.get(&cid) {
14937 None | Some(Value::Null) => {}
14938 Some(_) => count += 1,
14939 },
14940 },
14941 _ => match column.and_then(|cid| r.columns.get(&cid)) {
14942 Some(Value::Int64(n)) => {
14943 count += 1;
14944 sum_i += *n as i128;
14945 mn_i = mn_i.min(*n);
14946 mx_i = mx_i.max(*n);
14947 saw_int = true;
14948 }
14949 Some(Value::Float64(f)) => {
14950 count += 1;
14951 sum_f += f;
14952 mn_f = mn_f.min(*f);
14953 mx_f = mx_f.max(*f);
14954 saw_float = true;
14955 }
14956 _ => {}
14957 },
14958 }
14959 }
14960 Ok(match agg {
14961 NativeAgg::Count => {
14962 if count == 0 {
14963 AggState::Empty
14964 } else {
14965 AggState::Count(count)
14966 }
14967 }
14968 NativeAgg::Sum => {
14969 if count == 0 {
14970 AggState::Empty
14971 } else if saw_int {
14972 AggState::SumI { sum: sum_i, count }
14973 } else {
14974 AggState::SumF { sum: sum_f, count }
14975 }
14976 }
14977 NativeAgg::Avg => {
14978 if count == 0 {
14979 AggState::Empty
14980 } else if saw_int {
14981 AggState::AvgI { sum: sum_i, count }
14982 } else {
14983 AggState::AvgF { sum: sum_f, count }
14984 }
14985 }
14986 NativeAgg::Min => {
14987 if !saw_int && !saw_float {
14988 AggState::Empty
14989 } else if saw_int {
14990 AggState::MinI(mn_i)
14991 } else {
14992 AggState::MinF(mn_f)
14993 }
14994 }
14995 NativeAgg::Max => {
14996 if !saw_int && !saw_float {
14997 AggState::Empty
14998 } else if saw_int {
14999 AggState::MaxI(mx_i)
15000 } else {
15001 AggState::MaxF(mx_f)
15002 }
15003 }
15004 })
15005}
15006
15007fn condition_matches_row(c: &crate::query::Condition, row: &Row, schema: &Schema) -> bool {
15011 use crate::query::Condition;
15012 match c {
15013 Condition::Pk(key) => match schema.primary_key() {
15014 Some(pk) => row
15015 .columns
15016 .get(&pk.id)
15017 .map(|v| v.encode_key() == *key)
15018 .unwrap_or(false),
15019 None => false,
15020 },
15021 Condition::BitmapEq { column_id, value } => row
15022 .columns
15023 .get(column_id)
15024 .map(|v| v.encode_key() == *value)
15025 .unwrap_or(false),
15026 Condition::BitmapIn { column_id, values } => {
15027 let key = row.columns.get(column_id).map(|v| v.encode_key());
15028 match key {
15029 Some(k) => values.contains(&k),
15030 None => false,
15031 }
15032 }
15033 Condition::BytesPrefix { column_id, prefix } => row
15034 .columns
15035 .get(column_id)
15036 .map(|v| v.encode_key().starts_with(prefix))
15037 .unwrap_or(false),
15038 Condition::Range { column_id, lo, hi } => match row.columns.get(column_id) {
15039 Some(Value::Int64(n)) => *n >= *lo && *n <= *hi,
15040 _ => false,
15041 },
15042 Condition::RangeF64 {
15043 column_id,
15044 lo,
15045 lo_inclusive,
15046 hi,
15047 hi_inclusive,
15048 } => match row.columns.get(column_id) {
15049 Some(Value::Float64(n)) => {
15050 let lo_ok = if *lo_inclusive { *n >= *lo } else { *n > *lo };
15051 let hi_ok = if *hi_inclusive { *n <= *hi } else { *n < *hi };
15052 lo_ok && hi_ok
15053 }
15054 _ => false,
15055 },
15056 Condition::FmContains { column_id, pattern } => match row.columns.get(column_id) {
15057 Some(Value::Bytes(b)) => {
15058 !pattern.is_empty() && b.windows(pattern.len()).any(|w| w == &pattern[..])
15059 }
15060 _ => false,
15061 },
15062 Condition::FmContainsAll {
15063 column_id,
15064 patterns,
15065 } => match row.columns.get(column_id) {
15066 Some(Value::Bytes(b)) => patterns
15067 .iter()
15068 .all(|pat| !pat.is_empty() && b.windows(pat.len()).any(|w| w == &pat[..])),
15069 _ => false,
15070 },
15071 Condition::Ann { .. }
15072 | Condition::SparseMatch { .. }
15073 | Condition::MinHashSimilar { .. } => true,
15074 Condition::IsNull { column_id } => {
15075 matches!(row.columns.get(column_id), Some(Value::Null) | None)
15076 }
15077 Condition::IsNotNull { column_id } => {
15078 !matches!(row.columns.get(column_id), Some(Value::Null) | None)
15079 }
15080 }
15081}
15082
15083fn as_f64(v: Option<&Value>) -> Option<f64> {
15085 match v {
15086 Some(Value::Int64(n)) => Some(*n as f64),
15087 Some(Value::Float64(f)) => Some(*f),
15088 _ => None,
15089 }
15090}
15091
15092fn accumulate_int(
15096 cursor: &mut dyn crate::cursor::Cursor,
15097 control: Option<&crate::ExecutionControl>,
15098) -> Result<(u64, i128, i64, i64)> {
15099 let mut count: u64 = 0;
15100 let mut sum: i128 = 0;
15101 let mut mn: i64 = i64::MAX;
15102 let mut mx: i64 = i64::MIN;
15103 while let Some(cols) = cursor.next_batch()? {
15104 execution_checkpoint(control, 0)?;
15105 if let Some(crate::columnar::NativeColumn::Int64 { data, validity }) = cols.first() {
15106 if crate::columnar::all_non_null(validity, data.len()) {
15107 count += data.len() as u64;
15109 for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15110 execution_checkpoint(control, chunk_index * 1024)?;
15111 sum += chunk.iter().map(|&v| v as i128).sum::<i128>();
15112 mn = mn.min(*chunk.iter().min().unwrap_or(&mn));
15113 mx = mx.max(*chunk.iter().max().unwrap_or(&mx));
15114 }
15115 } else {
15116 for (i, &v) in data.iter().enumerate() {
15117 execution_checkpoint(control, i)?;
15118 if crate::columnar::validity_bit(validity, i) {
15119 count += 1;
15120 sum += v as i128;
15121 mn = mn.min(v);
15122 mx = mx.max(v);
15123 }
15124 }
15125 }
15126 }
15127 }
15128 Ok((count, sum, mn, mx))
15129}
15130
15131fn accumulate_float(
15133 cursor: &mut dyn crate::cursor::Cursor,
15134 control: Option<&crate::ExecutionControl>,
15135) -> Result<(u64, f64, f64, f64)> {
15136 let mut count: u64 = 0;
15137 let mut sum: f64 = 0.0;
15138 let mut mn: f64 = f64::INFINITY;
15139 let mut mx: f64 = f64::NEG_INFINITY;
15140 while let Some(cols) = cursor.next_batch()? {
15141 execution_checkpoint(control, 0)?;
15142 if let Some(crate::columnar::NativeColumn::Float64 { data, validity }) = cols.first() {
15143 if crate::columnar::all_non_null(validity, data.len()) {
15144 count += data.len() as u64;
15145 for (chunk_index, chunk) in data.chunks(1024).enumerate() {
15146 execution_checkpoint(control, chunk_index * 1024)?;
15147 sum += chunk.iter().sum::<f64>();
15148 mn = mn.min(chunk.iter().copied().fold(f64::INFINITY, f64::min));
15149 mx = mx.max(chunk.iter().copied().fold(f64::NEG_INFINITY, f64::max));
15150 }
15151 } else {
15152 for (i, &v) in data.iter().enumerate() {
15153 execution_checkpoint(control, i)?;
15154 if crate::columnar::validity_bit(validity, i) {
15155 count += 1;
15156 sum += v;
15157 mn = mn.min(v);
15158 mx = mx.max(v);
15159 }
15160 }
15161 }
15162 }
15163 }
15164 Ok((count, sum, mn, mx))
15165}
15166
15167#[inline]
15168fn execution_checkpoint(control: Option<&crate::ExecutionControl>, index: usize) -> Result<()> {
15169 if index.is_multiple_of(256) {
15170 control
15171 .map(crate::ExecutionControl::checkpoint)
15172 .transpose()?;
15173 }
15174 Ok(())
15175}
15176
15177fn pack_int(agg: NativeAgg, count: u64, sum: i128, mn: i64, mx: i64) -> NativeAggResult {
15178 if count == 0 && !matches!(agg, NativeAgg::Count) {
15179 return NativeAggResult::Null;
15180 }
15181 match agg {
15182 NativeAgg::Count => NativeAggResult::Count(count),
15183 NativeAgg::Sum => match sum.try_into() {
15186 Ok(v) => NativeAggResult::Int(v),
15187 Err(_) => NativeAggResult::Null,
15188 },
15189 NativeAgg::Min => NativeAggResult::Int(mn),
15190 NativeAgg::Max => NativeAggResult::Int(mx),
15191 NativeAgg::Avg => NativeAggResult::Float((sum as f64) / (count as f64)),
15192 }
15193}
15194
15195fn pack_float(agg: NativeAgg, count: u64, sum: f64, mn: f64, mx: f64) -> NativeAggResult {
15196 if count == 0 && !matches!(agg, NativeAgg::Count) {
15197 return NativeAggResult::Null;
15198 }
15199 match agg {
15200 NativeAgg::Count => NativeAggResult::Count(count),
15201 NativeAgg::Sum => NativeAggResult::Float(sum),
15202 NativeAgg::Min => NativeAggResult::Float(mn),
15203 NativeAgg::Max => NativeAggResult::Float(mx),
15204 NativeAgg::Avg => NativeAggResult::Float(sum / (count as f64)),
15205 }
15206}
15207
15208fn agg_int(
15211 stats: &[crate::page::PageStat],
15212 decode: fn(Option<&[u8]>) -> Option<i64>,
15213) -> Option<(Option<i64>, Option<i64>, u64)> {
15214 let (mut mn, mut mx, mut nulls) = (i64::MAX, i64::MIN, 0u64);
15215 let mut any = false;
15216 for s in stats {
15217 if let Some(v) = decode(s.min.as_deref()) {
15218 mn = mn.min(v);
15219 any = true;
15220 }
15221 if let Some(v) = decode(s.max.as_deref()) {
15222 mx = mx.max(v);
15223 any = true;
15224 }
15225 nulls += s.null_count;
15226 }
15227 any.then_some((Some(mn), Some(mx), nulls))
15228}
15229
15230fn agg_float(
15232 stats: &[crate::page::PageStat],
15233 decode: fn(Option<&[u8]>) -> Option<f64>,
15234) -> Option<(Option<f64>, Option<f64>, u64)> {
15235 let (mut mn, mut mx, mut nulls) = (f64::INFINITY, f64::NEG_INFINITY, 0u64);
15236 let mut any = false;
15237 for s in stats {
15238 if let Some(v) = decode(s.min.as_deref()) {
15239 mn = mn.min(v);
15240 any = true;
15241 }
15242 if let Some(v) = decode(s.max.as_deref()) {
15243 mx = mx.max(v);
15244 any = true;
15245 }
15246 nulls += s.null_count;
15247 }
15248 any.then_some((Some(mn), Some(mx), nulls))
15249}
15250
15251type SecondaryIndexes = (
15253 HashMap<u16, BitmapIndex>,
15254 HashMap<u16, AnnIndex>,
15255 HashMap<u16, FmIndex>,
15256 HashMap<u16, SparseIndex>,
15257 HashMap<u16, MinHashIndex>,
15258);
15259
15260fn empty_indexes(schema: &Schema) -> SecondaryIndexes {
15261 let mut bitmap = HashMap::new();
15262 let mut ann = HashMap::new();
15263 let mut fm = HashMap::new();
15264 let mut sparse = HashMap::new();
15265 let mut minhash = HashMap::new();
15266 for idef in &schema.indexes {
15267 match idef.kind {
15268 IndexKind::Bitmap => {
15269 bitmap.insert(idef.column_id, BitmapIndex::new());
15270 }
15271 IndexKind::Ann => {
15272 let dim = schema
15273 .columns
15274 .iter()
15275 .find(|c| c.id == idef.column_id)
15276 .and_then(|c| match c.ty {
15277 TypeId::Embedding { dim } => Some(dim as usize),
15278 _ => None,
15279 })
15280 .unwrap_or(0);
15281 let options = idef.options.ann.clone().unwrap_or_default();
15282 ann.insert(
15283 idef.column_id,
15284 AnnIndex::with_full_options(
15285 dim,
15286 options.m,
15287 options.ef_construction,
15288 options.ef_search,
15289 &options,
15290 ),
15291 );
15292 }
15293 IndexKind::FmIndex => {
15294 fm.insert(idef.column_id, FmIndex::new());
15295 }
15296 IndexKind::Sparse => {
15297 sparse.insert(idef.column_id, SparseIndex::new());
15298 }
15299 IndexKind::MinHash => {
15300 let options = idef.options.minhash.clone().unwrap_or_default();
15301 minhash.insert(
15302 idef.column_id,
15303 MinHashIndex::with_options(options.permutations, options.bands),
15304 );
15305 }
15306 _ => {}
15307 }
15308 }
15309 (bitmap, ann, fm, sparse, minhash)
15310}
15311
15312const ALTER_COLUMN_PROTECTED_FLAGS: u32 = ColumnFlags::PRIMARY_KEY
15313 | ColumnFlags::AUTO_INCREMENT
15314 | ColumnFlags::ENCRYPTED
15315 | ColumnFlags::ENCRYPTED_INDEXABLE
15316 | ColumnFlags::EMBEDDING_BINARY_QUANTIZED;
15317
15318fn validate_alter_column_flags(old: ColumnFlags, new: ColumnFlags) -> Result<()> {
15319 if (old.bits() ^ new.bits()) & ALTER_COLUMN_PROTECTED_FLAGS != 0 {
15320 return Err(MongrelError::Schema(
15321 "ALTER COLUMN may only change NULLABLE; primary key, auto-increment, encryption, and embedding flags are immutable".into(),
15322 ));
15323 }
15324 Ok(())
15325}
15326
15327fn validate_alter_column_type(
15328 schema: &Schema,
15329 old: &ColumnDef,
15330 next: &ColumnDef,
15331 has_stored_versions: bool,
15332) -> Result<()> {
15333 if old.ty == next.ty {
15334 return Ok(());
15335 }
15336 if schema.indexes.iter().any(|i| i.column_id == old.id) {
15337 return Err(MongrelError::Schema(format!(
15338 "ALTER COLUMN TYPE is not supported for indexed column '{}'",
15339 old.name
15340 )));
15341 }
15342 if !has_stored_versions || storage_compatible_type_change(old.ty.clone(), next.ty.clone()) {
15343 return Ok(());
15344 }
15345 Err(MongrelError::Schema(format!(
15346 "ALTER COLUMN TYPE from {:?} to {:?} requires an empty column or a representation-compatible type",
15347 old.ty, next.ty
15348 )))
15349}
15350
15351fn storage_compatible_type_change(old: TypeId, new: TypeId) -> bool {
15352 matches!(
15353 (old, new),
15354 (TypeId::Int64, TypeId::TimestampNanos) | (TypeId::TimestampNanos, TypeId::Int64)
15355 )
15356}
15357
15358fn rows_pk_strictly_increasing(rows: &[Row], pk_id: u16) -> bool {
15364 let mut prev: Option<i64> = None;
15365 for r in rows {
15366 match r.columns.get(&pk_id) {
15367 Some(Value::Int64(v)) => {
15368 if prev.is_some_and(|p| p >= *v) {
15369 return false;
15370 }
15371 prev = Some(*v);
15372 }
15373 _ => return false,
15374 }
15375 }
15376 true
15377}
15378
15379#[allow(clippy::too_many_arguments)]
15380fn index_into(
15381 schema: &Schema,
15382 row: &Row,
15383 hot: &mut HotIndex,
15384 bitmap: &mut HashMap<u16, BitmapIndex>,
15385 ann: &mut HashMap<u16, AnnIndex>,
15386 fm: &mut HashMap<u16, FmIndex>,
15387 sparse: &mut HashMap<u16, SparseIndex>,
15388 minhash: &mut HashMap<u16, MinHashIndex>,
15389) {
15390 for idef in &schema.indexes {
15391 let Some(val) = row.columns.get(&idef.column_id) else {
15392 continue;
15393 };
15394 match idef.kind {
15395 IndexKind::Bitmap => {
15396 if let Some(b) = bitmap.get_mut(&idef.column_id) {
15397 b.insert(val.encode_key(), row.row_id);
15398 }
15399 }
15400 IndexKind::Ann => {
15401 if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15402 if let Some(meta) = val.generated_embedding_metadata() {
15403 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15405 continue;
15406 }
15407 if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15408 .is_err()
15409 {
15410 continue;
15411 }
15412 }
15413 a.insert_validated(v, row.row_id);
15414 }
15415 }
15416 IndexKind::FmIndex => {
15417 if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15418 f.insert(b.clone(), row.row_id);
15419 }
15420 }
15421 IndexKind::Sparse => {
15422 if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15423 if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15426 s.insert(&terms, row.row_id);
15427 }
15428 }
15429 }
15430 IndexKind::MinHash => {
15431 if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15432 let tokens = crate::index::token_hashes_from_bytes(b);
15435 mh.insert(&tokens, row.row_id);
15436 }
15437 }
15438 _ => {}
15439 }
15440 }
15441 if let Some(pk_col) = schema.primary_key() {
15442 if let Some(pk_val) = row.columns.get(&pk_col.id) {
15443 hot.insert(pk_val.encode_key(), row.row_id);
15444 }
15445 }
15446}
15447
15448#[allow(clippy::too_many_arguments)]
15451fn index_into_single(
15452 idef: &IndexDef,
15453 _schema: &Schema,
15454 row: &Row,
15455 _hot: &mut HotIndex,
15456 bitmap: &mut HashMap<u16, BitmapIndex>,
15457 ann: &mut HashMap<u16, AnnIndex>,
15458 fm: &mut HashMap<u16, FmIndex>,
15459 sparse: &mut HashMap<u16, SparseIndex>,
15460 minhash: &mut HashMap<u16, MinHashIndex>,
15461) {
15462 let Some(val) = row.columns.get(&idef.column_id) else {
15463 return;
15464 };
15465 match idef.kind {
15466 IndexKind::Bitmap => {
15467 if let Some(b) = bitmap.get_mut(&idef.column_id) {
15468 b.insert(val.encode_key(), row.row_id);
15469 }
15470 }
15471 IndexKind::Ann => {
15472 if let (Some(a), Some(v)) = (ann.get_mut(&idef.column_id), val.as_embedding()) {
15473 if let Some(meta) = val.generated_embedding_metadata() {
15474 if !crate::embedding_jobs::embedding_status_is_ann_eligible(meta.status) {
15476 return;
15477 }
15478 if a.bind_or_check_semantic_identity(&meta.semantic_identity)
15479 .is_err()
15480 {
15481 return;
15482 }
15483 }
15484 a.insert_validated(v, row.row_id);
15485 }
15486 }
15487 IndexKind::FmIndex => {
15488 if let (Some(f), Value::Bytes(b)) = (fm.get_mut(&idef.column_id), val) {
15489 f.insert(b.clone(), row.row_id);
15490 }
15491 }
15492 IndexKind::Sparse => {
15493 if let (Some(s), Value::Bytes(b)) = (sparse.get_mut(&idef.column_id), val) {
15494 if let Ok(terms) = bincode::deserialize::<Vec<(u32, f32)>>(b) {
15495 s.insert(&terms, row.row_id);
15496 }
15497 }
15498 }
15499 IndexKind::MinHash => {
15500 if let (Some(mh), Value::Bytes(b)) = (minhash.get_mut(&idef.column_id), val) {
15501 let tokens = crate::index::token_hashes_from_bytes(b);
15502 mh.insert(&tokens, row.row_id);
15503 }
15504 }
15505 _ => {}
15506 }
15507}
15508
15509fn eval_partial_predicate(
15515 pred: &str,
15516 columns_map: &HashMap<u16, &Value>,
15517 name_to_id: &HashMap<&str, u16>,
15518) -> bool {
15519 let lower = pred.trim().to_ascii_lowercase();
15520 if let Some(rest) = lower.strip_suffix(" is not null") {
15522 let col_name = rest.trim();
15523 if let Some(col_id) = name_to_id.get(col_name) {
15524 return columns_map
15525 .get(col_id)
15526 .is_some_and(|v| !matches!(v, Value::Null));
15527 }
15528 }
15529 if let Some(rest) = lower.strip_suffix(" is null") {
15531 let col_name = rest.trim();
15532 if let Some(col_id) = name_to_id.get(col_name) {
15533 return columns_map
15534 .get(col_id)
15535 .is_none_or(|v| matches!(v, Value::Null));
15536 }
15537 }
15538 true
15541}
15542
15543#[allow(dead_code)]
15549fn bulk_index_key(
15550 column_keys: &HashMap<u16, ([u8; 32], u8)>,
15551 column_id: u16,
15552 ty: TypeId,
15553 col: &columnar::NativeColumn,
15554 i: usize,
15555) -> Option<Vec<u8>> {
15556 let encoded = columnar::encode_key_native(ty, col, i)?;
15557 {
15558 use crate::encryption::{hmac_token, ope_token_f64, ope_token_i64, SCHEME_HMAC_EQ};
15559 if let Some((key, scheme)) = column_keys.get(&column_id) {
15560 return Some(match (*scheme, col) {
15561 (SCHEME_HMAC_EQ, _) => hmac_token(key, &encoded).to_vec(),
15562 (_, columnar::NativeColumn::Int64 { data, .. }) => {
15563 ope_token_i64(key, data[i]).to_vec()
15564 }
15565 (_, columnar::NativeColumn::Float64 { data, .. }) => {
15566 ope_token_f64(key, data[i]).to_vec()
15567 }
15568 _ => hmac_token(key, &encoded).to_vec(),
15569 });
15570 }
15571 }
15572 Some(encoded)
15573}
15574
15575pub(crate) fn write_schema(dir: &Path, schema: &Schema) -> Result<()> {
15576 write_schema_with_after(dir, schema, || {})
15577}
15578
15579pub(crate) fn write_schema_durable(
15580 root: &crate::durable_file::DurableRoot,
15581 schema: &Schema,
15582) -> Result<()> {
15583 write_schema_durable_with_after(root, schema, || {})
15584}
15585
15586fn write_schema_with_after<F>(dir: &Path, schema: &Schema, after_publish: F) -> Result<()>
15587where
15588 F: FnOnce(),
15589{
15590 let json = serde_json::to_string_pretty(schema)
15591 .map_err(|e| MongrelError::Schema(format!("encode schema: {e}")))?;
15592 crate::durable_file::write_atomic_with_after(
15593 &dir.join(SCHEMA_FILENAME),
15594 json.as_bytes(),
15595 after_publish,
15596 )?;
15597 Ok(())
15598}
15599
15600fn write_schema_durable_with_after<F>(
15601 root: &crate::durable_file::DurableRoot,
15602 schema: &Schema,
15603 after_publish: F,
15604) -> Result<()>
15605where
15606 F: FnOnce(),
15607{
15608 let json = serde_json::to_string_pretty(schema)
15609 .map_err(|error| MongrelError::Schema(format!("encode schema: {error}")))?;
15610 root.write_atomic_with_after(SCHEMA_FILENAME, json.as_bytes(), after_publish)?;
15611 Ok(())
15612}
15613
15614fn checkpoint_current_schema(table: &mut Table) -> Result<()> {
15615 let mut schema_published = false;
15616 let schema_result = match table._root_guard.as_deref() {
15617 Some(root) => write_schema_durable_with_after(root, &table.schema, || {
15618 schema_published = true;
15619 }),
15620 None => write_schema_with_after(&table.dir, &table.schema, || {
15621 schema_published = true;
15622 }),
15623 };
15624 if schema_result.is_err() && !schema_published {
15625 return schema_result;
15626 }
15627 match table.persist_manifest(table.current_epoch()) {
15628 Ok(()) => Ok(()),
15629 Err(manifest_error) => Err(match schema_result {
15630 Ok(()) => manifest_error,
15631 Err(schema_error) => MongrelError::Other(format!(
15632 "schema publication sync failed ({schema_error}); matching manifest publication also failed ({manifest_error})"
15633 )),
15634 }),
15635 }
15636}
15637
15638fn read_schema(dir: &Path) -> Result<Schema> {
15639 let file = crate::durable_file::open_regular_nofollow(&dir.join(SCHEMA_FILENAME))?;
15640 read_schema_file(file)
15641}
15642
15643fn read_schema_file(file: std::fs::File) -> Result<Schema> {
15644 const MAX_SCHEMA_BYTES: u64 = 16 * 1024 * 1024;
15645 use std::io::Read;
15646
15647 let length = file.metadata()?.len();
15648 if length > MAX_SCHEMA_BYTES {
15649 return Err(MongrelError::ResourceLimitExceeded {
15650 resource: "schema bytes",
15651 requested: usize::try_from(length).unwrap_or(usize::MAX),
15652 limit: MAX_SCHEMA_BYTES as usize,
15653 });
15654 }
15655 let mut bytes = Vec::with_capacity(length as usize);
15656 file.take(MAX_SCHEMA_BYTES + 1).read_to_end(&mut bytes)?;
15657 if bytes.len() as u64 != length {
15658 return Err(MongrelError::Schema(
15659 "schema length changed while reading".into(),
15660 ));
15661 }
15662 serde_json::from_slice(&bytes).map_err(|e| MongrelError::Schema(format!("decode schema: {e}")))
15663}
15664
15665fn preflight_standalone_open(
15666 dir: &Path,
15667 runs_root: Option<&crate::durable_file::DurableRoot>,
15668 idx_root: Option<&crate::durable_file::DurableRoot>,
15669 manifest: &Manifest,
15670 schema: &Schema,
15671 records: &[crate::wal::Record],
15672 kek: Option<Arc<Kek>>,
15673) -> Result<()> {
15674 crate::wal::validate_shared_transaction_framing(records)?;
15675 if manifest.schema_id > schema.schema_id
15676 || manifest.flushed_epoch > manifest.current_epoch
15677 || manifest.global_idx_epoch > manifest.current_epoch
15678 || manifest.next_row_id == u64::MAX
15679 || manifest.auto_inc_next < 0
15680 || manifest.auto_inc_next == i64::MAX
15681 || (schema.auto_increment_column().is_none() && manifest.auto_inc_next != 0)
15682 {
15683 return Err(MongrelError::InvalidArgument(
15684 "manifest counters or schema identity are invalid".into(),
15685 ));
15686 }
15687 let mut run_ids = HashSet::new();
15688 let mut maximum_row_id = None::<u64>;
15689 for run in &manifest.runs {
15690 if run.run_id >= u64::MAX as u128
15691 || !run_ids.insert(run.run_id)
15692 || run.epoch_created > manifest.current_epoch
15693 {
15694 return Err(MongrelError::InvalidArgument(
15695 "manifest contains an invalid or duplicate active run".into(),
15696 ));
15697 }
15698 let mut reader = match runs_root {
15699 Some(root) => RunReader::open_file(
15700 root.open_regular(format!("r-{}.sr", run.run_id as u64))?,
15701 schema.clone(),
15702 kek.clone(),
15703 )?,
15704 None => RunReader::open(
15705 dir.join(RUNS_DIR)
15706 .join(format!("r-{}.sr", run.run_id as u64)),
15707 schema.clone(),
15708 kek.clone(),
15709 )?,
15710 };
15711 let header = reader.header();
15712 if header.run_id != run.run_id
15713 || header.level != run.level
15714 || header.row_count != run.row_count
15715 || !header.is_uniform_epoch() && header.epoch_created != run.epoch_created
15716 || header.is_uniform_epoch() && header.epoch_created != 0
15717 || header.schema_id > schema.schema_id
15718 {
15719 return Err(MongrelError::InvalidArgument(format!(
15720 "run {} differs from its manifest",
15721 run.run_id
15722 )));
15723 }
15724 if header.row_count != 0 {
15725 maximum_row_id = Some(
15726 maximum_row_id.map_or(header.max_row_id, |value| value.max(header.max_row_id)),
15727 );
15728 }
15729 reader.validate_all_pages()?;
15730 }
15731 if maximum_row_id.is_some_and(|maximum| manifest.next_row_id <= maximum) {
15732 return Err(MongrelError::InvalidArgument(
15733 "manifest next_row_id does not advance beyond persisted rows".into(),
15734 ));
15735 }
15736 for run in &manifest.retiring {
15737 if run.run_id >= u64::MAX as u128
15738 || run.retire_epoch > manifest.current_epoch
15739 || !run_ids.insert(run.run_id)
15740 {
15741 return Err(MongrelError::InvalidArgument(
15742 "manifest contains an invalid or duplicate retired run".into(),
15743 ));
15744 }
15745 }
15746 let idx_dek = kek.as_ref().map(|key| key.derive_idx_key());
15747 match idx_root {
15748 Some(root) => {
15749 global_idx::read_root(root, manifest.table_id, schema, idx_dek.as_deref())?;
15750 }
15751 None => {
15752 global_idx::read(dir, manifest.table_id, schema, idx_dek.as_deref())?;
15753 }
15754 }
15755
15756 let committed = records
15757 .iter()
15758 .filter_map(|record| match record.op {
15759 Op::TxnCommit { epoch, .. } => Some((record.txn_id, epoch)),
15760 _ => None,
15761 })
15762 .collect::<HashMap<_, _>>();
15763 for record in records {
15764 let Some(&_commit_epoch) = committed.get(&record.txn_id) else {
15765 continue;
15766 };
15767 match &record.op {
15768 Op::Put { table_id, rows } => {
15769 if *table_id != manifest.table_id {
15770 return Err(MongrelError::CorruptWal {
15771 offset: record.seq.0,
15772 reason: format!(
15773 "private WAL record references table {table_id}, expected {}",
15774 manifest.table_id
15775 ),
15776 });
15777 }
15778 let rows: Vec<Row> =
15779 bincode::deserialize(rows).map_err(|error| MongrelError::CorruptWal {
15780 offset: record.seq.0,
15781 reason: format!("committed Put payload could not be decoded: {error}"),
15782 })?;
15783 for row in rows {
15784 if row.deleted || row.row_id.0 == u64::MAX {
15785 return Err(MongrelError::CorruptWal {
15786 offset: record.seq.0,
15787 reason: "committed Put contains an invalid row identity".into(),
15788 });
15789 }
15790 let cells = row.columns.into_iter().collect::<Vec<_>>();
15791 schema
15792 .validate_values(&cells)
15793 .map_err(|error| MongrelError::CorruptWal {
15794 offset: record.seq.0,
15795 reason: format!("committed Put violates table schema: {error}"),
15796 })?;
15797 if schema.auto_increment_column().is_some_and(|column| {
15798 matches!(
15799 cells.iter().find(|(id, _)| *id == column.id),
15800 Some((_, Value::Int64(value))) if *value == i64::MAX
15801 )
15802 }) {
15803 return Err(MongrelError::CorruptWal {
15804 offset: record.seq.0,
15805 reason: "committed Put exhausts AUTO_INCREMENT".into(),
15806 });
15807 }
15808 }
15809 }
15810 Op::Delete { table_id, .. } | Op::TruncateTable { table_id }
15811 if *table_id != manifest.table_id =>
15812 {
15813 return Err(MongrelError::CorruptWal {
15814 offset: record.seq.0,
15815 reason: format!(
15816 "private WAL record references table {table_id}, expected {}",
15817 manifest.table_id
15818 ),
15819 });
15820 }
15821 Op::TxnCommit { added_runs, .. } if !added_runs.is_empty() => {
15822 return Err(MongrelError::CorruptWal {
15823 offset: record.seq.0,
15824 reason: "private WAL contains shared spilled-run metadata".into(),
15825 });
15826 }
15827 _ => {}
15828 }
15829 }
15830 Ok(())
15831}
15832
15833fn next_wal_segment(wal_dir: &Path) -> Result<PathBuf> {
15834 Ok(wal_dir.join(format!("seg-{:06}.wal", next_wal_number(wal_dir)?)))
15835}
15836
15837fn wal_segment_number(path: &Path) -> Option<u64> {
15838 path.file_stem()
15839 .and_then(|stem| stem.to_str())
15840 .and_then(|stem| stem.strip_prefix("seg-"))
15841 .and_then(|number| number.parse().ok())
15842}
15843
15844fn latest_wal_segment(wal_dir: &Path) -> Result<Option<PathBuf>> {
15845 let n = list_wal_numbers(wal_dir)?;
15846 Ok(n.map(|max| wal_dir.join(format!("seg-{max:06}.wal"))))
15847}
15848
15849fn next_wal_number(wal_dir: &Path) -> Result<u32> {
15850 list_wal_numbers(wal_dir)?
15851 .map(|maximum| {
15852 maximum
15853 .checked_add(1)
15854 .ok_or_else(|| MongrelError::Full("WAL segment namespace exhausted".into()))
15855 })
15856 .unwrap_or(Ok(0))
15857}
15858
15859fn list_wal_numbers(wal_dir: &Path) -> Result<Option<u32>> {
15860 let mut max_n = None;
15861 let entries = match std::fs::read_dir(wal_dir) {
15862 Ok(entries) => entries,
15863 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
15864 Err(error) => return Err(error.into()),
15865 };
15866 for entry in entries {
15867 let entry = entry?;
15868 let fname = entry.file_name();
15869 let Some(s) = fname.to_str() else {
15870 continue;
15871 };
15872 let Some(stripped) = s.strip_prefix("seg-") else {
15873 continue;
15874 };
15875 let Some(number) = stripped.strip_suffix(".wal") else {
15876 return Err(MongrelError::CorruptWal {
15877 offset: 0,
15878 reason: format!("malformed WAL segment name {s:?}"),
15879 });
15880 };
15881 let n = number
15882 .parse::<u32>()
15883 .map_err(|_| MongrelError::CorruptWal {
15884 offset: 0,
15885 reason: format!("malformed WAL segment name {s:?}"),
15886 })?;
15887 if s != format!("seg-{n:06}.wal") || !entry.file_type()?.is_file() {
15888 return Err(MongrelError::CorruptWal {
15889 offset: n as u64,
15890 reason: format!("noncanonical or nonregular WAL segment {s:?}"),
15891 });
15892 }
15893 max_n = Some(max_n.map(|m: u32| m.max(n)).unwrap_or(n));
15894 }
15895 Ok(max_n)
15896}
15897
15898#[cfg(test)]
15923mod rem001_multi_run_hlc_authority {
15924 use super::*;
15925 use crate::epoch::{Epoch, Snapshot, VersionStamp};
15926 use crate::memtable::{Row, Value};
15927 use crate::query::{Condition, Query};
15928 use crate::schema::{ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema, TypeId};
15929 use mongreldb_types::hlc::HlcTimestamp;
15930 use tempfile::tempdir;
15931
15932 fn hlc(physical_micros: u64) -> HlcTimestamp {
15933 HlcTimestamp {
15934 physical_micros,
15935 logical: 0,
15936 node_tiebreaker: 1,
15937 }
15938 }
15939
15940 fn pk_schema() -> Schema {
15941 Schema {
15942 schema_id: 1,
15943 columns: vec![
15944 ColumnDef {
15945 id: 1,
15946 name: "id".into(),
15947 ty: TypeId::Int64,
15948 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
15949 default_value: None,
15950 embedding_source: None,
15951 },
15952 ColumnDef {
15953 id: 2,
15954 name: "name".into(),
15955 ty: TypeId::Bytes,
15956 flags: ColumnFlags::empty(),
15957 default_value: None,
15958 embedding_source: None,
15959 },
15960 ],
15961 indexes: Vec::new(),
15962 colocation: vec![],
15963 constraints: Default::default(),
15964 clustered: false,
15965 }
15966 }
15967
15968 fn pk_schema_with_bitmap() -> Schema {
15969 Schema {
15970 schema_id: 1,
15971 columns: vec![
15972 ColumnDef {
15973 id: 1,
15974 name: "id".into(),
15975 ty: TypeId::Int64,
15976 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
15977 default_value: None,
15978 embedding_source: None,
15979 },
15980 ColumnDef {
15981 id: 2,
15982 name: "name".into(),
15983 ty: TypeId::Bytes,
15984 flags: ColumnFlags::empty(),
15985 default_value: None,
15986 embedding_source: None,
15987 },
15988 ],
15989 indexes: vec![IndexDef {
15992 name: "name_bitmap".into(),
15993 column_id: 2,
15994 kind: IndexKind::Bitmap,
15995 predicate: None,
15996 options: Default::default(),
15997 }],
15998 colocation: vec![],
15999 constraints: Default::default(),
16000 clustered: false,
16001 }
16002 }
16003
16004 fn encode_put(table_id: u64, row: &Row) -> Vec<u8> {
16005 use crate::database::StagedTxnWrite;
16006 bincode::serialize(&StagedTxnWrite::Put {
16007 table_id,
16008 rows: bincode::serialize(&vec![row.clone()]).expect("encode row"),
16009 })
16010 .expect("encode payload")
16011 }
16012
16013 fn build_inverted_database(dir: &std::path::Path, schema: Schema) -> crate::Database {
16027 let db = crate::Database::create(dir).unwrap();
16028 db.create_table("t", schema).unwrap();
16029 let table_id = db.table_id("t").unwrap();
16030 let rid = RowId(7);
16031
16032 let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16033 .with_column(1, Value::Int64(7))
16034 .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()));
16035 let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16036 .with_column(1, Value::Int64(7))
16037 .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()));
16038
16039 db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16040 .expect("first apply");
16041 {
16042 let table = db.table("t").unwrap();
16043 table.lock().force_flush().expect("flush run A");
16044 }
16045
16046 db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16047 .expect("second apply");
16048 {
16049 let table = db.table("t").unwrap();
16050 table.lock().force_flush().expect("flush run B");
16051 }
16052
16053 db
16054 }
16055
16056 fn build_inverted_ttl_database(dir: &std::path::Path) -> crate::Database {
16061 let db = crate::Database::create(dir).unwrap();
16062 db.create_table("t", ttl_schema()).unwrap();
16063 let table_id = db.table_id("t").unwrap();
16064 let rid = RowId(7);
16065 let read_time_ns: i64 = 1_000_000_000;
16066 let newer = Row::new_with_hlc(rid, Epoch(1), hlc(500))
16067 .with_column(1, Value::Int64(7))
16068 .with_column(2, Value::Bytes(b"newer-by-HLC".to_vec()))
16069 .with_column(3, Value::Int64(read_time_ns + 60 * 1_000_000_000));
16070 let older = Row::new_with_hlc(rid, Epoch(2), hlc(400))
16071 .with_column(1, Value::Int64(7))
16072 .with_column(2, Value::Bytes(b"older-by-HLC".to_vec()))
16073 .with_column(3, Value::Int64(read_time_ns - 60 * 1_000_000_000));
16074
16075 db.apply_staged_txn_writes(1, &[encode_put(table_id, &newer)], hlc(500))
16076 .expect("first apply");
16077 {
16078 let table = db.table("t").unwrap();
16079 table.lock().force_flush().expect("flush run A");
16080 }
16081 db.apply_staged_txn_writes(2, &[encode_put(table_id, &older)], hlc(400))
16082 .expect("second apply");
16083 {
16084 let table = db.table("t").unwrap();
16085 table.lock().force_flush().expect("flush run B");
16086 }
16087
16088 db
16089 }
16090
16091 fn ttl_schema() -> Schema {
16092 Schema {
16093 schema_id: 1,
16094 columns: vec![
16095 ColumnDef {
16096 id: 1,
16097 name: "id".into(),
16098 ty: TypeId::Int64,
16099 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
16100 default_value: None,
16101 embedding_source: None,
16102 },
16103 ColumnDef {
16104 id: 2,
16105 name: "name".into(),
16106 ty: TypeId::Bytes,
16107 flags: ColumnFlags::empty(),
16108 default_value: None,
16109 embedding_source: None,
16110 },
16111 ColumnDef {
16112 id: 3,
16113 name: "ttl_ts".into(),
16114 ty: TypeId::Int64,
16115 flags: ColumnFlags::empty(),
16116 default_value: None,
16117 embedding_source: None,
16118 },
16119 ],
16120 indexes: Vec::new(),
16121 colocation: vec![],
16122 constraints: Default::default(),
16123 clustered: false,
16124 }
16125 }
16126
16127 #[test]
16128 fn multi_run_rows_for_rids_uses_hlc_winner_when_epoch_is_inverted() {
16129 let dir = tempdir().unwrap();
16130 let db = build_inverted_database(dir.path(), pk_schema());
16131 let table = db.table("t").unwrap();
16132 let table = table.lock();
16133 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16137 let rows = table
16138 .rows_for_rids(&[7], snap)
16139 .expect("rows_for_rids across two runs");
16140 assert_eq!(rows.len(), 1, "one row materialised across two runs");
16141 assert_eq!(
16142 rows[0].columns.get(&2),
16143 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16144 "multi-run rows_for_rids must honor HLC authority"
16145 );
16146 }
16147
16148 #[test]
16149 fn multi_run_projected_column_uses_hlc_winner_when_epoch_is_inverted() {
16150 let dir = tempdir().unwrap();
16151 let db = build_inverted_database(dir.path(), pk_schema());
16152 let table = db.table("t").unwrap();
16153 let table = table.lock();
16154 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16155 let projected = table
16156 .values_for_rids_at(&[7], 2, snap, i64::MAX)
16157 .expect("values_for_rids_at across two runs");
16158 assert_eq!(projected.len(), 1);
16159 assert_eq!(
16160 projected[0].1,
16161 Value::Bytes(b"newer-by-HLC".to_vec()),
16162 "multi-run projection must pick the HLC-newer column"
16163 );
16164 }
16165
16166 #[test]
16167 fn ann_candidate_eligibility_uses_hlc_winner_across_runs() {
16168 let dir = tempdir().unwrap();
16169 let db = build_inverted_database(dir.path(), pk_schema());
16170 let table = db.table("t").unwrap();
16171 let table = table.lock();
16172 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16173 let eligible = table
16176 .eligible_candidate_ids(&[RowId(7)], 2, snap, None)
16177 .expect("eligibility across runs");
16178 assert!(
16179 eligible.contains(&RowId(7)),
16180 "HLC-newer rid must remain eligible across runs"
16181 );
16182 }
16183
16184 #[test]
16185 fn ttl_inverted_run_is_admitted_via_values_for_rids_at() {
16186 let dir = tempdir().unwrap();
16187 let db = build_inverted_ttl_database(dir.path());
16188 let table = db.table("t").unwrap();
16189 let table = table.lock();
16190 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16191 let now_ns: i64 = 1_000_000_000;
16192 let projected = table
16196 .values_for_rids_at(&[7], 2, snap, now_ns)
16197 .expect("ttl-aware projection");
16198 assert_eq!(projected.len(), 1, "TTL must admit the HLC-newer row");
16199 assert_eq!(
16200 projected[0].1,
16201 Value::Bytes(b"newer-by-HLC".to_vec()),
16202 "TTL must be read from the HLC-newer run; older run's timestamp is expired"
16203 );
16204 }
16205
16206 #[test]
16207 fn hot_candidate_inspection_uses_full_snapshot_for_run_versions() {
16208 let dir = tempdir().unwrap();
16213 let db = build_inverted_database(dir.path(), pk_schema());
16214 let table = db.table("t").unwrap();
16215 let table = table.lock();
16216 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16217 let row = table
16218 .get(RowId(7), snap)
16219 .expect("Table::get across two runs");
16220 assert_eq!(
16221 row.columns.get(&2),
16222 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16223 "Table::get must surface the HLC-newer winner"
16224 );
16225 }
16226
16227 #[test]
16228 fn learned_range_rebuild_indexes_only_hlc_visible_winners() {
16229 let dir = tempdir().unwrap();
16236 let db = build_inverted_database(dir.path(), pk_schema());
16237 let handle = db.table("t").unwrap();
16238 let mut table = handle.lock();
16239 table.rebuild_indexes_from_runs().expect("rebuild");
16240 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16241 let rows = table
16242 .rows_for_rids(&[7], snap)
16243 .expect("post-rebuild rows_for_rids");
16244 assert_eq!(rows.len(), 1);
16245 assert_eq!(
16246 rows[0].columns.get(&2),
16247 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16248 "post-rebuild row must be the HLC-newer winner"
16249 );
16250 }
16251
16252 #[test]
16253 fn rebuild_indexes_uses_global_hlc_winners_not_run_iteration_order() {
16254 let dir = tempdir().unwrap();
16267 let db = build_inverted_database(dir.path(), pk_schema_with_bitmap());
16268 let handle = db.table("t").unwrap();
16269 let mut table = handle.lock();
16270 table.rebuild_indexes_from_runs().expect("rebuild");
16271 let snap = Snapshot::at_hlc(Epoch(10), hlc(600));
16272 let row = table.get(RowId(7), snap).expect("post-rebuild Table::get");
16274 assert_eq!(
16275 row.columns.get(&2),
16276 Some(&Value::Bytes(b"newer-by-HLC".to_vec())),
16277 "PK lookup must resolve to the HLC-newer winner"
16278 );
16279 let query_newer = Query::new().and(Condition::BitmapEq {
16283 column_id: 2,
16284 value: b"newer-by-HLC".to_vec(),
16285 });
16286 let rows_newer = table.query(&query_newer).expect("bitmap eq newer");
16287 let rids_newer: Vec<u64> = rows_newer.iter().map(|r| r.row_id.0).collect();
16288 assert!(
16289 rids_newer.contains(&7),
16290 "bitmap must include the HLC-newer value (got {rids_newer:?})"
16291 );
16292 let query_older = Query::new().and(Condition::BitmapEq {
16293 column_id: 2,
16294 value: b"older-by-HLC".to_vec(),
16295 });
16296 let rows_older = table.query(&query_older).expect("bitmap eq older");
16297 let rids_older: Vec<u64> = rows_older.iter().map(|r| r.row_id.0).collect();
16298 assert!(
16299 !rids_older.contains(&7),
16300 "bitmap must NOT include the HLC-older value (got {rids_older:?})"
16301 );
16302 }
16303
16304 #[test]
16305 fn version_stamp_is_newer_than_matches_snapshot_rule() {
16306 let early = hlc(100);
16309 let late = hlc(200);
16310 let newer = VersionStamp {
16311 epoch: Epoch(9),
16312 commit_ts: Some(late),
16313 };
16314 let older = VersionStamp {
16315 epoch: Epoch(50),
16316 commit_ts: Some(early),
16317 };
16318 assert!(newer.is_newer_than(older));
16319 assert!(!older.is_newer_than(newer));
16320 let a = VersionStamp {
16321 epoch: Epoch(5),
16322 commit_ts: None,
16323 };
16324 let b = VersionStamp {
16325 epoch: Epoch(4),
16326 commit_ts: None,
16327 };
16328 assert!(a.is_newer_than(b));
16329 }
16330}