1#![forbid(unsafe_code)]
29
30use std::cmp::Ordering;
31use std::collections::{HashMap, VecDeque};
32use std::fs::{File, OpenOptions};
33use std::io::{Read, Seek, SeekFrom};
34use std::mem::{size_of, size_of_val};
35use std::path::Path;
36use std::sync::atomic::{AtomicUsize, Ordering as Atomic};
37use std::sync::{Arc, Mutex, OnceLock};
38
39use rudb_common::bounds::{Bound, Op};
40use rudb_common::{Error, Field, LogicalType, Result, Value};
41use rudb_encoding::{chooser, integer, string};
42use rudb_storage::sieve::Sieve;
43use rudb_storage::{Probe, Range, Zone};
44use rudb_vector::string::StringColumn;
45use rudb_vector::validity::Validity;
46use rudb_vector::{Buffer, Chunk, Data, Packed, TextSource, Vector};
47
48const MAGIC: &[u8; 8] = b"RUDBNV10";
49const DIRECTORY: &[u8; 8] = b"RUDBDI10";
50const FORMAT: u32 = 14;
51const HEADER: u64 = 80;
52const SLOT_BYTES: usize = 28;
53const MAX_PAGE: usize = 256 * 1024 * 1024;
54const MAX_DIRECTORY: usize = 128 * 1024 * 1024;
55const FREQUENCIES: &[u8; 8] = b"RUDBFQ2\0";
56const FREQUENCY_CANDIDATES: usize = 32_768;
57const FREQUENCY_ENTRIES: usize = 512;
58const FREQUENCY_BUILD_RANK: usize = 10;
59const FREQUENCY_ORDINALS: usize = 65_536;
60const MAX_FREQUENCY_WORKERS: usize = 16;
61
62const MAX_ENCODE_WORKERS: usize = 32;
69
70const SIEVE_BUDGET: usize = 8 * 1024;
76
77fn io(error: std::io::Error) -> Error {
78 Error::io(error.to_string())
79}
80
81fn invalid(message: &str) -> Error {
82 Error::invalid_input(format!("invalid rudb native file: {message}"))
83}
84
85fn sum(counts: impl Iterator<Item = u64>) -> u64 {
87 counts.fold(0, u64::saturating_add)
88}
89
90fn span_bytes(spans: &[Span], at: usize) -> u64 {
92 spans.get(at).map_or(0, |span| u64::from(span.length))
93}
94
95fn page_bytes(pages: &[Option<Page>], at: usize) -> u64 {
97 pages.get(at).and_then(Option::as_ref).map_or(0, Page::bytes)
98}
99
100fn checksum(bytes: &[u8]) -> u64 {
101 const P1: u64 = 11_400_714_785_074_694_791;
102 const P2: u64 = 14_029_467_366_897_019_727;
103 const P3: u64 = 1_609_587_929_392_839_161;
104 const P4: u64 = 9_650_029_242_287_828_579;
105 const P5: u64 = 2_870_177_450_012_600_261;
106 let round = |state: u64, word: u64| {
107 state.wrapping_add(word.wrapping_mul(P2)).rotate_left(31).wrapping_mul(P1)
108 };
109 let merge = |state: u64, lane: u64| (state ^ round(0, lane)).wrapping_mul(P1).wrapping_add(P4);
110 let word =
111 |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("eight checksum bytes"));
112
113 let mut at = 0;
114 let mut hash = if bytes.len() >= 32 {
115 let mut one = P1.wrapping_add(P2);
116 let mut two = P2;
117 let mut three = 0;
118 let mut four = 0_u64.wrapping_sub(P1);
119 while at + 32 <= bytes.len() {
120 one = round(one, word(at));
121 two = round(two, word(at + 8));
122 three = round(three, word(at + 16));
123 four = round(four, word(at + 24));
124 at += 32;
125 }
126 let combined = one
127 .rotate_left(1)
128 .wrapping_add(two.rotate_left(7))
129 .wrapping_add(three.rotate_left(12))
130 .wrapping_add(four.rotate_left(18));
131 merge(merge(merge(merge(combined, one), two), three), four)
132 } else {
133 P5
134 };
135 hash = hash.wrapping_add(bytes.len() as u64);
136 while at + 8 <= bytes.len() {
137 hash ^= round(0, word(at));
138 hash = hash.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
139 at += 8;
140 }
141 if at + 4 <= bytes.len() {
142 let tail = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four checksum bytes"));
143 hash ^= u64::from(tail).wrapping_mul(P1);
144 hash = hash.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
145 at += 4;
146 }
147 while at < bytes.len() {
148 hash ^= u64::from(bytes[at]).wrapping_mul(P5);
149 hash = hash.rotate_left(11).wrapping_mul(P1);
150 at += 1;
151 }
152 hash ^= hash >> 33;
153 hash = hash.wrapping_mul(P2);
154 hash ^= hash >> 29;
155 hash = hash.wrapping_mul(P3);
156 hash ^ (hash >> 32)
157}
158
159#[derive(Debug, Clone, Copy)]
160struct Slot {
161 offset: u64,
162 length: u32,
163 generation: u64,
164 hash: u64,
165}
166
167impl Slot {
168 fn bytes(self) -> [u8; SLOT_BYTES] {
169 let mut result = [0; SLOT_BYTES];
170 result[..8].copy_from_slice(&self.offset.to_le_bytes());
171 result[8..12].copy_from_slice(&self.length.to_le_bytes());
172 result[12..20].copy_from_slice(&self.generation.to_le_bytes());
173 result[20..28].copy_from_slice(&self.hash.to_le_bytes());
174 result
175 }
176
177 fn read(bytes: &[u8]) -> Self {
178 Self {
179 offset: u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")),
180 length: u32::from_le_bytes(bytes[8..12].try_into().expect("four bytes")),
181 generation: u64::from_le_bytes(bytes[12..20].try_into().expect("eight bytes")),
182 hash: u64::from_le_bytes(bytes[20..28].try_into().expect("eight bytes")),
183 }
184 }
185}
186
187#[derive(Debug, Clone, Copy)]
188struct Page {
189 offset: u64,
190 length: u32,
191 hash: u64,
192}
193
194impl Page {
195 fn bytes(&self) -> u64 {
197 u64::from(self.length)
198 }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
202enum FrequencyValue {
203 Null,
204 Integer(i128),
205 Code(u32),
206}
207
208#[derive(Debug, Clone)]
209struct FrequencyEntry {
210 value: FrequencyValue,
211 count: u64,
212}
213
214#[derive(Debug, Clone)]
219struct FrequencySummary {
220 entries: Vec<FrequencyEntry>,
221 omitted_max: u64,
222 ordinals: Vec<u64>,
223}
224
225#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct FrequencyOccurrences {
228 pub omitted_max: u64,
230 pub ordinals: Vec<u64>,
232}
233
234#[derive(Debug, Clone, Copy, Default)]
241struct Span {
242 offset: u64,
243 length: u32,
244}
245
246#[derive(Debug, Clone)]
248pub struct Stripe {
249 rows: usize,
250 parts: Vec<u32>,
253 index: Span,
257 pages: Vec<Span>,
258 memberships: Vec<Option<Page>>,
259 sieves: Vec<Option<Page>>,
262 zone: Zone,
263}
264
265impl Stripe {
266 #[must_use]
268 pub fn rows(&self) -> usize {
269 self.rows
270 }
271
272 #[must_use]
274 pub fn parts(&self) -> usize {
275 self.parts.len()
276 }
277}
278
279#[derive(Debug, Clone)]
281pub struct Table {
282 name: String,
283 fields: Vec<Field>,
284 stripes: Vec<Stripe>,
285 rows: usize,
286 dictionaries: Vec<Option<Page>>,
287 frequencies: Vec<Option<FrequencySummary>>,
288}
289
290impl Table {
291 #[must_use]
293 pub fn name(&self) -> &str {
294 &self.name
295 }
296
297 #[must_use]
299 pub fn fields(&self) -> &[Field] {
300 &self.fields
301 }
302
303 #[must_use]
305 pub fn rows(&self) -> usize {
306 self.rows
307 }
308
309 #[must_use]
311 pub fn stripes(&self) -> &[Stripe] {
312 &self.stripes
313 }
314}
315
316#[derive(Debug, Clone)]
318pub struct ColumnLayout {
319 pub name: String,
321 pub kind: String,
323 pub pages: u64,
325 pub memberships: u64,
327 pub sieves: u64,
329 pub dictionary: u64,
331}
332
333impl ColumnLayout {
334 #[must_use]
336 pub fn total(&self) -> u64 {
337 self.pages
338 .saturating_add(self.memberships)
339 .saturating_add(self.sieves)
340 .saturating_add(self.dictionary)
341 }
342}
343
344#[derive(Debug, Clone)]
355pub struct Layout {
356 pub file: u64,
358 pub rows: usize,
360 pub stripes: usize,
362 pub parts: usize,
364 pub columns: Vec<ColumnLayout>,
366 pub indexes: u64,
369 pub directory: u64,
371 pub header: u64,
373}
374
375impl Layout {
376 #[must_use]
378 pub fn columns_total(&self) -> u64 {
379 self.columns.iter().map(ColumnLayout::total).fold(0, u64::saturating_add)
380 }
381
382 #[must_use]
388 pub fn unaccounted(&self) -> u64 {
389 self.file
390 .saturating_sub(self.columns_total())
391 .saturating_sub(self.indexes)
392 .saturating_sub(self.directory)
393 .saturating_sub(self.header)
394 }
395}
396
397#[derive(Debug)]
399struct GlobalDictionary {
400 primary: HashMap<u64, u32>,
401 collisions: HashMap<u64, Vec<u32>>,
402 offsets: Vec<u32>,
403 payload: Vec<u8>,
404 counts: Vec<u64>,
405 nulls: u64,
406}
407
408impl GlobalDictionary {
409 fn new() -> Self {
410 Self {
411 primary: HashMap::new(),
412 collisions: HashMap::new(),
413 offsets: vec![0],
414 payload: Vec::new(),
415 counts: Vec::new(),
416 nulls: 0,
417 }
418 }
419
420 fn bytes(&self, code: u32) -> Option<&[u8]> {
421 let start = *self.offsets.get(code as usize)? as usize;
422 let end = *self.offsets.get(code as usize + 1)? as usize;
423 self.payload.get(start..end)
424 }
425
426 fn code(&mut self, text: &str) -> Result<u32> {
427 let hash = checksum(text.as_bytes());
428 if let Some(&code) = self.primary.get(&hash) {
429 if self.bytes(code) == Some(text.as_bytes()) {
430 return Ok(code);
431 }
432 if let Some(codes) = self.collisions.get(&hash) {
433 if let Some(code) =
434 codes.iter().copied().find(|&code| self.bytes(code) == Some(text.as_bytes()))
435 {
436 return Ok(code);
437 }
438 }
439 let code = self.insert(text)?;
440 self.collisions.entry(hash).or_default().push(code);
441 return Ok(code);
442 }
443 let code = self.insert(text)?;
444 self.primary.insert(hash, code);
445 Ok(code)
446 }
447
448 fn insert(&mut self, text: &str) -> Result<u32> {
449 let code = u32::try_from(self.offsets.len() - 1)
450 .map_err(|_| invalid("global dictionary has too many values"))?;
451 self.payload.extend_from_slice(text.as_bytes());
452 self.offsets.push(
453 u32::try_from(self.payload.len())
454 .map_err(|_| invalid("global dictionary payload exceeds 4 GiB"))?,
455 );
456 self.counts.push(0);
457 Ok(code)
458 }
459
460 fn ranked(&self) -> Vec<(u64, u32)> {
480 let count = self.offsets.len() - 1;
481 let mut ranked = (0..count)
482 .map(|code| {
483 let code = code as u32;
484 (head(self.bytes(code).unwrap_or_default()), code)
485 })
486 .collect::<Vec<_>>();
487 ranked.sort_unstable_by(|left, right| {
488 left.0.cmp(&right.0).then_with(|| self.bytes(left.1).cmp(&self.bytes(right.1)))
489 });
490 ranked
491 }
492
493 fn observe(&mut self, code: u32, null: bool) -> Result<()> {
494 if null {
495 self.nulls = self.nulls.saturating_add(1);
496 return Ok(());
497 }
498 let count = self
499 .counts
500 .get_mut(code as usize)
501 .ok_or_else(|| invalid("global dictionary count code is out of range"))?;
502 *count = count.saturating_add(1);
503 Ok(())
504 }
505}
506
507#[derive(Debug)]
509pub struct Writer {
510 file: File,
511 at: u64,
519 table: Table,
520 generation: u64,
521 order: Vec<((u64, u64), (u64, u64))>,
524 next_order: u64,
525 dictionaries: Vec<Option<GlobalDictionary>>,
526 pending: Vec<PendingChunk>,
527}
528
529#[derive(Debug)]
537struct PendingChunk {
538 order: (u64, u64),
539 chunk: Chunk,
540}
541
542#[derive(Debug)]
548struct ColumnStripe {
549 pages: Vec<Vec<u8>>,
550 codes: Vec<Option<Vec<u32>>>,
551 sieves: Vec<Option<Sieve>>,
552 ranges: Vec<Range>,
553}
554
555fn weight(ty: &LogicalType) -> usize {
563 match ty {
564 LogicalType::Varchar | LogicalType::Blob => 64,
565 LogicalType::BigInt
566 | LogicalType::UBigInt
567 | LogicalType::Timestamp
568 | LogicalType::Double
569 | LogicalType::Decimal { .. } => 8,
570 LogicalType::Integer | LogicalType::UInteger | LogicalType::Date | LogicalType::Float => 4,
571 LogicalType::SmallInt | LogicalType::USmallInt => 2,
572 _ => 1,
573 }
574}
575
576const STRIPE_PARTS: usize = 64;
583
584const INDEX_ENTRY: usize = size_of::<u32>() + size_of::<u64>();
586
587fn index_section(parts: usize) -> Result<usize> {
589 parts
590 .checked_mul(INDEX_ENTRY)
591 .and_then(|bytes| bytes.checked_add(size_of::<u64>()))
592 .ok_or_else(|| invalid("index page length overflow"))
593}
594
595impl Writer {
596 pub fn create(
602 path: impl AsRef<Path>,
603 name: impl Into<String>,
604 fields: Vec<Field>,
605 ) -> Result<Self> {
606 for field in &fields {
607 type_tag(&field.ty)?;
608 }
609 let file =
610 OpenOptions::new().write(true).read(true).create_new(true).open(path).map_err(io)?;
611 let mut header = [0; HEADER as usize];
612 header[..8].copy_from_slice(MAGIC);
613 header[8..12].copy_from_slice(&FORMAT.to_le_bytes());
614 write_at(&file, 0, &header)?;
615 Ok(Self {
616 file,
617 at: HEADER,
618 dictionaries: fields
619 .iter()
620 .map(|field| (field.ty == LogicalType::Varchar).then(GlobalDictionary::new))
621 .collect(),
622 table: Table {
623 name: name.into(),
624 dictionaries: vec![None; fields.len()],
625 fields,
626 stripes: Vec::new(),
627 rows: 0,
628 frequencies: Vec::new(),
629 },
630 generation: 1,
631 order: Vec::new(),
632 next_order: 0,
633 pending: Vec::with_capacity(STRIPE_PARTS),
634 })
635 }
636
637 fn put(&mut self, bytes: &[u8]) -> Result<()> {
642 write_at(&self.file, self.at, bytes)?;
643 self.at = self
644 .at
645 .checked_add(bytes.len() as u64)
646 .ok_or_else(|| invalid("native file length overflow"))?;
647 Ok(())
648 }
649
650 pub fn append(&mut self, chunk: &Chunk) -> Result<()> {
656 let order = (self.next_order, 0);
657 self.next_order = self.next_order.saturating_add(1);
658 self.append_at(order, chunk)
659 }
660
661 pub fn append_at(&mut self, order: (u64, u64), chunk: &Chunk) -> Result<()> {
672 if chunk.is_empty() {
673 return Ok(());
674 }
675 if chunk.width() != self.table.fields.len() {
676 return Err(invalid("chunk width differs from table schema"));
677 }
678 for (index, field) in self.table.fields.iter().enumerate() {
679 if chunk.column(index)?.logical_type() != &field.ty {
680 return Err(invalid("chunk type differs from table schema"));
681 }
682 }
683 self.table.rows = self
684 .table
685 .rows
686 .checked_add(chunk.len())
687 .ok_or_else(|| invalid("row count overflow"))?;
688 if self.pending.last().is_some_and(|last| last.order > order) {
689 self.flush_pending()?;
690 }
691 self.pending.push(PendingChunk { order, chunk: chunk.clone() });
696 if self.pending.len() == STRIPE_PARTS {
697 self.flush_pending()?;
698 }
699 Ok(())
700 }
701
702 fn encode_column(
710 index: usize,
711 held: &[PendingChunk],
712 mut dictionary: Option<&mut GlobalDictionary>,
713 ) -> Result<ColumnStripe> {
714 let mut stripe = ColumnStripe {
715 pages: Vec::with_capacity(held.len()),
716 codes: Vec::with_capacity(held.len()),
717 sieves: Vec::with_capacity(held.len()),
718 ranges: Vec::with_capacity(held.len()),
719 };
720 for pending in held {
721 let column = pending.chunk.column(index)?;
722 let (bytes, unique) = encode(column, dictionary.as_deref_mut())?;
723 if bytes.len() > MAX_PAGE {
724 return Err(invalid("column page exceeds the configured bound"));
725 }
726 let range = Range::of(column);
729 let sieve = match dictionary {
734 Some(_) => None,
735 None => Sieve::of(column, &range, SIEVE_BUDGET),
736 };
737 stripe.pages.push(bytes);
738 stripe.codes.push(unique);
739 stripe.sieves.push(sieve);
740 stripe.ranges.push(range);
741 }
742 Ok(stripe)
743 }
744
745 fn encode_columns(&mut self, held: &[PendingChunk]) -> Result<Vec<ColumnStripe>> {
754 let width = self.table.fields.len();
755 let workers = std::thread::available_parallelism()
756 .map_or(1, usize::from)
757 .min(MAX_ENCODE_WORKERS)
758 .min(width);
759 if workers <= 1 || held.len() <= 1 {
760 return self
761 .dictionaries
762 .iter_mut()
763 .enumerate()
764 .map(|(index, dictionary)| Self::encode_column(index, held, dictionary.as_mut()))
765 .collect();
766 }
767 let mut jobs: Vec<(usize, Option<GlobalDictionary>)> =
770 std::mem::take(&mut self.dictionaries).into_iter().enumerate().collect();
771 jobs.sort_by_key(|(index, _)| weight(&self.table.fields[*index].ty));
773 let queue = Mutex::new(jobs);
774 let pieces = std::thread::scope(|scope| {
775 (0..workers)
776 .map(|_| {
777 scope.spawn(|| {
778 let mut mine = Vec::new();
779 loop {
780 let taken = queue
781 .lock()
782 .map_err(|_| Error::internal("a native encode worker panicked"))?
783 .pop();
784 let Some((index, mut dictionary)) = taken else { break };
785 let encoded = Self::encode_column(index, held, dictionary.as_mut())?;
786 mine.push((index, dictionary, encoded));
787 }
788 Ok(mine)
789 })
790 })
791 .collect::<Vec<_>>()
792 .into_iter()
793 .map(|handle| {
794 handle.join().map_err(|_| Error::internal("a native encode worker panicked"))?
795 })
796 .collect::<Result<Vec<_>>>()
797 })?;
798 let mut dictionaries: Vec<Option<GlobalDictionary>> = (0..width).map(|_| None).collect();
799 let mut encoded: Vec<Option<ColumnStripe>> = (0..width).map(|_| None).collect();
800 for piece in pieces {
801 for (index, dictionary, stripe) in piece {
802 dictionaries[index] = dictionary;
803 encoded[index] = Some(stripe);
804 }
805 }
806 self.dictionaries = dictionaries;
807 encoded
808 .into_iter()
809 .map(|stripe| stripe.ok_or_else(|| Error::internal("a column was never encoded")))
810 .collect()
811 }
812
813 fn flush_pending(&mut self) -> Result<()> {
815 if self.pending.is_empty() {
816 return Ok(());
817 }
818 let width = self.table.fields.len();
819 let mut held = std::mem::take(&mut self.pending);
822 let parts = held.len();
823 let encoded = self.encode_columns(&held)?;
824 let mut pages = Vec::with_capacity(width);
825 let mut memberships = vec![None; width];
826 let mut ranges = Vec::with_capacity(width);
827 let mut index = Vec::with_capacity(width.saturating_mul(index_section(parts)?));
828 for stripe in &encoded {
829 let offset = self.at;
830 let section = index.len();
831 let mut length = 0_usize;
832 for bytes in &stripe.pages {
833 write_at(&self.file, self.at + length as u64, bytes)?;
834 put_u32(
835 &mut index,
836 u32::try_from(bytes.len()).map_err(|_| invalid("part length overflow"))?,
837 );
838 put_u64(&mut index, checksum(bytes));
839 length = length
840 .checked_add(bytes.len())
841 .ok_or_else(|| invalid("column page length overflow"))?;
842 }
843 let hash = checksum(&index[section..]);
844 put_u64(&mut index, hash);
845 if length > MAX_PAGE {
846 return Err(invalid("column page exceeds the configured bound"));
847 }
848 self.at = self
849 .at
850 .checked_add(length as u64)
851 .ok_or_else(|| invalid("native file length overflow"))?;
852 pages.push(Span {
853 offset,
854 length: u32::try_from(length).map_err(|_| invalid("page length overflow"))?,
855 });
856 ranges.push(merged_range(stripe.ranges.iter().cloned()));
857 }
858 for (membership, stripe) in memberships.iter_mut().zip(&encoded) {
859 if stripe.codes.iter().all(Option::is_none) {
860 continue;
861 }
862 let lists = stripe
863 .codes
864 .iter()
865 .map(|codes| codes.clone().unwrap_or_default())
866 .collect::<Vec<_>>();
867 let bytes = encode_membership(&merged_codes(lists));
868 let offset = self.at;
869 self.put(&bytes)?;
870 *membership = Some(Page {
871 offset,
872 length: u32::try_from(bytes.len())
873 .map_err(|_| invalid("membership page length overflow"))?,
874 hash: checksum(&bytes),
875 });
876 }
877 let mut sieves = vec![None; width];
878 for (page, stripe) in sieves.iter_mut().zip(&encoded) {
879 if stripe.sieves.iter().all(Option::is_none) {
880 continue;
881 }
882 let bytes = encode_sieves(stripe.sieves.iter())?;
883 let offset = self.at;
884 self.put(&bytes)?;
885 *page = Some(Page {
886 offset,
887 length: u32::try_from(bytes.len())
888 .map_err(|_| invalid("sieve page length overflow"))?,
889 hash: checksum(&bytes),
890 });
891 }
892 let offset = self.at;
893 self.put(&index)?;
894 let index = Span {
895 offset,
896 length: u32::try_from(index.len())
897 .map_err(|_| invalid("index page length overflow"))?,
898 };
899 let mut rows = 0_usize;
900 let mut lengths = Vec::with_capacity(parts);
901 let mut span = None;
902 for pending in held.drain(..) {
903 let part = pending.chunk.len();
904 rows = rows.checked_add(part).ok_or_else(|| invalid("row count overflow"))?;
905 lengths.push(u32::try_from(part).map_err(|_| invalid("part row count overflow"))?);
906 span = Some(
907 span.map_or((pending.order, pending.order), |(first, _)| (first, pending.order)),
908 );
909 }
910 self.order.push(span.ok_or_else(|| invalid("a stripe was flushed with no parts"))?);
911 self.table.stripes.push(Stripe {
912 rows,
913 parts: lengths,
914 index,
915 pages,
916 memberships,
917 sieves,
918 zone: Zone::from_ranges(ranges),
919 });
920 self.pending = held;
922 Ok(())
923 }
924
925 fn numeric_frequency(&self, column: usize) -> Result<Option<FrequencySummary>> {
929 let ty = &self.table.fields[column].ty;
930 if !matches!(
931 ty,
932 LogicalType::TinyInt
933 | LogicalType::SmallInt
934 | LogicalType::Integer
935 | LogicalType::BigInt
936 | LogicalType::UTinyInt
937 | LogicalType::USmallInt
938 | LogicalType::UInteger
939 | LogicalType::UBigInt
940 | LogicalType::Date
941 | LogicalType::Timestamp
942 ) {
943 return Ok(None);
944 }
945 let mut candidates: HashMap<FrequencyValue, u32> = HashMap::new();
946 let mut decrements = 0_u64;
947 self.visit_numeric(column, |_, value| {
948 if let Some(count) = candidates.get_mut(&value) {
949 *count = count.saturating_add(1);
950 } else if candidates.len() < FREQUENCY_CANDIDATES {
951 candidates.insert(value, 1);
952 } else {
953 candidates.retain(|_, count| {
954 *count -= 1;
955 *count != 0
956 });
957 decrements = decrements.saturating_add(1);
958 }
959 })?;
960 let (exact, ordinals) = if decrements == 0 {
961 (
962 candidates
963 .into_iter()
964 .map(|(value, count)| (value, u64::from(count)))
965 .collect::<HashMap<_, _>>(),
966 Vec::new(),
967 )
968 } else {
969 let mut lower = candidates.values().copied().collect::<Vec<_>>();
970 lower.sort_unstable_by(|left, right| right.cmp(left));
971 if lower.len() < FREQUENCY_BUILD_RANK
972 || u64::from(lower[FREQUENCY_BUILD_RANK - 1]) <= decrements
973 {
974 return Ok(None);
975 }
976 let mut exact =
977 candidates.into_keys().map(|value| (value, 0_u64)).collect::<HashMap<_, _>>();
978 let mut ordinals = Vec::new();
979 let mut exceeded = false;
980 self.visit_numeric(column, |ordinal, value| {
981 if let Some(count) = exact.get_mut(&value) {
982 *count = count.saturating_add(1);
983 if !exceeded {
984 if ordinals.len() < FREQUENCY_ORDINALS {
985 ordinals.push(ordinal);
986 } else {
987 ordinals.clear();
988 exceeded = true;
989 }
990 }
991 }
992 })?;
993 (exact, ordinals)
994 };
995 let mut entries = exact
996 .into_iter()
997 .map(|(value, count)| FrequencyEntry { value, count })
998 .collect::<Vec<_>>();
999 entries.sort_unstable_by(|left, right| {
1000 right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
1001 });
1002 let omitted_max =
1003 entries.get(FREQUENCY_ENTRIES).map_or(decrements, |entry| decrements.max(entry.count));
1004 entries.truncate(FREQUENCY_ENTRIES);
1005 Ok(Some(FrequencySummary { entries, omitted_max, ordinals }))
1006 }
1007
1008 fn visit_numeric(
1009 &self,
1010 column: usize,
1011 mut visit: impl FnMut(u64, FrequencyValue),
1012 ) -> Result<()> {
1013 let ty = &self.table.fields[column].ty;
1014 let mut start = 0_u64;
1015 for stripe in &self.table.stripes {
1016 let spans = read_index(&self.file, stripe, column)?;
1017 let page = stripe.pages[column];
1018 let mut bytes = vec![0; page.length as usize];
1019 read_at(&self.file, page.offset, &mut bytes)?;
1020 for (span, &rows) in spans.iter().zip(&stripe.parts) {
1021 let part = part_bytes(&bytes, *span)?;
1022 if checksum(part) != span.hash {
1023 return Err(invalid("column page checksum differs while building frequencies"));
1024 }
1025 let rows = rows as usize;
1026 let vector = decode(ty, rows, part, None)?;
1027 for row in 0..rows {
1029 let value = if vector.is_null_at(row) {
1030 FrequencyValue::Null
1031 } else {
1032 let widened = match vector.signed_at(row) {
1036 Some(value) => Some(value),
1037 None => match vector.value_at(row) {
1038 Value::UTinyInt(value) => Some(i128::from(value)),
1039 Value::USmallInt(value) => Some(i128::from(value)),
1040 Value::UInteger(value) => Some(i128::from(value)),
1041 Value::UBigInt(value) => Some(i128::from(value)),
1042 _ => None,
1043 },
1044 };
1045 FrequencyValue::Integer(widened.ok_or_else(|| {
1046 invalid("numeric frequency page did not contain an integer value")
1047 })?)
1048 };
1049 visit(start.saturating_add(row as u64), value);
1050 }
1051 start = start.saturating_add(rows as u64);
1052 }
1053 }
1054 Ok(())
1055 }
1056
1057 fn numeric_frequencies(&self) -> Result<Vec<Option<FrequencySummary>>> {
1059 let columns = self
1060 .table
1061 .fields
1062 .iter()
1063 .enumerate()
1064 .filter_map(|(column, field)| {
1065 matches!(
1066 field.ty,
1067 LogicalType::TinyInt
1068 | LogicalType::SmallInt
1069 | LogicalType::Integer
1070 | LogicalType::BigInt
1071 | LogicalType::UTinyInt
1072 | LogicalType::USmallInt
1073 | LogicalType::UInteger
1074 | LogicalType::UBigInt
1075 | LogicalType::Date
1076 | LogicalType::Timestamp
1077 )
1078 .then_some(column)
1079 })
1080 .collect::<Vec<_>>();
1081 let workers = std::thread::available_parallelism()
1082 .map_or(1, usize::from)
1083 .min(MAX_FREQUENCY_WORKERS)
1084 .min(columns.len());
1085 if workers <= 1 {
1086 let mut frequencies = vec![None; self.table.fields.len()];
1087 for column in columns {
1088 frequencies[column] = self.numeric_frequency(column)?;
1089 }
1090 return Ok(frequencies);
1091 }
1092 let width = columns.len().div_ceil(workers);
1093 let pieces = std::thread::scope(|scope| {
1094 columns
1095 .chunks(width)
1096 .map(|columns| {
1097 scope.spawn(|| {
1098 columns
1099 .iter()
1100 .map(|&column| Ok((column, self.numeric_frequency(column)?)))
1101 .collect::<Result<Vec<_>>>()
1102 })
1103 })
1104 .collect::<Vec<_>>()
1105 .into_iter()
1106 .map(|handle| {
1107 handle
1108 .join()
1109 .map_err(|_| Error::internal("a native frequency worker panicked"))?
1110 })
1111 .collect::<Result<Vec<_>>>()
1112 })?;
1113 let mut frequencies = vec![None; self.table.fields.len()];
1114 for piece in pieces {
1115 for (column, summary) in piece {
1116 frequencies[column] = summary;
1117 }
1118 }
1119 Ok(frequencies)
1120 }
1121
1122 pub fn finish(mut self) -> Result<Table> {
1128 self.flush_pending()?;
1129 let mut stripes = std::mem::take(&mut self.order)
1130 .into_iter()
1131 .zip(std::mem::take(&mut self.table.stripes))
1132 .collect::<Vec<_>>();
1133 stripes.sort_by_key(|(order, _)| order.0);
1134 let mut previous: Option<(u64, u64)> = None;
1135 for ((first, last), _) in &stripes {
1136 if previous.is_some_and(|previous| previous >= *first) {
1137 return Err(invalid("chunks did not arrive in source order"));
1138 }
1139 previous = Some(*last);
1140 }
1141 self.table.stripes = stripes.into_iter().map(|(_, stripe)| stripe).collect();
1142 self.table.frequencies = self.numeric_frequencies()?;
1143 let dictionaries = std::mem::take(&mut self.dictionaries);
1144 let orders = rankings(&dictionaries)?;
1145 for (index, (dictionary, order)) in dictionaries.into_iter().zip(orders).enumerate() {
1146 let Some(dictionary) = dictionary else { continue };
1147 self.table.frequencies[index] = Some(code_frequency(&dictionary));
1148 let encoded = encode_global_dictionary(dictionary, &order)?;
1149 let offset = self.at;
1150 self.put(&encoded.index)?;
1151 self.put(&encoded.ranks)?;
1152 self.put(&encoded.payload)?;
1153 let length = encoded
1154 .index
1155 .len()
1156 .checked_add(encoded.ranks.len())
1157 .and_then(|len| len.checked_add(encoded.payload.len()))
1158 .ok_or_else(|| invalid("dictionary page length overflow"))?;
1159 self.table.dictionaries[index] = Some(Page {
1160 offset,
1161 length: u32::try_from(length)
1162 .map_err(|_| invalid("dictionary page length overflow"))?,
1163 hash: checksum(&encoded.index),
1164 });
1165 }
1166 let directory = encode_directory(&self.table)?;
1167 if directory.len() > MAX_DIRECTORY {
1168 return Err(invalid("directory exceeds the configured bound"));
1169 }
1170 let offset = self.at;
1171 self.put(&directory)?;
1172 self.file.sync_all().map_err(io)?;
1173 let slot = Slot {
1174 offset,
1175 length: u32::try_from(directory.len())
1176 .map_err(|_| invalid("directory length overflow"))?,
1177 generation: self.generation,
1178 hash: checksum(&directory),
1179 };
1180 write_at(&self.file, 16, &slot.bytes())?;
1183 self.file.sync_all().map_err(io)?;
1184 Ok(self.table)
1185 }
1186}
1187
1188#[derive(Debug, Clone)]
1190pub struct Reader {
1191 file: Arc<File>,
1192 table: Arc<Table>,
1193 dictionaries: Arc<Vec<OnceLock<Arc<Vector>>>>,
1194 sieves: Arc<Vec<Vec<SieveSlot>>>,
1198 places: Arc<Vec<Place>>,
1200 cache: Arc<Vec<Mutex<Cached>>>,
1201 pages: Arc<AtomicUsize>,
1204 indexes: Arc<AtomicUsize>,
1207 kept: Arc<AtomicUsize>,
1210 size: u64,
1212 directory: u64,
1214 opening: Opening,
1216}
1217
1218#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1230pub struct Opening {
1231 pub reads: u32,
1234 pub bytes: u64,
1236}
1237
1238#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1240pub struct Reads {
1241 pub opening: Opening,
1243 pub pages: usize,
1245 pub indexes: usize,
1247}
1248
1249#[derive(Debug, Clone, Copy)]
1251struct Place {
1252 stripe: u32,
1253 part: u32,
1254 rows: u32,
1255}
1256
1257#[derive(Debug, Clone, Copy)]
1259struct PartSpan {
1260 start: usize,
1261 length: usize,
1262 hash: u64,
1263}
1264
1265#[derive(Debug, Clone)]
1271struct CachedColumn {
1272 stripe: usize,
1273 index: Arc<Vec<PartSpan>>,
1274 page: Option<Arc<Vec<u8>>>,
1275}
1276
1277#[derive(Debug, Default)]
1297struct Cached {
1298 pages: Vec<Option<Arc<Vec<u8>>>>,
1299 order: VecDeque<usize>,
1300 loading: Vec<usize>,
1301 index: Vec<Option<Arc<Vec<PartSpan>>>>,
1302}
1303
1304const CACHED_STRIPES_PER_COLUMN: usize = 4;
1316
1317type SieveSlot = OnceLock<Arc<Vec<Option<Sieve>>>>;
1319
1320type CrossingCache = OnceLock<Box<[OnceLock<Result<Vec<u8>>>]>>;
1321
1322#[derive(Debug)]
1323struct NativeText {
1324 file: Arc<File>,
1325 offsets: Vec<u32>,
1326 ranks: usize,
1328 rank_at: u64,
1332 rank_hashes: Vec<u64>,
1333 rank_blocks: Vec<OnceLock<Result<Vec<u8>>>>,
1334 payload: u64,
1335 payload_len: usize,
1336 hashes: Vec<u64>,
1337 payload_extents: Vec<OnceLock<Result<Vec<u8>>>>,
1339 crossing: Vec<CrossingCache>,
1340}
1341
1342const TEXT_PAYLOAD_BLOCK: usize = 64 * 1024;
1343
1344const TEXT_PAYLOAD_EXTENT: usize = 8;
1365const TEXT_CROSSING_BLOCK: usize = 1024;
1366
1367const TEXT_RANK_BLOCK: usize = 512;
1377
1378const RANK_ENTRY: usize = size_of::<u64>() + size_of::<u32>();
1380
1381impl NativeText {
1382 fn payload_block(&self, block: usize) -> Result<Option<&[u8]>> {
1383 if block >= self.hashes.len() {
1384 return Ok(None);
1385 }
1386 let extent = block / TEXT_PAYLOAD_EXTENT;
1387 let Some(slot) = self.payload_extents.get(extent) else { return Ok(None) };
1388 let bytes = slot
1389 .get_or_init(|| {
1390 let start = extent
1391 .checked_mul(TEXT_PAYLOAD_EXTENT * TEXT_PAYLOAD_BLOCK)
1392 .ok_or_else(|| invalid("global dictionary block offset overflow"))?;
1393 let len = (TEXT_PAYLOAD_EXTENT * TEXT_PAYLOAD_BLOCK).min(
1394 self.payload_len
1395 .checked_sub(start)
1396 .ok_or_else(|| invalid("global dictionary block starts past payload"))?,
1397 );
1398 let mut bytes = vec![0; len];
1399 read_at(&self.file, self.payload + start as u64, &mut bytes)?;
1400 for (within, piece) in bytes.chunks(TEXT_PAYLOAD_BLOCK).enumerate() {
1403 if checksum(piece)
1404 != *self
1405 .hashes
1406 .get(extent * TEXT_PAYLOAD_EXTENT + within)
1407 .ok_or_else(|| invalid("global dictionary block has no checksum"))?
1408 {
1409 return Err(invalid("global dictionary payload checksum differs"));
1410 }
1411 }
1412 Ok(bytes)
1413 })
1414 .as_ref()
1415 .map_err(Clone::clone)?;
1416 let within = (block % TEXT_PAYLOAD_EXTENT) * TEXT_PAYLOAD_BLOCK;
1417 let end = (within + TEXT_PAYLOAD_BLOCK).min(bytes.len());
1418 Ok(bytes.get(within..end))
1419 }
1420
1421 fn rank_parts(&self, rank: usize) -> Result<(&[u8], usize)> {
1428 let slot = self
1429 .rank_blocks
1430 .get(rank / TEXT_RANK_BLOCK)
1431 .ok_or_else(|| invalid("global dictionary rank is past the order"))?;
1432 let block = slot
1433 .get_or_init(|| {
1434 let first = rank / TEXT_RANK_BLOCK * TEXT_RANK_BLOCK;
1435 let len = TEXT_RANK_BLOCK.min(self.ranks - first) * RANK_ENTRY;
1436 let mut bytes = vec![0; len];
1437 read_at(&self.file, self.rank_at + (first * RANK_ENTRY) as u64, &mut bytes)?;
1438 if checksum(&bytes)
1439 != *self
1440 .rank_hashes
1441 .get(rank / TEXT_RANK_BLOCK)
1442 .ok_or_else(|| invalid("global dictionary rank block has no checksum"))?
1443 {
1444 return Err(invalid("global dictionary rank checksum differs"));
1445 }
1446 Ok(bytes)
1447 })
1448 .as_ref()
1449 .map_err(Clone::clone)?;
1450 Ok((block.as_slice(), rank % TEXT_RANK_BLOCK))
1451 }
1452
1453 fn head_at(&self, rank: usize) -> Result<u64> {
1455 let (block, within) = self.rank_parts(rank)?;
1456 let at = within * size_of::<u64>();
1457 let bytes = block
1458 .get(at..at + size_of::<u64>())
1459 .ok_or_else(|| invalid("global dictionary rank block is short of heads"))?;
1460 Ok(u64::from_le_bytes(bytes.try_into().expect("eight bytes")))
1461 }
1462}
1463
1464impl TextSource for NativeText {
1465 fn len(&self) -> usize {
1466 self.offsets.len().saturating_sub(1)
1467 }
1468
1469 fn bytes_at(&self, index: usize) -> Result<Option<&[u8]>> {
1470 let (Some(&start), Some(&end)) = (self.offsets.get(index), self.offsets.get(index + 1))
1471 else {
1472 return Ok(None);
1473 };
1474 if start == end {
1475 return Ok(Some(&[]));
1476 }
1477 let first = start as usize / TEXT_PAYLOAD_BLOCK;
1478 let last = (end as usize - 1) / TEXT_PAYLOAD_BLOCK;
1479 if first == last {
1480 let Some(block) = self.payload_block(first)? else { return Ok(None) };
1481 let within = start as usize % TEXT_PAYLOAD_BLOCK;
1482 return Ok(block.get(within..within + (end - start) as usize));
1483 }
1484 let Some(crossing) = self.crossing.get(index / TEXT_CROSSING_BLOCK) else {
1485 return Ok(None);
1486 };
1487 let block = crossing.get_or_init(|| {
1488 (0..TEXT_CROSSING_BLOCK).map(|_| OnceLock::new()).collect::<Vec<_>>().into_boxed_slice()
1489 });
1490 block[index % TEXT_CROSSING_BLOCK]
1491 .get_or_init(|| {
1492 let mut bytes = Vec::with_capacity((end - start) as usize);
1493 for part in first..=last {
1494 let source = self
1495 .payload_block(part)?
1496 .ok_or_else(|| invalid("global dictionary block is missing"))?;
1497 let from = if part == first { start as usize % TEXT_PAYLOAD_BLOCK } else { 0 };
1498 let to = if part == last {
1499 (end as usize - 1) % TEXT_PAYLOAD_BLOCK + 1
1500 } else {
1501 source.len()
1502 };
1503 bytes.extend_from_slice(source.get(from..to).ok_or_else(|| {
1504 invalid("global dictionary value exceeds its payload block")
1505 })?);
1506 }
1507 Ok(bytes)
1508 })
1509 .as_ref()
1510 .map(|bytes| Some(bytes.as_slice()))
1511 .map_err(Clone::clone)
1512 }
1513
1514 fn bytes_len_at(&self, index: usize) -> Result<Option<usize>> {
1515 let (Some(&start), Some(&end)) = (self.offsets.get(index), self.offsets.get(index + 1))
1516 else {
1517 return Ok(None);
1518 };
1519 Ok(Some((end - start) as usize))
1520 }
1521
1522 fn ranks(&self) -> Option<usize> {
1523 (self.ranks > 0).then_some(self.ranks)
1524 }
1525
1526 fn compare_rank(&self, rank: usize, wanted: &[u8]) -> Result<Ordering> {
1527 let settled = self.head_at(rank)?.cmp(&head(wanted));
1531 if settled != Ordering::Equal {
1532 return Ok(settled);
1533 }
1534 let code = self.code_at_rank(rank)?;
1535 let bytes = self
1536 .bytes_at(code as usize)?
1537 .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
1538 Ok(bytes.cmp(wanted))
1539 }
1540
1541 fn code_at_rank(&self, rank: usize) -> Result<u32> {
1542 let (block, within) = self.rank_parts(rank)?;
1543 let heads = block.len() / RANK_ENTRY * size_of::<u64>();
1544 let at = heads + within * size_of::<u32>();
1545 let bytes = block
1546 .get(at..at + size_of::<u32>())
1547 .ok_or_else(|| invalid("global dictionary rank block is short of codes"))?;
1548 let code = u32::from_le_bytes(bytes.try_into().expect("four bytes"));
1549 if code as usize >= self.len() {
1550 return Err(invalid("global dictionary order names a code it does not have"));
1551 }
1552 Ok(code)
1553 }
1554
1555 fn footprint(&self) -> usize {
1556 self.offsets.capacity() * size_of::<u32>()
1557 + self.rank_hashes.capacity() * size_of::<u64>()
1558 + self.rank_blocks.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
1559 + self
1560 .rank_blocks
1561 .iter()
1562 .filter_map(OnceLock::get)
1563 .filter_map(|result| result.as_ref().ok())
1564 .map(Vec::capacity)
1565 .sum::<usize>()
1566 + self.payload_extents.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
1567 + self.hashes.capacity() * size_of::<u64>()
1568 + self
1569 .payload_extents
1570 .iter()
1571 .filter_map(OnceLock::get)
1572 .filter_map(|result| result.as_ref().ok())
1573 .map(Vec::capacity)
1574 .sum::<usize>()
1575 + self.crossing.capacity() * size_of::<CrossingCache>()
1576 + self
1577 .crossing
1578 .iter()
1579 .filter_map(OnceLock::get)
1580 .map(|block| {
1581 block.len() * size_of::<OnceLock<Result<Vec<u8>>>>()
1582 + block
1583 .iter()
1584 .filter_map(OnceLock::get)
1585 .filter_map(|result| result.as_ref().ok())
1586 .map(Vec::capacity)
1587 .sum::<usize>()
1588 })
1589 .sum::<usize>()
1590 }
1591}
1592
1593fn places(table: &Table) -> Result<Vec<Place>> {
1595 let mut places = Vec::with_capacity(table.stripes.len().saturating_mul(STRIPE_PARTS));
1596 for (at, stripe) in table.stripes.iter().enumerate() {
1597 let index = u32::try_from(at).map_err(|_| invalid("too many stripes"))?;
1598 for (part, &rows) in stripe.parts.iter().enumerate() {
1599 places.push(Place {
1600 stripe: index,
1601 part: u32::try_from(part).map_err(|_| invalid("too many parts in a stripe"))?,
1602 rows,
1603 });
1604 }
1605 }
1606 Ok(places)
1607}
1608
1609fn read_index(file: &File, stripe: &Stripe, column: usize) -> Result<Vec<PartSpan>> {
1614 let parts = stripe.parts.len();
1615 let section = index_section(parts)?;
1616 let at = column.checked_mul(section).ok_or_else(|| invalid("index page offset overflow"))?;
1617 let end = at.checked_add(section).ok_or_else(|| invalid("index page offset overflow"))?;
1618 if end > stripe.index.length as usize {
1619 return Err(invalid("index page is shorter than its columns"));
1620 }
1621 let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
1622 let mut bytes = vec![0; section];
1623 let offset = stripe
1624 .index
1625 .offset
1626 .checked_add(at as u64)
1627 .ok_or_else(|| invalid("index page offset overflow"))?;
1628 read_at(file, offset, &mut bytes)?;
1629 let entries = section - size_of::<u64>();
1630 let stored = u64::from_le_bytes(bytes[entries..].try_into().expect("eight bytes"));
1631 if checksum(&bytes[..entries]) != stored {
1632 return Err(invalid(&format!(
1635 "index page section checksum differs, column {column} of {parts} parts at {offset}, \
1636 wanted {stored:016x} and got {:016x}",
1637 checksum(&bytes[..entries]),
1638 )));
1639 }
1640 let mut spans = Vec::with_capacity(parts);
1641 let mut start = 0_usize;
1642 for part in 0..parts {
1643 let at = part * INDEX_ENTRY;
1644 let length = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes")) as usize;
1645 let hash = u64::from_le_bytes(bytes[at + 4..at + 12].try_into().expect("eight bytes"));
1646 spans.push(PartSpan { start, length, hash });
1647 start = start.checked_add(length).ok_or_else(|| invalid("column page length overflow"))?;
1648 }
1649 if start != page.length as usize {
1650 return Err(invalid("column page length differs from its index"));
1651 }
1652 Ok(spans)
1653}
1654
1655fn part_bytes(page: &[u8], span: PartSpan) -> Result<&[u8]> {
1657 let end = span.start.checked_add(span.length).ok_or_else(|| invalid("part range overflow"))?;
1658 page.get(span.start..end).ok_or_else(|| invalid("part exceeds its column page"))
1659}
1660
1661fn remember(cached: &mut Cached, held: &CachedColumn, kept: usize) {
1666 if let Some(slot) = cached.index.get_mut(held.stripe) {
1667 if slot.is_none() {
1668 *slot = Some(Arc::clone(&held.index));
1669 }
1670 }
1671 let Some(page) = held.page.clone() else { return };
1672 let Some(slot) = cached.pages.get_mut(held.stripe) else { return };
1673 if slot.is_none() {
1674 cached.order.push_back(held.stripe);
1675 }
1676 *slot = Some(page);
1677 while cached.order.len() > kept.max(1) {
1678 let Some(oldest) = cached.order.pop_front() else { break };
1679 if let Some(slot) = cached.pages.get_mut(oldest) {
1680 *slot = None;
1681 }
1682 }
1683}
1684
1685impl Reader {
1686 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
1692 let mut file = File::open(path).map_err(io)?;
1693 let size = file.metadata().map_err(io)?.len();
1694 if size < HEADER {
1695 return Err(invalid("file is shorter than its header"));
1696 }
1697 let mut header = [0; HEADER as usize];
1698 file.read_exact(&mut header).map_err(io)?;
1699 let mut opening = Opening { reads: 1, bytes: HEADER };
1700 let version = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
1701 if &header[..8] != MAGIC {
1706 return Err(invalid("the header does not begin with a rudb native magic"));
1707 }
1708 if version != FORMAT {
1709 return Err(invalid(&format!(
1710 "the file is format {version} and this build reads format {FORMAT}, so it has to \
1711 be written again"
1712 )));
1713 }
1714 let mut selected = None;
1715 for start in [16, 16 + SLOT_BYTES] {
1716 let slot = Slot::read(&header[start..start + SLOT_BYTES]);
1717 if slot.generation == 0 || slot.length == 0 || slot.length as usize > MAX_DIRECTORY {
1718 continue;
1719 }
1720 let Some(end) = slot.offset.checked_add(u64::from(slot.length)) else { continue };
1721 if slot.offset < HEADER || end > size {
1722 continue;
1723 }
1724 let mut bytes = vec![0; slot.length as usize];
1725 file.seek(SeekFrom::Start(slot.offset)).map_err(io)?;
1726 file.read_exact(&mut bytes).map_err(io)?;
1727 opening.reads += 1;
1728 opening.bytes += u64::from(slot.length);
1729 if checksum(&bytes) == slot.hash
1730 && selected
1731 .as_ref()
1732 .is_none_or(|(old, _): &(Slot, Vec<u8>)| old.generation < slot.generation)
1733 {
1734 selected = Some((slot, bytes));
1735 }
1736 }
1737 let (slot, bytes) =
1738 selected.ok_or_else(|| invalid("no committed directory slot is valid"))?;
1739 let table = decode_directory(&bytes, size)?;
1740 let places = places(&table)?;
1741 let dictionaries = (0..table.fields.len()).map(|_| OnceLock::new()).collect();
1742 let stripes = table.stripes.len();
1743 let cache = (0..table.fields.len())
1744 .map(|_| {
1745 Mutex::new(Cached {
1746 pages: (0..stripes).map(|_| None).collect(),
1747 index: (0..stripes).map(|_| None).collect(),
1748 ..Cached::default()
1749 })
1750 })
1751 .collect::<Vec<_>>();
1752 let sieves = (0..table.fields.len())
1753 .map(|_| table.stripes.iter().map(|_| OnceLock::new()).collect())
1754 .collect();
1755 Ok(Self {
1756 file: Arc::new(file),
1757 table: Arc::new(table),
1758 dictionaries: Arc::new(dictionaries),
1759 sieves: Arc::new(sieves),
1760 places: Arc::new(places),
1761 cache: Arc::new(cache),
1762 pages: Arc::new(AtomicUsize::new(0)),
1763 indexes: Arc::new(AtomicUsize::new(0)),
1764 kept: Arc::new(AtomicUsize::new(CACHED_STRIPES_PER_COLUMN)),
1765 size,
1766 directory: u64::from(slot.length),
1767 opening,
1768 })
1769 }
1770
1771 #[must_use]
1778 pub fn reads(&self) -> Reads {
1779 Reads {
1780 opening: self.opening,
1781 pages: self.pages.load(Atomic::Relaxed),
1782 indexes: self.indexes.load(Atomic::Relaxed),
1783 }
1784 }
1785
1786 #[must_use]
1791 pub fn layout(&self) -> Layout {
1792 let table = &self.table;
1793 let stripes = table.stripes.as_slice();
1794 let columns = table
1795 .fields
1796 .iter()
1797 .enumerate()
1798 .map(|(at, field)| ColumnLayout {
1799 name: field.name.clone(),
1800 kind: field.ty.to_string(),
1801 pages: sum(stripes.iter().map(|stripe| span_bytes(&stripe.pages, at))),
1802 memberships: sum(stripes.iter().map(|stripe| page_bytes(&stripe.memberships, at))),
1803 sieves: sum(stripes.iter().map(|stripe| page_bytes(&stripe.sieves, at))),
1804 dictionary: page_bytes(&table.dictionaries, at),
1805 })
1806 .collect();
1807 Layout {
1808 file: self.size,
1809 rows: table.rows,
1810 stripes: stripes.len(),
1811 parts: self.places.len(),
1812 columns,
1813 indexes: sum(stripes.iter().map(|stripe| u64::from(stripe.index.length))),
1814 directory: self.directory,
1815 header: HEADER,
1816 }
1817 }
1818
1819 #[must_use]
1821 pub fn parts(&self) -> usize {
1822 self.places.len()
1823 }
1824
1825 #[must_use]
1832 pub fn stripe_parts(&self) -> Vec<std::ops::Range<usize>> {
1833 let mut runs = Vec::with_capacity(self.table.stripes.len());
1834 let mut start = 0;
1835 for stripe in &self.table.stripes {
1836 let end = start + stripe.parts.len();
1837 runs.push(start..end);
1838 start = end;
1839 }
1840 runs
1841 }
1842
1843 pub fn keep_stripes(&self, stripes: usize) {
1850 self.kept.fetch_max(stripes, Atomic::Relaxed);
1851 }
1852
1853 #[must_use]
1855 pub fn part_rows(&self, at: usize) -> usize {
1856 self.places.get(at).map_or(0, |place| place.rows as usize)
1857 }
1858
1859 #[must_use]
1861 pub fn table(&self) -> &Table {
1862 &self.table
1863 }
1864
1865 pub fn top_frequencies(&self, column: usize, top: usize) -> Result<Option<Vec<(Value, u64)>>> {
1874 let field = self
1875 .table
1876 .fields
1877 .get(column)
1878 .ok_or_else(|| invalid("frequency column index out of range"))?;
1879 let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
1880 return Ok(None);
1881 };
1882 if top == 0 || summary.entries.len() < top {
1883 return Ok(None);
1884 }
1885 let boundary = summary.entries[top - 1].count;
1886 if boundary <= summary.omitted_max {
1887 return Ok(None);
1888 }
1889 let dictionary =
1890 if field.ty == LogicalType::Varchar { self.dictionary(column)? } else { None };
1891 let mut out = Vec::with_capacity(summary.entries.len());
1892 for entry in &summary.entries {
1893 let value = match entry.value {
1894 FrequencyValue::Null => Value::Null,
1895 FrequencyValue::Integer(value) => match field.ty {
1896 LogicalType::TinyInt => Value::TinyInt(
1897 i8::try_from(value)
1898 .map_err(|_| invalid("frequency TINYINT is out of range"))?,
1899 ),
1900 LogicalType::UTinyInt => Value::UTinyInt(
1901 u8::try_from(value)
1902 .map_err(|_| invalid("frequency UTINYINT is out of range"))?,
1903 ),
1904 LogicalType::USmallInt => Value::USmallInt(
1905 u16::try_from(value)
1906 .map_err(|_| invalid("frequency USMALLINT is out of range"))?,
1907 ),
1908 LogicalType::UInteger => Value::UInteger(
1909 u32::try_from(value)
1910 .map_err(|_| invalid("frequency UINTEGER is out of range"))?,
1911 ),
1912 LogicalType::UBigInt => Value::UBigInt(
1913 u64::try_from(value)
1914 .map_err(|_| invalid("frequency UBIGINT is out of range"))?,
1915 ),
1916 LogicalType::SmallInt => Value::SmallInt(
1917 i16::try_from(value)
1918 .map_err(|_| invalid("frequency SMALLINT is out of range"))?,
1919 ),
1920 LogicalType::Integer => Value::Integer(
1921 i32::try_from(value)
1922 .map_err(|_| invalid("frequency INTEGER is out of range"))?,
1923 ),
1924 LogicalType::BigInt => Value::BigInt(
1925 i64::try_from(value)
1926 .map_err(|_| invalid("frequency BIGINT is out of range"))?,
1927 ),
1928 LogicalType::Date => Value::Date(
1929 i32::try_from(value)
1930 .map_err(|_| invalid("frequency DATE is out of range"))?,
1931 ),
1932 LogicalType::Timestamp => Value::Timestamp(
1933 i64::try_from(value)
1934 .map_err(|_| invalid("frequency TIMESTAMP is out of range"))?,
1935 ),
1936 _ => return Err(invalid("integer frequency belongs to another type")),
1937 },
1938 FrequencyValue::Code(code) => dictionary
1939 .as_ref()
1940 .ok_or_else(|| invalid("frequency code has no dictionary"))?
1941 .try_value_at(code as usize)?,
1942 };
1943 out.push((value, entry.count));
1944 }
1945 Ok(Some(out))
1946 }
1947
1948 pub fn frequency_occurrences(&self, column: usize) -> Result<Option<FrequencyOccurrences>> {
1958 self.table
1959 .fields
1960 .get(column)
1961 .ok_or_else(|| invalid("frequency column index out of range"))?;
1962 let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
1963 return Ok(None);
1964 };
1965 if summary.ordinals.is_empty() {
1966 return Ok(None);
1967 }
1968 Ok(Some(FrequencyOccurrences {
1969 omitted_max: summary.omitted_max,
1970 ordinals: summary.ordinals.clone(),
1971 }))
1972 }
1973
1974 pub fn distinct_values(&self, column: usize) -> Result<Option<u64>> {
1994 if self.null_count(column)? > 0 {
1995 return Ok(None);
1996 }
1997 Ok(self.dictionary(column)?.map(|dictionary| dictionary.len() as u64))
1998 }
1999
2000 pub fn null_count(&self, column: usize) -> Result<u64> {
2011 if column >= self.table.fields.len() {
2012 return Err(invalid("null count column index out of range"));
2013 }
2014 let mut nulls = 0_u64;
2015 for stripe in &self.table.stripes {
2016 let range = stripe
2017 .zone
2018 .column(column)
2019 .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2020 nulls = nulls
2021 .checked_add(range.nulls as u64)
2022 .ok_or_else(|| invalid("null count overflow"))?;
2023 }
2024 Ok(nulls)
2025 }
2026
2027 pub fn text_extremes(&self, column: usize) -> Result<Option<(Value, Value)>> {
2042 if self.null_count(column)? > 0 {
2043 return Ok(None);
2044 }
2045 let Some(dictionary) = self.dictionary(column)? else { return Ok(None) };
2046 let Some(ranks) = dictionary.ranks() else { return Ok(None) };
2047 if ranks == 0 {
2048 return Ok(None);
2049 }
2050 let low = text_at_rank(&dictionary, 0)?;
2051 let high = text_at_rank(&dictionary, ranks - 1)?;
2052 Ok(Some((low, high)))
2053 }
2054
2055 pub fn exact_extremes(&self, column: usize) -> Result<Option<(Bound, Bound)>> {
2078 if column >= self.table.fields.len() {
2079 return Err(invalid("extremes column index out of range"));
2080 }
2081 let mut low: Option<Bound> = None;
2082 let mut high: Option<Bound> = None;
2083 for stripe in &self.table.stripes {
2084 let range = stripe
2085 .zone
2086 .column(column)
2087 .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2088 if !range.exact {
2089 return Ok(None);
2090 }
2091 let (Some(small), Some(large)) = (range.low.as_ref(), range.high.as_ref()) else {
2096 if stripe.rows > range.nulls {
2097 return Ok(None);
2098 }
2099 continue;
2100 };
2101 low = Some(low.map_or_else(|| small.clone(), |held| held.smaller(small.clone())));
2102 high = Some(high.map_or_else(|| large.clone(), |held| held.larger(large.clone())));
2103 }
2104 Ok(low.zip(high))
2105 }
2106
2107 pub fn exact_sum(&self, column: usize) -> Result<Option<(i128, u64)>> {
2120 if column >= self.table.fields.len() {
2121 return Err(invalid("sum column index out of range"));
2122 }
2123 let mut total = 0_i128;
2124 let mut rows = 0_u64;
2125 for stripe in &self.table.stripes {
2126 let range = stripe
2127 .zone
2128 .column(column)
2129 .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2130 let Some(part) = range.sum else { return Ok(None) };
2131 let Some(sum) = total.checked_add(part) else { return Ok(None) };
2132 total = sum;
2133 rows = rows.saturating_add(stripe.rows as u64 - range.nulls as u64);
2134 }
2135 Ok(Some((total, rows)))
2136 }
2137
2138 fn dictionary(&self, column: usize) -> Result<Option<Arc<Vector>>> {
2139 let Some(page) = self.table.dictionaries[column] else { return Ok(None) };
2140 if let Some(dictionary) = self.dictionaries[column].get() {
2141 return Ok(Some(Arc::clone(dictionary)));
2142 }
2143 let dictionary = Arc::new(open_global_dictionary(
2144 Arc::clone(&self.file),
2145 page,
2146 &self.table.fields[column].ty,
2147 )?);
2148 let _ = self.dictionaries[column].set(Arc::clone(&dictionary));
2149 Ok(Some(self.dictionaries[column].get().map_or(dictionary, Arc::clone)))
2150 }
2151
2152 pub fn read(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2161 self.read_impl(part, columns, true)
2162 }
2163
2164 pub fn read_sparse(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2174 self.read_impl(part, columns, false)
2175 }
2176
2177 pub fn skips_codes(&self, part: usize, column: usize, candidates: &[u32]) -> Result<bool> {
2184 if candidates.is_empty() {
2185 return Ok(true);
2186 }
2187 if candidates.windows(2).any(|pair| pair[0] >= pair[1]) {
2188 return Err(Error::internal("native code candidates are not sorted and unique"));
2189 }
2190 let stripe = self.stripe_of(part)?;
2191 let Some(page) = stripe.memberships.get(column).copied().flatten() else {
2192 return Ok(false);
2193 };
2194 let mut bytes = vec![0; page.length as usize];
2195 read_at(&self.file, page.offset, &mut bytes)?;
2196 if checksum(&bytes) != page.hash {
2197 return Err(invalid("membership page checksum differs"));
2198 }
2199 let codes = decode_membership(&bytes)?;
2200 let mut left = 0;
2201 let mut right = 0;
2202 while left < codes.len() && right < candidates.len() {
2203 match codes[left].cmp(&candidates[right]) {
2204 Ordering::Less => left += 1,
2205 Ordering::Greater => right += 1,
2206 Ordering::Equal => return Ok(false),
2207 }
2208 }
2209 Ok(true)
2210 }
2211
2212 fn stripe_of(&self, part: usize) -> Result<&Stripe> {
2213 let place = self.places.get(part).ok_or_else(|| invalid("part index out of range"))?;
2214 self.table
2215 .stripes
2216 .get(place.stripe as usize)
2217 .ok_or_else(|| invalid("stripe index out of range"))
2218 }
2219
2220 fn held(&self, at: usize, stripe: &Stripe, column: usize, whole: bool) -> Result<CachedColumn> {
2237 let cache = self.cache.get(column).ok_or_else(|| invalid("column index out of range"))?;
2238 let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2239 let known = cached.index.get(at).and_then(Clone::clone);
2240 let page = cached.pages.get(at).and_then(Clone::clone);
2241 if let Some(index) = known.clone() {
2242 if !whole || page.is_some() {
2243 return Ok(CachedColumn { stripe: at, index, page });
2244 }
2245 }
2246 if cached.loading.contains(&at) {
2247 drop(cached);
2248 if let Some(index) = known {
2252 return Ok(CachedColumn { stripe: at, index, page: None });
2253 }
2254 let held = self.page_of(stripe, column, at, false, None)?;
2255 let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2256 remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2257 return Ok(held);
2258 }
2259 cached.loading.push(at);
2260 drop(cached);
2261
2262 let read = self.page_of(stripe, column, at, whole, known);
2263
2264 let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2268 if let Some(position) = cached.loading.iter().position(|loading| *loading == at) {
2269 cached.loading.remove(position);
2270 }
2271 let held = read?;
2272 remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2273 Ok(held)
2274 }
2275
2276 fn page_of(
2282 &self,
2283 stripe: &Stripe,
2284 column: usize,
2285 at: usize,
2286 whole: bool,
2287 known: Option<Arc<Vec<PartSpan>>>,
2288 ) -> Result<CachedColumn> {
2289 let index = match known {
2290 Some(index) => index,
2291 None => {
2292 self.indexes.fetch_add(1, Atomic::Relaxed);
2293 Arc::new(read_index(&self.file, stripe, column)?)
2294 }
2295 };
2296 let page = if whole {
2297 self.pages.fetch_add(1, Atomic::Relaxed);
2298 let span = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2299 let mut bytes = vec![0; span.length as usize];
2300 read_at(&self.file, span.offset, &mut bytes)?;
2301 Some(Arc::new(bytes))
2302 } else {
2303 None
2304 };
2305 Ok(CachedColumn { stripe: at, index, page })
2306 }
2307
2308 fn read_impl(&self, at: usize, columns: &[usize], whole: bool) -> Result<Chunk> {
2309 let place = *self.places.get(at).ok_or_else(|| invalid("part index out of range"))?;
2310 let index = place.stripe as usize;
2311 let stripe =
2312 self.table.stripes.get(index).ok_or_else(|| invalid("stripe index out of range"))?;
2313 let rows = place.rows as usize;
2314 let mut picked = Vec::with_capacity(columns.len());
2315 for &column in columns {
2316 let field = self
2317 .table
2318 .fields
2319 .get(column)
2320 .ok_or_else(|| invalid("column index out of range"))?;
2321 let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2322 let held = self.held(index, stripe, column, whole)?;
2323 let span = *held
2324 .index
2325 .get(place.part as usize)
2326 .ok_or_else(|| invalid("part index out of range"))?;
2327 let owned;
2328 let bytes = match &held.page {
2329 Some(held) => part_bytes(held, span)?,
2330 None => {
2331 let offset = page
2332 .offset
2333 .checked_add(span.start as u64)
2334 .ok_or_else(|| invalid("part range overflow"))?;
2335 let mut bytes = vec![0; span.length];
2336 read_at(&self.file, offset, &mut bytes)?;
2337 owned = bytes;
2338 &owned
2339 }
2340 };
2341 if checksum(bytes) != span.hash {
2342 return Err(invalid(&format!(
2343 "column page checksum differs, column {column} part {} at {}+{} of {} bytes, \
2344 wanted {:016x} and got {:016x}",
2345 place.part,
2346 page.offset,
2347 span.start,
2348 span.length,
2349 span.hash,
2350 checksum(bytes),
2351 )));
2352 }
2353 let dictionary = self.dictionary(column)?;
2354 picked.push(decode(&field.ty, rows, bytes, dictionary)?);
2355 }
2356 Chunk::with_rows(picked, rows)
2357 }
2358
2359 #[must_use]
2369 pub fn skips(&self, part: usize, probes: &[Probe]) -> bool {
2370 let Some(place) = self.places.get(part).copied() else { return false };
2371 let Some(stripe) = self.table.stripes.get(place.stripe as usize) else { return false };
2372 if stripe.zone.skips(probes) {
2373 return true;
2374 }
2375 probes.iter().any(|probe| self.sifted(place, probe))
2376 }
2377
2378 fn sifted(&self, place: Place, probe: &Probe) -> bool {
2384 if probe.op != Op::Equal {
2385 return false;
2386 }
2387 match self.stripe_sieves(place.stripe as usize, probe.column) {
2388 Some(sieves) => sieves
2389 .get(place.part as usize)
2390 .and_then(Option::as_ref)
2391 .is_some_and(|sieve| sieve.excludes(&probe.value)),
2392 None => false,
2393 }
2394 }
2395
2396 fn stripe_sieves(&self, stripe: usize, column: usize) -> Option<&[Option<Sieve>]> {
2403 let slot = self.sieves.get(column)?.get(stripe)?;
2404 if let Some(held) = slot.get() {
2405 return Some(held);
2406 }
2407 let page = self.table.stripes.get(stripe)?.sieves.get(column).copied().flatten()?;
2408 let mut bytes = vec![0; page.length as usize];
2409 read_at(&self.file, page.offset, &mut bytes).ok()?;
2410 if checksum(&bytes) != page.hash {
2411 return None;
2412 }
2413 let sieves = Arc::new(decode_sieves(&bytes).ok()?);
2414 let _ = slot.set(sieves);
2415 slot.get().map(|held| held.as_slice())
2416 }
2417}
2418
2419fn text_at_rank(dictionary: &Vector, rank: usize) -> Result<Value> {
2421 let code = dictionary.code_at_rank(rank)? as usize;
2422 let text = dictionary
2423 .try_text_at(code)?
2424 .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
2425 Ok(Value::Varchar(text.into()))
2426}
2427
2428#[cfg(unix)]
2433fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
2434 use std::os::unix::fs::FileExt;
2435 while !bytes.is_empty() {
2436 let written = file.write_at(bytes, offset).map_err(io)?;
2437 if written == 0 {
2438 return Err(invalid("a write to the native file wrote nothing"));
2439 }
2440 offset += written as u64;
2441 bytes = &bytes[written..];
2442 }
2443 Ok(())
2444}
2445
2446#[cfg(windows)]
2448fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
2449 use std::os::windows::fs::FileExt;
2450 while !bytes.is_empty() {
2451 let written = file.seek_write(bytes, offset).map_err(io)?;
2452 if written == 0 {
2453 return Err(invalid("a write to the native file wrote nothing"));
2454 }
2455 offset += written as u64;
2456 bytes = &bytes[written..];
2457 }
2458 Ok(())
2459}
2460
2461#[cfg(not(any(unix, windows)))]
2463fn write_at(file: &File, offset: u64, bytes: &[u8]) -> Result<()> {
2464 use std::io::Write;
2465 let mut file = file.try_clone().map_err(io)?;
2466 file.seek(SeekFrom::Start(offset)).map_err(io)?;
2467 file.write_all(bytes).map_err(io)
2468}
2469
2470#[cfg(unix)]
2480fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
2481 use std::os::unix::fs::FileExt;
2482 while !bytes.is_empty() {
2483 let read = file.read_at(bytes, offset).map_err(io)?;
2484 if read == 0 {
2485 return Err(invalid("column page ends before its declared length"));
2486 }
2487 offset += read as u64;
2488 bytes = &mut bytes[read..];
2489 }
2490 Ok(())
2491}
2492
2493#[cfg(windows)]
2499fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
2500 use std::os::windows::fs::FileExt;
2501 while !bytes.is_empty() {
2502 let read = file.seek_read(bytes, offset).map_err(io)?;
2503 if read == 0 {
2504 return Err(invalid("column page ends before its declared length"));
2505 }
2506 offset += read as u64;
2507 bytes = &mut bytes[read..];
2508 }
2509 Ok(())
2510}
2511
2512#[cfg(not(any(unix, windows)))]
2517fn read_at(file: &File, offset: u64, bytes: &mut [u8]) -> Result<()> {
2518 let mut file = file.try_clone().map_err(io)?;
2519 file.seek(SeekFrom::Start(offset)).map_err(io)?;
2520 file.read_exact(bytes).map_err(io)
2521}
2522
2523fn type_tag(ty: &LogicalType) -> Result<u8> {
2524 match ty {
2525 LogicalType::SmallInt => Ok(1),
2526 LogicalType::Integer => Ok(2),
2527 LogicalType::BigInt => Ok(3),
2528 LogicalType::Varchar => Ok(4),
2529 LogicalType::Date => Ok(5),
2530 LogicalType::Timestamp => Ok(6),
2531 LogicalType::Boolean => Ok(7),
2532 LogicalType::TinyInt => Ok(8),
2533 LogicalType::UTinyInt => Ok(9),
2534 LogicalType::USmallInt => Ok(10),
2535 LogicalType::UInteger => Ok(11),
2536 LogicalType::UBigInt => Ok(12),
2537 _ => Err(Error::not_implemented(format!("native storage for {ty}"))),
2538 }
2539}
2540
2541fn tag_type(tag: u8) -> Result<LogicalType> {
2542 match tag {
2543 1 => Ok(LogicalType::SmallInt),
2544 2 => Ok(LogicalType::Integer),
2545 3 => Ok(LogicalType::BigInt),
2546 4 => Ok(LogicalType::Varchar),
2547 5 => Ok(LogicalType::Date),
2548 6 => Ok(LogicalType::Timestamp),
2549 7 => Ok(LogicalType::Boolean),
2550 8 => Ok(LogicalType::TinyInt),
2551 9 => Ok(LogicalType::UTinyInt),
2552 10 => Ok(LogicalType::USmallInt),
2553 11 => Ok(LogicalType::UInteger),
2554 12 => Ok(LogicalType::UBigInt),
2555 _ => Err(invalid("column type tag is unknown")),
2556 }
2557}
2558
2559fn put_u16(out: &mut Vec<u8>, value: u16) {
2560 out.extend_from_slice(&value.to_le_bytes());
2561}
2562fn put_u32(out: &mut Vec<u8>, value: u32) {
2563 out.extend_from_slice(&value.to_le_bytes());
2564}
2565fn put_u64(out: &mut Vec<u8>, value: u64) {
2566 out.extend_from_slice(&value.to_le_bytes());
2567}
2568fn put_var_u64(out: &mut Vec<u8>, mut value: u64) {
2569 while value >= 0x80 {
2570 out.push((value as u8 & 0x7f) | 0x80);
2571 value >>= 7;
2572 }
2573 out.push(value as u8);
2574}
2575
2576fn frequency_order(left: FrequencyValue, right: FrequencyValue) -> Ordering {
2577 match (left, right) {
2578 (FrequencyValue::Null, FrequencyValue::Null) => Ordering::Equal,
2579 (FrequencyValue::Null, _) => Ordering::Less,
2580 (_, FrequencyValue::Null) => Ordering::Greater,
2581 (FrequencyValue::Integer(left), FrequencyValue::Integer(right)) => left.cmp(&right),
2582 (FrequencyValue::Code(left), FrequencyValue::Code(right)) => left.cmp(&right),
2583 (FrequencyValue::Integer(_), FrequencyValue::Code(_)) => Ordering::Less,
2584 (FrequencyValue::Code(_), FrequencyValue::Integer(_)) => Ordering::Greater,
2585 }
2586}
2587
2588fn code_frequency(dictionary: &GlobalDictionary) -> FrequencySummary {
2589 let mut entries = dictionary
2590 .counts
2591 .iter()
2592 .enumerate()
2593 .filter(|(_, count)| **count != 0)
2594 .map(|(code, &count)| FrequencyEntry { value: FrequencyValue::Code(code as u32), count })
2595 .collect::<Vec<_>>();
2596 if dictionary.nulls != 0 {
2597 entries.push(FrequencyEntry { value: FrequencyValue::Null, count: dictionary.nulls });
2598 }
2599 entries.sort_unstable_by(|left, right| {
2600 right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
2601 });
2602 let omitted_max = entries.get(FREQUENCY_ENTRIES).map_or(0, |entry| entry.count);
2603 entries.truncate(FREQUENCY_ENTRIES);
2604 FrequencySummary { entries, omitted_max, ordinals: Vec::new() }
2605}
2606
2607fn encode_directory(table: &Table) -> Result<Vec<u8>> {
2608 let mut out = DIRECTORY.to_vec();
2609 let name = table.name.as_bytes();
2610 put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("table name too long"))?);
2611 out.extend_from_slice(name);
2612 put_u16(&mut out, u16::try_from(table.fields.len()).map_err(|_| invalid("too many columns"))?);
2613 for field in &table.fields {
2614 let name = field.name.as_bytes();
2615 put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("column name too long"))?);
2616 out.extend_from_slice(name);
2617 out.push(type_tag(&field.ty)?);
2618 out.push(u8::from(field.not_null));
2619 }
2620 for dictionary in &table.dictionaries {
2621 match dictionary {
2622 None => out.push(0),
2623 Some(page) => {
2624 out.push(1);
2625 put_u64(&mut out, page.offset);
2626 put_u32(&mut out, page.length);
2627 put_u64(&mut out, page.hash);
2628 }
2629 }
2630 }
2631 put_u64(&mut out, u64::try_from(table.rows).map_err(|_| invalid("row count overflow"))?);
2632 put_u32(&mut out, u32::try_from(table.stripes.len()).map_err(|_| invalid("too many stripes"))?);
2633 for stripe in &table.stripes {
2634 put_u32(
2635 &mut out,
2636 u32::try_from(stripe.parts.len()).map_err(|_| invalid("too many parts in a stripe"))?,
2637 );
2638 for &rows in &stripe.parts {
2639 put_u32(&mut out, rows);
2640 }
2641 put_u64(&mut out, stripe.index.offset);
2642 put_u32(&mut out, stripe.index.length);
2643 for page in &stripe.pages {
2644 put_u64(&mut out, page.offset);
2645 put_u32(&mut out, page.length);
2646 }
2647 for (field, membership) in table.fields.iter().zip(&stripe.memberships) {
2648 if field.ty != LogicalType::Varchar {
2649 continue;
2650 }
2651 let page =
2652 membership.ok_or_else(|| invalid("string page has no code membership index"))?;
2653 put_u64(&mut out, page.offset);
2654 put_u32(&mut out, page.length);
2655 put_u64(&mut out, page.hash);
2656 }
2657 for sieve in &stripe.sieves {
2658 match sieve {
2659 None => out.push(0),
2660 Some(page) => {
2661 out.push(1);
2662 put_u64(&mut out, page.offset);
2663 put_u32(&mut out, page.length);
2664 put_u64(&mut out, page.hash);
2665 }
2666 }
2667 }
2668 for range in stripe.zone.columns() {
2669 put_bound(&mut out, range.low.as_ref())?;
2670 put_bound(&mut out, range.high.as_ref())?;
2671 put_u32(
2672 &mut out,
2673 u32::try_from(range.nulls).map_err(|_| invalid("null count overflow"))?,
2674 );
2675 out.push(u8::from(range.exact));
2676 match range.sum {
2677 None => out.push(0),
2678 Some(total) => {
2679 out.push(1);
2680 out.extend_from_slice(&total.to_le_bytes());
2681 }
2682 }
2683 }
2684 }
2685 out.extend_from_slice(FREQUENCIES);
2686 put_u16(
2687 &mut out,
2688 u16::try_from(table.frequencies.len())
2689 .map_err(|_| invalid("too many frequency columns"))?,
2690 );
2691 for summary in &table.frequencies {
2692 let Some(summary) = summary else {
2693 out.push(0);
2694 continue;
2695 };
2696 out.push(1);
2697 put_u64(&mut out, summary.omitted_max);
2698 put_u32(
2699 &mut out,
2700 u32::try_from(summary.entries.len())
2701 .map_err(|_| invalid("too many frequency entries"))?,
2702 );
2703 for entry in &summary.entries {
2704 match entry.value {
2705 FrequencyValue::Null => out.push(0),
2706 FrequencyValue::Integer(value) => {
2707 out.push(1);
2708 out.extend_from_slice(&value.to_le_bytes());
2709 }
2710 FrequencyValue::Code(value) => {
2711 out.push(2);
2712 put_u32(&mut out, value);
2713 }
2714 }
2715 put_u64(&mut out, entry.count);
2716 }
2717 put_u32(
2718 &mut out,
2719 u32::try_from(summary.ordinals.len())
2720 .map_err(|_| invalid("too many frequency ordinals"))?,
2721 );
2722 let mut previous = 0_u64;
2723 for (at, &ordinal) in summary.ordinals.iter().enumerate() {
2724 let delta = if at == 0 {
2725 ordinal
2726 } else {
2727 ordinal
2728 .checked_sub(previous)
2729 .ok_or_else(|| invalid("frequency ordinals are not ordered"))?
2730 };
2731 if at != 0 && delta == 0 {
2732 return Err(invalid("frequency ordinals are not unique"));
2733 }
2734 put_var_u64(&mut out, delta);
2735 previous = ordinal;
2736 }
2737 }
2738 Ok(out)
2739}
2740
2741struct Cursor<'a> {
2742 bytes: &'a [u8],
2743 at: usize,
2744}
2745impl<'a> Cursor<'a> {
2746 fn take(&mut self, len: usize) -> Result<&'a [u8]> {
2747 let end = self.at.checked_add(len).ok_or_else(|| invalid("directory offset overflow"))?;
2748 let bytes =
2749 self.bytes.get(self.at..end).ok_or_else(|| invalid("directory is truncated"))?;
2750 self.at = end;
2751 Ok(bytes)
2752 }
2753 fn u8(&mut self) -> Result<u8> {
2754 Ok(self.take(1)?[0])
2755 }
2756 fn u16(&mut self) -> Result<u16> {
2757 Ok(u16::from_le_bytes(self.take(2)?.try_into().expect("two bytes")))
2758 }
2759 fn u32(&mut self) -> Result<u32> {
2760 Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("four bytes")))
2761 }
2762 fn u64(&mut self) -> Result<u64> {
2763 Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("eight bytes")))
2764 }
2765 fn var_u64(&mut self) -> Result<u64> {
2766 let mut value = 0_u64;
2767 for shift in (0..=63).step_by(7) {
2768 let byte = self.u8()?;
2769 let part = u64::from(byte & 0x7f);
2770 if shift == 63 && part > 1 {
2771 return Err(invalid("frequency ordinal varint overflows"));
2772 }
2773 value |= part << shift;
2774 if byte & 0x80 == 0 {
2775 return Ok(value);
2776 }
2777 }
2778 Err(invalid("frequency ordinal varint is too long"))
2779 }
2780 fn bound(&mut self) -> Result<Option<Bound>> {
2781 Ok(match self.u8()? {
2782 0 => None,
2783 1 => Some(Bound::Int(i128::from_le_bytes(
2784 self.take(16)?.try_into().expect("sixteen bytes"),
2785 ))),
2786 2 => Some(Bound::Real(f64::from_le_bytes(
2787 self.take(8)?.try_into().expect("eight bytes"),
2788 ))),
2789 3 => {
2790 let length = self.u32()? as usize;
2791 Some(Bound::Bytes(self.take(length)?.to_vec()))
2792 }
2793 _ => return Err(invalid("bound tag differs")),
2794 })
2795 }
2796 fn text(&mut self) -> Result<String> {
2797 let len = self.u16()? as usize;
2798 String::from_utf8(self.take(len)?.to_vec()).map_err(|_| invalid("name is not UTF-8"))
2799 }
2800}
2801
2802fn decode_directory(bytes: &[u8], size: u64) -> Result<Table> {
2803 let mut cur = Cursor { bytes, at: 0 };
2804 if cur.take(8)? != DIRECTORY {
2805 return Err(invalid("directory magic differs"));
2806 }
2807 let name = cur.text()?;
2808 let width = cur.u16()? as usize;
2809 let mut fields = Vec::with_capacity(width);
2810 for _ in 0..width {
2811 let name = cur.text()?;
2812 let ty = tag_type(cur.u8()?)?;
2813 let not_null = match cur.u8()? {
2814 0 => false,
2815 1 => true,
2816 _ => return Err(invalid("nullability flag differs")),
2817 };
2818 fields.push(Field { name, ty, not_null });
2819 }
2820 let mut dictionaries = Vec::with_capacity(width);
2821 for _ in 0..width {
2822 dictionaries.push(match cur.u8()? {
2823 0 => None,
2824 1 => {
2825 let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2826 let end = page
2827 .offset
2828 .checked_add(u64::from(page.length))
2829 .ok_or_else(|| invalid("dictionary page offset overflow"))?;
2830 if page.offset < HEADER || end > size {
2835 return Err(invalid("dictionary page range is outside the file"));
2836 }
2837 Some(page)
2838 }
2839 _ => return Err(invalid("dictionary page tag differs")),
2840 });
2841 }
2842 let rows = usize::try_from(cur.u64()?).map_err(|_| invalid("row count does not fit"))?;
2843 let count = cur.u32()? as usize;
2844 let mut stripes = Vec::with_capacity(count);
2845 let mut total = 0_usize;
2846 for _ in 0..count {
2847 let count = cur.u32()? as usize;
2848 if count == 0 || count > STRIPE_PARTS {
2849 return Err(invalid("stripe part count is outside its bound"));
2850 }
2851 let mut parts = Vec::with_capacity(count);
2852 let mut stripe_rows = 0_usize;
2853 for _ in 0..count {
2854 let rows = cur.u32()?;
2855 if rows == 0 {
2856 return Err(invalid("empty part"));
2857 }
2858 parts.push(rows);
2859 stripe_rows = stripe_rows
2860 .checked_add(rows as usize)
2861 .ok_or_else(|| invalid("stripe row count overflow"))?;
2862 }
2863 total =
2864 total.checked_add(stripe_rows).ok_or_else(|| invalid("stripe row count overflow"))?;
2865 let index = Span { offset: cur.u64()?, length: cur.u32()? };
2866 let section = index_section(count)?;
2867 let wanted = section
2868 .checked_mul(width)
2869 .and_then(|bytes| u32::try_from(bytes).ok())
2870 .ok_or_else(|| invalid("index page length overflow"))?;
2871 let end = index
2872 .offset
2873 .checked_add(u64::from(index.length))
2874 .ok_or_else(|| invalid("index page offset overflow"))?;
2875 if index.offset < HEADER || end > size || index.length != wanted {
2876 return Err(invalid("index page range is outside the file"));
2877 }
2878 let mut pages = Vec::with_capacity(width);
2879 for _ in 0..width {
2880 let offset = cur.u64()?;
2881 let length = cur.u32()?;
2882 let end = offset
2883 .checked_add(u64::from(length))
2884 .ok_or_else(|| invalid("page offset overflow"))?;
2885 if offset < HEADER || end > size || length as usize > MAX_PAGE {
2886 return Err(invalid("page range is outside the file"));
2887 }
2888 pages.push(Span { offset, length });
2889 }
2890 let mut memberships = vec![None; width];
2891 for (column, field) in fields.iter().enumerate() {
2892 if field.ty != LogicalType::Varchar {
2893 continue;
2894 }
2895 let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2896 let end = page
2897 .offset
2898 .checked_add(u64::from(page.length))
2899 .ok_or_else(|| invalid("membership page offset overflow"))?;
2900 if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
2901 return Err(invalid("membership page range is outside the file"));
2902 }
2903 memberships[column] = Some(page);
2904 }
2905 let mut sieves = vec![None; width];
2906 for sieve in sieves.iter_mut().take(width) {
2907 match cur.u8()? {
2908 0 => continue,
2909 1 => {}
2910 _ => return Err(invalid("a sieve page has an unknown tag")),
2911 }
2912 let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2913 let end = page
2914 .offset
2915 .checked_add(u64::from(page.length))
2916 .ok_or_else(|| invalid("sieve page offset overflow"))?;
2917 if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
2918 return Err(invalid("sieve page range is outside the file"));
2919 }
2920 *sieve = Some(page);
2921 }
2922 let mut ranges = Vec::with_capacity(width);
2923 for _ in 0..width {
2924 let low = cur.bound()?;
2925 let high = cur.bound()?;
2926 let nulls = cur.u32()? as usize;
2927 if nulls > stripe_rows {
2928 return Err(invalid("null count exceeds stripe rows"));
2929 }
2930 let exact = cur.u8()? != 0;
2931 let sum = match cur.u8()? {
2932 0 => None,
2933 1 => Some(i128::from_le_bytes(
2934 cur.take(16)?.try_into().map_err(|_| invalid("a stripe sum is truncated"))?,
2935 )),
2936 _ => return Err(invalid("a stripe sum has an unknown tag")),
2937 };
2938 ranges.push(Range { low, high, nulls, exact, sum });
2939 }
2940 stripes.push(Stripe {
2941 rows: stripe_rows,
2942 parts,
2943 index,
2944 pages,
2945 memberships,
2946 sieves,
2947 zone: Zone::from_ranges(ranges),
2948 });
2949 }
2950 if total != rows {
2951 return Err(invalid("table row count differs from stripes"));
2952 }
2953 let frequencies = if cur.at == bytes.len() {
2954 vec![None; width]
2955 } else {
2956 if cur.take(8)? != FREQUENCIES {
2957 return Err(invalid("directory extension magic differs"));
2958 }
2959 if cur.u16()? as usize != width {
2960 return Err(invalid("frequency column count differs"));
2961 }
2962 let mut frequencies = Vec::with_capacity(width);
2963 for field in &fields {
2964 let summary = match cur.u8()? {
2965 0 => None,
2966 1 => {
2967 let omitted_max = cur.u64()?;
2968 let count = cur.u32()? as usize;
2969 if count > FREQUENCY_ENTRIES {
2970 return Err(invalid("frequency entry count exceeds its bound"));
2971 }
2972 let mut entries = Vec::with_capacity(count);
2973 for _ in 0..count {
2975 let value = match cur.u8()? {
2976 0 => FrequencyValue::Null,
2977 1 => FrequencyValue::Integer(i128::from_le_bytes(
2978 cur.take(16)?.try_into().expect("sixteen bytes"),
2979 )),
2980 2 => FrequencyValue::Code(cur.u32()?),
2981 _ => return Err(invalid("frequency value tag differs")),
2982 };
2983 let valid = matches!(
2984 (&field.ty, value),
2985 (_, FrequencyValue::Null)
2986 | (LogicalType::Varchar, FrequencyValue::Code(_))
2987 | (
2988 LogicalType::TinyInt
2989 | LogicalType::SmallInt
2990 | LogicalType::Integer
2991 | LogicalType::BigInt
2992 | LogicalType::UTinyInt
2993 | LogicalType::USmallInt
2994 | LogicalType::UInteger
2995 | LogicalType::UBigInt
2996 | LogicalType::Date
2997 | LogicalType::Timestamp,
2998 FrequencyValue::Integer(_),
2999 )
3000 );
3001 if !valid {
3002 return Err(invalid("frequency value does not match its column"));
3003 }
3004 let count = cur.u64()?;
3005 if count == 0 || count > rows as u64 {
3006 return Err(invalid("frequency count is outside the table"));
3007 }
3008 entries.push(FrequencyEntry { value, count });
3009 }
3010 if entries.windows(2).any(|pair| pair[0].count < pair[1].count) {
3011 return Err(invalid("frequency entries are not descending"));
3012 }
3013 let ordinals = {
3014 let ordinal_count = cur.u32()? as usize;
3015 if ordinal_count > FREQUENCY_ORDINALS || ordinal_count > rows {
3016 return Err(invalid("frequency ordinal count exceeds its bound"));
3017 }
3018 let mut ordinals = Vec::with_capacity(ordinal_count);
3019 let mut previous = 0_u64;
3020 for at in 0..ordinal_count {
3021 let delta = cur.var_u64()?;
3022 if at != 0 && delta == 0 {
3023 return Err(invalid("frequency ordinals are not increasing"));
3024 }
3025 let ordinal = if at == 0 {
3026 delta
3027 } else {
3028 previous
3029 .checked_add(delta)
3030 .ok_or_else(|| invalid("frequency ordinal overflows"))?
3031 };
3032 if ordinal >= rows as u64 {
3033 return Err(invalid("frequency ordinal is outside the table"));
3034 }
3035 ordinals.push(ordinal);
3036 previous = ordinal;
3037 }
3038 ordinals
3039 };
3040 Some(FrequencySummary { entries, omitted_max, ordinals })
3041 }
3042 _ => return Err(invalid("frequency summary tag differs")),
3043 };
3044 frequencies.push(summary);
3045 }
3046 frequencies
3047 };
3048 if cur.at != bytes.len() {
3049 return Err(invalid("directory has trailing bytes"));
3050 }
3051 Ok(Table { name, fields, stripes, rows, dictionaries, frequencies })
3052}
3053
3054fn put_bound(out: &mut Vec<u8>, bound: Option<&Bound>) -> Result<()> {
3055 match bound {
3056 None => out.push(0),
3057 Some(Bound::Int(value)) => {
3058 out.push(1);
3059 out.extend_from_slice(&value.to_le_bytes());
3060 }
3061 Some(Bound::Real(value)) => {
3062 out.push(2);
3063 out.extend_from_slice(&value.to_le_bytes());
3064 }
3065 Some(Bound::Bytes(value)) => {
3066 out.push(3);
3067 put_u32(out, u32::try_from(value.len()).map_err(|_| invalid("bound length overflow"))?);
3068 out.extend_from_slice(value);
3069 }
3070 }
3071 Ok(())
3072}
3073
3074#[derive(Debug)]
3091struct Codes;
3092
3093impl chooser::Chooser for Codes {
3094 fn name(&self) -> &'static str {
3095 "codes"
3096 }
3097
3098 fn narrow_strings(
3099 &self,
3100 _values: &[&[u8]],
3101 offered: &[string::Kind],
3102 _depth: u8,
3103 ) -> Vec<string::Kind> {
3104 offered.to_vec()
3107 }
3108
3109 fn narrow_integers(
3110 &self,
3111 _values: &[i64],
3112 offered: &[integer::Kind],
3113 depth: u8,
3114 ) -> Vec<integer::Kind> {
3115 let keep: &[integer::Kind] = if depth == 0 {
3116 &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Rle]
3117 } else {
3118 &[integer::Kind::Constant, integer::Kind::Packed]
3119 };
3120 let narrowed: Vec<integer::Kind> =
3121 offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3122 if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3125 }
3126}
3127
3128#[derive(Debug)]
3138struct Fixed;
3139
3140impl chooser::Chooser for Fixed {
3141 fn name(&self) -> &'static str {
3142 "fixed"
3143 }
3144
3145 fn narrow_strings(
3146 &self,
3147 _values: &[&[u8]],
3148 offered: &[string::Kind],
3149 _depth: u8,
3150 ) -> Vec<string::Kind> {
3151 offered.to_vec()
3152 }
3153
3154 fn narrow_integers(
3155 &self,
3156 _values: &[i64],
3157 offered: &[integer::Kind],
3158 depth: u8,
3159 ) -> Vec<integer::Kind> {
3160 let keep: &[integer::Kind] = if depth == 0 {
3161 &[
3162 integer::Kind::Constant,
3163 integer::Kind::Packed,
3164 integer::Kind::Delta,
3165 integer::Kind::Rle,
3166 integer::Kind::Sparse,
3167 ]
3168 } else {
3169 &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Delta]
3170 };
3171 let narrowed: Vec<integer::Kind> =
3172 offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3173 if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3174 }
3175}
3176
3177fn widened(data: &Data) -> Option<Vec<i64>> {
3184 match data {
3185 Data::Int8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3186 Data::UInt8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3187 Data::Int16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3188 Data::UInt16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3189 Data::Int32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3190 Data::UInt32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3191 Data::Int64(values) => Some(values.to_vec()),
3192 _ => None,
3193 }
3194}
3195
3196fn narrowed(ty: &LogicalType, values: Vec<i64>) -> Result<Data> {
3201 fn fit<T: TryFrom<i64>>(values: &[i64]) -> Result<Vec<T>> {
3202 values
3203 .iter()
3204 .map(|value| T::try_from(*value).map_err(|_| invalid("page value is not of its type")))
3205 .collect()
3206 }
3207 Ok(match ty {
3208 LogicalType::TinyInt => Data::Int8(fit::<i8>(&values)?.into()),
3209 LogicalType::UTinyInt => Data::UInt8(fit::<u8>(&values)?.into()),
3210 LogicalType::SmallInt => Data::Int16(fit::<i16>(&values)?.into()),
3211 LogicalType::USmallInt => Data::UInt16(fit::<u16>(&values)?.into()),
3212 LogicalType::Integer | LogicalType::Date => Data::Int32(fit::<i32>(&values)?.into()),
3213 LogicalType::UInteger => Data::UInt32(fit::<u32>(&values)?.into()),
3214 LogicalType::BigInt | LogicalType::Timestamp => Data::Int64(values.into()),
3215 _ => return Err(invalid("cascade codec belongs to a page that is not integers")),
3216 })
3217}
3218
3219fn plain_width(ty: &LogicalType) -> Option<usize> {
3222 Some(match ty {
3223 LogicalType::TinyInt | LogicalType::UTinyInt => 1,
3224 LogicalType::SmallInt | LogicalType::USmallInt => 2,
3225 LogicalType::Integer | LogicalType::UInteger | LogicalType::Date => 4,
3226 LogicalType::BigInt | LogicalType::Timestamp => 8,
3227 _ => return None,
3228 })
3229}
3230
3231fn cascaded(
3237 flat: &Vector,
3238 ty: &LogicalType,
3239 packed: Option<&Packed<'_>>,
3240) -> Result<Option<Vec<u8>>> {
3241 let (Some(width), Some(data)) = (plain_width(ty), flat.data()) else { return Ok(None) };
3242 let Some(values) = widened(data) else { return Ok(None) };
3243 let plain = values.len().saturating_mul(width);
3244 let best = match packed {
3245 Some(packed) => plain.min(21 + size_of_val(packed.words())),
3247 None => plain,
3248 };
3249 let out = integer::encode_with(&values, &Fixed)?;
3250 Ok((out.len() < best).then_some(out))
3251}
3252
3253fn encoded_codes(codes: &[u32]) -> Result<Option<Vec<u8>>> {
3265 let wide: Vec<i64> = codes.iter().map(|code| i64::from(*code)).collect();
3266 let coded = integer::encode_with(&wide, &Codes)?;
3267 let plain = codes.len().saturating_mul(size_of::<u32>());
3268 Ok((coded.len() < plain).then_some(coded))
3269}
3270
3271fn encode(
3272 vector: &Vector,
3273 global: Option<&mut GlobalDictionary>,
3274) -> Result<(Vec<u8>, Option<Vec<u32>>)> {
3275 let ty = vector.logical_type();
3276 let flat = vector.flatten()?;
3278 let mut out = Vec::new();
3279 let mut global_codes = None;
3280 if let Some(global) = global {
3281 let mut codes = Vec::with_capacity(flat.len());
3282 for row in 0..flat.len() {
3283 let text = flat.text_at(row).unwrap_or("");
3284 let code = global.code(text)?;
3285 global.observe(code, flat.is_null_at(row))?;
3286 codes.push(code);
3287 }
3288 global_codes = Some(codes);
3289 }
3290 let membership = global_codes.as_deref().map(unique_codes);
3291 let dictionary = if global_codes.is_none() && ty == &LogicalType::Varchar {
3292 string_dictionary(&flat)?
3293 } else {
3294 None
3295 };
3296 let packed_vector = if dictionary.is_none() && global_codes.is_none() {
3297 Some(flat.bit_packed()?)
3298 } else {
3299 None
3300 };
3301 let packed = packed_vector.as_ref().and_then(Vector::packed_parts);
3302 let coded = match global_codes.as_deref() {
3303 Some(codes) => encoded_codes(codes)?,
3304 None => None,
3305 };
3306 let cascade = if dictionary.is_none() && global_codes.is_none() {
3310 cascaded(&flat, ty, packed.as_ref())?
3311 } else {
3312 None
3313 };
3314 out.push(if coded.is_some() {
3315 4
3316 } else if cascade.is_some() {
3317 5
3318 } else if global_codes.is_some() {
3319 3
3320 } else if dictionary.is_some() {
3321 1
3322 } else if packed.is_some() {
3323 2
3324 } else {
3325 0
3326 });
3327 let nulls = flat.validity();
3328 let flag = match nulls {
3329 Validity::AllValid => 0,
3330 Validity::AllInvalid => 1,
3331 Validity::Mask(_) => 2,
3332 };
3333 out.push(flag);
3334 if flag == 2 {
3335 for group in (0..vector.len()).step_by(8) {
3336 let mut bits = 0_u8;
3337 for bit in 0..8 {
3338 if group + bit < vector.len() && !flat.is_null_at(group + bit) {
3339 bits |= 1 << bit;
3340 }
3341 }
3342 out.push(bits);
3343 }
3344 }
3345 if let Some(coded) = coded {
3346 out.extend_from_slice(&coded);
3347 return Ok((out, membership));
3348 }
3349 if let Some(cascade) = cascade {
3350 out.extend_from_slice(&cascade);
3351 return Ok((out, membership));
3352 }
3353 if let Some(codes) = global_codes {
3354 for code in codes {
3355 put_u32(&mut out, code);
3356 }
3357 return Ok((out, membership));
3358 }
3359 if let Some(dictionary) = dictionary {
3360 out.extend_from_slice(&dictionary);
3361 return Ok((out, membership));
3362 }
3363 if let Some(packed) = packed {
3364 if packed.offset() != 0 {
3365 return Err(invalid("writer received a sliced packed vector"));
3366 }
3367 out.push(u8::try_from(packed.width()).map_err(|_| invalid("packed width overflow"))?);
3368 out.extend_from_slice(&packed.base().to_le_bytes());
3369 put_u32(
3370 &mut out,
3371 u32::try_from(packed.words().len()).map_err(|_| invalid("too many packed words"))?,
3372 );
3373 for word in packed.words() {
3374 put_u64(&mut out, *word);
3375 }
3376 return Ok((out, membership));
3377 }
3378 let data = flat.data().ok_or_else(|| invalid("scalar column did not flatten"))?;
3379 match (ty, data) {
3380 (LogicalType::TinyInt, Data::Int8(values)) => {
3381 for value in &**values {
3382 out.extend_from_slice(&value.to_le_bytes());
3383 }
3384 }
3385 (LogicalType::UTinyInt, Data::UInt8(values)) => {
3386 for value in &**values {
3387 out.extend_from_slice(&value.to_le_bytes());
3388 }
3389 }
3390 (LogicalType::SmallInt, Data::Int16(values)) => {
3391 for value in &**values {
3392 out.extend_from_slice(&value.to_le_bytes());
3393 }
3394 }
3395 (LogicalType::USmallInt, Data::UInt16(values)) => {
3396 for value in &**values {
3397 out.extend_from_slice(&value.to_le_bytes());
3398 }
3399 }
3400 (LogicalType::UInteger, Data::UInt32(values)) => {
3401 for value in &**values {
3402 out.extend_from_slice(&value.to_le_bytes());
3403 }
3404 }
3405 (LogicalType::UBigInt, Data::UInt64(values)) => {
3406 for value in &**values {
3407 out.extend_from_slice(&value.to_le_bytes());
3408 }
3409 }
3410 (LogicalType::Integer | LogicalType::Date, Data::Int32(values)) => {
3411 for value in &**values {
3412 out.extend_from_slice(&value.to_le_bytes());
3413 }
3414 }
3415 (LogicalType::BigInt | LogicalType::Timestamp, Data::Int64(values)) => {
3416 for value in &**values {
3417 out.extend_from_slice(&value.to_le_bytes());
3418 }
3419 }
3420 (LogicalType::Boolean, Data::Bool(values)) => {
3421 for value in &**values {
3422 out.push(u8::from(*value));
3423 }
3424 }
3425 (LogicalType::Varchar, Data::Varlen(values)) => {
3426 let mut bytes = Vec::new();
3427 put_u32(&mut out, 0);
3428 for row in 0..vector.len() {
3429 let value = values.bytes(row).ok_or_else(|| invalid("string view is invalid"))?;
3430 bytes.extend_from_slice(value);
3431 put_u32(
3432 &mut out,
3433 u32::try_from(bytes.len())
3434 .map_err(|_| invalid("string payload exceeds 4GiB"))?,
3435 );
3436 }
3437 out.extend_from_slice(&bytes);
3438 }
3439 _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
3440 }
3441 Ok((out, membership))
3442}
3443
3444fn put_varint(out: &mut Vec<u8>, mut value: u32) {
3445 while value >= 0x80 {
3446 out.push((value as u8 & 0x7f) | 0x80);
3447 value >>= 7;
3448 }
3449 out.push(value as u8);
3450}
3451
3452fn unique_codes(codes: &[u32]) -> Vec<u32> {
3454 let mut unique = codes.to_vec();
3455 unique.sort_unstable();
3456 unique.dedup();
3457 unique
3458}
3459
3460fn merged_codes(lists: Vec<Vec<u32>>) -> Vec<u32> {
3466 let mut lists = lists;
3467 while lists.len() > 1 {
3468 let mut next = Vec::with_capacity(lists.len().div_ceil(2));
3469 for pair in lists.chunks(2) {
3470 match pair {
3471 [left, right] => next.push(merged_pair(left, right)),
3472 [only] => next.push(only.clone()),
3473 _ => {}
3474 }
3475 }
3476 lists = next;
3477 }
3478 lists.pop().unwrap_or_default()
3479}
3480
3481fn merged_pair(left: &[u32], right: &[u32]) -> Vec<u32> {
3482 let mut out = Vec::with_capacity(left.len().saturating_add(right.len()));
3483 let mut at = 0;
3484 let mut to = 0;
3485 while at < left.len() && to < right.len() {
3486 match left[at].cmp(&right[to]) {
3487 Ordering::Less => {
3488 out.push(left[at]);
3489 at += 1;
3490 }
3491 Ordering::Greater => {
3492 out.push(right[to]);
3493 to += 1;
3494 }
3495 Ordering::Equal => {
3496 out.push(left[at]);
3497 at += 1;
3498 to += 1;
3499 }
3500 }
3501 }
3502 out.extend_from_slice(&left[at..]);
3503 out.extend_from_slice(&right[to..]);
3504 out
3505}
3506
3507fn merged_range(ranges: impl Iterator<Item = Range>) -> Range {
3512 let mut merged = Range::default();
3513 let mut first = true;
3514 for range in ranges {
3515 merged.nulls = merged.nulls.saturating_add(range.nulls);
3516 merged.sum = match (merged.sum.take(), range.sum) {
3520 (Some(held), Some(next)) if !first => held.checked_add(next),
3521 (_, next) if first => next,
3522 _ => None,
3523 };
3524 merged.exact = if first { range.exact } else { merged.exact && range.exact };
3525 if first {
3526 merged.low = range.low;
3527 merged.high = range.high;
3528 first = false;
3529 continue;
3530 }
3531 merged.low = match (merged.low.take(), range.low) {
3532 (Some(held), Some(next)) => Some(held.smaller(next)),
3533 _ => None,
3534 };
3535 merged.high = match (merged.high.take(), range.high) {
3536 (Some(held), Some(next)) => Some(held.larger(next)),
3537 _ => None,
3538 };
3539 }
3540 merged
3541}
3542
3543fn encode_sieves<'a>(sieves: impl Iterator<Item = &'a Option<Sieve>>) -> Result<Vec<u8>> {
3549 let held: Vec<&Option<Sieve>> = sieves.collect();
3550 let mut out = Vec::new();
3551 put_u32(
3552 &mut out,
3553 u32::try_from(held.len()).map_err(|_| invalid("too many parts in a stripe"))?,
3554 );
3555 for sieve in &held {
3556 let length = sieve.as_ref().map_or(0, Sieve::len);
3557 put_u32(&mut out, u32::try_from(length).map_err(|_| invalid("sieve length overflow"))?);
3558 }
3559 for sieve in held.into_iter().flatten() {
3561 out.extend_from_slice(&sieve.to_bytes());
3562 }
3563 Ok(out)
3564}
3565
3566fn decode_sieves(bytes: &[u8]) -> Result<Vec<Option<Sieve>>> {
3572 let parts = u32::from_le_bytes(
3573 bytes
3574 .get(..4)
3575 .ok_or_else(|| invalid("sieve page is truncated"))?
3576 .try_into()
3577 .map_err(|_| invalid("sieve page is truncated"))?,
3578 ) as usize;
3579 let mut lengths = Vec::with_capacity(parts);
3580 for part in 0..parts {
3581 let at = 4 + part * 4;
3582 let field = bytes.get(at..at + 4).ok_or_else(|| invalid("sieve page is truncated"))?;
3583 lengths.push(u32::from_le_bytes(
3584 field.try_into().map_err(|_| invalid("sieve page is truncated"))?,
3585 ) as usize);
3586 }
3587 let mut at = 4 + parts * 4;
3588 let mut out = Vec::with_capacity(parts);
3589 for length in lengths {
3590 if length == 0 {
3591 out.push(None);
3592 continue;
3593 }
3594 let end = at.checked_add(length).ok_or_else(|| invalid("sieve page is truncated"))?;
3595 let field = bytes.get(at..end).ok_or_else(|| invalid("sieve page is truncated"))?;
3596 out.push(Sieve::from_bytes(field));
3597 at = end;
3598 }
3599 if at != bytes.len() {
3600 return Err(invalid("sieve page has trailing bytes"));
3601 }
3602 Ok(out)
3603}
3604
3605fn encode_membership(unique: &[u32]) -> Vec<u8> {
3611 let mut out = Vec::with_capacity(unique.len().saturating_mul(2).saturating_add(5));
3612 put_varint(&mut out, u32::try_from(unique.len()).unwrap_or(u32::MAX));
3613 let mut previous = 0;
3614 for (at, &code) in unique.iter().enumerate() {
3615 put_varint(&mut out, if at == 0 { code } else { code - previous });
3616 previous = code;
3617 }
3618 out
3619}
3620
3621fn take_varint(bytes: &[u8], at: &mut usize) -> Result<u32> {
3622 let mut value = 0_u32;
3623 for shift in (0..35).step_by(7) {
3624 let byte = *bytes.get(*at).ok_or_else(|| invalid("membership varint is truncated"))?;
3625 *at += 1;
3626 let part = u32::from(byte & 0x7f);
3627 if shift == 28 && part > 0x0f {
3628 return Err(invalid("membership varint overflow"));
3629 }
3630 value = value
3631 .checked_add(
3632 part.checked_shl(shift).ok_or_else(|| invalid("membership varint overflow"))?,
3633 )
3634 .ok_or_else(|| invalid("membership varint overflow"))?;
3635 if byte & 0x80 == 0 {
3636 return Ok(value);
3637 }
3638 }
3639 Err(invalid("membership varint is too long"))
3640}
3641
3642fn decode_membership(bytes: &[u8]) -> Result<Vec<u32>> {
3643 let mut at = 0;
3644 let count = take_varint(bytes, &mut at)? as usize;
3645 let mut codes = Vec::with_capacity(count);
3646 let mut previous = 0_u32;
3647 for index in 0..count {
3648 let delta = take_varint(bytes, &mut at)?;
3649 let code = if index == 0 {
3650 delta
3651 } else {
3652 previous.checked_add(delta).ok_or_else(|| invalid("membership code overflow"))?
3653 };
3654 if index > 0 && code <= previous {
3655 return Err(invalid("membership codes are not increasing"));
3656 }
3657 codes.push(code);
3658 previous = code;
3659 }
3660 if at != bytes.len() {
3661 return Err(invalid("membership page has trailing bytes"));
3662 }
3663 Ok(codes)
3664}
3665
3666fn string_dictionary(vector: &Vector) -> Result<Option<Vec<u8>>> {
3667 let mut by_text = HashMap::new();
3668 let mut values = Vec::new();
3669 let mut codes = Vec::with_capacity(vector.len());
3670 let mut plain_bytes = 0_usize;
3671 for row in 0..vector.len() {
3672 let text = vector.text_at(row).unwrap_or("");
3673 plain_bytes = plain_bytes.saturating_add(text.len());
3674 let code = match by_text.get(text) {
3675 Some(&code) => code,
3676 None => {
3677 let code = u32::try_from(values.len())
3678 .map_err(|_| invalid("too many dictionary values"))?;
3679 by_text.insert(text, code);
3680 values.push(text);
3681 code
3682 }
3683 };
3684 codes.push(code);
3685 }
3686 let dictionary_bytes = values.iter().map(|value| value.len()).sum::<usize>();
3687 let encoded = 8_usize
3688 .saturating_add((values.len() + 1).saturating_mul(4))
3689 .saturating_add(dictionary_bytes)
3690 .saturating_add(codes.len().saturating_mul(4));
3691 let plain = (vector.len() + 1).saturating_mul(4).saturating_add(plain_bytes);
3692 if encoded >= plain {
3693 return Ok(None);
3694 }
3695 let mut out = Vec::with_capacity(encoded);
3696 put_u32(
3697 &mut out,
3698 u32::try_from(values.len()).map_err(|_| invalid("too many dictionary values"))?,
3699 );
3700 put_u32(
3701 &mut out,
3702 u32::try_from(dictionary_bytes).map_err(|_| invalid("dictionary payload exceeds 4GiB"))?,
3703 );
3704 let mut offset = 0_u32;
3705 put_u32(&mut out, offset);
3706 for value in &values {
3707 offset = offset
3708 .checked_add(
3709 u32::try_from(value.len()).map_err(|_| invalid("dictionary value is too long"))?,
3710 )
3711 .ok_or_else(|| invalid("dictionary payload exceeds 4GiB"))?;
3712 put_u32(&mut out, offset);
3713 }
3714 for value in values {
3715 out.extend_from_slice(value.as_bytes());
3716 }
3717 for code in codes {
3718 put_u32(&mut out, code);
3719 }
3720 Ok(Some(out))
3721}
3722
3723struct EncodedDictionary {
3724 index: Vec<u8>,
3725 ranks: Vec<u8>,
3726 payload: Vec<u8>,
3727}
3728
3729fn head(bytes: &[u8]) -> u64 {
3731 let mut word = [0; 8];
3732 let take = bytes.len().min(8);
3733 word[..take].copy_from_slice(&bytes[..take]);
3734 u64::from_be_bytes(word)
3735}
3736
3737fn rankings(dictionaries: &[Option<GlobalDictionary>]) -> Result<Vec<Vec<(u64, u32)>>> {
3745 let present =
3746 dictionaries.iter().enumerate().filter(|(_, held)| held.is_some()).map(|(at, _)| at);
3747 let present = present.collect::<Vec<_>>();
3748 let mut orders = vec![Vec::new(); dictionaries.len()];
3749 let workers = std::thread::available_parallelism()
3750 .map_or(1, usize::from)
3751 .min(MAX_FREQUENCY_WORKERS)
3752 .min(present.len());
3753 if workers <= 1 {
3754 for at in present {
3755 if let Some(dictionary) = &dictionaries[at] {
3756 orders[at] = dictionary.ranked();
3757 }
3758 }
3759 return Ok(orders);
3760 }
3761 let width = present.len().div_ceil(workers);
3762 let pieces = std::thread::scope(|scope| {
3763 present
3764 .chunks(width)
3765 .map(|columns| {
3766 scope.spawn(|| {
3767 columns
3768 .iter()
3769 .filter_map(|&at| dictionaries[at].as_ref().map(|held| (at, held.ranked())))
3770 .collect::<Vec<_>>()
3771 })
3772 })
3773 .collect::<Vec<_>>()
3774 .into_iter()
3775 .map(|handle| {
3776 handle.join().map_err(|_| Error::internal("a dictionary sort worker panicked"))
3777 })
3778 .collect::<Result<Vec<_>>>()
3779 })?;
3780 for piece in pieces {
3781 for (at, order) in piece {
3782 orders[at] = order;
3783 }
3784 }
3785 Ok(orders)
3786}
3787
3788fn encode_global_dictionary(
3789 dictionary: GlobalDictionary,
3790 order: &[(u64, u32)],
3791) -> Result<EncodedDictionary> {
3792 let values = dictionary.offsets.len() - 1;
3793 if order.len() != values {
3794 return Err(invalid("global dictionary order does not cover its values"));
3795 }
3796 let payload_len = dictionary.payload.len();
3797 let blocks = payload_len.div_ceil(TEXT_PAYLOAD_BLOCK);
3798 let ranks = encode_ranks(order);
3799 let rank_blocks = values.div_ceil(TEXT_RANK_BLOCK);
3800 let mut index = Vec::with_capacity(12 + (values + 1) * 4 + (blocks + rank_blocks) * 8);
3801 put_u32(
3802 &mut index,
3803 u32::try_from(values).map_err(|_| invalid("global dictionary has too many values"))?,
3804 );
3805 put_u32(&mut index, TEXT_PAYLOAD_BLOCK as u32);
3806 put_u32(
3807 &mut index,
3808 u32::try_from(blocks).map_err(|_| invalid("global dictionary has too many blocks"))?,
3809 );
3810 for offset in dictionary.offsets {
3811 put_u32(&mut index, offset);
3812 }
3813 for block in dictionary.payload.chunks(TEXT_PAYLOAD_BLOCK) {
3814 put_u64(&mut index, checksum(block));
3815 }
3816 for block in ranks.chunks(TEXT_RANK_BLOCK * RANK_ENTRY) {
3817 put_u64(&mut index, checksum(block));
3818 }
3819 Ok(EncodedDictionary { index, ranks, payload: dictionary.payload })
3820}
3821
3822fn encode_ranks(order: &[(u64, u32)]) -> Vec<u8> {
3829 let mut out = Vec::with_capacity(order.len() * RANK_ENTRY);
3830 for block in order.chunks(TEXT_RANK_BLOCK) {
3831 for &(head, _) in block {
3832 put_u64(&mut out, head);
3833 }
3834 for &(_, code) in block {
3835 put_u32(&mut out, code);
3836 }
3837 }
3838 out
3839}
3840
3841fn open_global_dictionary(file: Arc<File>, page: Page, ty: &LogicalType) -> Result<Vector> {
3842 if ty != &LogicalType::Varchar {
3843 return Err(invalid("global dictionary belongs to a non-string column"));
3844 }
3845 let mut header = [0; 12];
3846 read_at(&file, page.offset, &mut header)?;
3847 let count = u32::from_le_bytes(header[0..4].try_into().expect("four bytes")) as usize;
3848 let block_size = u32::from_le_bytes(header[4..8].try_into().expect("four bytes")) as usize;
3849 let blocks = u32::from_le_bytes(header[8..12].try_into().expect("four bytes")) as usize;
3850 if block_size != TEXT_PAYLOAD_BLOCK {
3851 return Err(invalid("global dictionary block width differs"));
3852 }
3853 let offset_len = (count + 1)
3854 .checked_mul(4)
3855 .ok_or_else(|| invalid("global dictionary offset count overflow"))?;
3856 let ranks = count;
3861 let rank_blocks = ranks.div_ceil(TEXT_RANK_BLOCK);
3862 let rank_len =
3863 ranks.checked_mul(RANK_ENTRY).ok_or_else(|| invalid("global dictionary rank overflow"))?;
3864 let hash_len = blocks
3865 .checked_add(rank_blocks)
3866 .and_then(|count| count.checked_mul(8))
3867 .ok_or_else(|| invalid("global dictionary block count overflow"))?;
3868 let index_len = 12usize
3869 .checked_add(offset_len)
3870 .and_then(|len| len.checked_add(hash_len))
3871 .ok_or_else(|| invalid("global dictionary header overflow"))?;
3872 let body_len = index_len
3873 .checked_add(rank_len)
3874 .ok_or_else(|| invalid("global dictionary header overflow"))?;
3875 if body_len > page.length as usize {
3876 return Err(invalid("global dictionary offset index exceeds its page"));
3877 }
3878 let mut index = vec![0; index_len];
3879 index[..12].copy_from_slice(&header);
3880 read_at(&file, page.offset + 12, &mut index[12..])?;
3881 if checksum(&index) != page.hash {
3882 return Err(invalid("global dictionary index checksum differs"));
3883 }
3884 let offsets = index[12..12 + offset_len]
3885 .chunks_exact(4)
3886 .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
3887 .collect::<Vec<_>>();
3888 let mut hashes = index[12 + offset_len..]
3889 .chunks_exact(8)
3890 .map(|part| u64::from_le_bytes(part.try_into().expect("eight bytes")))
3891 .collect::<Vec<_>>();
3892 let rank_hashes = hashes.split_off(blocks);
3893 let payload_len = page.length as usize - body_len;
3894 if blocks != payload_len.div_ceil(TEXT_PAYLOAD_BLOCK) {
3895 return Err(invalid("global dictionary block count differs from its payload"));
3896 }
3897 if offsets.first() != Some(&0)
3898 || offsets.last().copied().map(|last| last as usize) != Some(payload_len)
3899 || offsets.windows(2).any(|pair| pair[0] > pair[1])
3900 {
3901 return Err(invalid("global dictionary offsets do not bound the payload"));
3902 }
3903 let payload_extents = (0..payload_len.div_ceil(TEXT_PAYLOAD_BLOCK * TEXT_PAYLOAD_EXTENT))
3904 .map(|_| OnceLock::new())
3905 .collect();
3906 let crossing = (0..count.div_ceil(TEXT_CROSSING_BLOCK)).map(|_| OnceLock::new()).collect();
3907 Vector::external_text(
3908 LogicalType::Varchar,
3909 Arc::new(NativeText {
3910 file,
3911 offsets,
3912 ranks,
3913 rank_at: page.offset + index_len as u64,
3914 rank_hashes,
3915 rank_blocks: (0..rank_blocks).map(|_| OnceLock::new()).collect(),
3916 payload: page.offset + body_len as u64,
3917 payload_len,
3918 hashes,
3919 payload_extents,
3920 crossing,
3921 }),
3922 )
3923}
3924
3925fn decode(
3926 ty: &LogicalType,
3927 rows: usize,
3928 bytes: &[u8],
3929 global: Option<Arc<Vector>>,
3930) -> Result<Vector> {
3931 let mut cur = Cursor { bytes, at: 0 };
3932 let codec = cur.u8()?;
3933 let flag = cur.u8()?;
3934 let validity = match flag {
3935 0 => Validity::AllValid,
3936 1 => Validity::AllInvalid,
3937 2 => {
3938 let mask = cur.take(rows.div_ceil(8))?;
3939 Validity::from_iter(rows, |row| mask[row / 8] >> (row % 8) & 1 == 1)
3940 }
3941 _ => return Err(invalid("page validity tag differs")),
3942 };
3943 if codec == 1 {
3944 if ty != &LogicalType::Varchar {
3945 return Err(invalid("dictionary codec belongs to a non-string page"));
3946 }
3947 let count = cur.u32()? as usize;
3948 let payload_len = cur.u32()? as usize;
3949 let offset_bytes = cur.take(
3950 (count + 1)
3951 .checked_mul(4)
3952 .ok_or_else(|| invalid("dictionary offset count overflow"))?,
3953 )?;
3954 let offsets = offset_bytes
3955 .chunks_exact(4)
3956 .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
3957 .collect::<Vec<_>>();
3958 let payload = cur.take(payload_len)?.to_vec();
3959 if offsets.first() != Some(&0)
3960 || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
3961 || offsets.windows(2).any(|pair| pair[0] > pair[1])
3962 {
3963 return Err(invalid("dictionary offsets do not bound the payload"));
3964 }
3965 let mut strings = StringColumn::over(Buffer::from_vec(payload));
3966 for pair in offsets.windows(2) {
3967 strings.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
3968 }
3969 let mut codes = Vec::with_capacity(rows);
3970 for _ in 0..rows {
3971 codes.push(cur.u32()?);
3972 }
3973 if codes.iter().any(|code| *code as usize >= count) {
3974 return Err(invalid("dictionary code is out of range"));
3975 }
3976 if cur.at != bytes.len() {
3977 return Err(invalid("dictionary page has trailing bytes"));
3978 }
3979 let dictionary = Vector::flat(LogicalType::Varchar, Data::Varlen(strings))?;
3980 return Ok(Vector::dictionary(codes, dictionary)?.with_validity(validity));
3981 }
3982 if codec == 3 || codec == 4 {
3983 let dictionary = global.ok_or_else(|| invalid("global code page has no dictionary"))?;
3984 let codes = if codec == 4 {
3985 let wide = integer::decode(&bytes[cur.at..])?;
3988 if wide.len() != rows {
3989 return Err(invalid("encoded code page holds the wrong number of rows"));
3990 }
3991 wide.into_iter()
3992 .map(|code| u32::try_from(code).map_err(|_| invalid("code is not a code")))
3993 .collect::<Result<Vec<u32>>>()?
3994 } else {
3995 let mut codes = Vec::with_capacity(rows);
3996 for _ in 0..rows {
3997 codes.push(cur.u32()?);
3998 }
3999 if cur.at != bytes.len() {
4000 return Err(invalid("global code page has trailing bytes"));
4001 }
4002 codes
4003 };
4004 let highest = codes.iter().copied().max();
4005 return Ok(Vector::stable_dictionary_validated(codes, dictionary, highest)?
4006 .with_validity(validity));
4007 }
4008 if codec == 5 {
4009 let values = integer::decode(&bytes[cur.at..])?;
4011 if values.len() != rows {
4012 return Err(invalid("cascade page holds the wrong number of rows"));
4013 }
4014 let data = narrowed(ty, values)?;
4015 return Ok(Vector::flat(ty.clone(), data)?.with_validity(validity));
4016 }
4017 if codec == 2 {
4018 let width = u32::from(cur.u8()?);
4019 let base = i128::from_le_bytes(cur.take(16)?.try_into().expect("sixteen bytes"));
4020 let count = cur.u32()? as usize;
4021 let mut words = Vec::with_capacity(count);
4022 for _ in 0..count {
4023 words.push(cur.u64()?);
4024 }
4025 if cur.at != bytes.len() {
4026 return Err(invalid("packed page has trailing bytes"));
4027 }
4028 return Ok(Vector::packed(ty.clone(), words, width, base, rows)?.with_validity(validity));
4029 }
4030 if codec != 0 {
4031 return Err(invalid("page codec is unknown"));
4032 }
4033 let data = match ty {
4034 LogicalType::TinyInt => {
4035 let values = cur.take(rows)?;
4036 Data::Int8(values.iter().map(|item| *item as i8).collect::<Vec<_>>().into())
4037 }
4038 LogicalType::UTinyInt => Data::UInt8(cur.take(rows)?.to_vec().into()),
4039 LogicalType::SmallInt => {
4040 let values =
4041 cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
4042 Data::Int16(
4043 values
4044 .chunks_exact(2)
4045 .map(|item| i16::from_le_bytes(item.try_into().expect("two bytes")))
4046 .collect::<Vec<_>>()
4047 .into(),
4048 )
4049 }
4050 LogicalType::USmallInt => {
4051 let values =
4052 cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
4053 Data::UInt16(
4054 values
4055 .chunks_exact(2)
4056 .map(|item| u16::from_le_bytes(item.try_into().expect("two bytes")))
4057 .collect::<Vec<_>>()
4058 .into(),
4059 )
4060 }
4061 LogicalType::UInteger => {
4062 let values =
4063 cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
4064 Data::UInt32(
4065 values
4066 .chunks_exact(4)
4067 .map(|item| u32::from_le_bytes(item.try_into().expect("four bytes")))
4068 .collect::<Vec<_>>()
4069 .into(),
4070 )
4071 }
4072 LogicalType::UBigInt => {
4073 let values =
4074 cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
4075 Data::UInt64(
4076 values
4077 .chunks_exact(8)
4078 .map(|item| u64::from_le_bytes(item.try_into().expect("eight bytes")))
4079 .collect::<Vec<_>>()
4080 .into(),
4081 )
4082 }
4083 LogicalType::Integer | LogicalType::Date => {
4084 let values =
4085 cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
4086 Data::Int32(
4087 values
4088 .chunks_exact(4)
4089 .map(|item| i32::from_le_bytes(item.try_into().expect("four bytes")))
4090 .collect::<Vec<_>>()
4091 .into(),
4092 )
4093 }
4094 LogicalType::BigInt | LogicalType::Timestamp => {
4095 let values =
4096 cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
4097 Data::Int64(
4098 values
4099 .chunks_exact(8)
4100 .map(|item| i64::from_le_bytes(item.try_into().expect("eight bytes")))
4101 .collect::<Vec<_>>()
4102 .into(),
4103 )
4104 }
4105 LogicalType::Boolean => {
4106 let values = cur.take(rows)?;
4107 if values.iter().any(|value| *value > 1) {
4108 return Err(invalid("boolean page has another value"));
4109 }
4110 Data::Bool(values.iter().map(|value| *value == 1).collect::<Vec<_>>().into())
4111 }
4112 LogicalType::Varchar => {
4113 let offset_bytes = cur
4114 .take((rows + 1).checked_mul(4).ok_or_else(|| invalid("offset count overflow"))?)?;
4115 let offsets = offset_bytes
4116 .chunks_exact(4)
4117 .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
4118 .collect::<Vec<_>>();
4119 let payload = cur.take(bytes.len() - cur.at)?.to_vec();
4120 if offsets.first() != Some(&0)
4121 || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
4122 || offsets.windows(2).any(|pair| pair[0] > pair[1])
4123 {
4124 return Err(invalid("string offsets do not bound the payload"));
4125 }
4126 let mut values = StringColumn::over(Buffer::from_vec(payload));
4127 for pair in offsets.windows(2) {
4128 values.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
4129 }
4130 Data::Varlen(values)
4131 }
4132 _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
4133 };
4134 if cur.at != bytes.len() {
4135 return Err(invalid("page has trailing bytes"));
4136 }
4137 Ok(Vector::flat(ty.clone(), data)?.with_validity(validity))
4138}
4139
4140#[cfg(test)]
4141mod tests {
4142 use std::fs;
4143 use std::io::{Seek, SeekFrom, Write};
4144 use std::path::PathBuf;
4145 use std::time::{SystemTime, UNIX_EPOCH};
4146
4147 use rudb_common::Value;
4148 use rudb_common::bounds::Op;
4149
4150 use super::*;
4151
4152 #[test]
4153 fn checksum_matches_fixed_vectors() {
4154 assert_eq!(checksum(b""), 0xef46_db37_51d8_e999);
4155 assert_eq!(checksum(b"a"), 0xd24e_c4f1_a98c_6e5b);
4156 assert_eq!(checksum(b"abc"), 0x44bc_2cf5_ad77_0999);
4157 }
4158
4159 fn path(label: &str) -> PathBuf {
4160 let stamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("time advances").as_nanos();
4161 std::env::temp_dir().join(format!("rudb-native-{label}-{}-{stamp}.rdb", std::process::id()))
4162 }
4163
4164 #[test]
4166 fn a_read_at_an_offset_ignores_where_another_thread_left_the_cursor() {
4167 const SPANS: usize = 64;
4168 const SPAN: usize = 512;
4169 let path = path("positional");
4170 let content: Vec<u8> =
4171 (0..SPANS).flat_map(|span| std::iter::repeat_n(span as u8, SPAN)).collect();
4172 fs::write(&path, &content).expect("the file is written");
4173 let file = Arc::new(File::open(&path).expect("the file opens"));
4174 std::thread::scope(|scope| {
4175 for _ in 0..8 {
4176 let file = Arc::clone(&file);
4177 scope.spawn(move || {
4178 for _ in 0..64 {
4179 for span in 0..SPANS {
4180 let mut bytes = [0_u8; SPAN];
4181 read_at(&file, (span * SPAN) as u64, &mut bytes)
4182 .expect("the span reads");
4183 assert!(
4184 bytes.iter().all(|byte| *byte == span as u8),
4185 "span {span} came back as {}",
4186 bytes[0],
4187 );
4188 }
4189 }
4190 });
4191 }
4192 });
4193 let mut past = [0_u8; SPAN];
4194 let end = (SPANS * SPAN) as u64;
4195 let error = read_at(&file, end, &mut past).expect_err("a read past the end is refused");
4196 assert!(error.message().contains("ends before its declared length"), "{error}");
4197 drop(file);
4198 let _ = fs::remove_file(&path);
4199 }
4200
4201 #[test]
4207 fn a_writer_puts_a_page_where_it_said_it_did_wherever_the_cursor_has_got_to() {
4208 let path = path("cursor");
4209 let mut writer = Writer::create(
4210 &path,
4211 "items",
4212 vec![
4213 Field::required("id", LogicalType::Integer),
4214 Field::new("text", LogicalType::Varchar),
4215 ],
4216 )
4217 .expect("new file");
4218 writer.append(&sample()).expect("first part");
4219 writer.file.seek(SeekFrom::Start(0)).expect("the cursor goes back to the header");
4220 writer.append(&sample()).expect("second part");
4221 writer.file.seek(SeekFrom::Start(1)).expect("and somewhere useless again");
4222 writer.finish().expect("commit");
4223 let reader = Reader::open(&path).expect("reopen from disk");
4224 assert_eq!(reader.table().rows(), 6);
4225 let ids = reader.read(0, &[0]).expect("the integer page reads back");
4226 assert_eq!(ids.value_at(0, 0), Value::Integer(4));
4227 assert_eq!(ids.value_at(2, 0), Value::Integer(-2));
4228 let text = reader.read(1, &[1]).expect("the text page reads back");
4229 assert_eq!(text.value_at(1, 0), Value::Null);
4230 assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4231 let end = reader.table().stripes().iter().flat_map(|stripe| {
4234 stripe
4235 .pages
4236 .iter()
4237 .map(|page| page.offset + u64::from(page.length))
4238 .chain(std::iter::once(stripe.index.offset + u64::from(stripe.index.length)))
4239 });
4240 let last = end.fold(HEADER, u64::max);
4241 let directory = fs::metadata(&path).expect("the file is there").len();
4242 assert!(last <= directory, "a page runs to {last} in a file of {directory} bytes");
4243 fs::remove_file(path).expect("remove scratch file");
4244 }
4245
4246 fn sample() -> Chunk {
4247 Chunk::new(vec![
4248 Vector::from_values(
4249 LogicalType::Integer,
4250 &[Value::Integer(4), Value::Integer(9), Value::Integer(-2)],
4251 )
4252 .expect("integers"),
4253 Vector::from_values(
4254 LogicalType::Varchar,
4255 &[
4256 Value::Varchar("alpha".into()),
4257 Value::Null,
4258 Value::Varchar("long text after a slash".into()),
4259 ],
4260 )
4261 .expect("strings"),
4262 ])
4263 .expect("matching rows")
4264 }
4265
4266 fn sample_ids() -> Chunk {
4267 Chunk::new(vec![
4268 Vector::flat(LogicalType::Integer, Data::Int32(vec![7, 8, 9].into()))
4269 .expect("integers"),
4270 ])
4271 .expect("one column")
4272 }
4273
4274 #[test]
4275 fn committed_file_reopens_and_reads_only_requested_columns() {
4276 let path = path("reopen");
4277 let mut writer = Writer::create(
4278 &path,
4279 "items",
4280 vec![
4281 Field::required("id", LogicalType::Integer),
4282 Field::new("text", LogicalType::Varchar),
4283 ],
4284 )
4285 .expect("new file");
4286 writer.append(&sample()).expect("first part");
4287 writer.append(&sample()).expect("second part");
4288 writer.finish().expect("commit");
4289 let reader = Reader::open(&path).expect("reopen from disk");
4290 assert_eq!(reader.table().rows(), 6);
4291 assert_eq!(reader.table().stripes().len(), 1);
4294 assert_eq!(reader.parts(), 2);
4295 assert_eq!(reader.part_rows(0), 3);
4296 assert_eq!(reader.part_rows(1), 3);
4297 let text = reader.read(1, &[1]).expect("only text page");
4298 assert_eq!(text.width(), 1);
4299 assert_eq!(text.value_at(1, 0), Value::Null);
4300 assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4301 let sparse = reader.read_sparse(1, &[1]).expect("one part without its whole page");
4302 assert_eq!(sparse.width(), 1);
4303 assert_eq!(sparse.value_at(1, 0), Value::Null);
4304 assert_eq!(sparse.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4305 assert!(!reader.skips_codes(0, 1, &[0]).expect("alpha is in the stripe"));
4306 assert!(!reader.skips_codes(0, 1, &[2]).expect("long text is in the stripe"));
4307 assert!(reader.skips_codes(0, 1, &[3]).expect("unknown code is absent"));
4308 let count = reader.read(0, &[]).expect("no page is needed for count");
4309 assert_eq!(count.len(), 3);
4310 assert!(reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }]));
4311 assert!(!reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(0) }]));
4312 let integers = reader.top_frequencies(0, 1).expect("valid integer synopsis").expect("kept");
4313 assert_eq!(
4314 integers,
4315 vec![(Value::Integer(-2), 2), (Value::Integer(4), 2), (Value::Integer(9), 2),]
4316 );
4317 let strings = reader.top_frequencies(1, 1).expect("valid string synopsis").expect("kept");
4318 assert_eq!(strings.len(), 3);
4319 assert!(strings.contains(&(Value::Null, 2)));
4320 assert!(strings.contains(&(Value::Varchar("alpha".into()), 2)));
4321 assert!(strings.contains(&(Value::Varchar("long text after a slash".into()), 2)));
4322 fs::remove_file(path).expect("remove scratch file");
4323 }
4324
4325 #[test]
4331 fn parts_past_the_stripe_bound_start_a_new_stripe() {
4332 let path = path("stripe-bound");
4333 let mut writer = Writer::create(
4334 &path,
4335 "items",
4336 vec![
4337 Field::required("id", LogicalType::Integer),
4338 Field::new("text", LogicalType::Varchar),
4339 ],
4340 )
4341 .expect("new file");
4342 let parts = STRIPE_PARTS * 2 + 3;
4343 for part in 0..parts {
4344 let id = part as i32;
4345 let chunk = Chunk::new(vec![
4346 Vector::from_values(
4347 LogicalType::Integer,
4348 &[Value::Integer(id), Value::Integer(-id)],
4349 )
4350 .expect("integers"),
4351 Vector::from_values(
4352 LogicalType::Varchar,
4353 &[Value::Varchar(format!("value {part}")), Value::Null],
4354 )
4355 .expect("strings"),
4356 ])
4357 .expect("matching rows");
4358 writer.append(&chunk).expect("one part");
4359 }
4360 writer.finish().expect("commit");
4361
4362 let reader = Reader::open(&path).expect("reopen from disk");
4363 assert_eq!(reader.parts(), parts);
4364 assert_eq!(reader.table().rows(), parts * 2);
4365 assert_eq!(reader.table().stripes().len(), parts.div_ceil(STRIPE_PARTS));
4366 assert_eq!(reader.table().stripes()[0].parts(), STRIPE_PARTS);
4367 assert_eq!(reader.table().stripes()[0].rows(), STRIPE_PARTS * 2);
4368 assert_eq!(reader.table().stripes()[2].parts(), 3);
4369 for part in (0..parts).rev() {
4372 let dense = reader.read(part, &[0, 1]).expect("a whole page read");
4373 let sparse = reader.read_sparse(part, &[0, 1]).expect("one part read");
4374 for chunk in [&dense, &sparse] {
4375 assert_eq!(chunk.len(), 2, "part {part} has its own row count");
4376 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4377 assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
4378 assert_eq!(chunk.value_at(0, 1), Value::Varchar(format!("value {part}")));
4379 assert_eq!(chunk.value_at(1, 1), Value::Null);
4380 }
4381 }
4382 let above = [Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }];
4385 assert!(reader.skips(0, &above), "the first stripe stops at 63");
4386 assert!(!reader.skips(STRIPE_PARTS * 2, &above), "the third stripe reaches 130");
4387 fs::remove_file(path).expect("remove scratch file");
4388 }
4389
4390 fn scattered(n: i64) -> i64 {
4392 n.wrapping_mul(-7_046_029_254_386_353_131)
4393 }
4394
4395 #[test]
4401 fn a_part_is_skipped_when_its_sieve_does_not_hold_the_constant() {
4402 let path = path("sieve-skip");
4403 let mut writer =
4404 Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
4405 .expect("new file");
4406 let parts = STRIPE_PARTS + 3;
4407 let per_part = 8;
4408 for part in 0..parts {
4409 let held: Vec<Value> = (0..per_part)
4410 .map(|row| Value::BigInt(scattered((part * per_part + row) as i64)))
4411 .collect();
4412 let chunk =
4413 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
4414 .expect("one column");
4415 writer.append(&chunk).expect("one part");
4416 }
4417 writer.finish().expect("commit");
4418
4419 let reader = Reader::open(&path).expect("reopen from disk");
4420 let probe = |value: i64| Probe {
4421 column: 0,
4422 op: Op::Equal,
4423 value: Bound::Int(i128::from(scattered(value))),
4424 };
4425 for wanted in [0_i64, 9, (parts * per_part - 1) as i64] {
4426 let tests = [probe(wanted)];
4427 let kept: Vec<usize> = (0..parts).filter(|&part| !reader.skips(part, &tests)).collect();
4428 let home = wanted as usize / per_part;
4429 assert_eq!(kept, vec![home], "only the part holding {wanted} is read");
4430 }
4431 let absent = [probe((parts * per_part) as i64 + 1)];
4432 assert!((0..parts).all(|part| reader.skips(part, &absent)), "no part holds it");
4433 let tests = [probe(0)];
4436 assert!(
4437 reader.table().stripes().iter().all(|stripe| !stripe.zone.skips(&tests)),
4438 "the bounds rule out no stripe at all"
4439 );
4440 fs::remove_file(path).expect("remove scratch file");
4441 }
4442
4443 #[test]
4449 fn a_damaged_sieve_page_is_read_through_rather_than_refused() {
4450 let path = path("sieve-damaged");
4451 let mut writer =
4452 Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
4453 .expect("new file");
4454 let held: Vec<Value> = (0..8).map(|row| Value::BigInt(scattered(row))).collect();
4455 let chunk =
4456 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
4457 .expect("one column");
4458 writer.append(&chunk).expect("one part");
4459 writer.finish().expect("commit");
4460
4461 let page =
4462 Reader::open(&path).expect("reopen").table.stripes[0].sieves[0].expect("a sieve page");
4463 let mut file = OpenOptions::new().write(true).open(&path).expect("open the sieve page");
4464 file.seek(SeekFrom::Start(page.offset + u64::from(page.length) - 1)).expect("seek");
4465 file.write_all(&[0xff]).expect("damage one byte");
4466 drop(file);
4467
4468 let reader = Reader::open(&path).expect("reopen the damaged file");
4469 let absent =
4470 [Probe { column: 0, op: Op::Equal, value: Bound::Int(i128::from(scattered(99))) }];
4471 assert!(!reader.skips(0, &absent), "a sieve that cannot be read skips nothing");
4472 assert_eq!(reader.read(0, &[0]).expect("the rows are untouched").len(), 8);
4473 fs::remove_file(path).expect("remove scratch file");
4474 }
4475
4476 #[test]
4487 fn workers_that_want_the_same_stripe_read_it_once() {
4488 let path = path("single-flight");
4489 let mut writer =
4490 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4491 .expect("new file");
4492 for part in 0..STRIPE_PARTS {
4493 let id = part as i32;
4494 let chunk = Chunk::new(vec![
4495 Vector::from_values(
4496 LogicalType::Integer,
4497 &[Value::Integer(id), Value::Integer(-id)],
4498 )
4499 .expect("integers"),
4500 ])
4501 .expect("matching rows");
4502 writer.append(&chunk).expect("one part");
4503 }
4504 writer.finish().expect("commit");
4505
4506 let reader = Reader::open(&path).expect("reopen from disk");
4507 assert_eq!(reader.table().stripes().len(), 1, "one stripe is the point of the test");
4508 let barrier = std::sync::Barrier::new(8);
4509 std::thread::scope(|scope| {
4510 for worker in 0..8 {
4511 let reader = &reader;
4512 let barrier = &barrier;
4513 scope.spawn(move || {
4514 barrier.wait();
4515 for part in (worker..STRIPE_PARTS).step_by(8) {
4516 let chunk = reader.read(part, &[0]).expect("a whole page read");
4517 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4518 assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
4519 }
4520 });
4521 }
4522 });
4523 assert_eq!(reader.pages.load(Atomic::Relaxed), 1, "one stripe, one page read, whoever won");
4524 fs::remove_file(path).expect("remove scratch file");
4525 }
4526
4527 #[test]
4540 fn opening_costs_the_same_over_a_thousand_times_the_rows() {
4541 let opened = |label: &str, rows_per_part: i32| {
4542 let path = path(label);
4543 let mut writer =
4544 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4545 .expect("new file");
4546 for part in 0..STRIPE_PARTS * 3 {
4547 let values = (0..rows_per_part)
4551 .map(|row| {
4552 Value::Integer((part as i32 * rows_per_part + row).wrapping_mul(2_654_435))
4553 })
4554 .collect::<Vec<_>>();
4555 let chunk = Chunk::new(vec![
4556 Vector::from_values(LogicalType::Integer, &values).expect("integers"),
4557 ])
4558 .expect("matching rows");
4559 writer.append(&chunk).expect("one part");
4560 }
4561 writer.finish().expect("commit");
4562 let reader = Reader::open(&path).expect("reopen from disk");
4563 let size = fs::metadata(&path).expect("the file is there").len();
4564 let out = (reader.reads(), reader.table().stripes().len(), size);
4565 fs::remove_file(path).expect("remove scratch file");
4566 out
4567 };
4568
4569 let (thin, thin_stripes, thin_size) = opened("open-thin", 1);
4570 let (fat, fat_stripes, fat_size) = opened("open-fat", 1000);
4571 assert_eq!(
4572 thin_stripes, fat_stripes,
4573 "the same stripe count is what makes this a fair ask"
4574 );
4575 assert!(
4576 fat_size > thin_size * 50,
4577 "the fat file has to actually be larger, and it is {fat_size} against {thin_size}"
4578 );
4579
4580 assert_eq!(thin.opening.reads, fat.opening.reads, "the same reads either way");
4581 assert_eq!(thin.pages, 0, "opening read a page");
4582 assert_eq!(fat.pages, 0, "opening read a page");
4583 assert_eq!(thin.indexes, 0, "opening read an index");
4584 assert_eq!(fat.indexes, 0, "opening read an index");
4585 assert!(
4588 fat.opening.bytes < thin.opening.bytes * 2,
4589 "opening the thin file read {} bytes and the fat one read {}",
4590 thin.opening.bytes,
4591 fat.opening.bytes
4592 );
4593 }
4594
4595 #[test]
4603 fn two_opens_of_one_file_cost_the_same_and_the_second_is_not_cheaper() {
4604 let path = path("open-twice");
4605 let mut writer =
4606 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4607 .expect("new file");
4608 for part in 0..STRIPE_PARTS * 3 {
4609 let chunk = Chunk::new(vec![
4610 Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
4611 .expect("integers"),
4612 ])
4613 .expect("matching rows");
4614 writer.append(&chunk).expect("one part");
4615 }
4616 writer.finish().expect("commit");
4617
4618 let first = Reader::open(&path).expect("open");
4619 for part in 0..first.parts() {
4622 first.read(part, &[0]).expect("a part");
4623 }
4624 assert!(first.reads().pages > 0, "the scan has to have read something");
4625 let second = Reader::open(&path).expect("open again");
4626
4627 assert_eq!(first.reads().opening, second.reads().opening);
4628 assert_eq!(
4629 second.reads().pages,
4630 0,
4631 "the second open read a page off the back of the first"
4632 );
4633 assert_eq!(second.reads().indexes, 0, "the second open read an index it inherited");
4634 fs::remove_file(path).expect("remove scratch file");
4635 }
4636
4637 #[test]
4645 fn an_index_is_read_once_per_stripe_however_often_the_page_is_evicted() {
4646 let path = path("index-cache");
4647 let mut writer =
4648 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4649 .expect("new file");
4650 let parts = STRIPE_PARTS * (CACHED_STRIPES_PER_COLUMN + 2);
4651 for part in 0..parts {
4652 let id = part as i32;
4653 let chunk = Chunk::new(vec![
4654 Vector::from_values(LogicalType::Integer, &[Value::Integer(id)]).expect("integers"),
4655 ])
4656 .expect("matching rows");
4657 writer.append(&chunk).expect("one part");
4658 }
4659 writer.finish().expect("commit");
4660
4661 let reader = Reader::open(&path).expect("reopen from disk");
4662 let stripes = reader.table().stripes().len();
4663 assert!(stripes > CACHED_STRIPES_PER_COLUMN, "the page cache has to be too small for this");
4664 for _ in 0..2 {
4666 for part in 0..parts {
4667 let chunk = reader.read(part, &[0]).expect("a part");
4668 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4669 }
4670 }
4671 assert_eq!(reader.indexes.load(Atomic::Relaxed), stripes, "one index read per stripe");
4672 assert!(
4673 reader.pages.load(Atomic::Relaxed) > stripes,
4674 "the pages are the ones that get read again, which is what makes the index count mean \
4675 something"
4676 );
4677 fs::remove_file(path).expect("remove scratch file");
4678 }
4679
4680 #[test]
4689 fn a_worker_per_stripe_reads_its_page_once_when_the_cache_was_told_to_expect_it() {
4690 let workers = CACHED_STRIPES_PER_COLUMN + 4;
4691 let path = path("stripe-per-worker");
4692 let mut writer =
4693 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4694 .expect("new file");
4695 for part in 0..STRIPE_PARTS * workers {
4696 let chunk = Chunk::new(vec![
4697 Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
4698 .expect("integers"),
4699 ])
4700 .expect("matching rows");
4701 writer.append(&chunk).expect("one part");
4702 }
4703 writer.finish().expect("commit");
4704
4705 let read = |told: bool| {
4706 let reader = Reader::open(&path).expect("reopen from disk");
4707 assert_eq!(reader.table().stripes().len(), workers, "a stripe per worker");
4708 if told {
4709 reader.keep_stripes(workers);
4710 }
4711 let barrier = std::sync::Barrier::new(workers);
4712 std::thread::scope(|scope| {
4713 for (worker, run) in reader.stripe_parts().into_iter().enumerate() {
4714 let reader = &reader;
4715 let barrier = &barrier;
4716 scope.spawn(move || {
4717 for part in run {
4718 barrier.wait();
4719 let chunk = reader.read(part, &[0]).expect("a part of my own stripe");
4720 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4721 }
4722 assert!(worker < workers);
4723 });
4724 }
4725 });
4726 reader.pages.load(Atomic::Relaxed)
4727 };
4728
4729 assert_eq!(read(true), workers, "one page read per stripe and no more");
4730 assert!(read(false) > workers, "a cache that small is read again on every part");
4731 fs::remove_file(path).expect("remove scratch file");
4732 }
4733
4734 #[test]
4739 fn a_damaged_index_page_is_an_error() {
4740 let path = path("damaged-index");
4741 let mut writer =
4742 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4743 .expect("new file");
4744 writer.append(&sample_ids()).expect("first part");
4745 writer.append(&sample_ids()).expect("second part");
4746 writer.finish().expect("commit");
4747
4748 let reader = Reader::open(&path).expect("valid directory");
4749 let index = reader.table.stripes[0].index;
4750 let mut byte = [0; 1];
4751 read_at(&reader.file, index.offset, &mut byte).expect("the first part length");
4752 let mut file = OpenOptions::new().write(true).open(&path).expect("open index page");
4753 file.seek(SeekFrom::Start(index.offset)).expect("index start");
4754 file.write_all(&[!byte[0]]).expect("damage the first part length");
4755 let error = reader.read(1, &[0]).expect_err("a damaged index must not be used");
4756 assert!(error.message().contains("index page section checksum differs"), "{error}");
4757 fs::remove_file(path).expect("remove scratch file");
4758 }
4759
4760 #[test]
4767 fn every_integer_width_round_trips_through_a_page() {
4768 let path = path("integer-widths");
4769 let columns = [
4770 (LogicalType::TinyInt, vec![Value::TinyInt(i8::MIN), Value::TinyInt(i8::MAX)]),
4771 (LogicalType::UTinyInt, vec![Value::UTinyInt(0), Value::UTinyInt(u8::MAX)]),
4772 (LogicalType::SmallInt, vec![Value::SmallInt(i16::MIN), Value::SmallInt(i16::MAX)]),
4773 (LogicalType::USmallInt, vec![Value::USmallInt(0), Value::USmallInt(u16::MAX)]),
4774 (LogicalType::Integer, vec![Value::Integer(i32::MIN), Value::Integer(i32::MAX)]),
4775 (LogicalType::UInteger, vec![Value::UInteger(0), Value::UInteger(u32::MAX)]),
4776 (LogicalType::BigInt, vec![Value::BigInt(i64::MIN), Value::BigInt(i64::MAX)]),
4777 (LogicalType::UBigInt, vec![Value::UBigInt(0), Value::UBigInt(u64::MAX)]),
4778 ];
4779 let fields = columns
4780 .iter()
4781 .enumerate()
4782 .map(|(at, (ty, _))| Field::required(format!("c{at}"), ty.clone()))
4783 .collect::<Vec<_>>();
4784 let vectors = columns
4785 .iter()
4786 .map(|(ty, values)| Vector::from_values(ty.clone(), values).expect("a vector"))
4787 .collect::<Vec<_>>();
4788 let mut writer = Writer::create(&path, "widths", fields).expect("new file");
4789 writer.append(&Chunk::new(vectors).expect("matching rows")).expect("one stripe");
4790 writer.finish().expect("commit");
4791
4792 let reader = Reader::open(&path).expect("reopen from disk");
4793 let wanted = (0..columns.len()).collect::<Vec<_>>();
4794 let read = reader.read(0, &wanted).expect("every column");
4795 assert_eq!(read.len(), 2);
4796 for (at, (ty, values)) in columns.iter().enumerate() {
4798 assert_eq!(read.value_at(0, at), values[0], "the low end of {ty}");
4799 assert_eq!(read.value_at(1, at), values[1], "the high end of {ty}");
4800 }
4801 fs::remove_file(path).expect("remove scratch file");
4802 }
4803
4804 #[test]
4805 fn numeric_frequency_candidates_keep_bounded_row_ordinals() {
4806 let path = path("frequency-ordinals");
4807 let mut writer =
4808 Writer::create(&path, "items", vec![Field::required("id", LogicalType::BigInt)])
4809 .expect("new file");
4810 let mut values = Vec::new();
4811 for leader in 0..10_i64 {
4812 values.extend(std::iter::repeat_n(leader, 100));
4813 }
4814 values.extend(1_000_i64..41_000);
4815 for part in values.chunks(1_024) {
4816 let vector = Vector::flat(LogicalType::BigInt, Data::Int64(part.to_vec().into()))
4817 .expect("big integers");
4818 writer.append(&Chunk::new(vec![vector]).expect("one column")).expect("one stripe");
4819 }
4820 writer.finish().expect("commit");
4821
4822 let reader = Reader::open(&path).expect("reopen from disk");
4823 let occurrences =
4824 reader.frequency_occurrences(0).expect("valid metadata").expect("bounded ordinals");
4825 assert!(occurrences.omitted_max < 100);
4826 assert!(occurrences.ordinals.len() <= FREQUENCY_ORDINALS);
4827 assert!(occurrences.ordinals.windows(2).all(|pair| pair[0] < pair[1]));
4828 assert_eq!(&occurrences.ordinals[..1_000], &(0_u64..1_000).collect::<Vec<_>>());
4829 fs::remove_file(path).expect("remove scratch file");
4830 }
4831
4832 #[test]
4838 fn a_file_from_another_format_says_which_format_it_is() {
4839 let older = path("older-format");
4840 let mut writer =
4841 Writer::create(&older, "items", vec![Field::new("id", LogicalType::Integer)])
4842 .expect("new file");
4843 let chunk = Chunk::new(vec![
4844 Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
4845 .expect("integers"),
4846 ])
4847 .expect("chunk");
4848 writer.append(&chunk).expect("page written");
4849 writer.finish().expect("commit");
4850
4851 let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
4852 file.seek(SeekFrom::Start(8)).expect("the version follows the magic");
4853 file.write_all(&(FORMAT - 1).to_le_bytes()).expect("write an older version");
4854 drop(file);
4855 let complaint = Reader::open(&older).expect_err("an older format is refused").to_string();
4856 assert!(complaint.contains(&format!("format {}", FORMAT - 1)), "{complaint}");
4857 assert!(complaint.contains(&format!("format {FORMAT}")), "{complaint}");
4858
4859 let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
4860 file.seek(SeekFrom::Start(0)).expect("the magic is first");
4861 file.write_all(b"NOTRUDB!").expect("write another engine's magic");
4862 drop(file);
4863 let complaint = Reader::open(&older).expect_err("a foreign file is refused").to_string();
4864 assert!(complaint.contains("magic"), "{complaint}");
4865 assert!(!complaint.contains("format"), "a version has nothing to do with it: {complaint}");
4866 fs::remove_file(older).expect("remove scratch file");
4867 }
4868
4869 #[test]
4870 fn an_unfinished_or_damaged_file_does_not_answer_with_partial_rows() {
4871 let unfinished = path("unfinished");
4872 let mut writer =
4873 Writer::create(&unfinished, "items", vec![Field::new("id", LogicalType::Integer)])
4874 .expect("new file");
4875 let chunk = Chunk::new(vec![
4876 Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
4877 .expect("integers"),
4878 ])
4879 .expect("chunk");
4880 writer.append(&chunk).expect("page written");
4881 drop(writer);
4882 assert!(Reader::open(&unfinished).is_err(), "no directory was committed");
4883 fs::remove_file(unfinished).expect("remove scratch file");
4884
4885 let damaged = path("damaged");
4886 let mut writer =
4887 Writer::create(&damaged, "items", vec![Field::new("id", LogicalType::Integer)])
4888 .expect("new file");
4889 writer.append(&chunk).expect("page written");
4890 writer.finish().expect("commit");
4891 let reader = Reader::open(&damaged).expect("valid directory");
4892 let mut file =
4893 OpenOptions::new().write(true).open(&damaged).expect("open for a damaged page");
4894 file.seek(SeekFrom::Start(HEADER + 1)).expect("inside first page");
4895 file.write_all(&[255]).expect("damage one byte");
4896 assert!(reader.read(0, &[0]).is_err(), "page checksum rejects corruption");
4897 fs::remove_file(damaged).expect("remove scratch file");
4898 }
4899
4900 #[test]
4901 fn damaged_lazy_dictionary_payload_is_an_error() {
4902 let path = path("damaged-dictionary");
4903 let mut writer = Writer::create(
4904 &path,
4905 "items",
4906 vec![
4907 Field::required("id", LogicalType::Integer),
4908 Field::new("text", LogicalType::Varchar),
4909 ],
4910 )
4911 .expect("new file");
4912 writer.append(&sample()).expect("stripe written");
4913 writer.finish().expect("commit");
4914
4915 let reader = Reader::open(&path).expect("valid directory");
4916 let dictionary = reader.table.dictionaries[1].expect("string dictionary page");
4917 let mut header = [0; 12];
4920 read_at(&reader.file, dictionary.offset, &mut header).expect("dictionary header");
4921 let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
4922 let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
4923 let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
4924 let index_len =
4925 12 + (count + 1) * 4 + (blocks + rank_blocks) * 8 + count * RANK_ENTRY as u64;
4926 let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
4927 file.seek(SeekFrom::Start(dictionary.offset + index_len))
4928 .expect("inside dictionary payload");
4929 file.write_all(&[255]).expect("damage dictionary payload");
4930
4931 let chunk = reader.read(0, &[1]).expect("code page and dictionary index remain valid");
4932 let error =
4933 chunk.validate_external().expect_err("payload corruption must reach the caller");
4934 assert!(error.message().contains("payload checksum differs"), "{error}");
4935 fs::remove_file(path).expect("remove scratch file");
4936 }
4937
4938 #[test]
4945 fn a_dictionary_over_one_extent_checks_every_block_of_it() {
4946 let path = path("dictionary-extents");
4947 let value =
4948 |row: usize| format!("{row:07} a value long enough to be worth a payload block");
4949 let parts = 30;
4950 let per_part = 1000;
4951 let mut writer =
4952 Writer::create(&path, "items", vec![Field::required("text", LogicalType::Varchar)])
4953 .expect("new file");
4954 for part in 0..parts {
4955 let values = (0..per_part)
4956 .map(|row| Value::Varchar(value(part * per_part + row)))
4957 .collect::<Vec<_>>();
4958 let chunk = Chunk::new(vec![
4959 Vector::from_values(LogicalType::Varchar, &values).expect("strings"),
4960 ])
4961 .expect("matching rows");
4962 writer.append(&chunk).expect("a part");
4963 }
4964 writer.finish().expect("commit");
4965
4966 let reader = Reader::open(&path).expect("reopen from disk");
4967 let dictionary = reader.table.dictionaries[0].expect("string dictionary page");
4968 assert!(
4969 dictionary.length as usize > TEXT_PAYLOAD_BLOCK * TEXT_PAYLOAD_EXTENT,
4970 "the dictionary has to be over one extent for this to be testing anything"
4971 );
4972 for part in [0, parts - 1] {
4973 let chunk = reader.read(part, &[0]).expect("a part");
4974 chunk.validate_external().expect("every payload block checks out");
4975 assert_eq!(chunk.value_at(0, 0), Value::Varchar(value(part * per_part)));
4976 }
4977
4978 let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
4979 file.seek(SeekFrom::Start(dictionary.offset + u64::from(dictionary.length) - 4))
4980 .expect("the last bytes of the page are payload");
4981 file.write_all(&[255]).expect("damage the last payload block");
4982 let reader = Reader::open(&path).expect("the directory and the index are untouched");
4983 let chunk = reader.read(parts - 1, &[0]).expect("the code page remains valid");
4984 let error = chunk.validate_external().expect_err("the damage must reach the caller");
4985 assert!(error.message().contains("payload checksum differs"), "{error}");
4986 fs::remove_file(path).expect("remove scratch file");
4987 }
4988
4989 #[test]
4994 fn a_damaged_sorted_order_is_an_error() {
4995 let path = path("damaged-order");
4996 let mut writer = Writer::create(
4997 &path,
4998 "items",
4999 vec![
5000 Field::required("id", LogicalType::Integer),
5001 Field::new("text", LogicalType::Varchar),
5002 ],
5003 )
5004 .expect("new file");
5005 writer.append(&sample()).expect("stripe written");
5006 writer.finish().expect("commit");
5007
5008 let reader = Reader::open(&path).expect("valid directory");
5009 let page = reader.table.dictionaries[1].expect("string dictionary page");
5010 let mut header = [0; 12];
5011 read_at(&reader.file, page.offset, &mut header).expect("dictionary header");
5012 let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
5013 let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
5014 let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
5015 let index_len = 12 + (count + 1) * 4 + (blocks + rank_blocks) * 8;
5016 let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
5017 file.seek(SeekFrom::Start(page.offset + index_len)).expect("the first head");
5018 file.write_all(&[255]).expect("damage the order");
5019
5020 let dictionary = reader.dictionary(1).expect("read").expect("a string column has one");
5021 let error = dictionary.compare_rank(0, b"anything").expect_err("a damaged order is caught");
5022 assert!(error.message().contains("rank checksum differs"), "{error}");
5023 fs::remove_file(path).expect("remove scratch file");
5024 }
5025
5026 #[test]
5030 fn a_global_dictionary_carries_the_sorted_order_of_its_values() {
5031 let spellings = ["overlong1z", "b", "", "overlong1a", "overlong", "ab", "a", "overlong1"];
5034 let path = path("dictionary-order");
5035 let mut writer =
5036 Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
5037 .expect("new file");
5038 writer
5039 .append(
5040 &Chunk::new(vec![
5041 Vector::from_values(
5042 LogicalType::Varchar,
5043 &spellings.map(|text| Value::Varchar(text.into())),
5044 )
5045 .expect("strings"),
5046 ])
5047 .expect("one column"),
5048 )
5049 .expect("stripe written");
5050 writer.finish().expect("commit");
5051
5052 let reader = Reader::open(&path).expect("valid directory");
5053 let dictionary = reader.dictionary(0).expect("read").expect("a string column has one");
5054 let count = dictionary.ranks().expect("a v10 file stores one");
5055 assert_eq!(count, spellings.len(), "every distinct value has a rank");
5056 let order = (0..count)
5057 .map(|rank| dictionary.code_at_rank(rank).expect("a code"))
5058 .collect::<Vec<_>>();
5059 let mut seen = order.clone();
5060 seen.sort_unstable();
5061 assert_eq!(seen, (0..spellings.len() as u32).collect::<Vec<_>>(), "a permutation of codes");
5062
5063 let ranked = order
5064 .iter()
5065 .map(|&code| {
5066 dictionary.try_bytes_at(code as usize).expect("read").expect("a value").to_vec()
5067 })
5068 .collect::<Vec<_>>();
5069 let mut expected = spellings.map(|text| text.as_bytes().to_vec()).to_vec();
5070 expected.sort();
5071 assert_eq!(ranked, expected, "rank order is value order");
5072
5073 for (rank, value) in expected.iter().enumerate() {
5076 assert_eq!(
5077 dictionary.compare_rank(rank, value).expect("compare"),
5078 Ordering::Equal,
5079 "rank {rank} is its own value"
5080 );
5081 if rank > 0 {
5082 assert_eq!(
5083 dictionary.compare_rank(rank - 1, value).expect("compare"),
5084 Ordering::Less,
5085 "rank {rank} follows the one before it"
5086 );
5087 }
5088 }
5089 fs::remove_file(path).expect("remove scratch file");
5090 }
5091
5092 #[test]
5093 fn damaged_membership_cannot_skip_a_string_page() {
5094 let path = path("damaged-membership");
5095 let mut writer = Writer::create(
5096 &path,
5097 "items",
5098 vec![
5099 Field::required("id", LogicalType::Integer),
5100 Field::new("text", LogicalType::Varchar),
5101 ],
5102 )
5103 .expect("new file");
5104 writer.append(&sample()).expect("stripe written");
5105 writer.finish().expect("commit");
5106
5107 let reader = Reader::open(&path).expect("valid directory");
5108 let membership = reader.table.stripes[0].memberships[1].expect("string membership");
5109 let mut file = OpenOptions::new().write(true).open(&path).expect("open membership page");
5110 file.seek(SeekFrom::Start(membership.offset)).expect("membership start");
5111 file.write_all(&[255]).expect("damage membership");
5112 let error = reader.skips_codes(0, 1, &[3]).expect_err("corruption must not skip rows");
5113 assert!(error.message().contains("membership page checksum differs"), "{error}");
5114 fs::remove_file(path).expect("remove scratch file");
5115 }
5116
5117 #[test]
5118 fn membership_delta_stream_is_sorted_exact_and_bounded() {
5119 let unique = unique_codes(&[900, 4, 4, 72, 9, u32::MAX]);
5120 assert_eq!(unique, [4, 9, 72, 900, u32::MAX]);
5121 let encoded = encode_membership(&unique);
5122 assert_eq!(
5123 decode_membership(&encoded).expect("valid membership"),
5124 [4, 9, 72, 900, u32::MAX]
5125 );
5126 let merged = merged_codes(vec![vec![4, 900], vec![9, 900, u32::MAX], vec![72]]);
5129 assert_eq!(merged, [4, 9, 72, 900, u32::MAX]);
5130 assert_eq!(
5131 decode_membership(&encode_membership(&merged)).expect("valid membership"),
5132 unique
5133 );
5134 assert!(decode_membership(&[1, 0x80]).is_err(), "a truncated varint is invalid");
5135 assert!(
5136 decode_membership(&[1, 0xff, 0xff, 0xff, 0xff, 0x10]).is_err(),
5137 "a value past u32 is invalid"
5138 );
5139 }
5140
5141 #[test]
5142 fn a_global_dictionary_may_be_larger_than_one_column_page() {
5143 let dictionary = Page {
5144 offset: HEADER,
5145 length: u32::try_from(MAX_PAGE + 1).expect("the page bound fits on disk"),
5146 hash: 0,
5147 };
5148 let table = Table {
5149 name: "items".to_owned(),
5150 fields: vec![Field::new("text", LogicalType::Varchar)],
5151 stripes: Vec::new(),
5152 rows: 0,
5153 dictionaries: vec![Some(dictionary)],
5154 frequencies: vec![None],
5155 };
5156 let directory = encode_directory(&table).expect("directory");
5157 let file_size = dictionary.offset + u64::from(dictionary.length) + 1;
5158
5159 let decoded = decode_directory(&directory, file_size).expect("large lazy dictionary");
5160 assert_eq!(decoded.dictionaries[0].expect("dictionary").length, dictionary.length);
5161 }
5162
5163 #[test]
5164 fn a_column_with_one_value_everywhere_costs_almost_nothing_a_row() {
5165 let path = path("constant-codes");
5166 let mut writer =
5167 Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
5168 .expect("new file");
5169 let empty = vec![Value::Varchar(String::new()); 1024];
5170 for _ in 0..4 {
5171 let column = Vector::from_values(LogicalType::Varchar, &empty).expect("strings");
5172 writer.append(&Chunk::new(vec![column]).expect("one column")).expect("a part");
5173 }
5174 writer.finish().expect("commit");
5175
5176 let reader = Reader::open(&path).expect("valid directory");
5177 let pages = reader.layout().columns.first().expect("one column").pages;
5178 assert!(pages < 256, "{pages} bytes of pages for 4,096 rows of one value");
5182 let read = reader.read(3, &[0]).expect("the last part back");
5183 assert_eq!(read.value_at(0, 0), Value::Varchar(String::new()));
5184 assert_eq!(read.value_at(1023, 0), Value::Varchar(String::new()));
5185 fs::remove_file(path).expect("remove scratch file");
5186 }
5187
5188 #[test]
5189 fn a_cascade_value_too_wide_for_its_column_is_refused_rather_than_cut() {
5190 let over = vec![i64::from(i32::MAX) + 1];
5193 let error = narrowed(&LogicalType::Integer, over).expect_err("a page that disagrees");
5194 assert!(format!("{error}").contains("not of its type"), "{error}");
5195 assert!(narrowed(&LogicalType::BigInt, vec![i64::MIN]).is_ok(), "bigint holds all of i64");
5196 assert!(narrowed(&LogicalType::Varchar, vec![0]).is_err(), "strings are not integers");
5197 }
5198
5199 #[test]
5200 fn a_code_stream_the_cascade_cannot_shrink_is_left_alone() {
5201 let mut state: u32 = 0x9e37_79b9;
5205 let spread: Vec<u32> = (0..1024)
5206 .map(|_| {
5207 state ^= state << 13;
5208 state ^= state >> 17;
5209 state ^= state << 5;
5210 state
5211 })
5212 .collect();
5213 assert_eq!(encoded_codes(&spread).expect("no failure"), None);
5214 let near: Vec<u32> = (0..1024).collect();
5215 let coded = encoded_codes(&near).expect("no failure").expect("counting up is packable");
5216 assert!(coded.len() < near.len() * 4, "{} bytes for a run of 1,024", coded.len());
5217 }
5218
5219 #[test]
5225 fn two_writes_of_the_same_rows_give_the_same_bytes() {
5226 fn written(path: &PathBuf) {
5227 let fields = (0..40)
5228 .map(|column| {
5229 let ty =
5230 if column % 4 == 0 { LogicalType::Varchar } else { LogicalType::BigInt };
5231 Field::new(format!("c{column}"), ty)
5232 })
5233 .collect::<Vec<_>>();
5234 let mut writer = Writer::create(path, "wide", fields).expect("new file");
5235 for part in 0..70_u64 {
5236 let columns = (0..40)
5237 .map(|column| {
5238 let values = (0..64_u64)
5239 .map(|row| {
5240 let seed = part.wrapping_mul(31).wrapping_add(row);
5241 if column % 4 == 0 {
5242 Value::Varchar(format!("v{}", seed % 17))
5243 } else {
5244 Value::BigInt(i64::try_from(seed % 97).expect("small"))
5245 }
5246 })
5247 .collect::<Vec<_>>();
5248 let ty = if column % 4 == 0 {
5249 LogicalType::Varchar
5250 } else {
5251 LogicalType::BigInt
5252 };
5253 Vector::from_values(ty, &values).expect("a column")
5254 })
5255 .collect::<Vec<_>>();
5256 writer.append(&Chunk::new(columns).expect("forty columns")).expect("a part");
5257 }
5258 writer.finish().expect("commit");
5259 }
5260
5261 let first = path("repeatable-one");
5262 let second = path("repeatable-two");
5263 written(&first);
5264 written(&second);
5265 let left = fs::read(&first).expect("the first file");
5266 let right = fs::read(&second).expect("the second file");
5267 assert_eq!(left.len(), right.len(), "two writes of the same rows differ in length");
5268 assert!(left == right, "two writes of the same rows differ in their bytes");
5269
5270 let reader = Reader::open(&first).expect("valid directory");
5273 assert_eq!(reader.table().rows(), 70 * 64);
5274 let read = reader.read(0, &[0, 1]).expect("the first part back");
5275 assert_eq!(read.value_at(0, 0), Value::Varchar("v0".to_owned()));
5276 assert_eq!(read.value_at(0, 1), Value::BigInt(0));
5277 fs::remove_file(first).expect("remove scratch file");
5278 fs::remove_file(second).expect("remove scratch file");
5279 }
5280}