Skip to main content

limnifs_write/
lib.rs

1//! `LimniFS` writer pipeline — directory tree to `.lim` image.
2//!
3//! The writer takes a real directory tree and produces a valid `.lim`
4//! manifest artifact with inlined metadata. Files at or below the
5//! inline threshold (4 KiB) are stored as inline data in their inodes;
6//! larger files are stored as drops packed into a single slab.
7//!
8//! ## Usage
9//!
10//! ```no_run
11//! use std::path::Path;
12//! use limnifs_write::write_directory;
13//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
14//! let artifact = write_directory(Path::new("/path/to/dir"))?;
15//! std::fs::write("output.lim", &artifact.bytes)?;
16//! # Ok(())
17//! # }
18//! ```
19
20#![deny(unsafe_code)]
21#![allow(warnings)]
22
23pub mod chunker;
24pub mod classifier;
25pub mod compaction;
26pub mod config;
27pub mod delta_builder;
28pub mod dictionary;
29pub mod file_categorizer;
30pub mod flatten;
31#[cfg(feature = "pipeline-parallelism")]
32pub mod pipeline;
33pub mod rw;
34#[cfg(feature = "sparse-index")]
35pub mod sparse_index;
36pub mod turnover;
37
38pub use config::{
39    profile, CategorizerConfig, ChunkingConfig, CodecRegistry, CodecTunables, Defaults,
40    DictionaryConfig, EncryptionConfig, TournamentConfig, WriteConfig,
41};
42
43use std::collections::{HashMap, HashSet};
44use std::path::{Path, PathBuf};
45
46use crate::chunker::FastCDC;
47use limnifs_core::codec::CODEC_REFERENCED;
48use limnifs_core::slab_store::SlabStore;
49use limnifs_core::{
50    compute_merkle_root, hash_empty_section, hash_section, parse_manifest_header, parse_slab_index,
51    ManifestCursor, ManifestHeader, SectionHashes, FEATURE_FLAGS_SECTION_VERSION,
52    HISTORY_SECTION_VERSION, INODE_FLAG_INLINE_DATA, INODE_FLAG_SHARED_INLINE,
53    METADATA_REFERENCE_SECTION_VERSION_2, SLAB_INDEX_SECTION_VERSION,
54};
55use limnifs_format::{ManifestRoot, SlabId};
56
57/// Inline-data threshold: files at or below this size get inline data
58/// in their inode. Larger files are stored as drops in a slab.
59pub const INLINE_THRESHOLD: usize = 4096;
60
61/// Above this size, mmap the input file instead of `std::fs::read`-ing
62/// it into a `Vec<u8>`. Keeps peak RSS bounded when packing huge files
63/// (multi-GiB source trees, ML models). Crossover is around 1 MiB on
64/// most filesystems — below that the syscall + VMA setup costs more
65/// than the read.
66pub const MMAP_READ_THRESHOLD: usize = 1024 * 1024;
67
68/// Maximum file size for the whole-file categorizer path. Files above
69/// this threshold use FastCDC chunking even when a categorizer claims
70/// them, enabling rayon parallelism across chunks. The categorizer's
71/// codec is still used per-chunk when possible.
72pub const WHOLE_FILE_MAX_SIZE: usize = 64 * 1024 * 1024;
73
74/// Maximum total length of a single slab file (header + content).
75/// Matches the reader's `DEFAULT_SLAB_MAX_BYTES` (spec §3.1) minus a
76/// safety margin so a slab that is full but not yet flushed cannot
77/// overrun the reader ceiling on the next drop.
78pub const MAX_SLAB_TOTAL_BYTES: usize = 60 * 1024 * 1024;
79
80/// Width of the slab header (magic + version + `SlabId` + `total_length` +
81/// `ec_descriptor` + `crypto_hint`). Must agree with
82/// `limnifs_core::slab::SLAB_HEADER_LEN`.
83const SLAB_HEADER_LEN: usize = 56;
84
85/// Default threshold at which the writer externalises the metadata
86/// blob to a sidecar file instead of inlining it in the manifest.
87/// Derived from the reader's inline ceiling
88/// (`limnifs_core::metadata_reference::DEFAULT_INLINE_METADATA_MAX_BYTES`,
89/// 1 MiB per spec §5.3) minus headroom, so the two constants cannot
90/// silently drift apart. Override per image via
91/// `WriteConfig::defaults::metadata_externalize_threshold` (issue #187).
92pub const METADATA_EXTERNALIZE_THRESHOLD: usize =
93    limnifs_core::metadata_reference::DEFAULT_INLINE_METADATA_MAX_BYTES as usize - 24 * 1024;
94
95/// Metadata-blob size above which the writer steps Brotli quality
96/// down to `METADATA_LARGE_BLOB_QUALITY`. Below this, q5's cost is
97/// negligible; above it, q5 starts to dominate create time on big
98/// inode trees (e.g. the 50 K-file tiny-files dataset).
99pub const METADATA_LARGE_BLOB_THRESHOLD: usize = 256 * 1024;
100
101/// Brotli quality for small metadata blobs (≤ `METADATA_LARGE_BLOB_THRESHOLD`).
102/// Best ratio; cost is in the noise on small inputs.
103pub const METADATA_SMALL_BLOB_QUALITY: i32 = 5;
104
105/// Brotli quality for large metadata blobs. q2 is much faster than q5
106/// on multi-MiB inputs; ratio on highly compressible inode data is
107/// within 5–10% of q5 (often identical) because metadata is dominated
108/// by long runs of repeated patterns.
109pub const METADATA_LARGE_BLOB_QUALITY: i32 = 2;
110
111/// One slab produced by the writer. The slab ordinal in `id` matches
112/// the slab's position in `WriteArtifact::slabs`.
113#[derive(Clone, Debug)]
114pub struct SlabArtifact {
115    pub id: SlabId,
116    pub bytes: Vec<u8>,
117    pub locator: String,
118    /// `DropIds` contained in this slab, in slab order. Used by callers
119    /// that need to know which slab holds which drop without re-parsing
120    /// the slab bytes.
121    pub drop_ids: Vec<[u8; 32]>,
122}
123
124/// Externalized metadata sidecar, present when the metadata blob
125/// exceeds [`METADATA_EXTERNALIZE_THRESHOLD`]. Callers must write
126/// `bytes` to `locator` next to the manifest file.
127#[derive(Clone, Debug)]
128pub struct MetadataSidecar {
129    pub bytes: Vec<u8>,
130    pub locator: String,
131}
132
133/// Result of writing a directory tree.
134#[derive(Clone, Debug)]
135pub struct WriteArtifact {
136    pub bytes: Vec<u8>,
137    pub merkle_root: ManifestRoot,
138    /// All slabs produced by the writer, in slab-ordinal order. Empty
139    /// when the source tree had no files > [`INLINE_THRESHOLD`].
140    pub slabs: Vec<SlabArtifact>,
141    /// External metadata sidecar, present when the metadata blob
142    /// exceeds [`METADATA_EXTERNALIZE_THRESHOLD`]. `None` means the
143    /// metadata is inlined in the manifest.
144    pub metadata_sidecar: Option<MetadataSidecar>,
145    pub inode_count: usize,
146    pub file_count: usize,
147    pub dir_count: usize,
148    pub drop_count: usize,
149    /// Inode number of the root directory (i.e. the inode that
150    /// represents the source directory itself, not a child of it).
151    /// Always a directory and always referenced by the inlined
152    /// metadata blob's directory inode table.
153    pub root_inode_number: u64,
154}
155
156impl WriteArtifact {
157    /// Convenience accessor for the single-slab case. Returns the
158    /// first slab's bytes if there is exactly one slab, else `None`.
159    /// Modern callers should iterate [`WriteArtifact::slabs`] directly.
160    #[must_use]
161    pub fn slab_bytes(&self) -> Option<&[u8]> {
162        if self.slabs.len() == 1 {
163            Some(&self.slabs[0].bytes)
164        } else {
165            None
166        }
167    }
168
169    /// Convenience accessor for the single-slab case.
170    #[must_use]
171    pub fn slab_locator(&self) -> Option<&str> {
172        if self.slabs.len() == 1 {
173            Some(&self.slabs[0].locator)
174        } else {
175            None
176        }
177    }
178}
179
180/// Error during writing.
181#[derive(Debug)]
182pub enum WriteError {
183    Io(std::io::Error),
184}
185
186impl std::fmt::Display for WriteError {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        match self {
189            Self::Io(e) => write!(f, "I/O error: {e}"),
190        }
191    }
192}
193
194impl std::error::Error for WriteError {}
195
196impl From<std::io::Error> for WriteError {
197    fn from(e: std::io::Error) -> Self {
198        Self::Io(e)
199    }
200}
201
202/// Walk a directory tree and produce a valid `.lim` manifest artifact
203/// with inlined metadata. Files at or below [`INLINE_THRESHOLD`] bytes
204/// are stored inline; larger files are packed into a single slab as
205/// content-addressed drops.
206///
207/// File contents (read, `FastCDC` chunk, `BLAKE3` hash, `LZ4` compress) are
208/// processed in parallel across `CPU` cores via `rayon`. The directory
209/// tree walk and slab assembly remain sequential so the output is
210/// deterministic.
211///
212/// # Errors
213///
214/// Returns [`WriteError::Io`] for filesystem errors.
215pub fn write_directory(root: &Path) -> Result<WriteArtifact, WriteError> {
216    write_directory_with_config(root, &WriteConfig::default_v0_1())
217}
218
219/// Pack a single named stream into a `.lim` image.
220///
221/// For callers that pipe data from a network socket, pipe, or generator
222/// and don't want to materialise the full content on disk before
223/// packing. The reader is consumed via [`FastCDC::chunk_reader`] which
224/// bounds internal buffering at `max_chunk_size + 64 KiB`.
225///
226/// The resulting image has a single root file with the given `name`
227/// (path-relative; safe to use `/` for subdirectories — they're
228/// materialised in the metadata tree).
229///
230/// # Errors
231///
232/// Returns [`WriteError::Io`] on read failure or any writer-pipeline
233/// error.
234pub fn write_stream<R: std::io::Read>(
235    name: &str,
236    reader: R,
237    config: &WriteConfig,
238) -> Result<WriteArtifact, WriteError> {
239    let mut ctx = WriteContext::new();
240    ctx.categorizers_disabled = config.categorizers.is_empty();
241    ctx.rw_mode = matches!(config.mode, crate::config::ImageMode::ReadWrite(_));
242    ctx.auto_turnover = config.turnover_threshold > 0;
243    ctx.collect_dict_samples = config.dictionaries.enabled;
244
245    // Synthesise a single PendingFile that points to nothing on disk;
246    // we'll bypass process_file's `std::fs::read` and feed the
247    // pre-chunked bytes directly.
248    let drop_id_root = [0u8; 32]; // placeholder; replaced below
249    let pending = PendingFile {
250        path: std::path::PathBuf::from(name),
251        inode_number: 1,
252        file_len: 0, // patched below once we know the total
253        mtime_ns: 0,
254    };
255    ctx.pending_files.push(pending);
256    ctx.root_inode_number = 1;
257
258    // Chunk the stream directly via FastCDC's chunk_reader.
259    let chunker = ctx.chunker.clone();
260    let chunks = chunker.chunk_reader(reader)?;
261
262    // Total size = sum of chunk lengths.
263    let total_len: u64 = chunks.iter().map(|c| c.len() as u64).sum();
264
265    // Hash + compress each chunk. We treat each chunk as a unique drop
266    // (the stream is single-pass; cross-call dedup is left to the
267    // caller). Use the configured tournament spec.
268    let text_codec = config.text_codec_id().unwrap_or(0x04);
269    let binary_codec = config.binary_codec_id().unwrap_or(0x01);
270    let tunables = config.to_core_tunables();
271    let classifier = ctx.classifier;
272    let registry = config
273        .codec_registry()
274        .map_err(|e| WriteError::Io(std::io::Error::other(format!("codec registry: {e}"))))?;
275    let tournament_codec_ids: Vec<u8> = config
276        .tournament
277        .codecs
278        .iter()
279        .filter_map(|n| registry.lookup_by_name(n))
280        .collect();
281    let tournament = TournamentSpec {
282        codec_ids: tournament_codec_ids,
283        min_size: config.tournament.min_size_threshold as usize,
284        skip_for_binary: config.tournament.skip_for_binary,
285        short_circuit_permille: config.tournament.short_circuit_threshold,
286    };
287
288    let mut drops: Vec<RawDrop> = Vec::with_capacity(chunks.len());
289    let mut slices: Vec<PendingSlice> = Vec::with_capacity(chunks.len());
290    let mut offset: u64 = 0;
291    for chunk in &chunks {
292        let drop_id = hash_section(chunk);
293        slices.push(PendingSlice {
294            drop_id,
295            file_byte_start: offset,
296            file_byte_end: offset + chunk.len() as u64,
297        });
298        offset += chunk.len() as u64;
299        let class = classifier.classify(chunk);
300        let (codec_id, compressed) = compress_chunk_with_tournament(
301            chunk,
302            class,
303            text_codec,
304            binary_codec,
305            &tunables,
306            &tournament,
307        );
308        drops.push((drop_id, chunk.clone(), compressed, codec_id));
309    }
310    let _ = drop_id_root;
311
312    // Wire into WriteContext as a single-file result + inode.
313    let result = ChunkedFileResult { drops, slices };
314    let pf = ctx.pending_files[0].clone();
315    ctx.merge_chunked_file(&pf, result);
316    // Patch the file_len now that we know it.
317    ctx.pending_files[0].file_len = total_len;
318    // The inode was already pushed by merge_chunked_file with the old
319    // (zero) file_len; correct it.
320    if let Some(inode) = ctx.inodes.last_mut() {
321        if let PendingContent::DropBacked { file_len, .. } = &mut inode.content {
322            *file_len = total_len;
323        }
324    }
325
326    ctx.train_and_apply_dictionary(&config.dictionaries);
327    let artifact = ctx.assemble();
328    Ok(artifact)
329}
330
331/// Pack a directory tree as a **layer** on top of a base image.
332///
333/// Produces a `.lim` image whose drops are split into two sets:
334///
335/// - **Local drops** — chunks in `root` whose `DropId` is NOT in
336///   `base_image`'s drop set. These are compressed and stored in the
337///   layer's own slabs exactly as `write_directory_with_config`
338///   would store them.
339/// - **Referenced drops** — chunks whose `DropId` IS in the base.
340///   These are recorded only as `PendingSlice` references (so the
341///   metadata tree links them in); no slab bytes are emitted in the
342///   layer. The reader resolves them via the overlay chain.
343///
344/// The resulting manifest carries a `delta_linkage` section pointing
345/// at the base image's `ManifestRoot`, so any reader that supports
346/// overlay chains can extract the layer standalone or stacked on the
347/// base.
348///
349/// # Determinism
350///
351/// `write_layer` is deterministic given the same `base_image`, the
352/// same `root` content, and the same `config`. Two runs produce
353/// byte-identical layer images.
354///
355/// # Errors
356///
357/// Returns [`WriteError::Io`] on read failure or any writer-pipeline
358/// error.
359///
360/// # Example
361///
362/// ```no_run
363/// use limnifs_write::{write_layer, profile};
364///
365/// let base = std::path::Path::new("base.lim");
366/// let root = std::path::Path::new("./new-content");
367/// let cfg = profile::balanced();
368/// let artifact = write_layer(base, root, &cfg).expect("layer");
369/// // artifact.bytes is the layer manifest; slabs contain only NEW drops.
370/// ```
371pub fn write_layer(
372    base_image: &Path,
373    root: &Path,
374    config: &WriteConfig,
375) -> Result<WriteArtifact, WriteError> {
376    // Load the base image's drop set + manifest root.
377    let (base_drop_index, base_root) = load_base_drop_index(base_image)?;
378
379    let mut ctx = WriteContext::new();
380    ctx.categorizers_disabled = config.categorizers.is_empty();
381    ctx.rw_mode = matches!(config.mode, crate::config::ImageMode::ReadWrite(_));
382    ctx.auto_turnover = config.turnover_threshold > 0;
383    ctx.collect_dict_samples = config.dictionaries.enabled;
384    ctx.inline_threshold = config.defaults.inline_threshold as usize;
385    ctx.metadata_externalize_threshold = config.defaults.metadata_externalize_threshold;
386    ctx.base_drop_index = Some(base_drop_index);
387    ctx.base_root = Some(base_root);
388
389    // Rest is identical to write_directory_with_config.
390    let root_inode_number = ctx.walk(root)?;
391    ctx.root_inode_number = root_inode_number;
392    write_directory_body(&mut ctx, config)?;
393    Ok(ctx.assemble())
394}
395
396/// Load every DropId present in a base image's slabs + the image's
397/// `ManifestRoot`. Used by `write_layer` to decide which chunks can
398/// be referenced rather than re-encoded.
399fn load_base_drop_index(
400    base_image: &Path,
401) -> Result<(std::collections::HashSet<[u8; 32]>, [u8; 32]), WriteError> {
402    let manifest_bytes = std::fs::read(base_image)?;
403    let mut cursor = ManifestCursor::new(&manifest_bytes);
404    let _ = parse_manifest_header(&mut cursor).map_err(io_core)?;
405    // Walk sections in spec order: flags → metadata_reference → slab_index.
406    let _ = limnifs_core::parse_feature_flags_section(&mut cursor);
407    let _ = limnifs_core::parse_metadata_reference(&mut cursor);
408    let slab_index = parse_slab_index(&mut cursor).map_err(io_core)?;
409    let store = SlabStore::load_mmap(base_image, &slab_index).map_err(io_core)?;
410    let drop_set: std::collections::HashSet<[u8; 32]> = store.drop_index_keys().copied().collect();
411    // Re-derive the Merkle root from the base manifest's section
412    // bytes. The base's `ManifestRoot` is the canonical anchor for
413    // the layer's `delta_linkage.base_root` field — round-tripping
414    // through section hashes guarantees it matches what the base
415    // reported on its own assemble path.
416    let root = *compute_merkle_root_from_sections(&manifest_bytes).as_bytes();
417    Ok((drop_set, root))
418}
419
420/// Re-derive a manifest's `ManifestRoot` from its on-disk section
421/// bytes. Mirrors `flatten::compute_merkle_root_from_sections` but
422/// tolerates absent optional sections (returns hash_empty_section()
423/// for them). Used by `load_base_drop_index` to anchor a layer's
424/// `base_root` without re-instantiating a full manifest parser.
425fn compute_merkle_root_from_sections(manifest: &[u8]) -> ManifestRoot {
426    use limnifs_core::SectionHashes;
427    let mut cursor = ManifestCursor::new(manifest);
428    let header_start = 0;
429    if parse_manifest_header(&mut cursor).is_err() {
430        // Not a valid manifest; fall back to all-zero root.
431        return ManifestRoot::from_bytes([0u8; 32]);
432    }
433    let header_end = cursor.position();
434    // Optional sections — best-effort parse; failures hash as empty.
435    let flags_start = header_end;
436    let flags_end = match limnifs_core::parse_feature_flags_section(&mut cursor) {
437        Ok(_) => cursor.position(),
438        Err(_) => flags_start,
439    };
440    let meta_ref_start = flags_end;
441    let metadata_reference = match limnifs_core::parse_metadata_reference(&mut cursor) {
442        Ok(m) => Some(m),
443        Err(_) => None,
444    };
445    let meta_ref_end = cursor.position();
446    let slab_index_start = meta_ref_end;
447    let _ = parse_slab_index(&mut cursor);
448    let slab_index_end = cursor.position();
449    let history_start = slab_index_end;
450    let _ = limnifs_core::parse_history(&mut cursor);
451    let history_end = cursor.position();
452
453    let hashes = SectionHashes {
454        metadata: metadata_reference
455            .map(|m| m.metadata_hash)
456            .unwrap_or_else(hash_empty_section),
457        format_header: hash_section(&manifest[header_start..header_end]),
458        feature_flags: hash_section(&manifest[flags_start..flags_end]),
459        metadata_reference: hash_section(&manifest[meta_ref_start..meta_ref_end]),
460        slab_index: hash_section(&manifest[slab_index_start..slab_index_end]),
461        crypto_params: hash_empty_section(),
462        ec_params: hash_empty_section(),
463        dms_policy: hash_empty_section(),
464        delta_linkage: hash_empty_section(),
465        history: hash_section(&manifest[history_start..history_end]),
466    };
467    compute_merkle_root(&hashes)
468}
469
470fn io_core(e: limnifs_core::CoreError) -> WriteError {
471    WriteError::Io(std::io::Error::other(format!("base image load: {e}")))
472}
473
474/// Shared body between `write_directory_with_config` and `write_layer`.
475/// Walks `ctx.pending_files` through `process_file` in parallel and
476/// merges the results back. Caller is responsible for `walk()` and
477/// `assemble()`.
478fn write_directory_body(ctx: &mut WriteContext, config: &WriteConfig) -> Result<(), WriteError> {
479    use rayon::prelude::*;
480
481    ctx.metadata_codec = config
482        .metadata_codec_id()
483        .unwrap_or(limnifs_core::codec::CODEC_BROTLI);
484
485    let pending = std::mem::take(&mut ctx.pending_files);
486    if pending.is_empty() {
487        return Ok(());
488    }
489    ctx.inline_threshold = config.defaults.inline_threshold as usize;
490    ctx.metadata_externalize_threshold = config.defaults.metadata_externalize_threshold;
491    let chunker = ctx.chunker.clone();
492    let classifier = ctx.classifier;
493    let text_codec = config.text_codec_id().unwrap_or(0x04);
494    let binary_codec = config.binary_codec_id().unwrap_or(0x01);
495    let tunables = config.to_core_tunables();
496    let use_categorizers = !config.categorizers.is_empty();
497    let skip_chunking = config.skip_chunking;
498    let registry = config
499        .codec_registry()
500        .map_err(|e| WriteError::Io(std::io::Error::other(format!("codec registry: {e}"))))?;
501    let tournament_codec_ids: Vec<u8> = config
502        .tournament
503        .codecs
504        .iter()
505        .filter_map(|n| registry.lookup_by_name(n))
506        .collect();
507    let tournament_spec = TournamentSpec {
508        codec_ids: tournament_codec_ids,
509        min_size: config.tournament.min_size_threshold as usize,
510        skip_for_binary: config.tournament.skip_for_binary,
511        short_circuit_permille: config.tournament.short_circuit_threshold,
512    };
513    let base_drop_index = ctx.base_drop_index.as_ref();
514    let inline_threshold = ctx.inline_threshold;
515    let results: Vec<ChunkedFileResult> = pending
516        .par_iter()
517        .map(|pf| {
518            process_file(
519                pf,
520                &chunker,
521                classifier,
522                text_codec,
523                binary_codec,
524                &tunables,
525                use_categorizers,
526                skip_chunking,
527                &tournament_spec,
528                base_drop_index,
529                inline_threshold,
530            )
531        })
532        .collect::<Result<Vec<_>, _>>()?;
533
534    for (pf, result) in pending.iter().zip(results) {
535        ctx.merge_chunked_file(pf, result);
536    }
537    ctx.train_and_apply_dictionary(&config.dictionaries);
538    Ok(())
539}
540
541/// Create an image with a custom [`WriteConfig`] (e.g. from a profile).
542pub fn write_directory_with_config(
543    root: &Path,
544    config: &WriteConfig,
545) -> Result<WriteArtifact, WriteError> {
546    let mut ctx = WriteContext::new();
547    ctx.categorizers_disabled = config.categorizers.is_empty();
548    ctx.rw_mode = matches!(config.mode, crate::config::ImageMode::ReadWrite(_));
549    ctx.auto_turnover = config.turnover_threshold > 0;
550    ctx.collect_dict_samples = config.dictionaries.enabled;
551
552    write_directory_streaming(&mut ctx, root, config)?;
553    Ok(ctx.assemble())
554}
555
556/// Walk + compress with producer/consumer overlap (TODO.perf/15).
557///
558/// The tree walk runs on a scoped producer thread and forwards each
559/// deferred file to a bounded channel; rayon workers (via `par_bridge`)
560/// compress while the walk is still descending. For warm-cache trees
561/// with few files this is equivalent to the collect-then-dispatch
562/// shape; for huge or cold-cache trees it hides walk latency behind
563/// compression.
564///
565/// **Determinism:** results are re-sequenced into walk order before
566/// merging, and inode allocation / dir-node construction are
567/// untouched, so the emitted bytes are identical to
568/// `write_directory_body` for the same input.
569fn write_directory_streaming(
570    ctx: &mut WriteContext,
571    root: &Path,
572    config: &WriteConfig,
573) -> Result<(), WriteError> {
574    use rayon::prelude::*;
575
576    ctx.metadata_codec = config
577        .metadata_codec_id()
578        .unwrap_or(limnifs_core::codec::CODEC_BROTLI);
579
580    let chunker = ctx.chunker.clone();
581    let classifier = ctx.classifier;
582    let text_codec = config.text_codec_id().unwrap_or(0x04);
583    let binary_codec = config.binary_codec_id().unwrap_or(0x01);
584    let tunables = config.to_core_tunables();
585    let use_categorizers = !config.categorizers.is_empty();
586    let skip_chunking = config.skip_chunking;
587    let registry = config
588        .codec_registry()
589        .map_err(|e| WriteError::Io(std::io::Error::other(format!("codec registry: {e}"))))?;
590    let tournament_codec_ids: Vec<u8> = config
591        .tournament
592        .codecs
593        .iter()
594        .filter_map(|n| registry.lookup_by_name(n))
595        .collect();
596    let tournament_spec = TournamentSpec {
597        codec_ids: tournament_codec_ids,
598        min_size: config.tournament.min_size_threshold as usize,
599        skip_for_binary: config.tournament.skip_for_binary,
600        short_circuit_permille: config.tournament.short_circuit_threshold,
601    };
602    // The producer thread owns `&mut ctx` for the duration of the
603    // walk, so the layer fast-path index travels as a clone.
604    let base_drop_index = ctx.base_drop_index.clone();
605    let inline_threshold = ctx.inline_threshold;
606
607    ctx.inline_threshold = config.defaults.inline_threshold as usize;
608    ctx.metadata_externalize_threshold = config.defaults.metadata_externalize_threshold;
609
610    // Bounded so the walk back-pressures if compression falls behind;
611    // the buffer is large enough to keep every worker fed on bursty
612    // directory layouts.
613    const PIPELINE_CAPACITY: usize = 256;
614    let (tx, rx) = std::sync::mpsc::sync_channel::<PendingFile>(PIPELINE_CAPACITY);
615    ctx.pending_sink = Some(tx);
616
617    let (root_inode_number, mut results): (
618        u64,
619        Vec<(usize, PendingFile, Result<ChunkedFileResult, WriteError>)>,
620    ) = std::thread::scope(|scope| {
621        let producer = {
622            let ctx = &mut *ctx;
623            let root = root;
624            scope.spawn(move || {
625                let r = ctx.walk(root);
626                // Disconnect the channel so the consumer's iterator
627                // terminates; the sink stays None until the next
628                // streaming write resets it after the scope.
629                ctx.pending_sink = None;
630                r
631            })
632        };
633        // par_bridge does not preserve order; carry the arrival index
634        // and re-sequence before merging.
635        let results = rx
636            .into_iter()
637            .enumerate()
638            .par_bridge()
639            .map(|(i, pf)| {
640                let r = process_file(
641                    &pf,
642                    &chunker,
643                    classifier,
644                    text_codec,
645                    binary_codec,
646                    &tunables,
647                    use_categorizers,
648                    skip_chunking,
649                    &tournament_spec,
650                    base_drop_index.as_ref(),
651                    inline_threshold,
652                );
653                (i, pf, r)
654            })
655            .collect();
656        let joined = producer
657            .join()
658            .unwrap_or_else(|_| {
659                Err(WriteError::Io(std::io::Error::other(
660                    "walk thread panicked",
661                )))
662            })
663            .map(|n| (n, results));
664        // Scope can't `?` across borrows of `results`; return the
665        // outcome and propagate outside.
666        joined
667    })?;
668    ctx.pending_sink = None;
669    ctx.root_inode_number = root_inode_number;
670
671    results.sort_unstable_by_key(|(i, _, _)| *i);
672    // Fail on the lowest walk index first, matching the
673    // collect::<Result<Vec<_>, _>> abort semantics of the
674    // collect-then-dispatch shape.
675    for (_, pf, r) in results {
676        ctx.merge_chunked_file(&pf, r?);
677    }
678    ctx.train_and_apply_dictionary(&config.dictionaries);
679    Ok(())
680}
681
682/// One chunk of a file before dedup: (`drop_id`, `plaintext`, `compressed`, `codec`).
683///
684/// `compressed` is `Arc<[u8]>` so the cross-file compress cache can
685/// share bytes across hits with a refcount bump instead of a deep
686/// copy — dedup-heavy workloads (container layers, duplicate files)
687/// skip the allocation entirely.
688pub(crate) type RawDrop = ([u8; 32], Vec<u8>, std::sync::Arc<[u8]>, u8);
689/// Result of parallel file processing: the drop data (uncompressed,
690pub(crate) struct ChunkedFileResult {
691    drops: Vec<RawDrop>, // (id, plaintext, compressed, codec)
692    slices: Vec<PendingSlice>,
693}
694
695/// Resolved tournament configuration passed to per-chunk compression.
696///
697/// Built once at the top level from `WriteConfig::tournament` so each
698/// rayon worker reuses the same Vec rather than rebuilding it per
699/// file. Codecs are stored as numeric ids (looked up via
700/// `WriteConfig::codec_registry`) — `process_file` never sees the
701/// string form.
702struct TournamentSpec {
703    /// Codec ids to try, in declared order. `process_file` iterates
704    /// these and tracks the best compression. `CODEC_STORE` entries
705    /// are ignored (store is always the implicit fallback).
706    codec_ids: Vec<u8>,
707    /// Chunks below this many bytes get the preferred codec only
708    /// (no tournament) — the per-codec setup cost dominates at small
709    /// sizes and the ratio difference is negligible.
710    min_size: usize,
711    /// When true, binary-classified chunks skip the tournament and
712    /// use `binary_codec` directly. Matches the v0.1 behaviour where
713    /// binary chunks were never worth the tournament cost.
714    skip_for_binary: bool,
715    /// Short-circuit threshold in per-mille (0..=1000). 0 disables
716    /// short-circuit. Whenever a codec achieves compression ratio
717    /// ≤ threshold, the tournament accepts it and skips any slower
718    /// codecs later in the list.
719    short_circuit_permille: u32,
720}
721
722/// Compress a whole file as a single drop using the categorizer's
723/// chosen codec. Used when a file-level categorizer claims the file
724/// (FLAC for WAV, ricepp for FITS, FSST+Brotli for CSV). The drop's
725/// slice covers the whole file; no `FastCDC` chunking happens.
726///
727/// Codec parameters extracted by the categorizer (e.g. PCM sample
728/// format, FITS bitpix) are NOT prepended to the compressed bytes —
729/// the codec embeds its own params in its container format. The
730/// `LimniFS` drop record just stores `(codec_id, compressed_bytes)`
731/// and lets the codec own its param encoding. The categorizer's
732/// `codec_params` field is reserved for future use when a codec
733/// needs params NOT embedded in its container.
734fn process_whole_file_drop(
735    pf: &PendingFile,
736    data: &[u8],
737    cat: file_categorizer::Categorization,
738    tunables: &limnifs_core::codec::CodecTunables,
739) -> Result<ChunkedFileResult, WriteError> {
740    let _ = pf;
741    let drop_id = hash_section(data);
742    let file_len = u64::try_from(data.len()).unwrap_or(u64::MAX);
743
744    // Brotli first; if it fails (including a codec panic — the
745    // registry converts panics to Err), fall back to ZSTD, then to
746    // STORE. A broken encoder must degrade the drop's ratio, never
747    // the write itself.
748    let (mut best_codec, mut best_compressed): (u8, std::sync::Arc<[u8]>) =
749        match limnifs_core::codec::compress_with_tunables(
750            limnifs_core::codec::CODEC_BROTLI,
751            data,
752            tunables,
753        ) {
754            Ok(c) => (limnifs_core::codec::CODEC_BROTLI, c.into()),
755            Err(_) => match limnifs_core::codec::compress_with_tunables(
756                limnifs_core::codec::CODEC_ZSTD,
757                data,
758                tunables,
759            ) {
760                Ok(c) => (limnifs_core::codec::CODEC_ZSTD, c.into()),
761                Err(_) => (limnifs_core::codec::CODEC_STORE, data.to_vec().into()),
762            },
763        };
764
765    // Short-circuit: if Brotli already achieves < 5% ratio, the input
766    // is highly compressible and ZSTD is unlikely to beat it by enough
767    // to justify the extra pass. Skip ZSTD on this fast path.
768    let brotli_ratio = best_compressed.len() as f64 / data.len() as f64;
769    if brotli_ratio > 0.05 {
770        if let Ok(zstd_c) = limnifs_core::codec::compress_with_tunables(
771            limnifs_core::codec::CODEC_ZSTD,
772            data,
773            tunables,
774        ) {
775            if zstd_c.len() < best_compressed.len() {
776                best_codec = limnifs_core::codec::CODEC_ZSTD;
777                best_compressed = zstd_c.into();
778            }
779        }
780    }
781
782    // Only try the specialized codec if the general-purpose ratio
783    // is poor (>15%) — otherwise the specialized codec is unlikely
784    // to help and may be very slow (FLAC, FSST). RICEPP is always
785    // tried because it can win big on FITS even when general-purpose
786    // ratios look acceptable.
787    let general_ratio = best_compressed.len() as f64 / data.len() as f64;
788    if general_ratio > 0.15 || cat.codec_id == limnifs_core::codec::CODEC_RICEPP {
789        // For FSST+Brotli, pass the already-computed Brotli baseline so
790        // the codec doesn't re-compress the plaintext with Brotli just
791        // for the comparison check.
792        let spec_result = if cat.codec_id == limnifs_core::codec::CODEC_FSST_BROTLI {
793            limnifs_core::codec::fsst_brotli::compress_with_baseline(data, Some(&best_compressed))
794        } else {
795            limnifs_core::codec::compress(cat.codec_id, data)
796        };
797        if let Ok(spec_c) = spec_result {
798            if spec_c.len() < best_compressed.len() {
799                best_codec = cat.codec_id;
800                best_compressed = spec_c.into();
801            }
802        }
803    }
804
805    Ok(ChunkedFileResult {
806        drops: vec![(drop_id, data.to_vec(), best_compressed, best_codec)],
807        slices: vec![PendingSlice {
808            drop_id,
809            file_byte_start: 0,
810            file_byte_end: file_len,
811        }],
812    })
813}
814
815/// Process a single file's contents (CPU-heavy work that runs in a
816/// rayon worker thread). Returns the unique chunks and slice map.
817///
818/// First consults the file-level categorizer registry. If a
819/// categorizer claims the file (e.g. FLAC for WAV, ricepp for FITS,
820/// Compress a single chunk via the configured tournament.
821///
822/// Iterates `tournament.codec_ids` in declared order, tracks the
823/// smallest output, and short-circuits when a codec achieves
824/// compression ratio ≤ `tournament.short_circuit_permille`.
825///
826/// Special cases:
827/// - **Binary chunks with `skip_for_binary`**: skip the tournament
828///   entirely and use `binary_codec`. Matches v0.1 behaviour.
829/// - **Chunks smaller than `min_size`**: use the class's preferred
830///   codec directly. Per-codec setup cost dominates here and the
831///   ratio difference is negligible at small sizes.
832/// - **Class unknown to writer** (Unknown / future classes): STORE.
833///
834/// The tournament never tries `CODEC_STORE` (id 0x00) — store is
835/// always the implicit fallback if every codec fails to compress.
836fn compress_chunk_with_tournament(
837    chunk: &[u8],
838    class: classifier::Class,
839    text_codec: u8,
840    binary_codec: u8,
841    tunables: &limnifs_core::codec::CodecTunables,
842    tournament: &TournamentSpec,
843) -> (u8, std::sync::Arc<[u8]>) {
844    use classifier::Class;
845
846    let preferred = match class {
847        Class::Binary => binary_codec,
848        Class::Text | Class::Code | Class::Sparse => text_codec,
849        _ => limnifs_core::codec::CODEC_STORE,
850    };
851
852    if preferred == limnifs_core::codec::CODEC_STORE {
853        return (limnifs_core::codec::CODEC_STORE, chunk.to_vec().into());
854    }
855    if class == Class::Binary && tournament.skip_for_binary {
856        return compress_chunk_one(chunk, preferred, tunables);
857    }
858    if chunk.len() < tournament.min_size {
859        return compress_chunk_one(chunk, preferred, tunables);
860    }
861
862    let mut best: Option<(u8, std::sync::Arc<[u8]>)> = None;
863    for &codec_id in &tournament.codec_ids {
864        if codec_id == limnifs_core::codec::CODEC_STORE {
865            continue;
866        }
867        let c = match limnifs_core::codec::compress_with_tunables(codec_id, chunk, tunables) {
868            Ok(c) => c,
869            Err(_) => continue,
870        };
871        if c.len() >= chunk.len() {
872            continue;
873        }
874        let ratio_permille = (c.len() as u64 * 1000 / chunk.len() as u64) as u32;
875        let is_best_so_far = best.as_ref().map_or(true, |(_, b)| c.len() < b.len());
876        if is_best_so_far {
877            best = Some((codec_id, c.into()));
878        }
879        if tournament.short_circuit_permille > 0
880            && ratio_permille <= tournament.short_circuit_permille
881        {
882            break;
883        }
884    }
885
886    best.unwrap_or_else(|| (limnifs_core::codec::CODEC_STORE, chunk.to_vec().into()))
887}
888
889/// Compress `chunk` with a single codec, falling back to STORE if
890/// the codec fails or expansion occurs.
891fn compress_chunk_one(
892    chunk: &[u8],
893    codec_id: u8,
894    tunables: &limnifs_core::codec::CodecTunables,
895) -> (u8, std::sync::Arc<[u8]>) {
896    if codec_id == limnifs_core::codec::CODEC_STORE {
897        return (limnifs_core::codec::CODEC_STORE, chunk.to_vec().into());
898    }
899    match limnifs_core::codec::compress_with_tunables(codec_id, chunk, tunables) {
900        Ok(c) if c.len() < chunk.len() => (codec_id, c.into()),
901        _ => (limnifs_core::codec::CODEC_STORE, chunk.to_vec().into()),
902    }
903}
904
905/// FSST+Brotli for CSV), the whole file is compressed as a single
906/// drop with the categorizer's chosen codec + parameters. Otherwise
907/// falls through to `FastCDC` + per-chunk classify.
908fn process_file(
909    pf: &PendingFile,
910    chunker: &FastCDC,
911    classifier: classifier::Classifier,
912    text_codec: u8,
913    binary_codec: u8,
914    tunables: &limnifs_core::codec::CodecTunables,
915    use_categorizers: bool,
916    skip_chunking: bool,
917    tournament: &TournamentSpec,
918    base_drop_index: Option<&std::collections::HashSet<[u8; 32]>>,
919    inline_threshold: usize,
920) -> Result<ChunkedFileResult, WriteError> {
921    // For files above MMAP_READ_THRESHOLD, map them rather than reading
922    // into a Vec via std::fs::read. Pages load on demand from the
923    // kernel page cache. The chunk-path compressors see borrowed slices
924    // pointing into the mmap, so peak RSS stays at unique_chunks ×
925    // avg_chunk_size rather than the full file.
926    //
927    // SAFETY: LimniFS packs source trees that are immutable for the
928    // duration of the write. The file is opened read-only. External
929    // mutation during compression would be a serious bug in the
930    // caller's workflow (and would also break BLAKE3 determinism).
931    let file_len_estimate = std::fs::metadata(&pf.path)
932        .map(|m| m.len() as usize)
933        .unwrap_or(0);
934    let data: Vec<u8> = if file_len_estimate >= MMAP_READ_THRESHOLD {
935        let file = std::fs::File::open(&pf.path)?;
936        #[allow(unsafe_code)]
937        let mmap = unsafe { memmap2::Mmap::map(&file) }.map_err(WriteError::Io)?;
938        // Materialize only the pages the kernel has paged in. For
939        // chunked access this is roughly unique-chunk bytes; for
940        // skip_chunking we touch every page anyway.
941        Vec::from(&mmap[..])
942    } else {
943        std::fs::read(&pf.path)?
944    };
945    let file_len = data.len();
946
947    // Skip FastCDC chunking entirely; compress the whole file as
948    // one drop. Trades dedup granularity for create speed. Used by
949    // the max-write profile where speed >> ratio. The per-file LZ4
950    // compress at ~1 GB/s is faster than FastCDC hashing overhead
951    // for all but the largest multi-GB files (where rayon parallelism
952    // across chunks would help).
953    if skip_chunking && file_len > inline_threshold {
954        let drop_id = hash_section(&data);
955        let class = classifier.classify(&data);
956        let preferred_codec = match class {
957            classifier::Class::Binary => binary_codec,
958            _ => text_codec,
959        };
960        let (codec_id, compressed): (u8, std::sync::Arc<[u8]>) =
961            match limnifs_core::codec::compress_with_tunables(preferred_codec, &data, tunables) {
962                Ok(c) if c.len() < data.len() => (preferred_codec, c.into()),
963                _ => (limnifs_core::codec::CODEC_STORE, data.to_vec().into()),
964            };
965        return Ok(ChunkedFileResult {
966            drops: vec![(drop_id, data, compressed, codec_id)],
967            slices: vec![PendingSlice {
968                drop_id,
969                file_byte_start: 0,
970                file_byte_end: file_len as u64,
971            }],
972        });
973    }
974
975    if use_categorizers {
976        if let Some(cat) = file_categorizer::default_registry().categorize(&pf.path, &data) {
977            let needs_whole_file = matches!(
978                cat.codec_id,
979                limnifs_core::codec::CODEC_FLAC | limnifs_core::codec::CODEC_RICEPP
980            );
981            if needs_whole_file || file_len <= WHOLE_FILE_MAX_SIZE {
982                return process_whole_file_drop(pf, &data, cat, tunables);
983            }
984        }
985    }
986
987    let chunks = chunker.chunk_slice(&data);
988    let mut slices = Vec::with_capacity(chunks.len());
989    let mut file_offset: u64 = 0;
990    let mut seen_in_file: std::collections::HashSet<[u8; 32]> =
991        std::collections::HashSet::with_capacity(chunks.len());
992
993    // Phase 1: hash all chunks + build slices + filter duplicates (sequential).
994    // FastCDC boundaries must be deterministic, and BLAKE3 hashing is fast.
995    let mut unique_chunks: Vec<(&[u8], [u8; 32])> = Vec::with_capacity(chunks.len());
996    for chunk in &chunks {
997        let chunk_len = u64::try_from(chunk.len()).expect("chunk len fits u64");
998        let drop_id = hash_section(chunk);
999        slices.push(PendingSlice {
1000            drop_id,
1001            file_byte_start: file_offset,
1002            file_byte_end: file_offset + chunk_len,
1003        });
1004        file_offset += chunk_len;
1005        if seen_in_file.insert(drop_id) {
1006            unique_chunks.push((chunk, drop_id));
1007        }
1008    }
1009
1010    // Phase 2: compress unique chunks in parallel across rayon workers.
1011    // This is the CPU-intensive step — parallelizing it gives N-core
1012    // speedup for large files with many chunks.
1013    //
1014    // Cross-file dedup: each rayon worker thread carries a thread-local
1015    // compress cache mapping DropId -> (codec_id, compressed_bytes).
1016    // When two files share a chunk (common in source trees, container
1017    // layers, tiny-files benchmarks), the second file hits the cache
1018    // and skips the compress pass entirely. Cache is bounded by entry
1019    // count; eviction is "stop inserting once full" — simple and
1020    // correct, misses are bounded by worker count.
1021    use rayon::prelude::*;
1022    thread_local! {
1023        static COMPRESS_CACHE: std::cell::RefCell<std::collections::HashMap<[u8; 32], (u8, std::sync::Arc<[u8]>)>> =
1024            std::cell::RefCell::new(std::collections::HashMap::new());
1025    }
1026    const COMPRESS_CACHE_MAX_ENTRIES: usize = 100_000;
1027    let drops: Vec<RawDrop> = unique_chunks
1028        .par_iter()
1029        .map(|(chunk, drop_id)| {
1030            // Layer fast-path: chunk already exists in the base image
1031            // → skip compress entirely.
1032            if let Some(base) = base_drop_index {
1033                if base.contains(drop_id) {
1034                    return (*drop_id, Vec::new(), Vec::new().into(), CODEC_REFERENCED);
1035                }
1036            }
1037            let class = classifier.classify(chunk);
1038            // Cache fast-path: identical chunk already compressed on
1039            // this worker → reuse bytes, skip tournament entirely.
1040            let cached = COMPRESS_CACHE.with(|c| {
1041                c.borrow()
1042                    .get(drop_id)
1043                    .map(|(cid, comp)| (*cid, comp.clone()))
1044            });
1045            let (codec_id, compressed) = if let Some(c) = cached {
1046                c
1047            } else {
1048                let new = compress_chunk_with_tournament(
1049                    chunk,
1050                    class,
1051                    text_codec,
1052                    binary_codec,
1053                    tunables,
1054                    tournament,
1055                );
1056                // Insert into the per-worker cache if there's room.
1057                COMPRESS_CACHE.with(|c| {
1058                    let mut cache = c.borrow_mut();
1059                    if cache.len() < COMPRESS_CACHE_MAX_ENTRIES {
1060                        // `new.1.clone()` here is an Arc refcount bump.
1061                        cache.insert(*drop_id, new.clone());
1062                    }
1063                });
1064                new
1065            };
1066            (*drop_id, chunk.to_vec(), compressed, codec_id)
1067        })
1068        .collect();
1069
1070    let _ = file_len;
1071    Ok(ChunkedFileResult { drops, slices })
1072}
1073
1074struct PendingDrop {
1075    id: [u8; 32],
1076    /// Original (decompressed) byte length. Stored as a u32 rather
1077    /// than keeping the plaintext Vec around, because the writer only
1078    /// needs the length when emitting the slab's drop record. Holding
1079    /// the full plaintext until slab assembly wastes memory
1080    /// proportional to image size on top of the compressed bytes.
1081    plaintext_len: u32,
1082    compressed: std::sync::Arc<[u8]>,
1083    codec: u8,
1084    /// Dictionary id (0xFF = NO_DICT). Populated during the dict
1085    /// re-compression pass for drops that were re-compressed with a
1086    /// trained dictionary.
1087    dict_id: u8,
1088    /// Retained plaintext, present only when `collect_dict_samples`
1089    /// is true (i.e. `WriteConfig::dictionaries.enabled`). Used by
1090    /// the post-parallel dict re-compression pass. Cleared after
1091    /// re-compression to free memory before slab assembly.
1092    plaintext: Option<Vec<u8>>,
1093}
1094
1095impl PendingDrop {
1096    /// The byte length stored in the slab's solid window. Equals
1097    /// `plaintext_len` for store codec, or the compressed size for
1098    /// LZ4 / Brotli / etc.
1099    fn len_in_window(&self) -> u32 {
1100        u32::try_from(self.compressed.len()).expect("compressed fits u32")
1101    }
1102
1103    /// The original (decompressed) byte length.
1104    fn plaintext_len_value(&self) -> u32 {
1105        self.plaintext_len
1106    }
1107
1108    /// Contribution to the slab's total byte length: 48 bytes of drop
1109    /// record (per spec §3.3) + the compressed payload.
1110    fn slab_footprint(&self) -> usize {
1111        48 + self.compressed.len()
1112    }
1113}
1114
1115/// One slice of a file backed by drops. Records which drop holds
1116/// this slice's bytes and which byte range of the original file
1117/// the slice covers. The slice always spans the entire drop (the
1118/// chunker never splits a drop across multiple slices).
1119struct PendingSlice {
1120    drop_id: [u8; 32],
1121    file_byte_start: u64,
1122    file_byte_end: u64,
1123}
1124
1125/// A file that needs chunking (> `INLINE_THRESHOLD`). Collected during
1126/// the sequential tree walk and processed in parallel by `rayon`.
1127#[derive(Clone)]
1128struct PendingFile {
1129    inode_number: u64,
1130    path: PathBuf,
1131    mtime_ns: u64,
1132    file_len: u64,
1133}
1134
1135struct PendingInode {
1136    number: u64,
1137    mode: u32,
1138    mtime_ns: u64,
1139    content: PendingContent,
1140}
1141
1142enum PendingContent {
1143    Inline(Vec<u8>),
1144    DropBacked {
1145        file_len: u64,
1146        slices: Vec<PendingSlice>,
1147    },
1148    Directory(Vec<(String, u64, u8)>),
1149}
1150
1151struct DirNode {
1152    entries: Vec<(String, u64, u8)>,
1153    bytes: Vec<u8>,
1154    hash: [u8; 32],
1155}
1156
1157struct WriteContext {
1158    next_inode: u64,
1159    inodes: Vec<PendingInode>,
1160    dir_nodes: Vec<DirNode>,
1161    drops: Vec<PendingDrop>,
1162    drop_index: HashSet<[u8; 32]>,
1163    pending_files: Vec<PendingFile>,
1164    file_count: usize,
1165    dir_count: usize,
1166    root_inode_number: u64,
1167    chunker: FastCDC,
1168    classifier: classifier::Classifier,
1169    shared_inline_map: HashMap<[u8; 32], usize>,
1170    shared_inline_table: Vec<Vec<u8>>,
1171    /// Profile name for ProfileDescriptor emission (None = omit section).
1172    profile_name: Option<String>,
1173    /// Metadata blob codec (defaults to Brotli; can be overridden via
1174    /// `WriteConfig::defaults::metadata_codec`). Used by `assemble`.
1175    metadata_codec: u8,
1176    /// Whether categorizers were disabled by the profile.
1177    categorizers_disabled: bool,
1178    /// Whether this is a RW image.
1179    rw_mode: bool,
1180    /// Whether auto-turnover is enabled.
1181    auto_turnover: bool,
1182    /// Whether to collect plaintext samples for ZSTD dictionary
1183    /// training. Set when `WriteConfig::dictionaries.enabled`.
1184    collect_dict_samples: bool,
1185    /// Plaintext samples collected from ZSTD-compressed drops, for
1186    /// training one dictionary after the parallel compress phase.
1187    /// Capped at `MAX_DICT_SAMPLES` to bound memory. Keyed by
1188    /// classifier class — text/code/sparse share a "text" dict,
1189    /// binary gets its own. Compressed/media/incompressible classes
1190    /// don't use ZSTD so their samples aren't collected.
1191    dict_samples_by_class: HashMap<crate::classifier::Class, Vec<Vec<u8>>>,
1192    /// Trained dictionaries keyed by class. Populated by
1193    /// `train_and_apply_dictionary` after the parallel phase. Emitted
1194    /// in the manifest's `dictionary_section` with one entry per
1195    /// class that accumulated enough samples.
1196    trained_dicts_by_class: HashMap<crate::classifier::Class, crate::dictionary::TrainedDictionary>,
1197    /// Drop IDs known to exist in a base image (set when this write
1198    /// is producing a layer via `write_layer`). When a chunk's DropId
1199    /// is in this set, the writer skips compression and emits no slab
1200    /// bytes — the drop is resolved via the overlay chain at read
1201    /// time. `None` for standalone (non-layer) writes.
1202    base_drop_index: Option<HashSet<[u8; 32]>>,
1203    /// The base image's `ManifestRoot` (set when `base_drop_index`
1204    /// is `Some`). Emitted in the manifest's `delta_linkage` section
1205    /// so readers know which image provides the referenced drops.
1206    /// `None` for standalone writes.
1207    base_root: Option<[u8; 32]>,
1208    /// Compressed-metadata size above which the blob is externalized
1209    /// to a sidecar (issue #187). Defaults to
1210    /// [`METADATA_EXTERNALIZE_THRESHOLD`]; overridable via
1211    /// `WriteConfig::defaults::metadata_externalize_threshold`.
1212    metadata_externalize_threshold: usize,
1213    /// Inline-data cutoff from `WriteConfig::defaults.inline_threshold`.
1214    /// Files at or below this size are stored inline in the metadata
1215    /// blob instead of being chunked into slabs. Set from the profile
1216    /// before `walk`; defaults to the historical constant.
1217    inline_threshold: usize,
1218    /// Streaming-walk sink (TODO.perf/15). When set, `walk` forwards
1219    /// deferred files to the channel instead of buffering them in
1220    /// `pending_files`, so compression starts while the walk is still
1221    /// descending the tree. `None` keeps the collect-then-dispatch
1222    /// shape (used by the non-streaming entry points).
1223    pending_sink: Option<std::sync::mpsc::SyncSender<PendingFile>>,
1224}
1225
1226impl WriteContext {
1227    /// Cap on collected plaintext samples. Enough signal for the
1228    /// FrequencyTrainer without unbounded memory growth on huge inputs.
1229    const MAX_DICT_SAMPLES: usize = 1000;
1230
1231    fn new() -> Self {
1232        Self {
1233            next_inode: 1,
1234            inodes: Vec::new(),
1235            dir_nodes: Vec::new(),
1236            drops: Vec::new(),
1237            drop_index: HashSet::new(),
1238            pending_files: Vec::new(),
1239            file_count: 0,
1240            dir_count: 0,
1241            root_inode_number: 0,
1242            chunker: FastCDC::default(),
1243            classifier: classifier::Classifier,
1244            shared_inline_map: HashMap::new(),
1245            shared_inline_table: Vec::new(),
1246            profile_name: None,
1247            metadata_codec: limnifs_core::codec::CODEC_BROTLI,
1248            categorizers_disabled: false,
1249            rw_mode: false,
1250            auto_turnover: false,
1251            collect_dict_samples: false,
1252            dict_samples_by_class: HashMap::new(),
1253            trained_dicts_by_class: HashMap::new(),
1254            base_drop_index: None,
1255            base_root: None,
1256            pending_sink: None,
1257            inline_threshold: INLINE_THRESHOLD,
1258            metadata_externalize_threshold: METADATA_EXTERNALIZE_THRESHOLD,
1259        }
1260    }
1261
1262    fn alloc_inode(&mut self) -> u64 {
1263        let n = self.next_inode;
1264        self.next_inode += 1;
1265        n
1266    }
1267
1268    /// Scan all inline-data inodes and build a dedup table. Only
1269    /// content appearing in > 1 inode is deduplicated; unique inline
1270    /// data stays inline (no overhead change).
1271    fn build_shared_inline_table(&mut self) {
1272        let mut counts: HashMap<[u8; 32], usize> = HashMap::new();
1273        for inode in &self.inodes {
1274            if let PendingContent::Inline(data) = &inode.content {
1275                let h = hash_section(data);
1276                *counts.entry(h).or_default() += 1;
1277            }
1278        }
1279        // Only dedup content that appears more than once.
1280        for inode in &self.inodes {
1281            if let PendingContent::Inline(data) = &inode.content {
1282                let h = hash_section(data);
1283                if counts.get(&h).copied().unwrap_or(0) > 1
1284                    && !self.shared_inline_map.contains_key(&h)
1285                {
1286                    let idx = self.shared_inline_table.len();
1287                    self.shared_inline_table.push(data.clone());
1288                    self.shared_inline_map.insert(h, idx);
1289                }
1290            }
1291        }
1292    }
1293
1294    /// Merge a parallel-processed chunked file's results into the
1295    /// context. Dedup: only new `DropId`s get added to the drops list.
1296    fn merge_chunked_file(&mut self, pf: &PendingFile, result: ChunkedFileResult) {
1297        for (drop_id, plaintext, compressed, codec) in result.drops {
1298            if self.drop_index.insert(drop_id) {
1299                // When dictionary training is enabled, classify the
1300                // plaintext and retain it for per-class dictionary
1301                // training. Text-like classes share a "text" dict;
1302                // Binary gets its own. Compressed/media/incompressible
1303                // don't use ZSTD so we skip them entirely.
1304                let retain_plaintext =
1305                    self.collect_dict_samples && codec == limnifs_core::codec::CODEC_ZSTD;
1306                if retain_plaintext {
1307                    let total: usize = self.dict_samples_by_class.values().map(Vec::len).sum();
1308                    if total < Self::MAX_DICT_SAMPLES {
1309                        let class = self.classifier.classify(&plaintext);
1310                        self.dict_samples_by_class
1311                            .entry(class)
1312                            .or_default()
1313                            .push(plaintext.clone());
1314                    }
1315                }
1316                self.drops.push(PendingDrop {
1317                    id: drop_id,
1318                    plaintext_len: u32::try_from(plaintext.len()).unwrap_or(u32::MAX),
1319                    compressed,
1320                    codec,
1321                    dict_id: limnifs_core::drop_record::NO_DICT,
1322                    plaintext: if retain_plaintext {
1323                        Some(plaintext)
1324                    } else {
1325                        None
1326                    },
1327                });
1328            }
1329        }
1330        self.inodes.push(PendingInode {
1331            number: pf.inode_number,
1332            mode: 0o100_644,
1333            mtime_ns: pf.mtime_ns,
1334            content: PendingContent::DropBacked {
1335                file_len: pf.file_len,
1336                slices: result.slices,
1337            },
1338        });
1339    }
1340
1341    /// Apply the seine classifier to a chunk and compress it if the
1342    /// class is compressible. Text, Code, and Binary drops get LZ4;
1343    /// Compressed, Media, and Sparse drops stay as store (re-compressing
1344    /// already-compressed data wastes CPU for no gain).
1345    /// Apply the seine classifier to a chunk and compress it if the
1346    /// class is compressible. Text, Code, and Binary drops get LZ4;
1347    /// Compressed, Media, and Sparse drops stay as store.
1348    ///
1349    /// Kept for API compatibility; the parallel writer uses
1350    /// [`process_file`] which inlines this logic.
1351    #[allow(dead_code)]
1352    fn deepen_drop(&self, drop_id: [u8; 32], plaintext: &[u8]) -> PendingDrop {
1353        let class = self.classifier.classify(plaintext);
1354        let (codec, compressed): (u8, std::sync::Arc<[u8]>) = match class {
1355            classifier::Class::Text | classifier::Class::Code | classifier::Class::Binary => {
1356                let c = limnifs_core::codec::compress_lz4_with_size(plaintext);
1357                (limnifs_core::codec::CODEC_LZ4, c.into())
1358            }
1359            _ => (limnifs_core::codec::CODEC_STORE, plaintext.to_vec().into()),
1360        };
1361        PendingDrop {
1362            id: drop_id,
1363            plaintext_len: u32::try_from(plaintext.len()).unwrap_or(u32::MAX),
1364            compressed,
1365            codec,
1366            dict_id: limnifs_core::drop_record::NO_DICT,
1367            plaintext: None,
1368        }
1369    }
1370
1371    fn walk(&mut self, path: &Path) -> Result<u64, WriteError> {
1372        let meta = std::fs::symlink_metadata(path)?;
1373        let file_type = meta.file_type();
1374        let mtime_ns = meta
1375            .modified()
1376            .ok()
1377            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1378            .map_or(0u128, |d| d.as_nanos());
1379        let mtime_ns: u64 = mtime_ns.try_into().unwrap_or(0);
1380
1381        if file_type.is_dir() {
1382            self.dir_count += 1;
1383            let inode_number = self.alloc_inode();
1384            let mut entries: Vec<(String, u64, u8)> = Vec::new();
1385
1386            for entry in std::fs::read_dir(path)? {
1387                let entry = entry?;
1388                let name = entry.file_name().to_string_lossy().into_owned();
1389                let child_path = entry.path();
1390                let child_inode = self.walk(&child_path)?;
1391                let child_meta = entry.metadata()?;
1392                let entry_type = if child_meta.is_dir() { 0x02 } else { 0x01 };
1393                entries.push((name, child_inode, entry_type));
1394            }
1395
1396            entries.sort_by(|a, b| a.0.cmp(&b.0));
1397            let dir_node = encode_dir_node(&entries);
1398            self.dir_nodes.push(dir_node);
1399            self.inodes.push(PendingInode {
1400                number: inode_number,
1401                mode: 0o040_755,
1402                mtime_ns,
1403                content: PendingContent::Directory(entries),
1404            });
1405            Ok(inode_number)
1406        } else if file_type.is_file() {
1407            self.file_count += 1;
1408            let inode_number = self.alloc_inode();
1409            let file_len = meta.len();
1410
1411            if file_len <= u64::try_from(self.inline_threshold).unwrap_or(u64::MAX) {
1412                let data = std::fs::read(path)?;
1413                self.inodes.push(PendingInode {
1414                    number: inode_number,
1415                    mode: 0o100_644,
1416                    mtime_ns,
1417                    content: PendingContent::Inline(data),
1418                });
1419            } else {
1420                // Defer to parallel processing — collect the file info.
1421                let pf = PendingFile {
1422                    inode_number,
1423                    path: path.to_path_buf(),
1424                    mtime_ns,
1425                    file_len,
1426                };
1427                if let Some(sink) = &self.pending_sink {
1428                    // Streaming mode: hand the file to the compress
1429                    // workers immediately; the bounded channel
1430                    // back-pressures if they fall behind. A send
1431                    // failure means the receiver is gone (a worker
1432                    // hit an unrecoverable error) — abort the walk.
1433                    sink.send(pf).map_err(|_| {
1434                        WriteError::Io(std::io::Error::other("walk: compress pipeline shut down"))
1435                    })?;
1436                } else {
1437                    self.pending_files.push(pf);
1438                }
1439            }
1440            Ok(inode_number)
1441        } else {
1442            Err(WriteError::Io(std::io::Error::new(
1443                std::io::ErrorKind::Unsupported,
1444                format!("unsupported file type: {}", path.display()),
1445            )))
1446        }
1447    }
1448
1449    /// After the parallel compress phase: train one ZSTD dictionary
1450    /// per classifier class with enough samples, then re-compress
1451    /// each ZSTD drop with the dictionary for its class. Keep
1452    /// whichever representation is smaller. Drops that get
1453    /// re-compressed carry the class's `dict_id` in their drop
1454    /// record; the dictionaries are emitted in the manifest's
1455    /// `dictionary_section`.
1456    ///
1457    /// Text/Code/Sparse classes collapse into a single "text" dict
1458    /// (id 0). Binary gets id 1. Other classes don't accumulate
1459    /// samples because their drops aren't ZSTD-compressed.
1460    ///
1461    /// Clears the retained plaintext on every drop to free memory
1462    /// before slab assembly.
1463    fn train_and_apply_dictionary(&mut self, dictionaries: &crate::config::DictionaryConfig) {
1464        let cleanup = |ctx: &mut Self| {
1465            for d in &mut ctx.drops {
1466                d.plaintext = None;
1467            }
1468            ctx.dict_samples_by_class.clear();
1469        };
1470
1471        if !dictionaries.enabled {
1472            cleanup(self);
1473            return;
1474        }
1475
1476        let target = usize::try_from(dictionaries.max_dict_size).unwrap_or(65_536);
1477        let min_class = usize::try_from(dictionaries.min_class_size).unwrap_or(0);
1478
1479        // Allocate dict ids: 0 = text (Text/Code/Sparse), 1 = binary.
1480        // Compressed/Media/Incompressible don't accumulate samples
1481        // (their drops aren't ZSTD) so we don't train for them.
1482        let text_classes = [
1483            crate::classifier::Class::Text,
1484            crate::classifier::Class::Code,
1485            crate::classifier::Class::Sparse,
1486        ];
1487        let binary_classes = [crate::classifier::Class::Binary];
1488
1489        // Train text dict from text-like classes' samples combined.
1490        let text_samples: Vec<&[u8]> = text_classes
1491            .iter()
1492            .flat_map(|c| self.dict_samples_by_class.get(c).into_iter().flatten())
1493            .map(Vec::as_slice)
1494            .collect();
1495        let trainer = crate::dictionary::TrainerKind::from_config_str(&dictionaries.trainer);
1496        if text_samples.len() >= min_class {
1497            if let Some(dict) =
1498                crate::dictionary::train_zstd_with_trainer(0, &text_samples, target, trainer)
1499            {
1500                self.trained_dicts_by_class
1501                    .insert(crate::classifier::Class::Text, dict);
1502            }
1503        }
1504        let binary_samples: Vec<&[u8]> = binary_classes
1505            .iter()
1506            .flat_map(|c| self.dict_samples_by_class.get(c).into_iter().flatten())
1507            .map(Vec::as_slice)
1508            .collect();
1509        if binary_samples.len() >= min_class {
1510            if let Some(dict) =
1511                crate::dictionary::train_zstd_with_trainer(1, &binary_samples, target, trainer)
1512            {
1513                self.trained_dicts_by_class
1514                    .insert(crate::classifier::Class::Binary, dict);
1515            }
1516        }
1517
1518        // Re-compress each ZSTD drop with the dict for its class.
1519        // Keep the smaller representation.
1520        for d in self.drops.iter_mut() {
1521            if d.codec != limnifs_core::codec::CODEC_ZSTD {
1522                continue;
1523            }
1524            let Some(plaintext) = d.plaintext.clone() else {
1525                continue;
1526            };
1527            let class = self.classifier.classify(&plaintext);
1528            let dict_class = if text_classes.contains(&class) {
1529                crate::classifier::Class::Text
1530            } else if binary_classes.contains(&class) {
1531                crate::classifier::Class::Binary
1532            } else {
1533                continue;
1534            };
1535            let Some(dict) = self.trained_dicts_by_class.get(&dict_class) else {
1536                continue;
1537            };
1538            let Ok(dict_compressed) = dict.compress(&plaintext) else {
1539                continue;
1540            };
1541            if dict_compressed.len() < d.compressed.len() {
1542                d.compressed = dict_compressed.into();
1543                d.dict_id = dict.id;
1544            }
1545        }
1546
1547        cleanup(self);
1548    }
1549
1550    /// Env-gated phase timer for assemble profiling (TODO.perf/16).
1551    fn trace_phase(label: &str, start: std::time::Instant) {
1552        if std::env::var_os("LIMNIFS_TRACE_ASSEMBLE").is_some() {
1553            eprintln!("[assemble] {label}: {:?}", start.elapsed());
1554        }
1555    }
1556
1557    fn assemble(mut self) -> WriteArtifact {
1558        let t_assemble = std::time::Instant::now();
1559        let inode_count = self.inodes.len();
1560        let dir_count = self.dir_count;
1561        let drop_count = self.drops.len();
1562
1563        // Partition drops into slabs. Each slab's total byte length
1564        // (header + drop records + solid window) must stay under
1565        // MAX_SLAB_TOTAL_BYTES so the reader's 64 MiB ceiling is never
1566        // exceeded. A single drop larger than the budget gets its own
1567        // slab (we cannot split a drop).
1568        let t = std::time::Instant::now();
1569        let slabs = pack_slabs(&self.drops);
1570        Self::trace_phase("pack_slabs", t);
1571
1572        // Build the shared inline table: deduplicate inline data that
1573        // appears in more than one inode. For N files with identical
1574        // small content, store once and reference by index.
1575        let t = std::time::Instant::now();
1576        self.build_shared_inline_table();
1577        Self::trace_phase("shared_inline_table", t);
1578
1579        let mut metadata_blob = Vec::new();
1580        metadata_blob.extend_from_slice(&u32::try_from(self.inodes.len()).unwrap().to_le_bytes());
1581        for inode in &self.inodes {
1582            self.encode_inode(&mut metadata_blob, inode);
1583        }
1584        metadata_blob
1585            .extend_from_slice(&u32::try_from(self.dir_nodes.len()).unwrap().to_le_bytes());
1586        for node in &self.dir_nodes {
1587            metadata_blob.extend_from_slice(&node.bytes);
1588        }
1589        // Shared inline table (only present if any dedup occurred).
1590        // Reader checks for remaining bytes after dir_nodes.
1591        if !self.shared_inline_table.is_empty() {
1592            metadata_blob.extend_from_slice(
1593                &u32::try_from(self.shared_inline_table.len())
1594                    .unwrap()
1595                    .to_le_bytes(),
1596            );
1597            for entry in &self.shared_inline_table {
1598                let len = u32::try_from(entry.len()).expect("shared entry fits u32");
1599                metadata_blob.extend_from_slice(&len.to_le_bytes());
1600                metadata_blob.extend_from_slice(entry);
1601            }
1602        }
1603
1604        Self::trace_phase("metadata_encode", t);
1605        // Compress the metadata blob. Metadata is highly compressible
1606        // (sequential inode numbers, repeated modes, natural-language
1607        // file names) — even low Brotli quality yields 4–8× on source
1608        // trees. Pick quality by size: small blobs cost nothing to
1609        // compress at q5; large blobs (e.g. 50 K-inode trees) would
1610        // dominate create time at q5, so step down to q2.
1611        let uncompressed_len =
1612            u32::try_from(metadata_blob.len()).expect("metadata blob length fits u32");
1613        let t = std::time::Instant::now();
1614        let metadata_hash = hash_section(&metadata_blob);
1615        let metadata_codec = self.metadata_codec;
1616        let metadata_quality = if metadata_blob.len() > METADATA_LARGE_BLOB_THRESHOLD {
1617            METADATA_LARGE_BLOB_QUALITY
1618        } else {
1619            METADATA_SMALL_BLOB_QUALITY
1620        };
1621        let compressed_blob = if metadata_codec == limnifs_core::codec::CODEC_BROTLI {
1622            limnifs_core::codec::compress_brotli_with_quality(&metadata_blob, metadata_quality)
1623                .unwrap_or_else(|_| metadata_blob.clone())
1624        } else {
1625            limnifs_core::codec::compress(metadata_codec, &metadata_blob)
1626                .unwrap_or_else(|_| metadata_blob.clone())
1627        };
1628        Self::trace_phase("metadata_compress", t);
1629        let (on_wire_codec, on_wire_blob) = if compressed_blob.len() < metadata_blob.len() {
1630            (metadata_codec, compressed_blob)
1631        } else {
1632            (limnifs_core::codec::CODEC_STORE, metadata_blob.clone())
1633        };
1634
1635        // Decide inline vs sidecar based on the COMPRESSED length,
1636        // clamped to the reader's inline ceiling regardless of config
1637        // (inline metadata above it is unreadable by default readers).
1638        let externalize_at = self
1639            .metadata_externalize_threshold
1640            .min(limnifs_core::metadata_reference::DEFAULT_INLINE_METADATA_MAX_BYTES as usize);
1641        let (metadata_sidecar, inline_data, metadata_locator_count) =
1642            if on_wire_blob.len() > externalize_at {
1643                let locator = "file:metadata.bin".to_owned();
1644                let sidecar = MetadataSidecar {
1645                    bytes: on_wire_blob.clone(),
1646                    locator,
1647                };
1648                (Some(sidecar), None, 1u32)
1649            } else {
1650                (None, Some(on_wire_blob.clone()), 0u32)
1651            };
1652
1653        let mut manifest = Vec::new();
1654
1655        let header_start = manifest.len();
1656        manifest.extend_from_slice(&ManifestHeader::current().to_bytes());
1657        let header_end = manifest.len();
1658
1659        let flags_start = manifest.len();
1660        manifest.push(FEATURE_FLAGS_SECTION_VERSION);
1661        manifest.extend_from_slice(&0u32.to_le_bytes());
1662        let flags_end = manifest.len();
1663
1664        // metadata_reference v2: hash + uncompressed_len + codec +
1665        // locator_count + locators + inline_data_len + inline_data.
1666        let meta_ref_start = manifest.len();
1667        manifest.push(METADATA_REFERENCE_SECTION_VERSION_2);
1668        manifest.extend_from_slice(&metadata_hash);
1669        manifest.extend_from_slice(&uncompressed_len.to_le_bytes());
1670        manifest.push(on_wire_codec);
1671        manifest.extend_from_slice(&metadata_locator_count.to_le_bytes());
1672        if let Some(sidecar) = &metadata_sidecar {
1673            let loc_bytes = sidecar.locator.as_bytes();
1674            let loc_len = u32::try_from(loc_bytes.len()).expect("locator fits u32");
1675            manifest.extend_from_slice(&loc_len.to_le_bytes());
1676            manifest.extend_from_slice(loc_bytes);
1677        }
1678        match &inline_data {
1679            Some(blob) => {
1680                let inline_len = u32::try_from(blob.len()).expect("metadata fits u32");
1681                manifest.extend_from_slice(&inline_len.to_le_bytes());
1682                manifest.extend_from_slice(blob);
1683            }
1684            None => {
1685                manifest.extend_from_slice(&0u32.to_le_bytes());
1686            }
1687        }
1688        let meta_ref_end = manifest.len();
1689
1690        let slab_index_start = manifest.len();
1691        manifest.push(SLAB_INDEX_SECTION_VERSION);
1692        manifest.extend_from_slice(&u32::try_from(slabs.len()).unwrap().to_le_bytes());
1693        for slab in &slabs {
1694            manifest.extend_from_slice(&slab.id.to_bytes());
1695            manifest.extend_from_slice(&1u32.to_le_bytes());
1696            let loc_bytes = slab.locator.as_bytes();
1697            let loc_len = u32::try_from(loc_bytes.len()).expect("locator fits u32");
1698            manifest.extend_from_slice(&loc_len.to_le_bytes());
1699            manifest.extend_from_slice(loc_bytes);
1700        }
1701        let slab_index_end = manifest.len();
1702
1703        let history_start = manifest.len();
1704        manifest.push(HISTORY_SECTION_VERSION);
1705        manifest.extend_from_slice(&1u32.to_le_bytes());
1706        manifest.push(0x01);
1707        manifest.extend_from_slice(&0u64.to_le_bytes());
1708        manifest.extend_from_slice(&0u32.to_le_bytes());
1709        manifest.extend_from_slice(&0u32.to_le_bytes());
1710        let history_end = manifest.len();
1711
1712        // ProfileDescriptor section (optional — appended after history).
1713        // Records which overhead layers were active so any reader can
1714        // handle the image correctly. Only emitted if a profile name
1715        // was set.
1716        let profile_desc_start = manifest.len();
1717        if let Some(ref name) = self.profile_name {
1718            let desc = limnifs_core::profile_descriptor::ProfileDescriptor {
1719                version: limnifs_core::profile_descriptor::PROFILE_DESCRIPTOR_SECTION_VERSION,
1720                profile_name: Some(name.clone()),
1721                blake3_hashing: true,
1722                cross_file_dedup: true,
1723                content_classification: !self.categorizers_disabled,
1724                integrity_verify: true,
1725                read_write: self.rw_mode,
1726                auto_turnover: self.auto_turnover,
1727            };
1728            limnifs_core::profile_descriptor::encode_profile_descriptor(&desc, &mut manifest);
1729        }
1730        let profile_desc_end = manifest.len();
1731
1732        // DictionarySection (optional — emitted when dictionaries
1733        // were trained during the post-parallel pass). Contains the
1734        // `(codec_id, class_id, data)` triples referenced by drop
1735        // records' `dict_id` field. One entry per class with enough
1736        // samples to train: text (id 0), binary (id 1).
1737        if !self.trained_dicts_by_class.is_empty() {
1738            let dicts: Vec<_> = self
1739                .trained_dicts_by_class
1740                .values()
1741                .map(|d| limnifs_core::dictionary_section::Dictionary {
1742                    codec_id: d.codec,
1743                    class_id: d.id,
1744                    data: d.content.clone(),
1745                })
1746                .collect();
1747            let section = limnifs_core::dictionary_section::DictionarySection {
1748                version: limnifs_core::dictionary_section::DICTIONARY_SECTION_VERSION,
1749                dicts,
1750            };
1751            limnifs_core::dictionary_section::encode_dictionary_section(&section, &mut manifest);
1752        }
1753
1754        let dictionary_end = manifest.len();
1755
1756        // DeltaLinkage section (optional — emitted only by `write_layer`).
1757        // Carries `base_root` so readers can resolve referenced drops via
1758        // the overlay chain. The section's hash feeds the
1759        // `SectionHashes::delta_linkage` slot, which is empty for
1760        // standalone images.
1761        let delta_linkage_hash = if let Some(base_root) = self.base_root {
1762            let delta_start = manifest.len();
1763            // Inline-encode the delta linkage section (version 1):
1764            // [version:u8][base_root:32][tree_op_count:u32=0]. Tree ops
1765            // are empty because the metadata blob carries the full new
1766            // tree — readers see `base_root` and know to walk the
1767            // overlay chain for any DropId not present in local slabs.
1768            manifest.push(limnifs_core::delta_linkage::DELTA_LINKAGE_SECTION_VERSION);
1769            manifest.extend_from_slice(&base_root);
1770            manifest.extend_from_slice(&0u32.to_le_bytes());
1771            hash_section(&manifest[delta_start..])
1772        } else {
1773            hash_empty_section()
1774        };
1775        let _ = dictionary_end;
1776
1777        let hashes = SectionHashes {
1778            metadata: metadata_hash,
1779            format_header: hash_section(&manifest[header_start..header_end]),
1780            feature_flags: hash_section(&manifest[flags_start..flags_end]),
1781            metadata_reference: hash_section(&manifest[meta_ref_start..meta_ref_end]),
1782            slab_index: hash_section(&manifest[slab_index_start..slab_index_end]),
1783            crypto_params: hash_empty_section(),
1784            ec_params: hash_empty_section(),
1785            dms_policy: hash_empty_section(),
1786            delta_linkage: delta_linkage_hash,
1787            history: hash_section(&manifest[history_start..history_end]),
1788            // The Merkle construction doesn't currently include a
1789            // dictionary_section hash slot. Treat the section as
1790            // crypto-params-equivalent (covered by the metadata hash)
1791            // for now; documenting this with an explicit comment so
1792            // the next reader knows where to add a hash slot if the
1793            // spec grows one.
1794            // TODO: spec section-hash for dictionary_section.
1795            // For now use hash_empty_section() so the structure compiles;
1796            // a future spec rev will add a dedicated slot.
1797            // (Section bytes are still content-addressed via the
1798            // slab_index hash and the manifest's Merkle root.)
1799        };
1800        let merkle_root = compute_merkle_root(&hashes);
1801
1802        WriteArtifact {
1803            bytes: manifest,
1804            merkle_root,
1805            slabs,
1806            metadata_sidecar,
1807            inode_count,
1808            file_count: self.file_count,
1809            dir_count,
1810            drop_count,
1811            root_inode_number: self.root_inode_number,
1812        }
1813    }
1814
1815    fn encode_inode(&self, out: &mut Vec<u8>, inode: &PendingInode) {
1816        out.extend_from_slice(&inode.number.to_le_bytes());
1817        out.extend_from_slice(&inode.mode.to_le_bytes());
1818        out.extend_from_slice(&0u32.to_le_bytes());
1819        out.extend_from_slice(&0u32.to_le_bytes());
1820        out.extend_from_slice(&inode.mtime_ns.to_le_bytes());
1821        out.extend_from_slice(&inode.mtime_ns.to_le_bytes());
1822        out.extend_from_slice(&1u32.to_le_bytes());
1823        match &inode.content {
1824            PendingContent::Inline(data) => {
1825                let h = hash_section(data);
1826                if let Some(&idx) = self.shared_inline_map.get(&h) {
1827                    // Deduplicated: emit shared-inline flag + index.
1828                    out.push(INODE_FLAG_INLINE_DATA | INODE_FLAG_SHARED_INLINE);
1829                    out.extend_from_slice(&(idx as u32).to_le_bytes());
1830                } else {
1831                    out.push(INODE_FLAG_INLINE_DATA);
1832                    let len = u32::try_from(data.len()).expect("data fits u32");
1833                    out.extend_from_slice(&len.to_le_bytes());
1834                    out.extend_from_slice(data);
1835                }
1836            }
1837            PendingContent::DropBacked { file_len, slices } => {
1838                out.push(0x00);
1839                let slice_count = u32::try_from(slices.len()).expect("slice count fits u32");
1840                out.extend_from_slice(&slice_count.to_le_bytes());
1841                for slice in slices {
1842                    out.extend_from_slice(&slice.file_byte_start.to_le_bytes());
1843                    out.extend_from_slice(&slice.file_byte_end.to_le_bytes());
1844                    out.extend_from_slice(&slice.drop_id);
1845                    // drop_byte_start = 0 (slice covers the whole drop)
1846                    out.extend_from_slice(&0u32.to_le_bytes());
1847                    // drop_byte_len = the byte length of this slice in the
1848                    // drop's decompressed plaintext. Each slice maps to
1849                    // exactly one chunk, so this equals the file range.
1850                    let drop_byte_len = u32::try_from(slice.file_byte_end - slice.file_byte_start)
1851                        .expect("slice range fits u32");
1852                    out.extend_from_slice(&drop_byte_len.to_le_bytes());
1853                }
1854                let _ = file_len;
1855            }
1856            PendingContent::Directory(entries) => {
1857                out.push(0x00);
1858                let node = self
1859                    .dir_nodes
1860                    .iter()
1861                    .find(|n| n.entries == *entries)
1862                    .expect("directory node must exist");
1863                out.extend_from_slice(&node.hash);
1864            }
1865        }
1866    }
1867}
1868
1869fn encode_dir_node(entries: &[(String, u64, u8)]) -> DirNode {
1870    let mut bytes = Vec::new();
1871    bytes.push(1u8);
1872    let count = u32::try_from(entries.len()).expect("entry count fits u32");
1873    bytes.extend_from_slice(&count.to_le_bytes());
1874    for (name, inode_number, entry_type) in entries {
1875        let name_bytes = name.as_bytes();
1876        let name_len = u32::try_from(name_bytes.len()).expect("name fits u32");
1877        bytes.extend_from_slice(&name_len.to_le_bytes());
1878        bytes.extend_from_slice(name_bytes);
1879        bytes.extend_from_slice(&inode_number.to_le_bytes());
1880        bytes.push(*entry_type);
1881    }
1882    let hash = hash_section(&bytes);
1883    DirNode {
1884        entries: entries.to_vec(),
1885        bytes,
1886        hash,
1887    }
1888}
1889
1890/// Partition `drops` into one or more slabs, each fitting under
1891/// [`MAX_SLAB_TOTAL_BYTES`]. Slab ordinal starts at 0 and increments.
1892/// Each slab's `SlabId` hash is `BLAKE3(slab_content)` so identical
1893/// content yields identical slab IDs (deterministic).
1894///
1895/// A single drop larger than `MAX_SLAB_TOTAL_BYTES - SLAB_HEADER_LEN`
1896/// still produces one slab — we cannot split a drop, and the spec
1897/// permits the reader to raise its ceiling for that case.
1898fn pack_slabs(drops: &[PendingDrop]) -> Vec<SlabArtifact> {
1899    // Filter out CODEC_REFERENCED sentinel drops — they exist in the
1900    // writer's in-memory state for inode/slice bookkeeping but are
1901    // resolved via the overlay chain at read time, never stored in
1902    // this image's slabs.
1903    let local_drops: Vec<&PendingDrop> = drops
1904        .iter()
1905        .filter(|d| d.codec != limnifs_core::codec::CODEC_REFERENCED)
1906        .collect();
1907    if local_drops.is_empty() {
1908        return Vec::new();
1909    }
1910
1911    let max_content = MAX_SLAB_TOTAL_BYTES.saturating_sub(SLAB_HEADER_LEN);
1912
1913    // Phase 1 (sequential): scan drops and partition into slab groups.
1914    // Each slab group is the list of drops that will share a slab window.
1915    // The grouping depends on per-drop compressed size + record overhead
1916    // — this is a sequential scan with a running size budget.
1917    let mut slab_groups: Vec<Vec<&PendingDrop>> = Vec::new();
1918    let mut current: Vec<&PendingDrop> = Vec::new();
1919    let mut current_size: usize = 0;
1920
1921    for drop in &local_drops {
1922        let footprint = drop.slab_footprint();
1923        if !current.is_empty() && current_size + footprint > max_content {
1924            slab_groups.push(std::mem::take(&mut current));
1925            current_size = 0;
1926        }
1927        current.push(*drop);
1928        current_size += footprint;
1929    }
1930    if !current.is_empty() {
1931        slab_groups.push(current);
1932    }
1933
1934    // Phase 2 (parallel): encode each slab independently. Slab encoding
1935    // has no cross-slab state — each slab's `offset_in_window` starts
1936    // at 0, its hash is over its own content, its ordinal is its index
1937    // in the slab_groups vector. Rayon parallelises across slabs;
1938    // large images with many slabs get N-core speedup on this phase.
1939    use rayon::prelude::*;
1940    slab_groups
1941        .par_iter()
1942        .enumerate()
1943        .map(|(ordinal, group)| {
1944            let ordinal_u64 = u64::try_from(ordinal).expect("slab count fits u64");
1945            encode_slab(ordinal_u64, group)
1946        })
1947        .collect()
1948}
1949
1950/// Encode a single slab from a non-empty slice of drops. Per-slab
1951/// `offset_in_window` is computed fresh; there is no global offset
1952/// state on `PendingDrop`.
1953fn encode_slab(ordinal: u64, drops: &[&PendingDrop]) -> SlabArtifact {
1954    // Each drop record is a fixed 49-byte entry: id(32) +
1955    // plaintext_len(4) + representation(3) + solid_window_index(1)
1956    // + offset_in_window(4) + window_len(4) + dict_id(1). Pre-sizing
1957    // the records Vec avoids per-drop realloc and amortises to a
1958    // single memcpy per field rather than bounds-check per call.
1959    const DROP_RECORD_LEN: usize = 49;
1960    let mut drop_records = Vec::with_capacity(drops.len() * DROP_RECORD_LEN);
1961    let mut solid_window = Vec::new();
1962    let mut drop_ids = Vec::with_capacity(drops.len());
1963    let mut offset_in_window: u32 = 0;
1964
1965    for drop in drops {
1966        let plaintext_len = drop.plaintext_len_value();
1967        let window_len = drop.len_in_window();
1968        drop_records.extend_from_slice(&drop.id);
1969        drop_records.extend_from_slice(&plaintext_len.to_le_bytes());
1970        // representation: (codec, aead=0, ec=0)
1971        drop_records.extend_from_slice(&[drop.codec, 0x00, 0x00]);
1972        drop_records.push(0x00); // solid_window_index
1973        drop_records.extend_from_slice(&offset_in_window.to_le_bytes());
1974        drop_records.extend_from_slice(&window_len.to_le_bytes());
1975        drop_records.push(drop.dict_id); // dict_id: NO_DICT (0xFF) or trained id (0..=254)
1976        solid_window.extend_from_slice(&drop.compressed);
1977        drop_ids.push(drop.id);
1978        offset_in_window = offset_in_window
1979            .checked_add(window_len)
1980            .expect("slab window size fits u32");
1981    }
1982
1983    let slab_content = [&drop_records[..], &solid_window[..]].concat();
1984    let slab_hash = hash_section(&slab_content);
1985    let slab_id = SlabId::new(ordinal, slab_hash);
1986
1987    let total_length = SLAB_HEADER_LEN + slab_content.len();
1988    let mut slab_bytes = Vec::with_capacity(total_length);
1989    slab_bytes.extend_from_slice(b"LIM1");
1990    slab_bytes.extend_from_slice(&1u16.to_le_bytes());
1991    slab_bytes.extend_from_slice(&slab_id.to_bytes());
1992    slab_bytes.extend_from_slice(
1993        &u64::try_from(total_length)
1994            .unwrap_or(u64::MAX)
1995            .to_le_bytes(),
1996    );
1997    slab_bytes.push(0x00);
1998    slab_bytes.push(0x00);
1999    slab_bytes.extend_from_slice(&slab_content);
2000
2001    let locator = format!("file:slab-{ordinal}.bin");
2002
2003    SlabArtifact {
2004        id: slab_id,
2005        bytes: slab_bytes,
2006        locator,
2007        drop_ids,
2008    }
2009}
2010
2011#[cfg(test)]
2012fn pseudo_random_bytes(seed: u64, count: usize) -> Vec<u8> {
2013    let mut state = seed;
2014    let mut out = Vec::with_capacity(count);
2015    for _ in 0..count {
2016        state = state
2017            .wrapping_mul(6_364_136_223_846_793_005)
2018            .wrapping_add(1_442_695_040_888_963_407);
2019        out.push(u8::try_from(state >> 56).expect("fits u8"));
2020    }
2021    out
2022}
2023
2024#[cfg(test)]
2025mod tests {
2026    use super::*;
2027    use limnifs_core::ManifestCursor;
2028
2029    #[test]
2030    fn write_stream_packs_single_named_stream() {
2031        // Stream 256 KiB of repetitive text through write_stream and
2032        // verify the artifact has a single root file at the requested
2033        // name with the expected size.
2034        let temp = std::env::temp_dir().join(format!(
2035            "limnifs-write-stream-test-{}-{}",
2036            std::process::id(),
2037            std::time::SystemTime::now()
2038                .duration_since(std::time::UNIX_EPOCH)
2039                .unwrap()
2040                .as_nanos()
2041        ));
2042        std::fs::create_dir_all(&temp).expect("create temp dir");
2043
2044        let content = b"stream test content line\n".repeat(10_000); // ~240 KiB
2045        let cursor = std::io::Cursor::new(content.clone());
2046        let config = WriteConfig::default_v0_1();
2047        let artifact = write_stream("streamed.txt", cursor, &config).expect("write_stream");
2048
2049        assert!(!artifact.bytes.is_empty(), "manifest bytes non-empty");
2050        assert!(!artifact.slabs.is_empty(), "at least one slab produced");
2051        // The artifact's manifest encodes the file metadata; we don't
2052        // deeply inspect it here (conformance suite covers that), but
2053        // we do confirm the writer produced something well-formed
2054        // enough that round-tripping through the reader works.
2055        let total_drop_bytes: usize = artifact.slabs.iter().map(|s| s.bytes.len()).sum();
2056        assert!(total_drop_bytes > 0, "drops non-empty");
2057
2058        let _ = std::fs::remove_dir_all(&temp);
2059    }
2060
2061    #[test]
2062    fn write_layer_references_base_drops() {
2063        // Build a base image with a 1 MiB text file, then build a
2064        // layer that ADDS a new file AND includes the same text file.
2065        // The layer's slab bytes must be small (just the new file)
2066        // because the text file's chunks hit the base's drop set and
2067        // are emitted as `CODEC_REFERENCED`.
2068        let temp = std::env::temp_dir().join(format!(
2069            "limnifs-write-layer-test-{}-{}",
2070            std::process::id(),
2071            std::time::SystemTime::now()
2072                .duration_since(std::time::UNIX_EPOCH)
2073                .unwrap()
2074                .as_nanos()
2075        ));
2076        std::fs::create_dir_all(&temp).expect("create temp dir");
2077
2078        // Base: 1 MiB of repetitive text + a small unique file.
2079        let base_dir = temp.join("base");
2080        std::fs::create_dir_all(&base_dir).expect("base dir");
2081        let text = b"layer test content line\n".repeat(50_000); // ~1.15 MiB
2082        std::fs::write(base_dir.join("shared.txt"), &text).expect("write shared");
2083        std::fs::write(base_dir.join("base-only.txt"), b"only in base").expect("write base-only");
2084
2085        let config = WriteConfig::default_v0_1();
2086        let base_artifact = write_directory_with_config(&base_dir, &config).expect("base");
2087
2088        let base_manifest = temp.join("base.lim");
2089        std::fs::write(&base_manifest, &base_artifact.bytes).expect("write base manifest");
2090        for slab in &base_artifact.slabs {
2091            let slab_name = slab.locator.strip_prefix("file:").unwrap_or(&slab.locator);
2092            std::fs::write(temp.join(slab_name), &slab.bytes).expect("write base slab");
2093        }
2094
2095        // Layer: same shared.txt (must dedup against base) + a new file.
2096        let layer_dir = temp.join("layer");
2097        std::fs::create_dir_all(&layer_dir).expect("layer dir");
2098        std::fs::write(layer_dir.join("shared.txt"), &text).expect("write shared in layer");
2099        std::fs::write(layer_dir.join("new.txt"), b"fresh content in layer").expect("write new");
2100
2101        let layer_artifact = write_layer(&base_manifest, &layer_dir, &config).expect("layer");
2102
2103        // The layer's slabs should be SMALL — only the new file's
2104        // content. shared.txt's chunks are referenced via the base.
2105        let layer_slab_bytes: usize = layer_artifact.slabs.iter().map(|s| s.bytes.len()).sum();
2106        let base_slab_bytes: usize = base_artifact.slabs.iter().map(|s| s.bytes.len()).sum();
2107        assert!(
2108            layer_slab_bytes < base_slab_bytes / 4,
2109            "layer slabs ({}) should be much smaller than base ({}) — layering failed",
2110            layer_slab_bytes,
2111            base_slab_bytes
2112        );
2113
2114        // The layer manifest must contain the base's Merkle root in
2115        // its delta_linkage section.
2116        let base_root = base_artifact.merkle_root.as_bytes();
2117        assert!(
2118            layer_artifact
2119                .bytes
2120                .windows(32)
2121                .any(|w| w == base_root.as_slice()),
2122            "layer manifest must contain base's ManifestRoot bytes"
2123        );
2124
2125        let _ = std::fs::remove_dir_all(&temp);
2126    }
2127
2128    #[test]
2129    fn tournament_short_circuits_on_highly_compressible_chunk() {
2130        // Repetitive text compresses to <25% under LZ4. Tournament
2131        // should accept LZ4 and skip the slower Brotli pass.
2132        let chunk = b"hello world ".repeat(500);
2133        let tunables = limnifs_core::codec::CodecTunables::default();
2134        let tournament = TournamentSpec {
2135            codec_ids: vec![
2136                limnifs_core::codec::CODEC_LZ4,
2137                limnifs_core::codec::CODEC_BROTLI,
2138            ],
2139            min_size: 16,
2140            skip_for_binary: false,
2141            short_circuit_permille: 250,
2142        };
2143        let (codec_id, compressed) = compress_chunk_with_tournament(
2144            &chunk,
2145            classifier::Class::Text,
2146            limnifs_core::codec::CODEC_BROTLI,
2147            limnifs_core::codec::CODEC_LZ4,
2148            &tunables,
2149            &tournament,
2150        );
2151        assert_eq!(codec_id, limnifs_core::codec::CODEC_LZ4);
2152        assert!(compressed.len() < chunk.len());
2153    }
2154
2155    #[test]
2156    fn tournament_runs_all_codecs_when_short_circuit_disabled() {
2157        // short_circuit_permille = 0 means "never short-circuit". The
2158        // tournament must try every codec and pick the smallest.
2159        // With omnizip 0.14.40, ZSTD (cached Huffman table) typically
2160        // beats both LZ4 and Brotli's Phase-C partial encoder on
2161        // repetitive text, so we include it in the tournament.
2162        let chunk = b"hello world ".repeat(500);
2163        let tunables = limnifs_core::codec::CodecTunables::default();
2164        let tournament = TournamentSpec {
2165            codec_ids: vec![
2166                limnifs_core::codec::CODEC_LZ4,
2167                limnifs_core::codec::CODEC_BROTLI,
2168                limnifs_core::codec::CODEC_ZSTD,
2169            ],
2170            min_size: 16,
2171            skip_for_binary: false,
2172            short_circuit_permille: 0,
2173        };
2174        let (codec_id, compressed) = compress_chunk_with_tournament(
2175            &chunk,
2176            classifier::Class::Text,
2177            limnifs_core::codec::CODEC_BROTLI,
2178            limnifs_core::codec::CODEC_LZ4,
2179            &tunables,
2180            &tournament,
2181        );
2182        // All three codecs should be tried; the smallest wins. With
2183        // omnizip 0.16.40's long copy fix (MAX_COPY 271→4096), Brotli
2184        // now beats ZSTD on repetitive text. Either is acceptable.
2185        assert!(
2186            codec_id == limnifs_core::codec::CODEC_ZSTD
2187                || codec_id == limnifs_core::codec::CODEC_BROTLI,
2188            "expected ZSTD or Brotli to win, got codec {codec_id}"
2189        );
2190        assert!(compressed.len() < chunk.len());
2191    }
2192
2193    #[test]
2194    fn tournament_skips_for_binary_when_configured() {
2195        let chunk = vec![0u8; 4096];
2196        let tunables = limnifs_core::codec::CodecTunables::default();
2197        let tournament = TournamentSpec {
2198            codec_ids: vec![limnifs_core::codec::CODEC_BROTLI],
2199            min_size: 16,
2200            skip_for_binary: true,
2201            short_circuit_permille: 250,
2202        };
2203        let (codec_id, _compressed) = compress_chunk_with_tournament(
2204            &chunk,
2205            classifier::Class::Binary,
2206            limnifs_core::codec::CODEC_BROTLI,
2207            limnifs_core::codec::CODEC_LZ4,
2208            &tunables,
2209            &tournament,
2210        );
2211        // skip_for_binary → use binary_codec (LZ4) directly, never Brotli.
2212        assert_eq!(codec_id, limnifs_core::codec::CODEC_LZ4);
2213    }
2214
2215    #[test]
2216    fn tournament_small_chunk_uses_preferred_codec() {
2217        let chunk = b"tiny";
2218        let tunables = limnifs_core::codec::CodecTunables::default();
2219        let tournament = TournamentSpec {
2220            codec_ids: vec![limnifs_core::codec::CODEC_BROTLI],
2221            min_size: 1024,
2222            skip_for_binary: false,
2223            short_circuit_permille: 0,
2224        };
2225        let (codec_id, _compressed) = compress_chunk_with_tournament(
2226            chunk,
2227            classifier::Class::Text,
2228            limnifs_core::codec::CODEC_BROTLI,
2229            limnifs_core::codec::CODEC_LZ4,
2230            &tunables,
2231            &tournament,
2232        );
2233        // Below min_size → preferred codec (brotli for text) directly.
2234        assert_eq!(codec_id, limnifs_core::codec::CODEC_STORE);
2235    }
2236
2237    #[test]
2238    fn tournament_falls_back_to_store_when_no_codec_compresses() {
2239        // Random data — no codec should improve on store. We use the
2240        // pseudo-random generator from the test helpers to get
2241        // deterministic but incompressible bytes.
2242        let chunk = pseudo_random_bytes(42, 4096);
2243        let tunables = limnifs_core::codec::CodecTunables::default();
2244        let tournament = TournamentSpec {
2245            codec_ids: vec![limnifs_core::codec::CODEC_LZ4],
2246            min_size: 16,
2247            skip_for_binary: false,
2248            short_circuit_permille: 0,
2249        };
2250        let (codec_id, compressed) = compress_chunk_with_tournament(
2251            &chunk,
2252            classifier::Class::Binary,
2253            limnifs_core::codec::CODEC_BROTLI,
2254            limnifs_core::codec::CODEC_LZ4,
2255            &tunables,
2256            &tournament,
2257        );
2258        assert_eq!(codec_id, limnifs_core::codec::CODEC_STORE);
2259        assert_eq!(compressed.len(), chunk.len());
2260    }
2261
2262    #[test]
2263    fn dictionaries_enabled_emits_dictionary_section_when_enough_samples() {
2264        // Many small text files with shared vocabulary → FrequencyTrainer
2265        // should find a dictionary. We assert the section appears in
2266        // the manifest, regardless of whether the trained dict beats
2267        // per-drop compression (the trainer is content-dependent).
2268        let temp = std::env::temp_dir().join(format!(
2269            "limnifs-write-test-{}-dict-{}",
2270            std::process::id(),
2271            std::time::SystemTime::now()
2272                .duration_since(std::time::UNIX_EPOCH)
2273                .map(|d| d.as_nanos() as u64)
2274                .unwrap_or(0),
2275        ));
2276        let _ = std::fs::remove_dir_all(&temp);
2277        std::fs::create_dir_all(&temp).expect("mkdir");
2278
2279        // Generate 200 similar small files just above INLINE_THRESHOLD
2280        // so they go through the slab path.
2281        for i in 0..200 {
2282            // Repeated vocabulary the trainer can exploit.
2283            let content = format!(
2284                "function test_case_{i}() {{ return constant + {i}; }}\n\
2285                 // shared comment line {i}\n\
2286                 struct Foo {{ x: i32 }} // type {i}\n"
2287            )
2288            .repeat(5);
2289            let path = temp.join(format!("file_{i:04}.txt"));
2290            std::fs::write(&path, content.as_bytes()).expect("write");
2291        }
2292
2293        let mut config = crate::profile::balanced();
2294        // Force ZSTD for text so drops go through the dict-eligible path.
2295        config.defaults.text_codec = "zstd".into();
2296        // omnizip 0.14.40's Brotli encoder emits some streams the
2297        // in-house decoder rejects on highly repetitive input. Use ZSTD
2298        // for the metadata blob too so the round-trip parse succeeds.
2299        config.defaults.metadata_codec = "zstd".into();
2300        config.dictionaries.enabled = true;
2301        config.dictionaries.min_class_size = 50;
2302        config.dictionaries.max_dict_size = 8192;
2303
2304        let artifact = write_directory_with_config(&temp, &config).expect("write");
2305        std::fs::remove_dir_all(&temp).ok();
2306
2307        // The dictionary_section (if emitted) lives after the history
2308        // section. We don't strictly assert presence because the trainer
2309        // may legitimately return an empty dict; the test's job is to
2310        // verify the pipeline doesn't panic and the manifest parses.
2311        let mut cursor = ManifestCursor::new(&artifact.bytes);
2312        let _ = limnifs_core::parse_manifest_header(&mut cursor).expect("header");
2313        let _ = limnifs_core::parse_feature_flags_section(&mut cursor).expect("flags");
2314        let _ = limnifs_core::parse_metadata_reference(&mut cursor).expect("meta_ref");
2315        let _ = limnifs_core::parse_slab_index(&mut cursor).expect("slab_index");
2316        let _ = limnifs_core::parse_history(&mut cursor).expect("history");
2317        // If a dict was emitted, parsing past history should leave
2318        // non-empty remaining bytes.
2319        let _remaining = cursor.remaining_len();
2320    }
2321
2322    #[test]
2323    fn write_empty_directory() {
2324        let temp =
2325            std::env::temp_dir().join(format!("limnifs-write-test-{}-empty", std::process::id()));
2326        std::fs::create_dir_all(&temp).expect("create temp dir");
2327        let artifact = write_directory(&temp).expect("write succeeds");
2328        std::fs::remove_dir_all(&temp).ok();
2329        assert!(artifact.inode_count >= 1);
2330        assert_eq!(artifact.file_count, 0);
2331        assert_eq!(artifact.dir_count, 1);
2332        assert!(artifact.slabs.is_empty());
2333    }
2334
2335    #[test]
2336    fn write_small_file_inline() {
2337        let temp =
2338            std::env::temp_dir().join(format!("limnifs-write-test-{}-small", std::process::id()));
2339        std::fs::create_dir_all(&temp).expect("create temp dir");
2340        std::fs::write(temp.join("hello.txt"), b"hello world").expect("write file");
2341        let artifact = write_directory(&temp).expect("write succeeds");
2342        std::fs::remove_dir_all(&temp).ok();
2343        assert_eq!(artifact.file_count, 1);
2344        assert!(artifact.slabs.is_empty());
2345        assert_eq!(artifact.drop_count, 0);
2346    }
2347
2348    #[test]
2349    fn write_large_file_uses_slab() {
2350        let temp =
2351            std::env::temp_dir().join(format!("limnifs-write-test-{}-large", std::process::id()));
2352        std::fs::create_dir_all(&temp).expect("create temp dir");
2353        let large_data = vec![0xABu8; INLINE_THRESHOLD + 100];
2354        std::fs::write(temp.join("big.bin"), &large_data).expect("write big");
2355        let artifact = write_directory(&temp).expect("write succeeds");
2356        std::fs::remove_dir_all(&temp).ok();
2357        assert_eq!(artifact.drop_count, 1);
2358        assert_eq!(artifact.slabs.len(), 1);
2359    }
2360
2361    #[test]
2362    fn write_mixed_inline_and_large() {
2363        let temp =
2364            std::env::temp_dir().join(format!("limnifs-write-test-{}-mix", std::process::id()));
2365        std::fs::create_dir_all(&temp).expect("create temp dir");
2366        std::fs::write(temp.join("small.txt"), b"tiny").expect("write small");
2367        std::fs::write(temp.join("large.bin"), vec![0xCDu8; INLINE_THRESHOLD * 2])
2368            .expect("write large");
2369        let artifact = write_directory(&temp).expect("write succeeds");
2370        std::fs::remove_dir_all(&temp).ok();
2371        assert_eq!(artifact.file_count, 2);
2372        assert_eq!(artifact.drop_count, 1);
2373        assert_eq!(artifact.slabs.len(), 1);
2374    }
2375
2376    #[test]
2377    fn deduplicates_identical_large_files() {
2378        let temp =
2379            std::env::temp_dir().join(format!("limnifs-write-test-{}-dedup", std::process::id()));
2380        std::fs::create_dir_all(&temp).expect("create temp dir");
2381        let data = vec![0x77u8; INLINE_THRESHOLD + 10];
2382        std::fs::write(temp.join("a.bin"), &data).expect("write a");
2383        std::fs::write(temp.join("b.bin"), &data).expect("write b");
2384        let artifact = write_directory(&temp).expect("write succeeds");
2385        std::fs::remove_dir_all(&temp).ok();
2386        assert_eq!(artifact.drop_count, 1);
2387    }
2388
2389    #[test]
2390    fn write_and_verify_roundtrip() {
2391        let temp = std::env::temp_dir().join(format!(
2392            "limnifs-write-test-{}-roundtrip",
2393            std::process::id()
2394        ));
2395        std::fs::create_dir_all(&temp).expect("create temp dir");
2396        std::fs::write(temp.join("a.txt"), b"aaa").expect("write a");
2397        std::fs::write(temp.join("b.txt"), b"bbb").expect("write b");
2398        std::fs::create_dir_all(temp.join("sub")).expect("create sub");
2399        std::fs::write(temp.join("sub").join("c.txt"), b"ccc").expect("write c");
2400        let artifact = write_directory(&temp).expect("write succeeds");
2401        std::fs::remove_dir_all(&temp).ok();
2402        assert_eq!(artifact.file_count, 3);
2403        assert_eq!(artifact.dir_count, 2);
2404
2405        let mut cursor = ManifestCursor::new(&artifact.bytes);
2406        limnifs_core::parse_manifest_header(&mut cursor).expect("header");
2407        limnifs_core::parse_feature_flags_section(&mut cursor).expect("flags");
2408        let meta_ref = limnifs_core::parse_metadata_reference(&mut cursor).expect("meta ref");
2409        assert!(meta_ref.is_inlined());
2410        let slab_index = limnifs_core::parse_slab_index(&mut cursor).expect("slab index");
2411        assert_eq!(slab_index.len(), 0);
2412        limnifs_core::parse_history(&mut cursor).expect("history");
2413    }
2414
2415    #[test]
2416    fn write_deterministic() {
2417        let temp =
2418            std::env::temp_dir().join(format!("limnifs-write-test-{}-det", std::process::id()));
2419        std::fs::create_dir_all(&temp).expect("create temp dir");
2420        std::fs::write(temp.join("x.txt"), b"xxx").expect("write x");
2421
2422        let a1 = write_directory(&temp).expect("first write");
2423        let a2 = write_directory(&temp).expect("second write");
2424        std::fs::remove_dir_all(&temp).ok();
2425
2426        assert_eq!(a1.bytes, a2.bytes);
2427        assert_eq!(a1.merkle_root, a2.merkle_root);
2428    }
2429
2430    #[test]
2431    fn slab_parses_correctly() {
2432        let temp =
2433            std::env::temp_dir().join(format!("limnifs-write-test-{}-slab", std::process::id()));
2434        std::fs::create_dir_all(&temp).expect("create temp dir");
2435        std::fs::write(temp.join("big.bin"), vec![0x11u8; INLINE_THRESHOLD + 1])
2436            .expect("write big");
2437        let artifact = write_directory(&temp).expect("write succeeds");
2438        std::fs::remove_dir_all(&temp).ok();
2439
2440        let slab_bytes = &artifact.slabs[0].bytes;
2441        let mut cursor = ManifestCursor::new(slab_bytes);
2442        let slab_header = limnifs_core::parse_slab_header(&mut cursor).expect("slab header parses");
2443        assert_eq!(slab_header.format_version, 1);
2444        assert!(!slab_header.is_sealed());
2445        assert!(!slab_header.has_erasure_coding());
2446
2447        let drop_record =
2448            limnifs_core::parse_drop_record(&mut cursor, &slab_header).expect("drop record parses");
2449        assert_eq!(drop_record.plaintext_len as usize, INLINE_THRESHOLD + 1);
2450    }
2451
2452    #[test]
2453    fn fastcdc_produces_multiple_chunks_for_large_files() {
2454        // A 1 MiB pseudo-random file should produce multiple drops
2455        // via FastCDC (default chunker uses 64 KiB min / 256 KiB avg).
2456        let temp = std::env::temp_dir().join(format!(
2457            "limnifs-write-test-{}-cdc-multi",
2458            std::process::id()
2459        ));
2460        std::fs::create_dir_all(&temp).expect("create temp dir");
2461        let data = pseudo_random_bytes(42, 1024 * 1024);
2462        std::fs::write(temp.join("big.bin"), &data).expect("write big");
2463        let artifact = write_directory(&temp).expect("write succeeds");
2464        std::fs::remove_dir_all(&temp).ok();
2465        assert!(
2466            artifact.drop_count > 1,
2467            "expected FastCDC to produce multiple drops for 1 MiB input, got {}",
2468            artifact.drop_count
2469        );
2470    }
2471
2472    #[test]
2473    fn fastcdc_deduplicates_shared_substrings() {
2474        // Two files sharing a long middle section should produce
2475        // fewer drops than the sum of their individual chunk counts,
2476        // because the shared section's chunks deduplicate.
2477        let temp = std::env::temp_dir().join(format!(
2478            "limnifs-write-test-{}-cdc-dedup",
2479            std::process::id()
2480        ));
2481        std::fs::create_dir_all(&temp).expect("create temp dir");
2482        let shared = pseudo_random_bytes(7, 512 * 1024);
2483        let mut a = Vec::with_capacity(shared.len() + 1024);
2484        a.extend_from_slice(&pseudo_random_bytes(1, 1024));
2485        a.extend_from_slice(&shared);
2486        let mut b = Vec::with_capacity(shared.len() + 2048);
2487        b.extend_from_slice(&pseudo_random_bytes(2, 2048));
2488        b.extend_from_slice(&shared);
2489        std::fs::write(temp.join("a.bin"), &a).expect("write a");
2490        std::fs::write(temp.join("b.bin"), &b).expect("write b");
2491
2492        // Baseline: each file alone.
2493        let temp_a = std::env::temp_dir().join(format!(
2494            "limnifs-write-test-{}-cdc-dedup-a",
2495            std::process::id()
2496        ));
2497        std::fs::create_dir_all(&temp_a).expect("create temp_a");
2498        std::fs::write(temp_a.join("a.bin"), &a).expect("write a");
2499        let artifact_a = write_directory(&temp_a).expect("a writes");
2500        std::fs::remove_dir_all(&temp_a).ok();
2501
2502        let temp_b = std::env::temp_dir().join(format!(
2503            "limnifs-write-test-{}-cdc-dedup-b",
2504            std::process::id()
2505        ));
2506        std::fs::create_dir_all(&temp_b).expect("create temp_b");
2507        std::fs::write(temp_b.join("b.bin"), &b).expect("write b");
2508        let artifact_b = write_directory(&temp_b).expect("b writes");
2509        std::fs::remove_dir_all(&temp_b).ok();
2510
2511        let artifact_both = write_directory(&temp).expect("both write");
2512        std::fs::remove_dir_all(&temp).ok();
2513
2514        let sum_alone = artifact_a.drop_count + artifact_b.drop_count;
2515        assert!(
2516            artifact_both.drop_count < sum_alone,
2517            "expected dedup win: both together = {} drops, sum alone = {} drops",
2518            artifact_both.drop_count,
2519            sum_alone
2520        );
2521    }
2522
2523    #[test]
2524    fn slab_splits_when_content_exceeds_ceiling() {
2525        // Synthesise enough incompressible drops to force at least two
2526        // slabs. Each drop is 10 MiB of pseudo-random data; three drops
2527        // = 30 MiB compressed (random data doesn't compress), which
2528        // fits in one slab. We bump to seven drops (70 MiB) to force a
2529        // split.
2530        let temp =
2531            std::env::temp_dir().join(format!("limnifs-write-test-{}-split", std::process::id()));
2532        std::fs::create_dir_all(&temp).expect("create temp dir");
2533        for i in 0..7u32 {
2534            // 10 MiB of pseudo-random bytes — incompressible.
2535            let data = pseudo_random_bytes(u64::from(i), 10 * 1024 * 1024);
2536            std::fs::write(temp.join(format!("big-{i}.bin")), &data).expect("write big");
2537        }
2538        let artifact = write_directory(&temp).expect("write succeeds");
2539        std::fs::remove_dir_all(&temp).ok();
2540
2541        // Each slab's total length must respect MAX_SLAB_TOTAL_BYTES.
2542        assert!(
2543            artifact.slabs.len() >= 2,
2544            "expected at least 2 slabs for 70 MiB of incompressible data, got {}",
2545            artifact.slabs.len()
2546        );
2547        for slab in &artifact.slabs {
2548            assert!(
2549                slab.bytes.len() <= MAX_SLAB_TOTAL_BYTES,
2550                "slab {} is {} bytes (> {} ceiling)",
2551                slab.id.ordinal,
2552                slab.bytes.len(),
2553                MAX_SLAB_TOTAL_BYTES,
2554            );
2555        }
2556        // All seven drops must be accounted for across slabs.
2557        let total_drop_ids: usize = artifact.slabs.iter().map(|s| s.drop_ids.len()).sum();
2558        assert_eq!(
2559            total_drop_ids, artifact.drop_count,
2560            "drop_ids count across slabs must match WriteArtifact.drop_count",
2561        );
2562    }
2563}