Skip to main content

mongreldb_core/
sorted_run.rs

1//! Sorted Run — the immutable columnar unit (`.sr`).
2//!
3//! On-disk layout: a 256-byte header, a columnar page region (PAX), a column
4//! directory, an index trailer, and a checksummed footer. [`RunWriter`] flushes
5//! drained memtable rows into encoded columns
6//! (system columns `_row_id` / `_epoch` / `_deleted` plus user columns), and
7//! [`RunReader`] decodes them back, answering MVCC point lookups and scans.
8//!
9//! # HLC stamps (P0.5-T3)
10//!
11//! Sorted runs may carry an optional [`SYS_COMMIT_TS`] system column (16-byte
12//! little-endian HLC encoding). Writers emit it whenever any flushed row has a
13//! `commit_ts`; readers restore stamps when the column is present and treat a
14//! missing column as legacy (`commit_ts: None`). Epoch remains the always-on
15//! system column so pre-stamp runs stay readable without a format bump.
16//! Full PITR-at-HLC still depends on archive targets (P0.5-X10).
17
18use crate::columnar;
19use crate::encryption::{setup_run_encryption, Cipher, Kek, RunEncryption};
20use crate::epoch::Epoch;
21use crate::error::{MongrelError, Result};
22use crate::index::pgm::PgmIndex;
23use crate::memtable::{Row, Value};
24use crate::page::{Encoding, PageStat};
25use crate::row_id_set::RowIdSet;
26use crate::rowid::RowId;
27use crate::schema::{Schema, TypeId};
28use mongreldb_types::hlc::HlcTimestamp;
29use serde::{Deserialize, Serialize};
30use sha2::{Digest, Sha256};
31use std::collections::HashMap;
32use std::fs::{File, OpenOptions};
33use std::io::{Read, Seek, SeekFrom, Write};
34use std::path::{Path, PathBuf};
35use std::sync::Arc;
36
37pub const RUN_MAGIC: [u8; 8] = *b"MONGRRUN";
38pub const RUN_FORMAT_VERSION: u16 = 1;
39/// v2 appends `encrypted_stats_offset`/`encrypted_stats_len` to [`RunHeader`].
40/// The fields are trailing and the header region is zero-padded, so a run
41/// written before v2 deserializes with both fields = 0 ("no encrypted stats
42/// section"). Pre-v2 *encrypted* runs are not readable (their MAC covers the
43/// shorter v1 header serialization) — recreate them; no released data exists.
44pub const RUN_HEADER_VERSION: u16 = 2;
45pub const RUN_HEADER_PAD: usize = 256;
46const MAX_RUN_PAGE_BYTES: u64 = 64 * 1024 * 1024 + 32;
47
48/// Reserved `(column_id, page_seq)` nonce coordinates for the encrypted
49/// page-stats envelope (see [`RunHeader::encrypted_stats_offset`]). Pages per
50/// column are capped strictly below `u16::MAX` at encode, so no page nonce can
51/// ever collide with this pair under the run's DEK.
52const ENC_STATS_NONCE_COLUMN: u16 = u16::MAX;
53const ENC_STATS_NONCE_SEQ: u32 = u16::MAX as u32;
54
55/// One page's `(min, max)` bounds as stored in the encrypted stats envelope.
56type PageMinMax = (Option<Vec<u8>>, Option<Vec<u8>>);
57
58/// Per-page `(min, max)` bounds of one encrypted column, keyed by column id —
59/// the plaintext shape of the encrypted stats envelope. The cleartext column
60/// directory must not carry these (they would leak values to anyone holding
61/// the file without the key), so they travel AES-256-GCM-encrypted under the
62/// run DEK and are overlaid onto the in-memory [`PageStat`]s at open, which
63/// restores zone-map page pruning for encrypted columns.
64type EncryptedColumnStats = Vec<(u16, Vec<PageMinMax>)>;
65
66/// AES-256-GCM authentication-tag length appended to every ciphertext. Used to
67/// precompute on-disk page sizes so the direct-to-mmap writer can lay the whole
68/// run out before encrypting (Phase 14.6). Validated against the cipher's real
69/// output in [`write_run_mmap`].
70const GCM_TAG_LEN: usize = 16;
71
72/// On-disk length of a page payload: ciphertext = plaintext + GCM tag when
73/// encrypted, else the plaintext length itself.
74fn on_disk_len(page_len: usize, encrypted: bool) -> usize {
75    if encrypted {
76        page_len + GCM_TAG_LEN
77    } else {
78        page_len
79    }
80}
81
82pub const RUN_FLAG_ENCRYPTED: u8 = 1 << 0;
83pub const RUN_FLAG_TOMBSTONE_ONLY: u8 = 1 << 1;
84/// Run is "clean": exactly one version per `RowId`, no tombstones, and row_ids
85/// are strictly ascending. Bulk-loaded and compacted runs are clean by
86/// construction. For a clean run, MVCC visibility is trivially *every* position
87/// (the newest visible version of a rid is the only version, and it is not
88/// deleted), so the visibility pass can skip decoding the epoch/deleted system
89/// columns and the group-collapse loop — only the row_id column is needed (for
90/// survivor↔position mapping). Old runs lack this bit and default to not-clean
91/// (safe fallback to the full pass).
92pub const RUN_FLAG_CLEAN: u8 = 1 << 2;
93/// Run is "uniform-epoch": every row's commit epoch is the run's commit epoch,
94/// which is **not** baked into the file (it is assigned at commit/link time and
95/// recorded in the manifest `RunRef.epoch_created`). Spill runs from large
96/// transactions are written before the commit epoch is known, so their stored
97/// `_epoch` column is a placeholder; the reader must overlay the real epoch from
98/// the `RunRef`. The engine calls [`RunReader::set_uniform_epoch`] with that
99/// value after opening such a run.
100pub const RUN_FLAG_UNIFORM_EPOCH: u8 = 1 << 3;
101pub const SORT_KEY_ROW_ID: u16 = 0xFFFF;
102
103/// Reserved column ids for the MVCC system columns, stored in every run.
104pub const SYS_ROW_ID: u16 = 0xFFFE;
105pub const SYS_EPOCH: u16 = 0xFFFD;
106pub const SYS_DELETED: u16 = 0xFFFC;
107/// Optional HLC commit stamp (P0.5-T3). Absent on legacy runs → `commit_ts: None`.
108///
109/// Encoding: 16 little-endian bytes
110/// `(physical_micros:u64, logical:u32, node_tiebreaker:u32)`, or `Null` when
111/// a particular row version was not stamped.
112pub const SYS_COMMIT_TS: u16 = 0xFFFB;
113
114/// Bytes length of the on-disk HLC encoding for [`SYS_COMMIT_TS`].
115const COMMIT_TS_BYTES: usize = 16;
116
117/// Encode an optional HLC stamp for the optional [`SYS_COMMIT_TS`] column.
118fn encode_commit_ts_value(ts: Option<HlcTimestamp>) -> Value {
119    match ts {
120        None => Value::Null,
121        Some(ts) => {
122            let mut buf = [0u8; COMMIT_TS_BYTES];
123            buf[0..8].copy_from_slice(&ts.physical_micros.to_le_bytes());
124            buf[8..12].copy_from_slice(&ts.logical.to_le_bytes());
125            buf[12..16].copy_from_slice(&ts.node_tiebreaker.to_le_bytes());
126            Value::Bytes(buf.to_vec())
127        }
128    }
129}
130
131/// Decode a [`SYS_COMMIT_TS`] cell. Malformed/null/absent → `None` (legacy).
132fn decode_commit_ts_value(value: Option<&Value>) -> Option<HlcTimestamp> {
133    match value {
134        Some(Value::Bytes(bytes)) if bytes.len() == COMMIT_TS_BYTES => {
135            let physical_micros = u64::from_le_bytes(bytes[0..8].try_into().ok()?);
136            let logical = u32::from_le_bytes(bytes[8..12].try_into().ok()?);
137            let node_tiebreaker = u32::from_le_bytes(bytes[12..16].try_into().ok()?);
138            Some(HlcTimestamp {
139                physical_micros,
140                logical,
141                node_tiebreaker,
142            })
143        }
144        _ => None,
145    }
146}
147
148/// True when `column_id` is a reserved system column (including optional HLC).
149fn is_system_column_id(column_id: u16) -> bool {
150    matches!(
151        column_id,
152        SYS_ROW_ID | SYS_EPOCH | SYS_DELETED | SYS_COMMIT_TS
153    )
154}
155
156/// Guaranteed positional error of the stored PGM model (the predicted offset is
157/// within `± LEARNED_EPSILON` of the true position; a tiny final scan corrects).
158const LEARNED_EPSILON: usize = 64;
159
160/// Build the learned-index trailer as a compressed PGM-index over
161/// `(row_id, array_index)`. Near-linear row-id sequences collapse to a single
162/// segment, so the trailer is typically a few dozen bytes regardless of run size.
163fn build_learned_trailer(row_ids: &[Value]) -> Vec<u8> {
164    let points: Vec<(u64, usize)> = row_ids
165        .iter()
166        .enumerate()
167        .filter_map(|(i, v)| match v {
168            Value::Int64(r) => Some((*r as u64, i)),
169            _ => None,
170        })
171        .collect();
172    let pgm = PgmIndex::build(&points, LEARNED_EPSILON);
173    bincode::serialize(&pgm).expect("pgm serialize")
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct RunHeader {
178    pub magic: [u8; 8],
179    pub format_version: u16,
180    pub header_layout_version: u16,
181    pub run_id: u128,
182    pub content_hash: [u8; 32],
183    pub schema_id: u64,
184    pub epoch_created: u64,
185    pub level: u8,
186    pub flags: u8,
187    pub sort_key_column_id: u16,
188    pub row_count: u64,
189    pub min_row_id: u64,
190    pub max_row_id: u64,
191    pub column_count: u64,
192    pub column_dir_offset: u64,
193    pub index_trailer_offset: u64,
194    pub encryption_descriptor_offset: u64,
195    pub footer_offset: u64,
196    /// Offset/length of the AES-256-GCM-encrypted per-page min/max envelope
197    /// for encrypted columns (0/0 = absent; always 0 for plaintext runs and
198    /// pre-v2 files, whose zero header padding deserializes to 0 here).
199    pub encrypted_stats_offset: u64,
200    pub encrypted_stats_len: u64,
201}
202
203impl RunHeader {
204    pub fn is_encrypted(&self) -> bool {
205        self.flags & RUN_FLAG_ENCRYPTED != 0
206    }
207    pub fn is_clean(&self) -> bool {
208        self.flags & RUN_FLAG_CLEAN != 0
209    }
210    pub fn is_uniform_epoch(&self) -> bool {
211        self.flags & RUN_FLAG_UNIFORM_EPOCH != 0
212    }
213}
214
215#[derive(Debug, Clone, Serialize, Deserialize)]
216pub struct ColumnPageHeader {
217    pub column_id: u16,
218    pub type_id_tag: u16,
219    pub encoding: u8,
220    pub flags: u8,
221    pub page_count: u32,
222    pub page_region_offset: u64,
223    pub page_region_len: u64,
224    pub page_stats: Vec<PageStat>,
225}
226
227impl ColumnPageHeader {
228    const PAGE_ENCRYPTED: u8 = 1 << 0;
229}
230
231/// Length of the run-metadata HMAC tag appended after the footer of an encrypted
232/// run (HMAC-SHA256, see [`crate::encryption::run_metadata_mac`]).
233const RUN_MAC_LEN: usize = 32;
234
235/// Compute the run-metadata MAC tag for an encrypted run, or `None` for a
236/// plaintext run (or when the `encryption` feature is off, where `enc` is always
237/// `None`). MACs `header ‖ dir ‖ descriptor` under the run's KEK-derived key.
238fn compute_run_mac(
239    enc: Option<&RunEncryption>,
240    header_bytes: &[u8],
241    dir_bytes: &[u8],
242) -> Option<[u8; RUN_MAC_LEN]> {
243    {
244        if let Some(e) = enc {
245            if let Some(mac_key) = &e.mac_key {
246                return Some(crate::encryption::run_metadata_mac(
247                    mac_key,
248                    header_bytes,
249                    dir_bytes,
250                    &e.descriptor_bytes,
251                ));
252            }
253        }
254    }
255    None
256}
257
258/// A column's pages handed to the low-level writer.
259pub struct ColumnPayload {
260    pub column_id: u16,
261    pub type_id_tag: u16,
262    pub encoding: Encoding,
263    pub pages: Vec<Vec<u8>>,
264    /// Optional value-derived stats per page (parallel to [`Self::pages`]). When
265    /// present, [`write_run_with`] fills only the offset/length slots; when a
266    /// slot is missing it falls back to an empty stat.
267    pub page_stats: Vec<PageStat>,
268}
269
270/// Specification handed to [`write_run`] / [`write_run_with`].
271pub struct RunSpec<'a> {
272    pub run_id: u128,
273    pub schema_id: u64,
274    pub epoch_created: u64,
275    pub level: u8,
276    pub flags: u8,
277    pub sort_key_column_id: u16,
278    pub row_count: u64,
279    pub min_row_id: u64,
280    pub max_row_id: u64,
281    pub columns: &'a [ColumnPayload],
282}
283
284/// Write a run with no encryption and no index trailer (back-compat entry point).
285pub fn write_run(path: impl AsRef<Path>, spec: &RunSpec) -> Result<RunHeader> {
286    write_run_with(path, spec, None, &[], None)
287}
288
289/// Write a run, optionally encrypting page payloads with a per-file DEK
290/// (wrapped by the table `kek`, see §7) and appending an `index_trailer` blob
291/// (used by [`RunWriter`] for the learned index).
292///
293/// Tries the direct-to-mmap writer (Phase 14.6 — pages are encrypted + placed
294/// straight into a memory mapping of the output file, in parallel, with no
295/// intermediate whole-file `Vec<u8>`), and falls back to the in-buffer writer
296/// only when the mapping itself can't be created (some filesystems/environments
297/// reject `mmap`). The two writers produce a byte-identical run.
298pub fn write_run_with(
299    path: impl AsRef<Path>,
300    spec: &RunSpec,
301    kek: Option<&Kek>,
302    indexable_columns: &[(u16, u8)],
303    index_trailer: Option<&[u8]>,
304) -> Result<RunHeader> {
305    // Assemble per-run encryption material (fresh DEK + nonce prefix + wrapped
306    // descriptor) when a KEK is supplied. The page cipher lives only for this
307    // write; the wrapped DEK is embedded in the run below.
308    let enc: Option<RunEncryption> = match kek {
309        Some(k) => Some(setup_run_encryption(k, indexable_columns)?),
310        None => None,
311    };
312    match write_run_mmap(path.as_ref(), spec, enc.as_ref(), index_trailer) {
313        Ok(h) => Ok(h),
314        Err(e) if is_mmap_unavailable(&e) => write_run_vec(path, spec, enc, index_trailer),
315        Err(e) => Err(e),
316    }
317}
318
319fn write_run_with_file(
320    mut file: File,
321    spec: &RunSpec,
322    kek: Option<&Kek>,
323    indexable_columns: &[(u16, u8)],
324    index_trailer: Option<&[u8]>,
325) -> Result<RunHeader> {
326    let enc = match kek {
327        Some(key) => Some(setup_run_encryption(key, indexable_columns)?),
328        None => None,
329    };
330    match write_run_mmap_file(&file, spec, enc.as_ref(), index_trailer) {
331        Ok(header) => Ok(header),
332        Err(error) if is_mmap_unavailable(&error) => {
333            file.set_len(0)?;
334            file.seek(SeekFrom::Start(0))?;
335            let (bytes, header) = encode_run_vec(spec, enc, index_trailer)?;
336            file.write_all(&bytes)?;
337            file.sync_all()?;
338            Ok(header)
339        }
340        Err(error) => Err(error),
341    }
342}
343
344/// `true` when `write_run_mmap` could not create the mapping (the only case
345/// where we fall back to the in-buffer writer). Any other error — encryption,
346/// serialization, a genuine write failure — must surface.
347fn is_mmap_unavailable(e: &MongrelError) -> bool {
348    matches!(e, MongrelError::InvalidArgument(m) if m.starts_with("__mmap_unavailable__:"))
349}
350
351/// Direct-to-mmap run writer (Phases 14.5 + 14.6).
352///
353/// Lays the whole run out up front (computing each page's on-disk offset/length
354/// without encrypting), sizes the file, memory-maps it, then encrypts + copies
355/// every page **straight into the mapping** on the rayon pool. Because pages
356/// land in the kernel page cache (the mapping) instead of a heap `Vec<u8>`,
357/// the kernel can begin writeback of earlier pages while later ones are still
358/// being encrypted — CPU encryption overlaps with disk I/O (the double-buffer
359/// intent of 14.5). There is no whole-run buffer; peak extra memory is a few
360/// transient ciphertext `Vec`s (one per worker thread), not the full run.
361/// Direct-to-mmap run writer (Phases 14.5 + 14.6).
362///
363/// Lays the whole run out ([`plan_run`]), sizes the file, memory-maps it, then
364/// delegates to [`place_run`] which encrypts + copies every page **straight into
365/// the mapping** on the rayon pool. Because pages land in the kernel page cache
366/// (the mapping) instead of a heap `Vec<u8>`, the kernel can begin writeback of
367/// earlier pages while later ones are still being encrypted — CPU encryption
368/// overlaps with disk I/O (the double-buffer intent of 14.5). There is no
369/// whole-run buffer; peak extra memory is a few transient ciphertext `Vec`s
370/// (one per worker thread), not the full run.
371fn write_run_mmap(
372    path: &Path,
373    spec: &RunSpec,
374    enc: Option<&RunEncryption>,
375    index_trailer: Option<&[u8]>,
376) -> Result<RunHeader> {
377    let file = OpenOptions::new().create_new(true).write(true).open(path)?;
378    let result = write_run_mmap_file(&file, spec, enc, index_trailer);
379    if result.as_ref().is_err_and(is_mmap_unavailable) {
380        drop(file);
381        let _ = std::fs::remove_file(path);
382    }
383    result
384}
385
386fn write_run_mmap_file(
387    file: &File,
388    spec: &RunSpec,
389    enc: Option<&RunEncryption>,
390    index_trailer: Option<&[u8]>,
391) -> Result<RunHeader> {
392    let plan = plan_run(spec, enc, index_trailer)?;
393    file.set_len(plan.total as u64)?;
394    let mut mmap = match unsafe { memmap2::MmapMut::map_mut(file) } {
395        Ok(m) => m,
396        Err(e) => {
397            return Err(MongrelError::InvalidArgument(format!(
398                "__mmap_unavailable__: {e}"
399            )));
400        }
401    };
402    let header = place_run(spec, enc, index_trailer, &plan, &mut mmap[..])?;
403    mmap.flush()?;
404    file.sync_all()?;
405    Ok(header)
406}
407
408/// A precomputed run layout: the page-placement jobs, the serialized column
409/// directory (stats already filled), and every on-disk offset/length. The
410/// layout is independent of the backing buffer, so [`place_run`] can target a
411/// mmap'd file or a plain `Vec` interchangeably — which is what lets the
412/// placement path be unit-tested even where file mmap is unavailable.
413struct RunPlan {
414    jobs: Vec<(usize, usize, u64, usize)>, // (col_idx, page_seq, offset, on_disk_len)
415    dir_bytes: Vec<u8>,
416    encrypted: bool,
417    column_dir_offset: u64,
418    index_trailer_offset: u64,
419    encryption_descriptor_offset: u64,
420    footer_offset: u64,
421    total: usize,
422    /// Serialized (plaintext) [`EncryptedColumnStats`]; encrypted into the
423    /// stats section by the writer. `None` when the run is plaintext or no
424    /// encrypted column carries min/max.
425    encrypted_stats_plain: Option<Vec<u8>>,
426    encrypted_stats_offset: u64,
427    encrypted_stats_len: u64,
428}
429
430/// Compute the run layout: per-page offset + on-disk length, the filled column
431/// directory (serialized), and the dir / trailer / descriptor / footer offsets.
432/// Validates the encrypted-page-seq nonce-exhaustion bound.
433fn plan_run(
434    spec: &RunSpec,
435    enc: Option<&RunEncryption>,
436    index_trailer: Option<&[u8]>,
437) -> Result<RunPlan> {
438    let encrypted = enc.is_some();
439    let columns = spec.columns;
440    let mut jobs: Vec<(usize, usize, u64, usize)> = Vec::new();
441    let mut dir: Vec<ColumnPageHeader> = Vec::with_capacity(columns.len());
442    let mut enc_stats: EncryptedColumnStats = Vec::new();
443    let mut cursor: u64 = RUN_HEADER_PAD as u64;
444    for (ci, col) in columns.iter().enumerate() {
445        let region_offset = cursor;
446        let mut region_len = 0u64;
447        let mut stats = Vec::with_capacity(col.pages.len());
448        let mut col_minmax: Vec<PageMinMax> = Vec::new();
449        for (ps, page) in col.pages.iter().enumerate() {
450            // The per-page GCM nonce encodes page_seq in 2 bytes; refuse to
451            // silently truncate at 65 535 pages/column (4.29e9 rows), which
452            // would otherwise reuse a nonce under the run's DEK. Sequence
453            // 0xFFFF itself is reserved for the encrypted-stats envelope.
454            if encrypted && ps >= u16::MAX as usize {
455                return Err(MongrelError::Full(format!(
456                    "column {:#x} exceeds 65534 pages; encrypted-run page-seq nonce space exhausted",
457                    col.column_id
458                )));
459            }
460            let odl = on_disk_len(page.len(), encrypted);
461            jobs.push((ci, ps, cursor, odl));
462            let mut stat = col.page_stats.get(ps).cloned().unwrap_or(PageStat {
463                first_row_id: 0,
464                last_row_id: 0,
465                null_count: 0,
466                row_count: 0,
467                min: None,
468                max: None,
469                offset: 0,
470                compressed_len: 0,
471                uncompressed_len: 0,
472            });
473            stat.offset = cursor;
474            stat.compressed_len = odl as u32;
475            stat.uncompressed_len = page.len() as u32;
476            // The column directory is serialized in cleartext, so per-page
477            // min/max would leak raw plaintext values (literal bytes for `Bytes`
478            // columns) of every encrypted page to anyone reading the file
479            // without the key. Move them out of the directory and into the
480            // DEK-encrypted stats envelope, which the reader overlays back at
481            // open — zone-map page pruning works identically to plaintext runs.
482            if encrypted {
483                col_minmax.push((stat.min.take(), stat.max.take()));
484            }
485            stats.push(stat);
486            cursor += odl as u64;
487            region_len += odl as u64;
488        }
489        if col_minmax
490            .iter()
491            .any(|(mn, mx)| mn.is_some() || mx.is_some())
492        {
493            enc_stats.push((col.column_id, col_minmax));
494        }
495        let page_flags = if encrypted {
496            ColumnPageHeader::PAGE_ENCRYPTED
497        } else {
498            0
499        };
500        dir.push(ColumnPageHeader {
501            column_id: col.column_id,
502            type_id_tag: col.type_id_tag,
503            encoding: col.encoding as u8,
504            flags: page_flags,
505            page_count: col.pages.len() as u32,
506            page_region_offset: region_offset,
507            page_region_len: region_len,
508            page_stats: stats,
509        });
510    }
511    let dir_bytes = bincode::serialize(&dir)?;
512    let column_dir_offset = cursor;
513    cursor += dir_bytes.len() as u64;
514    let index_trailer_offset = match index_trailer {
515        Some(t) => {
516            let off = cursor;
517            cursor += t.len() as u64;
518            off
519        }
520        None => 0,
521    };
522    let encryption_descriptor_offset = match enc {
523        Some(e) => {
524            let off = cursor;
525            cursor += 4 + e.descriptor_bytes.len() as u64;
526            off
527        }
528        None => 0,
529    };
530    let (encrypted_stats_plain, encrypted_stats_offset, encrypted_stats_len) =
531        if encrypted && !enc_stats.is_empty() {
532            let plain = bincode::serialize(&enc_stats)?;
533            let ct_len = on_disk_len(plain.len(), true) as u64;
534            let off = cursor;
535            cursor += ct_len;
536            (Some(plain), off, ct_len)
537        } else {
538            (None, 0, 0)
539        };
540    let footer_offset = cursor;
541    // footer = MAGIC(8) + footer_offset(8) + checksum(32); encrypted runs append
542    // a 32-byte HMAC tag (RUN_MAC_LEN) authenticating header+dir+descriptor.
543    let total = footer_offset as usize + 8 + 8 + 32 + if encrypted { RUN_MAC_LEN } else { 0 };
544    Ok(RunPlan {
545        jobs,
546        dir_bytes,
547        encrypted,
548        column_dir_offset,
549        index_trailer_offset,
550        encryption_descriptor_offset,
551        footer_offset,
552        total,
553        encrypted_stats_plain,
554        encrypted_stats_offset,
555        encrypted_stats_len,
556    })
557}
558
559/// Place a run into `buf` (which must be exactly [`RunPlan::total`] bytes):
560/// encrypt + copy every page into its precomputed slot on the rayon pool, then
561/// write the column directory, index trailer, encryption descriptor, header,
562/// and checksummed footer. Backed by a mmap'd file in production and by a
563/// `Vec<u8>` in tests — the placement logic is identical either way, which is
564/// what makes the Phase 14.6 path unit-testable.
565fn place_run(
566    spec: &RunSpec,
567    enc: Option<&RunEncryption>,
568    index_trailer: Option<&[u8]>,
569    plan: &RunPlan,
570    buf: &mut [u8],
571) -> Result<RunHeader> {
572    use rayon::prelude::*;
573    use std::borrow::Cow;
574    debug_assert_eq!(
575        buf.len(),
576        plan.total,
577        "place_run: buffer must be exactly plan.total bytes"
578    );
579
580    let cipher: Option<&dyn Cipher> = enc.map(|e| e.cipher.as_ref());
581    let nonce_prefix = enc.map(|e| e.nonce_prefix);
582    let columns = spec.columns;
583
584    // ---- parallel placement: encrypt + copy each page into its slot ----
585    // Disjointness is by construction: every job targets [offset, offset+len)
586    // and `plan_run` made those ranges non-overlapping. The `SyncPtr` newtype
587    // lets the base pointer cross thread boundaries for that purpose.
588    struct SyncPtr(*mut u8);
589    unsafe impl Send for SyncPtr {}
590    unsafe impl Sync for SyncPtr {}
591    impl SyncPtr {
592        fn get(&self) -> *mut u8 {
593            self.0
594        }
595    }
596    let base = SyncPtr(buf.as_mut_ptr());
597    plan.jobs
598        .par_iter()
599        .map(
600            |&(ci, ps, offset, odl): &(usize, usize, u64, usize)| -> Result<()> {
601                let page = &columns[ci].pages[ps];
602                let dst =
603                    unsafe { std::slice::from_raw_parts_mut(base.get().add(offset as usize), odl) };
604                let bytes: Cow<[u8]> = match cipher {
605                    Some(c) => {
606                        let nonce =
607                            page_nonce(nonce_prefix.unwrap(), columns[ci].column_id, ps as u32);
608                        let ct = c.encrypt_page(&nonce, page)?;
609                        // Guards the GCM_TAG_LEN assumption: a future cipher with a
610                        // different tag size must change `on_disk_len` too.
611                        assert_eq!(
612                        ct.len(), odl,
613                        "ciphertext length {} != predicted {}; GCM tag size assumption is stale",
614                        ct.len(), odl
615                    );
616                        Cow::Owned(ct)
617                    }
618                    None => {
619                        debug_assert_eq!(page.len(), odl);
620                        Cow::Borrowed(page.as_slice())
621                    }
622                };
623                dst.copy_from_slice(&bytes);
624                Ok(())
625            },
626        )
627        .collect::<Result<()>>()?;
628
629    // ---- content hash over the on-disk page region (column-major, page order) ----
630    let content_hash = {
631        let mut h = Sha256::new();
632        h.update(&buf[RUN_HEADER_PAD..plan.column_dir_offset as usize]);
633        h.finalize()
634    };
635
636    // ---- dir / trailer / descriptor ----
637    let doff = plan.column_dir_offset as usize;
638    buf[doff..doff + plan.dir_bytes.len()].copy_from_slice(&plan.dir_bytes);
639    if let Some(t) = index_trailer {
640        let off = plan.index_trailer_offset as usize;
641        buf[off..off + t.len()].copy_from_slice(t);
642    }
643    if let Some(e) = enc {
644        let off = plan.encryption_descriptor_offset as usize;
645        buf[off..off + 4].copy_from_slice(&(e.descriptor_bytes.len() as u32).to_le_bytes());
646        buf[off + 4..off + 4 + e.descriptor_bytes.len()].copy_from_slice(&e.descriptor_bytes);
647    }
648    if let (Some(e), Some(plain)) = (enc, plan.encrypted_stats_plain.as_ref()) {
649        let nonce = page_nonce(e.nonce_prefix, ENC_STATS_NONCE_COLUMN, ENC_STATS_NONCE_SEQ);
650        let ct = e.cipher.encrypt_page(&nonce, plain)?;
651        debug_assert_eq!(ct.len() as u64, plan.encrypted_stats_len);
652        let off = plan.encrypted_stats_offset as usize;
653        buf[off..off + ct.len()].copy_from_slice(&ct);
654    }
655
656    // ---- header + footer ----
657    let header_flags = if plan.encrypted {
658        spec.flags | RUN_FLAG_ENCRYPTED
659    } else {
660        spec.flags
661    };
662    let header = RunHeader {
663        magic: RUN_MAGIC,
664        format_version: RUN_FORMAT_VERSION,
665        header_layout_version: RUN_HEADER_VERSION,
666        run_id: spec.run_id,
667        content_hash: content_hash.into(),
668        schema_id: spec.schema_id,
669        epoch_created: spec.epoch_created,
670        level: spec.level,
671        flags: header_flags,
672        sort_key_column_id: spec.sort_key_column_id,
673        row_count: spec.row_count,
674        min_row_id: spec.min_row_id,
675        max_row_id: spec.max_row_id,
676        column_count: columns.len() as u64,
677        column_dir_offset: plan.column_dir_offset,
678        index_trailer_offset: plan.index_trailer_offset,
679        encryption_descriptor_offset: plan.encryption_descriptor_offset,
680        footer_offset: plan.footer_offset,
681        encrypted_stats_offset: plan.encrypted_stats_offset,
682        encrypted_stats_len: plan.encrypted_stats_len,
683    };
684    let header_bytes = bincode::serialize(&header)?;
685    if header_bytes.len() > RUN_HEADER_PAD {
686        return Err(MongrelError::InvalidArgument(format!(
687            "run header too large: {} > {RUN_HEADER_PAD}",
688            header_bytes.len()
689        )));
690    }
691    buf[..header_bytes.len()].copy_from_slice(&header_bytes);
692
693    let checksum = Sha256::digest(&buf[..plan.footer_offset as usize]);
694    let foot = plan.footer_offset as usize;
695    buf[foot..foot + 8].copy_from_slice(&RUN_MAGIC);
696    buf[foot + 8..foot + 16].copy_from_slice(&plan.footer_offset.to_le_bytes());
697    buf[foot + 16..foot + 48].copy_from_slice(&checksum);
698    // Encrypted runs: append the keyed metadata MAC over header‖dir‖descriptor.
699    if let Some(tag) = compute_run_mac(enc, &header_bytes, &plan.dir_bytes) {
700        buf[foot + 48..foot + 48 + RUN_MAC_LEN].copy_from_slice(&tag);
701    }
702    Ok(header)
703}
704
705/// Fallback in-buffer writer (used when the output file can't be mmap'd).
706/// Produces a byte-identical run to [`write_run_mmap`].
707fn write_run_vec(
708    path: impl AsRef<Path>,
709    spec: &RunSpec,
710    enc: Option<RunEncryption>,
711    index_trailer: Option<&[u8]>,
712) -> Result<RunHeader> {
713    let (buf, header) = encode_run_vec(spec, enc, index_trailer)?;
714    let mut file = OpenOptions::new().create_new(true).write(true).open(path)?;
715    file.write_all(&buf)?;
716    file.sync_all()?;
717    Ok(header)
718}
719
720fn encode_run_vec(
721    spec: &RunSpec,
722    enc: Option<RunEncryption>,
723    index_trailer: Option<&[u8]>,
724) -> Result<(Vec<u8>, RunHeader)> {
725    let mut buf: Vec<u8> = vec![0; RUN_HEADER_PAD]; // reserve header region
726    let mut content_hasher = Sha256::new();
727    let mut dir: Vec<ColumnPageHeader> = Vec::with_capacity(spec.columns.len());
728    let mut enc_stats: EncryptedColumnStats = Vec::new();
729
730    for col in spec.columns {
731        let region_offset = buf.len() as u64;
732        let mut region_len = 0u64;
733        let mut stats = Vec::with_capacity(col.pages.len());
734        let mut col_minmax: Vec<PageMinMax> = Vec::new();
735        for (page_seq, page) in col.pages.iter().enumerate() {
736            if enc.is_some() && page_seq >= u16::MAX as usize {
737                return Err(MongrelError::Full(format!(
738                    "column {:#x} exceeds 65534 pages; encrypted-run page-seq nonce space exhausted",
739                    col.column_id
740                )));
741            }
742            let on_disk: Vec<u8> = match &enc {
743                Some(e) => e.cipher.encrypt_page(
744                    &page_nonce(e.nonce_prefix, col.column_id, page_seq as u32),
745                    page,
746                )?,
747                None => page.clone(),
748            };
749            let offset = buf.len() as u64;
750            buf.write_all(&on_disk)?;
751            content_hasher.update(&on_disk);
752            region_len += on_disk.len() as u64;
753            let mut stat = if let Some(s) = col.page_stats.get(page_seq) {
754                s.clone()
755            } else {
756                PageStat {
757                    first_row_id: 0,
758                    last_row_id: 0,
759                    null_count: 0,
760                    row_count: 0,
761                    min: None,
762                    max: None,
763                    offset: 0,
764                    compressed_len: 0,
765                    uncompressed_len: 0,
766                }
767            };
768            stat.offset = offset;
769            stat.compressed_len = on_disk.len() as u32;
770            stat.uncompressed_len = page.len() as u32;
771            // See plan_run: the cleartext directory must not carry plaintext
772            // min/max for encrypted columns — they move into the encrypted
773            // stats envelope. Keep this byte-identical to plan_run so both
774            // writers emit the same run.
775            if enc.is_some() {
776                col_minmax.push((stat.min.take(), stat.max.take()));
777            }
778            stats.push(stat);
779        }
780        if col_minmax
781            .iter()
782            .any(|(mn, mx)| mn.is_some() || mx.is_some())
783        {
784            enc_stats.push((col.column_id, col_minmax));
785        }
786        let page_flags = if enc.is_some() {
787            ColumnPageHeader::PAGE_ENCRYPTED
788        } else {
789            0
790        };
791        dir.push(ColumnPageHeader {
792            column_id: col.column_id,
793            type_id_tag: col.type_id_tag,
794            encoding: col.encoding as u8,
795            flags: page_flags,
796            page_count: col.pages.len() as u32,
797            page_region_offset: region_offset,
798            page_region_len: region_len,
799            page_stats: stats,
800        });
801    }
802
803    let column_dir_offset = buf.len() as u64;
804    let dir_bytes = bincode::serialize(&dir)?;
805    buf.write_all(&dir_bytes)?;
806
807    let index_trailer_offset = match index_trailer {
808        Some(trailer) => {
809            let off = buf.len() as u64;
810            buf.write_all(trailer)?;
811            off
812        }
813        None => 0,
814    };
815    let encryption_descriptor_offset = match &enc {
816        Some(e) => {
817            let off = buf.len() as u64;
818            buf.write_all(&(e.descriptor_bytes.len() as u32).to_le_bytes())?;
819            buf.write_all(&e.descriptor_bytes)?;
820            off
821        }
822        None => 0,
823    };
824    let (encrypted_stats_offset, encrypted_stats_len) = match &enc {
825        Some(e) if !enc_stats.is_empty() => {
826            let plain = bincode::serialize(&enc_stats)?;
827            let nonce = page_nonce(e.nonce_prefix, ENC_STATS_NONCE_COLUMN, ENC_STATS_NONCE_SEQ);
828            let ct = e.cipher.encrypt_page(&nonce, &plain)?;
829            let off = buf.len() as u64;
830            let len = ct.len() as u64;
831            buf.write_all(&ct)?;
832            (off, len)
833        }
834        _ => (0, 0),
835    };
836    let footer_offset = buf.len() as u64;
837
838    let header_flags = if enc.is_some() {
839        spec.flags | RUN_FLAG_ENCRYPTED
840    } else {
841        spec.flags
842    };
843    let header = RunHeader {
844        magic: RUN_MAGIC,
845        format_version: RUN_FORMAT_VERSION,
846        header_layout_version: RUN_HEADER_VERSION,
847        run_id: spec.run_id,
848        content_hash: content_hasher.finalize().into(),
849        schema_id: spec.schema_id,
850        epoch_created: spec.epoch_created,
851        level: spec.level,
852        flags: header_flags,
853        sort_key_column_id: spec.sort_key_column_id,
854        row_count: spec.row_count,
855        min_row_id: spec.min_row_id,
856        max_row_id: spec.max_row_id,
857        column_count: spec.columns.len() as u64,
858        column_dir_offset,
859        index_trailer_offset,
860        encryption_descriptor_offset,
861        footer_offset,
862        encrypted_stats_offset,
863        encrypted_stats_len,
864    };
865    let header_bytes = bincode::serialize(&header)?;
866    if header_bytes.len() > RUN_HEADER_PAD {
867        return Err(MongrelError::InvalidArgument(format!(
868            "run header too large: {} > {RUN_HEADER_PAD}",
869            header_bytes.len()
870        )));
871    }
872    buf[..header_bytes.len()].copy_from_slice(&header_bytes);
873
874    let checksum = Sha256::digest(&buf[..footer_offset as usize]);
875    buf.write_all(&RUN_MAGIC)?;
876    buf.write_all(&footer_offset.to_le_bytes())?;
877    buf.write_all(&checksum)?;
878    // Encrypted runs: append the keyed metadata MAC (byte-identical to the mmap
879    // writer). `dir_bytes`/`header_bytes` here are the exact serialized forms.
880    if let Some(tag) = compute_run_mac(enc.as_ref(), &header_bytes, &dir_bytes) {
881        buf.write_all(&tag)?;
882    }
883
884    Ok((buf, header))
885}
886
887fn page_nonce(nonce_prefix: [u8; 12], column_id: u16, page_seq: u32) -> [u8; 12] {
888    let mut n = nonce_prefix;
889    n[8..10].copy_from_slice(&column_id.to_le_bytes());
890    n[10..12].copy_from_slice(&(page_seq as u16).to_le_bytes());
891    n
892}
893
894/// Decrypt the run's per-page min/max envelope ([`EncryptedColumnStats`]) and
895/// overlay the bounds onto the in-memory column directory, restoring zone-map
896/// page pruning for encrypted columns. Caller must have verified the run
897/// metadata MAC first (the envelope's offset/len live in the header); the
898/// envelope itself is AES-256-GCM-authenticated, so tampering fails loudly —
899/// the same posture as a tampered page payload.
900fn overlay_encrypted_stats(
901    file: &mut File,
902    header: &RunHeader,
903    cipher: &dyn Cipher,
904    nonce_prefix: [u8; 12],
905    dir: &mut [ColumnPageHeader],
906) -> Result<()> {
907    file.seek(SeekFrom::Start(header.encrypted_stats_offset))?;
908    const MAX_ENCRYPTED_STATS_BYTES: u64 = 64 * 1024 * 1024;
909    if header.encrypted_stats_len > MAX_ENCRYPTED_STATS_BYTES {
910        return Err(MongrelError::InvalidArgument(format!(
911            "encrypted run stats length {} exceeds {MAX_ENCRYPTED_STATS_BYTES}",
912            header.encrypted_stats_len
913        )));
914    }
915    let mut ct = vec![0u8; header.encrypted_stats_len as usize];
916    file.read_exact(&mut ct)?;
917    let nonce = page_nonce(nonce_prefix, ENC_STATS_NONCE_COLUMN, ENC_STATS_NONCE_SEQ);
918    let plain = cipher.decrypt_page(&nonce, &ct)?;
919    let stats: EncryptedColumnStats = bincode::deserialize(&plain)
920        .map_err(|e| MongrelError::Encryption(format!("bad encrypted page-stats envelope: {e}")))?;
921    for (cid, minmax) in stats {
922        let Some(col) = dir.iter_mut().find(|c| c.column_id == cid) else {
923            continue;
924        };
925        for (stat, (mn, mx)) in col.page_stats.iter_mut().zip(minmax) {
926            stat.min = mn;
927            stat.max = mx;
928        }
929    }
930    Ok(())
931}
932
933/// Stable content-address of an immutable run page (the cache key): SHA-256 of
934/// `(table_id, run_id, column_id, page_seq)`. Runs are immutable, so this
935/// identity is also the page's content address — a rewritten page lives in a
936/// different run (different id) and so gets a different key without any
937/// invalidation sweep. `table_id` namespaces the shared cache across tables in
938/// a `Database` so two tables' identically-numbered runs never collide.
939pub(crate) fn page_cache_key(
940    table_id: u64,
941    run_id: u128,
942    column_id: u16,
943    page_seq: usize,
944) -> [u8; 32] {
945    let mut h = Sha256::new();
946    h.update(table_id.to_be_bytes());
947    h.update(run_id.to_be_bytes());
948    h.update(column_id.to_be_bytes());
949    h.update((page_seq as u64).to_be_bytes());
950    let out = h.finalize();
951    let mut k = [0u8; 32];
952    k.copy_from_slice(&out);
953    k
954}
955
956/// Decrypt a raw (on-disk) page when the column is encrypted, else pass it
957/// through. The shared page cache stores the raw bytes (ciphertext when
958/// encrypted), so this runs after every cache hit or disk read.
959fn decrypt_or_passthrough(
960    cipher: Option<&dyn Cipher>,
961    nonce_prefix: [u8; 12],
962    column_id: u16,
963    page_seq: usize,
964    encrypted: bool,
965    buf: &[u8],
966) -> Result<Vec<u8>> {
967    if encrypted {
968        match cipher {
969            Some(c) => {
970                Ok(c.decrypt_page(&page_nonce(nonce_prefix, column_id, page_seq as u32), buf)?)
971            }
972            None => Err(MongrelError::Decryption(
973                "encrypted page but no cipher".into(),
974            )),
975        }
976    } else {
977        Ok(buf.to_vec())
978    }
979}
980
981/// Read just the header and confirm the footer magic, without hashing the
982/// body. Cheap: two small fixed-size reads, no allocation proportional to
983/// run size. Only safe as a substitute for [`read_header`] when the caller
984/// has independent evidence this exact `run_id`'s checksum already verified
985/// in this process (see `open_with_cache`'s `verified_runs` cache) — `.sr`
986/// runs are immutable once written, so a checksum verified once cannot
987/// regress later in the same process lifetime. Still catches gross
988/// corruption (truncation, garbled header) via the magic checks and the
989/// bincode deserialize.
990fn read_header_fast_from_file(file: &mut File) -> Result<RunHeader> {
991    file.seek(SeekFrom::Start(0))?;
992    let mut header_buf = [0u8; RUN_HEADER_PAD];
993    file.read_exact(&mut header_buf)?;
994    let header: RunHeader = bincode::deserialize(&header_buf)
995        .map_err(|e| MongrelError::InvalidArgument(format!("bad run header: {e}")))?;
996    validate_run_header_bytes(&header, &header_buf)?;
997    validate_run_layout(&header, file.metadata()?.len())?;
998    file.seek(SeekFrom::Start(header.footer_offset))?;
999    let mut footer_magic = [0u8; 8];
1000    file.read_exact(&mut footer_magic)?;
1001    if footer_magic != RUN_MAGIC {
1002        return Err(MongrelError::MagicMismatch {
1003            what: "sorted run footer",
1004            expected: RUN_MAGIC,
1005            got: footer_magic,
1006        });
1007    }
1008    Ok(header)
1009}
1010
1011/// Read and validate a run header (magic + footer checksum).
1012pub fn read_header(path: impl AsRef<Path>) -> Result<RunHeader> {
1013    let mut file = crate::durable_file::open_regular_nofollow(path.as_ref())?;
1014    read_header_from_file(&mut file)
1015}
1016
1017fn validate_run_layout(header: &RunHeader, file_len: u64) -> Result<()> {
1018    let footer_len = 8u64
1019        + 8
1020        + 32
1021        + if header.is_encrypted() {
1022            RUN_MAC_LEN as u64
1023        } else {
1024            0
1025        };
1026    let expected_len = header
1027        .footer_offset
1028        .checked_add(footer_len)
1029        .ok_or_else(|| MongrelError::InvalidArgument("sorted run length overflow".into()))?;
1030    if header.footer_offset < RUN_HEADER_PAD as u64 || expected_len != file_len {
1031        return Err(MongrelError::InvalidArgument(format!(
1032            "invalid sorted run layout: footer={} file={file_len}",
1033            header.footer_offset
1034        )));
1035    }
1036    let in_body = |offset: u64| {
1037        offset == 0 || (offset >= RUN_HEADER_PAD as u64 && offset <= header.footer_offset)
1038    };
1039    if header.column_dir_offset < RUN_HEADER_PAD as u64
1040        || header.column_dir_offset > header.footer_offset
1041        || !in_body(header.index_trailer_offset)
1042        || !in_body(header.encryption_descriptor_offset)
1043        || !in_body(header.encrypted_stats_offset)
1044        || header
1045            .encrypted_stats_offset
1046            .checked_add(header.encrypted_stats_len)
1047            .is_none_or(|end| end > header.footer_offset)
1048    {
1049        return Err(MongrelError::InvalidArgument(
1050            "sorted run metadata offsets are outside the file".into(),
1051        ));
1052    }
1053    Ok(())
1054}
1055
1056fn validate_run_header_bytes(header: &RunHeader, bytes: &[u8; RUN_HEADER_PAD]) -> Result<()> {
1057    if header.magic != RUN_MAGIC {
1058        return Err(MongrelError::MagicMismatch {
1059            what: "sorted run",
1060            expected: RUN_MAGIC,
1061            got: header.magic,
1062        });
1063    }
1064    const KNOWN_FLAGS: u8 =
1065        RUN_FLAG_ENCRYPTED | RUN_FLAG_TOMBSTONE_ONLY | RUN_FLAG_CLEAN | RUN_FLAG_UNIFORM_EPOCH;
1066    if header.format_version != RUN_FORMAT_VERSION
1067        || header.header_layout_version != RUN_HEADER_VERSION
1068        || header.flags & !KNOWN_FLAGS != 0
1069        || (header.row_count == 0 && (header.min_row_id != 0 || header.max_row_id != 0))
1070        || (header.row_count != 0 && header.min_row_id > header.max_row_id)
1071    {
1072        return Err(MongrelError::InvalidArgument(
1073            "unsupported or invalid sorted run header".into(),
1074        ));
1075    }
1076    let canonical = bincode::serialize(header)?;
1077    if canonical.len() > RUN_HEADER_PAD
1078        || bytes[..canonical.len()] != canonical
1079        || bytes[canonical.len()..].iter().any(|byte| *byte != 0)
1080    {
1081        return Err(MongrelError::InvalidArgument(
1082            "sorted run header has noncanonical bytes or nonzero padding".into(),
1083        ));
1084    }
1085    Ok(())
1086}
1087
1088fn read_header_from_file(file: &mut File) -> Result<RunHeader> {
1089    file.seek(SeekFrom::Start(0))?;
1090    let mut header_buf = [0u8; RUN_HEADER_PAD];
1091    file.read_exact(&mut header_buf)?;
1092    let header: RunHeader = bincode::deserialize(&header_buf)
1093        .map_err(|e| MongrelError::InvalidArgument(format!("bad run header: {e}")))?;
1094    validate_run_header_bytes(&header, &header_buf)?;
1095
1096    validate_run_layout(&header, file.metadata()?.len())?;
1097    file.seek(SeekFrom::Start(header.footer_offset))?;
1098    let mut footer = [0u8; 8 + 8 + 32];
1099    file.read_exact(&mut footer)?;
1100    if footer[..8] != RUN_MAGIC {
1101        return Err(MongrelError::MagicMismatch {
1102            what: "sorted run footer",
1103            expected: RUN_MAGIC,
1104            got: footer[..8].try_into().unwrap(),
1105        });
1106    }
1107    let mut hasher = Sha256::new();
1108    file.seek(SeekFrom::Start(0))?;
1109    let mut remaining = header.footer_offset;
1110    let mut buffer = [0u8; 64 * 1024];
1111    while remaining != 0 {
1112        let length = usize::try_from(remaining.min(buffer.len() as u64)).unwrap();
1113        file.read_exact(&mut buffer[..length])?;
1114        hasher.update(&buffer[..length]);
1115        remaining -= length as u64;
1116    }
1117    let computed: [u8; 32] = hasher.finalize().into();
1118    let stored: [u8; 32] = footer[16..].try_into().unwrap();
1119    if computed != stored {
1120        return Err(MongrelError::ChecksumMismatch {
1121            expected: u64::from_be_bytes(stored[..8].try_into().unwrap()),
1122            actual: u64::from_be_bytes(computed[..8].try_into().unwrap()),
1123            context: "sorted run footer".into(),
1124        });
1125    }
1126    file.seek(SeekFrom::Start(RUN_HEADER_PAD as u64))?;
1127    let mut remaining = header.column_dir_offset - RUN_HEADER_PAD as u64;
1128    let mut content = Sha256::new();
1129    while remaining != 0 {
1130        let length = usize::try_from(remaining.min(buffer.len() as u64)).unwrap();
1131        file.read_exact(&mut buffer[..length])?;
1132        content.update(&buffer[..length]);
1133        remaining -= length as u64;
1134    }
1135    let content_hash: [u8; 32] = content.finalize().into();
1136    if content_hash != header.content_hash {
1137        return Err(MongrelError::ChecksumMismatch {
1138            expected: u64::from_be_bytes(header.content_hash[..8].try_into().unwrap()),
1139            actual: u64::from_be_bytes(content_hash[..8].try_into().unwrap()),
1140            context: "sorted run content hash".into(),
1141        });
1142    }
1143    Ok(header)
1144}
1145
1146/// Read the column directory.
1147pub fn read_column_dir(
1148    path: impl AsRef<Path>,
1149    header: &RunHeader,
1150) -> Result<Vec<ColumnPageHeader>> {
1151    let mut file = crate::durable_file::open_regular_nofollow(path.as_ref())?;
1152    read_column_dir_from_file(&mut file, header)
1153}
1154
1155fn read_column_dir_from_file(file: &mut File, header: &RunHeader) -> Result<Vec<ColumnPageHeader>> {
1156    file.seek(SeekFrom::Start(header.column_dir_offset))?;
1157    let end = [
1158        header.index_trailer_offset,
1159        header.encryption_descriptor_offset,
1160        header.encrypted_stats_offset,
1161        header.footer_offset,
1162    ]
1163    .into_iter()
1164    .filter(|offset| *offset > header.column_dir_offset)
1165    .min()
1166    .ok_or_else(|| {
1167        MongrelError::InvalidArgument("sorted run column directory has no end".into())
1168    })?;
1169    let len = end.checked_sub(header.column_dir_offset).ok_or_else(|| {
1170        MongrelError::InvalidArgument("sorted run column directory offsets are reversed".into())
1171    })?;
1172    const MAX_COLUMN_DIR_BYTES: u64 = 64 * 1024 * 1024;
1173    if len > MAX_COLUMN_DIR_BYTES {
1174        return Err(MongrelError::InvalidArgument(format!(
1175            "sorted run column directory length {len} exceeds {MAX_COLUMN_DIR_BYTES}"
1176        )));
1177    }
1178    let mut buf = vec![0u8; len as usize];
1179    file.read_exact(&mut buf)?;
1180    let dir: Vec<ColumnPageHeader> = bincode::deserialize(&buf)
1181        .map_err(|e| MongrelError::InvalidArgument(format!("bad column dir: {e}")))?;
1182    Ok(dir)
1183}
1184
1185fn validate_column_directory_layout(header: &RunHeader, dir: &[ColumnPageHeader]) -> Result<()> {
1186    if header.column_count != dir.len() as u64 || dir.len() > u16::MAX as usize {
1187        return Err(MongrelError::InvalidArgument(
1188            "sorted run column count is invalid".into(),
1189        ));
1190    }
1191    let mut regions = Vec::with_capacity(dir.len());
1192    let mut ids = std::collections::HashSet::new();
1193    for column in dir {
1194        if !ids.insert(column.column_id)
1195            || column.flags & !ColumnPageHeader::PAGE_ENCRYPTED != 0
1196            || column.page_count as usize != column.page_stats.len()
1197        {
1198            return Err(MongrelError::InvalidArgument(
1199                "sorted run column directory identity is invalid".into(),
1200            ));
1201        }
1202        let region_end = column
1203            .page_region_offset
1204            .checked_add(column.page_region_len)
1205            .ok_or_else(|| MongrelError::InvalidArgument("run page region overflows".into()))?;
1206        if column.page_region_offset < RUN_HEADER_PAD as u64
1207            || region_end > header.column_dir_offset
1208        {
1209            return Err(MongrelError::InvalidArgument(
1210                "sorted run page region is outside its body".into(),
1211            ));
1212        }
1213        let mut cursor = column.page_region_offset;
1214        let mut rows = 0_u64;
1215        for stat in &column.page_stats {
1216            let length = stat.compressed_len as u64;
1217            let end = stat
1218                .offset
1219                .checked_add(length)
1220                .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
1221            if stat.offset != cursor
1222                || length == 0
1223                || length > MAX_RUN_PAGE_BYTES
1224                || stat.uncompressed_len as u64 > MAX_RUN_PAGE_BYTES
1225                || stat.row_count as usize > PAGE_ROWS
1226                || end > region_end
1227            {
1228                return Err(MongrelError::InvalidArgument(
1229                    "sorted run page metadata is outside its region".into(),
1230                ));
1231            }
1232            rows = rows.checked_add(stat.row_count as u64).ok_or_else(|| {
1233                MongrelError::InvalidArgument("sorted run row count overflows".into())
1234            })?;
1235            cursor = end;
1236        }
1237        if cursor != region_end || rows != header.row_count {
1238            return Err(MongrelError::InvalidArgument(
1239                "sorted run page region length or row count is inconsistent".into(),
1240            ));
1241        }
1242        regions.push((column.page_region_offset, region_end));
1243    }
1244    regions.sort_unstable();
1245    if regions.windows(2).any(|pair| pair[0].1 > pair[1].0) {
1246        return Err(MongrelError::InvalidArgument(
1247            "sorted run page regions overlap".into(),
1248        ));
1249    }
1250    Ok(())
1251}
1252
1253fn read_encryption_descriptor_bytes_from_file(
1254    file: &mut File,
1255    header: &RunHeader,
1256) -> Result<Vec<u8>> {
1257    file.seek(SeekFrom::Start(header.encryption_descriptor_offset))?;
1258    let mut len_buf = [0u8; 4];
1259    file.read_exact(&mut len_buf)?;
1260    let len = u32::from_le_bytes(len_buf) as usize;
1261    // The descriptor is tiny (~60 bytes + a few column entries); clamp to a
1262    // sane ceiling so a corrupt/malicious header can't trigger a multi-GiB
1263    // allocation. (The footer checksum already guards integrity; this is a
1264    // defense-in-depth bound on the pre-checksum read.)
1265    const MAX_DESCRIPTOR_BYTES: usize = 65_536;
1266    if len > MAX_DESCRIPTOR_BYTES {
1267        return Err(MongrelError::InvalidArgument(format!(
1268            "encryption descriptor length {len} exceeds {MAX_DESCRIPTOR_BYTES}"
1269        )));
1270    }
1271    let mut buf = vec![0u8; len];
1272    file.read_exact(&mut buf)?;
1273    Ok(buf)
1274}
1275
1276/// Authenticate an encrypted run's cleartext metadata (`header ‖ dir ‖
1277/// descriptor`) against the keyed MAC tag stored after the footer. Run BEFORE
1278/// any offset/stat from the directory is trusted to drive a read. Errors if the
1279/// tag is missing (a run written before run-metadata MACs existed) or does not
1280/// match (tampering, or the wrong key). The on-disk page payloads are AEAD-
1281/// authenticated separately, so they are not covered here.
1282fn verify_run_mac(
1283    file: &mut File,
1284    header: &RunHeader,
1285    dir: &[ColumnPageHeader],
1286    kek: &Kek,
1287    desc_bytes: &[u8],
1288) -> Result<()> {
1289    let header_bytes = bincode::serialize(header)?;
1290    let dir_bytes = bincode::serialize(dir)?;
1291    let mac_key = kek.derive_run_mac_key();
1292    let expected =
1293        crate::encryption::run_metadata_mac(&mac_key, &header_bytes, &dir_bytes, desc_bytes);
1294    file.seek(SeekFrom::Start(header.footer_offset + 8 + 8 + 32))?;
1295    let mut tag = [0u8; RUN_MAC_LEN];
1296    file.read_exact(&mut tag).map_err(|_| {
1297        MongrelError::Decryption(
1298            "encrypted run is missing or truncated its metadata MAC; cannot \
1299             authenticate metadata"
1300                .into(),
1301        )
1302    })?;
1303    // Constant-time comparison (no early-exit timing oracle on the tag).
1304    let mut diff = 0u8;
1305    for (x, y) in tag.iter().zip(expected.iter()) {
1306        diff |= x ^ y;
1307    }
1308    if diff != 0 {
1309        return Err(MongrelError::Decryption(
1310            "run metadata authentication failed — tampered run or wrong key".into(),
1311        ));
1312    }
1313    Ok(())
1314}
1315
1316// ============================ high-level writer ============================
1317
1318/// Builds and writes a sorted run from drained memtable rows.
1319///
1320/// `rows` must be sorted ascending by `(row_id, epoch)` (the memtable's natural
1321/// drain order). System columns `_row_id`, `_epoch`, `_deleted` are always
1322/// emitted; each user column in `schema` is emitted, with `Null` for rows that
1323/// don't set it.
1324pub struct RunWriter<'a> {
1325    schema: &'a Schema,
1326    run_id: u128,
1327    epoch_created: Epoch,
1328    level: u8,
1329    kek: Option<&'a Kek>,
1330    /// `(column_id, scheme)` for each ENCRYPTED_INDEXABLE column — wrapped into
1331    /// the run's Encryption Descriptor (Phase 10.2).
1332    indexable_columns: Vec<(u16, u8)>,
1333    /// Per-page compression policy (Phase 14.4 / 15.3). Default `Zstd(3)`
1334    /// (compaction); the bulk path uses `Zstd(1)` or `Lz4` (hot, scan-heavy
1335    /// runs), and `Plain` skips compression entirely (`bulk_load_fast`).
1336    compress: columnar::Compress,
1337    /// Whether this run is "clean" (one version per RowId, no tombstones,
1338    /// ascending row_ids) — written into [`RUN_FLAG_CLEAN`] so readers can skip
1339    /// the MVCC visibility pass. Set true only by paths that construct clean
1340    /// system columns by construction (typed bulk load, compaction output).
1341    clean: bool,
1342    /// Whether this run's stored `_epoch` column is a placeholder and its real
1343    /// commit epoch lives in the manifest `RunRef.epoch_created` (set only by the
1344    /// large-transaction spill path, which writes before the epoch is assigned).
1345    /// Stamps [`RUN_FLAG_UNIFORM_EPOCH`] so the reader overlays the real epoch.
1346    uniform_epoch: bool,
1347    /// Write fixed-width page payloads in little-endian (Phase 15.7) so the
1348    /// decode path is a memcpy on real (x86/ARM) hardware instead of a
1349    /// per-element `swap_bytes`. Default **true** for the typed write paths
1350    /// (`write_native`); the legacy `write` (Value) path keeps big-endian for
1351    /// back-compat with pre-15.7 runs. The flag is stored per-page (bit 3 of the
1352    /// algo byte), so a run may freely mix LE and BE pages.
1353    le: bool,
1354}
1355
1356impl<'a> RunWriter<'a> {
1357    pub fn new(schema: &'a Schema, run_id: u128, epoch_created: Epoch, level: u8) -> Self {
1358        Self {
1359            schema,
1360            run_id,
1361            epoch_created,
1362            level,
1363            kek: None,
1364            indexable_columns: Vec::new(),
1365            compress: columnar::Compress::Zstd(3),
1366            clean: false,
1367            uniform_epoch: false,
1368            le: false,
1369        }
1370    }
1371
1372    /// Mark this run as uniform-epoch: its stored `_epoch` column is a
1373    /// placeholder and the real commit epoch is supplied at read time from the
1374    /// manifest `RunRef.epoch_created` (see [`RUN_FLAG_UNIFORM_EPOCH`]). Used by
1375    /// the large-transaction spill path, which writes the run before the commit
1376    /// epoch is assigned.
1377    pub fn uniform_epoch(mut self, uniform: bool) -> Self {
1378        self.uniform_epoch = uniform;
1379        self
1380    }
1381
1382    /// Encrypt this run's pages with a fresh per-file DEK wrapped by `kek`.
1383    /// `indexable_columns` are the ENCRYPTED_INDEXABLE `(column_id, scheme)`
1384    /// pairs whose column keys are derived+wrapped into the descriptor.
1385    pub fn with_encryption(mut self, kek: &'a Kek, indexable_columns: Vec<(u16, u8)>) -> Self {
1386        self.kek = Some(kek);
1387        self.indexable_columns = indexable_columns;
1388        self
1389    }
1390
1391    /// Override the zstd level for this run's pages (Phase 14.4). The bulk
1392    /// ingest path uses level 1; background compaction upgrades cold runs to 3.
1393    pub fn with_zstd_level(mut self, level: i32) -> Self {
1394        self.compress = columnar::Compress::Zstd(level);
1395        self
1396    }
1397
1398    /// Compress hot/mutable-run pages with LZ4 (Phase 15.3): 3–5× faster decode
1399    /// than zstd with ~10% worse ratio. The right default for runs that get
1400    /// scanned (bulk-loaded analytical runs).
1401    pub fn with_lz4(mut self) -> Self {
1402        self.compress = columnar::Compress::Lz4;
1403        self
1404    }
1405
1406    /// Emit raw `ALGO_PLAIN` pages with no compression (Phase 14.4
1407    /// `bulk_load_fast`): maximal encode throughput at the cost of ~3–4× size.
1408    pub fn with_plain(mut self) -> Self {
1409        self.compress = columnar::Compress::Plain;
1410        self
1411    }
1412
1413    /// Mark this run as "clean" (one version per RowId, no tombstones, ascending
1414    /// row_ids). Only set when the caller constructs the system columns so by
1415    /// construction (typed bulk load of fresh, contiguous row_ids; compaction
1416    /// output that has collapsed versions and dropped tombstones). Stamps
1417    /// [`RUN_FLAG_CLEAN`] into the header so readers skip the MVCC pass.
1418    pub fn clean(mut self, clean: bool) -> Self {
1419        self.clean = clean;
1420        self
1421    }
1422
1423    /// Write fixed-width page payloads in little-endian (Phase 15.7): the decode
1424    /// path becomes a memcpy on little-endian targets. Only effective on the
1425    /// typed `write_native` path; no-op on big-endian writers (they keep the
1426    /// portable BE layout, since "native" would not be LE there).
1427    pub fn with_native_endian(mut self) -> Self {
1428        if cfg!(target_endian = "little") {
1429            self.le = true;
1430        }
1431        self
1432    }
1433
1434    /// Write a run straight from typed columns (no `Value`). `user_columns` are
1435    /// the schema's user columns as [`NativeColumn`]s; the system columns
1436    /// (`_row_id`/`_epoch`/`_deleted`) are built from `first_row_id..+n` /
1437    /// `epoch_created` / all-false. Sorted Int64 columns (always the system
1438    /// `_row_id`, plus any sorted user Int64) use delta encoding unless
1439    /// [`RunWriter::with_plain`] forces raw `ALGO_PLAIN` everywhere.
1440    pub fn write_native(
1441        self,
1442        path: impl AsRef<Path>,
1443        user_columns: &[(u16, columnar::NativeColumn)],
1444        n: usize,
1445        first_row_id: u64,
1446    ) -> Result<RunHeader> {
1447        self.write_native_target(Some(path.as_ref()), None, user_columns, n, first_row_id)
1448    }
1449
1450    pub(crate) fn write_native_file(
1451        self,
1452        file: File,
1453        user_columns: &[(u16, columnar::NativeColumn)],
1454        n: usize,
1455        first_row_id: u64,
1456    ) -> Result<RunHeader> {
1457        self.write_native_target(None, Some(file), user_columns, n, first_row_id)
1458    }
1459
1460    fn write_native_target(
1461        self,
1462        path: Option<&Path>,
1463        file: Option<File>,
1464        user_columns: &[(u16, columnar::NativeColumn)],
1465        n: usize,
1466        first_row_id: u64,
1467    ) -> Result<RunHeader> {
1468        use columnar::NativeColumn;
1469        let row_id_col = NativeColumn::int64_sequence(first_row_id as i64, n);
1470        let epoch_col = NativeColumn::int64_constant(self.epoch_created.0 as i64, n);
1471        let deleted_col = NativeColumn::bool_constant(false, n);
1472
1473        let learned_trailer = build_learned_trailer_native(&row_id_col);
1474
1475        // All columns split on the same row-position boundaries so a reader can
1476        // skip whole pages of any column via its [min,max] stat.
1477        let row_ids = match &row_id_col {
1478            NativeColumn::Int64 { data, .. } => data.as_slice(),
1479            _ => &[],
1480        };
1481        let bounds = page_bounds(row_ids);
1482        let compress = self.compress;
1483        let le = self.le;
1484        let plain = matches!(compress, columnar::Compress::Plain);
1485        // In plain mode every column is `Encoding::Plain` (raw); otherwise keep
1486        // the chosen encoding (Delta for the sorted _row_id, Zstd for the rest).
1487        let row_id_enc = if plain {
1488            Encoding::Plain
1489        } else {
1490            Encoding::Delta
1491        };
1492        let sys_enc = if plain {
1493            Encoding::Plain
1494        } else {
1495            Encoding::Zstd
1496        };
1497
1498        let mut columns: Vec<ColumnPayload> = Vec::with_capacity(3 + self.schema.columns.len());
1499        let (pages, stats) = native_column_pages(
1500            TypeId::Int64,
1501            &row_id_col,
1502            row_id_enc,
1503            compress,
1504            le,
1505            &bounds,
1506        )?;
1507        columns.push(ColumnPayload {
1508            column_id: SYS_ROW_ID,
1509            type_id_tag: type_tag(&TypeId::Int64),
1510            encoding: row_id_enc,
1511            pages,
1512            page_stats: stats,
1513        });
1514        let (pages, stats) =
1515            native_column_pages(TypeId::Int64, &epoch_col, sys_enc, compress, le, &bounds)?;
1516        columns.push(ColumnPayload {
1517            column_id: SYS_EPOCH,
1518            type_id_tag: type_tag(&TypeId::Int64),
1519            encoding: sys_enc,
1520            pages,
1521            page_stats: stats,
1522        });
1523        let (pages, stats) =
1524            native_column_pages(TypeId::Bool, &deleted_col, sys_enc, compress, le, &bounds)?;
1525        columns.push(ColumnPayload {
1526            column_id: SYS_DELETED,
1527            type_id_tag: type_tag(&TypeId::Bool),
1528            encoding: sys_enc,
1529            pages,
1530            page_stats: stats,
1531        });
1532        // Encode all user columns in parallel (Phase 14.3): each column's pages
1533        // are independent, and the page-level work is itself parallel, so a
1534        // wide table saturates the pool without oversubscribing (rayon
1535        // work-steals across the nested parallelism). Order is preserved so the
1536        // column directory matches `schema.columns` order.
1537        use rayon::prelude::*;
1538        let user_cols: Vec<ColumnPayload> = self
1539            .schema
1540            .columns
1541            .par_iter()
1542            .map(|cdef| -> Result<ColumnPayload> {
1543                let col = user_columns
1544                    .iter()
1545                    .find(|(id, _)| *id == cdef.id)
1546                    .map(|(_, c)| c)
1547                    .ok_or_else(|| {
1548                        MongrelError::ColumnNotFound(format!("user column {}", cdef.id))
1549                    })?;
1550                let encoding = if plain {
1551                    Encoding::Plain
1552                } else {
1553                    choose_encoding_native(&cdef.ty, col)
1554                };
1555                let (pages, stats) =
1556                    native_column_pages(cdef.ty.clone(), col, encoding, compress, le, &bounds)?;
1557                Ok(ColumnPayload {
1558                    column_id: cdef.id,
1559                    type_id_tag: type_tag(&cdef.ty),
1560                    encoding,
1561                    pages,
1562                    page_stats: stats,
1563                })
1564            })
1565            .collect::<Result<Vec<_>>>()?;
1566        columns.extend(user_cols);
1567
1568        // A uniform-epoch run's `_epoch` column is a placeholder (the real commit
1569        // epoch is overlaid from the RunRef at read time), so it must NOT be
1570        // marked clean — the clean fast path skips snapshot gating — and must
1571        // carry the overlay flag. write_native is not the spill path today, but
1572        // keep it sound if it ever is.
1573        let flags = if self.uniform_epoch {
1574            RUN_FLAG_UNIFORM_EPOCH
1575        } else {
1576            RUN_FLAG_CLEAN
1577        };
1578        let spec = RunSpec {
1579            run_id: self.run_id,
1580            schema_id: self.schema.schema_id,
1581            epoch_created: self.epoch_created.0,
1582            level: self.level,
1583            flags,
1584            sort_key_column_id: SYS_ROW_ID,
1585            row_count: n as u64,
1586            min_row_id: first_row_id,
1587            max_row_id: first_row_id + n as u64 - 1,
1588            columns: &columns,
1589        };
1590        match file {
1591            Some(file) => write_run_with_file(
1592                file,
1593                &spec,
1594                self.kek,
1595                &self.indexable_columns,
1596                Some(&learned_trailer),
1597            ),
1598            None => write_run_with(
1599                path.ok_or_else(|| {
1600                    MongrelError::InvalidArgument("sorted run output is missing".into())
1601                })?,
1602                &spec,
1603                self.kek,
1604                &self.indexable_columns,
1605                Some(&learned_trailer),
1606            ),
1607        }
1608    }
1609
1610    pub fn write(self, path: impl AsRef<Path>, rows: &[Row]) -> Result<RunHeader> {
1611        self.write_target(Some(path.as_ref()), None, rows)
1612    }
1613
1614    pub(crate) fn write_file(self, file: File, rows: &[Row]) -> Result<RunHeader> {
1615        self.write_target(None, Some(file), rows)
1616    }
1617
1618    fn write_target(
1619        self,
1620        path: Option<&Path>,
1621        file: Option<File>,
1622        rows: &[Row],
1623    ) -> Result<RunHeader> {
1624        let n = rows.len();
1625        // System columns.
1626        let mut row_ids = Vec::with_capacity(n);
1627        let mut epochs = Vec::with_capacity(n);
1628        let mut deleted = Vec::with_capacity(n);
1629        let mut commit_ts_vals = Vec::with_capacity(n);
1630        // Emit SYS_COMMIT_TS when any version is HLC-stamped (P0.5-T3).
1631        let has_commit_ts = rows.iter().any(|r| r.commit_ts.is_some());
1632        for r in rows {
1633            row_ids.push(Value::Int64(r.row_id.0 as i64));
1634            epochs.push(Value::Int64(r.committed_epoch.0 as i64));
1635            deleted.push(Value::Bool(r.deleted));
1636            if has_commit_ts {
1637                commit_ts_vals.push(encode_commit_ts_value(r.commit_ts));
1638            }
1639        }
1640        let learned_trailer = build_learned_trailer(&row_ids);
1641        let (min_rid, max_rid) = row_id_bounds(rows);
1642        let row_id_i64: Vec<i64> = rows.iter().map(|r| r.row_id.0 as i64).collect();
1643        let bounds = page_bounds(&row_id_i64);
1644
1645        let mut columns: Vec<ColumnPayload> =
1646            Vec::with_capacity(3 + usize::from(has_commit_ts) + self.schema.columns.len());
1647        let (pages, stats, enc) = value_column_pages(TypeId::Int64, &row_ids, &bounds)?;
1648        columns.push(ColumnPayload {
1649            column_id: SYS_ROW_ID,
1650            type_id_tag: type_tag(&TypeId::Int64),
1651            encoding: enc,
1652            pages,
1653            page_stats: stats,
1654        });
1655        let (pages, stats, enc) = value_column_pages(TypeId::Int64, &epochs, &bounds)?;
1656        columns.push(ColumnPayload {
1657            column_id: SYS_EPOCH,
1658            type_id_tag: type_tag(&TypeId::Int64),
1659            encoding: enc,
1660            pages,
1661            page_stats: stats,
1662        });
1663        let (pages, stats, enc) = value_column_pages(TypeId::Bool, &deleted, &bounds)?;
1664        columns.push(ColumnPayload {
1665            column_id: SYS_DELETED,
1666            type_id_tag: type_tag(&TypeId::Bool),
1667            encoding: enc,
1668            pages,
1669            page_stats: stats,
1670        });
1671        if has_commit_ts {
1672            let (pages, stats, enc) = value_column_pages(TypeId::Bytes, &commit_ts_vals, &bounds)?;
1673            columns.push(ColumnPayload {
1674                column_id: SYS_COMMIT_TS,
1675                type_id_tag: type_tag(&TypeId::Bytes),
1676                encoding: enc,
1677                pages,
1678                page_stats: stats,
1679            });
1680        }
1681        // User columns — choose an encoding per column from run-time stats.
1682        for cdef in &self.schema.columns {
1683            let vals: Vec<Value> = rows
1684                .iter()
1685                .map(|r| r.columns.get(&cdef.id).cloned().unwrap_or(Value::Null))
1686                .collect();
1687            let (pages, stats, encoding) = value_column_pages(cdef.ty.clone(), &vals, &bounds)?;
1688            columns.push(ColumnPayload {
1689                column_id: cdef.id,
1690                type_id_tag: type_tag(&cdef.ty),
1691                encoding,
1692                pages,
1693                page_stats: stats,
1694            });
1695        }
1696
1697        let spec = RunSpec {
1698            run_id: self.run_id,
1699            schema_id: self.schema.schema_id,
1700            epoch_created: self.epoch_created.0,
1701            level: self.level,
1702            flags: {
1703                let mut f = if self.clean { RUN_FLAG_CLEAN } else { 0 };
1704                if self.uniform_epoch {
1705                    f |= RUN_FLAG_UNIFORM_EPOCH;
1706                }
1707                f
1708            },
1709            sort_key_column_id: SYS_ROW_ID,
1710            row_count: n as u64,
1711            min_row_id: min_rid,
1712            max_row_id: max_rid,
1713            columns: &columns,
1714        };
1715        match file {
1716            Some(file) => write_run_with_file(
1717                file,
1718                &spec,
1719                self.kek,
1720                &self.indexable_columns,
1721                Some(&learned_trailer),
1722            ),
1723            None => write_run_with(
1724                path.ok_or_else(|| {
1725                    MongrelError::InvalidArgument("sorted run output is missing".into())
1726                })?,
1727                &spec,
1728                self.kek,
1729                &self.indexable_columns,
1730                Some(&learned_trailer),
1731            ),
1732        }
1733    }
1734}
1735
1736fn type_tag(ty: &TypeId) -> u16 {
1737    // Informational only; the reader resolves the full type from the schema.
1738    match ty {
1739        TypeId::Bool => 1,
1740        TypeId::Int64 => 8,
1741        TypeId::Float64 => 9,
1742        TypeId::Bytes => 12,
1743        TypeId::Embedding { .. } => 13,
1744        _ => 0,
1745    }
1746}
1747
1748/// Decode a big-endian i64 from a `PageStat` min/max slot (None if absent or
1749/// truncated — treated as "all-null page" by the caller).
1750pub(crate) fn be_i64(b: Option<&[u8]>) -> Option<i64> {
1751    let b = b?;
1752    (b.len() == 8).then(|| i64::from_be_bytes(b.try_into().unwrap()))
1753}
1754
1755/// Decode a big-endian f64 (stored as `to_bits`) from a stat slot.
1756pub(crate) fn be_f64(b: Option<&[u8]>) -> Option<f64> {
1757    let b = b?;
1758    (b.len() == 8).then(|| f64::from_bits(u64::from_be_bytes(b.try_into().unwrap())))
1759}
1760
1761/// Rows per columnar page. Small enough to prune effectively, large enough to
1762/// keep per-page overhead negligible. ~16 pages per 1M-row column.
1763const PAGE_ROWS: usize = 65_536;
1764
1765/// `(start, end, first_row_id, last_row_id)` for each page, derived from the
1766/// actual row-id column so flush paths with non-contiguous ids stay correct.
1767fn page_bounds(row_ids: &[i64]) -> Vec<(usize, usize, u64, u64)> {
1768    let n = row_ids.len();
1769    if n == 0 {
1770        return vec![(0, 0, 0, 0)];
1771    }
1772    let mut out = Vec::new();
1773    let mut start = 0;
1774    while start < n {
1775        let end = (start + PAGE_ROWS).min(n);
1776        out.push((start, end, row_ids[start] as u64, row_ids[end - 1] as u64));
1777        start = end;
1778    }
1779    out
1780}
1781
1782/// Split a typed column into per-page encoded bytes + value-derived stats.
1783/// Pages are encoded in parallel across the rayon pool when a column spans more
1784/// than one page (Phase 14.3) — a 1M-row column has 16 independent encode tasks.
1785/// `compress` selects the page algorithm (Phase 14.4 / 15.3). Order is preserved
1786/// so the column directory stays sequential by page_seq.
1787fn native_column_pages(
1788    ty: TypeId,
1789    col: &columnar::NativeColumn,
1790    encoding: Encoding,
1791    compress: columnar::Compress,
1792    le: bool,
1793    bounds: &[(usize, usize, u64, u64)],
1794) -> Result<(Vec<Vec<u8>>, Vec<PageStat>)> {
1795    use rayon::prelude::*;
1796    let encode_one =
1797        |&(s, e, frid, lrid): &(usize, usize, u64, u64)| -> Result<(Vec<u8>, PageStat)> {
1798            let chunk = col.slice_range(s, e);
1799            let stat = columnar::page_stat_for(ty.clone(), &chunk, frid, lrid);
1800            let page = columnar::encode_page_native(ty.clone(), &chunk, encoding, compress, le)?;
1801            Ok((page, stat))
1802        };
1803    // Single-page columns skip the thread-pool handshake.
1804    let pairs: Vec<(Vec<u8>, PageStat)> = if bounds.len() > 1 {
1805        bounds
1806            .par_iter()
1807            .map(encode_one)
1808            .collect::<Result<Vec<_>>>()?
1809    } else {
1810        bounds.iter().map(encode_one).collect::<Result<Vec<_>>>()?
1811    };
1812    let (pages, stats) = pairs.into_iter().unzip();
1813    Ok((pages, stats))
1814}
1815
1816/// Split a `Value` column into per-page encoded bytes + stats (flush path).
1817fn value_column_pages(
1818    ty: TypeId,
1819    vals: &[Value],
1820    bounds: &[(usize, usize, u64, u64)],
1821) -> Result<(Vec<Vec<u8>>, Vec<PageStat>, Encoding)> {
1822    let encoding = choose_encoding(&ty, vals);
1823    let mut pages = Vec::with_capacity(bounds.len());
1824    let mut stats = Vec::with_capacity(bounds.len());
1825    for &(s, e, frid, lrid) in bounds {
1826        let chunk = &vals[s..e];
1827        pages.push(columnar::encode_page(ty.clone(), chunk, encoding)?);
1828        let native = columnar::values_to_native(ty.clone(), chunk);
1829        stats.push(columnar::page_stat_for(ty.clone(), &native, frid, lrid));
1830    }
1831    Ok((pages, stats, encoding))
1832}
1833
1834/// Pick a page encoding from run-time stats: dictionary for low-cardinality
1835/// strings, zstd-plain otherwise.
1836fn choose_encoding(ty: &TypeId, values: &[Value]) -> Encoding {
1837    use std::collections::HashSet;
1838    if matches!(ty, TypeId::Bytes) {
1839        let n = values.len();
1840        if n > 0 {
1841            let distinct = values
1842                .iter()
1843                .filter(|v| !matches!(v, Value::Null))
1844                .map(|v| v.encode_key())
1845                .collect::<HashSet<_>>()
1846                .len();
1847            if (distinct as f64 / n as f64) < 0.5 {
1848                return Encoding::Dictionary;
1849            }
1850        }
1851    }
1852    Encoding::Zstd
1853}
1854
1855/// Encoding choice for the typed (native) path: delta for sorted Int64,
1856/// dictionary for low-cardinality Bytes, zstd otherwise.
1857fn choose_encoding_native(ty: &TypeId, col: &columnar::NativeColumn) -> Encoding {
1858    use std::collections::HashSet;
1859    match (ty, col) {
1860        (TypeId::Int64 | TypeId::TimestampNanos, columnar::NativeColumn::Int64 { data, .. }) => {
1861            if data.windows(2).all(|w| w[0] <= w[1]) {
1862                Encoding::Delta
1863            } else {
1864                Encoding::Zstd
1865            }
1866        }
1867        (
1868            TypeId::Bytes,
1869            columnar::NativeColumn::Bytes {
1870                offsets, values, ..
1871            },
1872        ) => {
1873            let n = offsets.len().saturating_sub(1);
1874            if n > 0 {
1875                let distinct: HashSet<&[u8]> = (0..n)
1876                    .map(|i| &values[offsets[i] as usize..offsets[i + 1] as usize])
1877                    .collect();
1878                if (distinct.len() as f64 / n as f64) < 0.5 {
1879                    return Encoding::Dictionary;
1880                }
1881            }
1882            Encoding::Zstd
1883        }
1884        _ => Encoding::Zstd,
1885    }
1886}
1887
1888/// PGM-index trailer built straight from the typed row-id column.
1889fn build_learned_trailer_native(col: &columnar::NativeColumn) -> Vec<u8> {
1890    let points: Vec<(u64, usize)> = match col {
1891        columnar::NativeColumn::Int64 { data, .. } => data
1892            .iter()
1893            .enumerate()
1894            .map(|(i, v)| (*v as u64, i))
1895            .collect(),
1896        _ => Vec::new(),
1897    };
1898    let pgm = PgmIndex::build(&points, LEARNED_EPSILON);
1899    bincode::serialize(&pgm).expect("pgm serialize")
1900}
1901
1902fn row_id_bounds(rows: &[Row]) -> (u64, u64) {
1903    match (rows.first(), rows.last()) {
1904        (Some(f), Some(l)) => (f.row_id.0, l.row_id.0),
1905        _ => (0, 0),
1906    }
1907}
1908
1909// ============================ high-level reader ============================
1910
1911/// Reads a sorted run: decodes columns lazily (cached), answers MVCC point
1912/// lookups via page-pruned `SYS_ROW_ID` bounds, and materializes visible rows
1913/// for scans.
1914pub struct RunReader {
1915    file: File,
1916    mmap: Option<memmap2::Mmap>,
1917    header: RunHeader,
1918    dir: Vec<ColumnPageHeader>,
1919    schema: Schema,
1920    /// Owning table id — namespaces the shared page cache across tables.
1921    table_id: u64,
1922    /// Per-run page cipher, built from the unwrapped DEK (None when plaintext).
1923    cipher: Option<Box<dyn Cipher>>,
1924    /// Per-run nonce prefix (overlaid per page with column_id + page_seq).
1925    nonce_prefix: [u8; 12],
1926    col_cache: HashMap<u16, Vec<Value>>,
1927    /// Shared, MVCC content-addressed page cache (Phase 9.2). Caches raw page
1928    /// bytes (ciphertext when encrypted) so all readers share decoded/decrypted
1929    /// pages. `None` only in standalone tests.
1930    page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
1931    /// Shared decoded-page cache (Phase 15.4): the post-decompress/decrypt typed
1932    /// page, so a repeat scan skips decode. Keyed by `(run_id, column_id,
1933    /// page_seq)` identity; `None` in standalone tests.
1934    decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
1935    /// Uniform-epoch overlay (see [`RUN_FLAG_UNIFORM_EPOCH`]). When `Some`, every
1936    /// row's commit epoch is taken to be this value instead of the placeholder
1937    /// stored in the `_epoch` column. Set by [`Self::set_uniform_epoch`].
1938    epoch_override: Option<Epoch>,
1939}
1940
1941#[derive(Debug, Clone, Copy)]
1942pub(crate) struct RunVisibleVersion {
1943    pub(crate) row_id: RowId,
1944    pub(crate) committed_epoch: Epoch,
1945    pub(crate) deleted: bool,
1946    page_seq: usize,
1947    within_page: usize,
1948}
1949
1950/// Page-bounded cursor over one run's newest snapshot-visible version per row.
1951/// Only the three compact system columns and one user-data page are decoded at
1952/// a time. Full `Vec<Row>` materialization is deliberately avoided.
1953pub(crate) struct RunVisibleVersionCursor {
1954    reader: RunReader,
1955    snapshot: Epoch,
1956    page_row_counts: Vec<usize>,
1957    page_seq: usize,
1958    within_page: usize,
1959    row_ids: Vec<i64>,
1960    epochs: Vec<i64>,
1961    deleted: Vec<u8>,
1962    lookahead: Option<RunVisibleVersion>,
1963    materialized_page: Option<usize>,
1964    materialized_columns: Vec<(u16, columnar::NativeColumn)>,
1965}
1966
1967impl RunVisibleVersionCursor {
1968    fn new(reader: RunReader, snapshot: Epoch) -> Result<Self> {
1969        let page_row_counts = reader.page_row_counts(SYS_ROW_ID)?;
1970        Ok(Self {
1971            reader,
1972            snapshot,
1973            page_row_counts,
1974            page_seq: 0,
1975            within_page: 0,
1976            row_ids: Vec::new(),
1977            epochs: Vec::new(),
1978            deleted: Vec::new(),
1979            lookahead: None,
1980            materialized_page: None,
1981            materialized_columns: Vec::new(),
1982        })
1983    }
1984
1985    fn load_system_page(&mut self, control: &crate::ExecutionControl) -> Result<bool> {
1986        while self.page_seq < self.page_row_counts.len() {
1987            control.checkpoint()?;
1988            let rows = self.page_row_counts[self.page_seq];
1989            if rows == 0 {
1990                self.page_seq += 1;
1991                continue;
1992            }
1993            self.row_ids = match columnar::decode_page_native(
1994                TypeId::Int64,
1995                &self.reader.read_page(SYS_ROW_ID, self.page_seq)?,
1996                rows,
1997            )? {
1998                columnar::NativeColumn::Int64 { data, .. } => data,
1999                _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
2000            };
2001            self.epochs = if let Some(epoch) = self.reader.epoch_override {
2002                vec![epoch.0 as i64; rows]
2003            } else {
2004                match columnar::decode_page_native(
2005                    TypeId::Int64,
2006                    &self.reader.read_page(SYS_EPOCH, self.page_seq)?,
2007                    rows,
2008                )? {
2009                    columnar::NativeColumn::Int64 { data, .. } => data,
2010                    _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
2011                }
2012            };
2013            self.deleted = match columnar::decode_page_native(
2014                TypeId::Bool,
2015                &self.reader.read_page(SYS_DELETED, self.page_seq)?,
2016                rows,
2017            )? {
2018                columnar::NativeColumn::Bool { data, .. } => data,
2019                _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
2020            };
2021            self.within_page = 0;
2022            return Ok(true);
2023        }
2024        Ok(false)
2025    }
2026
2027    fn next_raw(&mut self, control: &crate::ExecutionControl) -> Result<Option<RunVisibleVersion>> {
2028        if self.within_page >= self.row_ids.len() {
2029            if !self.row_ids.is_empty() {
2030                self.page_seq += 1;
2031                self.row_ids.clear();
2032                self.epochs.clear();
2033                self.deleted.clear();
2034            }
2035            if !self.load_system_page(control)? {
2036                return Ok(None);
2037            }
2038        }
2039        if self.within_page.is_multiple_of(256) {
2040            control.checkpoint()?;
2041        }
2042        let position = self.within_page;
2043        self.within_page += 1;
2044        Ok(Some(RunVisibleVersion {
2045            row_id: RowId(self.row_ids[position] as u64),
2046            committed_epoch: Epoch(self.epochs[position] as u64),
2047            deleted: self.deleted[position] != 0,
2048            page_seq: self.page_seq,
2049            within_page: position,
2050        }))
2051    }
2052
2053    pub(crate) fn next_visible_version(
2054        &mut self,
2055        control: &crate::ExecutionControl,
2056    ) -> Result<Option<RunVisibleVersion>> {
2057        loop {
2058            let first = match self.lookahead.take() {
2059                Some(version) => version,
2060                None => match self.next_raw(control)? {
2061                    Some(version) => version,
2062                    None => return Ok(None),
2063                },
2064            };
2065            let row_id = first.row_id;
2066            let mut best = (first.committed_epoch <= self.snapshot).then_some(first);
2067            while let Some(candidate) = self.next_raw(control)? {
2068                if candidate.row_id != row_id {
2069                    self.lookahead = Some(candidate);
2070                    break;
2071                }
2072                if candidate.committed_epoch <= self.snapshot
2073                    && best
2074                        .is_none_or(|current| candidate.committed_epoch > current.committed_epoch)
2075                {
2076                    best = Some(candidate);
2077                }
2078            }
2079            if best.is_some() {
2080                return Ok(best);
2081            }
2082        }
2083    }
2084
2085    pub(crate) fn materialize(
2086        &mut self,
2087        version: RunVisibleVersion,
2088        control: &crate::ExecutionControl,
2089    ) -> Result<Row> {
2090        if self.materialized_page != Some(version.page_seq) {
2091            let rows = self.page_row_counts[version.page_seq];
2092            let columns = self.reader.schema.columns.clone();
2093            let mut materialized = Vec::with_capacity(columns.len());
2094            for (index, column) in columns.into_iter().enumerate() {
2095                if index % 16 == 0 {
2096                    control.checkpoint()?;
2097                }
2098                let native = if self.reader.has_column(column.id) {
2099                    columnar::decode_page_native(
2100                        column.ty,
2101                        &self.reader.read_page(column.id, version.page_seq)?,
2102                        rows,
2103                    )?
2104                } else {
2105                    columnar::null_native(column.ty, rows)
2106                };
2107                materialized.push((column.id, native));
2108            }
2109            self.materialized_columns = materialized;
2110            self.materialized_page = Some(version.page_seq);
2111        }
2112        let columns = self
2113            .materialized_columns
2114            .iter()
2115            .map(|(column_id, column)| {
2116                (
2117                    *column_id,
2118                    column.value_at(version.within_page).unwrap_or(Value::Null),
2119                )
2120            })
2121            .collect();
2122        // Optional HLC stamp (P0.5-T3): load from SYS_COMMIT_TS when present.
2123        let commit_ts = if self.reader.has_column(SYS_COMMIT_TS) {
2124            let page = self.reader.read_page(SYS_COMMIT_TS, version.page_seq)?;
2125            let native = columnar::decode_page_native(
2126                TypeId::Bytes,
2127                &page,
2128                self.page_row_counts[version.page_seq],
2129            )?;
2130            decode_commit_ts_value(native.value_at(version.within_page).as_ref())
2131        } else {
2132            None
2133        };
2134        Ok(Row {
2135            row_id: version.row_id,
2136            committed_epoch: version.committed_epoch,
2137            columns,
2138            deleted: version.deleted,
2139            commit_ts,
2140        })
2141    }
2142}
2143
2144impl RunReader {
2145    pub fn open(path: impl AsRef<Path>, schema: Schema, kek: Option<Arc<Kek>>) -> Result<Self> {
2146        Self::open_with_cache(path, schema, kek, None, None, 0, None)
2147    }
2148
2149    pub(crate) fn open_file(file: File, schema: Schema, kek: Option<Arc<Kek>>) -> Result<Self> {
2150        Self::open_file_with_cache(file, schema, kek, None, None, 0, None, None)
2151    }
2152
2153    #[allow(clippy::too_many_arguments)]
2154    pub(crate) fn open_with_cache(
2155        path: impl AsRef<Path>,
2156        schema: Schema,
2157        kek: Option<Arc<Kek>>,
2158        page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
2159        decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
2160        table_id: u64,
2161        verified_runs: Option<&parking_lot::Mutex<std::collections::HashSet<u128>>>,
2162    ) -> Result<Self> {
2163        let path = path.as_ref().to_path_buf();
2164        let file = crate::durable_file::open_regular_nofollow(&path)?;
2165        Self::open_file_with_cache(
2166            file,
2167            schema,
2168            kek,
2169            page_cache,
2170            decoded_cache,
2171            table_id,
2172            verified_runs,
2173            Some(path),
2174        )
2175    }
2176
2177    #[allow(clippy::too_many_arguments)]
2178    pub(crate) fn open_file_with_cache(
2179        mut file: File,
2180        schema: Schema,
2181        kek: Option<Arc<Kek>>,
2182        page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
2183        decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
2184        table_id: u64,
2185        verified_runs: Option<&parking_lot::Mutex<std::collections::HashSet<u128>>>,
2186        path: Option<PathBuf>,
2187    ) -> Result<Self> {
2188        let header = match verified_runs {
2189            Some(cache) => {
2190                let header = read_header_fast_from_file(&mut file)?;
2191                if cache.lock().contains(&header.run_id) {
2192                    header
2193                } else {
2194                    let verified = read_header_from_file(&mut file)?;
2195                    cache.lock().insert(verified.run_id);
2196                    verified
2197                }
2198            }
2199            None => read_header_from_file(&mut file)?,
2200        };
2201        let mut dir = read_column_dir_from_file(&mut file, &header)?;
2202        validate_column_directory_layout(&header, &dir)?;
2203        if header.is_encrypted() != kek.is_some() {
2204            return Err(MongrelError::Encryption(
2205                "sorted-run encryption mode differs from the database".into(),
2206            ));
2207        }
2208        // Unwrap this run's per-file DEK (stored wrapped in its Encryption
2209        // Descriptor) using the table KEK, then build the page cipher.
2210        let (cipher, nonce_prefix): (Option<Box<dyn Cipher>>, [u8; 12]) = if header.is_encrypted() {
2211            let kek = kek.as_ref().ok_or_else(|| {
2212                MongrelError::Encryption(
2213                    "run is encrypted but no key-encryption key was provided".into(),
2214                )
2215            })?;
2216            if header.encryption_descriptor_offset == 0 {
2217                return Err(MongrelError::Encryption(
2218                    "encrypted run has no encryption descriptor".into(),
2219                ));
2220            }
2221            let desc_bytes = read_encryption_descriptor_bytes_from_file(&mut file, &header)?;
2222            // Authenticate the cleartext metadata (header‖dir‖descriptor) under
2223            // the KEK-derived MAC key BEFORE trusting any offset/stat to drive a
2224            // read. Required for every encrypted run (no downgrade path: an
2225            // attacker can neither strip the encryption — pages stay ciphertext —
2226            // nor forge the tag without the key).
2227            verify_run_mac(&mut file, &header, &dir, kek, &desc_bytes)?;
2228            let enc = crate::encryption::build_run_cipher(kek, &desc_bytes)?;
2229            // With the metadata authenticated, decrypt the per-page min/max
2230            // envelope (v2 runs) and overlay it so zone-map pruning works on
2231            // encrypted columns exactly as it does on plaintext ones.
2232            if header.encrypted_stats_offset != 0 {
2233                overlay_encrypted_stats(
2234                    &mut file,
2235                    &header,
2236                    enc.cipher.as_ref(),
2237                    enc.nonce_prefix,
2238                    &mut dir,
2239                )?;
2240            }
2241            (Some(enc.cipher), enc.nonce_prefix)
2242        } else {
2243            (None, [0u8; 12])
2244        };
2245        // Best-effort memory map: lets the OS page cache manage I/O and removes
2246        // per-page seek+read syscalls. Falls back to read() on empty/unmappable
2247        // files. The `file` handle is kept for the lifetime of the mapping.
2248        // (Per-column `MADV_WILLNEED` read-ahead is issued from
2249        // `column_native_shared` — see Phase 15.2 — so a global advice policy is
2250        // not set here; that would degrade concurrent point lookups.)
2251        let mmap = unsafe { memmap2::MmapOptions::new().map(&file) }.ok();
2252        let _ = path;
2253        Ok(Self {
2254            file,
2255            mmap,
2256            header,
2257            dir,
2258            schema,
2259            table_id,
2260            cipher,
2261            nonce_prefix,
2262            col_cache: HashMap::new(),
2263            epoch_override: None,
2264            page_cache,
2265            decoded_cache,
2266        })
2267    }
2268
2269    pub fn header(&self) -> &RunHeader {
2270        &self.header
2271    }
2272
2273    pub(crate) fn validate_all_pages(&mut self) -> Result<()> {
2274        let mut columns = std::collections::HashSet::new();
2275        let row_header = self.find_header(SYS_ROW_ID)?.clone();
2276        let expected_rows = row_header
2277            .page_stats
2278            .iter()
2279            .map(|stat| stat.row_count)
2280            .collect::<Vec<_>>();
2281        let mut row_bounds = Vec::with_capacity(row_header.page_stats.len());
2282        let mut previous = None::<u64>;
2283        let mut first = None::<u64>;
2284        let mut last = None::<u64>;
2285        let mut counted = 0_u64;
2286        for (page, stat) in row_header.page_stats.iter().enumerate() {
2287            let bytes = self.read_page(SYS_ROW_ID, page)?;
2288            let native =
2289                columnar::decode_page_native(TypeId::Int64, &bytes, stat.row_count as usize)?;
2290            if columnar::page_stat_for(TypeId::Int64, &native, 0, 0).null_count != 0 {
2291                return Err(MongrelError::InvalidArgument(
2292                    "sorted run row-id page contains nulls".into(),
2293                ));
2294            }
2295            let columnar::NativeColumn::Int64 { data, validity } = native else {
2296                return Err(MongrelError::InvalidArgument(
2297                    "sorted run row-id page has the wrong type".into(),
2298                ));
2299            };
2300            let _ = validity;
2301            if data.is_empty() {
2302                if self.header.row_count != 0 || stat.row_count != 0 {
2303                    return Err(MongrelError::InvalidArgument(
2304                        "sorted run row-id page is unexpectedly empty".into(),
2305                    ));
2306                }
2307                row_bounds.push((0, 0));
2308                continue;
2309            }
2310            if data.iter().any(|value| *value < 0) {
2311                return Err(MongrelError::InvalidArgument(
2312                    "sorted run contains a negative row id".into(),
2313                ));
2314            }
2315            let page_first = data[0] as u64;
2316            let page_last = data[data.len() - 1] as u64;
2317            for value in data {
2318                let value = value as u64;
2319                if previous.is_some_and(|prior| {
2320                    value < prior || (self.header.is_clean() && value == prior)
2321                }) {
2322                    return Err(MongrelError::InvalidArgument(
2323                        "sorted run row ids are not ordered".into(),
2324                    ));
2325                }
2326                first.get_or_insert(value);
2327                previous = Some(value);
2328                last = Some(value);
2329                counted += 1;
2330            }
2331            if stat.first_row_id != page_first || stat.last_row_id != page_last {
2332                return Err(MongrelError::InvalidArgument(
2333                    "sorted run row-id page bounds are stale".into(),
2334                ));
2335            }
2336            row_bounds.push((page_first, page_last));
2337        }
2338        if counted != self.header.row_count
2339            || first.unwrap_or(0) != self.header.min_row_id
2340            || last.unwrap_or(0) != self.header.max_row_id
2341        {
2342            return Err(MongrelError::InvalidArgument(
2343                "sorted run header row bounds differ from its pages".into(),
2344            ));
2345        }
2346        for column in self.dir.clone() {
2347            if !columns.insert(column.column_id) {
2348                return Err(MongrelError::InvalidArgument(format!(
2349                    "sorted run contains duplicate column {}",
2350                    column.column_id
2351                )));
2352            }
2353            let rows = column
2354                .page_stats
2355                .iter()
2356                .map(|stat| stat.row_count)
2357                .collect::<Vec<_>>();
2358            if rows != expected_rows {
2359                return Err(MongrelError::InvalidArgument(
2360                    "sorted run columns have inconsistent page row counts".into(),
2361                ));
2362            }
2363            let ty = self.resolve_type(column.column_id);
2364            if column.type_id_tag != type_tag(&ty)
2365                || column.encoding > Encoding::Zstd as u8
2366                || (!is_system_column_id(column.column_id)
2367                    && self
2368                        .schema
2369                        .columns
2370                        .iter()
2371                        .all(|item| item.id != column.column_id))
2372            {
2373                return Err(MongrelError::InvalidArgument(
2374                    "sorted run column type or encoding is invalid".into(),
2375                ));
2376            }
2377            for (page, stat) in column.page_stats.iter().enumerate() {
2378                let bytes = self.read_page(column.column_id, page)?;
2379                if bytes.len() != stat.uncompressed_len as usize {
2380                    return Err(MongrelError::InvalidArgument(
2381                        "sorted run page length differs from its metadata".into(),
2382                    ));
2383                }
2384                let native =
2385                    match columnar::decode_page_native(ty.clone(), &bytes, stat.row_count as usize)
2386                    {
2387                        Ok(native) => native,
2388                        Err(MongrelError::InvalidArgument(message))
2389                            if message.starts_with("decode_page_native: unsupported ty") =>
2390                        {
2391                            let values =
2392                                columnar::decode_page(ty.clone(), &bytes, stat.row_count as usize)?;
2393                            columnar::values_to_native(ty.clone(), &values)
2394                        }
2395                        Err(error) => return Err(error),
2396                    };
2397                let (first_row_id, last_row_id) =
2398                    row_bounds.get(page).copied().ok_or_else(|| {
2399                        MongrelError::InvalidArgument(
2400                            "sorted run column has more pages than its row-id column".into(),
2401                        )
2402                    })?;
2403                let expected =
2404                    columnar::page_stat_for(ty.clone(), &native, first_row_id, last_row_id);
2405                if stat.first_row_id != expected.first_row_id
2406                    || stat.last_row_id != expected.last_row_id
2407                    || stat.null_count != expected.null_count
2408                    || stat.min != expected.min
2409                    || stat.max != expected.max
2410                {
2411                    return Err(MongrelError::InvalidArgument(
2412                        "sorted run page statistics differ from decoded values".into(),
2413                    ));
2414                }
2415            }
2416        }
2417        if !columns.contains(&SYS_ROW_ID)
2418            || !columns.contains(&SYS_EPOCH)
2419            || !columns.contains(&SYS_DELETED)
2420            || expected_rows.into_iter().map(u64::from).sum::<u64>() != self.header.row_count
2421        {
2422            return Err(MongrelError::InvalidArgument(
2423                "sorted run system columns or row count are invalid".into(),
2424            ));
2425        }
2426        if self.header.schema_id == self.schema.schema_id
2427            && self
2428                .schema
2429                .columns
2430                .iter()
2431                .any(|column| !columns.contains(&column.id))
2432        {
2433            return Err(MongrelError::InvalidArgument(
2434                "sorted run is missing a column from its declared schema".into(),
2435            ));
2436        }
2437
2438        // Page encodings and statistics are not enough to establish semantic
2439        // validity.  Reconstruct every materialized row and apply the schema's
2440        // row-level rules before the run can participate in recovery.
2441        for row_index in 0..usize::try_from(self.header.row_count).map_err(|_| {
2442            MongrelError::InvalidArgument("sorted run row count exceeds this platform".into())
2443        })? {
2444            let epoch = match self.column(SYS_EPOCH)?.get(row_index) {
2445                Some(Value::Int64(value)) if *value >= 0 => *value as u64,
2446                _ => {
2447                    return Err(MongrelError::InvalidArgument(
2448                        "sorted run contains an invalid commit epoch".into(),
2449                    ))
2450                }
2451            };
2452            if epoch > self.header.epoch_created || (self.header.is_uniform_epoch() && epoch != 0) {
2453                return Err(MongrelError::InvalidArgument(
2454                    "sorted run commit epoch exceeds its creation epoch".into(),
2455                ));
2456            }
2457            let deleted = match self.column(SYS_DELETED)?.get(row_index) {
2458                Some(Value::Bool(value)) => *value,
2459                _ => {
2460                    return Err(MongrelError::InvalidArgument(
2461                        "sorted run contains an invalid tombstone marker".into(),
2462                    ))
2463                }
2464            };
2465            let mut values = Vec::with_capacity(self.schema.columns.len());
2466            for column in self.schema.columns.clone() {
2467                let value = if columns.contains(&column.id) {
2468                    self.column(column.id)?
2469                        .get(row_index)
2470                        .cloned()
2471                        .unwrap_or(Value::Null)
2472                } else {
2473                    Value::Null
2474                };
2475                values.push((column.id, value));
2476            }
2477            if !deleted {
2478                self.schema
2479                    .validate_persisted_values(&values)
2480                    .map_err(|error| {
2481                        MongrelError::InvalidArgument(format!(
2482                            "sorted run row violates its schema: {error}"
2483                        ))
2484                    })?;
2485            }
2486        }
2487        Ok(())
2488    }
2489
2490    /// Overlay the real commit epoch for a uniform-epoch run (see
2491    /// [`RUN_FLAG_UNIFORM_EPOCH`]). No-op unless the run carries that flag, so it
2492    /// is always safe for the engine to call with the `RunRef.epoch_created`.
2493    pub(crate) fn set_uniform_epoch(&mut self, epoch: Epoch) {
2494        if self.header.is_uniform_epoch() {
2495            self.epoch_override = Some(epoch);
2496            // Drop any cached placeholder epoch column so the overlay takes hold.
2497            self.col_cache.remove(&SYS_EPOCH);
2498        }
2499    }
2500
2501    pub(crate) fn into_visible_version_cursor(
2502        self,
2503        snapshot: Epoch,
2504    ) -> Result<RunVisibleVersionCursor> {
2505        RunVisibleVersionCursor::new(self, snapshot)
2506    }
2507
2508    /// Whether this run is "clean" (one version per RowId, no tombstones,
2509    /// ascending row_ids) — stamped at write time via [`RUN_FLAG_CLEAN`].
2510    pub fn is_clean(&self) -> bool {
2511        self.header.is_clean()
2512    }
2513
2514    pub fn row_count(&self) -> usize {
2515        self.header.row_count as usize
2516    }
2517
2518    pub(crate) fn clean_contiguous_row_ids(&self) -> bool {
2519        let n = self.row_count();
2520        n > 0
2521            && self.is_clean()
2522            && self.epoch_override.is_none()
2523            && self.header.max_row_id >= self.header.min_row_id
2524            && self
2525                .header
2526                .max_row_id
2527                .checked_sub(self.header.min_row_id)
2528                .and_then(|span| span.checked_add(1))
2529                == Some(n as u64)
2530    }
2531
2532    pub(crate) fn position_for_row_id_fast(&self, row_id: u64) -> Option<usize> {
2533        if !self.clean_contiguous_row_ids()
2534            || row_id < self.header.min_row_id
2535            || row_id > self.header.max_row_id
2536        {
2537            return None;
2538        }
2539        Some((row_id - self.header.min_row_id) as usize)
2540    }
2541
2542    pub(crate) fn positions_for_row_ids_fast(&self, row_ids: &[u64]) -> Option<Vec<usize>> {
2543        if !self.clean_contiguous_row_ids() {
2544            return None;
2545        }
2546        let mut positions = Vec::with_capacity(row_ids.len());
2547        for &row_id in row_ids {
2548            if let Some(pos) = self.position_for_row_id_fast(row_id) {
2549                positions.push(pos);
2550            }
2551        }
2552        positions.sort_unstable();
2553        Some(positions)
2554    }
2555
2556    fn resolve_type(&self, column_id: u16) -> TypeId {
2557        match column_id {
2558            SYS_ROW_ID | SYS_EPOCH => TypeId::Int64,
2559            SYS_DELETED => TypeId::Bool,
2560            SYS_COMMIT_TS => TypeId::Bytes,
2561            _ => self
2562                .schema
2563                .columns
2564                .iter()
2565                .find(|c| c.id == column_id)
2566                .map(|c| c.ty.clone())
2567                .unwrap_or(TypeId::Bytes),
2568        }
2569    }
2570
2571    /// Optional HLC stamp at row `index` (P0.5-T3). Missing column → `None`.
2572    fn commit_ts_at(&mut self, index: usize) -> Result<Option<HlcTimestamp>> {
2573        if !self.has_column(SYS_COMMIT_TS) {
2574            return Ok(None);
2575        }
2576        Ok(decode_commit_ts_value(
2577            self.column(SYS_COMMIT_TS)?.get(index),
2578        ))
2579    }
2580
2581    fn find_header(&self, column_id: u16) -> Result<&ColumnPageHeader> {
2582        self.dir
2583            .iter()
2584            .find(|h| h.column_id == column_id)
2585            .ok_or_else(|| MongrelError::ColumnNotFound(format!("column {column_id}")))
2586    }
2587
2588    /// Whether `column_id`'s pages are encrypted. Encrypted runs carry no
2589    /// cleartext per-page min/max (they would leak plaintext values), so the
2590    /// range resolvers must NOT prune by stats for such columns — a missing
2591    /// stat there means "hidden", not "all-null". They fall back to decrypting
2592    /// and scanning every page.
2593    fn col_encrypted(&self, column_id: u16) -> bool {
2594        self.dir
2595            .iter()
2596            .find(|h| h.column_id == column_id)
2597            .map(|h| h.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0)
2598            .unwrap_or(false)
2599    }
2600
2601    pub(crate) fn read_page(&mut self, column_id: u16, page_seq: usize) -> Result<Vec<u8>> {
2602        let (offset, compressed_len, encrypted) = {
2603            let ch = self.find_header(column_id)?;
2604            let stat = ch
2605                .page_stats
2606                .get(page_seq)
2607                .ok_or_else(|| MongrelError::InvalidArgument("page seq out of range".into()))?;
2608            (
2609                stat.offset,
2610                stat.compressed_len,
2611                ch.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0,
2612            )
2613        };
2614        let end = offset
2615            .checked_add(compressed_len as u64)
2616            .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
2617        let start = usize::try_from(offset)
2618            .map_err(|_| MongrelError::InvalidArgument("run page offset is too large".into()))?;
2619        let end = usize::try_from(end)
2620            .map_err(|_| MongrelError::InvalidArgument("run page end is too large".into()))?;
2621        // Shared cache: serve the raw (on-disk / ciphertext) page bytes if
2622        // present, so concurrent readers never re-read or re-decrypt a page.
2623        let key = page_cache_key(self.table_id, self.header.run_id, column_id, page_seq);
2624        if let Some(cache) = &self.page_cache {
2625            if let Some(bytes) = cache.lock(&key).get(
2626                &key,
2627                crate::epoch::Snapshot::at(crate::epoch::Epoch(u64::MAX)),
2628            ) {
2629                return decrypt_or_passthrough(
2630                    self.cipher.as_deref(),
2631                    self.nonce_prefix,
2632                    column_id,
2633                    page_seq,
2634                    encrypted,
2635                    &bytes,
2636                );
2637            }
2638        }
2639        let buf = match &self.mmap {
2640            // Slice the mapping — no seek/read syscalls; the OS page cache fills
2641            // the pages on first touch.
2642            Some(m) => m
2643                .get(start..end)
2644                .ok_or_else(|| {
2645                    MongrelError::InvalidArgument("run page is outside the mapped file".into())
2646                })?
2647                .to_vec(),
2648            None => {
2649                self.file.seek(SeekFrom::Start(offset))?;
2650                let mut buf = vec![0u8; compressed_len as usize];
2651                self.file.read_exact(&mut buf)?;
2652                buf
2653            }
2654        };
2655        // Spill the raw bytes into the shared cache (post-read, pre-decrypt).
2656        if let Some(cache) = &self.page_cache {
2657            cache.lock(&key).insert(crate::page::CachedPage {
2658                committed_epoch: crate::epoch::Epoch(self.header.epoch_created),
2659                content_hash: key,
2660                bytes: bytes::Bytes::copy_from_slice(&buf),
2661            });
2662        }
2663        decrypt_or_passthrough(
2664            self.cipher.as_deref(),
2665            self.nonce_prefix,
2666            column_id,
2667            page_seq,
2668            encrypted,
2669            &buf,
2670        )
2671    }
2672
2673    /// `&self` version of [`Self::read_page`] restricted to the mmap-backed
2674    /// path, so page bytes can be read concurrently (rayon) without the
2675    /// `&mut self` file handle. Decryption (when enabled) uses the `Sync`
2676    /// cipher and a deterministic per-page nonce, so it is also parallel-safe.
2677    fn read_page_shared(&self, column_id: u16, page_seq: usize) -> Result<Vec<u8>> {
2678        let ch = self.find_header(column_id)?;
2679        let stat = ch
2680            .page_stats
2681            .get(page_seq)
2682            .ok_or_else(|| MongrelError::InvalidArgument("page seq out of range".into()))?;
2683        let encrypted = ch.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0;
2684        // Non-blocking probe of the shared cache: never block the rayon pool on
2685        // a contended lock. On a hit, avoid the mmap slice + decrypt entirely.
2686        let key = page_cache_key(self.table_id, self.header.run_id, column_id, page_seq);
2687        if let Some(cache) = &self.page_cache {
2688            if let Some(guard) = cache.try_lock(&key) {
2689                if let Some(bytes) = guard.try_get(
2690                    &key,
2691                    crate::epoch::Snapshot::at(crate::epoch::Epoch(u64::MAX)),
2692                ) {
2693                    return decrypt_or_passthrough(
2694                        self.cipher.as_deref(),
2695                        self.nonce_prefix,
2696                        column_id,
2697                        page_seq,
2698                        encrypted,
2699                        &bytes,
2700                    );
2701                }
2702            }
2703        }
2704        let mmap = self.mmap.as_ref().ok_or_else(|| {
2705            MongrelError::InvalidArgument("parallel page decode requires an mmap-backed run".into())
2706        })?;
2707        let end = stat
2708            .offset
2709            .checked_add(stat.compressed_len as u64)
2710            .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
2711        let start = usize::try_from(stat.offset)
2712            .map_err(|_| MongrelError::InvalidArgument("run page offset is too large".into()))?;
2713        let end = usize::try_from(end)
2714            .map_err(|_| MongrelError::InvalidArgument("run page end is too large".into()))?;
2715        let buf = mmap
2716            .get(start..end)
2717            .ok_or_else(|| {
2718                MongrelError::InvalidArgument("run page is outside the mapped file".into())
2719            })?
2720            .to_vec();
2721        // Opportunistic, non-blocking insert: populate the shared cache so later
2722        // readers (and encrypted re-reads) skip the mmap slice + decrypt. Never
2723        // block the rayon pool — if the lock is contended, just skip the insert.
2724        if let Some(cache) = &self.page_cache {
2725            if let Some(mut guard) = cache.try_lock(&key) {
2726                guard.insert(crate::page::CachedPage {
2727                    committed_epoch: crate::epoch::Epoch(self.header.epoch_created),
2728                    content_hash: key,
2729                    bytes: bytes::Bytes::copy_from_slice(&buf),
2730                });
2731            }
2732        }
2733        decrypt_or_passthrough(
2734            self.cipher.as_deref(),
2735            self.nonce_prefix,
2736            column_id,
2737            page_seq,
2738            encrypted,
2739            &buf,
2740        )
2741    }
2742
2743    /// Decode (and cache) a full column, concatenating all pages.
2744    fn column(&mut self, column_id: u16) -> Result<&[Value]> {
2745        // Uniform-epoch overlay: serve the `_epoch` column as a constant of the
2746        // real commit epoch instead of the placeholder stored on disk.
2747        if column_id == SYS_EPOCH {
2748            if let Some(ov) = self.epoch_override {
2749                if !self.col_cache.contains_key(&column_id) {
2750                    let n = self.row_count();
2751                    self.col_cache
2752                        .insert(column_id, vec![Value::Int64(ov.0 as i64); n]);
2753                }
2754                return Ok(self.col_cache.get(&column_id).unwrap().as_slice());
2755            }
2756        }
2757        if !self.col_cache.contains_key(&column_id) {
2758            let ty = self.resolve_type(column_id);
2759            let page_rows: Vec<usize> = {
2760                let ch = self.find_header(column_id)?;
2761                ch.page_stats.iter().map(|s| s.row_count as usize).collect()
2762            };
2763            let mut decoded: Vec<Value> = Vec::with_capacity(self.row_count());
2764            for (seq, &pr) in page_rows.iter().enumerate() {
2765                let page = self.read_page(column_id, seq)?;
2766                decoded.extend(columnar::decode_page(ty.clone(), &page, pr)?);
2767            }
2768            self.col_cache.insert(column_id, decoded);
2769        }
2770        Ok(self.col_cache.get(&column_id).unwrap().as_slice())
2771    }
2772
2773    /// Newest version of `row_id` with `epoch <= snapshot`, including tombstones
2774    /// (returned as a `Row` with `deleted=true`). `None` if no such version.
2775    ///
2776    /// Page-pruned: `SYS_ROW_ID` pages carry exact `first_row_id`/`last_row_id`
2777    /// bounds (rows are written in ascending `(RowId, Epoch)` order), so this
2778    /// decodes only the page(s) that can contain `row_id` instead of the whole
2779    /// column — the old implementation decoded every row's `SYS_ROW_ID` (and
2780    /// `SYS_EPOCH`) up front, making every single-row point lookup (the common
2781    /// case for a PK/unique check feeding insert/update/delete) pay a
2782    /// full-column decode. A row's version group can span at most two adjacent
2783    /// pages (split at a page boundary mid-group); `candidate_pages` below
2784    /// collects every page whose bounds include `row_id`, which is normally
2785    /// one page and two only in that split case.
2786    pub fn get_version(&mut self, row_id: RowId, snapshot: Epoch) -> Result<Option<(Epoch, Row)>> {
2787        match self.find_version_page(row_id, snapshot)? {
2788            None => Ok(None),
2789            Some((epoch, seq, local_index)) => Ok(Some((
2790                Epoch(epoch),
2791                self.materialize_in_page(seq, local_index)?,
2792            ))),
2793        }
2794    }
2795
2796    /// Page-pruned search for the newest version of `row_id` with `epoch <=
2797    /// snapshot`: `(epoch, page_seq, local_index)`, or `None` if no such
2798    /// version exists in this run. Factored out of [`Self::get_version`] so
2799    /// [`Self::get_version_column`] can reuse the exact same page-finding
2800    /// logic without re-deriving it.
2801    fn find_version_page(
2802        &mut self,
2803        row_id: RowId,
2804        snapshot: Epoch,
2805    ) -> Result<Option<(u64, usize, usize)>> {
2806        let n = self.row_count();
2807        if n == 0 {
2808            return Ok(None);
2809        }
2810        let target = row_id.0 as i64;
2811        let ch = self.find_header(SYS_ROW_ID)?;
2812        let mut page_start = 0u64;
2813        let candidate_pages: Vec<(usize, u64)> = ch // (page_seq, row offset of page start)
2814            .page_stats
2815            .iter()
2816            .enumerate()
2817            .filter_map(|(seq, s)| {
2818                let start = page_start;
2819                page_start += s.row_count as u64;
2820                (s.first_row_id <= row_id.0 && row_id.0 <= s.last_row_id).then_some((seq, start))
2821            })
2822            .collect();
2823        if candidate_pages.is_empty() {
2824            return Ok(None);
2825        }
2826        let ty = self.resolve_type(SYS_ROW_ID);
2827        let mut best: Option<(u64, usize, usize)> = None; // (epoch, page_seq, local index)
2828        for (seq, _page_row_start) in candidate_pages {
2829            let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2830            let row_ids =
2831                match self.decode_page_native_cached(ty.clone(), SYS_ROW_ID, seq, page_rows)? {
2832                    columnar::NativeColumn::Int64 { data, .. } => data,
2833                    _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
2834                };
2835            let local = match row_ids.binary_search(&target) {
2836                Ok(i) => i,
2837                Err(_) => continue,
2838            };
2839            let epoch_ty = self.resolve_type(SYS_EPOCH);
2840            let epochs =
2841                match self.decode_page_native_cached(epoch_ty, SYS_EPOCH, seq, page_rows)? {
2842                    columnar::NativeColumn::Int64 { data, .. } => data,
2843                    _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
2844                };
2845            // `local` is one match; the row-id's full version group is the
2846            // contiguous run of equal row-ids around it within this page.
2847            let mut lo = local;
2848            while lo > 0 && row_ids[lo - 1] == target {
2849                lo -= 1;
2850            }
2851            let mut hi = local;
2852            while hi + 1 < row_ids.len() && row_ids[hi + 1] == target {
2853                hi += 1;
2854            }
2855            for (i, &epoch) in epochs[lo..=hi].iter().enumerate() {
2856                let epoch = epoch as u64;
2857                if epoch <= snapshot.0 && best.map(|(be, ..)| epoch > be).unwrap_or(true) {
2858                    best = Some((epoch, seq, lo + i));
2859                }
2860            }
2861        }
2862        Ok(best)
2863    }
2864
2865    /// Like [`Self::get_version`], but decodes only `column_id` (plus the
2866    /// `SYS_DELETED` flag) instead of materializing every schema column via
2867    /// [`Self::materialize_in_page`]. For a wide schema this avoids paying to
2868    /// decode every other column's page just to read one value and throw the
2869    /// rest away — e.g. `Table::remove_hot_for_row`'s PK-only lookup, which
2870    /// used to pull the whole row (every column, every page) just for the
2871    /// primary key.
2872    pub fn get_version_column(
2873        &mut self,
2874        row_id: RowId,
2875        snapshot: Epoch,
2876        column_id: u16,
2877    ) -> Result<Option<(Epoch, bool, Option<Value>)>> {
2878        let Some((epoch, seq, local_index)) = self.find_version_page(row_id, snapshot)? else {
2879            return Ok(None);
2880        };
2881        let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2882        let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
2883            .iter()
2884            .map(|s| s.row_count as usize)
2885            .sum();
2886        let global_index = page_start + local_index;
2887        let native_at = |slf: &mut Self, cid: u16| -> Result<Option<Value>> {
2888            if !slf.dir.iter().any(|h| h.column_id == cid) {
2889                return Ok(None);
2890            }
2891            let ty = slf.resolve_type(cid);
2892            if !matches!(
2893                ty,
2894                TypeId::Bool
2895                    | TypeId::Int8
2896                    | TypeId::Int16
2897                    | TypeId::Int32
2898                    | TypeId::Int64
2899                    | TypeId::UInt8
2900                    | TypeId::UInt16
2901                    | TypeId::UInt32
2902                    | TypeId::UInt64
2903                    | TypeId::Float32
2904                    | TypeId::Float64
2905                    | TypeId::TimestampNanos
2906                    | TypeId::Date32
2907                    | TypeId::Bytes
2908            ) {
2909                return Ok(slf.column(cid)?.get(global_index).cloned());
2910            }
2911            Ok(slf
2912                .decode_page_native_cached(ty, cid, seq, page_rows)?
2913                .value_at(local_index))
2914        };
2915        let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
2916        let value = native_at(self, column_id)?;
2917        Ok(Some((Epoch(epoch), deleted, value)))
2918    }
2919
2920    /// Newest version epoch and tombstone flag without decoding a user column.
2921    pub fn get_version_visibility(
2922        &mut self,
2923        row_id: RowId,
2924        snapshot: Epoch,
2925    ) -> Result<Option<(Epoch, bool)>> {
2926        let Some((epoch, seq, local_index)) = self.find_version_page(row_id, snapshot)? else {
2927            return Ok(None);
2928        };
2929        let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2930        let deleted = match self.decode_page_native_cached(
2931            self.resolve_type(SYS_DELETED),
2932            SYS_DELETED,
2933            seq,
2934            page_rows,
2935        )? {
2936            columnar::NativeColumn::Bool { data, .. } => data[local_index] != 0,
2937            _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
2938        };
2939        Ok(Some((Epoch(epoch), deleted)))
2940    }
2941
2942    /// Build a `Row` from page `seq`'s data at `local_index`, decoding only
2943    /// that one page per column instead of [`Self::materialize`]'s whole-column
2944    /// `Vec<Value>` decode — used by [`Self::get_version`], which already knows
2945    /// the exact page from its page-pruned search. Only for scalar types with a
2946    /// [`columnar::NativeColumn`] representation; any other column (e.g. a
2947    /// fixed-size `Embedding`, which `NativeColumn` has no variant for) falls
2948    /// back to the whole-column path for that column specifically, so this is
2949    /// never wrong, only sometimes not faster.
2950    fn materialize_in_page(&mut self, seq: usize, local_index: usize) -> Result<Row> {
2951        let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2952        let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
2953            .iter()
2954            .map(|s| s.row_count as usize)
2955            .sum();
2956        let global_index = page_start + local_index;
2957        let native_at = |slf: &mut Self, column_id: u16| -> Result<Option<Value>> {
2958            // Absent column (schema evolution: added after this run was
2959            // written) reads as null, matching `materialize`'s own guard.
2960            if !slf.dir.iter().any(|h| h.column_id == column_id) {
2961                return Ok(None);
2962            }
2963            let ty = slf.resolve_type(column_id);
2964            if !matches!(
2965                ty,
2966                TypeId::Bool
2967                    | TypeId::Int8
2968                    | TypeId::Int16
2969                    | TypeId::Int32
2970                    | TypeId::Int64
2971                    | TypeId::UInt8
2972                    | TypeId::UInt16
2973                    | TypeId::UInt32
2974                    | TypeId::UInt64
2975                    | TypeId::Float32
2976                    | TypeId::Float64
2977                    | TypeId::TimestampNanos
2978                    | TypeId::Date32
2979                    | TypeId::Bytes
2980            ) {
2981                // Not a NativeColumn-representable scalar (e.g. Embedding) —
2982                // fall back to the always-correct whole-column decode.
2983                return Ok(slf.column(column_id)?.get(global_index).cloned());
2984            }
2985            Ok(slf
2986                .decode_page_native_cached(ty, column_id, seq, page_rows)?
2987                .value_at(local_index))
2988        };
2989        let row_id = RowId(match native_at(self, SYS_ROW_ID)? {
2990            Some(Value::Int64(x)) => x as u64,
2991            _ => 0,
2992        });
2993        let committed_epoch = Epoch(match native_at(self, SYS_EPOCH)? {
2994            Some(Value::Int64(x)) => x as u64,
2995            _ => 0,
2996        });
2997        let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
2998        let commit_ts = if self.has_column(SYS_COMMIT_TS) {
2999            decode_commit_ts_value(native_at(self, SYS_COMMIT_TS)?.as_ref())
3000        } else {
3001            None
3002        };
3003        let col_ids: Vec<u16> = self.schema.columns.iter().map(|c| c.id).collect();
3004        let mut columns = HashMap::new();
3005        for id in col_ids {
3006            columns.insert(id, native_at(self, id)?.unwrap_or(Value::Null));
3007        }
3008        Ok(Row {
3009            row_id,
3010            committed_epoch,
3011            columns,
3012            deleted,
3013            commit_ts,
3014        })
3015    }
3016
3017    /// Every row in the run (all versions), in `(RowId, Epoch)` order. Used by
3018    /// compaction, which must see every version to apply snapshot retention.
3019    pub fn all_rows(&mut self) -> Result<Vec<Row>> {
3020        let n = self.row_count();
3021        let mut out = Vec::with_capacity(n);
3022        for i in 0..n {
3023            out.push(self.materialize(i)?);
3024        }
3025        Ok(out)
3026    }
3027
3028    /// Every version with cooperative cancellation and a hard row bound.
3029    pub fn all_rows_controlled(
3030        &mut self,
3031        control: &crate::ExecutionControl,
3032        max_rows: usize,
3033    ) -> Result<Vec<Row>> {
3034        let n = self.row_count();
3035        if n > max_rows {
3036            return Err(MongrelError::ResourceLimitExceeded {
3037                resource: "controlled run row materialization",
3038                requested: n,
3039                limit: max_rows,
3040            });
3041        }
3042        let mut out = Vec::with_capacity(n);
3043        for i in 0..n {
3044            if i % 256 == 0 {
3045                control.checkpoint()?;
3046            }
3047            out.push(self.materialize(i)?);
3048        }
3049        control.checkpoint()?;
3050        Ok(out)
3051    }
3052
3053    /// Indices of the newest non-deleted version per `RowId` visible at
3054    /// `snapshot`, ascending. This is the columnar scan primitive: compute the
3055    /// visible set once (one pass over the row-id/epoch/deleted columns), then
3056    /// [`Self::gather_column`] each user column at these indices — no per-row
3057    /// `HashMap`/`Row` materialization.
3058    pub fn visible_indices(&mut self, snapshot: Epoch) -> Result<Vec<usize>> {
3059        let n = self.row_count();
3060        if n == 0 {
3061            return Ok(Vec::new());
3062        }
3063        let row_ids = self.column(SYS_ROW_ID)?.to_vec();
3064        let epochs = self.column(SYS_EPOCH)?.to_vec();
3065        let deleted = self.column(SYS_DELETED)?.to_vec();
3066        let mut best: HashMap<u64, (u64, usize)> = HashMap::new();
3067        for i in 0..n {
3068            let rid = int_at(&row_ids, i);
3069            let e = int_at(&epochs, i);
3070            if e > snapshot.0 {
3071                continue;
3072            }
3073            best.entry(rid)
3074                .and_modify(|(be, bi)| {
3075                    if e > *be {
3076                        *be = e;
3077                        *bi = i;
3078                    }
3079                })
3080                .or_insert((e, i));
3081        }
3082        let mut idxs: Vec<usize> = best.into_values().map(|(_, i)| i).collect();
3083        idxs.retain(|&i| !bool_at(&deleted, i));
3084        idxs.sort_unstable();
3085        Ok(idxs)
3086    }
3087
3088    /// Gather `column_id`'s values at the given indices (column cached). Used
3089    /// with [`Self::visible_indices`] for vectorized scans. A column absent from
3090    /// this run (e.g. added via schema evolution after the run was written)
3091    /// yields all-nulls.
3092    pub fn gather_column(&mut self, column_id: u16, indices: &[usize]) -> Result<Vec<Value>> {
3093        if !self.dir.iter().any(|h| h.column_id == column_id) {
3094            return Ok(vec![Value::Null; indices.len()]);
3095        }
3096        let col = self.column(column_id)?;
3097        Ok(indices
3098            .iter()
3099            .map(|&i| col.get(i).cloned().unwrap_or(Value::Null))
3100            .collect())
3101    }
3102
3103    /// Decode a column straight to a typed [`NativeColumn`] (no `Value`),
3104    /// concatenating all pages. A column absent from this run (schema evolution)
3105    /// yields an all-null column. Pages are decoded in parallel (rayon) when the
3106    /// run is mmap-backed and has more than one page; otherwise sequentially.
3107    pub fn column_native(&mut self, column_id: u16) -> Result<columnar::NativeColumn> {
3108        use rayon::prelude::*;
3109        if column_id == SYS_EPOCH {
3110            if let Some(ov) = self.epoch_override {
3111                return Ok(columnar::NativeColumn::int64_constant(
3112                    ov.0 as i64,
3113                    self.row_count(),
3114                ));
3115            }
3116        }
3117        let ty = self.resolve_type(column_id);
3118        let n = self.row_count();
3119        let Some(ch) = self.dir.iter().find(|h| h.column_id == column_id) else {
3120            return Ok(columnar::null_native(ty, n));
3121        };
3122        let page_count = ch.page_count as usize;
3123        let page_rows: Vec<usize> = ch.page_stats.iter().map(|s| s.row_count as usize).collect();
3124        if page_count == 0 {
3125            return Ok(columnar::null_native(ty, n));
3126        }
3127        let parts: Vec<columnar::NativeColumn> = if self.mmap.is_some() && page_count > 1 {
3128            // Parallel decode: each page is an independent region of the shared
3129            // mmap; the cipher (if any) is Sync. Spread the (CPU-bound) decode
3130            // across the rayon thread pool.
3131            let reader: &RunReader = self;
3132            (0..page_count)
3133                .into_par_iter()
3134                .map(|seq| {
3135                    let raw = reader.read_page_shared(column_id, seq)?;
3136                    columnar::decode_page_native(ty.clone(), &raw, page_rows[seq])
3137                })
3138                .collect::<Result<Vec<_>>>()?
3139        } else {
3140            let mut out = Vec::with_capacity(page_count);
3141            for (seq, &pr) in page_rows.iter().enumerate() {
3142                let page = self.read_page(column_id, seq)?;
3143                out.push(columnar::decode_page_native(ty.clone(), &page, pr)?);
3144            }
3145            out
3146        };
3147        Ok(columnar::NativeColumn::concat(&parts))
3148    }
3149
3150    /// Whether this reader is backed by a memory map (the prerequisite for the
3151    /// `&self` parallel decode paths). Readers on filesystems that reject mmap
3152    /// fall back to per-page `read()` and `has_mmap()` is false.
3153    pub fn has_mmap(&self) -> bool {
3154        self.mmap.is_some()
3155    }
3156
3157    /// `&self` variant of [`column_native`] for cross-column parallel scans
3158    /// (Phase 15.1). Requires the mmap backing (uses [`read_page_shared`], which
3159    /// is rayon-safe); callers without mmap use the `&mut` [`column_native`].
3160    /// Pages within the column decode in parallel when there is more than one,
3161    /// and `MADV_WILLNEED` is hinted up front so the kernel pre-faults the whole
3162    /// column's byte range (Phase 15.2) before the decode workers touch it.
3163    pub fn column_native_shared(&self, column_id: u16) -> Result<columnar::NativeColumn> {
3164        use rayon::prelude::*;
3165        if column_id == SYS_EPOCH {
3166            if let Some(ov) = self.epoch_override {
3167                return Ok(columnar::NativeColumn::int64_constant(
3168                    ov.0 as i64,
3169                    self.row_count(),
3170                ));
3171            }
3172        }
3173        let ty = self.resolve_type(column_id);
3174        let n = self.row_count();
3175        let Some(ch) = self.dir.iter().find(|h| h.column_id == column_id) else {
3176            return Ok(columnar::null_native(ty, n));
3177        };
3178        let page_count = ch.page_count as usize;
3179        let page_rows: Vec<usize> = ch.page_stats.iter().map(|s| s.row_count as usize).collect();
3180        if page_count == 0 {
3181            return Ok(columnar::null_native(ty, n));
3182        }
3183        // Phase 15.2: best-effort read-ahead. Tell the kernel to page-in the
3184        // column's full byte range before the workers fan out, overlapping the
3185        // disk I/O with the upcoming decode CPU.
3186        #[cfg(unix)]
3187        {
3188            if let (Some(m), Some(first)) = (&self.mmap, ch.page_stats.first()) {
3189                let start = first.offset as usize;
3190                let end = (ch.page_region_offset as usize) + (ch.page_region_len as usize);
3191                if end > start {
3192                    let _ = m.advise_range(memmap2::Advice::WillNeed, start, end - start);
3193                }
3194            }
3195        }
3196        let run_id = self.header.run_id;
3197        // Decode in parallel (cache probes use `try_lock` → no worker blocking).
3198        // Each item is the decoded page plus its key when it was a cache miss
3199        // (hits return `None` for the key so we don't re-insert/clone them).
3200        let mut parts_keys: Vec<(columnar::NativeColumn, Option<[u8; 32]>)> = if page_count > 1 {
3201            (0..page_count)
3202                .into_par_iter()
3203                .map(|seq| {
3204                    self.decode_page_cached(ty.clone(), column_id, seq, page_rows[seq], run_id)
3205                })
3206                .collect::<Result<Vec<_>>>()?
3207        } else {
3208            vec![self.decode_page_cached(ty, column_id, 0, page_rows[0], run_id)?]
3209        };
3210        // Sequentially cache the freshly-decoded pages — no parallel contention
3211        // on the insert, so every miss is reliably stored for the next scan.
3212        if let Some(cache) = &self.decoded_cache {
3213            for (col, key) in parts_keys.iter_mut() {
3214                if let Some(k) = key.take() {
3215                    cache.lock(&k).insert(k, Arc::new(col.clone()));
3216                }
3217            }
3218        }
3219        let parts: Vec<columnar::NativeColumn> = parts_keys.into_iter().map(|(c, _)| c).collect();
3220        Ok(columnar::NativeColumn::concat(&parts))
3221    }
3222
3223    /// Decode one page for the shared scan path, consulting the decoded-page
3224    /// cache first (Phase 15.4). Returns the decoded page plus `Some(key)` on a
3225    /// cache miss (so the caller can insert it) or `None` on a hit (already
3226    /// cached). Cache probes use `try_lock` so rayon workers never block.
3227    fn decode_page_cached(
3228        &self,
3229        ty: TypeId,
3230        column_id: u16,
3231        seq: usize,
3232        nrows: usize,
3233        run_id: u128,
3234    ) -> Result<(columnar::NativeColumn, Option<[u8; 32]>)> {
3235        let key = page_cache_key(self.table_id, run_id, column_id, seq);
3236        if let Some(cache) = &self.decoded_cache {
3237            if let Some(g) = cache.try_lock(&key) {
3238                if let Some(hit) = g.try_get(&key) {
3239                    return Ok(((*hit).clone(), None));
3240                }
3241            }
3242        }
3243        let raw = self.read_page_shared(column_id, seq)?;
3244        let col = columnar::decode_page_native(ty, &raw, nrows)?;
3245        Ok((col, Some(key)))
3246    }
3247
3248    /// [`Self::decode_page_cached`], but for the sequential point-lookup paths
3249    /// (`find_version_page`, `materialize_in_page`, `get_version_column`) via
3250    /// [`Self::read_page`] (handles the non-mmap-backed fallback) instead of
3251    /// [`Self::read_page_shared`] (mmap-only, for the parallel rayon scan
3252    /// path). No rayon pool to avoid blocking here, so a plain `.lock()` is
3253    /// fine — unlike the scan path's `try_lock`, this always consults the
3254    /// cache rather than skipping it under contention. Without this, every
3255    /// point lookup re-decompressed its page from scratch even when a prior
3256    /// lookup had just decoded the exact same page (the dominant remaining
3257    /// cost measured for `remove_hot_for_row`'s on-disk path).
3258    fn decode_page_native_cached(
3259        &mut self,
3260        ty: TypeId,
3261        column_id: u16,
3262        seq: usize,
3263        nrows: usize,
3264    ) -> Result<columnar::NativeColumn> {
3265        let key = page_cache_key(self.table_id, self.header.run_id, column_id, seq);
3266        if let Some(cache) = &self.decoded_cache {
3267            if let Some(hit) = cache.lock(&key).try_get(&key) {
3268                return Ok((*hit).clone());
3269            }
3270        }
3271        let raw = self.read_page(column_id, seq)?;
3272        let col = columnar::decode_page_native(ty, &raw, nrows)?;
3273        if let Some(cache) = &self.decoded_cache {
3274            cache
3275                .lock(&key)
3276                .insert(key, std::sync::Arc::new(col.clone()));
3277        }
3278        Ok(col)
3279    }
3280
3281    /// Row ids whose Int64 value is in `[lo, hi]`, **skipping pages whose
3282    /// `[min,max]` stat excludes the range** (Parquet-style page-index pruning).
3283    /// Nulls are excluded. Used by `Table::query_columns_native` to serve
3284    /// `Condition::Range` without decoding every page.
3285    pub fn range_row_ids_i64(
3286        &mut self,
3287        column_id: u16,
3288        lo: i64,
3289        hi: i64,
3290    ) -> Result<std::collections::HashSet<u64>> {
3291        Ok(self
3292            .range_row_id_set_i64(column_id, lo, hi)?
3293            .into_sorted_vec()
3294            .into_iter()
3295            .collect())
3296    }
3297
3298    pub(crate) fn range_row_id_set_i64(
3299        &mut self,
3300        column_id: u16,
3301        lo: i64,
3302        hi: i64,
3303    ) -> Result<RowIdSet> {
3304        let info: Vec<(Option<i64>, Option<i64>, usize)> =
3305            match self.dir.iter().find(|h| h.column_id == column_id) {
3306                Some(ch) => ch
3307                    .page_stats
3308                    .iter()
3309                    .map(|s| {
3310                        (
3311                            be_i64(s.min.as_deref()),
3312                            be_i64(s.max.as_deref()),
3313                            s.row_count as usize,
3314                        )
3315                    })
3316                    .collect(),
3317                None => return Ok(RowIdSet::empty()),
3318            };
3319        // Encrypted columns are pruneable only when this run carries the
3320        // decrypted stats envelope (overlaid at open). Without one (a run
3321        // whose writer recorded no stats at all), a missing min/max means
3322        // "unknown" — never prune — whereas with the envelope (and always for
3323        // plaintext runs) a missing min/max means an all-null page.
3324        let stats_pruneable =
3325            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3326        let clean_contiguous = self.clean_contiguous_row_ids();
3327        let mut out = Vec::new();
3328        let mut page_start = 0usize;
3329        for (seq, (mn, mx, nrows)) in info.into_iter().enumerate() {
3330            let current_page_start = page_start;
3331            page_start += nrows;
3332            // Skip pages that cannot contain a match (or are all-null).
3333            let skip = stats_pruneable
3334                && match (mn, mx) {
3335                    (Some(mn), Some(mx)) => mx < lo || mn > hi,
3336                    _ => true,
3337                };
3338            if skip {
3339                continue;
3340            }
3341            let val_page = self.read_page(column_id, seq)?;
3342            let vals =
3343                columnar::decode_page_native(self.resolve_type(column_id), &val_page, nrows)?;
3344            if let columnar::NativeColumn::Int64 { data: v, validity } = vals {
3345                if clean_contiguous {
3346                    for (i, val) in v.iter().enumerate() {
3347                        if columnar::validity_bit(&validity, i) && *val >= lo && *val <= hi {
3348                            out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3349                        }
3350                    }
3351                } else {
3352                    let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3353                    let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3354                    if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3355                        for (i, val) in v.iter().enumerate() {
3356                            if columnar::validity_bit(&validity, i) && *val >= lo && *val <= hi {
3357                                out.push(r[i] as u64);
3358                            }
3359                        }
3360                    }
3361                }
3362            }
3363        }
3364        Ok(RowIdSet::from_unsorted(out))
3365    }
3366
3367    /// Float64 analogue of [`Self::range_row_ids_i64`] with per-bound
3368    /// inclusivity, for `Condition::RangeF64`.
3369    pub fn range_row_ids_f64(
3370        &mut self,
3371        column_id: u16,
3372        lo: f64,
3373        lo_inclusive: bool,
3374        hi: f64,
3375        hi_inclusive: bool,
3376    ) -> Result<std::collections::HashSet<u64>> {
3377        Ok(self
3378            .range_row_id_set_f64(column_id, lo, lo_inclusive, hi, hi_inclusive)?
3379            .into_sorted_vec()
3380            .into_iter()
3381            .collect())
3382    }
3383
3384    pub(crate) fn range_row_id_set_f64(
3385        &mut self,
3386        column_id: u16,
3387        lo: f64,
3388        lo_inclusive: bool,
3389        hi: f64,
3390        hi_inclusive: bool,
3391    ) -> Result<RowIdSet> {
3392        let info: Vec<(Option<f64>, Option<f64>, usize)> =
3393            match self.dir.iter().find(|h| h.column_id == column_id) {
3394                Some(ch) => ch
3395                    .page_stats
3396                    .iter()
3397                    .map(|s| {
3398                        (
3399                            be_f64(s.min.as_deref()),
3400                            be_f64(s.max.as_deref()),
3401                            s.row_count as usize,
3402                        )
3403                    })
3404                    .collect(),
3405                None => return Ok(RowIdSet::empty()),
3406            };
3407        // Encrypted columns are pruneable only when this run carries the
3408        // decrypted stats envelope (overlaid at open). Without one (a run
3409        // whose writer recorded no stats at all), a missing min/max means
3410        // "unknown" — never prune — whereas with the envelope (and always for
3411        // plaintext runs) a missing min/max means an all-null page.
3412        let stats_pruneable =
3413            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3414        let clean_contiguous = self.clean_contiguous_row_ids();
3415        let mut out = Vec::new();
3416        let mut page_start = 0usize;
3417        for (seq, (mn, mx, nrows)) in info.into_iter().enumerate() {
3418            let current_page_start = page_start;
3419            page_start += nrows;
3420            // A page can be dropped iff every value fails the predicate, i.e. the
3421            // largest fails the lo-test or the smallest fails the hi-test.
3422            let skip = stats_pruneable
3423                && match (mn, mx) {
3424                    (Some(mn), Some(mx)) => {
3425                        let skip_lo = mx < lo || (!lo_inclusive && mx == lo);
3426                        let skip_hi = mn > hi || (!hi_inclusive && mn == hi);
3427                        skip_lo || skip_hi
3428                    }
3429                    _ => true,
3430                };
3431            if skip {
3432                continue;
3433            }
3434            let val_page = self.read_page(column_id, seq)?;
3435            let vals = columnar::decode_page_native(TypeId::Float64, &val_page, nrows)?;
3436            if let columnar::NativeColumn::Float64 { data: v, validity } = vals {
3437                if clean_contiguous {
3438                    for (i, val) in v.iter().enumerate() {
3439                        if !columnar::validity_bit(&validity, i) || val.is_nan() {
3440                            continue;
3441                        }
3442                        let ok_lo = if lo_inclusive { *val >= lo } else { *val > lo };
3443                        let ok_hi = if hi_inclusive { *val <= hi } else { *val < hi };
3444                        if ok_lo && ok_hi {
3445                            out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3446                        }
3447                    }
3448                } else {
3449                    let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3450                    let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3451                    if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3452                        for (i, val) in v.iter().enumerate() {
3453                            if !columnar::validity_bit(&validity, i) || val.is_nan() {
3454                                continue;
3455                            }
3456                            let ok_lo = if lo_inclusive { *val >= lo } else { *val > lo };
3457                            let ok_hi = if hi_inclusive { *val <= hi } else { *val < hi };
3458                            if ok_lo && ok_hi {
3459                                out.push(r[i] as u64);
3460                            }
3461                        }
3462                    }
3463                }
3464            }
3465        }
3466        Ok(RowIdSet::from_unsorted(out))
3467    }
3468
3469    /// Page-pruned row-id set for `IS NULL` / `IS NOT NULL` on `column_id`.
3470    /// Skips pages whose `null_count` makes a match impossible (no nulls for
3471    /// `IS NULL`, all-nulls for `IS NOT NULL`), then decodes the validity bitmap
3472    /// of surviving pages to pinpoint matching rows.
3473    pub(crate) fn null_row_id_set(&mut self, column_id: u16, want_nulls: bool) -> Result<RowIdSet> {
3474        let stats: Vec<(usize, usize)> = match self.dir.iter().find(|h| h.column_id == column_id) {
3475            Some(ch) => ch
3476                .page_stats
3477                .iter()
3478                .map(|s| (s.null_count as usize, s.row_count as usize))
3479                .collect(),
3480            None => return Ok(RowIdSet::empty()),
3481        };
3482        let ty = self.resolve_type(column_id);
3483        let clean_contiguous = self.clean_contiguous_row_ids();
3484        let mut out = Vec::new();
3485        let mut page_start = 0usize;
3486        for (seq, (null_count, nrows)) in stats.into_iter().enumerate() {
3487            let current_page_start = page_start;
3488            page_start += nrows;
3489            // Skip pages that cannot match.
3490            if want_nulls && null_count == 0 {
3491                continue;
3492            }
3493            if !want_nulls && null_count == nrows {
3494                continue;
3495            }
3496            let val_page = self.read_page(column_id, seq)?;
3497            let col = columnar::decode_page_native(ty.clone(), &val_page, nrows)?;
3498            let validity = col.validity();
3499            if clean_contiguous {
3500                for i in 0..nrows {
3501                    let is_null = !columnar::validity_bit(validity, i);
3502                    if is_null == want_nulls {
3503                        out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3504                    }
3505                }
3506            } else {
3507                let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3508                let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3509                if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3510                    for (i, &rid) in r.iter().enumerate().take(nrows) {
3511                        let is_null = !columnar::validity_bit(validity, i);
3512                        if is_null == want_nulls {
3513                            out.push(rid as u64);
3514                        }
3515                    }
3516                }
3517            }
3518        }
3519        Ok(RowIdSet::from_unsorted(out))
3520    }
3521
3522    pub fn visible_indices_native(&mut self, snapshot: Epoch) -> Result<Vec<usize>> {
3523        let n = self.row_count();
3524        if n == 0 {
3525            return Ok(Vec::new());
3526        }
3527        let (row_ids, epochs, deleted) = self.system_columns_native()?;
3528        let mut best: HashMap<u64, (u64, usize)> = HashMap::new();
3529        for i in 0..n {
3530            let rid = row_ids[i] as u64;
3531            let e = epochs[i] as u64;
3532            if e > snapshot.0 {
3533                continue;
3534            }
3535            best.entry(rid)
3536                .and_modify(|(be, bi)| {
3537                    if e > *be {
3538                        *be = e;
3539                        *bi = i;
3540                    }
3541                })
3542                .or_insert((e, i));
3543        }
3544        let mut idxs: Vec<usize> = best.into_values().map(|(_, i)| i).collect();
3545        idxs.retain(|&i| deleted[i] == 0);
3546        idxs.sort_unstable();
3547        Ok(idxs)
3548    }
3549
3550    /// Page-pruned, **MVCC-visible** Int64 range resolution (Phase 16.3).
3551    ///
3552    /// Like [`Self::range_row_ids_i64`] (skips pages whose `[min,max]` excludes
3553    /// `[lo, hi]`) but restricts the output to the newest non-deleted version per
3554    /// `RowId` visible at `snapshot`. This is the layout-independent range
3555    /// primitive: correct under any memtable / multi-run / deletion-vector state,
3556    /// so the engine no longer has to fall back to a full-column decode when the
3557    /// "single clean run" invariant doesn't hold. Nulls are excluded.
3558    pub fn range_row_ids_visible_i64(
3559        &mut self,
3560        column_id: u16,
3561        lo: i64,
3562        hi: i64,
3563        snapshot: Epoch,
3564    ) -> Result<Vec<u64>> {
3565        let stats: Vec<(Option<i64>, Option<i64>, usize)> = match self.column_page_stats(column_id)
3566        {
3567            Some(s) => s
3568                .iter()
3569                .map(|st| {
3570                    (
3571                        be_i64(st.min.as_deref()),
3572                        be_i64(st.max.as_deref()),
3573                        st.row_count as usize,
3574                    )
3575                })
3576                .collect(),
3577            None => return Ok(Vec::new()),
3578        };
3579        // Encrypted columns are pruneable only when this run carries the
3580        // decrypted stats envelope (overlaid at open). Without one (a run
3581        // whose writer recorded no stats at all), a missing min/max means
3582        // "unknown" — never prune — whereas with the envelope (and always for
3583        // plaintext runs) a missing min/max means an all-null page.
3584        let stats_pruneable =
3585            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3586        let (positions, rids) = self.visible_positions_with_rids(snapshot)?;
3587        let mut out: Vec<u64> = Vec::new();
3588        let mut vis = 0usize;
3589        let mut page_start = 0usize;
3590        for (seq, &(mn, mx, nrows)) in stats.iter().enumerate() {
3591            let page_end = page_start + nrows;
3592            // A page can be dropped iff every value fails the predicate.
3593            let skip = stats_pruneable
3594                && match (mn, mx) {
3595                    (Some(mn), Some(mx)) => mx < lo || mn > hi,
3596                    _ => true, // all-null / no stats → nulls never match
3597                };
3598            if !skip {
3599                let val_page = self.read_page(column_id, seq)?;
3600                let vals = columnar::decode_page_native(TypeId::Int64, &val_page, nrows)?;
3601                if let columnar::NativeColumn::Int64 { data: v, validity } = vals {
3602                    while vis < positions.len() && positions[vis] < page_end {
3603                        let local = positions[vis] - page_start;
3604                        if columnar::validity_bit(&validity, local)
3605                            && v[local] >= lo
3606                            && v[local] <= hi
3607                        {
3608                            out.push(rids[vis] as u64);
3609                        }
3610                        vis += 1;
3611                    }
3612                }
3613            } else {
3614                while vis < positions.len() && positions[vis] < page_end {
3615                    vis += 1;
3616                }
3617            }
3618            page_start = page_end;
3619        }
3620        Ok(out)
3621    }
3622
3623    /// Float64 analogue of [`Self::range_row_ids_visible_i64`] with per-bound
3624    /// inclusivity (Phase 16.3).
3625    pub fn range_row_ids_visible_f64(
3626        &mut self,
3627        column_id: u16,
3628        lo: f64,
3629        lo_inclusive: bool,
3630        hi: f64,
3631        hi_inclusive: bool,
3632        snapshot: Epoch,
3633    ) -> Result<Vec<u64>> {
3634        let stats: Vec<(Option<f64>, Option<f64>, usize)> = match self.column_page_stats(column_id)
3635        {
3636            Some(s) => s
3637                .iter()
3638                .map(|st| {
3639                    (
3640                        be_f64(st.min.as_deref()),
3641                        be_f64(st.max.as_deref()),
3642                        st.row_count as usize,
3643                    )
3644                })
3645                .collect(),
3646            None => return Ok(Vec::new()),
3647        };
3648        // Encrypted columns are pruneable only when this run carries the
3649        // decrypted stats envelope (overlaid at open). Without one (a run
3650        // whose writer recorded no stats at all), a missing min/max means
3651        // "unknown" — never prune — whereas with the envelope (and always for
3652        // plaintext runs) a missing min/max means an all-null page.
3653        let stats_pruneable =
3654            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3655        let (positions, rids) = self.visible_positions_with_rids(snapshot)?;
3656        let mut out: Vec<u64> = Vec::new();
3657        let mut vis = 0usize;
3658        let mut page_start = 0usize;
3659        for (seq, &(mn, mx, nrows)) in stats.iter().enumerate() {
3660            let page_end = page_start + nrows;
3661            let skip = stats_pruneable
3662                && match (mn, mx) {
3663                    (Some(mn), Some(mx)) => {
3664                        let skip_lo = mx < lo || (!lo_inclusive && mx == lo);
3665                        let skip_hi = mn > hi || (!hi_inclusive && mn == hi);
3666                        skip_lo || skip_hi
3667                    }
3668                    _ => true,
3669                };
3670            if !skip {
3671                let val_page = self.read_page(column_id, seq)?;
3672                let vals = columnar::decode_page_native(TypeId::Float64, &val_page, nrows)?;
3673                if let columnar::NativeColumn::Float64 { data: v, validity } = vals {
3674                    while vis < positions.len() && positions[vis] < page_end {
3675                        let local = positions[vis] - page_start;
3676                        if columnar::validity_bit(&validity, local) && !v[local].is_nan() {
3677                            let val = v[local];
3678                            let ok_lo = if lo_inclusive { val >= lo } else { val > lo };
3679                            let ok_hi = if hi_inclusive { val <= hi } else { val < hi };
3680                            if ok_lo && ok_hi {
3681                                out.push(rids[vis] as u64);
3682                            }
3683                        }
3684                        vis += 1;
3685                    }
3686                }
3687            } else {
3688                while vis < positions.len() && positions[vis] < page_end {
3689                    vis += 1;
3690                }
3691            }
3692            page_start = page_end;
3693        }
3694        Ok(out)
3695    }
3696
3697    /// MVCC-visible `IS NULL` / `IS NOT NULL` resolution. Follows the same
3698    /// page-stat-pruned + visible-positions pattern as
3699    /// [`Self::range_row_ids_visible_i64`], but checks the validity bitmap
3700    /// instead of a value range. Pages with no nulls (for IS NULL) or all-nulls
3701    /// (for IS NOT NULL) are skipped.
3702    pub fn null_row_ids_visible(
3703        &mut self,
3704        column_id: u16,
3705        want_nulls: bool,
3706        snapshot: Epoch,
3707    ) -> Result<Vec<u64>> {
3708        let stats: Vec<(usize, usize)> = match self.column_page_stats(column_id) {
3709            Some(s) => s
3710                .iter()
3711                .map(|st| (st.null_count as usize, st.row_count as usize))
3712                .collect(),
3713            None => return Ok(Vec::new()),
3714        };
3715        let ty = self.resolve_type(column_id);
3716        let (positions, rids) = self.visible_positions_with_rids(snapshot)?;
3717        let mut out: Vec<u64> = Vec::new();
3718        let mut vis = 0usize;
3719        let mut page_start = 0usize;
3720        for (seq, &(null_count, nrows)) in stats.iter().enumerate() {
3721            let page_end = page_start + nrows;
3722            let skip = (want_nulls && null_count == 0) || (!want_nulls && null_count == nrows);
3723            if !skip {
3724                let val_page = self.read_page(column_id, seq)?;
3725                let col = columnar::decode_page_native(ty.clone(), &val_page, nrows)?;
3726                let validity = col.validity();
3727                while vis < positions.len() && positions[vis] < page_end {
3728                    let local = positions[vis] - page_start;
3729                    let is_null = !columnar::validity_bit(validity, local);
3730                    if is_null == want_nulls {
3731                        out.push(rids[vis] as u64);
3732                    }
3733                    vis += 1;
3734                }
3735            } else {
3736                while vis < positions.len() && positions[vis] < page_end {
3737                    vis += 1;
3738                }
3739            }
3740            page_start = page_end;
3741        }
3742        Ok(out)
3743    }
3744
3745    /// tombstones excluded) paired with each position's `RowId`, in one pass.
3746    /// Used by [`crate::cursor::NativePageCursor`] to map survivors to pages
3747    /// without re-decoding the system columns.
3748    pub fn visible_positions_with_rids(
3749        &mut self,
3750        snapshot: Epoch,
3751    ) -> Result<(Vec<usize>, Vec<i64>)> {
3752        let n = self.row_count();
3753        if n == 0 {
3754            return Ok((Vec::new(), Vec::new()));
3755        }
3756        // Clean-run fast path (Phase 16.3c): one version per RowId, no
3757        // tombstones, ascending row_ids ⟹ every position is the newest (and
3758        // only) visible version. Skip decoding epoch/deleted and the group-
3759        // collapse loop; just decode row_ids (needed for survivor↔position
3760        // mapping) and return identity positions [0..n).
3761        // A uniform-epoch overlay must still gate by snapshot, so skip the clean
3762        // fast path when an override is active (defensive: spill runs are never
3763        // written clean).
3764        if self.is_clean()
3765            && self.epoch_override.is_none()
3766            && self.header.epoch_created <= snapshot.0
3767        {
3768            let row_ids = match self.column_native_shared(SYS_ROW_ID)? {
3769                columnar::NativeColumn::Int64 { data, .. } => data,
3770                _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
3771            };
3772            let positions: Vec<usize> = (0..n).collect();
3773            return Ok((positions, row_ids));
3774        }
3775        let (row_ids, epochs, deleted) = self.system_columns_native()?;
3776        // Runs are written in `(RowId, Epoch)` ascending order (Bε-tree
3777        // composite key), so same-rid positions are consecutive with the
3778        // newest (highest epoch) last. One linear pass keeps the last position
3779        // per rid with `epoch <= snapshot`, dropping tombstones — no HashMap,
3780        // no per-row hashing, sequential memory access. (Phase 16.3.)
3781        //
3782        // Invariant: every write path (memtable drain, mutable-run spill,
3783        // bulk_load's sequential alloc) produces runs in this order; if a path
3784        // ever wrote an unsorted run this would under-count (only consecutive
3785        // dup groups merge) and must be reverted to the HashMap form.
3786        let mut idxs: Vec<usize> = Vec::new();
3787        let mut i = 0;
3788        while i < n {
3789            let rid = row_ids[i] as u64;
3790            // Walk the consecutive rid group; epochs rise within it, so the
3791            // last position with epoch <= snapshot is the newest visible one.
3792            let mut best: Option<usize> = None;
3793            let mut j = i;
3794            while j < n && row_ids[j] as u64 == rid {
3795                if epochs[j] as u64 <= snapshot.0 {
3796                    best = Some(j);
3797                }
3798                j += 1;
3799            }
3800            if let Some(b) = best {
3801                if deleted[b] == 0 {
3802                    idxs.push(b);
3803                }
3804            }
3805            i = j;
3806        }
3807        // Groups are processed in rid-ascending = position-ascending order.
3808        let rids: Vec<i64> = idxs.iter().map(|&k| row_ids[k]).collect();
3809        Ok((idxs, rids))
3810    }
3811
3812    /// Row count of each PAX page of `column_id`, in page order. Every column
3813    /// in a run shares the same PAX row partition, so this yields the table's
3814    /// page layout (cumulative sums give page start offsets).
3815    pub fn page_row_counts(&self, column_id: u16) -> Result<Vec<usize>> {
3816        Ok(self
3817            .find_header(column_id)?
3818            .page_stats
3819            .iter()
3820            .map(|s| s.row_count as usize)
3821            .collect())
3822    }
3823
3824    /// Whether this run stores `column_id` (false for a column added via
3825    /// `add_column` after the run was written — those read as all-null).
3826    pub fn has_column(&self, column_id: u16) -> bool {
3827        self.dir.iter().any(|h| h.column_id == column_id)
3828    }
3829
3830    /// The per-page [`PageStat`]s for `column_id`, or `None` if the column is
3831    /// absent from this run (schema evolution). Used to compute exact column
3832    /// min/max/null_count for the analytical aggregate fast path.
3833    pub fn column_page_stats(&self, column_id: u16) -> Option<&[crate::page::PageStat]> {
3834        self.dir
3835            .iter()
3836            .find(|h| h.column_id == column_id)
3837            .map(|ch| ch.page_stats.as_slice())
3838    }
3839
3840    /// Decode the system columns once, as typed buffers. Uses the shared
3841    /// parallel + decoded-page-cached path (`column_native_shared`) so the
3842    /// row-id/epoch/deleted pages decode concurrently and stay cached across
3843    /// queries — MVCC visibility resolution is on every scan's hot path.
3844    pub(crate) fn system_columns_native(&mut self) -> Result<(Vec<i64>, Vec<i64>, Vec<u8>)> {
3845        let row_ids = match self.column_native_shared(SYS_ROW_ID)? {
3846            columnar::NativeColumn::Int64 { data, .. } => data,
3847            _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
3848        };
3849        let epochs = match self.column_native_shared(SYS_EPOCH)? {
3850            columnar::NativeColumn::Int64 { data, .. } => data,
3851            _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
3852        };
3853        let deleted = match self.column_native_shared(SYS_DELETED)? {
3854            columnar::NativeColumn::Bool { data, .. } => data,
3855            _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
3856        };
3857        Ok((row_ids, epochs, deleted))
3858    }
3859
3860    /// Newest visible version per `RowId` at `snapshot`, **including
3861    /// tombstones** (as `Row`s with `deleted=true`). Ascending `RowId`. Used by
3862    /// the engine to merge versions across runs and the memtable.
3863    ///
3864    /// HLC stamps are restored when [`SYS_COMMIT_TS`] is present (P0.5-T3);
3865    /// legacy runs without the column materialise `commit_ts: None`. Callers
3866    /// that hold a full [`crate::epoch::Snapshot`] still apply
3867    /// [`crate::epoch::Snapshot::observes_row`].
3868    pub fn visible_versions(&mut self, snapshot: Epoch) -> Result<Vec<Row>> {
3869        let n = self.row_count();
3870        if n == 0 {
3871            return Ok(Vec::new());
3872        }
3873        let row_ids = self.column(SYS_ROW_ID)?.to_vec();
3874        let epochs = self.column(SYS_EPOCH)?.to_vec();
3875        let mut best: HashMap<u64, (u64, usize)> = HashMap::new();
3876        for i in 0..n {
3877            let rid = int_at(&row_ids, i);
3878            let epoch = int_at(&epochs, i);
3879            if epoch > snapshot.0 {
3880                continue;
3881            }
3882            best.entry(rid)
3883                .and_modify(|e| {
3884                    if epoch > e.0 {
3885                        *e = (epoch, i);
3886                    }
3887                })
3888                .or_insert((epoch, i));
3889        }
3890        let mut picks: Vec<usize> = best.into_values().map(|(_, i)| i).collect();
3891        picks.sort();
3892        let mut out = Vec::with_capacity(picks.len());
3893        for i in picks {
3894            out.push(self.materialize(i)?);
3895        }
3896        Ok(out)
3897    }
3898
3899    /// All non-deleted rows visible at `snapshot`. Ascending `RowId`.
3900    pub fn visible_rows(&mut self, snapshot: Epoch) -> Result<Vec<Row>> {
3901        Ok(self
3902            .visible_versions(snapshot)?
3903            .into_iter()
3904            .filter(|r| !r.deleted)
3905            .collect())
3906    }
3907
3908    pub(crate) fn materialize(&mut self, index: usize) -> Result<Row> {
3909        let row_id = RowId(int_at(self.column(SYS_ROW_ID)?, index));
3910        let epoch = Epoch(int_at(self.column(SYS_EPOCH)?, index));
3911        let deleted = bool_at(self.column(SYS_DELETED)?, index);
3912        let commit_ts = self.commit_ts_at(index)?;
3913        let col_ids: Vec<u16> = self.schema.columns.iter().map(|c| c.id).collect();
3914        let mut columns = HashMap::new();
3915        for id in col_ids {
3916            let val = if self.dir.iter().any(|h| h.column_id == id) {
3917                self.column(id)?.get(index).cloned().unwrap_or(Value::Null)
3918            } else {
3919                // Column added via schema evolution after this run was written.
3920                Value::Null
3921            };
3922            columns.insert(id, val);
3923        }
3924        Ok(Row {
3925            row_id,
3926            committed_epoch: epoch,
3927            columns,
3928            deleted,
3929            commit_ts,
3930        })
3931    }
3932
3933    /// Batched row materialization (Phase 16.3b finish): decode each system +
3934    /// user column **once** via the typed, page-cached `column_native` path and
3935    /// gather only the requested `indices` straight into `Row`s. This replaces
3936    /// N independent `materialize` calls, each of which rebuilt a full-column
3937    /// `Vec<Value>` (heap-allocating one `Value` per row) and then `.cloned()`
3938    /// a single slot. Exact semantics retained: schema-evolved columns absent
3939    /// from this run read `Value::Null`; deleted rows are still returned (the
3940    /// caller filters them).
3941    pub(crate) fn materialize_batch(&mut self, indices: &[usize]) -> Result<Vec<Row>> {
3942        if indices.is_empty() {
3943            return Ok(Vec::new());
3944        }
3945        use std::collections::HashMap;
3946        let rid_col = self.column_native_shared(SYS_ROW_ID)?;
3947        let epoch_col = self.column_native_shared(SYS_EPOCH)?;
3948        let del_col = self.column_native_shared(SYS_DELETED)?;
3949        let commit_ts_col = if self.has_column(SYS_COMMIT_TS) {
3950            Some(self.column_native_shared(SYS_COMMIT_TS)?)
3951        } else {
3952            None
3953        };
3954        let mut user: HashMap<u16, columnar::NativeColumn> = HashMap::new();
3955        let present: Vec<u16> = self
3956            .schema
3957            .columns
3958            .iter()
3959            .map(|c| c.id)
3960            .filter(|id| self.dir.iter().any(|h| h.column_id == *id))
3961            .collect();
3962        for id in present {
3963            user.insert(id, self.column_native(id)?);
3964        }
3965        let i64_at = |col: &columnar::NativeColumn, i: usize| -> i64 {
3966            match col {
3967                columnar::NativeColumn::Int64 { data, .. } => data.get(i).copied().unwrap_or(0),
3968                _ => 0,
3969            }
3970        };
3971        let bool_at_native = |col: &columnar::NativeColumn, i: usize| -> bool {
3972            match col {
3973                columnar::NativeColumn::Bool { data, .. } => {
3974                    data.get(i).copied().map(|b| b != 0).unwrap_or(false)
3975                }
3976                _ => false,
3977            }
3978        };
3979        let mut rows = Vec::with_capacity(indices.len());
3980        for &idx in indices {
3981            let row_id = RowId(i64_at(&rid_col, idx) as u64);
3982            let epoch = Epoch(i64_at(&epoch_col, idx) as u64);
3983            let deleted = bool_at_native(&del_col, idx);
3984            let commit_ts = commit_ts_col
3985                .as_ref()
3986                .and_then(|col| decode_commit_ts_value(col.value_at(idx).as_ref()));
3987            let mut columns = HashMap::with_capacity(self.schema.columns.len());
3988            for cdef in self.schema.columns.iter() {
3989                let val = match user.get(&cdef.id) {
3990                    Some(col) => col.value_at(idx).unwrap_or(Value::Null),
3991                    None => Value::Null,
3992                };
3993                columns.insert(cdef.id, val);
3994            }
3995            rows.push(Row {
3996                row_id,
3997                committed_epoch: epoch,
3998                columns,
3999                deleted,
4000                commit_ts,
4001            });
4002        }
4003        Ok(rows)
4004    }
4005}
4006
4007fn int_at(vals: &[Value], i: usize) -> u64 {
4008    match vals.get(i) {
4009        Some(Value::Int64(x)) => *x as u64,
4010        _ => 0,
4011    }
4012}
4013
4014fn bool_at(vals: &[Value], i: usize) -> bool {
4015    matches!(vals.get(i), Some(Value::Bool(true)))
4016}
4017
4018#[cfg(test)]
4019mod tests {
4020    use super::*;
4021    use crate::columnar::NativeColumn;
4022    use crate::memtable::Value;
4023    use crate::rowid::RowId;
4024    use crate::schema::{ColumnDef, ColumnFlags};
4025    use tempfile::tempdir;
4026
4027    fn schema() -> Schema {
4028        Schema {
4029            schema_id: 1,
4030            columns: vec![
4031                ColumnDef {
4032                    id: 1,
4033                    name: "id".into(),
4034                    ty: TypeId::Int64,
4035                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
4036                    default_value: None,
4037                    embedding_source: None,
4038                },
4039                ColumnDef {
4040                    id: 2,
4041                    name: "name".into(),
4042                    ty: TypeId::Bytes,
4043                    flags: ColumnFlags::empty(),
4044                    default_value: None,
4045                    embedding_source: None,
4046                },
4047            ],
4048            indexes: Vec::new(),
4049            colocation: vec![],
4050            constraints: Default::default(),
4051            clustered: false,
4052        }
4053    }
4054
4055    fn rows() -> Vec<Row> {
4056        vec![
4057            Row::new(RowId(1), Epoch(10))
4058                .with_column(1, Value::Int64(1))
4059                .with_column(2, Value::Bytes(b"alice".to_vec())),
4060            Row::new(RowId(2), Epoch(10))
4061                .with_column(1, Value::Int64(2))
4062                .with_column(2, Value::Bytes(b"bob".to_vec())),
4063            Row::new(RowId(3), Epoch(10))
4064                .with_column(1, Value::Int64(3))
4065                .with_column(2, Value::Bytes(b"carol".to_vec())),
4066        ]
4067    }
4068
4069    #[test]
4070    fn flush_then_read_mvcc() {
4071        let dir = tempdir().unwrap();
4072        let path = dir.path().join("r-1.sr");
4073        let header = RunWriter::new(&schema(), 1, Epoch(10), 0)
4074            .write(&path, &rows())
4075            .unwrap();
4076        assert_eq!(header.row_count, 3);
4077
4078        let mut r = RunReader::open(&path, schema(), None).unwrap();
4079        // Point lookup.
4080        let (e, row) = r.get_version(RowId(2), Epoch(20)).unwrap().unwrap();
4081        assert_eq!(e, Epoch(10));
4082        assert_eq!(row.row_id, RowId(2));
4083        assert!(matches!(row.columns.get(&2), Some(Value::Bytes(_))));
4084        // Missing.
4085        assert!(r.get_version(RowId(99), Epoch(20)).unwrap().is_none());
4086        // Scan.
4087        let all = r.visible_rows(Epoch(20)).unwrap();
4088        assert_eq!(all.len(), 3);
4089        // Unstamped flush omits SYS_COMMIT_TS (legacy path).
4090        assert!(!r.has_column(SYS_COMMIT_TS));
4091        assert!(all.iter().all(|row| row.commit_ts.is_none()));
4092    }
4093
4094    /// ID: P0.5-T3 — flush preserves HLC stamps via optional SYS_COMMIT_TS;
4095    /// legacy runs without the column materialise commit_ts as None.
4096    #[test]
4097    fn p05_t3_sys_commit_ts_preserved_on_flush_and_legacy_is_none() {
4098        let dir = tempdir().unwrap();
4099        let stamped_path = dir.path().join("r-hlc.sr");
4100        let stamp = HlcTimestamp {
4101            physical_micros: 42_000_000,
4102            logical: 7,
4103            node_tiebreaker: 3,
4104        };
4105        let stamped = vec![
4106            Row::new_with_hlc(RowId(1), Epoch(10), stamp)
4107                .with_column(1, Value::Int64(1))
4108                .with_column(2, Value::Bytes(b"alice".to_vec())),
4109            Row::new(RowId(2), Epoch(11)) // mixed: unstamped sibling
4110                .with_column(1, Value::Int64(2))
4111                .with_column(2, Value::Bytes(b"bob".to_vec())),
4112        ];
4113        RunWriter::new(&schema(), 9, Epoch(11), 0)
4114            .write(&stamped_path, &stamped)
4115            .unwrap();
4116        let mut reader = RunReader::open(&stamped_path, schema(), None).unwrap();
4117        assert!(
4118            reader.has_column(SYS_COMMIT_TS),
4119            "stamped flush must emit optional SYS_COMMIT_TS"
4120        );
4121        let (_, row1) = reader
4122            .get_version(RowId(1), Epoch(20))
4123            .unwrap()
4124            .expect("row 1");
4125        assert_eq!(row1.commit_ts, Some(stamp));
4126        let (_, row2) = reader
4127            .get_version(RowId(2), Epoch(20))
4128            .unwrap()
4129            .expect("row 2");
4130        assert_eq!(row2.commit_ts, None, "Null stamp cell stays None");
4131        let versions = reader.visible_versions(Epoch(20)).unwrap();
4132        assert_eq!(versions.len(), 2);
4133        assert_eq!(
4134            versions
4135                .iter()
4136                .find(|r| r.row_id == RowId(1))
4137                .and_then(|r| r.commit_ts),
4138            Some(stamp)
4139        );
4140
4141        // Legacy run (no stamps on write) lacks the column → always None.
4142        let legacy_path = dir.path().join("r-legacy.sr");
4143        RunWriter::new(&schema(), 10, Epoch(10), 0)
4144            .write(&legacy_path, &rows())
4145            .unwrap();
4146        let mut legacy = RunReader::open(&legacy_path, schema(), None).unwrap();
4147        assert!(!legacy.has_column(SYS_COMMIT_TS));
4148        let all = legacy.visible_versions(Epoch(20)).unwrap();
4149        assert!(all.iter().all(|r| r.commit_ts.is_none()));
4150    }
4151
4152    #[test]
4153    fn visible_version_cursor_preserves_order_snapshot_and_tombstones() {
4154        let dir = tempdir().unwrap();
4155        let path = dir.path().join("r-cursor.sr");
4156        let mut tombstone = Row::new(RowId(2), Epoch(2));
4157        tombstone.deleted = true;
4158        let versions = vec![
4159            Row::new(RowId(1), Epoch(4)).with_column(1, Value::Int64(10)),
4160            Row::new(RowId(2), Epoch(1)).with_column(1, Value::Int64(2)),
4161            tombstone,
4162            Row::new(RowId(3), Epoch(1)).with_column(1, Value::Int64(20)),
4163            Row::new(RowId(3), Epoch(3)).with_column(1, Value::Int64(23)),
4164            Row::new(RowId(4), Epoch(4)).with_column(1, Value::Int64(30)),
4165        ];
4166        RunWriter::new(&schema(), 7, Epoch(4), 0)
4167            .write(&path, &versions)
4168            .unwrap();
4169
4170        let control = crate::ExecutionControl::new(None);
4171        let mut cursor = RunReader::open(&path, schema(), None)
4172            .unwrap()
4173            .into_visible_version_cursor(Epoch(2))
4174            .unwrap();
4175        let first = cursor.next_visible_version(&control).unwrap().unwrap();
4176        assert_eq!(first.row_id, RowId(2));
4177        assert!(first.deleted);
4178        assert_eq!(first.committed_epoch, Epoch(2));
4179        let second = cursor.next_visible_version(&control).unwrap().unwrap();
4180        assert_eq!(second.row_id, RowId(3));
4181        assert_eq!(second.committed_epoch, Epoch(1));
4182        let row = cursor.materialize(second, &control).unwrap();
4183        assert_eq!(row.columns.get(&1), Some(&Value::Int64(20)));
4184        assert!(cursor.next_visible_version(&control).unwrap().is_none());
4185    }
4186
4187    #[test]
4188    fn learned_index_was_stored() {
4189        let dir = tempdir().unwrap();
4190        let path = dir.path().join("r-2.sr");
4191        RunWriter::new(&schema(), 2, Epoch(1), 0)
4192            .write(&path, &rows())
4193            .unwrap();
4194        let header = read_header(&path).unwrap();
4195        assert!(
4196            header.index_trailer_offset != 0,
4197            "trailer should be present"
4198        );
4199    }
4200
4201    #[test]
4202    fn low_level_container_still_round_trips() {
4203        let dir = tempdir().unwrap();
4204        let path = dir.path().join("r-3.sr");
4205        let cols = vec![ColumnPayload {
4206            column_id: 1,
4207            type_id_tag: 8,
4208            encoding: Encoding::Plain,
4209            pages: vec![vec![1, 2, 3, 4]],
4210            page_stats: Vec::new(),
4211        }];
4212        let header = write_run(
4213            &path,
4214            &RunSpec {
4215                run_id: 1,
4216                schema_id: 1,
4217                epoch_created: 1,
4218                level: 0,
4219                flags: 0,
4220                sort_key_column_id: SORT_KEY_ROW_ID,
4221                row_count: 1,
4222                min_row_id: 0,
4223                max_row_id: 0,
4224                columns: &cols,
4225            },
4226        )
4227        .unwrap();
4228        let back = read_header(&path).unwrap();
4229        assert_eq!(back.content_hash, header.content_hash);
4230        assert_eq!(read_column_dir(&path, &back).unwrap().len(), 1);
4231    }
4232
4233    #[test]
4234    fn detects_corruption() {
4235        let dir = tempdir().unwrap();
4236        let path = dir.path().join("r-4.sr");
4237        write_run(
4238            &path,
4239            &RunSpec {
4240                run_id: 1,
4241                schema_id: 1,
4242                epoch_created: 1,
4243                level: 0,
4244                flags: 0,
4245                sort_key_column_id: SORT_KEY_ROW_ID,
4246                row_count: 1,
4247                min_row_id: 0,
4248                max_row_id: 0,
4249                columns: &[ColumnPayload {
4250                    column_id: 1,
4251                    type_id_tag: 8,
4252                    encoding: Encoding::Plain,
4253                    pages: vec![vec![1, 2, 3]],
4254                    page_stats: Vec::new(),
4255                }],
4256            },
4257        )
4258        .unwrap();
4259        let mut bytes = std::fs::read(&path).unwrap();
4260        bytes[300] ^= 0xFF;
4261        std::fs::write(&path, bytes).unwrap();
4262        let err = read_header(&path).unwrap_err();
4263        assert!(
4264            matches!(err, MongrelError::ChecksumMismatch { .. }),
4265            "got {err:?}"
4266        );
4267    }
4268
4269    /// Phase 14.6: the direct-to-mmap placement logic must produce a byte-
4270    /// identical run to the in-buffer fallback. We drive `plan_run` + `place_run`
4271    /// into a plain `Vec<u8>` (so it's testable even where file mmap is denied —
4272    /// e.g. this sandbox), compare against `write_run_vec`, and additionally
4273    /// check that `write_run_mmap` agrees wherever a mapping can be created.
4274    #[test]
4275    fn mmap_and_vec_writers_are_byte_identical() {
4276        let dir = tempdir().unwrap();
4277        let stats = vec![PageStat {
4278            first_row_id: 0,
4279            last_row_id: 1,
4280            null_count: 0,
4281            row_count: 2,
4282            min: Some(vec![0]),
4283            max: Some(vec![9]),
4284            offset: 0,
4285            compressed_len: 0,
4286            uncompressed_len: 0,
4287        }];
4288        let spec = RunSpec {
4289            run_id: 7,
4290            schema_id: 1,
4291            epoch_created: 10,
4292            level: 0,
4293            flags: 0,
4294            sort_key_column_id: SORT_KEY_ROW_ID,
4295            row_count: 2,
4296            min_row_id: 0,
4297            max_row_id: 1,
4298            columns: &[
4299                ColumnPayload {
4300                    column_id: 1,
4301                    type_id_tag: 8,
4302                    encoding: Encoding::Plain,
4303                    pages: vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]],
4304                    page_stats: stats.clone(),
4305                },
4306                ColumnPayload {
4307                    column_id: 2,
4308                    type_id_tag: 8,
4309                    encoding: Encoding::Plain,
4310                    pages: vec![vec![10, 20], vec![30, 40]],
4311                    page_stats: stats.clone(),
4312                },
4313            ],
4314        };
4315        let trailer = b"learned-trailer-bytes";
4316
4317        // (1) placement path into a Vec-backed buffer.
4318        let plan = plan_run(&spec, None, Some(trailer)).expect("plan");
4319        let mut buf = vec![0u8; plan.total];
4320        let h_place = place_run(&spec, None, Some(trailer), &plan, &mut buf)
4321            .expect("place_run into Vec succeeds");
4322
4323        // (2) in-buffer fallback writer to a real file.
4324        let path_vec = dir.path().join("vec.sr");
4325        let h_vec = write_run_vec(&path_vec, &spec, None, Some(trailer)).unwrap();
4326        let bv = std::fs::read(&path_vec).unwrap();
4327
4328        assert_eq!(h_place.content_hash, h_vec.content_hash);
4329        assert_eq!(h_place.footer_offset, h_vec.footer_offset);
4330        assert_eq!(
4331            buf, bv,
4332            "place_run and write_run_vec must be byte-identical"
4333        );
4334        assert!(read_header(&path_vec).is_ok());
4335
4336        // (3) the mmap writer, when the FS supports it, must also agree. Where
4337        // file mmap is denied (some sandboxes), it reports the fallback sentinel
4338        // and `write_run_with` transparently uses the vec path instead.
4339        let path_mmap = dir.path().join("mmap.sr");
4340        match write_run_mmap(&path_mmap, &spec, None, Some(trailer)) {
4341            Ok(h_mmap) => {
4342                let bm = std::fs::read(&path_mmap).unwrap();
4343                assert_eq!(bm, bv, "mmap run must be byte-identical to vec run");
4344                assert_eq!(h_mmap.content_hash, h_vec.content_hash);
4345            }
4346            Err(e) if is_mmap_unavailable(&e) => {
4347                eprintln!("note: file mmap unavailable here; vec path covered (1)/(2)");
4348            }
4349            Err(e) => panic!("unexpected mmap error: {e:?}"),
4350        }
4351    }
4352
4353    /// Phase 15.1: the `&self` parallel-decode path (`column_native_shared`)
4354    /// must yield the same `NativeColumn` as the `&mut` `column_native` path,
4355    /// column for column, on a multi-page run. This guards the cross-column
4356    /// parallel scan used by `visible_columns_native`.
4357    #[test]
4358    fn column_native_shared_matches_column_native() {
4359        let dir = tempdir().unwrap();
4360        let path = dir.path().join("r.sr");
4361        // Enough rows to span >1 page (PAGE_ROWS = 65 536) so the parallel page
4362        // branch runs, plus a partial tail page.
4363        let n = 65_536 * 2 + 9;
4364        let id_col = NativeColumn::int64_sequence(1, n);
4365        let mut offsets = vec![0u32];
4366        let mut values = Vec::new();
4367        for i in 0..n {
4368            values.extend_from_slice(format!("v{}", i % 17).as_bytes());
4369            offsets.push(values.len() as u32);
4370        }
4371        let name_col = NativeColumn::Bytes {
4372            offsets,
4373            values,
4374            validity: vec![0xFF; n.div_ceil(8)],
4375        };
4376        let header = RunWriter::new(&schema(), 9, Epoch(5), 0)
4377            .write_native(&path, &[(1, id_col), (2, name_col)], n, 1)
4378            .unwrap();
4379
4380        let mut reader = RunReader::open_with_cache(&path, schema(), None, None, None, 0, None)
4381            .expect("open reader");
4382        assert!(reader.has_mmap(), "test env must support read-only mmap");
4383        assert_eq!(reader.row_count(), header.row_count as usize);
4384
4385        for cid in [1u16, 2] {
4386            let a = reader.column_native(cid).expect("column_native");
4387            let b = reader
4388                .column_native_shared(cid)
4389                .expect("column_native_shared");
4390            assert_eq!(a.len(), b.len(), "len mismatch col {cid}");
4391            // Byte-level equality of the typed buffers.
4392            match (&a, &b) {
4393                (
4394                    NativeColumn::Int64 {
4395                        data: da,
4396                        validity: va,
4397                    },
4398                    NativeColumn::Int64 {
4399                        data: db,
4400                        validity: vb,
4401                    },
4402                ) => {
4403                    assert_eq!(da, db, "Int64 data col {cid}");
4404                    assert_eq!(va, vb, "Int64 validity col {cid}");
4405                }
4406                (
4407                    NativeColumn::Bytes {
4408                        offsets: oa,
4409                        values: ua,
4410                        validity: va,
4411                    },
4412                    NativeColumn::Bytes {
4413                        offsets: ob,
4414                        values: ub,
4415                        validity: vb,
4416                    },
4417                ) => {
4418                    assert_eq!(oa, ob, "Bytes offsets col {cid}");
4419                    assert_eq!(ua, ub, "Bytes values col {cid}");
4420                    assert_eq!(va, vb, "Bytes validity col {cid}");
4421                }
4422                _ => panic!("type mismatch col {cid}: {a:?} vs {b:?}"),
4423            }
4424        }
4425    }
4426
4427    #[test]
4428    fn page_cache_key_distinguishes_tables() {
4429        let a = page_cache_key(1, 5, 2, 3);
4430        let b = page_cache_key(2, 5, 2, 3);
4431        assert_ne!(a, b, "same run/col/page, different table must differ");
4432        // same table different run/col/page also differ (sanity)
4433        assert_ne!(page_cache_key(1, 5, 2, 3), page_cache_key(1, 6, 2, 3));
4434        assert_ne!(page_cache_key(1, 5, 2, 3), page_cache_key(1, 5, 2, 4));
4435    }
4436}