hexz_core/ops/pack.rs
1//! High-level snapshot packing operations.
2//!
3//! This module implements the core business logic for creating Hexz snapshot files
4//! from raw disk and memory images. It orchestrates a multi-stage pipeline that
5//! transforms raw input data into compressed, indexed, and optionally encrypted
6//! snapshot files optimized for fast random access and deduplication.
7//!
8//! # Core Capabilities
9//!
10//! - **Dictionary Training**: Intelligent sampling and Zstd dictionary optimization
11//! - **Chunking Strategies**: Fixed-size blocks or content-defined (FastCDC) for better deduplication
12//! - **Compression**: LZ4 (fast) or Zstd (high-ratio) with optional dictionary support
13//! - **Encryption**: Per-block AES-256-GCM authenticated encryption
14//! - **Deduplication**: BLAKE3 based content deduplication (disabled for encrypted data)
15//! - **Hierarchical Indexing**: Two-level index structure for efficient random access
16//! - **Progress Reporting**: Optional callback interface for UI integration
17//!
18//! # Architecture
19//!
20//! The packing process follows a carefully orchestrated pipeline. Each stage is designed
21//! to be memory-efficient (streaming) and to minimize write amplification:
22//!
23//! ```text
24//! ┌─────────────────────────────────────────────────────────────────────┐
25//! │ Stage 1: Dictionary Training (Optional, Zstd only) │
26//! │ │
27//! │ Input File → Stratified Sampling → Entropy Filtering → Zstd Train │
28//! │ │
29//! │ - Samples ~4000 blocks evenly distributed across input │
30//! │ - Filters out zero blocks and high-entropy data (>6.0 bits/byte) │
31//! │ - Produces dictionary (max 110 KiB) optimized for dataset │
32//! │ - Training time: 2-5 seconds for typical VM images │
33//! └─────────────────────────────────────────────────────────────────────┘
34//! ↓
35//! ┌─────────────────────────────────────────────────────────────────────┐
36//! │ Stage 2: Stream Processing (Per Input: Disk, Memory) │
37//! │ │
38//! │ Raw Input → Chunking → Compression → Encryption → Dedup → Write │
39//! │ │
40//! │ Chunking: │
41//! │ - Fixed-size: Divide into equal blocks (default 64 KiB) │
42//! │ - FastCDC: Content-defined boundaries for better deduplication │
43//! │ │
44//! │ Zero Block Optimization: │
45//! │ - Detect all-zero chunks (common in VM images) │
46//! │ - Store as metadata only (offset=0, length=0) │
47//! │ - Saves significant space for sparse images │
48//! │ │
49//! │ Deduplication (Unencrypted only): │
50//! │ - Compute BLAKE3 hash of compressed data │
51//! │ - Check hash table for existing block │
52//! │ - Reuse offset if duplicate found │
53//! │ - Note: Disabled for encrypted data (unique nonces prevent dedup) │
54//! │ │
55//! │ Index Page Building: │
56//! │ - Accumulate BlockInfo metadata (offset, length, checksum) │
57//! │ - Flush page when reaching 4096 entries (~16 MB logical data) │
58//! │ - Write serialized page to output, record PageEntry │
59//! └─────────────────────────────────────────────────────────────────────┘
60//! ↓
61//! ┌─────────────────────────────────────────────────────────────────────┐
62//! │ Stage 3: Index Finalization │
63//! │ │
64//! │ MasterIndex (disk_pages[], memory_pages[], sizes) → Serialize │
65//! │ │
66//! │ - Collect all PageEntry records from both streams │
67//! │ - Write master index at end of file │
68//! │ - Record index offset in header │
69//! └─────────────────────────────────────────────────────────────────────┘
70//! ↓
71//! ┌─────────────────────────────────────────────────────────────────────┐
72//! │ Stage 4: Header Writing │
73//! │ │
74//! │ - Seek to file start (reserved 512 bytes) │
75//! │ - Write Header with format metadata │
76//! │ - Includes: compression type, encryption params, index offset │
77//! │ - Flush to ensure atomicity │
78//! └─────────────────────────────────────────────────────────────────────┘
79//! ```
80//!
81//! # Optimization Strategies
82//!
83//! ## Dictionary Training Algorithm
84//!
85//! The dictionary training process improves compression ratios by 10-30% for
86//! structured data (file systems, databases) by building a Zstd shared dictionary:
87//!
88//! 1. **Stratified Sampling**: Sample blocks evenly across input to capture diversity
89//! - Step size = file_size / target_samples (typically 4000 samples)
90//! - Ensures coverage of different file system regions
91//!
92//! 2. **Quality Filtering**: Exclude unsuitable blocks
93//! - Skip all-zero blocks (no compressible patterns)
94//! - Compute Shannon entropy for each block
95//! - Reject blocks with entropy > 6.0 bits/byte (likely encrypted/random)
96//!
97//! 3. **Training**: Feed filtered samples to Zstd dictionary builder
98//! - Target dictionary size: 110 KiB (fits in L2 cache)
99//! - Uses Zstd's COVER algorithm to extract common patterns
100//!
101//! ## Deduplication Mechanism
102//!
103//! Content-based deduplication eliminates redundant blocks:
104//!
105//! - **Hash Table**: Maps BLAKE3 hash → physical offset for each unique compressed block
106//! - **Collision Handling**: BLAKE3 collisions are astronomically unlikely (2^128 blocks)
107//! - **Memory Usage**: ~48 bytes per unique block (32-byte hash + 8-byte offset + HashMap overhead)
108//! - **Write Behavior**: Only write each unique block once; reuse offset for duplicates
109//! - **Encryption Interaction**: Disabled when encrypting (each block gets unique nonce/ciphertext)
110//!
111//! ## Index Page Management
112//!
113//! The two-level index hierarchy balances random access performance and metadata overhead:
114//!
115//! - **Page Size**: 4096 entries per page
116//! - With 64 KiB blocks: Each page covers ~256 MB of logical data
117//! - Serialized page size: ~64 KiB (fits in L2 cache)
118//!
119//! - **Flushing Strategy**: Eager flush when page fills
120//! - Prevents memory growth during large packs
121//! - Enables streaming operation (constant memory)
122//!
123//! - **Master Index**: Array of PageEntry records
124//! - Binary search for O(log N) page lookup
125//! - Typical overhead: 1 KiB per GB of data
126//!
127//! # Memory Usage Patterns
128//!
129//! The packing operation is designed for constant memory usage regardless of input size:
130//!
131//! - **Chunking Buffer**: 1 block (64 KiB default)
132//! - **Compression Output**: ~1.5× block size (worst case: incompressible data)
133//! - **Current Index Page**: Up to 4096 × 20 bytes = 80 KiB
134//! - **Deduplication Map**: ~48 bytes × unique_blocks
135//! - Example: 10 GB image with 50% dedup = ~80 MB HashMap
136//! - **Dictionary**: 110 KiB (if trained)
137//!
138//! Total typical memory: 100-200 MB for dedup hash table + ~1 MB working set.
139//!
140//! # Error Recovery
141//!
142//! The packing operation is not atomic. On failure:
143//!
144//! - **Partial File**: Output file is left in incomplete state
145//! - **Header Invalid**: Header is written last, so partial packs have zeroed header
146//! - **Detection**: Readers validate magic bytes and header checksum
147//! - **Recovery**: None; must delete partial file and retry pack operation
148//!
149//! Future enhancement: Two-phase commit with temporary file + atomic rename.
150//!
151//! # Usage Contexts
152//!
153//! This module is designed to be called from multiple contexts:
154//!
155//! - **CLI Commands**: `hexz data pack` (with terminal progress bars)
156//! - **Python Bindings**: `hexz.pack()` (with optional callbacks)
157//! - **Rust Applications**: Direct API usage for embedded scenarios
158//!
159//! By keeping pack operations separate from UI/CLI code, we avoid pulling in
160//! heavy dependencies (`clap`, `indicatif`) into library contexts.
161//!
162//! # Examples
163//!
164//! ## Basic Packing (LZ4, No Encryption)
165//!
166//! ```no_run
167//! use hexz_core::ops::pack::{pack_snapshot, PackConfig};
168//! use std::path::PathBuf;
169//!
170//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
171//! let config = PackConfig {
172//! disk: Some(PathBuf::from("disk.raw")),
173//! memory: None,
174//! output: PathBuf::from("snapshot.hxz"),
175//! compression: "lz4".to_string(),
176//! ..Default::default()
177//! };
178//!
179//! pack_snapshot::<fn(u64, u64)>(config, None)?;
180//! # Ok(())
181//! # }
182//! ```
183//!
184//! ## Advanced Packing (Zstd with Dictionary, CDC, Encryption)
185//!
186//! ```no_run
187//! use hexz_core::ops::pack::{pack_snapshot, PackConfig};
188//! use std::path::PathBuf;
189//!
190//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
191//! let config = PackConfig {
192//! disk: Some(PathBuf::from("ubuntu.qcow2")),
193//! output: PathBuf::from("ubuntu.hxz"),
194//! compression: "zstd".to_string(),
195//! train_dict: true, // Train dictionary for better ratio
196//! cdc_enabled: true, // Content-defined chunking
197//! encrypt: true,
198//! password: Some("secure_passphrase".to_string()),
199//! min_chunk: 16384, // 16 KiB minimum chunk
200//! avg_chunk: 65536, // 64 KiB average chunk
201//! max_chunk: 262144, // 256 KiB maximum chunk
202//! ..Default::default()
203//! };
204//!
205//! pack_snapshot::<fn(u64, u64)>(config, None)?;
206//! # Ok(())
207//! # }
208//! ```
209//!
210//! ## Progress Reporting
211//!
212//! ```no_run
213//! use hexz_core::ops::pack::{pack_snapshot, PackConfig};
214//! use std::path::PathBuf;
215//!
216//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
217//! let config = PackConfig {
218//! disk: Some(PathBuf::from("disk.raw")),
219//! output: PathBuf::from("snapshot.hxz"),
220//! ..Default::default()
221//! };
222//!
223//! // Callback receives (current_logical_pos, total_size)
224//! pack_snapshot(config, Some(|pos, total| {
225//! let pct = (pos as f64 / total as f64) * 100.0;
226//! println!("Packing: {:.1}%", pct);
227//! }))?;
228//! # Ok(())
229//! # }
230//! ```
231//!
232//! # Performance Characteristics
233//!
234//! ## Throughput (Single-Threaded, i7-14700K)
235//!
236//! Validated benchmarks (see `docs/project-docs/BENCHMARKS.md` for details):
237//!
238//! - **LZ4 Compression**: 22 GB/s (minimal CPU overhead)
239//! - **LZ4 Decompression**: 31 GB/s
240//! - **Zstd Level 3 Compression**: 8.7 GB/s
241//! - **Zstd Level 3 Decompression**: 12.9 GB/s
242//! - **BLAKE3 Hashing**: 5.3 GB/s (2.2× faster than SHA-256)
243//! - **SHA-256 Hashing**: 2.5 GB/s
244//! - **FastCDC Chunking**: 2.7 GB/s (gear-based rolling hash)
245//! - **AES-256-GCM Encryption**: 2.1 GB/s (hardware AES-NI acceleration)
246//! - **Pack Throughput (LZ4, no CDC)**: 4.9 GB/s (64KB blocks)
247//! - **Pack Throughput (LZ4 + CDC)**: 1.9 GB/s (CDC adds 2.6× overhead)
248//! - **Pack Throughput (Zstd-3)**: 1.6 GB/s
249//! - **Block Size Impact**: 2.3 GB/s (4KB) → 4.7 GB/s (64KB) → 5.1 GB/s (1MB)
250//!
251//! Typical bottleneck: CDC chunking (when enabled) or compression CPU time. SSD I/O rarely limits.
252//!
253//! Run benchmarks: `cargo bench --bench compression`, `cargo bench --bench hashing`, `cargo bench --bench cdc_chunking`, `cargo bench --bench encryption`, `cargo bench --bench write_throughput`, and `cargo bench --bench block_size_tradeoffs`
254//!
255//! ## Compression Ratios (Typical VM Images)
256//!
257//! - **LZ4**: 2-3× (fast but lower ratio)
258//! - **Zstd Level 3**: 3-5× (good balance)
259//! - **Zstd + Dictionary**: 4-7× (+30% improvement from dictionary)
260//! - **CDC Deduplication**: Not validated - need benchmark comparing CDC vs fixed-size chunking
261//!
262//! ## Time Estimates (64 GB VM Image, Single Thread)
263//!
264//! - **LZ4, Fixed Blocks**: ~30-45 seconds
265//! - **Zstd, Fixed Blocks**: ~2-3 minutes
266//! - **Zstd + Dictionary + CDC**: ~3-5 minutes (includes 2-5s training time)
267//!
268//! # Atomicity and Crash Safety
269//!
270//! **WARNING**: Pack operations are NOT atomic. If interrupted:
271//!
272//! - Output file is left in a partially written state
273//! - The header (written last) will be all zeros
274//! - Readers will reject the file due to invalid magic bytes
275//! - Manual cleanup is required (delete partial file)
276//!
277//! For production use cases requiring atomicity, write to a temporary file and
278//! perform an atomic rename after successful completion.
279
280use hexz_common::constants::{DICT_TRAINING_SIZE, ENTROPY_THRESHOLD};
281use hexz_common::crypto::KeyDerivationParams;
282use hexz_common::{Error, Result};
283use std::fs::File;
284use std::io::{Read, Seek, SeekFrom};
285use std::path::{Path, PathBuf};
286
287use crate::algo::compression::{create_compressor_from_str, zstd::ZstdCompressor};
288use crate::algo::dedup::cdc::StreamChunker;
289use crate::algo::dedup::dcam::DedupeParams;
290use crate::algo::encryption::{Encryptor, aes_gcm::AesGcmEncryptor};
291use crate::ops::snapshot_writer::SnapshotWriter;
292
293/// Configuration parameters for snapshot packing.
294///
295/// This struct encapsulates all settings for the packing process. It's designed
296/// to be easily constructed from CLI arguments or programmatic APIs.
297///
298/// # Examples
299///
300/// ```
301/// use hexz_core::ops::pack::PackConfig;
302/// use std::path::PathBuf;
303///
304/// // Basic configuration with defaults
305/// let config = PackConfig {
306/// disk: Some(PathBuf::from("disk.img")),
307/// output: PathBuf::from("snapshot.hxz"),
308/// ..Default::default()
309/// };
310///
311/// // Advanced configuration with CDC and encryption
312/// let advanced = PackConfig {
313/// disk: Some(PathBuf::from("disk.img")),
314/// output: PathBuf::from("snapshot.hxz"),
315/// compression: "zstd".to_string(),
316/// encrypt: true,
317/// password: Some("secret".to_string()),
318/// cdc_enabled: true,
319/// min_chunk: 16384,
320/// avg_chunk: 65536,
321/// max_chunk: 131072,
322/// ..Default::default()
323/// };
324/// ```
325#[derive(Debug, Clone)]
326pub struct PackConfig {
327 /// Path to the disk image (optional).
328 pub disk: Option<PathBuf>,
329 /// Path to the memory image (optional).
330 pub memory: Option<PathBuf>,
331 /// Output snapshot file path.
332 pub output: PathBuf,
333 /// Compression algorithm ("lz4" or "zstd").
334 pub compression: String,
335 /// Enable encryption.
336 pub encrypt: bool,
337 /// Encryption password (required if encrypt=true).
338 pub password: Option<String>,
339 /// Train a compression dictionary (zstd only).
340 pub train_dict: bool,
341 /// Block size in bytes.
342 pub block_size: u32,
343 /// Enable content-defined chunking (CDC).
344 pub cdc_enabled: bool,
345 /// Minimum chunk size for CDC.
346 pub min_chunk: u32,
347 /// Average chunk size for CDC.
348 pub avg_chunk: u32,
349 /// Maximum chunk size for CDC.
350 pub max_chunk: u32,
351}
352
353impl Default for PackConfig {
354 fn default() -> Self {
355 Self {
356 disk: None,
357 memory: None,
358 output: PathBuf::from("output.hxz"),
359 compression: "lz4".to_string(),
360 encrypt: false,
361 password: None,
362 train_dict: false,
363 block_size: 65536,
364 cdc_enabled: false,
365 min_chunk: 16384,
366 avg_chunk: 65536,
367 max_chunk: 131072,
368 }
369 }
370}
371
372/// Calculates Shannon entropy of a byte slice.
373///
374/// Shannon entropy measures the "randomness" or information content of data:
375/// - **0.0**: All bytes are identical (highly compressible)
376/// - **8.0**: Maximum entropy, random data (incompressible)
377///
378/// # Formula
379///
380/// ```text
381/// H(X) = -Σ p(x) * log2(p(x))
382/// ```
383///
384/// Where `p(x)` is the frequency of each byte value.
385///
386/// # Usage
387///
388/// Used during dictionary training to filter out high-entropy (random) blocks
389/// that wouldn't benefit from compression. Only blocks with entropy below
390/// `ENTROPY_THRESHOLD` are included in the training set.
391///
392/// # Parameters
393///
394/// - `data`: Byte slice to analyze
395///
396/// # Returns
397///
398/// Entropy value from 0.0 (homogeneous) to 8.0 (random).
399///
400/// # Examples
401///
402/// ```
403/// # use hexz_core::ops::pack::calculate_entropy;
404/// // Homogeneous data (low entropy)
405/// let zeros = vec![0u8; 1024];
406/// let entropy = calculate_entropy(&zeros);
407/// assert_eq!(entropy, 0.0);
408///
409/// // Random data (high entropy)
410/// let random: Vec<u8> = (0..=255).cycle().take(1024).collect();
411/// let entropy = calculate_entropy(&random);
412/// assert!(entropy > 7.0);
413/// ```
414pub fn calculate_entropy(data: &[u8]) -> f64 {
415 if data.is_empty() {
416 return 0.0;
417 }
418
419 let mut frequencies = [0u32; 256];
420 for &byte in data {
421 frequencies[byte as usize] += 1;
422 }
423
424 let len = data.len() as f64;
425 let mut entropy = 0.0;
426
427 for &count in frequencies.iter() {
428 if count > 0 {
429 let p = count as f64 / len;
430 entropy -= p * p.log2();
431 }
432 }
433
434 entropy
435}
436
437/// Fixed-size block chunker with buffer reuse.
438///
439/// Splits input into equal-sized blocks (except possibly the last one).
440/// Simpler and faster than CDC, but less effective for deduplication.
441///
442/// Reuses an internal buffer across calls to `next_chunk()`, eliminating
443/// per-chunk allocation after the first call.
444pub struct FixedChunker<R> {
445 reader: R,
446 block_size: usize,
447 buffer: Vec<u8>,
448 done: bool,
449}
450
451impl<R: Read> FixedChunker<R> {
452 /// Creates a new fixed-size chunker.
453 pub fn new(reader: R, block_size: usize) -> Self {
454 Self {
455 reader,
456 block_size,
457 buffer: vec![0u8; block_size],
458 done: false,
459 }
460 }
461
462 /// Returns the next chunk as a borrowed slice, or `None` at EOF.
463 ///
464 /// Zero allocations after the first call thanks to buffer reuse.
465 fn next_chunk(&mut self) -> std::io::Result<Option<&[u8]>> {
466 if self.done {
467 return Ok(None);
468 }
469 let mut pos = 0;
470 self.buffer.resize(self.block_size, 0);
471 while pos < self.block_size {
472 match self.reader.read(&mut self.buffer[pos..]) {
473 Ok(0) => break,
474 Ok(n) => pos += n,
475 Err(e) => return Err(e),
476 }
477 }
478 if pos == 0 {
479 self.done = true;
480 Ok(None)
481 } else {
482 self.buffer.truncate(pos);
483 Ok(Some(&self.buffer))
484 }
485 }
486}
487
488impl<R: Read> Iterator for FixedChunker<R> {
489 type Item = std::io::Result<Vec<u8>>;
490
491 fn next(&mut self) -> Option<Self::Item> {
492 match self.next_chunk() {
493 Ok(Some(slice)) => Some(Ok(slice.to_vec())),
494 Ok(None) => None,
495 Err(e) => Some(Err(e)),
496 }
497 }
498}
499
500/// Packs a snapshot file from disk and/or memory images.
501///
502/// This is the main entry point for creating Hexz snapshot files. It orchestrates
503/// the complete packing pipeline: dictionary training, stream processing, index
504/// building, and header finalization.
505///
506/// # Workflow
507///
508/// 1. **Validation**: Ensure at least one input (disk or memory) is provided
509/// 2. **File Creation**: Create output file, reserve 512 bytes for header
510/// 3. **Dictionary Training**: If requested (Zstd only), train dictionary from input samples
511/// 4. **Dictionary Writing**: If trained, write dictionary immediately after header
512/// 5. **Compressor Initialization**: Create LZ4 or Zstd compressor (with optional dictionary)
513/// 6. **Encryptor Initialization**: If requested, derive key from password using PBKDF2
514/// 7. **Stream Processing**: Process disk stream (if provided), then memory stream (if provided)
515/// - Each stream independently chunks, compresses, encrypts, deduplicates, and indexes
516/// 8. **Master Index Writing**: Serialize master index (all PageEntry records) to end of file
517/// 9. **Header Writing**: Seek to start, write complete header with metadata and offsets
518/// 10. **Flush**: Ensure all data is written to disk
519///
520/// # Parameters
521///
522/// - `config`: Packing configuration parameters (see [`PackConfig`])
523/// - `progress_callback`: Optional callback for progress reporting
524/// - Called frequently during stream processing (~once per 64 KiB)
525/// - Signature: `Fn(logical_pos: u64, total_size: u64)`
526/// - Example: `|pos, total| println!("Progress: {:.1}%", (pos as f64 / total as f64) * 100.0)`
527///
528/// # Returns
529///
530/// - `Ok(())`: Snapshot packed successfully
531/// - `Err(Error::Io)`: I/O error (file access, disk full, permission denied)
532/// - `Err(Error::Compression)`: Compression error (unlikely, usually indicates invalid state)
533/// - `Err(Error::Encryption)`: Encryption error (invalid password format, crypto failure)
534///
535/// # Errors
536///
537/// This function can fail for several reasons:
538///
539/// ## I/O Errors
540///
541/// - **Input file not found**: `config.disk` or `config.memory` path doesn't exist
542/// - **Permission denied**: Cannot read input or write output
543/// - **Disk full**: Insufficient space for output file
544/// - **Output exists**: May overwrite existing file without warning
545///
546/// ## Configuration Errors
547///
548/// - **No inputs**: Neither `disk` nor `memory` is provided
549/// - **Missing password**: `encrypt = true` but `password = None`
550/// - **Invalid block size**: Block size too small (<1 KiB) or too large (>16 MiB)
551/// - **Invalid CDC params**: `min_chunk >= avg_chunk >= max_chunk` constraint violated
552///
553/// ## Compression/Encryption Errors
554///
555/// - **Dictionary training failure**: Zstd training fails (rare, usually on corrupted input)
556/// - **Compression failure**: Compressor returns error (rare, usually indicates bug)
557/// - **Encryption failure**: Key derivation or cipher initialization fails
558///
559/// # Examples
560///
561/// ## Basic Usage
562///
563/// ```no_run
564/// use hexz_core::ops::pack::{pack_snapshot, PackConfig};
565/// use std::path::PathBuf;
566///
567/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
568/// let config = PackConfig {
569/// disk: Some(PathBuf::from("disk.raw")),
570/// output: PathBuf::from("snapshot.hxz"),
571/// ..Default::default()
572/// };
573///
574/// pack_snapshot::<fn(u64, u64)>(config, None)?;
575/// # Ok(())
576/// # }
577/// ```
578///
579/// ## With Progress Reporting
580///
581/// ```no_run
582/// use hexz_core::ops::pack::{pack_snapshot, PackConfig};
583/// use std::path::PathBuf;
584///
585/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
586/// let config = PackConfig {
587/// disk: Some(PathBuf::from("ubuntu.qcow2")),
588/// output: PathBuf::from("ubuntu.hxz"),
589/// compression: "zstd".to_string(),
590/// train_dict: true,
591/// ..Default::default()
592/// };
593///
594/// pack_snapshot(config, Some(|pos, total| {
595/// eprint!("\rPacking: {:.1}%", (pos as f64 / total as f64) * 100.0);
596/// }))?;
597/// eprintln!("\nDone!");
598/// # Ok(())
599/// # }
600/// ```
601///
602/// ## Encrypted Snapshot
603///
604/// ```no_run
605/// use hexz_core::ops::pack::{pack_snapshot, PackConfig};
606/// use std::path::PathBuf;
607///
608/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
609/// let config = PackConfig {
610/// disk: Some(PathBuf::from("sensitive.raw")),
611/// output: PathBuf::from("sensitive.hxz"),
612/// encrypt: true,
613/// password: Some("strong_passphrase".to_string()),
614/// ..Default::default()
615/// };
616///
617/// pack_snapshot::<fn(u64, u64)>(config, None)?;
618/// println!("Encrypted snapshot created");
619/// # Ok(())
620/// # }
621/// ```
622///
623/// ## Content-Defined Chunking for Deduplication
624///
625/// ```no_run
626/// use hexz_core::ops::pack::{pack_snapshot, PackConfig};
627/// use std::path::PathBuf;
628///
629/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
630/// let config = PackConfig {
631/// disk: Some(PathBuf::from("incremental-backup.raw")),
632/// output: PathBuf::from("backup.hxz"),
633/// cdc_enabled: true,
634/// min_chunk: 16384, // 16 KiB
635/// avg_chunk: 65536, // 64 KiB
636/// max_chunk: 262144, // 256 KiB
637/// ..Default::default()
638/// };
639///
640/// pack_snapshot::<fn(u64, u64)>(config, None)?;
641/// # Ok(())
642/// # }
643/// ```
644///
645/// # Performance
646///
647/// See module-level documentation for detailed performance characteristics.
648///
649/// Typical throughput for a 64 GB VM image on modern hardware (Intel i7, NVMe SSD):
650///
651/// - **LZ4, no encryption**: ~2 GB/s (~30 seconds total)
652/// - **Zstd level 3, no encryption**: ~500 MB/s (~2 minutes total)
653/// - **Zstd + dictionary + CDC**: ~400 MB/s (~3 minutes including training)
654///
655/// # Atomicity
656///
657/// This operation is NOT atomic. On failure, the output file will be left in a
658/// partially written state. The file header is written last, so incomplete files
659/// will have an all-zero header and will be rejected by readers.
660///
661/// For atomic pack operations, write to a temporary file and perform an atomic
662/// rename after success:
663///
664/// ```no_run
665/// # use hexz_core::ops::pack::{pack_snapshot, PackConfig};
666/// # use std::path::PathBuf;
667/// # use std::fs;
668/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
669/// let mut config = PackConfig {
670/// disk: Some(PathBuf::from("disk.raw")),
671/// output: PathBuf::from("snapshot.st.tmp"),
672/// ..Default::default()
673/// };
674///
675/// pack_snapshot::<fn(u64, u64)>(config.clone(), None)?;
676/// fs::rename("snapshot.st.tmp", "snapshot.hxz")?;
677/// # Ok(())
678/// # }
679/// ```
680///
681/// # Thread Safety
682///
683/// This function is not thread-safe with respect to the output file. Do not call
684/// `pack_snapshot` concurrently with the same output path. Concurrent packing to
685/// different output files is safe.
686///
687/// The progress callback must be `Send + Sync` if you want to call this function
688/// from a non-main thread.
689pub fn pack_snapshot<F>(config: PackConfig, progress_callback: Option<F>) -> Result<()>
690where
691 F: Fn(u64, u64) + Send + Sync,
692{
693 // Validate inputs
694 if config.disk.is_none() && config.memory.is_none() {
695 return Err(Error::Io(std::io::Error::new(
696 std::io::ErrorKind::InvalidInput,
697 "At least one input (disk or memory) must be provided",
698 )));
699 }
700
701 // Train compression dictionary if requested
702 let dictionary = if config.compression == "zstd" && config.train_dict {
703 Some(train_dictionary(
704 config
705 .disk
706 .as_ref()
707 .or(config.memory.as_ref())
708 .ok_or_else(|| {
709 Error::Io(std::io::Error::new(
710 std::io::ErrorKind::InvalidInput,
711 "No input file available for dictionary training",
712 ))
713 })?,
714 config.block_size,
715 )?)
716 } else {
717 None
718 };
719
720 // Initialize compressor
721 let (compressor, compression_type) =
722 create_compressor_from_str(&config.compression, None, dictionary.clone())?;
723
724 // Initialize encryptor if requested
725 let (encryptor, enc_params): (Option<Box<dyn Encryptor>>, _) = if config.encrypt {
726 let password = config.password.clone().ok_or_else(|| {
727 Error::Io(std::io::Error::new(
728 std::io::ErrorKind::InvalidInput,
729 "Password required for encryption",
730 ))
731 })?;
732 let params = KeyDerivationParams::default();
733 let enc = AesGcmEncryptor::new(password.as_bytes(), ¶ms.salt, params.iterations)?;
734 (Some(Box::new(enc) as Box<dyn Encryptor>), Some(params))
735 } else {
736 (None, None)
737 };
738
739 // Build the snapshot writer with optional encryption
740 let mut builder = SnapshotWriter::builder(&config.output, compressor, compression_type)
741 .block_size(config.block_size)
742 .variable_blocks(config.cdc_enabled);
743
744 if let (Some(enc), Some(params)) = (encryptor, enc_params) {
745 builder = builder.encryption(enc, params);
746 }
747
748 let mut writer = builder.build()?;
749
750 // Write dictionary to file
751 if let Some(d) = &dictionary {
752 writer.write_dictionary(d)?;
753 }
754
755 // Process disk stream
756 if let Some(ref path) = config.disk {
757 process_stream(
758 path.clone(),
759 true,
760 &mut writer,
761 &config,
762 progress_callback.as_ref(),
763 )?;
764 }
765
766 // Process memory stream
767 if let Some(ref path) = config.memory {
768 process_stream(
769 path.clone(),
770 false,
771 &mut writer,
772 &config,
773 progress_callback.as_ref(),
774 )?;
775 }
776
777 writer.finalize(None, None)?;
778
779 Ok(())
780}
781
782/// Trains a Zstd compression dictionary from stratified samples.
783///
784/// Dictionary training analyzes a representative sample of input blocks to build
785/// a shared dictionary that improves compression ratios for structured data
786/// (file systems, databases, logs) by capturing common patterns.
787///
788/// # Algorithm
789///
790/// 1. **Stratified Sampling**: Sample blocks evenly across the file
791/// - Compute step size: `file_size / target_samples`
792/// - Read one block at each sample point
793/// - Ensures coverage of different regions (boot sector, metadata, data)
794///
795/// 2. **Quality Filtering**: Exclude unsuitable blocks
796/// - Skip all-zero blocks (no compressible patterns)
797/// - Compute Shannon entropy (0-8 bits per byte)
798/// - Reject blocks with entropy > `ENTROPY_THRESHOLD` (6.0)
799/// - Rationale: High-entropy data (encrypted, random) doesn't benefit from dictionaries
800///
801/// 3. **Dictionary Training**: Feed filtered samples to Zstd
802/// - Uses Zstd's COVER algorithm (fast_cover variant)
803/// - Analyzes n-grams to find common subsequences
804/// - Outputs dictionary up to `DICT_TRAINING_SIZE` (110 KiB)
805///
806/// # Parameters
807///
808/// - `input_path`: Path to the input file to sample from
809/// - `block_size`: Size of each sample block in bytes
810///
811/// # Returns
812///
813/// - `Ok(Vec<u8>)`: Trained dictionary bytes (empty if training fails or no suitable samples)
814/// - `Err(Error)`: I/O error reading input file
815///
816/// # Performance
817///
818/// - **Sampling time**: ~100-500 ms (depends on file size and disk speed)
819/// - **Training time**: ~2-5 seconds for 4000 samples
820/// - **Memory usage**: ~256 MB (sample corpus in RAM)
821///
822/// # Compression Improvement
823///
824/// - **Typical**: 10-30% better ratio vs. no dictionary
825/// - **Best case**: 50%+ improvement for highly structured data (databases)
826/// - **Worst case**: No improvement or slight regression (already compressed data)
827///
828/// # Edge Cases
829///
830/// - **Empty file**: Returns empty dictionary with warning
831/// - **All high-entropy data**: Returns empty dictionary with warning
832/// - **Small files**: May not reach target sample count (trains on available data)
833///
834/// # Examples
835///
836/// Called internally by `pack_snapshot` when `train_dict` is enabled:
837///
838/// ```text
839/// let dict = train_dictionary(Path::new("disk.raw"), 65536)?;
840/// // dict: Vec<u8> containing the trained zstd dictionary
841/// ```
842fn train_dictionary(input_path: &Path, block_size: u32) -> Result<Vec<u8>> {
843 let mut f = File::open(input_path)?;
844 let file_len = f.metadata()?.len();
845
846 let mut samples = Vec::new();
847 let mut buffer = vec![0u8; block_size as usize];
848 let target_samples = DICT_TRAINING_SIZE;
849
850 let step = if file_len > 0 {
851 (file_len / target_samples as u64).max(block_size as u64)
852 } else {
853 0
854 };
855
856 let mut attempts = 0;
857 while samples.len() < target_samples && attempts < target_samples * 2 {
858 let offset = attempts as u64 * step;
859 if offset >= file_len {
860 break;
861 }
862
863 f.seek(SeekFrom::Start(offset))?;
864 let n = f.read(&mut buffer)?;
865 if n == 0 {
866 break;
867 }
868 let chunk = &buffer[..n];
869 let is_zeros = chunk.iter().all(|&b| b == 0);
870
871 if !is_zeros {
872 let entropy = calculate_entropy(chunk);
873 if entropy < ENTROPY_THRESHOLD {
874 samples.push(chunk.to_vec());
875 }
876 }
877 attempts += 1;
878 }
879
880 if samples.is_empty() {
881 tracing::warn!("Input seems to be empty or high entropy. Dictionary will be empty.");
882 Ok(Vec::new())
883 } else {
884 let dict_bytes = ZstdCompressor::train(&samples, DICT_TRAINING_SIZE)?;
885 tracing::info!("Dictionary trained: {} bytes", dict_bytes.len());
886 Ok(dict_bytes)
887 }
888}
889
890/// Processes a single input stream (disk or memory) via the [`SnapshotWriter`].
891fn process_stream<F>(
892 path: PathBuf,
893 is_disk: bool,
894 writer: &mut SnapshotWriter,
895 config: &PackConfig,
896 progress_callback: Option<&F>,
897) -> Result<()>
898where
899 F: Fn(u64, u64),
900{
901 let f = File::open(&path)?;
902 let len = f.metadata()?.len();
903
904 writer.begin_stream(is_disk, len);
905
906 let mut logical_pos = 0u64;
907
908 if config.cdc_enabled {
909 let params = DedupeParams {
910 f: (config.avg_chunk as f64).log2() as u32,
911 m: config.min_chunk,
912 z: config.max_chunk,
913 w: 48,
914 v: 8,
915 };
916 let chunker = StreamChunker::new(f, params);
917 for chunk_res in chunker {
918 let chunk = chunk_res?;
919 logical_pos += chunk.len() as u64;
920 writer.write_data_block(&chunk)?;
921 if let Some(callback) = progress_callback {
922 callback(logical_pos, len);
923 }
924 }
925 } else {
926 // Fixed chunker: zero-copy path via next_chunk() buffer reuse
927 let mut chunker = FixedChunker::new(f, config.block_size as usize);
928 loop {
929 match chunker.next_chunk() {
930 Ok(Some(chunk)) => {
931 logical_pos += chunk.len() as u64;
932 writer.write_data_block(chunk)?;
933 if let Some(callback) = progress_callback {
934 callback(logical_pos, len);
935 }
936 }
937 Ok(None) => break,
938 Err(e) => return Err(Error::Io(e)),
939 }
940 }
941 }
942
943 writer.end_stream()?;
944 Ok(())
945}
946
947#[cfg(test)]
948mod tests {
949 use super::*;
950 use std::io::Cursor;
951
952 #[test]
953 fn test_calculate_entropy_empty() {
954 assert_eq!(calculate_entropy(&[]), 0.0);
955 }
956
957 #[test]
958 fn test_calculate_entropy_uniform() {
959 // All same byte - lowest entropy
960 let data = vec![0x42; 1000];
961 let entropy = calculate_entropy(&data);
962 assert!(
963 entropy < 0.01,
964 "Entropy should be near 0.0 for uniform data"
965 );
966 }
967
968 #[test]
969 fn test_calculate_entropy_binary() {
970 // Two values - low entropy
971 let mut data = vec![0u8; 500];
972 data.extend(vec![1u8; 500]);
973 let entropy = calculate_entropy(&data);
974 assert!(
975 entropy > 0.9 && entropy < 1.1,
976 "Entropy should be ~1.0 for binary data"
977 );
978 }
979
980 #[test]
981 fn test_calculate_entropy_random() {
982 // All 256 values - high entropy
983 let data: Vec<u8> = (0..=255).cycle().take(256 * 4).collect();
984 let entropy = calculate_entropy(&data);
985 assert!(
986 entropy > 7.5,
987 "Entropy should be high for all byte values: got {}",
988 entropy
989 );
990 }
991
992 #[test]
993 fn test_calculate_entropy_single_byte() {
994 assert_eq!(calculate_entropy(&[42]), 0.0);
995 }
996
997 #[test]
998 fn test_calculate_entropy_two_different_bytes() {
999 let data = vec![0, 255];
1000 let entropy = calculate_entropy(&data);
1001 assert!(entropy > 0.9 && entropy < 1.1, "Entropy should be ~1.0");
1002 }
1003
1004 #[test]
1005 fn test_fixed_chunker_exact_blocks() {
1006 let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
1007 let cursor = Cursor::new(data);
1008 let chunker = FixedChunker::new(cursor, 4);
1009
1010 let chunks: Vec<_> = chunker.map(|r| r.unwrap()).collect();
1011
1012 assert_eq!(chunks.len(), 2);
1013 assert_eq!(chunks[0], vec![1, 2, 3, 4]);
1014 assert_eq!(chunks[1], vec![5, 6, 7, 8]);
1015 }
1016
1017 #[test]
1018 fn test_fixed_chunker_partial_last_block() {
1019 let data = vec![1, 2, 3, 4, 5];
1020 let cursor = Cursor::new(data);
1021 let chunker = FixedChunker::new(cursor, 3);
1022
1023 let chunks: Vec<_> = chunker.map(|r| r.unwrap()).collect();
1024
1025 assert_eq!(chunks.len(), 2);
1026 assert_eq!(chunks[0], vec![1, 2, 3]);
1027 assert_eq!(chunks[1], vec![4, 5]);
1028 }
1029
1030 #[test]
1031 fn test_fixed_chunker_empty_input() {
1032 let data = vec![];
1033 let cursor = Cursor::new(data);
1034 let chunker = FixedChunker::new(cursor, 1024);
1035
1036 let chunks: Vec<_> = chunker.map(|r| r.unwrap()).collect();
1037
1038 assert_eq!(chunks.len(), 0);
1039 }
1040
1041 #[test]
1042 fn test_fixed_chunker_single_byte_blocks() {
1043 let data = vec![1, 2, 3];
1044 let cursor = Cursor::new(data);
1045 let chunker = FixedChunker::new(cursor, 1);
1046
1047 let chunks: Vec<_> = chunker.map(|r| r.unwrap()).collect();
1048
1049 assert_eq!(chunks.len(), 3);
1050 assert_eq!(chunks[0], vec![1]);
1051 assert_eq!(chunks[1], vec![2]);
1052 assert_eq!(chunks[2], vec![3]);
1053 }
1054
1055 #[test]
1056 fn test_fixed_chunker_large_block_size() {
1057 let data = vec![1, 2, 3, 4, 5];
1058 let cursor = Cursor::new(data.clone());
1059 let chunker = FixedChunker::new(cursor, 10000);
1060
1061 let chunks: Vec<_> = chunker.map(|r| r.unwrap()).collect();
1062
1063 assert_eq!(chunks.len(), 1);
1064 assert_eq!(chunks[0], data);
1065 }
1066
1067 #[test]
1068 fn test_pack_config_default() {
1069 let config = PackConfig::default();
1070
1071 assert_eq!(config.compression, "lz4");
1072 assert!(!config.encrypt);
1073 assert_eq!(config.password, None);
1074 assert!(!config.train_dict);
1075 assert_eq!(config.block_size, 65536);
1076 assert!(!config.cdc_enabled);
1077 assert_eq!(config.min_chunk, 16384);
1078 assert_eq!(config.avg_chunk, 65536);
1079 assert_eq!(config.max_chunk, 131072);
1080 }
1081
1082 #[test]
1083 fn test_pack_config_clone() {
1084 let config1 = PackConfig {
1085 disk: Some(PathBuf::from("/dev/sda")),
1086 output: PathBuf::from("output.hxz"),
1087 compression: "zstd".to_string(),
1088 encrypt: true,
1089 password: Some("secret".to_string()),
1090 ..Default::default()
1091 };
1092
1093 let config2 = config1.clone();
1094
1095 assert_eq!(config2.disk, config1.disk);
1096 assert_eq!(config2.output, config1.output);
1097 assert_eq!(config2.compression, config1.compression);
1098 assert_eq!(config2.encrypt, config1.encrypt);
1099 assert_eq!(config2.password, config1.password);
1100 }
1101
1102 #[test]
1103 fn test_pack_config_debug() {
1104 let config = PackConfig::default();
1105 let debug_str = format!("{:?}", config);
1106
1107 assert!(debug_str.contains("PackConfig"));
1108 assert!(debug_str.contains("lz4"));
1109 }
1110
1111 #[test]
1112 fn test_entropy_threshold_filtering() {
1113 // Test data with entropy below threshold (compressible)
1114 let low_entropy_data = vec![0u8; 1024];
1115 assert!(calculate_entropy(&low_entropy_data) < ENTROPY_THRESHOLD);
1116
1117 // Test data with entropy above threshold (random)
1118 let high_entropy_data: Vec<u8> = (0..1024).map(|i| ((i * 7) % 256) as u8).collect();
1119 let entropy = calculate_entropy(&high_entropy_data);
1120 // This might not always be above threshold depending on the pattern,
1121 // but we can still test that entropy calculation works
1122 assert!((0.0..=8.0).contains(&entropy));
1123 }
1124
1125 #[test]
1126 fn test_entropy_calculation_properties() {
1127 // Entropy should increase with more unique values
1128 let data1 = vec![0u8; 100];
1129 let data2 = [0u8, 1u8].repeat(50);
1130 let mut data3 = Vec::new();
1131 for i in 0..100 {
1132 data3.push((i % 10) as u8);
1133 }
1134
1135 let entropy1 = calculate_entropy(&data1);
1136 let entropy2 = calculate_entropy(&data2);
1137 let entropy3 = calculate_entropy(&data3);
1138
1139 assert!(
1140 entropy1 < entropy2,
1141 "More unique values should increase entropy"
1142 );
1143 assert!(
1144 entropy2 < entropy3,
1145 "Even more unique values should further increase entropy"
1146 );
1147 }
1148
1149 #[test]
1150 fn test_fixed_chunker_with_different_sizes() {
1151 let data = vec![0u8; 10000];
1152
1153 // Test with various chunk sizes
1154 for chunk_size in [64, 256, 1024, 4096, 65536] {
1155 let cursor = Cursor::new(data.clone());
1156 let chunker = FixedChunker::new(cursor, chunk_size);
1157
1158 let chunks: Vec<_> = chunker.map(|r| r.unwrap()).collect();
1159
1160 // Verify total data matches
1161 let total_len: usize = chunks.iter().map(|c| c.len()).sum();
1162 assert_eq!(
1163 total_len,
1164 data.len(),
1165 "Total chunked data should match original for chunk_size={}",
1166 chunk_size
1167 );
1168
1169 // Verify all except possibly last chunk have correct size
1170 for (i, chunk) in chunks.iter().enumerate() {
1171 if i < chunks.len() - 1 {
1172 assert_eq!(
1173 chunk.len(),
1174 chunk_size,
1175 "Non-final chunks should be exactly chunk_size"
1176 );
1177 } else {
1178 assert!(
1179 chunk.len() <= chunk_size,
1180 "Final chunk should be <= chunk_size"
1181 );
1182 }
1183 }
1184 }
1185 }
1186}