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    /// Optional HLC from SYS_COMMIT_TS when the run carries that column.
1947    /// Used by controlled merge for HLC-authoritative cross-tier winners
1948    /// without forcing full materialization first.
1949    pub(crate) commit_ts: Option<HlcTimestamp>,
1950    page_seq: usize,
1951    within_page: usize,
1952}
1953
1954/// Page-bounded cursor over one run's newest snapshot-visible version per row.
1955/// Only the three compact system columns and one user-data page are decoded at
1956/// a time. Full `Vec<Row>` materialization is deliberately avoided.
1957pub(crate) struct RunVisibleVersionCursor {
1958    reader: RunReader,
1959    snapshot: Epoch,
1960    page_row_counts: Vec<usize>,
1961    page_seq: usize,
1962    within_page: usize,
1963    row_ids: Vec<i64>,
1964    epochs: Vec<i64>,
1965    deleted: Vec<u8>,
1966    /// Per-row optional HLC stamps for the loaded system page (parallel to
1967    /// `row_ids`). Empty when the run has no SYS_COMMIT_TS column.
1968    commit_ts: Vec<Option<HlcTimestamp>>,
1969    has_commit_ts_col: bool,
1970    lookahead: Option<RunVisibleVersion>,
1971    materialized_page: Option<usize>,
1972    materialized_columns: Vec<(u16, columnar::NativeColumn)>,
1973}
1974
1975impl RunVisibleVersionCursor {
1976    fn new(reader: RunReader, snapshot: Epoch) -> Result<Self> {
1977        let page_row_counts = reader.page_row_counts(SYS_ROW_ID)?;
1978        let has_commit_ts_col = reader.has_column(SYS_COMMIT_TS);
1979        Ok(Self {
1980            reader,
1981            snapshot,
1982            page_row_counts,
1983            page_seq: 0,
1984            within_page: 0,
1985            row_ids: Vec::new(),
1986            epochs: Vec::new(),
1987            deleted: Vec::new(),
1988            commit_ts: Vec::new(),
1989            has_commit_ts_col,
1990            lookahead: None,
1991            materialized_page: None,
1992            materialized_columns: Vec::new(),
1993        })
1994    }
1995
1996    fn load_system_page(&mut self, control: &crate::ExecutionControl) -> Result<bool> {
1997        while self.page_seq < self.page_row_counts.len() {
1998            control.checkpoint()?;
1999            let rows = self.page_row_counts[self.page_seq];
2000            if rows == 0 {
2001                self.page_seq += 1;
2002                continue;
2003            }
2004            self.row_ids = match columnar::decode_page_native(
2005                TypeId::Int64,
2006                &self.reader.read_page(SYS_ROW_ID, self.page_seq)?,
2007                rows,
2008            )? {
2009                columnar::NativeColumn::Int64 { data, .. } => data,
2010                _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
2011            };
2012            self.epochs = if let Some(epoch) = self.reader.epoch_override {
2013                vec![epoch.0 as i64; rows]
2014            } else {
2015                match columnar::decode_page_native(
2016                    TypeId::Int64,
2017                    &self.reader.read_page(SYS_EPOCH, self.page_seq)?,
2018                    rows,
2019                )? {
2020                    columnar::NativeColumn::Int64 { data, .. } => data,
2021                    _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
2022                }
2023            };
2024            self.deleted = match columnar::decode_page_native(
2025                TypeId::Bool,
2026                &self.reader.read_page(SYS_DELETED, self.page_seq)?,
2027                rows,
2028            )? {
2029                columnar::NativeColumn::Bool { data, .. } => data,
2030                _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
2031            };
2032            self.commit_ts.clear();
2033            if self.has_commit_ts_col {
2034                let page = self.reader.read_page(SYS_COMMIT_TS, self.page_seq)?;
2035                let native = columnar::decode_page_native(TypeId::Bytes, &page, rows)?;
2036                self.commit_ts.reserve(rows);
2037                for i in 0..rows {
2038                    self.commit_ts
2039                        .push(decode_commit_ts_value(native.value_at(i).as_ref()));
2040                }
2041            }
2042            self.within_page = 0;
2043            return Ok(true);
2044        }
2045        Ok(false)
2046    }
2047
2048    fn next_raw(&mut self, control: &crate::ExecutionControl) -> Result<Option<RunVisibleVersion>> {
2049        if self.within_page >= self.row_ids.len() {
2050            if !self.row_ids.is_empty() {
2051                self.page_seq += 1;
2052                self.row_ids.clear();
2053                self.epochs.clear();
2054                self.deleted.clear();
2055                self.commit_ts.clear();
2056            }
2057            if !self.load_system_page(control)? {
2058                return Ok(None);
2059            }
2060        }
2061        if self.within_page.is_multiple_of(256) {
2062            control.checkpoint()?;
2063        }
2064        let position = self.within_page;
2065        self.within_page += 1;
2066        let commit_ts = self.commit_ts.get(position).copied().flatten();
2067        Ok(Some(RunVisibleVersion {
2068            row_id: RowId(self.row_ids[position] as u64),
2069            committed_epoch: Epoch(self.epochs[position] as u64),
2070            deleted: self.deleted[position] != 0,
2071            commit_ts,
2072            page_seq: self.page_seq,
2073            within_page: position,
2074        }))
2075    }
2076
2077    pub(crate) fn next_visible_version(
2078        &mut self,
2079        control: &crate::ExecutionControl,
2080    ) -> Result<Option<RunVisibleVersion>> {
2081        loop {
2082            let first = match self.lookahead.take() {
2083                Some(version) => version,
2084                None => match self.next_raw(control)? {
2085                    Some(version) => version,
2086                    None => return Ok(None),
2087                },
2088            };
2089            let row_id = first.row_id;
2090            let mut best = (first.committed_epoch <= self.snapshot).then_some(first);
2091            while let Some(candidate) = self.next_raw(control)? {
2092                if candidate.row_id != row_id {
2093                    self.lookahead = Some(candidate);
2094                    break;
2095                }
2096                if candidate.committed_epoch <= self.snapshot
2097                    && best.is_none_or(|current| {
2098                        crate::epoch::Snapshot::version_is_newer(
2099                            candidate.committed_epoch,
2100                            candidate.commit_ts,
2101                            current.committed_epoch,
2102                            current.commit_ts,
2103                        )
2104                    })
2105                {
2106                    best = Some(candidate);
2107                }
2108            }
2109            if best.is_some() {
2110                return Ok(best);
2111            }
2112        }
2113    }
2114
2115    pub(crate) fn materialize(
2116        &mut self,
2117        version: RunVisibleVersion,
2118        control: &crate::ExecutionControl,
2119    ) -> Result<Row> {
2120        if self.materialized_page != Some(version.page_seq) {
2121            let rows = self.page_row_counts[version.page_seq];
2122            let columns = self.reader.schema.columns.clone();
2123            let mut materialized = Vec::with_capacity(columns.len());
2124            for (index, column) in columns.into_iter().enumerate() {
2125                if index % 16 == 0 {
2126                    control.checkpoint()?;
2127                }
2128                let native = if self.reader.has_column(column.id) {
2129                    columnar::decode_page_native(
2130                        column.ty,
2131                        &self.reader.read_page(column.id, version.page_seq)?,
2132                        rows,
2133                    )?
2134                } else {
2135                    columnar::null_native(column.ty, rows)
2136                };
2137                materialized.push((column.id, native));
2138            }
2139            self.materialized_columns = materialized;
2140            self.materialized_page = Some(version.page_seq);
2141        }
2142        let columns = self
2143            .materialized_columns
2144            .iter()
2145            .map(|(column_id, column)| {
2146                (
2147                    *column_id,
2148                    column.value_at(version.within_page).unwrap_or(Value::Null),
2149                )
2150            })
2151            .collect();
2152        // Prefer the stamp already loaded on the candidate; fall back to a
2153        // page read for legacy cursors that predate per-candidate stamps.
2154        let commit_ts = version.commit_ts.or_else(|| {
2155            if self.reader.has_column(SYS_COMMIT_TS) {
2156                let page = self.reader.read_page(SYS_COMMIT_TS, version.page_seq).ok()?;
2157                let native = columnar::decode_page_native(
2158                    TypeId::Bytes,
2159                    &page,
2160                    self.page_row_counts[version.page_seq],
2161                )
2162                .ok()?;
2163                decode_commit_ts_value(native.value_at(version.within_page).as_ref())
2164            } else {
2165                None
2166            }
2167        });
2168        Ok(Row {
2169            row_id: version.row_id,
2170            committed_epoch: version.committed_epoch,
2171            columns,
2172            deleted: version.deleted,
2173            commit_ts,
2174        })
2175    }
2176}
2177
2178impl RunReader {
2179    pub fn open(path: impl AsRef<Path>, schema: Schema, kek: Option<Arc<Kek>>) -> Result<Self> {
2180        Self::open_with_cache(path, schema, kek, None, None, 0, None)
2181    }
2182
2183    pub(crate) fn open_file(file: File, schema: Schema, kek: Option<Arc<Kek>>) -> Result<Self> {
2184        Self::open_file_with_cache(file, schema, kek, None, None, 0, None, None)
2185    }
2186
2187    #[allow(clippy::too_many_arguments)]
2188    pub(crate) fn open_with_cache(
2189        path: impl AsRef<Path>,
2190        schema: Schema,
2191        kek: Option<Arc<Kek>>,
2192        page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
2193        decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
2194        table_id: u64,
2195        verified_runs: Option<&parking_lot::Mutex<std::collections::HashSet<u128>>>,
2196    ) -> Result<Self> {
2197        let path = path.as_ref().to_path_buf();
2198        let file = crate::durable_file::open_regular_nofollow(&path)?;
2199        Self::open_file_with_cache(
2200            file,
2201            schema,
2202            kek,
2203            page_cache,
2204            decoded_cache,
2205            table_id,
2206            verified_runs,
2207            Some(path),
2208        )
2209    }
2210
2211    #[allow(clippy::too_many_arguments)]
2212    pub(crate) fn open_file_with_cache(
2213        mut file: File,
2214        schema: Schema,
2215        kek: Option<Arc<Kek>>,
2216        page_cache: Option<Arc<crate::cache::Sharded<crate::cache::PageCache>>>,
2217        decoded_cache: Option<Arc<crate::cache::Sharded<crate::cache::DecodedPageCache>>>,
2218        table_id: u64,
2219        verified_runs: Option<&parking_lot::Mutex<std::collections::HashSet<u128>>>,
2220        path: Option<PathBuf>,
2221    ) -> Result<Self> {
2222        let header = match verified_runs {
2223            Some(cache) => {
2224                let header = read_header_fast_from_file(&mut file)?;
2225                if cache.lock().contains(&header.run_id) {
2226                    header
2227                } else {
2228                    let verified = read_header_from_file(&mut file)?;
2229                    cache.lock().insert(verified.run_id);
2230                    verified
2231                }
2232            }
2233            None => read_header_from_file(&mut file)?,
2234        };
2235        let mut dir = read_column_dir_from_file(&mut file, &header)?;
2236        validate_column_directory_layout(&header, &dir)?;
2237        if header.is_encrypted() != kek.is_some() {
2238            return Err(MongrelError::Encryption(
2239                "sorted-run encryption mode differs from the database".into(),
2240            ));
2241        }
2242        // Unwrap this run's per-file DEK (stored wrapped in its Encryption
2243        // Descriptor) using the table KEK, then build the page cipher.
2244        let (cipher, nonce_prefix): (Option<Box<dyn Cipher>>, [u8; 12]) = if header.is_encrypted() {
2245            let kek = kek.as_ref().ok_or_else(|| {
2246                MongrelError::Encryption(
2247                    "run is encrypted but no key-encryption key was provided".into(),
2248                )
2249            })?;
2250            if header.encryption_descriptor_offset == 0 {
2251                return Err(MongrelError::Encryption(
2252                    "encrypted run has no encryption descriptor".into(),
2253                ));
2254            }
2255            let desc_bytes = read_encryption_descriptor_bytes_from_file(&mut file, &header)?;
2256            // Authenticate the cleartext metadata (header‖dir‖descriptor) under
2257            // the KEK-derived MAC key BEFORE trusting any offset/stat to drive a
2258            // read. Required for every encrypted run (no downgrade path: an
2259            // attacker can neither strip the encryption — pages stay ciphertext —
2260            // nor forge the tag without the key).
2261            verify_run_mac(&mut file, &header, &dir, kek, &desc_bytes)?;
2262            let enc = crate::encryption::build_run_cipher(kek, &desc_bytes)?;
2263            // With the metadata authenticated, decrypt the per-page min/max
2264            // envelope (v2 runs) and overlay it so zone-map pruning works on
2265            // encrypted columns exactly as it does on plaintext ones.
2266            if header.encrypted_stats_offset != 0 {
2267                overlay_encrypted_stats(
2268                    &mut file,
2269                    &header,
2270                    enc.cipher.as_ref(),
2271                    enc.nonce_prefix,
2272                    &mut dir,
2273                )?;
2274            }
2275            (Some(enc.cipher), enc.nonce_prefix)
2276        } else {
2277            (None, [0u8; 12])
2278        };
2279        // Best-effort memory map: lets the OS page cache manage I/O and removes
2280        // per-page seek+read syscalls. Falls back to read() on empty/unmappable
2281        // files. The `file` handle is kept for the lifetime of the mapping.
2282        // (Per-column `MADV_WILLNEED` read-ahead is issued from
2283        // `column_native_shared` — see Phase 15.2 — so a global advice policy is
2284        // not set here; that would degrade concurrent point lookups.)
2285        let mmap = unsafe { memmap2::MmapOptions::new().map(&file) }.ok();
2286        let _ = path;
2287        Ok(Self {
2288            file,
2289            mmap,
2290            header,
2291            dir,
2292            schema,
2293            table_id,
2294            cipher,
2295            nonce_prefix,
2296            col_cache: HashMap::new(),
2297            epoch_override: None,
2298            page_cache,
2299            decoded_cache,
2300        })
2301    }
2302
2303    pub fn header(&self) -> &RunHeader {
2304        &self.header
2305    }
2306
2307    pub(crate) fn validate_all_pages(&mut self) -> Result<()> {
2308        let mut columns = std::collections::HashSet::new();
2309        let row_header = self.find_header(SYS_ROW_ID)?.clone();
2310        let expected_rows = row_header
2311            .page_stats
2312            .iter()
2313            .map(|stat| stat.row_count)
2314            .collect::<Vec<_>>();
2315        let mut row_bounds = Vec::with_capacity(row_header.page_stats.len());
2316        let mut previous = None::<u64>;
2317        let mut first = None::<u64>;
2318        let mut last = None::<u64>;
2319        let mut counted = 0_u64;
2320        for (page, stat) in row_header.page_stats.iter().enumerate() {
2321            let bytes = self.read_page(SYS_ROW_ID, page)?;
2322            let native =
2323                columnar::decode_page_native(TypeId::Int64, &bytes, stat.row_count as usize)?;
2324            if columnar::page_stat_for(TypeId::Int64, &native, 0, 0).null_count != 0 {
2325                return Err(MongrelError::InvalidArgument(
2326                    "sorted run row-id page contains nulls".into(),
2327                ));
2328            }
2329            let columnar::NativeColumn::Int64 { data, validity } = native else {
2330                return Err(MongrelError::InvalidArgument(
2331                    "sorted run row-id page has the wrong type".into(),
2332                ));
2333            };
2334            let _ = validity;
2335            if data.is_empty() {
2336                if self.header.row_count != 0 || stat.row_count != 0 {
2337                    return Err(MongrelError::InvalidArgument(
2338                        "sorted run row-id page is unexpectedly empty".into(),
2339                    ));
2340                }
2341                row_bounds.push((0, 0));
2342                continue;
2343            }
2344            if data.iter().any(|value| *value < 0) {
2345                return Err(MongrelError::InvalidArgument(
2346                    "sorted run contains a negative row id".into(),
2347                ));
2348            }
2349            let page_first = data[0] as u64;
2350            let page_last = data[data.len() - 1] as u64;
2351            for value in data {
2352                let value = value as u64;
2353                if previous.is_some_and(|prior| {
2354                    value < prior || (self.header.is_clean() && value == prior)
2355                }) {
2356                    return Err(MongrelError::InvalidArgument(
2357                        "sorted run row ids are not ordered".into(),
2358                    ));
2359                }
2360                first.get_or_insert(value);
2361                previous = Some(value);
2362                last = Some(value);
2363                counted += 1;
2364            }
2365            if stat.first_row_id != page_first || stat.last_row_id != page_last {
2366                return Err(MongrelError::InvalidArgument(
2367                    "sorted run row-id page bounds are stale".into(),
2368                ));
2369            }
2370            row_bounds.push((page_first, page_last));
2371        }
2372        if counted != self.header.row_count
2373            || first.unwrap_or(0) != self.header.min_row_id
2374            || last.unwrap_or(0) != self.header.max_row_id
2375        {
2376            return Err(MongrelError::InvalidArgument(
2377                "sorted run header row bounds differ from its pages".into(),
2378            ));
2379        }
2380        for column in self.dir.clone() {
2381            if !columns.insert(column.column_id) {
2382                return Err(MongrelError::InvalidArgument(format!(
2383                    "sorted run contains duplicate column {}",
2384                    column.column_id
2385                )));
2386            }
2387            let rows = column
2388                .page_stats
2389                .iter()
2390                .map(|stat| stat.row_count)
2391                .collect::<Vec<_>>();
2392            if rows != expected_rows {
2393                return Err(MongrelError::InvalidArgument(
2394                    "sorted run columns have inconsistent page row counts".into(),
2395                ));
2396            }
2397            let ty = self.resolve_type(column.column_id);
2398            if column.type_id_tag != type_tag(&ty)
2399                || column.encoding > Encoding::Zstd as u8
2400                || (!is_system_column_id(column.column_id)
2401                    && self
2402                        .schema
2403                        .columns
2404                        .iter()
2405                        .all(|item| item.id != column.column_id))
2406            {
2407                return Err(MongrelError::InvalidArgument(
2408                    "sorted run column type or encoding is invalid".into(),
2409                ));
2410            }
2411            for (page, stat) in column.page_stats.iter().enumerate() {
2412                let bytes = self.read_page(column.column_id, page)?;
2413                if bytes.len() != stat.uncompressed_len as usize {
2414                    return Err(MongrelError::InvalidArgument(
2415                        "sorted run page length differs from its metadata".into(),
2416                    ));
2417                }
2418                let native =
2419                    match columnar::decode_page_native(ty.clone(), &bytes, stat.row_count as usize)
2420                    {
2421                        Ok(native) => native,
2422                        Err(MongrelError::InvalidArgument(message))
2423                            if message.starts_with("decode_page_native: unsupported ty") =>
2424                        {
2425                            let values =
2426                                columnar::decode_page(ty.clone(), &bytes, stat.row_count as usize)?;
2427                            columnar::values_to_native(ty.clone(), &values)
2428                        }
2429                        Err(error) => return Err(error),
2430                    };
2431                let (first_row_id, last_row_id) =
2432                    row_bounds.get(page).copied().ok_or_else(|| {
2433                        MongrelError::InvalidArgument(
2434                            "sorted run column has more pages than its row-id column".into(),
2435                        )
2436                    })?;
2437                let expected =
2438                    columnar::page_stat_for(ty.clone(), &native, first_row_id, last_row_id);
2439                if stat.first_row_id != expected.first_row_id
2440                    || stat.last_row_id != expected.last_row_id
2441                    || stat.null_count != expected.null_count
2442                    || stat.min != expected.min
2443                    || stat.max != expected.max
2444                {
2445                    return Err(MongrelError::InvalidArgument(
2446                        "sorted run page statistics differ from decoded values".into(),
2447                    ));
2448                }
2449            }
2450        }
2451        if !columns.contains(&SYS_ROW_ID)
2452            || !columns.contains(&SYS_EPOCH)
2453            || !columns.contains(&SYS_DELETED)
2454            || expected_rows.into_iter().map(u64::from).sum::<u64>() != self.header.row_count
2455        {
2456            return Err(MongrelError::InvalidArgument(
2457                "sorted run system columns or row count are invalid".into(),
2458            ));
2459        }
2460        if self.header.schema_id == self.schema.schema_id
2461            && self
2462                .schema
2463                .columns
2464                .iter()
2465                .any(|column| !columns.contains(&column.id))
2466        {
2467            return Err(MongrelError::InvalidArgument(
2468                "sorted run is missing a column from its declared schema".into(),
2469            ));
2470        }
2471
2472        // Page encodings and statistics are not enough to establish semantic
2473        // validity.  Reconstruct every materialized row and apply the schema's
2474        // row-level rules before the run can participate in recovery.
2475        for row_index in 0..usize::try_from(self.header.row_count).map_err(|_| {
2476            MongrelError::InvalidArgument("sorted run row count exceeds this platform".into())
2477        })? {
2478            let epoch = match self.column(SYS_EPOCH)?.get(row_index) {
2479                Some(Value::Int64(value)) if *value >= 0 => *value as u64,
2480                _ => {
2481                    return Err(MongrelError::InvalidArgument(
2482                        "sorted run contains an invalid commit epoch".into(),
2483                    ))
2484                }
2485            };
2486            if epoch > self.header.epoch_created || (self.header.is_uniform_epoch() && epoch != 0) {
2487                return Err(MongrelError::InvalidArgument(
2488                    "sorted run commit epoch exceeds its creation epoch".into(),
2489                ));
2490            }
2491            let deleted = match self.column(SYS_DELETED)?.get(row_index) {
2492                Some(Value::Bool(value)) => *value,
2493                _ => {
2494                    return Err(MongrelError::InvalidArgument(
2495                        "sorted run contains an invalid tombstone marker".into(),
2496                    ))
2497                }
2498            };
2499            let mut values = Vec::with_capacity(self.schema.columns.len());
2500            for column in self.schema.columns.clone() {
2501                let value = if columns.contains(&column.id) {
2502                    self.column(column.id)?
2503                        .get(row_index)
2504                        .cloned()
2505                        .unwrap_or(Value::Null)
2506                } else {
2507                    Value::Null
2508                };
2509                values.push((column.id, value));
2510            }
2511            if !deleted {
2512                self.schema
2513                    .validate_persisted_values(&values)
2514                    .map_err(|error| {
2515                        MongrelError::InvalidArgument(format!(
2516                            "sorted run row violates its schema: {error}"
2517                        ))
2518                    })?;
2519            }
2520        }
2521        Ok(())
2522    }
2523
2524    /// Overlay the real commit epoch for a uniform-epoch run (see
2525    /// [`RUN_FLAG_UNIFORM_EPOCH`]). No-op unless the run carries that flag, so it
2526    /// is always safe for the engine to call with the `RunRef.epoch_created`.
2527    pub(crate) fn set_uniform_epoch(&mut self, epoch: Epoch) {
2528        if self.header.is_uniform_epoch() {
2529            self.epoch_override = Some(epoch);
2530            // Drop any cached placeholder epoch column so the overlay takes hold.
2531            self.col_cache.remove(&SYS_EPOCH);
2532        }
2533    }
2534
2535    pub(crate) fn into_visible_version_cursor(
2536        self,
2537        snapshot: Epoch,
2538    ) -> Result<RunVisibleVersionCursor> {
2539        RunVisibleVersionCursor::new(self, snapshot)
2540    }
2541
2542    /// Whether this run is "clean" (one version per RowId, no tombstones,
2543    /// ascending row_ids) — stamped at write time via [`RUN_FLAG_CLEAN`].
2544    pub fn is_clean(&self) -> bool {
2545        self.header.is_clean()
2546    }
2547
2548    pub fn row_count(&self) -> usize {
2549        self.header.row_count as usize
2550    }
2551
2552    pub(crate) fn clean_contiguous_row_ids(&self) -> bool {
2553        let n = self.row_count();
2554        n > 0
2555            && self.is_clean()
2556            && self.epoch_override.is_none()
2557            && self.header.max_row_id >= self.header.min_row_id
2558            && self
2559                .header
2560                .max_row_id
2561                .checked_sub(self.header.min_row_id)
2562                .and_then(|span| span.checked_add(1))
2563                == Some(n as u64)
2564    }
2565
2566    pub(crate) fn position_for_row_id_fast(&self, row_id: u64) -> Option<usize> {
2567        if !self.clean_contiguous_row_ids()
2568            || row_id < self.header.min_row_id
2569            || row_id > self.header.max_row_id
2570        {
2571            return None;
2572        }
2573        Some((row_id - self.header.min_row_id) as usize)
2574    }
2575
2576    pub(crate) fn positions_for_row_ids_fast(&self, row_ids: &[u64]) -> Option<Vec<usize>> {
2577        if !self.clean_contiguous_row_ids() {
2578            return None;
2579        }
2580        let mut positions = Vec::with_capacity(row_ids.len());
2581        for &row_id in row_ids {
2582            if let Some(pos) = self.position_for_row_id_fast(row_id) {
2583                positions.push(pos);
2584            }
2585        }
2586        positions.sort_unstable();
2587        Some(positions)
2588    }
2589
2590    fn resolve_type(&self, column_id: u16) -> TypeId {
2591        match column_id {
2592            SYS_ROW_ID | SYS_EPOCH => TypeId::Int64,
2593            SYS_DELETED => TypeId::Bool,
2594            SYS_COMMIT_TS => TypeId::Bytes,
2595            _ => self
2596                .schema
2597                .columns
2598                .iter()
2599                .find(|c| c.id == column_id)
2600                .map(|c| c.ty.clone())
2601                .unwrap_or(TypeId::Bytes),
2602        }
2603    }
2604
2605    /// Optional HLC stamp at row `index` (P0.5-T3). Missing column → `None`.
2606    fn commit_ts_at(&mut self, index: usize) -> Result<Option<HlcTimestamp>> {
2607        if !self.has_column(SYS_COMMIT_TS) {
2608            return Ok(None);
2609        }
2610        Ok(decode_commit_ts_value(
2611            self.column(SYS_COMMIT_TS)?.get(index),
2612        ))
2613    }
2614
2615    fn find_header(&self, column_id: u16) -> Result<&ColumnPageHeader> {
2616        self.dir
2617            .iter()
2618            .find(|h| h.column_id == column_id)
2619            .ok_or_else(|| MongrelError::ColumnNotFound(format!("column {column_id}")))
2620    }
2621
2622    /// Whether `column_id`'s pages are encrypted. Encrypted runs carry no
2623    /// cleartext per-page min/max (they would leak plaintext values), so the
2624    /// range resolvers must NOT prune by stats for such columns — a missing
2625    /// stat there means "hidden", not "all-null". They fall back to decrypting
2626    /// and scanning every page.
2627    fn col_encrypted(&self, column_id: u16) -> bool {
2628        self.dir
2629            .iter()
2630            .find(|h| h.column_id == column_id)
2631            .map(|h| h.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0)
2632            .unwrap_or(false)
2633    }
2634
2635    pub(crate) fn read_page(&mut self, column_id: u16, page_seq: usize) -> Result<Vec<u8>> {
2636        let (offset, compressed_len, encrypted) = {
2637            let ch = self.find_header(column_id)?;
2638            let stat = ch
2639                .page_stats
2640                .get(page_seq)
2641                .ok_or_else(|| MongrelError::InvalidArgument("page seq out of range".into()))?;
2642            (
2643                stat.offset,
2644                stat.compressed_len,
2645                ch.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0,
2646            )
2647        };
2648        let end = offset
2649            .checked_add(compressed_len as u64)
2650            .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
2651        let start = usize::try_from(offset)
2652            .map_err(|_| MongrelError::InvalidArgument("run page offset is too large".into()))?;
2653        let end = usize::try_from(end)
2654            .map_err(|_| MongrelError::InvalidArgument("run page end is too large".into()))?;
2655        // Shared cache: serve the raw (on-disk / ciphertext) page bytes if
2656        // present, so concurrent readers never re-read or re-decrypt a page.
2657        let key = page_cache_key(self.table_id, self.header.run_id, column_id, page_seq);
2658        if let Some(cache) = &self.page_cache {
2659            if let Some(bytes) = cache.lock(&key).get(
2660                &key,
2661                crate::epoch::Snapshot::at(crate::epoch::Epoch(u64::MAX)),
2662            ) {
2663                return decrypt_or_passthrough(
2664                    self.cipher.as_deref(),
2665                    self.nonce_prefix,
2666                    column_id,
2667                    page_seq,
2668                    encrypted,
2669                    &bytes,
2670                );
2671            }
2672        }
2673        let buf = match &self.mmap {
2674            // Slice the mapping — no seek/read syscalls; the OS page cache fills
2675            // the pages on first touch.
2676            Some(m) => m
2677                .get(start..end)
2678                .ok_or_else(|| {
2679                    MongrelError::InvalidArgument("run page is outside the mapped file".into())
2680                })?
2681                .to_vec(),
2682            None => {
2683                self.file.seek(SeekFrom::Start(offset))?;
2684                let mut buf = vec![0u8; compressed_len as usize];
2685                self.file.read_exact(&mut buf)?;
2686                buf
2687            }
2688        };
2689        // Spill the raw bytes into the shared cache (post-read, pre-decrypt).
2690        if let Some(cache) = &self.page_cache {
2691            cache.lock(&key).insert(crate::page::CachedPage {
2692                committed_epoch: crate::epoch::Epoch(self.header.epoch_created),
2693                content_hash: key,
2694                bytes: bytes::Bytes::copy_from_slice(&buf),
2695            });
2696        }
2697        decrypt_or_passthrough(
2698            self.cipher.as_deref(),
2699            self.nonce_prefix,
2700            column_id,
2701            page_seq,
2702            encrypted,
2703            &buf,
2704        )
2705    }
2706
2707    /// `&self` version of [`Self::read_page`] restricted to the mmap-backed
2708    /// path, so page bytes can be read concurrently (rayon) without the
2709    /// `&mut self` file handle. Decryption (when enabled) uses the `Sync`
2710    /// cipher and a deterministic per-page nonce, so it is also parallel-safe.
2711    fn read_page_shared(&self, column_id: u16, page_seq: usize) -> Result<Vec<u8>> {
2712        let ch = self.find_header(column_id)?;
2713        let stat = ch
2714            .page_stats
2715            .get(page_seq)
2716            .ok_or_else(|| MongrelError::InvalidArgument("page seq out of range".into()))?;
2717        let encrypted = ch.flags & ColumnPageHeader::PAGE_ENCRYPTED != 0;
2718        // Non-blocking probe of the shared cache: never block the rayon pool on
2719        // a contended lock. On a hit, avoid the mmap slice + decrypt entirely.
2720        let key = page_cache_key(self.table_id, self.header.run_id, column_id, page_seq);
2721        if let Some(cache) = &self.page_cache {
2722            if let Some(guard) = cache.try_lock(&key) {
2723                if let Some(bytes) = guard.try_get(
2724                    &key,
2725                    crate::epoch::Snapshot::at(crate::epoch::Epoch(u64::MAX)),
2726                ) {
2727                    return decrypt_or_passthrough(
2728                        self.cipher.as_deref(),
2729                        self.nonce_prefix,
2730                        column_id,
2731                        page_seq,
2732                        encrypted,
2733                        &bytes,
2734                    );
2735                }
2736            }
2737        }
2738        let mmap = self.mmap.as_ref().ok_or_else(|| {
2739            MongrelError::InvalidArgument("parallel page decode requires an mmap-backed run".into())
2740        })?;
2741        let end = stat
2742            .offset
2743            .checked_add(stat.compressed_len as u64)
2744            .ok_or_else(|| MongrelError::InvalidArgument("run page offset overflows".into()))?;
2745        let start = usize::try_from(stat.offset)
2746            .map_err(|_| MongrelError::InvalidArgument("run page offset is too large".into()))?;
2747        let end = usize::try_from(end)
2748            .map_err(|_| MongrelError::InvalidArgument("run page end is too large".into()))?;
2749        let buf = mmap
2750            .get(start..end)
2751            .ok_or_else(|| {
2752                MongrelError::InvalidArgument("run page is outside the mapped file".into())
2753            })?
2754            .to_vec();
2755        // Opportunistic, non-blocking insert: populate the shared cache so later
2756        // readers (and encrypted re-reads) skip the mmap slice + decrypt. Never
2757        // block the rayon pool — if the lock is contended, just skip the insert.
2758        if let Some(cache) = &self.page_cache {
2759            if let Some(mut guard) = cache.try_lock(&key) {
2760                guard.insert(crate::page::CachedPage {
2761                    committed_epoch: crate::epoch::Epoch(self.header.epoch_created),
2762                    content_hash: key,
2763                    bytes: bytes::Bytes::copy_from_slice(&buf),
2764                });
2765            }
2766        }
2767        decrypt_or_passthrough(
2768            self.cipher.as_deref(),
2769            self.nonce_prefix,
2770            column_id,
2771            page_seq,
2772            encrypted,
2773            &buf,
2774        )
2775    }
2776
2777    /// Decode (and cache) a full column, concatenating all pages.
2778    fn column(&mut self, column_id: u16) -> Result<&[Value]> {
2779        // Uniform-epoch overlay: serve the `_epoch` column as a constant of the
2780        // real commit epoch instead of the placeholder stored on disk.
2781        if column_id == SYS_EPOCH {
2782            if let Some(ov) = self.epoch_override {
2783                if !self.col_cache.contains_key(&column_id) {
2784                    let n = self.row_count();
2785                    self.col_cache
2786                        .insert(column_id, vec![Value::Int64(ov.0 as i64); n]);
2787                }
2788                return Ok(self.col_cache.get(&column_id).unwrap().as_slice());
2789            }
2790        }
2791        if !self.col_cache.contains_key(&column_id) {
2792            let ty = self.resolve_type(column_id);
2793            let page_rows: Vec<usize> = {
2794                let ch = self.find_header(column_id)?;
2795                ch.page_stats.iter().map(|s| s.row_count as usize).collect()
2796            };
2797            let mut decoded: Vec<Value> = Vec::with_capacity(self.row_count());
2798            for (seq, &pr) in page_rows.iter().enumerate() {
2799                let page = self.read_page(column_id, seq)?;
2800                decoded.extend(columnar::decode_page(ty.clone(), &page, pr)?);
2801            }
2802            self.col_cache.insert(column_id, decoded);
2803        }
2804        Ok(self.col_cache.get(&column_id).unwrap().as_slice())
2805    }
2806
2807    /// Newest version of `row_id` with `epoch <= snapshot`, including tombstones
2808    /// (returned as a `Row` with `deleted=true`). `None` if no such version.
2809    ///
2810    /// Page-pruned: `SYS_ROW_ID` pages carry exact `first_row_id`/`last_row_id`
2811    /// bounds (rows are written in ascending `(RowId, Epoch)` order), so this
2812    /// decodes only the page(s) that can contain `row_id` instead of the whole
2813    /// column — the old implementation decoded every row's `SYS_ROW_ID` (and
2814    /// `SYS_EPOCH`) up front, making every single-row point lookup (the common
2815    /// case for a PK/unique check feeding insert/update/delete) pay a
2816    /// full-column decode. A row's version group can span at most two adjacent
2817    /// pages (split at a page boundary mid-group); `candidate_pages` below
2818    /// collects every page whose bounds include `row_id`, which is normally
2819    /// one page and two only in that split case.
2820    pub fn get_version(&mut self, row_id: RowId, snapshot: Epoch) -> Result<Option<(Epoch, Row)>> {
2821        match self.find_version_page(row_id, snapshot)? {
2822            None => Ok(None),
2823            Some((epoch, seq, local_index)) => Ok(Some((
2824                Epoch(epoch),
2825                self.materialize_in_page(seq, local_index)?,
2826            ))),
2827        }
2828    }
2829
2830    /// Page-pruned search for the newest version of `row_id` with `epoch <=
2831    /// snapshot`: `(epoch, page_seq, local_index)`, or `None` if no such
2832    /// version exists in this run. Factored out of [`Self::get_version`] so
2833    /// [`Self::get_version_column`] can reuse the exact same page-finding
2834    /// logic without re-deriving it.
2835    fn find_version_page(
2836        &mut self,
2837        row_id: RowId,
2838        snapshot: Epoch,
2839    ) -> Result<Option<(u64, usize, usize)>> {
2840        let n = self.row_count();
2841        if n == 0 {
2842            return Ok(None);
2843        }
2844        let target = row_id.0 as i64;
2845        let ch = self.find_header(SYS_ROW_ID)?;
2846        let mut page_start = 0u64;
2847        let candidate_pages: Vec<(usize, u64)> = ch // (page_seq, row offset of page start)
2848            .page_stats
2849            .iter()
2850            .enumerate()
2851            .filter_map(|(seq, s)| {
2852                let start = page_start;
2853                page_start += s.row_count as u64;
2854                (s.first_row_id <= row_id.0 && row_id.0 <= s.last_row_id).then_some((seq, start))
2855            })
2856            .collect();
2857        if candidate_pages.is_empty() {
2858            return Ok(None);
2859        }
2860        let ty = self.resolve_type(SYS_ROW_ID);
2861        let mut best: Option<(u64, usize, usize)> = None; // (epoch, page_seq, local index)
2862        for (seq, _page_row_start) in candidate_pages {
2863            let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2864            let row_ids =
2865                match self.decode_page_native_cached(ty.clone(), SYS_ROW_ID, seq, page_rows)? {
2866                    columnar::NativeColumn::Int64 { data, .. } => data,
2867                    _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
2868                };
2869            let local = match row_ids.binary_search(&target) {
2870                Ok(i) => i,
2871                Err(_) => continue,
2872            };
2873            let epoch_ty = self.resolve_type(SYS_EPOCH);
2874            let epochs =
2875                match self.decode_page_native_cached(epoch_ty, SYS_EPOCH, seq, page_rows)? {
2876                    columnar::NativeColumn::Int64 { data, .. } => data,
2877                    _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
2878                };
2879            // `local` is one match; the row-id's full version group is the
2880            // contiguous run of equal row-ids around it within this page.
2881            let mut lo = local;
2882            while lo > 0 && row_ids[lo - 1] == target {
2883                lo -= 1;
2884            }
2885            let mut hi = local;
2886            while hi + 1 < row_ids.len() && row_ids[hi + 1] == target {
2887                hi += 1;
2888            }
2889            for (i, &epoch) in epochs[lo..=hi].iter().enumerate() {
2890                let epoch = epoch as u64;
2891                if epoch <= snapshot.0 && best.map(|(be, ..)| epoch > be).unwrap_or(true) {
2892                    best = Some((epoch, seq, lo + i));
2893                }
2894            }
2895        }
2896        Ok(best)
2897    }
2898
2899    /// Like [`Self::get_version`], but decodes only `column_id` (plus the
2900    /// `SYS_DELETED` flag) instead of materializing every schema column via
2901    /// [`Self::materialize_in_page`]. For a wide schema this avoids paying to
2902    /// decode every other column's page just to read one value and throw the
2903    /// rest away — e.g. `Table::remove_hot_for_row`'s PK-only lookup, which
2904    /// used to pull the whole row (every column, every page) just for the
2905    /// primary key.
2906    pub fn get_version_column(
2907        &mut self,
2908        row_id: RowId,
2909        snapshot: Epoch,
2910        column_id: u16,
2911    ) -> Result<Option<(Epoch, bool, Option<Value>)>> {
2912        let Some((epoch, seq, local_index)) = self.find_version_page(row_id, snapshot)? else {
2913            return Ok(None);
2914        };
2915        let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2916        let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
2917            .iter()
2918            .map(|s| s.row_count as usize)
2919            .sum();
2920        let global_index = page_start + local_index;
2921        let native_at = |slf: &mut Self, cid: u16| -> Result<Option<Value>> {
2922            if !slf.dir.iter().any(|h| h.column_id == cid) {
2923                return Ok(None);
2924            }
2925            let ty = slf.resolve_type(cid);
2926            if !matches!(
2927                ty,
2928                TypeId::Bool
2929                    | TypeId::Int8
2930                    | TypeId::Int16
2931                    | TypeId::Int32
2932                    | TypeId::Int64
2933                    | TypeId::UInt8
2934                    | TypeId::UInt16
2935                    | TypeId::UInt32
2936                    | TypeId::UInt64
2937                    | TypeId::Float32
2938                    | TypeId::Float64
2939                    | TypeId::TimestampNanos
2940                    | TypeId::Date32
2941                    | TypeId::Bytes
2942            ) {
2943                return Ok(slf.column(cid)?.get(global_index).cloned());
2944            }
2945            Ok(slf
2946                .decode_page_native_cached(ty, cid, seq, page_rows)?
2947                .value_at(local_index))
2948        };
2949        let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
2950        let value = native_at(self, column_id)?;
2951        Ok(Some((Epoch(epoch), deleted, value)))
2952    }
2953
2954    /// Newest version epoch and tombstone flag without decoding a user column.
2955    pub fn get_version_visibility(
2956        &mut self,
2957        row_id: RowId,
2958        snapshot: Epoch,
2959    ) -> Result<Option<(Epoch, bool)>> {
2960        let Some((epoch, seq, local_index)) = self.find_version_page(row_id, snapshot)? else {
2961            return Ok(None);
2962        };
2963        let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2964        let deleted = match self.decode_page_native_cached(
2965            self.resolve_type(SYS_DELETED),
2966            SYS_DELETED,
2967            seq,
2968            page_rows,
2969        )? {
2970            columnar::NativeColumn::Bool { data, .. } => data[local_index] != 0,
2971            _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
2972        };
2973        Ok(Some((Epoch(epoch), deleted)))
2974    }
2975
2976    /// Build a `Row` from page `seq`'s data at `local_index`, decoding only
2977    /// that one page per column instead of [`Self::materialize`]'s whole-column
2978    /// `Vec<Value>` decode — used by [`Self::get_version`], which already knows
2979    /// the exact page from its page-pruned search. Only for scalar types with a
2980    /// [`columnar::NativeColumn`] representation; any other column (e.g. a
2981    /// fixed-size `Embedding`, which `NativeColumn` has no variant for) falls
2982    /// back to the whole-column path for that column specifically, so this is
2983    /// never wrong, only sometimes not faster.
2984    fn materialize_in_page(&mut self, seq: usize, local_index: usize) -> Result<Row> {
2985        let page_rows = self.find_header(SYS_ROW_ID)?.page_stats[seq].row_count as usize;
2986        let page_start: usize = self.find_header(SYS_ROW_ID)?.page_stats[..seq]
2987            .iter()
2988            .map(|s| s.row_count as usize)
2989            .sum();
2990        let global_index = page_start + local_index;
2991        let native_at = |slf: &mut Self, column_id: u16| -> Result<Option<Value>> {
2992            // Absent column (schema evolution: added after this run was
2993            // written) reads as null, matching `materialize`'s own guard.
2994            if !slf.dir.iter().any(|h| h.column_id == column_id) {
2995                return Ok(None);
2996            }
2997            let ty = slf.resolve_type(column_id);
2998            if !matches!(
2999                ty,
3000                TypeId::Bool
3001                    | TypeId::Int8
3002                    | TypeId::Int16
3003                    | TypeId::Int32
3004                    | TypeId::Int64
3005                    | TypeId::UInt8
3006                    | TypeId::UInt16
3007                    | TypeId::UInt32
3008                    | TypeId::UInt64
3009                    | TypeId::Float32
3010                    | TypeId::Float64
3011                    | TypeId::TimestampNanos
3012                    | TypeId::Date32
3013                    | TypeId::Bytes
3014            ) {
3015                // Not a NativeColumn-representable scalar (e.g. Embedding) —
3016                // fall back to the always-correct whole-column decode.
3017                return Ok(slf.column(column_id)?.get(global_index).cloned());
3018            }
3019            Ok(slf
3020                .decode_page_native_cached(ty, column_id, seq, page_rows)?
3021                .value_at(local_index))
3022        };
3023        let row_id = RowId(match native_at(self, SYS_ROW_ID)? {
3024            Some(Value::Int64(x)) => x as u64,
3025            _ => 0,
3026        });
3027        let committed_epoch = Epoch(match native_at(self, SYS_EPOCH)? {
3028            Some(Value::Int64(x)) => x as u64,
3029            _ => 0,
3030        });
3031        let deleted = matches!(native_at(self, SYS_DELETED)?, Some(Value::Bool(true)));
3032        let commit_ts = if self.has_column(SYS_COMMIT_TS) {
3033            decode_commit_ts_value(native_at(self, SYS_COMMIT_TS)?.as_ref())
3034        } else {
3035            None
3036        };
3037        let col_ids: Vec<u16> = self.schema.columns.iter().map(|c| c.id).collect();
3038        let mut columns = HashMap::new();
3039        for id in col_ids {
3040            columns.insert(id, native_at(self, id)?.unwrap_or(Value::Null));
3041        }
3042        Ok(Row {
3043            row_id,
3044            committed_epoch,
3045            columns,
3046            deleted,
3047            commit_ts,
3048        })
3049    }
3050
3051    /// Every row in the run (all versions), in `(RowId, Epoch)` order. Used by
3052    /// compaction, which must see every version to apply snapshot retention.
3053    pub fn all_rows(&mut self) -> Result<Vec<Row>> {
3054        let n = self.row_count();
3055        let mut out = Vec::with_capacity(n);
3056        for i in 0..n {
3057            out.push(self.materialize(i)?);
3058        }
3059        Ok(out)
3060    }
3061
3062    /// Every version with cooperative cancellation and a hard row bound.
3063    pub fn all_rows_controlled(
3064        &mut self,
3065        control: &crate::ExecutionControl,
3066        max_rows: usize,
3067    ) -> Result<Vec<Row>> {
3068        let n = self.row_count();
3069        if n > max_rows {
3070            return Err(MongrelError::ResourceLimitExceeded {
3071                resource: "controlled run row materialization",
3072                requested: n,
3073                limit: max_rows,
3074            });
3075        }
3076        let mut out = Vec::with_capacity(n);
3077        for i in 0..n {
3078            if i % 256 == 0 {
3079                control.checkpoint()?;
3080            }
3081            out.push(self.materialize(i)?);
3082        }
3083        control.checkpoint()?;
3084        Ok(out)
3085    }
3086
3087    /// Indices of the newest non-deleted version per `RowId` visible at
3088    /// `snapshot`, ascending. This is the columnar scan primitive: compute the
3089    /// visible set once (one pass over the row-id/epoch/deleted columns), then
3090    /// [`Self::gather_column`] each user column at these indices — no per-row
3091    /// `HashMap`/`Row` materialization.
3092    pub fn visible_indices(&mut self, snapshot: Epoch) -> Result<Vec<usize>> {
3093        let n = self.row_count();
3094        if n == 0 {
3095            return Ok(Vec::new());
3096        }
3097        let row_ids = self.column(SYS_ROW_ID)?.to_vec();
3098        let epochs = self.column(SYS_EPOCH)?.to_vec();
3099        let deleted = self.column(SYS_DELETED)?.to_vec();
3100        let mut best: HashMap<u64, (u64, usize)> = HashMap::new();
3101        for i in 0..n {
3102            let rid = int_at(&row_ids, i);
3103            let e = int_at(&epochs, i);
3104            if e > snapshot.0 {
3105                continue;
3106            }
3107            best.entry(rid)
3108                .and_modify(|(be, bi)| {
3109                    if e > *be {
3110                        *be = e;
3111                        *bi = i;
3112                    }
3113                })
3114                .or_insert((e, i));
3115        }
3116        let mut idxs: Vec<usize> = best.into_values().map(|(_, i)| i).collect();
3117        idxs.retain(|&i| !bool_at(&deleted, i));
3118        idxs.sort_unstable();
3119        Ok(idxs)
3120    }
3121
3122    /// Gather `column_id`'s values at the given indices (column cached). Used
3123    /// with [`Self::visible_indices`] for vectorized scans. A column absent from
3124    /// this run (e.g. added via schema evolution after the run was written)
3125    /// yields all-nulls.
3126    pub fn gather_column(&mut self, column_id: u16, indices: &[usize]) -> Result<Vec<Value>> {
3127        if !self.dir.iter().any(|h| h.column_id == column_id) {
3128            return Ok(vec![Value::Null; indices.len()]);
3129        }
3130        let col = self.column(column_id)?;
3131        Ok(indices
3132            .iter()
3133            .map(|&i| col.get(i).cloned().unwrap_or(Value::Null))
3134            .collect())
3135    }
3136
3137    /// Decode a column straight to a typed [`NativeColumn`] (no `Value`),
3138    /// concatenating all pages. A column absent from this run (schema evolution)
3139    /// yields an all-null column. Pages are decoded in parallel (rayon) when the
3140    /// run is mmap-backed and has more than one page; otherwise sequentially.
3141    pub fn column_native(&mut self, column_id: u16) -> Result<columnar::NativeColumn> {
3142        use rayon::prelude::*;
3143        if column_id == SYS_EPOCH {
3144            if let Some(ov) = self.epoch_override {
3145                return Ok(columnar::NativeColumn::int64_constant(
3146                    ov.0 as i64,
3147                    self.row_count(),
3148                ));
3149            }
3150        }
3151        let ty = self.resolve_type(column_id);
3152        let n = self.row_count();
3153        let Some(ch) = self.dir.iter().find(|h| h.column_id == column_id) else {
3154            return Ok(columnar::null_native(ty, n));
3155        };
3156        let page_count = ch.page_count as usize;
3157        let page_rows: Vec<usize> = ch.page_stats.iter().map(|s| s.row_count as usize).collect();
3158        if page_count == 0 {
3159            return Ok(columnar::null_native(ty, n));
3160        }
3161        let parts: Vec<columnar::NativeColumn> = if self.mmap.is_some() && page_count > 1 {
3162            // Parallel decode: each page is an independent region of the shared
3163            // mmap; the cipher (if any) is Sync. Spread the (CPU-bound) decode
3164            // across the rayon thread pool.
3165            let reader: &RunReader = self;
3166            (0..page_count)
3167                .into_par_iter()
3168                .map(|seq| {
3169                    let raw = reader.read_page_shared(column_id, seq)?;
3170                    columnar::decode_page_native(ty.clone(), &raw, page_rows[seq])
3171                })
3172                .collect::<Result<Vec<_>>>()?
3173        } else {
3174            let mut out = Vec::with_capacity(page_count);
3175            for (seq, &pr) in page_rows.iter().enumerate() {
3176                let page = self.read_page(column_id, seq)?;
3177                out.push(columnar::decode_page_native(ty.clone(), &page, pr)?);
3178            }
3179            out
3180        };
3181        Ok(columnar::NativeColumn::concat(&parts))
3182    }
3183
3184    /// Whether this reader is backed by a memory map (the prerequisite for the
3185    /// `&self` parallel decode paths). Readers on filesystems that reject mmap
3186    /// fall back to per-page `read()` and `has_mmap()` is false.
3187    pub fn has_mmap(&self) -> bool {
3188        self.mmap.is_some()
3189    }
3190
3191    /// `&self` variant of [`column_native`] for cross-column parallel scans
3192    /// (Phase 15.1). Requires the mmap backing (uses [`read_page_shared`], which
3193    /// is rayon-safe); callers without mmap use the `&mut` [`column_native`].
3194    /// Pages within the column decode in parallel when there is more than one,
3195    /// and `MADV_WILLNEED` is hinted up front so the kernel pre-faults the whole
3196    /// column's byte range (Phase 15.2) before the decode workers touch it.
3197    pub fn column_native_shared(&self, column_id: u16) -> Result<columnar::NativeColumn> {
3198        use rayon::prelude::*;
3199        if column_id == SYS_EPOCH {
3200            if let Some(ov) = self.epoch_override {
3201                return Ok(columnar::NativeColumn::int64_constant(
3202                    ov.0 as i64,
3203                    self.row_count(),
3204                ));
3205            }
3206        }
3207        let ty = self.resolve_type(column_id);
3208        let n = self.row_count();
3209        let Some(ch) = self.dir.iter().find(|h| h.column_id == column_id) else {
3210            return Ok(columnar::null_native(ty, n));
3211        };
3212        let page_count = ch.page_count as usize;
3213        let page_rows: Vec<usize> = ch.page_stats.iter().map(|s| s.row_count as usize).collect();
3214        if page_count == 0 {
3215            return Ok(columnar::null_native(ty, n));
3216        }
3217        // Phase 15.2: best-effort read-ahead. Tell the kernel to page-in the
3218        // column's full byte range before the workers fan out, overlapping the
3219        // disk I/O with the upcoming decode CPU.
3220        #[cfg(unix)]
3221        {
3222            if let (Some(m), Some(first)) = (&self.mmap, ch.page_stats.first()) {
3223                let start = first.offset as usize;
3224                let end = (ch.page_region_offset as usize) + (ch.page_region_len as usize);
3225                if end > start {
3226                    let _ = m.advise_range(memmap2::Advice::WillNeed, start, end - start);
3227                }
3228            }
3229        }
3230        let run_id = self.header.run_id;
3231        // Decode in parallel (cache probes use `try_lock` → no worker blocking).
3232        // Each item is the decoded page plus its key when it was a cache miss
3233        // (hits return `None` for the key so we don't re-insert/clone them).
3234        let mut parts_keys: Vec<(columnar::NativeColumn, Option<[u8; 32]>)> = if page_count > 1 {
3235            (0..page_count)
3236                .into_par_iter()
3237                .map(|seq| {
3238                    self.decode_page_cached(ty.clone(), column_id, seq, page_rows[seq], run_id)
3239                })
3240                .collect::<Result<Vec<_>>>()?
3241        } else {
3242            vec![self.decode_page_cached(ty, column_id, 0, page_rows[0], run_id)?]
3243        };
3244        // Sequentially cache the freshly-decoded pages — no parallel contention
3245        // on the insert, so every miss is reliably stored for the next scan.
3246        if let Some(cache) = &self.decoded_cache {
3247            for (col, key) in parts_keys.iter_mut() {
3248                if let Some(k) = key.take() {
3249                    cache.lock(&k).insert(k, Arc::new(col.clone()));
3250                }
3251            }
3252        }
3253        let parts: Vec<columnar::NativeColumn> = parts_keys.into_iter().map(|(c, _)| c).collect();
3254        Ok(columnar::NativeColumn::concat(&parts))
3255    }
3256
3257    /// Decode one page for the shared scan path, consulting the decoded-page
3258    /// cache first (Phase 15.4). Returns the decoded page plus `Some(key)` on a
3259    /// cache miss (so the caller can insert it) or `None` on a hit (already
3260    /// cached). Cache probes use `try_lock` so rayon workers never block.
3261    fn decode_page_cached(
3262        &self,
3263        ty: TypeId,
3264        column_id: u16,
3265        seq: usize,
3266        nrows: usize,
3267        run_id: u128,
3268    ) -> Result<(columnar::NativeColumn, Option<[u8; 32]>)> {
3269        let key = page_cache_key(self.table_id, run_id, column_id, seq);
3270        if let Some(cache) = &self.decoded_cache {
3271            if let Some(g) = cache.try_lock(&key) {
3272                if let Some(hit) = g.try_get(&key) {
3273                    return Ok(((*hit).clone(), None));
3274                }
3275            }
3276        }
3277        let raw = self.read_page_shared(column_id, seq)?;
3278        let col = columnar::decode_page_native(ty, &raw, nrows)?;
3279        Ok((col, Some(key)))
3280    }
3281
3282    /// [`Self::decode_page_cached`], but for the sequential point-lookup paths
3283    /// (`find_version_page`, `materialize_in_page`, `get_version_column`) via
3284    /// [`Self::read_page`] (handles the non-mmap-backed fallback) instead of
3285    /// [`Self::read_page_shared`] (mmap-only, for the parallel rayon scan
3286    /// path). No rayon pool to avoid blocking here, so a plain `.lock()` is
3287    /// fine — unlike the scan path's `try_lock`, this always consults the
3288    /// cache rather than skipping it under contention. Without this, every
3289    /// point lookup re-decompressed its page from scratch even when a prior
3290    /// lookup had just decoded the exact same page (the dominant remaining
3291    /// cost measured for `remove_hot_for_row`'s on-disk path).
3292    fn decode_page_native_cached(
3293        &mut self,
3294        ty: TypeId,
3295        column_id: u16,
3296        seq: usize,
3297        nrows: usize,
3298    ) -> Result<columnar::NativeColumn> {
3299        let key = page_cache_key(self.table_id, self.header.run_id, column_id, seq);
3300        if let Some(cache) = &self.decoded_cache {
3301            if let Some(hit) = cache.lock(&key).try_get(&key) {
3302                return Ok((*hit).clone());
3303            }
3304        }
3305        let raw = self.read_page(column_id, seq)?;
3306        let col = columnar::decode_page_native(ty, &raw, nrows)?;
3307        if let Some(cache) = &self.decoded_cache {
3308            cache
3309                .lock(&key)
3310                .insert(key, std::sync::Arc::new(col.clone()));
3311        }
3312        Ok(col)
3313    }
3314
3315    /// Row ids whose Int64 value is in `[lo, hi]`, **skipping pages whose
3316    /// `[min,max]` stat excludes the range** (Parquet-style page-index pruning).
3317    /// Nulls are excluded. Used by `Table::query_columns_native` to serve
3318    /// `Condition::Range` without decoding every page.
3319    pub fn range_row_ids_i64(
3320        &mut self,
3321        column_id: u16,
3322        lo: i64,
3323        hi: i64,
3324    ) -> Result<std::collections::HashSet<u64>> {
3325        Ok(self
3326            .range_row_id_set_i64(column_id, lo, hi)?
3327            .into_sorted_vec()
3328            .into_iter()
3329            .collect())
3330    }
3331
3332    pub(crate) fn range_row_id_set_i64(
3333        &mut self,
3334        column_id: u16,
3335        lo: i64,
3336        hi: i64,
3337    ) -> Result<RowIdSet> {
3338        let info: Vec<(Option<i64>, Option<i64>, usize)> =
3339            match self.dir.iter().find(|h| h.column_id == column_id) {
3340                Some(ch) => ch
3341                    .page_stats
3342                    .iter()
3343                    .map(|s| {
3344                        (
3345                            be_i64(s.min.as_deref()),
3346                            be_i64(s.max.as_deref()),
3347                            s.row_count as usize,
3348                        )
3349                    })
3350                    .collect(),
3351                None => return Ok(RowIdSet::empty()),
3352            };
3353        // Encrypted columns are pruneable only when this run carries the
3354        // decrypted stats envelope (overlaid at open). Without one (a run
3355        // whose writer recorded no stats at all), a missing min/max means
3356        // "unknown" — never prune — whereas with the envelope (and always for
3357        // plaintext runs) a missing min/max means an all-null page.
3358        let stats_pruneable =
3359            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3360        let clean_contiguous = self.clean_contiguous_row_ids();
3361        let mut out = Vec::new();
3362        let mut page_start = 0usize;
3363        for (seq, (mn, mx, nrows)) in info.into_iter().enumerate() {
3364            let current_page_start = page_start;
3365            page_start += nrows;
3366            // Skip pages that cannot contain a match (or are all-null).
3367            let skip = stats_pruneable
3368                && match (mn, mx) {
3369                    (Some(mn), Some(mx)) => mx < lo || mn > hi,
3370                    _ => true,
3371                };
3372            if skip {
3373                continue;
3374            }
3375            let val_page = self.read_page(column_id, seq)?;
3376            let vals =
3377                columnar::decode_page_native(self.resolve_type(column_id), &val_page, nrows)?;
3378            if let columnar::NativeColumn::Int64 { data: v, validity } = vals {
3379                if clean_contiguous {
3380                    for (i, val) in v.iter().enumerate() {
3381                        if columnar::validity_bit(&validity, i) && *val >= lo && *val <= hi {
3382                            out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3383                        }
3384                    }
3385                } else {
3386                    let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3387                    let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3388                    if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3389                        for (i, val) in v.iter().enumerate() {
3390                            if columnar::validity_bit(&validity, i) && *val >= lo && *val <= hi {
3391                                out.push(r[i] as u64);
3392                            }
3393                        }
3394                    }
3395                }
3396            }
3397        }
3398        Ok(RowIdSet::from_unsorted(out))
3399    }
3400
3401    /// Float64 analogue of [`Self::range_row_ids_i64`] with per-bound
3402    /// inclusivity, for `Condition::RangeF64`.
3403    pub fn range_row_ids_f64(
3404        &mut self,
3405        column_id: u16,
3406        lo: f64,
3407        lo_inclusive: bool,
3408        hi: f64,
3409        hi_inclusive: bool,
3410    ) -> Result<std::collections::HashSet<u64>> {
3411        Ok(self
3412            .range_row_id_set_f64(column_id, lo, lo_inclusive, hi, hi_inclusive)?
3413            .into_sorted_vec()
3414            .into_iter()
3415            .collect())
3416    }
3417
3418    pub(crate) fn range_row_id_set_f64(
3419        &mut self,
3420        column_id: u16,
3421        lo: f64,
3422        lo_inclusive: bool,
3423        hi: f64,
3424        hi_inclusive: bool,
3425    ) -> Result<RowIdSet> {
3426        let info: Vec<(Option<f64>, Option<f64>, usize)> =
3427            match self.dir.iter().find(|h| h.column_id == column_id) {
3428                Some(ch) => ch
3429                    .page_stats
3430                    .iter()
3431                    .map(|s| {
3432                        (
3433                            be_f64(s.min.as_deref()),
3434                            be_f64(s.max.as_deref()),
3435                            s.row_count as usize,
3436                        )
3437                    })
3438                    .collect(),
3439                None => return Ok(RowIdSet::empty()),
3440            };
3441        // Encrypted columns are pruneable only when this run carries the
3442        // decrypted stats envelope (overlaid at open). Without one (a run
3443        // whose writer recorded no stats at all), a missing min/max means
3444        // "unknown" — never prune — whereas with the envelope (and always for
3445        // plaintext runs) a missing min/max means an all-null page.
3446        let stats_pruneable =
3447            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3448        let clean_contiguous = self.clean_contiguous_row_ids();
3449        let mut out = Vec::new();
3450        let mut page_start = 0usize;
3451        for (seq, (mn, mx, nrows)) in info.into_iter().enumerate() {
3452            let current_page_start = page_start;
3453            page_start += nrows;
3454            // A page can be dropped iff every value fails the predicate, i.e. the
3455            // largest fails the lo-test or the smallest fails the hi-test.
3456            let skip = stats_pruneable
3457                && match (mn, mx) {
3458                    (Some(mn), Some(mx)) => {
3459                        let skip_lo = mx < lo || (!lo_inclusive && mx == lo);
3460                        let skip_hi = mn > hi || (!hi_inclusive && mn == hi);
3461                        skip_lo || skip_hi
3462                    }
3463                    _ => true,
3464                };
3465            if skip {
3466                continue;
3467            }
3468            let val_page = self.read_page(column_id, seq)?;
3469            let vals = columnar::decode_page_native(TypeId::Float64, &val_page, nrows)?;
3470            if let columnar::NativeColumn::Float64 { data: v, validity } = vals {
3471                if clean_contiguous {
3472                    for (i, val) in v.iter().enumerate() {
3473                        if !columnar::validity_bit(&validity, i) || val.is_nan() {
3474                            continue;
3475                        }
3476                        let ok_lo = if lo_inclusive { *val >= lo } else { *val > lo };
3477                        let ok_hi = if hi_inclusive { *val <= hi } else { *val < hi };
3478                        if ok_lo && ok_hi {
3479                            out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3480                        }
3481                    }
3482                } else {
3483                    let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3484                    let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3485                    if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3486                        for (i, val) in v.iter().enumerate() {
3487                            if !columnar::validity_bit(&validity, i) || val.is_nan() {
3488                                continue;
3489                            }
3490                            let ok_lo = if lo_inclusive { *val >= lo } else { *val > lo };
3491                            let ok_hi = if hi_inclusive { *val <= hi } else { *val < hi };
3492                            if ok_lo && ok_hi {
3493                                out.push(r[i] as u64);
3494                            }
3495                        }
3496                    }
3497                }
3498            }
3499        }
3500        Ok(RowIdSet::from_unsorted(out))
3501    }
3502
3503    /// Page-pruned row-id set for `IS NULL` / `IS NOT NULL` on `column_id`.
3504    /// Skips pages whose `null_count` makes a match impossible (no nulls for
3505    /// `IS NULL`, all-nulls for `IS NOT NULL`), then decodes the validity bitmap
3506    /// of surviving pages to pinpoint matching rows.
3507    pub(crate) fn null_row_id_set(&mut self, column_id: u16, want_nulls: bool) -> Result<RowIdSet> {
3508        let stats: Vec<(usize, usize)> = match self.dir.iter().find(|h| h.column_id == column_id) {
3509            Some(ch) => ch
3510                .page_stats
3511                .iter()
3512                .map(|s| (s.null_count as usize, s.row_count as usize))
3513                .collect(),
3514            None => return Ok(RowIdSet::empty()),
3515        };
3516        let ty = self.resolve_type(column_id);
3517        let clean_contiguous = self.clean_contiguous_row_ids();
3518        let mut out = Vec::new();
3519        let mut page_start = 0usize;
3520        for (seq, (null_count, nrows)) in stats.into_iter().enumerate() {
3521            let current_page_start = page_start;
3522            page_start += nrows;
3523            // Skip pages that cannot match.
3524            if want_nulls && null_count == 0 {
3525                continue;
3526            }
3527            if !want_nulls && null_count == nrows {
3528                continue;
3529            }
3530            let val_page = self.read_page(column_id, seq)?;
3531            let col = columnar::decode_page_native(ty.clone(), &val_page, nrows)?;
3532            let validity = col.validity();
3533            if clean_contiguous {
3534                for i in 0..nrows {
3535                    let is_null = !columnar::validity_bit(validity, i);
3536                    if is_null == want_nulls {
3537                        out.push(self.header.min_row_id + current_page_start as u64 + i as u64);
3538                    }
3539                }
3540            } else {
3541                let rid_page = self.read_page(SYS_ROW_ID, seq)?;
3542                let rids = columnar::decode_page_native(TypeId::Int64, &rid_page, nrows)?;
3543                if let columnar::NativeColumn::Int64 { data: r, .. } = rids {
3544                    for (i, &rid) in r.iter().enumerate().take(nrows) {
3545                        let is_null = !columnar::validity_bit(validity, i);
3546                        if is_null == want_nulls {
3547                            out.push(rid as u64);
3548                        }
3549                    }
3550                }
3551            }
3552        }
3553        Ok(RowIdSet::from_unsorted(out))
3554    }
3555
3556    pub fn visible_indices_native(&mut self, snapshot: Epoch) -> Result<Vec<usize>> {
3557        let n = self.row_count();
3558        if n == 0 {
3559            return Ok(Vec::new());
3560        }
3561        let (row_ids, epochs, deleted) = self.system_columns_native()?;
3562        let mut best: HashMap<u64, (u64, usize)> = HashMap::new();
3563        for i in 0..n {
3564            let rid = row_ids[i] as u64;
3565            let e = epochs[i] as u64;
3566            if e > snapshot.0 {
3567                continue;
3568            }
3569            best.entry(rid)
3570                .and_modify(|(be, bi)| {
3571                    if e > *be {
3572                        *be = e;
3573                        *bi = i;
3574                    }
3575                })
3576                .or_insert((e, i));
3577        }
3578        let mut idxs: Vec<usize> = best.into_values().map(|(_, i)| i).collect();
3579        idxs.retain(|&i| deleted[i] == 0);
3580        idxs.sort_unstable();
3581        Ok(idxs)
3582    }
3583
3584    /// Page-pruned, **MVCC-visible** Int64 range resolution (Phase 16.3).
3585    ///
3586    /// Like [`Self::range_row_ids_i64`] (skips pages whose `[min,max]` excludes
3587    /// `[lo, hi]`) but restricts the output to the newest non-deleted version per
3588    /// `RowId` visible at `snapshot`. This is the layout-independent range
3589    /// primitive: correct under any memtable / multi-run / deletion-vector state,
3590    /// so the engine no longer has to fall back to a full-column decode when the
3591    /// "single clean run" invariant doesn't hold. Nulls are excluded.
3592    pub fn range_row_ids_visible_i64(
3593        &mut self,
3594        column_id: u16,
3595        lo: i64,
3596        hi: i64,
3597        snapshot: Epoch,
3598    ) -> Result<Vec<u64>> {
3599        let stats: Vec<(Option<i64>, Option<i64>, usize)> = match self.column_page_stats(column_id)
3600        {
3601            Some(s) => s
3602                .iter()
3603                .map(|st| {
3604                    (
3605                        be_i64(st.min.as_deref()),
3606                        be_i64(st.max.as_deref()),
3607                        st.row_count as usize,
3608                    )
3609                })
3610                .collect(),
3611            None => return Ok(Vec::new()),
3612        };
3613        // Encrypted columns are pruneable only when this run carries the
3614        // decrypted stats envelope (overlaid at open). Without one (a run
3615        // whose writer recorded no stats at all), a missing min/max means
3616        // "unknown" — never prune — whereas with the envelope (and always for
3617        // plaintext runs) a missing min/max means an all-null page.
3618        let stats_pruneable =
3619            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3620        let (positions, rids) = self.visible_positions_with_rids(snapshot)?;
3621        let mut out: Vec<u64> = Vec::new();
3622        let mut vis = 0usize;
3623        let mut page_start = 0usize;
3624        for (seq, &(mn, mx, nrows)) in stats.iter().enumerate() {
3625            let page_end = page_start + nrows;
3626            // A page can be dropped iff every value fails the predicate.
3627            let skip = stats_pruneable
3628                && match (mn, mx) {
3629                    (Some(mn), Some(mx)) => mx < lo || mn > hi,
3630                    _ => true, // all-null / no stats → nulls never match
3631                };
3632            if !skip {
3633                let val_page = self.read_page(column_id, seq)?;
3634                let vals = columnar::decode_page_native(TypeId::Int64, &val_page, nrows)?;
3635                if let columnar::NativeColumn::Int64 { data: v, validity } = vals {
3636                    while vis < positions.len() && positions[vis] < page_end {
3637                        let local = positions[vis] - page_start;
3638                        if columnar::validity_bit(&validity, local)
3639                            && v[local] >= lo
3640                            && v[local] <= hi
3641                        {
3642                            out.push(rids[vis] as u64);
3643                        }
3644                        vis += 1;
3645                    }
3646                }
3647            } else {
3648                while vis < positions.len() && positions[vis] < page_end {
3649                    vis += 1;
3650                }
3651            }
3652            page_start = page_end;
3653        }
3654        Ok(out)
3655    }
3656
3657    /// Float64 analogue of [`Self::range_row_ids_visible_i64`] with per-bound
3658    /// inclusivity (Phase 16.3).
3659    pub fn range_row_ids_visible_f64(
3660        &mut self,
3661        column_id: u16,
3662        lo: f64,
3663        lo_inclusive: bool,
3664        hi: f64,
3665        hi_inclusive: bool,
3666        snapshot: Epoch,
3667    ) -> Result<Vec<u64>> {
3668        let stats: Vec<(Option<f64>, Option<f64>, usize)> = match self.column_page_stats(column_id)
3669        {
3670            Some(s) => s
3671                .iter()
3672                .map(|st| {
3673                    (
3674                        be_f64(st.min.as_deref()),
3675                        be_f64(st.max.as_deref()),
3676                        st.row_count as usize,
3677                    )
3678                })
3679                .collect(),
3680            None => return Ok(Vec::new()),
3681        };
3682        // Encrypted columns are pruneable only when this run carries the
3683        // decrypted stats envelope (overlaid at open). Without one (a run
3684        // whose writer recorded no stats at all), a missing min/max means
3685        // "unknown" — never prune — whereas with the envelope (and always for
3686        // plaintext runs) a missing min/max means an all-null page.
3687        let stats_pruneable =
3688            !self.col_encrypted(column_id) || self.header.encrypted_stats_offset != 0;
3689        let (positions, rids) = self.visible_positions_with_rids(snapshot)?;
3690        let mut out: Vec<u64> = Vec::new();
3691        let mut vis = 0usize;
3692        let mut page_start = 0usize;
3693        for (seq, &(mn, mx, nrows)) in stats.iter().enumerate() {
3694            let page_end = page_start + nrows;
3695            let skip = stats_pruneable
3696                && match (mn, mx) {
3697                    (Some(mn), Some(mx)) => {
3698                        let skip_lo = mx < lo || (!lo_inclusive && mx == lo);
3699                        let skip_hi = mn > hi || (!hi_inclusive && mn == hi);
3700                        skip_lo || skip_hi
3701                    }
3702                    _ => true,
3703                };
3704            if !skip {
3705                let val_page = self.read_page(column_id, seq)?;
3706                let vals = columnar::decode_page_native(TypeId::Float64, &val_page, nrows)?;
3707                if let columnar::NativeColumn::Float64 { data: v, validity } = vals {
3708                    while vis < positions.len() && positions[vis] < page_end {
3709                        let local = positions[vis] - page_start;
3710                        if columnar::validity_bit(&validity, local) && !v[local].is_nan() {
3711                            let val = v[local];
3712                            let ok_lo = if lo_inclusive { val >= lo } else { val > lo };
3713                            let ok_hi = if hi_inclusive { val <= hi } else { val < hi };
3714                            if ok_lo && ok_hi {
3715                                out.push(rids[vis] as u64);
3716                            }
3717                        }
3718                        vis += 1;
3719                    }
3720                }
3721            } else {
3722                while vis < positions.len() && positions[vis] < page_end {
3723                    vis += 1;
3724                }
3725            }
3726            page_start = page_end;
3727        }
3728        Ok(out)
3729    }
3730
3731    /// MVCC-visible `IS NULL` / `IS NOT NULL` resolution. Follows the same
3732    /// page-stat-pruned + visible-positions pattern as
3733    /// [`Self::range_row_ids_visible_i64`], but checks the validity bitmap
3734    /// instead of a value range. Pages with no nulls (for IS NULL) or all-nulls
3735    /// (for IS NOT NULL) are skipped.
3736    pub fn null_row_ids_visible(
3737        &mut self,
3738        column_id: u16,
3739        want_nulls: bool,
3740        snapshot: Epoch,
3741    ) -> Result<Vec<u64>> {
3742        let stats: Vec<(usize, usize)> = match self.column_page_stats(column_id) {
3743            Some(s) => s
3744                .iter()
3745                .map(|st| (st.null_count as usize, st.row_count as usize))
3746                .collect(),
3747            None => return Ok(Vec::new()),
3748        };
3749        let ty = self.resolve_type(column_id);
3750        let (positions, rids) = self.visible_positions_with_rids(snapshot)?;
3751        let mut out: Vec<u64> = Vec::new();
3752        let mut vis = 0usize;
3753        let mut page_start = 0usize;
3754        for (seq, &(null_count, nrows)) in stats.iter().enumerate() {
3755            let page_end = page_start + nrows;
3756            let skip = (want_nulls && null_count == 0) || (!want_nulls && null_count == nrows);
3757            if !skip {
3758                let val_page = self.read_page(column_id, seq)?;
3759                let col = columnar::decode_page_native(ty.clone(), &val_page, nrows)?;
3760                let validity = col.validity();
3761                while vis < positions.len() && positions[vis] < page_end {
3762                    let local = positions[vis] - page_start;
3763                    let is_null = !columnar::validity_bit(validity, local);
3764                    if is_null == want_nulls {
3765                        out.push(rids[vis] as u64);
3766                    }
3767                    vis += 1;
3768                }
3769            } else {
3770                while vis < positions.len() && positions[vis] < page_end {
3771                    vis += 1;
3772                }
3773            }
3774            page_start = page_end;
3775        }
3776        Ok(out)
3777    }
3778
3779    /// tombstones excluded) paired with each position's `RowId`, in one pass.
3780    /// Used by [`crate::cursor::NativePageCursor`] to map survivors to pages
3781    /// without re-decoding the system columns.
3782    pub fn visible_positions_with_rids(
3783        &mut self,
3784        snapshot: Epoch,
3785    ) -> Result<(Vec<usize>, Vec<i64>)> {
3786        let n = self.row_count();
3787        if n == 0 {
3788            return Ok((Vec::new(), Vec::new()));
3789        }
3790        // Clean-run fast path (Phase 16.3c): one version per RowId, no
3791        // tombstones, ascending row_ids ⟹ every position is the newest (and
3792        // only) visible version. Skip decoding epoch/deleted and the group-
3793        // collapse loop; just decode row_ids (needed for survivor↔position
3794        // mapping) and return identity positions [0..n).
3795        // A uniform-epoch overlay must still gate by snapshot, so skip the clean
3796        // fast path when an override is active (defensive: spill runs are never
3797        // written clean).
3798        if self.is_clean()
3799            && self.epoch_override.is_none()
3800            && self.header.epoch_created <= snapshot.0
3801        {
3802            let row_ids = match self.column_native_shared(SYS_ROW_ID)? {
3803                columnar::NativeColumn::Int64 { data, .. } => data,
3804                _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
3805            };
3806            let positions: Vec<usize> = (0..n).collect();
3807            return Ok((positions, row_ids));
3808        }
3809        let (row_ids, epochs, deleted) = self.system_columns_native()?;
3810        // Runs are written in `(RowId, Epoch)` ascending order (Bε-tree
3811        // composite key), so same-rid positions are consecutive with the
3812        // newest (highest epoch) last. One linear pass keeps the last position
3813        // per rid with `epoch <= snapshot`, dropping tombstones — no HashMap,
3814        // no per-row hashing, sequential memory access. (Phase 16.3.)
3815        //
3816        // Invariant: every write path (memtable drain, mutable-run spill,
3817        // bulk_load's sequential alloc) produces runs in this order; if a path
3818        // ever wrote an unsorted run this would under-count (only consecutive
3819        // dup groups merge) and must be reverted to the HashMap form.
3820        let mut idxs: Vec<usize> = Vec::new();
3821        let mut i = 0;
3822        while i < n {
3823            let rid = row_ids[i] as u64;
3824            // Walk the consecutive rid group; epochs rise within it, so the
3825            // last position with epoch <= snapshot is the newest visible one.
3826            let mut best: Option<usize> = None;
3827            let mut j = i;
3828            while j < n && row_ids[j] as u64 == rid {
3829                if epochs[j] as u64 <= snapshot.0 {
3830                    best = Some(j);
3831                }
3832                j += 1;
3833            }
3834            if let Some(b) = best {
3835                if deleted[b] == 0 {
3836                    idxs.push(b);
3837                }
3838            }
3839            i = j;
3840        }
3841        // Groups are processed in rid-ascending = position-ascending order.
3842        let rids: Vec<i64> = idxs.iter().map(|&k| row_ids[k]).collect();
3843        Ok((idxs, rids))
3844    }
3845
3846    /// Row count of each PAX page of `column_id`, in page order. Every column
3847    /// in a run shares the same PAX row partition, so this yields the table's
3848    /// page layout (cumulative sums give page start offsets).
3849    pub fn page_row_counts(&self, column_id: u16) -> Result<Vec<usize>> {
3850        Ok(self
3851            .find_header(column_id)?
3852            .page_stats
3853            .iter()
3854            .map(|s| s.row_count as usize)
3855            .collect())
3856    }
3857
3858    /// Whether this run stores `column_id` (false for a column added via
3859    /// `add_column` after the run was written — those read as all-null).
3860    pub fn has_column(&self, column_id: u16) -> bool {
3861        self.dir.iter().any(|h| h.column_id == column_id)
3862    }
3863
3864    /// The per-page [`PageStat`]s for `column_id`, or `None` if the column is
3865    /// absent from this run (schema evolution). Used to compute exact column
3866    /// min/max/null_count for the analytical aggregate fast path.
3867    pub fn column_page_stats(&self, column_id: u16) -> Option<&[crate::page::PageStat]> {
3868        self.dir
3869            .iter()
3870            .find(|h| h.column_id == column_id)
3871            .map(|ch| ch.page_stats.as_slice())
3872    }
3873
3874    /// Decode the system columns once, as typed buffers. Uses the shared
3875    /// parallel + decoded-page-cached path (`column_native_shared`) so the
3876    /// row-id/epoch/deleted pages decode concurrently and stay cached across
3877    /// queries — MVCC visibility resolution is on every scan's hot path.
3878    pub(crate) fn system_columns_native(&mut self) -> Result<(Vec<i64>, Vec<i64>, Vec<u8>)> {
3879        let row_ids = match self.column_native_shared(SYS_ROW_ID)? {
3880            columnar::NativeColumn::Int64 { data, .. } => data,
3881            _ => return Err(MongrelError::InvalidArgument("sys row_id not int64".into())),
3882        };
3883        let epochs = match self.column_native_shared(SYS_EPOCH)? {
3884            columnar::NativeColumn::Int64 { data, .. } => data,
3885            _ => return Err(MongrelError::InvalidArgument("sys epoch not int64".into())),
3886        };
3887        let deleted = match self.column_native_shared(SYS_DELETED)? {
3888            columnar::NativeColumn::Bool { data, .. } => data,
3889            _ => return Err(MongrelError::InvalidArgument("sys deleted not bool".into())),
3890        };
3891        Ok((row_ids, epochs, deleted))
3892    }
3893
3894    /// Newest visible version per `RowId` at `snapshot`, **including
3895    /// tombstones** (as `Row`s with `deleted=true`). Ascending `RowId`. Used by
3896    /// the engine to merge versions across runs and the memtable.
3897    ///
3898    /// HLC stamps are restored when [`SYS_COMMIT_TS`] is present (P0.5-T3);
3899    /// legacy runs without the column materialise `commit_ts: None`. Callers
3900    /// that hold a full [`crate::epoch::Snapshot`] still apply
3901    /// [`crate::epoch::Snapshot::observes_row`].
3902    pub fn visible_versions(&mut self, snapshot: Epoch) -> Result<Vec<Row>> {
3903        let n = self.row_count();
3904        if n == 0 {
3905            return Ok(Vec::new());
3906        }
3907        let row_ids = self.column(SYS_ROW_ID)?.to_vec();
3908        let epochs = self.column(SYS_EPOCH)?.to_vec();
3909        let mut best: HashMap<u64, (u64, usize)> = HashMap::new();
3910        for i in 0..n {
3911            let rid = int_at(&row_ids, i);
3912            let epoch = int_at(&epochs, i);
3913            if epoch > snapshot.0 {
3914                continue;
3915            }
3916            best.entry(rid)
3917                .and_modify(|e| {
3918                    if epoch > e.0 {
3919                        *e = (epoch, i);
3920                    }
3921                })
3922                .or_insert((epoch, i));
3923        }
3924        let mut picks: Vec<usize> = best.into_values().map(|(_, i)| i).collect();
3925        picks.sort();
3926        let mut out = Vec::with_capacity(picks.len());
3927        for i in picks {
3928            out.push(self.materialize(i)?);
3929        }
3930        Ok(out)
3931    }
3932
3933    /// All non-deleted rows visible at `snapshot`. Ascending `RowId`.
3934    pub fn visible_rows(&mut self, snapshot: Epoch) -> Result<Vec<Row>> {
3935        Ok(self
3936            .visible_versions(snapshot)?
3937            .into_iter()
3938            .filter(|r| !r.deleted)
3939            .collect())
3940    }
3941
3942    pub(crate) fn materialize(&mut self, index: usize) -> Result<Row> {
3943        let row_id = RowId(int_at(self.column(SYS_ROW_ID)?, index));
3944        let epoch = Epoch(int_at(self.column(SYS_EPOCH)?, index));
3945        let deleted = bool_at(self.column(SYS_DELETED)?, index);
3946        let commit_ts = self.commit_ts_at(index)?;
3947        let col_ids: Vec<u16> = self.schema.columns.iter().map(|c| c.id).collect();
3948        let mut columns = HashMap::new();
3949        for id in col_ids {
3950            let val = if self.dir.iter().any(|h| h.column_id == id) {
3951                self.column(id)?.get(index).cloned().unwrap_or(Value::Null)
3952            } else {
3953                // Column added via schema evolution after this run was written.
3954                Value::Null
3955            };
3956            columns.insert(id, val);
3957        }
3958        Ok(Row {
3959            row_id,
3960            committed_epoch: epoch,
3961            columns,
3962            deleted,
3963            commit_ts,
3964        })
3965    }
3966
3967    /// Batched row materialization (Phase 16.3b finish): decode each system +
3968    /// user column **once** via the typed, page-cached `column_native` path and
3969    /// gather only the requested `indices` straight into `Row`s. This replaces
3970    /// N independent `materialize` calls, each of which rebuilt a full-column
3971    /// `Vec<Value>` (heap-allocating one `Value` per row) and then `.cloned()`
3972    /// a single slot. Exact semantics retained: schema-evolved columns absent
3973    /// from this run read `Value::Null`; deleted rows are still returned (the
3974    /// caller filters them).
3975    pub(crate) fn materialize_batch(&mut self, indices: &[usize]) -> Result<Vec<Row>> {
3976        if indices.is_empty() {
3977            return Ok(Vec::new());
3978        }
3979        use std::collections::HashMap;
3980        let rid_col = self.column_native_shared(SYS_ROW_ID)?;
3981        let epoch_col = self.column_native_shared(SYS_EPOCH)?;
3982        let del_col = self.column_native_shared(SYS_DELETED)?;
3983        let commit_ts_col = if self.has_column(SYS_COMMIT_TS) {
3984            Some(self.column_native_shared(SYS_COMMIT_TS)?)
3985        } else {
3986            None
3987        };
3988        let mut user: HashMap<u16, columnar::NativeColumn> = HashMap::new();
3989        let present: Vec<u16> = self
3990            .schema
3991            .columns
3992            .iter()
3993            .map(|c| c.id)
3994            .filter(|id| self.dir.iter().any(|h| h.column_id == *id))
3995            .collect();
3996        for id in present {
3997            user.insert(id, self.column_native(id)?);
3998        }
3999        let i64_at = |col: &columnar::NativeColumn, i: usize| -> i64 {
4000            match col {
4001                columnar::NativeColumn::Int64 { data, .. } => data.get(i).copied().unwrap_or(0),
4002                _ => 0,
4003            }
4004        };
4005        let bool_at_native = |col: &columnar::NativeColumn, i: usize| -> bool {
4006            match col {
4007                columnar::NativeColumn::Bool { data, .. } => {
4008                    data.get(i).copied().map(|b| b != 0).unwrap_or(false)
4009                }
4010                _ => false,
4011            }
4012        };
4013        let mut rows = Vec::with_capacity(indices.len());
4014        for &idx in indices {
4015            let row_id = RowId(i64_at(&rid_col, idx) as u64);
4016            let epoch = Epoch(i64_at(&epoch_col, idx) as u64);
4017            let deleted = bool_at_native(&del_col, idx);
4018            let commit_ts = commit_ts_col
4019                .as_ref()
4020                .and_then(|col| decode_commit_ts_value(col.value_at(idx).as_ref()));
4021            let mut columns = HashMap::with_capacity(self.schema.columns.len());
4022            for cdef in self.schema.columns.iter() {
4023                let val = match user.get(&cdef.id) {
4024                    Some(col) => col.value_at(idx).unwrap_or(Value::Null),
4025                    None => Value::Null,
4026                };
4027                columns.insert(cdef.id, val);
4028            }
4029            rows.push(Row {
4030                row_id,
4031                committed_epoch: epoch,
4032                columns,
4033                deleted,
4034                commit_ts,
4035            });
4036        }
4037        Ok(rows)
4038    }
4039}
4040
4041fn int_at(vals: &[Value], i: usize) -> u64 {
4042    match vals.get(i) {
4043        Some(Value::Int64(x)) => *x as u64,
4044        _ => 0,
4045    }
4046}
4047
4048fn bool_at(vals: &[Value], i: usize) -> bool {
4049    matches!(vals.get(i), Some(Value::Bool(true)))
4050}
4051
4052#[cfg(test)]
4053mod tests {
4054    use super::*;
4055    use crate::columnar::NativeColumn;
4056    use crate::memtable::Value;
4057    use crate::rowid::RowId;
4058    use crate::schema::{ColumnDef, ColumnFlags};
4059    use tempfile::tempdir;
4060
4061    fn schema() -> Schema {
4062        Schema {
4063            schema_id: 1,
4064            columns: vec![
4065                ColumnDef {
4066                    id: 1,
4067                    name: "id".into(),
4068                    ty: TypeId::Int64,
4069                    flags: ColumnFlags::empty().with(ColumnFlags::PRIMARY_KEY),
4070                    default_value: None,
4071                    embedding_source: None,
4072                },
4073                ColumnDef {
4074                    id: 2,
4075                    name: "name".into(),
4076                    ty: TypeId::Bytes,
4077                    flags: ColumnFlags::empty(),
4078                    default_value: None,
4079                    embedding_source: None,
4080                },
4081            ],
4082            indexes: Vec::new(),
4083            colocation: vec![],
4084            constraints: Default::default(),
4085            clustered: false,
4086        }
4087    }
4088
4089    fn rows() -> Vec<Row> {
4090        vec![
4091            Row::new(RowId(1), Epoch(10))
4092                .with_column(1, Value::Int64(1))
4093                .with_column(2, Value::Bytes(b"alice".to_vec())),
4094            Row::new(RowId(2), Epoch(10))
4095                .with_column(1, Value::Int64(2))
4096                .with_column(2, Value::Bytes(b"bob".to_vec())),
4097            Row::new(RowId(3), Epoch(10))
4098                .with_column(1, Value::Int64(3))
4099                .with_column(2, Value::Bytes(b"carol".to_vec())),
4100        ]
4101    }
4102
4103    #[test]
4104    fn flush_then_read_mvcc() {
4105        let dir = tempdir().unwrap();
4106        let path = dir.path().join("r-1.sr");
4107        let header = RunWriter::new(&schema(), 1, Epoch(10), 0)
4108            .write(&path, &rows())
4109            .unwrap();
4110        assert_eq!(header.row_count, 3);
4111
4112        let mut r = RunReader::open(&path, schema(), None).unwrap();
4113        // Point lookup.
4114        let (e, row) = r.get_version(RowId(2), Epoch(20)).unwrap().unwrap();
4115        assert_eq!(e, Epoch(10));
4116        assert_eq!(row.row_id, RowId(2));
4117        assert!(matches!(row.columns.get(&2), Some(Value::Bytes(_))));
4118        // Missing.
4119        assert!(r.get_version(RowId(99), Epoch(20)).unwrap().is_none());
4120        // Scan.
4121        let all = r.visible_rows(Epoch(20)).unwrap();
4122        assert_eq!(all.len(), 3);
4123        // Unstamped flush omits SYS_COMMIT_TS (legacy path).
4124        assert!(!r.has_column(SYS_COMMIT_TS));
4125        assert!(all.iter().all(|row| row.commit_ts.is_none()));
4126    }
4127
4128    /// ID: P0.5-T3 — flush preserves HLC stamps via optional SYS_COMMIT_TS;
4129    /// legacy runs without the column materialise commit_ts as None.
4130    #[test]
4131    fn p05_t3_sys_commit_ts_preserved_on_flush_and_legacy_is_none() {
4132        let dir = tempdir().unwrap();
4133        let stamped_path = dir.path().join("r-hlc.sr");
4134        let stamp = HlcTimestamp {
4135            physical_micros: 42_000_000,
4136            logical: 7,
4137            node_tiebreaker: 3,
4138        };
4139        let stamped = vec![
4140            Row::new_with_hlc(RowId(1), Epoch(10), stamp)
4141                .with_column(1, Value::Int64(1))
4142                .with_column(2, Value::Bytes(b"alice".to_vec())),
4143            Row::new(RowId(2), Epoch(11)) // mixed: unstamped sibling
4144                .with_column(1, Value::Int64(2))
4145                .with_column(2, Value::Bytes(b"bob".to_vec())),
4146        ];
4147        RunWriter::new(&schema(), 9, Epoch(11), 0)
4148            .write(&stamped_path, &stamped)
4149            .unwrap();
4150        let mut reader = RunReader::open(&stamped_path, schema(), None).unwrap();
4151        assert!(
4152            reader.has_column(SYS_COMMIT_TS),
4153            "stamped flush must emit optional SYS_COMMIT_TS"
4154        );
4155        let (_, row1) = reader
4156            .get_version(RowId(1), Epoch(20))
4157            .unwrap()
4158            .expect("row 1");
4159        assert_eq!(row1.commit_ts, Some(stamp));
4160        let (_, row2) = reader
4161            .get_version(RowId(2), Epoch(20))
4162            .unwrap()
4163            .expect("row 2");
4164        assert_eq!(row2.commit_ts, None, "Null stamp cell stays None");
4165        let versions = reader.visible_versions(Epoch(20)).unwrap();
4166        assert_eq!(versions.len(), 2);
4167        assert_eq!(
4168            versions
4169                .iter()
4170                .find(|r| r.row_id == RowId(1))
4171                .and_then(|r| r.commit_ts),
4172            Some(stamp)
4173        );
4174
4175        // Legacy run (no stamps on write) lacks the column → always None.
4176        let legacy_path = dir.path().join("r-legacy.sr");
4177        RunWriter::new(&schema(), 10, Epoch(10), 0)
4178            .write(&legacy_path, &rows())
4179            .unwrap();
4180        let mut legacy = RunReader::open(&legacy_path, schema(), None).unwrap();
4181        assert!(!legacy.has_column(SYS_COMMIT_TS));
4182        let all = legacy.visible_versions(Epoch(20)).unwrap();
4183        assert!(all.iter().all(|r| r.commit_ts.is_none()));
4184    }
4185
4186    #[test]
4187    fn visible_version_cursor_preserves_order_snapshot_and_tombstones() {
4188        let dir = tempdir().unwrap();
4189        let path = dir.path().join("r-cursor.sr");
4190        let mut tombstone = Row::new(RowId(2), Epoch(2));
4191        tombstone.deleted = true;
4192        let versions = vec![
4193            Row::new(RowId(1), Epoch(4)).with_column(1, Value::Int64(10)),
4194            Row::new(RowId(2), Epoch(1)).with_column(1, Value::Int64(2)),
4195            tombstone,
4196            Row::new(RowId(3), Epoch(1)).with_column(1, Value::Int64(20)),
4197            Row::new(RowId(3), Epoch(3)).with_column(1, Value::Int64(23)),
4198            Row::new(RowId(4), Epoch(4)).with_column(1, Value::Int64(30)),
4199        ];
4200        RunWriter::new(&schema(), 7, Epoch(4), 0)
4201            .write(&path, &versions)
4202            .unwrap();
4203
4204        let control = crate::ExecutionControl::new(None);
4205        let mut cursor = RunReader::open(&path, schema(), None)
4206            .unwrap()
4207            .into_visible_version_cursor(Epoch(2))
4208            .unwrap();
4209        let first = cursor.next_visible_version(&control).unwrap().unwrap();
4210        assert_eq!(first.row_id, RowId(2));
4211        assert!(first.deleted);
4212        assert_eq!(first.committed_epoch, Epoch(2));
4213        let second = cursor.next_visible_version(&control).unwrap().unwrap();
4214        assert_eq!(second.row_id, RowId(3));
4215        assert_eq!(second.committed_epoch, Epoch(1));
4216        let row = cursor.materialize(second, &control).unwrap();
4217        assert_eq!(row.columns.get(&1), Some(&Value::Int64(20)));
4218        assert!(cursor.next_visible_version(&control).unwrap().is_none());
4219    }
4220
4221    #[test]
4222    fn learned_index_was_stored() {
4223        let dir = tempdir().unwrap();
4224        let path = dir.path().join("r-2.sr");
4225        RunWriter::new(&schema(), 2, Epoch(1), 0)
4226            .write(&path, &rows())
4227            .unwrap();
4228        let header = read_header(&path).unwrap();
4229        assert!(
4230            header.index_trailer_offset != 0,
4231            "trailer should be present"
4232        );
4233    }
4234
4235    #[test]
4236    fn low_level_container_still_round_trips() {
4237        let dir = tempdir().unwrap();
4238        let path = dir.path().join("r-3.sr");
4239        let cols = vec![ColumnPayload {
4240            column_id: 1,
4241            type_id_tag: 8,
4242            encoding: Encoding::Plain,
4243            pages: vec![vec![1, 2, 3, 4]],
4244            page_stats: Vec::new(),
4245        }];
4246        let header = write_run(
4247            &path,
4248            &RunSpec {
4249                run_id: 1,
4250                schema_id: 1,
4251                epoch_created: 1,
4252                level: 0,
4253                flags: 0,
4254                sort_key_column_id: SORT_KEY_ROW_ID,
4255                row_count: 1,
4256                min_row_id: 0,
4257                max_row_id: 0,
4258                columns: &cols,
4259            },
4260        )
4261        .unwrap();
4262        let back = read_header(&path).unwrap();
4263        assert_eq!(back.content_hash, header.content_hash);
4264        assert_eq!(read_column_dir(&path, &back).unwrap().len(), 1);
4265    }
4266
4267    #[test]
4268    fn detects_corruption() {
4269        let dir = tempdir().unwrap();
4270        let path = dir.path().join("r-4.sr");
4271        write_run(
4272            &path,
4273            &RunSpec {
4274                run_id: 1,
4275                schema_id: 1,
4276                epoch_created: 1,
4277                level: 0,
4278                flags: 0,
4279                sort_key_column_id: SORT_KEY_ROW_ID,
4280                row_count: 1,
4281                min_row_id: 0,
4282                max_row_id: 0,
4283                columns: &[ColumnPayload {
4284                    column_id: 1,
4285                    type_id_tag: 8,
4286                    encoding: Encoding::Plain,
4287                    pages: vec![vec![1, 2, 3]],
4288                    page_stats: Vec::new(),
4289                }],
4290            },
4291        )
4292        .unwrap();
4293        let mut bytes = std::fs::read(&path).unwrap();
4294        bytes[300] ^= 0xFF;
4295        std::fs::write(&path, bytes).unwrap();
4296        let err = read_header(&path).unwrap_err();
4297        assert!(
4298            matches!(err, MongrelError::ChecksumMismatch { .. }),
4299            "got {err:?}"
4300        );
4301    }
4302
4303    /// Phase 14.6: the direct-to-mmap placement logic must produce a byte-
4304    /// identical run to the in-buffer fallback. We drive `plan_run` + `place_run`
4305    /// into a plain `Vec<u8>` (so it's testable even where file mmap is denied —
4306    /// e.g. this sandbox), compare against `write_run_vec`, and additionally
4307    /// check that `write_run_mmap` agrees wherever a mapping can be created.
4308    #[test]
4309    fn mmap_and_vec_writers_are_byte_identical() {
4310        let dir = tempdir().unwrap();
4311        let stats = vec![PageStat {
4312            first_row_id: 0,
4313            last_row_id: 1,
4314            null_count: 0,
4315            row_count: 2,
4316            min: Some(vec![0]),
4317            max: Some(vec![9]),
4318            offset: 0,
4319            compressed_len: 0,
4320            uncompressed_len: 0,
4321        }];
4322        let spec = RunSpec {
4323            run_id: 7,
4324            schema_id: 1,
4325            epoch_created: 10,
4326            level: 0,
4327            flags: 0,
4328            sort_key_column_id: SORT_KEY_ROW_ID,
4329            row_count: 2,
4330            min_row_id: 0,
4331            max_row_id: 1,
4332            columns: &[
4333                ColumnPayload {
4334                    column_id: 1,
4335                    type_id_tag: 8,
4336                    encoding: Encoding::Plain,
4337                    pages: vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]],
4338                    page_stats: stats.clone(),
4339                },
4340                ColumnPayload {
4341                    column_id: 2,
4342                    type_id_tag: 8,
4343                    encoding: Encoding::Plain,
4344                    pages: vec![vec![10, 20], vec![30, 40]],
4345                    page_stats: stats.clone(),
4346                },
4347            ],
4348        };
4349        let trailer = b"learned-trailer-bytes";
4350
4351        // (1) placement path into a Vec-backed buffer.
4352        let plan = plan_run(&spec, None, Some(trailer)).expect("plan");
4353        let mut buf = vec![0u8; plan.total];
4354        let h_place = place_run(&spec, None, Some(trailer), &plan, &mut buf)
4355            .expect("place_run into Vec succeeds");
4356
4357        // (2) in-buffer fallback writer to a real file.
4358        let path_vec = dir.path().join("vec.sr");
4359        let h_vec = write_run_vec(&path_vec, &spec, None, Some(trailer)).unwrap();
4360        let bv = std::fs::read(&path_vec).unwrap();
4361
4362        assert_eq!(h_place.content_hash, h_vec.content_hash);
4363        assert_eq!(h_place.footer_offset, h_vec.footer_offset);
4364        assert_eq!(
4365            buf, bv,
4366            "place_run and write_run_vec must be byte-identical"
4367        );
4368        assert!(read_header(&path_vec).is_ok());
4369
4370        // (3) the mmap writer, when the FS supports it, must also agree. Where
4371        // file mmap is denied (some sandboxes), it reports the fallback sentinel
4372        // and `write_run_with` transparently uses the vec path instead.
4373        let path_mmap = dir.path().join("mmap.sr");
4374        match write_run_mmap(&path_mmap, &spec, None, Some(trailer)) {
4375            Ok(h_mmap) => {
4376                let bm = std::fs::read(&path_mmap).unwrap();
4377                assert_eq!(bm, bv, "mmap run must be byte-identical to vec run");
4378                assert_eq!(h_mmap.content_hash, h_vec.content_hash);
4379            }
4380            Err(e) if is_mmap_unavailable(&e) => {
4381                eprintln!("note: file mmap unavailable here; vec path covered (1)/(2)");
4382            }
4383            Err(e) => panic!("unexpected mmap error: {e:?}"),
4384        }
4385    }
4386
4387    /// Phase 15.1: the `&self` parallel-decode path (`column_native_shared`)
4388    /// must yield the same `NativeColumn` as the `&mut` `column_native` path,
4389    /// column for column, on a multi-page run. This guards the cross-column
4390    /// parallel scan used by `visible_columns_native`.
4391    #[test]
4392    fn column_native_shared_matches_column_native() {
4393        let dir = tempdir().unwrap();
4394        let path = dir.path().join("r.sr");
4395        // Enough rows to span >1 page (PAGE_ROWS = 65 536) so the parallel page
4396        // branch runs, plus a partial tail page.
4397        let n = 65_536 * 2 + 9;
4398        let id_col = NativeColumn::int64_sequence(1, n);
4399        let mut offsets = vec![0u32];
4400        let mut values = Vec::new();
4401        for i in 0..n {
4402            values.extend_from_slice(format!("v{}", i % 17).as_bytes());
4403            offsets.push(values.len() as u32);
4404        }
4405        let name_col = NativeColumn::Bytes {
4406            offsets,
4407            values,
4408            validity: vec![0xFF; n.div_ceil(8)],
4409        };
4410        let header = RunWriter::new(&schema(), 9, Epoch(5), 0)
4411            .write_native(&path, &[(1, id_col), (2, name_col)], n, 1)
4412            .unwrap();
4413
4414        let mut reader = RunReader::open_with_cache(&path, schema(), None, None, None, 0, None)
4415            .expect("open reader");
4416        assert!(reader.has_mmap(), "test env must support read-only mmap");
4417        assert_eq!(reader.row_count(), header.row_count as usize);
4418
4419        for cid in [1u16, 2] {
4420            let a = reader.column_native(cid).expect("column_native");
4421            let b = reader
4422                .column_native_shared(cid)
4423                .expect("column_native_shared");
4424            assert_eq!(a.len(), b.len(), "len mismatch col {cid}");
4425            // Byte-level equality of the typed buffers.
4426            match (&a, &b) {
4427                (
4428                    NativeColumn::Int64 {
4429                        data: da,
4430                        validity: va,
4431                    },
4432                    NativeColumn::Int64 {
4433                        data: db,
4434                        validity: vb,
4435                    },
4436                ) => {
4437                    assert_eq!(da, db, "Int64 data col {cid}");
4438                    assert_eq!(va, vb, "Int64 validity col {cid}");
4439                }
4440                (
4441                    NativeColumn::Bytes {
4442                        offsets: oa,
4443                        values: ua,
4444                        validity: va,
4445                    },
4446                    NativeColumn::Bytes {
4447                        offsets: ob,
4448                        values: ub,
4449                        validity: vb,
4450                    },
4451                ) => {
4452                    assert_eq!(oa, ob, "Bytes offsets col {cid}");
4453                    assert_eq!(ua, ub, "Bytes values col {cid}");
4454                    assert_eq!(va, vb, "Bytes validity col {cid}");
4455                }
4456                _ => panic!("type mismatch col {cid}: {a:?} vs {b:?}"),
4457            }
4458        }
4459    }
4460
4461    #[test]
4462    fn page_cache_key_distinguishes_tables() {
4463        let a = page_cache_key(1, 5, 2, 3);
4464        let b = page_cache_key(2, 5, 2, 3);
4465        assert_ne!(a, b, "same run/col/page, different table must differ");
4466        // same table different run/col/page also differ (sanity)
4467        assert_ne!(page_cache_key(1, 5, 2, 3), page_cache_key(1, 6, 2, 3));
4468        assert_ne!(page_cache_key(1, 5, 2, 3), page_cache_key(1, 5, 2, 4));
4469    }
4470}