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 = 32;
67
68const MAX_ENCODE_WORKERS: usize = 32;
75
76const SIEVE_BUDGET: usize = 8 * 1024;
82
83fn io(error: std::io::Error) -> Error {
84 Error::io(error.to_string())
85}
86
87fn invalid(message: &str) -> Error {
88 Error::invalid_input(format!("invalid rudb native file: {message}"))
89}
90
91fn sum(counts: impl Iterator<Item = u64>) -> u64 {
93 counts.fold(0, u64::saturating_add)
94}
95
96fn span_bytes(spans: &[Span], at: usize) -> u64 {
98 spans.get(at).map_or(0, |span| u64::from(span.length))
99}
100
101fn page_bytes(pages: &[Option<Page>], at: usize) -> u64 {
103 pages.get(at).and_then(Option::as_ref).map_or(0, Page::bytes)
104}
105
106fn checksum(bytes: &[u8]) -> u64 {
107 const P1: u64 = 11_400_714_785_074_694_791;
108 const P2: u64 = 14_029_467_366_897_019_727;
109 const P3: u64 = 1_609_587_929_392_839_161;
110 const P4: u64 = 9_650_029_242_287_828_579;
111 const P5: u64 = 2_870_177_450_012_600_261;
112 let round = |state: u64, word: u64| {
113 state.wrapping_add(word.wrapping_mul(P2)).rotate_left(31).wrapping_mul(P1)
114 };
115 let merge = |state: u64, lane: u64| (state ^ round(0, lane)).wrapping_mul(P1).wrapping_add(P4);
116 let word =
117 |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("eight checksum bytes"));
118
119 let mut at = 0;
120 let mut hash = if bytes.len() >= 32 {
121 let mut one = P1.wrapping_add(P2);
122 let mut two = P2;
123 let mut three = 0;
124 let mut four = 0_u64.wrapping_sub(P1);
125 while at + 32 <= bytes.len() {
126 one = round(one, word(at));
127 two = round(two, word(at + 8));
128 three = round(three, word(at + 16));
129 four = round(four, word(at + 24));
130 at += 32;
131 }
132 let combined = one
133 .rotate_left(1)
134 .wrapping_add(two.rotate_left(7))
135 .wrapping_add(three.rotate_left(12))
136 .wrapping_add(four.rotate_left(18));
137 merge(merge(merge(merge(combined, one), two), three), four)
138 } else {
139 P5
140 };
141 hash = hash.wrapping_add(bytes.len() as u64);
142 while at + 8 <= bytes.len() {
143 hash ^= round(0, word(at));
144 hash = hash.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
145 at += 8;
146 }
147 if at + 4 <= bytes.len() {
148 let tail = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four checksum bytes"));
149 hash ^= u64::from(tail).wrapping_mul(P1);
150 hash = hash.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
151 at += 4;
152 }
153 while at < bytes.len() {
154 hash ^= u64::from(bytes[at]).wrapping_mul(P5);
155 hash = hash.rotate_left(11).wrapping_mul(P1);
156 at += 1;
157 }
158 hash ^= hash >> 33;
159 hash = hash.wrapping_mul(P2);
160 hash ^= hash >> 29;
161 hash = hash.wrapping_mul(P3);
162 hash ^ (hash >> 32)
163}
164
165#[derive(Debug, Clone, Copy)]
166struct Slot {
167 offset: u64,
168 length: u32,
169 generation: u64,
170 hash: u64,
171}
172
173impl Slot {
174 fn bytes(self) -> [u8; SLOT_BYTES] {
175 let mut result = [0; SLOT_BYTES];
176 result[..8].copy_from_slice(&self.offset.to_le_bytes());
177 result[8..12].copy_from_slice(&self.length.to_le_bytes());
178 result[12..20].copy_from_slice(&self.generation.to_le_bytes());
179 result[20..28].copy_from_slice(&self.hash.to_le_bytes());
180 result
181 }
182
183 fn read(bytes: &[u8]) -> Self {
184 Self {
185 offset: u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")),
186 length: u32::from_le_bytes(bytes[8..12].try_into().expect("four bytes")),
187 generation: u64::from_le_bytes(bytes[12..20].try_into().expect("eight bytes")),
188 hash: u64::from_le_bytes(bytes[20..28].try_into().expect("eight bytes")),
189 }
190 }
191}
192
193#[derive(Debug, Clone, Copy)]
194struct Page {
195 offset: u64,
196 length: u32,
197 hash: u64,
198}
199
200impl Page {
201 fn bytes(&self) -> u64 {
203 u64::from(self.length)
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
208enum FrequencyValue {
209 Null,
210 Integer(i128),
211 Code(u32),
212}
213
214#[derive(Debug, Clone)]
215struct FrequencyEntry {
216 value: FrequencyValue,
217 count: u64,
218}
219
220#[derive(Debug, Clone)]
225struct FrequencySummary {
226 entries: Vec<FrequencyEntry>,
227 omitted_max: u64,
228 ordinals: Vec<u64>,
229}
230
231#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct FrequencyOccurrences {
234 pub omitted_max: u64,
236 pub ordinals: Vec<u64>,
238}
239
240#[derive(Debug, Clone, Copy, Default)]
247struct Span {
248 offset: u64,
249 length: u32,
250}
251
252#[derive(Debug, Clone)]
254pub struct Stripe {
255 rows: usize,
256 parts: Vec<u32>,
259 index: Span,
263 pages: Vec<Span>,
264 memberships: Vec<Option<Page>>,
265 sieves: Vec<Option<Page>>,
268 zone: Zone,
269}
270
271impl Stripe {
272 #[must_use]
274 pub fn rows(&self) -> usize {
275 self.rows
276 }
277
278 #[must_use]
280 pub fn parts(&self) -> usize {
281 self.parts.len()
282 }
283}
284
285#[derive(Debug, Clone)]
287pub struct Table {
288 name: String,
289 fields: Vec<Field>,
290 stripes: Vec<Stripe>,
291 rows: usize,
292 dictionaries: Vec<Option<Page>>,
293 frequencies: Vec<Option<FrequencySummary>>,
294}
295
296impl Table {
297 #[must_use]
299 pub fn name(&self) -> &str {
300 &self.name
301 }
302
303 #[must_use]
305 pub fn fields(&self) -> &[Field] {
306 &self.fields
307 }
308
309 #[must_use]
311 pub fn rows(&self) -> usize {
312 self.rows
313 }
314
315 #[must_use]
317 pub fn stripes(&self) -> &[Stripe] {
318 &self.stripes
319 }
320}
321
322#[derive(Debug, Clone)]
324pub struct ColumnLayout {
325 pub name: String,
327 pub kind: String,
329 pub pages: u64,
331 pub memberships: u64,
333 pub sieves: u64,
335 pub dictionary: u64,
337}
338
339impl ColumnLayout {
340 #[must_use]
342 pub fn total(&self) -> u64 {
343 self.pages
344 .saturating_add(self.memberships)
345 .saturating_add(self.sieves)
346 .saturating_add(self.dictionary)
347 }
348}
349
350#[derive(Debug, Clone)]
361pub struct Layout {
362 pub file: u64,
364 pub rows: usize,
366 pub stripes: usize,
368 pub parts: usize,
370 pub columns: Vec<ColumnLayout>,
372 pub indexes: u64,
375 pub directory: u64,
377 pub header: u64,
379}
380
381impl Layout {
382 #[must_use]
384 pub fn columns_total(&self) -> u64 {
385 self.columns.iter().map(ColumnLayout::total).fold(0, u64::saturating_add)
386 }
387
388 #[must_use]
394 pub fn unaccounted(&self) -> u64 {
395 self.file
396 .saturating_sub(self.columns_total())
397 .saturating_sub(self.indexes)
398 .saturating_sub(self.directory)
399 .saturating_sub(self.header)
400 }
401}
402
403#[derive(Debug)]
405struct GlobalDictionary {
406 primary: HashMap<u64, u32>,
407 collisions: HashMap<u64, Vec<u32>>,
408 offsets: Vec<u32>,
409 payload: Vec<u8>,
410 counts: Vec<u64>,
411 nulls: u64,
412}
413
414impl GlobalDictionary {
415 fn new() -> Self {
416 Self {
417 primary: HashMap::new(),
418 collisions: HashMap::new(),
419 offsets: vec![0],
420 payload: Vec::new(),
421 counts: Vec::new(),
422 nulls: 0,
423 }
424 }
425
426 fn bytes(&self, code: u32) -> Option<&[u8]> {
427 let start = *self.offsets.get(code as usize)? as usize;
428 let end = *self.offsets.get(code as usize + 1)? as usize;
429 self.payload.get(start..end)
430 }
431
432 fn code(&mut self, text: &str) -> Result<u32> {
433 let hash = checksum(text.as_bytes());
434 if let Some(&code) = self.primary.get(&hash) {
435 if self.bytes(code) == Some(text.as_bytes()) {
436 return Ok(code);
437 }
438 if let Some(codes) = self.collisions.get(&hash) {
439 if let Some(code) =
440 codes.iter().copied().find(|&code| self.bytes(code) == Some(text.as_bytes()))
441 {
442 return Ok(code);
443 }
444 }
445 let code = self.insert(text)?;
446 self.collisions.entry(hash).or_default().push(code);
447 return Ok(code);
448 }
449 let code = self.insert(text)?;
450 self.primary.insert(hash, code);
451 Ok(code)
452 }
453
454 fn insert(&mut self, text: &str) -> Result<u32> {
455 let code = u32::try_from(self.offsets.len() - 1)
456 .map_err(|_| invalid("global dictionary has too many values"))?;
457 self.payload.extend_from_slice(text.as_bytes());
458 self.offsets.push(
459 u32::try_from(self.payload.len())
460 .map_err(|_| invalid("global dictionary payload exceeds 4 GiB"))?,
461 );
462 self.counts.push(0);
463 Ok(code)
464 }
465
466 fn ranked(&self) -> Vec<(u64, u32)> {
486 let count = self.offsets.len() - 1;
487 let mut ranked = (0..count)
488 .map(|code| {
489 let code = code as u32;
490 (head(self.bytes(code).unwrap_or_default()), code)
491 })
492 .collect::<Vec<_>>();
493 ranked.sort_unstable_by(|left, right| {
494 left.0.cmp(&right.0).then_with(|| self.bytes(left.1).cmp(&self.bytes(right.1)))
495 });
496 ranked
497 }
498
499 fn observe(&mut self, code: u32, null: bool) -> Result<()> {
500 if null {
501 self.nulls = self.nulls.saturating_add(1);
502 return Ok(());
503 }
504 let count = self
505 .counts
506 .get_mut(code as usize)
507 .ok_or_else(|| invalid("global dictionary count code is out of range"))?;
508 *count = count.saturating_add(1);
509 Ok(())
510 }
511}
512
513#[derive(Debug)]
515pub struct Writer {
516 file: File,
517 at: u64,
525 table: Table,
526 generation: u64,
527 order: Vec<((u64, u64), (u64, u64))>,
530 next_order: u64,
531 dictionaries: Vec<Option<GlobalDictionary>>,
532 pending: Vec<PendingChunk>,
533}
534
535#[derive(Debug)]
543struct PendingChunk {
544 order: (u64, u64),
545 chunk: Chunk,
546}
547
548#[derive(Debug)]
554struct ColumnStripe {
555 pages: Vec<Vec<u8>>,
556 codes: Vec<Option<Vec<u32>>>,
557 sieves: Vec<Option<Sieve>>,
558 ranges: Vec<Range>,
559}
560
561fn weight(ty: &LogicalType) -> usize {
569 match ty {
570 LogicalType::Varchar | LogicalType::Blob => 64,
571 LogicalType::BigInt
572 | LogicalType::UBigInt
573 | LogicalType::Timestamp
574 | LogicalType::Double
575 | LogicalType::Decimal { .. } => 8,
576 LogicalType::Integer | LogicalType::UInteger | LogicalType::Date | LogicalType::Float => 4,
577 LogicalType::SmallInt | LogicalType::USmallInt => 2,
578 _ => 1,
579 }
580}
581
582pub const STRIPE_PARTS: usize = 64;
589
590const INDEX_ENTRY: usize = size_of::<u32>() + size_of::<u64>();
592
593fn index_section(parts: usize) -> Result<usize> {
595 parts
596 .checked_mul(INDEX_ENTRY)
597 .and_then(|bytes| bytes.checked_add(size_of::<u64>()))
598 .ok_or_else(|| invalid("index page length overflow"))
599}
600
601impl Writer {
602 pub fn create(
608 path: impl AsRef<Path>,
609 name: impl Into<String>,
610 fields: Vec<Field>,
611 ) -> Result<Self> {
612 for field in &fields {
613 type_tag(&field.ty)?;
614 }
615 let file =
616 OpenOptions::new().write(true).read(true).create_new(true).open(path).map_err(io)?;
617 let mut header = [0; HEADER as usize];
618 header[..8].copy_from_slice(MAGIC);
619 header[8..12].copy_from_slice(&FORMAT.to_le_bytes());
620 write_at(&file, 0, &header)?;
621 Ok(Self {
622 file,
623 at: HEADER,
624 dictionaries: fields
625 .iter()
626 .map(|field| (field.ty == LogicalType::Varchar).then(GlobalDictionary::new))
627 .collect(),
628 table: Table {
629 name: name.into(),
630 dictionaries: vec![None; fields.len()],
631 fields,
632 stripes: Vec::new(),
633 rows: 0,
634 frequencies: Vec::new(),
635 },
636 generation: 1,
637 order: Vec::new(),
638 next_order: 0,
639 pending: Vec::with_capacity(STRIPE_PARTS),
640 })
641 }
642
643 fn put(&mut self, bytes: &[u8]) -> Result<()> {
648 write_at(&self.file, self.at, bytes)?;
649 self.at = self
650 .at
651 .checked_add(bytes.len() as u64)
652 .ok_or_else(|| invalid("native file length overflow"))?;
653 Ok(())
654 }
655
656 pub fn append(&mut self, chunk: &Chunk) -> Result<()> {
662 let order = (self.next_order, 0);
663 self.next_order = self.next_order.saturating_add(1);
664 self.append_at(order, chunk)
665 }
666
667 pub fn append_at(&mut self, order: (u64, u64), chunk: &Chunk) -> Result<()> {
678 if chunk.is_empty() {
679 return Ok(());
680 }
681 self.admit(chunk)?;
682 if self.pending.last().is_some_and(|last| last.order > order) {
683 self.flush_pending()?;
684 }
685 self.pending.push(PendingChunk { order, chunk: chunk.clone() });
690 if self.pending.len() == STRIPE_PARTS {
691 self.flush_pending()?;
692 }
693 Ok(())
694 }
695
696 pub fn append_stripe(&mut self, parts: Vec<((u64, u64), Chunk)>) -> Result<()> {
712 if parts.len() > STRIPE_PARTS {
713 return Err(invalid("a stripe was handed more parts than it holds"));
714 }
715 self.flush_pending()?;
718 for (order, chunk) in parts {
719 if chunk.is_empty() {
720 continue;
721 }
722 self.admit(&chunk)?;
723 self.pending.push(PendingChunk { order, chunk });
724 }
725 self.flush_pending()
726 }
727
728 fn admit(&mut self, chunk: &Chunk) -> Result<()> {
730 if chunk.width() != self.table.fields.len() {
731 return Err(invalid("chunk width differs from table schema"));
732 }
733 for (index, field) in self.table.fields.iter().enumerate() {
734 if chunk.column(index)?.logical_type() != &field.ty {
735 return Err(invalid("chunk type differs from table schema"));
736 }
737 }
738 self.table.rows = self
739 .table
740 .rows
741 .checked_add(chunk.len())
742 .ok_or_else(|| invalid("row count overflow"))?;
743 Ok(())
744 }
745
746 fn encode_column(
754 index: usize,
755 held: &[PendingChunk],
756 mut dictionary: Option<&mut GlobalDictionary>,
757 ) -> Result<ColumnStripe> {
758 let mut stripe = ColumnStripe {
759 pages: Vec::with_capacity(held.len()),
760 codes: Vec::with_capacity(held.len()),
761 sieves: Vec::with_capacity(held.len()),
762 ranges: Vec::with_capacity(held.len()),
763 };
764 for pending in held {
765 let column = pending.chunk.column(index)?;
766 let (bytes, unique) = encode(column, dictionary.as_deref_mut())?;
767 if bytes.len() > MAX_PAGE {
768 return Err(invalid("column page exceeds the configured bound"));
769 }
770 let range = Range::of(column);
773 let sieve = match dictionary {
778 Some(_) => None,
779 None => Sieve::of(column, &range, SIEVE_BUDGET),
780 };
781 stripe.pages.push(bytes);
782 stripe.codes.push(unique);
783 stripe.sieves.push(sieve);
784 stripe.ranges.push(range);
785 }
786 Ok(stripe)
787 }
788
789 fn encode_columns(&mut self, held: &[PendingChunk]) -> Result<Vec<ColumnStripe>> {
798 let width = self.table.fields.len();
799 let workers = std::thread::available_parallelism()
800 .map_or(1, usize::from)
801 .min(MAX_ENCODE_WORKERS)
802 .min(width);
803 if workers <= 1 || held.len() <= 1 {
804 return self
805 .dictionaries
806 .iter_mut()
807 .enumerate()
808 .map(|(index, dictionary)| Self::encode_column(index, held, dictionary.as_mut()))
809 .collect();
810 }
811 let mut jobs: Vec<(usize, Option<GlobalDictionary>)> =
814 std::mem::take(&mut self.dictionaries).into_iter().enumerate().collect();
815 jobs.sort_by_key(|(index, _)| weight(&self.table.fields[*index].ty));
817 let queue = Mutex::new(jobs);
818 let pieces = std::thread::scope(|scope| {
819 (0..workers)
820 .map(|_| {
821 scope.spawn(|| {
822 let mut mine = Vec::new();
823 loop {
824 let taken = queue
825 .lock()
826 .map_err(|_| Error::internal("a native encode worker panicked"))?
827 .pop();
828 let Some((index, mut dictionary)) = taken else { break };
829 let encoded = Self::encode_column(index, held, dictionary.as_mut())?;
830 mine.push((index, dictionary, encoded));
831 }
832 Ok(mine)
833 })
834 })
835 .collect::<Vec<_>>()
836 .into_iter()
837 .map(|handle| {
838 handle.join().map_err(|_| Error::internal("a native encode worker panicked"))?
839 })
840 .collect::<Result<Vec<_>>>()
841 })?;
842 let mut dictionaries: Vec<Option<GlobalDictionary>> = (0..width).map(|_| None).collect();
843 let mut encoded: Vec<Option<ColumnStripe>> = (0..width).map(|_| None).collect();
844 for piece in pieces {
845 for (index, dictionary, stripe) in piece {
846 dictionaries[index] = dictionary;
847 encoded[index] = Some(stripe);
848 }
849 }
850 self.dictionaries = dictionaries;
851 encoded
852 .into_iter()
853 .map(|stripe| stripe.ok_or_else(|| Error::internal("a column was never encoded")))
854 .collect()
855 }
856
857 fn flush_pending(&mut self) -> Result<()> {
859 if self.pending.is_empty() {
860 return Ok(());
861 }
862 let width = self.table.fields.len();
863 let mut held = std::mem::take(&mut self.pending);
866 let parts = held.len();
867 let encoded = self.encode_columns(&held)?;
868 let mut pages = Vec::with_capacity(width);
869 let mut memberships = vec![None; width];
870 let mut ranges = Vec::with_capacity(width);
871 let mut index = Vec::with_capacity(width.saturating_mul(index_section(parts)?));
872 for stripe in &encoded {
873 let offset = self.at;
874 let section = index.len();
875 let mut length = 0_usize;
876 for bytes in &stripe.pages {
877 write_at(&self.file, self.at + length as u64, bytes)?;
878 put_u32(
879 &mut index,
880 u32::try_from(bytes.len()).map_err(|_| invalid("part length overflow"))?,
881 );
882 put_u64(&mut index, checksum(bytes));
883 length = length
884 .checked_add(bytes.len())
885 .ok_or_else(|| invalid("column page length overflow"))?;
886 }
887 let hash = checksum(&index[section..]);
888 put_u64(&mut index, hash);
889 if length > MAX_PAGE {
890 return Err(invalid("column page exceeds the configured bound"));
891 }
892 self.at = self
893 .at
894 .checked_add(length as u64)
895 .ok_or_else(|| invalid("native file length overflow"))?;
896 pages.push(Span {
897 offset,
898 length: u32::try_from(length).map_err(|_| invalid("page length overflow"))?,
899 });
900 ranges.push(merged_range(stripe.ranges.iter().cloned()));
901 }
902 for (membership, stripe) in memberships.iter_mut().zip(&encoded) {
903 if stripe.codes.iter().all(Option::is_none) {
904 continue;
905 }
906 let lists = stripe
907 .codes
908 .iter()
909 .map(|codes| codes.clone().unwrap_or_default())
910 .collect::<Vec<_>>();
911 let bytes = encode_membership(&merged_codes(lists));
912 let offset = self.at;
913 self.put(&bytes)?;
914 *membership = Some(Page {
915 offset,
916 length: u32::try_from(bytes.len())
917 .map_err(|_| invalid("membership page length overflow"))?,
918 hash: checksum(&bytes),
919 });
920 }
921 let mut sieves = vec![None; width];
922 for (page, stripe) in sieves.iter_mut().zip(&encoded) {
923 if stripe.sieves.iter().all(Option::is_none) {
924 continue;
925 }
926 let bytes = encode_sieves(stripe.sieves.iter())?;
927 let offset = self.at;
928 self.put(&bytes)?;
929 *page = Some(Page {
930 offset,
931 length: u32::try_from(bytes.len())
932 .map_err(|_| invalid("sieve page length overflow"))?,
933 hash: checksum(&bytes),
934 });
935 }
936 let offset = self.at;
937 self.put(&index)?;
938 let index = Span {
939 offset,
940 length: u32::try_from(index.len())
941 .map_err(|_| invalid("index page length overflow"))?,
942 };
943 let mut rows = 0_usize;
944 let mut lengths = Vec::with_capacity(parts);
945 let mut span = None;
946 for pending in held.drain(..) {
947 let part = pending.chunk.len();
948 rows = rows.checked_add(part).ok_or_else(|| invalid("row count overflow"))?;
949 lengths.push(u32::try_from(part).map_err(|_| invalid("part row count overflow"))?);
950 span = Some(
951 span.map_or((pending.order, pending.order), |(first, _)| (first, pending.order)),
952 );
953 }
954 self.order.push(span.ok_or_else(|| invalid("a stripe was flushed with no parts"))?);
955 self.table.stripes.push(Stripe {
956 rows,
957 parts: lengths,
958 index,
959 pages,
960 memberships,
961 sieves,
962 zone: Zone::from_ranges(ranges),
963 });
964 self.pending = held;
966 Ok(())
967 }
968
969 fn numeric_frequency(&self, column: usize) -> Result<Option<FrequencySummary>> {
973 let ty = &self.table.fields[column].ty;
974 if !matches!(
975 ty,
976 LogicalType::TinyInt
977 | LogicalType::SmallInt
978 | LogicalType::Integer
979 | LogicalType::BigInt
980 | LogicalType::UTinyInt
981 | LogicalType::USmallInt
982 | LogicalType::UInteger
983 | LogicalType::UBigInt
984 | LogicalType::Date
985 | LogicalType::Timestamp
986 ) {
987 return Ok(None);
988 }
989 let mut candidates: HashMap<FrequencyValue, u32> = HashMap::new();
990 let mut decrements = 0_u64;
991 self.visit_numeric(column, |_, value| {
992 if let Some(count) = candidates.get_mut(&value) {
993 *count = count.saturating_add(1);
994 } else if candidates.len() < FREQUENCY_CANDIDATES {
995 candidates.insert(value, 1);
996 } else {
997 candidates.retain(|_, count| {
998 *count -= 1;
999 *count != 0
1000 });
1001 decrements = decrements.saturating_add(1);
1002 }
1003 })?;
1004 let (exact, ordinals) = if decrements == 0 {
1005 (
1006 candidates
1007 .into_iter()
1008 .map(|(value, count)| (value, u64::from(count)))
1009 .collect::<HashMap<_, _>>(),
1010 Vec::new(),
1011 )
1012 } else {
1013 let mut lower = candidates.values().copied().collect::<Vec<_>>();
1014 lower.sort_unstable_by(|left, right| right.cmp(left));
1015 if lower.len() < FREQUENCY_BUILD_RANK
1016 || u64::from(lower[FREQUENCY_BUILD_RANK - 1]) <= decrements
1017 {
1018 return Ok(None);
1019 }
1020 let mut exact =
1021 candidates.into_keys().map(|value| (value, 0_u64)).collect::<HashMap<_, _>>();
1022 let mut ordinals = Vec::new();
1023 let mut exceeded = false;
1024 self.visit_numeric(column, |ordinal, value| {
1025 if let Some(count) = exact.get_mut(&value) {
1026 *count = count.saturating_add(1);
1027 if !exceeded {
1028 if ordinals.len() < FREQUENCY_ORDINALS {
1029 ordinals.push(ordinal);
1030 } else {
1031 ordinals.clear();
1032 exceeded = true;
1033 }
1034 }
1035 }
1036 })?;
1037 (exact, ordinals)
1038 };
1039 let mut entries = exact
1040 .into_iter()
1041 .map(|(value, count)| FrequencyEntry { value, count })
1042 .collect::<Vec<_>>();
1043 entries.sort_unstable_by(|left, right| {
1044 right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
1045 });
1046 let omitted_max =
1047 entries.get(FREQUENCY_ENTRIES).map_or(decrements, |entry| decrements.max(entry.count));
1048 entries.truncate(FREQUENCY_ENTRIES);
1049 Ok(Some(FrequencySummary { entries, omitted_max, ordinals }))
1050 }
1051
1052 fn visit_numeric(
1053 &self,
1054 column: usize,
1055 mut visit: impl FnMut(u64, FrequencyValue),
1056 ) -> Result<()> {
1057 let ty = &self.table.fields[column].ty;
1058 let mut start = 0_u64;
1059 for stripe in &self.table.stripes {
1060 let spans = read_index(&self.file, stripe, column)?;
1061 let page = stripe.pages[column];
1062 let mut bytes = vec![0; page.length as usize];
1063 read_at(&self.file, page.offset, &mut bytes)?;
1064 for (span, &rows) in spans.iter().zip(&stripe.parts) {
1065 let part = part_bytes(&bytes, *span)?;
1066 if checksum(part) != span.hash {
1067 return Err(invalid("column page checksum differs while building frequencies"));
1068 }
1069 let rows = rows as usize;
1070 let vector = decode(ty, rows, part, None)?;
1071 for row in 0..rows {
1073 let value = if vector.is_null_at(row) {
1074 FrequencyValue::Null
1075 } else {
1076 let widened = match vector.signed_at(row) {
1080 Some(value) => Some(value),
1081 None => match vector.value_at(row) {
1082 Value::UTinyInt(value) => Some(i128::from(value)),
1083 Value::USmallInt(value) => Some(i128::from(value)),
1084 Value::UInteger(value) => Some(i128::from(value)),
1085 Value::UBigInt(value) => Some(i128::from(value)),
1086 _ => None,
1087 },
1088 };
1089 FrequencyValue::Integer(widened.ok_or_else(|| {
1090 invalid("numeric frequency page did not contain an integer value")
1091 })?)
1092 };
1093 visit(start.saturating_add(row as u64), value);
1094 }
1095 start = start.saturating_add(rows as u64);
1096 }
1097 }
1098 Ok(())
1099 }
1100
1101 fn numeric_frequencies(&self) -> Result<Vec<Option<FrequencySummary>>> {
1109 let mut columns = self
1110 .table
1111 .fields
1112 .iter()
1113 .enumerate()
1114 .filter_map(|(column, field)| {
1115 matches!(
1116 field.ty,
1117 LogicalType::TinyInt
1118 | LogicalType::SmallInt
1119 | LogicalType::Integer
1120 | LogicalType::BigInt
1121 | LogicalType::UTinyInt
1122 | LogicalType::USmallInt
1123 | LogicalType::UInteger
1124 | LogicalType::UBigInt
1125 | LogicalType::Date
1126 | LogicalType::Timestamp
1127 )
1128 .then_some(column)
1129 })
1130 .collect::<Vec<_>>();
1131 let workers = std::thread::available_parallelism()
1132 .map_or(1, usize::from)
1133 .min(MAX_FREQUENCY_WORKERS)
1134 .min(columns.len());
1135 if workers <= 1 {
1136 let mut frequencies = vec![None; self.table.fields.len()];
1137 for column in columns {
1138 frequencies[column] = self.numeric_frequency(column)?;
1139 }
1140 return Ok(frequencies);
1141 }
1142 columns.sort_by_key(|&column| weight(&self.table.fields[column].ty));
1145 let queue = Mutex::new(columns);
1146 let pieces = std::thread::scope(|scope| {
1147 (0..workers)
1148 .map(|_| {
1149 scope.spawn(|| {
1150 let mut mine = Vec::new();
1151 loop {
1152 let taken = queue
1153 .lock()
1154 .map_err(|_| Error::internal("a native frequency worker panicked"))?
1155 .pop();
1156 let Some(column) = taken else { break };
1157 mine.push((column, self.numeric_frequency(column)?));
1158 }
1159 Ok(mine)
1160 })
1161 })
1162 .collect::<Vec<_>>()
1163 .into_iter()
1164 .map(|handle| {
1165 handle
1166 .join()
1167 .map_err(|_| Error::internal("a native frequency worker panicked"))?
1168 })
1169 .collect::<Result<Vec<_>>>()
1170 })?;
1171 let mut frequencies = vec![None; self.table.fields.len()];
1172 for piece in pieces {
1173 for (column, summary) in piece {
1174 frequencies[column] = summary;
1175 }
1176 }
1177 Ok(frequencies)
1178 }
1179
1180 pub fn finish(mut self) -> Result<Table> {
1186 self.flush_pending()?;
1187 let mut stripes = std::mem::take(&mut self.order)
1188 .into_iter()
1189 .zip(std::mem::take(&mut self.table.stripes))
1190 .collect::<Vec<_>>();
1191 stripes.sort_by_key(|(order, _)| order.0);
1192 let mut previous: Option<(u64, u64)> = None;
1193 for ((first, last), _) in &stripes {
1194 if previous.is_some_and(|previous| previous >= *first) {
1195 return Err(invalid("chunks did not arrive in source order"));
1196 }
1197 previous = Some(*last);
1198 }
1199 self.table.stripes = stripes.into_iter().map(|(_, stripe)| stripe).collect();
1200 self.table.frequencies = self.numeric_frequencies()?;
1201 let dictionaries = std::mem::take(&mut self.dictionaries);
1202 let orders = rankings(&dictionaries)?;
1203 for (index, (dictionary, order)) in dictionaries.into_iter().zip(orders).enumerate() {
1204 let Some(dictionary) = dictionary else { continue };
1205 self.table.frequencies[index] = Some(code_frequency(&dictionary));
1206 let encoded = encode_global_dictionary(dictionary, &order)?;
1207 let offset = self.at;
1208 self.put(&encoded.index)?;
1209 self.put(&encoded.ranks)?;
1210 self.put(&encoded.payload)?;
1211 let length = encoded
1212 .index
1213 .len()
1214 .checked_add(encoded.ranks.len())
1215 .and_then(|len| len.checked_add(encoded.payload.len()))
1216 .ok_or_else(|| invalid("dictionary page length overflow"))?;
1217 self.table.dictionaries[index] = Some(Page {
1218 offset,
1219 length: u32::try_from(length)
1220 .map_err(|_| invalid("dictionary page length overflow"))?,
1221 hash: checksum(&encoded.index),
1222 });
1223 }
1224 let directory = encode_directory(&self.table)?;
1225 if directory.len() > MAX_DIRECTORY {
1226 return Err(invalid("directory exceeds the configured bound"));
1227 }
1228 let offset = self.at;
1229 self.put(&directory)?;
1230 self.file.sync_all().map_err(io)?;
1231 let slot = Slot {
1232 offset,
1233 length: u32::try_from(directory.len())
1234 .map_err(|_| invalid("directory length overflow"))?,
1235 generation: self.generation,
1236 hash: checksum(&directory),
1237 };
1238 write_at(&self.file, 16, &slot.bytes())?;
1241 self.file.sync_all().map_err(io)?;
1242 Ok(self.table)
1243 }
1244}
1245
1246#[derive(Debug, Clone)]
1248pub struct Reader {
1249 file: Arc<File>,
1250 table: Arc<Table>,
1251 dictionaries: Arc<Vec<OnceLock<Arc<Vector>>>>,
1252 sieves: Arc<Vec<Vec<SieveSlot>>>,
1256 places: Arc<Vec<Place>>,
1258 cache: Arc<Vec<Mutex<Cached>>>,
1259 pages: Arc<AtomicUsize>,
1262 indexes: Arc<AtomicUsize>,
1265 kept: Arc<AtomicUsize>,
1268 size: u64,
1270 directory: u64,
1272 opening: Opening,
1274}
1275
1276#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1288pub struct Opening {
1289 pub reads: u32,
1292 pub bytes: u64,
1294}
1295
1296#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1298pub struct Reads {
1299 pub opening: Opening,
1301 pub pages: usize,
1303 pub indexes: usize,
1305}
1306
1307#[derive(Debug, Clone, Copy)]
1309struct Place {
1310 stripe: u32,
1311 part: u32,
1312 rows: u32,
1313}
1314
1315#[derive(Debug, Clone, Copy)]
1317struct PartSpan {
1318 start: usize,
1319 length: usize,
1320 hash: u64,
1321}
1322
1323#[derive(Debug, Clone)]
1329struct CachedColumn {
1330 stripe: usize,
1331 index: Arc<Vec<PartSpan>>,
1332 page: Option<Arc<Vec<u8>>>,
1333}
1334
1335#[derive(Debug, Default)]
1355struct Cached {
1356 pages: Vec<Option<Arc<Vec<u8>>>>,
1357 order: VecDeque<usize>,
1358 loading: Vec<usize>,
1359 index: Vec<Option<Arc<Vec<PartSpan>>>>,
1360}
1361
1362const CACHED_STRIPES_PER_COLUMN: usize = 4;
1374
1375type SieveSlot = OnceLock<Arc<Vec<Option<Sieve>>>>;
1377
1378type CrossingCache = OnceLock<Box<[OnceLock<Result<Vec<u8>>>]>>;
1379
1380#[derive(Debug)]
1381struct NativeText {
1382 file: Arc<File>,
1383 offsets: Vec<u32>,
1384 ranks: usize,
1386 rank_at: u64,
1390 rank_hashes: Vec<u64>,
1391 rank_blocks: Vec<OnceLock<Result<Vec<u8>>>>,
1392 code_ranks: OnceLock<Option<Vec<u32>>>,
1399 payload: u64,
1400 payload_len: usize,
1401 hashes: Vec<u64>,
1402 payload_extents: Vec<OnceLock<Result<Vec<u8>>>>,
1404 crossing: Vec<CrossingCache>,
1405}
1406
1407const TEXT_PAYLOAD_BLOCK: usize = 64 * 1024;
1408
1409const TEXT_PAYLOAD_EXTENT: usize = 8;
1430const TEXT_CROSSING_BLOCK: usize = 1024;
1431
1432const TEXT_RANK_BLOCK: usize = 512;
1442
1443const RANK_ENTRY: usize = size_of::<u64>() + size_of::<u32>();
1445
1446impl NativeText {
1447 fn payload_block(&self, block: usize) -> Result<Option<&[u8]>> {
1448 if block >= self.hashes.len() {
1449 return Ok(None);
1450 }
1451 let extent = block / TEXT_PAYLOAD_EXTENT;
1452 let Some(slot) = self.payload_extents.get(extent) else { return Ok(None) };
1453 let bytes = slot
1454 .get_or_init(|| {
1455 let start = extent
1456 .checked_mul(TEXT_PAYLOAD_EXTENT * TEXT_PAYLOAD_BLOCK)
1457 .ok_or_else(|| invalid("global dictionary block offset overflow"))?;
1458 let len = (TEXT_PAYLOAD_EXTENT * TEXT_PAYLOAD_BLOCK).min(
1459 self.payload_len
1460 .checked_sub(start)
1461 .ok_or_else(|| invalid("global dictionary block starts past payload"))?,
1462 );
1463 let mut bytes = vec![0; len];
1464 read_at(&self.file, self.payload + start as u64, &mut bytes)?;
1465 for (within, piece) in bytes.chunks(TEXT_PAYLOAD_BLOCK).enumerate() {
1468 if checksum(piece)
1469 != *self
1470 .hashes
1471 .get(extent * TEXT_PAYLOAD_EXTENT + within)
1472 .ok_or_else(|| invalid("global dictionary block has no checksum"))?
1473 {
1474 return Err(invalid("global dictionary payload checksum differs"));
1475 }
1476 }
1477 Ok(bytes)
1478 })
1479 .as_ref()
1480 .map_err(Clone::clone)?;
1481 let within = (block % TEXT_PAYLOAD_EXTENT) * TEXT_PAYLOAD_BLOCK;
1482 let end = (within + TEXT_PAYLOAD_BLOCK).min(bytes.len());
1483 Ok(bytes.get(within..end))
1484 }
1485
1486 fn rank_parts(&self, rank: usize) -> Result<(&[u8], usize)> {
1493 let slot = self
1494 .rank_blocks
1495 .get(rank / TEXT_RANK_BLOCK)
1496 .ok_or_else(|| invalid("global dictionary rank is past the order"))?;
1497 let block = slot
1498 .get_or_init(|| {
1499 let first = rank / TEXT_RANK_BLOCK * TEXT_RANK_BLOCK;
1500 let len = TEXT_RANK_BLOCK.min(self.ranks - first) * RANK_ENTRY;
1501 let mut bytes = vec![0; len];
1502 read_at(&self.file, self.rank_at + (first * RANK_ENTRY) as u64, &mut bytes)?;
1503 if checksum(&bytes)
1504 != *self
1505 .rank_hashes
1506 .get(rank / TEXT_RANK_BLOCK)
1507 .ok_or_else(|| invalid("global dictionary rank block has no checksum"))?
1508 {
1509 return Err(invalid("global dictionary rank checksum differs"));
1510 }
1511 Ok(bytes)
1512 })
1513 .as_ref()
1514 .map_err(Clone::clone)?;
1515 Ok((block.as_slice(), rank % TEXT_RANK_BLOCK))
1516 }
1517
1518 fn head_at(&self, rank: usize) -> Result<u64> {
1520 let (block, within) = self.rank_parts(rank)?;
1521 let at = within * size_of::<u64>();
1522 let bytes = block
1523 .get(at..at + size_of::<u64>())
1524 .ok_or_else(|| invalid("global dictionary rank block is short of heads"))?;
1525 Ok(u64::from_le_bytes(bytes.try_into().expect("eight bytes")))
1526 }
1527}
1528
1529impl TextSource for NativeText {
1530 fn len(&self) -> usize {
1531 self.offsets.len().saturating_sub(1)
1532 }
1533
1534 fn bytes_at(&self, index: usize) -> Result<Option<&[u8]>> {
1535 let (Some(&start), Some(&end)) = (self.offsets.get(index), self.offsets.get(index + 1))
1536 else {
1537 return Ok(None);
1538 };
1539 if start == end {
1540 return Ok(Some(&[]));
1541 }
1542 let first = start as usize / TEXT_PAYLOAD_BLOCK;
1543 let last = (end as usize - 1) / TEXT_PAYLOAD_BLOCK;
1544 if first == last {
1545 let Some(block) = self.payload_block(first)? else { return Ok(None) };
1546 let within = start as usize % TEXT_PAYLOAD_BLOCK;
1547 return Ok(block.get(within..within + (end - start) as usize));
1548 }
1549 let Some(crossing) = self.crossing.get(index / TEXT_CROSSING_BLOCK) else {
1550 return Ok(None);
1551 };
1552 let block = crossing.get_or_init(|| {
1553 (0..TEXT_CROSSING_BLOCK).map(|_| OnceLock::new()).collect::<Vec<_>>().into_boxed_slice()
1554 });
1555 block[index % TEXT_CROSSING_BLOCK]
1556 .get_or_init(|| {
1557 let mut bytes = Vec::with_capacity((end - start) as usize);
1558 for part in first..=last {
1559 let source = self
1560 .payload_block(part)?
1561 .ok_or_else(|| invalid("global dictionary block is missing"))?;
1562 let from = if part == first { start as usize % TEXT_PAYLOAD_BLOCK } else { 0 };
1563 let to = if part == last {
1564 (end as usize - 1) % TEXT_PAYLOAD_BLOCK + 1
1565 } else {
1566 source.len()
1567 };
1568 bytes.extend_from_slice(source.get(from..to).ok_or_else(|| {
1569 invalid("global dictionary value exceeds its payload block")
1570 })?);
1571 }
1572 Ok(bytes)
1573 })
1574 .as_ref()
1575 .map(|bytes| Some(bytes.as_slice()))
1576 .map_err(Clone::clone)
1577 }
1578
1579 fn bytes_len_at(&self, index: usize) -> Result<Option<usize>> {
1580 let (Some(&start), Some(&end)) = (self.offsets.get(index), self.offsets.get(index + 1))
1581 else {
1582 return Ok(None);
1583 };
1584 Ok(Some((end - start) as usize))
1585 }
1586
1587 fn ranks(&self) -> Option<usize> {
1588 (self.ranks > 0).then_some(self.ranks)
1589 }
1590
1591 fn compare_rank(&self, rank: usize, wanted: &[u8]) -> Result<Ordering> {
1592 let settled = self.head_at(rank)?.cmp(&head(wanted));
1596 if settled != Ordering::Equal {
1597 return Ok(settled);
1598 }
1599 let code = self.code_at_rank(rank)?;
1600 let bytes = self
1601 .bytes_at(code as usize)?
1602 .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
1603 Ok(bytes.cmp(wanted))
1604 }
1605
1606 fn code_at_rank(&self, rank: usize) -> Result<u32> {
1607 let (block, within) = self.rank_parts(rank)?;
1608 let heads = block.len() / RANK_ENTRY * size_of::<u64>();
1609 let at = heads + within * size_of::<u32>();
1610 let bytes = block
1611 .get(at..at + size_of::<u32>())
1612 .ok_or_else(|| invalid("global dictionary rank block is short of codes"))?;
1613 let code = u32::from_le_bytes(bytes.try_into().expect("four bytes"));
1614 if code as usize >= self.len() {
1615 return Err(invalid("global dictionary order names a code it does not have"));
1616 }
1617 Ok(code)
1618 }
1619
1620 fn code_ranks(&self) -> Option<&[u32]> {
1621 if self.ranks == 0 || self.ranks != self.len() {
1625 return None;
1626 }
1627 self.code_ranks
1628 .get_or_init(|| {
1629 let mut ranks = vec![u32::MAX; self.ranks];
1630 for first in (0..self.ranks).step_by(TEXT_RANK_BLOCK) {
1633 let (block, _) = self.rank_parts(first).ok()?;
1634 let heads = block.len() / RANK_ENTRY * size_of::<u64>();
1635 let codes = block.get(heads..)?;
1636 for (within, entry) in codes.chunks_exact(size_of::<u32>()).enumerate() {
1637 let code = u32::from_le_bytes(entry.try_into().ok()?) as usize;
1638 *ranks.get_mut(code)? = u32::try_from(first + within).ok()?;
1639 }
1640 }
1641 if ranks.contains(&u32::MAX) {
1642 return None;
1643 }
1644 Some(ranks)
1645 })
1646 .as_deref()
1647 }
1648
1649 fn footprint(&self) -> usize {
1650 self.offsets.capacity() * size_of::<u32>()
1651 + self
1652 .code_ranks
1653 .get()
1654 .and_then(Option::as_ref)
1655 .map_or(0, |ranks| ranks.capacity() * size_of::<u32>())
1656 + self.rank_hashes.capacity() * size_of::<u64>()
1657 + self.rank_blocks.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
1658 + self
1659 .rank_blocks
1660 .iter()
1661 .filter_map(OnceLock::get)
1662 .filter_map(|result| result.as_ref().ok())
1663 .map(Vec::capacity)
1664 .sum::<usize>()
1665 + self.payload_extents.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
1666 + self.hashes.capacity() * size_of::<u64>()
1667 + self
1668 .payload_extents
1669 .iter()
1670 .filter_map(OnceLock::get)
1671 .filter_map(|result| result.as_ref().ok())
1672 .map(Vec::capacity)
1673 .sum::<usize>()
1674 + self.crossing.capacity() * size_of::<CrossingCache>()
1675 + self
1676 .crossing
1677 .iter()
1678 .filter_map(OnceLock::get)
1679 .map(|block| {
1680 block.len() * size_of::<OnceLock<Result<Vec<u8>>>>()
1681 + block
1682 .iter()
1683 .filter_map(OnceLock::get)
1684 .filter_map(|result| result.as_ref().ok())
1685 .map(Vec::capacity)
1686 .sum::<usize>()
1687 })
1688 .sum::<usize>()
1689 }
1690}
1691
1692fn places(table: &Table) -> Result<Vec<Place>> {
1694 let mut places = Vec::with_capacity(table.stripes.len().saturating_mul(STRIPE_PARTS));
1695 for (at, stripe) in table.stripes.iter().enumerate() {
1696 let index = u32::try_from(at).map_err(|_| invalid("too many stripes"))?;
1697 for (part, &rows) in stripe.parts.iter().enumerate() {
1698 places.push(Place {
1699 stripe: index,
1700 part: u32::try_from(part).map_err(|_| invalid("too many parts in a stripe"))?,
1701 rows,
1702 });
1703 }
1704 }
1705 Ok(places)
1706}
1707
1708fn read_index(file: &File, stripe: &Stripe, column: usize) -> Result<Vec<PartSpan>> {
1713 let parts = stripe.parts.len();
1714 let section = index_section(parts)?;
1715 let at = column.checked_mul(section).ok_or_else(|| invalid("index page offset overflow"))?;
1716 let end = at.checked_add(section).ok_or_else(|| invalid("index page offset overflow"))?;
1717 if end > stripe.index.length as usize {
1718 return Err(invalid("index page is shorter than its columns"));
1719 }
1720 let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
1721 let mut bytes = vec![0; section];
1722 let offset = stripe
1723 .index
1724 .offset
1725 .checked_add(at as u64)
1726 .ok_or_else(|| invalid("index page offset overflow"))?;
1727 read_at(file, offset, &mut bytes)?;
1728 let entries = section - size_of::<u64>();
1729 let stored = u64::from_le_bytes(bytes[entries..].try_into().expect("eight bytes"));
1730 if checksum(&bytes[..entries]) != stored {
1731 return Err(invalid(&format!(
1734 "index page section checksum differs, column {column} of {parts} parts at {offset}, \
1735 wanted {stored:016x} and got {:016x}",
1736 checksum(&bytes[..entries]),
1737 )));
1738 }
1739 let mut spans = Vec::with_capacity(parts);
1740 let mut start = 0_usize;
1741 for part in 0..parts {
1742 let at = part * INDEX_ENTRY;
1743 let length = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes")) as usize;
1744 let hash = u64::from_le_bytes(bytes[at + 4..at + 12].try_into().expect("eight bytes"));
1745 spans.push(PartSpan { start, length, hash });
1746 start = start.checked_add(length).ok_or_else(|| invalid("column page length overflow"))?;
1747 }
1748 if start != page.length as usize {
1749 return Err(invalid("column page length differs from its index"));
1750 }
1751 Ok(spans)
1752}
1753
1754fn part_bytes(page: &[u8], span: PartSpan) -> Result<&[u8]> {
1756 let end = span.start.checked_add(span.length).ok_or_else(|| invalid("part range overflow"))?;
1757 page.get(span.start..end).ok_or_else(|| invalid("part exceeds its column page"))
1758}
1759
1760fn remember(cached: &mut Cached, held: &CachedColumn, kept: usize) {
1765 if let Some(slot) = cached.index.get_mut(held.stripe) {
1766 if slot.is_none() {
1767 *slot = Some(Arc::clone(&held.index));
1768 }
1769 }
1770 let Some(page) = held.page.clone() else { return };
1771 let Some(slot) = cached.pages.get_mut(held.stripe) else { return };
1772 if slot.is_none() {
1773 cached.order.push_back(held.stripe);
1774 }
1775 *slot = Some(page);
1776 while cached.order.len() > kept.max(1) {
1777 let Some(oldest) = cached.order.pop_front() else { break };
1778 if let Some(slot) = cached.pages.get_mut(oldest) {
1779 *slot = None;
1780 }
1781 }
1782}
1783
1784impl Reader {
1785 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
1791 let mut file = File::open(path).map_err(io)?;
1792 let size = file.metadata().map_err(io)?.len();
1793 if size < HEADER {
1794 return Err(invalid("file is shorter than its header"));
1795 }
1796 let mut header = [0; HEADER as usize];
1797 file.read_exact(&mut header).map_err(io)?;
1798 let mut opening = Opening { reads: 1, bytes: HEADER };
1799 let version = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
1800 if &header[..8] != MAGIC {
1805 return Err(invalid("the header does not begin with a rudb native magic"));
1806 }
1807 if version != FORMAT {
1808 return Err(invalid(&format!(
1809 "the file is format {version} and this build reads format {FORMAT}, so it has to \
1810 be written again"
1811 )));
1812 }
1813 let mut selected = None;
1814 for start in [16, 16 + SLOT_BYTES] {
1815 let slot = Slot::read(&header[start..start + SLOT_BYTES]);
1816 if slot.generation == 0 || slot.length == 0 || slot.length as usize > MAX_DIRECTORY {
1817 continue;
1818 }
1819 let Some(end) = slot.offset.checked_add(u64::from(slot.length)) else { continue };
1820 if slot.offset < HEADER || end > size {
1821 continue;
1822 }
1823 let mut bytes = vec![0; slot.length as usize];
1824 file.seek(SeekFrom::Start(slot.offset)).map_err(io)?;
1825 file.read_exact(&mut bytes).map_err(io)?;
1826 opening.reads += 1;
1827 opening.bytes += u64::from(slot.length);
1828 if checksum(&bytes) == slot.hash
1829 && selected
1830 .as_ref()
1831 .is_none_or(|(old, _): &(Slot, Vec<u8>)| old.generation < slot.generation)
1832 {
1833 selected = Some((slot, bytes));
1834 }
1835 }
1836 let (slot, bytes) =
1837 selected.ok_or_else(|| invalid("no committed directory slot is valid"))?;
1838 let table = decode_directory(&bytes, size)?;
1839 let places = places(&table)?;
1840 let dictionaries = (0..table.fields.len()).map(|_| OnceLock::new()).collect();
1841 let stripes = table.stripes.len();
1842 let cache = (0..table.fields.len())
1843 .map(|_| {
1844 Mutex::new(Cached {
1845 pages: (0..stripes).map(|_| None).collect(),
1846 index: (0..stripes).map(|_| None).collect(),
1847 ..Cached::default()
1848 })
1849 })
1850 .collect::<Vec<_>>();
1851 let sieves = (0..table.fields.len())
1852 .map(|_| table.stripes.iter().map(|_| OnceLock::new()).collect())
1853 .collect();
1854 Ok(Self {
1855 file: Arc::new(file),
1856 table: Arc::new(table),
1857 dictionaries: Arc::new(dictionaries),
1858 sieves: Arc::new(sieves),
1859 places: Arc::new(places),
1860 cache: Arc::new(cache),
1861 pages: Arc::new(AtomicUsize::new(0)),
1862 indexes: Arc::new(AtomicUsize::new(0)),
1863 kept: Arc::new(AtomicUsize::new(CACHED_STRIPES_PER_COLUMN)),
1864 size,
1865 directory: u64::from(slot.length),
1866 opening,
1867 })
1868 }
1869
1870 #[must_use]
1877 pub fn reads(&self) -> Reads {
1878 Reads {
1879 opening: self.opening,
1880 pages: self.pages.load(Atomic::Relaxed),
1881 indexes: self.indexes.load(Atomic::Relaxed),
1882 }
1883 }
1884
1885 #[must_use]
1890 pub fn layout(&self) -> Layout {
1891 let table = &self.table;
1892 let stripes = table.stripes.as_slice();
1893 let columns = table
1894 .fields
1895 .iter()
1896 .enumerate()
1897 .map(|(at, field)| ColumnLayout {
1898 name: field.name.clone(),
1899 kind: field.ty.to_string(),
1900 pages: sum(stripes.iter().map(|stripe| span_bytes(&stripe.pages, at))),
1901 memberships: sum(stripes.iter().map(|stripe| page_bytes(&stripe.memberships, at))),
1902 sieves: sum(stripes.iter().map(|stripe| page_bytes(&stripe.sieves, at))),
1903 dictionary: page_bytes(&table.dictionaries, at),
1904 })
1905 .collect();
1906 Layout {
1907 file: self.size,
1908 rows: table.rows,
1909 stripes: stripes.len(),
1910 parts: self.places.len(),
1911 columns,
1912 indexes: sum(stripes.iter().map(|stripe| u64::from(stripe.index.length))),
1913 directory: self.directory,
1914 header: HEADER,
1915 }
1916 }
1917
1918 #[must_use]
1920 pub fn parts(&self) -> usize {
1921 self.places.len()
1922 }
1923
1924 #[must_use]
1931 pub fn stripe_parts(&self) -> Vec<std::ops::Range<usize>> {
1932 let mut runs = Vec::with_capacity(self.table.stripes.len());
1933 let mut start = 0;
1934 for stripe in &self.table.stripes {
1935 let end = start + stripe.parts.len();
1936 runs.push(start..end);
1937 start = end;
1938 }
1939 runs
1940 }
1941
1942 pub fn keep_stripes(&self, stripes: usize) {
1949 self.kept.fetch_max(stripes, Atomic::Relaxed);
1950 }
1951
1952 #[must_use]
1954 pub fn part_rows(&self, at: usize) -> usize {
1955 self.places.get(at).map_or(0, |place| place.rows as usize)
1956 }
1957
1958 #[must_use]
1960 pub fn table(&self) -> &Table {
1961 &self.table
1962 }
1963
1964 pub fn top_frequencies(&self, column: usize, top: usize) -> Result<Option<Vec<(Value, u64)>>> {
1973 let field = self
1974 .table
1975 .fields
1976 .get(column)
1977 .ok_or_else(|| invalid("frequency column index out of range"))?;
1978 let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
1979 return Ok(None);
1980 };
1981 if top == 0 || summary.entries.len() < top {
1982 return Ok(None);
1983 }
1984 let boundary = summary.entries[top - 1].count;
1985 if boundary <= summary.omitted_max {
1986 return Ok(None);
1987 }
1988 self.decode_frequencies(column, &field.ty, &summary.entries).map(Some)
1989 }
1990
1991 pub fn exact_frequencies(&self, column: usize) -> Result<Option<Vec<(Value, u64)>>> {
2011 let field = self
2012 .table
2013 .fields
2014 .get(column)
2015 .ok_or_else(|| invalid("frequency column index out of range"))?;
2016 let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
2017 return Ok(None);
2018 };
2019 if summary.omitted_max > 0 {
2020 return Ok(None);
2021 }
2022 self.decode_frequencies(column, &field.ty, &summary.entries).map(Some)
2023 }
2024
2025 fn decode_frequencies(
2027 &self,
2028 column: usize,
2029 ty: &LogicalType,
2030 entries: &[FrequencyEntry],
2031 ) -> Result<Vec<(Value, u64)>> {
2032 let dictionary = if *ty == LogicalType::Varchar { self.dictionary(column)? } else { None };
2033 let mut out = Vec::with_capacity(entries.len());
2034 for entry in entries {
2035 let value = match entry.value {
2036 FrequencyValue::Null => Value::Null,
2037 FrequencyValue::Integer(value) => match *ty {
2038 LogicalType::TinyInt => Value::TinyInt(
2039 i8::try_from(value)
2040 .map_err(|_| invalid("frequency TINYINT is out of range"))?,
2041 ),
2042 LogicalType::UTinyInt => Value::UTinyInt(
2043 u8::try_from(value)
2044 .map_err(|_| invalid("frequency UTINYINT is out of range"))?,
2045 ),
2046 LogicalType::USmallInt => Value::USmallInt(
2047 u16::try_from(value)
2048 .map_err(|_| invalid("frequency USMALLINT is out of range"))?,
2049 ),
2050 LogicalType::UInteger => Value::UInteger(
2051 u32::try_from(value)
2052 .map_err(|_| invalid("frequency UINTEGER is out of range"))?,
2053 ),
2054 LogicalType::UBigInt => Value::UBigInt(
2055 u64::try_from(value)
2056 .map_err(|_| invalid("frequency UBIGINT is out of range"))?,
2057 ),
2058 LogicalType::SmallInt => Value::SmallInt(
2059 i16::try_from(value)
2060 .map_err(|_| invalid("frequency SMALLINT is out of range"))?,
2061 ),
2062 LogicalType::Integer => Value::Integer(
2063 i32::try_from(value)
2064 .map_err(|_| invalid("frequency INTEGER is out of range"))?,
2065 ),
2066 LogicalType::BigInt => Value::BigInt(
2067 i64::try_from(value)
2068 .map_err(|_| invalid("frequency BIGINT is out of range"))?,
2069 ),
2070 LogicalType::Date => Value::Date(
2071 i32::try_from(value)
2072 .map_err(|_| invalid("frequency DATE is out of range"))?,
2073 ),
2074 LogicalType::Timestamp => Value::Timestamp(
2075 i64::try_from(value)
2076 .map_err(|_| invalid("frequency TIMESTAMP is out of range"))?,
2077 ),
2078 _ => return Err(invalid("integer frequency belongs to another type")),
2079 },
2080 FrequencyValue::Code(code) => dictionary
2081 .as_ref()
2082 .ok_or_else(|| invalid("frequency code has no dictionary"))?
2083 .try_value_at(code as usize)?,
2084 };
2085 out.push((value, entry.count));
2086 }
2087 Ok(out)
2088 }
2089
2090 pub fn frequency_occurrences(&self, column: usize) -> Result<Option<FrequencyOccurrences>> {
2100 self.table
2101 .fields
2102 .get(column)
2103 .ok_or_else(|| invalid("frequency column index out of range"))?;
2104 let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
2105 return Ok(None);
2106 };
2107 if summary.ordinals.is_empty() {
2108 return Ok(None);
2109 }
2110 Ok(Some(FrequencyOccurrences {
2111 omitted_max: summary.omitted_max,
2112 ordinals: summary.ordinals.clone(),
2113 }))
2114 }
2115
2116 pub fn distinct_values(&self, column: usize) -> Result<Option<u64>> {
2136 if self.null_count(column)? > 0 {
2137 return Ok(None);
2138 }
2139 Ok(self.dictionary(column)?.map(|dictionary| dictionary.len() as u64))
2140 }
2141
2142 pub fn null_count(&self, column: usize) -> Result<u64> {
2153 if column >= self.table.fields.len() {
2154 return Err(invalid("null count column index out of range"));
2155 }
2156 let mut nulls = 0_u64;
2157 for stripe in &self.table.stripes {
2158 let range = stripe
2159 .zone
2160 .column(column)
2161 .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2162 nulls = nulls
2163 .checked_add(range.nulls as u64)
2164 .ok_or_else(|| invalid("null count overflow"))?;
2165 }
2166 Ok(nulls)
2167 }
2168
2169 pub fn text_extremes(&self, column: usize) -> Result<Option<(Value, Value)>> {
2184 if self.null_count(column)? > 0 {
2185 return Ok(None);
2186 }
2187 let Some(dictionary) = self.dictionary(column)? else { return Ok(None) };
2188 let Some(ranks) = dictionary.ranks() else { return Ok(None) };
2189 if ranks == 0 {
2190 return Ok(None);
2191 }
2192 let low = text_at_rank(&dictionary, 0)?;
2193 let high = text_at_rank(&dictionary, ranks - 1)?;
2194 Ok(Some((low, high)))
2195 }
2196
2197 pub fn exact_extremes(&self, column: usize) -> Result<Option<(Bound, Bound)>> {
2220 if column >= self.table.fields.len() {
2221 return Err(invalid("extremes column index out of range"));
2222 }
2223 let mut low: Option<Bound> = None;
2224 let mut high: Option<Bound> = None;
2225 for stripe in &self.table.stripes {
2226 let range = stripe
2227 .zone
2228 .column(column)
2229 .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2230 if !range.exact {
2231 return Ok(None);
2232 }
2233 let (Some(small), Some(large)) = (range.low.as_ref(), range.high.as_ref()) else {
2238 if stripe.rows > range.nulls {
2239 return Ok(None);
2240 }
2241 continue;
2242 };
2243 low = Some(low.map_or_else(|| small.clone(), |held| held.smaller(small.clone())));
2244 high = Some(high.map_or_else(|| large.clone(), |held| held.larger(large.clone())));
2245 }
2246 Ok(low.zip(high))
2247 }
2248
2249 pub fn exact_sum(&self, column: usize) -> Result<Option<(i128, u64)>> {
2262 if column >= self.table.fields.len() {
2263 return Err(invalid("sum column index out of range"));
2264 }
2265 let mut total = 0_i128;
2266 let mut rows = 0_u64;
2267 for stripe in &self.table.stripes {
2268 let range = stripe
2269 .zone
2270 .column(column)
2271 .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2272 let Some(part) = range.sum else { return Ok(None) };
2273 let Some(sum) = total.checked_add(part) else { return Ok(None) };
2274 total = sum;
2275 rows = rows.saturating_add(stripe.rows as u64 - range.nulls as u64);
2276 }
2277 Ok(Some((total, rows)))
2278 }
2279
2280 fn dictionary(&self, column: usize) -> Result<Option<Arc<Vector>>> {
2281 let Some(page) = self.table.dictionaries[column] else { return Ok(None) };
2282 if let Some(dictionary) = self.dictionaries[column].get() {
2283 return Ok(Some(Arc::clone(dictionary)));
2284 }
2285 let dictionary = Arc::new(open_global_dictionary(
2286 Arc::clone(&self.file),
2287 page,
2288 &self.table.fields[column].ty,
2289 )?);
2290 let _ = self.dictionaries[column].set(Arc::clone(&dictionary));
2291 Ok(Some(self.dictionaries[column].get().map_or(dictionary, Arc::clone)))
2292 }
2293
2294 pub fn read(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2303 self.read_impl(part, columns, true)
2304 }
2305
2306 pub fn read_sparse(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2316 self.read_impl(part, columns, false)
2317 }
2318
2319 pub fn skips_codes(&self, part: usize, column: usize, candidates: &[u32]) -> Result<bool> {
2326 if candidates.is_empty() {
2327 return Ok(true);
2328 }
2329 if candidates.windows(2).any(|pair| pair[0] >= pair[1]) {
2330 return Err(Error::internal("native code candidates are not sorted and unique"));
2331 }
2332 let stripe = self.stripe_of(part)?;
2333 let Some(page) = stripe.memberships.get(column).copied().flatten() else {
2334 return Ok(false);
2335 };
2336 let mut bytes = vec![0; page.length as usize];
2337 read_at(&self.file, page.offset, &mut bytes)?;
2338 if checksum(&bytes) != page.hash {
2339 return Err(invalid("membership page checksum differs"));
2340 }
2341 let codes = decode_membership(&bytes)?;
2342 let mut left = 0;
2343 let mut right = 0;
2344 while left < codes.len() && right < candidates.len() {
2345 match codes[left].cmp(&candidates[right]) {
2346 Ordering::Less => left += 1,
2347 Ordering::Greater => right += 1,
2348 Ordering::Equal => return Ok(false),
2349 }
2350 }
2351 Ok(true)
2352 }
2353
2354 fn stripe_of(&self, part: usize) -> Result<&Stripe> {
2355 let place = self.places.get(part).ok_or_else(|| invalid("part index out of range"))?;
2356 self.table
2357 .stripes
2358 .get(place.stripe as usize)
2359 .ok_or_else(|| invalid("stripe index out of range"))
2360 }
2361
2362 fn held(&self, at: usize, stripe: &Stripe, column: usize, whole: bool) -> Result<CachedColumn> {
2379 let cache = self.cache.get(column).ok_or_else(|| invalid("column index out of range"))?;
2380 let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2381 let known = cached.index.get(at).and_then(Clone::clone);
2382 let page = cached.pages.get(at).and_then(Clone::clone);
2383 if let Some(index) = known.clone() {
2384 if !whole || page.is_some() {
2385 return Ok(CachedColumn { stripe: at, index, page });
2386 }
2387 }
2388 if cached.loading.contains(&at) {
2389 drop(cached);
2390 if let Some(index) = known {
2394 return Ok(CachedColumn { stripe: at, index, page: None });
2395 }
2396 let held = self.page_of(stripe, column, at, false, None)?;
2397 let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2398 remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2399 return Ok(held);
2400 }
2401 cached.loading.push(at);
2402 drop(cached);
2403
2404 let read = self.page_of(stripe, column, at, whole, known);
2405
2406 let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2410 if let Some(position) = cached.loading.iter().position(|loading| *loading == at) {
2411 cached.loading.remove(position);
2412 }
2413 let held = read?;
2414 remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2415 Ok(held)
2416 }
2417
2418 fn page_of(
2424 &self,
2425 stripe: &Stripe,
2426 column: usize,
2427 at: usize,
2428 whole: bool,
2429 known: Option<Arc<Vec<PartSpan>>>,
2430 ) -> Result<CachedColumn> {
2431 let index = match known {
2432 Some(index) => index,
2433 None => {
2434 self.indexes.fetch_add(1, Atomic::Relaxed);
2435 Arc::new(read_index(&self.file, stripe, column)?)
2436 }
2437 };
2438 let page = if whole {
2439 self.pages.fetch_add(1, Atomic::Relaxed);
2440 let span = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2441 let mut bytes = vec![0; span.length as usize];
2442 read_at(&self.file, span.offset, &mut bytes)?;
2443 Some(Arc::new(bytes))
2444 } else {
2445 None
2446 };
2447 Ok(CachedColumn { stripe: at, index, page })
2448 }
2449
2450 fn read_impl(&self, at: usize, columns: &[usize], whole: bool) -> Result<Chunk> {
2451 let place = *self.places.get(at).ok_or_else(|| invalid("part index out of range"))?;
2452 let index = place.stripe as usize;
2453 let stripe =
2454 self.table.stripes.get(index).ok_or_else(|| invalid("stripe index out of range"))?;
2455 let rows = place.rows as usize;
2456 let mut picked = Vec::with_capacity(columns.len());
2457 for &column in columns {
2458 let field = self
2459 .table
2460 .fields
2461 .get(column)
2462 .ok_or_else(|| invalid("column index out of range"))?;
2463 let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2464 let held = self.held(index, stripe, column, whole)?;
2465 let span = *held
2466 .index
2467 .get(place.part as usize)
2468 .ok_or_else(|| invalid("part index out of range"))?;
2469 let owned;
2470 let bytes = match &held.page {
2471 Some(held) => part_bytes(held, span)?,
2472 None => {
2473 let offset = page
2474 .offset
2475 .checked_add(span.start as u64)
2476 .ok_or_else(|| invalid("part range overflow"))?;
2477 let mut bytes = vec![0; span.length];
2478 read_at(&self.file, offset, &mut bytes)?;
2479 owned = bytes;
2480 &owned
2481 }
2482 };
2483 if checksum(bytes) != span.hash {
2484 return Err(invalid(&format!(
2485 "column page checksum differs, column {column} part {} at {}+{} of {} bytes, \
2486 wanted {:016x} and got {:016x}",
2487 place.part,
2488 page.offset,
2489 span.start,
2490 span.length,
2491 span.hash,
2492 checksum(bytes),
2493 )));
2494 }
2495 let dictionary = self.dictionary(column)?;
2496 picked.push(decode(&field.ty, rows, bytes, dictionary)?);
2497 }
2498 Chunk::with_rows(picked, rows)
2499 }
2500
2501 #[must_use]
2511 pub fn skips(&self, part: usize, probes: &[Probe]) -> bool {
2512 let Some(place) = self.places.get(part).copied() else { return false };
2513 let Some(stripe) = self.table.stripes.get(place.stripe as usize) else { return false };
2514 if stripe.zone.skips(probes) {
2515 return true;
2516 }
2517 probes.iter().any(|probe| self.sifted(place, probe))
2518 }
2519
2520 #[must_use]
2531 pub fn stripe_skips(&self, stripe: usize, probes: &[Probe]) -> bool {
2532 self.table.stripes.get(stripe).is_some_and(|held| held.zone.skips(probes))
2533 }
2534
2535 fn sifted(&self, place: Place, probe: &Probe) -> bool {
2541 if probe.op != Op::Equal {
2542 return false;
2543 }
2544 match self.stripe_sieves(place.stripe as usize, probe.column) {
2545 Some(sieves) => sieves
2546 .get(place.part as usize)
2547 .and_then(Option::as_ref)
2548 .is_some_and(|sieve| sieve.excludes(&probe.value)),
2549 None => false,
2550 }
2551 }
2552
2553 fn stripe_sieves(&self, stripe: usize, column: usize) -> Option<&[Option<Sieve>]> {
2560 let slot = self.sieves.get(column)?.get(stripe)?;
2561 if let Some(held) = slot.get() {
2562 return Some(held);
2563 }
2564 let page = self.table.stripes.get(stripe)?.sieves.get(column).copied().flatten()?;
2565 let mut bytes = vec![0; page.length as usize];
2566 read_at(&self.file, page.offset, &mut bytes).ok()?;
2567 if checksum(&bytes) != page.hash {
2568 return None;
2569 }
2570 let sieves = Arc::new(decode_sieves(&bytes).ok()?);
2571 let _ = slot.set(sieves);
2572 slot.get().map(|held| held.as_slice())
2573 }
2574}
2575
2576fn text_at_rank(dictionary: &Vector, rank: usize) -> Result<Value> {
2578 let code = dictionary.code_at_rank(rank)? as usize;
2579 let text = dictionary
2580 .try_text_at(code)?
2581 .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
2582 Ok(Value::Varchar(text.into()))
2583}
2584
2585#[cfg(unix)]
2590fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
2591 use std::os::unix::fs::FileExt;
2592 while !bytes.is_empty() {
2593 let written = file.write_at(bytes, offset).map_err(io)?;
2594 if written == 0 {
2595 return Err(invalid("a write to the native file wrote nothing"));
2596 }
2597 offset += written as u64;
2598 bytes = &bytes[written..];
2599 }
2600 Ok(())
2601}
2602
2603#[cfg(windows)]
2605fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
2606 use std::os::windows::fs::FileExt;
2607 while !bytes.is_empty() {
2608 let written = file.seek_write(bytes, offset).map_err(io)?;
2609 if written == 0 {
2610 return Err(invalid("a write to the native file wrote nothing"));
2611 }
2612 offset += written as u64;
2613 bytes = &bytes[written..];
2614 }
2615 Ok(())
2616}
2617
2618#[cfg(not(any(unix, windows)))]
2620fn write_at(file: &File, offset: u64, bytes: &[u8]) -> Result<()> {
2621 use std::io::Write;
2622 let mut file = file.try_clone().map_err(io)?;
2623 file.seek(SeekFrom::Start(offset)).map_err(io)?;
2624 file.write_all(bytes).map_err(io)
2625}
2626
2627#[cfg(unix)]
2637fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
2638 use std::os::unix::fs::FileExt;
2639 while !bytes.is_empty() {
2640 let read = file.read_at(bytes, offset).map_err(io)?;
2641 if read == 0 {
2642 return Err(invalid("column page ends before its declared length"));
2643 }
2644 offset += read as u64;
2645 bytes = &mut bytes[read..];
2646 }
2647 Ok(())
2648}
2649
2650#[cfg(windows)]
2656fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
2657 use std::os::windows::fs::FileExt;
2658 while !bytes.is_empty() {
2659 let read = file.seek_read(bytes, offset).map_err(io)?;
2660 if read == 0 {
2661 return Err(invalid("column page ends before its declared length"));
2662 }
2663 offset += read as u64;
2664 bytes = &mut bytes[read..];
2665 }
2666 Ok(())
2667}
2668
2669#[cfg(not(any(unix, windows)))]
2674fn read_at(file: &File, offset: u64, bytes: &mut [u8]) -> Result<()> {
2675 let mut file = file.try_clone().map_err(io)?;
2676 file.seek(SeekFrom::Start(offset)).map_err(io)?;
2677 file.read_exact(bytes).map_err(io)
2678}
2679
2680fn type_tag(ty: &LogicalType) -> Result<u8> {
2681 match ty {
2682 LogicalType::SmallInt => Ok(1),
2683 LogicalType::Integer => Ok(2),
2684 LogicalType::BigInt => Ok(3),
2685 LogicalType::Varchar => Ok(4),
2686 LogicalType::Date => Ok(5),
2687 LogicalType::Timestamp => Ok(6),
2688 LogicalType::Boolean => Ok(7),
2689 LogicalType::TinyInt => Ok(8),
2690 LogicalType::UTinyInt => Ok(9),
2691 LogicalType::USmallInt => Ok(10),
2692 LogicalType::UInteger => Ok(11),
2693 LogicalType::UBigInt => Ok(12),
2694 _ => Err(Error::not_implemented(format!("native storage for {ty}"))),
2695 }
2696}
2697
2698fn tag_type(tag: u8) -> Result<LogicalType> {
2699 match tag {
2700 1 => Ok(LogicalType::SmallInt),
2701 2 => Ok(LogicalType::Integer),
2702 3 => Ok(LogicalType::BigInt),
2703 4 => Ok(LogicalType::Varchar),
2704 5 => Ok(LogicalType::Date),
2705 6 => Ok(LogicalType::Timestamp),
2706 7 => Ok(LogicalType::Boolean),
2707 8 => Ok(LogicalType::TinyInt),
2708 9 => Ok(LogicalType::UTinyInt),
2709 10 => Ok(LogicalType::USmallInt),
2710 11 => Ok(LogicalType::UInteger),
2711 12 => Ok(LogicalType::UBigInt),
2712 _ => Err(invalid("column type tag is unknown")),
2713 }
2714}
2715
2716fn put_u16(out: &mut Vec<u8>, value: u16) {
2717 out.extend_from_slice(&value.to_le_bytes());
2718}
2719fn put_u32(out: &mut Vec<u8>, value: u32) {
2720 out.extend_from_slice(&value.to_le_bytes());
2721}
2722fn put_u64(out: &mut Vec<u8>, value: u64) {
2723 out.extend_from_slice(&value.to_le_bytes());
2724}
2725fn put_var_u64(out: &mut Vec<u8>, mut value: u64) {
2726 while value >= 0x80 {
2727 out.push((value as u8 & 0x7f) | 0x80);
2728 value >>= 7;
2729 }
2730 out.push(value as u8);
2731}
2732
2733fn frequency_order(left: FrequencyValue, right: FrequencyValue) -> Ordering {
2734 match (left, right) {
2735 (FrequencyValue::Null, FrequencyValue::Null) => Ordering::Equal,
2736 (FrequencyValue::Null, _) => Ordering::Less,
2737 (_, FrequencyValue::Null) => Ordering::Greater,
2738 (FrequencyValue::Integer(left), FrequencyValue::Integer(right)) => left.cmp(&right),
2739 (FrequencyValue::Code(left), FrequencyValue::Code(right)) => left.cmp(&right),
2740 (FrequencyValue::Integer(_), FrequencyValue::Code(_)) => Ordering::Less,
2741 (FrequencyValue::Code(_), FrequencyValue::Integer(_)) => Ordering::Greater,
2742 }
2743}
2744
2745fn code_frequency(dictionary: &GlobalDictionary) -> FrequencySummary {
2746 let mut entries = dictionary
2747 .counts
2748 .iter()
2749 .enumerate()
2750 .filter(|(_, count)| **count != 0)
2751 .map(|(code, &count)| FrequencyEntry { value: FrequencyValue::Code(code as u32), count })
2752 .collect::<Vec<_>>();
2753 if dictionary.nulls != 0 {
2754 entries.push(FrequencyEntry { value: FrequencyValue::Null, count: dictionary.nulls });
2755 }
2756 entries.sort_unstable_by(|left, right| {
2757 right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
2758 });
2759 let omitted_max = entries.get(FREQUENCY_ENTRIES).map_or(0, |entry| entry.count);
2760 entries.truncate(FREQUENCY_ENTRIES);
2761 FrequencySummary { entries, omitted_max, ordinals: Vec::new() }
2762}
2763
2764fn encode_directory(table: &Table) -> Result<Vec<u8>> {
2765 let mut out = DIRECTORY.to_vec();
2766 let name = table.name.as_bytes();
2767 put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("table name too long"))?);
2768 out.extend_from_slice(name);
2769 put_u16(&mut out, u16::try_from(table.fields.len()).map_err(|_| invalid("too many columns"))?);
2770 for field in &table.fields {
2771 let name = field.name.as_bytes();
2772 put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("column name too long"))?);
2773 out.extend_from_slice(name);
2774 out.push(type_tag(&field.ty)?);
2775 out.push(u8::from(field.not_null));
2776 }
2777 for dictionary in &table.dictionaries {
2778 match dictionary {
2779 None => out.push(0),
2780 Some(page) => {
2781 out.push(1);
2782 put_u64(&mut out, page.offset);
2783 put_u32(&mut out, page.length);
2784 put_u64(&mut out, page.hash);
2785 }
2786 }
2787 }
2788 put_u64(&mut out, u64::try_from(table.rows).map_err(|_| invalid("row count overflow"))?);
2789 put_u32(&mut out, u32::try_from(table.stripes.len()).map_err(|_| invalid("too many stripes"))?);
2790 for stripe in &table.stripes {
2791 put_u32(
2792 &mut out,
2793 u32::try_from(stripe.parts.len()).map_err(|_| invalid("too many parts in a stripe"))?,
2794 );
2795 for &rows in &stripe.parts {
2796 put_u32(&mut out, rows);
2797 }
2798 put_u64(&mut out, stripe.index.offset);
2799 put_u32(&mut out, stripe.index.length);
2800 for page in &stripe.pages {
2801 put_u64(&mut out, page.offset);
2802 put_u32(&mut out, page.length);
2803 }
2804 for (field, membership) in table.fields.iter().zip(&stripe.memberships) {
2805 if field.ty != LogicalType::Varchar {
2806 continue;
2807 }
2808 let page =
2809 membership.ok_or_else(|| invalid("string page has no code membership index"))?;
2810 put_u64(&mut out, page.offset);
2811 put_u32(&mut out, page.length);
2812 put_u64(&mut out, page.hash);
2813 }
2814 for sieve in &stripe.sieves {
2815 match sieve {
2816 None => out.push(0),
2817 Some(page) => {
2818 out.push(1);
2819 put_u64(&mut out, page.offset);
2820 put_u32(&mut out, page.length);
2821 put_u64(&mut out, page.hash);
2822 }
2823 }
2824 }
2825 for range in stripe.zone.columns() {
2826 put_bound(&mut out, range.low.as_ref())?;
2827 put_bound(&mut out, range.high.as_ref())?;
2828 put_u32(
2829 &mut out,
2830 u32::try_from(range.nulls).map_err(|_| invalid("null count overflow"))?,
2831 );
2832 out.push(u8::from(range.exact));
2833 match range.sum {
2834 None => out.push(0),
2835 Some(total) => {
2836 out.push(1);
2837 out.extend_from_slice(&total.to_le_bytes());
2838 }
2839 }
2840 }
2841 }
2842 out.extend_from_slice(FREQUENCIES);
2843 put_u16(
2844 &mut out,
2845 u16::try_from(table.frequencies.len())
2846 .map_err(|_| invalid("too many frequency columns"))?,
2847 );
2848 for summary in &table.frequencies {
2849 let Some(summary) = summary else {
2850 out.push(0);
2851 continue;
2852 };
2853 out.push(1);
2854 put_u64(&mut out, summary.omitted_max);
2855 put_u32(
2856 &mut out,
2857 u32::try_from(summary.entries.len())
2858 .map_err(|_| invalid("too many frequency entries"))?,
2859 );
2860 for entry in &summary.entries {
2861 match entry.value {
2862 FrequencyValue::Null => out.push(0),
2863 FrequencyValue::Integer(value) => {
2864 out.push(1);
2865 out.extend_from_slice(&value.to_le_bytes());
2866 }
2867 FrequencyValue::Code(value) => {
2868 out.push(2);
2869 put_u32(&mut out, value);
2870 }
2871 }
2872 put_u64(&mut out, entry.count);
2873 }
2874 put_u32(
2875 &mut out,
2876 u32::try_from(summary.ordinals.len())
2877 .map_err(|_| invalid("too many frequency ordinals"))?,
2878 );
2879 let mut previous = 0_u64;
2880 for (at, &ordinal) in summary.ordinals.iter().enumerate() {
2881 let delta = if at == 0 {
2882 ordinal
2883 } else {
2884 ordinal
2885 .checked_sub(previous)
2886 .ok_or_else(|| invalid("frequency ordinals are not ordered"))?
2887 };
2888 if at != 0 && delta == 0 {
2889 return Err(invalid("frequency ordinals are not unique"));
2890 }
2891 put_var_u64(&mut out, delta);
2892 previous = ordinal;
2893 }
2894 }
2895 Ok(out)
2896}
2897
2898struct Cursor<'a> {
2899 bytes: &'a [u8],
2900 at: usize,
2901}
2902impl<'a> Cursor<'a> {
2903 fn take(&mut self, len: usize) -> Result<&'a [u8]> {
2904 let end = self.at.checked_add(len).ok_or_else(|| invalid("directory offset overflow"))?;
2905 let bytes =
2906 self.bytes.get(self.at..end).ok_or_else(|| invalid("directory is truncated"))?;
2907 self.at = end;
2908 Ok(bytes)
2909 }
2910 fn u8(&mut self) -> Result<u8> {
2911 Ok(self.take(1)?[0])
2912 }
2913 fn u16(&mut self) -> Result<u16> {
2914 Ok(u16::from_le_bytes(self.take(2)?.try_into().expect("two bytes")))
2915 }
2916 fn u32(&mut self) -> Result<u32> {
2917 Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("four bytes")))
2918 }
2919 fn u64(&mut self) -> Result<u64> {
2920 Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("eight bytes")))
2921 }
2922 fn var_u64(&mut self) -> Result<u64> {
2923 let mut value = 0_u64;
2924 for shift in (0..=63).step_by(7) {
2925 let byte = self.u8()?;
2926 let part = u64::from(byte & 0x7f);
2927 if shift == 63 && part > 1 {
2928 return Err(invalid("frequency ordinal varint overflows"));
2929 }
2930 value |= part << shift;
2931 if byte & 0x80 == 0 {
2932 return Ok(value);
2933 }
2934 }
2935 Err(invalid("frequency ordinal varint is too long"))
2936 }
2937 fn bound(&mut self) -> Result<Option<Bound>> {
2938 Ok(match self.u8()? {
2939 0 => None,
2940 1 => Some(Bound::Int(i128::from_le_bytes(
2941 self.take(16)?.try_into().expect("sixteen bytes"),
2942 ))),
2943 2 => Some(Bound::Real(f64::from_le_bytes(
2944 self.take(8)?.try_into().expect("eight bytes"),
2945 ))),
2946 3 => {
2947 let length = self.u32()? as usize;
2948 Some(Bound::Bytes(self.take(length)?.to_vec()))
2949 }
2950 _ => return Err(invalid("bound tag differs")),
2951 })
2952 }
2953 fn text(&mut self) -> Result<String> {
2954 let len = self.u16()? as usize;
2955 String::from_utf8(self.take(len)?.to_vec()).map_err(|_| invalid("name is not UTF-8"))
2956 }
2957}
2958
2959fn decode_directory(bytes: &[u8], size: u64) -> Result<Table> {
2960 let mut cur = Cursor { bytes, at: 0 };
2961 if cur.take(8)? != DIRECTORY {
2962 return Err(invalid("directory magic differs"));
2963 }
2964 let name = cur.text()?;
2965 let width = cur.u16()? as usize;
2966 let mut fields = Vec::with_capacity(width);
2967 for _ in 0..width {
2968 let name = cur.text()?;
2969 let ty = tag_type(cur.u8()?)?;
2970 let not_null = match cur.u8()? {
2971 0 => false,
2972 1 => true,
2973 _ => return Err(invalid("nullability flag differs")),
2974 };
2975 fields.push(Field { name, ty, not_null });
2976 }
2977 let mut dictionaries = Vec::with_capacity(width);
2978 for _ in 0..width {
2979 dictionaries.push(match cur.u8()? {
2980 0 => None,
2981 1 => {
2982 let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2983 let end = page
2984 .offset
2985 .checked_add(u64::from(page.length))
2986 .ok_or_else(|| invalid("dictionary page offset overflow"))?;
2987 if page.offset < HEADER || end > size {
2992 return Err(invalid("dictionary page range is outside the file"));
2993 }
2994 Some(page)
2995 }
2996 _ => return Err(invalid("dictionary page tag differs")),
2997 });
2998 }
2999 let rows = usize::try_from(cur.u64()?).map_err(|_| invalid("row count does not fit"))?;
3000 let count = cur.u32()? as usize;
3001 let mut stripes = Vec::with_capacity(count);
3002 let mut total = 0_usize;
3003 for _ in 0..count {
3004 let count = cur.u32()? as usize;
3005 if count == 0 || count > STRIPE_PARTS {
3006 return Err(invalid("stripe part count is outside its bound"));
3007 }
3008 let mut parts = Vec::with_capacity(count);
3009 let mut stripe_rows = 0_usize;
3010 for _ in 0..count {
3011 let rows = cur.u32()?;
3012 if rows == 0 {
3013 return Err(invalid("empty part"));
3014 }
3015 parts.push(rows);
3016 stripe_rows = stripe_rows
3017 .checked_add(rows as usize)
3018 .ok_or_else(|| invalid("stripe row count overflow"))?;
3019 }
3020 total =
3021 total.checked_add(stripe_rows).ok_or_else(|| invalid("stripe row count overflow"))?;
3022 let index = Span { offset: cur.u64()?, length: cur.u32()? };
3023 let section = index_section(count)?;
3024 let wanted = section
3025 .checked_mul(width)
3026 .and_then(|bytes| u32::try_from(bytes).ok())
3027 .ok_or_else(|| invalid("index page length overflow"))?;
3028 let end = index
3029 .offset
3030 .checked_add(u64::from(index.length))
3031 .ok_or_else(|| invalid("index page offset overflow"))?;
3032 if index.offset < HEADER || end > size || index.length != wanted {
3033 return Err(invalid("index page range is outside the file"));
3034 }
3035 let mut pages = Vec::with_capacity(width);
3036 for _ in 0..width {
3037 let offset = cur.u64()?;
3038 let length = cur.u32()?;
3039 let end = offset
3040 .checked_add(u64::from(length))
3041 .ok_or_else(|| invalid("page offset overflow"))?;
3042 if offset < HEADER || end > size || length as usize > MAX_PAGE {
3043 return Err(invalid("page range is outside the file"));
3044 }
3045 pages.push(Span { offset, length });
3046 }
3047 let mut memberships = vec![None; width];
3048 for (column, field) in fields.iter().enumerate() {
3049 if field.ty != LogicalType::Varchar {
3050 continue;
3051 }
3052 let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
3053 let end = page
3054 .offset
3055 .checked_add(u64::from(page.length))
3056 .ok_or_else(|| invalid("membership page offset overflow"))?;
3057 if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
3058 return Err(invalid("membership page range is outside the file"));
3059 }
3060 memberships[column] = Some(page);
3061 }
3062 let mut sieves = vec![None; width];
3063 for sieve in sieves.iter_mut().take(width) {
3064 match cur.u8()? {
3065 0 => continue,
3066 1 => {}
3067 _ => return Err(invalid("a sieve page has an unknown tag")),
3068 }
3069 let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
3070 let end = page
3071 .offset
3072 .checked_add(u64::from(page.length))
3073 .ok_or_else(|| invalid("sieve page offset overflow"))?;
3074 if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
3075 return Err(invalid("sieve page range is outside the file"));
3076 }
3077 *sieve = Some(page);
3078 }
3079 let mut ranges = Vec::with_capacity(width);
3080 for _ in 0..width {
3081 let low = cur.bound()?;
3082 let high = cur.bound()?;
3083 let nulls = cur.u32()? as usize;
3084 if nulls > stripe_rows {
3085 return Err(invalid("null count exceeds stripe rows"));
3086 }
3087 let exact = cur.u8()? != 0;
3088 let sum = match cur.u8()? {
3089 0 => None,
3090 1 => Some(i128::from_le_bytes(
3091 cur.take(16)?.try_into().map_err(|_| invalid("a stripe sum is truncated"))?,
3092 )),
3093 _ => return Err(invalid("a stripe sum has an unknown tag")),
3094 };
3095 ranges.push(Range { low, high, nulls, exact, sum });
3096 }
3097 stripes.push(Stripe {
3098 rows: stripe_rows,
3099 parts,
3100 index,
3101 pages,
3102 memberships,
3103 sieves,
3104 zone: Zone::from_ranges(ranges),
3105 });
3106 }
3107 if total != rows {
3108 return Err(invalid("table row count differs from stripes"));
3109 }
3110 let frequencies = if cur.at == bytes.len() {
3111 vec![None; width]
3112 } else {
3113 if cur.take(8)? != FREQUENCIES {
3114 return Err(invalid("directory extension magic differs"));
3115 }
3116 if cur.u16()? as usize != width {
3117 return Err(invalid("frequency column count differs"));
3118 }
3119 let mut frequencies = Vec::with_capacity(width);
3120 for field in &fields {
3121 let summary = match cur.u8()? {
3122 0 => None,
3123 1 => {
3124 let omitted_max = cur.u64()?;
3125 let count = cur.u32()? as usize;
3126 if count > FREQUENCY_ENTRIES {
3127 return Err(invalid("frequency entry count exceeds its bound"));
3128 }
3129 let mut entries = Vec::with_capacity(count);
3130 for _ in 0..count {
3132 let value = match cur.u8()? {
3133 0 => FrequencyValue::Null,
3134 1 => FrequencyValue::Integer(i128::from_le_bytes(
3135 cur.take(16)?.try_into().expect("sixteen bytes"),
3136 )),
3137 2 => FrequencyValue::Code(cur.u32()?),
3138 _ => return Err(invalid("frequency value tag differs")),
3139 };
3140 let valid = matches!(
3141 (&field.ty, value),
3142 (_, FrequencyValue::Null)
3143 | (LogicalType::Varchar, FrequencyValue::Code(_))
3144 | (
3145 LogicalType::TinyInt
3146 | LogicalType::SmallInt
3147 | LogicalType::Integer
3148 | LogicalType::BigInt
3149 | LogicalType::UTinyInt
3150 | LogicalType::USmallInt
3151 | LogicalType::UInteger
3152 | LogicalType::UBigInt
3153 | LogicalType::Date
3154 | LogicalType::Timestamp,
3155 FrequencyValue::Integer(_),
3156 )
3157 );
3158 if !valid {
3159 return Err(invalid("frequency value does not match its column"));
3160 }
3161 let count = cur.u64()?;
3162 if count == 0 || count > rows as u64 {
3163 return Err(invalid("frequency count is outside the table"));
3164 }
3165 entries.push(FrequencyEntry { value, count });
3166 }
3167 if entries.windows(2).any(|pair| pair[0].count < pair[1].count) {
3168 return Err(invalid("frequency entries are not descending"));
3169 }
3170 let ordinals = {
3171 let ordinal_count = cur.u32()? as usize;
3172 if ordinal_count > FREQUENCY_ORDINALS || ordinal_count > rows {
3173 return Err(invalid("frequency ordinal count exceeds its bound"));
3174 }
3175 let mut ordinals = Vec::with_capacity(ordinal_count);
3176 let mut previous = 0_u64;
3177 for at in 0..ordinal_count {
3178 let delta = cur.var_u64()?;
3179 if at != 0 && delta == 0 {
3180 return Err(invalid("frequency ordinals are not increasing"));
3181 }
3182 let ordinal = if at == 0 {
3183 delta
3184 } else {
3185 previous
3186 .checked_add(delta)
3187 .ok_or_else(|| invalid("frequency ordinal overflows"))?
3188 };
3189 if ordinal >= rows as u64 {
3190 return Err(invalid("frequency ordinal is outside the table"));
3191 }
3192 ordinals.push(ordinal);
3193 previous = ordinal;
3194 }
3195 ordinals
3196 };
3197 Some(FrequencySummary { entries, omitted_max, ordinals })
3198 }
3199 _ => return Err(invalid("frequency summary tag differs")),
3200 };
3201 frequencies.push(summary);
3202 }
3203 frequencies
3204 };
3205 if cur.at != bytes.len() {
3206 return Err(invalid("directory has trailing bytes"));
3207 }
3208 Ok(Table { name, fields, stripes, rows, dictionaries, frequencies })
3209}
3210
3211fn put_bound(out: &mut Vec<u8>, bound: Option<&Bound>) -> Result<()> {
3212 match bound {
3213 None => out.push(0),
3214 Some(Bound::Int(value)) => {
3215 out.push(1);
3216 out.extend_from_slice(&value.to_le_bytes());
3217 }
3218 Some(Bound::Real(value)) => {
3219 out.push(2);
3220 out.extend_from_slice(&value.to_le_bytes());
3221 }
3222 Some(Bound::Bytes(value)) => {
3223 out.push(3);
3224 put_u32(out, u32::try_from(value.len()).map_err(|_| invalid("bound length overflow"))?);
3225 out.extend_from_slice(value);
3226 }
3227 }
3228 Ok(())
3229}
3230
3231#[derive(Debug)]
3248struct Codes;
3249
3250impl chooser::Chooser for Codes {
3251 fn name(&self) -> &'static str {
3252 "codes"
3253 }
3254
3255 fn narrow_strings(
3256 &self,
3257 _values: &[&[u8]],
3258 offered: &[string::Kind],
3259 _depth: u8,
3260 ) -> Vec<string::Kind> {
3261 offered.to_vec()
3264 }
3265
3266 fn narrow_integers(
3267 &self,
3268 _values: &[i64],
3269 offered: &[integer::Kind],
3270 depth: u8,
3271 ) -> Vec<integer::Kind> {
3272 let keep: &[integer::Kind] = if depth == 0 {
3273 &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Rle]
3274 } else {
3275 &[integer::Kind::Constant, integer::Kind::Packed]
3276 };
3277 let narrowed: Vec<integer::Kind> =
3278 offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3279 if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3282 }
3283}
3284
3285#[derive(Debug)]
3295struct Fixed;
3296
3297impl chooser::Chooser for Fixed {
3298 fn name(&self) -> &'static str {
3299 "fixed"
3300 }
3301
3302 fn narrow_strings(
3303 &self,
3304 _values: &[&[u8]],
3305 offered: &[string::Kind],
3306 _depth: u8,
3307 ) -> Vec<string::Kind> {
3308 offered.to_vec()
3309 }
3310
3311 fn narrow_integers(
3312 &self,
3313 _values: &[i64],
3314 offered: &[integer::Kind],
3315 depth: u8,
3316 ) -> Vec<integer::Kind> {
3317 let keep: &[integer::Kind] = if depth == 0 {
3318 &[
3319 integer::Kind::Constant,
3320 integer::Kind::Packed,
3321 integer::Kind::Delta,
3322 integer::Kind::Rle,
3323 integer::Kind::Sparse,
3324 ]
3325 } else {
3326 &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Delta]
3327 };
3328 let narrowed: Vec<integer::Kind> =
3329 offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3330 if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3331 }
3332}
3333
3334fn widened(data: &Data) -> Option<Vec<i64>> {
3341 match data {
3342 Data::Int8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3343 Data::UInt8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3344 Data::Int16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3345 Data::UInt16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3346 Data::Int32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3347 Data::UInt32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3348 Data::Int64(values) => Some(values.to_vec()),
3349 _ => None,
3350 }
3351}
3352
3353fn narrowed(ty: &LogicalType, values: Vec<i64>) -> Result<Data> {
3358 fn fit<T: TryFrom<i64>>(values: &[i64]) -> Result<Vec<T>> {
3359 values
3360 .iter()
3361 .map(|value| T::try_from(*value).map_err(|_| invalid("page value is not of its type")))
3362 .collect()
3363 }
3364 Ok(match ty {
3365 LogicalType::TinyInt => Data::Int8(fit::<i8>(&values)?.into()),
3366 LogicalType::UTinyInt => Data::UInt8(fit::<u8>(&values)?.into()),
3367 LogicalType::SmallInt => Data::Int16(fit::<i16>(&values)?.into()),
3368 LogicalType::USmallInt => Data::UInt16(fit::<u16>(&values)?.into()),
3369 LogicalType::Integer | LogicalType::Date => Data::Int32(fit::<i32>(&values)?.into()),
3370 LogicalType::UInteger => Data::UInt32(fit::<u32>(&values)?.into()),
3371 LogicalType::BigInt | LogicalType::Timestamp => Data::Int64(values.into()),
3372 _ => return Err(invalid("cascade codec belongs to a page that is not integers")),
3373 })
3374}
3375
3376fn plain_width(ty: &LogicalType) -> Option<usize> {
3379 Some(match ty {
3380 LogicalType::TinyInt | LogicalType::UTinyInt => 1,
3381 LogicalType::SmallInt | LogicalType::USmallInt => 2,
3382 LogicalType::Integer | LogicalType::UInteger | LogicalType::Date => 4,
3383 LogicalType::BigInt | LogicalType::Timestamp => 8,
3384 _ => return None,
3385 })
3386}
3387
3388fn cascaded(
3394 flat: &Vector,
3395 ty: &LogicalType,
3396 packed: Option<&Packed<'_>>,
3397) -> Result<Option<Vec<u8>>> {
3398 let (Some(width), Some(data)) = (plain_width(ty), flat.data()) else { return Ok(None) };
3399 let Some(values) = widened(data) else { return Ok(None) };
3400 let plain = values.len().saturating_mul(width);
3401 let best = match packed {
3402 Some(packed) => plain.min(21 + size_of_val(packed.words())),
3404 None => plain,
3405 };
3406 let out = integer::encode_with(&values, &Fixed)?;
3407 Ok((out.len() < best).then_some(out))
3408}
3409
3410fn encoded_codes(codes: &[u32]) -> Result<Option<Vec<u8>>> {
3422 let wide: Vec<i64> = codes.iter().map(|code| i64::from(*code)).collect();
3423 let coded = integer::encode_with(&wide, &Codes)?;
3424 let plain = codes.len().saturating_mul(size_of::<u32>());
3425 Ok((coded.len() < plain).then_some(coded))
3426}
3427
3428fn encode(
3429 vector: &Vector,
3430 global: Option<&mut GlobalDictionary>,
3431) -> Result<(Vec<u8>, Option<Vec<u32>>)> {
3432 let ty = vector.logical_type();
3433 let flat = vector.flatten()?;
3435 let mut out = Vec::new();
3436 let mut global_codes = None;
3437 if let Some(global) = global {
3438 let mut codes = Vec::with_capacity(flat.len());
3439 for row in 0..flat.len() {
3440 let text = flat.text_at(row).unwrap_or("");
3441 let code = global.code(text)?;
3442 global.observe(code, flat.is_null_at(row))?;
3443 codes.push(code);
3444 }
3445 global_codes = Some(codes);
3446 }
3447 let membership = global_codes.as_deref().map(unique_codes);
3448 let dictionary = if global_codes.is_none() && ty == &LogicalType::Varchar {
3449 string_dictionary(&flat)?
3450 } else {
3451 None
3452 };
3453 let packed_vector = if dictionary.is_none() && global_codes.is_none() {
3454 Some(flat.bit_packed()?)
3455 } else {
3456 None
3457 };
3458 let packed = packed_vector.as_ref().and_then(Vector::packed_parts);
3459 let coded = match global_codes.as_deref() {
3460 Some(codes) => encoded_codes(codes)?,
3461 None => None,
3462 };
3463 let cascade = if dictionary.is_none() && global_codes.is_none() {
3467 cascaded(&flat, ty, packed.as_ref())?
3468 } else {
3469 None
3470 };
3471 out.push(if coded.is_some() {
3472 4
3473 } else if cascade.is_some() {
3474 5
3475 } else if global_codes.is_some() {
3476 3
3477 } else if dictionary.is_some() {
3478 1
3479 } else if packed.is_some() {
3480 2
3481 } else {
3482 0
3483 });
3484 let nulls = flat.validity();
3485 let flag = match nulls {
3486 Validity::AllValid => 0,
3487 Validity::AllInvalid => 1,
3488 Validity::Mask(_) => 2,
3489 };
3490 out.push(flag);
3491 if flag == 2 {
3492 for group in (0..vector.len()).step_by(8) {
3493 let mut bits = 0_u8;
3494 for bit in 0..8 {
3495 if group + bit < vector.len() && !flat.is_null_at(group + bit) {
3496 bits |= 1 << bit;
3497 }
3498 }
3499 out.push(bits);
3500 }
3501 }
3502 if let Some(coded) = coded {
3503 out.extend_from_slice(&coded);
3504 return Ok((out, membership));
3505 }
3506 if let Some(cascade) = cascade {
3507 out.extend_from_slice(&cascade);
3508 return Ok((out, membership));
3509 }
3510 if let Some(codes) = global_codes {
3511 for code in codes {
3512 put_u32(&mut out, code);
3513 }
3514 return Ok((out, membership));
3515 }
3516 if let Some(dictionary) = dictionary {
3517 out.extend_from_slice(&dictionary);
3518 return Ok((out, membership));
3519 }
3520 if let Some(packed) = packed {
3521 if packed.offset() != 0 {
3522 return Err(invalid("writer received a sliced packed vector"));
3523 }
3524 out.push(u8::try_from(packed.width()).map_err(|_| invalid("packed width overflow"))?);
3525 out.extend_from_slice(&packed.base().to_le_bytes());
3526 put_u32(
3527 &mut out,
3528 u32::try_from(packed.words().len()).map_err(|_| invalid("too many packed words"))?,
3529 );
3530 for word in packed.words() {
3531 put_u64(&mut out, *word);
3532 }
3533 return Ok((out, membership));
3534 }
3535 let data = flat.data().ok_or_else(|| invalid("scalar column did not flatten"))?;
3536 match (ty, data) {
3537 (LogicalType::TinyInt, Data::Int8(values)) => {
3538 for value in &**values {
3539 out.extend_from_slice(&value.to_le_bytes());
3540 }
3541 }
3542 (LogicalType::UTinyInt, Data::UInt8(values)) => {
3543 for value in &**values {
3544 out.extend_from_slice(&value.to_le_bytes());
3545 }
3546 }
3547 (LogicalType::SmallInt, Data::Int16(values)) => {
3548 for value in &**values {
3549 out.extend_from_slice(&value.to_le_bytes());
3550 }
3551 }
3552 (LogicalType::USmallInt, Data::UInt16(values)) => {
3553 for value in &**values {
3554 out.extend_from_slice(&value.to_le_bytes());
3555 }
3556 }
3557 (LogicalType::UInteger, Data::UInt32(values)) => {
3558 for value in &**values {
3559 out.extend_from_slice(&value.to_le_bytes());
3560 }
3561 }
3562 (LogicalType::UBigInt, Data::UInt64(values)) => {
3563 for value in &**values {
3564 out.extend_from_slice(&value.to_le_bytes());
3565 }
3566 }
3567 (LogicalType::Integer | LogicalType::Date, Data::Int32(values)) => {
3568 for value in &**values {
3569 out.extend_from_slice(&value.to_le_bytes());
3570 }
3571 }
3572 (LogicalType::BigInt | LogicalType::Timestamp, Data::Int64(values)) => {
3573 for value in &**values {
3574 out.extend_from_slice(&value.to_le_bytes());
3575 }
3576 }
3577 (LogicalType::Boolean, Data::Bool(values)) => {
3578 for value in &**values {
3579 out.push(u8::from(*value));
3580 }
3581 }
3582 (LogicalType::Varchar, Data::Varlen(values)) => {
3583 let mut bytes = Vec::new();
3584 put_u32(&mut out, 0);
3585 for row in 0..vector.len() {
3586 let value = values.bytes(row).ok_or_else(|| invalid("string view is invalid"))?;
3587 bytes.extend_from_slice(value);
3588 put_u32(
3589 &mut out,
3590 u32::try_from(bytes.len())
3591 .map_err(|_| invalid("string payload exceeds 4GiB"))?,
3592 );
3593 }
3594 out.extend_from_slice(&bytes);
3595 }
3596 _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
3597 }
3598 Ok((out, membership))
3599}
3600
3601fn put_varint(out: &mut Vec<u8>, mut value: u32) {
3602 while value >= 0x80 {
3603 out.push((value as u8 & 0x7f) | 0x80);
3604 value >>= 7;
3605 }
3606 out.push(value as u8);
3607}
3608
3609fn unique_codes(codes: &[u32]) -> Vec<u32> {
3611 let mut unique = codes.to_vec();
3612 unique.sort_unstable();
3613 unique.dedup();
3614 unique
3615}
3616
3617fn merged_codes(lists: Vec<Vec<u32>>) -> Vec<u32> {
3623 let mut lists = lists;
3624 while lists.len() > 1 {
3625 let mut next = Vec::with_capacity(lists.len().div_ceil(2));
3626 for pair in lists.chunks(2) {
3627 match pair {
3628 [left, right] => next.push(merged_pair(left, right)),
3629 [only] => next.push(only.clone()),
3630 _ => {}
3631 }
3632 }
3633 lists = next;
3634 }
3635 lists.pop().unwrap_or_default()
3636}
3637
3638fn merged_pair(left: &[u32], right: &[u32]) -> Vec<u32> {
3639 let mut out = Vec::with_capacity(left.len().saturating_add(right.len()));
3640 let mut at = 0;
3641 let mut to = 0;
3642 while at < left.len() && to < right.len() {
3643 match left[at].cmp(&right[to]) {
3644 Ordering::Less => {
3645 out.push(left[at]);
3646 at += 1;
3647 }
3648 Ordering::Greater => {
3649 out.push(right[to]);
3650 to += 1;
3651 }
3652 Ordering::Equal => {
3653 out.push(left[at]);
3654 at += 1;
3655 to += 1;
3656 }
3657 }
3658 }
3659 out.extend_from_slice(&left[at..]);
3660 out.extend_from_slice(&right[to..]);
3661 out
3662}
3663
3664fn merged_range(ranges: impl Iterator<Item = Range>) -> Range {
3669 let mut merged = Range::default();
3670 let mut first = true;
3671 for range in ranges {
3672 merged.nulls = merged.nulls.saturating_add(range.nulls);
3673 merged.sum = match (merged.sum.take(), range.sum) {
3677 (Some(held), Some(next)) if !first => held.checked_add(next),
3678 (_, next) if first => next,
3679 _ => None,
3680 };
3681 merged.exact = if first { range.exact } else { merged.exact && range.exact };
3682 if first {
3683 merged.low = range.low;
3684 merged.high = range.high;
3685 first = false;
3686 continue;
3687 }
3688 merged.low = match (merged.low.take(), range.low) {
3689 (Some(held), Some(next)) => Some(held.smaller(next)),
3690 _ => None,
3691 };
3692 merged.high = match (merged.high.take(), range.high) {
3693 (Some(held), Some(next)) => Some(held.larger(next)),
3694 _ => None,
3695 };
3696 }
3697 merged
3698}
3699
3700fn encode_sieves<'a>(sieves: impl Iterator<Item = &'a Option<Sieve>>) -> Result<Vec<u8>> {
3706 let held: Vec<&Option<Sieve>> = sieves.collect();
3707 let mut out = Vec::new();
3708 put_u32(
3709 &mut out,
3710 u32::try_from(held.len()).map_err(|_| invalid("too many parts in a stripe"))?,
3711 );
3712 for sieve in &held {
3713 let length = sieve.as_ref().map_or(0, Sieve::len);
3714 put_u32(&mut out, u32::try_from(length).map_err(|_| invalid("sieve length overflow"))?);
3715 }
3716 for sieve in held.into_iter().flatten() {
3718 out.extend_from_slice(&sieve.to_bytes());
3719 }
3720 Ok(out)
3721}
3722
3723fn decode_sieves(bytes: &[u8]) -> Result<Vec<Option<Sieve>>> {
3729 let parts = u32::from_le_bytes(
3730 bytes
3731 .get(..4)
3732 .ok_or_else(|| invalid("sieve page is truncated"))?
3733 .try_into()
3734 .map_err(|_| invalid("sieve page is truncated"))?,
3735 ) as usize;
3736 let mut lengths = Vec::with_capacity(parts);
3737 for part in 0..parts {
3738 let at = 4 + part * 4;
3739 let field = bytes.get(at..at + 4).ok_or_else(|| invalid("sieve page is truncated"))?;
3740 lengths.push(u32::from_le_bytes(
3741 field.try_into().map_err(|_| invalid("sieve page is truncated"))?,
3742 ) as usize);
3743 }
3744 let mut at = 4 + parts * 4;
3745 let mut out = Vec::with_capacity(parts);
3746 for length in lengths {
3747 if length == 0 {
3748 out.push(None);
3749 continue;
3750 }
3751 let end = at.checked_add(length).ok_or_else(|| invalid("sieve page is truncated"))?;
3752 let field = bytes.get(at..end).ok_or_else(|| invalid("sieve page is truncated"))?;
3753 out.push(Sieve::from_bytes(field));
3754 at = end;
3755 }
3756 if at != bytes.len() {
3757 return Err(invalid("sieve page has trailing bytes"));
3758 }
3759 Ok(out)
3760}
3761
3762fn encode_membership(unique: &[u32]) -> Vec<u8> {
3768 let mut out = Vec::with_capacity(unique.len().saturating_mul(2).saturating_add(5));
3769 put_varint(&mut out, u32::try_from(unique.len()).unwrap_or(u32::MAX));
3770 let mut previous = 0;
3771 for (at, &code) in unique.iter().enumerate() {
3772 put_varint(&mut out, if at == 0 { code } else { code - previous });
3773 previous = code;
3774 }
3775 out
3776}
3777
3778fn take_varint(bytes: &[u8], at: &mut usize) -> Result<u32> {
3779 let mut value = 0_u32;
3780 for shift in (0..35).step_by(7) {
3781 let byte = *bytes.get(*at).ok_or_else(|| invalid("membership varint is truncated"))?;
3782 *at += 1;
3783 let part = u32::from(byte & 0x7f);
3784 if shift == 28 && part > 0x0f {
3785 return Err(invalid("membership varint overflow"));
3786 }
3787 value = value
3788 .checked_add(
3789 part.checked_shl(shift).ok_or_else(|| invalid("membership varint overflow"))?,
3790 )
3791 .ok_or_else(|| invalid("membership varint overflow"))?;
3792 if byte & 0x80 == 0 {
3793 return Ok(value);
3794 }
3795 }
3796 Err(invalid("membership varint is too long"))
3797}
3798
3799fn decode_membership(bytes: &[u8]) -> Result<Vec<u32>> {
3800 let mut at = 0;
3801 let count = take_varint(bytes, &mut at)? as usize;
3802 let mut codes = Vec::with_capacity(count);
3803 let mut previous = 0_u32;
3804 for index in 0..count {
3805 let delta = take_varint(bytes, &mut at)?;
3806 let code = if index == 0 {
3807 delta
3808 } else {
3809 previous.checked_add(delta).ok_or_else(|| invalid("membership code overflow"))?
3810 };
3811 if index > 0 && code <= previous {
3812 return Err(invalid("membership codes are not increasing"));
3813 }
3814 codes.push(code);
3815 previous = code;
3816 }
3817 if at != bytes.len() {
3818 return Err(invalid("membership page has trailing bytes"));
3819 }
3820 Ok(codes)
3821}
3822
3823fn string_dictionary(vector: &Vector) -> Result<Option<Vec<u8>>> {
3824 let mut by_text = HashMap::new();
3825 let mut values = Vec::new();
3826 let mut codes = Vec::with_capacity(vector.len());
3827 let mut plain_bytes = 0_usize;
3828 for row in 0..vector.len() {
3829 let text = vector.text_at(row).unwrap_or("");
3830 plain_bytes = plain_bytes.saturating_add(text.len());
3831 let code = match by_text.get(text) {
3832 Some(&code) => code,
3833 None => {
3834 let code = u32::try_from(values.len())
3835 .map_err(|_| invalid("too many dictionary values"))?;
3836 by_text.insert(text, code);
3837 values.push(text);
3838 code
3839 }
3840 };
3841 codes.push(code);
3842 }
3843 let dictionary_bytes = values.iter().map(|value| value.len()).sum::<usize>();
3844 let encoded = 8_usize
3845 .saturating_add((values.len() + 1).saturating_mul(4))
3846 .saturating_add(dictionary_bytes)
3847 .saturating_add(codes.len().saturating_mul(4));
3848 let plain = (vector.len() + 1).saturating_mul(4).saturating_add(plain_bytes);
3849 if encoded >= plain {
3850 return Ok(None);
3851 }
3852 let mut out = Vec::with_capacity(encoded);
3853 put_u32(
3854 &mut out,
3855 u32::try_from(values.len()).map_err(|_| invalid("too many dictionary values"))?,
3856 );
3857 put_u32(
3858 &mut out,
3859 u32::try_from(dictionary_bytes).map_err(|_| invalid("dictionary payload exceeds 4GiB"))?,
3860 );
3861 let mut offset = 0_u32;
3862 put_u32(&mut out, offset);
3863 for value in &values {
3864 offset = offset
3865 .checked_add(
3866 u32::try_from(value.len()).map_err(|_| invalid("dictionary value is too long"))?,
3867 )
3868 .ok_or_else(|| invalid("dictionary payload exceeds 4GiB"))?;
3869 put_u32(&mut out, offset);
3870 }
3871 for value in values {
3872 out.extend_from_slice(value.as_bytes());
3873 }
3874 for code in codes {
3875 put_u32(&mut out, code);
3876 }
3877 Ok(Some(out))
3878}
3879
3880struct EncodedDictionary {
3881 index: Vec<u8>,
3882 ranks: Vec<u8>,
3883 payload: Vec<u8>,
3884}
3885
3886fn head(bytes: &[u8]) -> u64 {
3888 let mut word = [0; 8];
3889 let take = bytes.len().min(8);
3890 word[..take].copy_from_slice(&bytes[..take]);
3891 u64::from_be_bytes(word)
3892}
3893
3894fn rankings(dictionaries: &[Option<GlobalDictionary>]) -> Result<Vec<Vec<(u64, u32)>>> {
3902 let present =
3903 dictionaries.iter().enumerate().filter(|(_, held)| held.is_some()).map(|(at, _)| at);
3904 let present = present.collect::<Vec<_>>();
3905 let mut orders = vec![Vec::new(); dictionaries.len()];
3906 let workers = std::thread::available_parallelism()
3907 .map_or(1, usize::from)
3908 .min(MAX_FREQUENCY_WORKERS)
3909 .min(present.len());
3910 if workers <= 1 {
3911 for at in present {
3912 if let Some(dictionary) = &dictionaries[at] {
3913 orders[at] = dictionary.ranked();
3914 }
3915 }
3916 return Ok(orders);
3917 }
3918 let width = present.len().div_ceil(workers);
3919 let pieces = std::thread::scope(|scope| {
3920 present
3921 .chunks(width)
3922 .map(|columns| {
3923 scope.spawn(|| {
3924 columns
3925 .iter()
3926 .filter_map(|&at| dictionaries[at].as_ref().map(|held| (at, held.ranked())))
3927 .collect::<Vec<_>>()
3928 })
3929 })
3930 .collect::<Vec<_>>()
3931 .into_iter()
3932 .map(|handle| {
3933 handle.join().map_err(|_| Error::internal("a dictionary sort worker panicked"))
3934 })
3935 .collect::<Result<Vec<_>>>()
3936 })?;
3937 for piece in pieces {
3938 for (at, order) in piece {
3939 orders[at] = order;
3940 }
3941 }
3942 Ok(orders)
3943}
3944
3945fn encode_global_dictionary(
3946 dictionary: GlobalDictionary,
3947 order: &[(u64, u32)],
3948) -> Result<EncodedDictionary> {
3949 let values = dictionary.offsets.len() - 1;
3950 if order.len() != values {
3951 return Err(invalid("global dictionary order does not cover its values"));
3952 }
3953 let payload_len = dictionary.payload.len();
3954 let blocks = payload_len.div_ceil(TEXT_PAYLOAD_BLOCK);
3955 let ranks = encode_ranks(order);
3956 let rank_blocks = values.div_ceil(TEXT_RANK_BLOCK);
3957 let mut index = Vec::with_capacity(12 + (values + 1) * 4 + (blocks + rank_blocks) * 8);
3958 put_u32(
3959 &mut index,
3960 u32::try_from(values).map_err(|_| invalid("global dictionary has too many values"))?,
3961 );
3962 put_u32(&mut index, TEXT_PAYLOAD_BLOCK as u32);
3963 put_u32(
3964 &mut index,
3965 u32::try_from(blocks).map_err(|_| invalid("global dictionary has too many blocks"))?,
3966 );
3967 for offset in dictionary.offsets {
3968 put_u32(&mut index, offset);
3969 }
3970 for block in dictionary.payload.chunks(TEXT_PAYLOAD_BLOCK) {
3971 put_u64(&mut index, checksum(block));
3972 }
3973 for block in ranks.chunks(TEXT_RANK_BLOCK * RANK_ENTRY) {
3974 put_u64(&mut index, checksum(block));
3975 }
3976 Ok(EncodedDictionary { index, ranks, payload: dictionary.payload })
3977}
3978
3979fn encode_ranks(order: &[(u64, u32)]) -> Vec<u8> {
3986 let mut out = Vec::with_capacity(order.len() * RANK_ENTRY);
3987 for block in order.chunks(TEXT_RANK_BLOCK) {
3988 for &(head, _) in block {
3989 put_u64(&mut out, head);
3990 }
3991 for &(_, code) in block {
3992 put_u32(&mut out, code);
3993 }
3994 }
3995 out
3996}
3997
3998fn open_global_dictionary(file: Arc<File>, page: Page, ty: &LogicalType) -> Result<Vector> {
3999 if ty != &LogicalType::Varchar {
4000 return Err(invalid("global dictionary belongs to a non-string column"));
4001 }
4002 let mut header = [0; 12];
4003 read_at(&file, page.offset, &mut header)?;
4004 let count = u32::from_le_bytes(header[0..4].try_into().expect("four bytes")) as usize;
4005 let block_size = u32::from_le_bytes(header[4..8].try_into().expect("four bytes")) as usize;
4006 let blocks = u32::from_le_bytes(header[8..12].try_into().expect("four bytes")) as usize;
4007 if block_size != TEXT_PAYLOAD_BLOCK {
4008 return Err(invalid("global dictionary block width differs"));
4009 }
4010 let offset_len = (count + 1)
4011 .checked_mul(4)
4012 .ok_or_else(|| invalid("global dictionary offset count overflow"))?;
4013 let ranks = count;
4018 let rank_blocks = ranks.div_ceil(TEXT_RANK_BLOCK);
4019 let rank_len =
4020 ranks.checked_mul(RANK_ENTRY).ok_or_else(|| invalid("global dictionary rank overflow"))?;
4021 let hash_len = blocks
4022 .checked_add(rank_blocks)
4023 .and_then(|count| count.checked_mul(8))
4024 .ok_or_else(|| invalid("global dictionary block count overflow"))?;
4025 let index_len = 12usize
4026 .checked_add(offset_len)
4027 .and_then(|len| len.checked_add(hash_len))
4028 .ok_or_else(|| invalid("global dictionary header overflow"))?;
4029 let body_len = index_len
4030 .checked_add(rank_len)
4031 .ok_or_else(|| invalid("global dictionary header overflow"))?;
4032 if body_len > page.length as usize {
4033 return Err(invalid("global dictionary offset index exceeds its page"));
4034 }
4035 let mut index = vec![0; index_len];
4036 index[..12].copy_from_slice(&header);
4037 read_at(&file, page.offset + 12, &mut index[12..])?;
4038 if checksum(&index) != page.hash {
4039 return Err(invalid("global dictionary index checksum differs"));
4040 }
4041 let offsets = index[12..12 + offset_len]
4042 .chunks_exact(4)
4043 .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
4044 .collect::<Vec<_>>();
4045 let mut hashes = index[12 + offset_len..]
4046 .chunks_exact(8)
4047 .map(|part| u64::from_le_bytes(part.try_into().expect("eight bytes")))
4048 .collect::<Vec<_>>();
4049 let rank_hashes = hashes.split_off(blocks);
4050 let payload_len = page.length as usize - body_len;
4051 if blocks != payload_len.div_ceil(TEXT_PAYLOAD_BLOCK) {
4052 return Err(invalid("global dictionary block count differs from its payload"));
4053 }
4054 if offsets.first() != Some(&0)
4055 || offsets.last().copied().map(|last| last as usize) != Some(payload_len)
4056 || offsets.windows(2).any(|pair| pair[0] > pair[1])
4057 {
4058 return Err(invalid("global dictionary offsets do not bound the payload"));
4059 }
4060 let payload_extents = (0..payload_len.div_ceil(TEXT_PAYLOAD_BLOCK * TEXT_PAYLOAD_EXTENT))
4061 .map(|_| OnceLock::new())
4062 .collect();
4063 let crossing = (0..count.div_ceil(TEXT_CROSSING_BLOCK)).map(|_| OnceLock::new()).collect();
4064 Vector::external_text(
4065 LogicalType::Varchar,
4066 Arc::new(NativeText {
4067 file,
4068 offsets,
4069 ranks,
4070 rank_at: page.offset + index_len as u64,
4071 rank_hashes,
4072 rank_blocks: (0..rank_blocks).map(|_| OnceLock::new()).collect(),
4073 code_ranks: OnceLock::new(),
4074 payload: page.offset + body_len as u64,
4075 payload_len,
4076 hashes,
4077 payload_extents,
4078 crossing,
4079 }),
4080 )
4081}
4082
4083fn decode(
4084 ty: &LogicalType,
4085 rows: usize,
4086 bytes: &[u8],
4087 global: Option<Arc<Vector>>,
4088) -> Result<Vector> {
4089 let mut cur = Cursor { bytes, at: 0 };
4090 let codec = cur.u8()?;
4091 let flag = cur.u8()?;
4092 let validity = match flag {
4093 0 => Validity::AllValid,
4094 1 => Validity::AllInvalid,
4095 2 => {
4096 let mask = cur.take(rows.div_ceil(8))?;
4097 Validity::from_iter(rows, |row| mask[row / 8] >> (row % 8) & 1 == 1)
4098 }
4099 _ => return Err(invalid("page validity tag differs")),
4100 };
4101 if codec == 1 {
4102 if ty != &LogicalType::Varchar {
4103 return Err(invalid("dictionary codec belongs to a non-string page"));
4104 }
4105 let count = cur.u32()? as usize;
4106 let payload_len = cur.u32()? as usize;
4107 let offset_bytes = cur.take(
4108 (count + 1)
4109 .checked_mul(4)
4110 .ok_or_else(|| invalid("dictionary offset count overflow"))?,
4111 )?;
4112 let offsets = offset_bytes
4113 .chunks_exact(4)
4114 .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
4115 .collect::<Vec<_>>();
4116 let payload = cur.take(payload_len)?.to_vec();
4117 if offsets.first() != Some(&0)
4118 || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
4119 || offsets.windows(2).any(|pair| pair[0] > pair[1])
4120 {
4121 return Err(invalid("dictionary offsets do not bound the payload"));
4122 }
4123 let mut strings = StringColumn::over(Buffer::from_vec(payload));
4124 for pair in offsets.windows(2) {
4125 strings.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
4126 }
4127 let mut codes = Vec::with_capacity(rows);
4128 for _ in 0..rows {
4129 codes.push(cur.u32()?);
4130 }
4131 if codes.iter().any(|code| *code as usize >= count) {
4132 return Err(invalid("dictionary code is out of range"));
4133 }
4134 if cur.at != bytes.len() {
4135 return Err(invalid("dictionary page has trailing bytes"));
4136 }
4137 let dictionary = Vector::flat(LogicalType::Varchar, Data::Varlen(strings))?;
4138 return Ok(Vector::dictionary(codes, dictionary)?.with_validity(validity));
4139 }
4140 if codec == 3 || codec == 4 {
4141 let dictionary = global.ok_or_else(|| invalid("global code page has no dictionary"))?;
4142 let codes = if codec == 4 {
4143 let wide = integer::decode(&bytes[cur.at..])?;
4146 if wide.len() != rows {
4147 return Err(invalid("encoded code page holds the wrong number of rows"));
4148 }
4149 wide.into_iter()
4150 .map(|code| u32::try_from(code).map_err(|_| invalid("code is not a code")))
4151 .collect::<Result<Vec<u32>>>()?
4152 } else {
4153 let mut codes = Vec::with_capacity(rows);
4154 for _ in 0..rows {
4155 codes.push(cur.u32()?);
4156 }
4157 if cur.at != bytes.len() {
4158 return Err(invalid("global code page has trailing bytes"));
4159 }
4160 codes
4161 };
4162 let highest = codes.iter().copied().max();
4163 return Ok(Vector::stable_dictionary_validated(codes, dictionary, highest)?
4164 .with_validity(validity));
4165 }
4166 if codec == 5 {
4167 let values = integer::decode(&bytes[cur.at..])?;
4169 if values.len() != rows {
4170 return Err(invalid("cascade page holds the wrong number of rows"));
4171 }
4172 let data = narrowed(ty, values)?;
4173 return Ok(Vector::flat(ty.clone(), data)?.with_validity(validity));
4174 }
4175 if codec == 2 {
4176 let width = u32::from(cur.u8()?);
4177 let base = i128::from_le_bytes(cur.take(16)?.try_into().expect("sixteen bytes"));
4178 let count = cur.u32()? as usize;
4179 let mut words = Vec::with_capacity(count);
4180 for _ in 0..count {
4181 words.push(cur.u64()?);
4182 }
4183 if cur.at != bytes.len() {
4184 return Err(invalid("packed page has trailing bytes"));
4185 }
4186 return Ok(Vector::packed(ty.clone(), words, width, base, rows)?.with_validity(validity));
4187 }
4188 if codec != 0 {
4189 return Err(invalid("page codec is unknown"));
4190 }
4191 let data = match ty {
4192 LogicalType::TinyInt => {
4193 let values = cur.take(rows)?;
4194 Data::Int8(values.iter().map(|item| *item as i8).collect::<Vec<_>>().into())
4195 }
4196 LogicalType::UTinyInt => Data::UInt8(cur.take(rows)?.to_vec().into()),
4197 LogicalType::SmallInt => {
4198 let values =
4199 cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
4200 Data::Int16(
4201 values
4202 .chunks_exact(2)
4203 .map(|item| i16::from_le_bytes(item.try_into().expect("two bytes")))
4204 .collect::<Vec<_>>()
4205 .into(),
4206 )
4207 }
4208 LogicalType::USmallInt => {
4209 let values =
4210 cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
4211 Data::UInt16(
4212 values
4213 .chunks_exact(2)
4214 .map(|item| u16::from_le_bytes(item.try_into().expect("two bytes")))
4215 .collect::<Vec<_>>()
4216 .into(),
4217 )
4218 }
4219 LogicalType::UInteger => {
4220 let values =
4221 cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
4222 Data::UInt32(
4223 values
4224 .chunks_exact(4)
4225 .map(|item| u32::from_le_bytes(item.try_into().expect("four bytes")))
4226 .collect::<Vec<_>>()
4227 .into(),
4228 )
4229 }
4230 LogicalType::UBigInt => {
4231 let values =
4232 cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
4233 Data::UInt64(
4234 values
4235 .chunks_exact(8)
4236 .map(|item| u64::from_le_bytes(item.try_into().expect("eight bytes")))
4237 .collect::<Vec<_>>()
4238 .into(),
4239 )
4240 }
4241 LogicalType::Integer | LogicalType::Date => {
4242 let values =
4243 cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
4244 Data::Int32(
4245 values
4246 .chunks_exact(4)
4247 .map(|item| i32::from_le_bytes(item.try_into().expect("four bytes")))
4248 .collect::<Vec<_>>()
4249 .into(),
4250 )
4251 }
4252 LogicalType::BigInt | LogicalType::Timestamp => {
4253 let values =
4254 cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
4255 Data::Int64(
4256 values
4257 .chunks_exact(8)
4258 .map(|item| i64::from_le_bytes(item.try_into().expect("eight bytes")))
4259 .collect::<Vec<_>>()
4260 .into(),
4261 )
4262 }
4263 LogicalType::Boolean => {
4264 let values = cur.take(rows)?;
4265 if values.iter().any(|value| *value > 1) {
4266 return Err(invalid("boolean page has another value"));
4267 }
4268 Data::Bool(values.iter().map(|value| *value == 1).collect::<Vec<_>>().into())
4269 }
4270 LogicalType::Varchar => {
4271 let offset_bytes = cur
4272 .take((rows + 1).checked_mul(4).ok_or_else(|| invalid("offset count overflow"))?)?;
4273 let offsets = offset_bytes
4274 .chunks_exact(4)
4275 .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
4276 .collect::<Vec<_>>();
4277 let payload = cur.take(bytes.len() - cur.at)?.to_vec();
4278 if offsets.first() != Some(&0)
4279 || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
4280 || offsets.windows(2).any(|pair| pair[0] > pair[1])
4281 {
4282 return Err(invalid("string offsets do not bound the payload"));
4283 }
4284 let mut values = StringColumn::over(Buffer::from_vec(payload));
4285 for pair in offsets.windows(2) {
4286 values.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
4287 }
4288 Data::Varlen(values)
4289 }
4290 _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
4291 };
4292 if cur.at != bytes.len() {
4293 return Err(invalid("page has trailing bytes"));
4294 }
4295 Ok(Vector::flat(ty.clone(), data)?.with_validity(validity))
4296}
4297
4298#[cfg(test)]
4299mod tests {
4300 use std::fs;
4301 use std::io::{Seek, SeekFrom, Write};
4302 use std::path::PathBuf;
4303 use std::time::{SystemTime, UNIX_EPOCH};
4304
4305 use rudb_common::Value;
4306 use rudb_common::bounds::Op;
4307
4308 use super::*;
4309
4310 #[test]
4311 fn checksum_matches_fixed_vectors() {
4312 assert_eq!(checksum(b""), 0xef46_db37_51d8_e999);
4313 assert_eq!(checksum(b"a"), 0xd24e_c4f1_a98c_6e5b);
4314 assert_eq!(checksum(b"abc"), 0x44bc_2cf5_ad77_0999);
4315 }
4316
4317 fn path(label: &str) -> PathBuf {
4318 let stamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("time advances").as_nanos();
4319 std::env::temp_dir().join(format!("rudb-native-{label}-{}-{stamp}.rdb", std::process::id()))
4320 }
4321
4322 #[test]
4324 fn a_read_at_an_offset_ignores_where_another_thread_left_the_cursor() {
4325 const SPANS: usize = 64;
4326 const SPAN: usize = 512;
4327 let path = path("positional");
4328 let content: Vec<u8> =
4329 (0..SPANS).flat_map(|span| std::iter::repeat_n(span as u8, SPAN)).collect();
4330 fs::write(&path, &content).expect("the file is written");
4331 let file = Arc::new(File::open(&path).expect("the file opens"));
4332 std::thread::scope(|scope| {
4333 for _ in 0..8 {
4334 let file = Arc::clone(&file);
4335 scope.spawn(move || {
4336 for _ in 0..64 {
4337 for span in 0..SPANS {
4338 let mut bytes = [0_u8; SPAN];
4339 read_at(&file, (span * SPAN) as u64, &mut bytes)
4340 .expect("the span reads");
4341 assert!(
4342 bytes.iter().all(|byte| *byte == span as u8),
4343 "span {span} came back as {}",
4344 bytes[0],
4345 );
4346 }
4347 }
4348 });
4349 }
4350 });
4351 let mut past = [0_u8; SPAN];
4352 let end = (SPANS * SPAN) as u64;
4353 let error = read_at(&file, end, &mut past).expect_err("a read past the end is refused");
4354 assert!(error.message().contains("ends before its declared length"), "{error}");
4355 drop(file);
4356 let _ = fs::remove_file(&path);
4357 }
4358
4359 #[test]
4365 fn a_writer_puts_a_page_where_it_said_it_did_wherever_the_cursor_has_got_to() {
4366 let path = path("cursor");
4367 let mut writer = Writer::create(
4368 &path,
4369 "items",
4370 vec![
4371 Field::required("id", LogicalType::Integer),
4372 Field::new("text", LogicalType::Varchar),
4373 ],
4374 )
4375 .expect("new file");
4376 writer.append(&sample()).expect("first part");
4377 writer.file.seek(SeekFrom::Start(0)).expect("the cursor goes back to the header");
4378 writer.append(&sample()).expect("second part");
4379 writer.file.seek(SeekFrom::Start(1)).expect("and somewhere useless again");
4380 writer.finish().expect("commit");
4381 let reader = Reader::open(&path).expect("reopen from disk");
4382 assert_eq!(reader.table().rows(), 6);
4383 let ids = reader.read(0, &[0]).expect("the integer page reads back");
4384 assert_eq!(ids.value_at(0, 0), Value::Integer(4));
4385 assert_eq!(ids.value_at(2, 0), Value::Integer(-2));
4386 let text = reader.read(1, &[1]).expect("the text page reads back");
4387 assert_eq!(text.value_at(1, 0), Value::Null);
4388 assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4389 let end = reader.table().stripes().iter().flat_map(|stripe| {
4392 stripe
4393 .pages
4394 .iter()
4395 .map(|page| page.offset + u64::from(page.length))
4396 .chain(std::iter::once(stripe.index.offset + u64::from(stripe.index.length)))
4397 });
4398 let last = end.fold(HEADER, u64::max);
4399 let directory = fs::metadata(&path).expect("the file is there").len();
4400 assert!(last <= directory, "a page runs to {last} in a file of {directory} bytes");
4401 fs::remove_file(path).expect("remove scratch file");
4402 }
4403
4404 fn sample() -> Chunk {
4405 Chunk::new(vec![
4406 Vector::from_values(
4407 LogicalType::Integer,
4408 &[Value::Integer(4), Value::Integer(9), Value::Integer(-2)],
4409 )
4410 .expect("integers"),
4411 Vector::from_values(
4412 LogicalType::Varchar,
4413 &[
4414 Value::Varchar("alpha".into()),
4415 Value::Null,
4416 Value::Varchar("long text after a slash".into()),
4417 ],
4418 )
4419 .expect("strings"),
4420 ])
4421 .expect("matching rows")
4422 }
4423
4424 fn sample_ids() -> Chunk {
4425 Chunk::new(vec![
4426 Vector::flat(LogicalType::Integer, Data::Int32(vec![7, 8, 9].into()))
4427 .expect("integers"),
4428 ])
4429 .expect("one column")
4430 }
4431
4432 #[test]
4433 fn committed_file_reopens_and_reads_only_requested_columns() {
4434 let path = path("reopen");
4435 let mut writer = Writer::create(
4436 &path,
4437 "items",
4438 vec![
4439 Field::required("id", LogicalType::Integer),
4440 Field::new("text", LogicalType::Varchar),
4441 ],
4442 )
4443 .expect("new file");
4444 writer.append(&sample()).expect("first part");
4445 writer.append(&sample()).expect("second part");
4446 writer.finish().expect("commit");
4447 let reader = Reader::open(&path).expect("reopen from disk");
4448 assert_eq!(reader.table().rows(), 6);
4449 assert_eq!(reader.table().stripes().len(), 1);
4452 assert_eq!(reader.parts(), 2);
4453 assert_eq!(reader.part_rows(0), 3);
4454 assert_eq!(reader.part_rows(1), 3);
4455 let text = reader.read(1, &[1]).expect("only text page");
4456 assert_eq!(text.width(), 1);
4457 assert_eq!(text.value_at(1, 0), Value::Null);
4458 assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4459 let sparse = reader.read_sparse(1, &[1]).expect("one part without its whole page");
4460 assert_eq!(sparse.width(), 1);
4461 assert_eq!(sparse.value_at(1, 0), Value::Null);
4462 assert_eq!(sparse.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4463 assert!(!reader.skips_codes(0, 1, &[0]).expect("alpha is in the stripe"));
4464 assert!(!reader.skips_codes(0, 1, &[2]).expect("long text is in the stripe"));
4465 assert!(reader.skips_codes(0, 1, &[3]).expect("unknown code is absent"));
4466 let count = reader.read(0, &[]).expect("no page is needed for count");
4467 assert_eq!(count.len(), 3);
4468 assert!(reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }]));
4469 assert!(!reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(0) }]));
4470 let integers = reader.top_frequencies(0, 1).expect("valid integer synopsis").expect("kept");
4471 assert_eq!(
4472 integers,
4473 vec![(Value::Integer(-2), 2), (Value::Integer(4), 2), (Value::Integer(9), 2),]
4474 );
4475 let strings = reader.top_frequencies(1, 1).expect("valid string synopsis").expect("kept");
4476 assert_eq!(strings.len(), 3);
4477 assert!(strings.contains(&(Value::Null, 2)));
4478 assert!(strings.contains(&(Value::Varchar("alpha".into()), 2)));
4479 assert!(strings.contains(&(Value::Varchar("long text after a slash".into()), 2)));
4480 fs::remove_file(path).expect("remove scratch file");
4481 }
4482
4483 #[test]
4491 fn runs_handed_over_out_of_order_still_read_back_in_source_order() {
4492 let path = path("interleaved-runs");
4493 let mut writer =
4494 Writer::create(&path, "interleaved", vec![Field::new("v", LogicalType::BigInt)])
4495 .expect("new file");
4496 for morsel in [2_u64, 0, 3, 1] {
4497 let parts = (0..4_u64)
4498 .map(|chunk| {
4499 let first = i64::try_from(morsel * 32 + chunk * 8).expect("small");
4500 let values =
4501 (0..8_i64).map(|row| Value::BigInt(first + row)).collect::<Vec<_>>();
4502 let column =
4503 Vector::from_values(LogicalType::BigInt, &values).expect("a column");
4504 ((morsel, chunk), Chunk::new(vec![column]).expect("one column"))
4505 })
4506 .collect::<Vec<_>>();
4507 writer.append_stripe(parts).expect("a stripe");
4508 }
4509 writer.finish().expect("commit");
4510
4511 let reader = Reader::open(&path).expect("valid directory");
4512 assert_eq!(reader.table().stripes().len(), 4, "a run is a stripe of its own");
4513 assert_eq!(reader.table().rows(), 128);
4514 for part in 0..16_usize {
4515 let read = reader.read(part, &[0]).expect("a part back");
4516 for row in 0..8_usize {
4517 let want = i64::try_from(part * 8 + row).expect("small");
4518 assert_eq!(read.value_at(row, 0), Value::BigInt(want), "part {part} row {row}");
4519 }
4520 }
4521 fs::remove_file(path).expect("remove scratch file");
4522 }
4523
4524 #[test]
4527 fn runs_that_overlap_each_other_are_refused_at_commit() {
4528 let path = path("overlapping-runs");
4529 let mut writer =
4530 Writer::create(&path, "overlapping", vec![Field::new("v", LogicalType::BigInt)])
4531 .expect("new file");
4532 let one = |order: (u64, u64)| {
4533 let column =
4534 Vector::from_values(LogicalType::BigInt, &[Value::BigInt(1)]).expect("a column");
4535 (order, Chunk::new(vec![column]).expect("one column"))
4536 };
4537 writer.append_stripe(vec![one((0, 0)), one((0, 2))]).expect("a stripe");
4540 writer.append_stripe(vec![one((0, 1))]).expect("a stripe");
4541 let error = writer.finish().expect_err("the runs overlap");
4542 assert!(error.message().contains("source order"), "{error}");
4543 fs::remove_file(path).expect("remove scratch file");
4544 }
4545
4546 #[test]
4549 fn a_run_longer_than_a_stripe_is_refused() {
4550 let path = path("overlong-run");
4551 let mut writer =
4552 Writer::create(&path, "overlong", vec![Field::new("v", LogicalType::BigInt)])
4553 .expect("new file");
4554 let parts = (0..=STRIPE_PARTS)
4555 .map(|at| {
4556 let column = Vector::from_values(LogicalType::BigInt, &[Value::BigInt(1)])
4557 .expect("a column");
4558 let chunk = Chunk::new(vec![column]).expect("one column");
4559 ((0, u64::try_from(at).expect("small")), chunk)
4560 })
4561 .collect::<Vec<_>>();
4562 let error = writer.append_stripe(parts).expect_err("one part too many");
4563 assert!(error.message().contains("more parts than it holds"), "{error}");
4564 fs::remove_file(path).expect("remove scratch file");
4565 }
4566
4567 #[test]
4573 fn parts_past_the_stripe_bound_start_a_new_stripe() {
4574 let path = path("stripe-bound");
4575 let mut writer = Writer::create(
4576 &path,
4577 "items",
4578 vec![
4579 Field::required("id", LogicalType::Integer),
4580 Field::new("text", LogicalType::Varchar),
4581 ],
4582 )
4583 .expect("new file");
4584 let parts = STRIPE_PARTS * 2 + 3;
4585 for part in 0..parts {
4586 let id = part as i32;
4587 let chunk = Chunk::new(vec![
4588 Vector::from_values(
4589 LogicalType::Integer,
4590 &[Value::Integer(id), Value::Integer(-id)],
4591 )
4592 .expect("integers"),
4593 Vector::from_values(
4594 LogicalType::Varchar,
4595 &[Value::Varchar(format!("value {part}")), Value::Null],
4596 )
4597 .expect("strings"),
4598 ])
4599 .expect("matching rows");
4600 writer.append(&chunk).expect("one part");
4601 }
4602 writer.finish().expect("commit");
4603
4604 let reader = Reader::open(&path).expect("reopen from disk");
4605 assert_eq!(reader.parts(), parts);
4606 assert_eq!(reader.table().rows(), parts * 2);
4607 assert_eq!(reader.table().stripes().len(), parts.div_ceil(STRIPE_PARTS));
4608 assert_eq!(reader.table().stripes()[0].parts(), STRIPE_PARTS);
4609 assert_eq!(reader.table().stripes()[0].rows(), STRIPE_PARTS * 2);
4610 assert_eq!(reader.table().stripes()[2].parts(), 3);
4611 for part in (0..parts).rev() {
4614 let dense = reader.read(part, &[0, 1]).expect("a whole page read");
4615 let sparse = reader.read_sparse(part, &[0, 1]).expect("one part read");
4616 for chunk in [&dense, &sparse] {
4617 assert_eq!(chunk.len(), 2, "part {part} has its own row count");
4618 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4619 assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
4620 assert_eq!(chunk.value_at(0, 1), Value::Varchar(format!("value {part}")));
4621 assert_eq!(chunk.value_at(1, 1), Value::Null);
4622 }
4623 }
4624 let above = [Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }];
4627 assert!(reader.skips(0, &above), "the first stripe stops at 63");
4628 assert!(!reader.skips(STRIPE_PARTS * 2, &above), "the third stripe reaches 130");
4629 fs::remove_file(path).expect("remove scratch file");
4630 }
4631
4632 fn scattered(n: i64) -> i64 {
4634 n.wrapping_mul(-7_046_029_254_386_353_131)
4635 }
4636
4637 #[test]
4643 fn a_part_is_skipped_when_its_sieve_does_not_hold_the_constant() {
4644 let path = path("sieve-skip");
4645 let mut writer =
4646 Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
4647 .expect("new file");
4648 let parts = STRIPE_PARTS + 3;
4649 let per_part = 8;
4650 for part in 0..parts {
4651 let held: Vec<Value> = (0..per_part)
4652 .map(|row| Value::BigInt(scattered((part * per_part + row) as i64)))
4653 .collect();
4654 let chunk =
4655 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
4656 .expect("one column");
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 probe = |value: i64| Probe {
4663 column: 0,
4664 op: Op::Equal,
4665 value: Bound::Int(i128::from(scattered(value))),
4666 };
4667 for wanted in [0_i64, 9, (parts * per_part - 1) as i64] {
4668 let tests = [probe(wanted)];
4669 let kept: Vec<usize> = (0..parts).filter(|&part| !reader.skips(part, &tests)).collect();
4670 let home = wanted as usize / per_part;
4671 assert_eq!(kept, vec![home], "only the part holding {wanted} is read");
4672 }
4673 let absent = [probe((parts * per_part) as i64 + 1)];
4674 assert!((0..parts).all(|part| reader.skips(part, &absent)), "no part holds it");
4675 let tests = [probe(0)];
4678 assert!(
4679 reader.table().stripes().iter().all(|stripe| !stripe.zone.skips(&tests)),
4680 "the bounds rule out no stripe at all"
4681 );
4682 fs::remove_file(path).expect("remove scratch file");
4683 }
4684
4685 #[test]
4691 fn a_damaged_sieve_page_is_read_through_rather_than_refused() {
4692 let path = path("sieve-damaged");
4693 let mut writer =
4694 Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
4695 .expect("new file");
4696 let held: Vec<Value> = (0..8).map(|row| Value::BigInt(scattered(row))).collect();
4697 let chunk =
4698 Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
4699 .expect("one column");
4700 writer.append(&chunk).expect("one part");
4701 writer.finish().expect("commit");
4702
4703 let page =
4704 Reader::open(&path).expect("reopen").table.stripes[0].sieves[0].expect("a sieve page");
4705 let mut file = OpenOptions::new().write(true).open(&path).expect("open the sieve page");
4706 file.seek(SeekFrom::Start(page.offset + u64::from(page.length) - 1)).expect("seek");
4707 file.write_all(&[0xff]).expect("damage one byte");
4708 drop(file);
4709
4710 let reader = Reader::open(&path).expect("reopen the damaged file");
4711 let absent =
4712 [Probe { column: 0, op: Op::Equal, value: Bound::Int(i128::from(scattered(99))) }];
4713 assert!(!reader.skips(0, &absent), "a sieve that cannot be read skips nothing");
4714 assert_eq!(reader.read(0, &[0]).expect("the rows are untouched").len(), 8);
4715 fs::remove_file(path).expect("remove scratch file");
4716 }
4717
4718 #[test]
4729 fn workers_that_want_the_same_stripe_read_it_once() {
4730 let path = path("single-flight");
4731 let mut writer =
4732 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4733 .expect("new file");
4734 for part in 0..STRIPE_PARTS {
4735 let id = part as i32;
4736 let chunk = Chunk::new(vec![
4737 Vector::from_values(
4738 LogicalType::Integer,
4739 &[Value::Integer(id), Value::Integer(-id)],
4740 )
4741 .expect("integers"),
4742 ])
4743 .expect("matching rows");
4744 writer.append(&chunk).expect("one part");
4745 }
4746 writer.finish().expect("commit");
4747
4748 let reader = Reader::open(&path).expect("reopen from disk");
4749 assert_eq!(reader.table().stripes().len(), 1, "one stripe is the point of the test");
4750 let barrier = std::sync::Barrier::new(8);
4751 std::thread::scope(|scope| {
4752 for worker in 0..8 {
4753 let reader = &reader;
4754 let barrier = &barrier;
4755 scope.spawn(move || {
4756 barrier.wait();
4757 for part in (worker..STRIPE_PARTS).step_by(8) {
4758 let chunk = reader.read(part, &[0]).expect("a whole page read");
4759 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4760 assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
4761 }
4762 });
4763 }
4764 });
4765 assert_eq!(reader.pages.load(Atomic::Relaxed), 1, "one stripe, one page read, whoever won");
4766 fs::remove_file(path).expect("remove scratch file");
4767 }
4768
4769 #[test]
4782 fn opening_costs_the_same_over_a_thousand_times_the_rows() {
4783 let opened = |label: &str, rows_per_part: i32| {
4784 let path = path(label);
4785 let mut writer =
4786 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4787 .expect("new file");
4788 for part in 0..STRIPE_PARTS * 3 {
4789 let values = (0..rows_per_part)
4793 .map(|row| {
4794 Value::Integer((part as i32 * rows_per_part + row).wrapping_mul(2_654_435))
4795 })
4796 .collect::<Vec<_>>();
4797 let chunk = Chunk::new(vec![
4798 Vector::from_values(LogicalType::Integer, &values).expect("integers"),
4799 ])
4800 .expect("matching rows");
4801 writer.append(&chunk).expect("one part");
4802 }
4803 writer.finish().expect("commit");
4804 let reader = Reader::open(&path).expect("reopen from disk");
4805 let size = fs::metadata(&path).expect("the file is there").len();
4806 let out = (reader.reads(), reader.table().stripes().len(), size);
4807 fs::remove_file(path).expect("remove scratch file");
4808 out
4809 };
4810
4811 let (thin, thin_stripes, thin_size) = opened("open-thin", 1);
4812 let (fat, fat_stripes, fat_size) = opened("open-fat", 1000);
4813 assert_eq!(
4814 thin_stripes, fat_stripes,
4815 "the same stripe count is what makes this a fair ask"
4816 );
4817 assert!(
4818 fat_size > thin_size * 50,
4819 "the fat file has to actually be larger, and it is {fat_size} against {thin_size}"
4820 );
4821
4822 assert_eq!(thin.opening.reads, fat.opening.reads, "the same reads either way");
4823 assert_eq!(thin.pages, 0, "opening read a page");
4824 assert_eq!(fat.pages, 0, "opening read a page");
4825 assert_eq!(thin.indexes, 0, "opening read an index");
4826 assert_eq!(fat.indexes, 0, "opening read an index");
4827 assert!(
4830 fat.opening.bytes < thin.opening.bytes * 2,
4831 "opening the thin file read {} bytes and the fat one read {}",
4832 thin.opening.bytes,
4833 fat.opening.bytes
4834 );
4835 }
4836
4837 #[test]
4845 fn two_opens_of_one_file_cost_the_same_and_the_second_is_not_cheaper() {
4846 let path = path("open-twice");
4847 let mut writer =
4848 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4849 .expect("new file");
4850 for part in 0..STRIPE_PARTS * 3 {
4851 let chunk = Chunk::new(vec![
4852 Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
4853 .expect("integers"),
4854 ])
4855 .expect("matching rows");
4856 writer.append(&chunk).expect("one part");
4857 }
4858 writer.finish().expect("commit");
4859
4860 let first = Reader::open(&path).expect("open");
4861 for part in 0..first.parts() {
4864 first.read(part, &[0]).expect("a part");
4865 }
4866 assert!(first.reads().pages > 0, "the scan has to have read something");
4867 let second = Reader::open(&path).expect("open again");
4868
4869 assert_eq!(first.reads().opening, second.reads().opening);
4870 assert_eq!(
4871 second.reads().pages,
4872 0,
4873 "the second open read a page off the back of the first"
4874 );
4875 assert_eq!(second.reads().indexes, 0, "the second open read an index it inherited");
4876 fs::remove_file(path).expect("remove scratch file");
4877 }
4878
4879 #[test]
4887 fn an_index_is_read_once_per_stripe_however_often_the_page_is_evicted() {
4888 let path = path("index-cache");
4889 let mut writer =
4890 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4891 .expect("new file");
4892 let parts = STRIPE_PARTS * (CACHED_STRIPES_PER_COLUMN + 2);
4893 for part in 0..parts {
4894 let id = part as i32;
4895 let chunk = Chunk::new(vec![
4896 Vector::from_values(LogicalType::Integer, &[Value::Integer(id)]).expect("integers"),
4897 ])
4898 .expect("matching rows");
4899 writer.append(&chunk).expect("one part");
4900 }
4901 writer.finish().expect("commit");
4902
4903 let reader = Reader::open(&path).expect("reopen from disk");
4904 let stripes = reader.table().stripes().len();
4905 assert!(stripes > CACHED_STRIPES_PER_COLUMN, "the page cache has to be too small for this");
4906 for _ in 0..2 {
4908 for part in 0..parts {
4909 let chunk = reader.read(part, &[0]).expect("a part");
4910 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4911 }
4912 }
4913 assert_eq!(reader.indexes.load(Atomic::Relaxed), stripes, "one index read per stripe");
4914 assert!(
4915 reader.pages.load(Atomic::Relaxed) > stripes,
4916 "the pages are the ones that get read again, which is what makes the index count mean \
4917 something"
4918 );
4919 fs::remove_file(path).expect("remove scratch file");
4920 }
4921
4922 #[test]
4931 fn a_worker_per_stripe_reads_its_page_once_when_the_cache_was_told_to_expect_it() {
4932 let workers = CACHED_STRIPES_PER_COLUMN + 4;
4933 let path = path("stripe-per-worker");
4934 let mut writer =
4935 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4936 .expect("new file");
4937 for part in 0..STRIPE_PARTS * workers {
4938 let chunk = Chunk::new(vec![
4939 Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
4940 .expect("integers"),
4941 ])
4942 .expect("matching rows");
4943 writer.append(&chunk).expect("one part");
4944 }
4945 writer.finish().expect("commit");
4946
4947 let read = |told: bool| {
4948 let reader = Reader::open(&path).expect("reopen from disk");
4949 assert_eq!(reader.table().stripes().len(), workers, "a stripe per worker");
4950 if told {
4951 reader.keep_stripes(workers);
4952 }
4953 let barrier = std::sync::Barrier::new(workers);
4954 std::thread::scope(|scope| {
4955 for (worker, run) in reader.stripe_parts().into_iter().enumerate() {
4956 let reader = &reader;
4957 let barrier = &barrier;
4958 scope.spawn(move || {
4959 for part in run {
4960 barrier.wait();
4961 let chunk = reader.read(part, &[0]).expect("a part of my own stripe");
4962 assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4963 }
4964 assert!(worker < workers);
4965 });
4966 }
4967 });
4968 reader.pages.load(Atomic::Relaxed)
4969 };
4970
4971 assert_eq!(read(true), workers, "one page read per stripe and no more");
4972 assert!(read(false) > workers, "a cache that small is read again on every part");
4973 fs::remove_file(path).expect("remove scratch file");
4974 }
4975
4976 #[test]
4981 fn a_damaged_index_page_is_an_error() {
4982 let path = path("damaged-index");
4983 let mut writer =
4984 Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4985 .expect("new file");
4986 writer.append(&sample_ids()).expect("first part");
4987 writer.append(&sample_ids()).expect("second part");
4988 writer.finish().expect("commit");
4989
4990 let reader = Reader::open(&path).expect("valid directory");
4991 let index = reader.table.stripes[0].index;
4992 let mut byte = [0; 1];
4993 read_at(&reader.file, index.offset, &mut byte).expect("the first part length");
4994 let mut file = OpenOptions::new().write(true).open(&path).expect("open index page");
4995 file.seek(SeekFrom::Start(index.offset)).expect("index start");
4996 file.write_all(&[!byte[0]]).expect("damage the first part length");
4997 let error = reader.read(1, &[0]).expect_err("a damaged index must not be used");
4998 assert!(error.message().contains("index page section checksum differs"), "{error}");
4999 fs::remove_file(path).expect("remove scratch file");
5000 }
5001
5002 #[test]
5009 fn every_integer_width_round_trips_through_a_page() {
5010 let path = path("integer-widths");
5011 let columns = [
5012 (LogicalType::TinyInt, vec![Value::TinyInt(i8::MIN), Value::TinyInt(i8::MAX)]),
5013 (LogicalType::UTinyInt, vec![Value::UTinyInt(0), Value::UTinyInt(u8::MAX)]),
5014 (LogicalType::SmallInt, vec![Value::SmallInt(i16::MIN), Value::SmallInt(i16::MAX)]),
5015 (LogicalType::USmallInt, vec![Value::USmallInt(0), Value::USmallInt(u16::MAX)]),
5016 (LogicalType::Integer, vec![Value::Integer(i32::MIN), Value::Integer(i32::MAX)]),
5017 (LogicalType::UInteger, vec![Value::UInteger(0), Value::UInteger(u32::MAX)]),
5018 (LogicalType::BigInt, vec![Value::BigInt(i64::MIN), Value::BigInt(i64::MAX)]),
5019 (LogicalType::UBigInt, vec![Value::UBigInt(0), Value::UBigInt(u64::MAX)]),
5020 ];
5021 let fields = columns
5022 .iter()
5023 .enumerate()
5024 .map(|(at, (ty, _))| Field::required(format!("c{at}"), ty.clone()))
5025 .collect::<Vec<_>>();
5026 let vectors = columns
5027 .iter()
5028 .map(|(ty, values)| Vector::from_values(ty.clone(), values).expect("a vector"))
5029 .collect::<Vec<_>>();
5030 let mut writer = Writer::create(&path, "widths", fields).expect("new file");
5031 writer.append(&Chunk::new(vectors).expect("matching rows")).expect("one stripe");
5032 writer.finish().expect("commit");
5033
5034 let reader = Reader::open(&path).expect("reopen from disk");
5035 let wanted = (0..columns.len()).collect::<Vec<_>>();
5036 let read = reader.read(0, &wanted).expect("every column");
5037 assert_eq!(read.len(), 2);
5038 for (at, (ty, values)) in columns.iter().enumerate() {
5040 assert_eq!(read.value_at(0, at), values[0], "the low end of {ty}");
5041 assert_eq!(read.value_at(1, at), values[1], "the high end of {ty}");
5042 }
5043 fs::remove_file(path).expect("remove scratch file");
5044 }
5045
5046 #[test]
5047 fn numeric_frequency_candidates_keep_bounded_row_ordinals() {
5048 let path = path("frequency-ordinals");
5049 let mut writer =
5050 Writer::create(&path, "items", vec![Field::required("id", LogicalType::BigInt)])
5051 .expect("new file");
5052 let mut values = Vec::new();
5053 for leader in 0..10_i64 {
5054 values.extend(std::iter::repeat_n(leader, 100));
5055 }
5056 values.extend(1_000_i64..41_000);
5057 for part in values.chunks(1_024) {
5058 let vector = Vector::flat(LogicalType::BigInt, Data::Int64(part.to_vec().into()))
5059 .expect("big integers");
5060 writer.append(&Chunk::new(vec![vector]).expect("one column")).expect("one stripe");
5061 }
5062 writer.finish().expect("commit");
5063
5064 let reader = Reader::open(&path).expect("reopen from disk");
5065 let occurrences =
5066 reader.frequency_occurrences(0).expect("valid metadata").expect("bounded ordinals");
5067 assert!(occurrences.omitted_max < 100);
5068 assert!(occurrences.ordinals.len() <= FREQUENCY_ORDINALS);
5069 assert!(occurrences.ordinals.windows(2).all(|pair| pair[0] < pair[1]));
5070 assert_eq!(&occurrences.ordinals[..1_000], &(0_u64..1_000).collect::<Vec<_>>());
5071 fs::remove_file(path).expect("remove scratch file");
5072 }
5073
5074 #[test]
5080 fn a_file_from_another_format_says_which_format_it_is() {
5081 let older = path("older-format");
5082 let mut writer =
5083 Writer::create(&older, "items", vec![Field::new("id", LogicalType::Integer)])
5084 .expect("new file");
5085 let chunk = Chunk::new(vec![
5086 Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
5087 .expect("integers"),
5088 ])
5089 .expect("chunk");
5090 writer.append(&chunk).expect("page written");
5091 writer.finish().expect("commit");
5092
5093 let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
5094 file.seek(SeekFrom::Start(8)).expect("the version follows the magic");
5095 file.write_all(&(FORMAT - 1).to_le_bytes()).expect("write an older version");
5096 drop(file);
5097 let complaint = Reader::open(&older).expect_err("an older format is refused").to_string();
5098 assert!(complaint.contains(&format!("format {}", FORMAT - 1)), "{complaint}");
5099 assert!(complaint.contains(&format!("format {FORMAT}")), "{complaint}");
5100
5101 let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
5102 file.seek(SeekFrom::Start(0)).expect("the magic is first");
5103 file.write_all(b"NOTRUDB!").expect("write another engine's magic");
5104 drop(file);
5105 let complaint = Reader::open(&older).expect_err("a foreign file is refused").to_string();
5106 assert!(complaint.contains("magic"), "{complaint}");
5107 assert!(!complaint.contains("format"), "a version has nothing to do with it: {complaint}");
5108 fs::remove_file(older).expect("remove scratch file");
5109 }
5110
5111 #[test]
5112 fn an_unfinished_or_damaged_file_does_not_answer_with_partial_rows() {
5113 let unfinished = path("unfinished");
5114 let mut writer =
5115 Writer::create(&unfinished, "items", vec![Field::new("id", LogicalType::Integer)])
5116 .expect("new file");
5117 let chunk = Chunk::new(vec![
5118 Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
5119 .expect("integers"),
5120 ])
5121 .expect("chunk");
5122 writer.append(&chunk).expect("page written");
5123 drop(writer);
5124 assert!(Reader::open(&unfinished).is_err(), "no directory was committed");
5125 fs::remove_file(unfinished).expect("remove scratch file");
5126
5127 let damaged = path("damaged");
5128 let mut writer =
5129 Writer::create(&damaged, "items", vec![Field::new("id", LogicalType::Integer)])
5130 .expect("new file");
5131 writer.append(&chunk).expect("page written");
5132 writer.finish().expect("commit");
5133 let reader = Reader::open(&damaged).expect("valid directory");
5134 let mut file =
5135 OpenOptions::new().write(true).open(&damaged).expect("open for a damaged page");
5136 file.seek(SeekFrom::Start(HEADER + 1)).expect("inside first page");
5137 file.write_all(&[255]).expect("damage one byte");
5138 assert!(reader.read(0, &[0]).is_err(), "page checksum rejects corruption");
5139 fs::remove_file(damaged).expect("remove scratch file");
5140 }
5141
5142 #[test]
5143 fn damaged_lazy_dictionary_payload_is_an_error() {
5144 let path = path("damaged-dictionary");
5145 let mut writer = Writer::create(
5146 &path,
5147 "items",
5148 vec![
5149 Field::required("id", LogicalType::Integer),
5150 Field::new("text", LogicalType::Varchar),
5151 ],
5152 )
5153 .expect("new file");
5154 writer.append(&sample()).expect("stripe written");
5155 writer.finish().expect("commit");
5156
5157 let reader = Reader::open(&path).expect("valid directory");
5158 let dictionary = reader.table.dictionaries[1].expect("string dictionary page");
5159 let mut header = [0; 12];
5162 read_at(&reader.file, dictionary.offset, &mut header).expect("dictionary header");
5163 let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
5164 let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
5165 let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
5166 let index_len =
5167 12 + (count + 1) * 4 + (blocks + rank_blocks) * 8 + count * RANK_ENTRY as u64;
5168 let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
5169 file.seek(SeekFrom::Start(dictionary.offset + index_len))
5170 .expect("inside dictionary payload");
5171 file.write_all(&[255]).expect("damage dictionary payload");
5172
5173 let chunk = reader.read(0, &[1]).expect("code page and dictionary index remain valid");
5174 let error =
5175 chunk.validate_external().expect_err("payload corruption must reach the caller");
5176 assert!(error.message().contains("payload checksum differs"), "{error}");
5177 fs::remove_file(path).expect("remove scratch file");
5178 }
5179
5180 #[test]
5187 fn a_dictionary_over_one_extent_checks_every_block_of_it() {
5188 let path = path("dictionary-extents");
5189 let value =
5190 |row: usize| format!("{row:07} a value long enough to be worth a payload block");
5191 let parts = 30;
5192 let per_part = 1000;
5193 let mut writer =
5194 Writer::create(&path, "items", vec![Field::required("text", LogicalType::Varchar)])
5195 .expect("new file");
5196 for part in 0..parts {
5197 let values = (0..per_part)
5198 .map(|row| Value::Varchar(value(part * per_part + row)))
5199 .collect::<Vec<_>>();
5200 let chunk = Chunk::new(vec![
5201 Vector::from_values(LogicalType::Varchar, &values).expect("strings"),
5202 ])
5203 .expect("matching rows");
5204 writer.append(&chunk).expect("a part");
5205 }
5206 writer.finish().expect("commit");
5207
5208 let reader = Reader::open(&path).expect("reopen from disk");
5209 let dictionary = reader.table.dictionaries[0].expect("string dictionary page");
5210 assert!(
5211 dictionary.length as usize > TEXT_PAYLOAD_BLOCK * TEXT_PAYLOAD_EXTENT,
5212 "the dictionary has to be over one extent for this to be testing anything"
5213 );
5214 for part in [0, parts - 1] {
5215 let chunk = reader.read(part, &[0]).expect("a part");
5216 chunk.validate_external().expect("every payload block checks out");
5217 assert_eq!(chunk.value_at(0, 0), Value::Varchar(value(part * per_part)));
5218 }
5219
5220 let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
5221 file.seek(SeekFrom::Start(dictionary.offset + u64::from(dictionary.length) - 4))
5222 .expect("the last bytes of the page are payload");
5223 file.write_all(&[255]).expect("damage the last payload block");
5224 let reader = Reader::open(&path).expect("the directory and the index are untouched");
5225 let chunk = reader.read(parts - 1, &[0]).expect("the code page remains valid");
5226 let error = chunk.validate_external().expect_err("the damage must reach the caller");
5227 assert!(error.message().contains("payload checksum differs"), "{error}");
5228 fs::remove_file(path).expect("remove scratch file");
5229 }
5230
5231 #[test]
5236 fn a_damaged_sorted_order_is_an_error() {
5237 let path = path("damaged-order");
5238 let mut writer = Writer::create(
5239 &path,
5240 "items",
5241 vec![
5242 Field::required("id", LogicalType::Integer),
5243 Field::new("text", LogicalType::Varchar),
5244 ],
5245 )
5246 .expect("new file");
5247 writer.append(&sample()).expect("stripe written");
5248 writer.finish().expect("commit");
5249
5250 let reader = Reader::open(&path).expect("valid directory");
5251 let page = reader.table.dictionaries[1].expect("string dictionary page");
5252 let mut header = [0; 12];
5253 read_at(&reader.file, page.offset, &mut header).expect("dictionary header");
5254 let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
5255 let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
5256 let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
5257 let index_len = 12 + (count + 1) * 4 + (blocks + rank_blocks) * 8;
5258 let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
5259 file.seek(SeekFrom::Start(page.offset + index_len)).expect("the first head");
5260 file.write_all(&[255]).expect("damage the order");
5261
5262 let dictionary = reader.dictionary(1).expect("read").expect("a string column has one");
5263 let error = dictionary.compare_rank(0, b"anything").expect_err("a damaged order is caught");
5264 assert!(error.message().contains("rank checksum differs"), "{error}");
5265 fs::remove_file(path).expect("remove scratch file");
5266 }
5267
5268 #[test]
5272 fn a_global_dictionary_carries_the_sorted_order_of_its_values() {
5273 let spellings = ["overlong1z", "b", "", "overlong1a", "overlong", "ab", "a", "overlong1"];
5276 let path = path("dictionary-order");
5277 let mut writer =
5278 Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
5279 .expect("new file");
5280 writer
5281 .append(
5282 &Chunk::new(vec![
5283 Vector::from_values(
5284 LogicalType::Varchar,
5285 &spellings.map(|text| Value::Varchar(text.into())),
5286 )
5287 .expect("strings"),
5288 ])
5289 .expect("one column"),
5290 )
5291 .expect("stripe written");
5292 writer.finish().expect("commit");
5293
5294 let reader = Reader::open(&path).expect("valid directory");
5295 let dictionary = reader.dictionary(0).expect("read").expect("a string column has one");
5296 let count = dictionary.ranks().expect("a v10 file stores one");
5297 assert_eq!(count, spellings.len(), "every distinct value has a rank");
5298 let order = (0..count)
5299 .map(|rank| dictionary.code_at_rank(rank).expect("a code"))
5300 .collect::<Vec<_>>();
5301 let mut seen = order.clone();
5302 seen.sort_unstable();
5303 assert_eq!(seen, (0..spellings.len() as u32).collect::<Vec<_>>(), "a permutation of codes");
5304
5305 let ranked = order
5306 .iter()
5307 .map(|&code| {
5308 dictionary.try_bytes_at(code as usize).expect("read").expect("a value").to_vec()
5309 })
5310 .collect::<Vec<_>>();
5311 let mut expected = spellings.map(|text| text.as_bytes().to_vec()).to_vec();
5312 expected.sort();
5313 assert_eq!(ranked, expected, "rank order is value order");
5314
5315 for (rank, value) in expected.iter().enumerate() {
5318 assert_eq!(
5319 dictionary.compare_rank(rank, value).expect("compare"),
5320 Ordering::Equal,
5321 "rank {rank} is its own value"
5322 );
5323 if rank > 0 {
5324 assert_eq!(
5325 dictionary.compare_rank(rank - 1, value).expect("compare"),
5326 Ordering::Less,
5327 "rank {rank} follows the one before it"
5328 );
5329 }
5330 }
5331 fs::remove_file(path).expect("remove scratch file");
5332 }
5333
5334 #[test]
5335 fn damaged_membership_cannot_skip_a_string_page() {
5336 let path = path("damaged-membership");
5337 let mut writer = Writer::create(
5338 &path,
5339 "items",
5340 vec![
5341 Field::required("id", LogicalType::Integer),
5342 Field::new("text", LogicalType::Varchar),
5343 ],
5344 )
5345 .expect("new file");
5346 writer.append(&sample()).expect("stripe written");
5347 writer.finish().expect("commit");
5348
5349 let reader = Reader::open(&path).expect("valid directory");
5350 let membership = reader.table.stripes[0].memberships[1].expect("string membership");
5351 let mut file = OpenOptions::new().write(true).open(&path).expect("open membership page");
5352 file.seek(SeekFrom::Start(membership.offset)).expect("membership start");
5353 file.write_all(&[255]).expect("damage membership");
5354 let error = reader.skips_codes(0, 1, &[3]).expect_err("corruption must not skip rows");
5355 assert!(error.message().contains("membership page checksum differs"), "{error}");
5356 fs::remove_file(path).expect("remove scratch file");
5357 }
5358
5359 #[test]
5360 fn membership_delta_stream_is_sorted_exact_and_bounded() {
5361 let unique = unique_codes(&[900, 4, 4, 72, 9, u32::MAX]);
5362 assert_eq!(unique, [4, 9, 72, 900, u32::MAX]);
5363 let encoded = encode_membership(&unique);
5364 assert_eq!(
5365 decode_membership(&encoded).expect("valid membership"),
5366 [4, 9, 72, 900, u32::MAX]
5367 );
5368 let merged = merged_codes(vec![vec![4, 900], vec![9, 900, u32::MAX], vec![72]]);
5371 assert_eq!(merged, [4, 9, 72, 900, u32::MAX]);
5372 assert_eq!(
5373 decode_membership(&encode_membership(&merged)).expect("valid membership"),
5374 unique
5375 );
5376 assert!(decode_membership(&[1, 0x80]).is_err(), "a truncated varint is invalid");
5377 assert!(
5378 decode_membership(&[1, 0xff, 0xff, 0xff, 0xff, 0x10]).is_err(),
5379 "a value past u32 is invalid"
5380 );
5381 }
5382
5383 #[test]
5384 fn a_global_dictionary_may_be_larger_than_one_column_page() {
5385 let dictionary = Page {
5386 offset: HEADER,
5387 length: u32::try_from(MAX_PAGE + 1).expect("the page bound fits on disk"),
5388 hash: 0,
5389 };
5390 let table = Table {
5391 name: "items".to_owned(),
5392 fields: vec![Field::new("text", LogicalType::Varchar)],
5393 stripes: Vec::new(),
5394 rows: 0,
5395 dictionaries: vec![Some(dictionary)],
5396 frequencies: vec![None],
5397 };
5398 let directory = encode_directory(&table).expect("directory");
5399 let file_size = dictionary.offset + u64::from(dictionary.length) + 1;
5400
5401 let decoded = decode_directory(&directory, file_size).expect("large lazy dictionary");
5402 assert_eq!(decoded.dictionaries[0].expect("dictionary").length, dictionary.length);
5403 }
5404
5405 #[test]
5406 fn a_column_with_one_value_everywhere_costs_almost_nothing_a_row() {
5407 let path = path("constant-codes");
5408 let mut writer =
5409 Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
5410 .expect("new file");
5411 let empty = vec![Value::Varchar(String::new()); 1024];
5412 for _ in 0..4 {
5413 let column = Vector::from_values(LogicalType::Varchar, &empty).expect("strings");
5414 writer.append(&Chunk::new(vec![column]).expect("one column")).expect("a part");
5415 }
5416 writer.finish().expect("commit");
5417
5418 let reader = Reader::open(&path).expect("valid directory");
5419 let pages = reader.layout().columns.first().expect("one column").pages;
5420 assert!(pages < 256, "{pages} bytes of pages for 4,096 rows of one value");
5424 let read = reader.read(3, &[0]).expect("the last part back");
5425 assert_eq!(read.value_at(0, 0), Value::Varchar(String::new()));
5426 assert_eq!(read.value_at(1023, 0), Value::Varchar(String::new()));
5427 fs::remove_file(path).expect("remove scratch file");
5428 }
5429
5430 #[test]
5431 fn a_cascade_value_too_wide_for_its_column_is_refused_rather_than_cut() {
5432 let over = vec![i64::from(i32::MAX) + 1];
5435 let error = narrowed(&LogicalType::Integer, over).expect_err("a page that disagrees");
5436 assert!(format!("{error}").contains("not of its type"), "{error}");
5437 assert!(narrowed(&LogicalType::BigInt, vec![i64::MIN]).is_ok(), "bigint holds all of i64");
5438 assert!(narrowed(&LogicalType::Varchar, vec![0]).is_err(), "strings are not integers");
5439 }
5440
5441 #[test]
5442 fn a_code_stream_the_cascade_cannot_shrink_is_left_alone() {
5443 let mut state: u32 = 0x9e37_79b9;
5447 let spread: Vec<u32> = (0..1024)
5448 .map(|_| {
5449 state ^= state << 13;
5450 state ^= state >> 17;
5451 state ^= state << 5;
5452 state
5453 })
5454 .collect();
5455 assert_eq!(encoded_codes(&spread).expect("no failure"), None);
5456 let near: Vec<u32> = (0..1024).collect();
5457 let coded = encoded_codes(&near).expect("no failure").expect("counting up is packable");
5458 assert!(coded.len() < near.len() * 4, "{} bytes for a run of 1,024", coded.len());
5459 }
5460
5461 #[test]
5467 fn two_writes_of_the_same_rows_give_the_same_bytes() {
5468 fn written(path: &PathBuf) {
5469 let fields = (0..40)
5470 .map(|column| {
5471 let ty =
5472 if column % 4 == 0 { LogicalType::Varchar } else { LogicalType::BigInt };
5473 Field::new(format!("c{column}"), ty)
5474 })
5475 .collect::<Vec<_>>();
5476 let mut writer = Writer::create(path, "wide", fields).expect("new file");
5477 for part in 0..70_u64 {
5478 let columns = (0..40)
5479 .map(|column| {
5480 let values = (0..64_u64)
5481 .map(|row| {
5482 let seed = part.wrapping_mul(31).wrapping_add(row);
5483 if column % 4 == 0 {
5484 Value::Varchar(format!("v{}", seed % 17))
5485 } else {
5486 Value::BigInt(i64::try_from(seed % 97).expect("small"))
5487 }
5488 })
5489 .collect::<Vec<_>>();
5490 let ty = if column % 4 == 0 {
5491 LogicalType::Varchar
5492 } else {
5493 LogicalType::BigInt
5494 };
5495 Vector::from_values(ty, &values).expect("a column")
5496 })
5497 .collect::<Vec<_>>();
5498 writer.append(&Chunk::new(columns).expect("forty columns")).expect("a part");
5499 }
5500 writer.finish().expect("commit");
5501 }
5502
5503 let first = path("repeatable-one");
5504 let second = path("repeatable-two");
5505 written(&first);
5506 written(&second);
5507 let left = fs::read(&first).expect("the first file");
5508 let right = fs::read(&second).expect("the second file");
5509 assert_eq!(left.len(), right.len(), "two writes of the same rows differ in length");
5510 assert!(left == right, "two writes of the same rows differ in their bytes");
5511
5512 let reader = Reader::open(&first).expect("valid directory");
5515 assert_eq!(reader.table().rows(), 70 * 64);
5516 let read = reader.read(0, &[0, 1]).expect("the first part back");
5517 assert_eq!(read.value_at(0, 0), Value::Varchar("v0".to_owned()));
5518 assert_eq!(read.value_at(0, 1), Value::BigInt(0));
5519 fs::remove_file(first).expect("remove scratch file");
5520 fs::remove_file(second).expect("remove scratch file");
5521 }
5522}