1use crate::columnar;
19use crate::encryption::{setup_run_encryption, Cipher, Kek, RunEncryption};
20use crate::epoch::{Epoch, Snapshot, VersionStamp};
21use crate::error::{MongrelError, Result};
22use crate::index::pgm::PgmIndex;
23use crate::memtable::{Row, Value};
24use crate::page::{Encoding, PageStat};
25use crate::row_id_set::RowIdSet;
26use crate::rowid::RowId;
27use crate::schema::{Schema, TypeId};
28use mongreldb_types::hlc::HlcTimestamp;
29use serde::{Deserialize, Serialize};
30use sha2::{Digest, Sha256};
31use std::collections::HashMap;
32use std::fs::{File, OpenOptions};
33use std::io::{Read, Seek, SeekFrom, Write};
34use std::path::{Path, PathBuf};
35use std::sync::Arc;
36
37pub const RUN_MAGIC: [u8; 8] = *b"MONGRRUN";
38pub const RUN_FORMAT_VERSION: u16 = 1;
39pub const RUN_HEADER_VERSION: u16 = 2;
45pub const RUN_HEADER_PAD: usize = 256;
46const MAX_RUN_PAGE_BYTES: u64 = 64 * 1024 * 1024 + 32;
47
48const ENC_STATS_NONCE_COLUMN: u16 = u16::MAX;
53const ENC_STATS_NONCE_SEQ: u32 = u16::MAX as u32;
54
55type PageMinMax = (Option<Vec<u8>>, Option<Vec<u8>>);
57
58type EncryptedColumnStats = Vec<(u16, Vec<PageMinMax>)>;
65
66const GCM_TAG_LEN: usize = 16;
71
72fn on_disk_len(page_len: usize, encrypted: bool) -> usize {
75 if encrypted {
76 page_len + GCM_TAG_LEN
77 } else {
78 page_len
79 }
80}
81
82pub const RUN_FLAG_ENCRYPTED: u8 = 1 << 0;
83pub const RUN_FLAG_TOMBSTONE_ONLY: u8 = 1 << 1;
84pub const RUN_FLAG_CLEAN: u8 = 1 << 2;
93pub const RUN_FLAG_UNIFORM_EPOCH: u8 = 1 << 3;
101pub const SORT_KEY_ROW_ID: u16 = 0xFFFF;
102
103pub const SYS_ROW_ID: u16 = 0xFFFE;
105pub const SYS_EPOCH: u16 = 0xFFFD;
106pub const SYS_DELETED: u16 = 0xFFFC;
107pub const SYS_COMMIT_TS: u16 = 0xFFFB;
113
114const COMMIT_TS_BYTES: usize = 16;
116
117fn encode_commit_ts_value(ts: Option<HlcTimestamp>) -> Value {
119 match ts {
120 None => Value::Null,
121 Some(ts) => {
122 let mut buf = [0u8; COMMIT_TS_BYTES];
123 buf[0..8].copy_from_slice(&ts.physical_micros.to_le_bytes());
124 buf[8..12].copy_from_slice(&ts.logical.to_le_bytes());
125 buf[12..16].copy_from_slice(&ts.node_tiebreaker.to_le_bytes());
126 Value::Bytes(buf.to_vec())
127 }
128 }
129}
130
131pub(crate) fn decode_commit_ts_value(value: Option<&Value>) -> Option<HlcTimestamp> {
133 match value {
134 Some(Value::Bytes(bytes)) if bytes.len() == COMMIT_TS_BYTES => {
135 let physical_micros = u64::from_le_bytes(bytes[0..8].try_into().ok()?);
136 let logical = u32::from_le_bytes(bytes[8..12].try_into().ok()?);
137 let node_tiebreaker = u32::from_le_bytes(bytes[12..16].try_into().ok()?);
138 Some(HlcTimestamp {
139 physical_micros,
140 logical,
141 node_tiebreaker,
142 })
143 }
144 _ => None,
145 }
146}
147
148#[derive(Debug, Clone)]
152pub(crate) struct VersionedColumnValue {
153 pub stamp: VersionStamp,
154 pub deleted: bool,
155 pub value: Option<Value>,
156}
157
158#[derive(Debug, Clone, Copy)]
164pub(crate) struct VersionVisibility {
165 pub stamp: VersionStamp,
166 pub deleted: bool,
167}
168
169type FoundVersionPage = (u64, Option<HlcTimestamp>, usize, usize);
174
175fn is_system_column_id(column_id: u16) -> bool {
177 matches!(
178 column_id,
179 SYS_ROW_ID | SYS_EPOCH | SYS_DELETED | SYS_COMMIT_TS
180 )
181}
182
183const LEARNED_EPSILON: usize = 64;
186
187fn build_learned_trailer(row_ids: &[Value]) -> Vec<u8> {
191 let points: Vec<(u64, usize)> = row_ids
192 .iter()
193 .enumerate()
194 .filter_map(|(i, v)| match v {
195 Value::Int64(r) => Some((*r as u64, i)),
196 _ => None,
197 })
198 .collect();
199 let pgm = PgmIndex::build(&points, LEARNED_EPSILON);
200 bincode::serialize(&pgm).expect("pgm serialize")
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct RunHeader {
205 pub magic: [u8; 8],
206 pub format_version: u16,
207 pub header_layout_version: u16,
208 pub run_id: u128,
209 pub content_hash: [u8; 32],
210 pub schema_id: u64,
211 pub epoch_created: u64,
212 pub level: u8,
213 pub flags: u8,
214 pub sort_key_column_id: u16,
215 pub row_count: u64,
216 pub min_row_id: u64,
217 pub max_row_id: u64,
218 pub column_count: u64,
219 pub column_dir_offset: u64,
220 pub index_trailer_offset: u64,
221 pub encryption_descriptor_offset: u64,
222 pub footer_offset: u64,
223 pub encrypted_stats_offset: u64,
227 pub encrypted_stats_len: u64,
228}
229
230impl RunHeader {
231 pub fn is_encrypted(&self) -> bool {
232 self.flags & RUN_FLAG_ENCRYPTED != 0
233 }
234 pub fn is_clean(&self) -> bool {
235 self.flags & RUN_FLAG_CLEAN != 0
236 }
237 pub fn is_uniform_epoch(&self) -> bool {
238 self.flags & RUN_FLAG_UNIFORM_EPOCH != 0
239 }
240}
241
242#[derive(Debug, Clone, Serialize, Deserialize)]
243pub struct ColumnPageHeader {
244 pub column_id: u16,
245 pub type_id_tag: u16,
246 pub encoding: u8,
247 pub flags: u8,
248 pub page_count: u32,
249 pub page_region_offset: u64,
250 pub page_region_len: u64,
251 pub page_stats: Vec<PageStat>,
252}
253
254impl ColumnPageHeader {
255 const PAGE_ENCRYPTED: u8 = 1 << 0;
256}
257
258const RUN_MAC_LEN: usize = 32;
261
262fn compute_run_mac(
266 enc: Option<&RunEncryption>,
267 header_bytes: &[u8],
268 dir_bytes: &[u8],
269) -> Option<[u8; RUN_MAC_LEN]> {
270 {
271 if let Some(e) = enc {
272 if let Some(mac_key) = &e.mac_key {
273 return Some(crate::encryption::run_metadata_mac(
274 mac_key,
275 header_bytes,
276 dir_bytes,
277 &e.descriptor_bytes,
278 ));
279 }
280 }
281 }
282 None
283}
284
285pub struct ColumnPayload {
287 pub column_id: u16,
288 pub type_id_tag: u16,
289 pub encoding: Encoding,
290 pub pages: Vec<Vec<u8>>,
291 pub page_stats: Vec<PageStat>,
295}
296
297pub struct RunSpec<'a> {
299 pub run_id: u128,
300 pub schema_id: u64,
301 pub epoch_created: u64,
302 pub level: u8,
303 pub flags: u8,
304 pub sort_key_column_id: u16,
305 pub row_count: u64,
306 pub min_row_id: u64,
307 pub max_row_id: u64,
308 pub columns: &'a [ColumnPayload],
309}
310
311pub fn write_run(path: impl AsRef<Path>, spec: &RunSpec) -> Result<RunHeader> {
313 write_run_with(path, spec, None, &[], None)
314}
315
316pub fn write_run_with(
326 path: impl AsRef<Path>,
327 spec: &RunSpec,
328 kek: Option<&Kek>,
329 indexable_columns: &[(u16, u8)],
330 index_trailer: Option<&[u8]>,
331) -> Result<RunHeader> {
332 let enc: Option<RunEncryption> = match kek {
336 Some(k) => Some(setup_run_encryption(k, indexable_columns)?),
337 None => None,
338 };
339 match write_run_mmap(path.as_ref(), spec, enc.as_ref(), index_trailer) {
340 Ok(h) => Ok(h),
341 Err(e) if is_mmap_unavailable(&e) => write_run_vec(path, spec, enc, index_trailer),
342 Err(e) => Err(e),
343 }
344}
345
346fn write_run_with_file(
347 mut file: File,
348 spec: &RunSpec,
349 kek: Option<&Kek>,
350 indexable_columns: &[(u16, u8)],
351 index_trailer: Option<&[u8]>,
352) -> Result<RunHeader> {
353 let enc = match kek {
354 Some(key) => Some(setup_run_encryption(key, indexable_columns)?),
355 None => None,
356 };
357 match write_run_mmap_file(&file, spec, enc.as_ref(), index_trailer) {
358 Ok(header) => Ok(header),
359 Err(error) if is_mmap_unavailable(&error) => {
360 file.set_len(0)?;
361 file.seek(SeekFrom::Start(0))?;
362 let (bytes, header) = encode_run_vec(spec, enc, index_trailer)?;
363 file.write_all(&bytes)?;
364 file.sync_all()?;
365 Ok(header)
366 }
367 Err(error) => Err(error),
368 }
369}
370
371fn is_mmap_unavailable(e: &MongrelError) -> bool {
375 matches!(e, MongrelError::InvalidArgument(m) if m.starts_with("__mmap_unavailable__:"))
376}
377
378fn write_run_mmap(
399 path: &Path,
400 spec: &RunSpec,
401 enc: Option<&RunEncryption>,
402 index_trailer: Option<&[u8]>,
403) -> Result<RunHeader> {
404 let file = OpenOptions::new().create_new(true).write(true).open(path)?;
405 let result = write_run_mmap_file(&file, spec, enc, index_trailer);
406 if result.as_ref().is_err_and(is_mmap_unavailable) {
407 drop(file);
408 let _ = std::fs::remove_file(path);
409 }
410 result
411}
412
413fn write_run_mmap_file(
414 file: &File,
415 spec: &RunSpec,
416 enc: Option<&RunEncryption>,
417 index_trailer: Option<&[u8]>,
418) -> Result<RunHeader> {
419 let plan = plan_run(spec, enc, index_trailer)?;
420 file.set_len(plan.total as u64)?;
421 let mut mmap = match unsafe { memmap2::MmapMut::map_mut(file) } {
422 Ok(m) => m,
423 Err(e) => {
424 return Err(MongrelError::InvalidArgument(format!(
425 "__mmap_unavailable__: {e}"
426 )));
427 }
428 };
429 let header = place_run(spec, enc, index_trailer, &plan, &mut mmap[..])?;
430 mmap.flush()?;
431 file.sync_all()?;
432 Ok(header)
433}
434
435struct RunPlan {
441 jobs: Vec<(usize, usize, u64, usize)>, dir_bytes: Vec<u8>,
443 encrypted: bool,
444 column_dir_offset: u64,
445 index_trailer_offset: u64,
446 encryption_descriptor_offset: u64,
447 footer_offset: u64,
448 total: usize,
449 encrypted_stats_plain: Option<Vec<u8>>,
453 encrypted_stats_offset: u64,
454 encrypted_stats_len: u64,
455}
456
457fn plan_run(
461 spec: &RunSpec,
462 enc: Option<&RunEncryption>,
463 index_trailer: Option<&[u8]>,
464) -> Result<RunPlan> {
465 let encrypted = enc.is_some();
466 let columns = spec.columns;
467 let mut jobs: Vec<(usize, usize, u64, usize)> = Vec::new();
468 let mut dir: Vec<ColumnPageHeader> = Vec::with_capacity(columns.len());
469 let mut enc_stats: EncryptedColumnStats = Vec::new();
470 let mut cursor: u64 = RUN_HEADER_PAD as u64;
471 for (ci, col) in columns.iter().enumerate() {
472 let region_offset = cursor;
473 let mut region_len = 0u64;
474 let mut stats = Vec::with_capacity(col.pages.len());
475 let mut col_minmax: Vec<PageMinMax> = Vec::new();
476 for (ps, page) in col.pages.iter().enumerate() {
477 if encrypted && ps >= u16::MAX as usize {
482 return Err(MongrelError::Full(format!(
483 "column {:#x} exceeds 65534 pages; encrypted-run page-seq nonce space exhausted",
484 col.column_id
485 )));
486 }
487 let odl = on_disk_len(page.len(), encrypted);
488 jobs.push((ci, ps, cursor, odl));
489 let mut stat = col.page_stats.get(ps).cloned().unwrap_or(PageStat {
490 first_row_id: 0,
491 last_row_id: 0,
492 null_count: 0,
493 row_count: 0,
494 min: None,
495 max: None,
496 offset: 0,
497 compressed_len: 0,
498 uncompressed_len: 0,
499 });
500 stat.offset = cursor;
501 stat.compressed_len = odl as u32;
502 stat.uncompressed_len = page.len() as u32;
503 if encrypted {
510 col_minmax.push((stat.min.take(), stat.max.take()));
511 }
512 stats.push(stat);
513 cursor += odl as u64;
514 region_len += odl as u64;
515 }
516 if col_minmax
517 .iter()
518 .any(|(mn, mx)| mn.is_some() || mx.is_some())
519 {
520 enc_stats.push((col.column_id, col_minmax));
521 }
522 let page_flags = if encrypted {
523 ColumnPageHeader::PAGE_ENCRYPTED
524 } else {
525 0
526 };
527 dir.push(ColumnPageHeader {
528 column_id: col.column_id,
529 type_id_tag: col.type_id_tag,
530 encoding: col.encoding as u8,
531 flags: page_flags,
532 page_count: col.pages.len() as u32,
533 page_region_offset: region_offset,
534 page_region_len: region_len,
535 page_stats: stats,
536 });
537 }
538 let dir_bytes = bincode::serialize(&dir)?;
539 let column_dir_offset = cursor;
540 cursor += dir_bytes.len() as u64;
541 let index_trailer_offset = match index_trailer {
542 Some(t) => {
543 let off = cursor;
544 cursor += t.len() as u64;
545 off
546 }
547 None => 0,
548 };
549 let encryption_descriptor_offset = match enc {
550 Some(e) => {
551 let off = cursor;
552 cursor += 4 + e.descriptor_bytes.len() as u64;
553 off
554 }
555 None => 0,
556 };
557 let (encrypted_stats_plain, encrypted_stats_offset, encrypted_stats_len) =
558 if encrypted && !enc_stats.is_empty() {
559 let plain = bincode::serialize(&enc_stats)?;
560 let ct_len = on_disk_len(plain.len(), true) as u64;
561 let off = cursor;
562 cursor += ct_len;
563 (Some(plain), off, ct_len)
564 } else {
565 (None, 0, 0)
566 };
567 let footer_offset = cursor;
568 let total = footer_offset as usize + 8 + 8 + 32 + if encrypted { RUN_MAC_LEN } else { 0 };
571 Ok(RunPlan {
572 jobs,
573 dir_bytes,
574 encrypted,
575 column_dir_offset,
576 index_trailer_offset,
577 encryption_descriptor_offset,
578 footer_offset,
579 total,
580 encrypted_stats_plain,
581 encrypted_stats_offset,
582 encrypted_stats_len,
583 })
584}
585
586fn place_run(
593 spec: &RunSpec,
594 enc: Option<&RunEncryption>,
595 index_trailer: Option<&[u8]>,
596 plan: &RunPlan,
597 buf: &mut [u8],
598) -> Result<RunHeader> {
599 use rayon::prelude::*;
600 use std::borrow::Cow;
601 debug_assert_eq!(
602 buf.len(),
603 plan.total,
604 "place_run: buffer must be exactly plan.total bytes"
605 );
606
607 let cipher: Option<&dyn Cipher> = enc.map(|e| e.cipher.as_ref());
608 let nonce_prefix = enc.map(|e| e.nonce_prefix);
609 let columns = spec.columns;
610
611 struct SyncPtr(*mut u8);
616 unsafe impl Send for SyncPtr {}
617 unsafe impl Sync for SyncPtr {}
618 impl SyncPtr {
619 fn get(&self) -> *mut u8 {
620 self.0
621 }
622 }
623 let base = SyncPtr(buf.as_mut_ptr());
624 plan.jobs
625 .par_iter()
626 .map(
627 |&(ci, ps, offset, odl): &(usize, usize, u64, usize)| -> Result<()> {
628 let page = &columns[ci].pages[ps];
629 let dst =
630 unsafe { std::slice::from_raw_parts_mut(base.get().add(offset as usize), odl) };
631 let bytes: Cow<[u8]> = match cipher {
632 Some(c) => {
633 let nonce =
634 page_nonce(nonce_prefix.unwrap(), columns[ci].column_id, ps as u32);
635 let ct = c.encrypt_page(&nonce, page)?;
636 assert_eq!(
639 ct.len(), odl,
640 "ciphertext length {} != predicted {}; GCM tag size assumption is stale",
641 ct.len(), odl
642 );
643 Cow::Owned(ct)
644 }
645 None => {
646 debug_assert_eq!(page.len(), odl);
647 Cow::Borrowed(page.as_slice())
648 }
649 };
650 dst.copy_from_slice(&bytes);
651 Ok(())
652 },
653 )
654 .collect::<Result<()>>()?;
655
656 let content_hash = {
658 let mut h = Sha256::new();
659 h.update(&buf[RUN_HEADER_PAD..plan.column_dir_offset as usize]);
660 h.finalize()
661 };
662
663 let doff = plan.column_dir_offset as usize;
665 buf[doff..doff + plan.dir_bytes.len()].copy_from_slice(&plan.dir_bytes);
666 if let Some(t) = index_trailer {
667 let off = plan.index_trailer_offset as usize;
668 buf[off..off + t.len()].copy_from_slice(t);
669 }
670 if let Some(e) = enc {
671 let off = plan.encryption_descriptor_offset as usize;
672 buf[off..off + 4].copy_from_slice(&(e.descriptor_bytes.len() as u32).to_le_bytes());
673 buf[off + 4..off + 4 + e.descriptor_bytes.len()].copy_from_slice(&e.descriptor_bytes);
674 }
675 if let (Some(e), Some(plain)) = (enc, plan.encrypted_stats_plain.as_ref()) {
676 let nonce = page_nonce(e.nonce_prefix, ENC_STATS_NONCE_COLUMN, ENC_STATS_NONCE_SEQ);
677 let ct = e.cipher.encrypt_page(&nonce, plain)?;
678 debug_assert_eq!(ct.len() as u64, plan.encrypted_stats_len);
679 let off = plan.encrypted_stats_offset as usize;
680 buf[off..off + ct.len()].copy_from_slice(&ct);
681 }
682
683 let header_flags = if plan.encrypted {
685 spec.flags | RUN_FLAG_ENCRYPTED
686 } else {
687 spec.flags
688 };
689 let header = RunHeader {
690 magic: RUN_MAGIC,
691 format_version: RUN_FORMAT_VERSION,
692 header_layout_version: RUN_HEADER_VERSION,
693 run_id: spec.run_id,
694 content_hash: content_hash.into(),
695 schema_id: spec.schema_id,
696 epoch_created: spec.epoch_created,
697 level: spec.level,
698 flags: header_flags,
699 sort_key_column_id: spec.sort_key_column_id,
700 row_count: spec.row_count,
701 min_row_id: spec.min_row_id,
702 max_row_id: spec.max_row_id,
703 column_count: columns.len() as u64,
704 column_dir_offset: plan.column_dir_offset,
705 index_trailer_offset: plan.index_trailer_offset,
706 encryption_descriptor_offset: plan.encryption_descriptor_offset,
707 footer_offset: plan.footer_offset,
708 encrypted_stats_offset: plan.encrypted_stats_offset,
709 encrypted_stats_len: plan.encrypted_stats_len,
710 };
711 let header_bytes = bincode::serialize(&header)?;
712 if header_bytes.len() > RUN_HEADER_PAD {
713 return Err(MongrelError::InvalidArgument(format!(
714 "run header too large: {} > {RUN_HEADER_PAD}",
715 header_bytes.len()
716 )));
717 }
718 buf[..header_bytes.len()].copy_from_slice(&header_bytes);
719
720 let checksum = Sha256::digest(&buf[..plan.footer_offset as usize]);
721 let foot = plan.footer_offset as usize;
722 buf[foot..foot + 8].copy_from_slice(&RUN_MAGIC);
723 buf[foot + 8..foot + 16].copy_from_slice(&plan.footer_offset.to_le_bytes());
724 buf[foot + 16..foot + 48].copy_from_slice(&checksum);
725 if let Some(tag) = compute_run_mac(enc, &header_bytes, &plan.dir_bytes) {
727 buf[foot + 48..foot + 48 + RUN_MAC_LEN].copy_from_slice(&tag);
728 }
729 Ok(header)
730}
731
732fn write_run_vec(
735 path: impl AsRef<Path>,
736 spec: &RunSpec,
737 enc: Option<RunEncryption>,
738 index_trailer: Option<&[u8]>,
739) -> Result<RunHeader> {
740 let (buf, header) = encode_run_vec(spec, enc, index_trailer)?;
741 let mut file = OpenOptions::new().create_new(true).write(true).open(path)?;
742 file.write_all(&buf)?;
743 file.sync_all()?;
744 Ok(header)
745}
746
747fn encode_run_vec(
748 spec: &RunSpec,
749 enc: Option<RunEncryption>,
750 index_trailer: Option<&[u8]>,
751) -> Result<(Vec<u8>, RunHeader)> {
752 let mut buf: Vec<u8> = vec![0; RUN_HEADER_PAD]; let mut content_hasher = Sha256::new();
754 let mut dir: Vec<ColumnPageHeader> = Vec::with_capacity(spec.columns.len());
755 let mut enc_stats: EncryptedColumnStats = Vec::new();
756
757 for col in spec.columns {
758 let region_offset = buf.len() as u64;
759 let mut region_len = 0u64;
760 let mut stats = Vec::with_capacity(col.pages.len());
761 let mut col_minmax: Vec<PageMinMax> = Vec::new();
762 for (page_seq, page) in col.pages.iter().enumerate() {
763 if enc.is_some() && page_seq >= u16::MAX as usize {
764 return Err(MongrelError::Full(format!(
765 "column {:#x} exceeds 65534 pages; encrypted-run page-seq nonce space exhausted",
766 col.column_id
767 )));
768 }
769 let on_disk: Vec<u8> = match &enc {
770 Some(e) => e.cipher.encrypt_page(
771 &page_nonce(e.nonce_prefix, col.column_id, page_seq as u32),
772 page,
773 )?,
774 None => page.clone(),
775 };
776 let offset = buf.len() as u64;
777 buf.write_all(&on_disk)?;
778 content_hasher.update(&on_disk);
779 region_len += on_disk.len() as u64;
780 let mut stat = if let Some(s) = col.page_stats.get(page_seq) {
781 s.clone()
782 } else {
783 PageStat {
784 first_row_id: 0,
785 last_row_id: 0,
786 null_count: 0,
787 row_count: 0,
788 min: None,
789 max: None,
790 offset: 0,
791 compressed_len: 0,
792 uncompressed_len: 0,
793 }
794 };
795 stat.offset = offset;
796 stat.compressed_len = on_disk.len() as u32;
797 stat.uncompressed_len = page.len() as u32;
798 if enc.is_some() {
803 col_minmax.push((stat.min.take(), stat.max.take()));
804 }
805 stats.push(stat);
806 }
807 if col_minmax
808 .iter()
809 .any(|(mn, mx)| mn.is_some() || mx.is_some())
810 {
811 enc_stats.push((col.column_id, col_minmax));
812 }
813 let page_flags = if enc.is_some() {
814 ColumnPageHeader::PAGE_ENCRYPTED
815 } else {
816 0
817 };
818 dir.push(ColumnPageHeader {
819 column_id: col.column_id,
820 type_id_tag: col.type_id_tag,
821 encoding: col.encoding as u8,
822 flags: page_flags,
823 page_count: col.pages.len() as u32,
824 page_region_offset: region_offset,
825 page_region_len: region_len,
826 page_stats: stats,
827 });
828 }
829
830 let column_dir_offset = buf.len() as u64;
831 let dir_bytes = bincode::serialize(&dir)?;
832 buf.write_all(&dir_bytes)?;
833
834 let index_trailer_offset = match index_trailer {
835 Some(trailer) => {
836 let off = buf.len() as u64;
837 buf.write_all(trailer)?;
838 off
839 }
840 None => 0,
841 };
842 let encryption_descriptor_offset = match &enc {
843 Some(e) => {
844 let off = buf.len() as u64;
845 buf.write_all(&(e.descriptor_bytes.len() as u32).to_le_bytes())?;
846 buf.write_all(&e.descriptor_bytes)?;
847 off
848 }
849 None => 0,
850 };
851 let (encrypted_stats_offset, encrypted_stats_len) = match &enc {
852 Some(e) if !enc_stats.is_empty() => {
853 let plain = bincode::serialize(&enc_stats)?;
854 let nonce = page_nonce(e.nonce_prefix, ENC_STATS_NONCE_COLUMN, ENC_STATS_NONCE_SEQ);
855 let ct = e.cipher.encrypt_page(&nonce, &plain)?;
856 let off = buf.len() as u64;
857 let len = ct.len() as u64;
858 buf.write_all(&ct)?;
859 (off, len)
860 }
861 _ => (0, 0),
862 };
863 let footer_offset = buf.len() as u64;
864
865 let header_flags = if enc.is_some() {
866 spec.flags | RUN_FLAG_ENCRYPTED
867 } else {
868 spec.flags
869 };
870 let header = RunHeader {
871 magic: RUN_MAGIC,
872 format_version: RUN_FORMAT_VERSION,
873 header_layout_version: RUN_HEADER_VERSION,
874 run_id: spec.run_id,
875 content_hash: content_hasher.finalize().into(),
876 schema_id: spec.schema_id,
877 epoch_created: spec.epoch_created,
878 level: spec.level,
879 flags: header_flags,
880 sort_key_column_id: spec.sort_key_column_id,
881 row_count: spec.row_count,
882 min_row_id: spec.min_row_id,
883 max_row_id: spec.max_row_id,
884 column_count: spec.columns.len() as u64,
885 column_dir_offset,
886 index_trailer_offset,
887 encryption_descriptor_offset,
888 footer_offset,
889 encrypted_stats_offset,
890 encrypted_stats_len,
891 };
892 let header_bytes = bincode::serialize(&header)?;
893 if header_bytes.len() > RUN_HEADER_PAD {
894 return Err(MongrelError::InvalidArgument(format!(
895 "run header too large: {} > {RUN_HEADER_PAD}",
896 header_bytes.len()
897 )));
898 }
899 buf[..header_bytes.len()].copy_from_slice(&header_bytes);
900
901 let checksum = Sha256::digest(&buf[..footer_offset as usize]);
902 buf.write_all(&RUN_MAGIC)?;
903 buf.write_all(&footer_offset.to_le_bytes())?;
904 buf.write_all(&checksum)?;
905 if let Some(tag) = compute_run_mac(enc.as_ref(), &header_bytes, &dir_bytes) {
908 buf.write_all(&tag)?;
909 }
910
911 Ok((buf, header))
912}
913
914fn page_nonce(nonce_prefix: [u8; 12], column_id: u16, page_seq: u32) -> [u8; 12] {
915 let mut n = nonce_prefix;
916 n[8..10].copy_from_slice(&column_id.to_le_bytes());
917 n[10..12].copy_from_slice(&(page_seq as u16).to_le_bytes());
918 n
919}
920
921fn overlay_encrypted_stats(
928 file: &mut File,
929 header: &RunHeader,
930 cipher: &dyn Cipher,
931 nonce_prefix: [u8; 12],
932 dir: &mut [ColumnPageHeader],
933) -> Result<()> {
934 file.seek(SeekFrom::Start(header.encrypted_stats_offset))?;
935 const MAX_ENCRYPTED_STATS_BYTES: u64 = 64 * 1024 * 1024;
936 if header.encrypted_stats_len > MAX_ENCRYPTED_STATS_BYTES {
937 return Err(MongrelError::InvalidArgument(format!(
938 "encrypted run stats length {} exceeds {MAX_ENCRYPTED_STATS_BYTES}",
939 header.encrypted_stats_len
940 )));
941 }
942 let mut ct = vec![0u8; header.encrypted_stats_len as usize];
943 file.read_exact(&mut ct)?;
944 let nonce = page_nonce(nonce_prefix, ENC_STATS_NONCE_COLUMN, ENC_STATS_NONCE_SEQ);
945 let plain = cipher.decrypt_page(&nonce, &ct)?;
946 let stats: EncryptedColumnStats = bincode::deserialize(&plain)
947 .map_err(|e| MongrelError::Encryption(format!("bad encrypted page-stats envelope: {e}")))?;
948 for (cid, minmax) in stats {
949 let Some(col) = dir.iter_mut().find(|c| c.column_id == cid) else {
950 continue;
951 };
952 for (stat, (mn, mx)) in col.page_stats.iter_mut().zip(minmax) {
953 stat.min = mn;
954 stat.max = mx;
955 }
956 }
957 Ok(())
958}
959
960pub(crate) fn page_cache_key(
967 table_id: u64,
968 run_id: u128,
969 column_id: u16,
970 page_seq: usize,
971) -> [u8; 32] {
972 let mut h = Sha256::new();
973 h.update(table_id.to_be_bytes());
974 h.update(run_id.to_be_bytes());
975 h.update(column_id.to_be_bytes());
976 h.update((page_seq as u64).to_be_bytes());
977 let out = h.finalize();
978 let mut k = [0u8; 32];
979 k.copy_from_slice(&out);
980 k
981}
982
983fn decrypt_or_passthrough(
987 cipher: Option<&dyn Cipher>,
988 nonce_prefix: [u8; 12],
989 column_id: u16,
990 page_seq: usize,
991 encrypted: bool,
992 buf: &[u8],
993) -> Result<Vec<u8>> {
994 if encrypted {
995 match cipher {
996 Some(c) => {
997 Ok(c.decrypt_page(&page_nonce(nonce_prefix, column_id, page_seq as u32), buf)?)
998 }
999 None => Err(MongrelError::Decryption(
1000 "encrypted page but no cipher".into(),
1001 )),
1002 }
1003 } else {
1004 Ok(buf.to_vec())
1005 }
1006}
1007
1008fn read_header_fast_from_file(file: &mut File) -> Result<RunHeader> {
1018 file.seek(SeekFrom::Start(0))?;
1019 let mut header_buf = [0u8; RUN_HEADER_PAD];
1020 file.read_exact(&mut header_buf)?;
1021 let header: RunHeader = bincode::deserialize(&header_buf)
1022 .map_err(|e| MongrelError::InvalidArgument(format!("bad run header: {e}")))?;
1023 validate_run_header_bytes(&header, &header_buf)?;
1024 validate_run_layout(&header, file.metadata()?.len())?;
1025 file.seek(SeekFrom::Start(header.footer_offset))?;
1026 let mut footer_magic = [0u8; 8];
1027 file.read_exact(&mut footer_magic)?;
1028 if footer_magic != RUN_MAGIC {
1029 return Err(MongrelError::MagicMismatch {
1030 what: "sorted run footer",
1031 expected: RUN_MAGIC,
1032 got: footer_magic,
1033 });
1034 }
1035 Ok(header)
1036}
1037
1038pub fn read_header(path: impl AsRef<Path>) -> Result<RunHeader> {
1040 let mut file = crate::durable_file::open_regular_nofollow(path.as_ref())?;
1041 read_header_from_file(&mut file)
1042}
1043
1044fn validate_run_layout(header: &RunHeader, file_len: u64) -> Result<()> {
1045 let footer_len = 8u64
1046 + 8
1047 + 32
1048 + if header.is_encrypted() {
1049 RUN_MAC_LEN as u64
1050 } else {
1051 0
1052 };
1053 let expected_len = header
1054 .footer_offset
1055 .checked_add(footer_len)
1056 .ok_or_else(|| MongrelError::InvalidArgument("sorted run length overflow".into()))?;
1057 if header.footer_offset < RUN_HEADER_PAD as u64 || expected_len != file_len {
1058 return Err(MongrelError::InvalidArgument(format!(
1059 "invalid sorted run layout: footer={} file={file_len}",
1060 header.footer_offset
1061 )));
1062 }
1063 let in_body = |offset: u64| {
1064 offset == 0 || (offset >= RUN_HEADER_PAD as u64 && offset <= header.footer_offset)
1065 };
1066 if header.column_dir_offset < RUN_HEADER_PAD as u64
1067 || header.column_dir_offset > header.footer_offset
1068 || !in_body(header.index_trailer_offset)
1069 || !in_body(header.encryption_descriptor_offset)
1070 || !in_body(header.encrypted_stats_offset)
1071 || header
1072 .encrypted_stats_offset
1073 .checked_add(header.encrypted_stats_len)
1074 .is_none_or(|end| end > header.footer_offset)
1075 {
1076 return Err(MongrelError::InvalidArgument(
1077 "sorted run metadata offsets are outside the file".into(),
1078 ));
1079 }
1080 Ok(())
1081}
1082
1083fn validate_run_header_bytes(header: &RunHeader, bytes: &[u8; RUN_HEADER_PAD]) -> Result<()> {
1084 if header.magic != RUN_MAGIC {
1085 return Err(MongrelError::MagicMismatch {
1086 what: "sorted run",
1087 expected: RUN_MAGIC,
1088 got: header.magic,
1089 });
1090 }
1091 const KNOWN_FLAGS: u8 =
1092 RUN_FLAG_ENCRYPTED | RUN_FLAG_TOMBSTONE_ONLY | RUN_FLAG_CLEAN | RUN_FLAG_UNIFORM_EPOCH;
1093 if header.format_version != RUN_FORMAT_VERSION
1094 || header.header_layout_version != RUN_HEADER_VERSION
1095 || header.flags & !KNOWN_FLAGS != 0
1096 || (header.row_count == 0 && (header.min_row_id != 0 || header.max_row_id != 0))
1097 || (header.row_count != 0 && header.min_row_id > header.max_row_id)
1098 {
1099 return Err(MongrelError::InvalidArgument(
1100 "unsupported or invalid sorted run header".into(),
1101 ));
1102 }
1103 let canonical = bincode::serialize(header)?;
1104 if canonical.len() > RUN_HEADER_PAD
1105 || bytes[..canonical.len()] != canonical
1106 || bytes[canonical.len()..].iter().any(|byte| *byte != 0)
1107 {
1108 return Err(MongrelError::InvalidArgument(
1109 "sorted run header has noncanonical bytes or nonzero padding".into(),
1110 ));
1111 }
1112 Ok(())
1113}
1114
1115fn read_header_from_file(file: &mut File) -> Result<RunHeader> {
1116 file.seek(SeekFrom::Start(0))?;
1117 let mut header_buf = [0u8; RUN_HEADER_PAD];
1118 file.read_exact(&mut header_buf)?;
1119 let header: RunHeader = bincode::deserialize(&header_buf)
1120 .map_err(|e| MongrelError::InvalidArgument(format!("bad run header: {e}")))?;
1121 validate_run_header_bytes(&header, &header_buf)?;
1122
1123 validate_run_layout(&header, file.metadata()?.len())?;
1124 file.seek(SeekFrom::Start(header.footer_offset))?;
1125 let mut footer = [0u8; 8 + 8 + 32];
1126 file.read_exact(&mut footer)?;
1127 if footer[..8] != RUN_MAGIC {
1128 return Err(MongrelError::MagicMismatch {
1129 what: "sorted run footer",
1130 expected: RUN_MAGIC,
1131 got: footer[..8].try_into().unwrap(),
1132 });
1133 }
1134 let mut hasher = Sha256::new();
1135 file.seek(SeekFrom::Start(0))?;
1136 let mut remaining = header.footer_offset;
1137 let mut buffer = [0u8; 64 * 1024];
1138 while remaining != 0 {
1139 let length = usize::try_from(remaining.min(buffer.len() as u64)).unwrap();
1140 file.read_exact(&mut buffer[..length])?;
1141 hasher.update(&buffer[..length]);
1142 remaining -= length as u64;
1143 }
1144 let computed: [u8; 32] = hasher.finalize().into();
1145 let stored: [u8; 32] = footer[16..].try_into().unwrap();
1146 if computed != stored {
1147 return Err(MongrelError::ChecksumMismatch {
1148 expected: u64::from_be_bytes(stored[..8].try_into().unwrap()),
1149 actual: u64::from_be_bytes(computed[..8].try_into().unwrap()),
1150 context: "sorted run footer".into(),
1151 });
1152 }
1153 file.seek(SeekFrom::Start(RUN_HEADER_PAD as u64))?;
1154 let mut remaining = header.column_dir_offset - RUN_HEADER_PAD as u64;
1155 let mut content = Sha256::new();
1156 while remaining != 0 {
1157 let length = usize::try_from(remaining.min(buffer.len() as u64)).unwrap();
1158 file.read_exact(&mut buffer[..length])?;
1159 content.update(&buffer[..length]);
1160 remaining -= length as u64;
1161 }
1162 let content_hash: [u8; 32] = content.finalize().into();
1163 if content_hash != header.content_hash {
1164 return Err(MongrelError::ChecksumMismatch {
1165 expected: u64::from_be_bytes(header.content_hash[..8].try_into().unwrap()),
1166 actual: u64::from_be_bytes(content_hash[..8].try_into().unwrap()),
1167 context: "sorted run content hash".into(),
1168 });
1169 }
1170 Ok(header)
1171}
1172
1173pub fn read_column_dir(
1175 path: impl AsRef<Path>,
1176 header: &RunHeader,
1177) -> Result<Vec<ColumnPageHeader>> {
1178 let mut file = crate::durable_file::open_regular_nofollow(path.as_ref())?;
1179 read_column_dir_from_file(&mut file, header)
1180}
1181
1182fn read_column_dir_from_file(file: &mut File, header: &RunHeader) -> Result<Vec<ColumnPageHeader>> {
1183 file.seek(SeekFrom::Start(header.column_dir_offset))?;
1184 let end = [
1185 header.index_trailer_offset,
1186 header.encryption_descriptor_offset,
1187 header.encrypted_stats_offset,
1188 header.footer_offset,
1189 ]
1190 .into_iter()
1191 .filter(|offset| *offset > header.column_dir_offset)
1192 .min()
1193 .ok_or_else(|| {
1194 MongrelError::InvalidArgument("sorted run column directory has no end".into())
1195 })?;
1196 let len = end.checked_sub(header.column_dir_offset).ok_or_else(|| {
1197 MongrelError::InvalidArgument("sorted run column directory offsets are reversed".into())
1198 })?;
1199 const MAX_COLUMN_DIR_BYTES: u64 = 64 * 1024 * 1024;
1200 if len > MAX_COLUMN_DIR_BYTES {
1201 return Err(MongrelError::InvalidArgument(format!(
1202 "sorted run column directory length {len} exceeds {MAX_COLUMN_DIR_BYTES}"
1203 )));
1204 }
1205 let mut buf = vec![0u8; len as usize];
1206 file.read_exact(&mut buf)?;
1207 let dir: Vec<ColumnPageHeader> = bincode::deserialize(&buf)
1208 .map_err(|e| MongrelError::InvalidArgument(format!("bad column dir: {e}")))?;
1209 Ok(dir)
1210}
1211
1212fn validate_column_directory_layout(header: &RunHeader, dir: &[ColumnPageHeader]) -> Result<()> {
1213 if header.column_count != dir.len() as u64 || dir.len() > u16::MAX as usize {
1214 return Err(MongrelError::InvalidArgument(
1215 "sorted run column count is invalid".into(),
1216 ));
1217 }
1218 let mut regions = Vec::with_capacity(dir.len());
1219 let mut ids = std::collections::HashSet::new();
1220 for column in dir {
1221 if !ids.insert(column.column_id)
1222 || column.flags & !ColumnPageHeader::PAGE_ENCRYPTED != 0
1223 || column.page_count as usize != column.page_stats.len()
1224 {
1225 return Err(MongrelError::InvalidArgument(
1226 "sorted run column directory identity is invalid".into(),
1227 ));
1228 }
1229 let region_end = column
1230 .page_region_offset
1231 .checked_add(column.page_region_len)
1232 .ok_or_else(|| MongrelError::InvalidArgument("run page region overflows".into()))?;
1233 if column.page_region_offset < RUN_HEADER_PAD as u64
1234 || region_end > header.column_dir_offset
1235 {
1236 return Err(MongrelError::InvalidArgument(
1237 "sorted run page region is outside its body".into(),
1238 ));
1239 }
1240 let mut cursor = column.page_region_offset;
1241 let mut rows = 0_u64;
1242 for stat in &column.page_stats {
1243 let length = stat.compressed_len as u64;
1244 let end = stat
1245 .offset
1246 .checked_add(length)
1247 .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
1248 if stat.offset != cursor
1249 || length == 0
1250 || length > MAX_RUN_PAGE_BYTES
1251 || stat.uncompressed_len as u64 > MAX_RUN_PAGE_BYTES
1252 || stat.row_count as usize > PAGE_ROWS
1253 || end > region_end
1254 {
1255 return Err(MongrelError::InvalidArgument(
1256 "sorted run page metadata is outside its region".into(),
1257 ));
1258 }
1259 rows = rows.checked_add(stat.row_count as u64).ok_or_else(|| {
1260 MongrelError::InvalidArgument("sorted run row count overflows".into())
1261 })?;
1262 cursor = end;
1263 }
1264 if cursor != region_end || rows != header.row_count {
1265 return Err(MongrelError::InvalidArgument(
1266 "sorted run page region length or row count is inconsistent".into(),
1267 ));
1268 }
1269 regions.push((column.page_region_offset, region_end));
1270 }
1271 regions.sort_unstable();
1272 if regions.windows(2).any(|pair| pair[0].1 > pair[1].0) {
1273 return Err(MongrelError::InvalidArgument(
1274 "sorted run page regions overlap".into(),
1275 ));
1276 }
1277 Ok(())
1278}
1279
1280fn read_encryption_descriptor_bytes_from_file(
1281 file: &mut File,
1282 header: &RunHeader,
1283) -> Result<Vec<u8>> {
1284 file.seek(SeekFrom::Start(header.encryption_descriptor_offset))?;
1285 let mut len_buf = [0u8; 4];
1286 file.read_exact(&mut len_buf)?;
1287 let len = u32::from_le_bytes(len_buf) as usize;
1288 const MAX_DESCRIPTOR_BYTES: usize = 65_536;
1293 if len > MAX_DESCRIPTOR_BYTES {
1294 return Err(MongrelError::InvalidArgument(format!(
1295 "encryption descriptor length {len} exceeds {MAX_DESCRIPTOR_BYTES}"
1296 )));
1297 }
1298 let mut buf = vec![0u8; len];
1299 file.read_exact(&mut buf)?;
1300 Ok(buf)
1301}
1302
1303fn verify_run_mac(
1310 file: &mut File,
1311 header: &RunHeader,
1312 dir: &[ColumnPageHeader],
1313 kek: &Kek,
1314 desc_bytes: &[u8],
1315) -> Result<()> {
1316 let header_bytes = bincode::serialize(header)?;
1317 let dir_bytes = bincode::serialize(dir)?;
1318 let mac_key = kek.derive_run_mac_key();
1319 let expected =
1320 crate::encryption::run_metadata_mac(&mac_key, &header_bytes, &dir_bytes, desc_bytes);
1321 file.seek(SeekFrom::Start(header.footer_offset + 8 + 8 + 32))?;
1322 let mut tag = [0u8; RUN_MAC_LEN];
1323 file.read_exact(&mut tag).map_err(|_| {
1324 MongrelError::Decryption(
1325 "encrypted run is missing or truncated its metadata MAC; cannot \
1326 authenticate metadata"
1327 .into(),
1328 )
1329 })?;
1330 let mut diff = 0u8;
1332 for (x, y) in tag.iter().zip(expected.iter()) {
1333 diff |= x ^ y;
1334 }
1335 if diff != 0 {
1336 return Err(MongrelError::Decryption(
1337 "run metadata authentication failed — tampered run or wrong key".into(),
1338 ));
1339 }
1340 Ok(())
1341}
1342
1343pub struct RunWriter<'a> {
1352 schema: &'a Schema,
1353 run_id: u128,
1354 epoch_created: Epoch,
1355 level: u8,
1356 kek: Option<&'a Kek>,
1357 indexable_columns: Vec<(u16, u8)>,
1360 compress: columnar::Compress,
1364 clean: bool,
1369 uniform_epoch: bool,
1374 le: bool,
1381}
1382
1383impl<'a> RunWriter<'a> {
1384 pub fn new(schema: &'a Schema, run_id: u128, epoch_created: Epoch, level: u8) -> Self {
1385 Self {
1386 schema,
1387 run_id,
1388 epoch_created,
1389 level,
1390 kek: None,
1391 indexable_columns: Vec::new(),
1392 compress: columnar::Compress::Zstd(3),
1393 clean: false,
1394 uniform_epoch: false,
1395 le: false,
1396 }
1397 }
1398
1399 pub fn uniform_epoch(mut self, uniform: bool) -> Self {
1405 self.uniform_epoch = uniform;
1406 self
1407 }
1408
1409 pub fn with_encryption(mut self, kek: &'a Kek, indexable_columns: Vec<(u16, u8)>) -> Self {
1413 self.kek = Some(kek);
1414 self.indexable_columns = indexable_columns;
1415 self
1416 }
1417
1418 pub fn with_zstd_level(mut self, level: i32) -> Self {
1421 self.compress = columnar::Compress::Zstd(level);
1422 self
1423 }
1424
1425 pub fn with_lz4(mut self) -> Self {
1429 self.compress = columnar::Compress::Lz4;
1430 self
1431 }
1432
1433 pub fn with_plain(mut self) -> Self {
1436 self.compress = columnar::Compress::Plain;
1437 self
1438 }
1439
1440 pub fn clean(mut self, clean: bool) -> Self {
1446 self.clean = clean;
1447 self
1448 }
1449
1450 pub fn with_native_endian(mut self) -> Self {
1455 if cfg!(target_endian = "little") {
1456 self.le = true;
1457 }
1458 self
1459 }
1460
1461 pub fn write_native(
1468 self,
1469 path: impl AsRef<Path>,
1470 user_columns: &[(u16, columnar::NativeColumn)],
1471 n: usize,
1472 first_row_id: u64,
1473 ) -> Result<RunHeader> {
1474 self.write_native_target(Some(path.as_ref()), None, user_columns, n, first_row_id)
1475 }
1476
1477 pub(crate) fn write_native_file(
1478 self,
1479 file: File,
1480 user_columns: &[(u16, columnar::NativeColumn)],
1481 n: usize,
1482 first_row_id: u64,
1483 ) -> Result<RunHeader> {
1484 self.write_native_target(None, Some(file), user_columns, n, first_row_id)
1485 }
1486
1487 fn write_native_target(
1488 self,
1489 path: Option<&Path>,
1490 file: Option<File>,
1491 user_columns: &[(u16, columnar::NativeColumn)],
1492 n: usize,
1493 first_row_id: u64,
1494 ) -> Result<RunHeader> {
1495 use columnar::NativeColumn;
1496 let row_id_col = NativeColumn::int64_sequence(first_row_id as i64, n);
1497 let epoch_col = NativeColumn::int64_constant(self.epoch_created.0 as i64, n);
1498 let deleted_col = NativeColumn::bool_constant(false, n);
1499
1500 let learned_trailer = build_learned_trailer_native(&row_id_col);
1501
1502 let row_ids = match &row_id_col {
1505 NativeColumn::Int64 { data, .. } => data.as_slice(),
1506 _ => &[],
1507 };
1508 let bounds = page_bounds(row_ids);
1509 let compress = self.compress;
1510 let le = self.le;
1511 let plain = matches!(compress, columnar::Compress::Plain);
1512 let row_id_enc = if plain {
1515 Encoding::Plain
1516 } else {
1517 Encoding::Delta
1518 };
1519 let sys_enc = if plain {
1520 Encoding::Plain
1521 } else {
1522 Encoding::Zstd
1523 };
1524
1525 let mut columns: Vec<ColumnPayload> = Vec::with_capacity(3 + self.schema.columns.len());
1526 let (pages, stats) = native_column_pages(
1527 TypeId::Int64,
1528 &row_id_col,
1529 row_id_enc,
1530 compress,
1531 le,
1532 &bounds,
1533 )?;
1534 columns.push(ColumnPayload {
1535 column_id: SYS_ROW_ID,
1536 type_id_tag: type_tag(&TypeId::Int64),
1537 encoding: row_id_enc,
1538 pages,
1539 page_stats: stats,
1540 });
1541 let (pages, stats) =
1542 native_column_pages(TypeId::Int64, &epoch_col, sys_enc, compress, le, &bounds)?;
1543 columns.push(ColumnPayload {
1544 column_id: SYS_EPOCH,
1545 type_id_tag: type_tag(&TypeId::Int64),
1546 encoding: sys_enc,
1547 pages,
1548 page_stats: stats,
1549 });
1550 let (pages, stats) =
1551 native_column_pages(TypeId::Bool, &deleted_col, sys_enc, compress, le, &bounds)?;
1552 columns.push(ColumnPayload {
1553 column_id: SYS_DELETED,
1554 type_id_tag: type_tag(&TypeId::Bool),
1555 encoding: sys_enc,
1556 pages,
1557 page_stats: stats,
1558 });
1559 use rayon::prelude::*;
1565 let user_cols: Vec<ColumnPayload> = self
1566 .schema
1567 .columns
1568 .par_iter()
1569 .map(|cdef| -> Result<ColumnPayload> {
1570 let col = user_columns
1571 .iter()
1572 .find(|(id, _)| *id == cdef.id)
1573 .map(|(_, c)| c)
1574 .ok_or_else(|| {
1575 MongrelError::ColumnNotFound(format!("user column {}", cdef.id))
1576 })?;
1577 let encoding = if plain {
1578 Encoding::Plain
1579 } else {
1580 choose_encoding_native(&cdef.ty, col)
1581 };
1582 let (pages, stats) =
1583 native_column_pages(cdef.ty.clone(), col, encoding, compress, le, &bounds)?;
1584 Ok(ColumnPayload {
1585 column_id: cdef.id,
1586 type_id_tag: type_tag(&cdef.ty),
1587 encoding,
1588 pages,
1589 page_stats: stats,
1590 })
1591 })
1592 .collect::<Result<Vec<_>>>()?;
1593 columns.extend(user_cols);
1594
1595 let flags = if self.uniform_epoch {
1601 RUN_FLAG_UNIFORM_EPOCH
1602 } else {
1603 RUN_FLAG_CLEAN
1604 };
1605 let spec = RunSpec {
1606 run_id: self.run_id,
1607 schema_id: self.schema.schema_id,
1608 epoch_created: self.epoch_created.0,
1609 level: self.level,
1610 flags,
1611 sort_key_column_id: SYS_ROW_ID,
1612 row_count: n as u64,
1613 min_row_id: first_row_id,
1614 max_row_id: first_row_id + n as u64 - 1,
1615 columns: &columns,
1616 };
1617 match file {
1618 Some(file) => write_run_with_file(
1619 file,
1620 &spec,
1621 self.kek,
1622 &self.indexable_columns,
1623 Some(&learned_trailer),
1624 ),
1625 None => write_run_with(
1626 path.ok_or_else(|| {
1627 MongrelError::InvalidArgument("sorted run output is missing".into())
1628 })?,
1629 &spec,
1630 self.kek,
1631 &self.indexable_columns,
1632 Some(&learned_trailer),
1633 ),
1634 }
1635 }
1636
1637 pub fn write(self, path: impl AsRef<Path>, rows: &[Row]) -> Result<RunHeader> {
1638 self.write_target(Some(path.as_ref()), None, rows)
1639 }
1640
1641 pub(crate) fn write_file(self, file: File, rows: &[Row]) -> Result<RunHeader> {
1642 self.write_target(None, Some(file), rows)
1643 }
1644
1645 fn write_target(
1646 self,
1647 path: Option<&Path>,
1648 file: Option<File>,
1649 rows: &[Row],
1650 ) -> Result<RunHeader> {
1651 let n = rows.len();
1652 let mut row_ids = Vec::with_capacity(n);
1654 let mut epochs = Vec::with_capacity(n);
1655 let mut deleted = Vec::with_capacity(n);
1656 let mut commit_ts_vals = Vec::with_capacity(n);
1657 let has_commit_ts = rows.iter().any(|r| r.commit_ts.is_some());
1659 for r in rows {
1660 row_ids.push(Value::Int64(r.row_id.0 as i64));
1661 epochs.push(Value::Int64(r.committed_epoch.0 as i64));
1662 deleted.push(Value::Bool(r.deleted));
1663 if has_commit_ts {
1664 commit_ts_vals.push(encode_commit_ts_value(r.commit_ts));
1665 }
1666 }
1667 let learned_trailer = build_learned_trailer(&row_ids);
1668 let (min_rid, max_rid) = row_id_bounds(rows);
1669 let row_id_i64: Vec<i64> = rows.iter().map(|r| r.row_id.0 as i64).collect();
1670 let bounds = page_bounds(&row_id_i64);
1671
1672 let mut columns: Vec<ColumnPayload> =
1673 Vec::with_capacity(3 + usize::from(has_commit_ts) + self.schema.columns.len());
1674 let (pages, stats, enc) = value_column_pages(TypeId::Int64, &row_ids, &bounds)?;
1675 columns.push(ColumnPayload {
1676 column_id: SYS_ROW_ID,
1677 type_id_tag: type_tag(&TypeId::Int64),
1678 encoding: enc,
1679 pages,
1680 page_stats: stats,
1681 });
1682 let (pages, stats, enc) = value_column_pages(TypeId::Int64, &epochs, &bounds)?;
1683 columns.push(ColumnPayload {
1684 column_id: SYS_EPOCH,
1685 type_id_tag: type_tag(&TypeId::Int64),
1686 encoding: enc,
1687 pages,
1688 page_stats: stats,
1689 });
1690 let (pages, stats, enc) = value_column_pages(TypeId::Bool, &deleted, &bounds)?;
1691 columns.push(ColumnPayload {
1692 column_id: SYS_DELETED,
1693 type_id_tag: type_tag(&TypeId::Bool),
1694 encoding: enc,
1695 pages,
1696 page_stats: stats,
1697 });
1698 if has_commit_ts {
1699 let (pages, stats, enc) = value_column_pages(TypeId::Bytes, &commit_ts_vals, &bounds)?;
1700 columns.push(ColumnPayload {
1701 column_id: SYS_COMMIT_TS,
1702 type_id_tag: type_tag(&TypeId::Bytes),
1703 encoding: enc,
1704 pages,
1705 page_stats: stats,
1706 });
1707 }
1708 for cdef in &self.schema.columns {
1710 let vals: Vec<Value> = rows
1711 .iter()
1712 .map(|r| r.columns.get(&cdef.id).cloned().unwrap_or(Value::Null))
1713 .collect();
1714 let (pages, stats, encoding) = value_column_pages(cdef.ty.clone(), &vals, &bounds)?;
1715 columns.push(ColumnPayload {
1716 column_id: cdef.id,
1717 type_id_tag: type_tag(&cdef.ty),
1718 encoding,
1719 pages,
1720 page_stats: stats,
1721 });
1722 }
1723
1724 let spec = RunSpec {
1725 run_id: self.run_id,
1726 schema_id: self.schema.schema_id,
1727 epoch_created: self.epoch_created.0,
1728 level: self.level,
1729 flags: {
1730 let mut f = if self.clean { RUN_FLAG_CLEAN } else { 0 };
1731 if self.uniform_epoch {
1732 f |= RUN_FLAG_UNIFORM_EPOCH;
1733 }
1734 f
1735 },
1736 sort_key_column_id: SYS_ROW_ID,
1737 row_count: n as u64,
1738 min_row_id: min_rid,
1739 max_row_id: max_rid,
1740 columns: &columns,
1741 };
1742 match file {
1743 Some(file) => write_run_with_file(
1744 file,
1745 &spec,
1746 self.kek,
1747 &self.indexable_columns,
1748 Some(&learned_trailer),
1749 ),
1750 None => write_run_with(
1751 path.ok_or_else(|| {
1752 MongrelError::InvalidArgument("sorted run output is missing".into())
1753 })?,
1754 &spec,
1755 self.kek,
1756 &self.indexable_columns,
1757 Some(&learned_trailer),
1758 ),
1759 }
1760 }
1761}
1762
1763fn type_tag(ty: &TypeId) -> u16 {
1764 match ty {
1766 TypeId::Bool => 1,
1767 TypeId::Int64 => 8,
1768 TypeId::Float64 => 9,
1769 TypeId::Bytes => 12,
1770 TypeId::Embedding { .. } => 13,
1771 _ => 0,
1772 }
1773}
1774
1775pub(crate) fn be_i64(b: Option<&[u8]>) -> Option<i64> {
1778 let b = b?;
1779 (b.len() == 8).then(|| i64::from_be_bytes(b.try_into().unwrap()))
1780}
1781
1782pub(crate) fn be_f64(b: Option<&[u8]>) -> Option<f64> {
1784 let b = b?;
1785 (b.len() == 8).then(|| f64::from_bits(u64::from_be_bytes(b.try_into().unwrap())))
1786}
1787
1788const PAGE_ROWS: usize = 65_536;
1791
1792fn page_bounds(row_ids: &[i64]) -> Vec<(usize, usize, u64, u64)> {
1795 let n = row_ids.len();
1796 if n == 0 {
1797 return vec![(0, 0, 0, 0)];
1798 }
1799 let mut out = Vec::new();
1800 let mut start = 0;
1801 while start < n {
1802 let end = (start + PAGE_ROWS).min(n);
1803 out.push((start, end, row_ids[start] as u64, row_ids[end - 1] as u64));
1804 start = end;
1805 }
1806 out
1807}
1808
1809fn native_column_pages(
1815 ty: TypeId,
1816 col: &columnar::NativeColumn,
1817 encoding: Encoding,
1818 compress: columnar::Compress,
1819 le: bool,
1820 bounds: &[(usize, usize, u64, u64)],
1821) -> Result<(Vec<Vec<u8>>, Vec<PageStat>)> {
1822 use rayon::prelude::*;
1823 let encode_one =
1824 |&(s, e, frid, lrid): &(usize, usize, u64, u64)| -> Result<(Vec<u8>, PageStat)> {
1825 let chunk = col.slice_range(s, e);
1826 let stat = columnar::page_stat_for(ty.clone(), &chunk, frid, lrid);
1827 let page = columnar::encode_page_native(ty.clone(), &chunk, encoding, compress, le)?;
1828 Ok((page, stat))
1829 };
1830 let pairs: Vec<(Vec<u8>, PageStat)> = if bounds.len() > 1 {
1832 bounds
1833 .par_iter()
1834 .map(encode_one)
1835 .collect::<Result<Vec<_>>>()?
1836 } else {
1837 bounds.iter().map(encode_one).collect::<Result<Vec<_>>>()?
1838 };
1839 let (pages, stats) = pairs.into_iter().unzip();
1840 Ok((pages, stats))
1841}
1842
1843fn value_column_pages(
1845 ty: TypeId,
1846 vals: &[Value],
1847 bounds: &[(usize, usize, u64, u64)],
1848) -> Result<(Vec<Vec<u8>>, Vec<PageStat>, Encoding)> {
1849 let encoding = choose_encoding(&ty, vals);
1850 let mut pages = Vec::with_capacity(bounds.len());
1851 let mut stats = Vec::with_capacity(bounds.len());
1852 for &(s, e, frid, lrid) in bounds {
1853 let chunk = &vals[s..e];
1854 pages.push(columnar::encode_page(ty.clone(), chunk, encoding)?);
1855 let native = columnar::values_to_native(ty.clone(), chunk);
1856 stats.push(columnar::page_stat_for(ty.clone(), &native, frid, lrid));
1857 }
1858 Ok((pages, stats, encoding))
1859}
1860
1861fn choose_encoding(ty: &TypeId, values: &[Value]) -> Encoding {
1864 use std::collections::HashSet;
1865 if matches!(ty, TypeId::Bytes) {
1866 let n = values.len();
1867 if n > 0 {
1868 let distinct = values
1869 .iter()
1870 .filter(|v| !matches!(v, Value::Null))
1871 .map(|v| v.encode_key())
1872 .collect::<HashSet<_>>()
1873 .len();
1874 if (distinct as f64 / n as f64) < 0.5 {
1875 return Encoding::Dictionary;
1876 }
1877 }
1878 }
1879 Encoding::Zstd
1880}
1881
1882fn choose_encoding_native(ty: &TypeId, col: &columnar::NativeColumn) -> Encoding {
1885 use std::collections::HashSet;
1886 match (ty, col) {
1887 (TypeId::Int64 | TypeId::TimestampNanos, columnar::NativeColumn::Int64 { data, .. }) => {
1888 if data.windows(2).all(|w| w[0] <= w[1]) {
1889 Encoding::Delta
1890 } else {
1891 Encoding::Zstd
1892 }
1893 }
1894 (
1895 TypeId::Bytes,
1896 columnar::NativeColumn::Bytes {
1897 offsets, values, ..
1898 },
1899 ) => {
1900 let n = offsets.len().saturating_sub(1);
1901 if n > 0 {
1902 let distinct: HashSet<&[u8]> = (0..n)
1903 .map(|i| &values[offsets[i] as usize..offsets[i + 1] as usize])
1904 .collect();
1905 if (distinct.len() as f64 / n as f64) < 0.5 {
1906 return Encoding::Dictionary;
1907 }
1908 }
1909 Encoding::Zstd
1910 }
1911 _ => Encoding::Zstd,
1912 }
1913}
1914
1915fn build_learned_trailer_native(col: &columnar::NativeColumn) -> Vec<u8> {
1917 let points: Vec<(u64, usize)> = match col {
1918 columnar::NativeColumn::Int64 { data, .. } => data
1919 .iter()
1920 .enumerate()
1921 .map(|(i, v)| (*v as u64, i))
1922 .collect(),
1923 _ => Vec::new(),
1924 };
1925 let pgm = PgmIndex::build(&points, LEARNED_EPSILON);
1926 bincode::serialize(&pgm).expect("pgm serialize")
1927}
1928
1929fn row_id_bounds(rows: &[Row]) -> (u64, u64) {
1930 match (rows.first(), rows.last()) {
1931 (Some(f), Some(l)) => (f.row_id.0, l.row_id.0),
1932 _ => (0, 0),
1933 }
1934}
1935
1936pub struct RunReader {
1942 file: File,
1943 mmap: Option<memmap2::Mmap>,
1944 header: RunHeader,
1945 dir: Vec<ColumnPageHeader>,
1946 schema: Schema,
1947 table_id: u64,
1949 cipher: Option<Box<dyn Cipher>>,
1951 nonce_prefix: [u8; 12],
1953 col_cache: HashMap<u16, Vec<Value>>,
1954 page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
1958 decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
1962 epoch_override: Option<Epoch>,
1966}
1967
1968#[derive(Debug, Clone, Copy)]
1969pub struct RunVisibleVersion {
1970 pub row_id: RowId,
1971 pub committed_epoch: Epoch,
1972 pub deleted: bool,
1973 pub commit_ts: Option<HlcTimestamp>,
1977 pub(crate) page_seq: usize,
1978 pub(crate) within_page: usize,
1979}
1980
1981pub struct RunVisibleVersionCursor {
1989 reader: RunReader,
1990 snapshot: Snapshot,
1991 page_row_counts: Vec<usize>,
1992 page_seq: usize,
1993 within_page: usize,
1994 row_ids: Vec<i64>,
1995 epochs: Vec<i64>,
1996 deleted: Vec<u8>,
1997 commit_ts: Vec<Option<HlcTimestamp>>,
2000 has_commit_ts_col: bool,
2001 lookahead: Option<RunVisibleVersion>,
2002 materialized_page: Option<usize>,
2003 materialized_columns: Vec<(u16, columnar::NativeColumn)>,
2004}
2005
2006impl RunVisibleVersionCursor {
2007 pub(crate) fn new(reader: RunReader, snapshot: Snapshot) -> Result<Self> {
2008 let page_row_counts = reader.page_row_counts(SYS_ROW_ID)?;
2009 let has_commit_ts_col = reader.has_column(SYS_COMMIT_TS);
2010 Ok(Self {
2011 reader,
2012 snapshot,
2013 page_row_counts,
2014 page_seq: 0,
2015 within_page: 0,
2016 row_ids: Vec::new(),
2017 epochs: Vec::new(),
2018 deleted: Vec::new(),
2019 commit_ts: Vec::new(),
2020 has_commit_ts_col,
2021 lookahead: None,
2022 materialized_page: None,
2023 materialized_columns: Vec::new(),
2024 })
2025 }
2026
2027 fn load_system_page(&mut self, control: &crate::ExecutionControl) -> Result<bool> {
2028 while self.page_seq < self.page_row_counts.len() {
2029 control.checkpoint()?;
2030 let rows = self.page_row_counts[self.page_seq];
2031 if rows == 0 {
2032 self.page_seq += 1;
2033 continue;
2034 }
2035 self.row_ids = match columnar::decode_page_native(
2036 TypeId::Int64,
2037 &self.reader.read_page(SYS_ROW_ID, self.page_seq)?,
2038 rows,
2039 )? {
2040 columnar::NativeColumn::Int64 { data, .. } => data,
2041 _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
2042 };
2043 self.epochs = if let Some(epoch) = self.reader.epoch_override {
2044 vec![epoch.0 as i64; rows]
2045 } else {
2046 match columnar::decode_page_native(
2047 TypeId::Int64,
2048 &self.reader.read_page(SYS_EPOCH, self.page_seq)?,
2049 rows,
2050 )? {
2051 columnar::NativeColumn::Int64 { data, .. } => data,
2052 _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
2053 }
2054 };
2055 self.deleted = match columnar::decode_page_native(
2056 TypeId::Bool,
2057 &self.reader.read_page(SYS_DELETED, self.page_seq)?,
2058 rows,
2059 )? {
2060 columnar::NativeColumn::Bool { data, .. } => data,
2061 _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
2062 };
2063 self.commit_ts.clear();
2064 if self.has_commit_ts_col {
2065 let page = self.reader.read_page(SYS_COMMIT_TS, self.page_seq)?;
2066 let native = columnar::decode_page_native(TypeId::Bytes, &page, rows)?;
2067 self.commit_ts.reserve(rows);
2068 for i in 0..rows {
2069 self.commit_ts
2070 .push(decode_commit_ts_value(native.value_at(i).as_ref()));
2071 }
2072 }
2073 self.within_page = 0;
2074 return Ok(true);
2075 }
2076 Ok(false)
2077 }
2078
2079 fn next_raw(&mut self, control: &crate::ExecutionControl) -> Result<Option<RunVisibleVersion>> {
2080 if self.within_page >= self.row_ids.len() {
2081 if !self.row_ids.is_empty() {
2082 self.page_seq += 1;
2083 self.row_ids.clear();
2084 self.epochs.clear();
2085 self.deleted.clear();
2086 self.commit_ts.clear();
2087 }
2088 if !self.load_system_page(control)? {
2089 return Ok(None);
2090 }
2091 }
2092 if self.within_page.is_multiple_of(256) {
2093 control.checkpoint()?;
2094 }
2095 let position = self.within_page;
2096 self.within_page += 1;
2097 let commit_ts = self.commit_ts.get(position).copied().flatten();
2098 Ok(Some(RunVisibleVersion {
2099 row_id: RowId(self.row_ids[position] as u64),
2100 committed_epoch: Epoch(self.epochs[position] as u64),
2101 deleted: self.deleted[position] != 0,
2102 commit_ts,
2103 page_seq: self.page_seq,
2104 within_page: position,
2105 }))
2106 }
2107
2108 pub fn next_visible_version(
2109 &mut self,
2110 control: &crate::ExecutionControl,
2111 ) -> Result<Option<RunVisibleVersion>> {
2112 loop {
2113 let first = match self.lookahead.take() {
2114 Some(version) => version,
2115 None => match self.next_raw(control)? {
2116 Some(version) => version,
2117 None => return Ok(None),
2118 },
2119 };
2120 let row_id = first.row_id;
2121 let mut best = self
2126 .snapshot
2127 .observes_row(first.committed_epoch, first.commit_ts)
2128 .then_some(first);
2129 while let Some(candidate) = self.next_raw(control)? {
2130 if candidate.row_id != row_id {
2131 self.lookahead = Some(candidate);
2132 break;
2133 }
2134 if self
2135 .snapshot
2136 .observes_row(candidate.committed_epoch, candidate.commit_ts)
2137 && best.is_none_or(|current| {
2138 crate::epoch::Snapshot::version_is_newer(
2139 candidate.committed_epoch,
2140 candidate.commit_ts,
2141 current.committed_epoch,
2142 current.commit_ts,
2143 )
2144 })
2145 {
2146 best = Some(candidate);
2147 }
2148 }
2149 if best.is_some() {
2150 return Ok(best);
2151 }
2152 }
2153 }
2154
2155 pub fn materialize(
2156 &mut self,
2157 version: RunVisibleVersion,
2158 control: &crate::ExecutionControl,
2159 ) -> Result<Row> {
2160 if self.materialized_page != Some(version.page_seq) {
2161 let rows = self.page_row_counts[version.page_seq];
2162 let columns = self.reader.schema.columns.clone();
2163 let mut materialized = Vec::with_capacity(columns.len());
2164 for (index, column) in columns.into_iter().enumerate() {
2165 if index % 16 == 0 {
2166 control.checkpoint()?;
2167 }
2168 let native = if self.reader.has_column(column.id) {
2169 columnar::decode_page_native(
2170 column.ty,
2171 &self.reader.read_page(column.id, version.page_seq)?,
2172 rows,
2173 )?
2174 } else {
2175 columnar::null_native(column.ty, rows)
2176 };
2177 materialized.push((column.id, native));
2178 }
2179 self.materialized_columns = materialized;
2180 self.materialized_page = Some(version.page_seq);
2181 }
2182 let columns = self
2183 .materialized_columns
2184 .iter()
2185 .map(|(column_id, column)| {
2186 (
2187 *column_id,
2188 column.value_at(version.within_page).unwrap_or(Value::Null),
2189 )
2190 })
2191 .collect();
2192 let commit_ts = version.commit_ts.or_else(|| {
2195 if self.reader.has_column(SYS_COMMIT_TS) {
2196 let page = self
2197 .reader
2198 .read_page(SYS_COMMIT_TS, version.page_seq)
2199 .ok()?;
2200 let native = columnar::decode_page_native(
2201 TypeId::Bytes,
2202 &page,
2203 self.page_row_counts[version.page_seq],
2204 )
2205 .ok()?;
2206 decode_commit_ts_value(native.value_at(version.within_page).as_ref())
2207 } else {
2208 None
2209 }
2210 });
2211 Ok(Row {
2212 row_id: version.row_id,
2213 committed_epoch: version.committed_epoch,
2214 columns,
2215 deleted: version.deleted,
2216 commit_ts,
2217 })
2218 }
2219}
2220
2221impl RunReader {
2222 pub fn open(path: impl AsRef<Path>, schema: Schema, kek: Option<Arc<Kek>>) -> Result<Self> {
2223 Self::open_with_cache(path, schema, kek, None, None, 0, None)
2224 }
2225
2226 pub(crate) fn open_file(file: File, schema: Schema, kek: Option<Arc<Kek>>) -> Result<Self> {
2227 Self::open_file_with_cache(file, schema, kek, None, None, 0, None, None)
2228 }
2229
2230 #[allow(clippy::too_many_arguments)]
2231 pub(crate) fn open_with_cache(
2232 path: impl AsRef<Path>,
2233 schema: Schema,
2234 kek: Option<Arc<Kek>>,
2235 page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
2236 decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
2237 table_id: u64,
2238 verified_runs: Option<&parking_lot::Mutex<std::collections::HashSet<u128>>>,
2239 ) -> Result<Self> {
2240 let path = path.as_ref().to_path_buf();
2241 let file = crate::durable_file::open_regular_nofollow(&path)?;
2242 Self::open_file_with_cache(
2243 file,
2244 schema,
2245 kek,
2246 page_cache,
2247 decoded_cache,
2248 table_id,
2249 verified_runs,
2250 Some(path),
2251 )
2252 }
2253
2254 #[allow(clippy::too_many_arguments)]
2255 pub(crate) fn open_file_with_cache(
2256 mut file: File,
2257 schema: Schema,
2258 kek: Option<Arc<Kek>>,
2259 page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
2260 decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
2261 table_id: u64,
2262 verified_runs: Option<&parking_lot::Mutex<std::collections::HashSet<u128>>>,
2263 path: Option<PathBuf>,
2264 ) -> Result<Self> {
2265 let header = match verified_runs {
2266 Some(cache) => {
2267 let header = read_header_fast_from_file(&mut file)?;
2268 if cache.lock().contains(&header.run_id) {
2269 header
2270 } else {
2271 let verified = read_header_from_file(&mut file)?;
2272 cache.lock().insert(verified.run_id);
2273 verified
2274 }
2275 }
2276 None => read_header_from_file(&mut file)?,
2277 };
2278 let mut dir = read_column_dir_from_file(&mut file, &header)?;
2279 validate_column_directory_layout(&header, &dir)?;
2280 if header.is_encrypted() != kek.is_some() {
2281 return Err(MongrelError::Encryption(
2282 "sorted-run encryption mode differs from the database".into(),
2283 ));
2284 }
2285 let (cipher, nonce_prefix): (Option<Box<dyn Cipher>>, [u8; 12]) = if header.is_encrypted() {
2288 let kek = kek.as_ref().ok_or_else(|| {
2289 MongrelError::Encryption(
2290 "run is encrypted but no key-encryption key was provided".into(),
2291 )
2292 })?;
2293 if header.encryption_descriptor_offset == 0 {
2294 return Err(MongrelError::Encryption(
2295 "encrypted run has no encryption descriptor".into(),
2296 ));
2297 }
2298 let desc_bytes = read_encryption_descriptor_bytes_from_file(&mut file, &header)?;
2299 verify_run_mac(&mut file, &header, &dir, kek, &desc_bytes)?;
2305 let enc = crate::encryption::build_run_cipher(kek, &desc_bytes)?;
2306 if header.encrypted_stats_offset != 0 {
2310 overlay_encrypted_stats(
2311 &mut file,
2312 &header,
2313 enc.cipher.as_ref(),
2314 enc.nonce_prefix,
2315 &mut dir,
2316 )?;
2317 }
2318 (Some(enc.cipher), enc.nonce_prefix)
2319 } else {
2320 (None, [0u8; 12])
2321 };
2322 let mmap = unsafe { memmap2::MmapOptions::new().map(&file) }.ok();
2329 let _ = path;
2330 Ok(Self {
2331 file,
2332 mmap,
2333 header,
2334 dir,
2335 schema,
2336 table_id,
2337 cipher,
2338 nonce_prefix,
2339 col_cache: HashMap::new(),
2340 epoch_override: None,
2341 page_cache,
2342 decoded_cache,
2343 })
2344 }
2345
2346 pub fn header(&self) -> &RunHeader {
2347 &self.header
2348 }
2349
2350 pub(crate) fn validate_all_pages(&mut self) -> Result<()> {
2351 let mut columns = std::collections::HashSet::new();
2352 let row_header = self.find_header(SYS_ROW_ID)?.clone();
2353 let expected_rows = row_header
2354 .page_stats
2355 .iter()
2356 .map(|stat| stat.row_count)
2357 .collect::<Vec<_>>();
2358 let mut row_bounds = Vec::with_capacity(row_header.page_stats.len());
2359 let mut previous = None::<u64>;
2360 let mut first = None::<u64>;
2361 let mut last = None::<u64>;
2362 let mut counted = 0_u64;
2363 for (page, stat) in row_header.page_stats.iter().enumerate() {
2364 let bytes = self.read_page(SYS_ROW_ID, page)?;
2365 let native =
2366 columnar::decode_page_native(TypeId::Int64, &bytes, stat.row_count as usize)?;
2367 if columnar::page_stat_for(TypeId::Int64, &native, 0, 0).null_count != 0 {
2368 return Err(MongrelError::InvalidArgument(
2369 "sorted run row-id page contains nulls".into(),
2370 ));
2371 }
2372 let columnar::NativeColumn::Int64 { data, validity } = native else {
2373 return Err(MongrelError::InvalidArgument(
2374 "sorted run row-id page has the wrong type".into(),
2375 ));
2376 };
2377 let _ = validity;
2378 if data.is_empty() {
2379 if self.header.row_count != 0 || stat.row_count != 0 {
2380 return Err(MongrelError::InvalidArgument(
2381 "sorted run row-id page is unexpectedly empty".into(),
2382 ));
2383 }
2384 row_bounds.push((0, 0));
2385 continue;
2386 }
2387 if data.iter().any(|value| *value < 0) {
2388 return Err(MongrelError::InvalidArgument(
2389 "sorted run contains a negative row id".into(),
2390 ));
2391 }
2392 let page_first = data[0] as u64;
2393 let page_last = data[data.len() - 1] as u64;
2394 for value in data {
2395 let value = value as u64;
2396 if previous.is_some_and(|prior| {
2397 value < prior || (self.header.is_clean() && value == prior)
2398 }) {
2399 return Err(MongrelError::InvalidArgument(
2400 "sorted run row ids are not ordered".into(),
2401 ));
2402 }
2403 first.get_or_insert(value);
2404 previous = Some(value);
2405 last = Some(value);
2406 counted += 1;
2407 }
2408 if stat.first_row_id != page_first || stat.last_row_id != page_last {
2409 return Err(MongrelError::InvalidArgument(
2410 "sorted run row-id page bounds are stale".into(),
2411 ));
2412 }
2413 row_bounds.push((page_first, page_last));
2414 }
2415 if counted != self.header.row_count
2416 || first.unwrap_or(0) != self.header.min_row_id
2417 || last.unwrap_or(0) != self.header.max_row_id
2418 {
2419 return Err(MongrelError::InvalidArgument(
2420 "sorted run header row bounds differ from its pages".into(),
2421 ));
2422 }
2423 for column in self.dir.clone() {
2424 if !columns.insert(column.column_id) {
2425 return Err(MongrelError::InvalidArgument(format!(
2426 "sorted run contains duplicate column {}",
2427 column.column_id
2428 )));
2429 }
2430 let rows = column
2431 .page_stats
2432 .iter()
2433 .map(|stat| stat.row_count)
2434 .collect::<Vec<_>>();
2435 if rows != expected_rows {
2436 return Err(MongrelError::InvalidArgument(
2437 "sorted run columns have inconsistent page row counts".into(),
2438 ));
2439 }
2440 let ty = self.resolve_type(column.column_id);
2441 if column.type_id_tag != type_tag(&ty)
2442 || column.encoding > Encoding::Zstd as u8
2443 || (!is_system_column_id(column.column_id)
2444 && self
2445 .schema
2446 .columns
2447 .iter()
2448 .all(|item| item.id != column.column_id))
2449 {
2450 return Err(MongrelError::InvalidArgument(
2451 "sorted run column type or encoding is invalid".into(),
2452 ));
2453 }
2454 for (page, stat) in column.page_stats.iter().enumerate() {
2455 let bytes = self.read_page(column.column_id, page)?;
2456 if bytes.len() != stat.uncompressed_len as usize {
2457 return Err(MongrelError::InvalidArgument(
2458 "sorted run page length differs from its metadata".into(),
2459 ));
2460 }
2461 let native =
2462 match columnar::decode_page_native(ty.clone(), &bytes, stat.row_count as usize)
2463 {
2464 Ok(native) => native,
2465 Err(MongrelError::InvalidArgument(message))
2466 if message.starts_with("decode_page_native: unsupported ty") =>
2467 {
2468 let values =
2469 columnar::decode_page(ty.clone(), &bytes, stat.row_count as usize)?;
2470 columnar::values_to_native(ty.clone(), &values)
2471 }
2472 Err(error) => return Err(error),
2473 };
2474 let (first_row_id, last_row_id) =
2475 row_bounds.get(page).copied().ok_or_else(|| {
2476 MongrelError::InvalidArgument(
2477 "sorted run column has more pages than its row-id column".into(),
2478 )
2479 })?;
2480 let expected =
2481 columnar::page_stat_for(ty.clone(), &native, first_row_id, last_row_id);
2482 if stat.first_row_id != expected.first_row_id
2483 || stat.last_row_id != expected.last_row_id
2484 || stat.null_count != expected.null_count
2485 || stat.min != expected.min
2486 || stat.max != expected.max
2487 {
2488 return Err(MongrelError::InvalidArgument(
2489 "sorted run page statistics differ from decoded values".into(),
2490 ));
2491 }
2492 }
2493 }
2494 if !columns.contains(&SYS_ROW_ID)
2495 || !columns.contains(&SYS_EPOCH)
2496 || !columns.contains(&SYS_DELETED)
2497 || expected_rows.into_iter().map(u64::from).sum::<u64>() != self.header.row_count
2498 {
2499 return Err(MongrelError::InvalidArgument(
2500 "sorted run system columns or row count are invalid".into(),
2501 ));
2502 }
2503 if self.header.schema_id == self.schema.schema_id
2504 && self
2505 .schema
2506 .columns
2507 .iter()
2508 .any(|column| !columns.contains(&column.id))
2509 {
2510 return Err(MongrelError::InvalidArgument(
2511 "sorted run is missing a column from its declared schema".into(),
2512 ));
2513 }
2514
2515 for row_index in 0..usize::try_from(self.header.row_count).map_err(|_| {
2519 MongrelError::InvalidArgument("sorted run row count exceeds this platform".into())
2520 })? {
2521 let epoch = match self.column(SYS_EPOCH)?.get(row_index) {
2522 Some(Value::Int64(value)) if *value >= 0 => *value as u64,
2523 _ => {
2524 return Err(MongrelError::InvalidArgument(
2525 "sorted run contains an invalid commit epoch".into(),
2526 ))
2527 }
2528 };
2529 if epoch > self.header.epoch_created || (self.header.is_uniform_epoch() && epoch != 0) {
2530 return Err(MongrelError::InvalidArgument(
2531 "sorted run commit epoch exceeds its creation epoch".into(),
2532 ));
2533 }
2534 let deleted = match self.column(SYS_DELETED)?.get(row_index) {
2535 Some(Value::Bool(value)) => *value,
2536 _ => {
2537 return Err(MongrelError::InvalidArgument(
2538 "sorted run contains an invalid tombstone marker".into(),
2539 ))
2540 }
2541 };
2542 let mut values = Vec::with_capacity(self.schema.columns.len());
2543 for column in self.schema.columns.clone() {
2544 let value = if columns.contains(&column.id) {
2545 self.column(column.id)?
2546 .get(row_index)
2547 .cloned()
2548 .unwrap_or(Value::Null)
2549 } else {
2550 Value::Null
2551 };
2552 values.push((column.id, value));
2553 }
2554 if !deleted {
2555 self.schema
2556 .validate_persisted_values(&values)
2557 .map_err(|error| {
2558 MongrelError::InvalidArgument(format!(
2559 "sorted run row violates its schema: {error}"
2560 ))
2561 })?;
2562 }
2563 }
2564 Ok(())
2565 }
2566
2567 pub(crate) fn set_uniform_epoch(&mut self, epoch: Epoch) {
2571 if self.header.is_uniform_epoch() {
2572 self.epoch_override = Some(epoch);
2573 self.col_cache.remove(&SYS_EPOCH);
2575 }
2576 }
2577
2578 #[allow(dead_code)] pub(crate) fn into_visible_version_cursor(
2581 self,
2582 snapshot: Epoch,
2583 ) -> Result<RunVisibleVersionCursor> {
2584 RunVisibleVersionCursor::new(self, Snapshot::at(snapshot))
2587 }
2588
2589 pub fn into_visible_version_cursor_at(
2593 self,
2594 snapshot: Snapshot,
2595 ) -> Result<RunVisibleVersionCursor> {
2596 RunVisibleVersionCursor::new(self, snapshot)
2597 }
2598
2599 pub fn is_clean(&self) -> bool {
2602 self.header.is_clean()
2603 }
2604
2605 pub fn row_count(&self) -> usize {
2606 self.header.row_count as usize
2607 }
2608
2609 pub(crate) fn clean_contiguous_row_ids(&self) -> bool {
2610 let n = self.row_count();
2611 n > 0
2612 && self.is_clean()
2613 && self.epoch_override.is_none()
2614 && self.header.max_row_id >= self.header.min_row_id
2615 && self
2616 .header
2617 .max_row_id
2618 .checked_sub(self.header.min_row_id)
2619 .and_then(|span| span.checked_add(1))
2620 == Some(n as u64)
2621 }
2622
2623 pub(crate) fn position_for_row_id_fast(&self, row_id: u64) -> Option<usize> {
2624 if !self.clean_contiguous_row_ids()
2625 || row_id < self.header.min_row_id
2626 || row_id > self.header.max_row_id
2627 {
2628 return None;
2629 }
2630 Some((row_id - self.header.min_row_id) as usize)
2631 }
2632
2633 pub(crate) fn positions_for_row_ids_fast(&self, row_ids: &[u64]) -> Option<Vec<usize>> {
2634 if !self.clean_contiguous_row_ids() {
2635 return None;
2636 }
2637 let mut positions = Vec::with_capacity(row_ids.len());
2638 for &row_id in row_ids {
2639 if let Some(pos) = self.position_for_row_id_fast(row_id) {
2640 positions.push(pos);
2641 }
2642 }
2643 positions.sort_unstable();
2644 Some(positions)
2645 }
2646
2647 fn resolve_type(&self, column_id: u16) -> TypeId {
2648 match column_id {
2649 SYS_ROW_ID | SYS_EPOCH => TypeId::Int64,
2650 SYS_DELETED => TypeId::Bool,
2651 SYS_COMMIT_TS => TypeId::Bytes,
2652 _ => self
2653 .schema
2654 .columns
2655 .iter()
2656 .find(|c| c.id == column_id)
2657 .map(|c| c.ty.clone())
2658 .unwrap_or(TypeId::Bytes),
2659 }
2660 }
2661
2662 fn commit_ts_at(&mut self, index: usize) -> Result<Option<HlcTimestamp>> {
2664 if !self.has_column(SYS_COMMIT_TS) {
2665 return Ok(None);
2666 }
2667 Ok(decode_commit_ts_value(
2668 self.column(SYS_COMMIT_TS)?.get(index),
2669 ))
2670 }
2671
2672 fn find_header(&self, column_id: u16) -> Result<&ColumnPageHeader> {
2673 self.dir
2674 .iter()
2675 .find(|h| h.column_id == column_id)
2676 .ok_or_else(|| MongrelError::ColumnNotFound(format!("column {column_id}")))
2677 }
2678
2679 fn col_encrypted(&self, column_id: u16) -> bool {
2685 self.dir
2686 .iter()
2687 .find(|h| h.column_id == column_id)
2688 .map(|h| h.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0)
2689 .unwrap_or(false)
2690 }
2691
2692 pub(crate) fn read_page(&mut self, column_id: u16, page_seq: usize) -> Result<Vec<u8>> {
2693 let (offset, compressed_len, encrypted) = {
2694 let ch = self.find_header(column_id)?;
2695 let stat = ch
2696 .page_stats
2697 .get(page_seq)
2698 .ok_or_else(|| MongrelError::InvalidArgument("page seq out of range".into()))?;
2699 (
2700 stat.offset,
2701 stat.compressed_len,
2702 ch.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0,
2703 )
2704 };
2705 let end = offset
2706 .checked_add(compressed_len as u64)
2707 .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
2708 let start = usize::try_from(offset)
2709 .map_err(|_| MongrelError::InvalidArgument("run page offset is too large".into()))?;
2710 let end = usize::try_from(end)
2711 .map_err(|_| MongrelError::InvalidArgument("run page end is too large".into()))?;
2712 let key = page_cache_key(self.table_id, self.header.run_id, column_id, page_seq);
2715 if let Some(cache) = &self.page_cache {
2716 if let Some(bytes) = cache.lock(&key).get(
2717 &key,
2718 crate::epoch::Snapshot::at(crate::epoch::Epoch(u64::MAX)),
2719 ) {
2720 return decrypt_or_passthrough(
2721 self.cipher.as_deref(),
2722 self.nonce_prefix,
2723 column_id,
2724 page_seq,
2725 encrypted,
2726 &bytes,
2727 );
2728 }
2729 }
2730 let buf = match &self.mmap {
2731 Some(m) => m
2734 .get(start..end)
2735 .ok_or_else(|| {
2736 MongrelError::InvalidArgument("run page is outside the mapped file".into())
2737 })?
2738 .to_vec(),
2739 None => {
2740 self.file.seek(SeekFrom::Start(offset))?;
2741 let mut buf = vec![0u8; compressed_len as usize];
2742 self.file.read_exact(&mut buf)?;
2743 buf
2744 }
2745 };
2746 if let Some(cache) = &self.page_cache {
2748 cache.lock(&key).insert(crate::page::CachedPage {
2749 committed_epoch: crate::epoch::Epoch(self.header.epoch_created),
2750 content_hash: key,
2751 bytes: bytes::Bytes::copy_from_slice(&buf),
2752 });
2753 }
2754 decrypt_or_passthrough(
2755 self.cipher.as_deref(),
2756 self.nonce_prefix,
2757 column_id,
2758 page_seq,
2759 encrypted,
2760 &buf,
2761 )
2762 }
2763
2764 fn read_page_shared(&self, column_id: u16, page_seq: usize) -> Result<Vec<u8>> {
2769 let ch = self.find_header(column_id)?;
2770 let stat = ch
2771 .page_stats
2772 .get(page_seq)
2773 .ok_or_else(|| MongrelError::InvalidArgument("page seq out of range".into()))?;
2774 let encrypted = ch.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0;
2775 let key = page_cache_key(self.table_id, self.header.run_id, column_id, page_seq);
2778 if let Some(cache) = &self.page_cache {
2779 if let Some(guard) = cache.try_lock(&key) {
2780 if let Some(bytes) = guard.try_get(
2781 &key,
2782 crate::epoch::Snapshot::at(crate::epoch::Epoch(u64::MAX)),
2783 ) {
2784 return decrypt_or_passthrough(
2785 self.cipher.as_deref(),
2786 self.nonce_prefix,
2787 column_id,
2788 page_seq,
2789 encrypted,
2790 &bytes,
2791 );
2792 }
2793 }
2794 }
2795 let mmap = self.mmap.as_ref().ok_or_else(|| {
2796 MongrelError::InvalidArgument("parallel page decode requires an mmap-backed run".into())
2797 })?;
2798 let end = stat
2799 .offset
2800 .checked_add(stat.compressed_len as u64)
2801 .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
2802 let start = usize::try_from(stat.offset)
2803 .map_err(|_| MongrelError::InvalidArgument("run page offset is too large".into()))?;
2804 let end = usize::try_from(end)
2805 .map_err(|_| MongrelError::InvalidArgument("run page end is too large".into()))?;
2806 let buf = mmap
2807 .get(start..end)
2808 .ok_or_else(|| {
2809 MongrelError::InvalidArgument("run page is outside the mapped file".into())
2810 })?
2811 .to_vec();
2812 if let Some(cache) = &self.page_cache {
2816 if let Some(mut guard) = cache.try_lock(&key) {
2817 guard.insert(crate::page::CachedPage {
2818 committed_epoch: crate::epoch::Epoch(self.header.epoch_created),
2819 content_hash: key,
2820 bytes: bytes::Bytes::copy_from_slice(&buf),
2821 });
2822 }
2823 }
2824 decrypt_or_passthrough(
2825 self.cipher.as_deref(),
2826 self.nonce_prefix,
2827 column_id,
2828 page_seq,
2829 encrypted,
2830 &buf,
2831 )
2832 }
2833
2834 fn column(&mut self, column_id: u16) -> Result<&[Value]> {
2836 if column_id == SYS_EPOCH {
2839 if let Some(ov) = self.epoch_override {
2840 if !self.col_cache.contains_key(&column_id) {
2841 let n = self.row_count();
2842 self.col_cache
2843 .insert(column_id, vec![Value::Int64(ov.0 as i64); n]);
2844 }
2845 return Ok(self.col_cache.get(&column_id).unwrap().as_slice());
2846 }
2847 }
2848 if !self.col_cache.contains_key(&column_id) {
2849 let ty = self.resolve_type(column_id);
2850 let page_rows: Vec<usize> = {
2851 let ch = self.find_header(column_id)?;
2852 ch.page_stats.iter().map(|s| s.row_count as usize).collect()
2853 };
2854 let mut decoded: Vec<Value> = Vec::with_capacity(self.row_count());
2855 for (seq, &pr) in page_rows.iter().enumerate() {
2856 let page = self.read_page(column_id, seq)?;
2857 decoded.extend(columnar::decode_page(ty.clone(), &page, pr)?);
2858 }
2859 self.col_cache.insert(column_id, decoded);
2860 }
2861 Ok(self.col_cache.get(&column_id).unwrap().as_slice())
2862 }
2863
2864 pub fn get_version(&mut self, row_id: RowId, snapshot: Epoch) -> Result<Option<(Epoch, Row)>> {
2878 self.get_version_at(row_id, Snapshot::at(snapshot))
2879 }
2880
2881 pub fn get_version_at(
2893 &mut self,
2894 row_id: RowId,
2895 snapshot: Snapshot,
2896 ) -> Result<Option<(Epoch, Row)>> {
2897 match self.find_version_page_at(row_id, snapshot)? {
2898 None => Ok(None),
2899 Some((epoch, _commit_ts, seq, local_index)) => Ok(Some((
2900 Epoch(epoch),
2901 self.materialize_in_page(seq, local_index)?,
2902 ))),
2903 }
2904 }
2905
2906 pub(crate) fn get_version_stamp_at(
2912 &mut self,
2913 row_id: RowId,
2914 snapshot: Snapshot,
2915 ) -> Result<Option<(VersionStamp, Row)>> {
2916 match self.find_version_page_at(row_id, snapshot)? {
2917 None => Ok(None),
2918 Some((epoch, commit_ts, seq, local_index)) => Ok(Some((
2919 VersionStamp {
2920 epoch: Epoch(epoch),
2921 commit_ts,
2922 },
2923 self.materialize_in_page(seq, local_index)?,
2924 ))),
2925 }
2926 }
2927
2928 #[allow(dead_code)] fn find_version_page(
2935 &mut self,
2936 row_id: RowId,
2937 snapshot: Epoch,
2938 ) -> Result<Option<FoundVersionPage>> {
2939 self.find_version_page_at(row_id, Snapshot::at(snapshot))
2940 }
2941
2942 fn find_version_page_at(
2953 &mut self,
2954 row_id: RowId,
2955 snapshot: Snapshot,
2956 ) -> Result<Option<FoundVersionPage>> {
2957 let n = self.row_count();
2958 if n == 0 {
2959 return Ok(None);
2960 }
2961 let target = row_id.0 as i64;
2962 let ch = self.find_header(SYS_ROW_ID)?;
2963 let mut page_start = 0u64;
2964 let candidate_pages: Vec<(usize, u64)> = ch .page_stats
2966 .iter()
2967 .enumerate()
2968 .filter_map(|(seq, s)| {
2969 let start = page_start;
2970 page_start += s.row_count as u64;
2971 (s.first_row_id <= row_id.0 && row_id.0 <= s.last_row_id).then_some((seq, start))
2972 })
2973 .collect();
2974 if candidate_pages.is_empty() {
2975 return Ok(None);
2976 }
2977 let ty = self.resolve_type(SYS_ROW_ID);
2978 let has_commit_ts_col = self.has_column(SYS_COMMIT_TS);
2979 let mut best: Option<(u64, Option<HlcTimestamp>, usize, usize)> = None; for (seq, _page_row_start) in candidate_pages {
2986 let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2987 let row_id_col =
2988 self.decode_page_native_cached(ty.clone(), SYS_ROW_ID, seq, page_rows)?;
2989 let row_ids = match row_id_col.as_ref() {
2990 columnar::NativeColumn::Int64 { data, .. } => data,
2991 _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
2992 };
2993 let local = match row_ids.binary_search(&target) {
2994 Ok(i) => i,
2995 Err(_) => continue,
2996 };
2997 let epoch_ty = self.resolve_type(SYS_EPOCH);
2998 let epoch_col = self.decode_page_native_cached(epoch_ty, SYS_EPOCH, seq, page_rows)?;
2999 let epochs = match epoch_col.as_ref() {
3000 columnar::NativeColumn::Int64 { data, .. } => data,
3001 _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
3002 };
3003 let mut lo = local;
3006 while lo > 0 && row_ids[lo - 1] == target {
3007 lo -= 1;
3008 }
3009 let mut hi = local;
3010 while hi + 1 < row_ids.len() && row_ids[hi + 1] == target {
3011 hi += 1;
3012 }
3013 let commit_ts_native = if has_commit_ts_col {
3017 Some(self.decode_page_native_cached(
3018 TypeId::Bytes,
3019 SYS_COMMIT_TS,
3020 seq,
3021 page_rows,
3022 )?)
3023 } else {
3024 None
3025 };
3026 for (i, &epoch_val) in epochs[lo..=hi].iter().enumerate() {
3027 let epoch = epoch_val as u64;
3028 let commit_ts = commit_ts_native
3029 .as_ref()
3030 .and_then(|col| decode_commit_ts_value(col.value_at(lo + i).as_ref()));
3031 if !snapshot.observes_row(Epoch(epoch), commit_ts) {
3035 continue;
3036 }
3037 let candidate = (epoch, commit_ts, seq, lo + i);
3041 let is_newer = best.as_ref().is_none_or(|cur| {
3042 crate::epoch::version_supersedes(
3043 Epoch(candidate.0),
3044 candidate.1,
3045 Epoch(cur.0),
3046 cur.1,
3047 )
3048 });
3049 if is_newer {
3050 best = Some(candidate);
3051 }
3052 }
3053 }
3054 Ok(best)
3055 }
3056
3057 pub fn get_version_column(
3065 &mut self,
3066 row_id: RowId,
3067 snapshot: Epoch,
3068 column_id: u16,
3069 ) -> Result<Option<(Epoch, bool, Option<Value>)>> {
3070 self.get_version_column_at(row_id, Snapshot::at(snapshot), column_id)
3071 }
3072
3073 pub fn get_version_column_at(
3075 &mut self,
3076 row_id: RowId,
3077 snapshot: Snapshot,
3078 column_id: u16,
3079 ) -> Result<Option<(Epoch, bool, Option<Value>)>> {
3080 let Some((epoch, _commit_ts, seq, local_index)) =
3081 self.find_version_page_at(row_id, snapshot)?
3082 else {
3083 return Ok(None);
3084 };
3085 let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
3086 let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
3087 .iter()
3088 .map(|s| s.row_count as usize)
3089 .sum();
3090 let global_index = page_start + local_index;
3091 let native_at = |slf: &mut Self, cid: u16| -> Result<Option<Value>> {
3092 if !slf.dir.iter().any(|h| h.column_id == cid) {
3093 return Ok(None);
3094 }
3095 let ty = slf.resolve_type(cid);
3096 if !matches!(
3097 ty,
3098 TypeId::Bool
3099 | TypeId::Int8
3100 | TypeId::Int16
3101 | TypeId::Int32
3102 | TypeId::Int64
3103 | TypeId::UInt8
3104 | TypeId::UInt16
3105 | TypeId::UInt32
3106 | TypeId::UInt64
3107 | TypeId::Float32
3108 | TypeId::Float64
3109 | TypeId::TimestampNanos
3110 | TypeId::Date32
3111 | TypeId::Bytes
3112 ) {
3113 return Ok(slf.column(cid)?.get(global_index).cloned());
3114 }
3115 Ok(slf
3116 .decode_page_native_cached(ty, cid, seq, page_rows)?
3117 .value_at(local_index))
3118 };
3119 let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
3120 let value = native_at(self, column_id)?;
3121 Ok(Some((Epoch(epoch), deleted, value)))
3122 }
3123
3124 pub(crate) fn get_version_column_full_at(
3129 &mut self,
3130 row_id: RowId,
3131 snapshot: Snapshot,
3132 column_id: u16,
3133 ) -> Result<Option<VersionedColumnValue>> {
3134 let Some((epoch, commit_ts, seq, local_index)) =
3135 self.find_version_page_at(row_id, snapshot)?
3136 else {
3137 return Ok(None);
3138 };
3139 let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
3140 let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
3141 .iter()
3142 .map(|s| s.row_count as usize)
3143 .sum();
3144 let global_index = page_start + local_index;
3145 let native_at = |slf: &mut Self, cid: u16| -> Result<Option<Value>> {
3146 if !slf.dir.iter().any(|h| h.column_id == cid) {
3147 return Ok(None);
3148 }
3149 let ty = slf.resolve_type(cid);
3150 if !matches!(
3151 ty,
3152 TypeId::Bool
3153 | TypeId::Int8
3154 | TypeId::Int16
3155 | TypeId::Int32
3156 | TypeId::Int64
3157 | TypeId::UInt8
3158 | TypeId::UInt16
3159 | TypeId::UInt32
3160 | TypeId::UInt64
3161 | TypeId::Float32
3162 | TypeId::Float64
3163 | TypeId::TimestampNanos
3164 | TypeId::Date32
3165 | TypeId::Bytes
3166 ) {
3167 return Ok(slf.column(cid)?.get(global_index).cloned());
3168 }
3169 Ok(slf
3170 .decode_page_native_cached(ty, cid, seq, page_rows)?
3171 .value_at(local_index))
3172 };
3173 let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
3174 let value = native_at(self, column_id)?;
3175 Ok(Some(VersionedColumnValue {
3176 stamp: VersionStamp {
3177 epoch: Epoch(epoch),
3178 commit_ts,
3179 },
3180 deleted,
3181 value,
3182 }))
3183 }
3184
3185 pub fn get_version_visibility(
3187 &mut self,
3188 row_id: RowId,
3189 snapshot: Epoch,
3190 ) -> Result<Option<(Epoch, bool)>> {
3191 self.get_version_visibility_at(row_id, Snapshot::at(snapshot))
3192 }
3193
3194 pub fn get_version_visibility_at(
3196 &mut self,
3197 row_id: RowId,
3198 snapshot: Snapshot,
3199 ) -> Result<Option<(Epoch, bool)>> {
3200 let Some((epoch, _commit_ts, seq, local_index)) =
3201 self.find_version_page_at(row_id, snapshot)?
3202 else {
3203 return Ok(None);
3204 };
3205 let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
3206 let deleted_col = self.decode_page_native_cached(
3207 self.resolve_type(SYS_DELETED),
3208 SYS_DELETED,
3209 seq,
3210 page_rows,
3211 )?;
3212 let deleted = match deleted_col.as_ref() {
3213 columnar::NativeColumn::Bool { data, .. } => data[local_index] != 0,
3214 _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
3215 };
3216 Ok(Some((Epoch(epoch), deleted)))
3217 }
3218
3219 pub(crate) fn get_version_visibility_full_at(
3223 &mut self,
3224 row_id: RowId,
3225 snapshot: Snapshot,
3226 ) -> Result<Option<VersionVisibility>> {
3227 let Some((epoch, commit_ts, seq, local_index)) =
3228 self.find_version_page_at(row_id, snapshot)?
3229 else {
3230 return Ok(None);
3231 };
3232 let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
3233 let deleted_col = self.decode_page_native_cached(
3234 self.resolve_type(SYS_DELETED),
3235 SYS_DELETED,
3236 seq,
3237 page_rows,
3238 )?;
3239 let deleted = match deleted_col.as_ref() {
3240 columnar::NativeColumn::Bool { data, .. } => data[local_index] != 0,
3241 _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
3242 };
3243 Ok(Some(VersionVisibility {
3244 stamp: VersionStamp {
3245 epoch: Epoch(epoch),
3246 commit_ts,
3247 },
3248 deleted,
3249 }))
3250 }
3251
3252 fn materialize_in_page(&mut self, seq: usize, local_index: usize) -> Result<Row> {
3261 let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
3262 let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
3263 .iter()
3264 .map(|s| s.row_count as usize)
3265 .sum();
3266 let global_index = page_start + local_index;
3267 let native_at = |slf: &mut Self, column_id: u16| -> Result<Option<Value>> {
3268 if !slf.dir.iter().any(|h| h.column_id == column_id) {
3271 return Ok(None);
3272 }
3273 let ty = slf.resolve_type(column_id);
3274 if !matches!(
3275 ty,
3276 TypeId::Bool
3277 | TypeId::Int8
3278 | TypeId::Int16
3279 | TypeId::Int32
3280 | TypeId::Int64
3281 | TypeId::UInt8
3282 | TypeId::UInt16
3283 | TypeId::UInt32
3284 | TypeId::UInt64
3285 | TypeId::Float32
3286 | TypeId::Float64
3287 | TypeId::TimestampNanos
3288 | TypeId::Date32
3289 | TypeId::Bytes
3290 ) {
3291 return Ok(slf.column(column_id)?.get(global_index).cloned());
3294 }
3295 Ok(slf
3296 .decode_page_native_cached(ty, column_id, seq, page_rows)?
3297 .value_at(local_index))
3298 };
3299 let row_id = RowId(match native_at(self, SYS_ROW_ID)? {
3300 Some(Value::Int64(x)) => x as u64,
3301 _ => 0,
3302 });
3303 let committed_epoch = Epoch(match native_at(self, SYS_EPOCH)? {
3304 Some(Value::Int64(x)) => x as u64,
3305 _ => 0,
3306 });
3307 let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
3308 let commit_ts = if self.has_column(SYS_COMMIT_TS) {
3309 decode_commit_ts_value(native_at(self, SYS_COMMIT_TS)?.as_ref())
3310 } else {
3311 None
3312 };
3313 let col_ids: Vec<u16> = self.schema.columns.iter().map(|c| c.id).collect();
3314 let mut columns = HashMap::new();
3315 for id in col_ids {
3316 columns.insert(id, native_at(self, id)?.unwrap_or(Value::Null));
3317 }
3318 Ok(Row {
3319 row_id,
3320 committed_epoch,
3321 columns,
3322 deleted,
3323 commit_ts,
3324 })
3325 }
3326
3327 pub fn all_rows(&mut self) -> Result<Vec<Row>> {
3330 let n = self.row_count();
3331 let mut out = Vec::with_capacity(n);
3332 for i in 0..n {
3333 out.push(self.materialize(i)?);
3334 }
3335 Ok(out)
3336 }
3337
3338 pub fn for_each_system<F>(&mut self, mut visit: F) -> Result<()>
3345 where
3346 F: FnMut(RowId, Epoch, Option<HlcTimestamp>, bool) -> Result<()>,
3347 {
3348 let row_ids = self.column(SYS_ROW_ID)?.to_vec();
3352 let epochs = self.column(SYS_EPOCH)?.to_vec();
3353 let deleted = self.column(SYS_DELETED)?.to_vec();
3354 let has_commit_ts = self.has_column(SYS_COMMIT_TS);
3355 let commit_ts: Vec<Option<HlcTimestamp>> = if has_commit_ts {
3356 let col = self.column(SYS_COMMIT_TS)?;
3357 let mut out = Vec::with_capacity(col.len());
3358 for v in col {
3359 out.push(decode_commit_ts_value(Some(v)));
3360 }
3361 out
3362 } else {
3363 Vec::new()
3364 };
3365 debug_assert_eq!(row_ids.len(), epochs.len());
3366 debug_assert_eq!(row_ids.len(), deleted.len());
3367 for (i, rid_val) in row_ids.iter().enumerate() {
3368 let rid = match rid_val {
3369 Value::Int64(n) => RowId(*n as u64),
3370 _ => continue,
3371 };
3372 let epoch = match epochs[i] {
3373 Value::Int64(n) => Epoch(n as u64),
3374 _ => Epoch(0),
3375 };
3376 let ts = commit_ts.get(i).copied().flatten();
3377 let del = match deleted[i] {
3378 Value::Bool(b) => b,
3379 _ => false,
3380 };
3381 visit(rid, epoch, ts, del)?;
3382 }
3383 Ok(())
3384 }
3385
3386 pub fn all_rows_controlled(
3388 &mut self,
3389 control: &crate::ExecutionControl,
3390 max_rows: usize,
3391 ) -> Result<Vec<Row>> {
3392 let n = self.row_count();
3393 if n > max_rows {
3394 return Err(MongrelError::ResourceLimitExceeded {
3395 resource: "controlled run row materialization",
3396 requested: n,
3397 limit: max_rows,
3398 });
3399 }
3400 let mut out = Vec::with_capacity(n);
3401 for i in 0..n {
3402 if i % 256 == 0 {
3403 control.checkpoint()?;
3404 }
3405 out.push(self.materialize(i)?);
3406 }
3407 control.checkpoint()?;
3408 Ok(out)
3409 }
3410
3411 pub fn visible_indices(&mut self, snapshot: Epoch) -> Result<Vec<usize>> {
3417 self.visible_indices_at(Snapshot::at(snapshot))
3418 }
3419
3420 pub fn visible_indices_at(&mut self, snapshot: Snapshot) -> Result<Vec<usize>> {
3424 let n = self.row_count();
3425 if n == 0 {
3426 return Ok(Vec::new());
3427 }
3428 let row_ids = self.column(SYS_ROW_ID)?.to_vec();
3429 let epochs = self.column(SYS_EPOCH)?.to_vec();
3430 let deleted = self.column(SYS_DELETED)?.to_vec();
3431 let commit_ts_native = if self.has_column(SYS_COMMIT_TS) {
3432 Some(self.column(SYS_COMMIT_TS)?.to_vec())
3433 } else {
3434 None
3435 };
3436 let mut best: HashMap<u64, (u64, Option<HlcTimestamp>, usize)> = HashMap::new();
3437 for i in 0..n {
3438 let rid = int_at(&row_ids, i);
3439 let e = int_at(&epochs, i);
3440 let commit_ts = commit_ts_native
3441 .as_ref()
3442 .and_then(|vals| decode_commit_ts_value(vals.get(i)));
3443 if !snapshot.observes_row(Epoch(e), commit_ts) {
3444 continue;
3445 }
3446 best.entry(rid)
3447 .and_modify(|(be, bts, bi)| {
3448 if Snapshot::version_is_newer(Epoch(e), commit_ts, Epoch(*be), *bts) {
3449 *be = e;
3450 *bts = commit_ts;
3451 *bi = i;
3452 }
3453 })
3454 .or_insert((e, commit_ts, i));
3455 }
3456 let mut idxs: Vec<usize> = best.into_values().map(|(_, _, i)| i).collect();
3457 idxs.retain(|&i| !bool_at(&deleted, i));
3458 idxs.sort_unstable();
3459 Ok(idxs)
3460 }
3461
3462 pub fn gather_column(&mut self, column_id: u16, indices: &[usize]) -> Result<Vec<Value>> {
3467 if !self.dir.iter().any(|h| h.column_id == column_id) {
3468 return Ok(vec![Value::Null; indices.len()]);
3469 }
3470 let col = self.column(column_id)?;
3471 Ok(indices
3472 .iter()
3473 .map(|&i| col.get(i).cloned().unwrap_or(Value::Null))
3474 .collect())
3475 }
3476
3477 pub fn column_native(&mut self, column_id: u16) -> Result<columnar::NativeColumn> {
3482 use rayon::prelude::*;
3483 if column_id == SYS_EPOCH {
3484 if let Some(ov) = self.epoch_override {
3485 return Ok(columnar::NativeColumn::int64_constant(
3486 ov.0 as i64,
3487 self.row_count(),
3488 ));
3489 }
3490 }
3491 let ty = self.resolve_type(column_id);
3492 let n = self.row_count();
3493 let Some(ch) = self.dir.iter().find(|h| h.column_id == column_id) else {
3494 return Ok(columnar::null_native(ty, n));
3495 };
3496 let page_count = ch.page_count as usize;
3497 let page_rows: Vec<usize> = ch.page_stats.iter().map(|s| s.row_count as usize).collect();
3498 if page_count == 0 {
3499 return Ok(columnar::null_native(ty, n));
3500 }
3501 let parts: Vec<columnar::NativeColumn> = if self.mmap.is_some() && page_count > 1 {
3502 let reader: &RunReader = self;
3506 (0..page_count)
3507 .into_par_iter()
3508 .map(|seq| {
3509 let raw = reader.read_page_shared(column_id, seq)?;
3510 columnar::decode_page_native(ty.clone(), &raw, page_rows[seq])
3511 })
3512 .collect::<Result<Vec<_>>>()?
3513 } else {
3514 let mut out = Vec::with_capacity(page_count);
3515 for (seq, &pr) in page_rows.iter().enumerate() {
3516 let page = self.read_page(column_id, seq)?;
3517 out.push(columnar::decode_page_native(ty.clone(), &page, pr)?);
3518 }
3519 out
3520 };
3521 Ok(columnar::NativeColumn::concat(&parts))
3522 }
3523
3524 pub fn has_mmap(&self) -> bool {
3528 self.mmap.is_some()
3529 }
3530
3531 pub fn column_native_shared(&self, column_id: u16) -> Result<columnar::NativeColumn> {
3538 use rayon::prelude::*;
3539 if column_id == SYS_EPOCH {
3540 if let Some(ov) = self.epoch_override {
3541 return Ok(columnar::NativeColumn::int64_constant(
3542 ov.0 as i64,
3543 self.row_count(),
3544 ));
3545 }
3546 }
3547 let ty = self.resolve_type(column_id);
3548 let n = self.row_count();
3549 let Some(ch) = self.dir.iter().find(|h| h.column_id == column_id) else {
3550 return Ok(columnar::null_native(ty, n));
3551 };
3552 let page_count = ch.page_count as usize;
3553 let page_rows: Vec<usize> = ch.page_stats.iter().map(|s| s.row_count as usize).collect();
3554 if page_count == 0 {
3555 return Ok(columnar::null_native(ty, n));
3556 }
3557 #[cfg(unix)]
3561 {
3562 if let (Some(m), Some(first)) = (&self.mmap, ch.page_stats.first()) {
3563 let start = first.offset as usize;
3564 let end = (ch.page_region_offset as usize) + (ch.page_region_len as usize);
3565 if end > start {
3566 let _ = m.advise_range(memmap2::Advice::WillNeed, start, end - start);
3567 }
3568 }
3569 }
3570 let run_id = self.header.run_id;
3571 let mut parts_keys: Vec<(columnar::NativeColumn, Option<[u8; 32]>)> = if page_count > 1 {
3575 (0..page_count)
3576 .into_par_iter()
3577 .map(|seq| {
3578 self.decode_page_cached(ty.clone(), column_id, seq, page_rows[seq], run_id)
3579 })
3580 .collect::<Result<Vec<_>>>()?
3581 } else {
3582 vec![self.decode_page_cached(ty, column_id, 0, page_rows[0], run_id)?]
3583 };
3584 if let Some(cache) = &self.decoded_cache {
3587 for (col, key) in parts_keys.iter_mut() {
3588 if let Some(k) = key.take() {
3589 cache.lock(&k).insert(k, Arc::new(col.clone()));
3590 }
3591 }
3592 }
3593 let parts: Vec<columnar::NativeColumn> = parts_keys.into_iter().map(|(c, _)| c).collect();
3594 Ok(columnar::NativeColumn::concat(&parts))
3595 }
3596
3597 fn decode_page_cached(
3602 &self,
3603 ty: TypeId,
3604 column_id: u16,
3605 seq: usize,
3606 nrows: usize,
3607 run_id: u128,
3608 ) -> Result<(columnar::NativeColumn, Option<[u8; 32]>)> {
3609 let key = page_cache_key(self.table_id, run_id, column_id, seq);
3610 if let Some(cache) = &self.decoded_cache {
3611 if let Some(g) = cache.try_lock(&key) {
3612 if let Some(hit) = g.try_get(&key) {
3613 return Ok(((*hit).clone(), None));
3614 }
3615 }
3616 }
3617 let raw = self.read_page_shared(column_id, seq)?;
3618 let col = columnar::decode_page_native(ty, &raw, nrows)?;
3619 Ok((col, Some(key)))
3620 }
3621
3622 fn decode_page_native_cached(
3633 &mut self,
3634 ty: TypeId,
3635 column_id: u16,
3636 seq: usize,
3637 nrows: usize,
3638 ) -> Result<std::sync::Arc<columnar::NativeColumn>> {
3639 let key = page_cache_key(self.table_id, self.header.run_id, column_id, seq);
3640 if let Some(cache) = &self.decoded_cache {
3641 if let Some(hit) = cache.lock(&key).try_get(&key) {
3642 return Ok(hit);
3643 }
3644 }
3645 let raw = self.read_page(column_id, seq)?;
3646 let col = std::sync::Arc::new(columnar::decode_page_native(ty, &raw, nrows)?);
3647 if let Some(cache) = &self.decoded_cache {
3648 cache.lock(&key).insert(key, col.clone());
3649 }
3650 Ok(col)
3651 }
3652
3653 pub fn range_row_ids_i64(
3658 &mut self,
3659 column_id: u16,
3660 lo: i64,
3661 hi: i64,
3662 ) -> Result<std::collections::HashSet<u64>> {
3663 Ok(self
3664 .range_row_id_set_i64(column_id, lo, hi)?
3665 .into_sorted_vec()
3666 .into_iter()
3667 .collect())
3668 }
3669
3670 pub(crate) fn range_row_id_set_i64(
3671 &mut self,
3672 column_id: u16,
3673 lo: i64,
3674 hi: i64,
3675 ) -> Result<RowIdSet> {
3676 let info: Vec<(Option<i64>, Option<i64>, usize)> =
3677 match self.dir.iter().find(|h| h.column_id == column_id) {
3678 Some(ch) => ch
3679 .page_stats
3680 .iter()
3681 .map(|s| {
3682 (
3683 be_i64(s.min.as_deref()),
3684 be_i64(s.max.as_deref()),
3685 s.row_count as usize,
3686 )
3687 })
3688 .collect(),
3689 None => return Ok(RowIdSet::empty()),
3690 };
3691 let stats_pruneable =
3697 !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3698 let clean_contiguous = self.clean_contiguous_row_ids();
3699 let mut out = Vec::new();
3700 let mut page_start = 0usize;
3701 for (seq, (mn, mx, nrows)) in info.into_iter().enumerate() {
3702 let current_page_start = page_start;
3703 page_start += nrows;
3704 let skip = stats_pruneable
3706 && match (mn, mx) {
3707 (Some(mn), Some(mx)) => mx < lo || mn > hi,
3708 _ => true,
3709 };
3710 if skip {
3711 continue;
3712 }
3713 let val_page = self.read_page(column_id, seq)?;
3714 let vals =
3715 columnar::decode_page_native(self.resolve_type(column_id), &val_page, nrows)?;
3716 if let columnar::NativeColumn::Int64 { data: v, validity } = vals {
3717 if clean_contiguous {
3718 for (i, val) in v.iter().enumerate() {
3719 if columnar::validity_bit(&validity, i) && *val >= lo && *val <= hi {
3720 out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3721 }
3722 }
3723 } else {
3724 let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3725 let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3726 if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3727 for (i, val) in v.iter().enumerate() {
3728 if columnar::validity_bit(&validity, i) && *val >= lo && *val <= hi {
3729 out.push(r[i] as u64);
3730 }
3731 }
3732 }
3733 }
3734 }
3735 }
3736 Ok(RowIdSet::from_unsorted(out))
3737 }
3738
3739 pub fn range_row_ids_f64(
3742 &mut self,
3743 column_id: u16,
3744 lo: f64,
3745 lo_inclusive: bool,
3746 hi: f64,
3747 hi_inclusive: bool,
3748 ) -> Result<std::collections::HashSet<u64>> {
3749 Ok(self
3750 .range_row_id_set_f64(column_id, lo, lo_inclusive, hi, hi_inclusive)?
3751 .into_sorted_vec()
3752 .into_iter()
3753 .collect())
3754 }
3755
3756 pub(crate) fn range_row_id_set_f64(
3757 &mut self,
3758 column_id: u16,
3759 lo: f64,
3760 lo_inclusive: bool,
3761 hi: f64,
3762 hi_inclusive: bool,
3763 ) -> Result<RowIdSet> {
3764 let info: Vec<(Option<f64>, Option<f64>, usize)> =
3765 match self.dir.iter().find(|h| h.column_id == column_id) {
3766 Some(ch) => ch
3767 .page_stats
3768 .iter()
3769 .map(|s| {
3770 (
3771 be_f64(s.min.as_deref()),
3772 be_f64(s.max.as_deref()),
3773 s.row_count as usize,
3774 )
3775 })
3776 .collect(),
3777 None => return Ok(RowIdSet::empty()),
3778 };
3779 let stats_pruneable =
3785 !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3786 let clean_contiguous = self.clean_contiguous_row_ids();
3787 let mut out = Vec::new();
3788 let mut page_start = 0usize;
3789 for (seq, (mn, mx, nrows)) in info.into_iter().enumerate() {
3790 let current_page_start = page_start;
3791 page_start += nrows;
3792 let skip = stats_pruneable
3795 && match (mn, mx) {
3796 (Some(mn), Some(mx)) => {
3797 let skip_lo = mx < lo || (!lo_inclusive && mx == lo);
3798 let skip_hi = mn > hi || (!hi_inclusive && mn == hi);
3799 skip_lo || skip_hi
3800 }
3801 _ => true,
3802 };
3803 if skip {
3804 continue;
3805 }
3806 let val_page = self.read_page(column_id, seq)?;
3807 let vals = columnar::decode_page_native(TypeId::Float64, &val_page, nrows)?;
3808 if let columnar::NativeColumn::Float64 { data: v, validity } = vals {
3809 if clean_contiguous {
3810 for (i, val) in v.iter().enumerate() {
3811 if !columnar::validity_bit(&validity, i) || val.is_nan() {
3812 continue;
3813 }
3814 let ok_lo = if lo_inclusive { *val >= lo } else { *val > lo };
3815 let ok_hi = if hi_inclusive { *val <= hi } else { *val < hi };
3816 if ok_lo && ok_hi {
3817 out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3818 }
3819 }
3820 } else {
3821 let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3822 let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3823 if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3824 for (i, val) in v.iter().enumerate() {
3825 if !columnar::validity_bit(&validity, i) || val.is_nan() {
3826 continue;
3827 }
3828 let ok_lo = if lo_inclusive { *val >= lo } else { *val > lo };
3829 let ok_hi = if hi_inclusive { *val <= hi } else { *val < hi };
3830 if ok_lo && ok_hi {
3831 out.push(r[i] as u64);
3832 }
3833 }
3834 }
3835 }
3836 }
3837 }
3838 Ok(RowIdSet::from_unsorted(out))
3839 }
3840
3841 pub(crate) fn null_row_id_set(&mut self, column_id: u16, want_nulls: bool) -> Result<RowIdSet> {
3846 let stats: Vec<(usize, usize)> = match self.dir.iter().find(|h| h.column_id == column_id) {
3847 Some(ch) => ch
3848 .page_stats
3849 .iter()
3850 .map(|s| (s.null_count as usize, s.row_count as usize))
3851 .collect(),
3852 None => return Ok(RowIdSet::empty()),
3853 };
3854 let ty = self.resolve_type(column_id);
3855 let clean_contiguous = self.clean_contiguous_row_ids();
3856 let mut out = Vec::new();
3857 let mut page_start = 0usize;
3858 for (seq, (null_count, nrows)) in stats.into_iter().enumerate() {
3859 let current_page_start = page_start;
3860 page_start += nrows;
3861 if want_nulls && null_count == 0 {
3863 continue;
3864 }
3865 if !want_nulls && null_count == nrows {
3866 continue;
3867 }
3868 let val_page = self.read_page(column_id, seq)?;
3869 let col = columnar::decode_page_native(ty.clone(), &val_page, nrows)?;
3870 let validity = col.validity();
3871 if clean_contiguous {
3872 for i in 0..nrows {
3873 let is_null = !columnar::validity_bit(validity, i);
3874 if is_null == want_nulls {
3875 out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3876 }
3877 }
3878 } else {
3879 let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3880 let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3881 if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3882 for (i, &rid) in r.iter().enumerate().take(nrows) {
3883 let is_null = !columnar::validity_bit(validity, i);
3884 if is_null == want_nulls {
3885 out.push(rid as u64);
3886 }
3887 }
3888 }
3889 }
3890 }
3891 Ok(RowIdSet::from_unsorted(out))
3892 }
3893
3894 pub fn visible_indices_native(&mut self, snapshot: Epoch) -> Result<Vec<usize>> {
3895 self.visible_indices_native_at(Snapshot::at(snapshot))
3896 }
3897
3898 pub fn visible_indices_native_at(&mut self, snapshot: Snapshot) -> Result<Vec<usize>> {
3900 let n = self.row_count();
3901 if n == 0 {
3902 return Ok(Vec::new());
3903 }
3904 let (row_ids, epochs, deleted) = self.system_columns_native()?;
3905 let commit_ts_native = if self.has_column(SYS_COMMIT_TS) {
3906 Some(self.column_native_shared(SYS_COMMIT_TS)?)
3907 } else {
3908 None
3909 };
3910 let mut best: HashMap<u64, (u64, Option<HlcTimestamp>, usize)> = HashMap::new();
3911 for i in 0..n {
3912 let rid = row_ids[i] as u64;
3913 let e = epochs[i] as u64;
3914 let commit_ts = commit_ts_native
3915 .as_ref()
3916 .and_then(|col| decode_commit_ts_value(col.value_at(i).as_ref()));
3917 if !snapshot.observes_row(Epoch(e), commit_ts) {
3918 continue;
3919 }
3920 best.entry(rid)
3921 .and_modify(|(be, bts, bi)| {
3922 if Snapshot::version_is_newer(Epoch(e), commit_ts, Epoch(*be), *bts) {
3923 *be = e;
3924 *bts = commit_ts;
3925 *bi = i;
3926 }
3927 })
3928 .or_insert((e, commit_ts, i));
3929 }
3930 let mut idxs: Vec<usize> = best.into_values().map(|(_, _, i)| i).collect();
3931 idxs.retain(|&i| deleted[i] == 0);
3932 idxs.sort_unstable();
3933 Ok(idxs)
3934 }
3935
3936 pub fn range_row_ids_visible_i64(
3945 &mut self,
3946 column_id: u16,
3947 lo: i64,
3948 hi: i64,
3949 snapshot: Epoch,
3950 ) -> Result<Vec<u64>> {
3951 self.range_row_ids_visible_i64_at(column_id, lo, hi, Snapshot::at(snapshot))
3952 }
3953
3954 pub fn range_row_ids_visible_i64_at(
3956 &mut self,
3957 column_id: u16,
3958 lo: i64,
3959 hi: i64,
3960 snapshot: Snapshot,
3961 ) -> Result<Vec<u64>> {
3962 let stats: Vec<(Option<i64>, Option<i64>, usize)> = match self.column_page_stats(column_id)
3963 {
3964 Some(s) => s
3965 .iter()
3966 .map(|st| {
3967 (
3968 be_i64(st.min.as_deref()),
3969 be_i64(st.max.as_deref()),
3970 st.row_count as usize,
3971 )
3972 })
3973 .collect(),
3974 None => return Ok(Vec::new()),
3975 };
3976 let stats_pruneable =
3982 !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3983 let (positions, rids) = self.visible_positions_with_rids_at(snapshot)?;
3984 let mut out: Vec<u64> = Vec::new();
3985 let mut vis = 0usize;
3986 let mut page_start = 0usize;
3987 for (seq, &(mn, mx, nrows)) in stats.iter().enumerate() {
3988 let page_end = page_start + nrows;
3989 let skip = stats_pruneable
3991 && match (mn, mx) {
3992 (Some(mn), Some(mx)) => mx < lo || mn > hi,
3993 _ => true, };
3995 if !skip {
3996 let val_page = self.read_page(column_id, seq)?;
3997 let vals = columnar::decode_page_native(TypeId::Int64, &val_page, nrows)?;
3998 if let columnar::NativeColumn::Int64 { data: v, validity } = vals {
3999 while vis < positions.len() && positions[vis] < page_end {
4000 let local = positions[vis] - page_start;
4001 if columnar::validity_bit(&validity, local)
4002 && v[local] >= lo
4003 && v[local] <= hi
4004 {
4005 out.push(rids[vis] as u64);
4006 }
4007 vis += 1;
4008 }
4009 }
4010 } else {
4011 while vis < positions.len() && positions[vis] < page_end {
4012 vis += 1;
4013 }
4014 }
4015 page_start = page_end;
4016 }
4017 Ok(out)
4018 }
4019
4020 pub fn range_row_ids_visible_f64(
4023 &mut self,
4024 column_id: u16,
4025 lo: f64,
4026 lo_inclusive: bool,
4027 hi: f64,
4028 hi_inclusive: bool,
4029 snapshot: Epoch,
4030 ) -> Result<Vec<u64>> {
4031 self.range_row_ids_visible_f64_at(
4032 column_id,
4033 lo,
4034 lo_inclusive,
4035 hi,
4036 hi_inclusive,
4037 Snapshot::at(snapshot),
4038 )
4039 }
4040
4041 pub fn range_row_ids_visible_f64_at(
4043 &mut self,
4044 column_id: u16,
4045 lo: f64,
4046 lo_inclusive: bool,
4047 hi: f64,
4048 hi_inclusive: bool,
4049 snapshot: Snapshot,
4050 ) -> Result<Vec<u64>> {
4051 let stats: Vec<(Option<f64>, Option<f64>, usize)> = match self.column_page_stats(column_id)
4052 {
4053 Some(s) => s
4054 .iter()
4055 .map(|st| {
4056 (
4057 be_f64(st.min.as_deref()),
4058 be_f64(st.max.as_deref()),
4059 st.row_count as usize,
4060 )
4061 })
4062 .collect(),
4063 None => return Ok(Vec::new()),
4064 };
4065 let stats_pruneable =
4071 !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
4072 let (positions, rids) = self.visible_positions_with_rids_at(snapshot)?;
4073 let mut out: Vec<u64> = Vec::new();
4074 let mut vis = 0usize;
4075 let mut page_start = 0usize;
4076 for (seq, &(mn, mx, nrows)) in stats.iter().enumerate() {
4077 let page_end = page_start + nrows;
4078 let skip = stats_pruneable
4079 && match (mn, mx) {
4080 (Some(mn), Some(mx)) => {
4081 let skip_lo = mx < lo || (!lo_inclusive && mx == lo);
4082 let skip_hi = mn > hi || (!hi_inclusive && mn == hi);
4083 skip_lo || skip_hi
4084 }
4085 _ => true,
4086 };
4087 if !skip {
4088 let val_page = self.read_page(column_id, seq)?;
4089 let vals = columnar::decode_page_native(TypeId::Float64, &val_page, nrows)?;
4090 if let columnar::NativeColumn::Float64 { data: v, validity } = vals {
4091 while vis < positions.len() && positions[vis] < page_end {
4092 let local = positions[vis] - page_start;
4093 if columnar::validity_bit(&validity, local) && !v[local].is_nan() {
4094 let val = v[local];
4095 let ok_lo = if lo_inclusive { val >= lo } else { val > lo };
4096 let ok_hi = if hi_inclusive { val <= hi } else { val < hi };
4097 if ok_lo && ok_hi {
4098 out.push(rids[vis] as u64);
4099 }
4100 }
4101 vis += 1;
4102 }
4103 }
4104 } else {
4105 while vis < positions.len() && positions[vis] < page_end {
4106 vis += 1;
4107 }
4108 }
4109 page_start = page_end;
4110 }
4111 Ok(out)
4112 }
4113
4114 pub fn null_row_ids_visible(
4120 &mut self,
4121 column_id: u16,
4122 want_nulls: bool,
4123 snapshot: Epoch,
4124 ) -> Result<Vec<u64>> {
4125 self.null_row_ids_visible_at(column_id, want_nulls, Snapshot::at(snapshot))
4126 }
4127
4128 pub fn null_row_ids_visible_at(
4130 &mut self,
4131 column_id: u16,
4132 want_nulls: bool,
4133 snapshot: Snapshot,
4134 ) -> Result<Vec<u64>> {
4135 let stats: Vec<(usize, usize)> = match self.column_page_stats(column_id) {
4136 Some(s) => s
4137 .iter()
4138 .map(|st| (st.null_count as usize, st.row_count as usize))
4139 .collect(),
4140 None => return Ok(Vec::new()),
4141 };
4142 let ty = self.resolve_type(column_id);
4143 let (positions, rids) = self.visible_positions_with_rids_at(snapshot)?;
4144 let mut out: Vec<u64> = Vec::new();
4145 let mut vis = 0usize;
4146 let mut page_start = 0usize;
4147 for (seq, &(null_count, nrows)) in stats.iter().enumerate() {
4148 let page_end = page_start + nrows;
4149 let skip = (want_nulls && null_count == 0) || (!want_nulls && null_count == nrows);
4150 if !skip {
4151 let val_page = self.read_page(column_id, seq)?;
4152 let col = columnar::decode_page_native(ty.clone(), &val_page, nrows)?;
4153 let validity = col.validity();
4154 while vis < positions.len() && positions[vis] < page_end {
4155 let local = positions[vis] - page_start;
4156 let is_null = !columnar::validity_bit(validity, local);
4157 if is_null == want_nulls {
4158 out.push(rids[vis] as u64);
4159 }
4160 vis += 1;
4161 }
4162 } else {
4163 while vis < positions.len() && positions[vis] < page_end {
4164 vis += 1;
4165 }
4166 }
4167 page_start = page_end;
4168 }
4169 Ok(out)
4170 }
4171
4172 pub fn tombstoned_row_ids(&mut self, snapshot: Epoch) -> Result<Vec<u64>> {
4179 self.tombstoned_row_ids_at(Snapshot::at(snapshot))
4180 }
4181
4182 pub fn tombstoned_row_ids_at(&mut self, snapshot: Snapshot) -> Result<Vec<u64>> {
4184 let n = self.row_count();
4185 if n == 0 {
4186 return Ok(Vec::new());
4187 }
4188 if self.is_clean()
4190 && self.epoch_override.is_none()
4191 && self.header.epoch_created <= snapshot.epoch.0
4192 && (!snapshot.uses_hlc_authority() || !self.has_column(SYS_COMMIT_TS))
4193 {
4194 return Ok(Vec::new());
4195 }
4196 let (row_ids, epochs, deleted) = self.system_columns_native()?;
4197 let commit_ts_native = if self.has_column(SYS_COMMIT_TS) {
4198 Some(self.column_native_shared(SYS_COMMIT_TS)?)
4199 } else {
4200 None
4201 };
4202 let mut out = Vec::new();
4203 let mut i = 0;
4204 while i < n {
4205 let rid = row_ids[i] as u64;
4206 let mut best: Option<usize> = None;
4207 let mut j = i;
4208 while j < n && row_ids[j] as u64 == rid {
4209 let e = epochs[j] as u64;
4210 let commit_ts = commit_ts_native
4211 .as_ref()
4212 .and_then(|col| decode_commit_ts_value(col.value_at(j).as_ref()));
4213 if snapshot.observes_row(Epoch(e), commit_ts)
4214 && (best.is_none_or(|cur| {
4215 Snapshot::version_is_newer(
4216 Epoch(e),
4217 commit_ts,
4218 Epoch(epochs[cur] as u64),
4219 commit_ts_native
4220 .as_ref()
4221 .and_then(|col| decode_commit_ts_value(col.value_at(cur).as_ref())),
4222 )
4223 }))
4224 {
4225 best = Some(j);
4226 }
4227 j += 1;
4228 }
4229 if let Some(b) = best {
4230 if deleted[b] != 0 {
4231 out.push(rid);
4232 }
4233 }
4234 i = j;
4235 }
4236 Ok(out)
4237 }
4238
4239 pub fn visible_positions_with_rids(
4243 &mut self,
4244 snapshot: Epoch,
4245 ) -> Result<(Vec<usize>, Vec<i64>)> {
4246 self.visible_positions_with_rids_at(Snapshot::at(snapshot))
4247 }
4248
4249 pub fn visible_positions_with_rids_at(
4253 &mut self,
4254 snapshot: Snapshot,
4255 ) -> Result<(Vec<usize>, Vec<i64>)> {
4256 let n = self.row_count();
4257 if n == 0 {
4258 return Ok((Vec::new(), Vec::new()));
4259 }
4260 if self.is_clean()
4273 && self.epoch_override.is_none()
4274 && self.header.epoch_created <= snapshot.epoch.0
4275 {
4276 let row_ids = match self.column_native_shared(SYS_ROW_ID)? {
4277 columnar::NativeColumn::Int64 { data, .. } => data,
4278 _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
4279 };
4280 if !snapshot.uses_hlc_authority() || !self.has_column(SYS_COMMIT_TS) {
4282 let positions: Vec<usize> = (0..n).collect();
4283 return Ok((positions, row_ids));
4284 }
4285 let commit_ts_native = self.column_native_shared(SYS_COMMIT_TS)?;
4287 let mut idxs = Vec::with_capacity(n);
4288 let mut rids = Vec::with_capacity(n);
4289 for (i, &rid) in row_ids.iter().enumerate().take(n) {
4290 let ts = decode_commit_ts_value(commit_ts_native.value_at(i).as_ref());
4291 if snapshot.observes_row(Epoch(self.header.epoch_created), ts) {
4293 idxs.push(i);
4294 rids.push(rid);
4295 }
4296 }
4297 return Ok((idxs, rids));
4298 }
4299 let (row_ids, epochs, deleted) = self.system_columns_native()?;
4300 let commit_ts_native = if self.has_column(SYS_COMMIT_TS) {
4301 Some(self.column_native_shared(SYS_COMMIT_TS)?)
4302 } else {
4303 None
4304 };
4305 let mut idxs: Vec<usize> = Vec::new();
4312 let mut i = 0;
4313 while i < n {
4314 let rid = row_ids[i] as u64;
4315 let mut best: Option<usize> = None;
4316 let mut j = i;
4317 while j < n && row_ids[j] as u64 == rid {
4318 let e = epochs[j] as u64;
4319 let commit_ts = commit_ts_native
4320 .as_ref()
4321 .and_then(|col| decode_commit_ts_value(col.value_at(j).as_ref()));
4322 if snapshot.observes_row(Epoch(e), commit_ts) {
4323 let candidate = j;
4324 let is_newer = best.is_none_or(|cur| {
4325 Snapshot::version_is_newer(
4326 Epoch(e),
4327 commit_ts,
4328 Epoch(epochs[cur] as u64),
4329 commit_ts_native
4330 .as_ref()
4331 .and_then(|col| decode_commit_ts_value(col.value_at(cur).as_ref())),
4332 )
4333 });
4334 if best.is_none() || is_newer {
4335 best = Some(candidate);
4336 }
4337 }
4338 j += 1;
4339 }
4340 if let Some(b) = best {
4341 if deleted[b] == 0 {
4342 idxs.push(b);
4343 }
4344 }
4345 i = j;
4346 }
4347 let rids: Vec<i64> = idxs.iter().map(|&k| row_ids[k]).collect();
4348 Ok((idxs, rids))
4349 }
4350
4351 pub fn page_row_counts(&self, column_id: u16) -> Result<Vec<usize>> {
4355 Ok(self
4356 .find_header(column_id)?
4357 .page_stats
4358 .iter()
4359 .map(|s| s.row_count as usize)
4360 .collect())
4361 }
4362
4363 pub fn has_column(&self, column_id: u16) -> bool {
4366 self.dir.iter().any(|h| h.column_id == column_id)
4367 }
4368
4369 pub fn column_page_stats(&self, column_id: u16) -> Option<&[crate::page::PageStat]> {
4373 self.dir
4374 .iter()
4375 .find(|h| h.column_id == column_id)
4376 .map(|ch| ch.page_stats.as_slice())
4377 }
4378
4379 pub(crate) fn system_columns_native(&mut self) -> Result<(Vec<i64>, Vec<i64>, Vec<u8>)> {
4384 let row_ids = match self.column_native_shared(SYS_ROW_ID)? {
4385 columnar::NativeColumn::Int64 { data, .. } => data,
4386 _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
4387 };
4388 let epochs = match self.column_native_shared(SYS_EPOCH)? {
4389 columnar::NativeColumn::Int64 { data, .. } => data,
4390 _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
4391 };
4392 let deleted = match self.column_native_shared(SYS_DELETED)? {
4393 columnar::NativeColumn::Bool { data, .. } => data,
4394 _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
4395 };
4396 Ok((row_ids, epochs, deleted))
4397 }
4398
4399 pub fn visible_versions(&mut self, snapshot: Epoch) -> Result<Vec<Row>> {
4408 self.visible_versions_at(Snapshot::at(snapshot))
4409 }
4410
4411 pub fn visible_versions_at(&mut self, snapshot: Snapshot) -> Result<Vec<Row>> {
4415 let n = self.row_count();
4416 if n == 0 {
4417 return Ok(Vec::new());
4418 }
4419 let row_ids = self.column(SYS_ROW_ID)?.to_vec();
4420 let epochs = self.column(SYS_EPOCH)?.to_vec();
4421 let commit_ts_native = if self.has_column(SYS_COMMIT_TS) {
4422 Some(self.column(SYS_COMMIT_TS)?.to_vec())
4423 } else {
4424 None
4425 };
4426 let mut best: HashMap<u64, (u64, Option<HlcTimestamp>, usize)> = HashMap::new();
4427 for i in 0..n {
4428 let rid = int_at(&row_ids, i);
4429 let e = int_at(&epochs, i);
4430 let commit_ts = commit_ts_native
4431 .as_ref()
4432 .and_then(|vals| decode_commit_ts_value(vals.get(i)));
4433 if !snapshot.observes_row(Epoch(e), commit_ts) {
4434 continue;
4435 }
4436 best.entry(rid)
4440 .and_modify(|cur| {
4441 if crate::epoch::version_supersedes(Epoch(e), commit_ts, Epoch(cur.0), cur.1) {
4442 *cur = (e, commit_ts, i);
4443 }
4444 })
4445 .or_insert((e, commit_ts, i));
4446 }
4447 let mut picks: Vec<usize> = best.into_values().map(|(_, _, i)| i).collect();
4448 picks.sort();
4449 let mut out = Vec::with_capacity(picks.len());
4450 for i in picks {
4451 out.push(self.materialize(i)?);
4452 }
4453 Ok(out)
4454 }
4455
4456 pub fn visible_rows(&mut self, snapshot: Epoch) -> Result<Vec<Row>> {
4458 Ok(self
4459 .visible_versions_at(Snapshot::at(snapshot))?
4460 .into_iter()
4461 .filter(|r| !r.deleted)
4462 .collect())
4463 }
4464
4465 pub(crate) fn materialize(&mut self, index: usize) -> Result<Row> {
4466 let row_id = RowId(int_at(self.column(SYS_ROW_ID)?, index));
4467 let epoch = Epoch(int_at(self.column(SYS_EPOCH)?, index));
4468 let deleted = bool_at(self.column(SYS_DELETED)?, index);
4469 let commit_ts = self.commit_ts_at(index)?;
4470 let col_ids: Vec<u16> = self.schema.columns.iter().map(|c| c.id).collect();
4471 let mut columns = HashMap::new();
4472 for id in col_ids {
4473 let val = if self.dir.iter().any(|h| h.column_id == id) {
4474 self.column(id)?.get(index).cloned().unwrap_or(Value::Null)
4475 } else {
4476 Value::Null
4478 };
4479 columns.insert(id, val);
4480 }
4481 Ok(Row {
4482 row_id,
4483 committed_epoch: epoch,
4484 columns,
4485 deleted,
4486 commit_ts,
4487 })
4488 }
4489
4490 pub(crate) fn materialize_batch(&mut self, indices: &[usize]) -> Result<Vec<Row>> {
4499 if indices.is_empty() {
4500 return Ok(Vec::new());
4501 }
4502 use std::collections::HashMap;
4503 let rid_col = self.column_native_shared(SYS_ROW_ID)?;
4504 let epoch_col = self.column_native_shared(SYS_EPOCH)?;
4505 let del_col = self.column_native_shared(SYS_DELETED)?;
4506 let commit_ts_col = if self.has_column(SYS_COMMIT_TS) {
4507 Some(self.column_native_shared(SYS_COMMIT_TS)?)
4508 } else {
4509 None
4510 };
4511 let mut user: HashMap<u16, columnar::NativeColumn> = HashMap::new();
4512 let present: Vec<u16> = self
4513 .schema
4514 .columns
4515 .iter()
4516 .map(|c| c.id)
4517 .filter(|id| self.dir.iter().any(|h| h.column_id == *id))
4518 .collect();
4519 for id in present {
4520 user.insert(id, self.column_native(id)?);
4521 }
4522 let i64_at = |col: &columnar::NativeColumn, i: usize| -> i64 {
4523 match col {
4524 columnar::NativeColumn::Int64 { data, .. } => data.get(i).copied().unwrap_or(0),
4525 _ => 0,
4526 }
4527 };
4528 let bool_at_native = |col: &columnar::NativeColumn, i: usize| -> bool {
4529 match col {
4530 columnar::NativeColumn::Bool { data, .. } => {
4531 data.get(i).copied().map(|b| b != 0).unwrap_or(false)
4532 }
4533 _ => false,
4534 }
4535 };
4536 let mut rows = Vec::with_capacity(indices.len());
4537 for &idx in indices {
4538 let row_id = RowId(i64_at(&rid_col, idx) as u64);
4539 let epoch = Epoch(i64_at(&epoch_col, idx) as u64);
4540 let deleted = bool_at_native(&del_col, idx);
4541 let commit_ts = commit_ts_col
4542 .as_ref()
4543 .and_then(|col| decode_commit_ts_value(col.value_at(idx).as_ref()));
4544 let mut columns = HashMap::with_capacity(self.schema.columns.len());
4545 for cdef in self.schema.columns.iter() {
4546 let val = match user.get(&cdef.id) {
4547 Some(col) => col.value_at(idx).unwrap_or(Value::Null),
4548 None => Value::Null,
4549 };
4550 columns.insert(cdef.id, val);
4551 }
4552 rows.push(Row {
4553 row_id,
4554 committed_epoch: epoch,
4555 columns,
4556 deleted,
4557 commit_ts,
4558 });
4559 }
4560 Ok(rows)
4561 }
4562}
4563
4564fn int_at(vals: &[Value], i: usize) -> u64 {
4565 match vals.get(i) {
4566 Some(Value::Int64(x)) => *x as u64,
4567 _ => 0,
4568 }
4569}
4570
4571fn bool_at(vals: &[Value], i: usize) -> bool {
4572 matches!(vals.get(i), Some(Value::Bool(true)))
4573}
4574
4575#[cfg(test)]
4576mod tests {
4577 use super::*;
4578 use crate::columnar::NativeColumn;
4579 use crate::memtable::Value;
4580 use crate::rowid::RowId;
4581 use crate::schema::{ColumnDef, ColumnFlags};
4582 use tempfile::tempdir;
4583
4584 fn schema() -> Schema {
4585 Schema {
4586 schema_id: 1,
4587 columns: vec![
4588 ColumnDef {
4589 id: 1,
4590 name: "id".into(),
4591 ty: TypeId::Int64,
4592 flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
4593 default_value: None,
4594 embedding_source: None,
4595 },
4596 ColumnDef {
4597 id: 2,
4598 name: "name".into(),
4599 ty: TypeId::Bytes,
4600 flags: ColumnFlags::empty(),
4601 default_value: None,
4602 embedding_source: None,
4603 },
4604 ],
4605 indexes: Vec::new(),
4606 colocation: vec![],
4607 constraints: Default::default(),
4608 clustered: false,
4609 }
4610 }
4611
4612 fn rows() -> Vec<Row> {
4613 vec![
4614 Row::new(RowId(1), Epoch(10))
4615 .with_column(1, Value::Int64(1))
4616 .with_column(2, Value::Bytes(b"alice".to_vec())),
4617 Row::new(RowId(2), Epoch(10))
4618 .with_column(1, Value::Int64(2))
4619 .with_column(2, Value::Bytes(b"bob".to_vec())),
4620 Row::new(RowId(3), Epoch(10))
4621 .with_column(1, Value::Int64(3))
4622 .with_column(2, Value::Bytes(b"carol".to_vec())),
4623 ]
4624 }
4625
4626 #[test]
4627 fn flush_then_read_mvcc() {
4628 let dir = tempdir().unwrap();
4629 let path = dir.path().join("r-1.sr");
4630 let header = RunWriter::new(&schema(), 1, Epoch(10), 0)
4631 .write(&path, &rows())
4632 .unwrap();
4633 assert_eq!(header.row_count, 3);
4634
4635 let mut r = RunReader::open(&path, schema(), None).unwrap();
4636 let (e, row) = r.get_version(RowId(2), Epoch(20)).unwrap().unwrap();
4638 assert_eq!(e, Epoch(10));
4639 assert_eq!(row.row_id, RowId(2));
4640 assert!(matches!(row.columns.get(&2), Some(Value::Bytes(_))));
4641 assert!(r.get_version(RowId(99), Epoch(20)).unwrap().is_none());
4643 let all = r.visible_rows(Epoch(20)).unwrap();
4645 assert_eq!(all.len(), 3);
4646 assert!(!r.has_column(SYS_COMMIT_TS));
4648 assert!(all.iter().all(|row| row.commit_ts.is_none()));
4649 }
4650
4651 #[test]
4654 fn p05_t3_sys_commit_ts_preserved_on_flush_and_legacy_is_none() {
4655 let dir = tempdir().unwrap();
4656 let stamped_path = dir.path().join("r-hlc.sr");
4657 let stamp = HlcTimestamp {
4658 physical_micros: 42_000_000,
4659 logical: 7,
4660 node_tiebreaker: 3,
4661 };
4662 let stamped = vec![
4663 Row::new_with_hlc(RowId(1), Epoch(10), stamp)
4664 .with_column(1, Value::Int64(1))
4665 .with_column(2, Value::Bytes(b"alice".to_vec())),
4666 Row::new(RowId(2), Epoch(11)) .with_column(1, Value::Int64(2))
4668 .with_column(2, Value::Bytes(b"bob".to_vec())),
4669 ];
4670 RunWriter::new(&schema(), 9, Epoch(11), 0)
4671 .write(&stamped_path, &stamped)
4672 .unwrap();
4673 let mut reader = RunReader::open(&stamped_path, schema(), None).unwrap();
4674 assert!(
4675 reader.has_column(SYS_COMMIT_TS),
4676 "stamped flush must emit optional SYS_COMMIT_TS"
4677 );
4678 let (_, row1) = reader
4679 .get_version(RowId(1), Epoch(20))
4680 .unwrap()
4681 .expect("row 1");
4682 assert_eq!(row1.commit_ts, Some(stamp));
4683 let (_, row2) = reader
4684 .get_version(RowId(2), Epoch(20))
4685 .unwrap()
4686 .expect("row 2");
4687 assert_eq!(row2.commit_ts, None, "Null stamp cell stays None");
4688 let versions = reader.visible_versions(Epoch(20)).unwrap();
4689 assert_eq!(versions.len(), 2);
4690 assert_eq!(
4691 versions
4692 .iter()
4693 .find(|r| r.row_id == RowId(1))
4694 .and_then(|r| r.commit_ts),
4695 Some(stamp)
4696 );
4697
4698 let legacy_path = dir.path().join("r-legacy.sr");
4700 RunWriter::new(&schema(), 10, Epoch(10), 0)
4701 .write(&legacy_path, &rows())
4702 .unwrap();
4703 let mut legacy = RunReader::open(&legacy_path, schema(), None).unwrap();
4704 assert!(!legacy.has_column(SYS_COMMIT_TS));
4705 let all = legacy.visible_versions(Epoch(20)).unwrap();
4706 assert!(all.iter().all(|r| r.commit_ts.is_none()));
4707 }
4708
4709 #[test]
4710 fn visible_version_cursor_preserves_order_snapshot_and_tombstones() {
4711 let dir = tempdir().unwrap();
4712 let path = dir.path().join("r-cursor.sr");
4713 let mut tombstone = Row::new(RowId(2), Epoch(2));
4714 tombstone.deleted = true;
4715 let versions = vec![
4716 Row::new(RowId(1), Epoch(4)).with_column(1, Value::Int64(10)),
4717 Row::new(RowId(2), Epoch(1)).with_column(1, Value::Int64(2)),
4718 tombstone,
4719 Row::new(RowId(3), Epoch(1)).with_column(1, Value::Int64(20)),
4720 Row::new(RowId(3), Epoch(3)).with_column(1, Value::Int64(23)),
4721 Row::new(RowId(4), Epoch(4)).with_column(1, Value::Int64(30)),
4722 ];
4723 RunWriter::new(&schema(), 7, Epoch(4), 0)
4724 .write(&path, &versions)
4725 .unwrap();
4726
4727 let control = crate::ExecutionControl::new(None);
4728 let mut cursor = RunReader::open(&path, schema(), None)
4729 .unwrap()
4730 .into_visible_version_cursor(Epoch(2))
4731 .unwrap();
4732 let first = cursor.next_visible_version(&control).unwrap().unwrap();
4733 assert_eq!(first.row_id, RowId(2));
4734 assert!(first.deleted);
4735 assert_eq!(first.committed_epoch, Epoch(2));
4736 let second = cursor.next_visible_version(&control).unwrap().unwrap();
4737 assert_eq!(second.row_id, RowId(3));
4738 assert_eq!(second.committed_epoch, Epoch(1));
4739 let row = cursor.materialize(second, &control).unwrap();
4740 assert_eq!(row.columns.get(&1), Some(&Value::Int64(20)));
4741 assert!(cursor.next_visible_version(&control).unwrap().is_none());
4742 }
4743
4744 #[test]
4745 fn learned_index_was_stored() {
4746 let dir = tempdir().unwrap();
4747 let path = dir.path().join("r-2.sr");
4748 RunWriter::new(&schema(), 2, Epoch(1), 0)
4749 .write(&path, &rows())
4750 .unwrap();
4751 let header = read_header(&path).unwrap();
4752 assert!(
4753 header.index_trailer_offset != 0,
4754 "trailer should be present"
4755 );
4756 }
4757
4758 #[test]
4759 fn low_level_container_still_round_trips() {
4760 let dir = tempdir().unwrap();
4761 let path = dir.path().join("r-3.sr");
4762 let cols = vec![ColumnPayload {
4763 column_id: 1,
4764 type_id_tag: 8,
4765 encoding: Encoding::Plain,
4766 pages: vec![vec![1, 2, 3, 4]],
4767 page_stats: Vec::new(),
4768 }];
4769 let header = write_run(
4770 &path,
4771 &RunSpec {
4772 run_id: 1,
4773 schema_id: 1,
4774 epoch_created: 1,
4775 level: 0,
4776 flags: 0,
4777 sort_key_column_id: SORT_KEY_ROW_ID,
4778 row_count: 1,
4779 min_row_id: 0,
4780 max_row_id: 0,
4781 columns: &cols,
4782 },
4783 )
4784 .unwrap();
4785 let back = read_header(&path).unwrap();
4786 assert_eq!(back.content_hash, header.content_hash);
4787 assert_eq!(read_column_dir(&path, &back).unwrap().len(), 1);
4788 }
4789
4790 #[test]
4791 fn detects_corruption() {
4792 let dir = tempdir().unwrap();
4793 let path = dir.path().join("r-4.sr");
4794 write_run(
4795 &path,
4796 &RunSpec {
4797 run_id: 1,
4798 schema_id: 1,
4799 epoch_created: 1,
4800 level: 0,
4801 flags: 0,
4802 sort_key_column_id: SORT_KEY_ROW_ID,
4803 row_count: 1,
4804 min_row_id: 0,
4805 max_row_id: 0,
4806 columns: &[ColumnPayload {
4807 column_id: 1,
4808 type_id_tag: 8,
4809 encoding: Encoding::Plain,
4810 pages: vec![vec![1, 2, 3]],
4811 page_stats: Vec::new(),
4812 }],
4813 },
4814 )
4815 .unwrap();
4816 let mut bytes = std::fs::read(&path).unwrap();
4817 bytes[300] ^= 0xFF;
4818 std::fs::write(&path, bytes).unwrap();
4819 let err = read_header(&path).unwrap_err();
4820 assert!(
4821 matches!(err, MongrelError::ChecksumMismatch { .. }),
4822 "got {err:?}"
4823 );
4824 }
4825
4826 #[test]
4832 fn mmap_and_vec_writers_are_byte_identical() {
4833 let dir = tempdir().unwrap();
4834 let stats = vec![PageStat {
4835 first_row_id: 0,
4836 last_row_id: 1,
4837 null_count: 0,
4838 row_count: 2,
4839 min: Some(vec![0]),
4840 max: Some(vec![9]),
4841 offset: 0,
4842 compressed_len: 0,
4843 uncompressed_len: 0,
4844 }];
4845 let spec = RunSpec {
4846 run_id: 7,
4847 schema_id: 1,
4848 epoch_created: 10,
4849 level: 0,
4850 flags: 0,
4851 sort_key_column_id: SORT_KEY_ROW_ID,
4852 row_count: 2,
4853 min_row_id: 0,
4854 max_row_id: 1,
4855 columns: &[
4856 ColumnPayload {
4857 column_id: 1,
4858 type_id_tag: 8,
4859 encoding: Encoding::Plain,
4860 pages: vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]],
4861 page_stats: stats.clone(),
4862 },
4863 ColumnPayload {
4864 column_id: 2,
4865 type_id_tag: 8,
4866 encoding: Encoding::Plain,
4867 pages: vec![vec![10, 20], vec![30, 40]],
4868 page_stats: stats.clone(),
4869 },
4870 ],
4871 };
4872 let trailer = b"learned-trailer-bytes";
4873
4874 let plan = plan_run(&spec, None, Some(trailer)).expect("plan");
4876 let mut buf = vec![0u8; plan.total];
4877 let h_place = place_run(&spec, None, Some(trailer), &plan, &mut buf)
4878 .expect("place_run into Vec succeeds");
4879
4880 let path_vec = dir.path().join("vec.sr");
4882 let h_vec = write_run_vec(&path_vec, &spec, None, Some(trailer)).unwrap();
4883 let bv = std::fs::read(&path_vec).unwrap();
4884
4885 assert_eq!(h_place.content_hash, h_vec.content_hash);
4886 assert_eq!(h_place.footer_offset, h_vec.footer_offset);
4887 assert_eq!(
4888 buf, bv,
4889 "place_run and write_run_vec must be byte-identical"
4890 );
4891 assert!(read_header(&path_vec).is_ok());
4892
4893 let path_mmap = dir.path().join("mmap.sr");
4897 match write_run_mmap(&path_mmap, &spec, None, Some(trailer)) {
4898 Ok(h_mmap) => {
4899 let bm = std::fs::read(&path_mmap).unwrap();
4900 assert_eq!(bm, bv, "mmap run must be byte-identical to vec run");
4901 assert_eq!(h_mmap.content_hash, h_vec.content_hash);
4902 }
4903 Err(e) if is_mmap_unavailable(&e) => {
4904 eprintln!("note: file mmap unavailable here; vec path covered (1)/(2)");
4905 }
4906 Err(e) => panic!("unexpected mmap error: {e:?}"),
4907 }
4908 }
4909
4910 #[test]
4915 fn column_native_shared_matches_column_native() {
4916 let dir = tempdir().unwrap();
4917 let path = dir.path().join("r.sr");
4918 let n = 65_536 * 2 + 9;
4921 let id_col = NativeColumn::int64_sequence(1, n);
4922 let mut offsets = vec![0u32];
4923 let mut values = Vec::new();
4924 for i in 0..n {
4925 values.extend_from_slice(format!("v{}", i % 17).as_bytes());
4926 offsets.push(values.len() as u32);
4927 }
4928 let name_col = NativeColumn::Bytes {
4929 offsets,
4930 values,
4931 validity: vec![0xFF; n.div_ceil(8)],
4932 };
4933 let header = RunWriter::new(&schema(), 9, Epoch(5), 0)
4934 .write_native(&path, &[(1, id_col), (2, name_col)], n, 1)
4935 .unwrap();
4936
4937 let mut reader = RunReader::open_with_cache(&path, schema(), None, None, None, 0, None)
4938 .expect("open reader");
4939 assert!(reader.has_mmap(), "test env must support read-only mmap");
4940 assert_eq!(reader.row_count(), header.row_count as usize);
4941
4942 for cid in [1u16, 2] {
4943 let a = reader.column_native(cid).expect("column_native");
4944 let b = reader
4945 .column_native_shared(cid)
4946 .expect("column_native_shared");
4947 assert_eq!(a.len(), b.len(), "len mismatch col {cid}");
4948 match (&a, &b) {
4950 (
4951 NativeColumn::Int64 {
4952 data: da,
4953 validity: va,
4954 },
4955 NativeColumn::Int64 {
4956 data: db,
4957 validity: vb,
4958 },
4959 ) => {
4960 assert_eq!(da, db, "Int64 data col {cid}");
4961 assert_eq!(va, vb, "Int64 validity col {cid}");
4962 }
4963 (
4964 NativeColumn::Bytes {
4965 offsets: oa,
4966 values: ua,
4967 validity: va,
4968 },
4969 NativeColumn::Bytes {
4970 offsets: ob,
4971 values: ub,
4972 validity: vb,
4973 },
4974 ) => {
4975 assert_eq!(oa, ob, "Bytes offsets col {cid}");
4976 assert_eq!(ua, ub, "Bytes values col {cid}");
4977 assert_eq!(va, vb, "Bytes validity col {cid}");
4978 }
4979 _ => panic!("type mismatch col {cid}: {a:?} vs {b:?}"),
4980 }
4981 }
4982 }
4983
4984 #[test]
4985 fn page_cache_key_distinguishes_tables() {
4986 let a = page_cache_key(1, 5, 2, 3);
4987 let b = page_cache_key(2, 5, 2, 3);
4988 assert_ne!(a, b, "same run/col/page, different table must differ");
4989 assert_ne!(page_cache_key(1, 5, 2, 3), page_cache_key(1, 6, 2, 3));
4991 assert_ne!(page_cache_key(1, 5, 2, 3), page_cache_key(1, 5, 2, 4));
4992 }
4993}