Skip to main content

rudb_native/
lib.rs

1//! Rudb's single-file columnar snapshot format.
2//!
3//! A committed directory names independently readable column pages. The first version handles
4//! scalar columns and one table; the file header already has two generation slots so an unfinished
5//! replacement directory cannot hide the last complete one.
6//!
7//! # Parts and stripes
8//!
9//! A part is one appended chunk, which is a thousand rows, and it is the unit a scan decodes and
10//! hands to the pipeline. A stripe is sixty four parts, and it is the unit the directory describes
11//! and the unit the file is laid out in: one page per column per stripe, holding that column's
12//! sixty four part payloads end to end.
13//!
14//! The two are separate because they are sized by different pressures. A part wants to be small
15//! because it is a vector and vectors live in cache. A stripe wants to be large because everything
16//! the directory holds is per stripe and the directory is one buffer that has to be read and
17//! decoded before a single row can be answered. A hundred million rows of the hundred and five
18//! column ClickBench table is ninety seven thousand parts, and a directory with a page entry and a
19//! pair of bounds per part per column is several hundred megabytes, which is what made that load
20//! fail before this split existed. Sixty four parts to a stripe divides that by sixty four.
21//!
22//! Where the parts of a page start is not in the directory either, for the same reason. Each
23//! stripe writes one index page holding a length and a checksum per part per column, and a reader
24//! preads the sixty four entries belonging to the column it wants. A scan reads the whole column
25//! page once and slices it; a sparse row fetch reads the index entries and then only the part it
26//! needs.
27
28#![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;
60/// The most threads the two per column passes at the end of a commit are spread over.
61///
62/// A table like `hits` has ninety numeric columns, so on a machine with more cores than this the
63/// cap is what decides how long the frequencies take rather than the columns are. It is here at all
64/// because each worker holds a candidate table and a decoded part, and a hundred of those at once
65/// on a narrow machine would be worse than waiting.
66const MAX_FREQUENCY_WORKERS: usize = 32;
67
68/// The most threads one stripe's encode is spread over.
69///
70/// Higher than the frequency cap because this is the load itself rather than a pass at the end of
71/// it, and the work is one column of sixty four parts, which is large enough that a thread that
72/// takes one is not a thread that was started for nothing. A machine with more cores than this has
73/// the rest of them on the Parquet read, which is still one thread and is the other half of #808.
74const MAX_ENCODE_WORKERS: usize = 32;
75
76/// The most bytes one column of one part may spend on a membership sieve.
77///
78/// A part is a thousand rows, so a filter sized for every one of them being distinct is about
79/// thirteen hundred bytes and this never binds in practice. It is here so that a part that somehow
80/// arrives much wider than a vector cannot put an unbounded index in the file.
81const 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
91/// Adds a sequence of byte counts without an overflow the caller has to think about.
92fn sum(counts: impl Iterator<Item = u64>) -> u64 {
93    counts.fold(0, u64::saturating_add)
94}
95
96/// One column's span out of a per column list, or zero when the list is shorter than the column.
97fn span_bytes(spans: &[Span], at: usize) -> u64 {
98    spans.get(at).map_or(0, |span| u64::from(span.length))
99}
100
101/// One column's page out of a per column list, or zero when that column has no page at all.
102fn 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    /// How much of the file this page takes, for [`Reader::layout`].
202    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/// Exact leading frequencies for one column.
221///
222/// Values outside `entries` occur at most `omitted_max` times. This lets a count-descending TopN
223/// use the synopsis only when its last winner is strictly above every omitted value.
224#[derive(Debug, Clone)]
225struct FrequencySummary {
226    entries: Vec<FrequencyEntry>,
227    omitted_max: u64,
228    ordinals: Vec<u64>,
229}
230
231/// Sparse row ordinals covered by a numeric frequency candidate set.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct FrequencyOccurrences {
234    /// Upper bound for the frequency of every value absent from the fetched rows.
235    pub omitted_max: u64,
236    /// Table-wide row ordinals in ascending order.
237    pub ordinals: Vec<u64>,
238}
239
240/// Where one column's page for one stripe sits in the file.
241///
242/// A column page has no checksum of its own because every part inside it carries one, and the
243/// stripe's index page holds those. Checking a part on the way out of the page covers exactly the
244/// bytes a reader is about to decode, and covers them once whether the reader took the whole page
245/// or pulled one part out of the middle of it.
246#[derive(Debug, Clone, Copy, Default)]
247struct Span {
248    offset: u64,
249    length: u32,
250}
251
252/// One independently readable stripe of a table.
253#[derive(Debug, Clone)]
254pub struct Stripe {
255    rows: usize,
256    /// Rows in each part, in source order. Kept in the directory so that mapping a row ordinal to a
257    /// part, which every sparse fetch does, never reads the file.
258    parts: Vec<u32>,
259    /// The index page: one section per column, holding a length and a checksum for every part and
260    /// then a checksum of the section itself, so that a reader can pread one column's section and
261    /// still know it is intact.
262    index: Span,
263    pages: Vec<Span>,
264    memberships: Vec<Option<Page>>,
265    /// One page per column holding the membership sieve of every part of the stripe, for the
266    /// columns that have one. A column whose parts all declined a sieve has no page at all.
267    sieves: Vec<Option<Page>>,
268    zone: Zone,
269}
270
271impl Stripe {
272    /// Number of rows in this stripe.
273    #[must_use]
274    pub fn rows(&self) -> usize {
275        self.rows
276    }
277
278    /// Number of parts in this stripe.
279    #[must_use]
280    pub fn parts(&self) -> usize {
281        self.parts.len()
282    }
283}
284
285/// The committed table directory.
286#[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    /// The SQL table name held by this snapshot.
298    #[must_use]
299    pub fn name(&self) -> &str {
300        &self.name
301    }
302
303    /// Columns in their SQL order.
304    #[must_use]
305    pub fn fields(&self) -> &[Field] {
306        &self.fields
307    }
308
309    /// Committed row count.
310    #[must_use]
311    pub fn rows(&self) -> usize {
312        self.rows
313    }
314
315    /// Independently readable stripes.
316    #[must_use]
317    pub fn stripes(&self) -> &[Stripe] {
318        &self.stripes
319    }
320}
321
322/// Where one column's bytes went, taken from the directory rather than by reading pages.
323#[derive(Debug, Clone)]
324pub struct ColumnLayout {
325    /// The column's name, so a report does not have to carry the field list beside this.
326    pub name: String,
327    /// The type, spelled the way the catalog spells it.
328    pub kind: String,
329    /// Every stripe's page of this column added up, which is the encoded data itself.
330    pub pages: u64,
331    /// Every stripe's exact code membership page for this column.
332    pub memberships: u64,
333    /// Every stripe's membership sieve page for this column.
334    pub sieves: u64,
335    /// The table wide dictionary of this column, if it has one.
336    pub dictionary: u64,
337}
338
339impl ColumnLayout {
340    /// Everything this column costs, which is what the file would lose if the column went.
341    #[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/// Where a whole file's bytes went.
351///
352/// Every number here comes out of the committed directory, so taking it costs one directory read
353/// however large the file is. That is the point: a 45 GB table has to be able to say where it went
354/// without being read, or nobody will ask.
355///
356/// The parts that are not a column are kept apart rather than shared out over the columns. The
357/// stripe index page holds a section per column and could be split, and the directory and the
358/// header cannot be, so splitting one of the three and not the others would read as if the columns
359/// accounted for everything. They do not, and the gap is the thing worth looking at.
360#[derive(Debug, Clone)]
361pub struct Layout {
362    /// The size of the file on disk.
363    pub file: u64,
364    /// Committed rows.
365    pub rows: usize,
366    /// Committed stripes.
367    pub stripes: usize,
368    /// Committed parts, which is how many chunks a scan reads.
369    pub parts: usize,
370    /// One entry per column, in the table's column order.
371    pub columns: Vec<ColumnLayout>,
372    /// Every stripe's index page, which carries a length and a checksum for every part of every
373    /// column and is charged per stripe rather than per column.
374    pub indexes: u64,
375    /// The committed directory itself, the one that was read to build this.
376    pub directory: u64,
377    /// The fixed header, which holds the magic, the format and the two directory slots.
378    pub header: u64,
379}
380
381impl Layout {
382    /// Everything the columns cost together.
383    #[must_use]
384    pub fn columns_total(&self) -> u64 {
385        self.columns.iter().map(ColumnLayout::total).fold(0, u64::saturating_add)
386    }
387
388    /// What the file holds that this does not account for.
389    ///
390    /// A committed file is written once and never rewritten in place, so an earlier directory and
391    /// the pages of an earlier snapshot are still in it. That is the honest place for them: they
392    /// are bytes on disk that no column owns.
393    #[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/// Appends pages and commits a new directory for one table.
404#[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    /// This dictionary's values in sorted order, each as the first eight bytes of the value and the
467    /// code that holds it, so entry `rank` describes the value that sits at `rank` when the values
468    /// are sorted by their bytes.
469    ///
470    /// Codes themselves stay in first appearance order, which is what lets the writer hand one out
471    /// the moment it sees a value rather than waiting for the last stripe, and which also keeps a
472    /// stripe's codes close together because the data is clustered. This is what puts the values
473    /// back in order for anything that needs it, and it is separate from the codes so that getting
474    /// it costs a sort of the distinct values at the end rather than a rewrite of every code page.
475    ///
476    /// The sort compares the first eight bytes as one integer before it compares the values, which
477    /// settles almost every pair without touching the payload. Padding with zero on the right is
478    /// order preserving for byte strings, because a shorter value differs from a longer one that
479    /// starts the same way at a position where the shorter one has run out, and zero is below every
480    /// byte that could be there. A pair the head cannot settle falls through to the bytes.
481    ///
482    /// The heads are kept rather than thrown away once the sort is over, because a reader searching
483    /// this order wants exactly the same comparison and for exactly the same reason. Eight bytes an
484    /// entry of file is what buys a binary search that reads no values at all in the ordinary case.
485    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/// Appends pages and commits a new directory for one table.
514#[derive(Debug)]
515pub struct Writer {
516    file: File,
517    /// Where the next write goes, counted here rather than asked of the file.
518    ///
519    /// The file's own cursor is not ours. Building the numeric frequencies reads pages back through
520    /// [`read_at`], and a positional read is only positional about where it reads from: `pread`
521    /// leaves the cursor alone, and the call Windows has for it moves the cursor to the end of what
522    /// it read. A writer that asked the file where it was would then write the directory over a
523    /// page it had already written, which is what it did.
524    at: u64,
525    table: Table,
526    generation: u64,
527    /// The first and the last source position in every stripe, in the order the stripes were
528    /// written.
529    order: Vec<((u64, u64), (u64, u64))>,
530    next_order: u64,
531    dictionaries: Vec<Option<GlobalDictionary>>,
532    pending: Vec<PendingChunk>,
533}
534
535/// A chunk that has arrived and is waiting for the rest of its stripe.
536///
537/// The rows are kept rather than the pages they encode to, which is the whole of #808's first half.
538/// Encoding on arrival put every column of every part on the thread that called `append_at`, and
539/// that thread is the only one the load has. Encoding at the flush instead means a stripe's worth
540/// of work is on the table at once, and a stripe splits by column into a hundred and five pieces
541/// that share nothing.
542#[derive(Debug)]
543struct PendingChunk {
544    order: (u64, u64),
545    chunk: Chunk,
546}
547
548/// One column's share of a stripe, which is what one encode worker produces.
549///
550/// Indexed by part, so a stripe is a column of these and the write loop reads down one of them.
551/// That is also the order the loop wanted: `flush_pending` walks a column at a time and lays its
552/// parts next to each other, and it used to reach across a row of parts to do it.
553#[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
561/// Roughly what encoding a column of this type costs, for ordering the encode queue.
562///
563/// Only the order matters and only roughly. A string column hashes and copies every value into a
564/// dictionary and is in a different class from everything else, and among the fixed widths the wide
565/// ones carry more bytes through the cascade than the narrow ones. Anything finer than that would
566/// be a cost model, and the queue already absorbs a wrong guess: it only has to avoid finishing on
567/// a column nobody else can help with.
568fn 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
582/// Parts in one stripe.
583///
584/// Sixty four thousand rows is the smallest stripe that keeps the ClickBench directory in single
585/// digit megabytes at a hundred million rows, and it puts a four byte column's page at a quarter of
586/// a megabyte, which is the size a sequential read wants. Larger stripes buy a smaller directory
587/// and cost a sparse fetch, which has to read a page index before it can reach one part.
588pub const STRIPE_PARTS: usize = 64;
589
590/// Bytes one part takes in a stripe's index page: four for the length, eight for the checksum.
591const INDEX_ENTRY: usize = size_of::<u32>() + size_of::<u64>();
592
593/// Bytes one column's section of a stripe's index page takes, including its own trailing checksum.
594fn 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    /// Creates a new v10 file and its first table.
603    ///
604    /// # Errors
605    ///
606    /// If the file exists, a field has no scalar encoding, or the path cannot be written.
607    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    /// Appends bytes at the end of the file and moves the writer's own offset past them.
644    ///
645    /// Every write in here goes through this, so that [`Writer::at`] is the only answer to where
646    /// anything is and the file's cursor is never consulted for it.
647    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    /// Writes one chunk as independently readable column pages.
657    ///
658    /// # Errors
659    ///
660    /// If its width or types differ from the declared table, or a page exceeds its bound.
661    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    /// Writes one chunk and records its source position for directory ordering.
668    ///
669    /// Pages may be encoded by parallel pipeline instances and reach the file in completion order.
670    /// The stripe they land in is sorted by this key at commit, and [`Self::finish`] rejects a
671    /// sequence whose parts do not come out in source order once the stripes are sorted, because a
672    /// stripe groups whatever arrived together and cannot put a late part back where it belongs.
673    ///
674    /// # Errors
675    ///
676    /// The same as [`Self::append`].
677    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        // Cloned rather than encoded, and a clone of a chunk that owns its buffers is a copy of
686        // them. Sixty four parts of a hundred and five columns is tens of megabytes held for the
687        // length of a stripe and a few seconds of memory traffic over a whole ClickBench load,
688        // against the hundreds of seconds of encode this is what lets off one thread.
689        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    /// Writes a run of chunks as one stripe of its own.
697    ///
698    /// [`Self::append_at`] decides where a stripe ends by watching the orders go past, which works
699    /// when one caller hands over every chunk in source order and does not when several do. A
700    /// writer being fed by more than one pipeline instance sees the orders interleave, and a stripe
701    /// that ends every time two of them cross is a stripe of one or two parts.
702    ///
703    /// So the grouping moves to the caller. Whoever is buffering hands over a run it already knows
704    /// is contiguous and in order, and gets a stripe holding exactly that run. The orders still
705    /// have to come out in source order once the stripes are sorted, which [`Self::finish`] checks,
706    /// so the runs from different callers may interleave with each other but may not overlap.
707    ///
708    /// # Errors
709    ///
710    /// The same as [`Self::append`], and if the run is longer than [`STRIPE_PARTS`].
711    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        // Whatever an earlier caller left behind is its own stripe rather than the front of this
716        // one, because the two runs are from different places in the source and a stripe is a run.
717        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    /// Checks a chunk against the declared table and counts its rows in.
729    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    /// Encodes one column's parts of a stripe, with the column's dictionary to itself.
747    ///
748    /// Nothing here is shared with another column. The dictionary belongs to this one, the sieve
749    /// reads only this one, and the page bytes go in a vector of this one's own. That is why the
750    /// fan out below can hand a whole column to a thread and take a plain `&mut` on the dictionary
751    /// rather than making it something several threads can grow at once, which is the harder half
752    /// of #808 and is still open.
753    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            // The range is built first because the sieve reads it rather than walking the column a
771            // second time to find out how wide it is.
772            let range = Range::of(column);
773            // A column with a global dictionary already has an exact membership index per stripe,
774            // so an approximate one beside it would cost a hash of every string in the table to
775            // answer a question that is already answered. What it would buy is the finer grain, a
776            // part rather than a stripe, and that is worth coming back for on its own.
777            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    /// Encodes a whole stripe, one column to a worker.
790    ///
791    /// The columns are handed out through a queue rather than dealt in equal piles, because they
792    /// are nothing like equal: `URL` on ClickBench is a global dictionary of sixty one million
793    /// strings and `IsMobile` is a byte. A pile that happened to hold the four large string columns
794    /// would be the whole stripe and the other workers would be waiting on it. The queue is sorted
795    /// so the expensive ones are taken first, which is the classic answer to a last job that runs
796    /// longer than everything after it.
797    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        // The dictionaries are moved out and back rather than borrowed, because a worker that takes
812        // the next column off a queue cannot be holding a borrow of the vector the queue came from.
813        let mut jobs: Vec<(usize, Option<GlobalDictionary>)> =
814            std::mem::take(&mut self.dictionaries).into_iter().enumerate().collect();
815        // Popped from the back, so the expensive columns go last in the vector.
816        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    /// Writes the buffered parts as one stripe, each column's parts contiguous on disk.
858    fn flush_pending(&mut self) -> Result<()> {
859        if self.pending.is_empty() {
860            return Ok(());
861        }
862        let width = self.table.fields.len();
863        // Held here rather than read off the writer, because writing a page needs the writer and
864        // the borrow checker is right that those are two different uses of it.
865        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        // Back where it came from, empty, so the next stripe buffers into the same allocation.
965        self.pending = held;
966        Ok(())
967    }
968
969    /// Finds exact heavy hitters without keeping a hash table for every numeric column while the
970    /// load is live. The pages are already in the target file, so one column at a time uses a
971    /// bounded Misra-Gries candidate table and then recounts only those candidates.
972    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                // row at a time: frequency construction visits decoded values to update bounded candidates.
1072                for row in 0..rows {
1073                    let value = if vector.is_null_at(row) {
1074                        FrequencyValue::Null
1075                    } else {
1076                        // An unsigned column has no signed reading, and the documented fallback is
1077                        // the value itself. Every unsigned width the format stores fits in the
1078                        // `i128` a candidate is keyed by, so nothing is lost on the way through.
1079                        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    /// Builds independent numeric synopses concurrently after all column pages are committed.
1102    ///
1103    /// The columns go through a queue rather than being cut into equal runs, because they are not
1104    /// equally expensive and they are not shuffled. A `BIGINT` column carries eight times the bytes
1105    /// of a `TINYINT` through the decode, and a run of them sits together in a schema the way it
1106    /// sits together in `hits`, so a worker that was handed the wrong six columns finishes long
1107    /// after one that was handed the right six and the whole phase waits for it.
1108    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        // Popped from the back, so the expensive columns are the ones taken first and the cheap ones
1143        // are what is left to fill in behind them.
1144        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    /// Commits the directory and syncs the file before publishing its header slot.
1181    ///
1182    /// # Errors
1183    ///
1184    /// If directory encoding, writing, or syncing fails.
1185    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        // The one write that is not an append, and the last one. It goes back over the slot in the
1239        // header, so it names its offset rather than going through `put`, and `at` does not move.
1240        write_at(&self.file, 16, &slot.bytes())?;
1241        self.file.sync_all().map_err(io)?;
1242        Ok(self.table)
1243    }
1244}
1245
1246/// Reads committed native column pages without holding the table in memory.
1247#[derive(Debug, Clone)]
1248pub struct Reader {
1249    file: Arc<File>,
1250    table: Arc<Table>,
1251    dictionaries: Arc<Vec<OnceLock<Arc<Vector>>>>,
1252    /// The membership sieves of one stripe of one column, by column and then by stripe, read the
1253    /// first time a probe asks about them. A query filters on one or two columns and never looks at
1254    /// the rest, so reading these at open would be the whole index for the sake of a fraction of it.
1255    sieves: Arc<Vec<Vec<SieveSlot>>>,
1256    /// Which stripe and which part of it every part of the table is, by table wide part number.
1257    places: Arc<Vec<Place>>,
1258    cache: Arc<Vec<Mutex<Cached>>>,
1259    /// How many whole stripe pages have been read, which is what the sharing above is judged on. A
1260    /// scan of a column should read each of its stripes once however many workers it has.
1261    pages: Arc<AtomicUsize>,
1262    /// How many index sections have been read. A scan of a column should read each of its stripes
1263    /// once here too, and the test that says so is the only thing keeping it that way.
1264    indexes: Arc<AtomicUsize>,
1265    /// How many stripes of one column the page cache keeps. See [`CACHED_STRIPES_PER_COLUMN`] for
1266    /// what sets it and [`Reader::keep_stripes`] for who raises it.
1267    kept: Arc<AtomicUsize>,
1268    /// The file's size when it was opened, for [`Reader::layout`].
1269    size: u64,
1270    /// The committed directory's size, for [`Reader::layout`].
1271    directory: u64,
1272    /// What opening the file cost, which is a number rather than a claim.
1273    opening: Opening,
1274}
1275
1276/// What [`Reader::open`] read before it returned.
1277///
1278/// `spec/stats/04-in-memory.md` section 4.2 says opening a table reads the header and the directory
1279/// and nothing else, and once that document's statistics are in the file the tempting change is to
1280/// load a column summary or two on the way past, because they are small and the next query will
1281/// want them. A hundred milliseconds of that is a hundred milliseconds nobody asked for, and an
1282/// embedded database is opened by processes that are about to run one trivial query.
1283///
1284/// So the claim gets a number. Both of these are fixed by the schema and the stripe count and are
1285/// independent of how many rows the file holds, and the test that says so is what stops the
1286/// tempting change from landing quietly.
1287#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1288pub struct Opening {
1289    /// How many times the file was read. The header, then each directory slot that looked valid
1290    /// enough to check, so three at the most.
1291    pub reads: u32,
1292    /// How many bytes those reads asked for.
1293    pub bytes: u64,
1294}
1295
1296/// What a reader has read, while it was being opened and since.
1297#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1298pub struct Reads {
1299    /// What opening cost, before any query had been planned.
1300    pub opening: Opening,
1301    /// Whole stripe pages read since.
1302    pub pages: usize,
1303    /// Index sections read since.
1304    pub indexes: usize,
1305}
1306
1307/// Where one table wide part number lands.
1308#[derive(Debug, Clone, Copy)]
1309struct Place {
1310    stripe: u32,
1311    part: u32,
1312    rows: u32,
1313}
1314
1315/// One part's bytes inside one column page.
1316#[derive(Debug, Clone, Copy)]
1317struct PartSpan {
1318    start: usize,
1319    length: usize,
1320    hash: u64,
1321}
1322
1323/// What a reader holds for one stripe of one column.
1324///
1325/// The index is small and is loaded whether the caller wants the whole page or one part of it. The
1326/// page is loaded only by a scan, because a sparse fetch that wants a thousand rows out of sixty
1327/// four thousand would be reading sixty four times what it uses.
1328#[derive(Debug, Clone)]
1329struct CachedColumn {
1330    stripe: usize,
1331    index: Arc<Vec<PartSpan>>,
1332    page: Option<Arc<Vec<u8>>>,
1333}
1334
1335/// One column's stripes a reader holds, and which of them somebody is reading right now.
1336///
1337/// The pages are one slot per stripe of the table rather than a list of the ones being kept, so
1338/// finding a page is an index and not a walk. That matters because the walk happened under the
1339/// lock, once per part per column, and a scan that gives a whole stripe to each of thirty two
1340/// workers keeps enough pages that walking them was the longest thing the lock was held for. The
1341/// slots cost a pointer per stripe per column, which on the ClickBench file is eight kilobytes
1342/// against the forty megabytes of pages they point at. `order` is which of them are filled, oldest
1343/// first, because that is the one thing the slots cannot say by themselves.
1344///
1345/// `loading` is what keeps a scan from reading the same page once per worker. It is a list and not
1346/// a set because it holds at most one stripe per worker on the column and is walked far less often
1347/// than a hash of it would be built.
1348///
1349/// `index` is every index this reader has ever read for the column, one slot per stripe, and it is
1350/// never evicted. An index is a few hundred bytes and a page is a quarter of a megabyte, so the two
1351/// do not belong under the same budget. Riding in the page cache meant a worker that came back to a
1352/// stripe after its page had been evicted read the index again with it, which on the full
1353/// ClickBench file was about thirteen hundred reads out of a hundred and fourteen thousand.
1354#[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
1362/// Stripes of one column a reader keeps the bytes of, when nobody has asked for more.
1363///
1364/// This has to hold at least as many stripes as a column has workers in it at once, or the workers
1365/// evict each other's pages and read them again. Four is what a scan that hands parts out in order
1366/// needs, because then every worker is within a few parts of every other and at most a couple of
1367/// stripes are open at a time. A scan that hands a whole stripe to each worker has one stripe open
1368/// per worker for the length of that stripe, and it says so with [`Reader::keep_stripes`] rather
1369/// than paying for sixteen slots on every table that is read one part at a time.
1370///
1371/// It multiplies by the page size, which is a quarter of a megabyte for a four byte column, and by
1372/// the number of columns a query touches.
1373const CACHED_STRIPES_PER_COLUMN: usize = 4;
1374
1375/// The sieves of one stripe of one column, once somebody has asked for them.
1376type 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    /// How many entries the sorted order has, which is the value count.
1385    ranks: usize,
1386    /// Where the sorted order starts in the file. It is read a block at a time and only when
1387    /// something searches it, so a query that never compares this column against a literal never
1388    /// touches it at all.
1389    rank_at: u64,
1390    rank_hashes: Vec<u64>,
1391    rank_blocks: Vec<OnceLock<Result<Vec<u8>>>>,
1392    /// The sorted order turned round, built the first time a reader asks for it.
1393    ///
1394    /// Four bytes per value against the four the offsets already hold, so a column that has this is
1395    /// carrying half again what it carried before rather than something of a new order. It is built
1396    /// only when something asks, which is a grouped min or max over this column and nothing else,
1397    /// and that reader was going to read the payload of this column once per row otherwise.
1398    code_ranks: OnceLock<Option<Vec<u32>>>,
1399    payload: u64,
1400    payload_len: usize,
1401    hashes: Vec<u64>,
1402    /// The payload, read and kept an extent at a time. See [`TEXT_PAYLOAD_EXTENT`].
1403    payload_extents: Vec<OnceLock<Result<Vec<u8>>>>,
1404    crossing: Vec<CrossingCache>,
1405}
1406
1407const TEXT_PAYLOAD_BLOCK: usize = 64 * 1024;
1408
1409/// How many blocks are read, allocated and waited on as one.
1410///
1411/// The block is what a checksum covers and it is written into the file, so it cannot move without
1412/// the format moving. What a reader does with it can. A scan of a string column ends up wanting
1413/// every block, because the codes a part holds are spread over the whole dictionary, and reading
1414/// them one at a time made a hundred million row `LIKE` spend more than half its time in the kernel
1415/// rather than in the predicate: a pread and a `Vec` per sixty four kilobytes, over a dictionary
1416/// that is more than a gigabyte, is twenty thousand of each. Under a poor man's profile of ClickBench
1417/// query 21, 58 percent of the samples were in a syscall, 18 percent were in `mprotect` with the
1418/// allocator growing the heap by sixty four kilobytes at a time, and 20 percent were threads parked
1419/// on a `OnceLock` somebody else was filling.
1420///
1421/// Eight blocks is half a megabyte, which is one read, one allocation the allocator takes straight
1422/// from `mmap` rather than off the heap, and one wait. The cost is paid by a query that wants a few
1423/// values rather than a column of them, which now reads half a megabyte to get at sixty four
1424/// kilobytes, and that is what picks the number. Over the queries that go each way, with the scan
1425/// being ClickBench query 21 and the few value read being query 34, which takes its answer out of
1426/// the frequency page and then looks ten codes up: four blocks is 1.318s and 0.075s, eight is 1.168s
1427/// and 0.084s, sixteen is 1.205s and 0.116s. The scan stops improving after eight and the lookup
1428/// keeps getting worse.
1429const TEXT_PAYLOAD_EXTENT: usize = 8;
1430const TEXT_CROSSING_BLOCK: usize = 1024;
1431
1432/// How many entries of a dictionary's sorted order sit in one block that is read and checked as a
1433/// unit.
1434///
1435/// Five hundred and twelve entries is six kilobytes, which is a page and a half. A binary search
1436/// over half a million entries makes nineteen probes, and the first ten land in ten different
1437/// blocks while the last nine land in the one block that holds the answer, so the whole search
1438/// reads about sixty six kilobytes of a two megabyte order. A smaller block would save a little on
1439/// the early probes and cost a checksum list four times as long. A larger one would read more than
1440/// it uses on every probe.
1441const TEXT_RANK_BLOCK: usize = 512;
1442
1443/// Bytes one entry of the sorted order takes: eight for the head and four for the code.
1444const 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                // The checksums are per block and stay per block, because they are in the file. The
1466                // extent is only how much of the file one read and one allocation cover.
1467                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    /// The block of the sorted order that holds `rank`, and where in it that rank sits.
1487    ///
1488    /// The block is read from the file and checked against the hash the index carries for it the
1489    /// first time anything asks, and kept after that, the same way a payload block is. A search
1490    /// makes about as many probes as the order has bits, so the whole search reads a handful of
1491    /// these and never the rest.
1492    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    /// The first eight bytes of the value at `rank`, as the integer a comparison reads.
1519    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        // The head settles the probe unless the two values start with the same eight bytes, and
1593        // only then is a value read. On a column of URLs that is the difference between a search
1594        // that touches one block of the payload and a search that touches nineteen of them.
1595        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        // The order is a permutation of the positions, so inverting it needs every position to be
1622        // named exactly once. Anything else and the slice would have holes, and a caller indexing
1623        // it by a code would read a rank that belongs to nothing.
1624        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                // A block at a time rather than a rank at a time, because reading it per rank pays
1631                // for the bounds check, the division and the lock on every one of them.
1632                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
1692/// Every table wide part number in order, with the stripe it belongs to.
1693fn 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
1708/// Reads one column's section of a stripe's index page.
1709///
1710/// The section carries its own checksum, so a reader that wants one column out of a hundred and
1711/// five preads a few hundred bytes and still knows that what it got is what was written.
1712fn 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        // With where it was read from, because the two ways this fires look identical from the
1732        // message alone: a file somebody damaged, and a file we wrote to the wrong offset.
1733        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
1754/// One part's bytes out of a whole column page.
1755fn 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
1760/// Puts one stripe of one column in the cache, dropping the stripe that has been there longest.
1761///
1762/// The index goes in its own slot and stays. Only the page is under the budget, and `kept` is how
1763/// many pages that budget is.
1764fn 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    /// Opens the highest valid directory slot.
1786    ///
1787    /// # Errors
1788    ///
1789    /// If the file has no valid committed directory or a directory pointer is out of bounds.
1790    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        // The two halves are worth telling apart. A wrong magic is a file that was never ours and
1801        // the answer is to look at the path. A wrong version is our own file from another build,
1802        // and the number this build wants is the only thing that tells the reader whether to
1803        // rebuild the file or to go back to the binary that wrote it.
1804        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    /// What this reader has read so far, and what opening it cost.
1871    ///
1872    /// Public because the claim of `spec/stats/04-in-memory.md` section 4.2 is about this number
1873    /// and a claim nobody can check is a comment. A caller that wants to know whether opening a
1874    /// file touched the data asks here, and gets an answer that does not depend on what the page
1875    /// cache happened to hold.
1876    #[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    /// Where the file's bytes went, from the directory alone.
1886    ///
1887    /// No page is read, so this costs the same on a 45 GB table as on an empty one. See [`Layout`]
1888    /// for what is charged where and for why the three things that are not columns stay separate.
1889    #[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    /// How many parts the table has, which is how many chunks a scan of it reads.
1919    #[must_use]
1920    pub fn parts(&self) -> usize {
1921        self.places.len()
1922    }
1923
1924    /// The parts of each stripe, in table wide part numbers.
1925    ///
1926    /// A scan that wants one worker to own the page it reads hands work out in these runs. The
1927    /// stripes are contiguous in part numbering and all but the last hold sixty four parts, but a
1928    /// stripe can be flushed early when rows arrive out of order, so the runs are read off the
1929    /// directory rather than worked out from a constant.
1930    #[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    /// Asks the page cache to keep `stripes` stripes of every column instead of the default.
1943    ///
1944    /// This only ever raises the number. A scan that gives each worker a whole stripe has one page
1945    /// per column per worker open at once, and a cache smaller than that is worse than no cache at
1946    /// all: every worker's page is evicted by the others before it has finished its stripe, so it
1947    /// reads a quarter of a megabyte for every part it takes out of it.
1948    pub fn keep_stripes(&self, stripes: usize) {
1949        self.kept.fetch_max(stripes, Atomic::Relaxed);
1950    }
1951
1952    /// Rows in one part, or zero when the part number is past the table.
1953    #[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    /// The committed table directory.
1959    #[must_use]
1960    pub fn table(&self) -> &Table {
1961        &self.table
1962    }
1963
1964    /// Exact leading frequencies when the stored synopsis proves a count-descending prefix.
1965    ///
1966    /// The returned list can be longer than `top`. Keeping the stored tail lets a later TopN apply
1967    /// additional ordering keys without losing a value tied with the requested boundary.
1968    ///
1969    /// # Errors
1970    ///
1971    /// If the column is outside the schema or a stored value does not fit its declared type.
1972    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    /// Every value of one column with the number of rows holding it, when the synopsis is complete.
1992    ///
1993    /// The heavy hitter pass keeps a bounded set of candidates and decrements them all when it runs
1994    /// out of room, so what it usually ends with is the leading values and a bound on everything it
1995    /// dropped. `omitted_max` of zero says that never happened: no candidate was ever decremented and
1996    /// the entries did not overflow the stored budget, so the list is every distinct value of the
1997    /// column with an exact count, and a null counts as a value of its own rather than being skipped.
1998    ///
1999    /// That makes a whole class of question answerable without reading a row. How many rows hold a
2000    /// value, how many do not, and what a `GROUP BY` of that column with a count over it produces are
2001    /// all in here. It is only ever true of a column with few enough distinct values, which is the
2002    /// case worth having, because that is exactly the column a grouping or an equality filter would
2003    /// otherwise walk every row to answer.
2004    ///
2005    /// `None` when the column has no synopsis, or has one that dropped anything.
2006    ///
2007    /// # Errors
2008    ///
2009    /// If the column is outside the schema or a stored value does not fit its declared type.
2010    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    /// Turns stored frequency entries into values of the column's own type.
2026    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    /// Sparse rows belonging to the bounded numeric frequency candidate set.
2091    ///
2092    /// The list is omitted when collecting it would exceed the fixed storage budget. A composite
2093    /// aggregate may accept a result over these rows only when its requested boundary is strictly
2094    /// greater than `omitted_max`.
2095    ///
2096    /// # Errors
2097    ///
2098    /// If the column is outside the schema.
2099    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    /// How many distinct values one column holds, counting a null as no value.
2117    ///
2118    /// A string column of this format is written against one dictionary that covers the whole table.
2119    /// A code is handed out the first time a value is seen and nothing ever removes one, so the
2120    /// number of codes is the number of distinct values exactly rather than an estimate. That makes
2121    /// `COUNT(DISTINCT column)` over a whole table a question the directory already knows the answer
2122    /// to, and the alternative is a hash table with a row per distinct value built from a pass over
2123    /// every row.
2124    ///
2125    /// `None` for a column the file has no dictionary for, which is every column that is not a
2126    /// string, and `None` for a column with a null in it. A sketch would answer the first
2127    /// approximately and SQL asked for the exact number. The second is the placeholder: a null row
2128    /// is written as the code for the empty string, so a nullable column's dictionary may hold an
2129    /// empty string that no row of it actually has, and nothing persisted today tells the two cases
2130    /// apart.
2131    ///
2132    /// # Errors
2133    ///
2134    /// If the column is outside the schema, or the dictionary page does not read.
2135    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    /// How many rows of one column are null, added up over the stripes.
2143    ///
2144    /// Every stripe records this exactly when it is written, because a null count is not a bound
2145    /// that is allowed to be wide the way a minimum and a maximum are: a filter that reads one too
2146    /// many is slow and a `COUNT` that reads one too many is wrong. Adding up a few hundred numbers
2147    /// already in memory is what makes `COUNT(column)` over a whole table free.
2148    ///
2149    /// # Errors
2150    ///
2151    /// If the column is outside the schema.
2152    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    /// The smallest and the largest value of one string column, from the order beside its values.
2170    ///
2171    /// The dictionary holds exactly the values the column holds, so the first and the last of them
2172    /// in sorted order are the column's minimum and maximum. Two reads of a rank block settle what
2173    /// otherwise walks a million rows.
2174    ///
2175    /// `None` when the column is not a string, when the file was written before version 9 and so has
2176    /// no order, when the column has no values at all, or when it has a null in it, which is the
2177    /// placeholder again: the empty string a null is written as would sort ahead of every real
2178    /// value and be reported as the minimum.
2179    ///
2180    /// # Errors
2181    ///
2182    /// If the column is outside the schema, or a rank names a code the dictionary does not have.
2183    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    /// The smallest and the largest value of one column, when every stripe wrote exact ends.
2198    ///
2199    /// A stripe's ends are allowed to be wider than the truth, because a bound that rules out a
2200    /// chunk that could not match is still correct when it rules out nothing. That is what makes
2201    /// them cheap to write for a bit packed or a dictionary column, and it is also what stops them
2202    /// answering a `MIN`. So each stripe says which of the two it wrote, and this answers only when
2203    /// all of them walked their rows.
2204    ///
2205    /// `None` for a column with no ends, for an empty table, and for a column any stripe of which
2206    /// guessed. Nulls need no special case, because the ends skip them the same way `MIN` does.
2207    ///
2208    /// One case is given up on that did not have to be. A stripe merges the ends of its sixty four
2209    /// parts, and a part with no ends at all erases the merged ones, because a part whose rows are
2210    /// not covered by the stripe's ends is a stripe that would skip rows it should keep. A part of
2211    /// nothing but nulls has no rows to cover and so did not need to erase anything, but the merge
2212    /// cannot tell that part from a part whose layout it could not read. So a column with a chunk
2213    /// of nothing but nulls in the middle of it goes and reads the rows. That is slow and right,
2214    /// and the fix is a row count per part rather than anything here.
2215    ///
2216    /// # Errors
2217    ///
2218    /// If the column is outside the schema.
2219    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            // A stripe of nothing but nulls has no ends and says nothing about the column's, which
2234            // is why this skips it rather than giving up on the whole column. A stripe that has
2235            // rows and still has no end is a layout whose values this cannot see, and skipping that
2236            // one would answer with an end taken from the other stripes, so it gives up instead.
2237            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    /// The sum of one integer column and how many rows went into it, when every stripe wrote one.
2250    ///
2251    /// The count beside the sum is the non-null rows, because that is what a `SUM` adds up and what
2252    /// an `AVG` divides by, and a caller that had to work it out from the row count and the null
2253    /// count would be doing the same walk twice.
2254    ///
2255    /// `None` for anything that is not an integer column, for a file written by something that did
2256    /// not record it, and when adding the stripes together would overflow.
2257    ///
2258    /// # Errors
2259    ///
2260    /// If the column is outside the schema.
2261    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    /// Reads only the named columns from one part.
2295    ///
2296    /// The whole stripe page each column lives in is read and kept, because a scan asks for the
2297    /// parts of a stripe one after another and this is what turns sixty four reads into one.
2298    ///
2299    /// # Errors
2300    ///
2301    /// If a part, column, page, or checksum is invalid.
2302    pub fn read(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2303        self.read_impl(part, columns, true)
2304    }
2305
2306    /// Reads named columns from one part without keeping the stripe page it came out of.
2307    ///
2308    /// This is for sparse row fetches after a selective TopN or filter, which reach a few parts of
2309    /// a stripe rather than all of them. A caller that will read most of a stripe should use
2310    /// [`Self::read`] instead, because this reads and discards the page index every time.
2311    ///
2312    /// # Errors
2313    ///
2314    /// If a part, column, page, or checksum is invalid.
2315    pub fn read_sparse(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2316        self.read_impl(part, columns, false)
2317    }
2318
2319    /// Whether an exact global-code membership index proves that the stripe holding a part cannot
2320    /// contain any of the sorted candidate codes.
2321    ///
2322    /// # Errors
2323    ///
2324    /// If the part, column, index page, checksum, or delta stream is invalid.
2325    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    /// The page index of one column of one stripe, and its page when the caller wants all of it.
2363    ///
2364    /// A scan hands parts out in order, so every worker on a column crosses into a new stripe within
2365    /// a few parts of the others and they all want the same page at the same moment. This used to
2366    /// let all of them read it, which cost the scan as many copies of every page as it had workers.
2367    /// On the full ClickBench file a `MIN(EventDate), MAX(EventDate)` moved 3.2 GB off the disk to
2368    /// look at 400 MB of column.
2369    ///
2370    /// A worker that finds the page it wants already being read neither waits for it nor reads it
2371    /// again. It comes back with the index alone, which sends [`Reader::read_impl`] down the path
2372    /// that reads the one part it came for, a few kilobytes against a quarter of a megabyte, and it
2373    /// picks the page up from the cache on its next part. Waiting would be the other way to avoid
2374    /// the duplicate read and it is worse: the pages that matter are the wide string ones, they take
2375    /// milliseconds to copy even warm, and every other worker would be stopped for all of it.
2376    ///
2377    /// The file is never read under the lock.
2378    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            // The index is almost always already here, because somebody read this stripe to get
2391            // into the loading list in the first place, so this branch usually costs no read at
2392            // all and the one part read in `read_impl` is all the losing worker pays for.
2393            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        // The stripe leaves the loading list and its page enters the cache under one lock. Doing
2407        // them separately would leave a moment where another worker sees neither and reads the
2408        // page a second time, which is the whole thing this is here to stop.
2409        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    /// Reads one stripe's index for a column, and its page when the caller wants all of it.
2419    ///
2420    /// `known` is the index when the reader has already read it, which after the first worker
2421    /// through a stripe it always has, because [`remember`] keeps every index for the life of the
2422    /// reader. Without that a scan reads the index again on every part that misses the page cache.
2423    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    /// Whether persisted statistics prove that a part cannot match the predicates.
2502    ///
2503    /// Two of them. The bounds are per stripe, so every part of a stripe gets the same answer from
2504    /// those and a scan that skips one part that way skips all sixty four. The sieves are per part
2505    /// and answer equality, which is the test bounds are worst at: a column of identifiers has every
2506    /// stripe covering nearly the whole of its type, so the bounds keep every part of it and the
2507    /// sieve keeps the ones that really hold the value.
2508    ///
2509    /// The bounds go first because they are already in memory and the sieves are a read.
2510    #[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    /// Whether the bounds of one stripe prove that none of its parts can match the predicates.
2521    ///
2522    /// The cheap half of [`Self::skips`], asked about a whole stripe at once. The bounds live in the
2523    /// directory and are already in memory, so this answers without touching the file, and that is
2524    /// the reason it is worth having on its own: a caller that wants to know roughly where the work
2525    /// is before it starts any workers can ask this about sixteen stripes for nothing, where asking
2526    /// [`Self::skips`] about nine hundred parts would read and decode a sieve page per stripe first.
2527    ///
2528    /// It keeps stripes that [`Self::skips`] would rule out part by part, which is the right way for
2529    /// it to be wrong: the parts are still checked when they are read.
2530    #[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    /// Whether the sieve of one part rules out one probe.
2536    ///
2537    /// Only equality. An ordered comparison is what the bounds are for and a sieve says nothing
2538    /// about it, and a read that cannot answer keeps the part, which is the answer a caller with no
2539    /// sieve gets anyway.
2540    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    /// The sieves of one stripe of one column, read once and kept.
2554    ///
2555    /// `None` when the column has no sieves in that stripe, when the page is damaged, and when the
2556    /// bytes are not a page this version can read. A sieve is an index over data that is still there
2557    /// and a caller that cannot read one reads the rows, so this is the one place in the file where
2558    /// a bad checksum is a slow query rather than an error.
2559    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
2576/// The value sitting at one position of a dictionary's sorted order.
2577fn 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/// Writes one span of a file at an offset, without depending on where the cursor is.
2586///
2587/// The writer owns an offset of its own and passes it in here, so that nothing it writes depends on
2588/// a cursor that a read is entitled to move. Both of these can come back short and both loop.
2589#[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/// The same write, on the call Windows spells differently.
2604#[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/// Somewhere that is neither, where the cursor is all there is.
2619#[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/// Reads one span of a file at an offset, without moving a cursor anybody else can see.
2628///
2629/// Every reader of a table shares one [`File`] behind an [`Arc`], and a grouped aggregate reads its
2630/// pages from several threads at once, so this has to be positional. Seeking and then reading is
2631/// two calls with a gap in the middle, and in that gap another thread's seek lands and the read
2632/// comes back with somebody else's bytes.
2633///
2634/// Both of these can come back short, so both loop. A read of zero bytes before the span is filled
2635/// means the file stops earlier than the directory said it does.
2636#[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/// The same read, on the call Windows spells differently.
2651///
2652/// `seek_read` is one `ReadFile` carrying the offset with it, so two of them cannot interleave the
2653/// way a seek and a read can. It does leave the shared cursor somewhere afterwards, which is why
2654/// nothing in this file may read that cursor.
2655#[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/// Somewhere that is neither, where the cursor is all there is.
2670///
2671/// This one does race, and there is no way to write it so it does not. Nothing we build for runs
2672/// here, so it exists to keep the crate compiling rather than to be correct under threads.
2673#[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                // A global dictionary covers a whole column, not one bounded stripe. Its lazy
2988                // payload is intentionally allowed to grow past `MAX_PAGE`; only ordinary column
2989                // pages are capped there. `Writer::finish` has already bounded this length by the
2990                // on-disk `u32`, and the range check below keeps it inside the file.
2991                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                    // row at a time: directory decoding validates each persisted bounded frequency entry.
3131                    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/// Which cascades are worth trying on a run of dictionary codes.
3232///
3233/// The exhaustive chooser encodes every candidate at every level of a cascade three deep and keeps
3234/// the smallest, which on a part of 1024 codes is around a hundred full encodes to decide something
3235/// three candidates were always going to win. It is the right default for a crate that does not
3236/// know what it is looking at. Here we do know. Codes are counted from zero in the order the values
3237/// were first seen, so a part of them is one value, or a narrow band, or a few long runs, and those
3238/// are constant, frame of reference and run length. Nothing else has ever come first on this data.
3239///
3240/// A dictionary of dictionary codes is the one candidate that can never pay, because the codes are
3241/// already the dictionary, and it is also the most expensive one to try. Below the top level the
3242/// streams are an RLE's run values and run lengths, which are integers in their own right with no
3243/// runs left in them, so only the two flat candidates go down there.
3244///
3245/// This is size given up for time on purpose, and the ablation is this chooser against
3246/// [`chooser::EXHAUSTIVE`] on the same file.
3247#[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        // Never reached, because nothing here encodes strings through the cascade. The trait asks
3262        // for it and the honest answer to a question we have no opinion on is the whole list.
3263        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        // The contract is a non empty subset, and a chunk that offers none of the three is a chunk
3280        // this has no opinion about rather than one that cannot be written.
3281        if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3282    }
3283}
3284
3285/// Which cascades are worth trying on a part of plain integers.
3286///
3287/// Wider than [`Codes`] because the values are not codes and carry whatever shape the column has.
3288/// A timestamp column climbs, so delta is the one that matters and is the reason this exists at
3289/// all: three timestamp columns in ClickBench were coming out at exactly eight bytes a row with
3290/// nothing asked of them. A column that is one value with a handful of exceptions is sparse. What
3291/// is still left out is the dictionary, for the same reason as in [`Codes`]: it is the most
3292/// expensive candidate to try and this file already puts the columns that want one through a
3293/// dictionary of their own before they ever reach here.
3294#[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
3334/// Every value of an integer part as an `i64`, or `None` for a part this cannot widen without
3335/// losing one.
3336///
3337/// `UBIGINT` is the only integer type left out, because half its range does not fit and a page that
3338/// silently wrapped would be worse than a page that stays plain. Booleans and strings are not
3339/// integers and have their own ways of being small.
3340fn 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
3353/// The same values back in the width the column is declared at.
3354///
3355/// A value that does not fit is a page that disagrees with the directory about what the column is,
3356/// which is a damaged file rather than a caller error, so it is refused rather than truncated.
3357fn 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
3376/// How many bytes a part of this type costs written out plainly, which is what the cascade has to
3377/// beat before it is worth the decode.
3378fn 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
3388/// A part's plain integers through the cascade, or `None` when nothing it offers is worth it.
3389///
3390/// What it has to beat is whatever the page would otherwise have cost, which is the bit packed form
3391/// where there is one and the plain width where there is not. Both are cheaper to decode than a
3392/// cascade, so a tie goes to them.
3393fn 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        // The tag, the base, the word count and the words, which is what the codec 2 branch writes.
3403        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
3410/// A part's dictionary codes through the integer cascade, or `None` when the cascade did not pay.
3411///
3412/// Until now this stream was a `u32` a row with nothing asked of it, and on ClickBench that was
3413/// 400,185,326 bytes for every one of the 28 varchar columns, the same count for `URL` as for a
3414/// column holding the empty string in nearly every row. Codes are dense integers counted from zero
3415/// and a part holds 1024 of them, which is the shape frame of reference is best at, and a column
3416/// with one value everywhere comes back a constant costing nothing per row rather than four bytes.
3417///
3418/// The result is taken only when it is smaller than the plain form. A cascade is allowed to come
3419/// out larger on a part whose codes are genuinely wide, `URL` has about sixty million distinct
3420/// values, and there is no reason to pay for the decode when it does.
3421fn 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    // flatten: the file writer needs a uniform scalar page and does it once per loaded chunk.
3434    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    // Only where nothing else has claimed the page, which is the plain integer case. A packed part
3464    // is still on the table because the cascade has to beat it too: the bit pack takes a part only
3465    // when it halves it, so a column that shrinks by a third was coming out whole.
3466    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
3609/// The distinct codes of one part, which is what a stripe's membership index is merged from.
3610fn unique_codes(codes: &[u32]) -> Vec<u32> {
3611    let mut unique = codes.to_vec();
3612    unique.sort_unstable();
3613    unique.dedup();
3614    unique
3615}
3616
3617/// The union of the sorted distinct codes of every part in a stripe.
3618///
3619/// Pairwise up a tree rather than one long list concatenated and sorted. Both are the same order of
3620/// work on paper and the tree is the one that does not sort what is already in order: sixty four
3621/// sorted lists become one in six passes over the values.
3622fn 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
3664/// The widest bounds and the total null count of a stripe, from the bounds of its parts.
3665///
3666/// A bound that is missing from any part is missing from the stripe, because a missing bound means
3667/// nothing is known and a stripe that holds an unknown cannot claim one.
3668fn 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        // Both of these have to survive every part, so one part that could not say anything makes
3674        // the stripe unable to say it either. A sum is dropped on overflow rather than wrapped,
3675        // which leaves the stripe with exact ends and no total, which is a true thing to say.
3676        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
3700/// One stripe's sieves for one column: the part count, a length for each part, then their bytes.
3701///
3702/// One page for the whole stripe rather than one per part, because a part's sieve is a few hundred
3703/// bytes and sixty four of those are sixty four directory entries and sixty four reads for something
3704/// a scan walks straight through. A part with no sieve writes a length of zero and costs four bytes.
3705fn 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    // flatten: a part with no sieve wrote a length of zero above and contributes no bytes here.
3717    for sieve in held.into_iter().flatten() {
3718        out.extend_from_slice(&sieve.to_bytes());
3719    }
3720    Ok(out)
3721}
3722
3723/// The sieves one encoded page holds, one entry per part of the stripe.
3724///
3725/// A part whose bytes are not a sieve this version understands comes back as `None`, which is a part
3726/// that gets read. That is how a file written by a later version of the sieve stays readable rather
3727/// than being a corrupt page.
3728fn 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
3762/// One stripe's membership index: the code count and then the codes as ascending deltas.
3763///
3764/// The codes have to be sorted and distinct already, which is what [`unique_codes`] and
3765/// [`merged_codes`] hand over. Anything else decodes as different codes, so neither of those two is
3766/// a step a caller can skip.
3767fn 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
3886/// The first eight bytes of a value as an integer that sorts the way the bytes sort.
3887fn 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
3894/// The sorted order of every global dictionary, one entry per column and empty where there is no
3895/// dictionary.
3896///
3897/// One column's sort has nothing to do with another's, and a table like `hits` has fifteen string
3898/// columns, so this runs across threads the way the numeric synopses above do. It is the only part
3899/// of committing a file that is more than bookkeeping, and doing it serially would show up as a
3900/// pause at the end of a load that thirty two threads had been busy with until then.
3901fn 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
3979/// The sorted order laid out the way a reader reads it, in blocks of [`TEXT_RANK_BLOCK`] entries.
3980///
3981/// Each block holds its heads first and then its codes, rather than pairing them, because a search
3982/// asks for a head at every probe and for a code about once a search. Keeping the heads together
3983/// means a probe touches eight bytes of a block rather than twelve spread over it, and the last few
3984/// probes of a search, which are the ones that land in the same block, touch the same cache line.
3985fn 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    // The sorted order is kept out of the index on purpose. The index is read and checksummed in
4014    // full the moment the column is first touched, and the order is two thirds the size of the
4015    // offsets, so putting it there would make every query that reads a string column pay for a
4016    // search that most of them never make.
4017    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            // The cascade holds the whole tail of the page and says how long it is itself, so the
4144            // check that nothing is left over is the one the decoder already makes.
4145            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        // The cascade holds the whole tail of the page and says how long it is itself.
4168        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    /// A read names the offset it wants, so a cursor somebody else moved cannot reach it.
4323    #[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    /// The writer records where it put a page and puts it there, whatever the cursor is doing.
4360    ///
4361    /// The cursor is moved between the steps that record an offset, which is what reading the pages
4362    /// back to build the frequencies does on a platform with no `pread`. Without the fix the
4363    /// directory lands on top of a page and the file fails to reopen.
4364    #[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        // Nothing the directory points at may run past the end of the file, which is the shape the
4390        // failure took: a page recorded at an offset the directory had already been written over.
4391        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        // Two appends below the stripe bound are two parts of one stripe, which is the whole point
4450        // of the split: the directory describes the stripe and the scan still reads a part.
4451        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    /// Two pipeline instances handing over whole runs, which is what makes the native sink safe to
4484    /// instance.
4485    ///
4486    /// The runs arrive in the order the instances finished reading them rather than in source
4487    /// order, and the second one to finish is the one that read the earlier rows. Each run is still
4488    /// a stripe of its own and the table still reads back in source order, which is the whole of
4489    /// what the writer promises about ordering.
4490    #[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    /// Runs from different callers may interleave and may not overlap, and the commit is what
4525    /// catches an overlap.
4526    #[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        // The second run sits inside the first rather than after it, which is a thing no instance
4538        // holding its own contiguous run can produce and a thing the file cannot represent.
4539        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    /// A stripe holds [`STRIPE_PARTS`] parts, so a run longer than that is a caller bug rather than
4547    /// something to split, and the writer says so at the door instead of quietly cutting it in two.
4548    #[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    /// Parts past the stripe bound start a new stripe, and every part stays addressable on its own.
4568    ///
4569    /// This is the shape the format exists for, so both ends of the split are checked here. The
4570    /// directory holds three stripes rather than a hundred and thirty one, and a read of any one
4571    /// part still answers with that part's rows rather than with its whole stripe's.
4572    #[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        // Backwards on purpose. The reader keeps four stripes a column, so a scan that walks the
4612        // table the other way is what catches a cache that only ever holds what it just read.
4613        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        // The bounds are merged over the stripe, so they answer for the range the whole stripe
4625        // covers and not for the part that was asked about.
4626        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    /// A scattered value in the column that decides `WHERE UserID = ?`.
4633    fn scattered(n: i64) -> i64 {
4634        n.wrapping_mul(-7_046_029_254_386_353_131)
4635    }
4636
4637    /// A part whose sieve does not hold the constant is skipped, and a range would skip none of them.
4638    ///
4639    /// This is ClickBench query 19 in miniature. The values are spread over the whole of `BIGINT`, so
4640    /// every stripe's bounds cover nearly all of it and rule out nothing, and the part that really
4641    /// holds the value is the only one a scan has to read.
4642    #[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        // The same probes against the bounds alone, which is what this replaces. A column of
4676        // scattered numbers has a range per stripe that covers nearly the whole type.
4677        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    /// A damaged sieve page is a part that gets read, not a query that fails.
4686    ///
4687    /// A sieve is an index over rows that are still there and still correct, so losing one costs
4688    /// time and costs no answers. That is the opposite of the membership index beside it, which is
4689    /// the only thing standing between a string page and a wrong answer.
4690    #[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    /// Eight workers over one stripe read it once between them.
4719    ///
4720    /// This is the shape a scan actually has. Parts are handed out in order, so every worker on a
4721    /// column crosses into a stripe within a few parts of the others, and before [`Reader::held`]
4722    /// started sharing the read every one of them read the whole page. On the full ClickBench file
4723    /// that was a `MIN(EventDate), MAX(EventDate)` moving 3.2 GB off the disk to look at 400 MB of
4724    /// column, which is most of what a first touch costs.
4725    ///
4726    /// The workers that lose the race still answer, out of the part reads they do instead, which is
4727    /// what the values below are checking.
4728    #[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    /// Opening a file reads the header and the directory, and nothing that depends on the rows.
4770    ///
4771    /// `spec/stats/04-in-memory.md` section 4.2. There are no statistics in the file yet, so this
4772    /// holds today by not having anything to load, and that is exactly why it is worth pinning now.
4773    /// The change that breaks it is the reasonable looking one: summaries are a few hundred bytes,
4774    /// the next query will want them, so read them on the way past. A process that opened the
4775    /// database to run one trivial query pays for all of it and gets nothing.
4776    ///
4777    /// Two files of the same shape and a thousand times the rows in one of them, opened, and the
4778    /// two openings cost the same. The stripe count is held equal so that the directory is the same
4779    /// size in both, which leaves the rows as the only thing that changed. Anything read out of the
4780    /// data would show up here.
4781    #[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                // Scrambled rather than sequential, so that the fat file is actually fatter. A run
4790                // of consecutive integers encodes to almost nothing and would leave the two files
4791                // the same size, which would make this test pass for the wrong reason.
4792                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        // Not exactly equal, because a directory holds offsets and a larger file has larger ones,
4828        // and a handful of bytes of varint is not somebody loading statistics. A factor is.
4829        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    /// The reads a file costs to open are fixed by its shape and not by what ran before.
4838    ///
4839    /// `spec/stats/04-in-memory.md` section 4.3, which is the rule that keeps a plan reproducible:
4840    /// the plan is a function of the data, the generation and the settings, and never of what
4841    /// happened to be in cache. Opening the same file twice in the same process has to cost the
4842    /// same, because a second open that read less would be an open that was about to plan
4843    /// differently.
4844    #[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        // A whole scan in between, so the operating system's page cache is as warm as it gets and
4862        // anything that consulted it would show up in the second open.
4863        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    /// A scan reads a stripe's index once for the whole scan, not once per part that misses.
4880    ///
4881    /// The page cache holds four stripes and an index used to ride inside it, so a table with more
4882    /// stripes than that read the index again every time a stripe came back around. The index is a
4883    /// few hundred bytes and the page is a quarter of a megabyte, which is why they are now under
4884    /// different budgets. This is the test that keeps them there, since the saving is small enough
4885    /// that nothing in a benchmark would notice it going away again.
4886    #[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        // Twice over, so that the second pass finds every page evicted and every index kept.
4907        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    /// A worker per stripe reads its stripe once, once the cache has been told how many there are.
4923    ///
4924    /// This is the shape a scan has when it hands out a whole stripe per morsel rather than a part.
4925    /// Nobody races for a page any more, but every worker holds a different one for the length of a
4926    /// stripe, so a cache that keeps four pages while eight workers are in eight stripes evicts
4927    /// every one of them before its owner has finished with it, and the owner reads a quarter of a
4928    /// megabyte again for the next part. The barrier is what makes that certain rather than likely:
4929    /// without it a worker can run a whole stripe before the next one starts and never collide.
4930    #[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    /// A damaged index page is caught before anything decodes a part out of it.
4977    ///
4978    /// The index is the one structure a reader trusts to find bytes with, so it carries a checksum
4979    /// per column section rather than one for the page, and this is what says that check runs.
4980    #[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    /// Every integer width the format knows about, written and read back.
5003    ///
5004    /// The unsigned ones are the reason ClickBench can be stored at all: `hits` types `EventDate`
5005    /// as `USMALLINT`, and one unsupported column meant the whole table was refused. The extremes
5006    /// are in here on purpose, because a width that round trips through the wrong signedness only
5007    /// goes wrong at the end of its range.
5008    #[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        // row at a time: each column has its own type and its own pair of extremes.
5039        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    /// The bug this is here for cost a 43 GB ClickBench table and an hour of reloading it. The
5075    /// format went from 11 to 12, every binary built after that said "magic or major version is
5076    /// unsupported" about the file, and there was no way to tell from the message whether the path
5077    /// was wrong, the file was truncated, or it was ours and simply older. The number this build
5078    /// wants is the whole answer and it was the one thing the message did not carry.
5079    #[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        // Read the count out of the page rather than writing it here, so that adding something
5160        // else to the index does not silently turn this into a test that damages the index.
5161        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    /// A payload that spans more than one extent still reads and checks every block of it.
5181    ///
5182    /// The test above has a dictionary of three values, so it says nothing about the grouping a
5183    /// reader does over the blocks the checksums are written for. This one is over a megabyte,
5184    /// which is more than one extent, and it reads a value out of the first extent and a value out
5185    /// of the last and then damages the last and asks for it again.
5186    #[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    /// The sorted order sits outside the index the page checksum covers, because a query that
5232    /// never searches a dictionary should not read it, so it carries its own checksums and this is
5233    /// what says they are checked. A search that trusted a damaged order would give a wrong answer
5234    /// rather than a slow one.
5235    #[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    /// Codes stay in first appearance order and the sorted order is written beside them, so a
5269    /// reader can put the values back in order without the writer having had to know them all
5270    /// before it handed out the first code.
5271    #[test]
5272    fn a_global_dictionary_carries_the_sorted_order_of_its_values() {
5273        // Chosen so the sort cannot be decided on the first eight bytes alone. Three values share
5274        // a nine byte prefix, one is a prefix of another, and one is empty.
5275        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        // What a search asks, on the values themselves rather than through a kernel, so that a
5316        // file whose heads disagree with its bytes is caught here rather than as a wrong answer.
5317        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        // A stripe's index is the union of its parts', so a code in two of them is in it once and
5369        // the result is still one ascending run of deltas.
5370        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        // This column used to cost four bytes a row, 16,384 of them, the same as a column of four
5421        // thousand distinct URLs would. The cascade calls each part a constant, so what is left is
5422        // a tag, a count and the value, and the row count stops being what drives the number.
5423        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        // What a damaged page looks like from here: the cascade decoded, so the bytes are not
5433        // truncated, but the values do not belong to the column the directory says they do.
5434        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        // A shift register rather than a run, because an arithmetic run is the one wide shape the
5444        // cascade does shrink. This is what a column with tens of millions of distinct values hands
5445        // over: full width codes with no order to them.
5446        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    /// The columns of a stripe are encoded on whichever thread got to them, so the one thing that
5462    /// must not depend on which thread that was is the file. Two writes of the same rows are
5463    /// compared byte for byte rather than value for value, because a dictionary that two columns
5464    /// somehow shared would still read back correctly and would hand out its codes in the order the
5465    /// threads happened to run in, which is exactly what this is here to catch.
5466    #[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        // And the rows are still there, since a pair of identically wrong files would pass the
5513        // comparison above on its own.
5514        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}