Skip to main content

limnifs_write/
compaction.rs

1//! Slab compaction — removes unreferenced drops from a slab without
2//! re-reading file contents. Preserves codecs, drop identities, and
3//! metadata; only the slab and manifest's slab index / history change.
4//!
5//! ## Algorithm
6//!
7//! 1. Parse the source manifest's prefix (header, flags, metadata
8//!    reference — these are copied verbatim).
9//! 2. Walk the metadata blob to find all referenced `DropId`s.
10//! 3. Load the source slab, extract referenced drops with their
11//!    compressed bytes and codec (no decompression needed).
12//! 4. Build a new slab containing only the referenced drops.
13//! 5. Re-encode the slab index + history.
14//! 6. Recompute the Merkle root.
15
16use std::collections::HashSet;
17
18use limnifs_core::{
19    compute_merkle_root, hash_empty_section, hash_section, parse_feature_flags_section,
20    parse_manifest_header, parse_metadata_blob, parse_metadata_reference, parse_slab_index,
21    ContentHandle, CoreError, ManifestCursor, SectionHashes, HISTORY_SECTION_VERSION,
22    SLAB_INDEX_SECTION_VERSION,
23};
24use limnifs_format::{ManifestRoot, SlabId};
25
26/// Result of compacting an image.
27#[derive(Clone, Debug)]
28pub struct CompactionResult {
29    pub manifest_bytes: Vec<u8>,
30    pub merkle_root: ManifestRoot,
31    pub slab_bytes: Option<Vec<u8>>,
32    pub original_drop_count: usize,
33    pub compacted_drop_count: usize,
34    pub reclaimed_drops: usize,
35}
36
37/// Error during compaction.
38#[derive(Debug)]
39pub enum CompactionError {
40    Core(CoreError),
41    Io(std::io::Error),
42}
43
44impl std::fmt::Display for CompactionError {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            Self::Core(e) => write!(f, "{e}"),
48            Self::Io(e) => write!(f, "I/O: {e}"),
49        }
50    }
51}
52
53impl std::error::Error for CompactionError {}
54
55impl From<CoreError> for CompactionError {
56    fn from(e: CoreError) -> Self {
57        Self::Core(e)
58    }
59}
60
61impl From<std::io::Error> for CompactionError {
62    fn from(e: std::io::Error) -> Self {
63        Self::Io(e)
64    }
65}
66
67/// One drop extracted from the source slab, ready for re-packing.
68struct ExtractedDrop {
69    id: [u8; 32],
70    compressed: Vec<u8>,
71    codec: u8,
72    plaintext_len: u32,
73    /// Record flags carried through from the source slab (bit0 =
74    /// SEEKABLE container).
75    flags: u8,
76}
77
78/// Compact an image by removing unreferenced drops from its slab.
79/// The manifest's metadata, header, and flags are preserved; only the
80/// slab and the slab index / history sections are updated.
81///
82/// # Errors
83///
84/// Returns [`CompactionError`] if the image or slab cannot be parsed.
85pub fn compact_image(
86    manifest_bytes: &[u8],
87    slab_bytes: &[u8],
88) -> Result<CompactionResult, CompactionError> {
89    // 1. Parse the manifest prefix to find referenced drops.
90    let mut cursor = ManifestCursor::new(manifest_bytes);
91    let _header = parse_manifest_header(&mut cursor)?;
92
93    // Capture the raw prefix bytes (header + flags + metadata ref)
94    // for verbatim re-encoding.
95    let prefix_end = {
96        let flags_start = cursor.position();
97        let _ = parse_feature_flags_section(&mut cursor)?;
98        let flags_end = cursor.position();
99        let meta_ref_start = cursor.position();
100        let meta_ref = parse_metadata_reference(&mut cursor)?;
101        let _meta_ref_end = cursor.position();
102        let _ = (flags_start, flags_end, meta_ref_start);
103
104        // Walk inodes to find referenced drops.
105        let referenced = find_referenced_drops(&meta_ref)?;
106
107        // Parse slab index to capture its section bytes.
108        let slab_index_start = cursor.position();
109        let slab_index = parse_slab_index(&mut cursor)?;
110        let slab_index_end = cursor.position();
111        let _ = (slab_index_start, slab_index_end, &slab_index);
112
113        referenced
114    };
115
116    // 2. Parse and compact the slab using parse_slab (correctly
117    //    handles the record-then-window layout).
118    let view = limnifs_core::parse_slab(slab_bytes)?;
119    let original_count = view.drop_records().len();
120    let win_start = view.solid_window_offset();
121    let mut kept_drops: Vec<ExtractedDrop> = Vec::new();
122
123    for record in view.drop_records() {
124        if prefix_end.contains(record.drop_id.as_bytes()) {
125            let offset = usize::try_from(record.offset_in_window).unwrap_or(0);
126            let len = usize::try_from(record.len_in_window).unwrap_or(0);
127            let start = win_start + offset;
128            let end = start + len;
129            if end > slab_bytes.len() {
130                continue;
131            }
132            kept_drops.push(ExtractedDrop {
133                id: *record.drop_id.as_bytes(),
134                compressed: slab_bytes[start..end].to_vec(),
135                codec: record.representation.codec,
136                plaintext_len: record.plaintext_len,
137                flags: record.flags,
138            });
139        }
140    }
141
142    let compacted_count = kept_drops.len();
143    let reclaimed = original_count.saturating_sub(compacted_count);
144
145    // 3. Build the compacted slab.
146    let (new_slab_bytes, new_slab_id) = encode_compacted_slab(&kept_drops);
147
148    // 4. Re-assemble the manifest.
149    let new_manifest = reassemble_manifest(manifest_bytes, &new_slab_bytes, &new_slab_id)?;
150
151    Ok(CompactionResult {
152        manifest_bytes: new_manifest.bytes,
153        merkle_root: new_manifest.merkle_root,
154        slab_bytes: Some(new_slab_bytes),
155        original_drop_count: original_count,
156        compacted_drop_count: compacted_count,
157        reclaimed_drops: reclaimed,
158    })
159}
160
161/// Walk the metadata blob to find all referenced `DropIds`.
162fn find_referenced_drops(
163    meta_ref: &limnifs_core::MetadataReference,
164) -> Result<HashSet<[u8; 32]>, CompactionError> {
165    let mut referenced = HashSet::new();
166    if let Some(blob_bytes) = &meta_ref.inline_metadata {
167        let mut blob_cursor = ManifestCursor::new(blob_bytes);
168        let blob = parse_metadata_blob(&mut blob_cursor)?;
169        for inode in &blob.inodes {
170            if let ContentHandle::SliceMap(slices) = &inode.content_handle {
171                for slice in slices {
172                    referenced.insert(*slice.drop_id.as_bytes());
173                }
174            }
175        }
176    }
177    Ok(referenced)
178}
179
180/// Encode a compacted slab from extracted drops.
181fn encode_compacted_slab(drops: &[ExtractedDrop]) -> (Vec<u8>, SlabId) {
182    let mut drop_records = Vec::new();
183    let mut solid_window = Vec::new();
184
185    for drop in drops {
186        let win_len = u32::try_from(drop.compressed.len()).unwrap_or(0);
187        let offset = u32::try_from(solid_window.len()).unwrap_or(0);
188        drop_records.extend_from_slice(&drop.id);
189        drop_records.extend_from_slice(&drop.plaintext_len.to_le_bytes());
190        drop_records.extend_from_slice(&[drop.codec, 0x00, 0x00]); // (codec, aead=0, ec=0)
191        drop_records.push(0x00); // solid_window_index
192        drop_records.extend_from_slice(&offset.to_le_bytes());
193        drop_records.extend_from_slice(&win_len.to_le_bytes());
194        drop_records.push(limnifs_core::drop_record::NO_DICT); // dict_id: no dictionary
195        drop_records.push(drop.flags); // flags: bit0 = SEEKABLE container
196        solid_window.extend_from_slice(&drop.compressed);
197    }
198
199    let slab_content = [&drop_records[..], &solid_window[..]].concat();
200    let slab_hash = hash_section(&slab_content);
201    let slab_id = SlabId::new(0, slab_hash);
202
203    let total_length = 56 + slab_content.len();
204    let mut slab_bytes = Vec::with_capacity(total_length);
205    slab_bytes.extend_from_slice(b"LIM1");
206    slab_bytes.extend_from_slice(&1u16.to_le_bytes()); // the slab format version
207    slab_bytes.extend_from_slice(&slab_id.to_bytes());
208    slab_bytes.extend_from_slice(&(total_length as u64).to_le_bytes());
209    slab_bytes.push(0x00); // ec_descriptor
210    slab_bytes.push(0x00); // crypto_hint
211    slab_bytes.extend_from_slice(&slab_content);
212
213    (slab_bytes, slab_id)
214}
215
216struct ReassembledManifest {
217    bytes: Vec<u8>,
218    merkle_root: ManifestRoot,
219}
220
221/// Re-assemble the manifest with updated slab index.
222fn reassemble_manifest(
223    source: &[u8],
224    _slab_bytes: &[u8],
225    slab_id: &SlabId,
226) -> Result<ReassembledManifest, CompactionError> {
227    let mut cursor = ManifestCursor::new(source);
228
229    // Re-parse and capture each section's raw bytes.
230    let header_start = cursor.position();
231    let _ = parse_manifest_header(&mut cursor)?;
232    let header_end = cursor.position();
233
234    let flags_start = cursor.position();
235    let _ = parse_feature_flags_section(&mut cursor)?;
236    let flags_end = cursor.position();
237
238    let meta_ref_start = cursor.position();
239    let meta_ref = parse_metadata_reference(&mut cursor)?;
240    let meta_ref_end = cursor.position();
241
242    // Skip old slab index and history.
243    let _ = parse_slab_index(&mut cursor)?;
244    let _ = limnifs_core::parse_history(&mut cursor)?;
245
246    // Build new manifest.
247    let mut manifest = Vec::new();
248
249    // Copy header + flags + metadata reference verbatim.
250    manifest.extend_from_slice(&source[header_start..meta_ref_end]);
251
252    // New slab index.
253    let slab_index_start_new = manifest.len();
254    manifest.push(SLAB_INDEX_SECTION_VERSION);
255    manifest.extend_from_slice(&1u32.to_le_bytes());
256    manifest.extend_from_slice(&slab_id.to_bytes());
257    manifest.extend_from_slice(&1u32.to_le_bytes());
258    let locator = "file:slab-0.bin";
259    manifest.extend_from_slice(&u32::try_from(locator.len()).unwrap_or(0).to_le_bytes());
260    manifest.extend_from_slice(locator.as_bytes());
261    let slab_index_end_new = manifest.len();
262
263    // History.
264    let history_start_new = manifest.len();
265    manifest.push(HISTORY_SECTION_VERSION);
266    manifest.extend_from_slice(&1u32.to_le_bytes());
267    manifest.push(0x04); // turnover
268    manifest.extend_from_slice(&0u64.to_le_bytes());
269    manifest.extend_from_slice(&0u32.to_le_bytes());
270    manifest.extend_from_slice(&0u32.to_le_bytes());
271    let history_end_new = manifest.len();
272
273    let hashes = SectionHashes {
274        metadata: meta_ref.metadata_hash,
275        format_header: hash_section(&source[header_start..header_end]),
276        feature_flags: hash_section(&source[flags_start..flags_end]),
277        metadata_reference: hash_section(&source[meta_ref_start..meta_ref_end]),
278        slab_index: hash_section(&manifest[slab_index_start_new..slab_index_end_new]),
279        crypto_params: hash_empty_section(),
280        ec_params: hash_empty_section(),
281        dms_policy: hash_empty_section(),
282        delta_linkage: hash_empty_section(),
283        history: hash_section(&manifest[history_start_new..history_end_new]),
284    };
285    let merkle_root = compute_merkle_root(&hashes);
286
287    Ok(ReassembledManifest {
288        bytes: manifest,
289        merkle_root,
290    })
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn compact_preserves_referenced_drops() {
299        let temp =
300            std::env::temp_dir().join(format!("limnifs-compaction-test-{}", std::process::id()));
301        std::fs::create_dir_all(&temp).expect("create temp");
302        // Use large enough data to trigger slab-backed storage.
303        let data = vec![0xABu8; crate::INLINE_THRESHOLD + 100];
304        std::fs::write(temp.join("big.bin"), &data).expect("write big");
305
306        let artifact = crate::write_directory(&temp).expect("write");
307        std::fs::remove_dir_all(&temp).ok();
308
309        let slab_bytes = artifact.slab_bytes().map(Vec::from).unwrap_or_default();
310        if slab_bytes.is_empty() {
311            return;
312        }
313
314        let result = compact_image(&artifact.bytes, &slab_bytes).expect("compact");
315        assert_eq!(result.original_drop_count, result.compacted_drop_count);
316        assert_eq!(result.reclaimed_drops, 0);
317
318        // Verify the compacted slab parses correctly.
319        let new_slab = result.slab_bytes.as_ref().expect("slab exists");
320        let view = limnifs_core::parse_slab(new_slab).expect("compacted slab parses");
321        assert_eq!(view.drop_records().len(), result.compacted_drop_count);
322    }
323
324    #[test]
325    fn compact_preserves_drop_plaintext() {
326        let temp =
327            std::env::temp_dir().join(format!("limnifs-compaction-pt-{}", std::process::id()));
328        std::fs::create_dir_all(&temp).expect("create temp");
329        let data = vec![0xCDu8; crate::INLINE_THRESHOLD + 200];
330        std::fs::write(temp.join("data.bin"), &data).expect("write");
331
332        let artifact = crate::write_directory(&temp).expect("write");
333        std::fs::remove_dir_all(&temp).ok();
334
335        let slab_bytes = artifact.slab_bytes().map(Vec::from).unwrap_or_default();
336        if slab_bytes.is_empty() {
337            return;
338        }
339
340        let result = compact_image(&artifact.bytes, &slab_bytes).expect("compact");
341        let new_slab = result.slab_bytes.as_ref().expect("slab");
342
343        // Parse old slab and get plaintext.
344        let old_view = limnifs_core::parse_slab(&slab_bytes).expect("old slab parses");
345        let new_view = limnifs_core::parse_slab(new_slab).expect("new slab parses");
346
347        for old_record in old_view.drop_records() {
348            let old_pt = old_view
349                .plaintext_for(old_record.drop_id.as_bytes())
350                .expect("old drop exists")
351                .expect("decompress ok");
352            let new_pt = new_view
353                .plaintext_for(old_record.drop_id.as_bytes())
354                .expect("new drop exists")
355                .expect("decompress ok");
356            assert_eq!(old_pt, new_pt, "plaintext must match after compaction");
357        }
358    }
359
360    #[test]
361    fn compact_manifest_parses_correctly() {
362        let temp =
363            std::env::temp_dir().join(format!("limnifs-compaction-mp-{}", std::process::id()));
364        std::fs::create_dir_all(&temp).expect("create temp");
365        let data = vec![0xEFu8; crate::INLINE_THRESHOLD + 50];
366        std::fs::write(temp.join("file.bin"), &data).expect("write");
367
368        let artifact = crate::write_directory(&temp).expect("write");
369        std::fs::remove_dir_all(&temp).ok();
370
371        let slab_bytes = artifact.slab_bytes().map(Vec::from).unwrap_or_default();
372        if slab_bytes.is_empty() {
373            return;
374        }
375
376        let result = compact_image(&artifact.bytes, &slab_bytes).expect("compact");
377
378        // Verify the compacted manifest parses end-to-end.
379        let mut cursor = limnifs_core::ManifestCursor::new(&result.manifest_bytes);
380        limnifs_core::parse_manifest_header(&mut cursor).expect("header parses");
381        limnifs_core::parse_feature_flags_section(&mut cursor).expect("flags parse");
382        let meta_ref =
383            limnifs_core::parse_metadata_reference(&mut cursor).expect("metadata ref parses");
384        assert!(meta_ref.is_inlined());
385        limnifs_core::parse_slab_index(&mut cursor).expect("slab index parses");
386        limnifs_core::parse_history(&mut cursor).expect("history parses");
387    }
388}