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::slice;
37use std::sync::atomic::{AtomicUsize, Ordering as Atomic};
38use std::sync::{Arc, Mutex, OnceLock};
39
40use rudb_common::bounds::{Bound, Op, scaled_as};
41use rudb_common::{Error, Field, LogicalType, Result, Value};
42use rudb_encoding::{bitpack, chooser, integer, string};
43use rudb_storage::sieve::Sieve;
44use rudb_storage::{Probe, Range, Zone};
45use rudb_vector::string::StringColumn;
46use rudb_vector::validity::Validity;
47use rudb_vector::{Buffer, Chunk, Data, Packed, TextSource, Vector};
48
49const MAGIC: &[u8; 8] = b"RUDBNV10";
50const DIRECTORY: &[u8; 8] = b"RUDBDI10";
51const FORMAT: u32 = 21;
52const HEADER: u64 = 80;
53const SLOT_BYTES: usize = 28;
54const MAX_PAGE: usize = 256 * 1024 * 1024;
55const MAX_DIRECTORY: usize = 128 * 1024 * 1024;
56const FREQUENCIES: &[u8; 8] = b"RUDBFQ2\0";
57const FREQUENCY_CANDIDATES: usize = 32_768;
58const FREQUENCY_ENTRIES: usize = 512;
59const FREQUENCY_BUILD_RANK: usize = 10;
60const FREQUENCY_ORDINALS: usize = 65_536;
61/// The most threads the two per column passes at the end of a commit are spread over.
62///
63/// A table like `hits` has ninety numeric columns, so on a machine with more cores than this the
64/// cap is what decides how long the frequencies take rather than the columns are. It is here at all
65/// because each worker holds a candidate table and a decoded part, and a hundred of those at once
66/// on a narrow machine would be worse than waiting.
67const MAX_FREQUENCY_WORKERS: usize = 32;
68
69/// The most threads one stripe's encode is spread over.
70///
71/// Higher than the frequency cap because this is the load itself rather than a pass at the end of
72/// it, and the work is one column of sixty four parts, which is large enough that a thread that
73/// takes one is not a thread that was started for nothing. A machine with more cores than this has
74/// the rest of them on the Parquet read, which is still one thread and is the other half of #808.
75const MAX_ENCODE_WORKERS: usize = 32;
76
77/// The most bytes one column of one part may spend on a membership sieve.
78///
79/// A part is a thousand rows, so a filter sized for every one of them being distinct is about
80/// thirteen hundred bytes and this never binds in practice. It is here so that a part that somehow
81/// arrives much wider than a vector cannot put an unbounded index in the file. What does bind is the
82/// rule in `encode_column` that a sieve may not be as large as the part it indexes, which is a cap
83/// per column rather than one number for the whole file.
84const SIEVE_BUDGET: usize = 8 * 1024;
85
86/// The most bytes one end of a per part range may spend on a string.
87///
88/// A bound is allowed to be wider than the truth and never narrower, so a long string is cut down to
89/// this many bytes for the low end and cut down and then stepped up for the high end. The reason for
90/// a cap at all is that there are nine hundred and seventy four parts of a hundred and five columns
91/// in a million rows of ClickBench and `URL` runs to hundreds of bytes, so keeping every end whole
92/// would put more in the directory than the skipping is worth. Twenty four bytes is past the point
93/// where two URLs of the same site still look alike.
94const PART_BOUND_BYTES: usize = 24;
95
96fn io(error: std::io::Error) -> Error {
97    Error::io(error.to_string())
98}
99
100fn invalid(message: &str) -> Error {
101    Error::invalid_input(format!("invalid rudb native file: {message}"))
102}
103
104/// Adds a sequence of byte counts without an overflow the caller has to think about.
105fn sum(counts: impl Iterator<Item = u64>) -> u64 {
106    counts.fold(0, u64::saturating_add)
107}
108
109/// One column's span out of a per column list, or zero when the list is shorter than the column.
110fn span_bytes(spans: &[Span], at: usize) -> u64 {
111    spans.get(at).map_or(0, |span| u64::from(span.length))
112}
113
114/// One column's page out of a per column list, or zero when that column has no page at all.
115fn page_bytes(pages: &[Option<Page>], at: usize) -> u64 {
116    pages.get(at).and_then(Option::as_ref).map_or(0, Page::bytes)
117}
118
119fn checksum(bytes: &[u8]) -> u64 {
120    const P1: u64 = 11_400_714_785_074_694_791;
121    const P2: u64 = 14_029_467_366_897_019_727;
122    const P3: u64 = 1_609_587_929_392_839_161;
123    const P4: u64 = 9_650_029_242_287_828_579;
124    const P5: u64 = 2_870_177_450_012_600_261;
125    let round = |state: u64, word: u64| {
126        state.wrapping_add(word.wrapping_mul(P2)).rotate_left(31).wrapping_mul(P1)
127    };
128    let merge = |state: u64, lane: u64| (state ^ round(0, lane)).wrapping_mul(P1).wrapping_add(P4);
129    let word =
130        |at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("eight checksum bytes"));
131
132    let mut at = 0;
133    let mut hash = if bytes.len() >= 32 {
134        let mut one = P1.wrapping_add(P2);
135        let mut two = P2;
136        let mut three = 0;
137        let mut four = 0_u64.wrapping_sub(P1);
138        while at + 32 <= bytes.len() {
139            one = round(one, word(at));
140            two = round(two, word(at + 8));
141            three = round(three, word(at + 16));
142            four = round(four, word(at + 24));
143            at += 32;
144        }
145        let combined = one
146            .rotate_left(1)
147            .wrapping_add(two.rotate_left(7))
148            .wrapping_add(three.rotate_left(12))
149            .wrapping_add(four.rotate_left(18));
150        merge(merge(merge(merge(combined, one), two), three), four)
151    } else {
152        P5
153    };
154    hash = hash.wrapping_add(bytes.len() as u64);
155    while at + 8 <= bytes.len() {
156        hash ^= round(0, word(at));
157        hash = hash.rotate_left(27).wrapping_mul(P1).wrapping_add(P4);
158        at += 8;
159    }
160    if at + 4 <= bytes.len() {
161        let tail = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four checksum bytes"));
162        hash ^= u64::from(tail).wrapping_mul(P1);
163        hash = hash.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
164        at += 4;
165    }
166    while at < bytes.len() {
167        hash ^= u64::from(bytes[at]).wrapping_mul(P5);
168        hash = hash.rotate_left(11).wrapping_mul(P1);
169        at += 1;
170    }
171    hash ^= hash >> 33;
172    hash = hash.wrapping_mul(P2);
173    hash ^= hash >> 29;
174    hash = hash.wrapping_mul(P3);
175    hash ^ (hash >> 32)
176}
177
178#[derive(Debug, Clone, Copy)]
179struct Slot {
180    offset: u64,
181    length: u32,
182    generation: u64,
183    hash: u64,
184}
185
186impl Slot {
187    fn bytes(self) -> [u8; SLOT_BYTES] {
188        let mut result = [0; SLOT_BYTES];
189        result[..8].copy_from_slice(&self.offset.to_le_bytes());
190        result[8..12].copy_from_slice(&self.length.to_le_bytes());
191        result[12..20].copy_from_slice(&self.generation.to_le_bytes());
192        result[20..28].copy_from_slice(&self.hash.to_le_bytes());
193        result
194    }
195
196    fn read(bytes: &[u8]) -> Self {
197        Self {
198            offset: u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes")),
199            length: u32::from_le_bytes(bytes[8..12].try_into().expect("four bytes")),
200            generation: u64::from_le_bytes(bytes[12..20].try_into().expect("eight bytes")),
201            hash: u64::from_le_bytes(bytes[20..28].try_into().expect("eight bytes")),
202        }
203    }
204}
205
206#[derive(Debug, Clone, Copy)]
207struct Page {
208    offset: u64,
209    length: u32,
210    hash: u64,
211}
212
213impl Page {
214    /// How much of the file this page takes, for [`Reader::layout`].
215    fn bytes(&self) -> u64 {
216        u64::from(self.length)
217    }
218}
219
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
221enum FrequencyValue {
222    Null,
223    Integer(i128),
224    Code(u32),
225}
226
227#[derive(Debug, Clone)]
228struct FrequencyEntry {
229    value: FrequencyValue,
230    count: u64,
231}
232
233/// Exact leading frequencies for one column.
234///
235/// Values outside `entries` occur at most `omitted_max` times. This lets a count-descending TopN
236/// use the synopsis only when its last winner is strictly above every omitted value.
237#[derive(Debug, Clone)]
238struct FrequencySummary {
239    entries: Vec<FrequencyEntry>,
240    omitted_max: u64,
241    ordinals: Vec<u64>,
242}
243
244/// Sparse row ordinals covered by a numeric frequency candidate set.
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct FrequencyOccurrences {
247    /// Upper bound for the frequency of every value absent from the fetched rows.
248    pub omitted_max: u64,
249    /// Table-wide row ordinals in ascending order.
250    pub ordinals: Vec<u64>,
251}
252
253/// Where one column's page for one stripe sits in the file.
254///
255/// A column page has no checksum of its own because every part inside it carries one, and the
256/// stripe's index page holds those. Checking a part on the way out of the page covers exactly the
257/// bytes a reader is about to decode, and covers them once whether the reader took the whole page
258/// or pulled one part out of the middle of it.
259#[derive(Debug, Clone, Copy, Default)]
260struct Span {
261    offset: u64,
262    length: u32,
263}
264
265/// One independently readable stripe of a table.
266#[derive(Debug, Clone)]
267pub struct Stripe {
268    rows: usize,
269    /// Rows in each part, in source order. Kept in the directory so that mapping a row ordinal to a
270    /// part, which every sparse fetch does, never reads the file.
271    parts: Vec<u32>,
272    /// The index page: one section per column, holding a length and a checksum for every part and
273    /// then a checksum of the section itself, so that a reader can pread one column's section and
274    /// still know it is intact.
275    index: Span,
276    pages: Vec<Span>,
277    memberships: Vec<Option<Page>>,
278    /// One page per column holding the membership sieve of every part of the stripe, for the
279    /// columns that have one. A column whose parts all declined a sieve has no page at all.
280    sieves: Vec<Option<Page>>,
281    /// One page per column holding the two ends and the null count of every part of the stripe.
282    ///
283    /// The stripe's own `zone` below covers sixty four times as many rows, and on a column that is
284    /// not the one the rows are ordered by that is the difference between skipping half the file and
285    /// skipping all but three percent of it. On ClickBench 24 the cutoff the answer settles at
286    /// leaves eight stripes of sixteen alive and thirty parts of nine hundred and seventy four.
287    ///
288    /// A page per column rather than one page for the stripe, so that a query that compares one
289    /// column reads the ends of that column and not of the hundred and four beside it. Read lazily
290    /// for the same reason, like the sieves.
291    part_ranges: Vec<Option<Page>>,
292    zone: Zone,
293}
294
295impl Stripe {
296    /// Number of rows in this stripe.
297    #[must_use]
298    pub fn rows(&self) -> usize {
299        self.rows
300    }
301
302    /// Number of parts in this stripe.
303    #[must_use]
304    pub fn parts(&self) -> usize {
305        self.parts.len()
306    }
307}
308
309/// The committed table directory.
310#[derive(Debug, Clone)]
311pub struct Table {
312    name: String,
313    fields: Vec<Field>,
314    stripes: Vec<Stripe>,
315    rows: usize,
316    dictionaries: Vec<Option<Page>>,
317    frequencies: Vec<Option<FrequencySummary>>,
318    /// How many distinct values each column holds, for the columns that know.
319    ///
320    /// A dictionary entry is made the first time a value is seen and nothing ever removes one, so
321    /// the size of the dictionary is the number of distinct values in the column. That is the whole
322    /// story for a column with no null in it, and the wrong number by one for a column with a null
323    /// in it, because a null row is written as the code for the empty string and makes an entry the
324    /// dictionary would not otherwise have. The writer knows which case it is, since it counts the
325    /// non-null rows that use each code while it builds the frequency summary, and the reader cannot
326    /// work it out from the dictionary alone. So the writer settles it here.
327    distincts: Vec<Option<u64>>,
328}
329
330impl Table {
331    /// The SQL table name held by this snapshot.
332    #[must_use]
333    pub fn name(&self) -> &str {
334        &self.name
335    }
336
337    /// Columns in their SQL order.
338    #[must_use]
339    pub fn fields(&self) -> &[Field] {
340        &self.fields
341    }
342
343    /// Committed row count.
344    #[must_use]
345    pub fn rows(&self) -> usize {
346        self.rows
347    }
348
349    /// Independently readable stripes.
350    #[must_use]
351    pub fn stripes(&self) -> &[Stripe] {
352        &self.stripes
353    }
354}
355
356/// Where one column's bytes went, taken from the directory rather than by reading pages.
357#[derive(Debug, Clone)]
358pub struct ColumnLayout {
359    /// The column's name, so a report does not have to carry the field list beside this.
360    pub name: String,
361    /// The type, spelled the way the catalog spells it.
362    pub kind: String,
363    /// Every stripe's page of this column added up, which is the encoded data itself.
364    pub pages: u64,
365    /// Every stripe's exact code membership page for this column.
366    pub memberships: u64,
367    /// Every stripe's membership sieve page for this column.
368    pub sieves: u64,
369    /// Every stripe's per part range page for this column.
370    pub part_ranges: u64,
371    /// The table wide dictionary of this column, if it has one.
372    pub dictionary: u64,
373}
374
375impl ColumnLayout {
376    /// Everything this column costs, which is what the file would lose if the column went.
377    #[must_use]
378    pub fn total(&self) -> u64 {
379        self.pages
380            .saturating_add(self.memberships)
381            .saturating_add(self.sieves)
382            .saturating_add(self.part_ranges)
383            .saturating_add(self.dictionary)
384    }
385}
386
387/// Where a whole file's bytes went.
388///
389/// Every number here comes out of the committed directory, so taking it costs one directory read
390/// however large the file is. That is the point: a 45 GB table has to be able to say where it went
391/// without being read, or nobody will ask.
392///
393/// The parts that are not a column are kept apart rather than shared out over the columns. The
394/// stripe index page holds a section per column and could be split, and the directory and the
395/// header cannot be, so splitting one of the three and not the others would read as if the columns
396/// accounted for everything. They do not, and the gap is the thing worth looking at.
397#[derive(Debug, Clone)]
398pub struct Layout {
399    /// The size of the file on disk.
400    pub file: u64,
401    /// Committed rows.
402    pub rows: usize,
403    /// Committed stripes.
404    pub stripes: usize,
405    /// Committed parts, which is how many chunks a scan reads.
406    pub parts: usize,
407    /// One entry per column, in the table's column order.
408    pub columns: Vec<ColumnLayout>,
409    /// Every stripe's index page, which carries a length and a checksum for every part of every
410    /// column and is charged per stripe rather than per column.
411    pub indexes: u64,
412    /// The committed directory itself, the one that was read to build this.
413    pub directory: u64,
414    /// The fixed header, which holds the magic, the format and the two directory slots.
415    pub header: u64,
416}
417
418impl Layout {
419    /// Everything the columns cost together.
420    #[must_use]
421    pub fn columns_total(&self) -> u64 {
422        self.columns.iter().map(ColumnLayout::total).fold(0, u64::saturating_add)
423    }
424
425    /// What the file holds that this does not account for.
426    ///
427    /// A committed file is written once and never rewritten in place, so an earlier directory and
428    /// the pages of an earlier snapshot are still in it. That is the honest place for them: they
429    /// are bytes on disk that no column owns.
430    #[must_use]
431    pub fn unaccounted(&self) -> u64 {
432        self.file
433            .saturating_sub(self.columns_total())
434            .saturating_sub(self.indexes)
435            .saturating_sub(self.directory)
436            .saturating_sub(self.header)
437    }
438}
439
440/// Appends pages and commits a new directory for one table.
441#[derive(Debug)]
442struct GlobalDictionary {
443    primary: HashMap<u64, u32>,
444    collisions: HashMap<u64, Vec<u32>>,
445    offsets: Vec<u32>,
446    payload: Vec<u8>,
447    counts: Vec<u64>,
448    nulls: u64,
449}
450
451impl GlobalDictionary {
452    fn new() -> Self {
453        Self {
454            primary: HashMap::new(),
455            collisions: HashMap::new(),
456            offsets: vec![0],
457            payload: Vec::new(),
458            counts: Vec::new(),
459            nulls: 0,
460        }
461    }
462
463    fn bytes(&self, code: u32) -> Option<&[u8]> {
464        let start = *self.offsets.get(code as usize)? as usize;
465        let end = *self.offsets.get(code as usize + 1)? as usize;
466        self.payload.get(start..end)
467    }
468
469    fn code(&mut self, text: &str) -> Result<u32> {
470        let hash = checksum(text.as_bytes());
471        if let Some(&code) = self.primary.get(&hash) {
472            if self.bytes(code) == Some(text.as_bytes()) {
473                return Ok(code);
474            }
475            if let Some(codes) = self.collisions.get(&hash) {
476                if let Some(code) =
477                    codes.iter().copied().find(|&code| self.bytes(code) == Some(text.as_bytes()))
478                {
479                    return Ok(code);
480                }
481            }
482            let code = self.insert(text)?;
483            self.collisions.entry(hash).or_default().push(code);
484            return Ok(code);
485        }
486        let code = self.insert(text)?;
487        self.primary.insert(hash, code);
488        Ok(code)
489    }
490
491    fn insert(&mut self, text: &str) -> Result<u32> {
492        let code = u32::try_from(self.offsets.len() - 1)
493            .map_err(|_| invalid("global dictionary has too many values"))?;
494        self.payload.extend_from_slice(text.as_bytes());
495        self.offsets.push(
496            u32::try_from(self.payload.len())
497                .map_err(|_| invalid("global dictionary payload exceeds 4 GiB"))?,
498        );
499        self.counts.push(0);
500        Ok(code)
501    }
502
503    /// This dictionary's values in sorted order, each as the first eight bytes of the value and the
504    /// code that holds it, so entry `rank` describes the value that sits at `rank` when the values
505    /// are sorted by their bytes.
506    ///
507    /// Codes themselves stay in first appearance order, which is what lets the writer hand one out
508    /// the moment it sees a value rather than waiting for the last stripe, and which also keeps a
509    /// stripe's codes close together because the data is clustered. This is what puts the values
510    /// back in order for anything that needs it, and it is separate from the codes so that getting
511    /// it costs a sort of the distinct values at the end rather than a rewrite of every code page.
512    ///
513    /// The sort compares the first eight bytes as one integer before it compares the values, which
514    /// settles almost every pair without touching the payload. Padding with zero on the right is
515    /// order preserving for byte strings, because a shorter value differs from a longer one that
516    /// starts the same way at a position where the shorter one has run out, and zero is below every
517    /// byte that could be there. A pair the head cannot settle falls through to the bytes.
518    ///
519    /// The heads are kept rather than thrown away once the sort is over, because a reader searching
520    /// this order wants exactly the same comparison and for exactly the same reason. Eight bytes an
521    /// entry of file is what buys a binary search that reads no values at all in the ordinary case.
522    fn ranked(&self) -> Vec<(u64, u32)> {
523        let count = self.offsets.len() - 1;
524        let mut ranked = (0..count)
525            .map(|code| {
526                let code = code as u32;
527                (head(self.bytes(code).unwrap_or_default()), code)
528            })
529            .collect::<Vec<_>>();
530        ranked.sort_unstable_by(|left, right| {
531            left.0.cmp(&right.0).then_with(|| self.bytes(left.1).cmp(&self.bytes(right.1)))
532        });
533        ranked
534    }
535
536    fn observe(&mut self, code: u32, null: bool) -> Result<()> {
537        if null {
538            self.nulls = self.nulls.saturating_add(1);
539            return Ok(());
540        }
541        let count = self
542            .counts
543            .get_mut(code as usize)
544            .ok_or_else(|| invalid("global dictionary count code is out of range"))?;
545        *count = count.saturating_add(1);
546        Ok(())
547    }
548}
549
550/// Appends pages and commits a new directory for one table.
551#[derive(Debug)]
552pub struct Writer {
553    file: File,
554    /// Where the next write goes, counted here rather than asked of the file.
555    ///
556    /// The file's own cursor is not ours. Building the numeric frequencies reads pages back through
557    /// [`read_at`], and a positional read is only positional about where it reads from: `pread`
558    /// leaves the cursor alone, and the call Windows has for it moves the cursor to the end of what
559    /// it read. A writer that asked the file where it was would then write the directory over a
560    /// page it had already written, which is what it did.
561    at: u64,
562    table: Table,
563    generation: u64,
564    /// The first and the last source position in every stripe, in the order the stripes were
565    /// written.
566    order: Vec<((u64, u64), (u64, u64))>,
567    next_order: u64,
568    dictionaries: Vec<Option<GlobalDictionary>>,
569    pending: Vec<PendingChunk>,
570}
571
572/// A chunk that has arrived and is waiting for the rest of its stripe.
573///
574/// The rows are kept rather than the pages they encode to, which is the whole of #808's first half.
575/// Encoding on arrival put every column of every part on the thread that called `append_at`, and
576/// that thread is the only one the load has. Encoding at the flush instead means a stripe's worth
577/// of work is on the table at once, and a stripe splits by column into a hundred and five pieces
578/// that share nothing.
579#[derive(Debug)]
580struct PendingChunk {
581    order: (u64, u64),
582    chunk: Chunk,
583}
584
585/// One column's share of a stripe, which is what one encode worker produces.
586///
587/// Indexed by part, so a stripe is a column of these and the write loop reads down one of them.
588/// That is also the order the loop wanted: `flush_pending` walks a column at a time and lays its
589/// parts next to each other, and it used to reach across a row of parts to do it.
590#[derive(Debug)]
591struct ColumnStripe {
592    pages: Vec<Vec<u8>>,
593    codes: Vec<Option<Vec<u32>>>,
594    sieves: Vec<Option<Sieve>>,
595    ranges: Vec<Range>,
596}
597
598/// Roughly what encoding a column of this type costs, for ordering the encode queue.
599///
600/// Only the order matters and only roughly. A string column hashes and copies every value into a
601/// dictionary and is in a different class from everything else, and among the fixed widths the wide
602/// ones carry more bytes through the cascade than the narrow ones. Anything finer than that would
603/// be a cost model, and the queue already absorbs a wrong guess: it only has to avoid finishing on
604/// a column nobody else can help with.
605fn weight(ty: &LogicalType) -> usize {
606    match ty {
607        LogicalType::Varchar | LogicalType::Blob => 64,
608        LogicalType::BigInt
609        | LogicalType::UBigInt
610        | LogicalType::Timestamp
611        | LogicalType::Double
612        | LogicalType::Decimal { .. } => 8,
613        LogicalType::Integer | LogicalType::UInteger | LogicalType::Date | LogicalType::Float => 4,
614        LogicalType::SmallInt | LogicalType::USmallInt => 2,
615        _ => 1,
616    }
617}
618
619/// Parts in one stripe.
620///
621/// Sixty four thousand rows is the smallest stripe that keeps the ClickBench directory in single
622/// digit megabytes at a hundred million rows, and it puts a four byte column's page at a quarter of
623/// a megabyte, which is the size a sequential read wants. Larger stripes buy a smaller directory
624/// and cost a sparse fetch, which has to read a page index before it can reach one part.
625pub const STRIPE_PARTS: usize = 64;
626
627/// Bytes one part takes in a stripe's index page: four for the length, eight for the checksum.
628const INDEX_ENTRY: usize = size_of::<u32>() + size_of::<u64>();
629
630/// Bytes one column's section of a stripe's index page takes, including its own trailing checksum.
631fn index_section(parts: usize) -> Result<usize> {
632    parts
633        .checked_mul(INDEX_ENTRY)
634        .and_then(|bytes| bytes.checked_add(size_of::<u64>()))
635        .ok_or_else(|| invalid("index page length overflow"))
636}
637
638impl Writer {
639    /// Creates a new v10 file and its first table.
640    ///
641    /// # Errors
642    ///
643    /// If the file exists, a field has no scalar encoding, or the path cannot be written.
644    pub fn create(
645        path: impl AsRef<Path>,
646        name: impl Into<String>,
647        fields: Vec<Field>,
648    ) -> Result<Self> {
649        for field in &fields {
650            type_tag(&field.ty)?;
651        }
652        let file =
653            OpenOptions::new().write(true).read(true).create_new(true).open(path).map_err(io)?;
654        let mut header = [0; HEADER as usize];
655        header[..8].copy_from_slice(MAGIC);
656        header[8..12].copy_from_slice(&FORMAT.to_le_bytes());
657        write_at(&file, 0, &header)?;
658        Ok(Self {
659            file,
660            at: HEADER,
661            dictionaries: fields
662                .iter()
663                .map(|field| (field.ty == LogicalType::Varchar).then(GlobalDictionary::new))
664                .collect(),
665            table: Table {
666                name: name.into(),
667                dictionaries: vec![None; fields.len()],
668                distincts: vec![None; fields.len()],
669                fields,
670                stripes: Vec::new(),
671                rows: 0,
672                frequencies: Vec::new(),
673            },
674            generation: 1,
675            order: Vec::new(),
676            next_order: 0,
677            pending: Vec::with_capacity(STRIPE_PARTS),
678        })
679    }
680
681    /// Appends bytes at the end of the file and moves the writer's own offset past them.
682    ///
683    /// Every write in here goes through this, so that [`Writer::at`] is the only answer to where
684    /// anything is and the file's cursor is never consulted for it.
685    fn put(&mut self, bytes: &[u8]) -> Result<()> {
686        write_at(&self.file, self.at, bytes)?;
687        self.at = self
688            .at
689            .checked_add(bytes.len() as u64)
690            .ok_or_else(|| invalid("native file length overflow"))?;
691        Ok(())
692    }
693
694    /// Writes one chunk as independently readable column pages.
695    ///
696    /// # Errors
697    ///
698    /// If its width or types differ from the declared table, or a page exceeds its bound.
699    pub fn append(&mut self, chunk: &Chunk) -> Result<()> {
700        let order = (self.next_order, 0);
701        self.next_order = self.next_order.saturating_add(1);
702        self.append_at(order, chunk)
703    }
704
705    /// Writes one chunk and records its source position for directory ordering.
706    ///
707    /// Pages may be encoded by parallel pipeline instances and reach the file in completion order.
708    /// The stripe they land in is sorted by this key at commit, and [`Self::finish`] rejects a
709    /// sequence whose parts do not come out in source order once the stripes are sorted, because a
710    /// stripe groups whatever arrived together and cannot put a late part back where it belongs.
711    ///
712    /// # Errors
713    ///
714    /// The same as [`Self::append`].
715    pub fn append_at(&mut self, order: (u64, u64), chunk: &Chunk) -> Result<()> {
716        if chunk.is_empty() {
717            return Ok(());
718        }
719        self.admit(chunk)?;
720        if self.pending.last().is_some_and(|last| last.order > order) {
721            self.flush_pending()?;
722        }
723        // Cloned rather than encoded, and a clone of a chunk that owns its buffers is a copy of
724        // them. Sixty four parts of a hundred and five columns is tens of megabytes held for the
725        // length of a stripe and a few seconds of memory traffic over a whole ClickBench load,
726        // against the hundreds of seconds of encode this is what lets off one thread.
727        self.pending.push(PendingChunk { order, chunk: chunk.clone() });
728        if self.pending.len() == STRIPE_PARTS {
729            self.flush_pending()?;
730        }
731        Ok(())
732    }
733
734    /// Writes a run of chunks as one stripe of its own.
735    ///
736    /// [`Self::append_at`] decides where a stripe ends by watching the orders go past, which works
737    /// when one caller hands over every chunk in source order and does not when several do. A
738    /// writer being fed by more than one pipeline instance sees the orders interleave, and a stripe
739    /// that ends every time two of them cross is a stripe of one or two parts.
740    ///
741    /// So the grouping moves to the caller. Whoever is buffering hands over a run it already knows
742    /// is contiguous and in order, and gets a stripe holding exactly that run. The orders still
743    /// have to come out in source order once the stripes are sorted, which [`Self::finish`] checks,
744    /// so the runs from different callers may interleave with each other but may not overlap.
745    ///
746    /// # Errors
747    ///
748    /// The same as [`Self::append`], and if the run is longer than [`STRIPE_PARTS`].
749    pub fn append_stripe(&mut self, parts: Vec<((u64, u64), Chunk)>) -> Result<()> {
750        if parts.len() > STRIPE_PARTS {
751            return Err(invalid("a stripe was handed more parts than it holds"));
752        }
753        // Whatever an earlier caller left behind is its own stripe rather than the front of this
754        // one, because the two runs are from different places in the source and a stripe is a run.
755        self.flush_pending()?;
756        for (order, chunk) in parts {
757            if chunk.is_empty() {
758                continue;
759            }
760            self.admit(&chunk)?;
761            self.pending.push(PendingChunk { order, chunk });
762        }
763        self.flush_pending()
764    }
765
766    /// Checks a chunk against the declared table and counts its rows in.
767    fn admit(&mut self, chunk: &Chunk) -> Result<()> {
768        if chunk.width() != self.table.fields.len() {
769            return Err(invalid("chunk width differs from table schema"));
770        }
771        for (index, field) in self.table.fields.iter().enumerate() {
772            if chunk.column(index)?.logical_type() != &field.ty {
773                return Err(invalid("chunk type differs from table schema"));
774            }
775        }
776        self.table.rows = self
777            .table
778            .rows
779            .checked_add(chunk.len())
780            .ok_or_else(|| invalid("row count overflow"))?;
781        Ok(())
782    }
783
784    /// Encodes one column's parts of a stripe, with the column's dictionary to itself.
785    ///
786    /// Nothing here is shared with another column. The dictionary belongs to this one, the sieve
787    /// reads only this one, and the page bytes go in a vector of this one's own. That is why the
788    /// fan out below can hand a whole column to a thread and take a plain `&mut` on the dictionary
789    /// rather than making it something several threads can grow at once, which is the harder half
790    /// of #808 and is still open.
791    fn encode_column(
792        index: usize,
793        held: &[PendingChunk],
794        mut dictionary: Option<&mut GlobalDictionary>,
795    ) -> Result<ColumnStripe> {
796        let mut stripe = ColumnStripe {
797            pages: Vec::with_capacity(held.len()),
798            codes: Vec::with_capacity(held.len()),
799            sieves: Vec::with_capacity(held.len()),
800            ranges: Vec::with_capacity(held.len()),
801        };
802        for pending in held {
803            let column = pending.chunk.column(index)?;
804            let (bytes, unique) = encode(column, dictionary.as_deref_mut())?;
805            if bytes.len() > MAX_PAGE {
806                return Err(invalid("column page exceeds the configured bound"));
807            }
808            // The range is built first because the sieve reads it rather than walking the column a
809            // second time to find out how wide it is.
810            let range = Range::of(column);
811            // A column with a global dictionary already has an exact membership index per stripe,
812            // so an approximate one beside it would cost a hash of every string in the table to
813            // answer a question that is already answered. What it would buy is the finer grain, a
814            // part rather than a stripe, and that is worth coming back for on its own.
815            //
816            // A sieve at least as large as the part it indexes is not written. A reader reads the
817            // sieve to decide whether to read the part, so when the sieve is the larger of the two
818            // it has already spent more than the read it is trying to avoid, and that holds even if
819            // it rejects every time. It is a necessary condition rather than the whole rule, which
820            // is that a sieve pays when its bytes are under the rejection rate times the part's,
821            // but the rejection rate depends on what a query probes for and the writer does not
822            // know that. The necessary half needs two numbers that are both in hand here.
823            let sieve = match dictionary {
824                Some(_) => None,
825                None => Sieve::of(column, &range, SIEVE_BUDGET)
826                    .filter(|sieve| sieve.len() < bytes.len()),
827            };
828            stripe.pages.push(bytes);
829            stripe.codes.push(unique);
830            stripe.sieves.push(sieve);
831            stripe.ranges.push(range);
832        }
833        Ok(stripe)
834    }
835
836    /// Encodes a whole stripe, one column to a worker.
837    ///
838    /// The columns are handed out through a queue rather than dealt in equal piles, because they
839    /// are nothing like equal: `URL` on ClickBench is a global dictionary of sixty one million
840    /// strings and `IsMobile` is a byte. A pile that happened to hold the four large string columns
841    /// would be the whole stripe and the other workers would be waiting on it. The queue is sorted
842    /// so the expensive ones are taken first, which is the classic answer to a last job that runs
843    /// longer than everything after it.
844    fn encode_columns(&mut self, held: &[PendingChunk]) -> Result<Vec<ColumnStripe>> {
845        let width = self.table.fields.len();
846        let workers = std::thread::available_parallelism()
847            .map_or(1, usize::from)
848            .min(MAX_ENCODE_WORKERS)
849            .min(width);
850        if workers <= 1 || held.len() <= 1 {
851            return self
852                .dictionaries
853                .iter_mut()
854                .enumerate()
855                .map(|(index, dictionary)| Self::encode_column(index, held, dictionary.as_mut()))
856                .collect();
857        }
858        // The dictionaries are moved out and back rather than borrowed, because a worker that takes
859        // the next column off a queue cannot be holding a borrow of the vector the queue came from.
860        let mut jobs: Vec<(usize, Option<GlobalDictionary>)> =
861            std::mem::take(&mut self.dictionaries).into_iter().enumerate().collect();
862        // Popped from the back, so the expensive columns go last in the vector.
863        jobs.sort_by_key(|(index, _)| weight(&self.table.fields[*index].ty));
864        let queue = Mutex::new(jobs);
865        let pieces = std::thread::scope(|scope| {
866            (0..workers)
867                .map(|_| {
868                    scope.spawn(|| {
869                        let mut mine = Vec::new();
870                        loop {
871                            let taken = queue
872                                .lock()
873                                .map_err(|_| Error::internal("a native encode worker panicked"))?
874                                .pop();
875                            let Some((index, mut dictionary)) = taken else { break };
876                            let encoded = Self::encode_column(index, held, dictionary.as_mut())?;
877                            mine.push((index, dictionary, encoded));
878                        }
879                        Ok(mine)
880                    })
881                })
882                .collect::<Vec<_>>()
883                .into_iter()
884                .map(|handle| {
885                    handle.join().map_err(|_| Error::internal("a native encode worker panicked"))?
886                })
887                .collect::<Result<Vec<_>>>()
888        })?;
889        let mut dictionaries: Vec<Option<GlobalDictionary>> = (0..width).map(|_| None).collect();
890        let mut encoded: Vec<Option<ColumnStripe>> = (0..width).map(|_| None).collect();
891        for piece in pieces {
892            for (index, dictionary, stripe) in piece {
893                dictionaries[index] = dictionary;
894                encoded[index] = Some(stripe);
895            }
896        }
897        self.dictionaries = dictionaries;
898        encoded
899            .into_iter()
900            .map(|stripe| stripe.ok_or_else(|| Error::internal("a column was never encoded")))
901            .collect()
902    }
903
904    /// Writes the buffered parts as one stripe, each column's parts contiguous on disk.
905    fn flush_pending(&mut self) -> Result<()> {
906        if self.pending.is_empty() {
907            return Ok(());
908        }
909        let width = self.table.fields.len();
910        // Held here rather than read off the writer, because writing a page needs the writer and
911        // the borrow checker is right that those are two different uses of it.
912        let mut held = std::mem::take(&mut self.pending);
913        let parts = held.len();
914        let encoded = self.encode_columns(&held)?;
915        let mut pages = Vec::with_capacity(width);
916        let mut memberships = vec![None; width];
917        let mut ranges = Vec::with_capacity(width);
918        let mut index = Vec::with_capacity(width.saturating_mul(index_section(parts)?));
919        for stripe in &encoded {
920            let offset = self.at;
921            let section = index.len();
922            let mut length = 0_usize;
923            for bytes in &stripe.pages {
924                write_at(&self.file, self.at + length as u64, bytes)?;
925                put_u32(
926                    &mut index,
927                    u32::try_from(bytes.len()).map_err(|_| invalid("part length overflow"))?,
928                );
929                put_u64(&mut index, checksum(bytes));
930                length = length
931                    .checked_add(bytes.len())
932                    .ok_or_else(|| invalid("column page length overflow"))?;
933            }
934            let hash = checksum(&index[section..]);
935            put_u64(&mut index, hash);
936            if length > MAX_PAGE {
937                return Err(invalid("column page exceeds the configured bound"));
938            }
939            self.at = self
940                .at
941                .checked_add(length as u64)
942                .ok_or_else(|| invalid("native file length overflow"))?;
943            pages.push(Span {
944                offset,
945                length: u32::try_from(length).map_err(|_| invalid("page length overflow"))?,
946            });
947            ranges.push(merged_range(stripe.ranges.iter().cloned()));
948        }
949        for (membership, stripe) in memberships.iter_mut().zip(&encoded) {
950            if stripe.codes.iter().all(Option::is_none) {
951                continue;
952            }
953            let lists = stripe
954                .codes
955                .iter()
956                .map(|codes| codes.clone().unwrap_or_default())
957                .collect::<Vec<_>>();
958            let bytes = encode_membership(&merged_codes(lists));
959            let offset = self.at;
960            self.put(&bytes)?;
961            *membership = Some(Page {
962                offset,
963                length: u32::try_from(bytes.len())
964                    .map_err(|_| invalid("membership page length overflow"))?,
965                hash: checksum(&bytes),
966            });
967        }
968        let mut sieves = vec![None; width];
969        for (page, stripe) in sieves.iter_mut().zip(&encoded) {
970            if stripe.sieves.iter().all(Option::is_none) {
971                continue;
972            }
973            let bytes = encode_sieves(stripe.sieves.iter())?;
974            let offset = self.at;
975            self.put(&bytes)?;
976            *page = Some(Page {
977                offset,
978                length: u32::try_from(bytes.len())
979                    .map_err(|_| invalid("sieve page length overflow"))?,
980                hash: checksum(&bytes),
981            });
982        }
983        // A stripe of one part has the same rows in it as that part, so its own bounds are already
984        // the part's and a page here would say what the directory says. Everywhere else the page is
985        // written unless it comes to more than the column it indexes, which is the rule the sieves
986        // go by and for the same reason: a reader reads this to decide whether to read the column,
987        // so a page larger than the column has spent more than the read it is avoiding.
988        let mut part_ranges = vec![None; width];
989        if parts > 1 {
990            for ((page, stripe), span) in part_ranges.iter_mut().zip(&encoded).zip(&pages) {
991                let bytes = encode_part_ranges(&stripe.ranges)?;
992                if bytes.len() >= span.length as usize {
993                    continue;
994                }
995                let offset = self.at;
996                self.put(&bytes)?;
997                *page = Some(Page {
998                    offset,
999                    length: u32::try_from(bytes.len())
1000                        .map_err(|_| invalid("part range page length overflow"))?,
1001                    hash: checksum(&bytes),
1002                });
1003            }
1004        }
1005        let offset = self.at;
1006        self.put(&index)?;
1007        let index = Span {
1008            offset,
1009            length: u32::try_from(index.len())
1010                .map_err(|_| invalid("index page length overflow"))?,
1011        };
1012        let mut rows = 0_usize;
1013        let mut lengths = Vec::with_capacity(parts);
1014        let mut span = None;
1015        for pending in held.drain(..) {
1016            let part = pending.chunk.len();
1017            rows = rows.checked_add(part).ok_or_else(|| invalid("row count overflow"))?;
1018            lengths.push(u32::try_from(part).map_err(|_| invalid("part row count overflow"))?);
1019            span = Some(
1020                span.map_or((pending.order, pending.order), |(first, _)| (first, pending.order)),
1021            );
1022        }
1023        self.order.push(span.ok_or_else(|| invalid("a stripe was flushed with no parts"))?);
1024        self.table.stripes.push(Stripe {
1025            rows,
1026            parts: lengths,
1027            index,
1028            pages,
1029            memberships,
1030            sieves,
1031            part_ranges,
1032            zone: Zone::from_ranges(ranges),
1033        });
1034        // Back where it came from, empty, so the next stripe buffers into the same allocation.
1035        self.pending = held;
1036        Ok(())
1037    }
1038
1039    /// Finds exact heavy hitters without keeping a hash table for every numeric column while the
1040    /// load is live. The pages are already in the target file, so one column at a time uses a
1041    /// bounded Misra-Gries candidate table and then recounts only those candidates.
1042    fn numeric_frequency(&self, column: usize) -> Result<Option<FrequencySummary>> {
1043        let ty = &self.table.fields[column].ty;
1044        if !matches!(
1045            ty,
1046            LogicalType::TinyInt
1047                | LogicalType::SmallInt
1048                | LogicalType::Integer
1049                | LogicalType::BigInt
1050                | LogicalType::UTinyInt
1051                | LogicalType::USmallInt
1052                | LogicalType::UInteger
1053                | LogicalType::UBigInt
1054                | LogicalType::Date
1055                | LogicalType::Timestamp
1056        ) {
1057            return Ok(None);
1058        }
1059        let mut candidates: HashMap<FrequencyValue, u32> = HashMap::new();
1060        let mut decrements = 0_u64;
1061        self.visit_numeric(column, |_, value| {
1062            if let Some(count) = candidates.get_mut(&value) {
1063                *count = count.saturating_add(1);
1064            } else if candidates.len() < FREQUENCY_CANDIDATES {
1065                candidates.insert(value, 1);
1066            } else {
1067                candidates.retain(|_, count| {
1068                    *count -= 1;
1069                    *count != 0
1070                });
1071                decrements = decrements.saturating_add(1);
1072            }
1073        })?;
1074        let (exact, ordinals) = if decrements == 0 {
1075            (
1076                candidates
1077                    .into_iter()
1078                    .map(|(value, count)| (value, u64::from(count)))
1079                    .collect::<HashMap<_, _>>(),
1080                Vec::new(),
1081            )
1082        } else {
1083            let mut lower = candidates.values().copied().collect::<Vec<_>>();
1084            lower.sort_unstable_by(|left, right| right.cmp(left));
1085            if lower.len() < FREQUENCY_BUILD_RANK
1086                || u64::from(lower[FREQUENCY_BUILD_RANK - 1]) <= decrements
1087            {
1088                return Ok(None);
1089            }
1090            let mut exact =
1091                candidates.into_keys().map(|value| (value, 0_u64)).collect::<HashMap<_, _>>();
1092            let mut ordinals = Vec::new();
1093            let mut exceeded = false;
1094            self.visit_numeric(column, |ordinal, value| {
1095                if let Some(count) = exact.get_mut(&value) {
1096                    *count = count.saturating_add(1);
1097                    if !exceeded {
1098                        if ordinals.len() < FREQUENCY_ORDINALS {
1099                            ordinals.push(ordinal);
1100                        } else {
1101                            ordinals.clear();
1102                            exceeded = true;
1103                        }
1104                    }
1105                }
1106            })?;
1107            (exact, ordinals)
1108        };
1109        let mut entries = exact
1110            .into_iter()
1111            .map(|(value, count)| FrequencyEntry { value, count })
1112            .collect::<Vec<_>>();
1113        entries.sort_unstable_by(|left, right| {
1114            right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
1115        });
1116        let omitted_max =
1117            entries.get(FREQUENCY_ENTRIES).map_or(decrements, |entry| decrements.max(entry.count));
1118        entries.truncate(FREQUENCY_ENTRIES);
1119        Ok(Some(FrequencySummary { entries, omitted_max, ordinals }))
1120    }
1121
1122    fn visit_numeric(
1123        &self,
1124        column: usize,
1125        mut visit: impl FnMut(u64, FrequencyValue),
1126    ) -> Result<()> {
1127        let ty = &self.table.fields[column].ty;
1128        let mut start = 0_u64;
1129        for stripe in &self.table.stripes {
1130            let spans = read_index(&self.file, stripe, column)?;
1131            let page = stripe.pages[column];
1132            let mut bytes = vec![0; page.length as usize];
1133            read_at(&self.file, page.offset, &mut bytes)?;
1134            for (span, &rows) in spans.iter().zip(&stripe.parts) {
1135                let part = part_bytes(&bytes, *span)?;
1136                if checksum(part) != span.hash {
1137                    return Err(invalid("column page checksum differs while building frequencies"));
1138                }
1139                let rows = rows as usize;
1140                let vector = decode(ty, rows, part, None)?;
1141                // row at a time: frequency construction visits decoded values to update bounded candidates.
1142                for row in 0..rows {
1143                    let value = if vector.is_null_at(row) {
1144                        FrequencyValue::Null
1145                    } else {
1146                        // An unsigned column has no signed reading, and the documented fallback is
1147                        // the value itself. Every unsigned width the format stores fits in the
1148                        // `i128` a candidate is keyed by, so nothing is lost on the way through.
1149                        let widened = match vector.signed_at(row) {
1150                            Some(value) => Some(value),
1151                            None => match vector.value_at(row) {
1152                                Value::UTinyInt(value) => Some(i128::from(value)),
1153                                Value::USmallInt(value) => Some(i128::from(value)),
1154                                Value::UInteger(value) => Some(i128::from(value)),
1155                                Value::UBigInt(value) => Some(i128::from(value)),
1156                                _ => None,
1157                            },
1158                        };
1159                        FrequencyValue::Integer(widened.ok_or_else(|| {
1160                            invalid("numeric frequency page did not contain an integer value")
1161                        })?)
1162                    };
1163                    visit(start.saturating_add(row as u64), value);
1164                }
1165                start = start.saturating_add(rows as u64);
1166            }
1167        }
1168        Ok(())
1169    }
1170
1171    /// Builds independent numeric synopses concurrently after all column pages are committed.
1172    ///
1173    /// The columns go through a queue rather than being cut into equal runs, because they are not
1174    /// equally expensive and they are not shuffled. A `BIGINT` column carries eight times the bytes
1175    /// of a `TINYINT` through the decode, and a run of them sits together in a schema the way it
1176    /// sits together in `hits`, so a worker that was handed the wrong six columns finishes long
1177    /// after one that was handed the right six and the whole phase waits for it.
1178    fn numeric_frequencies(&self) -> Result<Vec<Option<FrequencySummary>>> {
1179        let mut columns = self
1180            .table
1181            .fields
1182            .iter()
1183            .enumerate()
1184            .filter_map(|(column, field)| {
1185                matches!(
1186                    field.ty,
1187                    LogicalType::TinyInt
1188                        | LogicalType::SmallInt
1189                        | LogicalType::Integer
1190                        | LogicalType::BigInt
1191                        | LogicalType::UTinyInt
1192                        | LogicalType::USmallInt
1193                        | LogicalType::UInteger
1194                        | LogicalType::UBigInt
1195                        | LogicalType::Date
1196                        | LogicalType::Timestamp
1197                )
1198                .then_some(column)
1199            })
1200            .collect::<Vec<_>>();
1201        let workers = std::thread::available_parallelism()
1202            .map_or(1, usize::from)
1203            .min(MAX_FREQUENCY_WORKERS)
1204            .min(columns.len());
1205        if workers <= 1 {
1206            let mut frequencies = vec![None; self.table.fields.len()];
1207            for column in columns {
1208                frequencies[column] = self.numeric_frequency(column)?;
1209            }
1210            return Ok(frequencies);
1211        }
1212        // Popped from the back, so the expensive columns are the ones taken first and the cheap ones
1213        // are what is left to fill in behind them.
1214        columns.sort_by_key(|&column| weight(&self.table.fields[column].ty));
1215        let queue = Mutex::new(columns);
1216        let pieces = std::thread::scope(|scope| {
1217            (0..workers)
1218                .map(|_| {
1219                    scope.spawn(|| {
1220                        let mut mine = Vec::new();
1221                        loop {
1222                            let taken = queue
1223                                .lock()
1224                                .map_err(|_| Error::internal("a native frequency worker panicked"))?
1225                                .pop();
1226                            let Some(column) = taken else { break };
1227                            mine.push((column, self.numeric_frequency(column)?));
1228                        }
1229                        Ok(mine)
1230                    })
1231                })
1232                .collect::<Vec<_>>()
1233                .into_iter()
1234                .map(|handle| {
1235                    handle
1236                        .join()
1237                        .map_err(|_| Error::internal("a native frequency worker panicked"))?
1238                })
1239                .collect::<Result<Vec<_>>>()
1240        })?;
1241        let mut frequencies = vec![None; self.table.fields.len()];
1242        for piece in pieces {
1243            for (column, summary) in piece {
1244                frequencies[column] = summary;
1245            }
1246        }
1247        Ok(frequencies)
1248    }
1249
1250    /// Commits the directory and syncs the file before publishing its header slot.
1251    ///
1252    /// # Errors
1253    ///
1254    /// If directory encoding, writing, or syncing fails.
1255    pub fn finish(mut self) -> Result<Table> {
1256        self.flush_pending()?;
1257        let mut stripes = std::mem::take(&mut self.order)
1258            .into_iter()
1259            .zip(std::mem::take(&mut self.table.stripes))
1260            .collect::<Vec<_>>();
1261        stripes.sort_by_key(|(order, _)| order.0);
1262        let mut previous: Option<(u64, u64)> = None;
1263        for ((first, last), _) in &stripes {
1264            if previous.is_some_and(|previous| previous >= *first) {
1265                return Err(invalid("chunks did not arrive in source order"));
1266            }
1267            previous = Some(*last);
1268        }
1269        self.table.stripes = stripes.into_iter().map(|(_, stripe)| stripe).collect();
1270        self.table.frequencies = self.numeric_frequencies()?;
1271        let dictionaries = std::mem::take(&mut self.dictionaries);
1272        let orders = rankings(&dictionaries)?;
1273        for (index, (dictionary, order)) in dictionaries.into_iter().zip(orders).enumerate() {
1274            let Some(dictionary) = dictionary else { continue };
1275            // A code nothing counted is a code no non-null row of this column holds, which is the
1276            // empty string a null was written as and nothing else, because a code is only ever made
1277            // by a row asking for one.
1278            self.table.distincts[index] =
1279                Some(dictionary.counts.iter().filter(|count| **count != 0).count() as u64);
1280            self.table.frequencies[index] = Some(code_frequency(&dictionary));
1281            let encoded = encode_global_dictionary(dictionary, &order)?;
1282            let offset = self.at;
1283            self.put(&encoded.index)?;
1284            self.put(&encoded.ranks)?;
1285            for block in &encoded.payload {
1286                self.put(block)?;
1287            }
1288            let payload_len =
1289                encoded.payload.iter().try_fold(0_usize, |len, block| len.checked_add(block.len()));
1290            let length = payload_len
1291                .and_then(|len| len.checked_add(encoded.index.len()))
1292                .and_then(|len| len.checked_add(encoded.ranks.len()))
1293                .ok_or_else(|| invalid("dictionary page length overflow"))?;
1294            self.table.dictionaries[index] = Some(Page {
1295                offset,
1296                length: u32::try_from(length)
1297                    .map_err(|_| invalid("dictionary page length overflow"))?,
1298                hash: checksum(&encoded.index),
1299            });
1300        }
1301        let directory = encode_directory(&self.table)?;
1302        if directory.len() > MAX_DIRECTORY {
1303            return Err(invalid("directory exceeds the configured bound"));
1304        }
1305        let offset = self.at;
1306        self.put(&directory)?;
1307        self.file.sync_all().map_err(io)?;
1308        let slot = Slot {
1309            offset,
1310            length: u32::try_from(directory.len())
1311                .map_err(|_| invalid("directory length overflow"))?,
1312            generation: self.generation,
1313            hash: checksum(&directory),
1314        };
1315        // The one write that is not an append, and the last one. It goes back over the slot in the
1316        // header, so it names its offset rather than going through `put`, and `at` does not move.
1317        write_at(&self.file, 16, &slot.bytes())?;
1318        self.file.sync_all().map_err(io)?;
1319        Ok(self.table)
1320    }
1321}
1322
1323/// Reads committed native column pages without holding the table in memory.
1324#[derive(Debug, Clone)]
1325pub struct Reader {
1326    file: Arc<File>,
1327    table: Arc<Table>,
1328    dictionaries: Arc<Vec<OnceLock<Arc<Vector>>>>,
1329    /// Held while a global dictionary is being opened, one per column.
1330    ///
1331    /// The [`OnceLock`] above says whether one has been opened, which is the question a reader that
1332    /// already has it needs answered and is free. It does not say whether one is being opened, and
1333    /// the difference matters because every worker of a scan wants the same dictionary at the same
1334    /// moment. Without this they all miss, all read the page, all verify it and all decode it, and
1335    /// all but one throw the answer away. ClickBench 38 reads the URL dictionary, which is 515,958
1336    /// entries, and was paying for it twice.
1337    loading: Arc<Vec<Mutex<()>>>,
1338    /// How many global dictionaries have been opened. A scan of a dictionary column should open its
1339    /// dictionary once however many workers it has, and the test that says so is the only thing
1340    /// keeping it that way.
1341    opened: Arc<AtomicUsize>,
1342    /// The membership sieves of one stripe of one column, by column and then by stripe, read the
1343    /// first time a probe asks about them. A query filters on one or two columns and never looks at
1344    /// the rest, so reading these at open would be the whole index for the sake of a fraction of it.
1345    sieves: Arc<Vec<Vec<SieveSlot>>>,
1346    /// The per part ranges of one stripe of one column, by column and then by stripe, read the
1347    /// first time something compares that column and kept after that.
1348    part_ranges: Arc<Vec<Vec<RangeSlot>>>,
1349    /// Which stripe and which part of it every part of the table is, by table wide part number.
1350    places: Arc<Vec<Place>>,
1351    cache: Arc<Vec<Mutex<Cached>>>,
1352    /// How many whole stripe pages have been read, which is what the sharing above is judged on. A
1353    /// scan of a column should read each of its stripes once however many workers it has.
1354    pages: Arc<AtomicUsize>,
1355    /// How many index sections have been read. A scan of a column should read each of its stripes
1356    /// once here too, and the test that says so is the only thing keeping it that way.
1357    indexes: Arc<AtomicUsize>,
1358    /// How many stripes of one column the page cache keeps. See [`CACHED_STRIPES_PER_COLUMN`] for
1359    /// what sets it and [`Reader::keep_stripes`] for who raises it.
1360    kept: Arc<AtomicUsize>,
1361    /// The file's size when it was opened, for [`Reader::layout`].
1362    size: u64,
1363    /// The committed directory's size, for [`Reader::layout`].
1364    directory: u64,
1365    /// What opening the file cost, which is a number rather than a claim.
1366    opening: Opening,
1367}
1368
1369/// What [`Reader::open`] read before it returned.
1370///
1371/// `spec/stats/04-in-memory.md` section 4.2 says opening a table reads the header and the directory
1372/// and nothing else, and once that document's statistics are in the file the tempting change is to
1373/// load a column summary or two on the way past, because they are small and the next query will
1374/// want them. A hundred milliseconds of that is a hundred milliseconds nobody asked for, and an
1375/// embedded database is opened by processes that are about to run one trivial query.
1376///
1377/// So the claim gets a number. Both of these are fixed by the schema and the stripe count and are
1378/// independent of how many rows the file holds, and the test that says so is what stops the
1379/// tempting change from landing quietly.
1380#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1381pub struct Opening {
1382    /// How many times the file was read. The header, then each directory slot that looked valid
1383    /// enough to check, so three at the most.
1384    pub reads: u32,
1385    /// How many bytes those reads asked for.
1386    pub bytes: u64,
1387}
1388
1389/// What a reader has read, while it was being opened and since.
1390#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1391pub struct Reads {
1392    /// What opening cost, before any query had been planned.
1393    pub opening: Opening,
1394    /// Whole stripe pages read since.
1395    pub pages: usize,
1396    /// Index sections read since.
1397    pub indexes: usize,
1398    /// Global dictionaries opened since. One per dictionary column that a query touched, however
1399    /// many workers touched it, which is a claim only a test can keep true.
1400    pub dictionaries: usize,
1401}
1402
1403/// Where one table wide part number lands.
1404#[derive(Debug, Clone, Copy)]
1405struct Place {
1406    stripe: u32,
1407    part: u32,
1408    rows: u32,
1409}
1410
1411/// One part's bytes inside one column page.
1412#[derive(Debug, Clone, Copy)]
1413struct PartSpan {
1414    start: usize,
1415    length: usize,
1416    hash: u64,
1417}
1418
1419/// What a reader holds for one stripe of one column.
1420///
1421/// The index is small and is loaded whether the caller wants the whole page or one part of it. The
1422/// page is loaded only by a scan, because a sparse fetch that wants a thousand rows out of sixty
1423/// four thousand would be reading sixty four times what it uses.
1424#[derive(Debug, Clone)]
1425struct CachedColumn {
1426    stripe: usize,
1427    index: Arc<Vec<PartSpan>>,
1428    page: Option<Arc<Vec<u8>>>,
1429}
1430
1431/// One column's stripes a reader holds, and which of them somebody is reading right now.
1432///
1433/// The pages are one slot per stripe of the table rather than a list of the ones being kept, so
1434/// finding a page is an index and not a walk. That matters because the walk happened under the
1435/// lock, once per part per column, and a scan that gives a whole stripe to each of thirty two
1436/// workers keeps enough pages that walking them was the longest thing the lock was held for. The
1437/// slots cost a pointer per stripe per column, which on the ClickBench file is eight kilobytes
1438/// against the forty megabytes of pages they point at. `order` is which of them are filled, oldest
1439/// first, because that is the one thing the slots cannot say by themselves.
1440///
1441/// `loading` is what keeps a scan from reading the same page once per worker. It is a list and not
1442/// a set because it holds at most one stripe per worker on the column and is walked far less often
1443/// than a hash of it would be built.
1444///
1445/// `index` is every index this reader has ever read for the column, one slot per stripe, and it is
1446/// never evicted. An index is a few hundred bytes and a page is a quarter of a megabyte, so the two
1447/// do not belong under the same budget. Riding in the page cache meant a worker that came back to a
1448/// stripe after its page had been evicted read the index again with it, which on the full
1449/// ClickBench file was about thirteen hundred reads out of a hundred and fourteen thousand.
1450#[derive(Debug, Default)]
1451struct Cached {
1452    pages: Vec<Option<Arc<Vec<u8>>>>,
1453    order: VecDeque<usize>,
1454    loading: Vec<usize>,
1455    index: Vec<Option<Arc<Vec<PartSpan>>>>,
1456}
1457
1458/// Stripes of one column a reader keeps the bytes of, when nobody has asked for more.
1459///
1460/// This has to hold at least as many stripes as a column has workers in it at once, or the workers
1461/// evict each other's pages and read them again. Four is what a scan that hands parts out in order
1462/// needs, because then every worker is within a few parts of every other and at most a couple of
1463/// stripes are open at a time. A scan that hands a whole stripe to each worker has one stripe open
1464/// per worker for the length of that stripe, and it says so with [`Reader::keep_stripes`] rather
1465/// than paying for sixteen slots on every table that is read one part at a time.
1466///
1467/// It multiplies by the page size, which is a quarter of a megabyte for a four byte column, and by
1468/// the number of columns a query touches.
1469const CACHED_STRIPES_PER_COLUMN: usize = 4;
1470
1471/// The sieves of one stripe of one column, once somebody has asked for them.
1472type SieveSlot = OnceLock<Arc<Vec<Option<Sieve>>>>;
1473
1474type RangeSlot = OnceLock<Arc<Vec<Range>>>;
1475
1476#[derive(Debug)]
1477struct NativeText {
1478    file: Arc<File>,
1479    /// How many values the dictionary holds.
1480    values: usize,
1481    /// Where each value ends inside its payload block, packed at `offset_bits` in runs of
1482    /// [`TEXT_OFFSET_RUN`].
1483    ///
1484    /// Ends rather than starts, because then a block of 1,024 values is 1,024 numbers rather than
1485    /// 1,025: the start of a value is the end of the one before it, and the first value of a block
1486    /// starts at zero by construction. Relative to the block rather than to the payload, because a
1487    /// reader decodes a whole block and slices it, so an offset into the payload is a number it
1488    /// would have to subtract a base from anyway.
1489    offsets: Vec<u8>,
1490    /// Bits one offset is packed at, which is what the largest block of this column spans and is the
1491    /// same for every block of it.
1492    offset_bits: usize,
1493    /// How many entries the sorted order has, which is the value count.
1494    ranks: usize,
1495    /// Where the sorted order starts in the file. It is read a block at a time and only when
1496    /// something searches it, so a query that never compares this column against a literal never
1497    /// touches it at all.
1498    rank_at: u64,
1499    /// Where each block of the sorted order ends, as a byte offset from `rank_at`. A block is packed
1500    /// at whatever width its own heads need, so unlike the entries it replaced its length is not
1501    /// arithmetic on the block number.
1502    rank_ends: Vec<u64>,
1503    rank_hashes: Vec<u64>,
1504    rank_blocks: Vec<OnceLock<Result<Vec<u8>>>>,
1505    /// Bits one code is packed at, which is what the value count needs and is the same for every
1506    /// block of the column.
1507    code_bits: usize,
1508    /// The sorted order turned round, built the first time a reader asks for it.
1509    ///
1510    /// Four bytes per value against the four the offsets already hold, so a column that has this is
1511    /// carrying half again what it carried before rather than something of a new order. It is built
1512    /// only when something asks, which is a grouped min or max over this column and nothing else,
1513    /// and that reader was going to read the payload of this column once per row otherwise.
1514    code_ranks: OnceLock<Option<Vec<u32>>>,
1515    payload: u64,
1516    /// Where each block of the payload ends in the file, as a byte offset from `payload`. The
1517    /// blocks are stored back to back, so a block starts where the one before it ended.
1518    ends: Vec<u64>,
1519    hashes: Vec<u64>,
1520    /// The payload, read and decoded a block at a time and kept after that.
1521    blocks: Vec<OnceLock<Result<Vec<u8>>>>,
1522    /// How many decoded payload bytes this column keeps before a sweep stops keeping what it reads.
1523    /// [`TEXT_KEEP_BUDGET`] everywhere but in the test of the ceiling.
1524    keep_budget: usize,
1525    /// Roughly how many decoded payload bytes are being kept, which is what [`TEXT_KEEP_BUDGET`]
1526    /// is measured against.
1527    ///
1528    /// Roughly, because two threads that keep the same block at the same time both add its length
1529    /// while [`OnceLock`] keeps one of the two. That makes the count read high and the budget bind
1530    /// a little early, which is the harmless direction, and it costs one relaxed add a block rather
1531    /// than a lock on the path every scan of a string column goes through.
1532    payload_kept: AtomicUsize,
1533}
1534
1535/// How many values of a dictionary go in one block of the payload.
1536///
1537/// The block is the unit the string cascade encodes, the unit a checksum covers, and the unit a
1538/// reader has to decode to get at a single value, so it is the one number the payload format turns
1539/// on. Blocking by values rather than by bytes is what keeps a value out of two blocks at once: the
1540/// block holding a code is `code / TEXT_PAYLOAD_VALUES` and nothing has to be stitched.
1541///
1542/// A probe on the five ClickBench columns that have a dictionary worth the name, written up on
1543/// #347, measured the ratio and the decode speed at 128, 256, 512, 1,024 and 4,096 values. Both get
1544/// better all the way up, because front coding and the LZ matcher have more to look back at and
1545/// because the per chunk setup is spread over more values. What stops it is the point read: a query
1546/// that wants ten values has to decode ten blocks, so the block is what a lookup costs. At 1,024
1547/// values a block is between 67 KB and 394 KB decoded across those five columns, and the ratios are
1548/// 2.3 to 4.5. Going up to 4,096 buys two to six percent more and makes a block as much as 1.5 MB.
1549/// Going down to 512 gives up five to nine percent.
1550const TEXT_PAYLOAD_VALUES: usize = 1024;
1551
1552/// How many decoded payload bytes one dictionary keeps before a sweep stops keeping what it reads.
1553///
1554/// A sweep of the whole dictionary decodes every block whatever it does, and the only question is
1555/// whether it hangs on to them. Keeping all of them is 4.2 GB on ClickBench `URL` at a hundred
1556/// million rows, which is what #997 was right to stop. Keeping none of them means the next query
1557/// asking the same thing decodes all of it again, and on the same column at a million rows that
1558/// took a `LIKE` from 2.7 ms to 16.2 ms, because the decode used to be paid once by a session and
1559/// is now paid by every statement in it. Neither end is the answer. A bound is.
1560///
1561/// So a sweep keeps what it decodes until the column is holding this much and decodes without
1562/// keeping after that. At a million rows the five ClickBench string columns decode to between 8 MB
1563/// and 85 MB, so they sit inside it and a repeated `LIKE` reads a decoded block rather than a
1564/// stored one. At a hundred million rows `URL` fills it and the rest of that column is read and
1565/// dropped, which is the old cost on the part that does not fit and none of the old footprint.
1566///
1567/// Two hundred and fifty six megabytes a column is a number and not a policy, and the policy is
1568/// what should replace it: this wants to be a buffer pool over the whole database, sized against
1569/// the memory limit the session was given, with the blocks of every column competing for it and the
1570/// least useful one evicted. That is F2 work. What is here is the part of it that can be written
1571/// without an eviction order, which is a ceiling.
1572const TEXT_KEEP_BUDGET: usize = 256 * 1024 * 1024;
1573
1574/// How many offsets go in one packed run.
1575///
1576/// A payload block holds 1,024 values and `bitpack::pack_tail` takes fewer than 1,024 at a time,
1577/// since a whole unit of that many belongs in the transposed layout instead. So the offsets of a
1578/// block go in two runs. Five hundred and twelve values at any width is a whole number of bytes, so
1579/// a run starts where a multiply says it does and nothing is padded.
1580const TEXT_OFFSET_RUN: usize = 512;
1581
1582/// Bytes at the front of a global dictionary index: the value count, the values a payload block
1583/// holds, the block count and the bits an offset is packed at.
1584const DICTIONARY_HEADER: usize = 16;
1585
1586/// How many entries of a dictionary's sorted order sit in one block that is read and checked as a
1587/// unit.
1588///
1589/// Five hundred and twelve entries is between two and three kilobytes on the ClickBench string
1590/// columns, which is well under a page. A binary search over half a million entries makes nineteen
1591/// probes, and the first ten land in ten different blocks while the last nine land in the one block
1592/// that holds the answer, so the whole search reads about thirty kilobytes of a megabyte of order. A
1593/// smaller block would save a little on the early probes, cost a checksum and an end list four times
1594/// as long, and give the heads less to share a base with. A larger one would read more than it uses
1595/// on every probe.
1596const TEXT_RANK_BLOCK: usize = 512;
1597
1598/// Bytes at the front of a rank block, which is the base of its heads and the width they are packed
1599/// at.
1600///
1601/// An entry used to be twelve bytes flat, eight for the head and four for the code, and on the five
1602/// ClickBench columns that have a dictionary worth the name that was 744 MB of a 12.2 GB file. Both
1603/// halves of it are nearly empty. The heads are the first eight bytes of the values in sorted order,
1604/// so a block of five hundred and twelve of them spans a tiny slice of the column, and on a column of
1605/// URLs they are all `http://w` and the block holds one distinct head. The codes are positions in a
1606/// dictionary of eighteen million, which is twenty five bits and not thirty two.
1607///
1608/// So a block now writes the smallest head in it, the bits the largest is above that, and the heads
1609/// and the codes packed at the width each needs. A block where every head agrees costs nine bytes
1610/// and the codes.
1611const RANK_BLOCK_HEADER: usize = size_of::<u64>() + 1;
1612
1613impl NativeText {
1614    /// One block of the payload, read and decoded the first time anything asks for a value in it.
1615    ///
1616    /// The bytes handed back are the values of the block laid end to end, which is what the offsets
1617    /// describe, so a caller slices it with the offsets it already has. Where the block sits in the
1618    /// file is the only thing the caller cannot work out for itself, because the stored form is
1619    /// shorter than the decoded one and by a different amount in every block.
1620    fn payload_block(&self, block: usize) -> Result<Option<&[u8]>> {
1621        let Some(slot) = self.blocks.get(block) else { return Ok(None) };
1622        let bytes = slot.get_or_init(|| self.decode_block(block)).as_ref().map_err(Clone::clone)?;
1623        Ok(Some(bytes.as_slice()))
1624    }
1625
1626    /// Reads and decodes one block of the payload, without deciding who keeps it.
1627    ///
1628    /// [`Self::payload_block`] keeps it forever, which is what a point read wants and what a walk
1629    /// of the whole dictionary must not do. Both call this and they differ in nothing else.
1630    fn decode_block(&self, block: usize) -> Result<Vec<u8>> {
1631        let start = if block == 0 { 0 } else { self.ends[block - 1] };
1632        let end = self.ends[block];
1633        let len = end
1634            .checked_sub(start)
1635            .ok_or_else(|| invalid("global dictionary block ends before it starts"))?;
1636        let mut stored = vec![
1637            0;
1638            usize::try_from(len).map_err(|_| invalid(
1639                "global dictionary block does not fit in memory"
1640            ))?
1641        ];
1642        read_at(&self.file, self.payload + start, &mut stored)?;
1643        if checksum(&stored) != self.hashes[block] {
1644            return Err(invalid("global dictionary payload checksum differs"));
1645        }
1646        let first = block * TEXT_PAYLOAD_VALUES;
1647        let last = (first + TEXT_PAYLOAD_VALUES).min(self.values);
1648        let want = self.end_within(last - 1)? as usize;
1649        let values = string::decode_flat(&stored)?;
1650        if values.len() != last - first {
1651            return Err(invalid("global dictionary block holds the wrong value count"));
1652        }
1653        let bytes = values.into_bytes();
1654        if bytes.len() != want {
1655            return Err(invalid("global dictionary block decodes to the wrong length"));
1656        }
1657        Ok(bytes)
1658    }
1659
1660    /// Where the value at `index` ends inside its payload block.
1661    fn end_within(&self, index: usize) -> Result<u32> {
1662        let run = index / TEXT_OFFSET_RUN;
1663        let bytes = self
1664            .offsets
1665            .get(run * TEXT_OFFSET_RUN / 8 * self.offset_bits..)
1666            .ok_or_else(|| invalid("global dictionary offsets are short"))?;
1667        let end = bitpack::tail_at(bytes, self.offset_bits, index % TEXT_OFFSET_RUN)
1668            .map_err(|_| invalid("global dictionary offsets are short"))?;
1669        u32::try_from(end).map_err(|_| invalid("global dictionary offset is past the payload"))
1670    }
1671
1672    /// Where every value in `first..last` ends inside its payload block, in one pass over the runs.
1673    ///
1674    /// [`Self::end_within`] answers for one value and pays for it twice over: it shifts a window to
1675    /// the bit the value starts at, and the copy that fills that window is a length the compiler does
1676    /// not know, so it is a call to `memcpy` rather than a load. A sweep asked for two of those per
1677    /// value, one for the end and one for the start that is the end before it, and on the ClickBench
1678    /// `URL` dictionary of eighteen million that was most of the half second a `LIKE` over it took.
1679    ///
1680    /// [`bitpack::unpack_tail`] walks the run instead, which makes the window a fixed sixteen bytes
1681    /// and so an unaligned load, and reads the bit position off a counter. A run is five hundred and
1682    /// twelve values and a block is two of them, so a block of a thousand and twenty four values
1683    /// costs two calls here and nothing per value.
1684    fn ends_within(&self, first: usize, last: usize) -> Result<Vec<u64>> {
1685        let mut ends = Vec::with_capacity(last.saturating_sub(first));
1686        let mut at = first;
1687        while at < last {
1688            let run = at / TEXT_OFFSET_RUN;
1689            let stop = ((run + 1) * TEXT_OFFSET_RUN).min(last);
1690            let held = self.values.saturating_sub(run * TEXT_OFFSET_RUN).min(TEXT_OFFSET_RUN);
1691            let bytes = self
1692                .offsets
1693                .get(run * TEXT_OFFSET_RUN / 8 * self.offset_bits..)
1694                .ok_or_else(|| invalid("global dictionary offsets are short"))?;
1695            let run_ends = bitpack::unpack_tail(bytes, self.offset_bits, held)
1696                .map_err(|_| invalid("global dictionary offsets are short"))?;
1697            let within = run_ends
1698                .get(at % TEXT_OFFSET_RUN..stop - run * TEXT_OFFSET_RUN)
1699                .ok_or_else(|| invalid("global dictionary offsets are short"))?;
1700            ends.extend_from_slice(within);
1701            at = stop;
1702        }
1703        Ok(ends)
1704    }
1705
1706    /// Where the value at `index` starts inside its payload block, which is where the value before
1707    /// it ended unless it is the first of the block.
1708    fn start_within(&self, index: usize) -> Result<u32> {
1709        if index % TEXT_PAYLOAD_VALUES == 0 { Ok(0) } else { self.end_within(index - 1) }
1710    }
1711
1712    /// Where the value at `index` starts and ends inside its payload block.
1713    fn span_within(&self, index: usize) -> Result<(u32, u32)> {
1714        let end = self.end_within(index)?;
1715        let start = self.start_within(index)?;
1716        if start > end {
1717            return Err(invalid("global dictionary value ends before it starts"));
1718        }
1719        Ok((start, end))
1720    }
1721
1722    /// The block of the sorted order that holds `rank`, and where in it that rank sits.
1723    ///
1724    /// The block is read from the file and checked against the hash the index carries for it the
1725    /// first time anything asks, and kept after that, the same way a payload block is. A search
1726    /// makes about as many probes as the order has bits, so the whole search reads a handful of
1727    /// these and never the rest.
1728    fn rank_parts(&self, rank: usize) -> Result<(&[u8], usize)> {
1729        let slot = self
1730            .rank_blocks
1731            .get(rank / TEXT_RANK_BLOCK)
1732            .ok_or_else(|| invalid("global dictionary rank is past the order"))?;
1733        let block = slot
1734            .get_or_init(|| {
1735                let which = rank / TEXT_RANK_BLOCK;
1736                let start = if which == 0 { 0 } else { self.rank_ends[which - 1] };
1737                let end = self.rank_ends[which];
1738                let mut bytes = vec![0; (end - start) as usize];
1739                read_at(&self.file, self.rank_at + start, &mut bytes)?;
1740                if checksum(&bytes)
1741                    != *self
1742                        .rank_hashes
1743                        .get(rank / TEXT_RANK_BLOCK)
1744                        .ok_or_else(|| invalid("global dictionary rank block has no checksum"))?
1745                {
1746                    return Err(invalid("global dictionary rank checksum differs"));
1747                }
1748                Ok(bytes)
1749            })
1750            .as_ref()
1751            .map_err(Clone::clone)?;
1752        Ok((block.as_slice(), rank % TEXT_RANK_BLOCK))
1753    }
1754
1755    /// The first eight bytes of the value at `rank`, as the integer a comparison reads.
1756    fn head_at(&self, rank: usize) -> Result<u64> {
1757        let (block, within) = self.rank_parts(rank)?;
1758        let (base, width, packed) = rank_heads(block)?;
1759        let above = bitpack::tail_at(packed, width, within)
1760            .map_err(|_| invalid("global dictionary rank block is short of heads"))?;
1761        Ok(base.wrapping_add(above))
1762    }
1763
1764    /// The packed codes of one rank block, which follow the heads on the next byte boundary.
1765    fn rank_codes<'block>(&self, block: &'block [u8], count: usize) -> Result<&'block [u8]> {
1766        let (_, width, packed) = rank_heads(block)?;
1767        packed
1768            .get(bitpack::tail_len(count, width)..)
1769            .ok_or_else(|| invalid("global dictionary rank block is short of codes"))
1770    }
1771
1772    /// How many entries the block holding `rank` has, which is a full block except at the end.
1773    fn rank_block_len(&self, rank: usize) -> usize {
1774        let first = rank / TEXT_RANK_BLOCK * TEXT_RANK_BLOCK;
1775        TEXT_RANK_BLOCK.min(self.ranks - first)
1776    }
1777}
1778
1779/// The base, the width and the packed bytes of one rank block's heads.
1780fn rank_heads(block: &[u8]) -> Result<(u64, usize, &[u8])> {
1781    let header = block
1782        .get(..RANK_BLOCK_HEADER)
1783        .ok_or_else(|| invalid("global dictionary rank block is short"))?;
1784    let base = u64::from_le_bytes(header[..8].try_into().expect("eight bytes"));
1785    let width = header[8] as usize;
1786    if width > 64 {
1787        return Err(invalid("global dictionary rank block packs heads past a word"));
1788    }
1789    Ok((base, width, &block[RANK_BLOCK_HEADER..]))
1790}
1791
1792/// Bits one offset of a dictionary takes, which is what its widest payload block spans.
1793///
1794/// One width for the whole column rather than one a block. A block is 1,024 values of the same
1795/// column, so the blocks of a column are within a factor of two of each other on every ClickBench
1796/// string column, and a width a block would save a fraction of a bit and cost a byte a block plus
1797/// the arithmetic that finds where a block starts.
1798fn offset_width(offsets: &[u32]) -> usize {
1799    let values = offsets.len() - 1;
1800    let mut span = 0;
1801    for first in (0..values).step_by(TEXT_PAYLOAD_VALUES) {
1802        let last = (first + TEXT_PAYLOAD_VALUES).min(values);
1803        span = span.max(offsets[last] - offsets[first]);
1804    }
1805    (u32::BITS - span.leading_zeros()) as usize
1806}
1807
1808/// How many bytes `values` offsets take at `bits`, which is what the reader has to know before it
1809/// has read any of them.
1810fn offset_bytes(values: usize, bits: usize) -> usize {
1811    let full = values / TEXT_OFFSET_RUN;
1812    let rest = values % TEXT_OFFSET_RUN;
1813    full * TEXT_OFFSET_RUN / 8 * bits + bitpack::tail_len(rest, bits)
1814}
1815
1816/// The end of every value within its payload block, packed a run at a time.
1817fn encode_offsets(offsets: &[u32], bits: usize, out: &mut Vec<u8>) -> Result<()> {
1818    let values = offsets.len() - 1;
1819    let mut run = Vec::with_capacity(TEXT_OFFSET_RUN);
1820    for first in (0..values).step_by(TEXT_OFFSET_RUN) {
1821        let last = (first + TEXT_OFFSET_RUN).min(values);
1822        let base = offsets[first / TEXT_PAYLOAD_VALUES * TEXT_PAYLOAD_VALUES];
1823        run.clear();
1824        run.extend((first..last).map(|value| u64::from(offsets[value + 1] - base)));
1825        bitpack::pack_tail(&run, bits, out)
1826            .map_err(|_| invalid("global dictionary offsets do not pack"))?;
1827    }
1828    Ok(())
1829}
1830
1831/// How many bits a code of a dictionary of `values` entries takes.
1832fn code_width(values: usize) -> usize {
1833    match u64::try_from(values).unwrap_or(u64::MAX) {
1834        0 | 1 => 0,
1835        last => (u64::BITS - (last - 1).leading_zeros()) as usize,
1836    }
1837}
1838
1839impl TextSource for NativeText {
1840    fn len(&self) -> usize {
1841        self.values
1842    }
1843
1844    fn bytes_at(&self, index: usize) -> Result<Option<&[u8]>> {
1845        if index >= self.values {
1846            return Ok(None);
1847        }
1848        let (start, end) = self.span_within(index)?;
1849        if start == end {
1850            return Ok(Some(&[]));
1851        }
1852        // A block holds a fixed number of values rather than a fixed number of bytes, so the value
1853        // is in one block and the offsets already say where in it.
1854        let block = index / TEXT_PAYLOAD_VALUES;
1855        let Some(bytes) = self.payload_block(block)? else { return Ok(None) };
1856        Ok(bytes.get(start as usize..end as usize))
1857    }
1858
1859    fn bytes_len_at(&self, index: usize) -> Result<Option<usize>> {
1860        if index >= self.values {
1861            return Ok(None);
1862        }
1863        let (start, end) = self.span_within(index)?;
1864        Ok(Some((end - start) as usize))
1865    }
1866
1867    /// The rest of the block holding `first`, decoded into a buffer that may die with the call.
1868    ///
1869    /// A block is the unit this format decodes, so a walk that wants every value is going to decode
1870    /// every block whatever it does. The question is whether it keeps them, and both answers are
1871    /// wrong on their own. [`Self::payload_block`] keeps every block it is asked for, so a reader
1872    /// that walked the whole dictionary through `bytes_at` ended up holding the whole dictionary
1873    /// decoded, 4.2 GB on ClickBench `URL`. Keeping none of them makes the next statement asking
1874    /// the same question decode all of it again, which on the same column at a million rows is a
1875    /// `LIKE` going from 2.7 ms to 16.2 ms.
1876    ///
1877    /// So a sweep keeps what it decodes while the column is under [`TEXT_KEEP_BUDGET`] and drops it
1878    /// after that. A block already in hand is used where it is there and costs nothing either way.
1879    fn sweep(
1880        &self,
1881        first: usize,
1882        limit: usize,
1883        body: &mut dyn FnMut(usize, &[u8]) -> Result<()>,
1884    ) -> Result<usize> {
1885        let limit = limit.min(self.values);
1886        if first >= limit {
1887            return Ok(first);
1888        }
1889        let block = first / TEXT_PAYLOAD_VALUES;
1890        let last = ((block + 1) * TEXT_PAYLOAD_VALUES).min(limit);
1891        let decoded;
1892        let bytes: &[u8] = match self.blocks.get(block).and_then(OnceLock::get) {
1893            Some(Ok(kept)) => kept,
1894            _ if self.payload_kept.load(Atomic::Relaxed) < self.keep_budget => {
1895                let kept = self
1896                    .payload_block(block)?
1897                    .ok_or_else(|| invalid("global dictionary block is past the payload"))?;
1898                self.payload_kept.fetch_add(kept.len(), Atomic::Relaxed);
1899                kept
1900            }
1901            _ => {
1902                decoded = self.decode_block(block)?;
1903                &decoded
1904            }
1905        };
1906        let ends = self.ends_within(first, last)?;
1907        if ends.len() != last - first {
1908            return Err(invalid("global dictionary offsets are short"));
1909        }
1910        let mut start = u64::from(self.start_within(first)?);
1911        // row at a time: the caller is handed one value after another, and what it does with one is
1912        // its own business, so there is no shape here for anything but a walk.
1913        for (index, &end) in (first..last).zip(&ends) {
1914            let value = usize::try_from(start)
1915                .ok()
1916                .zip(usize::try_from(end).ok())
1917                .and_then(|(from, to)| bytes.get(from..to))
1918                .ok_or_else(|| invalid("global dictionary value is past its block"))?;
1919            body(index, value)?;
1920            start = end;
1921        }
1922        Ok(last)
1923    }
1924
1925    fn ranks(&self) -> Option<usize> {
1926        (self.ranks > 0).then_some(self.ranks)
1927    }
1928
1929    fn compare_rank(&self, rank: usize, wanted: &[u8]) -> Result<Ordering> {
1930        // The head settles the probe unless the two values start with the same eight bytes, and
1931        // only then is a value read. On a column of URLs that is the difference between a search
1932        // that touches one block of the payload and a search that touches nineteen of them.
1933        let settled = self.head_at(rank)?.cmp(&head(wanted));
1934        if settled != Ordering::Equal {
1935            return Ok(settled);
1936        }
1937        let code = self.code_at_rank(rank)?;
1938        let bytes = self
1939            .bytes_at(code as usize)?
1940            .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
1941        Ok(bytes.cmp(wanted))
1942    }
1943
1944    fn code_at_rank(&self, rank: usize) -> Result<u32> {
1945        let (block, within) = self.rank_parts(rank)?;
1946        let codes = self.rank_codes(block, self.rank_block_len(rank))?;
1947        let code = bitpack::tail_at(codes, self.code_bits, within)
1948            .map_err(|_| invalid("global dictionary rank block is short of codes"))?;
1949        let code = u32::try_from(code)
1950            .map_err(|_| invalid("global dictionary order names a code it does not have"))?;
1951        if code as usize >= self.len() {
1952            return Err(invalid("global dictionary order names a code it does not have"));
1953        }
1954        Ok(code)
1955    }
1956
1957    fn code_ranks(&self) -> Option<&[u32]> {
1958        // The order is a permutation of the positions, so inverting it needs every position to be
1959        // named exactly once. Anything else and the slice would have holes, and a caller indexing
1960        // it by a code would read a rank that belongs to nothing.
1961        if self.ranks == 0 || self.ranks != self.len() {
1962            return None;
1963        }
1964        self.code_ranks
1965            .get_or_init(|| {
1966                let mut ranks = vec![u32::MAX; self.ranks];
1967                // A block at a time rather than a rank at a time, because reading it per rank pays
1968                // for the bounds check, the division and the lock on every one of them.
1969                for first in (0..self.ranks).step_by(TEXT_RANK_BLOCK) {
1970                    let (block, _) = self.rank_parts(first).ok()?;
1971                    let count = self.rank_block_len(first);
1972                    let codes = self.rank_codes(block, count).ok()?;
1973                    for (within, code) in bitpack::unpack_tail(codes, self.code_bits, count)
1974                        .ok()?
1975                        .into_iter()
1976                        .enumerate()
1977                    {
1978                        let code = usize::try_from(code).ok()?;
1979                        *ranks.get_mut(code)? = u32::try_from(first + within).ok()?;
1980                    }
1981                }
1982                if ranks.contains(&u32::MAX) {
1983                    return None;
1984                }
1985                Some(ranks)
1986            })
1987            .as_deref()
1988    }
1989
1990    fn footprint(&self) -> usize {
1991        self.offsets.capacity()
1992            + self
1993                .code_ranks
1994                .get()
1995                .and_then(Option::as_ref)
1996                .map_or(0, |ranks| ranks.capacity() * size_of::<u32>())
1997            + self.rank_hashes.capacity() * size_of::<u64>()
1998            + self.rank_ends.capacity() * size_of::<u64>()
1999            + self.rank_blocks.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
2000            + self
2001                .rank_blocks
2002                .iter()
2003                .filter_map(OnceLock::get)
2004                .filter_map(|result| result.as_ref().ok())
2005                .map(Vec::capacity)
2006                .sum::<usize>()
2007            + self.blocks.capacity() * size_of::<OnceLock<Result<Vec<u8>>>>()
2008            + self.hashes.capacity() * size_of::<u64>()
2009            + self.ends.capacity() * size_of::<u64>()
2010            + self
2011                .blocks
2012                .iter()
2013                .filter_map(OnceLock::get)
2014                .filter_map(|result| result.as_ref().ok())
2015                .map(Vec::capacity)
2016                .sum::<usize>()
2017    }
2018}
2019
2020/// Every table wide part number in order, with the stripe it belongs to.
2021fn places(table: &Table) -> Result<Vec<Place>> {
2022    let mut places = Vec::with_capacity(table.stripes.len().saturating_mul(STRIPE_PARTS));
2023    for (at, stripe) in table.stripes.iter().enumerate() {
2024        let index = u32::try_from(at).map_err(|_| invalid("too many stripes"))?;
2025        for (part, &rows) in stripe.parts.iter().enumerate() {
2026            places.push(Place {
2027                stripe: index,
2028                part: u32::try_from(part).map_err(|_| invalid("too many parts in a stripe"))?,
2029                rows,
2030            });
2031        }
2032    }
2033    Ok(places)
2034}
2035
2036/// Reads one column's section of a stripe's index page.
2037///
2038/// The section carries its own checksum, so a reader that wants one column out of a hundred and
2039/// five preads a few hundred bytes and still knows that what it got is what was written.
2040fn read_index(file: &File, stripe: &Stripe, column: usize) -> Result<Vec<PartSpan>> {
2041    let parts = stripe.parts.len();
2042    let section = index_section(parts)?;
2043    let at = column.checked_mul(section).ok_or_else(|| invalid("index page offset overflow"))?;
2044    let end = at.checked_add(section).ok_or_else(|| invalid("index page offset overflow"))?;
2045    if end > stripe.index.length as usize {
2046        return Err(invalid("index page is shorter than its columns"));
2047    }
2048    let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2049    let mut bytes = vec![0; section];
2050    let offset = stripe
2051        .index
2052        .offset
2053        .checked_add(at as u64)
2054        .ok_or_else(|| invalid("index page offset overflow"))?;
2055    read_at(file, offset, &mut bytes)?;
2056    let entries = section - size_of::<u64>();
2057    let stored = u64::from_le_bytes(bytes[entries..].try_into().expect("eight bytes"));
2058    if checksum(&bytes[..entries]) != stored {
2059        // With where it was read from, because the two ways this fires look identical from the
2060        // message alone: a file somebody damaged, and a file we wrote to the wrong offset.
2061        return Err(invalid(&format!(
2062            "index page section checksum differs, column {column} of {parts} parts at {offset}, \
2063             wanted {stored:016x} and got {:016x}",
2064            checksum(&bytes[..entries]),
2065        )));
2066    }
2067    let mut spans = Vec::with_capacity(parts);
2068    let mut start = 0_usize;
2069    for part in 0..parts {
2070        let at = part * INDEX_ENTRY;
2071        let length = u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes")) as usize;
2072        let hash = u64::from_le_bytes(bytes[at + 4..at + 12].try_into().expect("eight bytes"));
2073        spans.push(PartSpan { start, length, hash });
2074        start = start.checked_add(length).ok_or_else(|| invalid("column page length overflow"))?;
2075    }
2076    if start != page.length as usize {
2077        return Err(invalid("column page length differs from its index"));
2078    }
2079    Ok(spans)
2080}
2081
2082/// One part's bytes out of a whole column page.
2083fn part_bytes(page: &[u8], span: PartSpan) -> Result<&[u8]> {
2084    let end = span.start.checked_add(span.length).ok_or_else(|| invalid("part range overflow"))?;
2085    page.get(span.start..end).ok_or_else(|| invalid("part exceeds its column page"))
2086}
2087
2088/// Puts one stripe of one column in the cache, dropping the stripe that has been there longest.
2089///
2090/// The index goes in its own slot and stays. Only the page is under the budget, and `kept` is how
2091/// many pages that budget is.
2092fn remember(cached: &mut Cached, held: &CachedColumn, kept: usize) {
2093    if let Some(slot) = cached.index.get_mut(held.stripe) {
2094        if slot.is_none() {
2095            *slot = Some(Arc::clone(&held.index));
2096        }
2097    }
2098    let Some(page) = held.page.clone() else { return };
2099    let Some(slot) = cached.pages.get_mut(held.stripe) else { return };
2100    if slot.is_none() {
2101        cached.order.push_back(held.stripe);
2102    }
2103    *slot = Some(page);
2104    while cached.order.len() > kept.max(1) {
2105        let Some(oldest) = cached.order.pop_front() else { break };
2106        if let Some(slot) = cached.pages.get_mut(oldest) {
2107            *slot = None;
2108        }
2109    }
2110}
2111
2112impl Reader {
2113    /// Opens the highest valid directory slot.
2114    ///
2115    /// # Errors
2116    ///
2117    /// If the file has no valid committed directory or a directory pointer is out of bounds.
2118    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
2119        let mut file = File::open(path).map_err(io)?;
2120        let size = file.metadata().map_err(io)?.len();
2121        if size < HEADER {
2122            return Err(invalid("file is shorter than its header"));
2123        }
2124        let mut header = [0; HEADER as usize];
2125        file.read_exact(&mut header).map_err(io)?;
2126        let mut opening = Opening { reads: 1, bytes: HEADER };
2127        let version = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
2128        // The two halves are worth telling apart. A wrong magic is a file that was never ours and
2129        // the answer is to look at the path. A wrong version is our own file from another build,
2130        // and the number this build wants is the only thing that tells the reader whether to
2131        // rebuild the file or to go back to the binary that wrote it.
2132        if &header[..8] != MAGIC {
2133            return Err(invalid("the header does not begin with a rudb native magic"));
2134        }
2135        if version != FORMAT {
2136            return Err(invalid(&format!(
2137                "the file is format {version} and this build reads format {FORMAT}, so it has to \
2138                 be written again"
2139            )));
2140        }
2141        let mut selected = None;
2142        for start in [16, 16 + SLOT_BYTES] {
2143            let slot = Slot::read(&header[start..start + SLOT_BYTES]);
2144            if slot.generation == 0 || slot.length == 0 || slot.length as usize > MAX_DIRECTORY {
2145                continue;
2146            }
2147            let Some(end) = slot.offset.checked_add(u64::from(slot.length)) else { continue };
2148            if slot.offset < HEADER || end > size {
2149                continue;
2150            }
2151            let mut bytes = vec![0; slot.length as usize];
2152            file.seek(SeekFrom::Start(slot.offset)).map_err(io)?;
2153            file.read_exact(&mut bytes).map_err(io)?;
2154            opening.reads += 1;
2155            opening.bytes += u64::from(slot.length);
2156            if checksum(&bytes) == slot.hash
2157                && selected
2158                    .as_ref()
2159                    .is_none_or(|(old, _): &(Slot, Vec<u8>)| old.generation < slot.generation)
2160            {
2161                selected = Some((slot, bytes));
2162            }
2163        }
2164        let (slot, bytes) =
2165            selected.ok_or_else(|| invalid("no committed directory slot is valid"))?;
2166        let table = decode_directory(&bytes, size)?;
2167        let places = places(&table)?;
2168        let dictionaries = (0..table.fields.len()).map(|_| OnceLock::new()).collect();
2169        let table_fields = table.fields.len();
2170        let stripes = table.stripes.len();
2171        let cache = (0..table.fields.len())
2172            .map(|_| {
2173                Mutex::new(Cached {
2174                    pages: (0..stripes).map(|_| None).collect(),
2175                    index: (0..stripes).map(|_| None).collect(),
2176                    ..Cached::default()
2177                })
2178            })
2179            .collect::<Vec<_>>();
2180        let sieves: Vec<Vec<SieveSlot>> = (0..table.fields.len())
2181            .map(|_| table.stripes.iter().map(|_| OnceLock::new()).collect())
2182            .collect();
2183        let part_ranges: Vec<Vec<RangeSlot>> = (0..table.fields.len())
2184            .map(|_| table.stripes.iter().map(|_| OnceLock::new()).collect())
2185            .collect();
2186        Ok(Self {
2187            file: Arc::new(file),
2188            table: Arc::new(table),
2189            dictionaries: Arc::new(dictionaries),
2190            loading: Arc::new((0..table_fields).map(|_| Mutex::new(())).collect()),
2191            opened: Arc::new(AtomicUsize::new(0)),
2192            sieves: Arc::new(sieves),
2193            part_ranges: Arc::new(part_ranges),
2194            places: Arc::new(places),
2195            cache: Arc::new(cache),
2196            pages: Arc::new(AtomicUsize::new(0)),
2197            indexes: Arc::new(AtomicUsize::new(0)),
2198            kept: Arc::new(AtomicUsize::new(CACHED_STRIPES_PER_COLUMN)),
2199            size,
2200            directory: u64::from(slot.length),
2201            opening,
2202        })
2203    }
2204
2205    /// What this reader has read so far, and what opening it cost.
2206    ///
2207    /// Public because the claim of `spec/stats/04-in-memory.md` section 4.2 is about this number
2208    /// and a claim nobody can check is a comment. A caller that wants to know whether opening a
2209    /// file touched the data asks here, and gets an answer that does not depend on what the page
2210    /// cache happened to hold.
2211    #[must_use]
2212    pub fn reads(&self) -> Reads {
2213        Reads {
2214            opening: self.opening,
2215            pages: self.pages.load(Atomic::Relaxed),
2216            indexes: self.indexes.load(Atomic::Relaxed),
2217            dictionaries: self.opened.load(Atomic::Relaxed),
2218        }
2219    }
2220
2221    /// Where the file's bytes went, from the directory alone.
2222    ///
2223    /// No page is read, so this costs the same on a 45 GB table as on an empty one. See [`Layout`]
2224    /// for what is charged where and for why the three things that are not columns stay separate.
2225    #[must_use]
2226    pub fn layout(&self) -> Layout {
2227        let table = &self.table;
2228        let stripes = table.stripes.as_slice();
2229        let columns = table
2230            .fields
2231            .iter()
2232            .enumerate()
2233            .map(|(at, field)| ColumnLayout {
2234                name: field.name.clone(),
2235                kind: field.ty.to_string(),
2236                pages: sum(stripes.iter().map(|stripe| span_bytes(&stripe.pages, at))),
2237                memberships: sum(stripes.iter().map(|stripe| page_bytes(&stripe.memberships, at))),
2238                sieves: sum(stripes.iter().map(|stripe| page_bytes(&stripe.sieves, at))),
2239                part_ranges: sum(stripes.iter().map(|stripe| page_bytes(&stripe.part_ranges, at))),
2240                dictionary: page_bytes(&table.dictionaries, at),
2241            })
2242            .collect();
2243        Layout {
2244            file: self.size,
2245            rows: table.rows,
2246            stripes: stripes.len(),
2247            parts: self.places.len(),
2248            columns,
2249            indexes: sum(stripes.iter().map(|stripe| u64::from(stripe.index.length))),
2250            directory: self.directory,
2251            header: HEADER,
2252        }
2253    }
2254
2255    /// How many parts the table has, which is how many chunks a scan of it reads.
2256    #[must_use]
2257    pub fn parts(&self) -> usize {
2258        self.places.len()
2259    }
2260
2261    /// The parts of each stripe, in table wide part numbers.
2262    ///
2263    /// A scan that wants one worker to own the page it reads hands work out in these runs. The
2264    /// stripes are contiguous in part numbering and all but the last hold sixty four parts, but a
2265    /// stripe can be flushed early when rows arrive out of order, so the runs are read off the
2266    /// directory rather than worked out from a constant.
2267    #[must_use]
2268    pub fn stripe_parts(&self) -> Vec<std::ops::Range<usize>> {
2269        let mut runs = Vec::with_capacity(self.table.stripes.len());
2270        let mut start = 0;
2271        for stripe in &self.table.stripes {
2272            let end = start + stripe.parts.len();
2273            runs.push(start..end);
2274            start = end;
2275        }
2276        runs
2277    }
2278
2279    /// Asks the page cache to keep `stripes` stripes of every column instead of the default.
2280    ///
2281    /// This only ever raises the number. A scan that gives each worker a whole stripe has one page
2282    /// per column per worker open at once, and a cache smaller than that is worse than no cache at
2283    /// all: every worker's page is evicted by the others before it has finished its stripe, so it
2284    /// reads a quarter of a megabyte for every part it takes out of it.
2285    pub fn keep_stripes(&self, stripes: usize) {
2286        self.kept.fetch_max(stripes, Atomic::Relaxed);
2287    }
2288
2289    /// Rows in one part, or zero when the part number is past the table.
2290    #[must_use]
2291    pub fn part_rows(&self, at: usize) -> usize {
2292        self.places.get(at).map_or(0, |place| place.rows as usize)
2293    }
2294
2295    /// The committed table directory.
2296    #[must_use]
2297    pub fn table(&self) -> &Table {
2298        &self.table
2299    }
2300
2301    /// Exact leading frequencies when the stored synopsis proves a count-descending prefix.
2302    ///
2303    /// The returned list can be longer than `top`. Keeping the stored tail lets a later TopN apply
2304    /// additional ordering keys without losing a value tied with the requested boundary.
2305    ///
2306    /// # Errors
2307    ///
2308    /// If the column is outside the schema or a stored value does not fit its declared type.
2309    pub fn top_frequencies(&self, column: usize, top: usize) -> Result<Option<Vec<(Value, u64)>>> {
2310        let field = self
2311            .table
2312            .fields
2313            .get(column)
2314            .ok_or_else(|| invalid("frequency column index out of range"))?;
2315        let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
2316            return Ok(None);
2317        };
2318        if top == 0 || summary.entries.len() < top {
2319            return Ok(None);
2320        }
2321        let boundary = summary.entries[top - 1].count;
2322        if boundary <= summary.omitted_max {
2323            return Ok(None);
2324        }
2325        self.decode_frequencies(column, &field.ty, &summary.entries).map(Some)
2326    }
2327
2328    /// Every value of one column with the number of rows holding it, when the synopsis is complete.
2329    ///
2330    /// The heavy hitter pass keeps a bounded set of candidates and decrements them all when it runs
2331    /// out of room, so what it usually ends with is the leading values and a bound on everything it
2332    /// dropped. `omitted_max` of zero says that never happened: no candidate was ever decremented and
2333    /// the entries did not overflow the stored budget, so the list is every distinct value of the
2334    /// column with an exact count, and a null counts as a value of its own rather than being skipped.
2335    ///
2336    /// That makes a whole class of question answerable without reading a row. How many rows hold a
2337    /// value, how many do not, and what a `GROUP BY` of that column with a count over it produces are
2338    /// all in here. It is only ever true of a column with few enough distinct values, which is the
2339    /// case worth having, because that is exactly the column a grouping or an equality filter would
2340    /// otherwise walk every row to answer.
2341    ///
2342    /// `None` when the column has no synopsis, or has one that dropped anything.
2343    ///
2344    /// # Errors
2345    ///
2346    /// If the column is outside the schema or a stored value does not fit its declared type.
2347    pub fn exact_frequencies(&self, column: usize) -> Result<Option<Vec<(Value, u64)>>> {
2348        let field = self
2349            .table
2350            .fields
2351            .get(column)
2352            .ok_or_else(|| invalid("frequency column index out of range"))?;
2353        let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
2354            return Ok(None);
2355        };
2356        if summary.omitted_max > 0 {
2357            return Ok(None);
2358        }
2359        self.decode_frequencies(column, &field.ty, &summary.entries).map(Some)
2360    }
2361
2362    /// Turns stored frequency entries into values of the column's own type.
2363    fn decode_frequencies(
2364        &self,
2365        column: usize,
2366        ty: &LogicalType,
2367        entries: &[FrequencyEntry],
2368    ) -> Result<Vec<(Value, u64)>> {
2369        let dictionary = if *ty == LogicalType::Varchar { self.dictionary(column)? } else { None };
2370        let mut out = Vec::with_capacity(entries.len());
2371        for entry in entries {
2372            let value = match entry.value {
2373                FrequencyValue::Null => Value::Null,
2374                FrequencyValue::Integer(value) => match *ty {
2375                    LogicalType::TinyInt => Value::TinyInt(
2376                        i8::try_from(value)
2377                            .map_err(|_| invalid("frequency TINYINT is out of range"))?,
2378                    ),
2379                    LogicalType::UTinyInt => Value::UTinyInt(
2380                        u8::try_from(value)
2381                            .map_err(|_| invalid("frequency UTINYINT is out of range"))?,
2382                    ),
2383                    LogicalType::USmallInt => Value::USmallInt(
2384                        u16::try_from(value)
2385                            .map_err(|_| invalid("frequency USMALLINT is out of range"))?,
2386                    ),
2387                    LogicalType::UInteger => Value::UInteger(
2388                        u32::try_from(value)
2389                            .map_err(|_| invalid("frequency UINTEGER is out of range"))?,
2390                    ),
2391                    LogicalType::UBigInt => Value::UBigInt(
2392                        u64::try_from(value)
2393                            .map_err(|_| invalid("frequency UBIGINT is out of range"))?,
2394                    ),
2395                    LogicalType::SmallInt => Value::SmallInt(
2396                        i16::try_from(value)
2397                            .map_err(|_| invalid("frequency SMALLINT is out of range"))?,
2398                    ),
2399                    LogicalType::Integer => Value::Integer(
2400                        i32::try_from(value)
2401                            .map_err(|_| invalid("frequency INTEGER is out of range"))?,
2402                    ),
2403                    LogicalType::BigInt => Value::BigInt(
2404                        i64::try_from(value)
2405                            .map_err(|_| invalid("frequency BIGINT is out of range"))?,
2406                    ),
2407                    LogicalType::Date => Value::Date(
2408                        i32::try_from(value)
2409                            .map_err(|_| invalid("frequency DATE is out of range"))?,
2410                    ),
2411                    LogicalType::Timestamp => Value::Timestamp(
2412                        i64::try_from(value)
2413                            .map_err(|_| invalid("frequency TIMESTAMP is out of range"))?,
2414                    ),
2415                    _ => return Err(invalid("integer frequency belongs to another type")),
2416                },
2417                FrequencyValue::Code(code) => dictionary
2418                    .as_ref()
2419                    .ok_or_else(|| invalid("frequency code has no dictionary"))?
2420                    .try_value_at(code as usize)?,
2421            };
2422            out.push((value, entry.count));
2423        }
2424        Ok(out)
2425    }
2426
2427    /// Sparse rows belonging to the bounded numeric frequency candidate set.
2428    ///
2429    /// The list is omitted when collecting it would exceed the fixed storage budget. A composite
2430    /// aggregate may accept a result over these rows only when its requested boundary is strictly
2431    /// greater than `omitted_max`.
2432    ///
2433    /// # Errors
2434    ///
2435    /// If the column is outside the schema.
2436    pub fn frequency_occurrences(&self, column: usize) -> Result<Option<FrequencyOccurrences>> {
2437        self.table
2438            .fields
2439            .get(column)
2440            .ok_or_else(|| invalid("frequency column index out of range"))?;
2441        let Some(summary) = self.table.frequencies.get(column).and_then(Option::as_ref) else {
2442            return Ok(None);
2443        };
2444        if summary.ordinals.is_empty() {
2445            return Ok(None);
2446        }
2447        Ok(Some(FrequencyOccurrences {
2448            omitted_max: summary.omitted_max,
2449            ordinals: summary.ordinals.clone(),
2450        }))
2451    }
2452
2453    /// How many distinct values one column holds, counting a null as no value.
2454    ///
2455    /// A string column of this format is written against one dictionary that covers the whole table.
2456    /// A code is handed out the first time a value is seen and nothing ever removes one, so the
2457    /// number of codes is the number of distinct values exactly rather than an estimate. That makes
2458    /// `COUNT(DISTINCT column)` over a whole table a question the directory already knows the answer
2459    /// to, and the alternative is a hash table with a row per distinct value built from a pass over
2460    /// every row.
2461    ///
2462    /// A null in the column used to make this `None` and no longer does. A null row is written as
2463    /// the code for the empty string, so a nullable column's dictionary can hold an empty string
2464    /// that no row of it actually has, and the dictionary on its own does not say which case it is.
2465    /// The writer does know, because it counts the non-null rows that use each code on its way to
2466    /// the frequency summary, so it records how many codes any row holds and the directory carries
2467    /// that number. This reads it rather than the size of the dictionary, which also means the
2468    /// dictionary page is not opened to answer.
2469    ///
2470    /// `None` for a column the file has no dictionary for, which is every column that is not a
2471    /// string. A sketch would answer that approximately and SQL asked for the exact number.
2472    ///
2473    /// # Errors
2474    ///
2475    /// If the column is outside the schema.
2476    pub fn distinct_values(&self, column: usize) -> Result<Option<u64>> {
2477        self.table
2478            .distincts
2479            .get(column)
2480            .copied()
2481            .ok_or_else(|| invalid("distinct column index out of range"))
2482    }
2483
2484    /// How many rows of one column are null, added up over the stripes.
2485    ///
2486    /// Every stripe records this exactly when it is written, because a null count is not a bound
2487    /// that is allowed to be wide the way a minimum and a maximum are: a filter that reads one too
2488    /// many is slow and a `COUNT` that reads one too many is wrong. Adding up a few hundred numbers
2489    /// already in memory is what makes `COUNT(column)` over a whole table free.
2490    ///
2491    /// # Errors
2492    ///
2493    /// If the column is outside the schema.
2494    pub fn null_count(&self, column: usize) -> Result<u64> {
2495        if column >= self.table.fields.len() {
2496            return Err(invalid("null count column index out of range"));
2497        }
2498        let mut nulls = 0_u64;
2499        for stripe in &self.table.stripes {
2500            let range = stripe
2501                .zone
2502                .column(column)
2503                .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2504            nulls = nulls
2505                .checked_add(range.nulls as u64)
2506                .ok_or_else(|| invalid("null count overflow"))?;
2507        }
2508        Ok(nulls)
2509    }
2510
2511    /// The smallest and the largest value of one string column, from the order beside its values.
2512    ///
2513    /// The dictionary holds exactly the values the column holds, so the first and the last of them
2514    /// in sorted order are the column's minimum and maximum. Two reads of a rank block settle what
2515    /// otherwise walks a million rows.
2516    ///
2517    /// `None` when the column is not a string, when the file was written before version 9 and so has
2518    /// no order, when the column has no values at all, or when it has a null in it, which is the
2519    /// placeholder again: the empty string a null is written as would sort ahead of every real
2520    /// value and be reported as the minimum.
2521    ///
2522    /// # Errors
2523    ///
2524    /// If the column is outside the schema, or a rank names a code the dictionary does not have.
2525    pub fn text_extremes(&self, column: usize) -> Result<Option<(Value, Value)>> {
2526        if self.null_count(column)? > 0 {
2527            return Ok(None);
2528        }
2529        let Some(dictionary) = self.dictionary(column)? else { return Ok(None) };
2530        let Some(ranks) = dictionary.ranks() else { return Ok(None) };
2531        if ranks == 0 {
2532            return Ok(None);
2533        }
2534        let low = text_at_rank(&dictionary, 0)?;
2535        let high = text_at_rank(&dictionary, ranks - 1)?;
2536        Ok(Some((low, high)))
2537    }
2538
2539    /// The smallest and the largest value of one column, when every stripe wrote exact ends.
2540    ///
2541    /// A stripe's ends are allowed to be wider than the truth, because a bound that rules out a
2542    /// chunk that could not match is still correct when it rules out nothing. That is what makes
2543    /// them cheap to write for a bit packed or a dictionary column, and it is also what stops them
2544    /// answering a `MIN`. So each stripe says which of the two it wrote, and this answers only when
2545    /// all of them walked their rows.
2546    ///
2547    /// `None` for a column with no ends, for an empty table, and for a column any stripe of which
2548    /// guessed. Nulls need no special case, because the ends skip them the same way `MIN` does.
2549    ///
2550    /// One case is given up on that did not have to be. A stripe merges the ends of its sixty four
2551    /// parts, and a part with no ends at all erases the merged ones, because a part whose rows are
2552    /// not covered by the stripe's ends is a stripe that would skip rows it should keep. A part of
2553    /// nothing but nulls has no rows to cover and so did not need to erase anything, but the merge
2554    /// cannot tell that part from a part whose layout it could not read. So a column with a chunk
2555    /// of nothing but nulls in the middle of it goes and reads the rows. That is slow and right,
2556    /// and the fix is a row count per part rather than anything here.
2557    ///
2558    /// # Errors
2559    ///
2560    /// If the column is outside the schema.
2561    pub fn exact_extremes(&self, column: usize) -> Result<Option<(Bound, Bound)>> {
2562        if column >= self.table.fields.len() {
2563            return Err(invalid("extremes column index out of range"));
2564        }
2565        let mut low: Option<Bound> = None;
2566        let mut high: Option<Bound> = None;
2567        for stripe in &self.table.stripes {
2568            let range = stripe
2569                .zone
2570                .column(column)
2571                .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2572            if !range.exact {
2573                return Ok(None);
2574            }
2575            // A stripe of nothing but nulls has no ends and says nothing about the column's, which
2576            // is why this skips it rather than giving up on the whole column. A stripe that has
2577            // rows and still has no end is a layout whose values this cannot see, and skipping that
2578            // one would answer with an end taken from the other stripes, so it gives up instead.
2579            let (Some(small), Some(large)) = (range.low.as_ref(), range.high.as_ref()) else {
2580                if stripe.rows > range.nulls {
2581                    return Ok(None);
2582                }
2583                continue;
2584            };
2585            low = Some(low.map_or_else(|| small.clone(), |held| held.smaller(small.clone())));
2586            high = Some(high.map_or_else(|| large.clone(), |held| held.larger(large.clone())));
2587        }
2588        Ok(low.zip(high))
2589    }
2590
2591    /// The sum of one integer column and how many rows went into it, when every stripe wrote one.
2592    ///
2593    /// The count beside the sum is the non-null rows, because that is what a `SUM` adds up and what
2594    /// an `AVG` divides by, and a caller that had to work it out from the row count and the null
2595    /// count would be doing the same walk twice.
2596    ///
2597    /// `None` for anything that is not an integer column, for a file written by something that did
2598    /// not record it, and when adding the stripes together would overflow.
2599    ///
2600    /// # Errors
2601    ///
2602    /// If the column is outside the schema.
2603    pub fn exact_sum(&self, column: usize) -> Result<Option<(i128, u64)>> {
2604        if column >= self.table.fields.len() {
2605            return Err(invalid("sum column index out of range"));
2606        }
2607        let mut total = 0_i128;
2608        let mut rows = 0_u64;
2609        for stripe in &self.table.stripes {
2610            let range = stripe
2611                .zone
2612                .column(column)
2613                .ok_or_else(|| invalid("stripe zone is narrower than the schema"))?;
2614            let Some(part) = range.sum else { return Ok(None) };
2615            let Some(sum) = total.checked_add(part) else { return Ok(None) };
2616            total = sum;
2617            rows = rows.saturating_add(stripe.rows as u64 - range.nulls as u64);
2618        }
2619        Ok(Some((total, rows)))
2620    }
2621
2622    /// The global dictionary of a column, opened once however many workers ask for it at once.
2623    ///
2624    /// The unlocked look is first because it is the answer every time after the first and it costs a
2625    /// load. Everybody who misses it queues on [`Self::loading`] and looks again on the way in, so
2626    /// the one who arrived first does the reading and the rest take what it left. Waiting is the
2627    /// cheaper thing to do: the work behind the lock is a page read, a checksum and the decode of a
2628    /// dictionary that can hold half a million entries, and the alternative is every worker of the
2629    /// scan doing all of it and all but one dropping the result on the floor.
2630    fn dictionary(&self, column: usize) -> Result<Option<Arc<Vector>>> {
2631        let Some(page) = self.table.dictionaries[column] else { return Ok(None) };
2632        if let Some(dictionary) = self.dictionaries[column].get() {
2633            return Ok(Some(Arc::clone(dictionary)));
2634        }
2635        let _queued = self.loading[column].lock().map_err(|_| invalid("a poisoned dictionary"))?;
2636        if let Some(dictionary) = self.dictionaries[column].get() {
2637            return Ok(Some(Arc::clone(dictionary)));
2638        }
2639        self.opened.fetch_add(1, Atomic::Relaxed);
2640        let dictionary = Arc::new(open_global_dictionary(
2641            Arc::clone(&self.file),
2642            page,
2643            &self.table.fields[column].ty,
2644            TEXT_KEEP_BUDGET,
2645        )?);
2646        let _ = self.dictionaries[column].set(Arc::clone(&dictionary));
2647        Ok(Some(dictionary))
2648    }
2649
2650    /// Reads only the named columns from one part.
2651    ///
2652    /// The whole stripe page each column lives in is read and kept, because a scan asks for the
2653    /// parts of a stripe one after another and this is what turns sixty four reads into one.
2654    ///
2655    /// # Errors
2656    ///
2657    /// If a part, column, page, or checksum is invalid.
2658    pub fn read(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2659        self.read_impl(part, columns, true)
2660    }
2661
2662    /// Reads named columns from one part without keeping the stripe page it came out of.
2663    ///
2664    /// This is for sparse row fetches after a selective TopN or filter, which reach a few parts of
2665    /// a stripe rather than all of them. A caller that will read most of a stripe should use
2666    /// [`Self::read`] instead, because this reads and discards the page index every time.
2667    ///
2668    /// # Errors
2669    ///
2670    /// If a part, column, page, or checksum is invalid.
2671    pub fn read_sparse(&self, part: usize, columns: &[usize]) -> Result<Chunk> {
2672        self.read_impl(part, columns, false)
2673    }
2674
2675    /// Whether an exact global-code membership index proves that the stripe holding a part cannot
2676    /// contain any of the sorted candidate codes.
2677    ///
2678    /// # Errors
2679    ///
2680    /// If the part, column, index page, checksum, or delta stream is invalid.
2681    pub fn skips_codes(&self, part: usize, column: usize, candidates: &[u32]) -> Result<bool> {
2682        if candidates.is_empty() {
2683            return Ok(true);
2684        }
2685        if candidates.windows(2).any(|pair| pair[0] >= pair[1]) {
2686            return Err(Error::internal("native code candidates are not sorted and unique"));
2687        }
2688        let stripe = self.stripe_of(part)?;
2689        let Some(page) = stripe.memberships.get(column).copied().flatten() else {
2690            return Ok(false);
2691        };
2692        let mut bytes = vec![0; page.length as usize];
2693        read_at(&self.file, page.offset, &mut bytes)?;
2694        if checksum(&bytes) != page.hash {
2695            return Err(invalid("membership page checksum differs"));
2696        }
2697        let codes = decode_membership(&bytes)?;
2698        let mut left = 0;
2699        let mut right = 0;
2700        while left < codes.len() && right < candidates.len() {
2701            match codes[left].cmp(&candidates[right]) {
2702                Ordering::Less => left += 1,
2703                Ordering::Greater => right += 1,
2704                Ordering::Equal => return Ok(false),
2705            }
2706        }
2707        Ok(true)
2708    }
2709
2710    fn stripe_of(&self, part: usize) -> Result<&Stripe> {
2711        let place = self.places.get(part).ok_or_else(|| invalid("part index out of range"))?;
2712        self.table
2713            .stripes
2714            .get(place.stripe as usize)
2715            .ok_or_else(|| invalid("stripe index out of range"))
2716    }
2717
2718    /// The page index of one column of one stripe, and its page when the caller wants all of it.
2719    ///
2720    /// A scan hands parts out in order, so every worker on a column crosses into a new stripe within
2721    /// a few parts of the others and they all want the same page at the same moment. This used to
2722    /// let all of them read it, which cost the scan as many copies of every page as it had workers.
2723    /// On the full ClickBench file a `MIN(EventDate), MAX(EventDate)` moved 3.2 GB off the disk to
2724    /// look at 400 MB of column.
2725    ///
2726    /// A worker that finds the page it wants already being read neither waits for it nor reads it
2727    /// again. It comes back with the index alone, which sends [`Reader::read_impl`] down the path
2728    /// that reads the one part it came for, a few kilobytes against a quarter of a megabyte, and it
2729    /// picks the page up from the cache on its next part. Waiting would be the other way to avoid
2730    /// the duplicate read and it is worse: the pages that matter are the wide string ones, they take
2731    /// milliseconds to copy even warm, and every other worker would be stopped for all of it.
2732    ///
2733    /// The file is never read under the lock.
2734    fn held(&self, at: usize, stripe: &Stripe, column: usize, whole: bool) -> Result<CachedColumn> {
2735        let cache = self.cache.get(column).ok_or_else(|| invalid("column index out of range"))?;
2736        let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2737        let known = cached.index.get(at).and_then(Clone::clone);
2738        let page = cached.pages.get(at).and_then(Clone::clone);
2739        if let Some(index) = known.clone() {
2740            if !whole || page.is_some() {
2741                return Ok(CachedColumn { stripe: at, index, page });
2742            }
2743        }
2744        if cached.loading.contains(&at) {
2745            drop(cached);
2746            // The index is almost always already here, because somebody read this stripe to get
2747            // into the loading list in the first place, so this branch usually costs no read at
2748            // all and the one part read in `read_impl` is all the losing worker pays for.
2749            if let Some(index) = known {
2750                return Ok(CachedColumn { stripe: at, index, page: None });
2751            }
2752            let held = self.page_of(stripe, column, at, false, None)?;
2753            let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2754            remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2755            return Ok(held);
2756        }
2757        cached.loading.push(at);
2758        drop(cached);
2759
2760        let read = self.page_of(stripe, column, at, whole, known);
2761
2762        // The stripe leaves the loading list and its page enters the cache under one lock. Doing
2763        // them separately would leave a moment where another worker sees neither and reads the
2764        // page a second time, which is the whole thing this is here to stop.
2765        let mut cached = cache.lock().map_err(|_| invalid("column page cache is poisoned"))?;
2766        if let Some(position) = cached.loading.iter().position(|loading| *loading == at) {
2767            cached.loading.remove(position);
2768        }
2769        let held = read?;
2770        remember(&mut cached, &held, self.kept.load(Atomic::Relaxed));
2771        Ok(held)
2772    }
2773
2774    /// Reads one stripe's index for a column, and its page when the caller wants all of it.
2775    ///
2776    /// `known` is the index when the reader has already read it, which after the first worker
2777    /// through a stripe it always has, because [`remember`] keeps every index for the life of the
2778    /// reader. Without that a scan reads the index again on every part that misses the page cache.
2779    fn page_of(
2780        &self,
2781        stripe: &Stripe,
2782        column: usize,
2783        at: usize,
2784        whole: bool,
2785        known: Option<Arc<Vec<PartSpan>>>,
2786    ) -> Result<CachedColumn> {
2787        let index = match known {
2788            Some(index) => index,
2789            None => {
2790                self.indexes.fetch_add(1, Atomic::Relaxed);
2791                Arc::new(read_index(&self.file, stripe, column)?)
2792            }
2793        };
2794        let page = if whole {
2795            self.pages.fetch_add(1, Atomic::Relaxed);
2796            let span = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2797            let mut bytes = vec![0; span.length as usize];
2798            read_at(&self.file, span.offset, &mut bytes)?;
2799            Some(Arc::new(bytes))
2800        } else {
2801            None
2802        };
2803        Ok(CachedColumn { stripe: at, index, page })
2804    }
2805
2806    fn read_impl(&self, at: usize, columns: &[usize], whole: bool) -> Result<Chunk> {
2807        let place = *self.places.get(at).ok_or_else(|| invalid("part index out of range"))?;
2808        let index = place.stripe as usize;
2809        let stripe =
2810            self.table.stripes.get(index).ok_or_else(|| invalid("stripe index out of range"))?;
2811        let rows = place.rows as usize;
2812        let mut picked = Vec::with_capacity(columns.len());
2813        for &column in columns {
2814            let field = self
2815                .table
2816                .fields
2817                .get(column)
2818                .ok_or_else(|| invalid("column index out of range"))?;
2819            let page = stripe.pages.get(column).ok_or_else(|| invalid("stripe page is missing"))?;
2820            let held = self.held(index, stripe, column, whole)?;
2821            let span = *held
2822                .index
2823                .get(place.part as usize)
2824                .ok_or_else(|| invalid("part index out of range"))?;
2825            let owned;
2826            let bytes = match &held.page {
2827                Some(held) => part_bytes(held, span)?,
2828                None => {
2829                    let offset = page
2830                        .offset
2831                        .checked_add(span.start as u64)
2832                        .ok_or_else(|| invalid("part range overflow"))?;
2833                    let mut bytes = vec![0; span.length];
2834                    read_at(&self.file, offset, &mut bytes)?;
2835                    owned = bytes;
2836                    &owned
2837                }
2838            };
2839            if checksum(bytes) != span.hash {
2840                return Err(invalid(&format!(
2841                    "column page checksum differs, column {column} part {} at {}+{} of {} bytes, \
2842                     wanted {:016x} and got {:016x}",
2843                    place.part,
2844                    page.offset,
2845                    span.start,
2846                    span.length,
2847                    span.hash,
2848                    checksum(bytes),
2849                )));
2850            }
2851            let dictionary = self.dictionary(column)?;
2852            picked.push(decode(&field.ty, rows, bytes, dictionary)?);
2853        }
2854        Chunk::with_rows(picked, rows)
2855    }
2856
2857    /// Whether persisted statistics prove that a part cannot match the predicates.
2858    ///
2859    /// Three of them, asked cheapest first.
2860    ///
2861    /// The stripe's bounds are in memory already, so they are free, and they are also the coarsest:
2862    /// every part of a stripe gets the same answer and a scan that skips one part that way skips all
2863    /// sixty four. Then the part's own bounds, which are a read of one page per column per stripe
2864    /// and are sixty four times finer. Then the sieves, which are per part and answer equality, the
2865    /// test bounds are worst at: a column of identifiers has every stripe and nearly every part
2866    /// covering the whole of its type, so bounds keep them all and the sieve keeps the ones that
2867    /// really hold the value.
2868    ///
2869    /// The middle one is what an ordered comparison on a column the rows are not sorted by needs. On
2870    /// ClickBench 24 the stripe bounds leave eight stripes of sixteen alive, which is half the file,
2871    /// and the part bounds leave thirty parts of nine hundred and seventy four.
2872    #[must_use]
2873    pub fn skips(&self, part: usize, probes: &[Probe]) -> bool {
2874        let Some(place) = self.places.get(part).copied() else { return false };
2875        let Some(stripe) = self.table.stripes.get(place.stripe as usize) else { return false };
2876        if stripe.zone.skips(probes) {
2877            return true;
2878        }
2879        probes.iter().any(|probe| self.outside(place, probe) || self.sifted(place, probe))
2880    }
2881
2882    /// Whether the bounds of one part rule out one probe.
2883    ///
2884    /// The part's own two ends, which are narrower than the stripe's and cost a page read the first
2885    /// time this is asked about a column. A column with no page here answers `false`, which is the
2886    /// answer a caller got before there were any.
2887    fn outside(&self, place: Place, probe: &Probe) -> bool {
2888        match self.stripe_part_ranges(place.stripe as usize, probe.column) {
2889            Some(ranges) => ranges
2890                .get(place.part as usize)
2891                .is_some_and(|range| range.excludes(probe.op, &probe.value)),
2892            None => false,
2893        }
2894    }
2895
2896    /// The per part ranges of one stripe of one column, read once and kept.
2897    ///
2898    /// `None` when the column has no page in that stripe and when the page is damaged, on the same
2899    /// reasoning as the sieves: this is an index over data that is still there, so a caller that
2900    /// cannot read one reads the rows and gets the right answer slowly.
2901    fn stripe_part_ranges(&self, stripe: usize, column: usize) -> Option<&[Range]> {
2902        let slot = self.part_ranges.get(column)?.get(stripe)?;
2903        if let Some(held) = slot.get() {
2904            return Some(held);
2905        }
2906        let page = self.table.stripes.get(stripe)?.part_ranges.get(column).copied().flatten()?;
2907        let mut bytes = vec![0; page.length as usize];
2908        read_at(&self.file, page.offset, &mut bytes).ok()?;
2909        if checksum(&bytes) != page.hash {
2910            return None;
2911        }
2912        let ranges = Arc::new(decode_part_ranges(&bytes).ok()?);
2913        let _ = slot.set(ranges);
2914        slot.get().map(|held| held.as_slice())
2915    }
2916
2917    /// Whether persisted statistics prove that every row of a part matches the predicates.
2918    ///
2919    /// Only the bounds. The sieves say nothing here, because a sieve that holds a value is a sieve
2920    /// that may be holding somebody else's hash, so it can rule a part out and can never wave one
2921    /// through.
2922    ///
2923    /// The stripe first and the part after it, the same two steps and in the same order as
2924    /// [`Self::skips`]. The stripe's bounds are in memory already and its null count covers sixty
2925    /// four parts rather than one, so a stripe that answers is an answer for nothing, and the part's
2926    /// own bounds are only read for the probes it could not settle. Both directions are safe: a
2927    /// stretch where everything passes contains no narrower stretch where something fails, and a
2928    /// stripe with no nulls has no nulls in any of its parts.
2929    ///
2930    /// A string end a part recorded is cut down to its first few bytes, so a part's stretch can be
2931    /// wider than its rows really are as well. That is the same safe direction for the same reason,
2932    /// and it is why this asks the two ends rather than anything `exact` says.
2933    #[must_use]
2934    pub fn certain(&self, part: usize, probes: &[Probe]) -> bool {
2935        let Some(place) = self.places.get(part).copied() else { return false };
2936        let Some(stripe) = self.table.stripes.get(place.stripe as usize) else { return false };
2937        if stripe.zone.certain(probes) {
2938            return true;
2939        }
2940        probes
2941            .iter()
2942            .all(|probe| stripe.zone.certain(slice::from_ref(probe)) || self.inside(place, probe))
2943    }
2944
2945    /// Whether one part's own two ends prove that every row of it passes `probe`.
2946    ///
2947    /// The mirror of [`Self::outside`], reading the same page. `false` for a part whose stripe wrote
2948    /// no range page, which is a stripe of one part, because there the stripe's own bounds are the
2949    /// part's and the caller has already asked them.
2950    fn inside(&self, place: Place, probe: &Probe) -> bool {
2951        match self.stripe_part_ranges(place.stripe as usize, probe.column) {
2952            Some(ranges) => ranges
2953                .get(place.part as usize)
2954                .is_some_and(|range| range.certain(probe.op, &probe.value)),
2955            None => false,
2956        }
2957    }
2958
2959    /// Whether the bounds of one stripe prove that none of its parts can match the predicates.
2960    ///
2961    /// The cheap half of [`Self::skips`], asked about a whole stripe at once. The bounds live in the
2962    /// directory and are already in memory, so this answers without touching the file, and that is
2963    /// the reason it is worth having on its own: a caller that wants to know roughly where the work
2964    /// is before it starts any workers can ask this about sixteen stripes for nothing, where asking
2965    /// [`Self::skips`] about nine hundred parts would read and decode a sieve page per stripe first.
2966    ///
2967    /// It keeps stripes that [`Self::skips`] would rule out part by part, which is the right way for
2968    /// it to be wrong: the parts are still checked when they are read.
2969    #[must_use]
2970    pub fn stripe_skips(&self, stripe: usize, probes: &[Probe]) -> bool {
2971        self.table.stripes.get(stripe).is_some_and(|held| held.zone.skips(probes))
2972    }
2973
2974    /// Whether the sieve of one part rules out one probe.
2975    ///
2976    /// Only equality. An ordered comparison is what the bounds are for and a sieve says nothing
2977    /// about it, and a read that cannot answer keeps the part, which is the answer a caller with no
2978    /// sieve gets anyway.
2979    fn sifted(&self, place: Place, probe: &Probe) -> bool {
2980        if probe.op != Op::Equal {
2981            return false;
2982        }
2983        match self.stripe_sieves(place.stripe as usize, probe.column) {
2984            Some(sieves) => sieves
2985                .get(place.part as usize)
2986                .and_then(Option::as_ref)
2987                .is_some_and(|sieve| sieve.excludes(&probe.value)),
2988            None => false,
2989        }
2990    }
2991
2992    /// The sieves of one stripe of one column, read once and kept.
2993    ///
2994    /// `None` when the column has no sieves in that stripe, when the page is damaged, and when the
2995    /// bytes are not a page this version can read. A sieve is an index over data that is still there
2996    /// and a caller that cannot read one reads the rows, so this is the one place in the file where
2997    /// a bad checksum is a slow query rather than an error.
2998    fn stripe_sieves(&self, stripe: usize, column: usize) -> Option<&[Option<Sieve>]> {
2999        let slot = self.sieves.get(column)?.get(stripe)?;
3000        if let Some(held) = slot.get() {
3001            return Some(held);
3002        }
3003        let page = self.table.stripes.get(stripe)?.sieves.get(column).copied().flatten()?;
3004        let mut bytes = vec![0; page.length as usize];
3005        read_at(&self.file, page.offset, &mut bytes).ok()?;
3006        if checksum(&bytes) != page.hash {
3007            return None;
3008        }
3009        let sieves = Arc::new(decode_sieves(&bytes).ok()?);
3010        let _ = slot.set(sieves);
3011        slot.get().map(|held| held.as_slice())
3012    }
3013}
3014
3015/// The value sitting at one position of a dictionary's sorted order.
3016fn text_at_rank(dictionary: &Vector, rank: usize) -> Result<Value> {
3017    let code = dictionary.code_at_rank(rank)? as usize;
3018    let text = dictionary
3019        .try_text_at(code)?
3020        .ok_or_else(|| invalid("global dictionary order names a code it does not have"))?;
3021    Ok(Value::Varchar(text.into()))
3022}
3023
3024/// Writes one span of a file at an offset, without depending on where the cursor is.
3025///
3026/// The writer owns an offset of its own and passes it in here, so that nothing it writes depends on
3027/// a cursor that a read is entitled to move. Both of these can come back short and both loop.
3028#[cfg(unix)]
3029fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
3030    use std::os::unix::fs::FileExt;
3031    while !bytes.is_empty() {
3032        let written = file.write_at(bytes, offset).map_err(io)?;
3033        if written == 0 {
3034            return Err(invalid("a write to the native file wrote nothing"));
3035        }
3036        offset += written as u64;
3037        bytes = &bytes[written..];
3038    }
3039    Ok(())
3040}
3041
3042/// The same write, on the call Windows spells differently.
3043#[cfg(windows)]
3044fn write_at(file: &File, mut offset: u64, mut bytes: &[u8]) -> Result<()> {
3045    use std::os::windows::fs::FileExt;
3046    while !bytes.is_empty() {
3047        let written = file.seek_write(bytes, offset).map_err(io)?;
3048        if written == 0 {
3049            return Err(invalid("a write to the native file wrote nothing"));
3050        }
3051        offset += written as u64;
3052        bytes = &bytes[written..];
3053    }
3054    Ok(())
3055}
3056
3057/// Somewhere that is neither, where the cursor is all there is.
3058#[cfg(not(any(unix, windows)))]
3059fn write_at(file: &File, offset: u64, bytes: &[u8]) -> Result<()> {
3060    use std::io::Write;
3061    let mut file = file.try_clone().map_err(io)?;
3062    file.seek(SeekFrom::Start(offset)).map_err(io)?;
3063    file.write_all(bytes).map_err(io)
3064}
3065
3066/// Reads one span of a file at an offset, without moving a cursor anybody else can see.
3067///
3068/// Every reader of a table shares one [`File`] behind an [`Arc`], and a grouped aggregate reads its
3069/// pages from several threads at once, so this has to be positional. Seeking and then reading is
3070/// two calls with a gap in the middle, and in that gap another thread's seek lands and the read
3071/// comes back with somebody else's bytes.
3072///
3073/// Both of these can come back short, so both loop. A read of zero bytes before the span is filled
3074/// means the file stops earlier than the directory said it does.
3075#[cfg(unix)]
3076fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
3077    use std::os::unix::fs::FileExt;
3078    while !bytes.is_empty() {
3079        let read = file.read_at(bytes, offset).map_err(io)?;
3080        if read == 0 {
3081            return Err(invalid("column page ends before its declared length"));
3082        }
3083        offset += read as u64;
3084        bytes = &mut bytes[read..];
3085    }
3086    Ok(())
3087}
3088
3089/// The same read, on the call Windows spells differently.
3090///
3091/// `seek_read` is one `ReadFile` carrying the offset with it, so two of them cannot interleave the
3092/// way a seek and a read can. It does leave the shared cursor somewhere afterwards, which is why
3093/// nothing in this file may read that cursor.
3094#[cfg(windows)]
3095fn read_at(file: &File, mut offset: u64, mut bytes: &mut [u8]) -> Result<()> {
3096    use std::os::windows::fs::FileExt;
3097    while !bytes.is_empty() {
3098        let read = file.seek_read(bytes, offset).map_err(io)?;
3099        if read == 0 {
3100            return Err(invalid("column page ends before its declared length"));
3101        }
3102        offset += read as u64;
3103        bytes = &mut bytes[read..];
3104    }
3105    Ok(())
3106}
3107
3108/// Somewhere that is neither, where the cursor is all there is.
3109///
3110/// This one does race, and there is no way to write it so it does not. Nothing we build for runs
3111/// here, so it exists to keep the crate compiling rather than to be correct under threads.
3112#[cfg(not(any(unix, windows)))]
3113fn read_at(file: &File, offset: u64, bytes: &mut [u8]) -> Result<()> {
3114    let mut file = file.try_clone().map_err(io)?;
3115    file.seek(SeekFrom::Start(offset)).map_err(io)?;
3116    file.read_exact(bytes).map_err(io)
3117}
3118
3119fn type_tag(ty: &LogicalType) -> Result<u8> {
3120    match ty {
3121        LogicalType::SmallInt => Ok(1),
3122        LogicalType::Integer => Ok(2),
3123        LogicalType::BigInt => Ok(3),
3124        LogicalType::Varchar => Ok(4),
3125        LogicalType::Date => Ok(5),
3126        LogicalType::Timestamp => Ok(6),
3127        LogicalType::Boolean => Ok(7),
3128        LogicalType::TinyInt => Ok(8),
3129        LogicalType::UTinyInt => Ok(9),
3130        LogicalType::USmallInt => Ok(10),
3131        LogicalType::UInteger => Ok(11),
3132        LogicalType::UBigInt => Ok(12),
3133        _ => Err(Error::not_implemented(format!("native storage for {ty}"))),
3134    }
3135}
3136
3137fn tag_type(tag: u8) -> Result<LogicalType> {
3138    match tag {
3139        1 => Ok(LogicalType::SmallInt),
3140        2 => Ok(LogicalType::Integer),
3141        3 => Ok(LogicalType::BigInt),
3142        4 => Ok(LogicalType::Varchar),
3143        5 => Ok(LogicalType::Date),
3144        6 => Ok(LogicalType::Timestamp),
3145        7 => Ok(LogicalType::Boolean),
3146        8 => Ok(LogicalType::TinyInt),
3147        9 => Ok(LogicalType::UTinyInt),
3148        10 => Ok(LogicalType::USmallInt),
3149        11 => Ok(LogicalType::UInteger),
3150        12 => Ok(LogicalType::UBigInt),
3151        _ => Err(invalid("column type tag is unknown")),
3152    }
3153}
3154
3155fn put_u16(out: &mut Vec<u8>, value: u16) {
3156    out.extend_from_slice(&value.to_le_bytes());
3157}
3158fn put_u32(out: &mut Vec<u8>, value: u32) {
3159    out.extend_from_slice(&value.to_le_bytes());
3160}
3161fn put_u64(out: &mut Vec<u8>, value: u64) {
3162    out.extend_from_slice(&value.to_le_bytes());
3163}
3164fn put_var_u64(out: &mut Vec<u8>, mut value: u64) {
3165    while value >= 0x80 {
3166        out.push((value as u8 & 0x7f) | 0x80);
3167        value >>= 7;
3168    }
3169    out.push(value as u8);
3170}
3171
3172fn frequency_order(left: FrequencyValue, right: FrequencyValue) -> Ordering {
3173    match (left, right) {
3174        (FrequencyValue::Null, FrequencyValue::Null) => Ordering::Equal,
3175        (FrequencyValue::Null, _) => Ordering::Less,
3176        (_, FrequencyValue::Null) => Ordering::Greater,
3177        (FrequencyValue::Integer(left), FrequencyValue::Integer(right)) => left.cmp(&right),
3178        (FrequencyValue::Code(left), FrequencyValue::Code(right)) => left.cmp(&right),
3179        (FrequencyValue::Integer(_), FrequencyValue::Code(_)) => Ordering::Less,
3180        (FrequencyValue::Code(_), FrequencyValue::Integer(_)) => Ordering::Greater,
3181    }
3182}
3183
3184fn code_frequency(dictionary: &GlobalDictionary) -> FrequencySummary {
3185    let mut entries = dictionary
3186        .counts
3187        .iter()
3188        .enumerate()
3189        .filter(|(_, count)| **count != 0)
3190        .map(|(code, &count)| FrequencyEntry { value: FrequencyValue::Code(code as u32), count })
3191        .collect::<Vec<_>>();
3192    if dictionary.nulls != 0 {
3193        entries.push(FrequencyEntry { value: FrequencyValue::Null, count: dictionary.nulls });
3194    }
3195    entries.sort_unstable_by(|left, right| {
3196        right.count.cmp(&left.count).then_with(|| frequency_order(left.value, right.value))
3197    });
3198    let omitted_max = entries.get(FREQUENCY_ENTRIES).map_or(0, |entry| entry.count);
3199    entries.truncate(FREQUENCY_ENTRIES);
3200    FrequencySummary { entries, omitted_max, ordinals: Vec::new() }
3201}
3202
3203fn encode_directory(table: &Table) -> Result<Vec<u8>> {
3204    let mut out = DIRECTORY.to_vec();
3205    let name = table.name.as_bytes();
3206    put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("table name too long"))?);
3207    out.extend_from_slice(name);
3208    put_u16(&mut out, u16::try_from(table.fields.len()).map_err(|_| invalid("too many columns"))?);
3209    for field in &table.fields {
3210        let name = field.name.as_bytes();
3211        put_u16(&mut out, u16::try_from(name.len()).map_err(|_| invalid("column name too long"))?);
3212        out.extend_from_slice(name);
3213        out.push(type_tag(&field.ty)?);
3214        out.push(u8::from(field.not_null));
3215    }
3216    for dictionary in &table.dictionaries {
3217        match dictionary {
3218            None => out.push(0),
3219            Some(page) => {
3220                out.push(1);
3221                put_u64(&mut out, page.offset);
3222                put_u32(&mut out, page.length);
3223                put_u64(&mut out, page.hash);
3224            }
3225        }
3226    }
3227    for distinct in &table.distincts {
3228        match distinct {
3229            None => out.push(0),
3230            Some(count) => {
3231                out.push(1);
3232                put_u64(&mut out, *count);
3233            }
3234        }
3235    }
3236    put_u64(&mut out, u64::try_from(table.rows).map_err(|_| invalid("row count overflow"))?);
3237    put_u32(&mut out, u32::try_from(table.stripes.len()).map_err(|_| invalid("too many stripes"))?);
3238    for stripe in &table.stripes {
3239        put_u32(
3240            &mut out,
3241            u32::try_from(stripe.parts.len()).map_err(|_| invalid("too many parts in a stripe"))?,
3242        );
3243        for &rows in &stripe.parts {
3244            put_u32(&mut out, rows);
3245        }
3246        put_u64(&mut out, stripe.index.offset);
3247        put_u32(&mut out, stripe.index.length);
3248        for page in &stripe.pages {
3249            put_u64(&mut out, page.offset);
3250            put_u32(&mut out, page.length);
3251        }
3252        for (field, membership) in table.fields.iter().zip(&stripe.memberships) {
3253            if field.ty != LogicalType::Varchar {
3254                continue;
3255            }
3256            let page =
3257                membership.ok_or_else(|| invalid("string page has no code membership index"))?;
3258            put_u64(&mut out, page.offset);
3259            put_u32(&mut out, page.length);
3260            put_u64(&mut out, page.hash);
3261        }
3262        for sieve in &stripe.sieves {
3263            match sieve {
3264                None => out.push(0),
3265                Some(page) => {
3266                    out.push(1);
3267                    put_u64(&mut out, page.offset);
3268                    put_u32(&mut out, page.length);
3269                    put_u64(&mut out, page.hash);
3270                }
3271            }
3272        }
3273        for held in &stripe.part_ranges {
3274            match held {
3275                None => out.push(0),
3276                Some(page) => {
3277                    out.push(1);
3278                    put_u64(&mut out, page.offset);
3279                    put_u32(&mut out, page.length);
3280                    put_u64(&mut out, page.hash);
3281                }
3282            }
3283        }
3284        for range in stripe.zone.columns() {
3285            put_bound(&mut out, range.low.as_ref())?;
3286            put_bound(&mut out, range.high.as_ref())?;
3287            put_u32(
3288                &mut out,
3289                u32::try_from(range.nulls).map_err(|_| invalid("null count overflow"))?,
3290            );
3291            out.push(u8::from(range.exact));
3292            match range.sum {
3293                None => out.push(0),
3294                Some(total) => {
3295                    out.push(1);
3296                    out.extend_from_slice(&total.to_le_bytes());
3297                }
3298            }
3299        }
3300    }
3301    out.extend_from_slice(FREQUENCIES);
3302    put_u16(
3303        &mut out,
3304        u16::try_from(table.frequencies.len())
3305            .map_err(|_| invalid("too many frequency columns"))?,
3306    );
3307    for summary in &table.frequencies {
3308        let Some(summary) = summary else {
3309            out.push(0);
3310            continue;
3311        };
3312        out.push(1);
3313        put_u64(&mut out, summary.omitted_max);
3314        put_u32(
3315            &mut out,
3316            u32::try_from(summary.entries.len())
3317                .map_err(|_| invalid("too many frequency entries"))?,
3318        );
3319        for entry in &summary.entries {
3320            match entry.value {
3321                FrequencyValue::Null => out.push(0),
3322                FrequencyValue::Integer(value) => {
3323                    out.push(1);
3324                    out.extend_from_slice(&value.to_le_bytes());
3325                }
3326                FrequencyValue::Code(value) => {
3327                    out.push(2);
3328                    put_u32(&mut out, value);
3329                }
3330            }
3331            put_u64(&mut out, entry.count);
3332        }
3333        put_u32(
3334            &mut out,
3335            u32::try_from(summary.ordinals.len())
3336                .map_err(|_| invalid("too many frequency ordinals"))?,
3337        );
3338        let mut previous = 0_u64;
3339        for (at, &ordinal) in summary.ordinals.iter().enumerate() {
3340            let delta = if at == 0 {
3341                ordinal
3342            } else {
3343                ordinal
3344                    .checked_sub(previous)
3345                    .ok_or_else(|| invalid("frequency ordinals are not ordered"))?
3346            };
3347            if at != 0 && delta == 0 {
3348                return Err(invalid("frequency ordinals are not unique"));
3349            }
3350            put_var_u64(&mut out, delta);
3351            previous = ordinal;
3352        }
3353    }
3354    Ok(out)
3355}
3356
3357struct Cursor<'a> {
3358    bytes: &'a [u8],
3359    at: usize,
3360}
3361impl<'a> Cursor<'a> {
3362    fn take(&mut self, len: usize) -> Result<&'a [u8]> {
3363        let end = self.at.checked_add(len).ok_or_else(|| invalid("directory offset overflow"))?;
3364        let bytes =
3365            self.bytes.get(self.at..end).ok_or_else(|| invalid("directory is truncated"))?;
3366        self.at = end;
3367        Ok(bytes)
3368    }
3369    fn u8(&mut self) -> Result<u8> {
3370        Ok(self.take(1)?[0])
3371    }
3372    fn u16(&mut self) -> Result<u16> {
3373        Ok(u16::from_le_bytes(self.take(2)?.try_into().expect("two bytes")))
3374    }
3375    fn u32(&mut self) -> Result<u32> {
3376        Ok(u32::from_le_bytes(self.take(4)?.try_into().expect("four bytes")))
3377    }
3378    fn u64(&mut self) -> Result<u64> {
3379        Ok(u64::from_le_bytes(self.take(8)?.try_into().expect("eight bytes")))
3380    }
3381    fn var_u64(&mut self) -> Result<u64> {
3382        let mut value = 0_u64;
3383        for shift in (0..=63).step_by(7) {
3384            let byte = self.u8()?;
3385            let part = u64::from(byte & 0x7f);
3386            if shift == 63 && part > 1 {
3387                return Err(invalid("frequency ordinal varint overflows"));
3388            }
3389            value |= part << shift;
3390            if byte & 0x80 == 0 {
3391                return Ok(value);
3392            }
3393        }
3394        Err(invalid("frequency ordinal varint is too long"))
3395    }
3396    fn bound(&mut self) -> Result<Option<Bound>> {
3397        Ok(match self.u8()? {
3398            0 => None,
3399            1 => Some(Bound::Int(i128::from_le_bytes(
3400                self.take(16)?.try_into().expect("sixteen bytes"),
3401            ))),
3402            2 => Some(Bound::Real(f64::from_le_bytes(
3403                self.take(8)?.try_into().expect("eight bytes"),
3404            ))),
3405            3 => {
3406                let length = self.u32()? as usize;
3407                Some(Bound::Bytes(self.take(length)?.to_vec()))
3408            }
3409            4 => {
3410                let unscaled =
3411                    i128::from_le_bytes(self.take(16)?.try_into().expect("sixteen bytes"));
3412                Some(Bound::Scaled { unscaled, scale: self.u8()? })
3413            }
3414            _ => return Err(invalid("bound tag differs")),
3415        })
3416    }
3417    fn text(&mut self) -> Result<String> {
3418        let len = self.u16()? as usize;
3419        String::from_utf8(self.take(len)?.to_vec()).map_err(|_| invalid("name is not UTF-8"))
3420    }
3421}
3422
3423fn decode_directory(bytes: &[u8], size: u64) -> Result<Table> {
3424    let mut cur = Cursor { bytes, at: 0 };
3425    if cur.take(8)? != DIRECTORY {
3426        return Err(invalid("directory magic differs"));
3427    }
3428    let name = cur.text()?;
3429    let width = cur.u16()? as usize;
3430    let mut fields = Vec::with_capacity(width);
3431    for _ in 0..width {
3432        let name = cur.text()?;
3433        let ty = tag_type(cur.u8()?)?;
3434        let not_null = match cur.u8()? {
3435            0 => false,
3436            1 => true,
3437            _ => return Err(invalid("nullability flag differs")),
3438        };
3439        fields.push(Field { name, ty, not_null });
3440    }
3441    let mut dictionaries = Vec::with_capacity(width);
3442    for _ in 0..width {
3443        dictionaries.push(match cur.u8()? {
3444            0 => None,
3445            1 => {
3446                let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
3447                let end = page
3448                    .offset
3449                    .checked_add(u64::from(page.length))
3450                    .ok_or_else(|| invalid("dictionary page offset overflow"))?;
3451                // A global dictionary covers a whole column, not one bounded stripe. Its lazy
3452                // payload is intentionally allowed to grow past `MAX_PAGE`; only ordinary column
3453                // pages are capped there. `Writer::finish` has already bounded this length by the
3454                // on-disk `u32`, and the range check below keeps it inside the file.
3455                if page.offset < HEADER || end > size {
3456                    return Err(invalid("dictionary page range is outside the file"));
3457                }
3458                Some(page)
3459            }
3460            _ => return Err(invalid("dictionary page tag differs")),
3461        });
3462    }
3463    let mut distincts = Vec::with_capacity(width);
3464    for _ in 0..width {
3465        distincts.push(match cur.u8()? {
3466            0 => None,
3467            1 => Some(cur.u64()?),
3468            _ => return Err(invalid("distinct count tag differs")),
3469        });
3470    }
3471    let rows = usize::try_from(cur.u64()?).map_err(|_| invalid("row count does not fit"))?;
3472    let count = cur.u32()? as usize;
3473    let mut stripes = Vec::with_capacity(count);
3474    let mut total = 0_usize;
3475    for _ in 0..count {
3476        let count = cur.u32()? as usize;
3477        if count == 0 || count > STRIPE_PARTS {
3478            return Err(invalid("stripe part count is outside its bound"));
3479        }
3480        let mut parts = Vec::with_capacity(count);
3481        let mut stripe_rows = 0_usize;
3482        for _ in 0..count {
3483            let rows = cur.u32()?;
3484            if rows == 0 {
3485                return Err(invalid("empty part"));
3486            }
3487            parts.push(rows);
3488            stripe_rows = stripe_rows
3489                .checked_add(rows as usize)
3490                .ok_or_else(|| invalid("stripe row count overflow"))?;
3491        }
3492        total =
3493            total.checked_add(stripe_rows).ok_or_else(|| invalid("stripe row count overflow"))?;
3494        let index = Span { offset: cur.u64()?, length: cur.u32()? };
3495        let section = index_section(count)?;
3496        let wanted = section
3497            .checked_mul(width)
3498            .and_then(|bytes| u32::try_from(bytes).ok())
3499            .ok_or_else(|| invalid("index page length overflow"))?;
3500        let end = index
3501            .offset
3502            .checked_add(u64::from(index.length))
3503            .ok_or_else(|| invalid("index page offset overflow"))?;
3504        if index.offset < HEADER || end > size || index.length != wanted {
3505            return Err(invalid("index page range is outside the file"));
3506        }
3507        let mut pages = Vec::with_capacity(width);
3508        for _ in 0..width {
3509            let offset = cur.u64()?;
3510            let length = cur.u32()?;
3511            let end = offset
3512                .checked_add(u64::from(length))
3513                .ok_or_else(|| invalid("page offset overflow"))?;
3514            if offset < HEADER || end > size || length as usize > MAX_PAGE {
3515                return Err(invalid("page range is outside the file"));
3516            }
3517            pages.push(Span { offset, length });
3518        }
3519        let mut memberships = vec![None; width];
3520        for (column, field) in fields.iter().enumerate() {
3521            if field.ty != LogicalType::Varchar {
3522                continue;
3523            }
3524            let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
3525            let end = page
3526                .offset
3527                .checked_add(u64::from(page.length))
3528                .ok_or_else(|| invalid("membership page offset overflow"))?;
3529            if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
3530                return Err(invalid("membership page range is outside the file"));
3531            }
3532            memberships[column] = Some(page);
3533        }
3534        let mut sieves = vec![None; width];
3535        for sieve in sieves.iter_mut().take(width) {
3536            match cur.u8()? {
3537                0 => continue,
3538                1 => {}
3539                _ => return Err(invalid("a sieve page has an unknown tag")),
3540            }
3541            let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
3542            let end = page
3543                .offset
3544                .checked_add(u64::from(page.length))
3545                .ok_or_else(|| invalid("sieve page offset overflow"))?;
3546            if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
3547                return Err(invalid("sieve page range is outside the file"));
3548            }
3549            *sieve = Some(page);
3550        }
3551        let mut part_ranges = vec![None; width];
3552        for held in part_ranges.iter_mut().take(width) {
3553            match cur.u8()? {
3554                0 => continue,
3555                1 => {}
3556                _ => return Err(invalid("a part range page has an unknown tag")),
3557            }
3558            let page = Page { offset: cur.u64()?, length: cur.u32()?, hash: cur.u64()? };
3559            let end = page
3560                .offset
3561                .checked_add(u64::from(page.length))
3562                .ok_or_else(|| invalid("part range page offset overflow"))?;
3563            if page.offset < HEADER || end > size || page.length as usize > MAX_PAGE {
3564                return Err(invalid("part range page range is outside the file"));
3565            }
3566            *held = Some(page);
3567        }
3568        let mut ranges = Vec::with_capacity(width);
3569        for column in 0..width {
3570            let low = cur.bound()?;
3571            let high = cur.bound()?;
3572            let nulls = cur.u32()? as usize;
3573            if nulls > stripe_rows {
3574                return Err(invalid("null count exceeds stripe rows"));
3575            }
3576            let exact = cur.u8()? != 0;
3577            let sum = match cur.u8()? {
3578                0 => None,
3579                1 => Some(i128::from_le_bytes(
3580                    cur.take(16)?.try_into().map_err(|_| invalid("a stripe sum is truncated"))?,
3581                )),
3582                _ => return Err(invalid("a stripe sum has an unknown tag")),
3583            };
3584            // Files written before the ends of a decimal or a timestamp column carried their power
3585            // of ten hold a bare integer here, and that integer is the one the column holds, which
3586            // is what the power is over. So the type puts it back on the way in and an old file
3587            // prunes as well as a new one. A file that already wrote the power keeps it, because
3588            // this leaves anything that is not an integer alone.
3589            let ty = &fields.get(column).ok_or_else(|| invalid("a stripe range has no column"))?.ty;
3590            let low = low.map(|bound| scaled_as(bound, ty));
3591            let high = high.map(|bound| scaled_as(bound, ty));
3592            ranges.push(Range { low, high, nulls, exact, sum });
3593        }
3594        stripes.push(Stripe {
3595            rows: stripe_rows,
3596            parts,
3597            index,
3598            pages,
3599            memberships,
3600            sieves,
3601            part_ranges,
3602            zone: Zone::from_ranges(ranges),
3603        });
3604    }
3605    if total != rows {
3606        return Err(invalid("table row count differs from stripes"));
3607    }
3608    let frequencies = if cur.at == bytes.len() {
3609        vec![None; width]
3610    } else {
3611        if cur.take(8)? != FREQUENCIES {
3612            return Err(invalid("directory extension magic differs"));
3613        }
3614        if cur.u16()? as usize != width {
3615            return Err(invalid("frequency column count differs"));
3616        }
3617        let mut frequencies = Vec::with_capacity(width);
3618        for field in &fields {
3619            let summary = match cur.u8()? {
3620                0 => None,
3621                1 => {
3622                    let omitted_max = cur.u64()?;
3623                    let count = cur.u32()? as usize;
3624                    if count > FREQUENCY_ENTRIES {
3625                        return Err(invalid("frequency entry count exceeds its bound"));
3626                    }
3627                    let mut entries = Vec::with_capacity(count);
3628                    // row at a time: directory decoding validates each persisted bounded frequency entry.
3629                    for _ in 0..count {
3630                        let value = match cur.u8()? {
3631                            0 => FrequencyValue::Null,
3632                            1 => FrequencyValue::Integer(i128::from_le_bytes(
3633                                cur.take(16)?.try_into().expect("sixteen bytes"),
3634                            )),
3635                            2 => FrequencyValue::Code(cur.u32()?),
3636                            _ => return Err(invalid("frequency value tag differs")),
3637                        };
3638                        let valid = matches!(
3639                            (&field.ty, value),
3640                            (_, FrequencyValue::Null)
3641                                | (LogicalType::Varchar, FrequencyValue::Code(_))
3642                                | (
3643                                    LogicalType::TinyInt
3644                                        | LogicalType::SmallInt
3645                                        | LogicalType::Integer
3646                                        | LogicalType::BigInt
3647                                        | LogicalType::UTinyInt
3648                                        | LogicalType::USmallInt
3649                                        | LogicalType::UInteger
3650                                        | LogicalType::UBigInt
3651                                        | LogicalType::Date
3652                                        | LogicalType::Timestamp,
3653                                    FrequencyValue::Integer(_),
3654                                )
3655                        );
3656                        if !valid {
3657                            return Err(invalid("frequency value does not match its column"));
3658                        }
3659                        let count = cur.u64()?;
3660                        if count == 0 || count > rows as u64 {
3661                            return Err(invalid("frequency count is outside the table"));
3662                        }
3663                        entries.push(FrequencyEntry { value, count });
3664                    }
3665                    if entries.windows(2).any(|pair| pair[0].count < pair[1].count) {
3666                        return Err(invalid("frequency entries are not descending"));
3667                    }
3668                    let ordinals = {
3669                        let ordinal_count = cur.u32()? as usize;
3670                        if ordinal_count > FREQUENCY_ORDINALS || ordinal_count > rows {
3671                            return Err(invalid("frequency ordinal count exceeds its bound"));
3672                        }
3673                        let mut ordinals = Vec::with_capacity(ordinal_count);
3674                        let mut previous = 0_u64;
3675                        for at in 0..ordinal_count {
3676                            let delta = cur.var_u64()?;
3677                            if at != 0 && delta == 0 {
3678                                return Err(invalid("frequency ordinals are not increasing"));
3679                            }
3680                            let ordinal = if at == 0 {
3681                                delta
3682                            } else {
3683                                previous
3684                                    .checked_add(delta)
3685                                    .ok_or_else(|| invalid("frequency ordinal overflows"))?
3686                            };
3687                            if ordinal >= rows as u64 {
3688                                return Err(invalid("frequency ordinal is outside the table"));
3689                            }
3690                            ordinals.push(ordinal);
3691                            previous = ordinal;
3692                        }
3693                        ordinals
3694                    };
3695                    Some(FrequencySummary { entries, omitted_max, ordinals })
3696                }
3697                _ => return Err(invalid("frequency summary tag differs")),
3698            };
3699            frequencies.push(summary);
3700        }
3701        frequencies
3702    };
3703    if cur.at != bytes.len() {
3704        return Err(invalid("directory has trailing bytes"));
3705    }
3706    Ok(Table { name, fields, stripes, rows, dictionaries, distincts, frequencies })
3707}
3708
3709fn put_bound(out: &mut Vec<u8>, bound: Option<&Bound>) -> Result<()> {
3710    match bound {
3711        None => out.push(0),
3712        Some(Bound::Int(value)) => {
3713            out.push(1);
3714            out.extend_from_slice(&value.to_le_bytes());
3715        }
3716        Some(Bound::Real(value)) => {
3717            out.push(2);
3718            out.extend_from_slice(&value.to_le_bytes());
3719        }
3720        Some(Bound::Bytes(value)) => {
3721            out.push(3);
3722            put_u32(out, u32::try_from(value.len()).map_err(|_| invalid("bound length overflow"))?);
3723            out.extend_from_slice(value);
3724        }
3725        Some(Bound::Scaled { unscaled, scale }) => {
3726            out.push(4);
3727            out.extend_from_slice(&unscaled.to_le_bytes());
3728            out.push(*scale);
3729        }
3730    }
3731    Ok(())
3732}
3733
3734/// Which cascades are worth trying on a run of dictionary codes.
3735///
3736/// The exhaustive chooser encodes every candidate at every level of a cascade three deep and keeps
3737/// the smallest, which on a part of 1024 codes is around a hundred full encodes to decide something
3738/// three candidates were always going to win. It is the right default for a crate that does not
3739/// know what it is looking at. Here we do know. Codes are counted from zero in the order the values
3740/// were first seen, so a part of them is one value, or a narrow band, or a few long runs, and those
3741/// are constant, frame of reference and run length. Nothing else has ever come first on this data.
3742///
3743/// A dictionary of dictionary codes is the one candidate that can never pay, because the codes are
3744/// already the dictionary, and it is also the most expensive one to try. Below the top level the
3745/// streams are an RLE's run values and run lengths, which are integers in their own right with no
3746/// runs left in them, so only the two flat candidates go down there.
3747///
3748/// This is size given up for time on purpose, and the ablation is this chooser against
3749/// [`chooser::EXHAUSTIVE`] on the same file.
3750#[derive(Debug)]
3751struct Codes;
3752
3753impl chooser::Chooser for Codes {
3754    fn name(&self) -> &'static str {
3755        "codes"
3756    }
3757
3758    fn narrow_strings(
3759        &self,
3760        _values: &[&[u8]],
3761        offered: &[string::Kind],
3762        _depth: u8,
3763    ) -> Vec<string::Kind> {
3764        // Never reached, because nothing here encodes strings through the cascade. The trait asks
3765        // for it and the honest answer to a question we have no opinion on is the whole list.
3766        offered.to_vec()
3767    }
3768
3769    fn narrow_integers(
3770        &self,
3771        _values: &[i64],
3772        offered: &[integer::Kind],
3773        depth: u8,
3774    ) -> Vec<integer::Kind> {
3775        let keep: &[integer::Kind] = if depth == 0 {
3776            &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Rle]
3777        } else {
3778            &[integer::Kind::Constant, integer::Kind::Packed]
3779        };
3780        let narrowed: Vec<integer::Kind> =
3781            offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3782        // The contract is a non empty subset, and a chunk that offers none of the three is a chunk
3783        // this has no opinion about rather than one that cannot be written.
3784        if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3785    }
3786}
3787
3788/// Which cascades are worth trying on a part of plain integers.
3789///
3790/// Wider than [`Codes`] because the values are not codes and carry whatever shape the column has.
3791/// A timestamp column climbs, so delta is the one that matters and is the reason this exists at
3792/// all: three timestamp columns in ClickBench were coming out at exactly eight bytes a row with
3793/// nothing asked of them. The same three columns are why the stride is here, since a timestamp
3794/// loaded from a source that recorded whole seconds is microseconds with twenty zero bits under
3795/// every value. A column that is one value with a handful of exceptions is sparse. What is still
3796/// left out is the dictionary, for the same reason as in [`Codes`]: it is the most
3797/// expensive candidate to try and this file already puts the columns that want one through a
3798/// dictionary of their own before they ever reach here.
3799#[derive(Debug)]
3800struct Fixed;
3801
3802impl chooser::Chooser for Fixed {
3803    fn name(&self) -> &'static str {
3804        "fixed"
3805    }
3806
3807    fn narrow_strings(
3808        &self,
3809        _values: &[&[u8]],
3810        offered: &[string::Kind],
3811        _depth: u8,
3812    ) -> Vec<string::Kind> {
3813        offered.to_vec()
3814    }
3815
3816    fn narrow_integers(
3817        &self,
3818        _values: &[i64],
3819        offered: &[integer::Kind],
3820        depth: u8,
3821    ) -> Vec<integer::Kind> {
3822        let keep: &[integer::Kind] = if depth == 0 {
3823            &[
3824                integer::Kind::Constant,
3825                integer::Kind::Packed,
3826                integer::Kind::Delta,
3827                integer::Kind::Rle,
3828                integer::Kind::Sparse,
3829                integer::Kind::Strided,
3830            ]
3831        } else {
3832            &[integer::Kind::Constant, integer::Kind::Packed, integer::Kind::Delta]
3833        };
3834        let narrowed: Vec<integer::Kind> =
3835            offered.iter().copied().filter(|kind| keep.contains(kind)).collect();
3836        if narrowed.is_empty() { offered.to_vec() } else { narrowed }
3837    }
3838}
3839
3840/// Every value of an integer part as an `i64`, or `None` for a part this cannot widen without
3841/// losing one.
3842///
3843/// `UBIGINT` is the only integer type left out, because half its range does not fit and a page that
3844/// silently wrapped would be worse than a page that stays plain. Booleans and strings are not
3845/// integers and have their own ways of being small.
3846fn widened(data: &Data) -> Option<Vec<i64>> {
3847    match data {
3848        Data::Int8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3849        Data::UInt8(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3850        Data::Int16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3851        Data::UInt16(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3852        Data::Int32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3853        Data::UInt32(values) => Some(values.iter().map(|value| i64::from(*value)).collect()),
3854        Data::Int64(values) => Some(values.to_vec()),
3855        _ => None,
3856    }
3857}
3858
3859/// An integer type a cascaded page can be read back into, and how to tell whether a value fits.
3860///
3861/// This exists so that the check and the conversion can be two loops instead of one. `TryFrom` puts
3862/// them together, which is the right shape for one value and the wrong one for a page: a fallible
3863/// conversion a value at a time is a branch a value at a time, the branch decides whether the loop
3864/// keeps going, and a loop like that is one no compiler will widen.
3865trait Narrow: Copy {
3866    /// How wide this type is, and what to add to a value to put its range at the bottom of a `u64`.
3867    ///
3868    /// Half the width for a signed type, which is what moves its smallest value to zero, and nothing
3869    /// for an unsigned one, whose smallest value is already there.
3870    const BIASED: (u32, u64);
3871
3872    /// The value narrowed, which the caller has already shown fits.
3873    fn narrow(value: i64) -> Self;
3874}
3875
3876/// The bits of `value` a `T` cannot hold, and zero when the value fits.
3877///
3878/// The question is asked this way round because the answers or together. A page fits when every
3879/// residue in it is zero, so the loop is an or into an accumulator and the decision is one test
3880/// after it, where asking whether each value is between a floor and a ceiling gives an answer that
3881/// does not combine and turns into a running minimum and maximum.
3882///
3883/// Biasing and shifting is what the answer is made of, rather than anything that reads more like the
3884/// question, because those are the operations a machine has four of. A 64 bit integer minimum is
3885/// AVX-512. So is a 64 bit arithmetic shift right, which is how the sign extension this could be
3886/// written as would have to be done. An add and a logical shift right are AVX2 and are on every
3887/// machine this runs on, so this is the form that gets four values a cycle instead of one.
3888///
3889/// Adding the bias moves the type's range to `0..=2^bits`, wrapping, so everything in range shifts
3890/// away to nothing and everything outside it leaves something behind. A negative value under an
3891/// unsigned type is caught by the same shift, because a negative `i64` read as a `u64` is enormous.
3892#[allow(clippy::cast_sign_loss, reason = "a residue is a bit pattern and not a number")]
3893fn residue<T: Narrow>(value: i64) -> u64 {
3894    let (bits, bias) = T::BIASED;
3895    (value as u64).wrapping_add(bias) >> bits
3896}
3897
3898/// Says a primitive integer narrows with `as`, and where the bottom of its range is.
3899///
3900/// `as` is a truncation and is the right operation here only because [`fit`] has already found every
3901/// residue zero, and it is what makes the second loop a narrowing store with no branch in it.
3902macro_rules! narrows {
3903    ($($ty:ty => $bias:expr),* $(,)?) => {$(
3904        impl Narrow for $ty {
3905            const BIASED: (u32, u64) = (<$ty>::BITS, $bias);
3906
3907            #[allow(
3908                clippy::cast_possible_truncation,
3909                clippy::cast_sign_loss,
3910                reason = "the caller has checked the bits this truncates away"
3911            )]
3912            fn narrow(value: i64) -> Self {
3913                value as Self
3914            }
3915        }
3916    )*};
3917}
3918
3919narrows! {
3920    i8 => 1 << 7,
3921    u8 => 0,
3922    i16 => 1 << 15,
3923    u16 => 0,
3924    i32 => 1 << 31,
3925    u32 => 0,
3926}
3927
3928/// Narrows a page's values, refusing the page if any of them does not fit.
3929///
3930/// The check first and the conversion second, rather than a fallible conversion a value at a time.
3931/// Both loops here are ones a compiler widens: [`residue`] is three instructions a lane and a
3932/// narrowing store is one. The version before this was a `TryFrom` and a `collect` into a `Result`,
3933/// which is a compare, a branch and a short circuit a value at a time, and on ClickBench 39 it was
3934/// seven percent of the query. The version after that kept a running minimum and maximum, which is
3935/// the obvious way to ask and needs a 64 bit integer minimum that AVX2 does not have, so it stayed
3936/// a value at a time and was still ten percent of the same query.
3937///
3938/// An empty page has nothing to refuse, which falls out of the accumulator starting at zero rather
3939/// than needing a case of its own.
3940fn fit<T: Narrow>(values: &[i64]) -> Result<Vec<T>> {
3941    let mut spilled = 0u64;
3942    for value in values {
3943        spilled |= residue::<T>(*value);
3944    }
3945    if spilled != 0 {
3946        return Err(invalid("page value is not of its type"));
3947    }
3948    Ok(values.iter().map(|value| T::narrow(*value)).collect())
3949}
3950
3951/// The same values back in the width the column is declared at.
3952///
3953/// A value that does not fit is a page that disagrees with the directory about what the column is,
3954/// which is a damaged file rather than a caller error, so it is refused rather than truncated.
3955fn narrowed(ty: &LogicalType, values: Vec<i64>) -> Result<Data> {
3956    Ok(match ty {
3957        LogicalType::TinyInt => Data::Int8(fit::<i8>(&values)?.into()),
3958        LogicalType::UTinyInt => Data::UInt8(fit::<u8>(&values)?.into()),
3959        LogicalType::SmallInt => Data::Int16(fit::<i16>(&values)?.into()),
3960        LogicalType::USmallInt => Data::UInt16(fit::<u16>(&values)?.into()),
3961        LogicalType::Integer | LogicalType::Date => Data::Int32(fit::<i32>(&values)?.into()),
3962        LogicalType::UInteger => Data::UInt32(fit::<u32>(&values)?.into()),
3963        LogicalType::BigInt | LogicalType::Timestamp => Data::Int64(values.into()),
3964        _ => return Err(invalid("cascade codec belongs to a page that is not integers")),
3965    })
3966}
3967
3968/// How many bytes a part of this type costs written out plainly, which is what the cascade has to
3969/// beat before it is worth the decode.
3970fn plain_width(ty: &LogicalType) -> Option<usize> {
3971    Some(match ty {
3972        LogicalType::TinyInt | LogicalType::UTinyInt => 1,
3973        LogicalType::SmallInt | LogicalType::USmallInt => 2,
3974        LogicalType::Integer | LogicalType::UInteger | LogicalType::Date => 4,
3975        LogicalType::BigInt | LogicalType::Timestamp => 8,
3976        _ => return None,
3977    })
3978}
3979
3980/// A part's plain integers through the cascade, or `None` when nothing it offers is worth it.
3981///
3982/// What it has to beat is whatever the page would otherwise have cost, which is the bit packed form
3983/// where there is one and the plain width where there is not. Both are cheaper to decode than a
3984/// cascade, so a tie goes to them.
3985fn cascaded(
3986    flat: &Vector,
3987    ty: &LogicalType,
3988    packed: Option<&Packed<'_>>,
3989) -> Result<Option<Vec<u8>>> {
3990    let (Some(width), Some(data)) = (plain_width(ty), flat.data()) else { return Ok(None) };
3991    let Some(values) = widened(data) else { return Ok(None) };
3992    let plain = values.len().saturating_mul(width);
3993    let best = match packed {
3994        // The tag, the base, the word count and the words, which is what the codec 2 branch writes.
3995        Some(packed) => plain.min(21 + size_of_val(packed.words())),
3996        None => plain,
3997    };
3998    let out = integer::encode_with(&values, &Fixed)?;
3999    Ok((out.len() < best).then_some(out))
4000}
4001
4002/// A part's dictionary codes through the integer cascade, or `None` when the cascade did not pay.
4003///
4004/// Until now this stream was a `u32` a row with nothing asked of it, and on ClickBench that was
4005/// 400,185,326 bytes for every one of the 28 varchar columns, the same count for `URL` as for a
4006/// column holding the empty string in nearly every row. Codes are dense integers counted from zero
4007/// and a part holds 1024 of them, which is the shape frame of reference is best at, and a column
4008/// with one value everywhere comes back a constant costing nothing per row rather than four bytes.
4009///
4010/// The result is taken only when it is smaller than the plain form. A cascade is allowed to come
4011/// out larger on a part whose codes are genuinely wide, `URL` has about sixty million distinct
4012/// values, and there is no reason to pay for the decode when it does.
4013fn encoded_codes(codes: &[u32]) -> Result<Option<Vec<u8>>> {
4014    let wide: Vec<i64> = codes.iter().map(|code| i64::from(*code)).collect();
4015    let coded = integer::encode_with(&wide, &Codes)?;
4016    let plain = codes.len().saturating_mul(size_of::<u32>());
4017    Ok((coded.len() < plain).then_some(coded))
4018}
4019
4020fn encode(
4021    vector: &Vector,
4022    global: Option<&mut GlobalDictionary>,
4023) -> Result<(Vec<u8>, Option<Vec<u32>>)> {
4024    let ty = vector.logical_type();
4025    // flatten: the file writer needs a uniform scalar page and does it once per loaded chunk.
4026    let flat = vector.flatten()?;
4027    let mut out = Vec::new();
4028    let mut global_codes = None;
4029    if let Some(global) = global {
4030        let mut codes = Vec::with_capacity(flat.len());
4031        for row in 0..flat.len() {
4032            let text = flat.text_at(row).unwrap_or("");
4033            let code = global.code(text)?;
4034            global.observe(code, flat.is_null_at(row))?;
4035            codes.push(code);
4036        }
4037        global_codes = Some(codes);
4038    }
4039    let membership = global_codes.as_deref().map(unique_codes);
4040    let dictionary = if global_codes.is_none() && ty == &LogicalType::Varchar {
4041        string_dictionary(&flat)?
4042    } else {
4043        None
4044    };
4045    let packed_vector = if dictionary.is_none() && global_codes.is_none() {
4046        Some(flat.bit_packed()?)
4047    } else {
4048        None
4049    };
4050    let packed = packed_vector.as_ref().and_then(Vector::packed_parts);
4051    let coded = match global_codes.as_deref() {
4052        Some(codes) => encoded_codes(codes)?,
4053        None => None,
4054    };
4055    // Only where nothing else has claimed the page, which is the plain integer case. A packed part
4056    // is still on the table because the cascade has to beat it too: the bit pack takes a part only
4057    // when it halves it, so a column that shrinks by a third was coming out whole.
4058    let cascade = if dictionary.is_none() && global_codes.is_none() {
4059        cascaded(&flat, ty, packed.as_ref())?
4060    } else {
4061        None
4062    };
4063    out.push(if coded.is_some() {
4064        4
4065    } else if cascade.is_some() {
4066        5
4067    } else if global_codes.is_some() {
4068        3
4069    } else if dictionary.is_some() {
4070        1
4071    } else if packed.is_some() {
4072        2
4073    } else {
4074        0
4075    });
4076    let nulls = flat.validity();
4077    let flag = match nulls {
4078        Validity::AllValid => 0,
4079        Validity::AllInvalid => 1,
4080        Validity::Mask(_) => 2,
4081    };
4082    out.push(flag);
4083    if flag == 2 {
4084        for group in (0..vector.len()).step_by(8) {
4085            let mut bits = 0_u8;
4086            for bit in 0..8 {
4087                if group + bit < vector.len() && !flat.is_null_at(group + bit) {
4088                    bits |= 1 << bit;
4089                }
4090            }
4091            out.push(bits);
4092        }
4093    }
4094    if let Some(coded) = coded {
4095        out.extend_from_slice(&coded);
4096        return Ok((out, membership));
4097    }
4098    if let Some(cascade) = cascade {
4099        out.extend_from_slice(&cascade);
4100        return Ok((out, membership));
4101    }
4102    if let Some(codes) = global_codes {
4103        for code in codes {
4104            put_u32(&mut out, code);
4105        }
4106        return Ok((out, membership));
4107    }
4108    if let Some(dictionary) = dictionary {
4109        out.extend_from_slice(&dictionary);
4110        return Ok((out, membership));
4111    }
4112    if let Some(packed) = packed {
4113        if packed.offset() != 0 {
4114            return Err(invalid("writer received a sliced packed vector"));
4115        }
4116        out.push(u8::try_from(packed.width()).map_err(|_| invalid("packed width overflow"))?);
4117        out.extend_from_slice(&packed.base().to_le_bytes());
4118        put_u32(
4119            &mut out,
4120            u32::try_from(packed.words().len()).map_err(|_| invalid("too many packed words"))?,
4121        );
4122        for word in packed.words() {
4123            put_u64(&mut out, *word);
4124        }
4125        return Ok((out, membership));
4126    }
4127    let data = flat.data().ok_or_else(|| invalid("scalar column did not flatten"))?;
4128    match (ty, data) {
4129        (LogicalType::TinyInt, Data::Int8(values)) => {
4130            for value in &**values {
4131                out.extend_from_slice(&value.to_le_bytes());
4132            }
4133        }
4134        (LogicalType::UTinyInt, Data::UInt8(values)) => {
4135            for value in &**values {
4136                out.extend_from_slice(&value.to_le_bytes());
4137            }
4138        }
4139        (LogicalType::SmallInt, Data::Int16(values)) => {
4140            for value in &**values {
4141                out.extend_from_slice(&value.to_le_bytes());
4142            }
4143        }
4144        (LogicalType::USmallInt, Data::UInt16(values)) => {
4145            for value in &**values {
4146                out.extend_from_slice(&value.to_le_bytes());
4147            }
4148        }
4149        (LogicalType::UInteger, Data::UInt32(values)) => {
4150            for value in &**values {
4151                out.extend_from_slice(&value.to_le_bytes());
4152            }
4153        }
4154        (LogicalType::UBigInt, Data::UInt64(values)) => {
4155            for value in &**values {
4156                out.extend_from_slice(&value.to_le_bytes());
4157            }
4158        }
4159        (LogicalType::Integer | LogicalType::Date, Data::Int32(values)) => {
4160            for value in &**values {
4161                out.extend_from_slice(&value.to_le_bytes());
4162            }
4163        }
4164        (LogicalType::BigInt | LogicalType::Timestamp, Data::Int64(values)) => {
4165            for value in &**values {
4166                out.extend_from_slice(&value.to_le_bytes());
4167            }
4168        }
4169        (LogicalType::Boolean, Data::Bool(values)) => {
4170            for value in &**values {
4171                out.push(u8::from(*value));
4172            }
4173        }
4174        (LogicalType::Varchar, Data::Varlen(values)) => {
4175            let mut bytes = Vec::new();
4176            put_u32(&mut out, 0);
4177            for row in 0..vector.len() {
4178                let value = values.bytes(row).ok_or_else(|| invalid("string view is invalid"))?;
4179                bytes.extend_from_slice(value);
4180                put_u32(
4181                    &mut out,
4182                    u32::try_from(bytes.len())
4183                        .map_err(|_| invalid("string payload exceeds 4GiB"))?,
4184                );
4185            }
4186            out.extend_from_slice(&bytes);
4187        }
4188        _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
4189    }
4190    Ok((out, membership))
4191}
4192
4193fn put_varint(out: &mut Vec<u8>, mut value: u32) {
4194    while value >= 0x80 {
4195        out.push((value as u8 & 0x7f) | 0x80);
4196        value >>= 7;
4197    }
4198    out.push(value as u8);
4199}
4200
4201/// The distinct codes of one part, which is what a stripe's membership index is merged from.
4202fn unique_codes(codes: &[u32]) -> Vec<u32> {
4203    let mut unique = codes.to_vec();
4204    unique.sort_unstable();
4205    unique.dedup();
4206    unique
4207}
4208
4209/// The union of the sorted distinct codes of every part in a stripe.
4210///
4211/// Pairwise up a tree rather than one long list concatenated and sorted. Both are the same order of
4212/// work on paper and the tree is the one that does not sort what is already in order: sixty four
4213/// sorted lists become one in six passes over the values.
4214fn merged_codes(lists: Vec<Vec<u32>>) -> Vec<u32> {
4215    let mut lists = lists;
4216    while lists.len() > 1 {
4217        let mut next = Vec::with_capacity(lists.len().div_ceil(2));
4218        for pair in lists.chunks(2) {
4219            match pair {
4220                [left, right] => next.push(merged_pair(left, right)),
4221                [only] => next.push(only.clone()),
4222                _ => {}
4223            }
4224        }
4225        lists = next;
4226    }
4227    lists.pop().unwrap_or_default()
4228}
4229
4230fn merged_pair(left: &[u32], right: &[u32]) -> Vec<u32> {
4231    let mut out = Vec::with_capacity(left.len().saturating_add(right.len()));
4232    let mut at = 0;
4233    let mut to = 0;
4234    while at < left.len() && to < right.len() {
4235        match left[at].cmp(&right[to]) {
4236            Ordering::Less => {
4237                out.push(left[at]);
4238                at += 1;
4239            }
4240            Ordering::Greater => {
4241                out.push(right[to]);
4242                to += 1;
4243            }
4244            Ordering::Equal => {
4245                out.push(left[at]);
4246                at += 1;
4247                to += 1;
4248            }
4249        }
4250    }
4251    out.extend_from_slice(&left[at..]);
4252    out.extend_from_slice(&right[to..]);
4253    out
4254}
4255
4256/// The widest bounds and the total null count of a stripe, from the bounds of its parts.
4257///
4258/// A bound that is missing from any part is missing from the stripe, because a missing bound means
4259/// nothing is known and a stripe that holds an unknown cannot claim one.
4260fn merged_range(ranges: impl Iterator<Item = Range>) -> Range {
4261    let mut merged = Range::default();
4262    let mut first = true;
4263    for range in ranges {
4264        merged.nulls = merged.nulls.saturating_add(range.nulls);
4265        // Both of these have to survive every part, so one part that could not say anything makes
4266        // the stripe unable to say it either. A sum is dropped on overflow rather than wrapped,
4267        // which leaves the stripe with exact ends and no total, which is a true thing to say.
4268        merged.sum = match (merged.sum.take(), range.sum) {
4269            (Some(held), Some(next)) if !first => held.checked_add(next),
4270            (_, next) if first => next,
4271            _ => None,
4272        };
4273        merged.exact = if first { range.exact } else { merged.exact && range.exact };
4274        if first {
4275            merged.low = range.low;
4276            merged.high = range.high;
4277            first = false;
4278            continue;
4279        }
4280        merged.low = match (merged.low.take(), range.low) {
4281            (Some(held), Some(next)) => Some(held.smaller(next)),
4282            _ => None,
4283        };
4284        merged.high = match (merged.high.take(), range.high) {
4285            (Some(held), Some(next)) => Some(held.larger(next)),
4286            _ => None,
4287        };
4288    }
4289    merged
4290}
4291
4292/// One stripe's sieves for one column: the part count, a length for each part, then their bytes.
4293///
4294/// One page for the whole stripe rather than one per part, because a part's sieve is a few hundred
4295/// bytes and sixty four of those are sixty four directory entries and sixty four reads for something
4296/// a scan walks straight through. A part with no sieve writes a length of zero and costs four bytes.
4297/// `bound` cut down to [`PART_BOUND_BYTES`], still a bound of the side it was.
4298///
4299/// A prefix of a string sorts at or before the string, so cutting one down leaves a low end that is
4300/// still a low end. A high end has to go the other way, so the cut prefix is stepped up at the last
4301/// byte that can carry it, and a prefix of nothing but `0xFF` has no such byte and gives up the
4302/// bound rather than claiming one that is too small. Anything that is not a string is already a
4303/// fixed width and is left alone.
4304fn shortened(bound: Option<Bound>, high: bool) -> Option<Bound> {
4305    match bound {
4306        Some(Bound::Bytes(mut value)) if value.len() > PART_BOUND_BYTES => {
4307            value.truncate(PART_BOUND_BYTES);
4308            if !high {
4309                return Some(Bound::Bytes(value));
4310            }
4311            while let Some(last) = value.pop() {
4312                if last < u8::MAX {
4313                    value.push(last + 1);
4314                    return Some(Bound::Bytes(value));
4315                }
4316            }
4317            None
4318        }
4319        other => other,
4320    }
4321}
4322
4323/// The ranges of one column's parts of one stripe, as a page.
4324///
4325/// The two ends and the null count, and not `exact` or the total. Those two answer a `MIN` or a
4326/// `SUM` out of the directory, and the directory already answers those per stripe, where the same
4327/// number costs sixty times less to keep. What a part range is for is skipping the part, and
4328/// skipping needs the ends. So a range read back from here says it is not exact, which is true of a
4329/// string end that was cut down anyway.
4330fn encode_part_ranges(ranges: &[Range]) -> Result<Vec<u8>> {
4331    let mut out = Vec::new();
4332    put_u32(
4333        &mut out,
4334        u32::try_from(ranges.len()).map_err(|_| invalid("too many parts in a stripe"))?,
4335    );
4336    for range in ranges {
4337        put_bound(&mut out, shortened(range.low.clone(), false).as_ref())?;
4338        put_bound(&mut out, shortened(range.high.clone(), true).as_ref())?;
4339        put_u32(&mut out, u32::try_from(range.nulls).map_err(|_| invalid("null count overflow"))?);
4340    }
4341    Ok(out)
4342}
4343
4344/// The ranges one encoded page holds, one entry per part of the stripe.
4345fn decode_part_ranges(bytes: &[u8]) -> Result<Vec<Range>> {
4346    let mut cur = Cursor { bytes, at: 0 };
4347    let parts = cur.u32()? as usize;
4348    let mut out = Vec::new();
4349    for _ in 0..parts {
4350        let low = cur.bound()?;
4351        let high = cur.bound()?;
4352        let nulls = cur.u32()? as usize;
4353        out.push(Range { low, high, nulls, exact: false, sum: None });
4354    }
4355    Ok(out)
4356}
4357
4358fn encode_sieves<'a>(sieves: impl Iterator<Item = &'a Option<Sieve>>) -> Result<Vec<u8>> {
4359    let held: Vec<&Option<Sieve>> = sieves.collect();
4360    let mut out = Vec::new();
4361    put_u32(
4362        &mut out,
4363        u32::try_from(held.len()).map_err(|_| invalid("too many parts in a stripe"))?,
4364    );
4365    for sieve in &held {
4366        let length = sieve.as_ref().map_or(0, Sieve::len);
4367        put_u32(&mut out, u32::try_from(length).map_err(|_| invalid("sieve length overflow"))?);
4368    }
4369    // flatten: a part with no sieve wrote a length of zero above and contributes no bytes here.
4370    for sieve in held.into_iter().flatten() {
4371        out.extend_from_slice(&sieve.to_bytes());
4372    }
4373    Ok(out)
4374}
4375
4376/// The sieves one encoded page holds, one entry per part of the stripe.
4377///
4378/// A part whose bytes are not a sieve this version understands comes back as `None`, which is a part
4379/// that gets read. That is how a file written by a later version of the sieve stays readable rather
4380/// than being a corrupt page.
4381fn decode_sieves(bytes: &[u8]) -> Result<Vec<Option<Sieve>>> {
4382    let parts = u32::from_le_bytes(
4383        bytes
4384            .get(..4)
4385            .ok_or_else(|| invalid("sieve page is truncated"))?
4386            .try_into()
4387            .map_err(|_| invalid("sieve page is truncated"))?,
4388    ) as usize;
4389    let mut lengths = Vec::with_capacity(parts);
4390    for part in 0..parts {
4391        let at = 4 + part * 4;
4392        let field = bytes.get(at..at + 4).ok_or_else(|| invalid("sieve page is truncated"))?;
4393        lengths.push(u32::from_le_bytes(
4394            field.try_into().map_err(|_| invalid("sieve page is truncated"))?,
4395        ) as usize);
4396    }
4397    let mut at = 4 + parts * 4;
4398    let mut out = Vec::with_capacity(parts);
4399    for length in lengths {
4400        if length == 0 {
4401            out.push(None);
4402            continue;
4403        }
4404        let end = at.checked_add(length).ok_or_else(|| invalid("sieve page is truncated"))?;
4405        let field = bytes.get(at..end).ok_or_else(|| invalid("sieve page is truncated"))?;
4406        out.push(Sieve::from_bytes(field));
4407        at = end;
4408    }
4409    if at != bytes.len() {
4410        return Err(invalid("sieve page has trailing bytes"));
4411    }
4412    Ok(out)
4413}
4414
4415/// One stripe's membership index: the code count and then the codes as ascending deltas.
4416///
4417/// The codes have to be sorted and distinct already, which is what [`unique_codes`] and
4418/// [`merged_codes`] hand over. Anything else decodes as different codes, so neither of those two is
4419/// a step a caller can skip.
4420fn encode_membership(unique: &[u32]) -> Vec<u8> {
4421    let mut out = Vec::with_capacity(unique.len().saturating_mul(2).saturating_add(5));
4422    put_varint(&mut out, u32::try_from(unique.len()).unwrap_or(u32::MAX));
4423    let mut previous = 0;
4424    for (at, &code) in unique.iter().enumerate() {
4425        put_varint(&mut out, if at == 0 { code } else { code - previous });
4426        previous = code;
4427    }
4428    out
4429}
4430
4431fn take_varint(bytes: &[u8], at: &mut usize) -> Result<u32> {
4432    let mut value = 0_u32;
4433    for shift in (0..35).step_by(7) {
4434        let byte = *bytes.get(*at).ok_or_else(|| invalid("membership varint is truncated"))?;
4435        *at += 1;
4436        let part = u32::from(byte & 0x7f);
4437        if shift == 28 && part > 0x0f {
4438            return Err(invalid("membership varint overflow"));
4439        }
4440        value = value
4441            .checked_add(
4442                part.checked_shl(shift).ok_or_else(|| invalid("membership varint overflow"))?,
4443            )
4444            .ok_or_else(|| invalid("membership varint overflow"))?;
4445        if byte & 0x80 == 0 {
4446            return Ok(value);
4447        }
4448    }
4449    Err(invalid("membership varint is too long"))
4450}
4451
4452fn decode_membership(bytes: &[u8]) -> Result<Vec<u32>> {
4453    let mut at = 0;
4454    let count = take_varint(bytes, &mut at)? as usize;
4455    let mut codes = Vec::with_capacity(count);
4456    let mut previous = 0_u32;
4457    for index in 0..count {
4458        let delta = take_varint(bytes, &mut at)?;
4459        let code = if index == 0 {
4460            delta
4461        } else {
4462            previous.checked_add(delta).ok_or_else(|| invalid("membership code overflow"))?
4463        };
4464        if index > 0 && code <= previous {
4465            return Err(invalid("membership codes are not increasing"));
4466        }
4467        codes.push(code);
4468        previous = code;
4469    }
4470    if at != bytes.len() {
4471        return Err(invalid("membership page has trailing bytes"));
4472    }
4473    Ok(codes)
4474}
4475
4476fn string_dictionary(vector: &Vector) -> Result<Option<Vec<u8>>> {
4477    let mut by_text = HashMap::new();
4478    let mut values = Vec::new();
4479    let mut codes = Vec::with_capacity(vector.len());
4480    let mut plain_bytes = 0_usize;
4481    for row in 0..vector.len() {
4482        let text = vector.text_at(row).unwrap_or("");
4483        plain_bytes = plain_bytes.saturating_add(text.len());
4484        let code = match by_text.get(text) {
4485            Some(&code) => code,
4486            None => {
4487                let code = u32::try_from(values.len())
4488                    .map_err(|_| invalid("too many dictionary values"))?;
4489                by_text.insert(text, code);
4490                values.push(text);
4491                code
4492            }
4493        };
4494        codes.push(code);
4495    }
4496    let dictionary_bytes = values.iter().map(|value| value.len()).sum::<usize>();
4497    let encoded = 8_usize
4498        .saturating_add((values.len() + 1).saturating_mul(4))
4499        .saturating_add(dictionary_bytes)
4500        .saturating_add(codes.len().saturating_mul(4));
4501    let plain = (vector.len() + 1).saturating_mul(4).saturating_add(plain_bytes);
4502    if encoded >= plain {
4503        return Ok(None);
4504    }
4505    let mut out = Vec::with_capacity(encoded);
4506    put_u32(
4507        &mut out,
4508        u32::try_from(values.len()).map_err(|_| invalid("too many dictionary values"))?,
4509    );
4510    put_u32(
4511        &mut out,
4512        u32::try_from(dictionary_bytes).map_err(|_| invalid("dictionary payload exceeds 4GiB"))?,
4513    );
4514    let mut offset = 0_u32;
4515    put_u32(&mut out, offset);
4516    for value in &values {
4517        offset = offset
4518            .checked_add(
4519                u32::try_from(value.len()).map_err(|_| invalid("dictionary value is too long"))?,
4520            )
4521            .ok_or_else(|| invalid("dictionary payload exceeds 4GiB"))?;
4522        put_u32(&mut out, offset);
4523    }
4524    for value in values {
4525        out.extend_from_slice(value.as_bytes());
4526    }
4527    for code in codes {
4528        put_u32(&mut out, code);
4529    }
4530    Ok(Some(out))
4531}
4532
4533struct EncodedDictionary {
4534    index: Vec<u8>,
4535    ranks: Vec<u8>,
4536    /// The payload as the blocks it is written as, kept apart rather than joined because joining
4537    /// them is a second copy of a thing that is already gigabytes on the columns that matter.
4538    payload: Vec<Vec<u8>>,
4539}
4540
4541/// The first eight bytes of a value as an integer that sorts the way the bytes sort.
4542fn head(bytes: &[u8]) -> u64 {
4543    let mut word = [0; 8];
4544    let take = bytes.len().min(8);
4545    word[..take].copy_from_slice(&bytes[..take]);
4546    u64::from_be_bytes(word)
4547}
4548
4549/// The sorted order of every global dictionary, one entry per column and empty where there is no
4550/// dictionary.
4551///
4552/// One column's sort has nothing to do with another's, and a table like `hits` has fifteen string
4553/// columns, so this runs across threads the way the numeric synopses above do. It is the only part
4554/// of committing a file that is more than bookkeeping, and doing it serially would show up as a
4555/// pause at the end of a load that thirty two threads had been busy with until then.
4556fn rankings(dictionaries: &[Option<GlobalDictionary>]) -> Result<Vec<Vec<(u64, u32)>>> {
4557    let present =
4558        dictionaries.iter().enumerate().filter(|(_, held)| held.is_some()).map(|(at, _)| at);
4559    let present = present.collect::<Vec<_>>();
4560    let mut orders = vec![Vec::new(); dictionaries.len()];
4561    let workers = std::thread::available_parallelism()
4562        .map_or(1, usize::from)
4563        .min(MAX_FREQUENCY_WORKERS)
4564        .min(present.len());
4565    if workers <= 1 {
4566        for at in present {
4567            if let Some(dictionary) = &dictionaries[at] {
4568                orders[at] = dictionary.ranked();
4569            }
4570        }
4571        return Ok(orders);
4572    }
4573    let width = present.len().div_ceil(workers);
4574    let pieces = std::thread::scope(|scope| {
4575        present
4576            .chunks(width)
4577            .map(|columns| {
4578                scope.spawn(|| {
4579                    columns
4580                        .iter()
4581                        .filter_map(|&at| dictionaries[at].as_ref().map(|held| (at, held.ranked())))
4582                        .collect::<Vec<_>>()
4583                })
4584            })
4585            .collect::<Vec<_>>()
4586            .into_iter()
4587            .map(|handle| {
4588                handle.join().map_err(|_| Error::internal("a dictionary sort worker panicked"))
4589            })
4590            .collect::<Result<Vec<_>>>()
4591    })?;
4592    for piece in pieces {
4593        for (at, order) in piece {
4594            orders[at] = order;
4595        }
4596    }
4597    Ok(orders)
4598}
4599
4600fn encode_global_dictionary(
4601    dictionary: GlobalDictionary,
4602    order: &[(u64, u32)],
4603) -> Result<EncodedDictionary> {
4604    let values = dictionary.offsets.len() - 1;
4605    if order.len() != values {
4606        return Err(invalid("global dictionary order does not cover its values"));
4607    }
4608    let blocks = values.div_ceil(TEXT_PAYLOAD_VALUES);
4609    let payload = encode_payload(&dictionary)?;
4610    if payload.len() != blocks {
4611        return Err(invalid("global dictionary payload is not the blocks it says it is"));
4612    }
4613    let (ranks, rank_ends) = encode_ranks(order, code_width(values))?;
4614    let rank_blocks = values.div_ceil(TEXT_RANK_BLOCK);
4615    let offset_bits = offset_width(&dictionary.offsets);
4616    let mut index = Vec::with_capacity(
4617        DICTIONARY_HEADER + offset_bytes(values, offset_bits) + (blocks + rank_blocks) * 16,
4618    );
4619    put_u32(
4620        &mut index,
4621        u32::try_from(values).map_err(|_| invalid("global dictionary has too many values"))?,
4622    );
4623    put_u32(&mut index, TEXT_PAYLOAD_VALUES as u32);
4624    put_u32(
4625        &mut index,
4626        u32::try_from(blocks).map_err(|_| invalid("global dictionary has too many blocks"))?,
4627    );
4628    put_u32(&mut index, offset_bits as u32);
4629    encode_offsets(&dictionary.offsets, offset_bits, &mut index)?;
4630    // Where each block ends, so a reader can find one. The stored blocks are shorter than the
4631    // decoded ones and by a different amount each, so this is the one thing the offsets above no
4632    // longer say.
4633    let mut at = 0_u64;
4634    for block in &payload {
4635        at = at
4636            .checked_add(block.len() as u64)
4637            .ok_or_else(|| invalid("global dictionary payload overflow"))?;
4638        put_u64(&mut index, at);
4639    }
4640    for block in &payload {
4641        put_u64(&mut index, checksum(block));
4642    }
4643    // The same two lists for the sorted order. A rank block is packed at whatever width its own
4644    // heads need, so where one ends is no longer arithmetic on the block number.
4645    if rank_ends.len() != rank_blocks {
4646        return Err(invalid("global dictionary order is not the blocks it says it is"));
4647    }
4648    for end in &rank_ends {
4649        put_u64(&mut index, *end);
4650    }
4651    let mut at = 0_usize;
4652    for end in &rank_ends {
4653        let end = usize::try_from(*end).map_err(|_| invalid("global dictionary order overflow"))?;
4654        put_u64(&mut index, checksum(&ranks[at..end]));
4655        at = end;
4656    }
4657    Ok(EncodedDictionary { index, ranks, payload })
4658}
4659
4660/// How many blocks of the payload the shape is settled on.
4661///
4662/// Eight blocks is 8,192 values, which is the sample `chooser::Sampled` draws and is that size for
4663/// the same reason. They are spread across the dictionary rather than taken off the front, because
4664/// a dictionary is in the order values were first seen and the front of it is the first morsel of
4665/// the load.
4666const PAYLOAD_SAMPLE_BLOCKS: usize = 8;
4667
4668/// The shapes the payload encoder picks between.
4669///
4670/// Narrow on purpose. The exhaustive search encodes every candidate at every level and runs at two
4671/// to six megabytes a second on this data, which over the twelve gigabytes of dictionary `hits`
4672/// carries is about an hour of processor time, so it cannot be what a load does. Each of these
4673/// settles the outer level and the one below it, which is where almost all of that hour goes, and
4674/// leaves the levels under them to the exhaustive search where the chunks are small enough for it
4675/// to cost nothing.
4676///
4677/// Measured on the five ClickBench columns that have a dictionary worth the name, at 1,024 values a
4678/// block, against the exhaustive search over the same blocks:
4679///
4680/// | column | exhaustive | FRONT then LZ | LZ then FSST | LZ then PLAIN |
4681/// |---|---|---|---|---|
4682/// | 2 | 2.923 at 4.3 MB/s | 2.587 at 21.2 | 2.593 at 36.1 | 2.538 at 53.6 |
4683/// | 13 | 3.093 at 3.1 | 3.029 at 36.4 | 2.921 at 35.7 | 2.770 at 82.9 |
4684/// | 14 | 2.330 at 2.1 | 2.283 at 24.3 | 2.213 at 23.5 | 2.113 at 67.6 |
4685/// | 39 | 2.459 at 5.3 | 2.147 at 10.6 | 2.145 at 29.3 | 2.088 at 43.1 |
4686/// | 56 | 4.694 at 6.3 | 4.381 at 51.0 | 4.172 at 50.6 | 3.983 at 86.8 |
4687///
4688/// The best of the three per column is 98 percent of the exhaustive ratio for a tenth of the time.
4689/// `FSST` and `PLAIN` on their own are in the list as a floor rather than to win. `FSST` is the
4690/// right answer for text that does not share prefixes with its neighbours, and `PLAIN` is there so
4691/// that a column nothing compresses is found out in the sample and written at a gigabyte a second
4692/// rather than searched for an answer that does not exist.
4693fn payload_shapes() -> Vec<chooser::Settled> {
4694    let integers = vec![integer::Kind::Packed];
4695    [
4696        vec![string::Kind::Front, string::Kind::Lz],
4697        vec![string::Kind::Lz, string::Kind::Fsst],
4698        vec![string::Kind::Lz, string::Kind::Plain],
4699        vec![string::Kind::Fsst],
4700        vec![string::Kind::Plain],
4701    ]
4702    .into_iter()
4703    .map(|strings| chooser::Settled::new(strings, integers.clone()))
4704    .collect()
4705}
4706
4707/// The payload as encoded blocks of [`TEXT_PAYLOAD_VALUES`] values each.
4708///
4709/// Across threads because this is the only part of committing a file that is real work rather than
4710/// bookkeeping. The blocks are the same size and cost about the same, so an index each is enough of
4711/// a queue and there is nothing to weight the way the numeric synopses are weighted.
4712fn encode_payload(dictionary: &GlobalDictionary) -> Result<Vec<Vec<u8>>> {
4713    let values = dictionary.offsets.len() - 1;
4714    let blocks = values.div_ceil(TEXT_PAYLOAD_VALUES);
4715    let run = |block: usize| {
4716        let first = block * TEXT_PAYLOAD_VALUES;
4717        let last = (first + TEXT_PAYLOAD_VALUES).min(values);
4718        (first..last)
4719            .map(|value| {
4720                let from = dictionary.offsets[value] as usize;
4721                let to = dictionary.offsets[value + 1] as usize;
4722                &dictionary.payload[from..to]
4723            })
4724            .collect::<Vec<_>>()
4725    };
4726    // A dictionary small enough to be the sample is small enough to search in full, and searching
4727    // it costs less than deciding not to.
4728    let shape = (blocks > PAYLOAD_SAMPLE_BLOCKS).then(|| settle_shape(&run, blocks)).transpose()?;
4729    let one = |block: usize| match &shape {
4730        Some(shape) => string::encode_with(&run(block), shape),
4731        None => string::encode(&run(block)),
4732    };
4733    let workers = std::thread::available_parallelism()
4734        .map_or(1, usize::from)
4735        .min(MAX_FREQUENCY_WORKERS)
4736        .min(blocks);
4737    if workers <= 1 {
4738        return (0..blocks).map(one).collect();
4739    }
4740    let next = AtomicUsize::new(0);
4741    let pieces = std::thread::scope(|scope| {
4742        (0..workers)
4743            .map(|_| {
4744                scope.spawn(|| {
4745                    let mut mine = Vec::new();
4746                    loop {
4747                        let block = next.fetch_add(1, Atomic::Relaxed);
4748                        if block >= blocks {
4749                            break;
4750                        }
4751                        mine.push((block, one(block)?));
4752                    }
4753                    Ok(mine)
4754                })
4755            })
4756            .collect::<Vec<_>>()
4757            .into_iter()
4758            .map(|handle| {
4759                handle.join().map_err(|_| Error::internal("a dictionary encode worker panicked"))?
4760            })
4761            .collect::<Result<Vec<_>>>()
4762    })?;
4763    let mut payload = vec![Vec::new(); blocks];
4764    for piece in pieces {
4765        for (block, bytes) in piece {
4766            payload[block] = bytes;
4767        }
4768    }
4769    Ok(payload)
4770}
4771
4772/// Which of [`payload_shapes`] comes out smallest over a sample of the blocks.
4773///
4774/// Every shape is encoded over the same sample and the smallest wins, which is the exhaustive
4775/// search moved up a level: over shapes of a column rather than over candidates of a chunk. The
4776/// sample is spread across the dictionary so that the first and last blocks are both in it, because
4777/// a dictionary written in first seen order has its common values at the front and its long tail at
4778/// the back, and those do not compress alike.
4779fn settle_shape<'a>(
4780    run: &dyn Fn(usize) -> Vec<&'a [u8]>,
4781    blocks: usize,
4782) -> Result<chooser::Settled> {
4783    let last = blocks - 1;
4784    let sample = (0..PAYLOAD_SAMPLE_BLOCKS)
4785        .map(|region| run(region * last / (PAYLOAD_SAMPLE_BLOCKS - 1)))
4786        .collect::<Vec<_>>();
4787    let mut best: Option<(chooser::Settled, usize)> = None;
4788    for shape in payload_shapes() {
4789        let mut size = 0;
4790        for block in &sample {
4791            size += string::encode_with(block, &shape)?.len();
4792        }
4793        if best.as_ref().is_none_or(|(_, smallest)| size < *smallest) {
4794            best = Some((shape, size));
4795        }
4796    }
4797    best.map(|(shape, _)| shape)
4798        .ok_or_else(|| invalid("no shape applies to a global dictionary payload"))
4799}
4800
4801/// The sorted order laid out the way a reader reads it, in blocks of [`TEXT_RANK_BLOCK`] entries.
4802///
4803/// Each block holds its heads first and then its codes, rather than pairing them, because a search
4804/// asks for a head at every probe and for a code about once a search. Keeping the heads together
4805/// means a probe touches eight bytes of a block rather than twelve spread over it, and the last few
4806/// probes of a search, which are the ones that land in the same block, touch the same cache line.
4807fn encode_ranks(order: &[(u64, u32)], code_bits: usize) -> Result<(Vec<u8>, Vec<u64>)> {
4808    let mut out = Vec::with_capacity(order.len() * 4);
4809    let mut ends = Vec::with_capacity(order.len().div_ceil(TEXT_RANK_BLOCK));
4810    let mut heads = Vec::with_capacity(TEXT_RANK_BLOCK);
4811    let mut codes = Vec::with_capacity(TEXT_RANK_BLOCK);
4812    for block in order.chunks(TEXT_RANK_BLOCK) {
4813        // The order is sorted by value and a head is a prefix of a value, so the heads of a block
4814        // rise, the smallest is the first and the largest is the last.
4815        let base = block.first().map_or(0, |&(head, _)| head);
4816        let span = block.last().map_or(0, |&(head, _)| head.wrapping_sub(base));
4817        let width = (u64::BITS - span.leading_zeros()) as usize;
4818        heads.clear();
4819        codes.clear();
4820        for &(head, code) in block {
4821            heads.push(head.wrapping_sub(base));
4822            codes.push(u64::from(code));
4823        }
4824        put_u64(&mut out, base);
4825        out.push(width as u8);
4826        bitpack::pack_tail(&heads, width, &mut out)
4827            .map_err(|_| invalid("global dictionary heads do not pack"))?;
4828        bitpack::pack_tail(&codes, code_bits, &mut out)
4829            .map_err(|_| invalid("global dictionary codes do not pack"))?;
4830        ends.push(out.len() as u64);
4831    }
4832    Ok((out, ends))
4833}
4834
4835/// Opens a column's global dictionary, which reads its index and none of its payload.
4836///
4837/// `keep_budget` is how many decoded payload bytes this dictionary may hold on to, and every
4838/// caller bar the test of the ceiling passes [`TEXT_KEEP_BUDGET`]. It is a parameter rather than
4839/// the constant read where it is used because a test of a ceiling that cannot be moved has to build
4840/// a quarter of a gigabyte of dictionary to reach it.
4841fn open_global_dictionary(
4842    file: Arc<File>,
4843    page: Page,
4844    ty: &LogicalType,
4845    keep_budget: usize,
4846) -> Result<Vector> {
4847    if ty != &LogicalType::Varchar {
4848        return Err(invalid("global dictionary belongs to a non-string column"));
4849    }
4850    let mut header = [0; DICTIONARY_HEADER];
4851    read_at(&file, page.offset, &mut header)?;
4852    let count = u32::from_le_bytes(header[0..4].try_into().expect("four bytes")) as usize;
4853    let per_block = u32::from_le_bytes(header[4..8].try_into().expect("four bytes")) as usize;
4854    let blocks = u32::from_le_bytes(header[8..12].try_into().expect("four bytes")) as usize;
4855    let offset_bits = u32::from_le_bytes(header[12..16].try_into().expect("four bytes")) as usize;
4856    if per_block != TEXT_PAYLOAD_VALUES {
4857        return Err(invalid("global dictionary block width differs"));
4858    }
4859    if blocks != count.div_ceil(TEXT_PAYLOAD_VALUES) {
4860        return Err(invalid("global dictionary block count differs from its value count"));
4861    }
4862    if offset_bits > u32::BITS as usize {
4863        return Err(invalid("global dictionary packs offsets past a payload"));
4864    }
4865    let offset_len = offset_bytes(count, offset_bits);
4866    // The sorted order is kept out of the index on purpose. The index is read and checksummed in
4867    // full the moment the column is first touched, and the order is half again the size of the
4868    // offsets, so putting it there would make every query that reads a string column pay for a
4869    // search that most of them never make.
4870    let ranks = count;
4871    let rank_blocks = ranks.div_ceil(TEXT_RANK_BLOCK);
4872    // Two words a payload block, one for where it ends in the file and one for its checksum, and the
4873    // same two a rank block.
4874    let hash_len = blocks
4875        .checked_add(rank_blocks)
4876        .and_then(|words| words.checked_mul(16))
4877        .ok_or_else(|| invalid("global dictionary block count overflow"))?;
4878    let index_len = DICTIONARY_HEADER
4879        .checked_add(offset_len)
4880        .and_then(|len| len.checked_add(hash_len))
4881        .ok_or_else(|| invalid("global dictionary header overflow"))?;
4882    if index_len > page.length as usize {
4883        return Err(invalid("global dictionary offset index exceeds its page"));
4884    }
4885    let mut index = vec![0; index_len];
4886    index[..DICTIONARY_HEADER].copy_from_slice(&header);
4887    read_at(&file, page.offset + DICTIONARY_HEADER as u64, &mut index[DICTIONARY_HEADER..])?;
4888    if checksum(&index) != page.hash {
4889        return Err(invalid("global dictionary index checksum differs"));
4890    }
4891    let offsets = index[DICTIONARY_HEADER..DICTIONARY_HEADER + offset_len].to_vec();
4892    let mut words = index[DICTIONARY_HEADER + offset_len..]
4893        .chunks_exact(8)
4894        .map(|part| u64::from_le_bytes(part.try_into().expect("eight bytes")))
4895        .collect::<Vec<_>>();
4896    let mut hashes = words.split_off(blocks);
4897    let mut rank_ends = hashes.split_off(blocks);
4898    let rank_hashes = rank_ends.split_off(rank_blocks);
4899    let ends = words;
4900    // A rank block packs its heads at whatever width its own values need, so its length is no longer
4901    // arithmetic on the block number and the reader has to be told where each one ends.
4902    if rank_ends.windows(2).any(|pair| pair[0] >= pair[1]) {
4903        return Err(invalid("global dictionary order blocks do not rise"));
4904    }
4905    let rank_len = usize::try_from(rank_ends.last().copied().unwrap_or_default())
4906        .map_err(|_| invalid("global dictionary rank overflow"))?;
4907    let body_len = index_len
4908        .checked_add(rank_len)
4909        .ok_or_else(|| invalid("global dictionary header overflow"))?;
4910    if body_len > page.length as usize {
4911        return Err(invalid("global dictionary order exceeds its page"));
4912    }
4913    // What the offsets bound is the decoded payload, and what the page holds is the stored one, so
4914    // the last block end is the only thing that ties the index to the length of the page.
4915    let stored_len = page.length as usize - body_len;
4916    if ends.last().copied().unwrap_or_default() as usize != stored_len
4917        || ends.windows(2).any(|pair| pair[0] > pair[1])
4918    {
4919        return Err(invalid("global dictionary blocks do not bound the payload"));
4920    }
4921    Vector::external_text(
4922        LogicalType::Varchar,
4923        Arc::new(NativeText {
4924            file,
4925            values: count,
4926            offsets,
4927            offset_bits,
4928            ranks,
4929            rank_at: page.offset + index_len as u64,
4930            rank_ends,
4931            rank_hashes,
4932            rank_blocks: (0..rank_blocks).map(|_| OnceLock::new()).collect(),
4933            code_bits: code_width(count),
4934            code_ranks: OnceLock::new(),
4935            payload: page.offset + body_len as u64,
4936            ends,
4937            hashes,
4938            blocks: (0..blocks).map(|_| OnceLock::new()).collect(),
4939            keep_budget,
4940            payload_kept: AtomicUsize::new(0),
4941        }),
4942    )
4943}
4944
4945fn decode(
4946    ty: &LogicalType,
4947    rows: usize,
4948    bytes: &[u8],
4949    global: Option<Arc<Vector>>,
4950) -> Result<Vector> {
4951    let mut cur = Cursor { bytes, at: 0 };
4952    let codec = cur.u8()?;
4953    let flag = cur.u8()?;
4954    let validity = match flag {
4955        0 => Validity::AllValid,
4956        1 => Validity::AllInvalid,
4957        2 => {
4958            let mask = cur.take(rows.div_ceil(8))?;
4959            Validity::from_iter(rows, |row| mask[row / 8] >> (row % 8) & 1 == 1)
4960        }
4961        _ => return Err(invalid("page validity tag differs")),
4962    };
4963    if codec == 1 {
4964        if ty != &LogicalType::Varchar {
4965            return Err(invalid("dictionary codec belongs to a non-string page"));
4966        }
4967        let count = cur.u32()? as usize;
4968        let payload_len = cur.u32()? as usize;
4969        let offset_bytes = cur.take(
4970            (count + 1)
4971                .checked_mul(4)
4972                .ok_or_else(|| invalid("dictionary offset count overflow"))?,
4973        )?;
4974        let offsets = offset_bytes
4975            .chunks_exact(4)
4976            .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
4977            .collect::<Vec<_>>();
4978        let payload = cur.take(payload_len)?.to_vec();
4979        if offsets.first() != Some(&0)
4980            || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
4981            || offsets.windows(2).any(|pair| pair[0] > pair[1])
4982        {
4983            return Err(invalid("dictionary offsets do not bound the payload"));
4984        }
4985        let mut strings = StringColumn::over(Buffer::from_vec(payload));
4986        for pair in offsets.windows(2) {
4987            strings.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
4988        }
4989        let mut codes = Vec::with_capacity(rows);
4990        for _ in 0..rows {
4991            codes.push(cur.u32()?);
4992        }
4993        if codes.iter().any(|code| *code as usize >= count) {
4994            return Err(invalid("dictionary code is out of range"));
4995        }
4996        if cur.at != bytes.len() {
4997            return Err(invalid("dictionary page has trailing bytes"));
4998        }
4999        let dictionary = Vector::flat(LogicalType::Varchar, Data::Varlen(strings))?;
5000        return Ok(Vector::dictionary(codes, dictionary)?.with_validity(validity));
5001    }
5002    if codec == 3 || codec == 4 {
5003        let dictionary = global.ok_or_else(|| invalid("global code page has no dictionary"))?;
5004        let codes = if codec == 4 {
5005            // The cascade holds the whole tail of the page and says how long it is itself, so the
5006            // check that nothing is left over is the one the decoder already makes.
5007            let wide = integer::decode(&bytes[cur.at..])?;
5008            if wide.len() != rows {
5009                return Err(invalid("encoded code page holds the wrong number of rows"));
5010            }
5011            // Converted in one pass and checked in the same one, rather than a fallible conversion
5012            // per code. A `Result` an element is a short circuit the loop cannot be vectorized past,
5013            // and it was costing about twelve instructions a row to narrow a number that already
5014            // fits. Every code a file holds is inside a `u32` or the file is corrupt, so the check
5015            // belongs once at the end: or the codes together and the answer has a bit set above the
5016            // low thirty two, or the sign bit, exactly when one of them did.
5017            let mut codes = Vec::with_capacity(wide.len());
5018            let mut seen = 0_i64;
5019            for &code in &wide {
5020                seen |= code;
5021                codes.push(code as u32);
5022            }
5023            if seen < 0 || seen > i64::from(u32::MAX) {
5024                return Err(invalid("code is not a code"));
5025            }
5026            codes
5027        } else {
5028            let mut codes = Vec::with_capacity(rows);
5029            for _ in 0..rows {
5030                codes.push(cur.u32()?);
5031            }
5032            if cur.at != bytes.len() {
5033                return Err(invalid("global code page has trailing bytes"));
5034            }
5035            codes
5036        };
5037        let highest = codes.iter().copied().max();
5038        return Ok(Vector::stable_dictionary_validated(codes, dictionary, highest)?
5039            .with_validity(validity));
5040    }
5041    if codec == 5 {
5042        // The cascade holds the whole tail of the page and says how long it is itself.
5043        let values = integer::decode(&bytes[cur.at..])?;
5044        if values.len() != rows {
5045            return Err(invalid("cascade page holds the wrong number of rows"));
5046        }
5047        let data = narrowed(ty, values)?;
5048        return Ok(Vector::flat(ty.clone(), data)?.with_validity(validity));
5049    }
5050    if codec == 2 {
5051        let width = u32::from(cur.u8()?);
5052        let base = i128::from_le_bytes(cur.take(16)?.try_into().expect("sixteen bytes"));
5053        let count = cur.u32()? as usize;
5054        let mut words = Vec::with_capacity(count);
5055        for _ in 0..count {
5056            words.push(cur.u64()?);
5057        }
5058        if cur.at != bytes.len() {
5059            return Err(invalid("packed page has trailing bytes"));
5060        }
5061        return Ok(Vector::packed(ty.clone(), words, width, base, rows)?.with_validity(validity));
5062    }
5063    if codec != 0 {
5064        return Err(invalid("page codec is unknown"));
5065    }
5066    let data = match ty {
5067        LogicalType::TinyInt => {
5068            let values = cur.take(rows)?;
5069            Data::Int8(values.iter().map(|item| *item as i8).collect::<Vec<_>>().into())
5070        }
5071        LogicalType::UTinyInt => Data::UInt8(cur.take(rows)?.to_vec().into()),
5072        LogicalType::SmallInt => {
5073            let values =
5074                cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
5075            Data::Int16(
5076                values
5077                    .chunks_exact(2)
5078                    .map(|item| i16::from_le_bytes(item.try_into().expect("two bytes")))
5079                    .collect::<Vec<_>>()
5080                    .into(),
5081            )
5082        }
5083        LogicalType::USmallInt => {
5084            let values =
5085                cur.take(rows.checked_mul(2).ok_or_else(|| invalid("page size overflow"))?)?;
5086            Data::UInt16(
5087                values
5088                    .chunks_exact(2)
5089                    .map(|item| u16::from_le_bytes(item.try_into().expect("two bytes")))
5090                    .collect::<Vec<_>>()
5091                    .into(),
5092            )
5093        }
5094        LogicalType::UInteger => {
5095            let values =
5096                cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
5097            Data::UInt32(
5098                values
5099                    .chunks_exact(4)
5100                    .map(|item| u32::from_le_bytes(item.try_into().expect("four bytes")))
5101                    .collect::<Vec<_>>()
5102                    .into(),
5103            )
5104        }
5105        LogicalType::UBigInt => {
5106            let values =
5107                cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
5108            Data::UInt64(
5109                values
5110                    .chunks_exact(8)
5111                    .map(|item| u64::from_le_bytes(item.try_into().expect("eight bytes")))
5112                    .collect::<Vec<_>>()
5113                    .into(),
5114            )
5115        }
5116        LogicalType::Integer | LogicalType::Date => {
5117            let values =
5118                cur.take(rows.checked_mul(4).ok_or_else(|| invalid("page size overflow"))?)?;
5119            Data::Int32(
5120                values
5121                    .chunks_exact(4)
5122                    .map(|item| i32::from_le_bytes(item.try_into().expect("four bytes")))
5123                    .collect::<Vec<_>>()
5124                    .into(),
5125            )
5126        }
5127        LogicalType::BigInt | LogicalType::Timestamp => {
5128            let values =
5129                cur.take(rows.checked_mul(8).ok_or_else(|| invalid("page size overflow"))?)?;
5130            Data::Int64(
5131                values
5132                    .chunks_exact(8)
5133                    .map(|item| i64::from_le_bytes(item.try_into().expect("eight bytes")))
5134                    .collect::<Vec<_>>()
5135                    .into(),
5136            )
5137        }
5138        LogicalType::Boolean => {
5139            let values = cur.take(rows)?;
5140            if values.iter().any(|value| *value > 1) {
5141                return Err(invalid("boolean page has another value"));
5142            }
5143            Data::Bool(values.iter().map(|value| *value == 1).collect::<Vec<_>>().into())
5144        }
5145        LogicalType::Varchar => {
5146            let offset_bytes = cur
5147                .take((rows + 1).checked_mul(4).ok_or_else(|| invalid("offset count overflow"))?)?;
5148            let offsets = offset_bytes
5149                .chunks_exact(4)
5150                .map(|part| u32::from_le_bytes(part.try_into().expect("four bytes")))
5151                .collect::<Vec<_>>();
5152            let payload = cur.take(bytes.len() - cur.at)?.to_vec();
5153            if offsets.first() != Some(&0)
5154                || offsets.last().copied().map(|last| last as usize) != Some(payload.len())
5155                || offsets.windows(2).any(|pair| pair[0] > pair[1])
5156            {
5157                return Err(invalid("string offsets do not bound the payload"));
5158            }
5159            let mut values = StringColumn::over(Buffer::from_vec(payload));
5160            for pair in offsets.windows(2) {
5161                values.push_in_place(pair[0] as usize, (pair[1] - pair[0]) as usize)?;
5162            }
5163            Data::Varlen(values)
5164        }
5165        _ => return Err(Error::not_implemented(format!("native page for {ty}"))),
5166    };
5167    if cur.at != bytes.len() {
5168        return Err(invalid("page has trailing bytes"));
5169    }
5170    Ok(Vector::flat(ty.clone(), data)?.with_validity(validity))
5171}
5172
5173#[cfg(test)]
5174mod tests {
5175    use std::fs;
5176    use std::io::{Seek, SeekFrom, Write};
5177    use std::path::PathBuf;
5178    use std::time::{SystemTime, UNIX_EPOCH};
5179
5180    use rudb_common::Value;
5181    use rudb_common::bounds::Op;
5182
5183    use super::*;
5184
5185    #[test]
5186    fn checksum_matches_fixed_vectors() {
5187        assert_eq!(checksum(b""), 0xef46_db37_51d8_e999);
5188        assert_eq!(checksum(b"a"), 0xd24e_c4f1_a98c_6e5b);
5189        assert_eq!(checksum(b"abc"), 0x44bc_2cf5_ad77_0999);
5190    }
5191
5192    fn path(label: &str) -> PathBuf {
5193        let stamp = SystemTime::now().duration_since(UNIX_EPOCH).expect("time advances").as_nanos();
5194        std::env::temp_dir().join(format!("rudb-native-{label}-{}-{stamp}.rdb", std::process::id()))
5195    }
5196
5197    /// A read names the offset it wants, so a cursor somebody else moved cannot reach it.
5198    #[test]
5199    fn a_read_at_an_offset_ignores_where_another_thread_left_the_cursor() {
5200        const SPANS: usize = 64;
5201        const SPAN: usize = 512;
5202        let path = path("positional");
5203        let content: Vec<u8> =
5204            (0..SPANS).flat_map(|span| std::iter::repeat_n(span as u8, SPAN)).collect();
5205        fs::write(&path, &content).expect("the file is written");
5206        let file = Arc::new(File::open(&path).expect("the file opens"));
5207        std::thread::scope(|scope| {
5208            for _ in 0..8 {
5209                let file = Arc::clone(&file);
5210                scope.spawn(move || {
5211                    for _ in 0..64 {
5212                        for span in 0..SPANS {
5213                            let mut bytes = [0_u8; SPAN];
5214                            read_at(&file, (span * SPAN) as u64, &mut bytes)
5215                                .expect("the span reads");
5216                            assert!(
5217                                bytes.iter().all(|byte| *byte == span as u8),
5218                                "span {span} came back as {}",
5219                                bytes[0],
5220                            );
5221                        }
5222                    }
5223                });
5224            }
5225        });
5226        let mut past = [0_u8; SPAN];
5227        let end = (SPANS * SPAN) as u64;
5228        let error = read_at(&file, end, &mut past).expect_err("a read past the end is refused");
5229        assert!(error.message().contains("ends before its declared length"), "{error}");
5230        drop(file);
5231        let _ = fs::remove_file(&path);
5232    }
5233
5234    /// The writer records where it put a page and puts it there, whatever the cursor is doing.
5235    ///
5236    /// The cursor is moved between the steps that record an offset, which is what reading the pages
5237    /// back to build the frequencies does on a platform with no `pread`. Without the fix the
5238    /// directory lands on top of a page and the file fails to reopen.
5239    #[test]
5240    fn a_writer_puts_a_page_where_it_said_it_did_wherever_the_cursor_has_got_to() {
5241        let path = path("cursor");
5242        let mut writer = Writer::create(
5243            &path,
5244            "items",
5245            vec![
5246                Field::required("id", LogicalType::Integer),
5247                Field::new("text", LogicalType::Varchar),
5248            ],
5249        )
5250        .expect("new file");
5251        writer.append(&sample()).expect("first part");
5252        writer.file.seek(SeekFrom::Start(0)).expect("the cursor goes back to the header");
5253        writer.append(&sample()).expect("second part");
5254        writer.file.seek(SeekFrom::Start(1)).expect("and somewhere useless again");
5255        writer.finish().expect("commit");
5256        let reader = Reader::open(&path).expect("reopen from disk");
5257        assert_eq!(reader.table().rows(), 6);
5258        let ids = reader.read(0, &[0]).expect("the integer page reads back");
5259        assert_eq!(ids.value_at(0, 0), Value::Integer(4));
5260        assert_eq!(ids.value_at(2, 0), Value::Integer(-2));
5261        let text = reader.read(1, &[1]).expect("the text page reads back");
5262        assert_eq!(text.value_at(1, 0), Value::Null);
5263        assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
5264        // Nothing the directory points at may run past the end of the file, which is the shape the
5265        // failure took: a page recorded at an offset the directory had already been written over.
5266        let end = reader.table().stripes().iter().flat_map(|stripe| {
5267            stripe
5268                .pages
5269                .iter()
5270                .map(|page| page.offset + u64::from(page.length))
5271                .chain(std::iter::once(stripe.index.offset + u64::from(stripe.index.length)))
5272        });
5273        let last = end.fold(HEADER, u64::max);
5274        let directory = fs::metadata(&path).expect("the file is there").len();
5275        assert!(last <= directory, "a page runs to {last} in a file of {directory} bytes");
5276        fs::remove_file(path).expect("remove scratch file");
5277    }
5278
5279    /// How long a global dictionary index is, read out of the page's own header.
5280    ///
5281    /// The tests below damage a byte of the order or of the payload, so they need to know where each
5282    /// one starts, and working it out here rather than writing a number down means adding something
5283    /// to the index does not quietly turn one of them into a test that damages the index instead.
5284    fn dictionary_index_len(header: &[u8; DICTIONARY_HEADER]) -> u64 {
5285        let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
5286        let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
5287        let bits = u32::from_le_bytes(header[12..16].try_into().expect("four bytes")) as usize;
5288        let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
5289        DICTIONARY_HEADER as u64
5290            + offset_bytes(count as usize, bits) as u64
5291            + (blocks + rank_blocks) * 16
5292    }
5293
5294    /// How long the sorted order is, which is where its last block ends.
5295    fn last_rank_end(file: &File, offset: u64, header: &[u8; DICTIONARY_HEADER]) -> u64 {
5296        let count = u64::from(u32::from_le_bytes(header[0..4].try_into().expect("four bytes")));
5297        let blocks = u64::from(u32::from_le_bytes(header[8..12].try_into().expect("four bytes")));
5298        let bits = u32::from_le_bytes(header[12..16].try_into().expect("four bytes")) as usize;
5299        let rank_blocks = count.div_ceil(TEXT_RANK_BLOCK as u64);
5300        let at = offset
5301            + DICTIONARY_HEADER as u64
5302            + offset_bytes(count as usize, bits) as u64
5303            + blocks * 16
5304            + (rank_blocks - 1) * 8;
5305        let mut end = [0; 8];
5306        read_at(file, at, &mut end).expect("the last rank block end");
5307        u64::from_le_bytes(end)
5308    }
5309
5310    fn sample() -> Chunk {
5311        Chunk::new(vec![
5312            Vector::from_values(
5313                LogicalType::Integer,
5314                &[Value::Integer(4), Value::Integer(9), Value::Integer(-2)],
5315            )
5316            .expect("integers"),
5317            Vector::from_values(
5318                LogicalType::Varchar,
5319                &[
5320                    Value::Varchar("alpha".into()),
5321                    Value::Null,
5322                    Value::Varchar("long text after a slash".into()),
5323                ],
5324            )
5325            .expect("strings"),
5326        ])
5327        .expect("matching rows")
5328    }
5329
5330    fn sample_ids() -> Chunk {
5331        Chunk::new(vec![
5332            Vector::flat(LogicalType::Integer, Data::Int32(vec![7, 8, 9].into()))
5333                .expect("integers"),
5334        ])
5335        .expect("one column")
5336    }
5337
5338    #[test]
5339    fn committed_file_reopens_and_reads_only_requested_columns() {
5340        let path = path("reopen");
5341        let mut writer = Writer::create(
5342            &path,
5343            "items",
5344            vec![
5345                Field::required("id", LogicalType::Integer),
5346                Field::new("text", LogicalType::Varchar),
5347            ],
5348        )
5349        .expect("new file");
5350        writer.append(&sample()).expect("first part");
5351        writer.append(&sample()).expect("second part");
5352        writer.finish().expect("commit");
5353        let reader = Reader::open(&path).expect("reopen from disk");
5354        assert_eq!(reader.table().rows(), 6);
5355        // Two appends below the stripe bound are two parts of one stripe, which is the whole point
5356        // of the split: the directory describes the stripe and the scan still reads a part.
5357        assert_eq!(reader.table().stripes().len(), 1);
5358        assert_eq!(reader.parts(), 2);
5359        assert_eq!(reader.part_rows(0), 3);
5360        assert_eq!(reader.part_rows(1), 3);
5361        let text = reader.read(1, &[1]).expect("only text page");
5362        assert_eq!(text.width(), 1);
5363        assert_eq!(text.value_at(1, 0), Value::Null);
5364        assert_eq!(text.value_at(2, 0), Value::Varchar("long text after a slash".into()));
5365        let sparse = reader.read_sparse(1, &[1]).expect("one part without its whole page");
5366        assert_eq!(sparse.width(), 1);
5367        assert_eq!(sparse.value_at(1, 0), Value::Null);
5368        assert_eq!(sparse.value_at(2, 0), Value::Varchar("long text after a slash".into()));
5369        assert!(!reader.skips_codes(0, 1, &[0]).expect("alpha is in the stripe"));
5370        assert!(!reader.skips_codes(0, 1, &[2]).expect("long text is in the stripe"));
5371        assert!(reader.skips_codes(0, 1, &[3]).expect("unknown code is absent"));
5372        let count = reader.read(0, &[]).expect("no page is needed for count");
5373        assert_eq!(count.len(), 3);
5374        assert!(reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }]));
5375        assert!(!reader.skips(0, &[Probe { column: 0, op: Op::Greater, value: Bound::Int(0) }]));
5376        let integers = reader.top_frequencies(0, 1).expect("valid integer synopsis").expect("kept");
5377        assert_eq!(
5378            integers,
5379            vec![(Value::Integer(-2), 2), (Value::Integer(4), 2), (Value::Integer(9), 2),]
5380        );
5381        let strings = reader.top_frequencies(1, 1).expect("valid string synopsis").expect("kept");
5382        assert_eq!(strings.len(), 3);
5383        assert!(strings.contains(&(Value::Null, 2)));
5384        assert!(strings.contains(&(Value::Varchar("alpha".into()), 2)));
5385        assert!(strings.contains(&(Value::Varchar("long text after a slash".into()), 2)));
5386        fs::remove_file(path).expect("remove scratch file");
5387    }
5388
5389    /// Two pipeline instances handing over whole runs, which is what makes the native sink safe to
5390    /// instance.
5391    ///
5392    /// The runs arrive in the order the instances finished reading them rather than in source
5393    /// order, and the second one to finish is the one that read the earlier rows. Each run is still
5394    /// a stripe of its own and the table still reads back in source order, which is the whole of
5395    /// what the writer promises about ordering.
5396    #[test]
5397    fn runs_handed_over_out_of_order_still_read_back_in_source_order() {
5398        let path = path("interleaved-runs");
5399        let mut writer =
5400            Writer::create(&path, "interleaved", vec![Field::new("v", LogicalType::BigInt)])
5401                .expect("new file");
5402        for morsel in [2_u64, 0, 3, 1] {
5403            let parts = (0..4_u64)
5404                .map(|chunk| {
5405                    let first = i64::try_from(morsel * 32 + chunk * 8).expect("small");
5406                    let values =
5407                        (0..8_i64).map(|row| Value::BigInt(first + row)).collect::<Vec<_>>();
5408                    let column =
5409                        Vector::from_values(LogicalType::BigInt, &values).expect("a column");
5410                    ((morsel, chunk), Chunk::new(vec![column]).expect("one column"))
5411                })
5412                .collect::<Vec<_>>();
5413            writer.append_stripe(parts).expect("a stripe");
5414        }
5415        writer.finish().expect("commit");
5416
5417        let reader = Reader::open(&path).expect("valid directory");
5418        assert_eq!(reader.table().stripes().len(), 4, "a run is a stripe of its own");
5419        assert_eq!(reader.table().rows(), 128);
5420        for part in 0..16_usize {
5421            let read = reader.read(part, &[0]).expect("a part back");
5422            for row in 0..8_usize {
5423                let want = i64::try_from(part * 8 + row).expect("small");
5424                assert_eq!(read.value_at(row, 0), Value::BigInt(want), "part {part} row {row}");
5425            }
5426        }
5427        fs::remove_file(path).expect("remove scratch file");
5428    }
5429
5430    /// Runs from different callers may interleave and may not overlap, and the commit is what
5431    /// catches an overlap.
5432    #[test]
5433    fn runs_that_overlap_each_other_are_refused_at_commit() {
5434        let path = path("overlapping-runs");
5435        let mut writer =
5436            Writer::create(&path, "overlapping", vec![Field::new("v", LogicalType::BigInt)])
5437                .expect("new file");
5438        let one = |order: (u64, u64)| {
5439            let column =
5440                Vector::from_values(LogicalType::BigInt, &[Value::BigInt(1)]).expect("a column");
5441            (order, Chunk::new(vec![column]).expect("one column"))
5442        };
5443        // The second run sits inside the first rather than after it, which is a thing no instance
5444        // holding its own contiguous run can produce and a thing the file cannot represent.
5445        writer.append_stripe(vec![one((0, 0)), one((0, 2))]).expect("a stripe");
5446        writer.append_stripe(vec![one((0, 1))]).expect("a stripe");
5447        let error = writer.finish().expect_err("the runs overlap");
5448        assert!(error.message().contains("source order"), "{error}");
5449        fs::remove_file(path).expect("remove scratch file");
5450    }
5451
5452    /// A stripe holds [`STRIPE_PARTS`] parts, so a run longer than that is a caller bug rather than
5453    /// something to split, and the writer says so at the door instead of quietly cutting it in two.
5454    #[test]
5455    fn a_run_longer_than_a_stripe_is_refused() {
5456        let path = path("overlong-run");
5457        let mut writer =
5458            Writer::create(&path, "overlong", vec![Field::new("v", LogicalType::BigInt)])
5459                .expect("new file");
5460        let parts = (0..=STRIPE_PARTS)
5461            .map(|at| {
5462                let column = Vector::from_values(LogicalType::BigInt, &[Value::BigInt(1)])
5463                    .expect("a column");
5464                let chunk = Chunk::new(vec![column]).expect("one column");
5465                ((0, u64::try_from(at).expect("small")), chunk)
5466            })
5467            .collect::<Vec<_>>();
5468        let error = writer.append_stripe(parts).expect_err("one part too many");
5469        assert!(error.message().contains("more parts than it holds"), "{error}");
5470        fs::remove_file(path).expect("remove scratch file");
5471    }
5472
5473    /// Parts past the stripe bound start a new stripe, and every part stays addressable on its own.
5474    ///
5475    /// This is the shape the format exists for, so both ends of the split are checked here. The
5476    /// directory holds three stripes rather than a hundred and thirty one, and a read of any one
5477    /// part still answers with that part's rows rather than with its whole stripe's.
5478    #[test]
5479    fn parts_past_the_stripe_bound_start_a_new_stripe() {
5480        let path = path("stripe-bound");
5481        let mut writer = Writer::create(
5482            &path,
5483            "items",
5484            vec![
5485                Field::required("id", LogicalType::Integer),
5486                Field::new("text", LogicalType::Varchar),
5487            ],
5488        )
5489        .expect("new file");
5490        let parts = STRIPE_PARTS * 2 + 3;
5491        for part in 0..parts {
5492            let id = part as i32;
5493            let chunk = Chunk::new(vec![
5494                Vector::from_values(
5495                    LogicalType::Integer,
5496                    &[Value::Integer(id), Value::Integer(-id)],
5497                )
5498                .expect("integers"),
5499                Vector::from_values(
5500                    LogicalType::Varchar,
5501                    &[Value::Varchar(format!("value {part}")), Value::Null],
5502                )
5503                .expect("strings"),
5504            ])
5505            .expect("matching rows");
5506            writer.append(&chunk).expect("one part");
5507        }
5508        writer.finish().expect("commit");
5509
5510        let reader = Reader::open(&path).expect("reopen from disk");
5511        assert_eq!(reader.parts(), parts);
5512        assert_eq!(reader.table().rows(), parts * 2);
5513        assert_eq!(reader.table().stripes().len(), parts.div_ceil(STRIPE_PARTS));
5514        assert_eq!(reader.table().stripes()[0].parts(), STRIPE_PARTS);
5515        assert_eq!(reader.table().stripes()[0].rows(), STRIPE_PARTS * 2);
5516        assert_eq!(reader.table().stripes()[2].parts(), 3);
5517        // Backwards on purpose. The reader keeps four stripes a column, so a scan that walks the
5518        // table the other way is what catches a cache that only ever holds what it just read.
5519        for part in (0..parts).rev() {
5520            let dense = reader.read(part, &[0, 1]).expect("a whole page read");
5521            let sparse = reader.read_sparse(part, &[0, 1]).expect("one part read");
5522            for chunk in [&dense, &sparse] {
5523                assert_eq!(chunk.len(), 2, "part {part} has its own row count");
5524                assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
5525                assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
5526                assert_eq!(chunk.value_at(0, 1), Value::Varchar(format!("value {part}")));
5527                assert_eq!(chunk.value_at(1, 1), Value::Null);
5528            }
5529        }
5530        // The bounds are merged over the stripe, so they answer for the range the whole stripe
5531        // covers and not for the part that was asked about.
5532        let above = [Probe { column: 0, op: Op::Greater, value: Bound::Int(100) }];
5533        assert!(reader.skips(0, &above), "the first stripe stops at 63");
5534        assert!(!reader.skips(STRIPE_PARTS * 2, &above), "the third stripe reaches 130");
5535        fs::remove_file(path).expect("remove scratch file");
5536    }
5537
5538    /// A scattered value in the column that decides `WHERE UserID = ?`.
5539    fn scattered(n: i64) -> i64 {
5540        n.wrapping_mul(-7_046_029_254_386_353_131)
5541    }
5542
5543    /// A part whose sieve does not hold the constant is skipped, and a range would skip none of them.
5544    ///
5545    /// This is ClickBench query 19 in miniature. The values are spread over the whole of `BIGINT`, so
5546    /// every stripe's bounds cover nearly all of it and rule out nothing, and the part that really
5547    /// holds the value is the only one a scan has to read.
5548    #[test]
5549    fn a_part_is_skipped_when_its_sieve_does_not_hold_the_constant() {
5550        let path = path("sieve-skip");
5551        let mut writer =
5552            Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
5553                .expect("new file");
5554        let parts = STRIPE_PARTS + 3;
5555        // Big enough that the filter is worth its bytes. A part of eight numbers packs to under a
5556        // hundred bytes and the smallest filter there is is sixty nine, so a filter over a part
5557        // that small costs about as much to read as the rows do and is no longer written.
5558        let per_part = 128;
5559        for part in 0..parts {
5560            let held: Vec<Value> = (0..per_part)
5561                .map(|row| Value::BigInt(scattered((part * per_part + row) as i64)))
5562                .collect();
5563            let chunk =
5564                Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
5565                    .expect("one column");
5566            writer.append(&chunk).expect("one part");
5567        }
5568        writer.finish().expect("commit");
5569
5570        let reader = Reader::open(&path).expect("reopen from disk");
5571        let probe = |value: i64| Probe {
5572            column: 0,
5573            op: Op::Equal,
5574            value: Bound::Int(i128::from(scattered(value))),
5575        };
5576        for wanted in [0_i64, (per_part + 1) as i64, (parts * per_part - 1) as i64] {
5577            let tests = [probe(wanted)];
5578            let kept: Vec<usize> = (0..parts).filter(|&part| !reader.skips(part, &tests)).collect();
5579            let home = wanted as usize / per_part;
5580            assert!(kept.contains(&home), "the part holding {wanted} is read");
5581            // A filter answers maybe, so a part it keeps need not hold the value. Sixty seven parts
5582            // of a hundred and twenty eight numbers each, at a dozen bits a value, is about one
5583            // stray part across the whole file and that is what this leaves room for.
5584            assert!(kept.len() <= 2, "{wanted} keeps {kept:?}, which is more than one stray part");
5585        }
5586        let absent = [probe((parts * per_part) as i64 + 1)];
5587        let kept = (0..parts).filter(|&part| !reader.skips(part, &absent)).count();
5588        assert!(kept <= 1, "{kept} parts of {parts} kept a value no part holds");
5589        // The same probes against the bounds alone, which is what this replaces. A column of
5590        // scattered numbers has a range per stripe that covers nearly the whole type.
5591        let tests = [probe(0)];
5592        assert!(
5593            reader.table().stripes().iter().all(|stripe| !stripe.zone.skips(&tests)),
5594            "the bounds rule out no stripe at all"
5595        );
5596        fs::remove_file(path).expect("remove scratch file");
5597    }
5598
5599    /// A part whose own bounds rule out an ordered comparison is skipped where the stripe's keep it.
5600    ///
5601    /// This is the shape of ClickBench 24. Each part covers a narrow stretch of the column and the
5602    /// stripe covers all sixty four of them at once, so a comparison that lands inside the stripe
5603    /// rules out none of it and rules out all but a few parts.
5604    #[test]
5605    fn a_part_is_skipped_when_its_own_bounds_rule_out_a_comparison_the_stripe_keeps() {
5606        let path = path("part-range-skip");
5607        let mut writer =
5608            Writer::create(&path, "hits", vec![Field::required("at", LogicalType::BigInt)])
5609                .expect("new file");
5610        let parts = STRIPE_PARTS + 3;
5611        let per_part = 128;
5612        for part in 0..parts {
5613            // Scattered inside the part's own band rather than a run, because a run of
5614            // consecutive numbers encodes to a stride of a few bytes and then the page of ranges
5615            // costs more than reading the column it indexes, which is the case the writer declines.
5616            let held: Vec<Value> = (0..per_part)
5617                .map(|row| {
5618                    Value::BigInt((part * 1_000) as i64 + (scattered(row as i64).rem_euclid(900)))
5619                })
5620                .collect();
5621            let chunk =
5622                Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
5623                    .expect("one column");
5624            writer.append(&chunk).expect("one part");
5625        }
5626        writer.finish().expect("commit");
5627
5628        let reader = Reader::open(&path).expect("reopen from disk");
5629        let under = [Probe { column: 0, op: Op::Less, value: Bound::Int(3_000) }];
5630        let kept: Vec<usize> = (0..parts).filter(|&part| !reader.skips(part, &under)).collect();
5631        assert_eq!(kept, vec![0, 1, 2], "only the three parts that start under three thousand");
5632        // The same question asked of the stripe alone, which is what this replaces.
5633        assert!(!reader.stripe_skips(0, &under), "the stripe reaches from zero and keeps itself");
5634        fs::remove_file(path).expect("remove scratch file");
5635    }
5636
5637    /// The other half of the same page. A part whose own bounds put every row of it inside the
5638    /// filter is waved through, so the comparison never runs on it, where the stripe's bounds reach
5639    /// across every part and can prove nothing.
5640    #[test]
5641    fn a_part_is_waved_through_when_its_own_bounds_pass_a_comparison_the_stripe_cannot() {
5642        let path = path("part-range-certain");
5643        let mut writer =
5644            Writer::create(&path, "hits", vec![Field::required("at", LogicalType::BigInt)])
5645                .expect("new file");
5646        let parts = STRIPE_PARTS + 3;
5647        let per_part = 128;
5648        for part in 0..parts {
5649            let held: Vec<Value> = (0..per_part)
5650                .map(|row| {
5651                    Value::BigInt((part * 1_000) as i64 + (scattered(row as i64).rem_euclid(900)))
5652                })
5653                .collect();
5654            let chunk =
5655                Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
5656                    .expect("one column");
5657            writer.append(&chunk).expect("one part");
5658        }
5659        writer.finish().expect("commit");
5660
5661        let reader = Reader::open(&path).expect("reopen from disk");
5662        let under = [Probe { column: 0, op: Op::Less, value: Bound::Int(3_000) }];
5663        let waved: Vec<usize> = (0..parts).filter(|&part| reader.certain(part, &under)).collect();
5664        assert_eq!(waved, vec![0, 1, 2], "the three parts that end under three thousand");
5665        // The first stripe reaches from zero to past sixty thousand, so it straddles three thousand
5666        // and settles nothing either way. The three yeses above are the parts' own ends talking.
5667        assert!(!reader.stripe_skips(0, &under), "the stripe straddles the comparison");
5668        fs::remove_file(path).expect("remove scratch file");
5669    }
5670
5671    /// The page is worth its bytes on a column with parts to tell apart and is not written on one
5672    /// that has a single part, where the stripe bounds already are the part's.
5673    #[test]
5674    fn a_stripe_of_one_part_writes_no_range_page_and_a_stripe_of_many_does() {
5675        for (parts, wanted) in [(1_usize, false), (STRIPE_PARTS, true)] {
5676            let path = path("part-range-page");
5677            let mut writer =
5678                Writer::create(&path, "hits", vec![Field::required("at", LogicalType::BigInt)])
5679                    .expect("new file");
5680            for part in 0..parts {
5681                let held: Vec<Value> = (0..128)
5682                    .map(|row| {
5683                        Value::BigInt((part * 1_000) as i64 + scattered(row as i64).rem_euclid(900))
5684                    })
5685                    .collect();
5686                let chunk = Chunk::new(vec![
5687                    Vector::from_values(LogicalType::BigInt, &held).expect("numbers"),
5688                ])
5689                .expect("one column");
5690                writer.append(&chunk).expect("one part");
5691            }
5692            writer.finish().expect("commit");
5693            let reader = Reader::open(&path).expect("reopen from disk");
5694            let bytes = reader.layout().columns[0].part_ranges;
5695            assert_eq!(bytes > 0, wanted, "{parts} parts wrote {bytes} bytes of ranges");
5696            fs::remove_file(path).expect("remove scratch file");
5697        }
5698    }
5699
5700    /// A cut down string end is still an end on the side it was, which is the only thing that keeps
5701    /// a shortened bound from turning a skip into a wrong answer.
5702    #[test]
5703    fn a_string_end_that_is_cut_down_still_covers_the_value_it_came_from() {
5704        let long = vec![b'a'; PART_BOUND_BYTES * 2];
5705        let low = shortened(Some(Bound::Bytes(long.clone())), false).expect("a low end");
5706        let high = shortened(Some(Bound::Bytes(long.clone())), true).expect("a high end");
5707        let Bound::Bytes(low) = low else { panic!("a string stays a string") };
5708        let Bound::Bytes(high) = high else { panic!("a string stays a string") };
5709        assert!(low.len() <= PART_BOUND_BYTES && high.len() <= PART_BOUND_BYTES);
5710        assert!(low.as_slice() <= long.as_slice(), "the low end is at or under the value");
5711        assert!(high.as_slice() >= long.as_slice(), "the high end is at or over the value");
5712    }
5713
5714    /// A string of nothing but the largest byte has no prefix that can be stepped up, so the high
5715    /// end is given up rather than claimed too small. No end keeps the part, which is always safe.
5716    #[test]
5717    fn a_string_end_with_no_room_to_step_up_gives_up_the_bound() {
5718        let long = vec![u8::MAX; PART_BOUND_BYTES * 2];
5719        assert_eq!(shortened(Some(Bound::Bytes(long.clone())), true), None);
5720        let low = shortened(Some(Bound::Bytes(long)), false).expect("a low end is still a prefix");
5721        assert_eq!(low, Bound::Bytes(vec![u8::MAX; PART_BOUND_BYTES]));
5722    }
5723
5724    /// A sieve bigger than the part it indexes is not written, and one smaller than it still is.
5725    ///
5726    /// Both columns hold values spread over the whole of `BIGINT`, so neither gets a bitmap and both
5727    /// reach the filter. They differ in what the part costs to read. `spread` is a thousand distinct
5728    /// numbers and packs to eight kilobytes, so a filter of about thirteen hundred bytes is a good
5729    /// trade. `repeated` is the same thousand rows over four numbers in runs and encodes to
5730    /// almost nothing, but the filter is sized for the rows rather than the values it turns out to
5731    /// hold, so it comes out larger than the data. Reading it to decide whether to read the part spends more than
5732    /// the part, every time, and that is the case this drops.
5733    #[test]
5734    fn a_sieve_larger_than_the_part_it_indexes_is_not_written() {
5735        let path = path("sieve-pays");
5736        let fields = vec![
5737            Field::required("spread", LogicalType::BigInt),
5738            Field::required("repeated", LogicalType::BigInt),
5739        ];
5740        let mut writer = Writer::create(&path, "hits", fields).expect("new file");
5741        let parts = 3;
5742        let per_part = 1024;
5743        for part in 0..parts {
5744            let base = (part * per_part) as i64;
5745            let spread: Vec<Value> =
5746                (0..per_part).map(|row| Value::BigInt(scattered(base + row as i64))).collect();
5747            let repeated: Vec<Value> =
5748                (0..per_part).map(|row| Value::BigInt(scattered((row / 256) as i64))).collect();
5749            let chunk = Chunk::new(vec![
5750                Vector::from_values(LogicalType::BigInt, &spread).expect("numbers"),
5751                Vector::from_values(LogicalType::BigInt, &repeated).expect("numbers"),
5752            ])
5753            .expect("two columns");
5754            writer.append(&chunk).expect("one part");
5755        }
5756        writer.finish().expect("commit");
5757
5758        let reader = Reader::open(&path).expect("reopen from disk");
5759        let layout = reader.layout();
5760        let spread = &layout.columns[0];
5761        let repeated = &layout.columns[1];
5762        assert!(spread.sieves > 0, "a column whose parts are worth a filter keeps one");
5763        assert_eq!(
5764            repeated.sieves, 0,
5765            "a column whose filter costs more than its parts keeps none"
5766        );
5767        // Per part this is the rule itself, so it holds over the column as well: a part without a
5768        // sieve adds to one side of this and to nothing on the other.
5769        for column in &layout.columns {
5770            assert!(
5771                column.sieves < column.pages,
5772                "{} spends {} on sieves over {} of data",
5773                column.name,
5774                column.sieves,
5775                column.pages
5776            );
5777        }
5778        // The filter that was kept still does what it is for.
5779        let absent = [Probe {
5780            column: 0,
5781            op: Op::Equal,
5782            value: Bound::Int(i128::from(scattered((parts * per_part) as i64 + 1))),
5783        }];
5784        assert!((0..parts).all(|part| reader.skips(part, &absent)), "no part holds it");
5785        fs::remove_file(path).expect("remove scratch file");
5786    }
5787
5788    /// A damaged sieve page is a part that gets read, not a query that fails.
5789    ///
5790    /// A sieve is an index over rows that are still there and still correct, so losing one costs
5791    /// time and costs no answers. That is the opposite of the membership index beside it, which is
5792    /// the only thing standing between a string page and a wrong answer.
5793    #[test]
5794    fn a_damaged_sieve_page_is_read_through_rather_than_refused() {
5795        let path = path("sieve-damaged");
5796        let mut writer =
5797            Writer::create(&path, "hits", vec![Field::required("id", LogicalType::BigInt)])
5798                .expect("new file");
5799        let rows = 128;
5800        let held: Vec<Value> = (0..rows).map(|row| Value::BigInt(scattered(row))).collect();
5801        let chunk =
5802            Chunk::new(vec![Vector::from_values(LogicalType::BigInt, &held).expect("numbers")])
5803                .expect("one column");
5804        writer.append(&chunk).expect("one part");
5805        writer.finish().expect("commit");
5806
5807        let page =
5808            Reader::open(&path).expect("reopen").table.stripes[0].sieves[0].expect("a sieve page");
5809        let mut file = OpenOptions::new().write(true).open(&path).expect("open the sieve page");
5810        file.seek(SeekFrom::Start(page.offset + u64::from(page.length) - 1)).expect("seek");
5811        file.write_all(&[0xff]).expect("damage one byte");
5812        drop(file);
5813
5814        let reader = Reader::open(&path).expect("reopen the damaged file");
5815        let absent =
5816            [Probe { column: 0, op: Op::Equal, value: Bound::Int(i128::from(scattered(99))) }];
5817        assert!(!reader.skips(0, &absent), "a sieve that cannot be read skips nothing");
5818        assert_eq!(
5819            reader.read(0, &[0]).expect("the rows are untouched").len(),
5820            usize::try_from(rows).expect("a small count")
5821        );
5822        fs::remove_file(path).expect("remove scratch file");
5823    }
5824
5825    /// Eight workers over one stripe read it once between them.
5826    ///
5827    /// This is the shape a scan actually has. Parts are handed out in order, so every worker on a
5828    /// column crosses into a stripe within a few parts of the others, and before [`Reader::held`]
5829    /// started sharing the read every one of them read the whole page. On the full ClickBench file
5830    /// that was a `MIN(EventDate), MAX(EventDate)` moving 3.2 GB off the disk to look at 400 MB of
5831    /// column, which is most of what a first touch costs.
5832    ///
5833    /// The workers that lose the race still answer, out of the part reads they do instead, which is
5834    /// what the values below are checking.
5835    #[test]
5836    fn workers_that_want_the_same_stripe_read_it_once() {
5837        let path = path("single-flight");
5838        let mut writer =
5839            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
5840                .expect("new file");
5841        for part in 0..STRIPE_PARTS {
5842            let id = part as i32;
5843            let chunk = Chunk::new(vec![
5844                Vector::from_values(
5845                    LogicalType::Integer,
5846                    &[Value::Integer(id), Value::Integer(-id)],
5847                )
5848                .expect("integers"),
5849            ])
5850            .expect("matching rows");
5851            writer.append(&chunk).expect("one part");
5852        }
5853        writer.finish().expect("commit");
5854
5855        let reader = Reader::open(&path).expect("reopen from disk");
5856        assert_eq!(reader.table().stripes().len(), 1, "one stripe is the point of the test");
5857        let barrier = std::sync::Barrier::new(8);
5858        std::thread::scope(|scope| {
5859            for worker in 0..8 {
5860                let reader = &reader;
5861                let barrier = &barrier;
5862                scope.spawn(move || {
5863                    barrier.wait();
5864                    for part in (worker..STRIPE_PARTS).step_by(8) {
5865                        let chunk = reader.read(part, &[0]).expect("a whole page read");
5866                        assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
5867                        assert_eq!(chunk.value_at(1, 0), Value::Integer(-(part as i32)));
5868                    }
5869                });
5870            }
5871        });
5872        assert_eq!(reader.pages.load(Atomic::Relaxed), 1, "one stripe, one page read, whoever won");
5873        fs::remove_file(path).expect("remove scratch file");
5874    }
5875
5876    /// Opening a file reads the header and the directory, and nothing that depends on the rows.
5877    ///
5878    /// `spec/stats/04-in-memory.md` section 4.2. There are no statistics in the file yet, so this
5879    /// holds today by not having anything to load, and that is exactly why it is worth pinning now.
5880    /// The change that breaks it is the reasonable looking one: summaries are a few hundred bytes,
5881    /// the next query will want them, so read them on the way past. A process that opened the
5882    /// database to run one trivial query pays for all of it and gets nothing.
5883    ///
5884    /// Two files of the same shape and a thousand times the rows in one of them, opened, and the
5885    /// two openings cost the same. The stripe count is held equal so that the directory is the same
5886    /// size in both, which leaves the rows as the only thing that changed. Anything read out of the
5887    /// data would show up here.
5888    #[test]
5889    fn opening_costs_the_same_over_a_thousand_times_the_rows() {
5890        let opened = |label: &str, rows_per_part: i32| {
5891            let path = path(label);
5892            let mut writer =
5893                Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
5894                    .expect("new file");
5895            for part in 0..STRIPE_PARTS * 3 {
5896                // Scrambled rather than sequential, so that the fat file is actually fatter. A run
5897                // of consecutive integers encodes to almost nothing and would leave the two files
5898                // the same size, which would make this test pass for the wrong reason.
5899                let values = (0..rows_per_part)
5900                    .map(|row| {
5901                        Value::Integer((part as i32 * rows_per_part + row).wrapping_mul(2_654_435))
5902                    })
5903                    .collect::<Vec<_>>();
5904                let chunk = Chunk::new(vec![
5905                    Vector::from_values(LogicalType::Integer, &values).expect("integers"),
5906                ])
5907                .expect("matching rows");
5908                writer.append(&chunk).expect("one part");
5909            }
5910            writer.finish().expect("commit");
5911            let reader = Reader::open(&path).expect("reopen from disk");
5912            let size = fs::metadata(&path).expect("the file is there").len();
5913            let out = (reader.reads(), reader.table().stripes().len(), size);
5914            fs::remove_file(path).expect("remove scratch file");
5915            out
5916        };
5917
5918        let (thin, thin_stripes, thin_size) = opened("open-thin", 1);
5919        let (fat, fat_stripes, fat_size) = opened("open-fat", 1000);
5920        assert_eq!(
5921            thin_stripes, fat_stripes,
5922            "the same stripe count is what makes this a fair ask"
5923        );
5924        assert!(
5925            fat_size > thin_size * 50,
5926            "the fat file has to actually be larger, and it is {fat_size} against {thin_size}"
5927        );
5928
5929        assert_eq!(thin.opening.reads, fat.opening.reads, "the same reads either way");
5930        assert_eq!(thin.pages, 0, "opening read a page");
5931        assert_eq!(fat.pages, 0, "opening read a page");
5932        assert_eq!(thin.indexes, 0, "opening read an index");
5933        assert_eq!(fat.indexes, 0, "opening read an index");
5934        // Not exactly equal, because a directory holds offsets and a larger file has larger ones,
5935        // and a handful of bytes of varint is not somebody loading statistics. A factor is.
5936        assert!(
5937            fat.opening.bytes < thin.opening.bytes * 2,
5938            "opening the thin file read {} bytes and the fat one read {}",
5939            thin.opening.bytes,
5940            fat.opening.bytes
5941        );
5942    }
5943
5944    /// The reads a file costs to open are fixed by its shape and not by what ran before.
5945    ///
5946    /// `spec/stats/04-in-memory.md` section 4.3, which is the rule that keeps a plan reproducible:
5947    /// the plan is a function of the data, the generation and the settings, and never of what
5948    /// happened to be in cache. Opening the same file twice in the same process has to cost the
5949    /// same, because a second open that read less would be an open that was about to plan
5950    /// differently.
5951    #[test]
5952    fn two_opens_of_one_file_cost_the_same_and_the_second_is_not_cheaper() {
5953        let path = path("open-twice");
5954        let mut writer =
5955            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
5956                .expect("new file");
5957        for part in 0..STRIPE_PARTS * 3 {
5958            let chunk = Chunk::new(vec![
5959                Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
5960                    .expect("integers"),
5961            ])
5962            .expect("matching rows");
5963            writer.append(&chunk).expect("one part");
5964        }
5965        writer.finish().expect("commit");
5966
5967        let first = Reader::open(&path).expect("open");
5968        // A whole scan in between, so the operating system's page cache is as warm as it gets and
5969        // anything that consulted it would show up in the second open.
5970        for part in 0..first.parts() {
5971            first.read(part, &[0]).expect("a part");
5972        }
5973        assert!(first.reads().pages > 0, "the scan has to have read something");
5974        let second = Reader::open(&path).expect("open again");
5975
5976        assert_eq!(first.reads().opening, second.reads().opening);
5977        assert_eq!(
5978            second.reads().pages,
5979            0,
5980            "the second open read a page off the back of the first"
5981        );
5982        assert_eq!(second.reads().indexes, 0, "the second open read an index it inherited");
5983        fs::remove_file(path).expect("remove scratch file");
5984    }
5985
5986    /// A scan reads a stripe's index once for the whole scan, not once per part that misses.
5987    ///
5988    /// The page cache holds four stripes and an index used to ride inside it, so a table with more
5989    /// stripes than that read the index again every time a stripe came back around. The index is a
5990    /// few hundred bytes and the page is a quarter of a megabyte, which is why they are now under
5991    /// different budgets. This is the test that keeps them there, since the saving is small enough
5992    /// that nothing in a benchmark would notice it going away again.
5993    #[test]
5994    fn an_index_is_read_once_per_stripe_however_often_the_page_is_evicted() {
5995        let path = path("index-cache");
5996        let mut writer =
5997            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
5998                .expect("new file");
5999        let parts = STRIPE_PARTS * (CACHED_STRIPES_PER_COLUMN + 2);
6000        for part in 0..parts {
6001            let id = part as i32;
6002            let chunk = Chunk::new(vec![
6003                Vector::from_values(LogicalType::Integer, &[Value::Integer(id)]).expect("integers"),
6004            ])
6005            .expect("matching rows");
6006            writer.append(&chunk).expect("one part");
6007        }
6008        writer.finish().expect("commit");
6009
6010        let reader = Reader::open(&path).expect("reopen from disk");
6011        let stripes = reader.table().stripes().len();
6012        assert!(stripes > CACHED_STRIPES_PER_COLUMN, "the page cache has to be too small for this");
6013        // Twice over, so that the second pass finds every page evicted and every index kept.
6014        for _ in 0..2 {
6015            for part in 0..parts {
6016                let chunk = reader.read(part, &[0]).expect("a part");
6017                assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
6018            }
6019        }
6020        assert_eq!(reader.indexes.load(Atomic::Relaxed), stripes, "one index read per stripe");
6021        assert!(
6022            reader.pages.load(Atomic::Relaxed) > stripes,
6023            "the pages are the ones that get read again, which is what makes the index count mean \
6024             something"
6025        );
6026        fs::remove_file(path).expect("remove scratch file");
6027    }
6028
6029    /// A worker per stripe reads its stripe once, once the cache has been told how many there are.
6030    ///
6031    /// This is the shape a scan has when it hands out a whole stripe per morsel rather than a part.
6032    /// Nobody races for a page any more, but every worker holds a different one for the length of a
6033    /// stripe, so a cache that keeps four pages while eight workers are in eight stripes evicts
6034    /// every one of them before its owner has finished with it, and the owner reads a quarter of a
6035    /// megabyte again for the next part. The barrier is what makes that certain rather than likely:
6036    /// without it a worker can run a whole stripe before the next one starts and never collide.
6037    #[test]
6038    fn a_worker_per_stripe_reads_its_page_once_when_the_cache_was_told_to_expect_it() {
6039        let workers = CACHED_STRIPES_PER_COLUMN + 4;
6040        let path = path("stripe-per-worker");
6041        let mut writer =
6042            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
6043                .expect("new file");
6044        for part in 0..STRIPE_PARTS * workers {
6045            let chunk = Chunk::new(vec![
6046                Vector::from_values(LogicalType::Integer, &[Value::Integer(part as i32)])
6047                    .expect("integers"),
6048            ])
6049            .expect("matching rows");
6050            writer.append(&chunk).expect("one part");
6051        }
6052        writer.finish().expect("commit");
6053
6054        let read = |told: bool| {
6055            let reader = Reader::open(&path).expect("reopen from disk");
6056            assert_eq!(reader.table().stripes().len(), workers, "a stripe per worker");
6057            if told {
6058                reader.keep_stripes(workers);
6059            }
6060            let barrier = std::sync::Barrier::new(workers);
6061            std::thread::scope(|scope| {
6062                for (worker, run) in reader.stripe_parts().into_iter().enumerate() {
6063                    let reader = &reader;
6064                    let barrier = &barrier;
6065                    scope.spawn(move || {
6066                        for part in run {
6067                            barrier.wait();
6068                            let chunk = reader.read(part, &[0]).expect("a part of my own stripe");
6069                            assert_eq!(chunk.value_at(0, 0), Value::Integer(part as i32));
6070                        }
6071                        assert!(worker < workers);
6072                    });
6073                }
6074            });
6075            reader.pages.load(Atomic::Relaxed)
6076        };
6077
6078        assert_eq!(read(true), workers, "one page read per stripe and no more");
6079        assert!(read(false) > workers, "a cache that small is read again on every part");
6080        fs::remove_file(path).expect("remove scratch file");
6081    }
6082
6083    /// A damaged index page is caught before anything decodes a part out of it.
6084    ///
6085    /// The index is the one structure a reader trusts to find bytes with, so it carries a checksum
6086    /// per column section rather than one for the page, and this is what says that check runs.
6087    #[test]
6088    fn a_damaged_index_page_is_an_error() {
6089        let path = path("damaged-index");
6090        let mut writer =
6091            Writer::create(&path, "items", vec![Field::required("id", LogicalType::Integer)])
6092                .expect("new file");
6093        writer.append(&sample_ids()).expect("first part");
6094        writer.append(&sample_ids()).expect("second part");
6095        writer.finish().expect("commit");
6096
6097        let reader = Reader::open(&path).expect("valid directory");
6098        let index = reader.table.stripes[0].index;
6099        let mut byte = [0; 1];
6100        read_at(&reader.file, index.offset, &mut byte).expect("the first part length");
6101        let mut file = OpenOptions::new().write(true).open(&path).expect("open index page");
6102        file.seek(SeekFrom::Start(index.offset)).expect("index start");
6103        file.write_all(&[!byte[0]]).expect("damage the first part length");
6104        let error = reader.read(1, &[0]).expect_err("a damaged index must not be used");
6105        assert!(error.message().contains("index page section checksum differs"), "{error}");
6106        fs::remove_file(path).expect("remove scratch file");
6107    }
6108
6109    /// Every integer width the format knows about, written and read back.
6110    ///
6111    /// The unsigned ones are the reason ClickBench can be stored at all: `hits` types `EventDate`
6112    /// as `USMALLINT`, and one unsupported column meant the whole table was refused. The extremes
6113    /// are in here on purpose, because a width that round trips through the wrong signedness only
6114    /// goes wrong at the end of its range.
6115    #[test]
6116    fn every_integer_width_round_trips_through_a_page() {
6117        let path = path("integer-widths");
6118        let columns = [
6119            (LogicalType::TinyInt, vec![Value::TinyInt(i8::MIN), Value::TinyInt(i8::MAX)]),
6120            (LogicalType::UTinyInt, vec![Value::UTinyInt(0), Value::UTinyInt(u8::MAX)]),
6121            (LogicalType::SmallInt, vec![Value::SmallInt(i16::MIN), Value::SmallInt(i16::MAX)]),
6122            (LogicalType::USmallInt, vec![Value::USmallInt(0), Value::USmallInt(u16::MAX)]),
6123            (LogicalType::Integer, vec![Value::Integer(i32::MIN), Value::Integer(i32::MAX)]),
6124            (LogicalType::UInteger, vec![Value::UInteger(0), Value::UInteger(u32::MAX)]),
6125            (LogicalType::BigInt, vec![Value::BigInt(i64::MIN), Value::BigInt(i64::MAX)]),
6126            (LogicalType::UBigInt, vec![Value::UBigInt(0), Value::UBigInt(u64::MAX)]),
6127        ];
6128        let fields = columns
6129            .iter()
6130            .enumerate()
6131            .map(|(at, (ty, _))| Field::required(format!("c{at}"), ty.clone()))
6132            .collect::<Vec<_>>();
6133        let vectors = columns
6134            .iter()
6135            .map(|(ty, values)| Vector::from_values(ty.clone(), values).expect("a vector"))
6136            .collect::<Vec<_>>();
6137        let mut writer = Writer::create(&path, "widths", fields).expect("new file");
6138        writer.append(&Chunk::new(vectors).expect("matching rows")).expect("one stripe");
6139        writer.finish().expect("commit");
6140
6141        let reader = Reader::open(&path).expect("reopen from disk");
6142        let wanted = (0..columns.len()).collect::<Vec<_>>();
6143        let read = reader.read(0, &wanted).expect("every column");
6144        assert_eq!(read.len(), 2);
6145        // row at a time: each column has its own type and its own pair of extremes.
6146        for (at, (ty, values)) in columns.iter().enumerate() {
6147            assert_eq!(read.value_at(0, at), values[0], "the low end of {ty}");
6148            assert_eq!(read.value_at(1, at), values[1], "the high end of {ty}");
6149        }
6150        fs::remove_file(path).expect("remove scratch file");
6151    }
6152
6153    #[test]
6154    fn numeric_frequency_candidates_keep_bounded_row_ordinals() {
6155        let path = path("frequency-ordinals");
6156        let mut writer =
6157            Writer::create(&path, "items", vec![Field::required("id", LogicalType::BigInt)])
6158                .expect("new file");
6159        let mut values = Vec::new();
6160        for leader in 0..10_i64 {
6161            values.extend(std::iter::repeat_n(leader, 100));
6162        }
6163        values.extend(1_000_i64..41_000);
6164        for part in values.chunks(1_024) {
6165            let vector = Vector::flat(LogicalType::BigInt, Data::Int64(part.to_vec().into()))
6166                .expect("big integers");
6167            writer.append(&Chunk::new(vec![vector]).expect("one column")).expect("one stripe");
6168        }
6169        writer.finish().expect("commit");
6170
6171        let reader = Reader::open(&path).expect("reopen from disk");
6172        let occurrences =
6173            reader.frequency_occurrences(0).expect("valid metadata").expect("bounded ordinals");
6174        assert!(occurrences.omitted_max < 100);
6175        assert!(occurrences.ordinals.len() <= FREQUENCY_ORDINALS);
6176        assert!(occurrences.ordinals.windows(2).all(|pair| pair[0] < pair[1]));
6177        assert_eq!(&occurrences.ordinals[..1_000], &(0_u64..1_000).collect::<Vec<_>>());
6178        fs::remove_file(path).expect("remove scratch file");
6179    }
6180
6181    /// The bug this is here for cost a 43 GB ClickBench table and an hour of reloading it. The
6182    /// format went from 11 to 12, every binary built after that said "magic or major version is
6183    /// unsupported" about the file, and there was no way to tell from the message whether the path
6184    /// was wrong, the file was truncated, or it was ours and simply older. The number this build
6185    /// wants is the whole answer and it was the one thing the message did not carry.
6186    #[test]
6187    fn a_file_from_another_format_says_which_format_it_is() {
6188        let older = path("older-format");
6189        let mut writer =
6190            Writer::create(&older, "items", vec![Field::new("id", LogicalType::Integer)])
6191                .expect("new file");
6192        let chunk = Chunk::new(vec![
6193            Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
6194                .expect("integers"),
6195        ])
6196        .expect("chunk");
6197        writer.append(&chunk).expect("page written");
6198        writer.finish().expect("commit");
6199
6200        let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
6201        file.seek(SeekFrom::Start(8)).expect("the version follows the magic");
6202        file.write_all(&(FORMAT - 1).to_le_bytes()).expect("write an older version");
6203        drop(file);
6204        let complaint = Reader::open(&older).expect_err("an older format is refused").to_string();
6205        assert!(complaint.contains(&format!("format {}", FORMAT - 1)), "{complaint}");
6206        assert!(complaint.contains(&format!("format {FORMAT}")), "{complaint}");
6207
6208        let mut file = OpenOptions::new().write(true).open(&older).expect("open for the header");
6209        file.seek(SeekFrom::Start(0)).expect("the magic is first");
6210        file.write_all(b"NOTRUDB!").expect("write another engine's magic");
6211        drop(file);
6212        let complaint = Reader::open(&older).expect_err("a foreign file is refused").to_string();
6213        assert!(complaint.contains("magic"), "{complaint}");
6214        assert!(!complaint.contains("format"), "a version has nothing to do with it: {complaint}");
6215        fs::remove_file(older).expect("remove scratch file");
6216    }
6217
6218    #[test]
6219    fn an_unfinished_or_damaged_file_does_not_answer_with_partial_rows() {
6220        let unfinished = path("unfinished");
6221        let mut writer =
6222            Writer::create(&unfinished, "items", vec![Field::new("id", LogicalType::Integer)])
6223                .expect("new file");
6224        let chunk = Chunk::new(vec![
6225            Vector::flat(LogicalType::Integer, Data::Int32(vec![1, 2, 3].into()))
6226                .expect("integers"),
6227        ])
6228        .expect("chunk");
6229        writer.append(&chunk).expect("page written");
6230        drop(writer);
6231        assert!(Reader::open(&unfinished).is_err(), "no directory was committed");
6232        fs::remove_file(unfinished).expect("remove scratch file");
6233
6234        let damaged = path("damaged");
6235        let mut writer =
6236            Writer::create(&damaged, "items", vec![Field::new("id", LogicalType::Integer)])
6237                .expect("new file");
6238        writer.append(&chunk).expect("page written");
6239        writer.finish().expect("commit");
6240        let reader = Reader::open(&damaged).expect("valid directory");
6241        let mut file =
6242            OpenOptions::new().write(true).open(&damaged).expect("open for a damaged page");
6243        file.seek(SeekFrom::Start(HEADER + 1)).expect("inside first page");
6244        file.write_all(&[255]).expect("damage one byte");
6245        assert!(reader.read(0, &[0]).is_err(), "page checksum rejects corruption");
6246        fs::remove_file(damaged).expect("remove scratch file");
6247    }
6248
6249    #[test]
6250    fn damaged_lazy_dictionary_payload_is_an_error() {
6251        let path = path("damaged-dictionary");
6252        let mut writer = Writer::create(
6253            &path,
6254            "items",
6255            vec![
6256                Field::required("id", LogicalType::Integer),
6257                Field::new("text", LogicalType::Varchar),
6258            ],
6259        )
6260        .expect("new file");
6261        writer.append(&sample()).expect("stripe written");
6262        writer.finish().expect("commit");
6263
6264        let reader = Reader::open(&path).expect("valid directory");
6265        let dictionary = reader.table.dictionaries[1].expect("string dictionary page");
6266        // Read the count out of the page rather than writing it here, so that adding something
6267        // else to the index does not silently turn this into a test that damages the index.
6268        let mut header = [0; DICTIONARY_HEADER];
6269        read_at(&reader.file, dictionary.offset, &mut header).expect("dictionary header");
6270        let index_len = dictionary_index_len(&header);
6271        let rank_len = last_rank_end(&reader.file, dictionary.offset, &header);
6272        let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
6273        file.seek(SeekFrom::Start(dictionary.offset + index_len + rank_len))
6274            .expect("inside dictionary payload");
6275        file.write_all(&[255]).expect("damage dictionary payload");
6276
6277        let chunk = reader.read(0, &[1]).expect("code page and dictionary index remain valid");
6278        let error =
6279            chunk.validate_external().expect_err("payload corruption must reach the caller");
6280        assert!(error.message().contains("payload checksum differs"), "{error}");
6281        fs::remove_file(path).expect("remove scratch file");
6282    }
6283
6284    /// A payload of many blocks reads and checks every block of it.
6285    ///
6286    /// The test above has a dictionary of three values, which is one block, so it says nothing
6287    /// about a reader finding the right block among many. This one has thirty thousand values,
6288    /// which is thirty blocks, and it reads a value out of the first block and a value out of the
6289    /// last and then damages the last and asks for it again.
6290    #[test]
6291    fn a_dictionary_over_many_blocks_checks_every_block_of_it() {
6292        let path = path("dictionary-blocks");
6293        let value =
6294            |row: usize| format!("{row:07} a value long enough to be worth a payload block");
6295        let parts = 30;
6296        let per_part = 1000;
6297        let mut writer =
6298            Writer::create(&path, "items", vec![Field::required("text", LogicalType::Varchar)])
6299                .expect("new file");
6300        for part in 0..parts {
6301            let values = (0..per_part)
6302                .map(|row| Value::Varchar(value(part * per_part + row)))
6303                .collect::<Vec<_>>();
6304            let chunk = Chunk::new(vec![
6305                Vector::from_values(LogicalType::Varchar, &values).expect("strings"),
6306            ])
6307            .expect("matching rows");
6308            writer.append(&chunk).expect("a part");
6309        }
6310        writer.finish().expect("commit");
6311
6312        let reader = Reader::open(&path).expect("reopen from disk");
6313        let dictionary = reader.table.dictionaries[0].expect("string dictionary page");
6314        assert!(
6315            parts * per_part > TEXT_PAYLOAD_VALUES * 4,
6316            "the dictionary has to be several blocks for this to be testing anything"
6317        );
6318        for part in [0, parts - 1] {
6319            let chunk = reader.read(part, &[0]).expect("a part");
6320            chunk.validate_external().expect("every payload block checks out");
6321            assert_eq!(chunk.value_at(0, 0), Value::Varchar(value(part * per_part)));
6322        }
6323
6324        let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
6325        file.seek(SeekFrom::Start(dictionary.offset + u64::from(dictionary.length) - 4))
6326            .expect("the last bytes of the page are payload");
6327        file.write_all(&[255]).expect("damage the last payload block");
6328        let reader = Reader::open(&path).expect("the directory and the index are untouched");
6329        let chunk = reader.read(parts - 1, &[0]).expect("the code page remains valid");
6330        let error = chunk.validate_external().expect_err("the damage must reach the caller");
6331        assert!(error.message().contains("payload checksum differs"), "{error}");
6332        fs::remove_file(path).expect("remove scratch file");
6333    }
6334
6335    /// Values of different lengths read back where the offsets say they do.
6336    ///
6337    /// The offsets are packed at one width for the column, they are relative to the payload block a
6338    /// value lands in, and they go in runs of half a block, so there are two boundaries where the
6339    /// arithmetic could be off by one and neither shows up on values that are all the same length.
6340    /// This writes 5,000 values whose lengths cycle through a wide range and reads every one back,
6341    /// so the first value of a block, the last value of a run and the last value of a block are all
6342    /// covered several times over. An empty value is in the cycle because a zero length span is the
6343    /// case the reader short circuits.
6344    #[test]
6345    fn values_of_different_lengths_read_back_out_of_packed_offsets() {
6346        let path = path("dictionary-offsets");
6347        let value = |row: usize| {
6348            if row % 511 == 3 { String::new() } else { "x".repeat(row % 97) + &format!("{row:05}") }
6349        };
6350        let rows = 5_000;
6351        let mut writer =
6352            Writer::create(&path, "items", vec![Field::required("text", LogicalType::Varchar)])
6353                .expect("new file");
6354        let values = (0..rows).map(|row| Value::Varchar(value(row))).collect::<Vec<_>>();
6355        for part in values.chunks(1_000) {
6356            let chunk =
6357                Chunk::new(vec![Vector::from_values(LogicalType::Varchar, part).expect("strings")])
6358                    .expect("matching rows");
6359            writer.append(&chunk).expect("a part");
6360        }
6361        writer.finish().expect("commit");
6362
6363        let reader = Reader::open(&path).expect("reopen from disk");
6364        assert!(
6365            rows > TEXT_PAYLOAD_VALUES * 4,
6366            "the dictionary has to be several blocks for this to be testing anything"
6367        );
6368        for part in 0..rows / 1_000 {
6369            let chunk = reader.read(part, &[0]).expect("a part");
6370            for row in 0..1_000 {
6371                let row = part * 1_000 + row;
6372                assert_eq!(
6373                    chunk.value_at(row % 1_000, 0),
6374                    Value::Varchar(value(row)),
6375                    "value {row}"
6376                );
6377            }
6378        }
6379        fs::remove_file(path).expect("remove scratch file");
6380    }
6381
6382    /// Every worker of a scan wants the dictionary at the same moment and one of them fetches it.
6383    ///
6384    /// Asking a `OnceLock` whether it holds something answers the question a worker that already has
6385    /// the dictionary is asking and not the one a worker without it is asking, which is whether
6386    /// somebody is already on their way with it. Sixteen workers that all miss will all read the
6387    /// page, all verify it and all decode it, and fifteen will drop the result. Nothing about that
6388    /// is incorrect, which is why it went unnoticed, and it showed up as ClickBench 38 getting
6389    /// slower when the scan in front of it got faster and stopped staggering the arrivals.
6390    ///
6391    /// The barrier is what makes the test about that rather than about luck. Without it the first
6392    /// thread is usually finished before the last one starts and the count is one either way.
6393    #[test]
6394    fn a_global_dictionary_is_opened_once_however_many_workers_ask_at_once() {
6395        let path = path("dictionary-once");
6396        let parts = 8;
6397        let per_part = 500;
6398        let value =
6399            |row: usize| format!("{row:07} a value long enough to be worth a payload block");
6400        let mut writer =
6401            Writer::create(&path, "items", vec![Field::required("text", LogicalType::Varchar)])
6402                .expect("new file");
6403        for part in 0..parts {
6404            let values = (0..per_part)
6405                .map(|row| Value::Varchar(value(part * per_part + row)))
6406                .collect::<Vec<_>>();
6407            let chunk = Chunk::new(vec![
6408                Vector::from_values(LogicalType::Varchar, &values).expect("strings"),
6409            ])
6410            .expect("matching rows");
6411            writer.append(&chunk).expect("a part");
6412        }
6413        writer.finish().expect("commit");
6414
6415        let reader = Reader::open(&path).expect("reopen from disk");
6416        assert!(reader.table.dictionaries[0].is_some(), "the column has to have one to share");
6417        assert_eq!(reader.reads().dictionaries, 0, "opening the file does not open a dictionary");
6418
6419        let workers = 16;
6420        let gate = std::sync::Barrier::new(workers);
6421        std::thread::scope(|scope| {
6422            for worker in 0..workers {
6423                let reader = reader.clone();
6424                let gate = &gate;
6425                scope.spawn(move || {
6426                    gate.wait();
6427                    let chunk = reader.read(worker % parts, &[0]).expect("a part");
6428                    assert_eq!(
6429                        chunk.value_at(0, 0),
6430                        Value::Varchar(value((worker % parts) * per_part))
6431                    );
6432                });
6433            }
6434        });
6435
6436        assert_eq!(reader.reads().dictionaries, 1, "sixteen workers, one dictionary, one open");
6437        fs::remove_file(path).expect("remove scratch file");
6438    }
6439
6440    /// The sorted order sits outside the index the page checksum covers, because a query that
6441    /// never searches a dictionary should not read it, so it carries its own checksums and this is
6442    /// what says they are checked. A search that trusted a damaged order would give a wrong answer
6443    /// rather than a slow one.
6444    #[test]
6445    fn a_damaged_sorted_order_is_an_error() {
6446        let path = path("damaged-order");
6447        let mut writer = Writer::create(
6448            &path,
6449            "items",
6450            vec![
6451                Field::required("id", LogicalType::Integer),
6452                Field::new("text", LogicalType::Varchar),
6453            ],
6454        )
6455        .expect("new file");
6456        writer.append(&sample()).expect("stripe written");
6457        writer.finish().expect("commit");
6458
6459        let reader = Reader::open(&path).expect("valid directory");
6460        let page = reader.table.dictionaries[1].expect("string dictionary page");
6461        let mut header = [0; DICTIONARY_HEADER];
6462        read_at(&reader.file, page.offset, &mut header).expect("dictionary header");
6463        let index_len = dictionary_index_len(&header);
6464        let mut file = OpenOptions::new().write(true).open(&path).expect("open dictionary page");
6465        file.seek(SeekFrom::Start(page.offset + index_len)).expect("the first head");
6466        file.write_all(&[255]).expect("damage the order");
6467
6468        let dictionary = reader.dictionary(1).expect("read").expect("a string column has one");
6469        let error = dictionary.compare_rank(0, b"anything").expect_err("a damaged order is caught");
6470        assert!(error.message().contains("rank checksum differs"), "{error}");
6471        fs::remove_file(path).expect("remove scratch file");
6472    }
6473
6474    /// Codes stay in first appearance order and the sorted order is written beside them, so a
6475    /// reader can put the values back in order without the writer having had to know them all
6476    /// before it handed out the first code.
6477    #[test]
6478    fn a_global_dictionary_carries_the_sorted_order_of_its_values() {
6479        // Chosen so the sort cannot be decided on the first eight bytes alone. Three values share
6480        // a nine byte prefix, one is a prefix of another, and one is empty.
6481        let spellings = ["overlong1z", "b", "", "overlong1a", "overlong", "ab", "a", "overlong1"];
6482        let path = path("dictionary-order");
6483        let mut writer =
6484            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
6485                .expect("new file");
6486        writer
6487            .append(
6488                &Chunk::new(vec![
6489                    Vector::from_values(
6490                        LogicalType::Varchar,
6491                        &spellings.map(|text| Value::Varchar(text.into())),
6492                    )
6493                    .expect("strings"),
6494                ])
6495                .expect("one column"),
6496            )
6497            .expect("stripe written");
6498        writer.finish().expect("commit");
6499
6500        let reader = Reader::open(&path).expect("valid directory");
6501        let dictionary = reader.dictionary(0).expect("read").expect("a string column has one");
6502        let count = dictionary.ranks().expect("a v10 file stores one");
6503        assert_eq!(count, spellings.len(), "every distinct value has a rank");
6504        let order = (0..count)
6505            .map(|rank| dictionary.code_at_rank(rank).expect("a code"))
6506            .collect::<Vec<_>>();
6507        let mut seen = order.clone();
6508        seen.sort_unstable();
6509        assert_eq!(seen, (0..spellings.len() as u32).collect::<Vec<_>>(), "a permutation of codes");
6510
6511        let ranked = order
6512            .iter()
6513            .map(|&code| {
6514                dictionary.try_bytes_at(code as usize).expect("read").expect("a value").to_vec()
6515            })
6516            .collect::<Vec<_>>();
6517        let mut expected = spellings.map(|text| text.as_bytes().to_vec()).to_vec();
6518        expected.sort();
6519        assert_eq!(ranked, expected, "rank order is value order");
6520
6521        // What a search asks, on the values themselves rather than through a kernel, so that a
6522        // file whose heads disagree with its bytes is caught here rather than as a wrong answer.
6523        for (rank, value) in expected.iter().enumerate() {
6524            assert_eq!(
6525                dictionary.compare_rank(rank, value).expect("compare"),
6526                Ordering::Equal,
6527                "rank {rank} is its own value"
6528            );
6529            if rank > 0 {
6530                assert_eq!(
6531                    dictionary.compare_rank(rank - 1, value).expect("compare"),
6532                    Ordering::Less,
6533                    "rank {rank} follows the one before it"
6534                );
6535            }
6536        }
6537        fs::remove_file(path).expect("remove scratch file");
6538    }
6539
6540    /// A sweep of the dictionary reads every value and keeps what it read, up to the budget.
6541    ///
6542    /// The point of the sweep is the resident size rather than the answer, so both are checked
6543    /// here. A dictionary this small is well under [`TEXT_KEEP_BUDGET`], so it keeps everything and
6544    /// a second sweep decodes nothing, which is what makes the second statement of a session asking
6545    /// the same question cost what it should. The ceiling is the other half of it and it has its own
6546    /// test below, because a ceiling that never binds is not a ceiling anybody checked.
6547    #[test]
6548    fn a_dictionary_sweep_reads_every_value_and_keeps_it_under_the_budget() {
6549        let path = path("dictionary-sweep");
6550        // Two thousand five hundred distinct values is two whole payload blocks and a part of a
6551        // third, so the sweep has to be called more than once and the last call has to stop short.
6552        let spellings = (0..2_500)
6553            .map(|index| Value::Varchar(format!("value {index:08} {}", "x".repeat(index % 40))))
6554            .collect::<Vec<_>>();
6555        let mut writer =
6556            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
6557                .expect("new file");
6558        // A chunk is a part and a part is at most 1,024 rows, so the values go in three of them.
6559        // The dictionary is table wide and does not care where a value was written.
6560        for part in spellings.chunks(1_024) {
6561            writer
6562                .append(
6563                    &Chunk::new(vec![
6564                        Vector::from_values(LogicalType::Varchar, part).expect("strings"),
6565                    ])
6566                    .expect("one column"),
6567                )
6568                .expect("stripe written");
6569        }
6570        writer.finish().expect("commit");
6571
6572        let reader = Reader::open(&path).expect("valid directory");
6573        let dictionary = reader.dictionary(0).expect("read").expect("a string column has one");
6574        assert_eq!(dictionary.len(), spellings.len(), "every value is distinct");
6575
6576        let resting = dictionary.footprint();
6577        let mut swept: Vec<Vec<u8>> = Vec::new();
6578        let mut at = 0;
6579        let mut calls = 0;
6580        while at < dictionary.len() {
6581            let stopped = dictionary
6582                .sweep_text(at, dictionary.len(), &mut |index: usize, text: &[u8]| {
6583                    assert_eq!(index, swept.len(), "a sweep hands its values over in order");
6584                    swept.push(text.to_vec());
6585                    Ok(())
6586                })
6587                .expect("a sweep reads");
6588            assert!(stopped > at, "a sweep moves");
6589            at = stopped;
6590            calls += 1;
6591        }
6592        assert_eq!(calls, 3, "a sweep hands over one block at a time");
6593        let after = dictionary.footprint();
6594        assert!(after > resting, "a sweep under the budget keeps what it decoded");
6595
6596        let read = (0..dictionary.len())
6597            .map(|code| dictionary.try_bytes_at(code).expect("read").expect("a value").to_vec())
6598            .collect::<Vec<_>>();
6599        assert_eq!(swept, read, "a sweep answers what a point read answers");
6600        assert_eq!(dictionary.footprint(), after, "a point read of a kept block decodes nothing");
6601        fs::remove_file(path).expect("remove scratch file");
6602    }
6603
6604    /// A sweep over a block whose second run of offsets is short reads the same values as a point
6605    /// read does.
6606    ///
6607    /// The sweep decodes the offsets of a whole run at a time rather than a value at a time, and a
6608    /// run holds half a block, so the count it asks for is the run length everywhere but at the end
6609    /// of the dictionary. Two thousand five hundred values, which is what the test above writes,
6610    /// never puts a short run second in its block: the last block there begins on a run boundary and
6611    /// holds one run. Two thousand eight hundred does, so the last block is a whole run of five
6612    /// hundred and twelve followed by two hundred and forty, and an off by one in either the count
6613    /// asked for or the slice taken out of the answer shows up as a wrong value or a refusal.
6614    #[test]
6615    fn a_sweep_over_a_block_with_a_short_second_run_reads_what_a_point_read_reads() {
6616        let path = path("dictionary-sweep-short-run");
6617        let spellings = (0..2_800)
6618            .map(|index| Value::Varchar(format!("value {index:08} {}", "x".repeat(index % 40))))
6619            .collect::<Vec<_>>();
6620        let mut writer =
6621            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
6622                .expect("new file");
6623        for part in spellings.chunks(1_024) {
6624            writer
6625                .append(
6626                    &Chunk::new(vec![
6627                        Vector::from_values(LogicalType::Varchar, part).expect("strings"),
6628                    ])
6629                    .expect("one column"),
6630                )
6631                .expect("stripe written");
6632        }
6633        writer.finish().expect("commit");
6634
6635        let reader = Reader::open(&path).expect("valid directory");
6636        let dictionary = reader.dictionary(0).expect("read").expect("a string column has one");
6637        assert_eq!(dictionary.len(), spellings.len(), "every value is distinct");
6638        let last = dictionary.len() % TEXT_PAYLOAD_VALUES;
6639        assert!(last > TEXT_OFFSET_RUN, "the last block has to reach into a second run of offsets");
6640        assert!(last < TEXT_PAYLOAD_VALUES, "and that second run has to be short of a whole one");
6641
6642        let mut swept: Vec<Vec<u8>> = Vec::new();
6643        let mut at = 0;
6644        while at < dictionary.len() {
6645            let stopped = dictionary
6646                .sweep_text(at, dictionary.len(), &mut |index: usize, text: &[u8]| {
6647                    assert_eq!(index, swept.len(), "a sweep hands its values over in order");
6648                    swept.push(text.to_vec());
6649                    Ok(())
6650                })
6651                .expect("a sweep reads");
6652            assert!(stopped > at, "a sweep moves");
6653            at = stopped;
6654        }
6655        let read = (0..dictionary.len())
6656            .map(|code| dictionary.try_bytes_at(code).expect("read").expect("a value").to_vec())
6657            .collect::<Vec<_>>();
6658        assert_eq!(swept, read, "a sweep answers what a point read answers");
6659        fs::remove_file(path).expect("remove scratch file");
6660    }
6661
6662    /// Narrowing a page takes what fits and refuses the page for anything that does not.
6663    ///
6664    /// The edges of the range on both sides and one step past each of them, for every type, because
6665    /// checking a page separately from converting it is only right if the check refuses exactly what
6666    /// `TryFrom` would have refused, and off by one there is a file that reads back a different
6667    /// number than it was given. The check is a bit pattern rather than a comparison, so it is not
6668    /// the shape a reader would guess from the bounds, which is why all six are here. The empty page
6669    /// is here because a check written the obvious way starts with the extremes the wrong way round
6670    /// and refuses it.
6671    #[test]
6672    fn narrowing_a_page_takes_what_fits_and_refuses_what_does_not() {
6673        assert_eq!(fit::<i8>(&[]).expect("an empty page fits anything"), Vec::<i8>::new());
6674        assert_eq!(fit::<i8>(&[-128, 0, 127]).expect("the edges fit"), vec![-128_i8, 0, 127]);
6675        fit::<i8>(&[128]).expect_err("one past the top does not fit");
6676        fit::<i8>(&[-129]).expect_err("one past the bottom does not fit");
6677        assert_eq!(fit::<u8>(&[0, 255]).expect("the edges fit"), vec![0_u8, 255]);
6678        fit::<u8>(&[256]).expect_err("one past the top does not fit");
6679        fit::<u8>(&[-1]).expect_err("a negative does not fit an unsigned page");
6680        assert_eq!(
6681            fit::<i16>(&[-32_768, 0, 32_767]).expect("the edges fit"),
6682            vec![-32_768_i16, 0, 32_767]
6683        );
6684        fit::<i16>(&[32_768]).expect_err("one past the top does not fit");
6685        fit::<i16>(&[-32_769]).expect_err("one past the bottom does not fit");
6686        assert_eq!(fit::<u16>(&[0, 65_535]).expect("the edges fit"), vec![0_u16, 65_535]);
6687        fit::<u16>(&[65_536]).expect_err("one past the top does not fit");
6688        fit::<u16>(&[-1]).expect_err("a negative does not fit an unsigned page");
6689        assert_eq!(
6690            fit::<i32>(&[i64::from(i32::MIN), 0, i64::from(i32::MAX)]).expect("the edges fit"),
6691            vec![i32::MIN, 0, i32::MAX]
6692        );
6693        fit::<i32>(&[i64::from(i32::MAX) + 1]).expect_err("one past the top does not fit");
6694        fit::<i32>(&[i64::from(i32::MIN) - 1]).expect_err("one past the bottom does not fit");
6695        assert_eq!(
6696            fit::<u32>(&[0, 4_294_967_295]).expect("the edges fit"),
6697            vec![0_u32, 4_294_967_295]
6698        );
6699        fit::<u32>(&[4_294_967_296]).expect_err("one past the top does not fit");
6700        fit::<u32>(&[-1]).expect_err("a negative does not fit an unsigned page");
6701
6702        // One value in a page that fits is still a page that does not, which is the thing an or
6703        // into an accumulator could get wrong in a way a page of one value would never show.
6704        fit::<i8>(&[0, 1, 2, 128, 3]).expect_err("one bad value spoils the page");
6705    }
6706
6707    /// The residue says yes to exactly what `TryFrom` says yes to.
6708    ///
6709    /// The edges above are the cases anyone would think to write down. This is the argument that
6710    /// there are no others, made by asking both questions about every value either narrow type could
6711    /// have an opinion about, and then about the values around the wide edges and the ends of an
6712    /// `i64`, which a range that size cannot reach.
6713    #[test]
6714    fn the_residue_agrees_with_a_checked_conversion_everywhere() {
6715        for value in -70_000_i64..70_000 {
6716            assert_eq!(fit::<i8>(&[value]).is_ok(), i8::try_from(value).is_ok(), "{value} as i8");
6717            assert_eq!(fit::<u8>(&[value]).is_ok(), u8::try_from(value).is_ok(), "{value} as u8");
6718            assert_eq!(fit::<i16>(&[value]).is_ok(), i16::try_from(value).is_ok(), "{value} i16");
6719            assert_eq!(fit::<u16>(&[value]).is_ok(), u16::try_from(value).is_ok(), "{value} u16");
6720        }
6721        let wide = [i64::MIN, i64::MIN + 1, i64::from(i32::MIN), 0, i64::from(u32::MAX), i64::MAX];
6722        for edge in wide {
6723            for step in -2_i64..=2 {
6724                let value = edge.saturating_add(step);
6725                assert_eq!(
6726                    fit::<i32>(&[value]).is_ok(),
6727                    i32::try_from(value).is_ok(),
6728                    "{value} as i32"
6729                );
6730                assert_eq!(
6731                    fit::<u32>(&[value]).is_ok(),
6732                    u32::try_from(value).is_ok(),
6733                    "{value} as u32"
6734                );
6735            }
6736        }
6737    }
6738
6739    /// A dictionary at its budget sweeps without keeping, and still answers what it answered.
6740    ///
6741    /// The budget is a quarter of a gigabyte in a running database, which is a fine size for a real
6742    /// column and no size at all for a test, so this opens the same dictionary a second time with a
6743    /// budget of zero. That is the shape of the hundred million row case: `URL` fills the budget
6744    /// somewhere in the middle of itself and everything past that point is read and dropped, which
6745    /// costs the decode again and holds none of it.
6746    #[test]
6747    fn a_dictionary_at_its_budget_sweeps_without_keeping() {
6748        let path = path("dictionary-budget");
6749        let spellings = (0..2_500)
6750            .map(|index| Value::Varchar(format!("value {index:08} {}", "y".repeat(index % 40))))
6751            .collect::<Vec<_>>();
6752        let mut writer =
6753            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
6754                .expect("new file");
6755        for part in spellings.chunks(1_024) {
6756            writer
6757                .append(
6758                    &Chunk::new(vec![
6759                        Vector::from_values(LogicalType::Varchar, part).expect("strings"),
6760                    ])
6761                    .expect("one column"),
6762                )
6763                .expect("stripe written");
6764        }
6765        writer.finish().expect("commit");
6766
6767        let reader = Reader::open(&path).expect("valid directory");
6768        let page = reader.table.dictionaries[0].expect("a string column has one");
6769        let file = Arc::clone(&reader.file);
6770        let starved = open_global_dictionary(file, page, &LogicalType::Varchar, 0)
6771            .expect("a dictionary opens whatever it may keep");
6772
6773        let resting = starved.footprint();
6774        let mut swept: Vec<Vec<u8>> = Vec::new();
6775        let mut at = 0;
6776        while at < starved.len() {
6777            at = starved
6778                .sweep_text(at, starved.len(), &mut |_index: usize, text: &[u8]| {
6779                    swept.push(text.to_vec());
6780                    Ok(())
6781                })
6782                .expect("a sweep reads");
6783        }
6784        assert_eq!(swept.len(), spellings.len(), "a starved sweep still reads every value");
6785        assert_eq!(starved.footprint(), resting, "and keeps no block it decoded");
6786
6787        let generous = reader.dictionary(0).expect("read").expect("a string column has one");
6788        let read = (0..generous.len())
6789            .map(|code| generous.try_bytes_at(code).expect("read").expect("a value").to_vec())
6790            .collect::<Vec<_>>();
6791        assert_eq!(swept, read, "a starved sweep answers what a point read answers");
6792        fs::remove_file(path).expect("remove scratch file");
6793    }
6794
6795    #[test]
6796    fn damaged_membership_cannot_skip_a_string_page() {
6797        let path = path("damaged-membership");
6798        let mut writer = Writer::create(
6799            &path,
6800            "items",
6801            vec![
6802                Field::required("id", LogicalType::Integer),
6803                Field::new("text", LogicalType::Varchar),
6804            ],
6805        )
6806        .expect("new file");
6807        writer.append(&sample()).expect("stripe written");
6808        writer.finish().expect("commit");
6809
6810        let reader = Reader::open(&path).expect("valid directory");
6811        let membership = reader.table.stripes[0].memberships[1].expect("string membership");
6812        let mut file = OpenOptions::new().write(true).open(&path).expect("open membership page");
6813        file.seek(SeekFrom::Start(membership.offset)).expect("membership start");
6814        file.write_all(&[255]).expect("damage membership");
6815        let error = reader.skips_codes(0, 1, &[3]).expect_err("corruption must not skip rows");
6816        assert!(error.message().contains("membership page checksum differs"), "{error}");
6817        fs::remove_file(path).expect("remove scratch file");
6818    }
6819
6820    #[test]
6821    fn membership_delta_stream_is_sorted_exact_and_bounded() {
6822        let unique = unique_codes(&[900, 4, 4, 72, 9, u32::MAX]);
6823        assert_eq!(unique, [4, 9, 72, 900, u32::MAX]);
6824        let encoded = encode_membership(&unique);
6825        assert_eq!(
6826            decode_membership(&encoded).expect("valid membership"),
6827            [4, 9, 72, 900, u32::MAX]
6828        );
6829        // A stripe's index is the union of its parts', so a code in two of them is in it once and
6830        // the result is still one ascending run of deltas.
6831        let merged = merged_codes(vec![vec![4, 900], vec![9, 900, u32::MAX], vec![72]]);
6832        assert_eq!(merged, [4, 9, 72, 900, u32::MAX]);
6833        assert_eq!(
6834            decode_membership(&encode_membership(&merged)).expect("valid membership"),
6835            unique
6836        );
6837        assert!(decode_membership(&[1, 0x80]).is_err(), "a truncated varint is invalid");
6838        assert!(
6839            decode_membership(&[1, 0xff, 0xff, 0xff, 0xff, 0x10]).is_err(),
6840            "a value past u32 is invalid"
6841        );
6842    }
6843
6844    #[test]
6845    fn a_global_dictionary_may_be_larger_than_one_column_page() {
6846        let dictionary = Page {
6847            offset: HEADER,
6848            length: u32::try_from(MAX_PAGE + 1).expect("the page bound fits on disk"),
6849            hash: 0,
6850        };
6851        let table = Table {
6852            name: "items".to_owned(),
6853            fields: vec![Field::new("text", LogicalType::Varchar)],
6854            stripes: Vec::new(),
6855            rows: 0,
6856            dictionaries: vec![Some(dictionary)],
6857            distincts: vec![None],
6858            frequencies: vec![None],
6859        };
6860        let directory = encode_directory(&table).expect("directory");
6861        let file_size = dictionary.offset + u64::from(dictionary.length) + 1;
6862
6863        let decoded = decode_directory(&directory, file_size).expect("large lazy dictionary");
6864        assert_eq!(decoded.dictionaries[0].expect("dictionary").length, dictionary.length);
6865    }
6866
6867    #[test]
6868    fn a_column_with_one_value_everywhere_costs_almost_nothing_a_row() {
6869        let path = path("constant-codes");
6870        let mut writer =
6871            Writer::create(&path, "items", vec![Field::new("text", LogicalType::Varchar)])
6872                .expect("new file");
6873        let empty = vec![Value::Varchar(String::new()); 1024];
6874        for _ in 0..4 {
6875            let column = Vector::from_values(LogicalType::Varchar, &empty).expect("strings");
6876            writer.append(&Chunk::new(vec![column]).expect("one column")).expect("a part");
6877        }
6878        writer.finish().expect("commit");
6879
6880        let reader = Reader::open(&path).expect("valid directory");
6881        let pages = reader.layout().columns.first().expect("one column").pages;
6882        // This column used to cost four bytes a row, 16,384 of them, the same as a column of four
6883        // thousand distinct URLs would. The cascade calls each part a constant, so what is left is
6884        // a tag, a count and the value, and the row count stops being what drives the number.
6885        assert!(pages < 256, "{pages} bytes of pages for 4,096 rows of one value");
6886        let read = reader.read(3, &[0]).expect("the last part back");
6887        assert_eq!(read.value_at(0, 0), Value::Varchar(String::new()));
6888        assert_eq!(read.value_at(1023, 0), Value::Varchar(String::new()));
6889        fs::remove_file(path).expect("remove scratch file");
6890    }
6891
6892    #[test]
6893    fn a_cascade_value_too_wide_for_its_column_is_refused_rather_than_cut() {
6894        // What a damaged page looks like from here: the cascade decoded, so the bytes are not
6895        // truncated, but the values do not belong to the column the directory says they do.
6896        let over = vec![i64::from(i32::MAX) + 1];
6897        let error = narrowed(&LogicalType::Integer, over).expect_err("a page that disagrees");
6898        assert!(format!("{error}").contains("not of its type"), "{error}");
6899        assert!(narrowed(&LogicalType::BigInt, vec![i64::MIN]).is_ok(), "bigint holds all of i64");
6900        assert!(narrowed(&LogicalType::Varchar, vec![0]).is_err(), "strings are not integers");
6901    }
6902
6903    #[test]
6904    fn a_code_stream_the_cascade_cannot_shrink_is_left_alone() {
6905        // A shift register rather than a run, because an arithmetic run is the one wide shape the
6906        // cascade does shrink. This is what a column with tens of millions of distinct values hands
6907        // over: full width codes with no order to them.
6908        let mut state: u32 = 0x9e37_79b9;
6909        let spread: Vec<u32> = (0..1024)
6910            .map(|_| {
6911                state ^= state << 13;
6912                state ^= state >> 17;
6913                state ^= state << 5;
6914                state
6915            })
6916            .collect();
6917        assert_eq!(encoded_codes(&spread).expect("no failure"), None);
6918        let near: Vec<u32> = (0..1024).collect();
6919        let coded = encoded_codes(&near).expect("no failure").expect("counting up is packable");
6920        assert!(coded.len() < near.len() * 4, "{} bytes for a run of 1,024", coded.len());
6921    }
6922
6923    /// The columns of a stripe are encoded on whichever thread got to them, so the one thing that
6924    /// must not depend on which thread that was is the file. Two writes of the same rows are
6925    /// compared byte for byte rather than value for value, because a dictionary that two columns
6926    /// somehow shared would still read back correctly and would hand out its codes in the order the
6927    /// threads happened to run in, which is exactly what this is here to catch.
6928    #[test]
6929    fn two_writes_of_the_same_rows_give_the_same_bytes() {
6930        fn written(path: &PathBuf) {
6931            let fields = (0..40)
6932                .map(|column| {
6933                    let ty =
6934                        if column % 4 == 0 { LogicalType::Varchar } else { LogicalType::BigInt };
6935                    Field::new(format!("c{column}"), ty)
6936                })
6937                .collect::<Vec<_>>();
6938            let mut writer = Writer::create(path, "wide", fields).expect("new file");
6939            for part in 0..70_u64 {
6940                let columns = (0..40)
6941                    .map(|column| {
6942                        let values = (0..64_u64)
6943                            .map(|row| {
6944                                let seed = part.wrapping_mul(31).wrapping_add(row);
6945                                if column % 4 == 0 {
6946                                    Value::Varchar(format!("v{}", seed % 17))
6947                                } else {
6948                                    Value::BigInt(i64::try_from(seed % 97).expect("small"))
6949                                }
6950                            })
6951                            .collect::<Vec<_>>();
6952                        let ty = if column % 4 == 0 {
6953                            LogicalType::Varchar
6954                        } else {
6955                            LogicalType::BigInt
6956                        };
6957                        Vector::from_values(ty, &values).expect("a column")
6958                    })
6959                    .collect::<Vec<_>>();
6960                writer.append(&Chunk::new(columns).expect("forty columns")).expect("a part");
6961            }
6962            writer.finish().expect("commit");
6963        }
6964
6965        let first = path("repeatable-one");
6966        let second = path("repeatable-two");
6967        written(&first);
6968        written(&second);
6969        let left = fs::read(&first).expect("the first file");
6970        let right = fs::read(&second).expect("the second file");
6971        assert_eq!(left.len(), right.len(), "two writes of the same rows differ in length");
6972        assert!(left == right, "two writes of the same rows differ in their bytes");
6973
6974        // And the rows are still there, since a pair of identically wrong files would pass the
6975        // comparison above on its own.
6976        let reader = Reader::open(&first).expect("valid directory");
6977        assert_eq!(reader.table().rows(), 70 * 64);
6978        let read = reader.read(0, &[0, 1]).expect("the first part back");
6979        assert_eq!(read.value_at(0, 0), Value::Varchar("v0".to_owned()));
6980        assert_eq!(read.value_at(0, 1), Value::BigInt(0));
6981        fs::remove_file(first).expect("remove scratch file");
6982        fs::remove_file(second).expect("remove scratch file");
6983    }
6984}