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 ([`crate::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 [`crate::archive::ArchiveReader`] semantics.
33
34use crate::archive::{ArchiveReader, TileEntry};
35use crate::compression;
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 [`crate::archive::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    /// [`crate::archive::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        // --- Write objects ----------------------------------------------
490        fs::create_dir_all(&out_dir)?;
491        let index_dir = out_dir.join("index");
492        let packs_dir = out_dir.join("packs");
493        fs::create_dir_all(&index_dir)?;
494        fs::create_dir_all(&packs_dir)?;
495
496        // Write each pack to a temp file then atomically rename to its content
497        // address. Packs are immutable, so a re-sync skips an unchanged pack.
498        let mut pack_refs: Vec<PackRef> = Vec::with_capacity(packs_blob_ranges.len());
499        for (start, end) in &packs_blob_ranges {
500            let mut bytes: Vec<u8> = Vec::new();
501            for blob in &blobs[*start..*end] {
502                bytes.extend_from_slice(&blob.compressed);
503            }
504            let hex = blake3_128_hex(&bytes);
505            let rel = format!("packs/{hex}.sttp");
506            let final_path = out_dir.join(&rel);
507            write_atomic(&packs_dir, &final_path, &bytes)?;
508            pack_refs.push(PackRef {
509                key: rel,
510                length: bytes.len() as u64,
511            });
512        }
513
514        // Encode the directory. Both shapes are zstd-at-rest (declared via
515        // `directory.encoding`) — directories compress ~2x and sit on the
516        // cold-start critical path with no CDN content-encoding rescue:
517        //   - single (default): one zstd frame over the whole v5 codec buffer.
518        //   - paged (opt-in):   a root page + leaf pages, each its own zstd
519        //     frame, so a cold reader fetches only the leaves it touches. The
520        //     leaf codec is the same v5 directory.
521        // The object is content-addressed over its at-rest bytes either way.
522        let (index_bytes, directory_ref_fields): (Vec<u8>, _) = if let Some(k) = page_entries {
523            let paged =
524                crate::directory_page::encode_paged_directory_level(&entries, k, true, zstd_level)?;
525            (
526                paged.bytes,
527                (
528                    Some(DIRECTORY_LAYOUT_PAGED.to_string()),
529                    Some(paged.root_length),
530                    Some(paged.page_count as u64),
531                    Some(paged.page_entries as u64),
532                ),
533            )
534        } else {
535            let index_plain = crate::directory::encode_directory(&entries);
536            let bytes = compression::compress_zstd_with_dict_level(&index_plain, None, zstd_level)?;
537            (bytes, (None, None, None, None))
538        };
539        let index_hex = blake3_128_hex(&index_bytes);
540        let index_rel = format!("index/{index_hex}.sttd");
541        let index_path = out_dir.join(&index_rel);
542        write_atomic(&index_dir, &index_path, &index_bytes)?;
543
544        let (layout, root_length, page_count, page_entries_field) = directory_ref_fields;
545
546        // Build + write the manifest.
547        let manifest = Manifest {
548            format: PACKED_FORMAT.to_string(),
549            format_version: PACKED_FORMAT_VERSION,
550            compression: "zstd".to_string(),
551            directory: DirectoryRef {
552                key: index_rel,
553                length: index_bytes.len() as u64,
554                directory_version: crate::directory::DIRECTORY_VERSION,
555                encoding: Some(DIRECTORY_ENCODING_ZSTD.to_string()),
556                layout,
557                root_length,
558                page_count,
559                page_entries: page_entries_field,
560            },
561            packs: pack_refs,
562            metadata: metadata.clone(),
563        };
564        let manifest_bytes = manifest.to_json_bytes()?;
565        let manifest_path = out_dir.join("manifest.json");
566        let mut f = File::create(&manifest_path)?;
567        f.write_all(&manifest_bytes)?;
568        f.flush()?;
569
570        Ok(manifest)
571    }
572}
573
574/// Unwrap a directory object's at-rest encoding into raw codec bytes.
575/// `encoding` is the manifest's `directory.encoding`: absent = raw (every
576/// pre-encoding manifest), `"zstd"` = one zstd frame around the codec bytes.
577fn decode_directory_object(bytes: &[u8], encoding: Option<&str>) -> Result<Vec<u8>> {
578    match encoding {
579        None => Ok(bytes.to_vec()),
580        Some(DIRECTORY_ENCODING_ZSTD) => compression::decompress_zstd_with_dict(bytes, None),
581        Some(other) => Err(Error::InvalidArchive(format!(
582            "unknown directory encoding {other:?} (this reader supports absent or \"zstd\")"
583        ))),
584    }
585}
586
587/// Decode the full tile-entry list from a directory object's at-rest bytes,
588/// branching on the container layout. The single (whole-load) shape unwraps the
589/// at-rest encoding then runs the v5 codec; the paged shape decodes the root +
590/// every leaf (the local load-all path — a mmap'd file has no cold-start cost,
591/// so the paging *query* win lives in the TS HTTP reader). Used by the local
592/// `PackedReader` and `verify_packed_objects`.
593fn decode_directory_entries(bytes: &[u8], dref: &DirectoryRef) -> Result<Vec<TileEntry>> {
594    if dref.is_paged() {
595        let root_length = dref.root_length.ok_or_else(|| {
596            Error::InvalidArchive("paged directory: manifest missing rootLength".into())
597        })?;
598        let zstd = dref.encoding.as_deref() == Some(DIRECTORY_ENCODING_ZSTD);
599        crate::directory_page::decode_paged_directory(bytes, root_length, zstd)
600    } else {
601        let raw = decode_directory_object(bytes, dref.encoding.as_deref())?;
602        crate::directory::decode_directory(&raw)
603    }
604}
605
606/// Write `bytes` to a temp file inside `dir` then atomically rename to
607/// `final_path` (content-addressed, so an existing identical object is a no-op
608/// overwrite of the same bytes).
609fn write_atomic(dir: &Path, final_path: &Path, bytes: &[u8]) -> Result<()> {
610    // Unique temp name within the same directory so the rename is atomic.
611    let tmp = dir.join(format!(
612        ".tmp-{}-{}",
613        std::process::id(),
614        blake3_128_hex(bytes)
615    ));
616    {
617        let mut f = OpenOptions::new()
618            .write(true)
619            .create(true)
620            .truncate(true)
621            .open(&tmp)?;
622        f.write_all(bytes)?;
623        f.flush()?;
624    }
625    fs::rename(&tmp, final_path)?;
626    Ok(())
627}
628
629// ----------------------------------------------------------------------------
630// Transcode (single-file v4 archive -> packed dir)
631// ----------------------------------------------------------------------------
632
633/// Losslessly re-wrap a single-file v4 `.stt` archive into the packed format.
634///
635/// Reads every tile payload via [`ArchiveReader`] and streams it into a fresh
636/// [`PackWriter`], preserving the tight covering bound (`cover_t_min`) and the
637/// per-tile `temporal_bucket_ms` exactly (no thinning), then finalizes with the
638/// source archive's metadata. Writes `manifest.json`, `index/<hash>.sttd`, and
639/// one or more `packs/<hash>.sttp` objects under `out_dir`.
640///
641/// Shared by the `pack-transcode` example and `stt-build`'s `--streaming-arrow`
642/// path (which builds a temp single-file archive under bounded RAM, then
643/// transcodes it to packs).
644pub fn transcode_archive_to_packs<I: AsRef<Path>, O: AsRef<Path>>(
645    in_archive: I,
646    out_dir: O,
647    ordering: BlobOrdering,
648    pack_target_bytes: u64,
649) -> Result<Manifest> {
650    transcode_archive_to_packs_paged(in_archive, out_dir, ordering, pack_target_bytes, None)
651}
652
653/// [`transcode_archive_to_packs`] with an explicit paging choice.
654///
655/// `page_entries`: `Some(k)` emits a paged directory (root + leaf pages of ≤ `k`
656/// entries — Wave 2); `None` emits the single whole-load v5 directory. The tile
657/// payloads, packs, dedup and ordering are identical either way — only the
658/// `.sttd` directory shape changes — so a paged transcode of an existing dataset
659/// re-ships only `index/*.sttd` + `manifest.json` (the packs are unchanged
660/// content addresses).
661pub fn transcode_archive_to_packs_paged<I: AsRef<Path>, O: AsRef<Path>>(
662    in_archive: I,
663    out_dir: O,
664    ordering: BlobOrdering,
665    pack_target_bytes: u64,
666    page_entries: Option<usize>,
667) -> Result<Manifest> {
668    transcode_archive_to_packs_paged_level(
669        in_archive,
670        out_dir,
671        ordering,
672        pack_target_bytes,
673        page_entries,
674        compression::ZSTD_LEVEL,
675    )
676}
677
678/// [`transcode_archive_to_packs_paged`] at an explicit zstd `level` (see
679/// [`PackWriter::with_zstd_level`]). Re-compresses every blob at `level`, so —
680/// unlike [`repack_directory`] — it rewrites the packs, not just the directory.
681pub fn transcode_archive_to_packs_paged_level<I: AsRef<Path>, O: AsRef<Path>>(
682    in_archive: I,
683    out_dir: O,
684    ordering: BlobOrdering,
685    pack_target_bytes: u64,
686    page_entries: Option<usize>,
687    zstd_level: i32,
688) -> Result<Manifest> {
689    let reader = ArchiveReader::open(in_archive)?;
690    let meta = reader.metadata().clone();
691    let entries = reader.entries().to_vec();
692
693    let mut writer = PackWriter::create(out_dir, ordering, pack_target_bytes)?
694        .with_paging(page_entries)
695        .with_zstd_level(zstd_level);
696    for e in &entries {
697        let payload = reader.read_payload(e)?;
698        writer.add_tile_full(
699            &TileId::new(e.zoom, e.x, e.y, e.time_start.max(0) as u64),
700            e.time_start,
701            e.time_end,
702            e.cover_t_min,
703            e.feature_count,
704            e.temporal_bucket_ms,
705            &payload,
706        )?;
707    }
708    writer.finalize(&meta)
709}
710
711/// Re-transcode an existing **packed** dataset into a fresh packed dataset at an
712/// explicit zstd `level` and (optionally) a paged directory — the publish-build
713/// migration. Unlike [`repack_directory`] (directory-only) this re-reads and
714/// **re-compresses every tile payload**, so it picks up a higher `--zstd-level`
715/// (−10..19% on the wire) and re-pages the directory in one pass.
716///
717/// The input packed dir is the source of truth — important because several
718/// showcase datasets were rebuilt later than their legacy single-file `.stt`,
719/// so transcoding from the packs (not the stale `.stt`) preserves those fixes.
720/// Tile content is byte-for-byte preserved (lossless); only the compression
721/// level and directory shape change. `out_dir` MUST differ from the input dir.
722pub fn transcode_packs_to_packs_paged_level<I: AsRef<Path>, O: AsRef<Path>>(
723    in_manifest: I,
724    out_dir: O,
725    ordering: BlobOrdering,
726    pack_target_bytes: u64,
727    page_entries: Option<usize>,
728    zstd_level: i32,
729) -> Result<Manifest> {
730    let reader = PackedReader::open(in_manifest)?;
731    let meta = reader.metadata().clone();
732    let entries = reader.entries().to_vec();
733
734    let mut writer = PackWriter::create(out_dir, ordering, pack_target_bytes)?
735        .with_paging(page_entries)
736        .with_zstd_level(zstd_level);
737    for e in &entries {
738        let payload = reader.read_payload(e)?;
739        writer.add_tile_full(
740            &TileId::new(e.zoom, e.x, e.y, e.time_start.max(0) as u64),
741            e.time_start,
742            e.time_end,
743            e.cover_t_min,
744            e.feature_count,
745            e.temporal_bucket_ms,
746            &payload,
747        )?;
748    }
749    writer.finalize(&meta)
750}
751
752/// Re-encode **only the directory** of an existing packed dataset, optionally
753/// switching it to (or from) the paged container — without re-reading or
754/// re-compressing a single tile payload.
755///
756/// This is the cheap Wave-2 re-transcode: the directory entries already carry
757/// every blob's `(pack_id, offset, length, crc32c)`, and the packs are
758/// content-addressed and immutable, so a directory shape change re-ships only
759/// `index/<hash>.sttd` + `manifest.json` — the packs keep their exact bytes and
760/// names. `page_entries`: `Some(k)` → paged directory (leaf pages of ≤ `k`),
761/// `None` → single whole-load directory.
762///
763/// When `out_dir` differs from the input dataset's directory, the (unchanged)
764/// pack objects are copied across so `out_dir` is a complete dataset; an
765/// in-place re-pack (`out_dir` == the input dir) leaves the packs untouched and
766/// just adds the new index object + overwrites the manifest.
767pub fn repack_directory<P: AsRef<Path>, Q: AsRef<Path>>(
768    in_manifest: P,
769    out_dir: Q,
770    page_entries: Option<usize>,
771) -> Result<Manifest> {
772    let in_manifest = in_manifest.as_ref();
773    let in_dir = in_manifest
774        .parent()
775        .ok_or_else(|| Error::InvalidArchive("manifest path has no parent dir".into()))?;
776    let out_dir = out_dir.as_ref();
777
778    let reader = PackedReader::open(in_manifest)?;
779    let entries = reader.entries().to_vec();
780    let metadata = reader.metadata().clone();
781    let src = Manifest::from_json_bytes(&fs::read(in_manifest)?)?;
782
783    fs::create_dir_all(out_dir.join("index"))?;
784    fs::create_dir_all(out_dir.join("packs"))?;
785
786    // Copy the (unchanged, content-addressed) packs only when writing elsewhere.
787    let same_dir = fs::canonicalize(in_dir).ok() == fs::canonicalize(out_dir).ok();
788    if !same_dir {
789        for p in &src.packs {
790            let dst = out_dir.join(&p.key);
791            if !dst.exists() {
792                fs::copy(in_dir.join(&p.key), &dst)?;
793            }
794        }
795    }
796
797    // Re-encode the directory from the existing entries (no payload re-read).
798    let (index_bytes, layout, root_length, page_count, page_entries_field): (
799        Vec<u8>,
800        Option<String>,
801        Option<u64>,
802        Option<u64>,
803        Option<u64>,
804    ) = if let Some(k) = page_entries {
805        let paged = crate::directory_page::encode_paged_directory(&entries, k, true)?;
806        (
807            paged.bytes,
808            Some(DIRECTORY_LAYOUT_PAGED.to_string()),
809            Some(paged.root_length),
810            Some(paged.page_count as u64),
811            Some(paged.page_entries as u64),
812        )
813    } else {
814        let plain = crate::directory::encode_directory(&entries);
815        (
816            compression::compress_zstd_with_dict(&plain, None)?,
817            None,
818            None,
819            None,
820            None,
821        )
822    };
823
824    let index_hex = blake3_128_hex(&index_bytes);
825    let index_rel = format!("index/{index_hex}.sttd");
826    write_atomic(&out_dir.join("index"), &out_dir.join(&index_rel), &index_bytes)?;
827
828    let manifest = Manifest {
829        format: PACKED_FORMAT.to_string(),
830        format_version: PACKED_FORMAT_VERSION,
831        compression: src.compression.clone(),
832        directory: DirectoryRef {
833            key: index_rel,
834            length: index_bytes.len() as u64,
835            directory_version: crate::directory::DIRECTORY_VERSION,
836            encoding: Some(DIRECTORY_ENCODING_ZSTD.to_string()),
837            layout,
838            root_length,
839            page_count,
840            page_entries: page_entries_field,
841        },
842        packs: src.packs.clone(),
843        metadata,
844    };
845    let manifest_bytes = manifest.to_json_bytes()?;
846    let mut f = File::create(out_dir.join("manifest.json"))?;
847    f.write_all(&manifest_bytes)?;
848    f.flush()?;
849    Ok(manifest)
850}
851
852// ----------------------------------------------------------------------------
853// Integrity
854// ----------------------------------------------------------------------------
855
856/// Verify the on-disk integrity of a packed dataset against its manifest.
857///
858/// Because packs and the directory are **content-addressed**, integrity is a
859/// property anyone can check with no trusted side-channel: each object's bytes
860/// must blake3-hash to the name the manifest gave it, and its on-disk length
861/// must match the declared length. Additionally the directory must decode and
862/// reference no `pack_id` outside the manifest's pack table.
863///
864/// Returns the list of violations (empty ⇒ clean). Returns `Err` only when the
865/// manifest itself cannot be read or parsed (a missing referenced object is a
866/// reported violation, not an `Err`, so a full report is produced in one pass).
867pub fn verify_packed_objects<P: AsRef<Path>>(manifest_path: P) -> Result<Vec<String>> {
868    let manifest_path = manifest_path.as_ref();
869    let root = manifest_path
870        .parent()
871        .ok_or_else(|| Error::InvalidArchive("manifest path has no parent dir".into()))?;
872    let manifest = Manifest::from_json_bytes(&fs::read(manifest_path)?)?;
873
874    let mut issues = Vec::new();
875
876    if manifest.format != PACKED_FORMAT {
877        issues.push(format!(
878            "manifest format is {:?}, expected {PACKED_FORMAT:?}",
879            manifest.format
880        ));
881    }
882    if manifest.format_version != PACKED_FORMAT_VERSION {
883        issues.push(format!(
884            "manifest formatVersion is {}, expected {PACKED_FORMAT_VERSION}",
885            manifest.format_version
886        ));
887    }
888    if manifest.directory.directory_version != crate::directory::DIRECTORY_VERSION {
889        issues.push(format!(
890            "directoryVersion is {}, expected {}",
891            manifest.directory.directory_version,
892            crate::directory::DIRECTORY_VERSION
893        ));
894    }
895
896    // Each content-addressed object: name must equal blake3-128 of its bytes,
897    // and on-disk length must equal the declared length.
898    fn check_object(
899        root: &Path,
900        key: &str,
901        declared_len: u64,
902        prefix: &str,
903        ext: &str,
904        issues: &mut Vec<String>,
905    ) {
906        match fs::read(root.join(key)) {
907            Ok(bytes) => {
908                if bytes.len() as u64 != declared_len {
909                    issues.push(format!(
910                        "{key}: on-disk length {} != manifest-declared {declared_len}",
911                        bytes.len()
912                    ));
913                }
914                let expected = format!("{prefix}/{}.{ext}", blake3_128_hex(&bytes));
915                if key != expected {
916                    issues.push(format!(
917                        "{key}: content-address mismatch (bytes hash to {expected})"
918                    ));
919                }
920            }
921            Err(e) => issues.push(format!("{key}: cannot read object ({e})")),
922        }
923    }
924
925    check_object(
926        root,
927        &manifest.directory.key,
928        manifest.directory.length,
929        "index",
930        "sttd",
931        &mut issues,
932    );
933    for p in &manifest.packs {
934        check_object(root, &p.key, p.length, "packs", "sttp", &mut issues);
935    }
936
937    // Directory must decode (through its at-rest encoding + container layout)
938    // and reference only packs that exist.
939    match fs::read(root.join(&manifest.directory.key)) {
940        Ok(dir_bytes) => match decode_directory_entries(&dir_bytes, &manifest.directory) {
941            Ok(entries) => {
942                if let Some(max_pid) = entries.iter().map(|e| e.pack_id).max() {
943                    if max_pid as usize >= manifest.packs.len() {
944                        issues.push(format!(
945                            "directory references pack_id {max_pid} but the manifest lists only {} pack(s)",
946                            manifest.packs.len()
947                        ));
948                    }
949                }
950            }
951            Err(e) => issues.push(format!("directory failed to decode: {e}")),
952        },
953        // A read failure here is already reported by check_object above.
954        Err(_) => {}
955    }
956
957    // Paged directories: validate the container structure beyond plain decode —
958    // page descriptor bounds cover their leaf's entries (so a reader's prune
959    // never drops a matching tile) and cross-page key order is monotonic.
960    if manifest.directory.is_paged() {
961        match manifest.directory.root_length {
962            Some(rl) => {
963                if let Ok(dir_bytes) = fs::read(root.join(&manifest.directory.key)) {
964                    let zstd =
965                        manifest.directory.encoding.as_deref() == Some(DIRECTORY_ENCODING_ZSTD);
966                    match crate::directory_page::verify_paged_structure(&dir_bytes, rl, zstd) {
967                        Ok(mut more) => issues.append(&mut more),
968                        Err(e) => issues.push(format!("paged structure check failed: {e}")),
969                    }
970                }
971            }
972            None => issues.push("paged directory: manifest missing rootLength".into()),
973        }
974    }
975
976    Ok(issues)
977}
978
979// ----------------------------------------------------------------------------
980// Reader
981// ----------------------------------------------------------------------------
982
983/// One mapped pack, lazily loaded on first access.
984struct LoadedPack {
985    /// `None` until first read of a tile in this pack.
986    mmap: Option<Mmap>,
987    /// Absolute path to the pack object.
988    path: PathBuf,
989    /// Declared length from the manifest (for a bounds sanity check).
990    length: u64,
991}
992
993/// Reader for a **local** packed dataset. Remote/HTTP reads are the TS reader's
994/// job; this opens objects from the filesystem.
995///
996/// Mirrors [`crate::archive::ArchiveReader`]: [`entries`](Self::entries) returns
997/// the decoded v5 directory, [`metadata`](Self::metadata) the folded metadata,
998/// and [`read_payload`](Self::read_payload) selects the entry's pack, slices
999/// `[offset..offset+length]`, verifies CRC32C and decompresses the per-blob
1000/// zstd. Packs are mmap'd lazily by `pack_id`.
1001pub struct PackedReader {
1002    entries: Vec<TileEntry>,
1003    metadata: Metadata,
1004    compression: Compression,
1005    packs: Vec<std::cell::RefCell<LoadedPack>>,
1006}
1007
1008impl PackedReader {
1009    /// Open a packed dataset by its `manifest.json` path. The directory and pack
1010    /// objects are resolved relative to the manifest's parent directory.
1011    pub fn open<P: AsRef<Path>>(manifest_path: P) -> Result<Self> {
1012        let manifest_path = manifest_path.as_ref();
1013        let root = manifest_path
1014            .parent()
1015            .ok_or_else(|| Error::InvalidArchive("manifest path has no parent dir".into()))?
1016            .to_path_buf();
1017
1018        let manifest_bytes = fs::read(manifest_path)?;
1019        let manifest = Manifest::from_json_bytes(&manifest_bytes)?;
1020
1021        if manifest.format != PACKED_FORMAT {
1022            return Err(Error::InvalidArchive(format!(
1023                "not a packed manifest: format={:?} (expected {PACKED_FORMAT:?})",
1024                manifest.format
1025            )));
1026        }
1027        let compression = match manifest.compression.as_str() {
1028            "zstd" => Compression::Zstd,
1029            "none" => Compression::None,
1030            other => {
1031                return Err(Error::InvalidArchive(format!(
1032                    "unknown packed compression {other:?}"
1033                )))
1034            }
1035        };
1036
1037        // Load + decode the directory object. The single (whole-load) shape
1038        // unwraps the at-rest encoding then runs the v5 codec; the paged shape
1039        // decodes the root + every leaf (local load-all — a mmap'd file has no
1040        // cold-start cost). Both branches return the same full entry list.
1041        let dir_path = root.join(&manifest.directory.key);
1042        let dir_bytes = fs::read(&dir_path)?;
1043        let entries = decode_directory_entries(&dir_bytes, &manifest.directory)?;
1044
1045        // Prepare (lazy) pack handles in pack_id order.
1046        let packs = manifest
1047            .packs
1048            .iter()
1049            .map(|p| {
1050                std::cell::RefCell::new(LoadedPack {
1051                    mmap: None,
1052                    path: root.join(&p.key),
1053                    length: p.length,
1054                })
1055            })
1056            .collect();
1057
1058        Ok(Self {
1059            entries,
1060            metadata: manifest.metadata,
1061            compression,
1062            packs,
1063        })
1064    }
1065
1066    /// All directory entries (sorted by zoom then Hilbert index).
1067    pub fn entries(&self) -> &[TileEntry] {
1068        &self.entries
1069    }
1070
1071    /// Dataset metadata.
1072    pub fn metadata(&self) -> &Metadata {
1073        &self.metadata
1074    }
1075
1076    /// Read and decompress a tile's raw payload bytes, verifying its CRC32C.
1077    ///
1078    /// Selects the pack by `entry.pack_id`, slices `[offset..offset+length]`
1079    /// within it, checks the CRC, then decompresses the per-blob zstd. Mirrors
1080    /// [`crate::archive::ArchiveReader::read_payload`].
1081    pub fn read_payload(&self, entry: &TileEntry) -> Result<Vec<u8>> {
1082        let cell = self.packs.get(entry.pack_id as usize).ok_or_else(|| {
1083            Error::InvalidArchive(format!(
1084                "tile {:?} references pack {} but only {} packs exist",
1085                entry.tile_id(),
1086                entry.pack_id,
1087                self.packs.len()
1088            ))
1089        })?;
1090
1091        let payload = {
1092            let mut pack = cell.borrow_mut();
1093            if pack.mmap.is_none() {
1094                let file = File::open(&pack.path)?;
1095                // SAFETY: read-only mapping of a file we never write through; the
1096                // mapping is owned by the reader for its lifetime.
1097                let mmap = unsafe { Mmap::map(&file) }
1098                    .map_err(|e| Error::Other(format!("mmap failed: {e}")))?;
1099                if mmap.len() as u64 != pack.length {
1100                    return Err(Error::InvalidArchive(format!(
1101                        "pack {} is {} bytes, manifest declared {}",
1102                        pack.path.display(),
1103                        mmap.len(),
1104                        pack.length
1105                    )));
1106                }
1107                pack.mmap = Some(mmap);
1108            }
1109            let mmap = pack.mmap.as_ref().expect("just loaded");
1110
1111            let start = entry.offset as usize;
1112            let end = start + entry.length as usize;
1113            if end > mmap.len() {
1114                return Err(Error::InvalidArchive(format!(
1115                    "tile {:?} blob range {start}..{end} exceeds pack size {}",
1116                    entry.tile_id(),
1117                    mmap.len()
1118                )));
1119            }
1120            let compressed = &mmap[start..end];
1121
1122            if crc32c_tag(compressed) != entry.crc32c {
1123                return Err(Error::InvalidArchive(format!(
1124                    "tile {:?} failed integrity check (corrupt pack)",
1125                    entry.tile_id()
1126                )));
1127            }
1128
1129            if self.compression == Compression::Zstd {
1130                compression::decompress_zstd_with_dict(compressed, None)?
1131            } else {
1132                compression::decompress(compressed, self.compression)?
1133            }
1134        };
1135
1136        if payload.len() != entry.uncompressed_size as usize {
1137            return Err(Error::InvalidArchive(format!(
1138                "tile {:?} decompressed to {} bytes, expected {}",
1139                entry.tile_id(),
1140                payload.len(),
1141                entry.uncompressed_size
1142            )));
1143        }
1144        Ok(payload)
1145    }
1146
1147    /// Read and decode a tile into its Arrow layers.
1148    pub fn read_layers(&self, entry: &TileEntry) -> Result<Vec<crate::arrow_tile::DecodedLayer>> {
1149        let payload = self.read_payload(entry)?;
1150        crate::arrow_tile::decode_tile(&payload)
1151    }
1152}
1153
1154#[cfg(test)]
1155mod tests {
1156    use super::*;
1157    use crate::arrow_tile::{encode_tile, ColumnarLayer, GeometryColumn};
1158
1159    fn point_layer(name: &str, ids: Vec<u64>, t0: i64) -> ColumnarLayer {
1160        let n = ids.len();
1161        ColumnarLayer {
1162            name: name.to_string(),
1163            feature_ids: ids,
1164            start_times: vec![t0; n],
1165            end_times: vec![t0 + 100; n],
1166            geometry: GeometryColumn::Point(vec![[-122.4, 37.7]; n]),
1167            vertex_times: None,
1168            vertex_values: None,
1169            triangles: None,
1170            vertex_value_matrix: None,
1171            properties: vec![],
1172        }
1173    }
1174
1175    /// Distinct-payload tile so each blob is unique (forces many packs at a tiny
1176    /// target). `seed` perturbs the feature ids so compressed bytes differ.
1177    fn distinct_tile(seed: u64) -> Vec<u8> {
1178        let ids: Vec<u64> = (0..6).map(|i| seed * 100 + i).collect();
1179        encode_tile(&[point_layer("default", ids, (seed as i64) * 7)]).unwrap()
1180    }
1181
1182    #[test]
1183    fn blake3_128_hex_is_32_chars() {
1184        let h = blake3_128_hex(b"hello");
1185        assert_eq!(h.len(), 32);
1186        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
1187    }
1188
1189    #[test]
1190    fn manifest_json_roundtrips() {
1191        let m = Manifest {
1192            format: PACKED_FORMAT.to_string(),
1193            format_version: PACKED_FORMAT_VERSION,
1194            compression: "zstd".to_string(),
1195            directory: DirectoryRef {
1196                key: "index/abc.sttd".to_string(),
1197                length: 42,
1198                directory_version: 5,
1199                encoding: Some(DIRECTORY_ENCODING_ZSTD.to_string()),
1200                layout: None,
1201                root_length: None,
1202                page_count: None,
1203                page_entries: None,
1204            },
1205            packs: vec![
1206                PackRef { key: "packs/a.sttp".to_string(), length: 100 },
1207                PackRef { key: "packs/b.sttp".to_string(), length: 200 },
1208            ],
1209            metadata: Metadata::new("manifest-test"),
1210        };
1211        let bytes = m.to_json_bytes().unwrap();
1212        // The spec keys must be camelCase where renamed.
1213        let s = String::from_utf8(bytes.clone()).unwrap();
1214        assert!(s.contains("\"formatVersion\""), "{s}");
1215        assert!(s.contains("\"directoryVersion\""), "{s}");
1216        assert!(s.contains("\"stt-packed\""), "{s}");
1217        let back = Manifest::from_json_bytes(&bytes).unwrap();
1218        assert_eq!(back.format, m.format);
1219        assert_eq!(back.format_version, m.format_version);
1220        assert_eq!(back.packs.len(), 2);
1221        assert_eq!(back.directory.directory_version, 5);
1222        assert_eq!(back.directory.encoding.as_deref(), Some("zstd"));
1223        assert_eq!(back.metadata.name, "manifest-test");
1224
1225        // Backward compat: a pre-encoding manifest (no `encoding` key — the
1226        // shape of every deployed dataset) must parse with `encoding: None`,
1227        // and a None encoding must serialize without the key.
1228        let mut legacy_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1229        legacy_json["directory"]
1230            .as_object_mut()
1231            .unwrap()
1232            .remove("encoding");
1233        let legacy_back =
1234            Manifest::from_json_bytes(&serde_json::to_vec(&legacy_json).unwrap()).unwrap();
1235        assert_eq!(legacy_back.directory.encoding, None);
1236        let legacy_out =
1237            String::from_utf8(legacy_back.to_json_bytes().unwrap()).unwrap();
1238        assert!(!legacy_out.contains("\"encoding\""), "{legacy_out}");
1239    }
1240
1241    /// Full round-trip: 30 synthetic tiles (a couple byte-identical to exercise
1242    /// dedup) across 2 zooms + several time buckets, written with a tiny pack
1243    /// target to force multiple packs. Every payload must decode byte-identical.
1244    #[test]
1245    fn packwriter_roundtrips_through_multiple_packs() {
1246        let dir = tempfile::tempdir().unwrap();
1247        let out = dir.path().join("dataset");
1248
1249        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1250
1251        // Build 30 tiles. Tiles 0..28 distinct; the static one is reused so two
1252        // entries point at one byte-identical blob (dedup).
1253        let static_payload = encode_tile(&[point_layer("default", vec![7, 8, 9], 0)]).unwrap();
1254        let mut expected: Vec<(TileId, i64, i64, Vec<u8>)> = Vec::new();
1255        let bucket = 3_600_000i64;
1256        for k in 0..30u64 {
1257            let zoom = if k % 2 == 0 { 9u8 } else { 10u8 };
1258            let b = (k % 5) as i64; // several time buckets
1259            let t = b * bucket;
1260            let payload = if k == 13 || k == 27 {
1261                static_payload.clone() // two byte-identical → dedup
1262            } else {
1263                distinct_tile(k)
1264            };
1265            let id = TileId::new(zoom, (k % 7) as u32, (k / 7) as u32, t as u64);
1266            w.add_tile_full(&id, t, t + bucket - 1, Some(t), 6, Some(bucket as u64), &payload)
1267                .unwrap();
1268            expected.push((id, t, t + bucket - 1, payload));
1269        }
1270        assert_eq!(w.tile_count(), 30);
1271
1272        let meta = Metadata::new("packed-roundtrip").with_temporal_bucket_ms(bucket as u64);
1273        let manifest = w.finalize(&meta).unwrap();
1274
1275        // >1 pack produced at the tiny target.
1276        assert!(manifest.packs.len() > 1, "expected multiple packs, got {}", manifest.packs.len());
1277
1278        // Every pack file ≤ target, except a lone oversized blob owning a pack.
1279        for p in &manifest.packs {
1280            let bytes = fs::read(out.join(&p.key)).unwrap();
1281            assert_eq!(bytes.len() as u64, p.length);
1282            // A pack over target must contain exactly one blob (oversized loner).
1283            // We can't see blob boundaries here, but the cut rule guarantees a
1284            // pack only exceeds the target when it holds a single blob; the
1285            // round-trip below proves correctness regardless.
1286        }
1287
1288        // Pack/dir filenames are blake3-128 hex of their bytes.
1289        for p in &manifest.packs {
1290            let bytes = fs::read(out.join(&p.key)).unwrap();
1291            let hex = blake3_128_hex(&bytes);
1292            assert_eq!(p.key, format!("packs/{hex}.sttp"));
1293        }
1294        let dir_bytes = fs::read(out.join(&manifest.directory.key)).unwrap();
1295        assert_eq!(
1296            manifest.directory.key,
1297            format!("index/{}.sttd", blake3_128_hex(&dir_bytes))
1298        );
1299
1300        // pack_ids are contiguous from 0 across all entries.
1301        let reader = PackedReader::open(out.join("manifest.json")).unwrap();
1302        let max_pack = reader.entries().iter().map(|e| e.pack_id).max().unwrap();
1303        assert_eq!(max_pack as usize, manifest.packs.len() - 1);
1304        let observed: std::collections::BTreeSet<u32> =
1305            reader.entries().iter().map(|e| e.pack_id).collect();
1306        for pid in 0..manifest.packs.len() as u32 {
1307            assert!(observed.contains(&pid), "pack_id {pid} unused");
1308        }
1309
1310        // Metadata round-trips.
1311        assert_eq!(reader.metadata().name, "packed-roundtrip");
1312        assert_eq!(reader.metadata().temporal_bucket_ms, bucket as u64);
1313        assert_eq!(reader.entries().len(), 30);
1314
1315        // Every tile's decompressed payload is byte-identical.
1316        for (id, ts, _te, payload) in &expected {
1317            let e = reader
1318                .entries()
1319                .iter()
1320                .find(|e| {
1321                    e.zoom == id.z && e.x == id.x && e.y == id.y && e.time_start == *ts
1322                })
1323                .expect("entry present");
1324            let got = reader.read_payload(e).unwrap();
1325            assert_eq!(&got, payload, "payload mismatch for {id:?}");
1326        }
1327
1328        // Dedup: the two static tiles share one (pack, offset).
1329        let static_entries: Vec<&TileEntry> = reader
1330            .entries()
1331            .iter()
1332            .filter(|e| {
1333                let g = reader.read_payload(e).unwrap();
1334                g == static_payload
1335            })
1336            .collect();
1337        assert_eq!(static_entries.len(), 2);
1338        assert_eq!(static_entries[0].pack_id, static_entries[1].pack_id);
1339        assert_eq!(static_entries[0].offset, static_entries[1].offset);
1340    }
1341
1342    /// A **paged** directory build round-trips end-to-end through
1343    /// `PackedReader`: every input tile's payload decodes byte-identically, the
1344    /// manifest carries the container fields, and content-address verification
1345    /// is clean. Separately, a paged and a single build of the same input agree
1346    /// on the payload-independent address keys (the cross-build *blob* bytes are
1347    /// not comparable — Arrow IPC schema-metadata ordering isn't reproducible
1348    /// across `finalize` runs, the documented D6 caveat; the codec-level
1349    /// "paged == whole-load" equality is proven in `directory_page` tests).
1350    #[test]
1351    fn paged_directory_writer_roundtrips_and_matches_single() {
1352        let bucket = 3_600_000i64;
1353        // Deterministic input tiles: (id, time_start, time_end, payload).
1354        let mut input: Vec<(TileId, i64, i64, Vec<u8>)> = Vec::new();
1355        for k in 0..120u64 {
1356            let zoom = [6u8, 10, 13][(k % 3) as usize];
1357            let b = (k % 4) as i64;
1358            let t = b * bucket;
1359            let id = TileId::new(zoom, (k % 11) as u32, (k / 11) as u32, t as u64);
1360            input.push((id, t, t + bucket - 1, distinct_tile(k)));
1361        }
1362        let build = |out: &Path, page_entries: Option<usize>| -> Manifest {
1363            let mut w = PackWriter::create(out, BlobOrdering::Auto, 16 * 1024)
1364                .unwrap()
1365                .with_paging(page_entries);
1366            for (id, ts, te, payload) in &input {
1367                w.add_tile_full(id, *ts, *te, Some(*ts), 6, Some(bucket as u64), payload)
1368                    .unwrap();
1369            }
1370            let meta = Metadata::new("paged-roundtrip").with_temporal_bucket_ms(bucket as u64);
1371            w.finalize(&meta).unwrap()
1372        };
1373
1374        let dir = tempfile::tempdir().unwrap();
1375        let single_out = dir.path().join("single");
1376        let paged_out = dir.path().join("paged");
1377        let single = build(&single_out, None);
1378        // Small page size to force several leaf pages over 120 entries.
1379        let paged = build(&paged_out, Some(16));
1380
1381        // Paged manifest carries the container fields; single does not.
1382        assert!(single.directory.layout.is_none());
1383        assert_eq!(paged.directory.layout.as_deref(), Some(DIRECTORY_LAYOUT_PAGED));
1384        assert!(paged.directory.root_length.unwrap() > 0);
1385        assert!(paged.directory.page_count.unwrap() >= 2, "expected multiple leaf pages");
1386        assert_eq!(paged.directory.page_entries, Some(16));
1387        assert_eq!(paged.directory.directory_version, crate::directory::DIRECTORY_VERSION);
1388        assert_eq!(paged.directory.encoding.as_deref(), Some(DIRECTORY_ENCODING_ZSTD));
1389
1390        let r_single = PackedReader::open(single_out.join("manifest.json")).unwrap();
1391        let r_paged = PackedReader::open(paged_out.join("manifest.json")).unwrap();
1392        assert_eq!(r_paged.entries().len(), 120);
1393        assert_eq!(r_single.entries().len(), 120);
1394
1395        // Cross-build agreement on payload-INDEPENDENT address keys (sorted, so
1396        // the comparison ignores blob-byte non-reproducibility).
1397        let keys = |r: &PackedReader| -> Vec<(u8, u32, u32, i64, i64, u32, Option<u64>, Option<i64>)> {
1398            let mut v: Vec<_> = r
1399                .entries()
1400                .iter()
1401                .map(|e| {
1402                    (
1403                        e.zoom, e.x, e.y, e.time_start, e.time_end, e.feature_count,
1404                        e.temporal_bucket_ms, e.cover_t_min,
1405                    )
1406                })
1407                .collect();
1408            v.sort();
1409            v
1410        };
1411        assert_eq!(keys(&r_single), keys(&r_paged));
1412
1413        // Every INPUT tile decodes byte-identically through the paged reader.
1414        for (id, ts, _te, payload) in &input {
1415            let e = r_paged
1416                .entries()
1417                .iter()
1418                .find(|x| x.zoom == id.z && x.x == id.x && x.y == id.y && x.time_start == *ts)
1419                .expect("paged entry present");
1420            assert_eq!(&r_paged.read_payload(e).unwrap(), payload, "payload mismatch {id:?}");
1421        }
1422
1423        // Content-address integrity verifies clean on the paged dataset.
1424        let issues = verify_packed_objects(paged_out.join("manifest.json")).unwrap();
1425        assert!(issues.is_empty(), "paged verify issues: {issues:?}");
1426    }
1427
1428    /// `repack_directory` switches a built dataset's directory to paged WITHOUT
1429    /// re-reading payloads: the packs keep their exact content addresses, the
1430    /// re-opened entries are identical, and the result verifies clean.
1431    #[test]
1432    fn repack_directory_to_paged_preserves_packs_and_entries() {
1433        let dir = tempfile::tempdir().unwrap();
1434        let src = dir.path().join("src");
1435        let out = dir.path().join("out");
1436
1437        // A small single-directory dataset.
1438        let mut w = PackWriter::create(&src, BlobOrdering::Auto, 16 * 1024).unwrap();
1439        for k in 0..80u64 {
1440            let zoom = [8u8, 11][(k % 2) as usize];
1441            let t = (k % 3) as i64 * 3_600_000;
1442            let id = TileId::new(zoom, (k % 9) as u32, (k / 9) as u32, t as u64);
1443            w.add_tile_full(&id, t, t + 3_599_999, Some(t), 4, Some(3_600_000), &distinct_tile(k))
1444                .unwrap();
1445        }
1446        let src_manifest = w.finalize(&Metadata::new("repack-src")).unwrap();
1447        assert!(src_manifest.directory.layout.is_none());
1448
1449        // Directory-only re-pack into a fresh dir, paged.
1450        let out_manifest = repack_directory(src.join("manifest.json"), &out, Some(8)).unwrap();
1451        assert_eq!(out_manifest.directory.layout.as_deref(), Some(DIRECTORY_LAYOUT_PAGED));
1452        assert!(out_manifest.directory.page_count.unwrap() >= 2);
1453
1454        // Packs are byte-identical content addresses (only the directory changed).
1455        let src_keys: std::collections::BTreeSet<&str> =
1456            src_manifest.packs.iter().map(|p| p.key.as_str()).collect();
1457        let out_keys: std::collections::BTreeSet<&str> =
1458            out_manifest.packs.iter().map(|p| p.key.as_str()).collect();
1459        assert_eq!(src_keys, out_keys);
1460
1461        // Re-opened entries are identical, and integrity verifies clean.
1462        let r_src = PackedReader::open(src.join("manifest.json")).unwrap();
1463        let r_out = PackedReader::open(out.join("manifest.json")).unwrap();
1464        assert_eq!(r_src.entries(), r_out.entries());
1465        // A payload reads back identically through the re-packed (paged) dataset.
1466        let e = &r_out.entries()[0];
1467        assert_eq!(r_out.read_payload(e).unwrap(), r_src.read_payload(e).unwrap());
1468        assert!(verify_packed_objects(out.join("manifest.json")).unwrap().is_empty());
1469    }
1470
1471    /// A single blob larger than the pack target gets its own pack (never split).
1472    #[test]
1473    fn oversized_blob_gets_its_own_pack() {
1474        let dir = tempfile::tempdir().unwrap();
1475        let out = dir.path().join("dataset");
1476
1477        // One big tile (lots of distinct points → big compressed blob) plus a
1478        // few small ones, with a target smaller than the big blob.
1479        let big_ids: Vec<u64> = (0..4000).collect();
1480        let big = encode_tile(&[ColumnarLayer {
1481            name: "default".to_string(),
1482            feature_ids: big_ids.clone(),
1483            start_times: vec![0; big_ids.len()],
1484            end_times: vec![100; big_ids.len()],
1485            geometry: GeometryColumn::Point(
1486                (0..big_ids.len()).map(|i| [i as f64 * 0.01, i as f64 * 0.013]).collect(),
1487            ),
1488            vertex_times: None,
1489            vertex_values: None,
1490            triangles: None,
1491            vertex_value_matrix: None,
1492            properties: vec![],
1493        }])
1494        .unwrap();
1495        let big_compressed_len = compression::compress_zstd_with_dict(&big, None).unwrap().len();
1496
1497        let mut w = PackWriter::create(&out, BlobOrdering::SpatialMajor, 4 * 1024).unwrap();
1498        // target 4 KiB < big blob.
1499        assert!(big_compressed_len as u64 > 4 * 1024);
1500        w.add_tile_full(&TileId::new(10, 0, 0, 0), 0, 100, None, 4000, None, &big).unwrap();
1501        for k in 1..4u64 {
1502            let p = distinct_tile(k);
1503            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p).unwrap();
1504        }
1505        let _manifest = w.finalize(&Metadata::new("big")).unwrap();
1506
1507        // At least one pack exceeds the target (the loner). Reading proves it.
1508        let reader = PackedReader::open(out.join("manifest.json")).unwrap();
1509        let big_entry = reader.entries().iter().find(|e| e.x == 0).unwrap();
1510        assert_eq!(reader.read_payload(big_entry).unwrap(), big);
1511    }
1512
1513    /// Two builds of the same input — added in different orders, including
1514    /// curve-key ties (a base + temporal-LOD entry on one cell) — must produce
1515    /// byte-identical objects: same pack hashes, same directory hash. This is
1516    /// the immutable-pack CDN contract (a rebuild of unchanged data must not
1517    /// invalidate the edge cache).
1518    #[test]
1519    fn rebuilds_are_byte_reproducible() {
1520        // Tiles including a tie pair: same (z, x, y, time_start), one base
1521        // (bucket None) and one LOD (bucket Some) — the curve key alone can't
1522        // order them, the tiebreak must.
1523        let bucket = 3_600_000i64;
1524        let mut tiles: Vec<(TileId, i64, Option<u64>, Vec<u8>)> = Vec::new();
1525        for k in 0..10u64 {
1526            let t = (k % 4) as i64 * bucket;
1527            tiles.push((
1528                TileId::new(9, (k % 5) as u32, (k / 5) as u32, t as u64),
1529                t,
1530                None,
1531                distinct_tile(k),
1532            ));
1533        }
1534        // The tie pair on cell (1, 0): base + LOD aggregate at one time_start.
1535        tiles.push((TileId::new(9, 1, 0, 0), 0, None, distinct_tile(100)));
1536        tiles.push((
1537            TileId::new(9, 1, 0, 0),
1538            0,
1539            Some(24 * bucket as u64),
1540            distinct_tile(101),
1541        ));
1542
1543        let meta = Metadata::new("repro").with_temporal_bucket_ms(bucket as u64);
1544        let build = |order: &[usize]| {
1545            let dir = tempfile::tempdir().unwrap();
1546            let out = dir.path().join("dataset");
1547            let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1548            for &i in order {
1549                let (id, t, b, payload) = &tiles[i];
1550                w.add_tile_full(id, *t, t + bucket - 1, Some(*t), 6, *b, payload)
1551                    .unwrap();
1552            }
1553            let manifest = w.finalize(&meta).unwrap();
1554            (dir, manifest)
1555        };
1556
1557        let forward: Vec<usize> = (0..tiles.len()).collect();
1558        let reverse: Vec<usize> = (0..tiles.len()).rev().collect();
1559        let (_d1, m1) = build(&forward);
1560        let (_d2, m2) = build(&reverse);
1561
1562        assert_eq!(m1.directory.key, m2.directory.key, "directory hash must be stable");
1563        assert_eq!(
1564            m1.packs.iter().map(|p| &p.key).collect::<Vec<_>>(),
1565            m2.packs.iter().map(|p| &p.key).collect::<Vec<_>>(),
1566            "pack hashes must be stable across rebuilds"
1567        );
1568        assert_eq!(m1.to_json_bytes().unwrap(), m2.to_json_bytes().unwrap());
1569    }
1570
1571    /// The directory ships zstd-compressed at rest (declared via
1572    /// `directory.encoding`), and a legacy manifest with a RAW directory and
1573    /// no `encoding` key — the shape of every deployed dataset — must still
1574    /// open and verify.
1575    #[test]
1576    fn directory_encoding_compressed_and_raw_both_read() {
1577        let dir = tempfile::tempdir().unwrap();
1578        let out = dir.path().join("dataset");
1579        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1580        for k in 0..8u64 {
1581            let p = distinct_tile(k);
1582            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p)
1583                .unwrap();
1584        }
1585        let manifest = w.finalize(&Metadata::new("dir-enc")).unwrap();
1586        let manifest_path = out.join("manifest.json");
1587
1588        // Fresh output declares the encoding and the at-rest bytes are a
1589        // valid zstd frame that inflates to the codec bytes.
1590        assert_eq!(manifest.directory.encoding.as_deref(), Some("zstd"));
1591        let at_rest = fs::read(out.join(&manifest.directory.key)).unwrap();
1592        assert_eq!(at_rest.len() as u64, manifest.directory.length);
1593        let raw = compression::decompress_zstd_with_dict(&at_rest, None).unwrap();
1594        assert!(crate::directory::decode_directory(&raw).is_ok());
1595        assert!(verify_packed_objects(&manifest_path).unwrap().is_empty());
1596        let entries_compressed = PackedReader::open(&manifest_path).unwrap().entries().to_vec();
1597
1598        // Rewrite the dataset as a legacy (raw-directory) manifest: store the
1599        // raw codec bytes under their own content address and drop `encoding`.
1600        let raw_hex = blake3_128_hex(&raw);
1601        let raw_rel = format!("index/{raw_hex}.sttd");
1602        fs::write(out.join(&raw_rel), &raw).unwrap();
1603        let mut legacy = manifest.clone();
1604        legacy.directory = DirectoryRef {
1605            key: raw_rel,
1606            length: raw.len() as u64,
1607            directory_version: crate::directory::DIRECTORY_VERSION,
1608            encoding: None,
1609            layout: None,
1610            root_length: None,
1611            page_count: None,
1612            page_entries: None,
1613        };
1614        fs::write(&manifest_path, legacy.to_json_bytes().unwrap()).unwrap();
1615
1616        assert!(verify_packed_objects(&manifest_path).unwrap().is_empty());
1617        let entries_raw = PackedReader::open(&manifest_path).unwrap().entries().to_vec();
1618        assert_eq!(entries_raw, entries_compressed);
1619
1620        // An unknown encoding must fail loudly, not decode garbage.
1621        legacy.directory.encoding = Some("br".to_string());
1622        fs::write(&manifest_path, legacy.to_json_bytes().unwrap()).unwrap();
1623        assert!(PackedReader::open(&manifest_path).is_err());
1624    }
1625
1626    /// A clean packed dataset verifies with no issues; corrupting a pack's
1627    /// bytes (without changing its length) breaks the content address and is
1628    /// reported.
1629    #[test]
1630    fn verify_packed_objects_clean_then_detects_corruption() {
1631        let dir = tempfile::tempdir().unwrap();
1632        let out = dir.path().join("dataset");
1633
1634        let mut w = PackWriter::create(&out, BlobOrdering::Auto, 8 * 1024).unwrap();
1635        for k in 0..12u64 {
1636            let p = distinct_tile(k);
1637            w.add_tile_full(&TileId::new(10, k as u32, 0, 0), 0, 100, None, 6, None, &p)
1638                .unwrap();
1639        }
1640        let manifest = w.finalize(&Metadata::new("verify")).unwrap();
1641        let manifest_path = out.join("manifest.json");
1642
1643        // Clean dataset → no integrity violations.
1644        assert!(verify_packed_objects(&manifest_path).unwrap().is_empty());
1645
1646        // Flip a byte in pack 0: same length, but blake3 no longer matches the
1647        // filename it was addressed by.
1648        let pack0 = out.join(&manifest.packs[0].key);
1649        let mut bytes = fs::read(&pack0).unwrap();
1650        bytes[0] ^= 0xff;
1651        fs::write(&pack0, &bytes).unwrap();
1652
1653        let issues = verify_packed_objects(&manifest_path).unwrap();
1654        assert!(
1655            issues.iter().any(|s| s.contains("content-address mismatch")),
1656            "expected a content-address mismatch, got {issues:?}"
1657        );
1658    }
1659}