Skip to main content

stt_core/
pack.rs

1//! STT **packed format** — a multi-object, edge-cacheable container.
2//!
3//! Replaces the single-file v4 archive (`ArchiveWriter`) as
4//! the canonical write path. A single-file archive cannot be edge-cached once it
5//! exceeds the CDN per-object limit (Cloudflare = 512 MB): every range request
6//! hits origin forever. The packed format makes the *cacheable unit a small
7//! object, not the whole dataset* — tile blobs are split into many
8//! content-addressed **pack** objects (each `≤ pack_target_bytes`) plus a tiny
9//! mutable manifest. A dumb CDN caches each immutable pack natively; no Worker,
10//! no vendor lock-in.
11//!
12//! ## On-disk layout (per dataset)
13//!
14//! ```text
15//! <out_dir>/
16//!   manifest.json            tiny, MUTABLE   → short TTL
17//!   index/<blake3>.sttd      directory blob  → IMMUTABLE (content-addressed)
18//!   packs/<blake3>.sttp      tile blob data  → IMMUTABLE (content-addressed)
19//!   packs/<blake3>.sttp
20//!   ...
21//! ```
22//!
23//! Packs and the directory are content-addressed (blake3, 128-bit → 32 hex
24//! chars) so their bytes never change without their name changing. The directory
25//! is the v5 codec ([`crate::directory`]): per-run `pack_id` column +
26//! pack-relative offsets. See `docs/spec/stt-packed-format.md` for the full
27//! contract.
28//!
29//! [`PackWriter`] reuses the dedup / per-blob-zstd / curve-ordering logic of
30//! `ArchiveWriter::finalize_buffered`, then cuts the ordered, deduped blob stream
31//! into packs. [`PackedReader`] is the local-file reader (the TS reader handles
32//! remote/HTTP); it mirrors `ArchiveReader` semantics.
33
34use crate::compression;
35use crate::directory::TileEntry;
36use crate::curve::BlobOrdering;
37use crate::error::{Error, Result};
38use crate::metadata::Metadata;
39use crate::tile::TileId;
40use crate::types::Compression;
41use memmap2::Mmap;
42use rayon::prelude::*;
43use serde::{Deserialize, Serialize};
44use std::collections::HashMap;
45use std::fs::{self, File, OpenOptions};
46use std::io::Write;
47use std::path::{Path, PathBuf};
48
49/// `format` discriminator written into every packed manifest.
50pub const PACKED_FORMAT: &str = "stt-packed";
51
52/// Packed-format version (the manifest schema, distinct from the directory
53/// codec's [`crate::directory::DIRECTORY_VERSION`]).
54pub const PACKED_FORMAT_VERSION: u32 = 1;
55
56/// Default pack target size — 64 MiB. Well under the 512 MB CDN per-object cap,
57/// with enough granularity for fine cache + parallel range reads.
58pub const DEFAULT_PACK_TARGET_BYTES: u64 = 64 * 1024 * 1024;
59
60/// CRC32C integrity tag for a compressed blob (mirrors the archive writer).
61fn crc32c_tag(bytes: &[u8]) -> u32 {
62    crc32c::crc32c(bytes)
63}
64
65/// blake3 content address, 128-bit → 32 lowercase hex chars.
66fn blake3_128_hex(bytes: &[u8]) -> String {
67    let hash = blake3::hash(bytes);
68    // Take the first 16 bytes (128 bits) of the 256-bit digest.
69    hash.as_bytes()[..16]
70        .iter()
71        .map(|b| format!("{b:02x}"))
72        .collect()
73}
74
75// ----------------------------------------------------------------------------
76// Manifest
77// ----------------------------------------------------------------------------
78
79/// At-rest encoding value for a zstd-compressed directory object.
80pub const DIRECTORY_ENCODING_ZSTD: &str = "zstd";
81
82/// `directory.layout` value for the paged container (root page + leaf pages,
83/// each independently framed). Absent or `"single"` = the whole-load v5 object.
84pub const DIRECTORY_LAYOUT_PAGED: &str = "paged";
85/// `directory.layout` value for the single whole-load object (the default).
86pub const DIRECTORY_LAYOUT_SINGLE: &str = "single";
87
88/// Pointer to the encoded directory object.
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct DirectoryRef {
91    /// Object key, relative to the dataset root (e.g. `index/<hash>.sttd`).
92    pub key: String,
93    /// Directory object length in bytes (the at-rest object, i.e. the
94    /// compressed length when `encoding` is set).
95    pub length: u64,
96    /// Directory codec version (`5` for the packed format). The leaf pages of a
97    /// paged directory are this same v5 codec — `layout` (below), not this
98    /// version, discriminates the container shape.
99    #[serde(rename = "directoryVersion")]
100    pub directory_version: u8,
101    /// At-rest encoding of the directory object. `Some("zstd")` means the
102    /// object bytes are a zstd frame wrapping the codec bytes; absent (the
103    /// shape every pre-encoding manifest has) means raw codec bytes. For a
104    /// paged directory it describes the framing of **each page** (root + every
105    /// leaf), not one frame over the whole object. The content address and
106    /// `length` always describe the at-rest bytes.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub encoding: Option<String>,
109    /// Container layout. `Some("paged")` = a root page + leaf pages (Wave 2);
110    /// absent or `Some("single")` = the single whole-load object. Readers that
111    /// don't know `"paged"` fail loudly (the root's first byte isn't a valid v5
112    /// directory version), which is why readers ship before any paged dataset.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub layout: Option<String>,
115    /// At-rest byte length of the root page (a prefix of the object). Present
116    /// iff `layout == "paged"`; the reader range-GETs `bytes=0-(rootLength-1)`
117    /// for the root, then leaf ranges on demand.
118    #[serde(default, rename = "rootLength", skip_serializing_if = "Option::is_none")]
119    pub root_length: Option<u64>,
120    /// Number of leaf pages (informational / validation). Paged only.
121    #[serde(default, rename = "pageCount", skip_serializing_if = "Option::is_none")]
122    pub page_count: Option<u64>,
123    /// Nominal entries-per-page used at build (informational). Paged only.
124    #[serde(default, rename = "pageEntries", skip_serializing_if = "Option::is_none")]
125    pub page_entries: Option<u64>,
126}
127
128impl DirectoryRef {
129    /// Is this a paged-container directory?
130    pub fn is_paged(&self) -> bool {
131        self.layout.as_deref() == Some(DIRECTORY_LAYOUT_PAGED)
132    }
133}
134
135/// Pointer to one pack object. The position in `Manifest::packs` **is** the
136/// `pack_id` the directory references.
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct PackRef {
139    /// Object key, relative to the dataset root (e.g. `packs/<hash>.sttp`).
140    pub key: String,
141    /// Pack object length in bytes.
142    pub length: u64,
143}
144
145/// The packed-format `manifest.json` — the only mutable object per dataset.
146///
147/// Folds the metadata, directory pointer and pack table into one tiny JSON so a
148/// cold reader needs exactly one manifest + one directory + N pack-range fetches
149/// (no separate header or metadata object).
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct Manifest {
152    /// Always [`PACKED_FORMAT`] (`"stt-packed"`).
153    pub format: String,
154    /// Manifest schema version.
155    #[serde(rename = "formatVersion")]
156    pub format_version: u32,
157    /// Blob compression codec (always `"zstd"`, per-blob, no shared dict).
158    pub compression: String,
159    /// Pointer to the encoded directory object.
160    pub directory: DirectoryRef,
161    /// Pack table. Index == `pack_id`.
162    pub packs: Vec<PackRef>,
163    /// The full `crate::metadata::Metadata` JSON, verbatim.
164    pub metadata: Metadata,
165}
166
167impl Manifest {
168    /// Parse a manifest from its JSON bytes.
169    pub fn from_json_bytes(bytes: &[u8]) -> Result<Self> {
170        serde_json::from_slice(bytes)
171            .map_err(|e| Error::InvalidArchive(format!("manifest JSON decode failed: {e}")))
172    }
173
174    /// Serialise the manifest to pretty JSON bytes.
175    pub fn to_json_bytes(&self) -> Result<Vec<u8>> {
176        serde_json::to_vec_pretty(self)
177            .map_err(|e| Error::Other(format!("manifest JSON encode failed: {e}")))
178    }
179}
180
181// ----------------------------------------------------------------------------
182// Writer
183// ----------------------------------------------------------------------------
184
185/// A tile buffered for deferred ordering + per-blob compression + pack-cutting.
186struct PendingTile {
187    z: u8,
188    x: u32,
189    y: u32,
190    hilbert: u64,
191    time_start: i64,
192    time_end: i64,
193    cover_t_min: Option<i64>,
194    feature_count: u32,
195    temporal_bucket_ms: Option<u64>,
196    payload: Vec<u8>,
197}
198
199/// Writer for the multi-object packed format.
200///
201/// Consumes an `(id, payload)` stream like `ArchiveWriter`,
202/// buffering every tile until [`finalize`](Self::finalize). At finalize it
203/// reuses the buffered-writer pipeline — resolve [`BlobOrdering::Auto`], sort by
204/// the space-time curve key, per-blob zstd (NO shared dictionary, so the fzstd
205/// TS reader can decode), byte-identical dedup via blake3 — then cuts the
206/// ordered/deduped blob stream into packs of `≤ pack_target_bytes`, never
207/// splitting a blob, and writes content-addressed `packs/*.sttp` +
208/// `index/*.sttd` + `manifest.json`.
209pub struct PackWriter {
210    out_dir: PathBuf,
211    ordering: BlobOrdering,
212    pack_target_bytes: u64,
213    pending: Vec<PendingTile>,
214    /// `Some(k)` → emit a **paged** directory (root + leaf pages of ≤ `k`
215    /// entries; see [`crate::directory_page`]); `None` → the single whole-load
216    /// v5 directory (the default). Set via [`with_paging`](Self::with_paging).
217    page_entries: Option<usize>,
218    /// zstd level for per-blob + directory compression. Defaults to
219    /// [`compression::ZSTD_LEVEL`]; a publish build raises it via
220    /// [`with_zstd_level`](Self::with_zstd_level). Decode is level-independent,
221    /// so this only trades build CPU for smaller on-the-wire bytes.
222    zstd_level: i32,
223}
224
225impl PackWriter {
226    /// Create a packed-format writer targeting `out_dir`.
227    ///
228    /// `out_dir` (and its `index/` + `packs/` subdirs) are created on
229    /// [`finalize`](Self::finalize). `ordering` controls the on-disk blob byte
230    /// order ([`BlobOrdering::Auto`] resolves per-dataset at finalize);
231    /// `pack_target_bytes` is the soft per-pack size cap — a single blob larger
232    /// than the target gets its own pack rather than being split.
233    pub fn create<P: AsRef<Path>>(
234        out_dir: P,
235        ordering: BlobOrdering,
236        pack_target_bytes: u64,
237    ) -> Result<Self> {
238        Ok(Self {
239            out_dir: out_dir.as_ref().to_path_buf(),
240            ordering,
241            pack_target_bytes: pack_target_bytes.max(1),
242            pending: Vec::new(),
243            page_entries: None,
244            zstd_level: compression::ZSTD_LEVEL,
245        })
246    }
247
248    /// Opt into a **paged** directory: the `.sttd` becomes a root page + leaf
249    /// pages of ≤ `page_entries` entries each, so a cold reader fetches only the
250    /// leaves its viewport/time-window touches (Wave 2). `None` (the default)
251    /// emits the single whole-load v5 directory — byte-identical output to a
252    /// pre-paging build. `Some(0)` is clamped to 1.
253    pub fn with_paging(mut self, page_entries: Option<usize>) -> Self {
254        self.page_entries = page_entries.map(|k| k.max(1));
255        self
256    }
257
258    /// Set the zstd compression level for tile blobs and the directory.
259    ///
260    /// The packed format is write-once / serve-many, so the higher build CPU of
261    /// a level like 19 is paid once while the smaller bytes are paid on every
262    /// fetch (measured −10..19% vs the level-3 default; decode is unaffected).
263    /// Clamped to zstd's valid 1..=22 range. The default
264    /// ([`compression::ZSTD_LEVEL`]) reproduces byte-identical pre-existing builds.
265    pub fn with_zstd_level(mut self, level: i32) -> Self {
266        self.zstd_level = level.clamp(1, compression::ZSTD_LEVEL_MAX);
267        self
268    }
269
270    /// Add a tile carrying the full directory metadata. Same shape as
271    /// `ArchiveWriter::add_tile_full`: `cover_t_min` is the
272    /// tight lower covering bound (`None` to omit), `temporal_bucket_ms` tags the
273    /// directory entry with the temporal bucket size the tile represents. The
274    /// `payload` is the uncompressed tile frame.
275    #[allow(clippy::too_many_arguments)]
276    pub fn add_tile_full(
277        &mut self,
278        id: &TileId,
279        time_start: i64,
280        time_end: i64,
281        cover_t_min: Option<i64>,
282        feature_count: u32,
283        temporal_bucket_ms: Option<u64>,
284        payload: &[u8],
285    ) -> Result<()> {
286        self.pending.push(PendingTile {
287            z: id.z,
288            x: id.x,
289            y: id.y,
290            hilbert: id.hilbert_index(),
291            time_start,
292            time_end,
293            cover_t_min,
294            feature_count,
295            temporal_bucket_ms,
296            payload: payload.to_vec(),
297        });
298        Ok(())
299    }
300
301    /// Number of tiles buffered so far.
302    pub fn tile_count(&self) -> usize {
303        self.pending.len()
304    }
305
306    /// Finalise: order + dedup + per-blob zstd, cut packs, write
307    /// `packs/*.sttp` + `index/*.sttd` + `manifest.json` into `out_dir`.
308    ///
309    /// Mirrors `ArchiveWriter::finalize_buffered`: the same time-bucket calc,
310    /// [`BlobOrdering::Auto`] → [`BlobOrdering::choose`] resolution, space-time
311    /// sort key, per-blob `compress_zstd_with_dict(_, None)` (no shared dict),
312    /// and blake3 byte-identical dedup. THEN the ordered, deduped blob stream is
313    /// cut into packs.
314    pub fn finalize(self, metadata: &Metadata) -> Result<Manifest> {
315        let PackWriter {
316            out_dir,
317            ordering,
318            pack_target_bytes,
319            mut pending,
320            page_entries,
321            zstd_level,
322        } = self;
323
324        // --- Blob ordering (identical to finalize_buffered) ---------------
325        let base_bucket = metadata.temporal_bucket_ms.max(1) as i64;
326        let tb = |p: &PendingTile| {
327            let b = p
328                .temporal_bucket_ms
329                .map(|v| v as i64)
330                .unwrap_or(base_bucket)
331                .max(1);
332            p.time_start.div_euclid(b)
333        };
334        let (tb_min, tb_max) = pending.iter().fold((i64::MAX, i64::MIN), |(lo, hi), p| {
335            let t = tb(p);
336            (lo.min(t), hi.max(t))
337        });
338        let tb_span = if pending.is_empty() { 0 } else { tb_max - tb_min };
339        // Resolve Auto from the dataset's space-vs-time cardinality.
340        let ordering = match ordering {
341            BlobOrdering::Auto => {
342                let max_z = pending.iter().map(|p| p.z).max().unwrap_or(0) as u32;
343                let time_bits = crate::curve::bits_for((tb_span.max(0) + 1) as u64);
344                BlobOrdering::choose(max_z, time_bits)
345            }
346            other => other,
347        };
348        // The curve key alone is not total (base and temporal-LOD tiles of one
349        // cell tie; the 21-bit cube cap can collide), and `pending` arrives in
350        // whatever order the (possibly parallel) tiler produced — so a total
351        // tiebreak makes the blob byte order, and therefore every content
352        // address, reproducible across identical rebuilds. Immutable-pack CDN
353        // caching depends on that: a rebuild of unchanged data must re-derive
354        // the same pack names.
355        pending.sort_by_key(|p| {
356            (
357                crate::curve::space_time_key(
358                    ordering,
359                    p.z,
360                    p.x,
361                    p.y,
362                    p.hilbert,
363                    p.time_start,
364                    tb(p),
365                    tb_min,
366                    tb_span,
367                ),
368                p.z,
369                p.x,
370                p.y,
371                p.time_start,
372                p.temporal_bucket_ms,
373            )
374        });
375
376        // --- Per-blob zstd + byte-identical dedup ------------------------
377        // Each pending tile is compressed (NO shared dictionary, so the fzstd TS
378        // reader can decode). Byte-identical compressed blobs collapse to a
379        // single physical blob — but, unlike the single-file writer, we DON'T
380        // assign byte offsets yet: pack assignment happens after dedup so a
381        // shared blob lands in exactly one pack.
382        struct Blob {
383            compressed: Vec<u8>,
384            uncompressed_size: u32,
385            crc: u32,
386        }
387        let mut blobs: Vec<Blob> = Vec::new();
388        // blake3(compressed) → blob index in `blobs`.
389        let mut blob_dedup: HashMap<[u8; 32], usize> = HashMap::new();
390        // Per pending tile (in sorted order): which blob it references.
391        let mut tile_blob: Vec<usize> = Vec::with_capacity(pending.len());
392        // Compress in parallel, dedup sequentially. zstd at a high level
393        // (`--zstd-level`) is the build-time bottleneck and is embarrassingly
394        // parallel per blob; the dedup/index assignment that follows stays
395        // strictly sequential over the sorted order, so the output is
396        // byte-identical to a single-threaded build. Chunking caps peak memory
397        // at ~CHUNK compressed blobs (a whole-dataset parallel pass would hold
398        // every pre-dedup blob at once — pathological on dedup-heavy datasets).
399        const COMPRESS_CHUNK: usize = 8192;
400        for chunk in pending.chunks(COMPRESS_CHUNK) {
401            let compressed_chunk: Vec<Vec<u8>> = chunk
402                .par_iter()
403                .map(|p| compression::compress_zstd_with_dict_level(&p.payload, None, zstd_level))
404                .collect::<Result<Vec<_>>>()?;
405            for (p, compressed) in chunk.iter().zip(compressed_chunk) {
406                let key = *blake3::hash(&compressed).as_bytes();
407                let idx = if let Some(&i) = blob_dedup.get(&key) {
408                    i
409                } else {
410                    let i = blobs.len();
411                    let crc = crc32c_tag(&compressed);
412                    let uncompressed_size = p.payload.len() as u32;
413                    blobs.push(Blob {
414                        compressed,
415                        uncompressed_size,
416                        crc,
417                    });
418                    blob_dedup.insert(key, i);
419                    i
420                };
421                tile_blob.push(idx);
422            }
423        }
424
425        // --- Pack cutting -----------------------------------------------
426        // Walk the deduped blobs in their (first-seen, i.e. curve) order and cut
427        // into packs of ≤ pack_target_bytes. Never split a blob; a single blob
428        // larger than the target gets its own pack. pack_id is assigned in cut
429        // order; offset_in_pack resets to 0 per pack. Each blob is placed once,
430        // so a tile shared across time buckets resolves to one (pack, offset).
431        struct Placement {
432            pack_id: u32,
433            offset: u64,
434        }
435        let mut placements: Vec<Placement> = Vec::with_capacity(blobs.len());
436        // Pack contents: each pack is a contiguous slice of `blobs` indices.
437        let mut packs_blob_ranges: Vec<(usize, usize)> = Vec::new(); // (start, end) into blobs
438        if !blobs.is_empty() {
439            let mut pack_start = 0usize;
440            let mut pack_id = 0u32;
441            let mut cur_offset = 0u64;
442            for (i, blob) in blobs.iter().enumerate() {
443                let blen = blob.compressed.len() as u64;
444                // Cut BEFORE this blob if adding it would exceed the target and
445                // the current pack is non-empty (so a lone oversized blob still
446                // fits — it just owns a pack).
447                if i > pack_start && cur_offset + blen > pack_target_bytes {
448                    packs_blob_ranges.push((pack_start, i));
449                    pack_start = i;
450                    pack_id += 1;
451                    cur_offset = 0;
452                }
453                placements.push(Placement {
454                    pack_id,
455                    offset: cur_offset,
456                });
457                cur_offset += blen;
458            }
459            packs_blob_ranges.push((pack_start, blobs.len()));
460        }
461
462        // --- Build directory entries ------------------------------------
463        let mut entries: Vec<TileEntry> = Vec::with_capacity(pending.len());
464        for (p, &bi) in pending.iter().zip(tile_blob.iter()) {
465            let blob = &blobs[bi];
466            let pl = &placements[bi];
467            entries.push(TileEntry {
468                zoom: p.z,
469                x: p.x,
470                y: p.y,
471                time_start: p.time_start,
472                time_end: p.time_end,
473                pack_id: pl.pack_id,
474                offset: pl.offset,
475                length: blob.compressed.len() as u32,
476                uncompressed_size: blob.uncompressed_size,
477                feature_count: p.feature_count,
478                hilbert: p.hilbert,
479                crc32c: blob.crc,
480                temporal_bucket_ms: p.temporal_bucket_ms,
481                cover_t_min: p.cover_t_min,
482            });
483        }
484        // Directory codec order is (zoom, hilbert, time_start); the extra
485        // bucket key totalizes ties between a cell's base and temporal-LOD
486        // entries so the encoded directory is byte-reproducible too.
487        entries.sort_by_key(|e| (e.zoom, e.hilbert, e.time_start, e.temporal_bucket_ms));
488
489        // The manifest's totals are derived from the directory itself, not
490        // taken from the caller: `tile_count` = directory entries,
491        // `feature_count` = sum of per-entry counts (the same total
492        // stt-validate reports as `feature_count_index`). Deriving here keeps
493        // manifest and directory consistent by construction for every writer
494        // path — historically no caller set these and manifests shipped 0s.
495        let mut metadata = metadata.clone();
496        metadata.tile_count = entries.len() as u64;
497        metadata.feature_count = entries.iter().map(|e| u64::from(e.feature_count)).sum();
498
499        // --- Write objects ----------------------------------------------
500        fs::create_dir_all(&out_dir)?;
501        let index_dir = out_dir.join("index");
502        let packs_dir = out_dir.join("packs");
503        fs::create_dir_all(&index_dir)?;
504        fs::create_dir_all(&packs_dir)?;
505
506        // Write each pack to a temp file then atomically rename to its content
507        // address. Packs are immutable, so a re-sync skips an unchanged pack.
508        let mut pack_refs: Vec<PackRef> = Vec::with_capacity(packs_blob_ranges.len());
509        for (start, end) in &packs_blob_ranges {
510            let mut bytes: Vec<u8> = Vec::new();
511            for blob in &blobs[*start..*end] {
512                bytes.extend_from_slice(&blob.compressed);
513            }
514            let hex = blake3_128_hex(&bytes);
515            let rel = format!("packs/{hex}.sttp");
516            let final_path = out_dir.join(&rel);
517            write_atomic(&packs_dir, &final_path, &bytes)?;
518            pack_refs.push(PackRef {
519                key: rel,
520                length: bytes.len() as u64,
521            });
522        }
523
524        // Encode the directory. Both shapes are zstd-at-rest (declared via
525        // `directory.encoding`) — directories compress ~2x and sit on the
526        // cold-start critical path with no CDN content-encoding rescue:
527        //   - single (default): one zstd frame over the whole v5 codec buffer.
528        //   - paged (opt-in):   a root page + leaf pages, each its own zstd
529        //     frame, so a cold reader fetches only the leaves it touches. The
530        //     leaf codec is the same v5 directory.
531        // The object is content-addressed over its at-rest bytes either way.
532        let (index_bytes, directory_ref_fields): (Vec<u8>, _) = if let Some(k) = page_entries {
533            let paged =
534                crate::directory_page::encode_paged_directory_level(&entries, k, true, zstd_level)?;
535            (
536                paged.bytes,
537                (
538                    Some(DIRECTORY_LAYOUT_PAGED.to_string()),
539                    Some(paged.root_length),
540                    Some(paged.page_count as u64),
541                    Some(paged.page_entries as u64),
542                ),
543            )
544        } else {
545            let index_plain = crate::directory::encode_directory(&entries);
546            let bytes = compression::compress_zstd_with_dict_level(&index_plain, None, zstd_level)?;
547            (bytes, (None, None, None, None))
548        };
549        let index_hex = blake3_128_hex(&index_bytes);
550        let index_rel = format!("index/{index_hex}.sttd");
551        let index_path = out_dir.join(&index_rel);
552        write_atomic(&index_dir, &index_path, &index_bytes)?;
553
554        let (layout, root_length, page_count, page_entries_field) = directory_ref_fields;
555
556        // Build + write the manifest.
557        let manifest = Manifest {
558            format: PACKED_FORMAT.to_string(),
559            format_version: PACKED_FORMAT_VERSION,
560            compression: "zstd".to_string(),
561            directory: DirectoryRef {
562                key: index_rel,
563                length: index_bytes.len() as u64,
564                directory_version: crate::directory::DIRECTORY_VERSION,
565                encoding: Some(DIRECTORY_ENCODING_ZSTD.to_string()),
566                layout,
567                root_length,
568                page_count,
569                page_entries: page_entries_field,
570            },
571            packs: pack_refs,
572            metadata,
573        };
574        let manifest_bytes = manifest.to_json_bytes()?;
575        let manifest_path = out_dir.join("manifest.json");
576        let mut f = File::create(&manifest_path)?;
577        f.write_all(&manifest_bytes)?;
578        f.flush()?;
579
580        Ok(manifest)
581    }
582}
583
584/// Unwrap a directory object's at-rest encoding into raw codec bytes.
585/// `encoding` is the manifest's `directory.encoding`: absent = raw (every
586/// pre-encoding manifest), `"zstd"` = one zstd frame around the codec bytes.
587fn decode_directory_object(bytes: &[u8], encoding: Option<&str>) -> Result<Vec<u8>> {
588    match encoding {
589        None => Ok(bytes.to_vec()),
590        Some(DIRECTORY_ENCODING_ZSTD) => compression::decompress_zstd_with_dict(bytes, None),
591        Some(other) => Err(Error::InvalidArchive(format!(
592            "unknown directory encoding {other:?} (this reader supports absent or \"zstd\")"
593        ))),
594    }
595}
596
597/// Decode the full tile-entry list from a directory object's at-rest bytes,
598/// branching on the container layout. The single (whole-load) shape unwraps the
599/// at-rest encoding then runs the v5 codec; the paged shape decodes the root +
600/// every leaf (the local load-all path — a mmap'd file has no cold-start cost,
601/// so the paging *query* win lives in the TS HTTP reader). Used by the local
602/// `PackedReader` and `verify_packed_objects`.
603fn decode_directory_entries(bytes: &[u8], dref: &DirectoryRef) -> Result<Vec<TileEntry>> {
604    if dref.is_paged() {
605        let root_length = dref.root_length.ok_or_else(|| {
606            Error::InvalidArchive("paged directory: manifest missing rootLength".into())
607        })?;
608        let zstd = dref.encoding.as_deref() == Some(DIRECTORY_ENCODING_ZSTD);
609        crate::directory_page::decode_paged_directory(bytes, root_length, zstd)
610    } else {
611        let raw = decode_directory_object(bytes, dref.encoding.as_deref())?;
612        crate::directory::decode_directory(&raw)
613    }
614}
615
616/// Write `bytes` to a temp file inside `dir` then atomically rename to
617/// `final_path` (content-addressed, so an existing identical object is a no-op
618/// overwrite of the same bytes).
619fn write_atomic(dir: &Path, final_path: &Path, bytes: &[u8]) -> Result<()> {
620    // Unique temp name within the same directory so the rename is atomic.
621    let tmp = dir.join(format!(
622        ".tmp-{}-{}",
623        std::process::id(),
624        blake3_128_hex(bytes)
625    ));
626    {
627        let mut f = OpenOptions::new()
628            .write(true)
629            .create(true)
630            .truncate(true)
631            .open(&tmp)?;
632        f.write_all(bytes)?;
633        f.flush()?;
634    }
635    fs::rename(&tmp, final_path)?;
636    Ok(())
637}
638
639// ----------------------------------------------------------------------------
640// Integrity
641// ----------------------------------------------------------------------------
642
643/// Verify the on-disk integrity of a packed dataset against its manifest.
644///
645/// Because packs and the directory are **content-addressed**, integrity is a
646/// property anyone can check with no trusted side-channel: each object's bytes
647/// must blake3-hash to the name the manifest gave it, and its on-disk length
648/// must match the declared length. Additionally the directory must decode and
649/// reference no `pack_id` outside the manifest's pack table.
650///
651/// Returns the list of violations (empty ⇒ clean). Returns `Err` only when the
652/// manifest itself cannot be read or parsed (a missing referenced object is a
653/// reported violation, not an `Err`, so a full report is produced in one pass).
654pub fn verify_packed_objects<P: AsRef<Path>>(manifest_path: P) -> Result<Vec<String>> {
655    let manifest_path = manifest_path.as_ref();
656    let root = manifest_path
657        .parent()
658        .ok_or_else(|| Error::InvalidArchive("manifest path has no parent dir".into()))?;
659    let manifest = Manifest::from_json_bytes(&fs::read(manifest_path)?)?;
660
661    let mut issues = Vec::new();
662
663    if manifest.format != PACKED_FORMAT {
664        issues.push(format!(
665            "manifest format is {:?}, expected {PACKED_FORMAT:?}",
666            manifest.format
667        ));
668    }
669    if manifest.format_version != PACKED_FORMAT_VERSION {
670        issues.push(format!(
671            "manifest formatVersion is {}, expected {PACKED_FORMAT_VERSION}",
672            manifest.format_version
673        ));
674    }
675    if manifest.directory.directory_version != crate::directory::DIRECTORY_VERSION {
676        issues.push(format!(
677            "directoryVersion is {}, expected {}",
678            manifest.directory.directory_version,
679            crate::directory::DIRECTORY_VERSION
680        ));
681    }
682
683    // Each content-addressed object: name must equal blake3-128 of its bytes,
684    // and on-disk length must equal the declared length.
685    fn check_object(
686        root: &Path,
687        key: &str,
688        declared_len: u64,
689        prefix: &str,
690        ext: &str,
691        issues: &mut Vec<String>,
692    ) {
693        match fs::read(root.join(key)) {
694            Ok(bytes) => {
695                if bytes.len() as u64 != declared_len {
696                    issues.push(format!(
697                        "{key}: on-disk length {} != manifest-declared {declared_len}",
698                        bytes.len()
699                    ));
700                }
701                let expected = format!("{prefix}/{}.{ext}", blake3_128_hex(&bytes));
702                if key != expected {
703                    issues.push(format!(
704                        "{key}: content-address mismatch (bytes hash to {expected})"
705                    ));
706                }
707            }
708            Err(e) => issues.push(format!("{key}: cannot read object ({e})")),
709        }
710    }
711
712    check_object(
713        root,
714        &manifest.directory.key,
715        manifest.directory.length,
716        "index",
717        "sttd",
718        &mut issues,
719    );
720    for p in &manifest.packs {
721        check_object(root, &p.key, p.length, "packs", "sttp", &mut issues);
722    }
723
724    // Directory must decode (through its at-rest encoding + container layout)
725    // and reference only packs that exist.
726    match fs::read(root.join(&manifest.directory.key)) {
727        Ok(dir_bytes) => match decode_directory_entries(&dir_bytes, &manifest.directory) {
728            Ok(entries) => {
729                if let Some(max_pid) = entries.iter().map(|e| e.pack_id).max() {
730                    if max_pid as usize >= manifest.packs.len() {
731                        issues.push(format!(
732                            "directory references pack_id {max_pid} but the manifest lists only {} pack(s)",
733                            manifest.packs.len()
734                        ));
735                    }
736                }
737            }
738            Err(e) => issues.push(format!("directory failed to decode: {e}")),
739        },
740        // A read failure here is already reported by check_object above.
741        Err(_) => {}
742    }
743
744    // Paged directories: validate the container structure beyond plain decode —
745    // page descriptor bounds cover their leaf's entries (so a reader's prune
746    // never drops a matching tile) and cross-page key order is monotonic.
747    if manifest.directory.is_paged() {
748        match manifest.directory.root_length {
749            Some(rl) => {
750                if let Ok(dir_bytes) = fs::read(root.join(&manifest.directory.key)) {
751                    let zstd =
752                        manifest.directory.encoding.as_deref() == Some(DIRECTORY_ENCODING_ZSTD);
753                    match crate::directory_page::verify_paged_structure(&dir_bytes, rl, zstd) {
754                        Ok(mut more) => issues.append(&mut more),
755                        Err(e) => issues.push(format!("paged structure check failed: {e}")),
756                    }
757                }
758            }
759            None => issues.push("paged directory: manifest missing rootLength".into()),
760        }
761    }
762
763    Ok(issues)
764}
765
766// ----------------------------------------------------------------------------
767// Reader
768// ----------------------------------------------------------------------------
769
770/// One mapped pack, lazily loaded on first access.
771struct LoadedPack {
772    /// `None` until first read of a tile in this pack.
773    mmap: Option<Mmap>,
774    /// Absolute path to the pack object.
775    path: PathBuf,
776    /// Declared length from the manifest (for a bounds sanity check).
777    length: u64,
778}
779
780/// Reader for a **local** packed dataset. Remote/HTTP reads are the TS reader's
781/// job; this opens objects from the filesystem.
782///
783/// Mirrors `ArchiveReader`: [`entries`](Self::entries) returns
784/// the decoded v5 directory, [`metadata`](Self::metadata) the folded metadata,
785/// and [`read_payload`](Self::read_payload) selects the entry's pack, slices
786/// `[offset..offset+length]`, verifies CRC32C and decompresses the per-blob
787/// zstd. Packs are mmap'd lazily by `pack_id`.
788pub struct PackedReader {
789    entries: Vec<TileEntry>,
790    metadata: Metadata,
791    compression: Compression,
792    packs: Vec<std::cell::RefCell<LoadedPack>>,
793}
794
795impl PackedReader {
796    /// Open a packed dataset by its `manifest.json` path. The directory and pack
797    /// objects are resolved relative to the manifest's parent directory.
798    pub fn open<P: AsRef<Path>>(manifest_path: P) -> Result<Self> {
799        let manifest_path = manifest_path.as_ref();
800        let root = manifest_path
801            .parent()
802            .ok_or_else(|| Error::InvalidArchive("manifest path has no parent dir".into()))?
803            .to_path_buf();
804
805        let manifest_bytes = fs::read(manifest_path)?;
806        let manifest = Manifest::from_json_bytes(&manifest_bytes)?;
807
808        if manifest.format != PACKED_FORMAT {
809            return Err(Error::InvalidArchive(format!(
810                "not a packed manifest: format={:?} (expected {PACKED_FORMAT:?})",
811                manifest.format
812            )));
813        }
814        let compression = match manifest.compression.as_str() {
815            "zstd" => Compression::Zstd,
816            "none" => Compression::None,
817            other => {
818                return Err(Error::InvalidArchive(format!(
819                    "unknown packed compression {other:?}"
820                )))
821            }
822        };
823
824        // Load + decode the directory object. The single (whole-load) shape
825        // unwraps the at-rest encoding then runs the v5 codec; the paged shape
826        // decodes the root + every leaf (local load-all — a mmap'd file has no
827        // cold-start cost). Both branches return the same full entry list.
828        let dir_path = root.join(&manifest.directory.key);
829        let dir_bytes = fs::read(&dir_path)?;
830        let entries = decode_directory_entries(&dir_bytes, &manifest.directory)?;
831
832        // Prepare (lazy) pack handles in pack_id order.
833        let packs = manifest
834            .packs
835            .iter()
836            .map(|p| {
837                std::cell::RefCell::new(LoadedPack {
838                    mmap: None,
839                    path: root.join(&p.key),
840                    length: p.length,
841                })
842            })
843            .collect();
844
845        Ok(Self {
846            entries,
847            metadata: manifest.metadata,
848            compression,
849            packs,
850        })
851    }
852
853    /// All directory entries (sorted by zoom then Hilbert index).
854    pub fn entries(&self) -> &[TileEntry] {
855        &self.entries
856    }
857
858    /// Dataset metadata.
859    pub fn metadata(&self) -> &Metadata {
860        &self.metadata
861    }
862
863    /// Read and decompress a tile's raw payload bytes, verifying its CRC32C.
864    ///
865    /// Selects the pack by `entry.pack_id`, slices `[offset..offset+length]`
866    /// within it, checks the CRC, then decompresses the per-blob zstd. Mirrors
867    /// `ArchiveReader::read_payload`.
868    pub fn read_payload(&self, entry: &TileEntry) -> Result<Vec<u8>> {
869        let cell = self.packs.get(entry.pack_id as usize).ok_or_else(|| {
870            Error::InvalidArchive(format!(
871                "tile {:?} references pack {} but only {} packs exist",
872                entry.tile_id(),
873                entry.pack_id,
874                self.packs.len()
875            ))
876        })?;
877
878        let payload = {
879            let mut pack = cell.borrow_mut();
880            if pack.mmap.is_none() {
881                let file = File::open(&pack.path)?;
882                // SAFETY: read-only mapping of a file we never write through; the
883                // mapping is owned by the reader for its lifetime.
884                let mmap = unsafe { Mmap::map(&file) }
885                    .map_err(|e| Error::Other(format!("mmap failed: {e}")))?;
886                if mmap.len() as u64 != pack.length {
887                    return Err(Error::InvalidArchive(format!(
888                        "pack {} is {} bytes, manifest declared {}",
889                        pack.path.display(),
890                        mmap.len(),
891                        pack.length
892                    )));
893                }
894                pack.mmap = Some(mmap);
895            }
896            let mmap = pack.mmap.as_ref().expect("just loaded");
897
898            let start = entry.offset as usize;
899            let end = start + entry.length as usize;
900            if end > mmap.len() {
901                return Err(Error::InvalidArchive(format!(
902                    "tile {:?} blob range {start}..{end} exceeds pack size {}",
903                    entry.tile_id(),
904                    mmap.len()
905                )));
906            }
907            let compressed = &mmap[start..end];
908
909            if crc32c_tag(compressed) != entry.crc32c {
910                return Err(Error::InvalidArchive(format!(
911                    "tile {:?} failed integrity check (corrupt pack)",
912                    entry.tile_id()
913                )));
914            }
915
916            if self.compression == Compression::Zstd {
917                compression::decompress_zstd_with_dict(compressed, None)?
918            } else {
919                compression::decompress(compressed, self.compression)?
920            }
921        };
922
923        if payload.len() != entry.uncompressed_size as usize {
924            return Err(Error::InvalidArchive(format!(
925                "tile {:?} decompressed to {} bytes, expected {}",
926                entry.tile_id(),
927                payload.len(),
928                entry.uncompressed_size
929            )));
930        }
931        Ok(payload)
932    }
933
934    /// Read and decode a tile into its Arrow layers.
935    pub fn read_layers(&self, entry: &TileEntry) -> Result<Vec<crate::arrow_tile::DecodedLayer>> {
936        let payload = self.read_payload(entry)?;
937        crate::arrow_tile::decode_tile(&payload)
938    }
939}
940
941#[cfg(test)]
942mod tests {
943    use super::*;
944    use crate::arrow_tile::{encode_tile, ColumnarLayer, GeometryColumn};
945
946    fn point_layer(name: &str, ids: Vec<u64>, t0: i64) -> ColumnarLayer {
947        let n = ids.len();
948        ColumnarLayer {
949            name: name.to_string(),
950            feature_ids: ids,
951            start_times: vec![t0; n],
952            end_times: vec![t0 + 100; n],
953            geometry: GeometryColumn::Point(vec![[-122.4, 37.7]; n]),
954            vertex_times: None,
955            vertex_values: None,
956            triangles: None,
957            vertex_value_matrix: None,
958            properties: vec![],
959        }
960    }
961
962    /// Distinct-payload tile so each blob is unique (forces many packs at a tiny
963    /// target). `seed` perturbs the feature ids so compressed bytes differ.
964    fn distinct_tile(seed: u64) -> Vec<u8> {
965        let ids: Vec<u64> = (0..6).map(|i| seed * 100 + i).collect();
966        encode_tile(&[point_layer("default", ids, (seed as i64) * 7)]).unwrap()
967    }
968
969    #[test]
970    fn blake3_128_hex_is_32_chars() {
971        let h = blake3_128_hex(b"hello");
972        assert_eq!(h.len(), 32);
973        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
974    }
975
976    #[test]
977    fn manifest_json_roundtrips() {
978        let m = Manifest {
979            format: PACKED_FORMAT.to_string(),
980            format_version: PACKED_FORMAT_VERSION,
981            compression: "zstd".to_string(),
982            directory: DirectoryRef {
983                key: "index/abc.sttd".to_string(),
984                length: 42,
985                directory_version: 5,
986                encoding: Some(DIRECTORY_ENCODING_ZSTD.to_string()),
987                layout: None,
988                root_length: None,
989                page_count: None,
990                page_entries: None,
991            },
992            packs: vec![
993                PackRef { key: "packs/a.sttp".to_string(), length: 100 },
994                PackRef { key: "packs/b.sttp".to_string(), length: 200 },
995            ],
996            metadata: Metadata::new("manifest-test"),
997        };
998        let bytes = m.to_json_bytes().unwrap();
999        // The spec keys must be camelCase where renamed.
1000        let s = String::from_utf8(bytes.clone()).unwrap();
1001        assert!(s.contains("\"formatVersion\""), "{s}");
1002        assert!(s.contains("\"directoryVersion\""), "{s}");
1003        assert!(s.contains("\"stt-packed\""), "{s}");
1004        let back = Manifest::from_json_bytes(&bytes).unwrap();
1005        assert_eq!(back.format, m.format);
1006        assert_eq!(back.format_version, m.format_version);
1007        assert_eq!(back.packs.len(), 2);
1008        assert_eq!(back.directory.directory_version, 5);
1009        assert_eq!(back.directory.encoding.as_deref(), Some("zstd"));
1010        assert_eq!(back.metadata.name, "manifest-test");
1011
1012        // Backward compat: a pre-encoding manifest (no `encoding` key — the
1013        // shape of every deployed dataset) must parse with `encoding: None`,
1014        // and a None encoding must serialize without the key.
1015        let mut legacy_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1016        legacy_json["directory"]
1017            .as_object_mut()
1018            .unwrap()
1019            .remove("encoding");
1020        let legacy_back =
1021            Manifest::from_json_bytes(&serde_json::to_vec(&legacy_json).unwrap()).unwrap();
1022        assert_eq!(legacy_back.directory.encoding, None);
1023        let legacy_out =
1024            String::from_utf8(legacy_back.to_json_bytes().unwrap()).unwrap();
1025        assert!(!legacy_out.contains("\"encoding\""), "{legacy_out}");
1026    }
1027
1028    /// Full round-trip: 30 synthetic tiles (a couple byte-identical to exercise
1029    /// dedup) across 2 zooms + several time buckets, written with a tiny pack
1030    /// target to force multiple packs. Every payload must decode byte-identical.
1031    #[test]
1032    fn packwriter_roundtrips_through_multiple_packs() {
1033        let dir = tempfile::tempdir().unwrap();
1034        let out = dir.path().join("dataset");
1035
1036        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1037
1038        // Build 30 tiles. Tiles 0..28 distinct; the static one is reused so two
1039        // entries point at one byte-identical blob (dedup).
1040        let static_payload = encode_tile(&[point_layer("default", vec![7, 8, 9], 0)]).unwrap();
1041        let mut expected: Vec<(TileId, i64, i64, Vec<u8>)> = Vec::new();
1042        let bucket = 3_600_000i64;
1043        for k in 0..30u64 {
1044            let zoom = if k % 2 == 0 { 9u8 } else { 10u8 };
1045            let b = (k % 5) as i64; // several time buckets
1046            let t = b * bucket;
1047            let payload = if k == 13 || k == 27 {
1048                static_payload.clone() // two byte-identical → dedup
1049            } else {
1050                distinct_tile(k)
1051            };
1052            let id = TileId::new(zoom, (k % 7) as u32, (k / 7) as u32, t as u64);
1053            w.add_tile_full(&id, t, t + bucket - 1, Some(t), 6, Some(bucket as u64), &payload)
1054                .unwrap();
1055            expected.push((id, t, t + bucket - 1, payload));
1056        }
1057        assert_eq!(w.tile_count(), 30);
1058
1059        let meta = Metadata::new("packed-roundtrip").with_temporal_bucket_ms(bucket as u64);
1060        let manifest = w.finalize(&meta).unwrap();
1061
1062        // >1 pack produced at the tiny target.
1063        assert!(manifest.packs.len() > 1, "expected multiple packs, got {}", manifest.packs.len());
1064
1065        // Every pack file ≤ target, except a lone oversized blob owning a pack.
1066        for p in &manifest.packs {
1067            let bytes = fs::read(out.join(&p.key)).unwrap();
1068            assert_eq!(bytes.len() as u64, p.length);
1069            // A pack over target must contain exactly one blob (oversized loner).
1070            // We can't see blob boundaries here, but the cut rule guarantees a
1071            // pack only exceeds the target when it holds a single blob; the
1072            // round-trip below proves correctness regardless.
1073        }
1074
1075        // Pack/dir filenames are blake3-128 hex of their bytes.
1076        for p in &manifest.packs {
1077            let bytes = fs::read(out.join(&p.key)).unwrap();
1078            let hex = blake3_128_hex(&bytes);
1079            assert_eq!(p.key, format!("packs/{hex}.sttp"));
1080        }
1081        let dir_bytes = fs::read(out.join(&manifest.directory.key)).unwrap();
1082        assert_eq!(
1083            manifest.directory.key,
1084            format!("index/{}.sttd", blake3_128_hex(&dir_bytes))
1085        );
1086
1087        // pack_ids are contiguous from 0 across all entries.
1088        let reader = PackedReader::open(out.join("manifest.json")).unwrap();
1089        let max_pack = reader.entries().iter().map(|e| e.pack_id).max().unwrap();
1090        assert_eq!(max_pack as usize, manifest.packs.len() - 1);
1091        let observed: std::collections::BTreeSet<u32> =
1092            reader.entries().iter().map(|e| e.pack_id).collect();
1093        for pid in 0..manifest.packs.len() as u32 {
1094            assert!(observed.contains(&pid), "pack_id {pid} unused");
1095        }
1096
1097        // Metadata round-trips.
1098        assert_eq!(reader.metadata().name, "packed-roundtrip");
1099        assert_eq!(reader.metadata().temporal_bucket_ms, bucket as u64);
1100        assert_eq!(reader.entries().len(), 30);
1101
1102        // The manifest totals are derived from the directory at finalize —
1103        // the caller's Metadata left them 0 and finalize must overwrite them.
1104        assert_eq!(manifest.metadata.tile_count, 30);
1105        assert_eq!(manifest.metadata.feature_count, 30 * 6);
1106        assert_eq!(reader.metadata().tile_count, 30);
1107        assert_eq!(reader.metadata().feature_count, 30 * 6);
1108
1109        // Every tile's decompressed payload is byte-identical.
1110        for (id, ts, _te, payload) in &expected {
1111            let e = reader
1112                .entries()
1113                .iter()
1114                .find(|e| {
1115                    e.zoom == id.z && e.x == id.x && e.y == id.y && e.time_start == *ts
1116                })
1117                .expect("entry present");
1118            let got = reader.read_payload(e).unwrap();
1119            assert_eq!(&got, payload, "payload mismatch for {id:?}");
1120        }
1121
1122        // Dedup: the two static tiles share one (pack, offset).
1123        let static_entries: Vec<&TileEntry> = reader
1124            .entries()
1125            .iter()
1126            .filter(|e| {
1127                let g = reader.read_payload(e).unwrap();
1128                g == static_payload
1129            })
1130            .collect();
1131        assert_eq!(static_entries.len(), 2);
1132        assert_eq!(static_entries[0].pack_id, static_entries[1].pack_id);
1133        assert_eq!(static_entries[0].offset, static_entries[1].offset);
1134    }
1135
1136    /// A **paged** directory build round-trips end-to-end through
1137    /// `PackedReader`: every input tile's payload decodes byte-identically, the
1138    /// manifest carries the container fields, and content-address verification
1139    /// is clean. Separately, a paged and a single build of the same input agree
1140    /// on the payload-independent address keys (the cross-build *blob* bytes are
1141    /// not comparable — Arrow IPC schema-metadata ordering isn't reproducible
1142    /// across `finalize` runs, the documented D6 caveat; the codec-level
1143    /// "paged == whole-load" equality is proven in `directory_page` tests).
1144    #[test]
1145    fn paged_directory_writer_roundtrips_and_matches_single() {
1146        let bucket = 3_600_000i64;
1147        // Deterministic input tiles: (id, time_start, time_end, payload).
1148        let mut input: Vec<(TileId, i64, i64, Vec<u8>)> = Vec::new();
1149        for k in 0..120u64 {
1150            let zoom = [6u8, 10, 13][(k % 3) as usize];
1151            let b = (k % 4) as i64;
1152            let t = b * bucket;
1153            let id = TileId::new(zoom, (k % 11) as u32, (k / 11) as u32, t as u64);
1154            input.push((id, t, t + bucket - 1, distinct_tile(k)));
1155        }
1156        let build = |out: &Path, page_entries: Option<usize>| -> Manifest {
1157            let mut w = PackWriter::create(out, BlobOrdering::Auto, 16 * 1024)
1158                .unwrap()
1159                .with_paging(page_entries);
1160            for (id, ts, te, payload) in &input {
1161                w.add_tile_full(id, *ts, *te, Some(*ts), 6, Some(bucket as u64), payload)
1162                    .unwrap();
1163            }
1164            let meta = Metadata::new("paged-roundtrip").with_temporal_bucket_ms(bucket as u64);
1165            w.finalize(&meta).unwrap()
1166        };
1167
1168        let dir = tempfile::tempdir().unwrap();
1169        let single_out = dir.path().join("single");
1170        let paged_out = dir.path().join("paged");
1171        let single = build(&single_out, None);
1172        // Small page size to force several leaf pages over 120 entries.
1173        let paged = build(&paged_out, Some(16));
1174
1175        // Paged manifest carries the container fields; single does not.
1176        assert!(single.directory.layout.is_none());
1177        assert_eq!(paged.directory.layout.as_deref(), Some(DIRECTORY_LAYOUT_PAGED));
1178        assert!(paged.directory.root_length.unwrap() > 0);
1179        assert!(paged.directory.page_count.unwrap() >= 2, "expected multiple leaf pages");
1180        assert_eq!(paged.directory.page_entries, Some(16));
1181        assert_eq!(paged.directory.directory_version, crate::directory::DIRECTORY_VERSION);
1182        assert_eq!(paged.directory.encoding.as_deref(), Some(DIRECTORY_ENCODING_ZSTD));
1183
1184        let r_single = PackedReader::open(single_out.join("manifest.json")).unwrap();
1185        let r_paged = PackedReader::open(paged_out.join("manifest.json")).unwrap();
1186        assert_eq!(r_paged.entries().len(), 120);
1187        assert_eq!(r_single.entries().len(), 120);
1188
1189        // Cross-build agreement on payload-INDEPENDENT address keys (sorted, so
1190        // the comparison ignores blob-byte non-reproducibility).
1191        let keys = |r: &PackedReader| -> Vec<(u8, u32, u32, i64, i64, u32, Option<u64>, Option<i64>)> {
1192            let mut v: Vec<_> = r
1193                .entries()
1194                .iter()
1195                .map(|e| {
1196                    (
1197                        e.zoom, e.x, e.y, e.time_start, e.time_end, e.feature_count,
1198                        e.temporal_bucket_ms, e.cover_t_min,
1199                    )
1200                })
1201                .collect();
1202            v.sort();
1203            v
1204        };
1205        assert_eq!(keys(&r_single), keys(&r_paged));
1206
1207        // Every INPUT tile decodes byte-identically through the paged reader.
1208        for (id, ts, _te, payload) in &input {
1209            let e = r_paged
1210                .entries()
1211                .iter()
1212                .find(|x| x.zoom == id.z && x.x == id.x && x.y == id.y && x.time_start == *ts)
1213                .expect("paged entry present");
1214            assert_eq!(&r_paged.read_payload(e).unwrap(), payload, "payload mismatch {id:?}");
1215        }
1216
1217        // Content-address integrity verifies clean on the paged dataset.
1218        let issues = verify_packed_objects(paged_out.join("manifest.json")).unwrap();
1219        assert!(issues.is_empty(), "paged verify issues: {issues:?}");
1220    }
1221
1222    /// A single blob larger than the pack target gets its own pack (never split).
1223    #[test]
1224    fn oversized_blob_gets_its_own_pack() {
1225        let dir = tempfile::tempdir().unwrap();
1226        let out = dir.path().join("dataset");
1227
1228        // One big tile (lots of distinct points → big compressed blob) plus a
1229        // few small ones, with a target smaller than the big blob.
1230        let big_ids: Vec<u64> = (0..4000).collect();
1231        let big = encode_tile(&[ColumnarLayer {
1232            name: "default".to_string(),
1233            feature_ids: big_ids.clone(),
1234            start_times: vec![0; big_ids.len()],
1235            end_times: vec![100; big_ids.len()],
1236            geometry: GeometryColumn::Point(
1237                (0..big_ids.len()).map(|i| [i as f64 * 0.01, i as f64 * 0.013]).collect(),
1238            ),
1239            vertex_times: None,
1240            vertex_values: None,
1241            triangles: None,
1242            vertex_value_matrix: None,
1243            properties: vec![],
1244        }])
1245        .unwrap();
1246        let big_compressed_len = compression::compress_zstd_with_dict(&big, None).unwrap().len();
1247
1248        let mut w = PackWriter::create(&out, BlobOrdering::SpatialMajor, 4 * 1024).unwrap();
1249        // target 4 KiB < big blob.
1250        assert!(big_compressed_len as u64 > 4 * 1024);
1251        w.add_tile_full(&TileId::new(10, 0, 0, 0), 0, 100, None, 4000, None, &big).unwrap();
1252        for k in 1..4u64 {
1253            let p = distinct_tile(k);
1254            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p).unwrap();
1255        }
1256        let _manifest = w.finalize(&Metadata::new("big")).unwrap();
1257
1258        // At least one pack exceeds the target (the loner). Reading proves it.
1259        let reader = PackedReader::open(out.join("manifest.json")).unwrap();
1260        let big_entry = reader.entries().iter().find(|e| e.x == 0).unwrap();
1261        assert_eq!(reader.read_payload(big_entry).unwrap(), big);
1262    }
1263
1264    /// Read-path integrity: flipping a byte inside a pack object makes
1265    /// [`PackedReader::read_payload`] fail the per-blob CRC32C check instead of
1266    /// returning silently-wrong bytes. Guards the integrity check in
1267    /// `read_payload` (replaces the archive-era `corrupt_blob_is_detected`).
1268    #[test]
1269    fn corrupt_pack_blob_is_detected_on_read() {
1270        let dir = tempfile::tempdir().unwrap();
1271        let out = dir.path().join("dataset");
1272
1273        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 64 * 1024 * 1024).unwrap();
1274        for k in 0..4u64 {
1275            let p = distinct_tile(k);
1276            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p).unwrap();
1277        }
1278        let manifest = w.finalize(&Metadata::new("crc")).unwrap();
1279
1280        // Clean read before corruption.
1281        let entry = PackedReader::open(out.join("manifest.json")).unwrap().entries()[0].clone();
1282        assert!(PackedReader::open(out.join("manifest.json"))
1283            .unwrap()
1284            .read_payload(&entry)
1285            .is_ok());
1286
1287        // Flip the first byte of that tile's compressed blob inside its pack.
1288        let pack_path = out.join(&manifest.packs[entry.pack_id as usize].key);
1289        let mut bytes = fs::read(&pack_path).unwrap();
1290        bytes[entry.offset as usize] ^= 0xff;
1291        fs::write(&pack_path, &bytes).unwrap();
1292
1293        // A fresh reader must now reject that tile's payload (CRC32C mismatch).
1294        let reader = PackedReader::open(out.join("manifest.json")).unwrap();
1295        assert!(
1296            reader.read_payload(&entry).is_err(),
1297            "corrupt pack blob must fail the read-path CRC32C check"
1298        );
1299    }
1300
1301    /// Two builds of the same input — added in different orders, including
1302    /// curve-key ties (a base + temporal-LOD entry on one cell) — must produce
1303    /// byte-identical objects: same pack hashes, same directory hash. This is
1304    /// the immutable-pack CDN contract (a rebuild of unchanged data must not
1305    /// invalidate the edge cache).
1306    #[test]
1307    fn rebuilds_are_byte_reproducible() {
1308        // Tiles including a tie pair: same (z, x, y, time_start), one base
1309        // (bucket None) and one LOD (bucket Some) — the curve key alone can't
1310        // order them, the tiebreak must.
1311        let bucket = 3_600_000i64;
1312        let mut tiles: Vec<(TileId, i64, Option<u64>, Vec<u8>)> = Vec::new();
1313        for k in 0..10u64 {
1314            let t = (k % 4) as i64 * bucket;
1315            tiles.push((
1316                TileId::new(9, (k % 5) as u32, (k / 5) as u32, t as u64),
1317                t,
1318                None,
1319                distinct_tile(k),
1320            ));
1321        }
1322        // The tie pair on cell (1, 0): base + LOD aggregate at one time_start.
1323        tiles.push((TileId::new(9, 1, 0, 0), 0, None, distinct_tile(100)));
1324        tiles.push((
1325            TileId::new(9, 1, 0, 0),
1326            0,
1327            Some(24 * bucket as u64),
1328            distinct_tile(101),
1329        ));
1330
1331        let meta = Metadata::new("repro").with_temporal_bucket_ms(bucket as u64);
1332        let build = |order: &[usize]| {
1333            let dir = tempfile::tempdir().unwrap();
1334            let out = dir.path().join("dataset");
1335            let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1336            for &i in order {
1337                let (id, t, b, payload) = &tiles[i];
1338                w.add_tile_full(id, *t, t + bucket - 1, Some(*t), 6, *b, payload)
1339                    .unwrap();
1340            }
1341            let manifest = w.finalize(&meta).unwrap();
1342            (dir, manifest)
1343        };
1344
1345        let forward: Vec<usize> = (0..tiles.len()).collect();
1346        let reverse: Vec<usize> = (0..tiles.len()).rev().collect();
1347        let (_d1, m1) = build(&forward);
1348        let (_d2, m2) = build(&reverse);
1349
1350        assert_eq!(m1.directory.key, m2.directory.key, "directory hash must be stable");
1351        assert_eq!(
1352            m1.packs.iter().map(|p| &p.key).collect::<Vec<_>>(),
1353            m2.packs.iter().map(|p| &p.key).collect::<Vec<_>>(),
1354            "pack hashes must be stable across rebuilds"
1355        );
1356        assert_eq!(m1.to_json_bytes().unwrap(), m2.to_json_bytes().unwrap());
1357    }
1358
1359    /// The directory ships zstd-compressed at rest (declared via
1360    /// `directory.encoding`), and a legacy manifest with a RAW directory and
1361    /// no `encoding` key — the shape of every deployed dataset — must still
1362    /// open and verify.
1363    #[test]
1364    fn directory_encoding_compressed_and_raw_both_read() {
1365        let dir = tempfile::tempdir().unwrap();
1366        let out = dir.path().join("dataset");
1367        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1368        for k in 0..8u64 {
1369            let p = distinct_tile(k);
1370            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p)
1371                .unwrap();
1372        }
1373        let manifest = w.finalize(&Metadata::new("dir-enc")).unwrap();
1374        let manifest_path = out.join("manifest.json");
1375
1376        // Fresh output declares the encoding and the at-rest bytes are a
1377        // valid zstd frame that inflates to the codec bytes.
1378        assert_eq!(manifest.directory.encoding.as_deref(), Some("zstd"));
1379        let at_rest = fs::read(out.join(&manifest.directory.key)).unwrap();
1380        assert_eq!(at_rest.len() as u64, manifest.directory.length);
1381        let raw = compression::decompress_zstd_with_dict(&at_rest, None).unwrap();
1382        assert!(crate::directory::decode_directory(&raw).is_ok());
1383        assert!(verify_packed_objects(&manifest_path).unwrap().is_empty());
1384        let entries_compressed = PackedReader::open(&manifest_path).unwrap().entries().to_vec();
1385
1386        // Rewrite the dataset as a legacy (raw-directory) manifest: store the
1387        // raw codec bytes under their own content address and drop `encoding`.
1388        let raw_hex = blake3_128_hex(&raw);
1389        let raw_rel = format!("index/{raw_hex}.sttd");
1390        fs::write(out.join(&raw_rel), &raw).unwrap();
1391        let mut legacy = manifest.clone();
1392        legacy.directory = DirectoryRef {
1393            key: raw_rel,
1394            length: raw.len() as u64,
1395            directory_version: crate::directory::DIRECTORY_VERSION,
1396            encoding: None,
1397            layout: None,
1398            root_length: None,
1399            page_count: None,
1400            page_entries: None,
1401        };
1402        fs::write(&manifest_path, legacy.to_json_bytes().unwrap()).unwrap();
1403
1404        assert!(verify_packed_objects(&manifest_path).unwrap().is_empty());
1405        let entries_raw = PackedReader::open(&manifest_path).unwrap().entries().to_vec();
1406        assert_eq!(entries_raw, entries_compressed);
1407
1408        // An unknown encoding must fail loudly, not decode garbage.
1409        legacy.directory.encoding = Some("br".to_string());
1410        fs::write(&manifest_path, legacy.to_json_bytes().unwrap()).unwrap();
1411        assert!(PackedReader::open(&manifest_path).is_err());
1412    }
1413
1414    /// A clean packed dataset verifies with no issues; corrupting a pack's
1415    /// bytes (without changing its length) breaks the content address and is
1416    /// reported.
1417    #[test]
1418    fn verify_packed_objects_clean_then_detects_corruption() {
1419        let dir = tempfile::tempdir().unwrap();
1420        let out = dir.path().join("dataset");
1421
1422        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1423        for k in 0..12u64 {
1424            let p = distinct_tile(k);
1425            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p)
1426                .unwrap();
1427        }
1428        let manifest = w.finalize(&Metadata::new("verify")).unwrap();
1429        let manifest_path = out.join("manifest.json");
1430
1431        // Clean dataset → no integrity violations.
1432        assert!(verify_packed_objects(&manifest_path).unwrap().is_empty());
1433
1434        // Flip a byte in pack 0: same length, but blake3 no longer matches the
1435        // filename it was addressed by.
1436        let pack0 = out.join(&manifest.packs[0].key);
1437        let mut bytes = fs::read(&pack0).unwrap();
1438        bytes[0] ^= 0xff;
1439        fs::write(&pack0, &bytes).unwrap();
1440
1441        let issues = verify_packed_objects(&manifest_path).unwrap();
1442        assert!(
1443            issues.iter().any(|s| s.contains("content-address mismatch")),
1444            "expected a content-address mismatch, got {issues:?}"
1445        );
1446    }
1447}