Skip to main content

mira_core/
block.rs

1//! Immutable block storage.
2//!
3//! A block is a *directory* holding one Arrow IPC file per table:
4//!
5//! ```text
6//! <root>/logs/p=<epoch_hour>/<min_ts:020>-<max_ts:020>-<node:08x>-<seq:012>-<wal_hi:020>/
7//!     logs.arrow  log_attrs.arrow  resources.arrow  resource_attrs.arrow  scope_attrs.arrow
8//! ```
9//!
10//! The filesystem *is* the manifest. Every reason a LSM engine needs a MANIFEST
11//! file is absent here: Mira publishes exactly one immutable object per commit
12//! via one directory rename, never mutates a published block, and never needs a
13//! multi-file atomic operation. The directory name carries the full pruning key,
14//! so booting is one `readdir` per partition with zero file opens, and there is
15//! no metadata state that can disagree with the data. That is what makes the
16//! process stateless in the sense that matters: kill it, restart it, point a
17//! second one at the same directory read-only — nothing to reconcile.
18//!
19//! Publish is write-tmp / fsync-files / fsync-tmpdir / rename-dir / fsync-parent
20//! / fsync-grandparent — the last because the partition directory itself is a
21//! new entry in `<root>/<signal>` on the first block of every hour.
22//! Directory rename is atomic on POSIX, so a block is either wholly visible or
23//! wholly absent; there is no torn state for recovery to clean up, and therefore
24//! no write-ahead log.
25//!
26//! Retention is `remove_dir_all` on the block directory. POSIX guarantees this is
27//! safe against in-flight readers: a mapping holds a reference to the inode that
28//! `close()` does not drop, so a query holding an `Arc<Mmap>` keeps reading
29//! correct data from an unlinked file until it drops the mapping. The `Arc` is
30//! the refcount; no lease protocol is needed.
31
32use std::collections::HashMap;
33use std::fs::{self, File};
34use std::io::{self, BufWriter, Write};
35use std::os::unix::fs::MetadataExt;
36use std::path::{Path, PathBuf};
37use std::ptr::NonNull;
38use std::sync::{Arc, Mutex, OnceLock};
39use std::time::SystemTime;
40
41use arrow_array::RecordBatch;
42use arrow_buffer::Buffer;
43use arrow_ipc::MetadataVersion;
44use arrow_ipc::reader::{FileDecoder, read_footer_length};
45use arrow_ipc::root_as_footer;
46use arrow_ipc::writer::{FileWriter, IpcWriteOptions};
47use memmap2::Mmap;
48
49use crate::error::{Error, IoContext, Result};
50use crate::signal::Sealed;
51
52/// Leading bytes of every Arrow IPC file. arrow-rs's own reader seeks straight
53/// to the trailer and never checks this, so a truncated-from-the-front file
54/// would decode as garbage; we check it ourselves.
55const MAGIC: &[u8; 6] = b"ARROW1";
56
57/// CRC32 of the record-batch body, stored in the footer's custom metadata along
58/// with the exact byte length it covers. arrow-ipc has no checksum of its own: a
59/// valid footer over a corrupt body decodes silently into wrong answers.
60///
61/// The length is stored rather than derived from the footer offset because
62/// `finish()` appends an end-of-stream marker *after* the last batch and before
63/// the footer, so "everything before the footer" and "everything the writer had
64/// emitted when we snapshotted" differ by those bytes.
65const CRC_KEY: &str = "mira.crc32";
66const CRC_LEN_KEY: &str = "mira.crc32.len";
67
68/// On-disk format version, stamped into every table's footer metadata beside
69/// the CRC — a place that already exists, so no second file and no second
70/// fsync. Read before the reader trusts anything else in the file.
71///
72/// What it is for: three of the five logs tables are read positionally
73/// (`attrs.rs`, `query.rs`: `column(3)` is the `str` value column), so inserting
74/// a field into a schema in `schema.rs` does not fail against blocks already on
75/// disk — it reinterprets them. Without a version there is nothing a reader can
76/// look at to tell the two layouts apart.
77///
78/// ponytail: this records the version and refuses the future — a block from a
79/// newer Mira is a named error, not a misparse — and that is all. It does not
80/// make an *older* block readable by a newer binary, because there is no
81/// migration to run and one version of one layout to run it on. The upgrade
82/// path, in order: move the positional readers onto `column_by_name` (which the
83/// root tables already use, which is why `LogRecord.event_name` could be added
84/// without rewriting a block); then a column insertion needs no bump at all.
85/// Until that lands, the rule is that any change to a published table's column
86/// list bumps [`FORMAT_VERSION`], and the compatibility branch for the older
87/// layout goes next to the check in [`open_table`].
88const FORMAT_KEY: &str = "mira.format";
89
90/// The format this binary writes, and the highest it will read.
91pub const FORMAT_VERSION: u32 = 1;
92
93/// The version blocks written before [`FORMAT_KEY`] existed are treated as.
94///
95/// They are byte-identical to version 1 — the key was added without changing
96/// anything else about the file — so absent means 1 rather than "refuse it".
97/// A format change that orphaned every block already on somebody's disk would
98/// be a worse bug than the one the version exists to catch.
99const LEGACY_VERSION: u32 = 1;
100
101/// The ZSTD level every compressed table is written at.
102///
103/// The same as arrow-ipc's default, and set explicitly anyway: the ratio in
104/// `docs/architecture/performance.md` section 11 is a published number, and an upstream
105/// default that moved would move it without anything in this tree changing.
106///
107/// 3 and not higher, which was measured and rejected. Over 8 real blocks per
108/// signal, level 9 buys **2.4%** fewer bytes (8.41x against 8.21x) and takes
109/// **1.4x** as long to rewrite a block. Compaction is a background sweep sharing
110/// cores with ingest, and a sweep that falls behind leaves blocks uncompressed,
111/// so 2.4% does not buy the risk. Nearly all of the ratio comes from the
112/// dictionary column in [`crate::schema::ATTRS`], not from the level.
113const ZSTD_LEVEL: i32 = 3;
114
115/// Where the schema message starts: `ARROW1` padded up to [`ALIGNMENT`], which
116/// is exactly how `FileWriter` places it (`pad_to_alignment` over the same
117/// constant we hand it in [`write_table_with`]).
118const HEADER_LEN: usize = MAGIC.len().next_multiple_of(ALIGNMENT);
119
120/// The prefix of every encapsulated IPC message since the legacy format was
121/// retired. We write V5 with `write_legacy_ipc_format` off, so a message that
122/// does not start with it is not a message this wrote.
123const CONTINUATION: [u8; 4] = [0xff; 4];
124
125/// A block file whose own metadata does not describe it.
126///
127/// Every length and offset in [`open_table`] is read *out of the file*, which
128/// makes it attacker-controlled-equivalent — a disk bit flip being the
129/// realistic case. Unchecked, they index the mapping out of bounds, and
130/// `panic = "abort"` (workspace release profile) turns that into a process
131/// death rather than a caught error: every open block and in-flight export
132/// dies with it, the bad block is still on disk afterwards, and the restart
133/// hits the same byte. One bad byte becomes an unattended crashloop. As an
134/// error it is one table a query skips.
135///
136/// ponytail: `io::ErrorKind::InvalidData` inside `Error::Io` rather than an
137/// `Error::CorruptBlock` of its own, following the NUL-byte case in
138/// [`fs_type`]. Every caller today treats a block it cannot read the same way
139/// whatever the reason; give it a variant when one of them needs to match on
140/// it.
141fn corrupt(path: &Path, what: String) -> Error {
142    Error::Io {
143        path: path.to_path_buf(),
144        source: io::Error::new(io::ErrorKind::InvalidData, what),
145    }
146}
147
148/// Buffer alignment for published blocks.
149///
150/// The *correctness* floor is `align_of::<T>()` — 16 bytes for the widest thing
151/// we store. 64 is the cache-line / SIMD figure and costs a few padding bytes
152/// per buffer. Blocks are written at 64 and read with `require_alignment(true)`
153/// so that a regression in the write path fails loudly instead of making
154/// arrow-rs quietly memcpy the entire body out of the mapping.
155const ALIGNMENT: usize = 64;
156
157const NANOS_PER_HOUR: i64 = 3_600 * 1_000_000_000;
158
159/// A `Write` that hashes everything passing through it.
160///
161/// Sits between the IPC writer and the `BufWriter` so it sees the byte stream
162/// exactly as it will land on disk, and can be read mid-stream (via
163/// `FileWriter::get_ref`) to stamp the CRC into the footer before `finish()`.
164struct CrcWriter<W> {
165    inner: W,
166    hasher: crc32fast::Hasher,
167    written: u64,
168}
169
170impl<W: Write> CrcWriter<W> {
171    fn new(inner: W) -> Self {
172        Self {
173            inner,
174            hasher: crc32fast::Hasher::new(),
175            written: 0,
176        }
177    }
178
179    /// Bytes hashed so far, and their CRC.
180    fn checksum(&self) -> (u64, u32) {
181        (self.written, self.hasher.clone().finalize())
182    }
183}
184
185impl<W: Write> Write for CrcWriter<W> {
186    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
187        let n = self.inner.write(buf)?;
188        self.hasher.update(&buf[..n]);
189        self.written += n as u64;
190        Ok(n)
191    }
192
193    fn flush(&mut self) -> io::Result<()> {
194        self.inner.flush()
195    }
196}
197
198/// Write one table as a self-contained, checksummed, 64-byte-aligned IPC file
199/// and fsync it. Uncompressed on purpose: IPC body compression forces the reader
200/// to decompress into fresh allocations, which is mutually exclusive with the
201/// zero-copy mmap read path.
202///
203/// Never point this at a path some reader may have mapped. It truncates, and a
204/// mapping over a truncated file is a SIGBUS on the next page touched, not an
205/// error anyone can catch. Replacing a published table means staging a new file
206/// and renaming, which is what [`compact`] does.
207pub fn write_table(path: &Path, batch: &RecordBatch) -> Result<()> {
208    write_table_with(path, std::slice::from_ref(batch), None)
209}
210
211/// The same file, ZSTD-compressed per buffer.
212///
213/// Only for the cold tier (section 11): a compressed block cannot be read out of its
214/// mapping, so this trades the zero-copy property for bytes. The retention
215/// worker applies it to blocks old enough that nothing is scanning them, which
216/// is where the trade is free.
217///
218/// The reader needs no flag — the IPC metadata records the codec per batch, so
219/// a directory can hold both tiers at once and does, mid-rewrite.
220pub fn write_table_zstd(path: &Path, batch: &RecordBatch) -> Result<()> {
221    write_table_with(
222        path,
223        std::slice::from_ref(batch),
224        Some(arrow_ipc::CompressionType::ZSTD),
225    )
226}
227
228/// The same again as LZ4_FRAME, so the `tier` example can price the pure-Rust
229/// alternative against the C one on real blocks. Nothing in the engine writes
230/// LZ4; see the decisions table in `docs/architecture/data-layout.md`.
231pub fn write_table_lz4(path: &Path, batch: &RecordBatch) -> Result<()> {
232    write_table_with(
233        path,
234        std::slice::from_ref(batch),
235        Some(arrow_ipc::CompressionType::LZ4_FRAME),
236    )
237}
238
239fn write_table_with(
240    path: &Path,
241    batches: &[RecordBatch],
242    codec: Option<arrow_ipc::CompressionType>,
243) -> Result<()> {
244    let Some(first) = batches.first() else {
245        return Ok(());
246    };
247    let file = File::create(path).ctx(path)?;
248    let opts = IpcWriteOptions::try_new(ALIGNMENT, false, MetadataVersion::V5)?;
249    let opts = match codec {
250        // LZ4 rejects a configured level outright rather than ignoring one, so
251        // the level goes on only where it means something.
252        Some(arrow_ipc::CompressionType::ZSTD) => opts
253            .try_with_compression(codec)?
254            .try_with_compression_level(Some(ZSTD_LEVEL))?,
255        Some(c) => opts.try_with_compression(Some(c))?,
256        None => opts,
257    };
258    let mut w = FileWriter::try_new_with_options(
259        CrcWriter::new(BufWriter::new(file)),
260        &first.schema(),
261        opts,
262    )?;
263    for batch in batches {
264        w.write(batch)?;
265    }
266
267    // Everything written so far is the body; the footer is emitted by finish().
268    let (len, crc) = w.get_ref().checksum();
269    w.write_metadata(FORMAT_KEY, FORMAT_VERSION.to_string());
270    w.write_metadata(CRC_KEY, format!("{crc:08x}"));
271    w.write_metadata(CRC_LEN_KEY, len.to_string());
272    w.finish()?;
273
274    let mut buf = w.into_inner()?;
275    buf.flush().ctx(path)?;
276    let file = buf.inner.into_inner().map_err(|e| Error::Io {
277        path: path.to_path_buf(),
278        source: e.into_error(),
279    })?;
280    crate::sync_all(&file).ctx(path)?;
281    Ok(())
282}
283
284/// A published block, discovered by reading directory names.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct BlockRef {
287    pub dir: PathBuf,
288    pub min_ts: i64,
289    pub max_ts: i64,
290    /// Which replica wrote this block. See [`node_id`].
291    pub node: u32,
292    pub seq: u64,
293    /// One past the highest write-ahead-log sequence whose records are in this
294    /// block, or `0` for a block published before the log existed.
295    ///
296    /// This is the entire manifest. Principle 4 says there is no coordination
297    /// state and the block directory *is* the manifest, so the one fact WAL
298    /// replay needs — how far the log has been absorbed — is carried in the
299    /// name rather than in a file someone has to keep consistent with the
300    /// blocks. Recovery therefore stays the `readdir` section 4 promises it is.
301    pub wal_hi: u64,
302}
303
304impl BlockRef {
305    /// True if this block could contain a row in `[from, to]`. The whole point
306    /// of the naming scheme: pruning without opening a single file.
307    pub fn overlaps(&self, from: i64, to: i64) -> bool {
308        self.min_ts <= to && self.max_ts >= from
309    }
310}
311
312/// One candidate the read path may have to open: a published block directory,
313/// or the snapshot of a block that is still open (section 4).
314///
315/// Everything a scan needs before it opens anything — the range to prune on, the
316/// identity a cursor is built from, and where the tables are. The two cases
317/// differ in exactly two ways: a snapshot has no directory to read sidecars out
318/// of, and its tables are already in memory.
319pub(crate) struct Src<'a> {
320    pub node: u32,
321    pub seq: u64,
322    pub min_ts: i64,
323    pub max_ts: i64,
324    /// `None` for a snapshot. Skipping the sidecar probes is not a special
325    /// case: "no filter file" already means "scan me" for every block published
326    /// before that filter existed.
327    pub dir: Option<&'a Path>,
328    tables: Option<&'a [(&'static str, RecordBatch)]>,
329}
330
331impl<'a> Src<'a> {
332    pub fn disk(b: &'a BlockRef) -> Src<'a> {
333        Src {
334            node: b.node,
335            seq: b.seq,
336            min_ts: b.min_ts,
337            max_ts: b.max_ts,
338            dir: Some(b.dir.as_path()),
339            tables: None,
340        }
341    }
342
343    pub fn open(o: &'a crate::signal::Open) -> Src<'a> {
344        Src {
345            node: o.node,
346            seq: o.seq,
347            min_ts: o.sealed.min_ts,
348            max_ts: o.sealed.max_ts,
349            dir: None,
350            tables: Some(&o.sealed.tables),
351        }
352    }
353
354    pub fn overlaps(&self, from: i64, to: i64) -> bool {
355        self.min_ts <= to && self.max_ts >= from
356    }
357
358    /// One named table, or `None` if this source does not have it.
359    ///
360    /// A missing table on disk is not an error: retention unlinking an expired
361    /// block underneath a scan is normal. An open block's tables are already
362    /// Arrow, under the same names the published files would carry — including
363    /// the empty ones, which `publish` skips and which read identically to
364    /// absent everywhere downstream.
365    pub fn load(&self, name: &str) -> Result<Option<RecordBatch>> {
366        match (self.tables, self.dir) {
367            (Some(tables), _) => Ok(tables
368                .iter()
369                .find(|(n, _)| *n == name)
370                .map(|(_, b)| b.clone())),
371            // `write_table` emits exactly one record batch per file, so row
372            // numbers are unambiguous and there is never a second batch to
373            // stitch.
374            (None, Some(dir)) => Ok(open_table_opt(&dir.join(format!("{name}.arrow")))?
375                .and_then(|t| t.batches.first().cloned())),
376            (None, None) => Ok(None),
377        }
378    }
379}
380
381/// The published blocks under `root/signal`, plus any open-block snapshots that
382/// have not yet been published under the same `(node, seq)`.
383///
384/// The published copy wins a collision: it is at least as complete, and it is
385/// the one whose cursors readers already hold. `(node, seq)` is enough to
386/// recognise it because the flusher snapshots under the sequence it will publish
387/// under — see [`crate::signal::Open`].
388pub(crate) fn sources<'a>(
389    disk: &'a [BlockRef],
390    open: &'a [std::sync::Arc<crate::signal::Open>],
391) -> Vec<Src<'a>> {
392    disk.iter()
393        .map(Src::disk)
394        .chain(
395            open.iter()
396                .filter(|o| !disk.iter().any(|b| b.node == o.node && b.seq == o.seq))
397                .map(|o| Src::open(o)),
398        )
399        .collect()
400}
401
402/// A replica's writer identity, derived from its name with no coordination.
403///
404/// The block name has to be unique across every process that can ever write to
405/// this directory tree, and it has to be so without asking anyone. Hashing the
406/// replica name gets that for free: in Kubernetes the name is the pod name,
407/// which the scheduler already guarantees is unique, so uniqueness is inherited
408/// from a namespace that exists rather than invented by a protocol we would then
409/// have to operate.
410/// Truncated to 32 bits: two replicas colliding needs ~77k of them on one
411/// volume, and a collision degrades to the loud `ENOTEMPTY` above rather than to
412/// anything silent.
413pub fn node_id(name: &str) -> u32 {
414    crate::identity::hash64(name.as_bytes()) as u32
415}
416
417/// `{min_ts}-{max_ts}-{node}-{seq}-{wal_hi}`.
418///
419/// `node` is what makes two active replicas sharing a volume safe. Without it,
420/// two writers allocate the same `seq` and the second `rename` lands on a
421/// non-empty directory — `ENOTEMPTY`, and a node that can never publish again.
422///
423/// Splitting on `-` is only safe because [`crate::signal::Sealed`] clamps both
424/// timestamps non-negative; a negative one would format with a leading `-` and
425/// make the name unparseable, which is to say invisible to `scan`.
426fn dir_name(min_ts: i64, max_ts: i64, node: u32, seq: u64, wal_hi: u64) -> String {
427    format!("{min_ts:020}-{max_ts:020}-{node:08x}-{seq:012}-{wal_hi:020}")
428}
429
430/// Parses both the five-field name above and the four-field name that predates
431/// the write-ahead log.
432///
433/// The old form has to keep working: a block directory written by an earlier
434/// build is still a valid block, and there is no migration step to run because
435/// there is no metadata store to migrate. A missing `wal_hi` reads as `0`,
436/// which is correct — those blocks came from a Mira with no log, so no
437/// sequence is covered by them and replay must not skip anything on their
438/// account.
439fn parse_dir_name(name: &str) -> Option<(i64, i64, u32, u64, u64)> {
440    let mut parts = name.split('-');
441    let min = parts.next()?.parse().ok()?;
442    let max = parts.next()?.parse().ok()?;
443    let node = u32::from_str_radix(parts.next()?, 16).ok()?;
444    let seq = parts.next()?.parse().ok()?;
445    let wal_hi = match parts.next() {
446        Some(field) => field.parse().ok()?,
447        None => 0,
448    };
449    if parts.next().is_some() {
450        return None;
451    }
452    Some((min, max, node, seq, wal_hi))
453}
454
455/// The same block name, saying it covers no log.
456///
457/// [`crate::offload::Target::pull`] lands blocks written by a volume that is
458/// gone. `wal_hi` is a position in *that* volume's log, and the log it arrives
459/// beside starts at sequence 0 — a re-created pod, a new claim — while
460/// [`wal_watermarks`] filters only by node, which is a hash of `--node` and so
461/// survives the re-creation. Kept as written, the restored name tells the fresh
462/// log that thousands of frames it has not issued yet are already published,
463/// and the next replay skips them.
464///
465/// Zero is what the four-field names that predate the log already mean, and
466/// [`publish`] states the rule: too high is silent loss, too low is a
467/// re-ingest.
468///
469/// A name `parse_dir_name` rejects is returned unchanged: it is not a block, so
470/// `scan` will not see it either way, and inventing a name for it here would be
471/// the only place in the tree that renames something it cannot read.
472pub fn name_covering_no_log(name: &str) -> String {
473    match parse_dir_name(name) {
474        Some((min_ts, max_ts, node, seq, _)) => dir_name(min_ts, max_ts, node, seq, 0),
475        None => name.to_string(),
476    }
477}
478
479fn fsync_dir(path: &Path) -> Result<()> {
480    crate::sync_all(&File::open(path).ctx(path)?).ctx(path)
481}
482
483/// Atomically publish a set of tables as one block under `<root>/<signal>/`.
484///
485/// Returns the published directory.
486///
487/// Acking an OTLP export requires that its records are recoverable, and until
488/// [`crate::wal`] existed this call was the only thing that made them so — so
489/// the caller had to wait for it. It no longer does, provided the export is in
490/// the log: `wal_hi` is what records that, and it must be whatever
491/// [`crate::wal::Wal::watermark_for`] answers for the sequences in `sealed` —
492/// an *exclusive* watermark over the signal as a whole, not one past this
493/// block's own highest sequence, because sibling shards are filling their own
494/// blocks from the same log and hold sequences below it that are not here. Pass
495/// `0` when there is no log.
496///
497/// Getting `wal_hi` too high is the dangerous direction. [`wal_watermarks`]
498/// takes the maximum over every block of the signal, so a watermark that claims
499/// sequences no block holds makes replay skip them — silent loss, with the
500/// client holding a 200. Too low only costs a re-ingest.
501pub fn publish(
502    root: &Path,
503    signal: &str,
504    node: u32,
505    seq: u64,
506    wal_hi: u64,
507    sealed: &Sealed,
508) -> Result<BlockRef> {
509    let (min_ts, max_ts) = (sealed.min_ts, sealed.max_ts);
510    // The staging name carries `node` for the same reason the final one does:
511    // two replicas on one volume must not stage into the same directory. It
512    // also carries the timestamp range, because `node` alone is not enough: two
513    // replicas started with the same `--node` — a misconfiguration, but a silent
514    // one — walk the same `seq` from 0 and collide. The observed cost was two
515    // lost publishes in 107, both retryable; the unobserved one is worse, since
516    // B's `remove_dir_all` can empty a directory A is still writing tables into
517    // and the winner then publishes a block assembled from two sealed sets.
518    // Adding the range the final name already carries makes the path unique per
519    // block content, which is exactly the granularity the collision needs.
520    let staging = root.join(".tmp");
521    let tmp = staging.join(format!(
522        "{signal}-{node:08x}-{seq:012}-{min_ts:020}-{max_ts:020}"
523    ));
524    fs::create_dir_all(&staging).ctx(&staging)?;
525    // `create_dir`, not `create_dir_all`: the latter succeeds on a directory
526    // that already exists, which is how a leftover from a killed publish gets
527    // silently merged into this one. Colliding here is a retryable error, and
528    // `sweep_staging` clears the leftover at the next boot.
529    fs::create_dir(&tmp).ctx(&tmp)?;
530
531    let signal_dir = root.join(signal);
532    let partition = signal_dir.join(format!("p={}", min_ts.div_euclid(NANOS_PER_HOUR)));
533    let dir = partition.join(dir_name(min_ts, max_ts, node, seq, wal_hi));
534    let staged = stage(&tmp, sealed).and_then(|()| {
535        fs::create_dir_all(&partition).ctx(&partition)?;
536        fs::rename(&tmp, &dir).ctx(&dir)?;
537        fsync_dir(&partition)?;
538        // And the directory naming the partition. fsyncing `partition` persists
539        // the entries inside it, not the entry for it in its own parent — so on
540        // the first block of a new hour the block is durable and the directory
541        // holding it is unflushed metadata, which loses an acked block on XFS
542        // and btrfs (ext4's ordered journal happens to cover it). One extra
543        // fsync per 32 MB block, against the per-table fsyncs already paid.
544        fsync_dir(&signal_dir)
545    });
546
547    if let Err(e) = staged {
548        unwind_staging(&tmp);
549        return Err(e);
550    }
551
552    Ok(BlockRef {
553        dir,
554        min_ts,
555        max_ts,
556        node,
557        seq,
558        wal_hi,
559    })
560}
561
562/// Unwind the staging directory of a publish that did not complete.
563///
564/// Every step of [`publish`] `?`s, and the staging name is unique per block
565/// content, so nothing reuses it: without this the tables already written are
566/// stranded under `.tmp`, where `expire` — which only ever scans
567/// `<root>/<signal>` — will never see them. That matters because the flusher
568/// retries every couple of seconds, so the failure this path exists for (a full
569/// disk, a read-only mount) leaks on the order of a thousand directories an hour
570/// per signal, and the space is still gone once the operator has freed the disk.
571/// `sweep_staging` keeps its boot-time role: it is for the kill -9 that never
572/// reaches this line.
573///
574/// Returns nothing, deliberately. The publish failure is the one the caller has
575/// to act on, and a cleanup that could not run is a leaked directory the next
576/// boot's sweep collects anyway — turning it into the returned error would
577/// replace the reason the publish failed with the reason the tidy-up did.
578fn unwind_staging(tmp: &Path) {
579    if let Err(rm) = fs::remove_dir_all(tmp) {
580        // NotFound is the normal shape of "the rename succeeded and a later
581        // fsync did not": there is nothing left at `tmp` to remove, and the
582        // block is published.
583        if rm.kind() != io::ErrorKind::NotFound {
584            tracing::warn!(
585                path = %tmp.display(),
586                error = %rm,
587                "cannot remove the staging directory of a failed publish",
588            );
589        }
590    }
591}
592
593/// Write one sealed block's files into an already-created staging directory.
594///
595/// Split out of [`publish`] only so that the failure of any step in it has one
596/// place to be cleaned up from.
597/// Drop an attribute table's trailing all-null value columns before it is
598/// written.
599///
600/// [`crate::schema::ATTRS`] carries a column per `AnyValue` variant and a row
601/// fills exactly one of them, so the other five are null down the whole block.
602/// Arrow IPC does not elide those: an all-null `Binary` column still writes a
603/// full offsets buffer and its validity bitmap, 4.125 bytes a row, and a
604/// corpus of ordinary string attributes spends 8.25 of its 36.26 bytes a row
605/// on the two that are almost never used — `bytes` holds `BytesValue` and
606/// `ser` holds slices and maps, and most telemetry emits neither.
607///
608/// Only a *suffix* is dropped, and only ever down to [`ATTR_UNGUARDED_COLS`].
609/// That is the whole reason this costs no reader a line: every surviving
610/// column keeps the position the read path indexes it by, which is part of the
611/// on-disk format (see the field order note above `FORMAT_VERSION`), and the
612/// two columns that can go are the only ones no reader touches unconditionally.
613///
614/// Here rather than in the builder or in [`Sealed::with`] on purpose: the
615/// bloom filter and the zone map select attribute tables with
616/// `Arc::ptr_eq(&schema, &ATTRS)`, so a projection upstream would silently
617/// leave them out of both indexes — and a key missing from the zone map reads
618/// as *this block has no such value*, which prunes blocks that do hold
619/// matches. By the time `stage` runs, both sidecars are built.
620///
621/// Not a format break, and no `FORMAT_VERSION` bump: the reader already has to
622/// treat an absent table as empty, because that is how a block written before
623/// a table existed reads back, and a short attribute table is the same
624/// tolerance one column at a time. Nothing else is trimmed — another table's
625/// trailing column may carry meaning this cannot see.
626fn trim_attr_tail(batch: &RecordBatch) -> Result<std::borrow::Cow<'_, RecordBatch>> {
627    use std::borrow::Cow;
628    if !Arc::ptr_eq(&batch.schema(), &crate::schema::ATTRS) {
629        return Ok(Cow::Borrowed(batch));
630    }
631    let live = (0..batch.num_columns())
632        .rposition(|i| batch.column(i).null_count() < batch.num_rows())
633        .map_or(0, |i| i + 1);
634    let keep = live.max(ATTR_UNGUARDED_COLS);
635    if keep >= batch.num_columns() {
636        return Ok(Cow::Borrowed(batch));
637    }
638    Ok(Cow::Owned(batch.project(&(0..keep).collect::<Vec<_>>())?))
639}
640
641/// How many of [`crate::schema::ATTRS`]' columns a reader may take without
642/// first asking whether they are there — and so the floor [`trim_attr_tail`]
643/// will not trim below.
644///
645/// Seven: `AttrPred::new` in `query.rs` reads `str`, `int`, `double` and
646/// `bool` — columns 3 to 6 — on every attribute batch it is handed, before any
647/// type byte is consulted. `RecordBatch::column` panics past the end, and
648/// `as_primitive_opt` guards a wrong type rather than a missing column, so
649/// trimming a column out from under it is a panic in a scan thread and not a
650/// null. Only `bytes` and `ser` sit above the line: the sole sites that reach
651/// them are `emit_attr`'s `BYTES` and `SLICE | MAP` arms, and a row arrives
652/// there only when its own stored type byte says so — which cannot happen in a
653/// table where those columns held nothing.
654const ATTR_UNGUARDED_COLS: usize = 7;
655
656fn stage(tmp: &Path, sealed: &Sealed) -> Result<()> {
657    // An empty table is not written. Arrow IPC framing for a zero-row table is
658    // ~1 KB for three columns and ~2.5 KB for nine (measured), which is nothing
659    // against a full 32 MB block and most of a block sealed by the age timer on
660    // a quiet node. A traces block has nine tables and typically five of them
661    // have any rows: the four event and link tables — span_events,
662    // span_links and the attribute table of each — stay empty unless a service
663    // emits events or links, which most do not. Measured on the smoke corpus,
664    // every traces block writes exactly those five and skips 8 KB of framing
665    // against 18 KB of tables; a metrics block writes eight of thirteen.
666    //
667    // The reader treats a missing file as an empty table, which it has to do
668    // anyway: it is also how a block written by an older version that did not
669    // have the table reads back.
670    for (name, batch) in &sealed.tables {
671        if batch.num_rows() > 0 {
672            let batch = trim_attr_tail(batch)?;
673            write_table(&tmp.join(format!("{name}.arrow")), &batch)?;
674        }
675    }
676    // Sidecars are written with the same durability as the tables: a block that
677    // lands with a stale or missing index is one the reader would either skip
678    // wrongly or scan slowly, and only the first of those is a correctness bug —
679    // but both are avoidable for one fsync each of files `bloom` sizes by row
680    // count — 1 KB apiece on the blocks a quiet node writes, 65 KB at the top
681    // end, against tens of MB of tables.
682    for (name, bytes) in &sealed.sidecars {
683        let path = tmp.join(name);
684        let mut f = File::create(&path).ctx(&path)?;
685        f.write_all(bytes).ctx(&path)?;
686        crate::sync_all(&f).ctx(&path)?;
687    }
688    fsync_dir(tmp)
689}
690
691/// Remove staging directories this node left behind for this signal.
692///
693/// Since the staging name carries the block's timestamp range it is never
694/// reused, so a publish killed between staging and `rename` leaks a directory
695/// that nothing else will ever clear. Sweeping is filtered by signal *and* node
696/// rather than emptying `.tmp` wholesale, because another replica on the same
697/// volume may have a publish in flight — deleting under it is exactly the
698/// corruption the unique staging name exists to prevent. Called once per signal
699/// at boot, before that signal's flusher can publish anything.
700pub fn sweep_staging(root: &Path, signal: &str, node: u32) -> Result<usize> {
701    let tmp = root.join(".tmp");
702    let prefix = format!("{signal}-{node:08x}-");
703    let entries = match fs::read_dir(&tmp) {
704        Ok(d) => d,
705        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(0),
706        Err(e) => {
707            return Err(Error::Io {
708                path: tmp,
709                source: e,
710            });
711        }
712    };
713    let mut removed = 0;
714    for entry in entries {
715        let path = entry.ctx(&tmp)?.path();
716        if path
717            .file_name()
718            .and_then(|n| n.to_str())
719            .is_some_and(|n| n.starts_with(&prefix))
720        {
721            fs::remove_dir_all(&path).ctx(&path)?;
722            removed += 1;
723        }
724    }
725    Ok(removed)
726}
727
728/// How far the write-ahead log has been absorbed into published blocks, per
729/// signal, in the order [`crate::wal::Signal::index`] uses.
730///
731/// This is the whole of WAL recovery's input, and it is three `readdir`s — the
732/// same ones the read path does at boot anyway. No manifest file, so nothing
733/// that can disagree with the blocks it describes.
734///
735/// The maximum over the blocks, not the last one published: `scan` sorts by
736/// timestamp, and a block covering an older hour can be published after a
737/// newer one when a late export arrives. Taking the last would then walk the
738/// watermark backwards and replay data that is already stored.
739///
740/// A signal with no blocks gets `0` — replay everything the log holds for it,
741/// which is right, because nothing has absorbed any of it.
742///
743/// `node` scopes it to one writer's blocks, and that is not an optimisation.
744/// Sequences are per-log: [`crate::wal::Wal`] hands them out from its own
745/// counter, so two replicas sharing a volume (section 12) number their frames
746/// independently and a sequence means nothing outside the log that issued it.
747/// An unscoped maximum therefore hands the quiet replica the busy one's
748/// progress, and both consumers act on it destructively — [`crate::wal::Wal::replay`]
749/// skips every frame below it, and `wal_sweep` unlinks the segments holding
750/// them. The blocks are still filtered by nothing else: `scan` returns the whole
751/// directory because the *read* path wants every replica's blocks, and only
752/// recovery wants one replica's.
753pub fn wal_watermarks(root: &Path, node: u32) -> Result<crate::wal::Watermarks> {
754    let mut out = [0u64; 3];
755    for signal in crate::wal::Signal::ALL {
756        out[signal.index()] = scan(root, signal.as_str())?
757            .iter()
758            .filter(|b| b.node == node)
759            .map(|b| b.wal_hi)
760            .max()
761            .unwrap_or(0);
762    }
763    Ok(out)
764}
765
766/// Rebuild the catalog from the filesystem. This is the entire boot sequence for
767/// the read path: no manifest to replay, and the write-ahead log's recovery
768/// point rides in the block names rather than in a file of its own.
769pub fn scan(root: &Path, signal: &str) -> Result<Vec<BlockRef>> {
770    let base = root.join(signal);
771    let mut out = Vec::new();
772    let partitions = match fs::read_dir(&base) {
773        Ok(d) => d,
774        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(out),
775        Err(e) => {
776            return Err(Error::Io {
777                path: base,
778                source: e,
779            });
780        }
781    };
782    for partition in partitions {
783        let partition = partition.ctx(&base)?.path();
784        if !partition.is_dir() {
785            continue;
786        }
787        for entry in fs::read_dir(&partition).ctx(&partition)? {
788            let dir = entry.ctx(&partition)?.path();
789            let Some((min_ts, max_ts, node, seq, wal_hi)) = dir
790                .file_name()
791                .and_then(|n| n.to_str())
792                .and_then(parse_dir_name)
793            else {
794                continue;
795            };
796            out.push(BlockRef {
797                dir,
798                min_ts,
799                max_ts,
800                node,
801                seq,
802                wal_hi,
803            });
804        }
805    }
806    out.sort_by_key(|b| (b.min_ts, b.seq));
807    Ok(out)
808}
809
810/// Drop every block whose newest row is older than `cutoff_ns`.
811///
812/// TTL is a directory unlink, not a compaction: there is no read-modify-write of
813/// live data, so retention costs no IO bandwidth and cannot interfere with
814/// ingest.
815pub fn expire(root: &Path, signal: &str, cutoff_ns: i64) -> Result<usize> {
816    expire_with(root, signal, cutoff_ns, &|_| Ok(()))
817}
818
819/// [`expire`], with something to do to each block before it is unlinked.
820///
821/// The hook exists for one caller — [`crate::offload`], copying the block to an
822/// object store — and the ordering is the whole point of putting it here rather
823/// than in a sweep of its own. A hook that returns an error keeps its block:
824/// the delete is skipped, the sweep continues, and the next minute tries again.
825/// So the failure direction is fixed at "two copies, never zero", and there is
826/// no window in which a block exists in neither place. A separate upload pass
827/// running beside `expire` could not promise that without a marker file to
828/// coordinate them, which is the coordination state principle 4 rules out.
829pub fn expire_with(
830    root: &Path,
831    signal: &str,
832    cutoff_ns: i64,
833    before_delete: &dyn Fn(&BlockRef) -> Result<()>,
834) -> Result<usize> {
835    let mut dropped = 0;
836    for block in scan(root, signal)? {
837        if block.max_ts < cutoff_ns {
838            if let Err(e) = before_delete(&block) {
839                tracing::warn!(
840                    block = %block.dir.display(),
841                    error = %e,
842                    "cannot offload block; keeping it locally and retrying next sweep",
843                );
844                continue;
845            }
846            match fs::remove_dir_all(&block.dir) {
847                Ok(()) => dropped += 1,
848                // Another replica sharing this volume expired it first. Racing
849                // to delete the same immutable block is not a conflict, and
850                // aborting here would leave the rest of the sweep undone.
851                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
852                // Anything else — a directory this process cannot traverse, a
853                // file the kernel refuses to unlink — is about *this* block and
854                // says nothing about the next one. Returning here stopped the
855                // sweep for the whole signal, so one undeletable block meant
856                // retention silently stopped reclaiming space for every other
857                // block beside it, which is the failure retention exists to
858                // prevent. Log it and keep going; the count returned is the
859                // blocks actually dropped, so a sweep that reclaimed nothing
860                // still reports nothing.
861                Err(e) => tracing::warn!(
862                    block = %block.dir.display(),
863                    error = %e,
864                    "cannot expire block; skipping it",
865                ),
866            }
867        }
868    }
869    Ok(dropped)
870}
871
872/// Refuse to start on a filesystem the read path cannot survive.
873///
874/// Every block is read through `mmap`. On a network filesystem a server that
875/// goes away, or a file that changes length underneath a mapping, is delivered
876/// as `SIGBUS` — a signal, not an `io::Error`. There is nothing to catch and no
877/// way to unwind; the process dies mid-query. The atomicity this design rests on
878/// is also weaker there: NFS `rename` is atomic on the server but a client may
879/// still serve a cached negative lookup, and `fsync` semantics vary by mount
880/// option. Both are reasons to say no at startup rather than at 3am.
881///
882/// Called once, on the data directory, before anything is published or mapped.
883pub fn check_filesystem(path: &Path) -> Result<()> {
884    check_fs_type(path, fs_type(path)?)
885}
886
887/// The decision [`check_filesystem`] makes, split from the mount it makes it
888/// about for the same reason [`check_format`] takes a string rather than a
889/// file: the rule is the part that can be wrong, and a test cannot conjure an
890/// NFS mount to state it over.
891fn check_fs_type(path: &Path, fs: Option<String>) -> Result<()> {
892    let Some(fs) = fs else {
893        return Ok(());
894    };
895    // FUSE is the ambiguous one and it has to stay a warning: the magic number
896    // is identical for `gcsfuse` and `s3fs`, which are exactly as fatal as NFS,
897    // and for a perfectly local userspace filesystem, which is fine. Refusing
898    // would strand the second case; staying silent would strand the first.
899    if fs == "fuse" {
900        tracing::warn!(
901            path = %path.display(),
902            "data directory is on a FUSE filesystem. If it is network-backed \
903             (gcsfuse, s3fs, rclone), mmap will raise SIGBUS and kill the \
904             process; if it is local, ignore this."
905        );
906        return Ok(());
907    }
908    Err(Error::NetworkFilesystem {
909        path: path.to_path_buf(),
910        fs,
911    })
912}
913
914/// Refuse to start on a data directory that cannot be written to.
915///
916/// `create_dir_all` returns `Ok` for a directory that already exists whatever
917/// its mode, so a read-only mount, a wrong-uid volume or a typo pointing at
918/// someone else's path gets all the way to a listening socket. The first
919/// evidence is then a flush error per export, minutes later, under load, which
920/// reads as a Mira fault rather than as a mount that was never writable — the
921/// same reasoning as [`check_filesystem`], and the same one line in `main`.
922///
923/// The probe carries the pid because replicas may share a directory (section 10) and
924/// two of them starting together must not race each other's cleanup.
925pub fn check_writable(path: &Path) -> Result<()> {
926    let probe = path.join(format!(".mira-write-probe-{}", std::process::id()));
927    // The error names the directory, not the probe: the probe is an
928    // implementation detail and nobody should go looking for that filename.
929    let fail = |source| Error::NotWritable {
930        path: path.to_path_buf(),
931        source,
932    };
933    fs::write(&probe, []).map_err(fail)?;
934    fs::remove_file(&probe).map_err(fail)
935}
936
937/// One filled `statfs`, shared by the two things that ask the mount a question.
938fn statfs(path: &Path) -> Result<libc::statfs> {
939    let c = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).map_err(|_| Error::Io {
940        path: path.to_path_buf(),
941        source: io::Error::new(io::ErrorKind::InvalidInput, "path contains a NUL byte"),
942    })?;
943    // SAFETY: `statfs` is POD — integers and fixed byte arrays — so all-zero is
944    // a valid value to hold until the call below fills it. Only fields `statfs`
945    // itself writes are read afterwards, and only on the success path.
946    let mut buf: libc::statfs = unsafe { std::mem::zeroed() };
947    // SAFETY: `c` is a `CString` — NUL-terminated by construction, rejected
948    // above if the path had an interior NUL — and it is still live at the call.
949    // `&mut buf` is a correctly typed, writable `statfs` the kernel fills.
950    if unsafe { libc::statfs(c.as_ptr(), &mut buf) } != 0 {
951        return Err(Error::Io {
952            path: path.to_path_buf(),
953            source: io::Error::last_os_error(),
954        });
955    }
956    Ok(buf)
957}
958
959/// How much of the filesystem holding `path` is still free: the fraction of its
960/// total size, and the same quantity in bytes.
961///
962/// Both come off one `statfs` because neither answers the question alone. A
963/// fraction calls 45 GiB free on a 1 TB volume "5% free, nearly full" when that
964/// is more room than most deployments ever use; a byte count cannot tell a
965/// comfortable 64 GB SSD from one about to wedge. Whoever is deciding to delete
966/// data wants both, and wants them from the same instant.
967///
968/// `f_bavail`, not `f_bfree`: the difference is the root reserve (5% on a
969/// default ext4), which is space the process cannot write into and therefore
970/// not space Mira has. Both terms of the ratio are in blocks of `f_bsize`, so
971/// the block size cancels out of the fraction — it only appears in the bytes.
972pub fn free(path: &Path) -> Result<(f64, u64)> {
973    let buf = statfs(path)?;
974    let bytes = (buf.f_bavail as u64).saturating_mul(buf.f_bsize as u64);
975    if buf.f_blocks == 0 {
976        // A mount that reports no blocks at all — some pseudo-filesystems do —
977        // is not a mount that can fill up, and calling it 0% free would stop
978        // ingest on a node with nothing wrong with it.
979        return Ok((1.0, bytes));
980    }
981    Ok((buf.f_bavail as f64 / buf.f_blocks as f64, bytes))
982}
983
984/// How much of the filesystem holding `path` is still free, as a fraction of
985/// its total size. The fraction half of [`free`], for the callers that report
986/// it rather than act on it: `/api/v1/stats`, the TUI header and the operator's
987/// scaling signal all want a number an operator can read at a glance.
988pub fn free_fraction(path: &Path) -> Result<f64> {
989    Ok(free(path)?.0)
990}
991
992/// The mount's filesystem type, if it is one of the ones that matter. `None`
993/// means "nothing to say about it", which is every local filesystem.
994fn fs_type(path: &Path) -> Result<Option<String>> {
995    // statfs(2) needs the path to exist; the caller creates the data directory
996    // before this runs, but a bare `Ok(None)` if it does not is friendlier than
997    // an ENOENT that says nothing about filesystems.
998    if !path.exists() {
999        return Ok(None);
1000    }
1001    let buf = statfs(path)?;
1002
1003    // macOS reports the type by name, which is both readable and complete.
1004    #[cfg(target_os = "macos")]
1005    {
1006        let name: Vec<u8> = buf
1007            .f_fstypename
1008            .iter()
1009            .take_while(|&&c| c != 0)
1010            .map(|&c| c as u8)
1011            .collect();
1012        Ok(remote_fs(&String::from_utf8_lossy(&name)))
1013    }
1014
1015    #[cfg(not(target_os = "macos"))]
1016    {
1017        // Masked to 32 bits: `f_type` is `__fsword_t`, which is i64 on x86_64
1018        // glibc but i32 on some musl and 32-bit targets, where a magic with the
1019        // high bit set (CIFS, SMB2) arrives sign-extended.
1020        Ok(remote_fs((buf.f_type as u64) & 0xffff_ffff))
1021    }
1022}
1023
1024/// The mounts that break `mmap`, keyed the way this platform names them.
1025///
1026/// Split from [`fs_type`] for the reason [`check_fs_type`] is: it is a table of
1027/// constants, and a `statfs` on any machine that runs the tests returns exactly
1028/// one of them — the fallthrough. Left inline, ten of the eleven arms below are
1029/// unreachable from a real mount, so a magic with a transposed digit would ship
1030/// looking as tested as the rest of the file.
1031#[cfg(target_os = "macos")]
1032fn remote_fs(name: &str) -> Option<String> {
1033    match name {
1034        "nfs" | "smbfs" | "cifs" | "webdav" | "afpfs" | "ftp" => Some(name.into()),
1035        n if n.contains("fuse") => Some("fuse".into()),
1036        _ => None,
1037    }
1038}
1039
1040/// Linux reports a magic number rather than a name. Listed rather than ranged
1041/// because the set of filesystems that break `mmap` is small, specific and does
1042/// not grow often; anything unrecognised is treated as local, which is the right
1043/// default for a check whose false positive is "Mira will not start".
1044#[cfg(not(target_os = "macos"))]
1045fn remote_fs(magic: u64) -> Option<String> {
1046    match magic {
1047        0x6969 => Some("NFS".into()),
1048        0x517b => Some("SMB".into()),
1049        0xff53_4d42 => Some("CIFS".into()),
1050        0xfe53_4d42 => Some("SMB2".into()),
1051        0x0102_1997 => Some("9P".into()),
1052        0x5346_414f => Some("AFS".into()),
1053        0x00c3_6400 => Some("CephFS".into()),
1054        0x0116_1970 => Some("GFS2".into()),
1055        0x7461_636f => Some("OCFS2".into()),
1056        0x0bd0_0bd0 => Some("Lustre".into()),
1057        0x6573_5546 => Some("fuse".into()),
1058        _ => None,
1059    }
1060}
1061
1062/// The cold-tier marker. Its presence means every table in the block is already
1063/// ZSTD-encoded, so a sweep can skip the directory without opening a file.
1064pub(crate) const COLD_MARKER: &str = "cold";
1065
1066/// A block goes cold once it has aged out of the hour it was partitioned into.
1067///
1068/// Reusing the partition width means the tier boundary is derived rather than
1069/// configured: the same instant that stops new rows landing next to this block
1070/// is the one that stops queries with a default window from reaching it.
1071pub const COLD_AFTER_NS: i64 = NANOS_PER_HOUR;
1072
1073/// ponytail: a flat cap per sweep, so the first pass over an existing volume
1074/// drains at a few hundred MB a minute instead of saturating the disk for an
1075/// hour. Make it adaptive when a real deployment says the backlog matters.
1076const MAX_COMPACT_PER_SWEEP: usize = 8;
1077
1078/// Rewrite aged blocks ZSTD-compressed, in place.
1079///
1080/// Measured by `cargo run --release -p miradb-core --example tier` over section
1081/// 11's corpus: 0.113 of the plain size for logs, 0.126 for traces, at 634
1082/// MiB/s on one core. Warm, reading a compacted block back costs 1.11× the
1083/// plain read — the inflate is real and it is small. Cold, which is the only
1084/// state a block old enough to be compacted is in, 8.4× fewer pages to fault
1085/// and 8.4× fewer bytes to CRC more than pays for it. So the tier costs the
1086/// read path the zero-copy property and a tenth of a warm read, and only for
1087/// data nothing is scanning any more.
1088///
1089/// Crash safety is the trick `publish` already uses: write beside the target,
1090/// then rename. A crash leaves a directory with some tables compressed and some
1091/// not, which reads correctly — the codec is per-batch IPC metadata, not a
1092/// property of the directory — and the absent marker makes the next sweep
1093/// finish the job.
1094pub fn compact(root: &Path, signal: &str, node: u32, cutoff_ns: i64) -> Result<usize> {
1095    let (mut done, mut tried) = (0, 0);
1096    for block in scan(root, signal)? {
1097        // The budget counts attempts, not successes. A block that fails is a
1098        // block whose tables were read and CRC'd before it failed, so charging
1099        // only the successes would let a directory full of unreadable blocks
1100        // re-read every one of them on every sweep, for ever.
1101        if tried == MAX_COMPACT_PER_SWEEP {
1102            break;
1103        }
1104        if block.max_ts >= cutoff_ns || block.dir.join(COLD_MARKER).exists() {
1105            continue;
1106        }
1107        tried += 1;
1108        match compact_block(&block.dir, node) {
1109            Ok(()) => done += 1,
1110            // Expired out from under the sweep, by this node's own retention or
1111            // another replica's. Nothing to compact is not a failure.
1112            Err(Error::Io { source, .. }) if source.kind() == io::ErrorKind::NotFound => {}
1113            // One block that cannot be rewritten — a corrupt table, a bad
1114            // checksum, a permission the sweep does not have — used to end the
1115            // sweep, which meant compaction for the whole signal stopped
1116            // permanently at the oldest broken block and every block behind it
1117            // stayed uncompressed. Skipping keeps the block exactly as
1118            // expirable as it was: `expire` walks the same `scan` and unlinks
1119            // the directory without opening a file, so the block that cannot be
1120            // compacted is still the block retention takes.
1121            Err(e) => tracing::warn!(
1122                block = %block.dir.display(),
1123                error = %e,
1124                "cannot compact block; skipping it",
1125            ),
1126        }
1127    }
1128    Ok(done)
1129}
1130
1131fn compact_block(dir: &Path, node: u32) -> Result<()> {
1132    // Collected before rewriting: entries created during an open `read_dir` may
1133    // or may not be returned, and one of these renames lands on a name the
1134    // iterator has not reached yet.
1135    let mut tables = Vec::new();
1136    for entry in fs::read_dir(dir).ctx(dir)? {
1137        let path = entry.ctx(dir)?.path();
1138        if path.extension().is_some_and(|e| e == "arrow") {
1139            tables.push(path);
1140        }
1141    }
1142
1143    for path in tables {
1144        let table = open_table(&path)?;
1145        // The staging name carries the node for the same reason `publish`'s
1146        // does: two replicas sharing this volume both see this block go cold,
1147        // and one truncating the other's half-written file would put garbage
1148        // under the rename.
1149        let tmp = path.with_extension(format!("{node:08x}.tmp"));
1150        write_table_with(&tmp, &table.batches, Some(arrow_ipc::CompressionType::ZSTD))?;
1151        // Rename rather than rewrite in place. A reader that already mapped the
1152        // old inode keeps reading it — POSIX holds an unlinked file open under
1153        // its mappings — which is the same guarantee `expire` depends on and
1154        // what keeps `open_table`'s immutability claim true.
1155        fs::rename(&tmp, &path).ctx(&path)?;
1156    }
1157
1158    // Marker last, so a crash mid-rewrite is retried rather than declared done.
1159    crate::sync_all(&File::create(dir.join(COLD_MARKER)).ctx(dir)?).ctx(dir)?;
1160    fsync_dir(dir)
1161}
1162
1163/// A table read straight out of its mapping.
1164///
1165/// The `RecordBatch` buffers point into the mmap; the mapping is kept alive by
1166/// the `Arc` that every `Buffer` holds, so `MappedTable` can be dropped while
1167/// batches derived from it are still in use.
1168pub struct MappedTable {
1169    pub batches: Vec<RecordBatch>,
1170    /// Address range of the mapping, so the zero-copy property can be asserted
1171    /// rather than assumed.
1172    mapping: std::ops::Range<usize>,
1173}
1174
1175impl MappedTable {
1176    /// `(buffers_pointing_into_the_mapping, buffers_total)`.
1177    ///
1178    /// Walks every buffer of every column including child data, so a partially
1179    /// copied nested array shows up. `require_alignment(true)` should already
1180    /// make a copy impossible; this is the assertion that says so out loud.
1181    ///
1182    /// A cold block (see [`compact`]) reports 0/n on purpose: decompression has
1183    /// to allocate. Only the hot tier is held to `inside == total`.
1184    pub fn zero_copy_ratio(&self) -> (usize, usize) {
1185        let (mut inside, mut total) = (0, 0);
1186        for batch in &self.batches {
1187            for col in batch.columns() {
1188                let mut stack = vec![col.to_data()];
1189                while let Some(d) = stack.pop() {
1190                    for buf in d.buffers() {
1191                        total += 1;
1192                        if self.mapping.contains(&(buf.as_ptr() as usize)) {
1193                            inside += 1;
1194                        }
1195                    }
1196                    stack.extend(d.child_data().iter().cloned());
1197                }
1198            }
1199        }
1200        (inside, total)
1201    }
1202}
1203
1204/// [`open_table`], but a missing file means an empty table rather than an error.
1205///
1206/// This is the normal way to read any table that can legitimately have no rows,
1207/// which is most of them: `publish` skips writing a zero-row table, so a traces
1208/// block from a service that emits no span links simply has no
1209/// `span_links.arrow`. It is also how a block written before a table existed
1210/// reads back, which is the same case a version from now.
1211pub fn open_table_opt(path: &Path) -> Result<Option<MappedTable>> {
1212    match open_table(path) {
1213        Err(Error::Io { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
1214        other => other.map(Some),
1215    }
1216}
1217
1218/// Decide whether this binary is allowed to read a block declaring `declared`
1219/// as its [`FORMAT_KEY`].
1220///
1221/// Refusing the future is the whole job: a newer block read as the current
1222/// format would not fail, it would answer wrongly, because the readers that go
1223/// through a table by column position cannot tell a shifted column from the one
1224/// they wanted.
1225fn check_format(path: &Path, declared: Option<&str>) -> Result<()> {
1226    let version = match declared {
1227        None => LEGACY_VERSION,
1228        Some(v) => v
1229            .parse::<u32>()
1230            .map_err(|_| corrupt(path, format!("{FORMAT_KEY} is `{v}`, not a version")))?,
1231    };
1232    if version > FORMAT_VERSION {
1233        return Err(Error::Io {
1234            path: path.to_path_buf(),
1235            source: io::Error::new(
1236                io::ErrorKind::Unsupported,
1237                format!(
1238                    "block format version {version} was written by a newer Mira; \
1239                     this binary reads up to version {FORMAT_VERSION}"
1240                ),
1241            ),
1242        });
1243    }
1244    Ok(())
1245}
1246
1247/// One encapsulated IPC message, described entirely by the *checksummed* bytes
1248/// it starts at.
1249///
1250/// Nothing in here comes from the footer, and that is the point. The footer's
1251/// `dictionaries` and `recordBatches` vectors are the file's table of contents,
1252/// they sit outside the CRC, and a flatbuffer vector's length is a single `u32`
1253/// — so clearing `recordBatches` is *one bit flip* that makes a block read back
1254/// `Ok` with no rows in it. Not a panic and not an error: a whole table of
1255/// telemetry silently gone, reported as success, which is the worst of the three
1256/// outcomes and the only one no caller can react to.
1257///
1258/// The body does not need that table of contents. Every message declares its own
1259/// metadata length in the 8-byte encapsulation prefix and its own body length in
1260/// its flatbuffer header, both inside `[0, body_len)`, so the messages chain: the
1261/// next one starts exactly [`Framed::stride`] bytes after this one. Walking that
1262/// chain costs one extra flatbuffer verify per message — a few hundred bytes each,
1263/// against a CRC of the whole body — and takes the footer out of the read path.
1264struct Framed {
1265    /// What arrow-rs is told about the message. Only `metaDataLength` is read
1266    /// back out of it (`read_record_batch` slices `data` by it); the offset is
1267    /// relative to `data`, which starts at the message, so it is zero.
1268    block: arrow_ipc::Block,
1269    /// Exactly this message: metadata, padding and body, and nothing after it.
1270    data: Buffer,
1271    header: arrow_ipc::MessageHeader,
1272    version: MetadataVersion,
1273}
1274
1275impl Framed {
1276    /// Distance to the next message. `metaDataLength` is padded to [`ALIGNMENT`]
1277    /// by the writer and is at least 8, so this always advances.
1278    fn stride(&self) -> usize {
1279        self.block.metaDataLength() as usize + self.block.bodyLength() as usize
1280    }
1281}
1282
1283/// Frame the message at `offset`, bounds-checking every number it declares
1284/// against the region the CRC covers.
1285///
1286/// The checks are not belt-and-braces. `Buffer::slice_with_length` panics on a
1287/// range it does not like, `panic = "abort"` makes that a process death, and the
1288/// numbers being checked were read off a disk — see [`corrupt`].
1289fn message_at(path: &Path, buffer: &Buffer, offset: usize, body_len: usize) -> Result<Framed> {
1290    let bad = |why: String| corrupt(path, format!("message at offset {offset}: {why}"));
1291    // Written as a subtraction from `body_len` rather than an addition to
1292    // `offset`, so that an offset near `usize::MAX` is rejected instead of
1293    // wrapping into the range it is being tested against.
1294    if offset > body_len || body_len - offset < 8 {
1295        return Err(bad(format!(
1296            "outside the {body_len} bytes the checksum covers"
1297        )));
1298    }
1299    let head = &buffer[offset..offset + 8];
1300    if head[..4] != CONTINUATION {
1301        return Err(bad("no message framing here".into()));
1302    }
1303    // `write_encoded_data` declares the padded metadata length *after* the
1304    // 8-byte prefix, so the header the decoder skips is exactly 8 more.
1305    let declared = i32::from_le_bytes(head[4..].try_into().expect("4 bytes"));
1306    let Some(meta) = declared.checked_add(8).filter(|m| *m >= 8) else {
1307        return Err(bad(format!("{declared} is not a metadata length")));
1308    };
1309    let meta = meta as usize;
1310    if body_len - offset < meta {
1311        return Err(bad(format!(
1312            "{meta} bytes of metadata run past the {body_len} bytes the checksum covers"
1313        )));
1314    }
1315    // The verifier here is what makes the two accessors below safe to call.
1316    let message = arrow_ipc::root_as_message(&buffer[offset + 8..offset + meta])
1317        .map_err(|e| bad(format!("not a readable IPC message: {e}")))?;
1318    let body = message.bodyLength();
1319    let room = (body_len - offset - meta) as i64;
1320    if body < 0 || body > room {
1321        return Err(bad(format!(
1322            "a {body}-byte body runs past the {body_len} bytes the checksum covers"
1323        )));
1324    }
1325    Ok(Framed {
1326        block: arrow_ipc::Block::new(0, meta as i32, body),
1327        data: buffer.slice_with_length(offset, meta + body as usize),
1328        header: message.header_type(),
1329        version: message.version(),
1330    })
1331}
1332
1333/// What this process has already checksummed, and the file it was.
1334///
1335/// The CRC is the right thing to do on a *first* read and pure waste on the
1336/// second. A published block never changes, so a scan that reopens the same
1337/// corpus re-hashes bytes this same process already hashed, to answer a question
1338/// the previous query already answered.
1339///
1340/// It is worth stating what that is and is not worth, because `docs/market.md`
1341/// named this fix on the back of a number that turned out to be a coincidence —
1342/// 4,380 MiB in 885 ms is ~5 GB/s, which was read as "that is `crc32fast`'s
1343/// rate here" and therefore as ~93% of an unpruned scan. Warm, it is nearer
1344/// 27 GB/s. Measured on both sides of one run instead, re-verification is
1345/// **between a quarter and two fifths** of a single block's read path, and
1346/// about 1.1x on a full-corpus scan — which is bound by page cache, not by
1347/// this. The "35-39%, a median of 1.55x" this comment used to carry was three
1348/// samples of a quantity that moves between 1.14x and 2.21x, and is withdrawn
1349/// as a median. `scan_cost_per_row` in `query.rs` is the run; section 11 of
1350/// `docs/architecture/performance-query.md` is the write-up.
1351///
1352/// The identity is the path *plus* [`FileId`], never the path alone, because a
1353/// name in this tree is not a file for life: [`compact`] renames a new table
1354/// over an existing name, and it must re-verify. Entries are keyed by path so a
1355/// replaced file overwrites its predecessor instead of accumulating beside it.
1356///
1357/// What this cannot see is a bit that rots under a live file without any of the
1358/// three fields moving. That is the whole of the trade, and it is the reason the
1359/// cache is process-scoped rather than persisted: a restart re-verifies
1360/// everything, so the window is one process lifetime and not the life of the
1361/// block. The alternative — dropping the CRC, or covering fewer tables — either
1362/// gives up detection entirely or gives it up for whichever table a query
1363/// skipped.
1364static VERIFIED: OnceLock<Mutex<HashMap<PathBuf, FileId>>> = OnceLock::new();
1365
1366/// Enough of a file to say it is the same file, for a cache whose wrong answer
1367/// is a corrupt block served as good data.
1368///
1369/// All three fields, and each one is load-bearing against a different way the
1370/// bytes under a path change without the others noticing:
1371///
1372/// * **`len`** is the cheap one and catches a rewrite of a different size.
1373/// * **`mtime`** catches a rewrite of the same size. Alone it is not enough,
1374///   because a length-preserving write inside one filesystem mtime tick does not
1375///   move it — see [`SETTLED`], which closes that by construction.
1376/// * **`ino`** catches a *replacement*, which is the case neither of the others
1377///   can see. `std::fs::copy` on APFS is `fcopyfile(COPYFILE_ALL)` and preserves
1378///   the source's mtime to the nanosecond; so do `cp -p`, `rsync -a`, `tar -xp`
1379///   and every backup agent worth using. Restoring a block from a copy of itself
1380///   therefore lands bytes this process never verified, at a path it has, under
1381///   a length and an mtime it remembers. A new file gets a new inode, and that is
1382///   the field that says so.
1383///
1384/// Keying on the inode *instead* would be worse than either: retention unlinks
1385/// block directories continuously and an inode number is reusable the moment its
1386/// last link goes, so a fresh table could be handed the number of an expired one
1387/// and inherit its verdict. Composed, that is a non-issue — a reused inode would
1388/// also have to arrive at the same path carrying the same length and the same
1389/// mtime — and each field covers what the others miss.
1390#[derive(Clone, Copy, PartialEq, Eq)]
1391struct FileId {
1392    len: u64,
1393    mtime: SystemTime,
1394    ino: u64,
1395}
1396
1397/// How old a file's mtime must be before a verification of it is worth
1398/// remembering.
1399///
1400/// Without this the cache has a real hole, and it is not hypothetical — it is
1401/// `corrupt_body_is_caught_not_returned_as_data` in `lib.rs`, which opens a
1402/// table, flips one bit of the body, and reopens expecting `BadChecksum`. The
1403/// flip does not change the length, so if both writes land inside one mtime tick
1404/// the identity is unchanged and a *corrupt block reads as already verified*.
1405///
1406/// A settle window closes it by construction rather than by hoping the clock is
1407/// fine-grained. An entry is only recorded once the file has been untouched for
1408/// longer than any filesystem's mtime granularity, so a subsequent write is
1409/// necessarily in a later tick and necessarily misses. Two seconds is rsync's
1410/// quick-check window and for the same reason: 1 s is the worst granularity in
1411/// the wild, and doubling it costs nothing here. A published block is renamed
1412/// into place and never written again, so by the second query that reads it, it
1413/// is hours old — the window only ever excludes a block being written right now,
1414/// which is the one that should be re-read anyway.
1415const SETTLED: std::time::Duration = std::time::Duration::from_secs(2);
1416
1417/// ponytail: clear-all rather than evict-oldest. Retention churns block paths,
1418/// so the map grows with the number of tables this process has ever opened, not
1419/// with the number that exist. At ~1,800 tables for the 8.33 GiB corpus this is
1420/// four orders of magnitude of headroom; an LRU is the upgrade path if a process
1421/// ever opens a million distinct tables and the re-verification spike after a
1422/// clear shows up in a p99.
1423const VERIFIED_CAP: usize = 1 << 16;
1424
1425/// What [`open_table`] should do about this file's checksum.
1426///
1427/// Three states and not a `bool`, because "already checked" and "cannot tell"
1428/// both mean "do not record" and only one of them means "do not check". Reading
1429/// them off one `Option` is how a cache turns into a hole.
1430enum Verify {
1431    /// This process has already checksummed this exact file. Skip it.
1432    Skip,
1433    /// Checksum it. On success, record it under this identity — `None` to check
1434    /// it again next time, which is the answer for a file whose metadata would
1435    /// not read and for one still inside its settle window.
1436    Check(Option<FileId>),
1437}
1438
1439/// Has this exact file already been checksummed by this process?
1440fn verify_plan(path: &Path, file: &File) -> Verify {
1441    // Off the open descriptor rather than the path, so every field describes the
1442    // file this mapping is about to cover.
1443    let Some(id) = file.metadata().ok().and_then(|m| {
1444        Some(FileId {
1445            len: m.len(),
1446            mtime: m.modified().ok()?,
1447            ino: m.ino(),
1448        })
1449    }) else {
1450        return Verify::Check(None);
1451    };
1452    let map = VERIFIED.get_or_init(Default::default);
1453    // A poisoned lock means another thread panicked mid-insert. The map is a
1454    // pure cache, so the recovery is to use it anyway rather than to propagate
1455    // a panic into every subsequent read.
1456    let seen = map.lock().unwrap_or_else(|e| e.into_inner());
1457    if seen.get(path) == Some(&id) {
1458        return Verify::Skip;
1459    }
1460    drop(seen);
1461    // A file still inside its settle window is checked and *not* recorded, so
1462    // the next open checks it again. See [`SETTLED`].
1463    let settled = SystemTime::now()
1464        .duration_since(id.mtime)
1465        .is_ok_and(|age| age >= SETTLED);
1466    Verify::Check(settled.then_some(id))
1467}
1468
1469/// Record that `path` passed its checksum as the file `id` describes.
1470fn mark_verified(path: &Path, id: FileId) {
1471    let mut seen = VERIFIED
1472        .get_or_init(Default::default)
1473        .lock()
1474        .unwrap_or_else(|e| e.into_inner());
1475    if seen.len() >= VERIFIED_CAP {
1476        seen.clear();
1477    }
1478    seen.insert(path.to_path_buf(), id);
1479}
1480
1481/// Open one table of a block with no buffer copies.
1482///
1483/// This is a blocking call that can take a hard page fault. It must never run on
1484/// a tokio worker: a cold fault stalls the whole OS thread with no yield point
1485/// and no signal to the runtime. Callers go through `spawn_blocking` or a
1486/// dedicated reader pool.
1487pub fn open_table(path: &Path) -> Result<MappedTable> {
1488    let file = File::open(path).ctx(path)?;
1489    // Off the open descriptor, not the path: `fstat` describes the file this
1490    // mapping is about to cover, where a later `stat` of the name could describe
1491    // whatever replaced it.
1492    let plan = verify_plan(path, &file);
1493    // SAFETY: the obligation is that nothing modifies or truncates this file
1494    // while the mapping lives — a truncation is a SIGBUS on the next page
1495    // touched, which no in-process check can catch. What discharges it is
1496    // Mira's own discipline, not the kernel: a block becomes visible by one
1497    // directory rename and is never written again ([`publish`]); [`compact`]
1498    // replaces a table by renaming a new file over the name, which unlinks the
1499    // old inode rather than truncating it; [`expire`] is `remove_dir_all`,
1500    // also unlink. POSIX keeps an unlinked inode alive under its mappings, so
1501    // every path Mira has lands on the safe side.
1502    //
1503    // That argument covers this process and every replica sharing the volume,
1504    // because they all run this code. It does not cover a third party editing
1505    // a block file in place, and nothing here can — the data directory is
1506    // Mira's, and that is a deployment property, not a checkable one.
1507    let mmap = unsafe { Mmap::map(&file) }.ctx(path)?;
1508    // A first open CRCs the whole body, so every page is touched; a later one
1509    // skips the CRC but a scan still reads most of what it mapped. Faulting them
1510    // in one at a time caps a cold read at fault latency; asking for the file up
1511    // front lets the kernel read ahead. A hint, so a failure is not an error.
1512    let _ = mmap.advise(memmap2::Advice::WillNeed);
1513
1514    if mmap.len() < MAGIC.len() + 10 || &mmap[..MAGIC.len()] != MAGIC {
1515        return Err(Error::BadMagic {
1516            path: path.to_path_buf(),
1517        });
1518    }
1519
1520    let len = mmap.len();
1521    let base = mmap.as_ptr() as usize;
1522    let ptr = NonNull::new(mmap.as_ptr().cast_mut()).expect("mmap is never null");
1523    // SAFETY: `ptr` and `len` are `mmap`'s own `as_ptr`/`len`, so they describe
1524    // exactly the mapped region and nothing beyond it, page-aligned. Moving the
1525    // `Mmap` into the `Arc` moves an (address, length) pair, not the mapping,
1526    // so `ptr` is still the same live region afterwards — and the `Arc` is the
1527    // allocation owner, so `munmap` runs only after the last `Buffer` sliced
1528    // from it is dropped. `cast_mut` is to fit the signature; `Buffer` is
1529    // read-only and never writes through it, which matters because the mapping
1530    // is `PROT_READ`.
1531    let buffer = unsafe { Buffer::from_custom_allocation(ptr, len, Arc::new(mmap)) };
1532
1533    let trailer = len - 10;
1534    let footer_len = read_footer_length(buffer[trailer..].try_into().expect("10 bytes"))?;
1535    // `read_footer_length` only rejects a negative length, so a garbled one is
1536    // still a number this would subtract past zero and then slice with. See
1537    // [`corrupt`] for why that must not be a panic.
1538    if footer_len > trailer {
1539        return Err(corrupt(
1540            path,
1541            format!("footer says it is {footer_len} bytes, in a {len}-byte file"),
1542        ));
1543    }
1544    let footer_start = trailer - footer_len;
1545    let footer = root_as_footer(&buffer[footer_start..trailer])
1546        .map_err(|e| arrow_schema::ArrowError::ParseError(e.to_string()))?;
1547
1548    let find = |key: &str| -> Option<&str> {
1549        footer
1550            .custom_metadata()
1551            .into_iter()
1552            .flatten()
1553            .find(|kv| kv.key() == Some(key))
1554            .and_then(|kv| kv.value())
1555    };
1556    let meta = |key: &'static str| -> Result<&str> {
1557        find(key).ok_or(Error::MissingMetadata {
1558            path: path.to_path_buf(),
1559            key,
1560        })
1561    };
1562
1563    // First, before the CRC and before a single byte of the body is read: the
1564    // version is what says the rest of this file means what this binary thinks
1565    // it means, so nothing else here is worth checking until it has passed.
1566    check_format(path, find(FORMAT_KEY))?;
1567
1568    let expected = u32::from_str_radix(meta(CRC_KEY)?, 16).map_err(|_| Error::MissingMetadata {
1569        path: path.to_path_buf(),
1570        key: CRC_KEY,
1571    })?;
1572    let body_len: usize = meta(CRC_LEN_KEY)?
1573        .parse()
1574        .ok()
1575        .filter(|&n: &usize| n <= footer_start)
1576        .ok_or(Error::MissingMetadata {
1577            path: path.to_path_buf(),
1578            key: CRC_LEN_KEY,
1579        })?;
1580    // The footer reads above are a few hundred bytes and run either way: they
1581    // are what proves `body_len` is in range, and the slicing below trusts it.
1582    // Only the hash of the body is skipped, and only for a file this process
1583    // has already hashed — see [`VERIFIED`].
1584    if let Verify::Check(id) = plan {
1585        let actual = crc32fast::hash(&buffer[..body_len]);
1586        if actual != expected {
1587            return Err(Error::BadChecksum {
1588                path: path.to_path_buf(),
1589                expected,
1590                actual,
1591            });
1592        }
1593        if let Some(id) = id {
1594            mark_verified(path, id);
1595        }
1596    }
1597
1598    // Everything from here on comes out of the *body*, not out of the footer.
1599    //
1600    // Extending the CRC over the footer was the obvious fix and it is not
1601    // possible without leaving the format: the checksum lives in the footer's
1602    // own custom metadata, and a checksum cannot cover the bytes it is stored
1603    // in. The two places outside the footer are a trailer appended after the
1604    // final `ARROW1` magic — which makes the file unreadable to every other
1605    // Arrow implementation, including arrow-rs's own `FileReader`, since they
1606    // all seek to `len - 10` — and a sidecar file per table, which doubles the
1607    // file count and the fsyncs and reintroduces the two-file atomicity problem
1608    // this design does not otherwise have.
1609    //
1610    // The other direction is free: an Arrow IPC file's body is *self-describing*
1611    // and holds a second copy of everything the footer says. The schema is
1612    // written as the first message as well as into the footer; the messages
1613    // chain, so the table of contents is derivable; and all of that is inside
1614    // `[0, body_len)`, which the CRC has just verified. So rather than covering
1615    // the footer, stop reading it. What is left of it is its custom metadata,
1616    // and that is self-checking — a corrupt CRC or length fails the CRC, and a
1617    // corrupt version is refused by [`check_format`].
1618    //
1619    // The schema is the half that mattered for memory safety: with validation
1620    // skipped below, a footer schema naming a wider type than the body holds
1621    // builds an array over a buffer too short for it, which is undefined
1622    // behaviour rather than an `Error::BadChecksum`.
1623    let first = message_at(path, &buffer, HEADER_LEN, body_len)?;
1624    if first.header != arrow_ipc::MessageHeader::Schema {
1625        return Err(corrupt(
1626            path,
1627            format!(
1628                "the body starts with {:?}, not a schema message",
1629                first.header.variant_name().unwrap_or("an unknown message")
1630            ),
1631        ));
1632    }
1633    let schema = Arc::new(
1634        arrow_ipc::convert::try_schema_from_ipc_buffer(&first.data).map_err(|e| {
1635            corrupt(
1636                path,
1637                format!("no readable schema at the head of the body: {e}"),
1638            )
1639        })?,
1640    );
1641
1642    // Skipping validation is what keeps this a mmap read: with it on, every
1643    // Utf8 column runs `std::str::from_utf8` over the whole values buffer — a
1644    // sequential scan that faults in every page of string data, which is
1645    // precisely what demand paging was supposed to avoid.
1646    //
1647    // SAFETY: only `with_skip_validation` is unsafe here. It turns off offset
1648    // bounds, buffer length and UTF-8 checks, so the arrays built below are
1649    // trusted rather than verified, and an out-of-range offset would read
1650    // arbitrary memory. What backs the trust is the CRC checked above: it
1651    // covers `[0, body_len)`, which is every byte the IPC writer emitted before
1652    // `finish()` — schema, dictionary and record-batch messages and their
1653    // bodies (see `write_table_with`, which snapshots the CRC at exactly that
1654    // point). Those bytes are therefore provably the ones arrow-rs's own writer
1655    // produced from arrays it had already validated, and by the paragraph above
1656    // they are the only bytes the decoder is shown.
1657    let mut decoder = unsafe {
1658        FileDecoder::new(schema, first.version)
1659            .with_require_alignment(true)
1660            .with_skip_validation(true)
1661    };
1662
1663    // Write order is decode order: `FileWriter` emits a dictionary before the
1664    // batch that refers to it, so one pass down the chain feeds the decoder in
1665    // the order it needs. `body_len` is the writer's position at the CRC
1666    // snapshot, which is the end of the last message — the end-of-stream marker
1667    // and the footer are emitted by `finish()`, after it — so the walk stops
1668    // exactly where the messages do.
1669    let mut batches = Vec::new();
1670    let mut offset = HEADER_LEN + first.stride();
1671    while offset < body_len {
1672        let msg = message_at(path, &buffer, offset, body_len)?;
1673        offset += msg.stride();
1674        let fail = |source| Error::Undecodable {
1675            path: path.to_path_buf(),
1676            source,
1677        };
1678        match msg.header {
1679            arrow_ipc::MessageHeader::DictionaryBatch => {
1680                decoder
1681                    .read_dictionary(&msg.block, &msg.data)
1682                    .map_err(fail)?;
1683            }
1684            arrow_ipc::MessageHeader::RecordBatch => {
1685                if let Some(rb) = decoder
1686                    .read_record_batch(&msg.block, &msg.data)
1687                    .map_err(fail)?
1688                {
1689                    batches.push(rb);
1690                }
1691            }
1692            other => {
1693                return Err(corrupt(
1694                    path,
1695                    format!(
1696                        "{} at offset {offset} is not a dictionary or a record batch",
1697                        other.variant_name().unwrap_or("an unknown message")
1698                    ),
1699                ));
1700            }
1701        }
1702    }
1703
1704    Ok(MappedTable {
1705        batches,
1706        mapping: base..base + len,
1707    })
1708}
1709
1710#[cfg(test)]
1711mod tests {
1712    use super::*;
1713    use arrow_array::{StringArray, UInt32Array};
1714    use arrow_schema::{DataType, Field, Schema};
1715
1716    fn dir(tag: &str) -> PathBuf {
1717        let d = std::env::temp_dir().join(format!("mira-blk-{tag}-{}", std::process::id()));
1718        let _ = fs::remove_dir_all(&d);
1719        fs::create_dir_all(&d).unwrap();
1720        d
1721    }
1722
1723    /// Two columns and a string, so that a footer schema naming a wider type
1724    /// than the body holds has something to be wrong about.
1725    fn batch() -> RecordBatch {
1726        let schema = Arc::new(Schema::new(vec![
1727            Field::new("id", DataType::UInt32, false),
1728            Field::new("body", DataType::Utf8, true),
1729        ]));
1730        RecordBatch::try_new(
1731            schema,
1732            vec![
1733                Arc::new(UInt32Array::from(vec![1, 2, 3])),
1734                Arc::new(StringArray::from(vec![Some("a"), None, Some("ccc")])),
1735            ],
1736        )
1737        .unwrap()
1738    }
1739
1740    /// The same two columns, wide and repetitive enough that ZSTD beats the
1741    /// plain bytes. `compress_to_vec` keeps the uncompressed copy whenever the
1742    /// frame comes out larger, so [`batch`] compressed has no frame in it at
1743    /// all and nothing for the cold-tier test to corrupt.
1744    fn compressible() -> RecordBatch {
1745        let n = 4_096u32;
1746        RecordBatch::try_new(
1747            batch().schema(),
1748            vec![
1749                Arc::new(UInt32Array::from_iter_values(0..n)),
1750                Arc::new(StringArray::from_iter_values(
1751                    (0..n).map(|_| "the same line of telemetry, over and over"),
1752                )),
1753            ],
1754        )
1755        .unwrap()
1756    }
1757
1758    fn sealed(min_ts: i64, max_ts: i64) -> Sealed {
1759        Sealed {
1760            tables: vec![("logs", batch())],
1761            sidecars: vec![],
1762            min_ts,
1763            max_ts,
1764            num_rows: 3,
1765        }
1766    }
1767
1768    /// A message header tag past `ENUM_MAX_MESSAGE_HEADER`, so that
1769    /// `variant_name()` has no name for it either — the reader has to say
1770    /// something useful about a message type that does not exist, not just
1771    /// about one it did not want.
1772    const UNKNOWN_MESSAGE: u8 = 42;
1773
1774    /// Where the footer starts, by the same three fields the reader uses.
1775    fn footer_start(bytes: &[u8]) -> usize {
1776        let n = bytes.len();
1777        let footer_len = i32::from_le_bytes(bytes[n - 10..n - 6].try_into().unwrap()) as usize;
1778        n - 10 - footer_len
1779    }
1780
1781    /// The two numbers in the footer that describe the checksummed region:
1782    /// where the CRC's own eight hex digits live in the file, and how many
1783    /// bytes they cover.
1784    fn crc_field(bytes: &[u8]) -> (usize, usize) {
1785        let start = footer_start(bytes);
1786        let footer = root_as_footer(&bytes[start..bytes.len() - 10]).unwrap();
1787        let md = footer.custom_metadata().unwrap();
1788        let find = |key: &str| {
1789            md.iter()
1790                .find(|kv| kv.key() == Some(key))
1791                .and_then(|kv| kv.value())
1792                .unwrap()
1793        };
1794        let hex = find(CRC_KEY);
1795        assert_eq!(hex.len(), 8, "the CRC is written as eight hex digits");
1796        (
1797            hex.as_ptr() as usize - bytes.as_ptr() as usize,
1798            find(CRC_LEN_KEY).parse().unwrap(),
1799        )
1800    }
1801
1802    /// Make the checksum agree with a body that has been changed underneath it.
1803    ///
1804    /// Repairing the CRC is the point of these tests rather than a way around
1805    /// them. Everything [`open_table`] checks *after* the checksum — the first
1806    /// message being a schema, the ones after it being dictionaries or batches,
1807    /// every length staying inside the covered region — exists for bytes the
1808    /// checksum cannot speak for: crc32 is 32 bits and collides, and the arrays
1809    /// below it are built with `with_skip_validation(true)`, so the first thing
1810    /// to notice a structurally wrong body would otherwise be a read off the
1811    /// end of the mapping. A mutation the checksum accepts is the only way to
1812    /// reach them, and it is the shape of the corruption they are for.
1813    ///
1814    /// The length is left alone deliberately: it is a decimal string of
1815    /// variable width, so anything that changes it changes the footer's size
1816    /// too. Every mutation here stays inside `[0, body_len)`.
1817    fn repair_crc(bytes: &mut [u8]) {
1818        let (at, body_len) = crc_field(bytes);
1819        let crc = crc32fast::hash(&bytes[..body_len]);
1820        bytes[at..at + 8].copy_from_slice(format!("{crc:08x}").as_bytes());
1821    }
1822
1823    /// Where the `header_type` union tag of the message at `offset` sits.
1824    ///
1825    /// Found by probing rather than by decoding a vtable: the layout inside the
1826    /// message is arrow-rs's business and a search that *verifies its own
1827    /// result* cannot land on the wrong byte. Same technique as
1828    /// [`a_footer_schema_naming_a_wider_type_is_not_the_one_the_read_uses`].
1829    fn header_tag(bytes: &[u8], offset: usize) -> usize {
1830        let declared =
1831            i32::from_le_bytes(bytes[offset + 4..offset + 8].try_into().unwrap()) as usize;
1832        let meta = offset + 8..offset + 8 + declared;
1833        for i in meta.clone() {
1834            let mut probe = bytes.to_vec();
1835            probe[i] = UNKNOWN_MESSAGE;
1836            let framed = arrow_ipc::root_as_message(&probe[meta.clone()]);
1837            if framed.is_ok_and(|m| m.header_type().0 == UNKNOWN_MESSAGE) {
1838                return i;
1839            }
1840        }
1841        panic!("the message at {offset} has no header tag to corrupt");
1842    }
1843
1844    /// The offset of the second message, which for every file this writes is
1845    /// the record batch: the schema is first and its stride leads here.
1846    fn second_message(path: &Path, bytes: &[u8]) -> usize {
1847        let covered = crc_field(bytes).1;
1848        let buffer = Buffer::from_vec(bytes.to_vec());
1849        HEADER_LEN
1850            + message_at(path, &buffer, HEADER_LEN, covered)
1851                .unwrap()
1852                .stride()
1853    }
1854
1855    /// The error every corruption has to produce: named, and not a panic.
1856    fn invalid_data(e: &Error, what: &str) {
1857        let Error::Io { source, .. } = e else {
1858            panic!("{what}: {e}")
1859        };
1860        assert_eq!(source.kind(), io::ErrorKind::InvalidData, "{what}: {e}");
1861    }
1862
1863    /// A footer length field that does not describe this file used to be a
1864    /// subtraction past zero and then a slice with the wrap-around — a panic,
1865    /// which `panic = "abort"` makes a process death and a crashloop, since the
1866    /// block is still there on the next start.
1867    #[test]
1868    fn a_corrupt_footer_length_is_an_error_not_a_panic() {
1869        let d = dir("footerlen");
1870        let path = d.join("logs.arrow");
1871        write_table(&path, &batch()).unwrap();
1872
1873        let good = fs::read(&path).unwrap();
1874        for len in [i32::MAX, good.len() as i32, good.len() as i32 - 9] {
1875            let mut bytes = good.clone();
1876            let n = bytes.len();
1877            bytes[n - 10..n - 6].copy_from_slice(&len.to_le_bytes());
1878            fs::write(&path, &bytes).unwrap();
1879            let Err(e) = open_table(&path) else {
1880                panic!("a footer length of {len} in a {n}-byte file read as a block")
1881            };
1882            assert!(
1883                matches!(&e, Error::Io { source, .. }
1884                    if source.kind() == io::ErrorKind::InvalidData),
1885                "{e}"
1886            );
1887        }
1888        let _ = fs::remove_dir_all(&d);
1889    }
1890
1891    /// The property the CRC cannot give directly, because it is stamped before
1892    /// the footer exists: every bit of the uncovered tail either fails the read
1893    /// or changes nothing about what the read returns. In particular the schema
1894    /// is the one the writer wrote — it comes from the covered copy at the head
1895    /// of the body — so no flip here can widen a column and build an array over
1896    /// a buffer too short for it.
1897    ///
1898    /// Exhaustive rather than sampled: the footer of this file is a few hundred
1899    /// bytes and the whole sweep is a fraction of a second, and the interesting
1900    /// bits (a length's high bit, an offset's sign bit) are exactly the ones a
1901    /// sample misses.
1902    #[test]
1903    fn no_bit_in_the_unchecked_footer_can_change_what_a_read_returns() {
1904        let d = dir("footerbits");
1905        let path = d.join("logs.arrow");
1906        let want = batch();
1907        write_table(&path, &want).unwrap();
1908
1909        let good = fs::read(&path).unwrap();
1910        let (start, n) = (footer_start(&good), good.len());
1911        assert!(start < n - 10, "no footer to corrupt");
1912        let mut flipped = 0;
1913        for i in start..n {
1914            for bit in 0..8u8 {
1915                let mut bytes = good.clone();
1916                bytes[i] ^= 1 << bit;
1917                fs::write(&path, &bytes).unwrap();
1918                if let Ok(t) = open_table(&path) {
1919                    assert_eq!(
1920                        t.batches,
1921                        vec![want.clone()],
1922                        "byte {i} bit {bit} decoded to other data"
1923                    );
1924                } else {
1925                    flipped += 1;
1926                }
1927            }
1928        }
1929        // Not every flip has to be caught — a bit in a padding byte or in the
1930        // unused half of a flatbuffer field is genuinely harmless — but a run
1931        // where nothing at all was rejected would mean the checks above never
1932        // ran.
1933        assert!(flipped > 0, "no corrupt footer was rejected");
1934        let _ = fs::remove_dir_all(&d);
1935    }
1936
1937    /// Both halves of what [`VERIFIED`] trades, in one test, because a cache
1938    /// whose only test is that it is fast is a cache nobody can review.
1939    ///
1940    /// The skip is not observable through the public API by design — a cached
1941    /// open and a fresh one return the same table — so it is observed the only
1942    /// way it can be: corrupt the body *without moving the mtime* and see
1943    /// whether the read still succeeds. On a settled file it does, and that is
1944    /// the documented trade. Move the mtime and it is caught, which is the part
1945    /// that has to keep working.
1946    #[test]
1947    fn a_settled_table_is_checksummed_once_and_a_touched_one_every_time() {
1948        let d = dir("verifycache");
1949        let path = d.join("logs.arrow");
1950        let want = batch();
1951        write_table(&path, &want).unwrap();
1952
1953        // Backdated past `SETTLED`, which is what a block that was published
1954        // even a few seconds ago looks like. Restored after every write below,
1955        // so the identity the cache holds never changes.
1956        let old = SystemTime::now() - std::time::Duration::from_secs(3600);
1957        let backdate = || {
1958            File::options()
1959                .write(true)
1960                .open(&path)
1961                .unwrap()
1962                .set_times(fs::FileTimes::new().set_modified(old))
1963                .unwrap();
1964        };
1965        backdate();
1966        assert_eq!(open_table(&path).unwrap().batches, vec![want]);
1967
1968        // Flip one bit deep in the covered body. The length does not change and
1969        // the mtime is put back, so this is byte-for-byte a different file
1970        // wearing the identity the cache remembers.
1971        let mut bytes = fs::read(&path).unwrap();
1972        let mid = crc_field(&bytes).1 / 2;
1973        bytes[mid] ^= 0x01;
1974        fs::write(&path, &bytes).unwrap();
1975        backdate();
1976        assert!(
1977            open_table(&path).is_ok(),
1978            "a settled file was re-checksummed; the cache is not doing anything"
1979        );
1980
1981        // The same corruption on a file whose mtime moved is caught, and that
1982        // is every real one: a writer that changes a byte changes the mtime,
1983        // and nothing in this tree rewrites a published block at all.
1984        fs::write(&path, &bytes).unwrap();
1985        assert!(
1986            matches!(open_table(&path), Err(Error::BadChecksum { .. })),
1987            "a corrupt body with a fresh mtime must still be caught"
1988        );
1989        let _ = fs::remove_dir_all(&d);
1990    }
1991
1992    /// A restore is a *replacement*, and neither the length nor the mtime can
1993    /// see one. See [`FileId`]: `std::fs::copy` on APFS preserves the source's
1994    /// mtime to the nanosecond, as do `cp -p`, `rsync -a` and every backup
1995    /// agent, so a block restored from a copy of itself arrives at a verified
1996    /// path wearing a verified length and a verified mtime while carrying bytes
1997    /// this process has never hashed. Only the inode is different, which is why
1998    /// the inode is in the key.
1999    ///
2000    /// Driven through a rename rather than a `copy`, because that is both what a
2001    /// careful restore does — write beside the target, then rename, the same
2002    /// trick [`publish`] uses — and the only way to hold the mtime fixed while
2003    /// the inode moves.
2004    #[test]
2005    fn a_block_replaced_under_a_verified_path_is_checksummed_again() {
2006        let d = dir("verifyrestore");
2007        let path = d.join("logs.arrow");
2008        let want = batch();
2009        write_table(&path, &want).unwrap();
2010
2011        let old = SystemTime::now() - std::time::Duration::from_secs(3600);
2012        let backdate = |p: &Path| {
2013            File::options()
2014                .write(true)
2015                .open(p)
2016                .unwrap()
2017                .set_times(fs::FileTimes::new().set_modified(old))
2018                .unwrap();
2019        };
2020        backdate(&path);
2021        assert_eq!(open_table(&path).unwrap().batches, vec![want]);
2022        let verified = fs::metadata(&path).unwrap();
2023
2024        // The restore: same bytes but for one flipped bit, so the same length,
2025        // and the archived mtime put back exactly as `fs::copy` would have.
2026        let mut bytes = fs::read(&path).unwrap();
2027        let mid = crc_field(&bytes).1 / 2;
2028        bytes[mid] ^= 0x01;
2029        let staged = d.join("logs.arrow.restored");
2030        fs::write(&staged, &bytes).unwrap();
2031        backdate(&staged);
2032        fs::rename(&staged, &path).unwrap();
2033
2034        let restored = fs::metadata(&path).unwrap();
2035        assert_eq!(restored.len(), verified.len());
2036        assert_eq!(restored.modified().unwrap(), verified.modified().unwrap());
2037        assert_ne!(
2038            restored.ino(),
2039            verified.ino(),
2040            "the rename did not replace the file, so this proves nothing"
2041        );
2042
2043        assert!(
2044            matches!(open_table(&path), Err(Error::BadChecksum { .. })),
2045            "a replaced block wearing the mtime of the one it replaced was \
2046             served from the cache without being checksummed"
2047        );
2048        let _ = fs::remove_dir_all(&d);
2049    }
2050
2051    /// The corruption a CRC over `[0, body_len)` could never have caught, driven
2052    /// directly rather than waited for: a footer that parses cleanly and names a
2053    /// *wider* type than the body holds.
2054    ///
2055    /// `Utf8` and `LargeUtf8` are both empty flatbuffer tables, so a footer
2056    /// naming one and a footer naming the other differ in exactly one byte — the
2057    /// union tag — which is why this is reachable by a single bit flip and why it
2058    /// can be constructed by patching one. What it asks for is a buffer of 4-byte
2059    /// offsets read as 8-byte offsets: with the schema taken from the footer and
2060    /// `with_skip_validation(true)` below, the last offset is read off the end of
2061    /// the mapping. Undefined behaviour, not `Error::BadChecksum`.
2062    ///
2063    /// The assertion is the strong one — the read returns the *right* data, not
2064    /// merely an error — because the schema now comes from the checksummed copy
2065    /// at the head of the body and the footer's copy is read by nobody.
2066    #[test]
2067    fn a_footer_schema_naming_a_wider_type_is_not_the_one_the_read_uses() {
2068        let d = dir("widen");
2069        let path = d.join("logs.arrow");
2070        let want = batch();
2071        write_table(&path, &want).unwrap();
2072
2073        let good = fs::read(&path).unwrap();
2074        let (start, end) = (footer_start(&good), good.len() - 10);
2075        // Raw flatbuffer accessors, not `fb_to_schema`: that one is a `todo!()`
2076        // on a type tag it does not know, so the probe for "did this patch land
2077        // on the tag" would itself panic on every patch that landed elsewhere.
2078        // Which is its own argument for keeping the footer schema out of the
2079        // read path — but here it is only in the way.
2080        let body_tag = |bytes: &[u8]| -> Option<u8> {
2081            let fields = root_as_footer(&bytes[start..end])
2082                .ok()?
2083                .schema()?
2084                .fields()?;
2085            let body = (fields.len() == 2).then(|| fields.get(1))?;
2086            (body.name() == Some("body")).then(|| body.type_type().0)
2087        };
2088        assert_eq!(body_tag(&good), Some(arrow_ipc::Type::Utf8.0));
2089
2090        let mut widened = 0;
2091        for i in start..end {
2092            let mut bytes = good.clone();
2093            bytes[i] = arrow_ipc::Type::LargeUtf8.0;
2094            if body_tag(&bytes) != Some(arrow_ipc::Type::LargeUtf8.0) {
2095                continue;
2096            }
2097            widened += 1;
2098            fs::write(&path, &bytes).unwrap();
2099            let t = open_table(&path).expect("a widened footer schema is not read at all");
2100            assert_eq!(t.batches, vec![want.clone()], "byte {i} widened the read");
2101        }
2102        assert!(widened > 0, "the footer schema could not be widened");
2103        let _ = fs::remove_dir_all(&d);
2104    }
2105
2106    /// The chain [`open_table`] walks instead of reading the footer, and the
2107    /// bounds every link in it is held to. Driven directly, because a body that
2108    /// declares a length running off the end of itself is not something a bit
2109    /// flip reaches often and it is the case that reads arbitrary memory.
2110    #[test]
2111    fn a_message_that_does_not_fit_the_checked_body_is_refused() {
2112        let d = dir("extent");
2113        let path = d.join("logs.arrow");
2114        write_table(&path, &batch()).unwrap();
2115        let bytes = fs::read(&path).unwrap();
2116        // What the CRC covers: everything up to the end-of-stream marker that
2117        // `finish()` writes just before the footer.
2118        let covered = footer_start(&bytes) - 8;
2119        let buffer = Buffer::from_vec(bytes);
2120
2121        // The schema message, which every Arrow file has at the same place, and
2122        // then the record batch its stride leads to.
2123        let schema = message_at(&path, &buffer, HEADER_LEN, covered).unwrap();
2124        assert_eq!(schema.header, arrow_ipc::MessageHeader::Schema);
2125        assert_eq!(schema.block.metaDataLength() % ALIGNMENT as i32, 0);
2126        assert_eq!(schema.block.bodyLength(), 0);
2127
2128        let at = HEADER_LEN + schema.stride();
2129        let rb = message_at(&path, &buffer, at, covered).unwrap();
2130        assert_eq!(rb.header, arrow_ipc::MessageHeader::RecordBatch);
2131        assert_eq!(rb.data.len(), rb.stride());
2132        // The property the walk rests on: the chain lands exactly on the end of
2133        // the checksummed region. If it did not, the loop would either stop
2134        // short of a batch or read one out of the uncovered tail.
2135        assert_eq!(
2136            at + rb.stride(),
2137            covered,
2138            "the chain does not end at the CRC"
2139        );
2140
2141        let bad = |offset: usize, body_len: usize| {
2142            let Err(e) = message_at(&path, &buffer, offset, body_len) else {
2143                panic!("offset {offset} framed a message inside {body_len} covered bytes")
2144            };
2145            assert!(
2146                matches!(&e, Error::Io { source, .. }
2147                    if source.kind() == io::ErrorKind::InvalidData),
2148                "{e}"
2149            );
2150        };
2151        bad(covered, covered); // at the end
2152        bad(usize::MAX, covered); // and far past it, without wrapping
2153        bad(HEADER_LEN + 1, covered); // no framing there
2154        bad(HEADER_LEN, HEADER_LEN + 8); // metadata past the checksum
2155        bad(at, at + rb.block.metaDataLength() as usize); // body past the checksum
2156        let _ = fs::remove_dir_all(&d);
2157    }
2158
2159    /// A version this binary does not understand has to be an error with a name
2160    /// on it. The alternative is the silent one: a block whose columns moved,
2161    /// read positionally, answers a query with the wrong column.
2162    #[test]
2163    fn a_newer_format_version_is_refused_and_an_older_one_is_not() {
2164        let path = Path::new("logs.arrow");
2165        // Written before the key existed. Byte-identical to version 1, so
2166        // refusing it would orphan every block on disk at upgrade time.
2167        check_format(path, None).unwrap();
2168        check_format(path, Some("1")).unwrap();
2169
2170        let e = check_format(path, Some("2")).unwrap_err();
2171        assert!(
2172            matches!(&e, Error::Io { source, .. }
2173                if source.kind() == io::ErrorKind::Unsupported),
2174            "{e}"
2175        );
2176        let e = check_format(path, Some("banana")).unwrap_err();
2177        assert!(
2178            matches!(&e, Error::Io { source, .. }
2179                if source.kind() == io::ErrorKind::InvalidData),
2180            "{e}"
2181        );
2182    }
2183
2184    /// A version is only worth stamping if somebody bumps it, and nothing in
2185    /// `schema.rs` — where the change that needs the bump gets made — says so.
2186    /// The readers that make it matter are somewhere else again: `attrs.rs`,
2187    /// `query.rs` and `series.rs` reach into the attribute tables by column
2188    /// *position* (`column(3)` is the `str` value), so inserting a field into
2189    /// [`crate::schema::ATTRS`] does not fail against the blocks already on
2190    /// disk — it reinterprets them, and a query answers with a different
2191    /// column's data and no error anywhere.
2192    ///
2193    /// So the rule is a test rather than a sentence in a doc comment three
2194    /// files away. Only `ATTRS` is pinned: the root tables are read through
2195    /// `column_by_name`, which is exactly why `LogRecord.event_name` could be
2196    /// added without rewriting a block, and pinning those here would be a
2197    /// tripwire on the wrong wire.
2198    #[test]
2199    fn the_positionally_read_columns_are_pinned_to_the_format_version() {
2200        let names: Vec<&str> = crate::schema::ATTRS
2201            .fields()
2202            .iter()
2203            .map(|f| f.name().as_str())
2204            .collect();
2205        assert_eq!(
2206            names,
2207            [
2208                "parent_id",
2209                "key",
2210                "type",
2211                "str",
2212                "int",
2213                "double",
2214                "bool",
2215                "bytes",
2216                "ser"
2217            ],
2218            "the attribute table's column order changed, and three readers take \
2219             those columns by index — so every block already written now decodes \
2220             with the wrong ones. Bump FORMAT_VERSION (currently {FORMAT_VERSION}), \
2221             put the compatibility branch for the old layout next to `check_format`, \
2222             and update this list."
2223        );
2224    }
2225
2226    /// The trim drops the tail and only the tail, so the positions the pin test
2227    /// above guards stay where the readers index them.
2228    ///
2229    /// The three cases are the three that matter: a block of ordinary string
2230    /// attributes gives up both `Binary` columns, one `ser` value anywhere in
2231    /// the block keeps *both* — because `bytes` is no longer trailing — and a
2232    /// table that is not an attribute table is never touched however null its
2233    /// last column is.
2234    #[test]
2235    fn the_trim_takes_the_null_tail_and_never_a_column_a_reader_indexes() {
2236        use crate::attrs::AttrsBuilder;
2237        use mira_proto::common::v1::{AnyValue, any_value::Value};
2238
2239        let built = |vals: &[Option<Value>]| {
2240            let mut b = AttrsBuilder::new("log_attrs.key");
2241            for (i, v) in vals.iter().enumerate() {
2242                let v = v.clone().map(|value| AnyValue { value: Some(value) });
2243                b.append(i as u32, "k", v.as_ref()).expect("append");
2244            }
2245            b.finish().expect("finish")
2246        };
2247
2248        // Strings and an int. `double`, `bool`, `bytes` and `ser` are all null,
2249        // but the trim stops at seven: `AttrPred::new` reads columns 3 to 6
2250        // before it looks at a type byte, so taking `double` and `bool` here
2251        // would be a panic in a scan thread rather than a null.
2252        let plain = built(&[
2253            Some(Value::StringValue("a".into())),
2254            Some(Value::IntValue(1)),
2255        ]);
2256        let got = trim_attr_tail(&plain).expect("trim");
2257        assert_eq!(
2258            got.num_columns(),
2259            ATTR_UNGUARDED_COLS,
2260            "bytes and ser are dead here, and they are the only two that may go"
2261        );
2262        for i in 0..got.num_columns() {
2263            assert_eq!(
2264                got.schema().field(i).name(),
2265                plain.schema().field(i).name(),
2266                "column {i} moved"
2267            );
2268            assert_eq!(got.column(i), plain.column(i), "column {i} changed");
2269        }
2270
2271        // One serialized value and the tail is one column long, so `bytes`
2272        // survives on position rather than on content.
2273        let nested = built(&[
2274            Some(Value::StringValue("a".into())),
2275            Some(Value::ArrayValue(Default::default())),
2276        ]);
2277        assert_eq!(
2278            trim_attr_tail(&nested).expect("trim").num_columns(),
2279            9,
2280            "`ser` is live, so `bytes` may not be dropped out from under it"
2281        );
2282
2283        // Some other table, entirely null in its last column, keeps it.
2284        let other = RecordBatch::try_new(
2285            Arc::new(Schema::new(vec![
2286                Field::new("id", DataType::UInt32, false),
2287                Field::new("body", DataType::Utf8, true),
2288            ])),
2289            vec![
2290                Arc::new(UInt32Array::from(vec![1, 2])),
2291                Arc::new(StringArray::from(vec![None as Option<&str>, None])),
2292            ],
2293        )
2294        .unwrap();
2295        assert_eq!(
2296            trim_attr_tail(&other).expect("trim").num_columns(),
2297            2,
2298            "only the attribute table is trimmed — another table's trailing \
2299             column may carry meaning this cannot see"
2300        );
2301    }
2302
2303    /// And the version actually reaches the disk, next to the CRC. Every table
2304    /// is written by [`write_table_with`], so one of them is all of them.
2305    #[test]
2306    fn a_written_table_carries_its_format_version() {
2307        let d = dir("version");
2308        let path = d.join("logs.arrow");
2309        write_table(&path, &batch()).unwrap();
2310
2311        let bytes = fs::read(&path).unwrap();
2312        let footer = root_as_footer(&bytes[footer_start(&bytes)..bytes.len() - 10]).unwrap();
2313        let stamped = footer
2314            .custom_metadata()
2315            .unwrap()
2316            .iter()
2317            .find(|kv| kv.key() == Some(FORMAT_KEY))
2318            .and_then(|kv| kv.value().map(str::to_string));
2319        assert_eq!(
2320            stamped.as_deref(),
2321            Some(FORMAT_VERSION.to_string().as_str())
2322        );
2323        assert!(open_table(&path).is_ok());
2324        let _ = fs::remove_dir_all(&d);
2325    }
2326
2327    /// A publish that fails after staging must take its staging directory with
2328    /// it. `expire` only ever scans `<root>/<signal>`, so anything left under
2329    /// `.tmp` is invisible to retention until the next boot sweep — and the
2330    /// flusher retries this every couple of seconds, which is what turns one
2331    /// full disk into a thousand leaked directories an hour.
2332    #[test]
2333    fn a_failed_publish_leaves_no_staging_directory() {
2334        let root = dir("leak");
2335        // A file where the signal directory goes, so `create_dir_all` on the
2336        // partition fails with the staging directory already written.
2337        fs::write(root.join("logs"), b"not a directory").unwrap();
2338
2339        assert!(publish(&root, "logs", node_id("a"), 0, 0, &sealed(1_000, 2_000)).is_err());
2340
2341        let staged: Vec<_> = fs::read_dir(root.join(".tmp"))
2342            .unwrap()
2343            .map(|e| e.unwrap().path())
2344            .collect();
2345        assert!(staged.is_empty(), "leaked {staged:?}");
2346        let _ = fs::remove_dir_all(&root);
2347    }
2348
2349    /// Two replicas share a volume, and the quiet one must not be handed the
2350    /// busy one's progress.
2351    ///
2352    /// Sequences are per-log, so the busy replica's 1000 says nothing about the
2353    /// quiet one's 5. Taking the maximum over both would drop frames 5..1000 on
2354    /// the quiet replica's next boot — [`crate::wal::Wal::replay`] skips every
2355    /// frame below the watermark — and then unlink the segments holding them,
2356    /// because `wal_sweep` truncates to the same number.
2357    #[test]
2358    fn a_watermark_covers_only_the_replica_that_wrote_the_blocks() {
2359        let root = dir("wm-per-node");
2360        let busy = node_id("busy");
2361        let quiet = node_id("quiet");
2362        publish(&root, "logs", busy, 0, 1_000, &sealed(1_000, 2_000)).unwrap();
2363        publish(&root, "logs", quiet, 0, 5, &sealed(3_000, 4_000)).unwrap();
2364
2365        assert_eq!(wal_watermarks(&root, quiet).unwrap()[0], 5);
2366        assert_eq!(wal_watermarks(&root, busy).unwrap()[0], 1_000);
2367        // A replica with no blocks of its own here replays its whole log, even
2368        // standing on a volume full of someone else's.
2369        assert_eq!(wal_watermarks(&root, node_id("new")).unwrap()[0], 0);
2370        let _ = fs::remove_dir_all(&root);
2371    }
2372
2373    /// A block directory written before the write-ahead log existed has four
2374    /// fields, not five, and it is still a block. There is no manifest to
2375    /// migrate and no version to bump, so the only place backward compatibility
2376    /// can live is here — and reading a legacy name as `wal_hi = 0` is not just
2377    /// lenient, it is the correct answer: nothing published by a Mira without a
2378    /// log covers any log sequence.
2379    #[test]
2380    fn a_block_name_from_before_the_log_parses_with_no_watermark() {
2381        let legacy = format!("{:020}-{:020}-{:08x}-{:012}", 10, 20, 0xabu32, 7u64);
2382        assert_eq!(parse_dir_name(&legacy), Some((10, 20, 0xab, 7, 0)));
2383        assert_eq!(
2384            parse_dir_name(&dir_name(10, 20, 0xab, 7, 99)),
2385            Some((10, 20, 0xab, 7, 99))
2386        );
2387        // A sixth field is not a name from the future to be read hopefully. The
2388        // format is positional, so guessing at one more would mean guessing at
2389        // what it means.
2390        assert_eq!(parse_dir_name(&format!("{legacy}-1-2")), None);
2391    }
2392
2393    /// The watermark is the maximum over a signal's blocks, never the last one
2394    /// listed. `scan` sorts by `(min_ts, seq)`, so a block covering an older
2395    /// hour can be published after a newer one — a backlog replay does exactly
2396    /// that — and taking the last would hand replay a watermark below what is
2397    /// already on disk.
2398    #[test]
2399    fn the_watermark_is_the_highest_per_signal_not_the_newest() {
2400        let root = dir("watermark");
2401        let node = node_id("a");
2402        assert_eq!(wal_watermarks(&root, node).unwrap(), [0, 0, 0]);
2403
2404        // Published second, timestamped first: `scan` puts this one at the
2405        // front, and its watermark is the low one.
2406        publish(&root, "logs", node, 0, 40, &sealed(5_000, 6_000)).unwrap();
2407        publish(&root, "logs", node, 1, 9, &sealed(1_000, 2_000)).unwrap();
2408        publish(&root, "traces", node, 0, 3, &sealed(1_000, 2_000)).unwrap();
2409
2410        // Indexed by `wal::Signal`: logs, traces, metrics.
2411        assert_eq!(wal_watermarks(&root, node).unwrap(), [40, 3, 0]);
2412        let _ = fs::remove_dir_all(&root);
2413    }
2414
2415    /// One block that cannot be read used to end the sweep for the whole
2416    /// signal: every block behind the broken one stayed uncompressed for ever,
2417    /// and the same early return in `expire` stopped reclaiming space.
2418    #[test]
2419    fn one_unreadable_block_does_not_stop_the_sweep() {
2420        let root = dir("badblock");
2421        let node = node_id("a");
2422        let bad = publish(&root, "logs", node, 0, 0, &sealed(1_000, 2_000))
2423            .unwrap()
2424            .dir;
2425        let good = publish(&root, "logs", node, 1, 0, &sealed(3_000, 4_000))
2426            .unwrap()
2427            .dir;
2428        // Not an Arrow file at all, which is what a table truncated by a full
2429        // disk looks like from here.
2430        fs::write(bad.join("logs.arrow"), b"junk").unwrap();
2431
2432        assert_eq!(compact(&root, "logs", node, i64::MAX).unwrap(), 1);
2433        assert!(good.join(COLD_MARKER).exists());
2434        assert!(!bad.join(COLD_MARKER).exists(), "declared cold unread");
2435        // The invariant the skip must not break: a block that cannot be
2436        // compacted is still a block retention can take, because expiry never
2437        // opens a file.
2438        assert_eq!(expire(&root, "logs", i64::MAX).unwrap(), 2);
2439        assert!(scan(&root, "logs").unwrap().is_empty());
2440        let _ = fs::remove_dir_all(&root);
2441    }
2442
2443    /// The same for a block that cannot be *deleted*: the rest of the signal
2444    /// still has to be swept, since a stuck retention is how a disk fills.
2445    #[test]
2446    fn one_undeletable_block_does_not_stop_retention() {
2447        use std::os::unix::fs::PermissionsExt;
2448
2449        let root = dir("stuck");
2450        let node = node_id("a");
2451        // Two partitions, an hour apart, so one can be locked without locking
2452        // the other.
2453        let stuck = publish(&root, "logs", node, 0, 0, &sealed(1_000, 2_000))
2454            .unwrap()
2455            .dir;
2456        let free = publish(
2457            &root,
2458            "logs",
2459            node,
2460            1,
2461            0,
2462            &sealed(2 * NANOS_PER_HOUR, 2 * NANOS_PER_HOUR + 1),
2463        )
2464        .unwrap()
2465        .dir;
2466
2467        let locked = stuck.parent().unwrap().to_path_buf();
2468        fs::set_permissions(&locked, fs::Permissions::from_mode(0o555)).unwrap();
2469        // Root ignores the mode bits, so ask the filesystem rather than assume.
2470        if fs::write(locked.join("canary"), []).is_err() {
2471            assert_eq!(expire(&root, "logs", i64::MAX).unwrap(), 1);
2472            assert!(stuck.is_dir(), "the locked block is still there");
2473            assert!(!free.exists(), "the block beside it was still dropped");
2474        }
2475        fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();
2476        let _ = fs::remove_dir_all(&root);
2477    }
2478
2479    /// A hook that fails keeps its block, and the sweep carries on.
2480    ///
2481    /// This is the ordering `--offload` is built on, stated as a test: the
2482    /// unlink is downstream of the copy, so a store that is unreachable costs
2483    /// disk rather than data. Mutation check: run the hook after
2484    /// `remove_dir_all`, or ignore its error, and the first assertion returns
2485    /// 2 instead of 1.
2486    #[test]
2487    fn a_failing_before_delete_hook_keeps_its_block() {
2488        let root = dir("hook");
2489        let node = node_id("a");
2490        let first = publish(&root, "logs", node, 0, 0, &sealed(1_000, 2_000))
2491            .unwrap()
2492            .dir;
2493        let second = publish(&root, "logs", node, 1, 0, &sealed(3_000, 4_000))
2494            .unwrap()
2495            .dir;
2496
2497        let seen = std::cell::RefCell::new(Vec::new());
2498        let dropped = expire_with(&root, "logs", i64::MAX, &|b| {
2499            seen.borrow_mut().push(b.seq);
2500            match b.seq {
2501                0 => Err(Error::OffloadScheme {
2502                    uri: "file://nowhere".into(),
2503                }),
2504                _ => Ok(()),
2505            }
2506        })
2507        .unwrap();
2508
2509        assert_eq!(dropped, 1);
2510        assert_eq!(*seen.borrow(), vec![0, 1], "every block was offered");
2511        assert!(first.is_dir(), "the block whose copy failed is still here");
2512        assert!(!second.exists(), "the one beside it went");
2513        // And the next sweep retries it, which is the other half of "two
2514        // copies, never zero": a failure is a delay, not a leak.
2515        assert_eq!(
2516            expire_with(&root, "logs", i64::MAX, &|_| Ok(())).unwrap(),
2517            1
2518        );
2519        assert!(scan(&root, "logs").unwrap().is_empty());
2520        let _ = fs::remove_dir_all(&root);
2521    }
2522
2523    /// Free space, for the ingest side to back off on. Only the shape can be
2524    /// asserted here — the number belongs to whatever volume the test runs on.
2525    #[test]
2526    fn free_fraction_is_a_fraction_of_a_real_mount() {
2527        let d = dir("free");
2528        let f = free_fraction(&d).unwrap();
2529        assert!(f > 0.0 && f <= 1.0, "{f} is not a fraction");
2530        // The temp dir and a file on it are the same mount.
2531        let path = d.join("logs.arrow");
2532        write_table(&path, &batch()).unwrap();
2533        assert!((free_fraction(&path).unwrap() - f).abs() < 0.01);
2534        // A path that is not there is an error, not a zero: "no space" and "no
2535        // such directory" are different operational answers.
2536        assert!(free_fraction(&d.join("nope")).is_err());
2537        let _ = fs::remove_dir_all(&d);
2538    }
2539
2540    /// The bytes half, which is the term that decides whether a volume with a
2541    /// low fraction is actually in trouble. Both halves come off one `statfs`,
2542    /// so they have to describe the same mount at the same instant.
2543    #[test]
2544    fn free_reports_bytes_beside_the_fraction() {
2545        let d = dir("freebytes");
2546        let (f, bytes) = free(&d).unwrap();
2547        // Two `statfs` calls, so not the same instant: a volume with anything
2548        // else running on it moves between them, and asserting exact equality
2549        // here fails on a busy laptop rather than on a real divergence.
2550        let drift = (f - free_fraction(&d).unwrap()).abs();
2551        assert!(drift < 0.01, "the same fraction, give or take {drift}");
2552        // A temp dir on a mount with no room at all is not a machine that can
2553        // run this suite, so a positive count is safe to assert.
2554        assert!(bytes > 0, "a real mount has some bytes free");
2555        // The two agree on scale: bytes / fraction is the volume, which has to
2556        // be at least as large as what is free on it.
2557        assert!(
2558            (bytes as f64 / f) >= bytes as f64,
2559            "{bytes} bytes at {f} free implies a volume smaller than its free space"
2560        );
2561        let _ = fs::remove_dir_all(&d);
2562    }
2563
2564    /// A path is bytes, not a string, and `statfs` takes a C string. An
2565    /// interior NUL would otherwise be truncated by the conversion and the
2566    /// answer would be about a *different* directory — the one whose name is
2567    /// the prefix — which is worse than a refusal because nothing about it
2568    /// looks wrong.
2569    #[test]
2570    fn a_path_with_a_nul_byte_is_refused_rather_than_truncated() {
2571        use std::os::unix::ffi::OsStrExt;
2572
2573        let d = dir("nul");
2574        let mut raw = d.as_os_str().as_encoded_bytes().to_vec();
2575        raw.extend_from_slice(b"\0suffix");
2576        let nul = PathBuf::from(std::ffi::OsStr::from_bytes(&raw));
2577
2578        // The prefix is a real directory this would happily answer about.
2579        assert!(free_fraction(&d).is_ok());
2580        let Err(e) = free_fraction(&nul) else {
2581            panic!("a path with a NUL byte was measured")
2582        };
2583        assert!(
2584            matches!(&e, Error::Io { source, .. }
2585                if source.kind() == io::ErrorKind::InvalidInput),
2586            "{e}"
2587        );
2588        let _ = fs::remove_dir_all(&d);
2589    }
2590
2591    /// A pseudo-filesystem reports no blocks at all. Dividing by that is a NaN
2592    /// the ingest side would read as "not above the threshold" — or a 0% free
2593    /// that stops ingest on a node with nothing wrong with it — so a mount that
2594    /// cannot fill up answers "empty".
2595    ///
2596    /// Conditional on finding one, like
2597    /// [`one_undeletable_block_does_not_stop_retention`] is conditional on not
2598    /// being root: `/proc` is Linux's, `/System/Volumes/Data/home` is the
2599    /// autofs trigger macOS mounts by default, and a host with neither has
2600    /// nothing to assert this over.
2601    #[test]
2602    fn a_mount_that_reports_no_blocks_is_empty_not_full() {
2603        let pseudo = ["/proc", "/sys", "/System/Volumes/Data/home"]
2604            .into_iter()
2605            .map(Path::new)
2606            .find(|p| statfs(p).is_ok_and(|b| b.f_blocks == 0));
2607        if let Some(p) = pseudo {
2608            assert_eq!(free_fraction(p).unwrap(), 1.0, "{}", p.display());
2609        }
2610    }
2611
2612    /// The rule [`check_filesystem`] applies, stated over the three answers
2613    /// [`fs_type`] can give. FUSE has to stay a warning — the magic number is
2614    /// the same for `gcsfuse`, which is as fatal as NFS, and for a local
2615    /// userspace filesystem, which is fine — and everything else it names has
2616    /// to be fatal, because `SIGBUS` under a mapping is not an error any Rust
2617    /// can catch.
2618    #[test]
2619    fn a_network_filesystem_refuses_to_start_and_fuse_only_warns() {
2620        let path = Path::new("/data");
2621        check_fs_type(path, None).unwrap();
2622        check_fs_type(path, Some("fuse".into())).unwrap();
2623
2624        let e = check_fs_type(path, Some("NFS".into())).unwrap_err();
2625        assert!(
2626            matches!(&e, Error::NetworkFilesystem { fs, .. } if fs == "NFS"),
2627            "{e}"
2628        );
2629        // The operator has to be told which mount type, or the message is a
2630        // refusal with no next step in it.
2631        assert!(e.to_string().contains("NFS"), "{e}");
2632    }
2633
2634    /// The other half of that rule: that the mounts it is stated over are the
2635    /// ones [`remote_fs`] actually names.
2636    #[cfg(target_os = "macos")]
2637    #[test]
2638    fn every_mount_the_check_refuses_is_one_the_table_names() {
2639        for name in ["nfs", "smbfs", "cifs", "webdav", "afpfs", "ftp"] {
2640            assert_eq!(remote_fs(name).as_deref(), Some(name));
2641        }
2642        // The FUSE spelling is the implementation's, and there are several of
2643        // them — `macfuse`, `osxfuse`, `fuse-t`. All collapse to the one word
2644        // the warning is written about.
2645        assert_eq!(remote_fs("macfuse").as_deref(), Some("fuse"));
2646        assert_eq!(remote_fs("apfs"), None);
2647    }
2648
2649    /// The other half of that rule: that the mounts it is stated over are the
2650    /// ones [`remote_fs`] actually names.
2651    ///
2652    /// Nothing that runs the tests is mounted on any of them, so the only arm a
2653    /// live `statfs` reaches is the fallthrough and the eleven above it are
2654    /// worth exactly what this test is worth. A transposed digit in a magic is
2655    /// a `SIGBUS` on somebody's NFS mount and a green build here.
2656    #[cfg(not(target_os = "macos"))]
2657    #[test]
2658    fn every_mount_the_check_refuses_is_one_the_table_names() {
2659        for (magic, want) in [
2660            (0x6969_u64, "NFS"),
2661            (0x517b, "SMB"),
2662            (0xff53_4d42, "CIFS"),
2663            (0xfe53_4d42, "SMB2"),
2664            (0x0102_1997, "9P"),
2665            (0x5346_414f, "AFS"),
2666            (0x00c3_6400, "CephFS"),
2667            (0x0116_1970, "GFS2"),
2668            (0x7461_636f, "OCFS2"),
2669            (0x0bd0_0bd0, "Lustre"),
2670            (0x6573_5546, "fuse"),
2671        ] {
2672            assert_eq!(remote_fs(magic).as_deref(), Some(want), "{magic:#x}");
2673        }
2674        // ext4 and overlayfs: the runner, the container and every deployment
2675        // this check is supposed to stay out of the way of.
2676        assert_eq!(remote_fs(0xef53), None);
2677        assert_eq!(remote_fs(0x794c_7630), None);
2678    }
2679
2680    /// A cleanup that cannot run is not the failure the caller has to act on.
2681    /// Returning it would replace "the disk is full" with "could not remove a
2682    /// temporary directory", and the second is the one nobody can fix.
2683    #[test]
2684    fn a_staging_directory_that_cannot_be_removed_is_logged_not_returned() {
2685        use std::os::unix::fs::PermissionsExt;
2686
2687        let root = dir("unwind");
2688        let tmp = root.join("logs-0000002a-000000000000-0-0");
2689        fs::create_dir(&tmp).unwrap();
2690        fs::write(tmp.join("logs.arrow"), b"a staged table").unwrap();
2691
2692        fs::set_permissions(&root, fs::Permissions::from_mode(0o555)).unwrap();
2693        // Root ignores the mode bits, so ask the filesystem rather than assume.
2694        if fs::create_dir(root.join("canary")).is_err() {
2695            unwind_staging(&tmp);
2696            assert!(tmp.is_dir(), "the undeletable staging directory went away");
2697        }
2698        fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).unwrap();
2699
2700        unwind_staging(&tmp);
2701        assert!(!tmp.exists(), "the deletable one did not");
2702        // And the ordinary shape of "the rename succeeded and a later fsync did
2703        // not": nothing left to remove, nothing to say about it.
2704        unwind_staging(&tmp);
2705        let _ = fs::remove_dir_all(&root);
2706    }
2707
2708    /// `publish` skips a zero-row table, and this is the same rule one level
2709    /// down. Writing the file anyway would put a header-and-footer-only Arrow
2710    /// file in the block for every table a signal does not use — which the
2711    /// reader would then open, map and CRC on every scan.
2712    #[test]
2713    fn a_table_with_no_batches_writes_no_file() {
2714        let d = dir("nobatch");
2715        let path = d.join("logs.arrow");
2716        write_table_with(&path, &[], None).unwrap();
2717        assert!(!path.exists(), "an empty table left a file behind");
2718        // Which is the same thing the reader sees for a table that was never
2719        // written, and it is not an error.
2720        assert!(open_table_opt(&path).unwrap().is_none());
2721        let _ = fs::remove_dir_all(&d);
2722    }
2723
2724    /// Neither constructor can build this — [`Src::disk`] always has a
2725    /// directory and [`Src::open`] always has tables — so the arm is here for
2726    /// the day a third one does. It answers "no rows", which is the answer
2727    /// every other missing table gets, rather than unwrapping something that is
2728    /// not there.
2729    #[test]
2730    fn a_source_with_neither_a_directory_nor_tables_reads_as_empty() {
2731        let src = Src {
2732            node: 0,
2733            seq: 0,
2734            min_ts: 0,
2735            max_ts: 1,
2736            dir: None,
2737            tables: None,
2738        };
2739        assert!(src.load("logs").unwrap().is_none());
2740        assert!(src.overlaps(0, 1));
2741    }
2742
2743    /// The sweep is capped so the first pass over an existing volume does not
2744    /// saturate the disk, and the cap counts *attempts*: a directory full of
2745    /// unreadable blocks must not re-read every one of them on every sweep for
2746    /// ever. What the cap must not do is lose blocks — the ones it did not
2747    /// reach are still there for the next pass.
2748    #[test]
2749    fn a_sweep_compacts_at_most_its_budget_and_the_next_one_finishes() {
2750        let root = dir("budget");
2751        let node = node_id("a");
2752        let blocks = MAX_COMPACT_PER_SWEEP + 1;
2753        for seq in 0..blocks as u64 {
2754            publish(&root, "logs", node, seq, 0, &sealed(1_000, 2_000)).unwrap();
2755        }
2756
2757        assert_eq!(
2758            compact(&root, "logs", node, i64::MAX).unwrap(),
2759            MAX_COMPACT_PER_SWEEP
2760        );
2761        let cold = |root: &Path| {
2762            scan(root, "logs")
2763                .unwrap()
2764                .iter()
2765                .filter(|b| b.dir.join(COLD_MARKER).exists())
2766                .count()
2767        };
2768        assert_eq!(cold(&root), MAX_COMPACT_PER_SWEEP);
2769
2770        // The next sweep skips the eight already marked and takes the ninth.
2771        assert_eq!(compact(&root, "logs", node, i64::MAX).unwrap(), 1);
2772        assert_eq!(cold(&root), blocks);
2773        // And a third has nothing left to do, which is what the marker is for.
2774        assert_eq!(compact(&root, "logs", node, i64::MAX).unwrap(), 0);
2775        let _ = fs::remove_dir_all(&root);
2776    }
2777
2778    /// Retention on this node or another replica can unlink a block between the
2779    /// `scan` that listed it and the rewrite that would have compacted it.
2780    /// Racing to delete an immutable block is not a conflict, so it must not be
2781    /// logged as a failure — and the sweep has to carry on to the blocks
2782    /// behind it.
2783    ///
2784    /// A block directory that is a dangling symlink stands in for the race: it
2785    /// is what `scan` sees for a name whose directory is no longer there, which
2786    /// is precisely the state the race leaves behind.
2787    #[test]
2788    fn a_block_that_vanished_mid_sweep_is_not_a_failure() {
2789        let root = dir("vanished");
2790        let node = node_id("a");
2791        let good = publish(&root, "logs", node, 0, 0, &sealed(1_000, 2_000))
2792            .unwrap()
2793            .dir;
2794        let gone = good
2795            .parent()
2796            .unwrap()
2797            .join(dir_name(1_000, 2_000, node, 99, 0));
2798        std::os::unix::fs::symlink(root.join("no-such-block"), &gone).unwrap();
2799        assert_eq!(scan(&root, "logs").unwrap().len(), 2);
2800        // Pinned to the exact error the sweep swallows. Anything else would
2801        // take the warning arm instead, which is the same visible outcome and
2802        // the wrong one: a routine race logged as a block that cannot be
2803        // compacted is a false alarm on every retention pass.
2804        assert!(
2805            matches!(compact_block(&gone, node), Err(Error::Io { source, .. })
2806                if source.kind() == io::ErrorKind::NotFound),
2807        );
2808
2809        assert_eq!(compact(&root, "logs", node, i64::MAX).unwrap(), 1);
2810        assert!(good.join(COLD_MARKER).exists(), "the block beside it");
2811        assert!(!gone.join(COLD_MARKER).exists(), "declared cold unread");
2812        let _ = fs::remove_dir_all(&root);
2813    }
2814
2815    /// The 8-byte encapsulation prefix carries a *signed* metadata length read
2816    /// straight off the disk. Negative, or large enough that adding the prefix
2817    /// back overflows, has to be a named error before it reaches
2818    /// `Buffer::slice_with_length` — which panics on a range it does not like,
2819    /// and `panic = "abort"` makes that the death of every open block in the
2820    /// process.
2821    #[test]
2822    fn a_metadata_length_that_is_not_a_length_is_refused() {
2823        let d = dir("metalen");
2824        let path = d.join("logs.arrow");
2825        write_table(&path, &batch()).unwrap();
2826        let good = fs::read(&path).unwrap();
2827        let covered = crc_field(&good).1;
2828
2829        for declared in [-1i32, -8, i32::MIN, i32::MAX, i32::MAX - 7] {
2830            let mut bytes = good.clone();
2831            bytes[HEADER_LEN + 4..HEADER_LEN + 8].copy_from_slice(&declared.to_le_bytes());
2832            let buffer = Buffer::from_vec(bytes);
2833            let Err(e) = message_at(&path, &buffer, HEADER_LEN, covered) else {
2834                panic!("a metadata length of {declared} framed a message")
2835            };
2836            invalid_data(&e, &format!("metadata length {declared}"));
2837            // The diagnostic has to carry the number, or it says nothing about
2838            // which of the file's several lengths is the broken one.
2839            assert!(e.to_string().contains(&declared.to_string()), "{e}");
2840        }
2841        let _ = fs::remove_dir_all(&d);
2842    }
2843
2844    /// The reader takes the schema from the head of the *body*, so the first
2845    /// thing it has to be sure of is that the body starts with a schema at all.
2846    /// Anything else there would be handed to `try_schema_from_ipc_buffer` and
2847    /// then to a decoder built with validation off, which is the combination
2848    /// that reads off the end of the mapping rather than erroring.
2849    #[test]
2850    fn a_body_that_does_not_start_with_a_schema_is_refused() {
2851        let d = dir("noschema");
2852        let path = d.join("logs.arrow");
2853        write_table(&path, &batch()).unwrap();
2854
2855        let mut bytes = fs::read(&path).unwrap();
2856        let tag = header_tag(&bytes, HEADER_LEN);
2857        bytes[tag] = UNKNOWN_MESSAGE;
2858        repair_crc(&mut bytes);
2859        fs::write(&path, &bytes).unwrap();
2860
2861        let Err(e) = open_table(&path) else {
2862            panic!("a body with no schema at the head of it read as a block")
2863        };
2864        invalid_data(&e, "a first message that is not a schema");
2865        assert!(e.to_string().contains("not a schema message"), "{e}");
2866        let _ = fs::remove_dir_all(&d);
2867    }
2868
2869    /// And every message after it is a dictionary or a record batch. A third
2870    /// kind is not something to skip: the chain is walked by stride, so a
2871    /// message the reader does not understand is a message whose length it is
2872    /// trusting without having understood what it describes.
2873    #[test]
2874    fn a_message_after_the_schema_that_is_not_a_batch_is_refused() {
2875        let d = dir("notabatch");
2876        let path = d.join("logs.arrow");
2877        write_table(&path, &batch()).unwrap();
2878
2879        let mut bytes = fs::read(&path).unwrap();
2880        let at = second_message(&path, &bytes);
2881        let tag = header_tag(&bytes, at);
2882        bytes[tag] = UNKNOWN_MESSAGE;
2883        repair_crc(&mut bytes);
2884        fs::write(&path, &bytes).unwrap();
2885
2886        let Err(e) = open_table(&path) else {
2887            panic!("a message that is neither a dictionary nor a batch decoded")
2888        };
2889        invalid_data(&e, "a message that is not a batch");
2890        assert!(
2891            e.to_string()
2892                .contains("is not a dictionary or a record batch"),
2893            "{e}"
2894        );
2895        let _ = fs::remove_dir_all(&d);
2896    }
2897
2898    /// The cold tier's own corruption. A compressed block is the one case where
2899    /// the body is not read out of the mapping, so it is also the one case
2900    /// where a byte the checksum happens to accept lands in a decompressor
2901    /// rather than in an array — and a ZSTD frame that will not decompress has
2902    /// to be an error naming the failure, not a short buffer an array is then
2903    /// built over.
2904    #[test]
2905    fn a_zstd_frame_that_will_not_decompress_is_an_error() {
2906        let d = dir("zstd");
2907        let path = d.join("logs.arrow");
2908        let want = compressible();
2909        write_table_zstd(&path, &want).unwrap();
2910        assert_eq!(open_table(&path).unwrap().batches, vec![want]);
2911
2912        let mut bytes = fs::read(&path).unwrap();
2913        let covered = crc_field(&bytes).1;
2914        // The start of a ZSTD frame, which is what `compress_to_vec` writes
2915        // after the 8-byte uncompressed length — unless the frame came out
2916        // bigger than the plain bytes, which is why the batch above is one
2917        // that compresses.
2918        let frame = bytes[..covered]
2919            .windows(4)
2920            .position(|w| w == [0x28, 0xb5, 0x2f, 0xfd])
2921            .expect("no compressed frame in a compressed table");
2922        bytes[frame..frame + 4].copy_from_slice(&[0xff; 4]);
2923        repair_crc(&mut bytes);
2924        fs::write(&path, &bytes).unwrap();
2925
2926        let Err(e) = open_table(&path) else {
2927            panic!("a block with a broken ZSTD frame decoded")
2928        };
2929        // One variant carries every way arrow-rs can refuse a body, so the
2930        // headline has to be true of all of them and the wrapped source is
2931        // what says which one this is. Pinned as the substring rather than
2932        // the whole sentence so a zstd wording change is not a red build.
2933        assert!(matches!(&e, Error::Undecodable { .. }), "{e}");
2934        assert!(e.to_string().contains("frame"), "{e}");
2935        assert!(!e.to_string().contains("align"), "{e}");
2936        let _ = fs::remove_dir_all(&d);
2937    }
2938}