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;
60const MAX_FREQUENCY_WORKERS: usize = 16;
61
62/// The most threads one stripe's encode is spread over.
63///
64/// Higher than the frequency cap because this is the load itself rather than a pass at the end of
65/// it, and the work is one column of sixty four parts, which is large enough that a thread that
66/// takes one is not a thread that was started for nothing. A machine with more cores than this has
67/// the rest of them on the Parquet read, which is still one thread and is the other half of #808.
68const MAX_ENCODE_WORKERS: usize = 32;
69
70/// The most bytes one column of one part may spend on a membership sieve.
71///
72/// A part is a thousand rows, so a filter sized for every one of them being distinct is about
73/// thirteen hundred bytes and this never binds in practice. It is here so that a part that somehow
74/// arrives much wider than a vector cannot put an unbounded index in the file.
75const SIEVE_BUDGET: usize = 8 * 1024;
76
77fn io(error: std::io::Error) -> Error {
78    Error::io(error.to_string())
79}
80
81fn invalid(message: &str) -> Error {
82    Error::invalid_input(format!("invalid rudb native file: {message}"))
83}
84
85/// Adds a sequence of byte counts without an overflow the caller has to think about.
86fn sum(counts: impl Iterator<Item = u64>) -> u64 {
87    counts.fold(0, u64::saturating_add)
88}
89
90/// One column's span out of a per column list, or zero when the list is shorter than the column.
91fn span_bytes(spans: &[Span], at: usize) -> u64 {
92    spans.get(at).map_or(0, |span| u64::from(span.length))
93}
94
95/// One column's page out of a per column list, or zero when that column has no page at all.
96fn page_bytes(pages: &[Option<Page>], at: usize) -> u64 {
97    pages.get(at).and_then(Option::as_ref).map_or(0, Page::bytes)
98}
99
100fn checksum(bytes: &[u8]) -> u64 {
101    const P1: u64 = 11_400_714_785_074_694_791;
102    const P2: u64 = 14_029_467_366_897_019_727;
103    const P3: u64 = 1_609_587_929_392_839_161;
104    const P4: u64 = 9_650_029_242_287_828_579;
105    const P5: u64 = 2_870_177_450_012_600_261;
106    let round = |state: u64, word: u64| {
107        state.wrapping_add(word.wrapping_mul(P2)).rotate_left(31).wrapping_mul(P1)
108    };
109    let merge = |state: u64, lane: u64| (state ^ round(0, lane)).wrapping_mul(P1).wrapping_add(P4);
110    let word =
111        |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("eight checksum bytes"));
112
113    let mut at = 0;
114    let mut hash = if bytes.len() >= 32 {
115        let mut one = P1.wrapping_add(P2);
116        let mut two = P2;
117        let mut three = 0;
118        let mut four = 0_u64.wrapping_sub(P1);
119        while at + 32 <= bytes.len() {
120            one = round(one, word(at));
121            two = round(two, word(at + 8));
122            three = round(three, word(at + 16));
123            four = round(four, word(at + 24));
124            at += 32;
125        }
126        let combined = one
127            .rotate_left(1)
128            .wrapping_add(two.rotate_left(7))
129            .wrapping_add(three.rotate_left(12))
130            .wrapping_add(four.rotate_left(18));
131        merge(merge(merge(merge(combined, one), two), three), four)
132    } else {
133        P5
134    };
135    hash = hash.wrapping_add(bytes.len() as u64);
136    while at + 8 <= bytes.len() {
137        hash ^= round(0, word(at));
138        hash = hash.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
139        at += 8;
140    }
141    if at + 4 <= bytes.len() {
142        let tail = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four checksum bytes"));
143        hash ^= u64::from(tail).wrapping_mul(P1);
144        hash = hash.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
145        at += 4;
146    }
147    while at < bytes.len() {
148        hash ^= u64::from(bytes[at]).wrapping_mul(P5);
149        hash = hash.rotate_left(11).wrapping_mul(P1);
150        at += 1;
151    }
152    hash ^= hash >> 33;
153    hash = hash.wrapping_mul(P2);
154    hash ^= hash >> 29;
155    hash = hash.wrapping_mul(P3);
156    hash ^ (hash >> 32)
157}
158
159#[derive(Debug, Clone, Copy)]
160struct Slot {
161    offset: u64,
162    length: u32,
163    generation: u64,
164    hash: u64,
165}
166
167impl Slot {
168    fn bytes(self) -> [u8; SLOT_BYTES] {
169        let mut result = [0; SLOT_BYTES];
170        result[..8].copy_from_slice(&self.offset.to_le_bytes());
171        result[8..12].copy_from_slice(&self.length.to_le_bytes());
172        result[12..20].copy_from_slice(&self.generation.to_le_bytes());
173        result[20..28].copy_from_slice(&self.hash.to_le_bytes());
174        result
175    }
176
177    fn read(bytes: &[u8]) -> Self {
178        Self {
179            offset: u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")),
180            length: u32::from_le_bytes(bytes[8..12].try_into().expect("four bytes")),
181            generation: u64::from_le_bytes(bytes[12..20].try_into().expect("eight bytes")),
182            hash: u64::from_le_bytes(bytes[20..28].try_into().expect("eight bytes")),
183        }
184    }
185}
186
187#[derive(Debug, Clone, Copy)]
188struct Page {
189    offset: u64,
190    length: u32,
191    hash: u64,
192}
193
194impl Page {
195    /// How much of the file this page takes, for [`Reader::layout`].
196    fn bytes(&self) -> u64 {
197        u64::from(self.length)
198    }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
202enum FrequencyValue {
203    Null,
204    Integer(i128),
205    Code(u32),
206}
207
208#[derive(Debug, Clone)]
209struct FrequencyEntry {
210    value: FrequencyValue,
211    count: u64,
212}
213
214/// Exact leading frequencies for one column.
215///
216/// Values outside `entries` occur at most `omitted_max` times. This lets a count-descending TopN
217/// use the synopsis only when its last winner is strictly above every omitted value.
218#[derive(Debug, Clone)]
219struct FrequencySummary {
220    entries: Vec<FrequencyEntry>,
221    omitted_max: u64,
222    ordinals: Vec<u64>,
223}
224
225/// Sparse row ordinals covered by a numeric frequency candidate set.
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct FrequencyOccurrences {
228    /// Upper bound for the frequency of every value absent from the fetched rows.
229    pub omitted_max: u64,
230    /// Table-wide row ordinals in ascending order.
231    pub ordinals: Vec<u64>,
232}
233
234/// Where one column's page for one stripe sits in the file.
235///
236/// A column page has no checksum of its own because every part inside it carries one, and the
237/// stripe's index page holds those. Checking a part on the way out of the page covers exactly the
238/// bytes a reader is about to decode, and covers them once whether the reader took the whole page
239/// or pulled one part out of the middle of it.
240#[derive(Debug, Clone, Copy, Default)]
241struct Span {
242    offset: u64,
243    length: u32,
244}
245
246/// One independently readable stripe of a table.
247#[derive(Debug, Clone)]
248pub struct Stripe {
249    rows: usize,
250    /// Rows in each part, in source order. Kept in the directory so that mapping a row ordinal to a
251    /// part, which every sparse fetch does, never reads the file.
252    parts: Vec<u32>,
253    /// The index page: one section per column, holding a length and a checksum for every part and
254    /// then a checksum of the section itself, so that a reader can pread one column's section and
255    /// still know it is intact.
256    index: Span,
257    pages: Vec<Span>,
258    memberships: Vec<Option<Page>>,
259    /// One page per column holding the membership sieve of every part of the stripe, for the
260    /// columns that have one. A column whose parts all declined a sieve has no page at all.
261    sieves: Vec<Option<Page>>,
262    zone: Zone,
263}
264
265impl Stripe {
266    /// Number of rows in this stripe.
267    #[must_use]
268    pub fn rows(&self) -> usize {
269        self.rows
270    }
271
272    /// Number of parts in this stripe.
273    #[must_use]
274    pub fn parts(&self) -> usize {
275        self.parts.len()
276    }
277}
278
279/// The committed table directory.
280#[derive(Debug, Clone)]
281pub struct Table {
282    name: String,
283    fields: Vec<Field>,
284    stripes: Vec<Stripe>,
285    rows: usize,
286    dictionaries: Vec<Option<Page>>,
287    frequencies: Vec<Option<FrequencySummary>>,
288}
289
290impl Table {
291    /// The SQL table name held by this snapshot.
292    #[must_use]
293    pub fn name(&self) -> &str {
294        &self.name
295    }
296
297    /// Columns in their SQL order.
298    #[must_use]
299    pub fn fields(&self) -> &[Field] {
300        &self.fields
301    }
302
303    /// Committed row count.
304    #[must_use]
305    pub fn rows(&self) -> usize {
306        self.rows
307    }
308
309    /// Independently readable stripes.
310    #[must_use]
311    pub fn stripes(&self) -> &[Stripe] {
312        &self.stripes
313    }
314}
315
316/// Where one column's bytes went, taken from the directory rather than by reading pages.
317#[derive(Debug, Clone)]
318pub struct ColumnLayout {
319    /// The column's name, so a report does not have to carry the field list beside this.
320    pub name: String,
321    /// The type, spelled the way the catalog spells it.
322    pub kind: String,
323    /// Every stripe's page of this column added up, which is the encoded data itself.
324    pub pages: u64,
325    /// Every stripe's exact code membership page for this column.
326    pub memberships: u64,
327    /// Every stripe's membership sieve page for this column.
328    pub sieves: u64,
329    /// The table wide dictionary of this column, if it has one.
330    pub dictionary: u64,
331}
332
333impl ColumnLayout {
334    /// Everything this column costs, which is what the file would lose if the column went.
335    #[must_use]
336    pub fn total(&self) -> u64 {
337        self.pages
338            .saturating_add(self.memberships)
339            .saturating_add(self.sieves)
340            .saturating_add(self.dictionary)
341    }
342}
343
344/// Where a whole file's bytes went.
345///
346/// Every number here comes out of the committed directory, so taking it costs one directory read
347/// however large the file is. That is the point: a 45 GB table has to be able to say where it went
348/// without being read, or nobody will ask.
349///
350/// The parts that are not a column are kept apart rather than shared out over the columns. The
351/// stripe index page holds a section per column and could be split, and the directory and the
352/// header cannot be, so splitting one of the three and not the others would read as if the columns
353/// accounted for everything. They do not, and the gap is the thing worth looking at.
354#[derive(Debug, Clone)]
355pub struct Layout {
356    /// The size of the file on disk.
357    pub file: u64,
358    /// Committed rows.
359    pub rows: usize,
360    /// Committed stripes.
361    pub stripes: usize,
362    /// Committed parts, which is how many chunks a scan reads.
363    pub parts: usize,
364    /// One entry per column, in the table's column order.
365    pub columns: Vec<ColumnLayout>,
366    /// Every stripe's index page, which carries a length and a checksum for every part of every
367    /// column and is charged per stripe rather than per column.
368    pub indexes: u64,
369    /// The committed directory itself, the one that was read to build this.
370    pub directory: u64,
371    /// The fixed header, which holds the magic, the format and the two directory slots.
372    pub header: u64,
373}
374
375impl Layout {
376    /// Everything the columns cost together.
377    #[must_use]
378    pub fn columns_total(&self) -> u64 {
379        self.columns.iter().map(ColumnLayout::total).fold(0, u64::saturating_add)
380    }
381
382    /// What the file holds that this does not account for.
383    ///
384    /// A committed file is written once and never rewritten in place, so an earlier directory and
385    /// the pages of an earlier snapshot are still in it. That is the honest place for them: they
386    /// are bytes on disk that no column owns.
387    #[must_use]
388    pub fn unaccounted(&self) -> u64 {
389        self.file
390            .saturating_sub(self.columns_total())
391            .saturating_sub(self.indexes)
392            .saturating_sub(self.directory)
393            .saturating_sub(self.header)
394    }
395}
396
397/// Appends pages and commits a new directory for one table.
398#[derive(Debug)]
399struct GlobalDictionary {
400    primary: HashMap<u64, u32>,
401    collisions: HashMap<u64, Vec<u32>>,
402    offsets: Vec<u32>,
403    payload: Vec<u8>,
404    counts: Vec<u64>,
405    nulls: u64,
406}
407
408impl GlobalDictionary {
409    fn new() -> Self {
410        Self {
411            primary: HashMap::new(),
412            collisions: HashMap::new(),
413            offsets: vec![0],
414            payload: Vec::new(),
415            counts: Vec::new(),
416            nulls: 0,
417        }
418    }
419
420    fn bytes(&self, code: u32) -> Option<&[u8]> {
421        let start = *self.offsets.get(code as usize)? as usize;
422        let end = *self.offsets.get(code as usize + 1)? as usize;
423        self.payload.get(start..end)
424    }
425
426    fn code(&mut self, text: &str) -> Result<u32> {
427        let hash = checksum(text.as_bytes());
428        if let Some(&code) = self.primary.get(&hash) {
429            if self.bytes(code) == Some(text.as_bytes()) {
430                return Ok(code);
431            }
432            if let Some(codes) = self.collisions.get(&hash) {
433                if let Some(code) =
434                    codes.iter().copied().find(|&code| self.bytes(code) == Some(text.as_bytes()))
435                {
436                    return Ok(code);
437                }
438            }
439            let code = self.insert(text)?;
440            self.collisions.entry(hash).or_default().push(code);
441            return Ok(code);
442        }
443        let code = self.insert(text)?;
444        self.primary.insert(hash, code);
445        Ok(code)
446    }
447
448    fn insert(&mut self, text: &str) -> Result<u32> {
449        let code = u32::try_from(self.offsets.len() - 1)
450            .map_err(|_| invalid("global dictionary has too many values"))?;
451        self.payload.extend_from_slice(text.as_bytes());
452        self.offsets.push(
453            u32::try_from(self.payload.len())
454                .map_err(|_| invalid("global dictionary payload exceeds 4 GiB"))?,
455        );
456        self.counts.push(0);
457        Ok(code)
458    }
459
460    /// This dictionary's values in sorted order, each as the first eight bytes of the value and the
461    /// code that holds it, so entry `rank` describes the value that sits at `rank` when the values
462    /// are sorted by their bytes.
463    ///
464    /// Codes themselves stay in first appearance order, which is what lets the writer hand one out
465    /// the moment it sees a value rather than waiting for the last stripe, and which also keeps a
466    /// stripe's codes close together because the data is clustered. This is what puts the values
467    /// back in order for anything that needs it, and it is separate from the codes so that getting
468    /// it costs a sort of the distinct values at the end rather than a rewrite of every code page.
469    ///
470    /// The sort compares the first eight bytes as one integer before it compares the values, which
471    /// settles almost every pair without touching the payload. Padding with zero on the right is
472    /// order preserving for byte strings, because a shorter value differs from a longer one that
473    /// starts the same way at a position where the shorter one has run out, and zero is below every
474    /// byte that could be there. A pair the head cannot settle falls through to the bytes.
475    ///
476    /// The heads are kept rather than thrown away once the sort is over, because a reader searching
477    /// this order wants exactly the same comparison and for exactly the same reason. Eight bytes an
478    /// entry of file is what buys a binary search that reads no values at all in the ordinary case.
479    fn ranked(&self) -> Vec<(u64, u32)> {
480        let count = self.offsets.len() - 1;
481        let mut ranked = (0..count)
482            .map(|code| {
483                let code = code as u32;
484                (head(self.bytes(code).unwrap_or_default()), code)
485            })
486            .collect::<Vec<_>>();
487        ranked.sort_unstable_by(|left, right| {
488            left.0.cmp(&right.0).then_with(|| self.bytes(left.1).cmp(&self.bytes(right.1)))
489        });
490        ranked
491    }
492
493    fn observe(&mut self, code: u32, null: bool) -> Result<()> {
494        if null {
495            self.nulls = self.nulls.saturating_add(1);
496            return Ok(());
497        }
498        let count = self
499            .counts
500            .get_mut(code as usize)
501            .ok_or_else(|| invalid("global dictionary count code is out of range"))?;
502        *count = count.saturating_add(1);
503        Ok(())
504    }
505}
506
507/// Appends pages and commits a new directory for one table.
508#[derive(Debug)]
509pub struct Writer {
510    file: File,
511    /// Where the next write goes, counted here rather than asked of the file.
512    ///
513    /// The file's own cursor is not ours. Building the numeric frequencies reads pages back through
514    /// [`read_at`], and a positional read is only positional about where it reads from: `pread`
515    /// leaves the cursor alone, and the call Windows has for it moves the cursor to the end of what
516    /// it read. A writer that asked the file where it was would then write the directory over a
517    /// page it had already written, which is what it did.
518    at: u64,
519    table: Table,
520    generation: u64,
521    /// The first and the last source position in every stripe, in the order the stripes were
522    /// written.
523    order: Vec<((u64, u64), (u64, u64))>,
524    next_order: u64,
525    dictionaries: Vec<Option<GlobalDictionary>>,
526    pending: Vec<PendingChunk>,
527}
528
529/// A chunk that has arrived and is waiting for the rest of its stripe.
530///
531/// The rows are kept rather than the pages they encode to, which is the whole of #808's first half.
532/// Encoding on arrival put every column of every part on the thread that called `append_at`, and
533/// that thread is the only one the load has. Encoding at the flush instead means a stripe's worth
534/// of work is on the table at once, and a stripe splits by column into a hundred and five pieces
535/// that share nothing.
536#[derive(Debug)]
537struct PendingChunk {
538    order: (u64, u64),
539    chunk: Chunk,
540}
541
542/// One column's share of a stripe, which is what one encode worker produces.
543///
544/// Indexed by part, so a stripe is a column of these and the write loop reads down one of them.
545/// That is also the order the loop wanted: `flush_pending` walks a column at a time and lays its
546/// parts next to each other, and it used to reach across a row of parts to do it.
547#[derive(Debug)]
548struct ColumnStripe {
549    pages: Vec<Vec<u8>>,
550    codes: Vec<Option<Vec<u32>>>,
551    sieves: Vec<Option<Sieve>>,
552    ranges: Vec<Range>,
553}
554
555/// Roughly what encoding a column of this type costs, for ordering the encode queue.
556///
557/// Only the order matters and only roughly. A string column hashes and copies every value into a
558/// dictionary and is in a different class from everything else, and among the fixed widths the wide
559/// ones carry more bytes through the cascade than the narrow ones. Anything finer than that would
560/// be a cost model, and the queue already absorbs a wrong guess: it only has to avoid finishing on
561/// a column nobody else can help with.
562fn weight(ty: &LogicalType) -> usize {
563    match ty {
564        LogicalType::Varchar | LogicalType::Blob => 64,
565        LogicalType::BigInt
566        | LogicalType::UBigInt
567        | LogicalType::Timestamp
568        | LogicalType::Double
569        | LogicalType::Decimal { .. } => 8,
570        LogicalType::Integer | LogicalType::UInteger | LogicalType::Date | LogicalType::Float => 4,
571        LogicalType::SmallInt | LogicalType::USmallInt => 2,
572        _ => 1,
573    }
574}
575
576/// Parts in one stripe.
577///
578/// Sixty four thousand rows is the smallest stripe that keeps the ClickBench directory in single
579/// digit megabytes at a hundred million rows, and it puts a four byte column's page at a quarter of
580/// a megabyte, which is the size a sequential read wants. Larger stripes buy a smaller directory
581/// and cost a sparse fetch, which has to read a page index before it can reach one part.
582const STRIPE_PARTS: usize = 64;
583
584/// Bytes one part takes in a stripe's index page: four for the length, eight for the checksum.
585const INDEX_ENTRY: usize = size_of::<u32>() + size_of::<u64>();
586
587/// Bytes one column's section of a stripe's index page takes, including its own trailing checksum.
588fn index_section(parts: usize) -> Result<usize> {
589    parts
590        .checked_mul(INDEX_ENTRY)
591        .and_then(|bytes| bytes.checked_add(size_of::<u64>()))
592        .ok_or_else(|| invalid("index page length overflow"))
593}
594
595impl Writer {
596    /// Creates a new v10 file and its first table.
597    ///
598    /// # Errors
599    ///
600    /// If the file exists, a field has no scalar encoding, or the path cannot be written.
601    pub fn create(
602        path: impl AsRef<Path>,
603        name: impl Into<String>,
604        fields: Vec<Field>,
605    ) -> Result<Self> {
606        for field in &fields {
607            type_tag(&field.ty)?;
608        }
609        let file =
610            OpenOptions::new().write(true).read(true).create_new(true).open(path).map_err(io)?;
611        let mut header = [0; HEADER as usize];
612        header[..8].copy_from_slice(MAGIC);
613        header[8..12].copy_from_slice(&FORMAT.to_le_bytes());
614        write_at(&file, 0, &header)?;
615        Ok(Self {
616            file,
617            at: HEADER,
618            dictionaries: fields
619                .iter()
620                .map(|field| (field.ty == LogicalType::Varchar).then(GlobalDictionary::new))
621                .collect(),
622            table: Table {
623                name: name.into(),
624                dictionaries: vec![None; fields.len()],
625                fields,
626                stripes: Vec::new(),
627                rows: 0,
628                frequencies: Vec::new(),
629            },
630            generation: 1,
631            order: Vec::new(),
632            next_order: 0,
633            pending: Vec::with_capacity(STRIPE_PARTS),
634        })
635    }
636
637    /// Appends bytes at the end of the file and moves the writer's own offset past them.
638    ///
639    /// Every write in here goes through this, so that [`Writer::at`] is the only answer to where
640    /// anything is and the file's cursor is never consulted for it.
641    fn put(&mut self, bytes: &[u8]) -> Result<()> {
642        write_at(&self.file, self.at, bytes)?;
643        self.at = self
644            .at
645            .checked_add(bytes.len() as u64)
646            .ok_or_else(|| invalid("native file length overflow"))?;
647        Ok(())
648    }
649
650    /// Writes one chunk as independently readable column pages.
651    ///
652    /// # Errors
653    ///
654    /// If its width or types differ from the declared table, or a page exceeds its bound.
655    pub fn append(&mut self, chunk: &Chunk) -> Result<()> {
656        let order = (self.next_order, 0);
657        self.next_order = self.next_order.saturating_add(1);
658        self.append_at(order, chunk)
659    }
660
661    /// Writes one chunk and records its source position for directory ordering.
662    ///
663    /// Pages may be encoded by parallel pipeline instances and reach the file in completion order.
664    /// The stripe they land in is sorted by this key at commit, and [`Self::finish`] rejects a
665    /// sequence whose parts do not come out in source order once the stripes are sorted, because a
666    /// stripe groups whatever arrived together and cannot put a late part back where it belongs.
667    ///
668    /// # Errors
669    ///
670    /// The same as [`Self::append`].
671    pub fn append_at(&mut self, order: (u64, u64), chunk: &Chunk) -> Result<()> {
672        if chunk.is_empty() {
673            return Ok(());
674        }
675        if chunk.width() != self.table.fields.len() {
676            return Err(invalid("chunk width differs from table schema"));
677        }
678        for (index, field) in self.table.fields.iter().enumerate() {
679            if chunk.column(index)?.logical_type() != &field.ty {
680                return Err(invalid("chunk type differs from table schema"));
681            }
682        }
683        self.table.rows = self
684            .table
685            .rows
686            .checked_add(chunk.len())
687            .ok_or_else(|| invalid("row count overflow"))?;
688        if self.pending.last().is_some_and(|last| last.order > order) {
689            self.flush_pending()?;
690        }
691        // Cloned rather than encoded, and a clone of a chunk that owns its buffers is a copy of
692        // them. Sixty four parts of a hundred and five columns is tens of megabytes held for the
693        // length of a stripe and a few seconds of memory traffic over a whole ClickBench load,
694        // against the hundreds of seconds of encode this is what lets off one thread.
695        self.pending.push(PendingChunk { order, chunk: chunk.clone() });
696        if self.pending.len() == STRIPE_PARTS {
697            self.flush_pending()?;
698        }
699        Ok(())
700    }
701
702    /// Encodes one column's parts of a stripe, with the column's dictionary to itself.
703    ///
704    /// Nothing here is shared with another column. The dictionary belongs to this one, the sieve
705    /// reads only this one, and the page bytes go in a vector of this one's own. That is why the
706    /// fan out below can hand a whole column to a thread and take a plain `&mut` on the dictionary
707    /// rather than making it something several threads can grow at once, which is the harder half
708    /// of #808 and is still open.
709    fn encode_column(
710        index: usize,
711        held: &[PendingChunk],
712        mut dictionary: Option<&mut GlobalDictionary>,
713    ) -> Result<ColumnStripe> {
714        let mut stripe = ColumnStripe {
715            pages: Vec::with_capacity(held.len()),
716            codes: Vec::with_capacity(held.len()),
717            sieves: Vec::with_capacity(held.len()),
718            ranges: Vec::with_capacity(held.len()),
719        };
720        for pending in held {
721            let column = pending.chunk.column(index)?;
722            let (bytes, unique) = encode(column, dictionary.as_deref_mut())?;
723            if bytes.len() > MAX_PAGE {
724                return Err(invalid("column page exceeds the configured bound"));
725            }
726            // The range is built first because the sieve reads it rather than walking the column a
727            // second time to find out how wide it is.
728            let range = Range::of(column);
729            // A column with a global dictionary already has an exact membership index per stripe,
730            // so an approximate one beside it would cost a hash of every string in the table to
731            // answer a question that is already answered. What it would buy is the finer grain, a
732            // part rather than a stripe, and that is worth coming back for on its own.
733            let sieve = match dictionary {
734                Some(_) => None,
735                None => Sieve::of(column, &range, SIEVE_BUDGET),
736            };
737            stripe.pages.push(bytes);
738            stripe.codes.push(unique);
739            stripe.sieves.push(sieve);
740            stripe.ranges.push(range);
741        }
742        Ok(stripe)
743    }
744
745    /// Encodes a whole stripe, one column to a worker.
746    ///
747    /// The columns are handed out through a queue rather than dealt in equal piles, because they
748    /// are nothing like equal: `URL` on ClickBench is a global dictionary of sixty one million
749    /// strings and `IsMobile` is a byte. A pile that happened to hold the four large string columns
750    /// would be the whole stripe and the other workers would be waiting on it. The queue is sorted
751    /// so the expensive ones are taken first, which is the classic answer to a last job that runs
752    /// longer than everything after it.
753    fn encode_columns(&mut self, held: &[PendingChunk]) -> Result<Vec<ColumnStripe>> {
754        let width = self.table.fields.len();
755        let workers = std::thread::available_parallelism()
756            .map_or(1, usize::from)
757            .min(MAX_ENCODE_WORKERS)
758            .min(width);
759        if workers <= 1 || held.len() <= 1 {
760            return self
761                .dictionaries
762                .iter_mut()
763                .enumerate()
764                .map(|(index, dictionary)| Self::encode_column(index, held, dictionary.as_mut()))
765                .collect();
766        }
767        // The dictionaries are moved out and back rather than borrowed, because a worker that takes
768        // the next column off a queue cannot be holding a borrow of the vector the queue came from.
769        let mut jobs: Vec<(usize, Option<GlobalDictionary>)> =
770            std::mem::take(&mut self.dictionaries).into_iter().enumerate().collect();
771        // Popped from the back, so the expensive columns go last in the vector.
772        jobs.sort_by_key(|(index, _)| weight(&self.table.fields[*index].ty));
773        let queue = Mutex::new(jobs);
774        let pieces = std::thread::scope(|scope| {
775            (0..workers)
776                .map(|_| {
777                    scope.spawn(|| {
778                        let mut mine = Vec::new();
779                        loop {
780                            let taken = queue
781                                .lock()
782                                .map_err(|_| Error::internal("a native encode worker panicked"))?
783                                .pop();
784                            let Some((index, mut dictionary)) = taken else { break };
785                            let encoded = Self::encode_column(index, held, dictionary.as_mut())?;
786                            mine.push((index, dictionary, encoded));
787                        }
788                        Ok(mine)
789                    })
790                })
791                .collect::<Vec<_>>()
792                .into_iter()
793                .map(|handle| {
794                    handle.join().map_err(|_| Error::internal("a native encode worker panicked"))?
795                })
796                .collect::<Result<Vec<_>>>()
797        })?;
798        let mut dictionaries: Vec<Option<GlobalDictionary>> = (0..width).map(|_| None).collect();
799        let mut encoded: Vec<Option<ColumnStripe>> = (0..width).map(|_| None).collect();
800        for piece in pieces {
801            for (index, dictionary, stripe) in piece {
802                dictionaries[index] = dictionary;
803                encoded[index] = Some(stripe);
804            }
805        }
806        self.dictionaries = dictionaries;
807        encoded
808            .into_iter()
809            .map(|stripe| stripe.ok_or_else(|| Error::internal("a column was never encoded")))
810            .collect()
811    }
812
813    /// Writes the buffered parts as one stripe, each column's parts contiguous on disk.
814    fn flush_pending(&mut self) -> Result<()> {
815        if self.pending.is_empty() {
816            return Ok(());
817        }
818        let width = self.table.fields.len();
819        // Held here rather than read off the writer, because writing a page needs the writer and
820        // the borrow checker is right that those are two different uses of it.
821        let mut held = std::mem::take(&mut self.pending);
822        let parts = held.len();
823        let encoded = self.encode_columns(&held)?;
824        let mut pages = Vec::with_capacity(width);
825        let mut memberships = vec![None; width];
826        let mut ranges = Vec::with_capacity(width);
827        let mut index = Vec::with_capacity(width.saturating_mul(index_section(parts)?));
828        for stripe in &encoded {
829            let offset = self.at;
830            let section = index.len();
831            let mut length = 0_usize;
832            for bytes in &stripe.pages {
833                write_at(&self.file, self.at + length as u64, bytes)?;
834                put_u32(
835                    &mut index,
836                    u32::try_from(bytes.len()).map_err(|_| invalid("part length overflow"))?,
837                );
838                put_u64(&mut index, checksum(bytes));
839                length = length
840                    .checked_add(bytes.len())
841                    .ok_or_else(|| invalid("column page length overflow"))?;
842            }
843            let hash = checksum(&index[section..]);
844            put_u64(&mut index, hash);
845            if length > MAX_PAGE {
846                return Err(invalid("column page exceeds the configured bound"));
847            }
848            self.at = self
849                .at
850                .checked_add(length as u64)
851                .ok_or_else(|| invalid("native file length overflow"))?;
852            pages.push(Span {
853                offset,
854                length: u32::try_from(length).map_err(|_| invalid("page length overflow"))?,
855            });
856            ranges.push(merged_range(stripe.ranges.iter().cloned()));
857        }
858        for (membership, stripe) in memberships.iter_mut().zip(&encoded) {
859            if stripe.codes.iter().all(Option::is_none) {
860                continue;
861            }
862            let lists = stripe
863                .codes
864                .iter()
865                .map(|codes| codes.clone().unwrap_or_default())
866                .collect::<Vec<_>>();
867            let bytes = encode_membership(&merged_codes(lists));
868            let offset = self.at;
869            self.put(&bytes)?;
870            *membership = Some(Page {
871                offset,
872                length: u32::try_from(bytes.len())
873                    .map_err(|_| invalid("membership page length overflow"))?,
874                hash: checksum(&bytes),
875            });
876        }
877        let mut sieves = vec![None; width];
878        for (page, stripe) in sieves.iter_mut().zip(&encoded) {
879            if stripe.sieves.iter().all(Option::is_none) {
880                continue;
881            }
882            let bytes = encode_sieves(stripe.sieves.iter())?;
883            let offset = self.at;
884            self.put(&bytes)?;
885            *page = Some(Page {
886                offset,
887                length: u32::try_from(bytes.len())
888                    .map_err(|_| invalid("sieve page length overflow"))?,
889                hash: checksum(&bytes),
890            });
891        }
892        let offset = self.at;
893        self.put(&index)?;
894        let index = Span {
895            offset,
896            length: u32::try_from(index.len())
897                .map_err(|_| invalid("index page length overflow"))?,
898        };
899        let mut rows = 0_usize;
900        let mut lengths = Vec::with_capacity(parts);
901        let mut span = None;
902        for pending in held.drain(..) {
903            let part = pending.chunk.len();
904            rows = rows.checked_add(part).ok_or_else(|| invalid("row count overflow"))?;
905            lengths.push(u32::try_from(part).map_err(|_| invalid("part row count overflow"))?);
906            span = Some(
907                span.map_or((pending.order, pending.order), |(first, _)| (first, pending.order)),
908            );
909        }
910        self.order.push(span.ok_or_else(|| invalid("a stripe was flushed with no parts"))?);
911        self.table.stripes.push(Stripe {
912            rows,
913            parts: lengths,
914            index,
915            pages,
916            memberships,
917            sieves,
918            zone: Zone::from_ranges(ranges),
919        });
920        // Back where it came from, empty, so the next stripe buffers into the same allocation.
921        self.pending = held;
922        Ok(())
923    }
924
925    /// Finds exact heavy hitters without keeping a hash table for every numeric column while the
926    /// load is live. The pages are already in the target file, so one column at a time uses a
927    /// bounded Misra-Gries candidate table and then recounts only those candidates.
928    fn numeric_frequency(&self, column: usize) -> Result<Option<FrequencySummary>> {
929        let ty = &self.table.fields[column].ty;
930        if !matches!(
931            ty,
932            LogicalType::TinyInt
933                | LogicalType::SmallInt
934                | LogicalType::Integer
935                | LogicalType::BigInt
936                | LogicalType::UTinyInt
937                | LogicalType::USmallInt
938                | LogicalType::UInteger
939                | LogicalType::UBigInt
940                | LogicalType::Date
941                | LogicalType::Timestamp
942        ) {
943            return Ok(None);
944        }
945        let mut candidates: HashMap<FrequencyValue, u32> = HashMap::new();
946        let mut decrements = 0_u64;
947        self.visit_numeric(column, |_, value| {
948            if let Some(count) = candidates.get_mut(&value) {
949                *count = count.saturating_add(1);
950            } else if candidates.len() < FREQUENCY_CANDIDATES {
951                candidates.insert(value, 1);
952            } else {
953                candidates.retain(|_, count| {
954                    *count -= 1;
955                    *count != 0
956                });
957                decrements = decrements.saturating_add(1);
958            }
959        })?;
960        let (exact, ordinals) = if decrements == 0 {
961            (
962                candidates
963                    .into_iter()
964                    .map(|(value, count)| (value, u64::from(count)))
965                    .collect::<HashMap<_, _>>(),
966                Vec::new(),
967            )
968        } else {
969            let mut lower = candidates.values().copied().collect::<Vec<_>>();
970            lower.sort_unstable_by(|left, right| right.cmp(left));
971            if lower.len() < FREQUENCY_BUILD_RANK
972                || u64::from(lower[FREQUENCY_BUILD_RANK - 1]) <= decrements
973            {
974                return Ok(None);
975            }
976            let mut exact =
977                candidates.into_keys().map(|value| (value, 0_u64)).collect::<HashMap<_, _>>();
978            let mut ordinals = Vec::new();
979            let mut exceeded = false;
980            self.visit_numeric(column, |ordinal, value| {
981                if let Some(count) = exact.get_mut(&value) {
982                    *count = count.saturating_add(1);
983                    if !exceeded {
984                        if ordinals.len() < FREQUENCY_ORDINALS {
985                            ordinals.push(ordinal);
986                        } else {
987                            ordinals.clear();
988                            exceeded = true;
989                        }
990                    }
991                }
992            })?;
993            (exact, ordinals)
994        };
995        let mut entries = exact
996            .into_iter()
997            .map(|(value, count)| FrequencyEntry { value, count })
998            .collect::<Vec<_>>();
999        entries.sort_unstable_by(|left, right| {
1000            right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
1001        });
1002        let omitted_max =
1003            entries.get(FREQUENCY_ENTRIES).map_or(decrements, |entry| decrements.max(entry.count));
1004        entries.truncate(FREQUENCY_ENTRIES);
1005        Ok(Some(FrequencySummary { entries, omitted_max, ordinals }))
1006    }
1007
1008    fn visit_numeric(
1009        &self,
1010        column: usize,
1011        mut visit: impl FnMut(u64, FrequencyValue),
1012    ) -> Result<()> {
1013        let ty = &self.table.fields[column].ty;
1014        let mut start = 0_u64;
1015        for stripe in &self.table.stripes {
1016            let spans = read_index(&self.file, stripe, column)?;
1017            let page = stripe.pages[column];
1018            let mut bytes = vec![0; page.length as usize];
1019            read_at(&self.file, page.offset, &mut bytes)?;
1020            for (span, &rows) in spans.iter().zip(&stripe.parts) {
1021                let part = part_bytes(&bytes, *span)?;
1022                if checksum(part) != span.hash {
1023                    return Err(invalid("column page checksum differs while building frequencies"));
1024                }
1025                let rows = rows as usize;
1026                let vector = decode(ty, rows, part, None)?;
1027                // row at a time: frequency construction visits decoded values to update bounded candidates.
1028                for row in 0..rows {
1029                    let value = if vector.is_null_at(row) {
1030                        FrequencyValue::Null
1031                    } else {
1032                        // An unsigned column has no signed reading, and the documented fallback is
1033                        // the value itself. Every unsigned width the format stores fits in the
1034                        // `i128` a candidate is keyed by, so nothing is lost on the way through.
1035                        let widened = match vector.signed_at(row) {
1036                            Some(value) => Some(value),
1037                            None => match vector.value_at(row) {
1038                                Value::UTinyInt(value) => Some(i128::from(value)),
1039                                Value::USmallInt(value) => Some(i128::from(value)),
1040                                Value::UInteger(value) => Some(i128::from(value)),
1041                                Value::UBigInt(value) => Some(i128::from(value)),
1042                                _ => None,
1043                            },
1044                        };
1045                        FrequencyValue::Integer(widened.ok_or_else(|| {
1046                            invalid("numeric frequency page did not contain an integer value")
1047                        })?)
1048                    };
1049                    visit(start.saturating_add(row as u64), value);
1050                }
1051                start = start.saturating_add(rows as u64);
1052            }
1053        }
1054        Ok(())
1055    }
1056
1057    /// Builds independent numeric synopses concurrently after all column pages are committed.
1058    fn numeric_frequencies(&self) -> Result<Vec<Option<FrequencySummary>>> {
1059        let columns = self
1060            .table
1061            .fields
1062            .iter()
1063            .enumerate()
1064            .filter_map(|(column, field)| {
1065                matches!(
1066                    field.ty,
1067                    LogicalType::TinyInt
1068                        | LogicalType::SmallInt
1069                        | LogicalType::Integer
1070                        | LogicalType::BigInt
1071                        | LogicalType::UTinyInt
1072                        | LogicalType::USmallInt
1073                        | LogicalType::UInteger
1074                        | LogicalType::UBigInt
1075                        | LogicalType::Date
1076                        | LogicalType::Timestamp
1077                )
1078                .then_some(column)
1079            })
1080            .collect::<Vec<_>>();
1081        let workers = std::thread::available_parallelism()
1082            .map_or(1, usize::from)
1083            .min(MAX_FREQUENCY_WORKERS)
1084            .min(columns.len());
1085        if workers <= 1 {
1086            let mut frequencies = vec![None; self.table.fields.len()];
1087            for column in columns {
1088                frequencies[column] = self.numeric_frequency(column)?;
1089            }
1090            return Ok(frequencies);
1091        }
1092        let width = columns.len().div_ceil(workers);
1093        let pieces = std::thread::scope(|scope| {
1094            columns
1095                .chunks(width)
1096                .map(|columns| {
1097                    scope.spawn(|| {
1098                        columns
1099                            .iter()
1100                            .map(|&column| Ok((column, self.numeric_frequency(column)?)))
1101                            .collect::<Result<Vec<_>>>()
1102                    })
1103                })
1104                .collect::<Vec<_>>()
1105                .into_iter()
1106                .map(|handle| {
1107                    handle
1108                        .join()
1109                        .map_err(|_| Error::internal("a native frequency worker panicked"))?
1110                })
1111                .collect::<Result<Vec<_>>>()
1112        })?;
1113        let mut frequencies = vec![None; self.table.fields.len()];
1114        for piece in pieces {
1115            for (column, summary) in piece {
1116                frequencies[column] = summary;
1117            }
1118        }
1119        Ok(frequencies)
1120    }
1121
1122    /// Commits the directory and syncs the file before publishing its header slot.
1123    ///
1124    /// # Errors
1125    ///
1126    /// If directory encoding, writing, or syncing fails.
1127    pub fn finish(mut self) -> Result<Table> {
1128        self.flush_pending()?;
1129        let mut stripes = std::mem::take(&mut self.order)
1130            .into_iter()
1131            .zip(std::mem::take(&mut self.table.stripes))
1132            .collect::<Vec<_>>();
1133        stripes.sort_by_key(|(order, _)| order.0);
1134        let mut previous: Option<(u64, u64)> = None;
1135        for ((first, last), _) in &stripes {
1136            if previous.is_some_and(|previous| previous >= *first) {
1137                return Err(invalid("chunks did not arrive in source order"));
1138            }
1139            previous = Some(*last);
1140        }
1141        self.table.stripes = stripes.into_iter().map(|(_, stripe)| stripe).collect();
1142        self.table.frequencies = self.numeric_frequencies()?;
1143        let dictionaries = std::mem::take(&mut self.dictionaries);
1144        let orders = rankings(&dictionaries)?;
1145        for (index, (dictionary, order)) in dictionaries.into_iter().zip(orders).enumerate() {
1146            let Some(dictionary) = dictionary else { continue };
1147            self.table.frequencies[index] = Some(code_frequency(&dictionary));
1148            let encoded = encode_global_dictionary(dictionary, &order)?;
1149            let offset = self.at;
1150            self.put(&encoded.index)?;
1151            self.put(&encoded.ranks)?;
1152            self.put(&encoded.payload)?;
1153            let length = encoded
1154                .index
1155                .len()
1156                .checked_add(encoded.ranks.len())
1157                .and_then(|len| len.checked_add(encoded.payload.len()))
1158                .ok_or_else(|| invalid("dictionary page length overflow"))?;
1159            self.table.dictionaries[index] = Some(Page {
1160                offset,
1161                length: u32::try_from(length)
1162                    .map_err(|_| invalid("dictionary page length overflow"))?,
1163                hash: checksum(&encoded.index),
1164            });
1165        }
1166        let directory = encode_directory(&self.table)?;
1167        if directory.len() > MAX_DIRECTORY {
1168            return Err(invalid("directory exceeds the configured bound"));
1169        }
1170        let offset = self.at;
1171        self.put(&directory)?;
1172        self.file.sync_all().map_err(io)?;
1173        let slot = Slot {
1174            offset,
1175            length: u32::try_from(directory.len())
1176                .map_err(|_| invalid("directory length overflow"))?,
1177            generation: self.generation,
1178            hash: checksum(&directory),
1179        };
1180        // The one write that is not an append, and the last one. It goes back over the slot in the
1181        // header, so it names its offset rather than going through `put`, and `at` does not move.
1182        write_at(&self.file, 16, &slot.bytes())?;
1183        self.file.sync_all().map_err(io)?;
1184        Ok(self.table)
1185    }
1186}
1187
1188/// Reads committed native column pages without holding the table in memory.
1189#[derive(Debug, Clone)]
1190pub struct Reader {
1191    file: Arc<File>,
1192    table: Arc<Table>,
1193    dictionaries: Arc<Vec<OnceLock<Arc<Vector>>>>,
1194    /// The membership sieves of one stripe of one column, by column and then by stripe, read the
1195    /// first time a probe asks about them. A query filters on one or two columns and never looks at
1196    /// the rest, so reading these at open would be the whole index for the sake of a fraction of it.
1197    sieves: Arc<Vec<Vec<SieveSlot>>>,
1198    /// Which stripe and which part of it every part of the table is, by table wide part number.
1199    places: Arc<Vec<Place>>,
1200    cache: Arc<Vec<Mutex<Cached>>>,
1201    /// How many whole stripe pages have been read, which is what the sharing above is judged on. A
1202    /// scan of a column should read each of its stripes once however many workers it has.
1203    pages: Arc<AtomicUsize>,
1204    /// How many index sections have been read. A scan of a column should read each of its stripes
1205    /// once here too, and the test that says so is the only thing keeping it that way.
1206    indexes: Arc<AtomicUsize>,
1207    /// How many stripes of one column the page cache keeps. See [`CACHED_STRIPES_PER_COLUMN`] for
1208    /// what sets it and [`Reader::keep_stripes`] for who raises it.
1209    kept: Arc<AtomicUsize>,
1210    /// The file's size when it was opened, for [`Reader::layout`].
1211    size: u64,
1212    /// The committed directory's size, for [`Reader::layout`].
1213    directory: u64,
1214    /// What opening the file cost, which is a number rather than a claim.
1215    opening: Opening,
1216}
1217
1218/// What [`Reader::open`] read before it returned.
1219///
1220/// `spec/stats/04-in-memory.md` section 4.2 says opening a table reads the header and the directory
1221/// and nothing else, and once that document's statistics are in the file the tempting change is to
1222/// load a column summary or two on the way past, because they are small and the next query will
1223/// want them. A hundred milliseconds of that is a hundred milliseconds nobody asked for, and an
1224/// embedded database is opened by processes that are about to run one trivial query.
1225///
1226/// So the claim gets a number. Both of these are fixed by the schema and the stripe count and are
1227/// independent of how many rows the file holds, and the test that says so is what stops the
1228/// tempting change from landing quietly.
1229#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1230pub struct Opening {
1231    /// How many times the file was read. The header, then each directory slot that looked valid
1232    /// enough to check, so three at the most.
1233    pub reads: u32,
1234    /// How many bytes those reads asked for.
1235    pub bytes: u64,
1236}
1237
1238/// What a reader has read, while it was being opened and since.
1239#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1240pub struct Reads {
1241    /// What opening cost, before any query had been planned.
1242    pub opening: Opening,
1243    /// Whole stripe pages read since.
1244    pub pages: usize,
1245    /// Index sections read since.
1246    pub indexes: usize,
1247}
1248
1249/// Where one table wide part number lands.
1250#[derive(Debug, Clone, Copy)]
1251struct Place {
1252    stripe: u32,
1253    part: u32,
1254    rows: u32,
1255}
1256
1257/// One part's bytes inside one column page.
1258#[derive(Debug, Clone, Copy)]
1259struct PartSpan {
1260    start: usize,
1261    length: usize,
1262    hash: u64,
1263}
1264
1265/// What a reader holds for one stripe of one column.
1266///
1267/// The index is small and is loaded whether the caller wants the whole page or one part of it. The
1268/// page is loaded only by a scan, because a sparse fetch that wants a thousand rows out of sixty
1269/// four thousand would be reading sixty four times what it uses.
1270#[derive(Debug, Clone)]
1271struct CachedColumn {
1272    stripe: usize,
1273    index: Arc<Vec<PartSpan>>,
1274    page: Option<Arc<Vec<u8>>>,
1275}
1276
1277/// One column's stripes a reader holds, and which of them somebody is reading right now.
1278///
1279/// The pages are one slot per stripe of the table rather than a list of the ones being kept, so
1280/// finding a page is an index and not a walk. That matters because the walk happened under the
1281/// lock, once per part per column, and a scan that gives a whole stripe to each of thirty two
1282/// workers keeps enough pages that walking them was the longest thing the lock was held for. The
1283/// slots cost a pointer per stripe per column, which on the ClickBench file is eight kilobytes
1284/// against the forty megabytes of pages they point at. `order` is which of them are filled, oldest
1285/// first, because that is the one thing the slots cannot say by themselves.
1286///
1287/// `loading` is what keeps a scan from reading the same page once per worker. It is a list and not
1288/// a set because it holds at most one stripe per worker on the column and is walked far less often
1289/// than a hash of it would be built.
1290///
1291/// `index` is every index this reader has ever read for the column, one slot per stripe, and it is
1292/// never evicted. An index is a few hundred bytes and a page is a quarter of a megabyte, so the two
1293/// do not belong under the same budget. Riding in the page cache meant a worker that came back to a
1294/// stripe after its page had been evicted read the index again with it, which on the full
1295/// ClickBench file was about thirteen hundred reads out of a hundred and fourteen thousand.
1296#[derive(Debug, Default)]
1297struct Cached {
1298    pages: Vec<Option<Arc<Vec<u8>>>>,
1299    order: VecDeque<usize>,
1300    loading: Vec<usize>,
1301    index: Vec<Option<Arc<Vec<PartSpan>>>>,
1302}
1303
1304/// Stripes of one column a reader keeps the bytes of, when nobody has asked for more.
1305///
1306/// This has to hold at least as many stripes as a column has workers in it at once, or the workers
1307/// evict each other's pages and read them again. Four is what a scan that hands parts out in order
1308/// needs, because then every worker is within a few parts of every other and at most a couple of
1309/// stripes are open at a time. A scan that hands a whole stripe to each worker has one stripe open
1310/// per worker for the length of that stripe, and it says so with [`Reader::keep_stripes`] rather
1311/// than paying for sixteen slots on every table that is read one part at a time.
1312///
1313/// It multiplies by the page size, which is a quarter of a megabyte for a four byte column, and by
1314/// the number of columns a query touches.
1315const CACHED_STRIPES_PER_COLUMN: usize = 4;
1316
1317/// The sieves of one stripe of one column, once somebody has asked for them.
1318type SieveSlot = OnceLock<Arc<Vec<Option<Sieve>>>>;
1319
1320type CrossingCache = OnceLock<Box<[OnceLock<Result<Vec<u8>>>]>>;
1321
1322#[derive(Debug)]
1323struct NativeText {
1324    file: Arc<File>,
1325    offsets: Vec<u32>,
1326    /// How many entries the sorted order has, which is the value count.
1327    ranks: usize,
1328    /// Where the sorted order starts in the file. It is read a block at a time and only when
1329    /// something searches it, so a query that never compares this column against a literal never
1330    /// touches it at all.
1331    rank_at: u64,
1332    rank_hashes: Vec<u64>,
1333    rank_blocks: Vec<OnceLock<Result<Vec<u8>>>>,
1334    payload: u64,
1335    payload_len: usize,
1336    hashes: Vec<u64>,
1337    /// The payload, read and kept an extent at a time. See [`TEXT_PAYLOAD_EXTENT`].
1338    payload_extents: Vec<OnceLock<Result<Vec<u8>>>>,
1339    crossing: Vec<CrossingCache>,
1340}
1341
1342const TEXT_PAYLOAD_BLOCK: usize = 64 * 1024;
1343
1344/// How many blocks are read, allocated and waited on as one.
1345///
1346/// The block is what a checksum covers and it is written into the file, so it cannot move without
1347/// the format moving. What a reader does with it can. A scan of a string column ends up wanting
1348/// every block, because the codes a part holds are spread over the whole dictionary, and reading
1349/// them one at a time made a hundred million row `LIKE` spend more than half its time in the kernel
1350/// rather than in the predicate: a pread and a `Vec` per sixty four kilobytes, over a dictionary
1351/// that is more than a gigabyte, is twenty thousand of each. Under a poor man's profile of ClickBench
1352/// query 21, 58 percent of the samples were in a syscall, 18 percent were in `mprotect` with the
1353/// allocator growing the heap by sixty four kilobytes at a time, and 20 percent were threads parked
1354/// on a `OnceLock` somebody else was filling.
1355///
1356/// Eight blocks is half a megabyte, which is one read, one allocation the allocator takes straight
1357/// from `mmap` rather than off the heap, and one wait. The cost is paid by a query that wants a few
1358/// values rather than a column of them, which now reads half a megabyte to get at sixty four
1359/// kilobytes, and that is what picks the number. Over the queries that go each way, with the scan
1360/// being ClickBench query 21 and the few value read being query 34, which takes its answer out of
1361/// the frequency page and then looks ten codes up: four blocks is 1.318s and 0.075s, eight is 1.168s
1362/// and 0.084s, sixteen is 1.205s and 0.116s. The scan stops improving after eight and the lookup
1363/// keeps getting worse.
1364const TEXT_PAYLOAD_EXTENT: usize = 8;
1365const TEXT_CROSSING_BLOCK: usize = 1024;
1366
1367/// How many entries of a dictionary's sorted order sit in one block that is read and checked as a
1368/// unit.
1369///
1370/// Five hundred and twelve entries is six kilobytes, which is a page and a half. A binary search
1371/// over half a million entries makes nineteen probes, and the first ten land in ten different
1372/// blocks while the last nine land in the one block that holds the answer, so the whole search
1373/// reads about sixty six kilobytes of a two megabyte order. A smaller block would save a little on
1374/// the early probes and cost a checksum list four times as long. A larger one would read more than
1375/// it uses on every probe.
1376const TEXT_RANK_BLOCK: usize = 512;
1377
1378/// Bytes one entry of the sorted order takes: eight for the head and four for the code.
1379const RANK_ENTRY: usize = size_of::<u64>() + size_of::<u32>();
1380
1381impl NativeText {
1382    fn payload_block(&self, block: usize) -> Result<Option<&[u8]>> {
1383        if block >= self.hashes.len() {
1384            return Ok(None);
1385        }
1386        let extent = block / TEXT_PAYLOAD_EXTENT;
1387        let Some(slot) = self.payload_extents.get(extent) else { return Ok(None) };
1388        let bytes = slot
1389            .get_or_init(|| {
1390                let start = extent
1391                    .checked_mul(TEXT_PAYLOAD_EXTENT * TEXT_PAYLOAD_BLOCK)
1392                    .ok_or_else(|| invalid("global dictionary block offset overflow"))?;
1393                let len = (TEXT_PAYLOAD_EXTENT * TEXT_PAYLOAD_BLOCK).min(
1394                    self.payload_len
1395                        .checked_sub(start)
1396                        .ok_or_else(|| invalid("global dictionary block starts past payload"))?,
1397                );
1398                let mut bytes = vec![0; len];
1399                read_at(&self.file, self.payload + start as u64, &mut bytes)?;
1400                // The checksums are per block and stay per block, because they are in the file. The
1401                // extent is only how much of the file one read and one allocation cover.
1402                for (within, piece) in bytes.chunks(TEXT_PAYLOAD_BLOCK).enumerate() {
1403                    if checksum(piece)
1404                        != *self
1405                            .hashes
1406                            .get(extent * TEXT_PAYLOAD_EXTENT + within)
1407                            .ok_or_else(|| invalid("global dictionary block has no checksum"))?
1408                    {
1409                        return Err(invalid("global dictionary payload checksum differs"));
1410                    }
1411                }
1412                Ok(bytes)
1413            })
1414            .as_ref()
1415            .map_err(Clone::clone)?;
1416        let within = (block % TEXT_PAYLOAD_EXTENT) * TEXT_PAYLOAD_BLOCK;
1417        let end = (within + TEXT_PAYLOAD_BLOCK).min(bytes.len());
1418        Ok(bytes.get(within..end))
1419    }
1420
1421    /// The block of the sorted order that holds `rank`, and where in it that rank sits.
1422    ///
1423    /// The block is read from the file and checked against the hash the index carries for it the
1424    /// first time anything asks, and kept after that, the same way a payload block is. A search
1425    /// makes about as many probes as the order has bits, so the whole search reads a handful of
1426    /// these and never the rest.
1427    fn rank_parts(&self, rank: usize) -> Result<(&[u8], usize)> {
1428        let slot = self
1429            .rank_blocks
1430            .get(rank / TEXT_RANK_BLOCK)
1431            .ok_or_else(|| invalid("global dictionary rank is past the order"))?;
1432        let block = slot
1433            .get_or_init(|| {
1434                let first = rank / TEXT_RANK_BLOCK * TEXT_RANK_BLOCK;
1435                let len = TEXT_RANK_BLOCK.min(self.ranks - first) * RANK_ENTRY;
1436                let mut bytes = vec![0; len];
1437                read_at(&self.file, self.rank_at + (first * RANK_ENTRY) as u64, &mut bytes)?;
1438                if checksum(&bytes)
1439                    != *self
1440                        .rank_hashes
1441                        .get(rank / TEXT_RANK_BLOCK)
1442                        .ok_or_else(|| invalid("global dictionary rank block has no checksum"))?
1443                {
1444                    return Err(invalid("global dictionary rank checksum differs"));
1445                }
1446                Ok(bytes)
1447            })
1448            .as_ref()
1449            .map_err(Clone::clone)?;
1450        Ok((block.as_slice(), rank % TEXT_RANK_BLOCK))
1451    }
1452
1453    /// The first eight bytes of the value at `rank`, as the integer a comparison reads.
1454    fn head_at(&self, rank: usize) -> Result<u64> {
1455        let (block, within) = self.rank_parts(rank)?;
1456        let at = within * size_of::<u64>();
1457        let bytes = block
1458            .get(at..at + size_of::<u64>())
1459            .ok_or_else(|| invalid("global dictionary rank block is short of heads"))?;
1460        Ok(u64::from_le_bytes(bytes.try_into().expect("eight bytes")))
1461    }
1462}
1463
1464impl TextSource for NativeText {
1465    fn len(&self) -> usize {
1466        self.offsets.len().saturating_sub(1)
1467    }
1468
1469    fn bytes_at(&self, index: usize) -> Result<Option<&[u8]>> {
1470        let (Some(&start), Some(&end)) = (self.offsets.get(index), self.offsets.get(index + 1))
1471        else {
1472            return Ok(None);
1473        };
1474        if start == end {
1475            return Ok(Some(&[]));
1476        }
1477        let first = start as usize / TEXT_PAYLOAD_BLOCK;
1478        let last = (end as usize - 1) / TEXT_PAYLOAD_BLOCK;
1479        if first == last {
1480            let Some(block) = self.payload_block(first)? else { return Ok(None) };
1481            let within = start as usize % TEXT_PAYLOAD_BLOCK;
1482            return Ok(block.get(within..within + (end - start) as usize));
1483        }
1484        let Some(crossing) = self.crossing.get(index / TEXT_CROSSING_BLOCK) else {
1485            return Ok(None);
1486        };
1487        let block = crossing.get_or_init(|| {
1488            (0..TEXT_CROSSING_BLOCK).map(|_| OnceLock::new()).collect::<Vec<_>>().into_boxed_slice()
1489        });
1490        block[index % TEXT_CROSSING_BLOCK]
1491            .get_or_init(|| {
1492                let mut bytes = Vec::with_capacity((end - start) as usize);
1493                for part in first..=last {
1494                    let source = self
1495                        .payload_block(part)?
1496                        .ok_or_else(|| invalid("global dictionary block is missing"))?;
1497                    let from = if part == first { start as usize % TEXT_PAYLOAD_BLOCK } else { 0 };
1498                    let to = if part == last {
1499                        (end as usize - 1) % TEXT_PAYLOAD_BLOCK + 1
1500                    } else {
1501                        source.len()
1502                    };
1503                    bytes.extend_from_slice(source.get(from..to).ok_or_else(|| {
1504                        invalid("global dictionary value exceeds its payload block")
1505                    })?);
1506                }
1507                Ok(bytes)
1508            })
1509            .as_ref()
1510            .map(|bytes| Some(bytes.as_slice()))
1511            .map_err(Clone::clone)
1512    }
1513
1514    fn bytes_len_at(&self, index: usize) -> Result<Option<usize>> {
1515        let (Some(&start), Some(&end)) = (self.offsets.get(index), self.offsets.get(index + 1))
1516        else {
1517            return Ok(None);
1518        };
1519        Ok(Some((end - start) as usize))
1520    }
1521
1522    fn ranks(&self) -> Option<usize> {
1523        (self.ranks > 0).then_some(self.ranks)
1524    }
1525
1526    fn compare_rank(&self, rank: usize, wanted: &[u8]) -> Result<Ordering> {
1527        // The head settles the probe unless the two values start with the same eight bytes, and
1528        // only then is a value read. On a column of URLs that is the difference between a search
1529        // that touches one block of the payload and a search that touches nineteen of them.
1530        let settled = self.head_at(rank)?.cmp(&head(wanted));
1531        if settled != Ordering::Equal {
1532            return Ok(settled);
1533        }
1534        let code = self.code_at_rank(rank)?;
1535        let bytes = self
1536            .bytes_at(code as usize)?
1537            .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
1538        Ok(bytes.cmp(wanted))
1539    }
1540
1541    fn code_at_rank(&self, rank: usize) -> Result<u32> {
1542        let (block, within) = self.rank_parts(rank)?;
1543        let heads = block.len() / RANK_ENTRY * size_of::<u64>();
1544        let at = heads + within * size_of::<u32>();
1545        let bytes = block
1546            .get(at..at + size_of::<u32>())
1547            .ok_or_else(|| invalid("global dictionary rank block is short of codes"))?;
1548        let code = u32::from_le_bytes(bytes.try_into().expect("four bytes"));
1549        if code as usize >= self.len() {
1550            return Err(invalid("global dictionary order names a code it does not have"));
1551        }
1552        Ok(code)
1553    }
1554
1555    fn footprint(&self) -> usize {
1556        self.offsets.capacity() * size_of::<u32>()
1557            + self.rank_hashes.capacity() * size_of::<u64>()
1558            + self.rank_blocks.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
1559            + self
1560                .rank_blocks
1561                .iter()
1562                .filter_map(OnceLock::get)
1563                .filter_map(|result| result.as_ref().ok())
1564                .map(Vec::capacity)
1565                .sum::<usize>()
1566            + self.payload_extents.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
1567            + self.hashes.capacity() * size_of::<u64>()
1568            + self
1569                .payload_extents
1570                .iter()
1571                .filter_map(OnceLock::get)
1572                .filter_map(|result| result.as_ref().ok())
1573                .map(Vec::capacity)
1574                .sum::<usize>()
1575            + self.crossing.capacity() * size_of::<CrossingCache>()
1576            + self
1577                .crossing
1578                .iter()
1579                .filter_map(OnceLock::get)
1580                .map(|block| {
1581                    block.len() * size_of::<OnceLock<Result<Vec<u8>>>>()
1582                        + block
1583                            .iter()
1584                            .filter_map(OnceLock::get)
1585                            .filter_map(|result| result.as_ref().ok())
1586                            .map(Vec::capacity)
1587                            .sum::<usize>()
1588                })
1589                .sum::<usize>()
1590    }
1591}
1592
1593/// Every table wide part number in order, with the stripe it belongs to.
1594fn places(table: &Table) -> Result<Vec<Place>> {
1595    let mut places = Vec::with_capacity(table.stripes.len().saturating_mul(STRIPE_PARTS));
1596    for (at, stripe) in table.stripes.iter().enumerate() {
1597        let index = u32::try_from(at).map_err(|_| invalid("too many stripes"))?;
1598        for (part, &rows) in stripe.parts.iter().enumerate() {
1599            places.push(Place {
1600                stripe: index,
1601                part: u32::try_from(part).map_err(|_| invalid("too many parts in a stripe"))?,
1602                rows,
1603            });
1604        }
1605    }
1606    Ok(places)
1607}
1608
1609/// Reads one column's section of a stripe's index page.
1610///
1611/// The section carries its own checksum, so a reader that wants one column out of a hundred and
1612/// five preads a few hundred bytes and still knows that what it got is what was written.
1613fn read_index(file: &File, stripe: &Stripe, column: usize) -> Result<Vec<PartSpan>> {
1614    let parts = stripe.parts.len();
1615    let section = index_section(parts)?;
1616    let at = column.checked_mul(section).ok_or_else(|| invalid("index page offset overflow"))?;
1617    let end = at.checked_add(section).ok_or_else(|| invalid("index page offset overflow"))?;
1618    if end > stripe.index.length as usize {
1619        return Err(invalid("index page is shorter than its columns"));
1620    }
1621    let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
1622    let mut bytes = vec![0; section];
1623    let offset = stripe
1624        .index
1625        .offset
1626        .checked_add(at as u64)
1627        .ok_or_else(|| invalid("index page offset overflow"))?;
1628    read_at(file, offset, &mut bytes)?;
1629    let entries = section - size_of::<u64>();
1630    let stored = u64::from_le_bytes(bytes[entries..].try_into().expect("eight bytes"));
1631    if checksum(&bytes[..entries]) != stored {
1632        // With where it was read from, because the two ways this fires look identical from the
1633        // message alone: a file somebody damaged, and a file we wrote to the wrong offset.
1634        return Err(invalid(&format!(
1635            "index page section checksum differs, column {column} of {parts} parts at {offset}, \
1636             wanted {stored:016x} and got {:016x}",
1637            checksum(&bytes[..entries]),
1638        )));
1639    }
1640    let mut spans = Vec::with_capacity(parts);
1641    let mut start = 0_usize;
1642    for part in 0..parts {
1643        let at = part * INDEX_ENTRY;
1644        let length = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes")) as usize;
1645        let hash = u64::from_le_bytes(bytes[at + 4..at + 12].try_into().expect("eight bytes"));
1646        spans.push(PartSpan { start, length, hash });
1647        start = start.checked_add(length).ok_or_else(|| invalid("column page length overflow"))?;
1648    }
1649    if start != page.length as usize {
1650        return Err(invalid("column page length differs from its index"));
1651    }
1652    Ok(spans)
1653}
1654
1655/// One part's bytes out of a whole column page.
1656fn part_bytes(page: &[u8], span: PartSpan) -> Result<&[u8]> {
1657    let end = span.start.checked_add(span.length).ok_or_else(|| invalid("part range overflow"))?;
1658    page.get(span.start..end).ok_or_else(|| invalid("part exceeds its column page"))
1659}
1660
1661/// Puts one stripe of one column in the cache, dropping the stripe that has been there longest.
1662///
1663/// The index goes in its own slot and stays. Only the page is under the budget, and `kept` is how
1664/// many pages that budget is.
1665fn remember(cached: &mut Cached, held: &CachedColumn, kept: usize) {
1666    if let Some(slot) = cached.index.get_mut(held.stripe) {
1667        if slot.is_none() {
1668            *slot = Some(Arc::clone(&held.index));
1669        }
1670    }
1671    let Some(page) = held.page.clone() else { return };
1672    let Some(slot) = cached.pages.get_mut(held.stripe) else { return };
1673    if slot.is_none() {
1674        cached.order.push_back(held.stripe);
1675    }
1676    *slot = Some(page);
1677    while cached.order.len() > kept.max(1) {
1678        let Some(oldest) = cached.order.pop_front() else { break };
1679        if let Some(slot) = cached.pages.get_mut(oldest) {
1680            *slot = None;
1681        }
1682    }
1683}
1684
1685impl Reader {
1686    /// Opens the highest valid directory slot.
1687    ///
1688    /// # Errors
1689    ///
1690    /// If the file has no valid committed directory or a directory pointer is out of bounds.
1691    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
1692        let mut file = File::open(path).map_err(io)?;
1693        let size = file.metadata().map_err(io)?.len();
1694        if size < HEADER {
1695            return Err(invalid("file is shorter than its header"));
1696        }
1697        let mut header = [0; HEADER as usize];
1698        file.read_exact(&mut header).map_err(io)?;
1699        let mut opening = Opening { reads: 1, bytes: HEADER };
1700        let version = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
1701        // The two halves are worth telling apart. A wrong magic is a file that was never ours and
1702        // the answer is to look at the path. A wrong version is our own file from another build,
1703        // and the number this build wants is the only thing that tells the reader whether to
1704        // rebuild the file or to go back to the binary that wrote it.
1705        if &header[..8] != MAGIC {
1706            return Err(invalid("the header does not begin with a rudb native magic"));
1707        }
1708        if version != FORMAT {
1709            return Err(invalid(&format!(
1710                "the file is format {version} and this build reads format {FORMAT}, so it has to \
1711                 be written again"
1712            )));
1713        }
1714        let mut selected = None;
1715        for start in [16, 16 + SLOT_BYTES] {
1716            let slot = Slot::read(&header[start..start + SLOT_BYTES]);
1717            if slot.generation == 0 || slot.length == 0 || slot.length as usize > MAX_DIRECTORY {
1718                continue;
1719            }
1720            let Some(end) = slot.offset.checked_add(u64::from(slot.length)) else { continue };
1721            if slot.offset < HEADER || end > size {
1722                continue;
1723            }
1724            let mut bytes = vec![0; slot.length as usize];
1725            file.seek(SeekFrom::Start(slot.offset)).map_err(io)?;
1726            file.read_exact(&mut bytes).map_err(io)?;
1727            opening.reads += 1;
1728            opening.bytes += u64::from(slot.length);
1729            if checksum(&bytes) == slot.hash
1730                && selected
1731                    .as_ref()
1732                    .is_none_or(|(old, _): &(Slot, Vec<u8>)| old.generation < slot.generation)
1733            {
1734                selected = Some((slot, bytes));
1735            }
1736        }
1737        let (slot, bytes) =
1738            selected.ok_or_else(|| invalid("no committed directory slot is valid"))?;
1739        let table = decode_directory(&bytes, size)?;
1740        let places = places(&table)?;
1741        let dictionaries = (0..table.fields.len()).map(|_| OnceLock::new()).collect();
1742        let stripes = table.stripes.len();
1743        let cache = (0..table.fields.len())
1744            .map(|_| {
1745                Mutex::new(Cached {
1746                    pages: (0..stripes).map(|_| None).collect(),
1747                    index: (0..stripes).map(|_| None).collect(),
1748                    ..Cached::default()
1749                })
1750            })
1751            .collect::<Vec<_>>();
1752        let sieves = (0..table.fields.len())
1753            .map(|_| table.stripes.iter().map(|_| OnceLock::new()).collect())
1754            .collect();
1755        Ok(Self {
1756            file: Arc::new(file),
1757            table: Arc::new(table),
1758            dictionaries: Arc::new(dictionaries),
1759            sieves: Arc::new(sieves),
1760            places: Arc::new(places),
1761            cache: Arc::new(cache),
1762            pages: Arc::new(AtomicUsize::new(0)),
1763            indexes: Arc::new(AtomicUsize::new(0)),
1764            kept: Arc::new(AtomicUsize::new(CACHED_STRIPES_PER_COLUMN)),
1765            size,
1766            directory: u64::from(slot.length),
1767            opening,
1768        })
1769    }
1770
1771    /// What this reader has read so far, and what opening it cost.
1772    ///
1773    /// Public because the claim of `spec/stats/04-in-memory.md` section 4.2 is about this number
1774    /// and a claim nobody can check is a comment. A caller that wants to know whether opening a
1775    /// file touched the data asks here, and gets an answer that does not depend on what the page
1776    /// cache happened to hold.
1777    #[must_use]
1778    pub fn reads(&self) -> Reads {
1779        Reads {
1780            opening: self.opening,
1781            pages: self.pages.load(Atomic::Relaxed),
1782            indexes: self.indexes.load(Atomic::Relaxed),
1783        }
1784    }
1785
1786    /// Where the file's bytes went, from the directory alone.
1787    ///
1788    /// No page is read, so this costs the same on a 45 GB table as on an empty one. See [`Layout`]
1789    /// for what is charged where and for why the three things that are not columns stay separate.
1790    #[must_use]
1791    pub fn layout(&self) -> Layout {
1792        let table = &self.table;
1793        let stripes = table.stripes.as_slice();
1794        let columns = table
1795            .fields
1796            .iter()
1797            .enumerate()
1798            .map(|(at, field)| ColumnLayout {
1799                name: field.name.clone(),
1800                kind: field.ty.to_string(),
1801                pages: sum(stripes.iter().map(|stripe| span_bytes(&stripe.pages, at))),
1802                memberships: sum(stripes.iter().map(|stripe| page_bytes(&stripe.memberships, at))),
1803                sieves: sum(stripes.iter().map(|stripe| page_bytes(&stripe.sieves, at))),
1804                dictionary: page_bytes(&table.dictionaries, at),
1805            })
1806            .collect();
1807        Layout {
1808            file: self.size,
1809            rows: table.rows,
1810            stripes: stripes.len(),
1811            parts: self.places.len(),
1812            columns,
1813            indexes: sum(stripes.iter().map(|stripe| u64::from(stripe.index.length))),
1814            directory: self.directory,
1815            header: HEADER,
1816        }
1817    }
1818
1819    /// How many parts the table has, which is how many chunks a scan of it reads.
1820    #[must_use]
1821    pub fn parts(&self) -> usize {
1822        self.places.len()
1823    }
1824
1825    /// The parts of each stripe, in table wide part numbers.
1826    ///
1827    /// A scan that wants one worker to own the page it reads hands work out in these runs. The
1828    /// stripes are contiguous in part numbering and all but the last hold sixty four parts, but a
1829    /// stripe can be flushed early when rows arrive out of order, so the runs are read off the
1830    /// directory rather than worked out from a constant.
1831    #[must_use]
1832    pub fn stripe_parts(&self) -> Vec<std::ops::Range<usize>> {
1833        let mut runs = Vec::with_capacity(self.table.stripes.len());
1834        let mut start = 0;
1835        for stripe in &self.table.stripes {
1836            let end = start + stripe.parts.len();
1837            runs.push(start..end);
1838            start = end;
1839        }
1840        runs
1841    }
1842
1843    /// Asks the page cache to keep `stripes` stripes of every column instead of the default.
1844    ///
1845    /// This only ever raises the number. A scan that gives each worker a whole stripe has one page
1846    /// per column per worker open at once, and a cache smaller than that is worse than no cache at
1847    /// all: every worker's page is evicted by the others before it has finished its stripe, so it
1848    /// reads a quarter of a megabyte for every part it takes out of it.
1849    pub fn keep_stripes(&self, stripes: usize) {
1850        self.kept.fetch_max(stripes, Atomic::Relaxed);
1851    }
1852
1853    /// Rows in one part, or zero when the part number is past the table.
1854    #[must_use]
1855    pub fn part_rows(&self, at: usize) -> usize {
1856        self.places.get(at).map_or(0, |place| place.rows as usize)
1857    }
1858
1859    /// The committed table directory.
1860    #[must_use]
1861    pub fn table(&self) -> &Table {
1862        &self.table
1863    }
1864
1865    /// Exact leading frequencies when the stored synopsis proves a count-descending prefix.
1866    ///
1867    /// The returned list can be longer than `top`. Keeping the stored tail lets a later TopN apply
1868    /// additional ordering keys without losing a value tied with the requested boundary.
1869    ///
1870    /// # Errors
1871    ///
1872    /// If the column is outside the schema or a stored value does not fit its declared type.
1873    pub fn top_frequencies(&self, column: usize, top: usize) -> Result<Option<Vec<(Value, u64)>>> {
1874        let field = self
1875            .table
1876            .fields
1877            .get(column)
1878            .ok_or_else(|| invalid("frequency column index out of range"))?;
1879        let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
1880            return Ok(None);
1881        };
1882        if top == 0 || summary.entries.len() < top {
1883            return Ok(None);
1884        }
1885        let boundary = summary.entries[top - 1].count;
1886        if boundary <= summary.omitted_max {
1887            return Ok(None);
1888        }
1889        let dictionary =
1890            if field.ty == LogicalType::Varchar { self.dictionary(column)? } else { None };
1891        let mut out = Vec::with_capacity(summary.entries.len());
1892        for entry in &summary.entries {
1893            let value = match entry.value {
1894                FrequencyValue::Null => Value::Null,
1895                FrequencyValue::Integer(value) => match field.ty {
1896                    LogicalType::TinyInt => Value::TinyInt(
1897                        i8::try_from(value)
1898                            .map_err(|_| invalid("frequency TINYINT is out of range"))?,
1899                    ),
1900                    LogicalType::UTinyInt => Value::UTinyInt(
1901                        u8::try_from(value)
1902                            .map_err(|_| invalid("frequency UTINYINT is out of range"))?,
1903                    ),
1904                    LogicalType::USmallInt => Value::USmallInt(
1905                        u16::try_from(value)
1906                            .map_err(|_| invalid("frequency USMALLINT is out of range"))?,
1907                    ),
1908                    LogicalType::UInteger => Value::UInteger(
1909                        u32::try_from(value)
1910                            .map_err(|_| invalid("frequency UINTEGER is out of range"))?,
1911                    ),
1912                    LogicalType::UBigInt => Value::UBigInt(
1913                        u64::try_from(value)
1914                            .map_err(|_| invalid("frequency UBIGINT is out of range"))?,
1915                    ),
1916                    LogicalType::SmallInt => Value::SmallInt(
1917                        i16::try_from(value)
1918                            .map_err(|_| invalid("frequency SMALLINT is out of range"))?,
1919                    ),
1920                    LogicalType::Integer => Value::Integer(
1921                        i32::try_from(value)
1922                            .map_err(|_| invalid("frequency INTEGER is out of range"))?,
1923                    ),
1924                    LogicalType::BigInt => Value::BigInt(
1925                        i64::try_from(value)
1926                            .map_err(|_| invalid("frequency BIGINT is out of range"))?,
1927                    ),
1928                    LogicalType::Date => Value::Date(
1929                        i32::try_from(value)
1930                            .map_err(|_| invalid("frequency DATE is out of range"))?,
1931                    ),
1932                    LogicalType::Timestamp => Value::Timestamp(
1933                        i64::try_from(value)
1934                            .map_err(|_| invalid("frequency TIMESTAMP is out of range"))?,
1935                    ),
1936                    _ => return Err(invalid("integer frequency belongs to another type")),
1937                },
1938                FrequencyValue::Code(code) => dictionary
1939                    .as_ref()
1940                    .ok_or_else(|| invalid("frequency code has no dictionary"))?
1941                    .try_value_at(code as usize)?,
1942            };
1943            out.push((value, entry.count));
1944        }
1945        Ok(Some(out))
1946    }
1947
1948    /// Sparse rows belonging to the bounded numeric frequency candidate set.
1949    ///
1950    /// The list is omitted when collecting it would exceed the fixed storage budget. A composite
1951    /// aggregate may accept a result over these rows only when its requested boundary is strictly
1952    /// greater than `omitted_max`.
1953    ///
1954    /// # Errors
1955    ///
1956    /// If the column is outside the schema.
1957    pub fn frequency_occurrences(&self, column: usize) -> Result<Option<FrequencyOccurrences>> {
1958        self.table
1959            .fields
1960            .get(column)
1961            .ok_or_else(|| invalid("frequency column index out of range"))?;
1962        let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
1963            return Ok(None);
1964        };
1965        if summary.ordinals.is_empty() {
1966            return Ok(None);
1967        }
1968        Ok(Some(FrequencyOccurrences {
1969            omitted_max: summary.omitted_max,
1970            ordinals: summary.ordinals.clone(),
1971        }))
1972    }
1973
1974    /// How many distinct values one column holds, counting a null as no value.
1975    ///
1976    /// A string column of this format is written against one dictionary that covers the whole table.
1977    /// A code is handed out the first time a value is seen and nothing ever removes one, so the
1978    /// number of codes is the number of distinct values exactly rather than an estimate. That makes
1979    /// `COUNT(DISTINCT column)` over a whole table a question the directory already knows the answer
1980    /// to, and the alternative is a hash table with a row per distinct value built from a pass over
1981    /// every row.
1982    ///
1983    /// `None` for a column the file has no dictionary for, which is every column that is not a
1984    /// string, and `None` for a column with a null in it. A sketch would answer the first
1985    /// approximately and SQL asked for the exact number. The second is the placeholder: a null row
1986    /// is written as the code for the empty string, so a nullable column's dictionary may hold an
1987    /// empty string that no row of it actually has, and nothing persisted today tells the two cases
1988    /// apart.
1989    ///
1990    /// # Errors
1991    ///
1992    /// If the column is outside the schema, or the dictionary page does not read.
1993    pub fn distinct_values(&self, column: usize) -> Result<Option<u64>> {
1994        if self.null_count(column)? > 0 {
1995            return Ok(None);
1996        }
1997        Ok(self.dictionary(column)?.map(|dictionary| dictionary.len() as u64))
1998    }
1999
2000    /// How many rows of one column are null, added up over the stripes.
2001    ///
2002    /// Every stripe records this exactly when it is written, because a null count is not a bound
2003    /// that is allowed to be wide the way a minimum and a maximum are: a filter that reads one too
2004    /// many is slow and a `COUNT` that reads one too many is wrong. Adding up a few hundred numbers
2005    /// already in memory is what makes `COUNT(column)` over a whole table free.
2006    ///
2007    /// # Errors
2008    ///
2009    /// If the column is outside the schema.
2010    pub fn null_count(&self, column: usize) -> Result<u64> {
2011        if column >= self.table.fields.len() {
2012            return Err(invalid("null count column index out of range"));
2013        }
2014        let mut nulls = 0_u64;
2015        for stripe in &self.table.stripes {
2016            let range = stripe
2017                .zone
2018                .column(column)
2019                .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2020            nulls = nulls
2021                .checked_add(range.nulls as u64)
2022                .ok_or_else(|| invalid("null count overflow"))?;
2023        }
2024        Ok(nulls)
2025    }
2026
2027    /// The smallest and the largest value of one string column, from the order beside its values.
2028    ///
2029    /// The dictionary holds exactly the values the column holds, so the first and the last of them
2030    /// in sorted order are the column's minimum and maximum. Two reads of a rank block settle what
2031    /// otherwise walks a million rows.
2032    ///
2033    /// `None` when the column is not a string, when the file was written before version 9 and so has
2034    /// no order, when the column has no values at all, or when it has a null in it, which is the
2035    /// placeholder again: the empty string a null is written as would sort ahead of every real
2036    /// value and be reported as the minimum.
2037    ///
2038    /// # Errors
2039    ///
2040    /// If the column is outside the schema, or a rank names a code the dictionary does not have.
2041    pub fn text_extremes(&self, column: usize) -> Result<Option<(Value, Value)>> {
2042        if self.null_count(column)? > 0 {
2043            return Ok(None);
2044        }
2045        let Some(dictionary) = self.dictionary(column)? else { return Ok(None) };
2046        let Some(ranks) = dictionary.ranks() else { return Ok(None) };
2047        if ranks == 0 {
2048            return Ok(None);
2049        }
2050        let low = text_at_rank(&dictionary, 0)?;
2051        let high = text_at_rank(&dictionary, ranks - 1)?;
2052        Ok(Some((low, high)))
2053    }
2054
2055    /// The smallest and the largest value of one column, when every stripe wrote exact ends.
2056    ///
2057    /// A stripe's ends are allowed to be wider than the truth, because a bound that rules out a
2058    /// chunk that could not match is still correct when it rules out nothing. That is what makes
2059    /// them cheap to write for a bit packed or a dictionary column, and it is also what stops them
2060    /// answering a `MIN`. So each stripe says which of the two it wrote, and this answers only when
2061    /// all of them walked their rows.
2062    ///
2063    /// `None` for a column with no ends, for an empty table, and for a column any stripe of which
2064    /// guessed. Nulls need no special case, because the ends skip them the same way `MIN` does.
2065    ///
2066    /// One case is given up on that did not have to be. A stripe merges the ends of its sixty four
2067    /// parts, and a part with no ends at all erases the merged ones, because a part whose rows are
2068    /// not covered by the stripe's ends is a stripe that would skip rows it should keep. A part of
2069    /// nothing but nulls has no rows to cover and so did not need to erase anything, but the merge
2070    /// cannot tell that part from a part whose layout it could not read. So a column with a chunk
2071    /// of nothing but nulls in the middle of it goes and reads the rows. That is slow and right,
2072    /// and the fix is a row count per part rather than anything here.
2073    ///
2074    /// # Errors
2075    ///
2076    /// If the column is outside the schema.
2077    pub fn exact_extremes(&self, column: usize) -> Result<Option<(Bound, Bound)>> {
2078        if column >= self.table.fields.len() {
2079            return Err(invalid("extremes column index out of range"));
2080        }
2081        let mut low: Option<Bound> = None;
2082        let mut high: Option<Bound> = None;
2083        for stripe in &self.table.stripes {
2084            let range = stripe
2085                .zone
2086                .column(column)
2087                .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2088            if !range.exact {
2089                return Ok(None);
2090            }
2091            // A stripe of nothing but nulls has no ends and says nothing about the column's, which
2092            // is why this skips it rather than giving up on the whole column. A stripe that has
2093            // rows and still has no end is a layout whose values this cannot see, and skipping that
2094            // one would answer with an end taken from the other stripes, so it gives up instead.
2095            let (Some(small), Some(large)) = (range.low.as_ref(), range.high.as_ref()) else {
2096                if stripe.rows > range.nulls {
2097                    return Ok(None);
2098                }
2099                continue;
2100            };
2101            low = Some(low.map_or_else(|| small.clone(), |held| held.smaller(small.clone())));
2102            high = Some(high.map_or_else(|| large.clone(), |held| held.larger(large.clone())));
2103        }
2104        Ok(low.zip(high))
2105    }
2106
2107    /// The sum of one integer column and how many rows went into it, when every stripe wrote one.
2108    ///
2109    /// The count beside the sum is the non-null rows, because that is what a `SUM` adds up and what
2110    /// an `AVG` divides by, and a caller that had to work it out from the row count and the null
2111    /// count would be doing the same walk twice.
2112    ///
2113    /// `None` for anything that is not an integer column, for a file written by something that did
2114    /// not record it, and when adding the stripes together would overflow.
2115    ///
2116    /// # Errors
2117    ///
2118    /// If the column is outside the schema.
2119    pub fn exact_sum(&self, column: usize) -> Result<Option<(i128, u64)>> {
2120        if column >= self.table.fields.len() {
2121            return Err(invalid("sum column index out of range"));
2122        }
2123        let mut total = 0_i128;
2124        let mut rows = 0_u64;
2125        for stripe in &self.table.stripes {
2126            let range = stripe
2127                .zone
2128                .column(column)
2129                .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2130            let Some(part) = range.sum else { return Ok(None) };
2131            let Some(sum) = total.checked_add(part) else { return Ok(None) };
2132            total = sum;
2133            rows = rows.saturating_add(stripe.rows as u64 - range.nulls as u64);
2134        }
2135        Ok(Some((total, rows)))
2136    }
2137
2138    fn dictionary(&self, column: usize) -> Result<Option<Arc<Vector>>> {
2139        let Some(page) = self.table.dictionaries[column] else { return Ok(None) };
2140        if let Some(dictionary) = self.dictionaries[column].get() {
2141            return Ok(Some(Arc::clone(dictionary)));
2142        }
2143        let dictionary = Arc::new(open_global_dictionary(
2144            Arc::clone(&self.file),
2145            page,
2146            &self.table.fields[column].ty,
2147        )?);
2148        let _ = self.dictionaries[column].set(Arc::clone(&dictionary));
2149        Ok(Some(self.dictionaries[column].get().map_or(dictionary, Arc::clone)))
2150    }
2151
2152    /// Reads only the named columns from one part.
2153    ///
2154    /// The whole stripe page each column lives in is read and kept, because a scan asks for the
2155    /// parts of a stripe one after another and this is what turns sixty four reads into one.
2156    ///
2157    /// # Errors
2158    ///
2159    /// If a part, column, page, or checksum is invalid.
2160    pub fn read(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2161        self.read_impl(part, columns, true)
2162    }
2163
2164    /// Reads named columns from one part without keeping the stripe page it came out of.
2165    ///
2166    /// This is for sparse row fetches after a selective TopN or filter, which reach a few parts of
2167    /// a stripe rather than all of them. A caller that will read most of a stripe should use
2168    /// [`Self::read`] instead, because this reads and discards the page index every time.
2169    ///
2170    /// # Errors
2171    ///
2172    /// If a part, column, page, or checksum is invalid.
2173    pub fn read_sparse(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2174        self.read_impl(part, columns, false)
2175    }
2176
2177    /// Whether an exact global-code membership index proves that the stripe holding a part cannot
2178    /// contain any of the sorted candidate codes.
2179    ///
2180    /// # Errors
2181    ///
2182    /// If the part, column, index page, checksum, or delta stream is invalid.
2183    pub fn skips_codes(&self, part: usize, column: usize, candidates: &[u32]) -> Result<bool> {
2184        if candidates.is_empty() {
2185            return Ok(true);
2186        }
2187        if candidates.windows(2).any(|pair| pair[0] >= pair[1]) {
2188            return Err(Error::internal("native code candidates are not sorted and unique"));
2189        }
2190        let stripe = self.stripe_of(part)?;
2191        let Some(page) = stripe.memberships.get(column).copied().flatten() else {
2192            return Ok(false);
2193        };
2194        let mut bytes = vec![0; page.length as usize];
2195        read_at(&self.file, page.offset, &mut bytes)?;
2196        if checksum(&bytes) != page.hash {
2197            return Err(invalid("membership page checksum differs"));
2198        }
2199        let codes = decode_membership(&bytes)?;
2200        let mut left = 0;
2201        let mut right = 0;
2202        while left < codes.len() && right < candidates.len() {
2203            match codes[left].cmp(&candidates[right]) {
2204                Ordering::Less => left += 1,
2205                Ordering::Greater => right += 1,
2206                Ordering::Equal => return Ok(false),
2207            }
2208        }
2209        Ok(true)
2210    }
2211
2212    fn stripe_of(&self, part: usize) -> Result<&Stripe> {
2213        let place = self.places.get(part).ok_or_else(|| invalid("part index out of range"))?;
2214        self.table
2215            .stripes
2216            .get(place.stripe as usize)
2217            .ok_or_else(|| invalid("stripe index out of range"))
2218    }
2219
2220    /// The page index of one column of one stripe, and its page when the caller wants all of it.
2221    ///
2222    /// A scan hands parts out in order, so every worker on a column crosses into a new stripe within
2223    /// a few parts of the others and they all want the same page at the same moment. This used to
2224    /// let all of them read it, which cost the scan as many copies of every page as it had workers.
2225    /// On the full ClickBench file a `MIN(EventDate), MAX(EventDate)` moved 3.2 GB off the disk to
2226    /// look at 400 MB of column.
2227    ///
2228    /// A worker that finds the page it wants already being read neither waits for it nor reads it
2229    /// again. It comes back with the index alone, which sends [`Reader::read_impl`] down the path
2230    /// that reads the one part it came for, a few kilobytes against a quarter of a megabyte, and it
2231    /// picks the page up from the cache on its next part. Waiting would be the other way to avoid
2232    /// the duplicate read and it is worse: the pages that matter are the wide string ones, they take
2233    /// milliseconds to copy even warm, and every other worker would be stopped for all of it.
2234    ///
2235    /// The file is never read under the lock.
2236    fn held(&self, at: usize, stripe: &Stripe, column: usize, whole: bool) -> Result<CachedColumn> {
2237        let cache = self.cache.get(column).ok_or_else(|| invalid("column index out of range"))?;
2238        let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2239        let known = cached.index.get(at).and_then(Clone::clone);
2240        let page = cached.pages.get(at).and_then(Clone::clone);
2241        if let Some(index) = known.clone() {
2242            if !whole || page.is_some() {
2243                return Ok(CachedColumn { stripe: at, index, page });
2244            }
2245        }
2246        if cached.loading.contains(&at) {
2247            drop(cached);
2248            // The index is almost always already here, because somebody read this stripe to get
2249            // into the loading list in the first place, so this branch usually costs no read at
2250            // all and the one part read in `read_impl` is all the losing worker pays for.
2251            if let Some(index) = known {
2252                return Ok(CachedColumn { stripe: at, index, page: None });
2253            }
2254            let held = self.page_of(stripe, column, at, false, None)?;
2255            let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2256            remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2257            return Ok(held);
2258        }
2259        cached.loading.push(at);
2260        drop(cached);
2261
2262        let read = self.page_of(stripe, column, at, whole, known);
2263
2264        // The stripe leaves the loading list and its page enters the cache under one lock. Doing
2265        // them separately would leave a moment where another worker sees neither and reads the
2266        // page a second time, which is the whole thing this is here to stop.
2267        let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2268        if let Some(position) = cached.loading.iter().position(|loading| *loading == at) {
2269            cached.loading.remove(position);
2270        }
2271        let held = read?;
2272        remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2273        Ok(held)
2274    }
2275
2276    /// Reads one stripe's index for a column, and its page when the caller wants all of it.
2277    ///
2278    /// `known` is the index when the reader has already read it, which after the first worker
2279    /// through a stripe it always has, because [`remember`] keeps every index for the life of the
2280    /// reader. Without that a scan reads the index again on every part that misses the page cache.
2281    fn page_of(
2282        &self,
2283        stripe: &Stripe,
2284        column: usize,
2285        at: usize,
2286        whole: bool,
2287        known: Option<Arc<Vec<PartSpan>>>,
2288    ) -> Result<CachedColumn> {
2289        let index = match known {
2290            Some(index) => index,
2291            None => {
2292                self.indexes.fetch_add(1, Atomic::Relaxed);
2293                Arc::new(read_index(&self.file, stripe, column)?)
2294            }
2295        };
2296        let page = if whole {
2297            self.pages.fetch_add(1, Atomic::Relaxed);
2298            let span = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2299            let mut bytes = vec![0; span.length as usize];
2300            read_at(&self.file, span.offset, &mut bytes)?;
2301            Some(Arc::new(bytes))
2302        } else {
2303            None
2304        };
2305        Ok(CachedColumn { stripe: at, index, page })
2306    }
2307
2308    fn read_impl(&self, at: usize, columns: &[usize], whole: bool) -> Result<Chunk> {
2309        let place = *self.places.get(at).ok_or_else(|| invalid("part index out of range"))?;
2310        let index = place.stripe as usize;
2311        let stripe =
2312            self.table.stripes.get(index).ok_or_else(|| invalid("stripe index out of range"))?;
2313        let rows = place.rows as usize;
2314        let mut picked = Vec::with_capacity(columns.len());
2315        for &column in columns {
2316            let field = self
2317                .table
2318                .fields
2319                .get(column)
2320                .ok_or_else(|| invalid("column index out of range"))?;
2321            let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2322            let held = self.held(index, stripe, column, whole)?;
2323            let span = *held
2324                .index
2325                .get(place.part as usize)
2326                .ok_or_else(|| invalid("part index out of range"))?;
2327            let owned;
2328            let bytes = match &held.page {
2329                Some(held) => part_bytes(held, span)?,
2330                None => {
2331                    let offset = page
2332                        .offset
2333                        .checked_add(span.start as u64)
2334                        .ok_or_else(|| invalid("part range overflow"))?;
2335                    let mut bytes = vec![0; span.length];
2336                    read_at(&self.file, offset, &mut bytes)?;
2337                    owned = bytes;
2338                    &owned
2339                }
2340            };
2341            if checksum(bytes) != span.hash {
2342                return Err(invalid(&format!(
2343                    "column page checksum differs, column {column} part {} at {}+{} of {} bytes, \
2344                     wanted {:016x} and got {:016x}",
2345                    place.part,
2346                    page.offset,
2347                    span.start,
2348                    span.length,
2349                    span.hash,
2350                    checksum(bytes),
2351                )));
2352            }
2353            let dictionary = self.dictionary(column)?;
2354            picked.push(decode(&field.ty, rows, bytes, dictionary)?);
2355        }
2356        Chunk::with_rows(picked, rows)
2357    }
2358
2359    /// Whether persisted statistics prove that a part cannot match the predicates.
2360    ///
2361    /// Two of them. The bounds are per stripe, so every part of a stripe gets the same answer from
2362    /// those and a scan that skips one part that way skips all sixty four. The sieves are per part
2363    /// and answer equality, which is the test bounds are worst at: a column of identifiers has every
2364    /// stripe covering nearly the whole of its type, so the bounds keep every part of it and the
2365    /// sieve keeps the ones that really hold the value.
2366    ///
2367    /// The bounds go first because they are already in memory and the sieves are a read.
2368    #[must_use]
2369    pub fn skips(&self, part: usize, probes: &[Probe]) -> bool {
2370        let Some(place) = self.places.get(part).copied() else { return false };
2371        let Some(stripe) = self.table.stripes.get(place.stripe as usize) else { return false };
2372        if stripe.zone.skips(probes) {
2373            return true;
2374        }
2375        probes.iter().any(|probe| self.sifted(place, probe))
2376    }
2377
2378    /// Whether the sieve of one part rules out one probe.
2379    ///
2380    /// Only equality. An ordered comparison is what the bounds are for and a sieve says nothing
2381    /// about it, and a read that cannot answer keeps the part, which is the answer a caller with no
2382    /// sieve gets anyway.
2383    fn sifted(&self, place: Place, probe: &Probe) -> bool {
2384        if probe.op != Op::Equal {
2385            return false;
2386        }
2387        match self.stripe_sieves(place.stripe as usize, probe.column) {
2388            Some(sieves) => sieves
2389                .get(place.part as usize)
2390                .and_then(Option::as_ref)
2391                .is_some_and(|sieve| sieve.excludes(&probe.value)),
2392            None => false,
2393        }
2394    }
2395
2396    /// The sieves of one stripe of one column, read once and kept.
2397    ///
2398    /// `None` when the column has no sieves in that stripe, when the page is damaged, and when the
2399    /// bytes are not a page this version can read. A sieve is an index over data that is still there
2400    /// and a caller that cannot read one reads the rows, so this is the one place in the file where
2401    /// a bad checksum is a slow query rather than an error.
2402    fn stripe_sieves(&self, stripe: usize, column: usize) -> Option<&[Option<Sieve>]> {
2403        let slot = self.sieves.get(column)?.get(stripe)?;
2404        if let Some(held) = slot.get() {
2405            return Some(held);
2406        }
2407        let page = self.table.stripes.get(stripe)?.sieves.get(column).copied().flatten()?;
2408        let mut bytes = vec![0; page.length as usize];
2409        read_at(&self.file, page.offset, &mut bytes).ok()?;
2410        if checksum(&bytes) != page.hash {
2411            return None;
2412        }
2413        let sieves = Arc::new(decode_sieves(&bytes).ok()?);
2414        let _ = slot.set(sieves);
2415        slot.get().map(|held| held.as_slice())
2416    }
2417}
2418
2419/// The value sitting at one position of a dictionary's sorted order.
2420fn text_at_rank(dictionary: &Vector, rank: usize) -> Result<Value> {
2421    let code = dictionary.code_at_rank(rank)? as usize;
2422    let text = dictionary
2423        .try_text_at(code)?
2424        .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
2425    Ok(Value::Varchar(text.into()))
2426}
2427
2428/// Writes one span of a file at an offset, without depending on where the cursor is.
2429///
2430/// The writer owns an offset of its own and passes it in here, so that nothing it writes depends on
2431/// a cursor that a read is entitled to move. Both of these can come back short and both loop.
2432#[cfg(unix)]
2433fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
2434    use std::os::unix::fs::FileExt;
2435    while !bytes.is_empty() {
2436        let written = file.write_at(bytes, offset).map_err(io)?;
2437        if written == 0 {
2438            return Err(invalid("a write to the native file wrote nothing"));
2439        }
2440        offset += written as u64;
2441        bytes = &bytes[written..];
2442    }
2443    Ok(())
2444}
2445
2446/// The same write, on the call Windows spells differently.
2447#[cfg(windows)]
2448fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
2449    use std::os::windows::fs::FileExt;
2450    while !bytes.is_empty() {
2451        let written = file.seek_write(bytes, offset).map_err(io)?;
2452        if written == 0 {
2453            return Err(invalid("a write to the native file wrote nothing"));
2454        }
2455        offset += written as u64;
2456        bytes = &bytes[written..];
2457    }
2458    Ok(())
2459}
2460
2461/// Somewhere that is neither, where the cursor is all there is.
2462#[cfg(not(any(unix, windows)))]
2463fn write_at(file: &File, offset: u64, bytes: &[u8]) -> Result<()> {
2464    use std::io::Write;
2465    let mut file = file.try_clone().map_err(io)?;
2466    file.seek(SeekFrom::Start(offset)).map_err(io)?;
2467    file.write_all(bytes).map_err(io)
2468}
2469
2470/// Reads one span of a file at an offset, without moving a cursor anybody else can see.
2471///
2472/// Every reader of a table shares one [`File`] behind an [`Arc`], and a grouped aggregate reads its
2473/// pages from several threads at once, so this has to be positional. Seeking and then reading is
2474/// two calls with a gap in the middle, and in that gap another thread's seek lands and the read
2475/// comes back with somebody else's bytes.
2476///
2477/// Both of these can come back short, so both loop. A read of zero bytes before the span is filled
2478/// means the file stops earlier than the directory said it does.
2479#[cfg(unix)]
2480fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
2481    use std::os::unix::fs::FileExt;
2482    while !bytes.is_empty() {
2483        let read = file.read_at(bytes, offset).map_err(io)?;
2484        if read == 0 {
2485            return Err(invalid("column page ends before its declared length"));
2486        }
2487        offset += read as u64;
2488        bytes = &mut bytes[read..];
2489    }
2490    Ok(())
2491}
2492
2493/// The same read, on the call Windows spells differently.
2494///
2495/// `seek_read` is one `ReadFile` carrying the offset with it, so two of them cannot interleave the
2496/// way a seek and a read can. It does leave the shared cursor somewhere afterwards, which is why
2497/// nothing in this file may read that cursor.
2498#[cfg(windows)]
2499fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
2500    use std::os::windows::fs::FileExt;
2501    while !bytes.is_empty() {
2502        let read = file.seek_read(bytes, offset).map_err(io)?;
2503        if read == 0 {
2504            return Err(invalid("column page ends before its declared length"));
2505        }
2506        offset += read as u64;
2507        bytes = &mut bytes[read..];
2508    }
2509    Ok(())
2510}
2511
2512/// Somewhere that is neither, where the cursor is all there is.
2513///
2514/// This one does race, and there is no way to write it so it does not. Nothing we build for runs
2515/// here, so it exists to keep the crate compiling rather than to be correct under threads.
2516#[cfg(not(any(unix, windows)))]
2517fn read_at(file: &File, offset: u64, bytes: &mut [u8]) -> Result<()> {
2518    let mut file = file.try_clone().map_err(io)?;
2519    file.seek(SeekFrom::Start(offset)).map_err(io)?;
2520    file.read_exact(bytes).map_err(io)
2521}
2522
2523fn type_tag(ty: &LogicalType) -> Result<u8> {
2524    match ty {
2525        LogicalType::SmallInt => Ok(1),
2526        LogicalType::Integer => Ok(2),
2527        LogicalType::BigInt => Ok(3),
2528        LogicalType::Varchar => Ok(4),
2529        LogicalType::Date => Ok(5),
2530        LogicalType::Timestamp => Ok(6),
2531        LogicalType::Boolean => Ok(7),
2532        LogicalType::TinyInt => Ok(8),
2533        LogicalType::UTinyInt => Ok(9),
2534        LogicalType::USmallInt => Ok(10),
2535        LogicalType::UInteger => Ok(11),
2536        LogicalType::UBigInt => Ok(12),
2537        _ => Err(Error::not_implemented(format!("native storage for {ty}"))),
2538    }
2539}
2540
2541fn tag_type(tag: u8) -> Result<LogicalType> {
2542    match tag {
2543        1 => Ok(LogicalType::SmallInt),
2544        2 => Ok(LogicalType::Integer),
2545        3 => Ok(LogicalType::BigInt),
2546        4 => Ok(LogicalType::Varchar),
2547        5 => Ok(LogicalType::Date),
2548        6 => Ok(LogicalType::Timestamp),
2549        7 => Ok(LogicalType::Boolean),
2550        8 => Ok(LogicalType::TinyInt),
2551        9 => Ok(LogicalType::UTinyInt),
2552        10 => Ok(LogicalType::USmallInt),
2553        11 => Ok(LogicalType::UInteger),
2554        12 => Ok(LogicalType::UBigInt),
2555        _ => Err(invalid("column type tag is unknown")),
2556    }
2557}
2558
2559fn put_u16(out: &mut Vec<u8>, value: u16) {
2560    out.extend_from_slice(&value.to_le_bytes());
2561}
2562fn put_u32(out: &mut Vec<u8>, value: u32) {
2563    out.extend_from_slice(&value.to_le_bytes());
2564}
2565fn put_u64(out: &mut Vec<u8>, value: u64) {
2566    out.extend_from_slice(&value.to_le_bytes());
2567}
2568fn put_var_u64(out: &mut Vec<u8>, mut value: u64) {
2569    while value >= 0x80 {
2570        out.push((value as u8 & 0x7f) | 0x80);
2571        value >>= 7;
2572    }
2573    out.push(value as u8);
2574}
2575
2576fn frequency_order(left: FrequencyValue, right: FrequencyValue) -> Ordering {
2577    match (left, right) {
2578        (FrequencyValue::Null, FrequencyValue::Null) => Ordering::Equal,
2579        (FrequencyValue::Null, _) => Ordering::Less,
2580        (_, FrequencyValue::Null) => Ordering::Greater,
2581        (FrequencyValue::Integer(left), FrequencyValue::Integer(right)) => left.cmp(&right),
2582        (FrequencyValue::Code(left), FrequencyValue::Code(right)) => left.cmp(&right),
2583        (FrequencyValue::Integer(_), FrequencyValue::Code(_)) => Ordering::Less,
2584        (FrequencyValue::Code(_), FrequencyValue::Integer(_)) => Ordering::Greater,
2585    }
2586}
2587
2588fn code_frequency(dictionary: &GlobalDictionary) -> FrequencySummary {
2589    let mut entries = dictionary
2590        .counts
2591        .iter()
2592        .enumerate()
2593        .filter(|(_, count)| **count != 0)
2594        .map(|(code, &count)| FrequencyEntry { value: FrequencyValue::Code(code as u32), count })
2595        .collect::<Vec<_>>();
2596    if dictionary.nulls != 0 {
2597        entries.push(FrequencyEntry { value: FrequencyValue::Null, count: dictionary.nulls });
2598    }
2599    entries.sort_unstable_by(|left, right| {
2600        right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
2601    });
2602    let omitted_max = entries.get(FREQUENCY_ENTRIES).map_or(0, |entry| entry.count);
2603    entries.truncate(FREQUENCY_ENTRIES);
2604    FrequencySummary { entries, omitted_max, ordinals: Vec::new() }
2605}
2606
2607fn encode_directory(table: &Table) -> Result<Vec<u8>> {
2608    let mut out = DIRECTORY.to_vec();
2609    let name = table.name.as_bytes();
2610    put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("table name too long"))?);
2611    out.extend_from_slice(name);
2612    put_u16(&mut out, u16::try_from(table.fields.len()).map_err(|_| invalid("too many columns"))?);
2613    for field in &table.fields {
2614        let name = field.name.as_bytes();
2615        put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("column name too long"))?);
2616        out.extend_from_slice(name);
2617        out.push(type_tag(&field.ty)?);
2618        out.push(u8::from(field.not_null));
2619    }
2620    for dictionary in &table.dictionaries {
2621        match dictionary {
2622            None => out.push(0),
2623            Some(page) => {
2624                out.push(1);
2625                put_u64(&mut out, page.offset);
2626                put_u32(&mut out, page.length);
2627                put_u64(&mut out, page.hash);
2628            }
2629        }
2630    }
2631    put_u64(&mut out, u64::try_from(table.rows).map_err(|_| invalid("row count overflow"))?);
2632    put_u32(&mut out, u32::try_from(table.stripes.len()).map_err(|_| invalid("too many stripes"))?);
2633    for stripe in &table.stripes {
2634        put_u32(
2635            &mut out,
2636            u32::try_from(stripe.parts.len()).map_err(|_| invalid("too many parts in a stripe"))?,
2637        );
2638        for &rows in &stripe.parts {
2639            put_u32(&mut out, rows);
2640        }
2641        put_u64(&mut out, stripe.index.offset);
2642        put_u32(&mut out, stripe.index.length);
2643        for page in &stripe.pages {
2644            put_u64(&mut out, page.offset);
2645            put_u32(&mut out, page.length);
2646        }
2647        for (field, membership) in table.fields.iter().zip(&stripe.memberships) {
2648            if field.ty != LogicalType::Varchar {
2649                continue;
2650            }
2651            let page =
2652                membership.ok_or_else(|| invalid("string page has no code membership index"))?;
2653            put_u64(&mut out, page.offset);
2654            put_u32(&mut out, page.length);
2655            put_u64(&mut out, page.hash);
2656        }
2657        for sieve in &stripe.sieves {
2658            match sieve {
2659                None => out.push(0),
2660                Some(page) => {
2661                    out.push(1);
2662                    put_u64(&mut out, page.offset);
2663                    put_u32(&mut out, page.length);
2664                    put_u64(&mut out, page.hash);
2665                }
2666            }
2667        }
2668        for range in stripe.zone.columns() {
2669            put_bound(&mut out, range.low.as_ref())?;
2670            put_bound(&mut out, range.high.as_ref())?;
2671            put_u32(
2672                &mut out,
2673                u32::try_from(range.nulls).map_err(|_| invalid("null count overflow"))?,
2674            );
2675            out.push(u8::from(range.exact));
2676            match range.sum {
2677                None => out.push(0),
2678                Some(total) => {
2679                    out.push(1);
2680                    out.extend_from_slice(&total.to_le_bytes());
2681                }
2682            }
2683        }
2684    }
2685    out.extend_from_slice(FREQUENCIES);
2686    put_u16(
2687        &mut out,
2688        u16::try_from(table.frequencies.len())
2689            .map_err(|_| invalid("too many frequency columns"))?,
2690    );
2691    for summary in &table.frequencies {
2692        let Some(summary) = summary else {
2693            out.push(0);
2694            continue;
2695        };
2696        out.push(1);
2697        put_u64(&mut out, summary.omitted_max);
2698        put_u32(
2699            &mut out,
2700            u32::try_from(summary.entries.len())
2701                .map_err(|_| invalid("too many frequency entries"))?,
2702        );
2703        for entry in &summary.entries {
2704            match entry.value {
2705                FrequencyValue::Null => out.push(0),
2706                FrequencyValue::Integer(value) => {
2707                    out.push(1);
2708                    out.extend_from_slice(&value.to_le_bytes());
2709                }
2710                FrequencyValue::Code(value) => {
2711                    out.push(2);
2712                    put_u32(&mut out, value);
2713                }
2714            }
2715            put_u64(&mut out, entry.count);
2716        }
2717        put_u32(
2718            &mut out,
2719            u32::try_from(summary.ordinals.len())
2720                .map_err(|_| invalid("too many frequency ordinals"))?,
2721        );
2722        let mut previous = 0_u64;
2723        for (at, &ordinal) in summary.ordinals.iter().enumerate() {
2724            let delta = if at == 0 {
2725                ordinal
2726            } else {
2727                ordinal
2728                    .checked_sub(previous)
2729                    .ok_or_else(|| invalid("frequency ordinals are not ordered"))?
2730            };
2731            if at != 0 && delta == 0 {
2732                return Err(invalid("frequency ordinals are not unique"));
2733            }
2734            put_var_u64(&mut out, delta);
2735            previous = ordinal;
2736        }
2737    }
2738    Ok(out)
2739}
2740
2741struct Cursor<'a> {
2742    bytes: &'a [u8],
2743    at: usize,
2744}
2745impl<'a> Cursor<'a> {
2746    fn take(&mut self, len: usize) -> Result<&'a [u8]> {
2747        let end = self.at.checked_add(len).ok_or_else(|| invalid("directory offset overflow"))?;
2748        let bytes =
2749            self.bytes.get(self.at..end).ok_or_else(|| invalid("directory is truncated"))?;
2750        self.at = end;
2751        Ok(bytes)
2752    }
2753    fn u8(&mut self) -> Result<u8> {
2754        Ok(self.take(1)?[0])
2755    }
2756    fn u16(&mut self) -> Result<u16> {
2757        Ok(u16::from_le_bytes(self.take(2)?.try_into().expect("two bytes")))
2758    }
2759    fn u32(&mut self) -> Result<u32> {
2760        Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("four bytes")))
2761    }
2762    fn u64(&mut self) -> Result<u64> {
2763        Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("eight bytes")))
2764    }
2765    fn var_u64(&mut self) -> Result<u64> {
2766        let mut value = 0_u64;
2767        for shift in (0..=63).step_by(7) {
2768            let byte = self.u8()?;
2769            let part = u64::from(byte & 0x7f);
2770            if shift == 63 && part > 1 {
2771                return Err(invalid("frequency ordinal varint overflows"));
2772            }
2773            value |= part << shift;
2774            if byte & 0x80 == 0 {
2775                return Ok(value);
2776            }
2777        }
2778        Err(invalid("frequency ordinal varint is too long"))
2779    }
2780    fn bound(&mut self) -> Result<Option<Bound>> {
2781        Ok(match self.u8()? {
2782            0 => None,
2783            1 => Some(Bound::Int(i128::from_le_bytes(
2784                self.take(16)?.try_into().expect("sixteen bytes"),
2785            ))),
2786            2 => Some(Bound::Real(f64::from_le_bytes(
2787                self.take(8)?.try_into().expect("eight bytes"),
2788            ))),
2789            3 => {
2790                let length = self.u32()? as usize;
2791                Some(Bound::Bytes(self.take(length)?.to_vec()))
2792            }
2793            _ => return Err(invalid("bound tag differs")),
2794        })
2795    }
2796    fn text(&mut self) -> Result<String> {
2797        let len = self.u16()? as usize;
2798        String::from_utf8(self.take(len)?.to_vec()).map_err(|_| invalid("name is not UTF-8"))
2799    }
2800}
2801
2802fn decode_directory(bytes: &[u8], size: u64) -> Result<Table> {
2803    let mut cur = Cursor { bytes, at: 0 };
2804    if cur.take(8)? != DIRECTORY {
2805        return Err(invalid("directory magic differs"));
2806    }
2807    let name = cur.text()?;
2808    let width = cur.u16()? as usize;
2809    let mut fields = Vec::with_capacity(width);
2810    for _ in 0..width {
2811        let name = cur.text()?;
2812        let ty = tag_type(cur.u8()?)?;
2813        let not_null = match cur.u8()? {
2814            0 => false,
2815            1 => true,
2816            _ => return Err(invalid("nullability flag differs")),
2817        };
2818        fields.push(Field { name, ty, not_null });
2819    }
2820    let mut dictionaries = Vec::with_capacity(width);
2821    for _ in 0..width {
2822        dictionaries.push(match cur.u8()? {
2823            0 => None,
2824            1 => {
2825                let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2826                let end = page
2827                    .offset
2828                    .checked_add(u64::from(page.length))
2829                    .ok_or_else(|| invalid("dictionary page offset overflow"))?;
2830                // A global dictionary covers a whole column, not one bounded stripe. Its lazy
2831                // payload is intentionally allowed to grow past `MAX_PAGE`; only ordinary column
2832                // pages are capped there. `Writer::finish` has already bounded this length by the
2833                // on-disk `u32`, and the range check below keeps it inside the file.
2834                if page.offset < HEADER || end > size {
2835                    return Err(invalid("dictionary page range is outside the file"));
2836                }
2837                Some(page)
2838            }
2839            _ => return Err(invalid("dictionary page tag differs")),
2840        });
2841    }
2842    let rows = usize::try_from(cur.u64()?).map_err(|_| invalid("row count does not fit"))?;
2843    let count = cur.u32()? as usize;
2844    let mut stripes = Vec::with_capacity(count);
2845    let mut total = 0_usize;
2846    for _ in 0..count {
2847        let count = cur.u32()? as usize;
2848        if count == 0 || count > STRIPE_PARTS {
2849            return Err(invalid("stripe part count is outside its bound"));
2850        }
2851        let mut parts = Vec::with_capacity(count);
2852        let mut stripe_rows = 0_usize;
2853        for _ in 0..count {
2854            let rows = cur.u32()?;
2855            if rows == 0 {
2856                return Err(invalid("empty part"));
2857            }
2858            parts.push(rows);
2859            stripe_rows = stripe_rows
2860                .checked_add(rows as usize)
2861                .ok_or_else(|| invalid("stripe row count overflow"))?;
2862        }
2863        total =
2864            total.checked_add(stripe_rows).ok_or_else(|| invalid("stripe row count overflow"))?;
2865        let index = Span { offset: cur.u64()?, length: cur.u32()? };
2866        let section = index_section(count)?;
2867        let wanted = section
2868            .checked_mul(width)
2869            .and_then(|bytes| u32::try_from(bytes).ok())
2870            .ok_or_else(|| invalid("index page length overflow"))?;
2871        let end = index
2872            .offset
2873            .checked_add(u64::from(index.length))
2874            .ok_or_else(|| invalid("index page offset overflow"))?;
2875        if index.offset < HEADER || end > size || index.length != wanted {
2876            return Err(invalid("index page range is outside the file"));
2877        }
2878        let mut pages = Vec::with_capacity(width);
2879        for _ in 0..width {
2880            let offset = cur.u64()?;
2881            let length = cur.u32()?;
2882            let end = offset
2883                .checked_add(u64::from(length))
2884                .ok_or_else(|| invalid("page offset overflow"))?;
2885            if offset < HEADER || end > size || length as usize > MAX_PAGE {
2886                return Err(invalid("page range is outside the file"));
2887            }
2888            pages.push(Span { offset, length });
2889        }
2890        let mut memberships = vec![None; width];
2891        for (column, field) in fields.iter().enumerate() {
2892            if field.ty != LogicalType::Varchar {
2893                continue;
2894            }
2895            let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2896            let end = page
2897                .offset
2898                .checked_add(u64::from(page.length))
2899                .ok_or_else(|| invalid("membership page offset overflow"))?;
2900            if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
2901                return Err(invalid("membership page range is outside the file"));
2902            }
2903            memberships[column] = Some(page);
2904        }
2905        let mut sieves = vec![None; width];
2906        for sieve in sieves.iter_mut().take(width) {
2907            match cur.u8()? {
2908                0 => continue,
2909                1 => {}
2910                _ => return Err(invalid("a sieve page has an unknown tag")),
2911            }
2912            let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
2913            let end = page
2914                .offset
2915                .checked_add(u64::from(page.length))
2916                .ok_or_else(|| invalid("sieve page offset overflow"))?;
2917            if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
2918                return Err(invalid("sieve page range is outside the file"));
2919            }
2920            *sieve = Some(page);
2921        }
2922        let mut ranges = Vec::with_capacity(width);
2923        for _ in 0..width {
2924            let low = cur.bound()?;
2925            let high = cur.bound()?;
2926            let nulls = cur.u32()? as usize;
2927            if nulls > stripe_rows {
2928                return Err(invalid("null count exceeds stripe rows"));
2929            }
2930            let exact = cur.u8()? != 0;
2931            let sum = match cur.u8()? {
2932                0 => None,
2933                1 => Some(i128::from_le_bytes(
2934                    cur.take(16)?.try_into().map_err(|_| invalid("a stripe sum is truncated"))?,
2935                )),
2936                _ => return Err(invalid("a stripe sum has an unknown tag")),
2937            };
2938            ranges.push(Range { low, high, nulls, exact, sum });
2939        }
2940        stripes.push(Stripe {
2941            rows: stripe_rows,
2942            parts,
2943            index,
2944            pages,
2945            memberships,
2946            sieves,
2947            zone: Zone::from_ranges(ranges),
2948        });
2949    }
2950    if total != rows {
2951        return Err(invalid("table row count differs from stripes"));
2952    }
2953    let frequencies = if cur.at == bytes.len() {
2954        vec![None; width]
2955    } else {
2956        if cur.take(8)? != FREQUENCIES {
2957            return Err(invalid("directory extension magic differs"));
2958        }
2959        if cur.u16()? as usize != width {
2960            return Err(invalid("frequency column count differs"));
2961        }
2962        let mut frequencies = Vec::with_capacity(width);
2963        for field in &fields {
2964            let summary = match cur.u8()? {
2965                0 => None,
2966                1 => {
2967                    let omitted_max = cur.u64()?;
2968                    let count = cur.u32()? as usize;
2969                    if count > FREQUENCY_ENTRIES {
2970                        return Err(invalid("frequency entry count exceeds its bound"));
2971                    }
2972                    let mut entries = Vec::with_capacity(count);
2973                    // row at a time: directory decoding validates each persisted bounded frequency entry.
2974                    for _ in 0..count {
2975                        let value = match cur.u8()? {
2976                            0 => FrequencyValue::Null,
2977                            1 => FrequencyValue::Integer(i128::from_le_bytes(
2978                                cur.take(16)?.try_into().expect("sixteen bytes"),
2979                            )),
2980                            2 => FrequencyValue::Code(cur.u32()?),
2981                            _ => return Err(invalid("frequency value tag differs")),
2982                        };
2983                        let valid = matches!(
2984                            (&field.ty, value),
2985                            (_, FrequencyValue::Null)
2986                                | (LogicalType::Varchar, FrequencyValue::Code(_))
2987                                | (
2988                                    LogicalType::TinyInt
2989                                        | LogicalType::SmallInt
2990                                        | LogicalType::Integer
2991                                        | LogicalType::BigInt
2992                                        | LogicalType::UTinyInt
2993                                        | LogicalType::USmallInt
2994                                        | LogicalType::UInteger
2995                                        | LogicalType::UBigInt
2996                                        | LogicalType::Date
2997                                        | LogicalType::Timestamp,
2998                                    FrequencyValue::Integer(_),
2999                                )
3000                        );
3001                        if !valid {
3002                            return Err(invalid("frequency value does not match its column"));
3003                        }
3004                        let count = cur.u64()?;
3005                        if count == 0 || count > rows as u64 {
3006                            return Err(invalid("frequency count is outside the table"));
3007                        }
3008                        entries.push(FrequencyEntry { value, count });
3009                    }
3010                    if entries.windows(2).any(|pair| pair[0].count < pair[1].count) {
3011                        return Err(invalid("frequency entries are not descending"));
3012                    }
3013                    let ordinals = {
3014                        let ordinal_count = cur.u32()? as usize;
3015                        if ordinal_count > FREQUENCY_ORDINALS || ordinal_count > rows {
3016                            return Err(invalid("frequency ordinal count exceeds its bound"));
3017                        }
3018                        let mut ordinals = Vec::with_capacity(ordinal_count);
3019                        let mut previous = 0_u64;
3020                        for at in 0..ordinal_count {
3021                            let delta = cur.var_u64()?;
3022                            if at != 0 && delta == 0 {
3023                                return Err(invalid("frequency ordinals are not increasing"));
3024                            }
3025                            let ordinal = if at == 0 {
3026                                delta
3027                            } else {
3028                                previous
3029                                    .checked_add(delta)
3030                                    .ok_or_else(|| invalid("frequency ordinal overflows"))?
3031                            };
3032                            if ordinal >= rows as u64 {
3033                                return Err(invalid("frequency ordinal is outside the table"));
3034                            }
3035                            ordinals.push(ordinal);
3036                            previous = ordinal;
3037                        }
3038                        ordinals
3039                    };
3040                    Some(FrequencySummary { entries, omitted_max, ordinals })
3041                }
3042                _ => return Err(invalid("frequency summary tag differs")),
3043            };
3044            frequencies.push(summary);
3045        }
3046        frequencies
3047    };
3048    if cur.at != bytes.len() {
3049        return Err(invalid("directory has trailing bytes"));
3050    }
3051    Ok(Table { name, fields, stripes, rows, dictionaries, frequencies })
3052}
3053
3054fn put_bound(out: &mut Vec<u8>, bound: Option<&Bound>) -> Result<()> {
3055    match bound {
3056        None => out.push(0),
3057        Some(Bound::Int(value)) => {
3058            out.push(1);
3059            out.extend_from_slice(&value.to_le_bytes());
3060        }
3061        Some(Bound::Real(value)) => {
3062            out.push(2);
3063            out.extend_from_slice(&value.to_le_bytes());
3064        }
3065        Some(Bound::Bytes(value)) => {
3066            out.push(3);
3067            put_u32(out, u32::try_from(value.len()).map_err(|_| invalid("bound length overflow"))?);
3068            out.extend_from_slice(value);
3069        }
3070    }
3071    Ok(())
3072}
3073
3074/// Which cascades are worth trying on a run of dictionary codes.
3075///
3076/// The exhaustive chooser encodes every candidate at every level of a cascade three deep and keeps
3077/// the smallest, which on a part of 1024 codes is around a hundred full encodes to decide something
3078/// three candidates were always going to win. It is the right default for a crate that does not
3079/// know what it is looking at. Here we do know. Codes are counted from zero in the order the values
3080/// were first seen, so a part of them is one value, or a narrow band, or a few long runs, and those
3081/// are constant, frame of reference and run length. Nothing else has ever come first on this data.
3082///
3083/// A dictionary of dictionary codes is the one candidate that can never pay, because the codes are
3084/// already the dictionary, and it is also the most expensive one to try. Below the top level the
3085/// streams are an RLE's run values and run lengths, which are integers in their own right with no
3086/// runs left in them, so only the two flat candidates go down there.
3087///
3088/// This is size given up for time on purpose, and the ablation is this chooser against
3089/// [`chooser::EXHAUSTIVE`] on the same file.
3090#[derive(Debug)]
3091struct Codes;
3092
3093impl chooser::Chooser for Codes {
3094    fn name(&self) -> &'static str {
3095        "codes"
3096    }
3097
3098    fn narrow_strings(
3099        &self,
3100        _values: &[&[u8]],
3101        offered: &[string::Kind],
3102        _depth: u8,
3103    ) -> Vec<string::Kind> {
3104        // Never reached, because nothing here encodes strings through the cascade. The trait asks
3105        // for it and the honest answer to a question we have no opinion on is the whole list.
3106        offered.to_vec()
3107    }
3108
3109    fn narrow_integers(
3110        &self,
3111        _values: &[i64],
3112        offered: &[integer::Kind],
3113        depth: u8,
3114    ) -> Vec<integer::Kind> {
3115        let keep: &[integer::Kind] = if depth == 0 {
3116            &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Rle]
3117        } else {
3118            &[integer::Kind::Constant, integer::Kind::Packed]
3119        };
3120        let narrowed: Vec<integer::Kind> =
3121            offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3122        // The contract is a non empty subset, and a chunk that offers none of the three is a chunk
3123        // this has no opinion about rather than one that cannot be written.
3124        if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3125    }
3126}
3127
3128/// Which cascades are worth trying on a part of plain integers.
3129///
3130/// Wider than [`Codes`] because the values are not codes and carry whatever shape the column has.
3131/// A timestamp column climbs, so delta is the one that matters and is the reason this exists at
3132/// all: three timestamp columns in ClickBench were coming out at exactly eight bytes a row with
3133/// nothing asked of them. A column that is one value with a handful of exceptions is sparse. What
3134/// is still left out is the dictionary, for the same reason as in [`Codes`]: it is the most
3135/// expensive candidate to try and this file already puts the columns that want one through a
3136/// dictionary of their own before they ever reach here.
3137#[derive(Debug)]
3138struct Fixed;
3139
3140impl chooser::Chooser for Fixed {
3141    fn name(&self) -> &'static str {
3142        "fixed"
3143    }
3144
3145    fn narrow_strings(
3146        &self,
3147        _values: &[&[u8]],
3148        offered: &[string::Kind],
3149        _depth: u8,
3150    ) -> Vec<string::Kind> {
3151        offered.to_vec()
3152    }
3153
3154    fn narrow_integers(
3155        &self,
3156        _values: &[i64],
3157        offered: &[integer::Kind],
3158        depth: u8,
3159    ) -> Vec<integer::Kind> {
3160        let keep: &[integer::Kind] = if depth == 0 {
3161            &[
3162                integer::Kind::Constant,
3163                integer::Kind::Packed,
3164                integer::Kind::Delta,
3165                integer::Kind::Rle,
3166                integer::Kind::Sparse,
3167            ]
3168        } else {
3169            &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Delta]
3170        };
3171        let narrowed: Vec<integer::Kind> =
3172            offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3173        if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3174    }
3175}
3176
3177/// Every value of an integer part as an `i64`, or `None` for a part this cannot widen without
3178/// losing one.
3179///
3180/// `UBIGINT` is the only integer type left out, because half its range does not fit and a page that
3181/// silently wrapped would be worse than a page that stays plain. Booleans and strings are not
3182/// integers and have their own ways of being small.
3183fn widened(data: &Data) -> Option<Vec<i64>> {
3184    match data {
3185        Data::Int8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3186        Data::UInt8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3187        Data::Int16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3188        Data::UInt16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3189        Data::Int32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3190        Data::UInt32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3191        Data::Int64(values) => Some(values.to_vec()),
3192        _ => None,
3193    }
3194}
3195
3196/// The same values back in the width the column is declared at.
3197///
3198/// A value that does not fit is a page that disagrees with the directory about what the column is,
3199/// which is a damaged file rather than a caller error, so it is refused rather than truncated.
3200fn narrowed(ty: &LogicalType, values: Vec<i64>) -> Result<Data> {
3201    fn fit<T: TryFrom<i64>>(values: &[i64]) -> Result<Vec<T>> {
3202        values
3203            .iter()
3204            .map(|value| T::try_from(*value).map_err(|_| invalid("page value is not of its type")))
3205            .collect()
3206    }
3207    Ok(match ty {
3208        LogicalType::TinyInt => Data::Int8(fit::<i8>(&values)?.into()),
3209        LogicalType::UTinyInt => Data::UInt8(fit::<u8>(&values)?.into()),
3210        LogicalType::SmallInt => Data::Int16(fit::<i16>(&values)?.into()),
3211        LogicalType::USmallInt => Data::UInt16(fit::<u16>(&values)?.into()),
3212        LogicalType::Integer | LogicalType::Date => Data::Int32(fit::<i32>(&values)?.into()),
3213        LogicalType::UInteger => Data::UInt32(fit::<u32>(&values)?.into()),
3214        LogicalType::BigInt | LogicalType::Timestamp => Data::Int64(values.into()),
3215        _ => return Err(invalid("cascade codec belongs to a page that is not integers")),
3216    })
3217}
3218
3219/// How many bytes a part of this type costs written out plainly, which is what the cascade has to
3220/// beat before it is worth the decode.
3221fn plain_width(ty: &LogicalType) -> Option<usize> {
3222    Some(match ty {
3223        LogicalType::TinyInt | LogicalType::UTinyInt => 1,
3224        LogicalType::SmallInt | LogicalType::USmallInt => 2,
3225        LogicalType::Integer | LogicalType::UInteger | LogicalType::Date => 4,
3226        LogicalType::BigInt | LogicalType::Timestamp => 8,
3227        _ => return None,
3228    })
3229}
3230
3231/// A part's plain integers through the cascade, or `None` when nothing it offers is worth it.
3232///
3233/// What it has to beat is whatever the page would otherwise have cost, which is the bit packed form
3234/// where there is one and the plain width where there is not. Both are cheaper to decode than a
3235/// cascade, so a tie goes to them.
3236fn cascaded(
3237    flat: &Vector,
3238    ty: &LogicalType,
3239    packed: Option<&Packed<'_>>,
3240) -> Result<Option<Vec<u8>>> {
3241    let (Some(width), Some(data)) = (plain_width(ty), flat.data()) else { return Ok(None) };
3242    let Some(values) = widened(data) else { return Ok(None) };
3243    let plain = values.len().saturating_mul(width);
3244    let best = match packed {
3245        // The tag, the base, the word count and the words, which is what the codec 2 branch writes.
3246        Some(packed) => plain.min(21 + size_of_val(packed.words())),
3247        None => plain,
3248    };
3249    let out = integer::encode_with(&values, &Fixed)?;
3250    Ok((out.len() < best).then_some(out))
3251}
3252
3253/// A part's dictionary codes through the integer cascade, or `None` when the cascade did not pay.
3254///
3255/// Until now this stream was a `u32` a row with nothing asked of it, and on ClickBench that was
3256/// 400,185,326 bytes for every one of the 28 varchar columns, the same count for `URL` as for a
3257/// column holding the empty string in nearly every row. Codes are dense integers counted from zero
3258/// and a part holds 1024 of them, which is the shape frame of reference is best at, and a column
3259/// with one value everywhere comes back a constant costing nothing per row rather than four bytes.
3260///
3261/// The result is taken only when it is smaller than the plain form. A cascade is allowed to come
3262/// out larger on a part whose codes are genuinely wide, `URL` has about sixty million distinct
3263/// values, and there is no reason to pay for the decode when it does.
3264fn encoded_codes(codes: &[u32]) -> Result<Option<Vec<u8>>> {
3265    let wide: Vec<i64> = codes.iter().map(|code| i64::from(*code)).collect();
3266    let coded = integer::encode_with(&wide, &Codes)?;
3267    let plain = codes.len().saturating_mul(size_of::<u32>());
3268    Ok((coded.len() < plain).then_some(coded))
3269}
3270
3271fn encode(
3272    vector: &Vector,
3273    global: Option<&mut GlobalDictionary>,
3274) -> Result<(Vec<u8>, Option<Vec<u32>>)> {
3275    let ty = vector.logical_type();
3276    // flatten: the file writer needs a uniform scalar page and does it once per loaded chunk.
3277    let flat = vector.flatten()?;
3278    let mut out = Vec::new();
3279    let mut global_codes = None;
3280    if let Some(global) = global {
3281        let mut codes = Vec::with_capacity(flat.len());
3282        for row in 0..flat.len() {
3283            let text = flat.text_at(row).unwrap_or("");
3284            let code = global.code(text)?;
3285            global.observe(code, flat.is_null_at(row))?;
3286            codes.push(code);
3287        }
3288        global_codes = Some(codes);
3289    }
3290    let membership = global_codes.as_deref().map(unique_codes);
3291    let dictionary = if global_codes.is_none() && ty == &LogicalType::Varchar {
3292        string_dictionary(&flat)?
3293    } else {
3294        None
3295    };
3296    let packed_vector = if dictionary.is_none() && global_codes.is_none() {
3297        Some(flat.bit_packed()?)
3298    } else {
3299        None
3300    };
3301    let packed = packed_vector.as_ref().and_then(Vector::packed_parts);
3302    let coded = match global_codes.as_deref() {
3303        Some(codes) => encoded_codes(codes)?,
3304        None => None,
3305    };
3306    // Only where nothing else has claimed the page, which is the plain integer case. A packed part
3307    // is still on the table because the cascade has to beat it too: the bit pack takes a part only
3308    // when it halves it, so a column that shrinks by a third was coming out whole.
3309    let cascade = if dictionary.is_none() && global_codes.is_none() {
3310        cascaded(&flat, ty, packed.as_ref())?
3311    } else {
3312        None
3313    };
3314    out.push(if coded.is_some() {
3315        4
3316    } else if cascade.is_some() {
3317        5
3318    } else if global_codes.is_some() {
3319        3
3320    } else if dictionary.is_some() {
3321        1
3322    } else if packed.is_some() {
3323        2
3324    } else {
3325        0
3326    });
3327    let nulls = flat.validity();
3328    let flag = match nulls {
3329        Validity::AllValid => 0,
3330        Validity::AllInvalid => 1,
3331        Validity::Mask(_) => 2,
3332    };
3333    out.push(flag);
3334    if flag == 2 {
3335        for group in (0..vector.len()).step_by(8) {
3336            let mut bits = 0_u8;
3337            for bit in 0..8 {
3338                if group + bit < vector.len() && !flat.is_null_at(group + bit) {
3339                    bits |= 1 << bit;
3340                }
3341            }
3342            out.push(bits);
3343        }
3344    }
3345    if let Some(coded) = coded {
3346        out.extend_from_slice(&coded);
3347        return Ok((out, membership));
3348    }
3349    if let Some(cascade) = cascade {
3350        out.extend_from_slice(&cascade);
3351        return Ok((out, membership));
3352    }
3353    if let Some(codes) = global_codes {
3354        for code in codes {
3355            put_u32(&mut out, code);
3356        }
3357        return Ok((out, membership));
3358    }
3359    if let Some(dictionary) = dictionary {
3360        out.extend_from_slice(&dictionary);
3361        return Ok((out, membership));
3362    }
3363    if let Some(packed) = packed {
3364        if packed.offset() != 0 {
3365            return Err(invalid("writer received a sliced packed vector"));
3366        }
3367        out.push(u8::try_from(packed.width()).map_err(|_| invalid("packed width overflow"))?);
3368        out.extend_from_slice(&packed.base().to_le_bytes());
3369        put_u32(
3370            &mut out,
3371            u32::try_from(packed.words().len()).map_err(|_| invalid("too many packed words"))?,
3372        );
3373        for word in packed.words() {
3374            put_u64(&mut out, *word);
3375        }
3376        return Ok((out, membership));
3377    }
3378    let data = flat.data().ok_or_else(|| invalid("scalar column did not flatten"))?;
3379    match (ty, data) {
3380        (LogicalType::TinyInt, Data::Int8(values)) => {
3381            for value in &**values {
3382                out.extend_from_slice(&value.to_le_bytes());
3383            }
3384        }
3385        (LogicalType::UTinyInt, Data::UInt8(values)) => {
3386            for value in &**values {
3387                out.extend_from_slice(&value.to_le_bytes());
3388            }
3389        }
3390        (LogicalType::SmallInt, Data::Int16(values)) => {
3391            for value in &**values {
3392                out.extend_from_slice(&value.to_le_bytes());
3393            }
3394        }
3395        (LogicalType::USmallInt, Data::UInt16(values)) => {
3396            for value in &**values {
3397                out.extend_from_slice(&value.to_le_bytes());
3398            }
3399        }
3400        (LogicalType::UInteger, Data::UInt32(values)) => {
3401            for value in &**values {
3402                out.extend_from_slice(&value.to_le_bytes());
3403            }
3404        }
3405        (LogicalType::UBigInt, Data::UInt64(values)) => {
3406            for value in &**values {
3407                out.extend_from_slice(&value.to_le_bytes());
3408            }
3409        }
3410        (LogicalType::Integer | LogicalType::Date, Data::Int32(values)) => {
3411            for value in &**values {
3412                out.extend_from_slice(&value.to_le_bytes());
3413            }
3414        }
3415        (LogicalType::BigInt | LogicalType::Timestamp, Data::Int64(values)) => {
3416            for value in &**values {
3417                out.extend_from_slice(&value.to_le_bytes());
3418            }
3419        }
3420        (LogicalType::Boolean, Data::Bool(values)) => {
3421            for value in &**values {
3422                out.push(u8::from(*value));
3423            }
3424        }
3425        (LogicalType::Varchar, Data::Varlen(values)) => {
3426            let mut bytes = Vec::new();
3427            put_u32(&mut out, 0);
3428            for row in 0..vector.len() {
3429                let value = values.bytes(row).ok_or_else(|| invalid("string view is invalid"))?;
3430                bytes.extend_from_slice(value);
3431                put_u32(
3432                    &mut out,
3433                    u32::try_from(bytes.len())
3434                        .map_err(|_| invalid("string payload exceeds 4GiB"))?,
3435                );
3436            }
3437            out.extend_from_slice(&bytes);
3438        }
3439        _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
3440    }
3441    Ok((out, membership))
3442}
3443
3444fn put_varint(out: &mut Vec<u8>, mut value: u32) {
3445    while value >= 0x80 {
3446        out.push((value as u8 & 0x7f) | 0x80);
3447        value >>= 7;
3448    }
3449    out.push(value as u8);
3450}
3451
3452/// The distinct codes of one part, which is what a stripe's membership index is merged from.
3453fn unique_codes(codes: &[u32]) -> Vec<u32> {
3454    let mut unique = codes.to_vec();
3455    unique.sort_unstable();
3456    unique.dedup();
3457    unique
3458}
3459
3460/// The union of the sorted distinct codes of every part in a stripe.
3461///
3462/// Pairwise up a tree rather than one long list concatenated and sorted. Both are the same order of
3463/// work on paper and the tree is the one that does not sort what is already in order: sixty four
3464/// sorted lists become one in six passes over the values.
3465fn merged_codes(lists: Vec<Vec<u32>>) -> Vec<u32> {
3466    let mut lists = lists;
3467    while lists.len() > 1 {
3468        let mut next = Vec::with_capacity(lists.len().div_ceil(2));
3469        for pair in lists.chunks(2) {
3470            match pair {
3471                [left, right] => next.push(merged_pair(left, right)),
3472                [only] => next.push(only.clone()),
3473                _ => {}
3474            }
3475        }
3476        lists = next;
3477    }
3478    lists.pop().unwrap_or_default()
3479}
3480
3481fn merged_pair(left: &[u32], right: &[u32]) -> Vec<u32> {
3482    let mut out = Vec::with_capacity(left.len().saturating_add(right.len()));
3483    let mut at = 0;
3484    let mut to = 0;
3485    while at < left.len() && to < right.len() {
3486        match left[at].cmp(&right[to]) {
3487            Ordering::Less => {
3488                out.push(left[at]);
3489                at += 1;
3490            }
3491            Ordering::Greater => {
3492                out.push(right[to]);
3493                to += 1;
3494            }
3495            Ordering::Equal => {
3496                out.push(left[at]);
3497                at += 1;
3498                to += 1;
3499            }
3500        }
3501    }
3502    out.extend_from_slice(&left[at..]);
3503    out.extend_from_slice(&right[to..]);
3504    out
3505}
3506
3507/// The widest bounds and the total null count of a stripe, from the bounds of its parts.
3508///
3509/// A bound that is missing from any part is missing from the stripe, because a missing bound means
3510/// nothing is known and a stripe that holds an unknown cannot claim one.
3511fn merged_range(ranges: impl Iterator<Item = Range>) -> Range {
3512    let mut merged = Range::default();
3513    let mut first = true;
3514    for range in ranges {
3515        merged.nulls = merged.nulls.saturating_add(range.nulls);
3516        // Both of these have to survive every part, so one part that could not say anything makes
3517        // the stripe unable to say it either. A sum is dropped on overflow rather than wrapped,
3518        // which leaves the stripe with exact ends and no total, which is a true thing to say.
3519        merged.sum = match (merged.sum.take(), range.sum) {
3520            (Some(held), Some(next)) if !first => held.checked_add(next),
3521            (_, next) if first => next,
3522            _ => None,
3523        };
3524        merged.exact = if first { range.exact } else { merged.exact && range.exact };
3525        if first {
3526            merged.low = range.low;
3527            merged.high = range.high;
3528            first = false;
3529            continue;
3530        }
3531        merged.low = match (merged.low.take(), range.low) {
3532            (Some(held), Some(next)) => Some(held.smaller(next)),
3533            _ => None,
3534        };
3535        merged.high = match (merged.high.take(), range.high) {
3536            (Some(held), Some(next)) => Some(held.larger(next)),
3537            _ => None,
3538        };
3539    }
3540    merged
3541}
3542
3543/// One stripe's sieves for one column: the part count, a length for each part, then their bytes.
3544///
3545/// One page for the whole stripe rather than one per part, because a part's sieve is a few hundred
3546/// bytes and sixty four of those are sixty four directory entries and sixty four reads for something
3547/// a scan walks straight through. A part with no sieve writes a length of zero and costs four bytes.
3548fn encode_sieves<'a>(sieves: impl Iterator<Item = &'a Option<Sieve>>) -> Result<Vec<u8>> {
3549    let held: Vec<&Option<Sieve>> = sieves.collect();
3550    let mut out = Vec::new();
3551    put_u32(
3552        &mut out,
3553        u32::try_from(held.len()).map_err(|_| invalid("too many parts in a stripe"))?,
3554    );
3555    for sieve in &held {
3556        let length = sieve.as_ref().map_or(0, Sieve::len);
3557        put_u32(&mut out, u32::try_from(length).map_err(|_| invalid("sieve length overflow"))?);
3558    }
3559    // flatten: a part with no sieve wrote a length of zero above and contributes no bytes here.
3560    for sieve in held.into_iter().flatten() {
3561        out.extend_from_slice(&sieve.to_bytes());
3562    }
3563    Ok(out)
3564}
3565
3566/// The sieves one encoded page holds, one entry per part of the stripe.
3567///
3568/// A part whose bytes are not a sieve this version understands comes back as `None`, which is a part
3569/// that gets read. That is how a file written by a later version of the sieve stays readable rather
3570/// than being a corrupt page.
3571fn decode_sieves(bytes: &[u8]) -> Result<Vec<Option<Sieve>>> {
3572    let parts = u32::from_le_bytes(
3573        bytes
3574            .get(..4)
3575            .ok_or_else(|| invalid("sieve page is truncated"))?
3576            .try_into()
3577            .map_err(|_| invalid("sieve page is truncated"))?,
3578    ) as usize;
3579    let mut lengths = Vec::with_capacity(parts);
3580    for part in 0..parts {
3581        let at = 4 + part * 4;
3582        let field = bytes.get(at..at + 4).ok_or_else(|| invalid("sieve page is truncated"))?;
3583        lengths.push(u32::from_le_bytes(
3584            field.try_into().map_err(|_| invalid("sieve page is truncated"))?,
3585        ) as usize);
3586    }
3587    let mut at = 4 + parts * 4;
3588    let mut out = Vec::with_capacity(parts);
3589    for length in lengths {
3590        if length == 0 {
3591            out.push(None);
3592            continue;
3593        }
3594        let end = at.checked_add(length).ok_or_else(|| invalid("sieve page is truncated"))?;
3595        let field = bytes.get(at..end).ok_or_else(|| invalid("sieve page is truncated"))?;
3596        out.push(Sieve::from_bytes(field));
3597        at = end;
3598    }
3599    if at != bytes.len() {
3600        return Err(invalid("sieve page has trailing bytes"));
3601    }
3602    Ok(out)
3603}
3604
3605/// One stripe's membership index: the code count and then the codes as ascending deltas.
3606///
3607/// The codes have to be sorted and distinct already, which is what [`unique_codes`] and
3608/// [`merged_codes`] hand over. Anything else decodes as different codes, so neither of those two is
3609/// a step a caller can skip.
3610fn encode_membership(unique: &[u32]) -> Vec<u8> {
3611    let mut out = Vec::with_capacity(unique.len().saturating_mul(2).saturating_add(5));
3612    put_varint(&mut out, u32::try_from(unique.len()).unwrap_or(u32::MAX));
3613    let mut previous = 0;
3614    for (at, &code) in unique.iter().enumerate() {
3615        put_varint(&mut out, if at == 0 { code } else { code - previous });
3616        previous = code;
3617    }
3618    out
3619}
3620
3621fn take_varint(bytes: &[u8], at: &mut usize) -> Result<u32> {
3622    let mut value = 0_u32;
3623    for shift in (0..35).step_by(7) {
3624        let byte = *bytes.get(*at).ok_or_else(|| invalid("membership varint is truncated"))?;
3625        *at += 1;
3626        let part = u32::from(byte & 0x7f);
3627        if shift == 28 && part > 0x0f {
3628            return Err(invalid("membership varint overflow"));
3629        }
3630        value = value
3631            .checked_add(
3632                part.checked_shl(shift).ok_or_else(|| invalid("membership varint overflow"))?,
3633            )
3634            .ok_or_else(|| invalid("membership varint overflow"))?;
3635        if byte & 0x80 == 0 {
3636            return Ok(value);
3637        }
3638    }
3639    Err(invalid("membership varint is too long"))
3640}
3641
3642fn decode_membership(bytes: &[u8]) -> Result<Vec<u32>> {
3643    let mut at = 0;
3644    let count = take_varint(bytes, &mut at)? as usize;
3645    let mut codes = Vec::with_capacity(count);
3646    let mut previous = 0_u32;
3647    for index in 0..count {
3648        let delta = take_varint(bytes, &mut at)?;
3649        let code = if index == 0 {
3650            delta
3651        } else {
3652            previous.checked_add(delta).ok_or_else(|| invalid("membership code overflow"))?
3653        };
3654        if index > 0 && code <= previous {
3655            return Err(invalid("membership codes are not increasing"));
3656        }
3657        codes.push(code);
3658        previous = code;
3659    }
3660    if at != bytes.len() {
3661        return Err(invalid("membership page has trailing bytes"));
3662    }
3663    Ok(codes)
3664}
3665
3666fn string_dictionary(vector: &Vector) -> Result<Option<Vec<u8>>> {
3667    let mut by_text = HashMap::new();
3668    let mut values = Vec::new();
3669    let mut codes = Vec::with_capacity(vector.len());
3670    let mut plain_bytes = 0_usize;
3671    for row in 0..vector.len() {
3672        let text = vector.text_at(row).unwrap_or("");
3673        plain_bytes = plain_bytes.saturating_add(text.len());
3674        let code = match by_text.get(text) {
3675            Some(&code) => code,
3676            None => {
3677                let code = u32::try_from(values.len())
3678                    .map_err(|_| invalid("too many dictionary values"))?;
3679                by_text.insert(text, code);
3680                values.push(text);
3681                code
3682            }
3683        };
3684        codes.push(code);
3685    }
3686    let dictionary_bytes = values.iter().map(|value| value.len()).sum::<usize>();
3687    let encoded = 8_usize
3688        .saturating_add((values.len() + 1).saturating_mul(4))
3689        .saturating_add(dictionary_bytes)
3690        .saturating_add(codes.len().saturating_mul(4));
3691    let plain = (vector.len() + 1).saturating_mul(4).saturating_add(plain_bytes);
3692    if encoded >= plain {
3693        return Ok(None);
3694    }
3695    let mut out = Vec::with_capacity(encoded);
3696    put_u32(
3697        &mut out,
3698        u32::try_from(values.len()).map_err(|_| invalid("too many dictionary values"))?,
3699    );
3700    put_u32(
3701        &mut out,
3702        u32::try_from(dictionary_bytes).map_err(|_| invalid("dictionary payload exceeds 4GiB"))?,
3703    );
3704    let mut offset = 0_u32;
3705    put_u32(&mut out, offset);
3706    for value in &values {
3707        offset = offset
3708            .checked_add(
3709                u32::try_from(value.len()).map_err(|_| invalid("dictionary value is too long"))?,
3710            )
3711            .ok_or_else(|| invalid("dictionary payload exceeds 4GiB"))?;
3712        put_u32(&mut out, offset);
3713    }
3714    for value in values {
3715        out.extend_from_slice(value.as_bytes());
3716    }
3717    for code in codes {
3718        put_u32(&mut out, code);
3719    }
3720    Ok(Some(out))
3721}
3722
3723struct EncodedDictionary {
3724    index: Vec<u8>,
3725    ranks: Vec<u8>,
3726    payload: Vec<u8>,
3727}
3728
3729/// The first eight bytes of a value as an integer that sorts the way the bytes sort.
3730fn head(bytes: &[u8]) -> u64 {
3731    let mut word = [0; 8];
3732    let take = bytes.len().min(8);
3733    word[..take].copy_from_slice(&bytes[..take]);
3734    u64::from_be_bytes(word)
3735}
3736
3737/// The sorted order of every global dictionary, one entry per column and empty where there is no
3738/// dictionary.
3739///
3740/// One column's sort has nothing to do with another's, and a table like `hits` has fifteen string
3741/// columns, so this runs across threads the way the numeric synopses above do. It is the only part
3742/// of committing a file that is more than bookkeeping, and doing it serially would show up as a
3743/// pause at the end of a load that thirty two threads had been busy with until then.
3744fn rankings(dictionaries: &[Option<GlobalDictionary>]) -> Result<Vec<Vec<(u64, u32)>>> {
3745    let present =
3746        dictionaries.iter().enumerate().filter(|(_, held)| held.is_some()).map(|(at, _)| at);
3747    let present = present.collect::<Vec<_>>();
3748    let mut orders = vec![Vec::new(); dictionaries.len()];
3749    let workers = std::thread::available_parallelism()
3750        .map_or(1, usize::from)
3751        .min(MAX_FREQUENCY_WORKERS)
3752        .min(present.len());
3753    if workers <= 1 {
3754        for at in present {
3755            if let Some(dictionary) = &dictionaries[at] {
3756                orders[at] = dictionary.ranked();
3757            }
3758        }
3759        return Ok(orders);
3760    }
3761    let width = present.len().div_ceil(workers);
3762    let pieces = std::thread::scope(|scope| {
3763        present
3764            .chunks(width)
3765            .map(|columns| {
3766                scope.spawn(|| {
3767                    columns
3768                        .iter()
3769                        .filter_map(|&at| dictionaries[at].as_ref().map(|held| (at, held.ranked())))
3770                        .collect::<Vec<_>>()
3771                })
3772            })
3773            .collect::<Vec<_>>()
3774            .into_iter()
3775            .map(|handle| {
3776                handle.join().map_err(|_| Error::internal("a dictionary sort worker panicked"))
3777            })
3778            .collect::<Result<Vec<_>>>()
3779    })?;
3780    for piece in pieces {
3781        for (at, order) in piece {
3782            orders[at] = order;
3783        }
3784    }
3785    Ok(orders)
3786}
3787
3788fn encode_global_dictionary(
3789    dictionary: GlobalDictionary,
3790    order: &[(u64, u32)],
3791) -> Result<EncodedDictionary> {
3792    let values = dictionary.offsets.len() - 1;
3793    if order.len() != values {
3794        return Err(invalid("global dictionary order does not cover its values"));
3795    }
3796    let payload_len = dictionary.payload.len();
3797    let blocks = payload_len.div_ceil(TEXT_PAYLOAD_BLOCK);
3798    let ranks = encode_ranks(order);
3799    let rank_blocks = values.div_ceil(TEXT_RANK_BLOCK);
3800    let mut index = Vec::with_capacity(12 + (values + 1) * 4 + (blocks + rank_blocks) * 8);
3801    put_u32(
3802        &mut index,
3803        u32::try_from(values).map_err(|_| invalid("global dictionary has too many values"))?,
3804    );
3805    put_u32(&mut index, TEXT_PAYLOAD_BLOCK as u32);
3806    put_u32(
3807        &mut index,
3808        u32::try_from(blocks).map_err(|_| invalid("global dictionary has too many blocks"))?,
3809    );
3810    for offset in dictionary.offsets {
3811        put_u32(&mut index, offset);
3812    }
3813    for block in dictionary.payload.chunks(TEXT_PAYLOAD_BLOCK) {
3814        put_u64(&mut index, checksum(block));
3815    }
3816    for block in ranks.chunks(TEXT_RANK_BLOCK * RANK_ENTRY) {
3817        put_u64(&mut index, checksum(block));
3818    }
3819    Ok(EncodedDictionary { index, ranks, payload: dictionary.payload })
3820}
3821
3822/// The sorted order laid out the way a reader reads it, in blocks of [`TEXT_RANK_BLOCK`] entries.
3823///
3824/// Each block holds its heads first and then its codes, rather than pairing them, because a search
3825/// asks for a head at every probe and for a code about once a search. Keeping the heads together
3826/// means a probe touches eight bytes of a block rather than twelve spread over it, and the last few
3827/// probes of a search, which are the ones that land in the same block, touch the same cache line.
3828fn encode_ranks(order: &[(u64, u32)]) -> Vec<u8> {
3829    let mut out = Vec::with_capacity(order.len() * RANK_ENTRY);
3830    for block in order.chunks(TEXT_RANK_BLOCK) {
3831        for &(head, _) in block {
3832            put_u64(&mut out, head);
3833        }
3834        for &(_, code) in block {
3835            put_u32(&mut out, code);
3836        }
3837    }
3838    out
3839}
3840
3841fn open_global_dictionary(file: Arc<File>, page: Page, ty: &LogicalType) -> Result<Vector> {
3842    if ty != &LogicalType::Varchar {
3843        return Err(invalid("global dictionary belongs to a non-string column"));
3844    }
3845    let mut header = [0; 12];
3846    read_at(&file, page.offset, &mut header)?;
3847    let count = u32::from_le_bytes(header[0..4].try_into().expect("four bytes")) as usize;
3848    let block_size = u32::from_le_bytes(header[4..8].try_into().expect("four bytes")) as usize;
3849    let blocks = u32::from_le_bytes(header[8..12].try_into().expect("four bytes")) as usize;
3850    if block_size != TEXT_PAYLOAD_BLOCK {
3851        return Err(invalid("global dictionary block width differs"));
3852    }
3853    let offset_len = (count + 1)
3854        .checked_mul(4)
3855        .ok_or_else(|| invalid("global dictionary offset count overflow"))?;
3856    // The sorted order is kept out of the index on purpose. The index is read and checksummed in
3857    // full the moment the column is first touched, and the order is two thirds the size of the
3858    // offsets, so putting it there would make every query that reads a string column pay for a
3859    // search that most of them never make.
3860    let ranks = count;
3861    let rank_blocks = ranks.div_ceil(TEXT_RANK_BLOCK);
3862    let rank_len =
3863        ranks.checked_mul(RANK_ENTRY).ok_or_else(|| invalid("global dictionary rank overflow"))?;
3864    let hash_len = blocks
3865        .checked_add(rank_blocks)
3866        .and_then(|count| count.checked_mul(8))
3867        .ok_or_else(|| invalid("global dictionary block count overflow"))?;
3868    let index_len = 12usize
3869        .checked_add(offset_len)
3870        .and_then(|len| len.checked_add(hash_len))
3871        .ok_or_else(|| invalid("global dictionary header overflow"))?;
3872    let body_len = index_len
3873        .checked_add(rank_len)
3874        .ok_or_else(|| invalid("global dictionary header overflow"))?;
3875    if body_len > page.length as usize {
3876        return Err(invalid("global dictionary offset index exceeds its page"));
3877    }
3878    let mut index = vec![0; index_len];
3879    index[..12].copy_from_slice(&header);
3880    read_at(&file, page.offset + 12, &mut index[12..])?;
3881    if checksum(&index) != page.hash {
3882        return Err(invalid("global dictionary index checksum differs"));
3883    }
3884    let offsets = index[12..12 + offset_len]
3885        .chunks_exact(4)
3886        .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
3887        .collect::<Vec<_>>();
3888    let mut hashes = index[12 + offset_len..]
3889        .chunks_exact(8)
3890        .map(|part| u64::from_le_bytes(part.try_into().expect("eight bytes")))
3891        .collect::<Vec<_>>();
3892    let rank_hashes = hashes.split_off(blocks);
3893    let payload_len = page.length as usize - body_len;
3894    if blocks != payload_len.div_ceil(TEXT_PAYLOAD_BLOCK) {
3895        return Err(invalid("global dictionary block count differs from its payload"));
3896    }
3897    if offsets.first() != Some(&0)
3898        || offsets.last().copied().map(|last| last as usize) != Some(payload_len)
3899        || offsets.windows(2).any(|pair| pair[0] > pair[1])
3900    {
3901        return Err(invalid("global dictionary offsets do not bound the payload"));
3902    }
3903    let payload_extents = (0..payload_len.div_ceil(TEXT_PAYLOAD_BLOCK * TEXT_PAYLOAD_EXTENT))
3904        .map(|_| OnceLock::new())
3905        .collect();
3906    let crossing = (0..count.div_ceil(TEXT_CROSSING_BLOCK)).map(|_| OnceLock::new()).collect();
3907    Vector::external_text(
3908        LogicalType::Varchar,
3909        Arc::new(NativeText {
3910            file,
3911            offsets,
3912            ranks,
3913            rank_at: page.offset + index_len as u64,
3914            rank_hashes,
3915            rank_blocks: (0..rank_blocks).map(|_| OnceLock::new()).collect(),
3916            payload: page.offset + body_len as u64,
3917            payload_len,
3918            hashes,
3919            payload_extents,
3920            crossing,
3921        }),
3922    )
3923}
3924
3925fn decode(
3926    ty: &LogicalType,
3927    rows: usize,
3928    bytes: &[u8],
3929    global: Option<Arc<Vector>>,
3930) -> Result<Vector> {
3931    let mut cur = Cursor { bytes, at: 0 };
3932    let codec = cur.u8()?;
3933    let flag = cur.u8()?;
3934    let validity = match flag {
3935        0 => Validity::AllValid,
3936        1 => Validity::AllInvalid,
3937        2 => {
3938            let mask = cur.take(rows.div_ceil(8))?;
3939            Validity::from_iter(rows, |row| mask[row / 8] >> (row % 8) & 1 == 1)
3940        }
3941        _ => return Err(invalid("page validity tag differs")),
3942    };
3943    if codec == 1 {
3944        if ty != &LogicalType::Varchar {
3945            return Err(invalid("dictionary codec belongs to a non-string page"));
3946        }
3947        let count = cur.u32()? as usize;
3948        let payload_len = cur.u32()? as usize;
3949        let offset_bytes = cur.take(
3950            (count + 1)
3951                .checked_mul(4)
3952                .ok_or_else(|| invalid("dictionary offset count overflow"))?,
3953        )?;
3954        let offsets = offset_bytes
3955            .chunks_exact(4)
3956            .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
3957            .collect::<Vec<_>>();
3958        let payload = cur.take(payload_len)?.to_vec();
3959        if offsets.first() != Some(&0)
3960            || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
3961            || offsets.windows(2).any(|pair| pair[0] > pair[1])
3962        {
3963            return Err(invalid("dictionary offsets do not bound the payload"));
3964        }
3965        let mut strings = StringColumn::over(Buffer::from_vec(payload));
3966        for pair in offsets.windows(2) {
3967            strings.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
3968        }
3969        let mut codes = Vec::with_capacity(rows);
3970        for _ in 0..rows {
3971            codes.push(cur.u32()?);
3972        }
3973        if codes.iter().any(|code| *code as usize >= count) {
3974            return Err(invalid("dictionary code is out of range"));
3975        }
3976        if cur.at != bytes.len() {
3977            return Err(invalid("dictionary page has trailing bytes"));
3978        }
3979        let dictionary = Vector::flat(LogicalType::Varchar, Data::Varlen(strings))?;
3980        return Ok(Vector::dictionary(codes, dictionary)?.with_validity(validity));
3981    }
3982    if codec == 3 || codec == 4 {
3983        let dictionary = global.ok_or_else(|| invalid("global code page has no dictionary"))?;
3984        let codes = if codec == 4 {
3985            // The cascade holds the whole tail of the page and says how long it is itself, so the
3986            // check that nothing is left over is the one the decoder already makes.
3987            let wide = integer::decode(&bytes[cur.at..])?;
3988            if wide.len() != rows {
3989                return Err(invalid("encoded code page holds the wrong number of rows"));
3990            }
3991            wide.into_iter()
3992                .map(|code| u32::try_from(code).map_err(|_| invalid("code is not a code")))
3993                .collect::<Result<Vec<u32>>>()?
3994        } else {
3995            let mut codes = Vec::with_capacity(rows);
3996            for _ in 0..rows {
3997                codes.push(cur.u32()?);
3998            }
3999            if cur.at != bytes.len() {
4000                return Err(invalid("global code page has trailing bytes"));
4001            }
4002            codes
4003        };
4004        let highest = codes.iter().copied().max();
4005        return Ok(Vector::stable_dictionary_validated(codes, dictionary, highest)?
4006            .with_validity(validity));
4007    }
4008    if codec == 5 {
4009        // The cascade holds the whole tail of the page and says how long it is itself.
4010        let values = integer::decode(&bytes[cur.at..])?;
4011        if values.len() != rows {
4012            return Err(invalid("cascade page holds the wrong number of rows"));
4013        }
4014        let data = narrowed(ty, values)?;
4015        return Ok(Vector::flat(ty.clone(), data)?.with_validity(validity));
4016    }
4017    if codec == 2 {
4018        let width = u32::from(cur.u8()?);
4019        let base = i128::from_le_bytes(cur.take(16)?.try_into().expect("sixteen bytes"));
4020        let count = cur.u32()? as usize;
4021        let mut words = Vec::with_capacity(count);
4022        for _ in 0..count {
4023            words.push(cur.u64()?);
4024        }
4025        if cur.at != bytes.len() {
4026            return Err(invalid("packed page has trailing bytes"));
4027        }
4028        return Ok(Vector::packed(ty.clone(), words, width, base, rows)?.with_validity(validity));
4029    }
4030    if codec != 0 {
4031        return Err(invalid("page codec is unknown"));
4032    }
4033    let data = match ty {
4034        LogicalType::TinyInt => {
4035            let values = cur.take(rows)?;
4036            Data::Int8(values.iter().map(|item| *item as i8).collect::<Vec<_>>().into())
4037        }
4038        LogicalType::UTinyInt => Data::UInt8(cur.take(rows)?.to_vec().into()),
4039        LogicalType::SmallInt => {
4040            let values =
4041                cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
4042            Data::Int16(
4043                values
4044                    .chunks_exact(2)
4045                    .map(|item| i16::from_le_bytes(item.try_into().expect("two bytes")))
4046                    .collect::<Vec<_>>()
4047                    .into(),
4048            )
4049        }
4050        LogicalType::USmallInt => {
4051            let values =
4052                cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
4053            Data::UInt16(
4054                values
4055                    .chunks_exact(2)
4056                    .map(|item| u16::from_le_bytes(item.try_into().expect("two bytes")))
4057                    .collect::<Vec<_>>()
4058                    .into(),
4059            )
4060        }
4061        LogicalType::UInteger => {
4062            let values =
4063                cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
4064            Data::UInt32(
4065                values
4066                    .chunks_exact(4)
4067                    .map(|item| u32::from_le_bytes(item.try_into().expect("four bytes")))
4068                    .collect::<Vec<_>>()
4069                    .into(),
4070            )
4071        }
4072        LogicalType::UBigInt => {
4073            let values =
4074                cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
4075            Data::UInt64(
4076                values
4077                    .chunks_exact(8)
4078                    .map(|item| u64::from_le_bytes(item.try_into().expect("eight bytes")))
4079                    .collect::<Vec<_>>()
4080                    .into(),
4081            )
4082        }
4083        LogicalType::Integer | LogicalType::Date => {
4084            let values =
4085                cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
4086            Data::Int32(
4087                values
4088                    .chunks_exact(4)
4089                    .map(|item| i32::from_le_bytes(item.try_into().expect("four bytes")))
4090                    .collect::<Vec<_>>()
4091                    .into(),
4092            )
4093        }
4094        LogicalType::BigInt | LogicalType::Timestamp => {
4095            let values =
4096                cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
4097            Data::Int64(
4098                values
4099                    .chunks_exact(8)
4100                    .map(|item| i64::from_le_bytes(item.try_into().expect("eight bytes")))
4101                    .collect::<Vec<_>>()
4102                    .into(),
4103            )
4104        }
4105        LogicalType::Boolean => {
4106            let values = cur.take(rows)?;
4107            if values.iter().any(|value| *value > 1) {
4108                return Err(invalid("boolean page has another value"));
4109            }
4110            Data::Bool(values.iter().map(|value| *value == 1).collect::<Vec<_>>().into())
4111        }
4112        LogicalType::Varchar => {
4113            let offset_bytes = cur
4114                .take((rows + 1).checked_mul(4).ok_or_else(|| invalid("offset count overflow"))?)?;
4115            let offsets = offset_bytes
4116                .chunks_exact(4)
4117                .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
4118                .collect::<Vec<_>>();
4119            let payload = cur.take(bytes.len() - cur.at)?.to_vec();
4120            if offsets.first() != Some(&0)
4121                || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
4122                || offsets.windows(2).any(|pair| pair[0] > pair[1])
4123            {
4124                return Err(invalid("string offsets do not bound the payload"));
4125            }
4126            let mut values = StringColumn::over(Buffer::from_vec(payload));
4127            for pair in offsets.windows(2) {
4128                values.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
4129            }
4130            Data::Varlen(values)
4131        }
4132        _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
4133    };
4134    if cur.at != bytes.len() {
4135        return Err(invalid("page has trailing bytes"));
4136    }
4137    Ok(Vector::flat(ty.clone(), data)?.with_validity(validity))
4138}
4139
4140#[cfg(test)]
4141mod tests {
4142    use std::fs;
4143    use std::io::{Seek, SeekFrom, Write};
4144    use std::path::PathBuf;
4145    use std::time::{SystemTime, UNIX_EPOCH};
4146
4147    use rudb_common::Value;
4148    use rudb_common::bounds::Op;
4149
4150    use super::*;
4151
4152    #[test]
4153    fn checksum_matches_fixed_vectors() {
4154        assert_eq!(checksum(b""), 0xef46_db37_51d8_e999);
4155        assert_eq!(checksum(b"a"), 0xd24e_c4f1_a98c_6e5b);
4156        assert_eq!(checksum(b"abc"), 0x44bc_2cf5_ad77_0999);
4157    }
4158
4159    fn path(label: &str) -> PathBuf {
4160        let stamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("time advances").as_nanos();
4161        std::env::temp_dir().join(format!("rudb-native-{label}-{}-{stamp}.rdb", std::process::id()))
4162    }
4163
4164    /// A read names the offset it wants, so a cursor somebody else moved cannot reach it.
4165    #[test]
4166    fn a_read_at_an_offset_ignores_where_another_thread_left_the_cursor() {
4167        const SPANS: usize = 64;
4168        const SPAN: usize = 512;
4169        let path = path("positional");
4170        let content: Vec<u8> =
4171            (0..SPANS).flat_map(|span| std::iter::repeat_n(span as u8, SPAN)).collect();
4172        fs::write(&path, &content).expect("the file is written");
4173        let file = Arc::new(File::open(&path).expect("the file opens"));
4174        std::thread::scope(|scope| {
4175            for _ in 0..8 {
4176                let file = Arc::clone(&file);
4177                scope.spawn(move || {
4178                    for _ in 0..64 {
4179                        for span in 0..SPANS {
4180                            let mut bytes = [0_u8; SPAN];
4181                            read_at(&file, (span * SPAN) as u64, &mut bytes)
4182                                .expect("the span reads");
4183                            assert!(
4184                                bytes.iter().all(|byte| *byte == span as u8),
4185                                "span {span} came back as {}",
4186                                bytes[0],
4187                            );
4188                        }
4189                    }
4190                });
4191            }
4192        });
4193        let mut past = [0_u8; SPAN];
4194        let end = (SPANS * SPAN) as u64;
4195        let error = read_at(&file, end, &mut past).expect_err("a read past the end is refused");
4196        assert!(error.message().contains("ends before its declared length"), "{error}");
4197        drop(file);
4198        let _ = fs::remove_file(&path);
4199    }
4200
4201    /// The writer records where it put a page and puts it there, whatever the cursor is doing.
4202    ///
4203    /// The cursor is moved between the steps that record an offset, which is what reading the pages
4204    /// back to build the frequencies does on a platform with no `pread`. Without the fix the
4205    /// directory lands on top of a page and the file fails to reopen.
4206    #[test]
4207    fn a_writer_puts_a_page_where_it_said_it_did_wherever_the_cursor_has_got_to() {
4208        let path = path("cursor");
4209        let mut writer = Writer::create(
4210            &path,
4211            "items",
4212            vec![
4213                Field::required("id", LogicalType::Integer),
4214                Field::new("text", LogicalType::Varchar),
4215            ],
4216        )
4217        .expect("new file");
4218        writer.append(&sample()).expect("first part");
4219        writer.file.seek(SeekFrom::Start(0)).expect("the cursor goes back to the header");
4220        writer.append(&sample()).expect("second part");
4221        writer.file.seek(SeekFrom::Start(1)).expect("and somewhere useless again");
4222        writer.finish().expect("commit");
4223        let reader = Reader::open(&path).expect("reopen from disk");
4224        assert_eq!(reader.table().rows(), 6);
4225        let ids = reader.read(0, &[0]).expect("the integer page reads back");
4226        assert_eq!(ids.value_at(0, 0), Value::Integer(4));
4227        assert_eq!(ids.value_at(2, 0), Value::Integer(-2));
4228        let text = reader.read(1, &[1]).expect("the text page reads back");
4229        assert_eq!(text.value_at(1, 0), Value::Null);
4230        assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4231        // Nothing the directory points at may run past the end of the file, which is the shape the
4232        // failure took: a page recorded at an offset the directory had already been written over.
4233        let end = reader.table().stripes().iter().flat_map(|stripe| {
4234            stripe
4235                .pages
4236                .iter()
4237                .map(|page| page.offset + u64::from(page.length))
4238                .chain(std::iter::once(stripe.index.offset + u64::from(stripe.index.length)))
4239        });
4240        let last = end.fold(HEADER, u64::max);
4241        let directory = fs::metadata(&path).expect("the file is there").len();
4242        assert!(last <= directory, "a page runs to {last} in a file of {directory} bytes");
4243        fs::remove_file(path).expect("remove scratch file");
4244    }
4245
4246    fn sample() -> Chunk {
4247        Chunk::new(vec![
4248            Vector::from_values(
4249                LogicalType::Integer,
4250                &[Value::Integer(4), Value::Integer(9), Value::Integer(-2)],
4251            )
4252            .expect("integers"),
4253            Vector::from_values(
4254                LogicalType::Varchar,
4255                &[
4256                    Value::Varchar("alpha".into()),
4257                    Value::Null,
4258                    Value::Varchar("long text after a slash".into()),
4259                ],
4260            )
4261            .expect("strings"),
4262        ])
4263        .expect("matching rows")
4264    }
4265
4266    fn sample_ids() -> Chunk {
4267        Chunk::new(vec![
4268            Vector::flat(LogicalType::Integer, Data::Int32(vec![7, 8, 9].into()))
4269                .expect("integers"),
4270        ])
4271        .expect("one column")
4272    }
4273
4274    #[test]
4275    fn committed_file_reopens_and_reads_only_requested_columns() {
4276        let path = path("reopen");
4277        let mut writer = Writer::create(
4278            &path,
4279            "items",
4280            vec![
4281                Field::required("id", LogicalType::Integer),
4282                Field::new("text", LogicalType::Varchar),
4283            ],
4284        )
4285        .expect("new file");
4286        writer.append(&sample()).expect("first part");
4287        writer.append(&sample()).expect("second part");
4288        writer.finish().expect("commit");
4289        let reader = Reader::open(&path).expect("reopen from disk");
4290        assert_eq!(reader.table().rows(), 6);
4291        // Two appends below the stripe bound are two parts of one stripe, which is the whole point
4292        // of the split: the directory describes the stripe and the scan still reads a part.
4293        assert_eq!(reader.table().stripes().len(), 1);
4294        assert_eq!(reader.parts(), 2);
4295        assert_eq!(reader.part_rows(0), 3);
4296        assert_eq!(reader.part_rows(1), 3);
4297        let text = reader.read(1, &[1]).expect("only text page");
4298        assert_eq!(text.width(), 1);
4299        assert_eq!(text.value_at(1, 0), Value::Null);
4300        assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4301        let sparse = reader.read_sparse(1, &[1]).expect("one part without its whole page");
4302        assert_eq!(sparse.width(), 1);
4303        assert_eq!(sparse.value_at(1, 0), Value::Null);
4304        assert_eq!(sparse.value_at(2, 0), Value::Varchar("long text after a slash".into()));
4305        assert!(!reader.skips_codes(0, 1, &[0]).expect("alpha is in the stripe"));
4306        assert!(!reader.skips_codes(0, 1, &[2]).expect("long text is in the stripe"));
4307        assert!(reader.skips_codes(0, 1, &[3]).expect("unknown code is absent"));
4308        let count = reader.read(0, &[]).expect("no page is needed for count");
4309        assert_eq!(count.len(), 3);
4310        assert!(reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }]));
4311        assert!(!reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(0) }]));
4312        let integers = reader.top_frequencies(0, 1).expect("valid integer synopsis").expect("kept");
4313        assert_eq!(
4314            integers,
4315            vec![(Value::Integer(-2), 2), (Value::Integer(4), 2), (Value::Integer(9), 2),]
4316        );
4317        let strings = reader.top_frequencies(1, 1).expect("valid string synopsis").expect("kept");
4318        assert_eq!(strings.len(), 3);
4319        assert!(strings.contains(&(Value::Null, 2)));
4320        assert!(strings.contains(&(Value::Varchar("alpha".into()), 2)));
4321        assert!(strings.contains(&(Value::Varchar("long text after a slash".into()), 2)));
4322        fs::remove_file(path).expect("remove scratch file");
4323    }
4324
4325    /// Parts past the stripe bound start a new stripe, and every part stays addressable on its own.
4326    ///
4327    /// This is the shape the format exists for, so both ends of the split are checked here. The
4328    /// directory holds three stripes rather than a hundred and thirty one, and a read of any one
4329    /// part still answers with that part's rows rather than with its whole stripe's.
4330    #[test]
4331    fn parts_past_the_stripe_bound_start_a_new_stripe() {
4332        let path = path("stripe-bound");
4333        let mut writer = Writer::create(
4334            &path,
4335            "items",
4336            vec![
4337                Field::required("id", LogicalType::Integer),
4338                Field::new("text", LogicalType::Varchar),
4339            ],
4340        )
4341        .expect("new file");
4342        let parts = STRIPE_PARTS * 2 + 3;
4343        for part in 0..parts {
4344            let id = part as i32;
4345            let chunk = Chunk::new(vec![
4346                Vector::from_values(
4347                    LogicalType::Integer,
4348                    &[Value::Integer(id), Value::Integer(-id)],
4349                )
4350                .expect("integers"),
4351                Vector::from_values(
4352                    LogicalType::Varchar,
4353                    &[Value::Varchar(format!("value {part}")), Value::Null],
4354                )
4355                .expect("strings"),
4356            ])
4357            .expect("matching rows");
4358            writer.append(&chunk).expect("one part");
4359        }
4360        writer.finish().expect("commit");
4361
4362        let reader = Reader::open(&path).expect("reopen from disk");
4363        assert_eq!(reader.parts(), parts);
4364        assert_eq!(reader.table().rows(), parts * 2);
4365        assert_eq!(reader.table().stripes().len(), parts.div_ceil(STRIPE_PARTS));
4366        assert_eq!(reader.table().stripes()[0].parts(), STRIPE_PARTS);
4367        assert_eq!(reader.table().stripes()[0].rows(), STRIPE_PARTS * 2);
4368        assert_eq!(reader.table().stripes()[2].parts(), 3);
4369        // Backwards on purpose. The reader keeps four stripes a column, so a scan that walks the
4370        // table the other way is what catches a cache that only ever holds what it just read.
4371        for part in (0..parts).rev() {
4372            let dense = reader.read(part, &[0, 1]).expect("a whole page read");
4373            let sparse = reader.read_sparse(part, &[0, 1]).expect("one part read");
4374            for chunk in [&dense, &sparse] {
4375                assert_eq!(chunk.len(), 2, "part {part} has its own row count");
4376                assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4377                assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
4378                assert_eq!(chunk.value_at(0, 1), Value::Varchar(format!("value {part}")));
4379                assert_eq!(chunk.value_at(1, 1), Value::Null);
4380            }
4381        }
4382        // The bounds are merged over the stripe, so they answer for the range the whole stripe
4383        // covers and not for the part that was asked about.
4384        let above = [Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }];
4385        assert!(reader.skips(0, &above), "the first stripe stops at 63");
4386        assert!(!reader.skips(STRIPE_PARTS * 2, &above), "the third stripe reaches 130");
4387        fs::remove_file(path).expect("remove scratch file");
4388    }
4389
4390    /// A scattered value in the column that decides `WHERE UserID = ?`.
4391    fn scattered(n: i64) -> i64 {
4392        n.wrapping_mul(-7_046_029_254_386_353_131)
4393    }
4394
4395    /// A part whose sieve does not hold the constant is skipped, and a range would skip none of them.
4396    ///
4397    /// This is ClickBench query 19 in miniature. The values are spread over the whole of `BIGINT`, so
4398    /// every stripe's bounds cover nearly all of it and rule out nothing, and the part that really
4399    /// holds the value is the only one a scan has to read.
4400    #[test]
4401    fn a_part_is_skipped_when_its_sieve_does_not_hold_the_constant() {
4402        let path = path("sieve-skip");
4403        let mut writer =
4404            Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
4405                .expect("new file");
4406        let parts = STRIPE_PARTS + 3;
4407        let per_part = 8;
4408        for part in 0..parts {
4409            let held: Vec<Value> = (0..per_part)
4410                .map(|row| Value::BigInt(scattered((part * per_part + row) as i64)))
4411                .collect();
4412            let chunk =
4413                Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
4414                    .expect("one column");
4415            writer.append(&chunk).expect("one part");
4416        }
4417        writer.finish().expect("commit");
4418
4419        let reader = Reader::open(&path).expect("reopen from disk");
4420        let probe = |value: i64| Probe {
4421            column: 0,
4422            op: Op::Equal,
4423            value: Bound::Int(i128::from(scattered(value))),
4424        };
4425        for wanted in [0_i64, 9, (parts * per_part - 1) as i64] {
4426            let tests = [probe(wanted)];
4427            let kept: Vec<usize> = (0..parts).filter(|&part| !reader.skips(part, &tests)).collect();
4428            let home = wanted as usize / per_part;
4429            assert_eq!(kept, vec![home], "only the part holding {wanted} is read");
4430        }
4431        let absent = [probe((parts * per_part) as i64 + 1)];
4432        assert!((0..parts).all(|part| reader.skips(part, &absent)), "no part holds it");
4433        // The same probes against the bounds alone, which is what this replaces. A column of
4434        // scattered numbers has a range per stripe that covers nearly the whole type.
4435        let tests = [probe(0)];
4436        assert!(
4437            reader.table().stripes().iter().all(|stripe| !stripe.zone.skips(&tests)),
4438            "the bounds rule out no stripe at all"
4439        );
4440        fs::remove_file(path).expect("remove scratch file");
4441    }
4442
4443    /// A damaged sieve page is a part that gets read, not a query that fails.
4444    ///
4445    /// A sieve is an index over rows that are still there and still correct, so losing one costs
4446    /// time and costs no answers. That is the opposite of the membership index beside it, which is
4447    /// the only thing standing between a string page and a wrong answer.
4448    #[test]
4449    fn a_damaged_sieve_page_is_read_through_rather_than_refused() {
4450        let path = path("sieve-damaged");
4451        let mut writer =
4452            Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
4453                .expect("new file");
4454        let held: Vec<Value> = (0..8).map(|row| Value::BigInt(scattered(row))).collect();
4455        let chunk =
4456            Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
4457                .expect("one column");
4458        writer.append(&chunk).expect("one part");
4459        writer.finish().expect("commit");
4460
4461        let page =
4462            Reader::open(&path).expect("reopen").table.stripes[0].sieves[0].expect("a sieve page");
4463        let mut file = OpenOptions::new().write(true).open(&path).expect("open the sieve page");
4464        file.seek(SeekFrom::Start(page.offset + u64::from(page.length) - 1)).expect("seek");
4465        file.write_all(&[0xff]).expect("damage one byte");
4466        drop(file);
4467
4468        let reader = Reader::open(&path).expect("reopen the damaged file");
4469        let absent =
4470            [Probe { column: 0, op: Op::Equal, value: Bound::Int(i128::from(scattered(99))) }];
4471        assert!(!reader.skips(0, &absent), "a sieve that cannot be read skips nothing");
4472        assert_eq!(reader.read(0, &[0]).expect("the rows are untouched").len(), 8);
4473        fs::remove_file(path).expect("remove scratch file");
4474    }
4475
4476    /// Eight workers over one stripe read it once between them.
4477    ///
4478    /// This is the shape a scan actually has. Parts are handed out in order, so every worker on a
4479    /// column crosses into a stripe within a few parts of the others, and before [`Reader::held`]
4480    /// started sharing the read every one of them read the whole page. On the full ClickBench file
4481    /// that was a `MIN(EventDate), MAX(EventDate)` moving 3.2 GB off the disk to look at 400 MB of
4482    /// column, which is most of what a first touch costs.
4483    ///
4484    /// The workers that lose the race still answer, out of the part reads they do instead, which is
4485    /// what the values below are checking.
4486    #[test]
4487    fn workers_that_want_the_same_stripe_read_it_once() {
4488        let path = path("single-flight");
4489        let mut writer =
4490            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4491                .expect("new file");
4492        for part in 0..STRIPE_PARTS {
4493            let id = part as i32;
4494            let chunk = Chunk::new(vec![
4495                Vector::from_values(
4496                    LogicalType::Integer,
4497                    &[Value::Integer(id), Value::Integer(-id)],
4498                )
4499                .expect("integers"),
4500            ])
4501            .expect("matching rows");
4502            writer.append(&chunk).expect("one part");
4503        }
4504        writer.finish().expect("commit");
4505
4506        let reader = Reader::open(&path).expect("reopen from disk");
4507        assert_eq!(reader.table().stripes().len(), 1, "one stripe is the point of the test");
4508        let barrier = std::sync::Barrier::new(8);
4509        std::thread::scope(|scope| {
4510            for worker in 0..8 {
4511                let reader = &reader;
4512                let barrier = &barrier;
4513                scope.spawn(move || {
4514                    barrier.wait();
4515                    for part in (worker..STRIPE_PARTS).step_by(8) {
4516                        let chunk = reader.read(part, &[0]).expect("a whole page read");
4517                        assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4518                        assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
4519                    }
4520                });
4521            }
4522        });
4523        assert_eq!(reader.pages.load(Atomic::Relaxed), 1, "one stripe, one page read, whoever won");
4524        fs::remove_file(path).expect("remove scratch file");
4525    }
4526
4527    /// Opening a file reads the header and the directory, and nothing that depends on the rows.
4528    ///
4529    /// `spec/stats/04-in-memory.md` section 4.2. There are no statistics in the file yet, so this
4530    /// holds today by not having anything to load, and that is exactly why it is worth pinning now.
4531    /// The change that breaks it is the reasonable looking one: summaries are a few hundred bytes,
4532    /// the next query will want them, so read them on the way past. A process that opened the
4533    /// database to run one trivial query pays for all of it and gets nothing.
4534    ///
4535    /// Two files of the same shape and a thousand times the rows in one of them, opened, and the
4536    /// two openings cost the same. The stripe count is held equal so that the directory is the same
4537    /// size in both, which leaves the rows as the only thing that changed. Anything read out of the
4538    /// data would show up here.
4539    #[test]
4540    fn opening_costs_the_same_over_a_thousand_times_the_rows() {
4541        let opened = |label: &str, rows_per_part: i32| {
4542            let path = path(label);
4543            let mut writer =
4544                Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4545                    .expect("new file");
4546            for part in 0..STRIPE_PARTS * 3 {
4547                // Scrambled rather than sequential, so that the fat file is actually fatter. A run
4548                // of consecutive integers encodes to almost nothing and would leave the two files
4549                // the same size, which would make this test pass for the wrong reason.
4550                let values = (0..rows_per_part)
4551                    .map(|row| {
4552                        Value::Integer((part as i32 * rows_per_part + row).wrapping_mul(2_654_435))
4553                    })
4554                    .collect::<Vec<_>>();
4555                let chunk = Chunk::new(vec![
4556                    Vector::from_values(LogicalType::Integer, &values).expect("integers"),
4557                ])
4558                .expect("matching rows");
4559                writer.append(&chunk).expect("one part");
4560            }
4561            writer.finish().expect("commit");
4562            let reader = Reader::open(&path).expect("reopen from disk");
4563            let size = fs::metadata(&path).expect("the file is there").len();
4564            let out = (reader.reads(), reader.table().stripes().len(), size);
4565            fs::remove_file(path).expect("remove scratch file");
4566            out
4567        };
4568
4569        let (thin, thin_stripes, thin_size) = opened("open-thin", 1);
4570        let (fat, fat_stripes, fat_size) = opened("open-fat", 1000);
4571        assert_eq!(
4572            thin_stripes, fat_stripes,
4573            "the same stripe count is what makes this a fair ask"
4574        );
4575        assert!(
4576            fat_size > thin_size * 50,
4577            "the fat file has to actually be larger, and it is {fat_size} against {thin_size}"
4578        );
4579
4580        assert_eq!(thin.opening.reads, fat.opening.reads, "the same reads either way");
4581        assert_eq!(thin.pages, 0, "opening read a page");
4582        assert_eq!(fat.pages, 0, "opening read a page");
4583        assert_eq!(thin.indexes, 0, "opening read an index");
4584        assert_eq!(fat.indexes, 0, "opening read an index");
4585        // Not exactly equal, because a directory holds offsets and a larger file has larger ones,
4586        // and a handful of bytes of varint is not somebody loading statistics. A factor is.
4587        assert!(
4588            fat.opening.bytes < thin.opening.bytes * 2,
4589            "opening the thin file read {} bytes and the fat one read {}",
4590            thin.opening.bytes,
4591            fat.opening.bytes
4592        );
4593    }
4594
4595    /// The reads a file costs to open are fixed by its shape and not by what ran before.
4596    ///
4597    /// `spec/stats/04-in-memory.md` section 4.3, which is the rule that keeps a plan reproducible:
4598    /// the plan is a function of the data, the generation and the settings, and never of what
4599    /// happened to be in cache. Opening the same file twice in the same process has to cost the
4600    /// same, because a second open that read less would be an open that was about to plan
4601    /// differently.
4602    #[test]
4603    fn two_opens_of_one_file_cost_the_same_and_the_second_is_not_cheaper() {
4604        let path = path("open-twice");
4605        let mut writer =
4606            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4607                .expect("new file");
4608        for part in 0..STRIPE_PARTS * 3 {
4609            let chunk = Chunk::new(vec![
4610                Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
4611                    .expect("integers"),
4612            ])
4613            .expect("matching rows");
4614            writer.append(&chunk).expect("one part");
4615        }
4616        writer.finish().expect("commit");
4617
4618        let first = Reader::open(&path).expect("open");
4619        // A whole scan in between, so the operating system's page cache is as warm as it gets and
4620        // anything that consulted it would show up in the second open.
4621        for part in 0..first.parts() {
4622            first.read(part, &[0]).expect("a part");
4623        }
4624        assert!(first.reads().pages > 0, "the scan has to have read something");
4625        let second = Reader::open(&path).expect("open again");
4626
4627        assert_eq!(first.reads().opening, second.reads().opening);
4628        assert_eq!(
4629            second.reads().pages,
4630            0,
4631            "the second open read a page off the back of the first"
4632        );
4633        assert_eq!(second.reads().indexes, 0, "the second open read an index it inherited");
4634        fs::remove_file(path).expect("remove scratch file");
4635    }
4636
4637    /// A scan reads a stripe's index once for the whole scan, not once per part that misses.
4638    ///
4639    /// The page cache holds four stripes and an index used to ride inside it, so a table with more
4640    /// stripes than that read the index again every time a stripe came back around. The index is a
4641    /// few hundred bytes and the page is a quarter of a megabyte, which is why they are now under
4642    /// different budgets. This is the test that keeps them there, since the saving is small enough
4643    /// that nothing in a benchmark would notice it going away again.
4644    #[test]
4645    fn an_index_is_read_once_per_stripe_however_often_the_page_is_evicted() {
4646        let path = path("index-cache");
4647        let mut writer =
4648            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4649                .expect("new file");
4650        let parts = STRIPE_PARTS * (CACHED_STRIPES_PER_COLUMN + 2);
4651        for part in 0..parts {
4652            let id = part as i32;
4653            let chunk = Chunk::new(vec![
4654                Vector::from_values(LogicalType::Integer, &[Value::Integer(id)]).expect("integers"),
4655            ])
4656            .expect("matching rows");
4657            writer.append(&chunk).expect("one part");
4658        }
4659        writer.finish().expect("commit");
4660
4661        let reader = Reader::open(&path).expect("reopen from disk");
4662        let stripes = reader.table().stripes().len();
4663        assert!(stripes > CACHED_STRIPES_PER_COLUMN, "the page cache has to be too small for this");
4664        // Twice over, so that the second pass finds every page evicted and every index kept.
4665        for _ in 0..2 {
4666            for part in 0..parts {
4667                let chunk = reader.read(part, &[0]).expect("a part");
4668                assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4669            }
4670        }
4671        assert_eq!(reader.indexes.load(Atomic::Relaxed), stripes, "one index read per stripe");
4672        assert!(
4673            reader.pages.load(Atomic::Relaxed) > stripes,
4674            "the pages are the ones that get read again, which is what makes the index count mean \
4675             something"
4676        );
4677        fs::remove_file(path).expect("remove scratch file");
4678    }
4679
4680    /// A worker per stripe reads its stripe once, once the cache has been told how many there are.
4681    ///
4682    /// This is the shape a scan has when it hands out a whole stripe per morsel rather than a part.
4683    /// Nobody races for a page any more, but every worker holds a different one for the length of a
4684    /// stripe, so a cache that keeps four pages while eight workers are in eight stripes evicts
4685    /// every one of them before its owner has finished with it, and the owner reads a quarter of a
4686    /// megabyte again for the next part. The barrier is what makes that certain rather than likely:
4687    /// without it a worker can run a whole stripe before the next one starts and never collide.
4688    #[test]
4689    fn a_worker_per_stripe_reads_its_page_once_when_the_cache_was_told_to_expect_it() {
4690        let workers = CACHED_STRIPES_PER_COLUMN + 4;
4691        let path = path("stripe-per-worker");
4692        let mut writer =
4693            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4694                .expect("new file");
4695        for part in 0..STRIPE_PARTS * workers {
4696            let chunk = Chunk::new(vec![
4697                Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
4698                    .expect("integers"),
4699            ])
4700            .expect("matching rows");
4701            writer.append(&chunk).expect("one part");
4702        }
4703        writer.finish().expect("commit");
4704
4705        let read = |told: bool| {
4706            let reader = Reader::open(&path).expect("reopen from disk");
4707            assert_eq!(reader.table().stripes().len(), workers, "a stripe per worker");
4708            if told {
4709                reader.keep_stripes(workers);
4710            }
4711            let barrier = std::sync::Barrier::new(workers);
4712            std::thread::scope(|scope| {
4713                for (worker, run) in reader.stripe_parts().into_iter().enumerate() {
4714                    let reader = &reader;
4715                    let barrier = &barrier;
4716                    scope.spawn(move || {
4717                        for part in run {
4718                            barrier.wait();
4719                            let chunk = reader.read(part, &[0]).expect("a part of my own stripe");
4720                            assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
4721                        }
4722                        assert!(worker < workers);
4723                    });
4724                }
4725            });
4726            reader.pages.load(Atomic::Relaxed)
4727        };
4728
4729        assert_eq!(read(true), workers, "one page read per stripe and no more");
4730        assert!(read(false) > workers, "a cache that small is read again on every part");
4731        fs::remove_file(path).expect("remove scratch file");
4732    }
4733
4734    /// A damaged index page is caught before anything decodes a part out of it.
4735    ///
4736    /// The index is the one structure a reader trusts to find bytes with, so it carries a checksum
4737    /// per column section rather than one for the page, and this is what says that check runs.
4738    #[test]
4739    fn a_damaged_index_page_is_an_error() {
4740        let path = path("damaged-index");
4741        let mut writer =
4742            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
4743                .expect("new file");
4744        writer.append(&sample_ids()).expect("first part");
4745        writer.append(&sample_ids()).expect("second part");
4746        writer.finish().expect("commit");
4747
4748        let reader = Reader::open(&path).expect("valid directory");
4749        let index = reader.table.stripes[0].index;
4750        let mut byte = [0; 1];
4751        read_at(&reader.file, index.offset, &mut byte).expect("the first part length");
4752        let mut file = OpenOptions::new().write(true).open(&path).expect("open index page");
4753        file.seek(SeekFrom::Start(index.offset)).expect("index start");
4754        file.write_all(&[!byte[0]]).expect("damage the first part length");
4755        let error = reader.read(1, &[0]).expect_err("a damaged index must not be used");
4756        assert!(error.message().contains("index page section checksum differs"), "{error}");
4757        fs::remove_file(path).expect("remove scratch file");
4758    }
4759
4760    /// Every integer width the format knows about, written and read back.
4761    ///
4762    /// The unsigned ones are the reason ClickBench can be stored at all: `hits` types `EventDate`
4763    /// as `USMALLINT`, and one unsupported column meant the whole table was refused. The extremes
4764    /// are in here on purpose, because a width that round trips through the wrong signedness only
4765    /// goes wrong at the end of its range.
4766    #[test]
4767    fn every_integer_width_round_trips_through_a_page() {
4768        let path = path("integer-widths");
4769        let columns = [
4770            (LogicalType::TinyInt, vec![Value::TinyInt(i8::MIN), Value::TinyInt(i8::MAX)]),
4771            (LogicalType::UTinyInt, vec![Value::UTinyInt(0), Value::UTinyInt(u8::MAX)]),
4772            (LogicalType::SmallInt, vec![Value::SmallInt(i16::MIN), Value::SmallInt(i16::MAX)]),
4773            (LogicalType::USmallInt, vec![Value::USmallInt(0), Value::USmallInt(u16::MAX)]),
4774            (LogicalType::Integer, vec![Value::Integer(i32::MIN), Value::Integer(i32::MAX)]),
4775            (LogicalType::UInteger, vec![Value::UInteger(0), Value::UInteger(u32::MAX)]),
4776            (LogicalType::BigInt, vec![Value::BigInt(i64::MIN), Value::BigInt(i64::MAX)]),
4777            (LogicalType::UBigInt, vec![Value::UBigInt(0), Value::UBigInt(u64::MAX)]),
4778        ];
4779        let fields = columns
4780            .iter()
4781            .enumerate()
4782            .map(|(at, (ty, _))| Field::required(format!("c{at}"), ty.clone()))
4783            .collect::<Vec<_>>();
4784        let vectors = columns
4785            .iter()
4786            .map(|(ty, values)| Vector::from_values(ty.clone(), values).expect("a vector"))
4787            .collect::<Vec<_>>();
4788        let mut writer = Writer::create(&path, "widths", fields).expect("new file");
4789        writer.append(&Chunk::new(vectors).expect("matching rows")).expect("one stripe");
4790        writer.finish().expect("commit");
4791
4792        let reader = Reader::open(&path).expect("reopen from disk");
4793        let wanted = (0..columns.len()).collect::<Vec<_>>();
4794        let read = reader.read(0, &wanted).expect("every column");
4795        assert_eq!(read.len(), 2);
4796        // row at a time: each column has its own type and its own pair of extremes.
4797        for (at, (ty, values)) in columns.iter().enumerate() {
4798            assert_eq!(read.value_at(0, at), values[0], "the low end of {ty}");
4799            assert_eq!(read.value_at(1, at), values[1], "the high end of {ty}");
4800        }
4801        fs::remove_file(path).expect("remove scratch file");
4802    }
4803
4804    #[test]
4805    fn numeric_frequency_candidates_keep_bounded_row_ordinals() {
4806        let path = path("frequency-ordinals");
4807        let mut writer =
4808            Writer::create(&path, "items", vec![Field::required("id", LogicalType::BigInt)])
4809                .expect("new file");
4810        let mut values = Vec::new();
4811        for leader in 0..10_i64 {
4812            values.extend(std::iter::repeat_n(leader, 100));
4813        }
4814        values.extend(1_000_i64..41_000);
4815        for part in values.chunks(1_024) {
4816            let vector = Vector::flat(LogicalType::BigInt, Data::Int64(part.to_vec().into()))
4817                .expect("big integers");
4818            writer.append(&Chunk::new(vec![vector]).expect("one column")).expect("one stripe");
4819        }
4820        writer.finish().expect("commit");
4821
4822        let reader = Reader::open(&path).expect("reopen from disk");
4823        let occurrences =
4824            reader.frequency_occurrences(0).expect("valid metadata").expect("bounded ordinals");
4825        assert!(occurrences.omitted_max < 100);
4826        assert!(occurrences.ordinals.len() <= FREQUENCY_ORDINALS);
4827        assert!(occurrences.ordinals.windows(2).all(|pair| pair[0] < pair[1]));
4828        assert_eq!(&occurrences.ordinals[..1_000], &(0_u64..1_000).collect::<Vec<_>>());
4829        fs::remove_file(path).expect("remove scratch file");
4830    }
4831
4832    /// The bug this is here for cost a 43 GB ClickBench table and an hour of reloading it. The
4833    /// format went from 11 to 12, every binary built after that said "magic or major version is
4834    /// unsupported" about the file, and there was no way to tell from the message whether the path
4835    /// was wrong, the file was truncated, or it was ours and simply older. The number this build
4836    /// wants is the whole answer and it was the one thing the message did not carry.
4837    #[test]
4838    fn a_file_from_another_format_says_which_format_it_is() {
4839        let older = path("older-format");
4840        let mut writer =
4841            Writer::create(&older, "items", vec![Field::new("id", LogicalType::Integer)])
4842                .expect("new file");
4843        let chunk = Chunk::new(vec![
4844            Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
4845                .expect("integers"),
4846        ])
4847        .expect("chunk");
4848        writer.append(&chunk).expect("page written");
4849        writer.finish().expect("commit");
4850
4851        let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
4852        file.seek(SeekFrom::Start(8)).expect("the version follows the magic");
4853        file.write_all(&(FORMAT - 1).to_le_bytes()).expect("write an older version");
4854        drop(file);
4855        let complaint = Reader::open(&older).expect_err("an older format is refused").to_string();
4856        assert!(complaint.contains(&format!("format {}", FORMAT - 1)), "{complaint}");
4857        assert!(complaint.contains(&format!("format {FORMAT}")), "{complaint}");
4858
4859        let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
4860        file.seek(SeekFrom::Start(0)).expect("the magic is first");
4861        file.write_all(b"NOTRUDB!").expect("write another engine's magic");
4862        drop(file);
4863        let complaint = Reader::open(&older).expect_err("a foreign file is refused").to_string();
4864        assert!(complaint.contains("magic"), "{complaint}");
4865        assert!(!complaint.contains("format"), "a version has nothing to do with it: {complaint}");
4866        fs::remove_file(older).expect("remove scratch file");
4867    }
4868
4869    #[test]
4870    fn an_unfinished_or_damaged_file_does_not_answer_with_partial_rows() {
4871        let unfinished = path("unfinished");
4872        let mut writer =
4873            Writer::create(&unfinished, "items", vec![Field::new("id", LogicalType::Integer)])
4874                .expect("new file");
4875        let chunk = Chunk::new(vec![
4876            Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
4877                .expect("integers"),
4878        ])
4879        .expect("chunk");
4880        writer.append(&chunk).expect("page written");
4881        drop(writer);
4882        assert!(Reader::open(&unfinished).is_err(), "no directory was committed");
4883        fs::remove_file(unfinished).expect("remove scratch file");
4884
4885        let damaged = path("damaged");
4886        let mut writer =
4887            Writer::create(&damaged, "items", vec![Field::new("id", LogicalType::Integer)])
4888                .expect("new file");
4889        writer.append(&chunk).expect("page written");
4890        writer.finish().expect("commit");
4891        let reader = Reader::open(&damaged).expect("valid directory");
4892        let mut file =
4893            OpenOptions::new().write(true).open(&damaged).expect("open for a damaged page");
4894        file.seek(SeekFrom::Start(HEADER + 1)).expect("inside first page");
4895        file.write_all(&[255]).expect("damage one byte");
4896        assert!(reader.read(0, &[0]).is_err(), "page checksum rejects corruption");
4897        fs::remove_file(damaged).expect("remove scratch file");
4898    }
4899
4900    #[test]
4901    fn damaged_lazy_dictionary_payload_is_an_error() {
4902        let path = path("damaged-dictionary");
4903        let mut writer = Writer::create(
4904            &path,
4905            "items",
4906            vec![
4907                Field::required("id", LogicalType::Integer),
4908                Field::new("text", LogicalType::Varchar),
4909            ],
4910        )
4911        .expect("new file");
4912        writer.append(&sample()).expect("stripe written");
4913        writer.finish().expect("commit");
4914
4915        let reader = Reader::open(&path).expect("valid directory");
4916        let dictionary = reader.table.dictionaries[1].expect("string dictionary page");
4917        // Read the count out of the page rather than writing it here, so that adding something
4918        // else to the index does not silently turn this into a test that damages the index.
4919        let mut header = [0; 12];
4920        read_at(&reader.file, dictionary.offset, &mut header).expect("dictionary header");
4921        let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
4922        let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
4923        let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
4924        let index_len =
4925            12 + (count + 1) * 4 + (blocks + rank_blocks) * 8 + count * RANK_ENTRY as u64;
4926        let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
4927        file.seek(SeekFrom::Start(dictionary.offset + index_len))
4928            .expect("inside dictionary payload");
4929        file.write_all(&[255]).expect("damage dictionary payload");
4930
4931        let chunk = reader.read(0, &[1]).expect("code page and dictionary index remain valid");
4932        let error =
4933            chunk.validate_external().expect_err("payload corruption must reach the caller");
4934        assert!(error.message().contains("payload checksum differs"), "{error}");
4935        fs::remove_file(path).expect("remove scratch file");
4936    }
4937
4938    /// A payload that spans more than one extent still reads and checks every block of it.
4939    ///
4940    /// The test above has a dictionary of three values, so it says nothing about the grouping a
4941    /// reader does over the blocks the checksums are written for. This one is over a megabyte,
4942    /// which is more than one extent, and it reads a value out of the first extent and a value out
4943    /// of the last and then damages the last and asks for it again.
4944    #[test]
4945    fn a_dictionary_over_one_extent_checks_every_block_of_it() {
4946        let path = path("dictionary-extents");
4947        let value =
4948            |row: usize| format!("{row:07} a value long enough to be worth a payload block");
4949        let parts = 30;
4950        let per_part = 1000;
4951        let mut writer =
4952            Writer::create(&path, "items", vec![Field::required("text", LogicalType::Varchar)])
4953                .expect("new file");
4954        for part in 0..parts {
4955            let values = (0..per_part)
4956                .map(|row| Value::Varchar(value(part * per_part + row)))
4957                .collect::<Vec<_>>();
4958            let chunk = Chunk::new(vec![
4959                Vector::from_values(LogicalType::Varchar, &values).expect("strings"),
4960            ])
4961            .expect("matching rows");
4962            writer.append(&chunk).expect("a part");
4963        }
4964        writer.finish().expect("commit");
4965
4966        let reader = Reader::open(&path).expect("reopen from disk");
4967        let dictionary = reader.table.dictionaries[0].expect("string dictionary page");
4968        assert!(
4969            dictionary.length as usize > TEXT_PAYLOAD_BLOCK * TEXT_PAYLOAD_EXTENT,
4970            "the dictionary has to be over one extent for this to be testing anything"
4971        );
4972        for part in [0, parts - 1] {
4973            let chunk = reader.read(part, &[0]).expect("a part");
4974            chunk.validate_external().expect("every payload block checks out");
4975            assert_eq!(chunk.value_at(0, 0), Value::Varchar(value(part * per_part)));
4976        }
4977
4978        let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
4979        file.seek(SeekFrom::Start(dictionary.offset + u64::from(dictionary.length) - 4))
4980            .expect("the last bytes of the page are payload");
4981        file.write_all(&[255]).expect("damage the last payload block");
4982        let reader = Reader::open(&path).expect("the directory and the index are untouched");
4983        let chunk = reader.read(parts - 1, &[0]).expect("the code page remains valid");
4984        let error = chunk.validate_external().expect_err("the damage must reach the caller");
4985        assert!(error.message().contains("payload checksum differs"), "{error}");
4986        fs::remove_file(path).expect("remove scratch file");
4987    }
4988
4989    /// The sorted order sits outside the index the page checksum covers, because a query that
4990    /// never searches a dictionary should not read it, so it carries its own checksums and this is
4991    /// what says they are checked. A search that trusted a damaged order would give a wrong answer
4992    /// rather than a slow one.
4993    #[test]
4994    fn a_damaged_sorted_order_is_an_error() {
4995        let path = path("damaged-order");
4996        let mut writer = Writer::create(
4997            &path,
4998            "items",
4999            vec![
5000                Field::required("id", LogicalType::Integer),
5001                Field::new("text", LogicalType::Varchar),
5002            ],
5003        )
5004        .expect("new file");
5005        writer.append(&sample()).expect("stripe written");
5006        writer.finish().expect("commit");
5007
5008        let reader = Reader::open(&path).expect("valid directory");
5009        let page = reader.table.dictionaries[1].expect("string dictionary page");
5010        let mut header = [0; 12];
5011        read_at(&reader.file, page.offset, &mut header).expect("dictionary header");
5012        let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
5013        let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
5014        let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
5015        let index_len = 12 + (count + 1) * 4 + (blocks + rank_blocks) * 8;
5016        let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
5017        file.seek(SeekFrom::Start(page.offset + index_len)).expect("the first head");
5018        file.write_all(&[255]).expect("damage the order");
5019
5020        let dictionary = reader.dictionary(1).expect("read").expect("a string column has one");
5021        let error = dictionary.compare_rank(0, b"anything").expect_err("a damaged order is caught");
5022        assert!(error.message().contains("rank checksum differs"), "{error}");
5023        fs::remove_file(path).expect("remove scratch file");
5024    }
5025
5026    /// Codes stay in first appearance order and the sorted order is written beside them, so a
5027    /// reader can put the values back in order without the writer having had to know them all
5028    /// before it handed out the first code.
5029    #[test]
5030    fn a_global_dictionary_carries_the_sorted_order_of_its_values() {
5031        // Chosen so the sort cannot be decided on the first eight bytes alone. Three values share
5032        // a nine byte prefix, one is a prefix of another, and one is empty.
5033        let spellings = ["overlong1z", "b", "", "overlong1a", "overlong", "ab", "a", "overlong1"];
5034        let path = path("dictionary-order");
5035        let mut writer =
5036            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
5037                .expect("new file");
5038        writer
5039            .append(
5040                &Chunk::new(vec![
5041                    Vector::from_values(
5042                        LogicalType::Varchar,
5043                        &spellings.map(|text| Value::Varchar(text.into())),
5044                    )
5045                    .expect("strings"),
5046                ])
5047                .expect("one column"),
5048            )
5049            .expect("stripe written");
5050        writer.finish().expect("commit");
5051
5052        let reader = Reader::open(&path).expect("valid directory");
5053        let dictionary = reader.dictionary(0).expect("read").expect("a string column has one");
5054        let count = dictionary.ranks().expect("a v10 file stores one");
5055        assert_eq!(count, spellings.len(), "every distinct value has a rank");
5056        let order = (0..count)
5057            .map(|rank| dictionary.code_at_rank(rank).expect("a code"))
5058            .collect::<Vec<_>>();
5059        let mut seen = order.clone();
5060        seen.sort_unstable();
5061        assert_eq!(seen, (0..spellings.len() as u32).collect::<Vec<_>>(), "a permutation of codes");
5062
5063        let ranked = order
5064            .iter()
5065            .map(|&code| {
5066                dictionary.try_bytes_at(code as usize).expect("read").expect("a value").to_vec()
5067            })
5068            .collect::<Vec<_>>();
5069        let mut expected = spellings.map(|text| text.as_bytes().to_vec()).to_vec();
5070        expected.sort();
5071        assert_eq!(ranked, expected, "rank order is value order");
5072
5073        // What a search asks, on the values themselves rather than through a kernel, so that a
5074        // file whose heads disagree with its bytes is caught here rather than as a wrong answer.
5075        for (rank, value) in expected.iter().enumerate() {
5076            assert_eq!(
5077                dictionary.compare_rank(rank, value).expect("compare"),
5078                Ordering::Equal,
5079                "rank {rank} is its own value"
5080            );
5081            if rank > 0 {
5082                assert_eq!(
5083                    dictionary.compare_rank(rank - 1, value).expect("compare"),
5084                    Ordering::Less,
5085                    "rank {rank} follows the one before it"
5086                );
5087            }
5088        }
5089        fs::remove_file(path).expect("remove scratch file");
5090    }
5091
5092    #[test]
5093    fn damaged_membership_cannot_skip_a_string_page() {
5094        let path = path("damaged-membership");
5095        let mut writer = Writer::create(
5096            &path,
5097            "items",
5098            vec![
5099                Field::required("id", LogicalType::Integer),
5100                Field::new("text", LogicalType::Varchar),
5101            ],
5102        )
5103        .expect("new file");
5104        writer.append(&sample()).expect("stripe written");
5105        writer.finish().expect("commit");
5106
5107        let reader = Reader::open(&path).expect("valid directory");
5108        let membership = reader.table.stripes[0].memberships[1].expect("string membership");
5109        let mut file = OpenOptions::new().write(true).open(&path).expect("open membership page");
5110        file.seek(SeekFrom::Start(membership.offset)).expect("membership start");
5111        file.write_all(&[255]).expect("damage membership");
5112        let error = reader.skips_codes(0, 1, &[3]).expect_err("corruption must not skip rows");
5113        assert!(error.message().contains("membership page checksum differs"), "{error}");
5114        fs::remove_file(path).expect("remove scratch file");
5115    }
5116
5117    #[test]
5118    fn membership_delta_stream_is_sorted_exact_and_bounded() {
5119        let unique = unique_codes(&[900, 4, 4, 72, 9, u32::MAX]);
5120        assert_eq!(unique, [4, 9, 72, 900, u32::MAX]);
5121        let encoded = encode_membership(&unique);
5122        assert_eq!(
5123            decode_membership(&encoded).expect("valid membership"),
5124            [4, 9, 72, 900, u32::MAX]
5125        );
5126        // A stripe's index is the union of its parts', so a code in two of them is in it once and
5127        // the result is still one ascending run of deltas.
5128        let merged = merged_codes(vec![vec![4, 900], vec![9, 900, u32::MAX], vec![72]]);
5129        assert_eq!(merged, [4, 9, 72, 900, u32::MAX]);
5130        assert_eq!(
5131            decode_membership(&encode_membership(&merged)).expect("valid membership"),
5132            unique
5133        );
5134        assert!(decode_membership(&[1, 0x80]).is_err(), "a truncated varint is invalid");
5135        assert!(
5136            decode_membership(&[1, 0xff, 0xff, 0xff, 0xff, 0x10]).is_err(),
5137            "a value past u32 is invalid"
5138        );
5139    }
5140
5141    #[test]
5142    fn a_global_dictionary_may_be_larger_than_one_column_page() {
5143        let dictionary = Page {
5144            offset: HEADER,
5145            length: u32::try_from(MAX_PAGE + 1).expect("the page bound fits on disk"),
5146            hash: 0,
5147        };
5148        let table = Table {
5149            name: "items".to_owned(),
5150            fields: vec![Field::new("text", LogicalType::Varchar)],
5151            stripes: Vec::new(),
5152            rows: 0,
5153            dictionaries: vec![Some(dictionary)],
5154            frequencies: vec![None],
5155        };
5156        let directory = encode_directory(&table).expect("directory");
5157        let file_size = dictionary.offset + u64::from(dictionary.length) + 1;
5158
5159        let decoded = decode_directory(&directory, file_size).expect("large lazy dictionary");
5160        assert_eq!(decoded.dictionaries[0].expect("dictionary").length, dictionary.length);
5161    }
5162
5163    #[test]
5164    fn a_column_with_one_value_everywhere_costs_almost_nothing_a_row() {
5165        let path = path("constant-codes");
5166        let mut writer =
5167            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
5168                .expect("new file");
5169        let empty = vec![Value::Varchar(String::new()); 1024];
5170        for _ in 0..4 {
5171            let column = Vector::from_values(LogicalType::Varchar, &empty).expect("strings");
5172            writer.append(&Chunk::new(vec![column]).expect("one column")).expect("a part");
5173        }
5174        writer.finish().expect("commit");
5175
5176        let reader = Reader::open(&path).expect("valid directory");
5177        let pages = reader.layout().columns.first().expect("one column").pages;
5178        // This column used to cost four bytes a row, 16,384 of them, the same as a column of four
5179        // thousand distinct URLs would. The cascade calls each part a constant, so what is left is
5180        // a tag, a count and the value, and the row count stops being what drives the number.
5181        assert!(pages < 256, "{pages} bytes of pages for 4,096 rows of one value");
5182        let read = reader.read(3, &[0]).expect("the last part back");
5183        assert_eq!(read.value_at(0, 0), Value::Varchar(String::new()));
5184        assert_eq!(read.value_at(1023, 0), Value::Varchar(String::new()));
5185        fs::remove_file(path).expect("remove scratch file");
5186    }
5187
5188    #[test]
5189    fn a_cascade_value_too_wide_for_its_column_is_refused_rather_than_cut() {
5190        // What a damaged page looks like from here: the cascade decoded, so the bytes are not
5191        // truncated, but the values do not belong to the column the directory says they do.
5192        let over = vec![i64::from(i32::MAX) + 1];
5193        let error = narrowed(&LogicalType::Integer, over).expect_err("a page that disagrees");
5194        assert!(format!("{error}").contains("not of its type"), "{error}");
5195        assert!(narrowed(&LogicalType::BigInt, vec![i64::MIN]).is_ok(), "bigint holds all of i64");
5196        assert!(narrowed(&LogicalType::Varchar, vec![0]).is_err(), "strings are not integers");
5197    }
5198
5199    #[test]
5200    fn a_code_stream_the_cascade_cannot_shrink_is_left_alone() {
5201        // A shift register rather than a run, because an arithmetic run is the one wide shape the
5202        // cascade does shrink. This is what a column with tens of millions of distinct values hands
5203        // over: full width codes with no order to them.
5204        let mut state: u32 = 0x9e37_79b9;
5205        let spread: Vec<u32> = (0..1024)
5206            .map(|_| {
5207                state ^= state << 13;
5208                state ^= state >> 17;
5209                state ^= state << 5;
5210                state
5211            })
5212            .collect();
5213        assert_eq!(encoded_codes(&spread).expect("no failure"), None);
5214        let near: Vec<u32> = (0..1024).collect();
5215        let coded = encoded_codes(&near).expect("no failure").expect("counting up is packable");
5216        assert!(coded.len() < near.len() * 4, "{} bytes for a run of 1,024", coded.len());
5217    }
5218
5219    /// The columns of a stripe are encoded on whichever thread got to them, so the one thing that
5220    /// must not depend on which thread that was is the file. Two writes of the same rows are
5221    /// compared byte for byte rather than value for value, because a dictionary that two columns
5222    /// somehow shared would still read back correctly and would hand out its codes in the order the
5223    /// threads happened to run in, which is exactly what this is here to catch.
5224    #[test]
5225    fn two_writes_of_the_same_rows_give_the_same_bytes() {
5226        fn written(path: &PathBuf) {
5227            let fields = (0..40)
5228                .map(|column| {
5229                    let ty =
5230                        if column % 4 == 0 { LogicalType::Varchar } else { LogicalType::BigInt };
5231                    Field::new(format!("c{column}"), ty)
5232                })
5233                .collect::<Vec<_>>();
5234            let mut writer = Writer::create(path, "wide", fields).expect("new file");
5235            for part in 0..70_u64 {
5236                let columns = (0..40)
5237                    .map(|column| {
5238                        let values = (0..64_u64)
5239                            .map(|row| {
5240                                let seed = part.wrapping_mul(31).wrapping_add(row);
5241                                if column % 4 == 0 {
5242                                    Value::Varchar(format!("v{}", seed % 17))
5243                                } else {
5244                                    Value::BigInt(i64::try_from(seed % 97).expect("small"))
5245                                }
5246                            })
5247                            .collect::<Vec<_>>();
5248                        let ty = if column % 4 == 0 {
5249                            LogicalType::Varchar
5250                        } else {
5251                            LogicalType::BigInt
5252                        };
5253                        Vector::from_values(ty, &values).expect("a column")
5254                    })
5255                    .collect::<Vec<_>>();
5256                writer.append(&Chunk::new(columns).expect("forty columns")).expect("a part");
5257            }
5258            writer.finish().expect("commit");
5259        }
5260
5261        let first = path("repeatable-one");
5262        let second = path("repeatable-two");
5263        written(&first);
5264        written(&second);
5265        let left = fs::read(&first).expect("the first file");
5266        let right = fs::read(&second).expect("the second file");
5267        assert_eq!(left.len(), right.len(), "two writes of the same rows differ in length");
5268        assert!(left == right, "two writes of the same rows differ in their bytes");
5269
5270        // And the rows are still there, since a pair of identically wrong files would pass the
5271        // comparison above on its own.
5272        let reader = Reader::open(&first).expect("valid directory");
5273        assert_eq!(reader.table().rows(), 70 * 64);
5274        let read = reader.read(0, &[0, 1]).expect("the first part back");
5275        assert_eq!(read.value_at(0, 0), Value::Varchar("v0".to_owned()));
5276        assert_eq!(read.value_at(0, 1), Value::BigInt(0));
5277        fs::remove_file(first).expect("remove scratch file");
5278        fs::remove_file(second).expect("remove scratch file");
5279    }
5280}