Skip to main content

znippy_common/
index.rs

1// index.rs — v0.6 format: blobs stored inline, Arrow IPC is a pure metadata index.
2//
3// File layout:
4//   [blob_0][blob_1]...[blob_N]  — compressed/raw chunk bytes, written as produced
5//   [Arrow IPC stream]           — metadata index, written after all blobs
6//   [8 bytes LE u64]             — byte offset where Arrow IPC starts (footer)
7//
8// Arrow schema columns:
9//   relative_path, chunk_seq, fdata_offset, checksum_group,
10//   compressed, uncompressed_size, blob_offset, blob_size, checksum
11
12use std::collections::HashMap;
13use std::fs::File;
14use std::io::{Read, Seek, SeekFrom};
15use std::path::{Path, PathBuf};
16use std::sync::Arc;
17
18use crate::common_config::StrategicConfig;
19use crate::meta::BlobMeta;
20use crate::plugin::ExtensionRow;
21use crate::{decompress_archive};
22use anyhow::Result;
23use arrow::array::{
24    Array, ArrayRef, BooleanBuilder, FixedSizeBinaryBuilder, Int8Builder, StringBuilder,
25    UInt32Builder, UInt64Builder,
26};
27use arrow::datatypes::{DataType, Field, Schema};
28use arrow::record_batch::RecordBatch;
29use once_cell::sync::Lazy;
30
31/// Per-file extension metadata carried into the Arrow index.
32/// (plugin_type_id, extracted fields) — None for files with no matching plugin.
33pub type FileExtMeta = Option<(i8, ExtensionRow)>;
34
35/// v0.6 schema: Arrow IPC is a pure metadata index; blobs are stored inline before it.
36/// Base index columns — present in every archive, type-agnostic.
37/// Package-type modules contribute their own columns on top via `schema_fields()`;
38/// the writer composes the on-disk schema with [`compose_index_schema`].
39pub static ZNIPPY_INDEX_SCHEMA: Lazy<Arc<Schema>> = Lazy::new(|| {
40    Arc::new(Schema::new(base_index_fields()))
41});
42
43fn base_index_fields() -> Vec<Field> {
44    vec![
45        Field::new("relative_path", DataType::Utf8, false),
46        Field::new("chunk_seq", DataType::UInt32, false),
47        Field::new("fdata_offset", DataType::UInt64, false),
48        Field::new("compressed", DataType::Boolean, false),
49        Field::new("uncompressed_size", DataType::UInt64, false),
50        Field::new("blob_offset", DataType::UInt64, false),
51        Field::new("blob_size", DataType::UInt64, false),
52        Field::new("checksum", DataType::FixedSizeBinary(32), false),
53    ]
54}
55
56pub fn znippy_index_schema() -> &'static Arc<Schema> {
57    &ZNIPPY_INDEX_SCHEMA
58}
59
60/// Compose the on-disk index schema: base columns, plus — when a module contributes columns —
61/// a `pkg_type` discriminator followed by the module's own `ext_fields`.
62/// With no module fields, this is exactly the base schema (v0.6 layout, directly DuckDB-queryable).
63pub fn compose_index_schema(ext_fields: &[Field]) -> Arc<Schema> {
64    let mut fields = base_index_fields();
65    if !ext_fields.is_empty() {
66        fields.push(Field::new("pkg_type", DataType::Int8, true));
67        fields.extend(ext_fields.iter().cloned());
68    }
69    Arc::new(Schema::new(fields))
70}
71
72/// On-disk archive format version, recorded in the Arrow index schema metadata
73/// under `znippy_format_version`. The reader refuses any archive whose recorded
74/// version is greater than this — a newer format it cannot safely parse — with a
75/// clear error instead of panicking or mis-parsing. Bump only on a real on-disk
76/// format change.
77pub const ZNIPPY_FORMAT_VERSION: u32 = 3;
78
79/// Schema-metadata key holding the on-disk [`ZNIPPY_FORMAT_VERSION`].
80pub const FORMAT_VERSION_KEY: &str = "znippy_format_version";
81
82/// Enforce that an archive's recorded format version is one this reader supports.
83/// `metadata` is an Arrow schema's key/value metadata. A *newer* version yields a
84/// clear error instead of a panic or silent mis-parse; equal/older versions — and
85/// archives with no recorded version — read exactly as before.
86pub fn check_format_version(metadata: &HashMap<String, String>) -> Result<()> {
87    if let Some(raw) = metadata.get(FORMAT_VERSION_KEY) {
88        let version: u32 = raw
89            .parse()
90            .map_err(|_| anyhow::anyhow!("invalid znippy archive format version {raw:?}"))?;
91        anyhow::ensure!(
92            version <= ZNIPPY_FORMAT_VERSION,
93            "znippy archive format v{version} is newer than this reader supports \
94             (max v{ZNIPPY_FORMAT_VERSION}) — upgrade znippy",
95        );
96    }
97    Ok(())
98}
99
100/// Build Arrow schema metadata containing config (no checksum entries — those live in column).
101pub fn build_arrow_metadata_for_config(config: &StrategicConfig) -> HashMap<String, String> {
102    let mut m = HashMap::new();
103    m.insert(FORMAT_VERSION_KEY.into(), ZNIPPY_FORMAT_VERSION.to_string());
104    m.insert("max_core_in_flight".into(), config.max_core_in_flight.to_string());
105    m.insert("max_core_in_compress".into(), config.max_core_in_compress.to_string());
106    m.insert("max_mem_allowed".into(), config.max_mem_allowed.to_string());
107    m.insert("min_free_memory_ratio".into(), config.min_free_memory_ratio.to_string());
108    m.insert("file_split_block_size".into(), config.file_split_block_size.to_string());
109    m.insert("max_chunks".into(), config.max_chunks.to_string());
110    m.insert("compression_level".into(), config.compression_level.to_string());
111    m.insert("zstd_output_buffer_size".into(), config.zstd_output_buffer_size.to_string());
112    m
113}
114
115pub fn extract_config_from_arrow_metadata(
116    metadata: &HashMap<String, String>,
117) -> anyhow::Result<StrategicConfig> {
118    Ok(StrategicConfig {
119        max_core_allowed: 0,
120        max_core_in_flight: metadata
121            .get("max_core_in_flight")
122            .ok_or_else(|| anyhow::anyhow!("Missing 'max_core_in_flight'"))?
123            .parse()?,
124        max_core_in_compress: metadata
125            .get("max_core_in_compress")
126            .ok_or_else(|| anyhow::anyhow!("Missing 'max_core_in_compress'"))?
127            .parse()?,
128        max_mem_allowed: metadata
129            .get("max_mem_allowed")
130            .ok_or_else(|| anyhow::anyhow!("Missing 'max_mem_allowed'"))?
131            .parse()?,
132        min_free_memory_ratio: metadata
133            .get("min_free_memory_ratio")
134            .ok_or_else(|| anyhow::anyhow!("Missing 'min_free_memory_ratio'"))?
135            .parse()?,
136        file_split_block_size: metadata
137            .get("file_split_block_size")
138            .ok_or_else(|| anyhow::anyhow!("Missing 'file_split_block_size'"))?
139            .parse()?,
140        max_chunks: metadata
141            .get("max_chunks")
142            .ok_or_else(|| anyhow::anyhow!("Missing 'max_chunks'"))?
143            .parse()?,
144        compression_level: metadata
145            .get("compression_level")
146            .ok_or_else(|| anyhow::anyhow!("Missing 'compression_level'"))?
147            .parse()?,
148        zstd_output_buffer_size: metadata
149            .get("zstd_output_buffer_size")
150            .ok_or_else(|| anyhow::anyhow!("Missing 'zstd_output_buffer_size'"))?
151            .parse()?,
152    })
153}
154
155/// Build the Arrow metadata index batch from blob positions.
156///
157/// Every row carries its own per-slice BLAKE3 in the `checksum` column
158/// (over the chunk's uncompressed bytes).
159pub fn build_metadata_batch<F>(
160    blobs: &[BlobMeta],
161    path_resolver: F,
162    ext_meta: &[FileExtMeta],
163    ext_fields: &[Field],
164) -> arrow::error::Result<RecordBatch>
165where
166    F: Fn(u64) -> String,
167{
168    let len = blobs.len();
169
170    let mut path_builder = StringBuilder::with_capacity(len, len * 64);
171    let mut seq_builder = UInt32Builder::with_capacity(len);
172    let mut fdata_builder = UInt64Builder::with_capacity(len);
173    let mut compressed_builder = BooleanBuilder::with_capacity(len);
174    let mut size_builder = UInt64Builder::with_capacity(len);
175    let mut blob_offset_builder = UInt64Builder::with_capacity(len);
176    let mut blob_size_builder = UInt64Builder::with_capacity(len);
177    let mut checksum_builder = FixedSizeBinaryBuilder::with_capacity(len, 32);
178
179    for blob in blobs {
180        let m = &blob.chunk_meta;
181        path_builder.append_value(path_resolver(m.file_index));
182        seq_builder.append_value(m.chunk_seq);
183        fdata_builder.append_value(m.fdata_offset);
184        compressed_builder.append_value(m.compressed);
185        size_builder.append_value(m.uncompressed_size);
186        blob_offset_builder.append_value(blob.blob_offset);
187        blob_size_builder.append_value(blob.blob_size);
188        checksum_builder.append_value(m.checksum)?;
189    }
190
191    let mut columns: Vec<ArrayRef> = vec![
192        Arc::new(path_builder.finish()),
193        Arc::new(seq_builder.finish()),
194        Arc::new(fdata_builder.finish()),
195        Arc::new(compressed_builder.finish()),
196        Arc::new(size_builder.finish()),
197        Arc::new(blob_offset_builder.finish()),
198        Arc::new(blob_size_builder.finish()),
199        Arc::new(checksum_builder.finish()),
200    ];
201
202    // Module-contributed columns: a pkg_type discriminator + one column per ext field.
203    if !ext_fields.is_empty() {
204        let mut pkg_type_builder = Int8Builder::with_capacity(len);
205        for blob in blobs {
206            match ext_meta.get(blob.chunk_meta.file_index as usize).and_then(|x| x.as_ref()) {
207                Some((type_id, _)) => pkg_type_builder.append_value(*type_id),
208                None => pkg_type_builder.append_null(),
209            }
210        }
211        columns.push(Arc::new(pkg_type_builder.finish()));
212
213        for field in ext_fields {
214            columns.push(build_ext_column(field, blobs, ext_meta));
215        }
216    }
217
218    RecordBatch::try_new(compose_index_schema(ext_fields), columns)
219}
220
221/// Build one extension column from the per-file `ExtensionRow`, keyed by the field name.
222/// Supports the Arrow types modules currently declare (Utf8, UInt32); other types yield nulls.
223fn build_ext_column(field: &Field, blobs: &[BlobMeta], ext_meta: &[FileExtMeta]) -> ArrayRef {
224    use crate::plugin::ExtensionValue;
225    let len = blobs.len();
226    let value_for = |blob: &BlobMeta| -> Option<&ExtensionValue> {
227        ext_meta
228            .get(blob.chunk_meta.file_index as usize)
229            .and_then(|x| x.as_ref())
230            .and_then(|(_, row)| row.fields.get(field.name()))
231    };
232
233    match field.data_type() {
234        DataType::UInt32 => {
235            let mut b = UInt32Builder::with_capacity(len);
236            for blob in blobs {
237                match value_for(blob) {
238                    Some(ExtensionValue::U32(n)) => b.append_value(*n),
239                    _ => b.append_null(),
240                }
241            }
242            Arc::new(b.finish())
243        }
244        // Default to Utf8 for string-like fields (Str / OptStr).
245        _ => {
246            let mut b = StringBuilder::with_capacity(len, len * 16);
247            for blob in blobs {
248                match value_for(blob) {
249                    Some(ExtensionValue::Str(s)) => b.append_value(s),
250                    Some(ExtensionValue::OptStr(Some(s))) => b.append_value(s),
251                    _ => b.append_null(),
252                }
253            }
254            Arc::new(b.finish())
255        }
256    }
257}
258
259// ─── Multi-index container codec (planned v0.7, see design.md §6) ──────────────
260//
261// A multi-type archive holds several Arrow IPC index streams (one per (pkg_type, repo)
262// sub-znippy, each with its own narrow schema), followed by a manifest stream that points
263// at them, and a footer. The footer layout still *distinguishes* the legacy v0.6 trailer
264// from the v0.7 one, but v0.6 archives are no longer readable — they are detected only to
265// emit a clear "unsupported, re-compress with v0.7" error (see `read_znippy_index_filtered`):
266//
267//   v0.6 single index:  [...index...] [8-byte LE u64 index_offset]
268//   v0.7 multi index:   [...sub-indexes...][manifest] [8-byte MAGIC] [8-byte LE u64 manifest_offset]
269//
270// A reader peeks the 8 bytes preceding the trailing offset: if they equal MAGIC it's a
271// multi-index (v0.7) archive; otherwise it's a legacy v0.6 single index, which the reader
272// rejects rather than parses.
273
274/// Magic preceding the trailing offset that marks a multi-index (v0.7) archive.
275pub const MULTI_INDEX_MAGIC: [u8; 8] = *b"ZNPYMIDX";
276
277/// One entry in the multi-index manifest: a sub-znippy's identity + byte range.
278#[derive(Debug, Clone, PartialEq)]
279pub struct ManifestEntry {
280    pub pkg_type: i8,
281    pub repo: String,
282    pub module_name: String,
283    pub index_offset: u64,
284    pub index_len: u64,
285    pub row_count: u64,
286}
287
288/// Reserved `module_name` for the sorted random-access lookup sub-index.
289/// Its rows are the base index columns re-sorted by `(relative_path, chunk_seq)`,
290/// so external tools can `SELECT … WHERE relative_path = …` in O(log n) and the
291/// native reader can binary-search it. Manifest readers filter this entry out of
292/// the data sub-index set; [`read_znippy_lookup`] reads it explicitly.
293pub const LOOKUP_MODULE: &str = "__znippy_lookup__";
294
295/// Reserved `module_name` for the fst trie blob: an `fst::Map` of
296/// `relative_path → first row index in the lookup sub-index`. Not Arrow IPC —
297/// raw fst bytes — so it must never be parsed as a sub-index.
298pub const TRIE_MODULE: &str = "__znippy_trie__";
299
300/// Reserved `module_name` for the per-artifact detached CMS signatures
301/// (feature `sign`). An Arrow IPC sub-index of `(relative_path, cms)` rows — one
302/// detached CMS `SignedData` per file, over that file's merkle-folded chunk
303/// hashes. Additive: readers that don't know it simply skip it (it is reserved),
304/// so unsigned archives are byte-identical and old readers ignore signed ones.
305pub const SIGN_ARTIFACTS_MODULE: &str = "__znippy_sign_artifacts__";
306
307/// Reserved `module_name` for the per-archive detached CMS signature (feature
308/// `sign`): raw CMS `SignedData` (DER) over the archive root digest.
309pub const SIGN_ARCHIVE_MODULE: &str = "__znippy_sign_archive__";
310
311/// Reserved `module_name` for the **searchable metadata sub-index**: typed
312/// key/value rows, per entry and per archive, sorted by `(key, relative_path)`.
313/// An Arrow IPC sub-index like the lookup — so "which entries carry key `X`" is
314/// answered by one seek to the footer plus one read of this section, at a cost
315/// set by the number of metadata rows and **not** by the payload size.
316///
317/// Reserved, therefore additive: a reader that predates it skips the entry, and
318/// an archive that predates it simply has no such entry — which
319/// [`crate::meta_index::read_archive_meta`] reports as
320/// [`ArchiveMeta::NoMetadata`](crate::meta_index::ArchiveMeta::NoMetadata),
321/// a state distinct from a present-but-empty index.
322pub const META_MODULE: &str = "__znippy_meta__";
323
324/// Reserved `module_name` for the **git oid index** written by the `git` package
325/// format (`znippy-plugin-git`): a raw (non-Arrow) `stree` payload over the first
326/// eight bytes of every object id, mapping to that object's first lookup row.
327/// Raw bytes, never an Arrow IPC stream — it must never be parsed as a sub-index.
328pub const GUNNAR_OID_MODULE: &str = "__gunnar_oid__";
329
330/// Reserved `module_name` for the **git commit graph** written by the `git`
331/// package format: an Arrow IPC sub-index of
332/// `(oid, parents[], tree, committer_time, generation)`. Reserved so ordinary
333/// `list`/`decompress`/iceberg readers skip it; queryable from DuckDB by slicing
334/// its manifest byte range.
335pub const GUNNAR_GRAPH_MODULE: &str = "__gunnar_graph__";
336
337/// Reserved `module_name` for the **git reachability bitmaps** written by the
338/// `git` package format: an Arrow IPC sub-index of `(commit_oid, bitmap)` where
339/// `bitmap` is a serialized roaring bitmap over object ordinals.
340pub const GUNNAR_REACH_MODULE: &str = "__gunnar_reach__";
341
342/// Reserved `module_name` for the **git ref log** written by the `git` package
343/// format: an Arrow IPC sub-index carrying **one RecordBatch per push**.
344///
345/// The batch boundary *is* the transaction boundary. There is no database here
346/// (D18: redb was a database wedged between two archive formats, and it is
347/// gone). A push is durable exactly when its IPC frame is complete on disk; a
348/// frame torn by a crash is not half a push, it is a trailing byte run that no
349/// reader will accept. Recovery is therefore "read forward while frames parse",
350/// never a journal replay.
351pub const GUNNAR_REFS_MODULE: &str = "__gunnar_refs__";
352
353/// Reserved `module_name` for the **git secrets log** written by the `git`
354/// package format: the same one-RecordBatch-per-push shape as
355/// [`GUNNAR_REFS_MODULE`], carrying already-encrypted material only. znippy
356/// never sees plaintext, and ciphertext is never compressed.
357pub const GUNNAR_SECRETS_MODULE: &str = "__gunnar_secrets__";
358
359/// `pkg_type` discriminant carried by reserved (non-data) manifest entries.
360pub const RESERVED_PKG_TYPE: i8 = i8::MIN;
361
362/// Every reserved `module_name` this reader knows, in one place.
363///
364/// Kept as a slice rather than a hand-written `||` chain so that adding a
365/// reserved module is a single edit that both [`is_reserved_module`] and the
366/// guard test see — the failure mode being avoided is a new module name that is
367/// written as reserved by the sink but classified as *data* by the manifest
368/// readers, which silently corrupts `list`, `decompress`, the iceberg sink and
369/// the manifest-count assertions.
370pub const RESERVED_MODULES: &[&str] = &[
371    LOOKUP_MODULE,
372    TRIE_MODULE,
373    SIGN_ARTIFACTS_MODULE,
374    SIGN_ARCHIVE_MODULE,
375    META_MODULE,
376    GUNNAR_OID_MODULE,
377    GUNNAR_GRAPH_MODULE,
378    GUNNAR_REACH_MODULE,
379    GUNNAR_REFS_MODULE,
380    GUNNAR_SECRETS_MODULE,
381];
382
383/// A reserved manifest entry holds a derived structure (lookup / trie / detached
384/// signatures / the git oid-index, commit-graph and reachability sections), not
385/// file rows. The merge + manifest readers skip these so data consumers are
386/// unaffected — which is exactly what makes those sections additive and
387/// backward-compatible.
388pub fn is_reserved_module(module_name: &str) -> bool {
389    RESERVED_MODULES.contains(&module_name)
390}
391
392/// Read the raw bytes of one reserved sub-section by module name, if present.
393/// Public entry point for the signature layer (feature `sign`) and any other
394/// reader that needs a reserved section's bytes without re-implementing the
395/// manifest walk.
396pub fn read_reserved_section_bytes(path: &Path, module_name: &str) -> Result<Option<Vec<u8>>> {
397    read_reserved_section(path, module_name)
398}
399
400/// Schema of the lookup sub-index — identical to the base index columns. The
401/// lookup is the same per-chunk rows, re-sorted by `(relative_path, chunk_seq)`
402/// and stripped of any plugin columns, so one path's chunks are contiguous.
403///
404/// **Carries no schema metadata**, and that is correct for the *lookup*: the
405/// lookup is a RESERVED sub-index, which every reader skips. It is NOT correct
406/// for a **data** sub-index — use [`data_subindex_schema`] there, or the archive
407/// records no format version and [`check_format_version`] has nothing to check.
408pub fn lookup_schema() -> Arc<Schema> {
409    Arc::new(Schema::new(base_index_fields()))
410}
411
412/// Schema for a base-column **data** sub-index: the same columns as
413/// [`lookup_schema`], stamped with the archive metadata that
414/// [`build_arrow_metadata_for_config`] produces — including
415/// [`FORMAT_VERSION_KEY`].
416///
417/// The reader (and holger's independent reader-side pin) determines an archive's
418/// on-disk format version from the Arrow schema metadata of the **first
419/// non-reserved sub-index**. A writer that seals its data sub-index with the bare
420/// [`lookup_schema`] therefore produces an archive that records no version at
421/// all, and the version pin degrades to "undetermined → read as before" for
422/// exactly those archives. Every data sub-index must be sealed with this.
423pub fn data_subindex_schema() -> Arc<Schema> {
424    Arc::new(Schema::new_with_metadata(
425        base_index_fields(),
426        build_arrow_metadata_for_config(&crate::common_config::CONFIG),
427    ))
428}
429
430/// One chunk's location for single-file random access.
431#[derive(Debug, Clone, PartialEq, Eq)]
432pub struct ChunkLoc {
433    pub chunk_seq: u32,
434    pub fdata_offset: u64,
435    pub blob_offset: u64,
436    pub blob_size: u64,
437    pub uncompressed_size: u64,
438    pub compressed: bool,
439    pub checksum: [u8; 32],
440}
441
442/// What the trailing footer of an archive points at.
443#[derive(Debug, Clone, PartialEq)]
444pub enum IndexFooter {
445    /// Legacy v0.6: a single Arrow IPC index began at this offset. Still detected
446    /// so the reader can reject v0.6 archives with a clear "re-compress with v0.7"
447    /// error — it is no longer a live read path.
448    Single { index_offset: u64 },
449    /// v0.7: the manifest stream begins at this offset.
450    Multi { manifest_offset: u64 },
451}
452
453/// Interpret an archive's trailing bytes. `tail` must be the last 16 bytes of the file
454/// (or last 8 for tiny v0.6 files — then it's always Single).
455pub fn interpret_footer(tail: &[u8]) -> IndexFooter {
456    let n = tail.len();
457    let offset = u64::from_le_bytes(tail[n - 8..].try_into().unwrap());
458    if n >= 16 && tail[n - 16..n - 8] == MULTI_INDEX_MAGIC {
459        IndexFooter::Multi { manifest_offset: offset }
460    } else {
461        IndexFooter::Single { index_offset: offset }
462    }
463}
464
465fn manifest_schema() -> Arc<Schema> {
466    Arc::new(Schema::new(vec![
467        Field::new("pkg_type", DataType::Int8, false),
468        Field::new("repo", DataType::Utf8, false),
469        Field::new("module_name", DataType::Utf8, false),
470        Field::new("index_offset", DataType::UInt64, false),
471        Field::new("index_len", DataType::UInt64, false),
472        Field::new("row_count", DataType::UInt64, false),
473    ]))
474}
475
476/// Serialize manifest entries to an Arrow IPC stream (itself DuckDB-readable).
477pub fn write_manifest_bytes(entries: &[ManifestEntry]) -> Result<Vec<u8>> {
478    use arrow::ipc::writer::StreamWriter;
479
480    let len = entries.len();
481    let mut pkg_type = Int8Builder::with_capacity(len);
482    let mut repo = StringBuilder::with_capacity(len, len * 16);
483    let mut module_name = StringBuilder::with_capacity(len, len * 16);
484    let mut index_offset = UInt64Builder::with_capacity(len);
485    let mut index_len = UInt64Builder::with_capacity(len);
486    let mut row_count = UInt64Builder::with_capacity(len);
487    for e in entries {
488        pkg_type.append_value(e.pkg_type);
489        repo.append_value(&e.repo);
490        module_name.append_value(&e.module_name);
491        index_offset.append_value(e.index_offset);
492        index_len.append_value(e.index_len);
493        row_count.append_value(e.row_count);
494    }
495
496    let schema = manifest_schema();
497    let batch = RecordBatch::try_new(
498        schema.clone(),
499        vec![
500            Arc::new(pkg_type.finish()),
501            Arc::new(repo.finish()),
502            Arc::new(module_name.finish()),
503            Arc::new(index_offset.finish()),
504            Arc::new(index_len.finish()),
505            Arc::new(row_count.finish()),
506        ],
507    )?;
508
509    let mut buf = Vec::new();
510    {
511        let mut w = StreamWriter::try_new(&mut buf, &schema)?;
512        w.write(&batch)?;
513        w.finish()?;
514    }
515    Ok(buf)
516}
517
518/// Parse a manifest Arrow IPC stream back into entries.
519pub fn read_manifest_bytes(bytes: &[u8]) -> Result<Vec<ManifestEntry>> {
520    use arrow::array::{Int8Array, StringArray, UInt64Array};
521    use arrow::ipc::reader::StreamReader;
522
523    let reader = StreamReader::try_new(std::io::Cursor::new(bytes), None)?;
524    let mut out = Vec::new();
525    for batch in reader {
526        let batch = batch?;
527        let col = |name: &str| batch.column_by_name(name)
528            .ok_or_else(|| anyhow::anyhow!("manifest missing column {name}"));
529        let pkg_type = col("pkg_type")?.as_any().downcast_ref::<Int8Array>()
530            .ok_or_else(|| anyhow::anyhow!("pkg_type type"))?;
531        let repo = col("repo")?.as_any().downcast_ref::<StringArray>()
532            .ok_or_else(|| anyhow::anyhow!("repo type"))?;
533        let module_name = col("module_name")?.as_any().downcast_ref::<StringArray>()
534            .ok_or_else(|| anyhow::anyhow!("module_name type"))?;
535        let index_offset = col("index_offset")?.as_any().downcast_ref::<UInt64Array>()
536            .ok_or_else(|| anyhow::anyhow!("index_offset type"))?;
537        let index_len = col("index_len")?.as_any().downcast_ref::<UInt64Array>()
538            .ok_or_else(|| anyhow::anyhow!("index_len type"))?;
539        let row_count = col("row_count")?.as_any().downcast_ref::<UInt64Array>()
540            .ok_or_else(|| anyhow::anyhow!("row_count type"))?;
541        for i in 0..batch.num_rows() {
542            out.push(ManifestEntry {
543                pkg_type: pkg_type.value(i),
544                repo: repo.value(i).to_string(),
545                module_name: module_name.value(i).to_string(),
546                index_offset: index_offset.value(i),
547                index_len: index_len.value(i),
548                row_count: row_count.value(i),
549            });
550        }
551    }
552    Ok(out)
553}
554
555/// Read the Arrow IPC index from a v0.7 .znippy file.
556///
557/// Reads the 16-byte footer (8-byte `ZNPYMIDX` magic + 8-byte LE u64 manifest_offset),
558/// parses the manifest, reads every sub-index, and merges all batches into one so callers
559/// need no format-version awareness.
560pub fn read_znippy_index(path: &Path) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
561    read_znippy_index_filtered(path, &IndexFilter::default())
562}
563
564/// Selective sub-index filter: keep only sub-indexes whose manifest entry
565/// matches. A `None` field matches anything, so `IndexFilter::default()` reads
566/// the whole archive (what [`read_znippy_index`] does). Filtering happens at the
567/// `(pkg_type, repo)` sub-index granularity — whole Arrow IPC streams are
568/// skipped, never read — so a selective extract touches only the matching rows.
569#[derive(Debug, Clone, Default)]
570pub struct IndexFilter {
571    /// Keep only this package-type discriminant (`ManifestEntry::pkg_type`).
572    pub pkg_type: Option<i8>,
573    /// Keep only this repo (`ManifestEntry::repo`).
574    pub repo: Option<String>,
575}
576
577impl IndexFilter {
578    pub fn is_empty(&self) -> bool {
579        self.pkg_type.is_none() && self.repo.is_none()
580    }
581    fn matches(&self, e: &ManifestEntry) -> bool {
582        self.pkg_type.is_none_or(|t| e.pkg_type == t)
583            && self.repo.as_deref().is_none_or(|r| e.repo == r)
584    }
585}
586
587/// Like [`read_znippy_index`] but keeps only sub-indexes matching `filter`.
588pub fn read_znippy_index_filtered(
589    path: &Path,
590    filter: &IndexFilter,
591) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
592    let mut file = File::open(path)?;
593    let file_len = file.metadata()?.len();
594    anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 znippy archive");
595
596    file.seek(SeekFrom::End(-16))?;
597    let mut tail = [0u8; 16];
598    file.read_exact(&mut tail)?;
599
600    match interpret_footer(&tail) {
601        IndexFooter::Multi { manifest_offset } => {
602            read_multi_index(&mut file, file_len, manifest_offset, filter)
603        }
604        IndexFooter::Single { .. } => {
605            anyhow::bail!("v0.6 archives are not supported; re-compress with v0.7")
606        }
607    }
608}
609
610/// Read all sub-indexes from a v0.7 multi-index archive and concatenate them.
611fn read_multi_index(
612    file: &mut File,
613    file_len: u64,
614    manifest_offset: u64,
615    filter: &IndexFilter,
616) -> Result<(Arc<Schema>, Vec<RecordBatch>)> {
617    use arrow::ipc::reader::StreamReader;
618
619    // manifest lives between manifest_offset and (file_len − 16): 8-byte magic + 8-byte offset
620    let manifest_end = file_len.checked_sub(16)
621        .ok_or_else(|| anyhow::anyhow!("v0.7 archive too small"))?;
622    anyhow::ensure!(manifest_offset <= manifest_end, "corrupt v0.7 manifest_offset");
623    let manifest_len = (manifest_end - manifest_offset) as usize;
624
625    file.seek(SeekFrom::Start(manifest_offset))?;
626    let mut manifest_bytes = vec![0u8; manifest_len];
627    file.read_exact(&mut manifest_bytes)?;
628    let entries = read_manifest_bytes(&manifest_bytes)?;
629
630    let mut all_batches: Vec<RecordBatch> = Vec::new();
631    let mut schema: Option<Arc<Schema>> = None;
632
633    for entry in &entries {
634        // Skip derived structures (lookup sub-index, trie blob) — they are not
635        // file-row data and must not be merged into the index.
636        if is_reserved_module(&entry.module_name) {
637            continue;
638        }
639        // Selective read: skip whole sub-indexes that don't match the filter.
640        if !filter.matches(entry) {
641            continue;
642        }
643        // Bound the attacker-controlled declared length against the real file
644        // size before allocating, so a corrupt manifest can't force a huge alloc.
645        anyhow::ensure!(
646            entry.index_offset.checked_add(entry.index_len)
647                .is_some_and(|end| end <= file_len),
648            "sub-index for module {} out of bounds (offset={}, len={}, file_len={})",
649            entry.module_name, entry.index_offset, entry.index_len, file_len
650        );
651        file.seek(SeekFrom::Start(entry.index_offset))?;
652        let mut sub_bytes = vec![0u8; entry.index_len as usize];
653        file.read_exact(&mut sub_bytes)?;
654        let cursor = std::io::Cursor::new(sub_bytes);
655        let reader = StreamReader::try_new(cursor, None)?;
656        if schema.is_none() {
657            let sub_schema = reader.schema();
658            // Refuse archives written by a newer znippy than this reader supports,
659            // before parsing any sub-index batches we might mis-interpret.
660            check_format_version(sub_schema.metadata())?;
661            schema = Some(sub_schema);
662        }
663        for batch in reader {
664            all_batches.push(batch.map_err(|e| anyhow::anyhow!("sub-index read error: {}", e))?);
665        }
666    }
667
668    let schema = schema.unwrap_or_else(|| Arc::new(Schema::new(base_index_fields())));
669
670    // Merge all sub-index batches into one so callers stay format-agnostic.
671    let merged = if all_batches.len() <= 1 {
672        all_batches
673    } else {
674        let batch = arrow_select::concat::concat_batches(&schema, all_batches.iter())
675            .map_err(|e| anyhow::anyhow!("concat sub-indexes: {}", e))?;
676        vec![batch]
677    };
678
679    Ok((schema, merged))
680}
681
682/// Read the manifest from a v0.7 multi-index archive.
683/// Returns an error if the file is a plain v0.6 single-index archive.
684pub fn read_znippy_manifest(path: &Path) -> Result<Vec<ManifestEntry>> {
685    let mut file = File::open(path)?;
686    let file_len = file.metadata()?.len();
687    anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 archive");
688
689    file.seek(SeekFrom::End(-16))?;
690    let mut tail = [0u8; 16];
691    file.read_exact(&mut tail)?;
692
693    match interpret_footer(&tail) {
694        IndexFooter::Single { .. } => {
695            anyhow::bail!("not a v0.7 multi-index archive (no MULTI_INDEX_MAGIC)")
696        }
697        IndexFooter::Multi { manifest_offset } => {
698            let manifest_end = file_len - 16;
699            anyhow::ensure!(manifest_offset <= manifest_end, "corrupt manifest_offset");
700            let manifest_len = (manifest_end - manifest_offset) as usize;
701            file.seek(SeekFrom::Start(manifest_offset))?;
702            let mut manifest_bytes = vec![0u8; manifest_len];
703            file.read_exact(&mut manifest_bytes)?;
704            let mut entries = read_manifest_bytes(&manifest_bytes)?;
705            // Hide reserved (lookup/trie) entries from data-manifest consumers.
706            entries.retain(|e| !is_reserved_module(&e.module_name));
707            Ok(entries)
708        }
709    }
710}
711
712/// Read **all** manifest entries of a sealed v0.7 archive, *including* the
713/// reserved (lookup/trie) ones, plus the manifest's byte offset.
714///
715/// Public entrypoint used by the append/resume sink
716/// ([`ArrowIpcSinkAppend::open_existing`](crate::ArrowIpcSinkAppend::open_existing)):
717/// it needs the reserved sections (to find the blob-region end and to recover
718/// the sorted lookup) which `read_znippy_manifest` hides. Read-only — does not
719/// touch the original write path.
720pub fn read_znippy_full_manifest(path: &Path) -> Result<(Vec<ManifestEntry>, u64)> {
721    let mut file = File::open(path)?;
722    let file_len = file.metadata()?.len();
723    read_full_manifest(&mut file, file_len)
724}
725
726/// Read all manifest entries, *including* reserved (lookup/trie) ones.
727fn read_full_manifest(file: &mut File, file_len: u64) -> Result<(Vec<ManifestEntry>, u64)> {
728    anyhow::ensure!(file_len >= 16, "file too small to be a v0.7 archive");
729    file.seek(SeekFrom::End(-16))?;
730    let mut tail = [0u8; 16];
731    file.read_exact(&mut tail)?;
732    let manifest_offset = match interpret_footer(&tail) {
733        IndexFooter::Multi { manifest_offset } => manifest_offset,
734        IndexFooter::Single { .. } => anyhow::bail!("not a v0.7 multi-index archive"),
735    };
736    let manifest_end = file_len.checked_sub(16)
737        .ok_or_else(|| anyhow::anyhow!("v0.7 archive too small"))?;
738    anyhow::ensure!(manifest_offset <= manifest_end, "corrupt manifest_offset");
739    let manifest_len = (manifest_end - manifest_offset) as usize;
740    file.seek(SeekFrom::Start(manifest_offset))?;
741    let mut manifest_bytes = vec![0u8; manifest_len];
742    file.read_exact(&mut manifest_bytes)?;
743    Ok((read_manifest_bytes(&manifest_bytes)?, manifest_offset))
744}
745
746/// Read the raw bytes of one reserved sub-section (lookup or trie), if present.
747fn read_reserved_section(path: &Path, module_name: &str) -> Result<Option<Vec<u8>>> {
748    let mut file = File::open(path)?;
749    let file_len = file.metadata()?.len();
750    let (entries, _) = read_full_manifest(&mut file, file_len)?;
751    let Some(entry) = entries.iter().find(|e| e.module_name == module_name) else {
752        return Ok(None);
753    };
754    // Bound the attacker-controlled declared length against the real file size
755    // before allocating, so a corrupt manifest can't force a huge allocation.
756    anyhow::ensure!(
757        entry.index_offset.checked_add(entry.index_len)
758            .is_some_and(|end| end <= file_len),
759        "reserved section {} out of bounds (offset={}, len={}, file_len={})",
760        entry.module_name, entry.index_offset, entry.index_len, file_len
761    );
762    file.seek(SeekFrom::Start(entry.index_offset))?;
763    let mut bytes = vec![0u8; entry.index_len as usize];
764    file.read_exact(&mut bytes)?;
765    Ok(Some(bytes))
766}
767
768/// Decode the lookup sub-index bytes into parallel column vectors (already sorted
769/// by `(relative_path, chunk_seq)` on disk).
770/// Read row `i` of an index/lookup `checksum` column as a 32-byte blake3 digest.
771///
772/// `FixedSizeBinaryArray` is one concrete Arrow type for *every* width, so a
773/// `downcast_ref::<FixedSizeBinaryArray>()` succeeds just as happily for
774/// `FixedSizeBinary(16)` as for `(32)`. Copying such a row straight into a
775/// `[u8; 32]` panics ("source slice length (16) does not match destination slice
776/// length (32)") — a process abort driven by an attacker-supplied schema, which
777/// is exactly what the downcast-or-error style everywhere else in this file
778/// exists to prevent. Check the declared width and return a clean `Err` instead.
779/// (`ZnippyArchive::build_file_index` already guards this with the same test.)
780fn checksum32(col: &arrow::array::FixedSizeBinaryArray, i: usize) -> Result<[u8; 32]> {
781    if col.value_length() != 32 {
782        return Err(anyhow::anyhow!(
783            "checksum column has width {}, expected 32",
784            col.value_length()
785        ));
786    }
787    let mut ck = [0u8; 32];
788    ck.copy_from_slice(col.value(i));
789    Ok(ck)
790}
791
792fn decode_lookup(bytes: &[u8]) -> Result<LookupColumns> {
793    use arrow::array::{BooleanArray, FixedSizeBinaryArray, StringArray, UInt32Array, UInt64Array};
794    use arrow::ipc::reader::StreamReader;
795
796    let reader = StreamReader::try_new(std::io::Cursor::new(bytes), None)?;
797    let mut cols = LookupColumns::default();
798    for batch in reader {
799        let batch = batch?;
800        let get = |n: &str| batch.column_by_name(n)
801            .ok_or_else(|| anyhow::anyhow!("lookup missing column {n}"));
802        let paths = get("relative_path")?.as_any().downcast_ref::<StringArray>()
803            .ok_or_else(|| anyhow::anyhow!("relative_path type"))?;
804        let chunk_seq = get("chunk_seq")?.as_any().downcast_ref::<UInt32Array>()
805            .ok_or_else(|| anyhow::anyhow!("chunk_seq type"))?;
806        let fdata = get("fdata_offset")?.as_any().downcast_ref::<UInt64Array>()
807            .ok_or_else(|| anyhow::anyhow!("fdata_offset type"))?;
808        let compressed = get("compressed")?.as_any().downcast_ref::<BooleanArray>()
809            .ok_or_else(|| anyhow::anyhow!("compressed type"))?;
810        let usize_col = get("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
811            .ok_or_else(|| anyhow::anyhow!("uncompressed_size type"))?;
812        let blob_offset = get("blob_offset")?.as_any().downcast_ref::<UInt64Array>()
813            .ok_or_else(|| anyhow::anyhow!("blob_offset type"))?;
814        let blob_size = get("blob_size")?.as_any().downcast_ref::<UInt64Array>()
815            .ok_or_else(|| anyhow::anyhow!("blob_size type"))?;
816        let checksum = get("checksum")?.as_any().downcast_ref::<FixedSizeBinaryArray>()
817            .ok_or_else(|| anyhow::anyhow!("checksum type"))?;
818        for i in 0..batch.num_rows() {
819            cols.paths.push(paths.value(i).to_string());
820            let ck = checksum32(checksum, i)?;
821            cols.locs.push(ChunkLoc {
822                chunk_seq: chunk_seq.value(i),
823                fdata_offset: fdata.value(i),
824                blob_offset: blob_offset.value(i),
825                blob_size: blob_size.value(i),
826                uncompressed_size: usize_col.value(i),
827                compressed: compressed.value(i),
828                checksum: ck,
829            });
830        }
831    }
832    Ok(cols)
833}
834
835#[derive(Default)]
836struct LookupColumns {
837    paths: Vec<String>,
838    locs: Vec<ChunkLoc>,
839}
840
841/// Locate every chunk of `target` for single-file random access.
842///
843/// Fast paths, in order: the fst trie (O(key length)) → binary search of the
844/// sorted lookup sub-index (O(log n)) → linear scan of the merged main index
845/// (O(n), for archives written before the lookup layer existed). Returns the
846/// chunks sorted by `chunk_seq`, or an empty vec if `target` is not in the archive.
847pub fn locate_file(path: &Path, target: &str) -> Result<Vec<ChunkLoc>> {
848    if let Some(lookup_bytes) = read_reserved_section(path, LOOKUP_MODULE)? {
849        let cols = decode_lookup(&lookup_bytes)?;
850        let n = cols.paths.len();
851
852        // Find any row whose path == target.
853        let hit = if let Some(trie_bytes) = read_reserved_section(path, TRIE_MODULE)? {
854            let map = fst::Map::new(trie_bytes)
855                .map_err(|e| anyhow::anyhow!("trie open: {e}"))?;
856            map.get(target.as_bytes()).map(|v| v as usize)
857        } else {
858            // Lookup is sorted by path; binary-search the path column.
859            match cols.paths.binary_search_by(|p| p.as_str().cmp(target)) {
860                Ok(i) => Some(i),
861                Err(_) => None,
862            }
863        };
864
865        let Some(hit) = hit else { return Ok(Vec::new()); };
866
867        // The trie value is attacker-controlled: a corrupt/malicious archive can
868        // map `target` to a row index past the (smaller) lookup table. Treat an
869        // out-of-range hit as "not found" instead of indexing OOB below — this is
870        // a remote-DoS guard on the random-access read path.
871        if hit >= n { return Ok(Vec::new()); }
872
873        // Expand to the contiguous run of rows sharing this path.
874        let mut start = hit;
875        while start > 0 && cols.paths[start - 1] == target { start -= 1; }
876        let mut end = hit + 1;
877        while end < n && cols.paths[end] == target { end += 1; }
878
879        let mut out: Vec<ChunkLoc> = cols.locs[start..end].to_vec();
880        out.sort_by_key(|c| c.chunk_seq);
881        return Ok(out);
882    }
883
884    // Fallback: no lookup layer — scan the merged main index.
885    locate_file_via_index(path, target)
886}
887
888/// Slim per-file (per-artifact) metadata for browsing an archive without
889/// reading file bytes. One row per file, aggregated across its chunks.
890#[derive(Debug, Clone, PartialEq)]
891pub struct ArtifactMeta {
892    pub relative_path: String,
893    /// Total uncompressed size across all of the file's chunks.
894    pub uncompressed_size: u64,
895    pub chunk_count: u32,
896    /// Whether the file's data was compressed (false on the stored-raw skip path).
897    pub compressed: bool,
898}
899
900/// Metadata for **every** file in the archive, sorted by `relative_path`.
901///
902/// Reads only the lookup sub-index (not the file bytes); falls back to the main
903/// index for archives written before the lookup layer.
904pub fn get_all_files_meta(path: &Path) -> Result<Vec<ArtifactMeta>> {
905    files_meta_impl(path, None)
906}
907
908/// Metadata for the files whose `relative_path` starts with `prefix` — for when
909/// you don't want all files (e.g. one `group/artifact/` subtree).
910///
911/// When the trie is present this jumps straight to the first matching key via the
912/// fst's ordered range (O(prefix) to seek, then O(matches)); otherwise it binary
913/// -searches the sorted lookup; otherwise it scans the legacy main index.
914pub fn get_files_meta_with_prefix(path: &Path, prefix: &str) -> Result<Vec<ArtifactMeta>> {
915    files_meta_impl(path, Some(prefix))
916}
917
918fn files_meta_impl(path: &Path, prefix: Option<&str>) -> Result<Vec<ArtifactMeta>> {
919    use fst::{IntoStreamer, Streamer};
920
921    if let Some(lookup_bytes) = read_reserved_section(path, LOOKUP_MODULE)? {
922        let cols = decode_lookup(&lookup_bytes)?; // sorted by (relative_path, chunk_seq)
923        let n = cols.paths.len();
924
925        // Resolve the contiguous row window [lo, hi) to aggregate.
926        let (lo, hi) = match prefix {
927            None | Some("") => (0, n),
928            Some(pre) => {
929                // Seek the first key >= prefix. Use the trie's ordered range when
930                // present (the "trie search"); else binary-search the sorted paths.
931                let lo = if let Some(trie_bytes) = read_reserved_section(path, TRIE_MODULE)? {
932                    let map = fst::Map::new(trie_bytes)
933                        .map_err(|e| anyhow::anyhow!("trie open: {e}"))?;
934                    let mut stream = map.range().ge(pre.as_bytes()).into_stream();
935                    match stream.next() {
936                        Some((k, v)) if k.starts_with(pre.as_bytes()) => v as usize,
937                        _ => return Ok(Vec::new()),
938                    }
939                } else {
940                    cols.paths.partition_point(|p| p.as_str() < pre)
941                };
942                if lo >= n || !cols.paths[lo].starts_with(pre) {
943                    return Ok(Vec::new());
944                }
945                let mut hi = lo;
946                while hi < n && cols.paths[hi].starts_with(pre) {
947                    hi += 1;
948                }
949                (lo, hi)
950            }
951        };
952
953        // Aggregate contiguous chunk rows per path.
954        let mut out = Vec::new();
955        let mut i = lo;
956        while i < hi {
957            let p = &cols.paths[i];
958            let mut total = 0u64;
959            let mut count = 0u32;
960            let mut compressed = false;
961            while i < hi && &cols.paths[i] == p {
962                total += cols.locs[i].uncompressed_size;
963                count += 1;
964                compressed |= cols.locs[i].compressed;
965                i += 1;
966            }
967            out.push(ArtifactMeta {
968                relative_path: p.clone(),
969                uncompressed_size: total,
970                chunk_count: count,
971                compressed,
972            });
973        }
974        return Ok(out);
975    }
976
977    files_meta_via_index(path, prefix)
978}
979
980/// A cached, open-once random-access reader over a sealed v0.7 archive.
981///
982/// The free functions [`locate_file`] and [`get_files_meta_with_prefix`] re-open
983/// the file and re-read the footer + manifest + both reserved sections (the
984/// lookup sub-index and the trie) on **every** call, and re-`decode_lookup` every
985/// row each time — three manifest reads per lookup (analysis §1.5). For a
986/// long-lived reader (a browsing UI, holger's dynamic side, selective restore)
987/// that is pure repeated I/O.
988///
989/// `ArchiveReader::open` reads the footer, manifest, lookup sub-index and trie
990/// **once**, decodes the lookup columns once, and builds the fst map once. Every
991/// subsequent [`locate`](ArchiveReader::locate),
992/// [`files_meta`](ArchiveReader::files_meta) and
993/// [`files_meta_with_prefix`](ArchiveReader::files_meta_with_prefix) query is then
994/// served from memory — an fst `get` (O(key)) or a binary search (O(log n)) over
995/// the already-decoded columns — with **zero** further I/O and **zero**
996/// per-call manifest reads. The on-disk format is untouched; results are
997/// identical to the equivalent free function.
998pub struct ArchiveReader {
999    /// Relative paths, sorted by `(relative_path, chunk_seq)` (lookup order).
1000    paths: Vec<String>,
1001    /// Chunk locators, index-aligned with `paths`.
1002    locs: Vec<ChunkLoc>,
1003    /// `path -> first row index` fst over the sorted paths, when the archive
1004    /// carries a trie section (it always does for v0.7 seals). Absent ⇒ fall back
1005    /// to binary search over `paths`.
1006    trie: Option<fst::Map<Vec<u8>>>,
1007    /// The archive handle kept open across calls, so [`read_file`](Self::read_file)
1008    /// serves selective restore with **one** open + cached locate (positioned
1009    /// `pread`s only — never seeks a shared cursor).
1010    file: File,
1011    /// Real archive length, for the same pre-alloc bounds check the free
1012    /// `get_file` does against attacker-controlled blob offsets/sizes.
1013    file_len: u64,
1014}
1015
1016impl ArchiveReader {
1017    /// Open a sealed v0.7 archive and cache its manifest + lookup + trie. Reads
1018    /// the manifest exactly once (vs three re-reads per free-function call).
1019    pub fn open(path: &Path) -> Result<Self> {
1020        let mut file = File::open(path)?;
1021        let file_len = file.metadata()?.len();
1022        let (entries, _) = read_full_manifest(&mut file, file_len)?;
1023
1024        // Read one reserved section by module name from the already-open handle,
1025        // bounding the attacker-controlled declared length against the real file
1026        // size before allocating (same guard as `read_reserved_section`).
1027        let mut read_section = |module: &str| -> Result<Option<Vec<u8>>> {
1028            let Some(entry) = entries.iter().find(|e| e.module_name == module) else {
1029                return Ok(None);
1030            };
1031            anyhow::ensure!(
1032                entry.index_offset.checked_add(entry.index_len)
1033                    .is_some_and(|end| end <= file_len),
1034                "reserved section {} out of bounds (offset={}, len={}, file_len={})",
1035                entry.module_name, entry.index_offset, entry.index_len, file_len
1036            );
1037            file.seek(SeekFrom::Start(entry.index_offset))?;
1038            let mut bytes = vec![0u8; entry.index_len as usize];
1039            file.read_exact(&mut bytes)?;
1040            Ok(Some(bytes))
1041        };
1042
1043        let lookup_bytes = read_section(LOOKUP_MODULE)?.ok_or_else(|| {
1044            anyhow::anyhow!("archive has no lookup sub-index (not a v0.7 sealed archive)")
1045        })?;
1046        let cols = decode_lookup(&lookup_bytes)?;
1047        let trie = match read_section(TRIE_MODULE)? {
1048            Some(tb) => Some(fst::Map::new(tb).map_err(|e| anyhow::anyhow!("trie open: {e}"))?),
1049            None => None,
1050        };
1051
1052        Ok(Self { paths: cols.paths, locs: cols.locs, trie, file, file_len })
1053    }
1054
1055    /// Total number of chunk rows cached (across all files).
1056    pub fn row_count(&self) -> usize {
1057        self.paths.len()
1058    }
1059
1060    /// Read a single file's bytes by relative path — the cached, held-open
1061    /// equivalent of [`get_file`](crate::get_file). Uses the in-memory locate
1062    /// (no manifest re-read, no per-call `decode_lookup`) and the archive handle
1063    /// opened once in [`open`](Self::open), then `pread`s + decompresses +
1064    /// blake3-verifies each chunk. This is the selective-restore entry point:
1065    /// hold one reader and call `read_file` per artifact instead of paying a full
1066    /// index re-parse on every `get_file`.
1067    ///
1068    /// Returns an error if `target` is not present in the archive.
1069    pub fn read_file(&self, target: &str) -> Result<Vec<u8>> {
1070        let chunks = self.locate(target);
1071        anyhow::ensure!(!chunks.is_empty(), "file not found in archive: {target}");
1072        crate::decompress::reassemble_file(&self.file, self.file_len, target, &chunks)
1073    }
1074
1075    /// Locate every chunk of `target`, sorted by `chunk_seq` — the cached
1076    /// equivalent of [`locate_file`], but with no I/O after `open`.
1077    pub fn locate(&self, target: &str) -> Vec<ChunkLoc> {
1078        let n = self.paths.len();
1079        let hit = match &self.trie {
1080            Some(map) => map.get(target.as_bytes()).map(|v| v as usize),
1081            None => self.paths.binary_search_by(|p| p.as_str().cmp(target)).ok(),
1082        };
1083        let Some(hit) = hit else { return Vec::new(); };
1084
1085        // The trie value is attacker-controlled (see `locate_file`): a malicious
1086        // archive can map `target` to a row index past the cached lookup table.
1087        // Treat an out-of-range hit as "not found" instead of panicking below.
1088        if hit >= n { return Vec::new(); }
1089
1090        // Expand to the contiguous run of rows sharing this path.
1091        let mut start = hit;
1092        while start > 0 && self.paths[start - 1] == target { start -= 1; }
1093        let mut end = hit + 1;
1094        while end < n && self.paths[end] == target { end += 1; }
1095
1096        let mut out: Vec<ChunkLoc> = self.locs[start..end].to_vec();
1097        out.sort_by_key(|c| c.chunk_seq);
1098        out
1099    }
1100
1101    /// Per-file metadata for **every** file, sorted by `relative_path` — the
1102    /// cached equivalent of [`get_all_files_meta`].
1103    pub fn files_meta(&self) -> Vec<ArtifactMeta> {
1104        self.aggregate(0, self.paths.len())
1105    }
1106
1107    /// Per-file metadata for files whose path starts with `prefix` — the cached
1108    /// equivalent of [`get_files_meta_with_prefix`].
1109    pub fn files_meta_with_prefix(&self, prefix: &str) -> Vec<ArtifactMeta> {
1110        let (lo, hi) = self.window(prefix);
1111        self.aggregate(lo, hi)
1112    }
1113
1114    /// Resolve the contiguous `[lo, hi)` row window matching `prefix` — trie
1115    /// range-seek when present, else binary search over the sorted paths. Empty
1116    /// prefix selects all rows; a non-matching prefix returns `(0, 0)`.
1117    fn window(&self, prefix: &str) -> (usize, usize) {
1118        use fst::{IntoStreamer, Streamer};
1119        let n = self.paths.len();
1120        if prefix.is_empty() {
1121            return (0, n);
1122        }
1123        let lo = match &self.trie {
1124            Some(map) => {
1125                let mut stream = map.range().ge(prefix.as_bytes()).into_stream();
1126                match stream.next() {
1127                    Some((k, v)) if k.starts_with(prefix.as_bytes()) => v as usize,
1128                    _ => return (0, 0),
1129                }
1130            }
1131            None => self.paths.partition_point(|p| p.as_str() < prefix),
1132        };
1133        if lo >= n || !self.paths[lo].starts_with(prefix) {
1134            return (0, 0);
1135        }
1136        let mut hi = lo;
1137        while hi < n && self.paths[hi].starts_with(prefix) {
1138            hi += 1;
1139        }
1140        (lo, hi)
1141    }
1142
1143    /// Aggregate the contiguous chunk rows in `[lo, hi)` into one `ArtifactMeta`
1144    /// per file (rows are already grouped by path in lookup order).
1145    fn aggregate(&self, lo: usize, hi: usize) -> Vec<ArtifactMeta> {
1146        let mut out = Vec::new();
1147        let mut i = lo;
1148        while i < hi {
1149            let p = &self.paths[i];
1150            let mut total = 0u64;
1151            let mut count = 0u32;
1152            let mut compressed = false;
1153            while i < hi && &self.paths[i] == p {
1154                total += self.locs[i].uncompressed_size;
1155                count += 1;
1156                compressed |= self.locs[i].compressed;
1157                i += 1;
1158            }
1159            out.push(ArtifactMeta {
1160                relative_path: p.clone(),
1161                uncompressed_size: total,
1162                chunk_count: count,
1163                compressed,
1164            });
1165        }
1166        out
1167    }
1168}
1169
1170/// Legacy fallback: aggregate per-file metadata from the merged main index.
1171fn files_meta_via_index(path: &Path, prefix: Option<&str>) -> Result<Vec<ArtifactMeta>> {
1172    use arrow::array::{BooleanArray, StringArray, UInt64Array};
1173
1174    let (schema, batches) = read_znippy_index(path)?;
1175    let batch = match batches.len() {
1176        0 => return Ok(Vec::new()),
1177        1 => batches.into_iter().next().unwrap(),
1178        _ => arrow_select::concat::concat_batches(&schema, batches.iter())?,
1179    };
1180    // Downcast-or-error: the schema is attacker-controlled, so a wrong column
1181    // type must surface as an `Err`, never an `unwrap` panic (DoS on `get`/meta).
1182    // Downcast-or-error: the schema is attacker-controlled, so a wrong column
1183    // type must surface as an `Err`, never an `unwrap` panic (DoS on `get`/meta).
1184    let col = |n: &str| batch.column_by_name(n)
1185        .ok_or_else(|| anyhow::anyhow!("index missing column {n}"));
1186    let paths = col("relative_path")?.as_any().downcast_ref::<StringArray>()
1187        .ok_or_else(|| anyhow::anyhow!("index column relative_path has unexpected type"))?;
1188    let usize_col = col("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
1189        .ok_or_else(|| anyhow::anyhow!("index column uncompressed_size has unexpected type"))?;
1190    let compressed = col("compressed")?.as_any().downcast_ref::<BooleanArray>()
1191        .ok_or_else(|| anyhow::anyhow!("index column compressed has unexpected type"))?;
1192
1193    // Main index rows are not path-sorted, so aggregate via a map.
1194    let mut agg: HashMap<&str, (u64, u32, bool)> = HashMap::new();
1195    for i in 0..batch.num_rows() {
1196        let p = paths.value(i);
1197        if let Some(pre) = prefix {
1198            if !p.starts_with(pre) { continue; }
1199        }
1200        let e = agg.entry(p).or_insert((0, 0, false));
1201        e.0 += usize_col.value(i);
1202        e.1 += 1;
1203        e.2 |= compressed.value(i);
1204    }
1205    let mut out: Vec<ArtifactMeta> = agg.into_iter().map(|(p, (sz, c, comp))| ArtifactMeta {
1206        relative_path: p.to_string(),
1207        uncompressed_size: sz,
1208        chunk_count: c,
1209        compressed: comp,
1210    }).collect();
1211    out.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
1212    Ok(out)
1213}
1214
1215/// O(n) fallback for archives written before the lookup sub-index existed.
1216fn locate_file_via_index(path: &Path, target: &str) -> Result<Vec<ChunkLoc>> {
1217    use arrow::array::{BooleanArray, FixedSizeBinaryArray, StringArray, UInt32Array, UInt64Array};
1218
1219    let (schema, batches) = read_znippy_index(path)?;
1220    let batch = match batches.len() {
1221        0 => return Ok(Vec::new()),
1222        1 => batches.into_iter().next().unwrap(),
1223        _ => arrow_select::concat::concat_batches(&schema, batches.iter())?,
1224    };
1225    // Downcast-or-error: the schema is attacker-controlled, so a wrong column
1226    // type must surface as an `Err`, never an `unwrap` panic (DoS on `get`).
1227    let col = |n: &str| batch.column_by_name(n)
1228        .ok_or_else(|| anyhow::anyhow!("index missing column {n}"));
1229    let paths = col("relative_path")?.as_any().downcast_ref::<StringArray>()
1230        .ok_or_else(|| anyhow::anyhow!("index column relative_path has unexpected type"))?;
1231    let chunk_seq = col("chunk_seq")?.as_any().downcast_ref::<UInt32Array>()
1232        .ok_or_else(|| anyhow::anyhow!("index column chunk_seq has unexpected type"))?;
1233    let fdata = col("fdata_offset")?.as_any().downcast_ref::<UInt64Array>()
1234        .ok_or_else(|| anyhow::anyhow!("index column fdata_offset has unexpected type"))?;
1235    let compressed = col("compressed")?.as_any().downcast_ref::<BooleanArray>()
1236        .ok_or_else(|| anyhow::anyhow!("index column compressed has unexpected type"))?;
1237    let usize_col = col("uncompressed_size")?.as_any().downcast_ref::<UInt64Array>()
1238        .ok_or_else(|| anyhow::anyhow!("index column uncompressed_size has unexpected type"))?;
1239    let blob_offset = col("blob_offset")?.as_any().downcast_ref::<UInt64Array>()
1240        .ok_or_else(|| anyhow::anyhow!("index column blob_offset has unexpected type"))?;
1241    let blob_size = col("blob_size")?.as_any().downcast_ref::<UInt64Array>()
1242        .ok_or_else(|| anyhow::anyhow!("index column blob_size has unexpected type"))?;
1243    let checksum = col("checksum")?.as_any().downcast_ref::<FixedSizeBinaryArray>()
1244        .ok_or_else(|| anyhow::anyhow!("index column checksum has unexpected type"))?;
1245
1246    let mut out = Vec::new();
1247    for i in 0..batch.num_rows() {
1248        if paths.value(i) == target {
1249            let ck = checksum32(checksum, i)?;
1250            out.push(ChunkLoc {
1251                chunk_seq: chunk_seq.value(i),
1252                fdata_offset: fdata.value(i),
1253                blob_offset: blob_offset.value(i),
1254                blob_size: blob_size.value(i),
1255                uncompressed_size: usize_col.value(i),
1256                compressed: compressed.value(i),
1257                checksum: ck,
1258            });
1259        }
1260    }
1261    out.sort_by_key(|c| c.chunk_seq);
1262    Ok(out)
1263}
1264
1265pub fn is_probably_compressed(path: &Path) -> bool {
1266    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
1267        let ext = ext.to_ascii_lowercase();
1268        matches!(
1269            ext.as_str(),
1270            "zip" | "gz" | "bz2" | "xz" | "lz" | "lzma" | "7z" | "rar" | "cab"
1271                | "jar" | "war" | "ear" | "zst" | "sz" | "lz4" | "tgz" | "txz"
1272                | "tbz" | "apk" | "dmg" | "deb" | "rpm" | "arrow" | "mpeg" | "mpg"
1273                | "jpeg" | "jpg" | "gif" | "bmp" | "png" | "crate" | "znippy"
1274                | "zdata" | "parquet" | "webp" | "webm"
1275                // already-compressed / high-entropy payloads (Skidbladnir bundles
1276                // carry these): age = encrypted (never shrinks), iso = squashfs
1277                // (already xz/zstd), pdf = Flate streams. NB: pg_dump plain-SQL
1278                // (`.dump`/`.sql`) is deliberately NOT here — it compresses well.
1279                | "age" | "iso" | "pdf"
1280                // git's pack directory — the bulk of any real `.git`, and of
1281                // gunnar's cold tier. `pack` holds deflated objects; `idx`,
1282                // `midx` and `bitmap` hold object ids (hash output) and EWAH
1283                // bitmaps, all incompressible. NB: `.rev` is deliberately NOT
1284                // here — it is a permutation of 0..N as big-endian u32s, whose
1285                // high bytes are mostly zero, so it genuinely does compress.
1286                | "pack" | "idx" | "midx" | "bitmap"
1287        )
1288    } else {
1289        false
1290    }
1291}
1292
1293/// The name-only decision, kept as the fast path it has always been.
1294///
1295/// This is step 2 of the policy in [`crate::precompressed`] — it sees a path and
1296/// nothing else, so it cannot reach an entry that carries no extension (a git
1297/// loose object is named for its oid) and it believes a name that lies. Callers
1298/// holding real bytes should go through
1299/// [`SkipPolicy`](crate::precompressed::SkipPolicy), which runs this first and
1300/// then refines it with a magic-byte probe.
1301pub fn should_skip_compression(path: &Path) -> bool {
1302    is_probably_compressed(path)
1303}
1304
1305#[cfg(test)]
1306mod skip_compression_tests {
1307    use super::*;
1308
1309    #[test]
1310    fn skips_already_compressed_and_encrypted() {
1311        for p in ["secrets/secrets.age", "infra/talos/talos-1.13.iso", "s3/doc.pdf", "x.PDF"] {
1312            assert!(should_skip_compression(Path::new(p)), "should skip {p}");
1313        }
1314    }
1315
1316    #[test]
1317    fn compresses_plain_dump_and_config() {
1318        // pg_dump plain-SQL + declarative config must still be compressed.
1319        for p in ["dbdump/njord.dump", "njord.sql", "lakespec.json", "njordconf/serverspec.json"] {
1320            assert!(!should_skip_compression(Path::new(p)), "should compress {p}");
1321        }
1322    }
1323
1324    /// A packfile and its index are the two largest things in any real `.git`,
1325    /// and neither was on the extension table.
1326    #[test]
1327    fn skips_git_pack_directory_artefacts() {
1328        for p in [
1329            ".git/objects/pack/pack-9f2c.pack",
1330            ".git/objects/pack/pack-9f2c.idx",
1331            ".git/objects/pack/multi-pack-index.midx",
1332            ".git/objects/pack/pack-9f2c.bitmap",
1333        ] {
1334            assert!(should_skip_compression(Path::new(p)), "should skip {p}");
1335        }
1336    }
1337
1338    /// The pack directory is not uniformly incompressible, and the table must
1339    /// not be widened to the whole directory. `.rev` is a permutation of
1340    /// `0..N` as big-endian u32s — its high bytes are mostly zero.
1341    #[test]
1342    fn still_compresses_the_compressible_git_artefacts() {
1343        for p in [
1344            ".git/objects/pack/pack-9f2c.rev",
1345            ".git/objects/pack/pack-9f2c.promisor",
1346            ".git/COMMIT_EDITMSG",
1347            ".git/config",
1348        ] {
1349            assert!(!should_skip_compression(Path::new(p)), "should compress {p}");
1350        }
1351    }
1352}
1353
1354#[derive(Debug, Default)]
1355pub struct VerifyReport {
1356    pub total_files: usize,
1357    pub verified_files: usize,
1358    pub corrupt_files: usize,
1359    pub total_bytes: u64,
1360    pub verified_bytes: u64,
1361    pub corrupt_bytes: u64,
1362    pub chunks: u64,
1363}
1364
1365pub fn list_archive_contents(path: &Path) -> Result<()> {
1366    let (_schema, batches) = read_znippy_index(path)?;
1367    for batch in &batches {
1368        let paths = batch
1369            .column_by_name("relative_path")
1370            .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>())
1371            .ok_or_else(|| anyhow::anyhow!("missing relative_path column"))?;
1372        let sizes = batch
1373            .column_by_name("uncompressed_size")
1374            .and_then(|c| c.as_any().downcast_ref::<arrow::array::UInt64Array>())
1375            .ok_or_else(|| anyhow::anyhow!("missing uncompressed_size column"))?;
1376        let chunk_seqs = batch
1377            .column_by_name("chunk_seq")
1378            .and_then(|c| c.as_any().downcast_ref::<arrow::array::UInt32Array>());
1379        let group_ids = batch
1380            .column_by_name("group_id")
1381            .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1382        let artifact_ids = batch
1383            .column_by_name("artifact_id")
1384            .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1385        let versions = batch
1386            .column_by_name("version")
1387            .and_then(|c| c.as_any().downcast_ref::<arrow::array::StringArray>());
1388        for i in 0..batch.num_rows() {
1389            // Only print once per file (chunk_seq == 0)
1390            if let Some(seqs) = chunk_seqs {
1391                if seqs.value(i) != 0 {
1392                    continue;
1393                }
1394            }
1395            if let (Some(g), Some(a), Some(v)) = (group_ids, artifact_ids, versions) {
1396                if !g.is_null(i) {
1397                    println!(
1398                        "{}\t{}\t{}:{}:{}",
1399                        paths.value(i),
1400                        sizes.value(i),
1401                        g.value(i),
1402                        a.value(i),
1403                        v.value(i)
1404                    );
1405                    continue;
1406                }
1407            }
1408            println!("{}\t{}", paths.value(i), sizes.value(i));
1409        }
1410    }
1411    Ok(())
1412}
1413
1414pub fn verify_archive_integrity(path: &Path) -> Result<VerifyReport> {
1415    let out_dir = PathBuf::from("/dev/null");
1416    decompress_archive(path, false, &out_dir)
1417}
1418
1419#[cfg(test)]
1420mod version_tests {
1421    use super::*;
1422
1423    #[test]
1424    fn current_and_older_versions_are_accepted() {
1425        let mut m = HashMap::new();
1426        // No version recorded (legacy / pre-version archives): read as before.
1427        check_format_version(&m).unwrap();
1428        // Exactly the supported version.
1429        m.insert(FORMAT_VERSION_KEY.into(), ZNIPPY_FORMAT_VERSION.to_string());
1430        check_format_version(&m).unwrap();
1431        // An older version.
1432        m.insert(FORMAT_VERSION_KEY.into(), (ZNIPPY_FORMAT_VERSION - 1).to_string());
1433        check_format_version(&m).unwrap();
1434    }
1435
1436    #[test]
1437    fn newer_version_is_rejected_clearly() {
1438        let mut m = HashMap::new();
1439        m.insert(FORMAT_VERSION_KEY.into(), (ZNIPPY_FORMAT_VERSION + 1).to_string());
1440        let err = check_format_version(&m).unwrap_err().to_string();
1441        assert!(err.contains("newer than this reader supports"), "got: {err}");
1442        assert!(err.contains("upgrade znippy"), "got: {err}");
1443    }
1444
1445    #[test]
1446    fn writer_records_the_current_version() {
1447        let meta = build_arrow_metadata_for_config(&crate::common_config::CONFIG);
1448        assert_eq!(
1449            meta.get(FORMAT_VERSION_KEY).map(String::as_str),
1450            Some(ZNIPPY_FORMAT_VERSION.to_string().as_str())
1451        );
1452    }
1453}
1454
1455#[cfg(test)]
1456mod checksum_width_tests {
1457    use super::*;
1458    use arrow::array::FixedSizeBinaryArray;
1459
1460    /// `FixedSizeBinaryArray` is ONE concrete Arrow type for every width, so the
1461    /// `downcast_ref::<FixedSizeBinaryArray>()` in `decode_lookup` /
1462    /// `locate_file_via_index` succeeds just as happily for a hostile archive
1463    /// declaring `FixedSizeBinary(16)`. The old code then did
1464    /// `[0u8; 32].copy_from_slice(col.value(i))`, which panics — a process abort
1465    /// driven purely by an attacker-supplied schema, on the `znippy get` path.
1466    #[test]
1467    fn narrow_checksum_column_errors_instead_of_panicking() {
1468        let narrow = FixedSizeBinaryArray::try_from_iter([[0u8; 16]].into_iter()).unwrap();
1469        assert_eq!(narrow.value_length(), 16);
1470        let err = checksum32(&narrow, 0).expect_err("a 16-byte checksum column must be an Err");
1471        assert!(
1472            err.to_string().contains("width 16"),
1473            "error must name the bad width, got: {err}"
1474        );
1475    }
1476
1477    #[test]
1478    fn wide_checksum_column_errors_instead_of_truncating() {
1479        let wide = FixedSizeBinaryArray::try_from_iter([[7u8; 64]].into_iter()).unwrap();
1480        assert!(checksum32(&wide, 0).is_err(), "a 64-byte checksum column must be an Err");
1481    }
1482
1483    #[test]
1484    fn correct_width_checksum_is_read_verbatim() {
1485        let mut digest = [0u8; 32];
1486        for (i, b) in digest.iter_mut().enumerate() {
1487            *b = i as u8;
1488        }
1489        let col = FixedSizeBinaryArray::try_from_iter([digest].into_iter()).unwrap();
1490        assert_eq!(checksum32(&col, 0).unwrap(), digest);
1491    }
1492}
1493
1494#[cfg(test)]
1495mod reserved_module_tests {
1496    use super::*;
1497
1498    /// The regression this guards is specific and it has teeth: a module name
1499    /// that the sink writes with `RESERVED_PKG_TYPE` but that
1500    /// [`is_reserved_module`] does not recognise is classified as a **data**
1501    /// sub-index. `read_multi_index` then merges its rows into the file index and
1502    /// `read_znippy_manifest` reports it as a data section — corrupting `list`,
1503    /// `decompress`, the iceberg sink and every manifest-count assertion.
1504    ///
1505    /// So the assertion is not "the constant exists"; it is "every reserved
1506    /// module name in the catalog is classified reserved, and nothing else is".
1507    #[test]
1508    fn every_reserved_module_is_classified_reserved() {
1509        for m in RESERVED_MODULES {
1510            assert!(
1511                is_reserved_module(m),
1512                "'{m}' is in RESERVED_MODULES but is_reserved_module says it is DATA — \
1513                 its rows would be merged into the file index"
1514            );
1515        }
1516    }
1517
1518    /// The three `git` package-format modules, named literally. If someone
1519    /// removes one from [`RESERVED_MODULES`], the loop above still passes
1520    /// (it iterates whatever is left) — this is the test that goes red.
1521    #[test]
1522    fn the_git_format_modules_are_reserved() {
1523        for m in [
1524            GUNNAR_OID_MODULE,
1525            GUNNAR_GRAPH_MODULE,
1526            GUNNAR_REACH_MODULE,
1527            GUNNAR_REFS_MODULE,
1528            GUNNAR_SECRETS_MODULE,
1529        ] {
1530            assert!(is_reserved_module(m), "git package-format module '{m}' must be reserved");
1531            assert!(
1532                RESERVED_MODULES.contains(&m),
1533                "git package-format module '{m}' must be in the catalog"
1534            );
1535        }
1536        assert_eq!(GUNNAR_OID_MODULE, "__gunnar_oid__");
1537        assert_eq!(GUNNAR_GRAPH_MODULE, "__gunnar_graph__");
1538        assert_eq!(GUNNAR_REACH_MODULE, "__gunnar_reach__");
1539        assert_eq!(GUNNAR_REFS_MODULE, "__gunnar_refs__");
1540        assert_eq!(GUNNAR_SECRETS_MODULE, "__gunnar_secrets__");
1541    }
1542
1543    /// The other direction: a data module must NOT be swept up as reserved, or
1544    /// its file rows would silently vanish from `list` and `decompress`.
1545    #[test]
1546    fn ordinary_module_names_stay_data() {
1547        for m in ["maven", "git", "rust", "", "__gunnar__", "gunnar_oid", "__gunnar_oid", "objects"] {
1548            assert!(!is_reserved_module(m), "'{m}' must be treated as a DATA sub-index");
1549        }
1550    }
1551
1552    /// No duplicates and no accidental empty entry in the catalog.
1553    #[test]
1554    fn the_catalog_is_well_formed() {
1555        let mut seen = std::collections::HashSet::new();
1556        for m in RESERVED_MODULES {
1557            assert!(!m.is_empty(), "empty reserved module name");
1558            assert!(seen.insert(*m), "duplicate reserved module name '{m}'");
1559        }
1560        assert_eq!(seen.len(), RESERVED_MODULES.len());
1561    }
1562}