Skip to main content

storage_kit/
fragment.rs

1//! Recursive fragmentation — format v3, locked by design decision,
2//! addressing retired to `(partition_id, content_id)` per the 2026-09-23
3//! storage-addressing rulings.
4//!
5//! Content is split into **leaves** (raw chunk bytes) by a configurable
6//! chunking profile (FastCDC or fixed-size), then leaves are folded
7//! bottom-up into **list-nodes** at a fixed 1024-child fanout until a
8//! single root remains. Both leaves and list-nodes are stored as ordinary
9//! content-addressed blocks, keyed on hash alone — the engine has no
10//! concept of logical identity for a fragmentation-internal node or for
11//! anything else; the "internal nodes are anonymous" rule this module used
12//! to enforce is gone along with the `Context` type it was stated in terms
13//! of (there is no longer anything for an internal node to be anonymous
14//! *relative to*).
15//!
16//! A list-node's body is nothing but its children's refs, back to back:
17//! `hash (32B) | uncompressed_len (8B)` per child, in order. Reconstruction
18//! needs to know how many list-node levels sit above the leaves for a given
19//! root — the builder always produces a depth-uniform tree (every leaf at
20//! the same depth), so a single `depth` counter alongside `root_type`
21//! disambiguates every level unambiguously. This is one field beyond the
22//! spec's literal `root_type: leaf|list`, added because reconstruction is
23//! otherwise ambiguous; it's additive, not a deviation from the locked
24//! wire format for leaves/list-nodes themselves.
25
26use crate::addressing::{Hash, HASH_LEN};
27use crate::error::{Result, StorageError};
28use crate::store::ImmutableStore;
29use fastcdc::v2020::FastCDC;
30use serde::{Deserialize, Serialize};
31
32/// Fixed child fanout for list-nodes — a determinism lock, not a tunable.
33pub const FANOUT: usize = 1024;
34
35/// Size in bytes of one child ref within a list-node body.
36pub const CHILD_REF_LEN: usize = HASH_LEN + 8;
37
38/// How raw content is split into leaves. Recorded in the manifest so any
39/// implementation reconstructing the same bytes from the same profile
40/// reaches the same root hash.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(tag = "codec", rename_all = "snake_case")]
43pub enum ChunkingProfile {
44    /// Fixed-size chunking: every chunk is `block_size` bytes except
45    /// possibly the last.
46    Fixed { block_size: u64 },
47    /// FastCDC content-defined chunking.
48    FastCdc {
49        min_size: u32,
50        avg_size: u32,
51        max_size: u32,
52    },
53}
54
55impl Default for ChunkingProfile {
56    fn default() -> Self {
57        ChunkingProfile::FastCdc {
58            min_size: 4 * 1024,
59            avg_size: 16 * 1024,
60            max_size: 64 * 1024,
61        }
62    }
63}
64
65/// Whether a fragment tree's root is a raw leaf (content fit in one chunk)
66/// or a list-node (one or more fold levels above the leaves).
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum RootType {
70    Leaf,
71    List,
72}
73
74/// The result of fragmenting a byte slice into the store.
75#[derive(Debug, Clone, Copy)]
76pub struct FragmentTree {
77    pub root: Hash,
78    pub root_type: RootType,
79    /// Number of list-node levels above the leaves (0 for a bare leaf).
80    pub depth: u32,
81    pub uncompressed_len: u64,
82}
83
84fn chunk_offsets(data: &[u8], profile: &ChunkingProfile) -> Vec<(usize, usize)> {
85    if data.is_empty() {
86        return Vec::new();
87    }
88    match profile {
89        ChunkingProfile::Fixed { block_size } => {
90            let block_size = (*block_size).max(1) as usize;
91            data.chunks(block_size)
92                .scan(0usize, |pos, c| {
93                    let start = *pos;
94                    *pos += c.len();
95                    Some((start, c.len()))
96                })
97                .collect()
98        }
99        ChunkingProfile::FastCdc {
100            min_size,
101            avg_size,
102            max_size,
103        } => FastCDC::new(data, *min_size, *avg_size, *max_size)
104            .map(|c| (c.offset, c.length))
105            .collect(),
106    }
107}
108
109/// Split `data` into leaves per `profile`, store each leaf, then fold
110/// leaves into list-nodes at `FANOUT` until a single root remains.
111pub fn build_fragment_tree(
112    data: &[u8],
113    profile: &ChunkingProfile,
114    store: &mut dyn ImmutableStore,
115) -> Result<FragmentTree> {
116    let offsets = chunk_offsets(data, profile);
117
118    if offsets.is_empty() {
119        let hash = store.put(&[])?;
120        return Ok(FragmentTree {
121            root: hash,
122            root_type: RootType::Leaf,
123            depth: 0,
124            uncompressed_len: 0,
125        });
126    }
127
128    let mut level: Vec<(Hash, u64)> = Vec::with_capacity(offsets.len());
129    for (start, len) in &offsets {
130        let chunk = &data[*start..*start + *len];
131        let hash = store.put(chunk)?;
132        level.push((hash, *len as u64));
133    }
134
135    let mut depth = 0u32;
136    let mut root_type = RootType::Leaf;
137    while level.len() > 1 {
138        root_type = RootType::List;
139        depth += 1;
140        let mut next = Vec::with_capacity(level.len().div_ceil(FANOUT));
141        for group in level.chunks(FANOUT) {
142            let mut body = Vec::with_capacity(group.len() * CHILD_REF_LEN);
143            let mut total = 0u64;
144            for (hash, len) in group {
145                body.extend_from_slice(hash.as_bytes());
146                body.extend_from_slice(&len.to_le_bytes());
147                total += len;
148            }
149            let hash = store.put(&body)?;
150            next.push((hash, total));
151        }
152        level = next;
153    }
154
155    let (root_hash, total_len) = level[0];
156    Ok(FragmentTree {
157        root: root_hash,
158        root_type,
159        depth,
160        uncompressed_len: total_len,
161    })
162}
163
164/// Reconstruct the original bytes for a fragment tree rooted at `root` with
165/// the given `depth` (list-node levels above the leaves).
166pub fn read_fragment_tree(root: Hash, depth: u32, store: &dyn ImmutableStore) -> Result<Vec<u8>> {
167    let mut out = Vec::new();
168    read_recursive(root, depth, store, &mut out)?;
169    Ok(out)
170}
171
172fn read_recursive(
173    hash: Hash,
174    depth: u32,
175    store: &dyn ImmutableStore,
176    out: &mut Vec<u8>,
177) -> Result<()> {
178    let bytes = store.get(&hash)?;
179    if depth == 0 {
180        out.extend_from_slice(&bytes);
181        return Ok(());
182    }
183    if bytes.len() % CHILD_REF_LEN != 0 {
184        return Err(StorageError::CorruptManifest(format!(
185            "list-node {hash} body length {} is not a multiple of {CHILD_REF_LEN}",
186            bytes.len()
187        )));
188    }
189    for record in bytes.chunks(CHILD_REF_LEN) {
190        let child_hash = Hash::from_bytes(record[..HASH_LEN].try_into().unwrap());
191        read_recursive(child_hash, depth - 1, store, out)?;
192    }
193    Ok(())
194}
195
196/// Walk a fragment tree without materializing content, collecting every
197/// hash reached (leaves and list-nodes). Used by GC's mark phase.
198pub fn walk_hashes(
199    hash: Hash,
200    depth: u32,
201    store: &dyn ImmutableStore,
202    live: &mut Vec<Hash>,
203) -> Result<()> {
204    live.push(hash);
205    if depth == 0 {
206        return Ok(());
207    }
208    let bytes = store.get(&hash)?;
209    if bytes.len() % CHILD_REF_LEN != 0 {
210        return Err(StorageError::CorruptManifest(format!(
211            "list-node {hash} body length {} is not a multiple of {CHILD_REF_LEN}",
212            bytes.len()
213        )));
214    }
215    for record in bytes.chunks(CHILD_REF_LEN) {
216        let child_hash = Hash::from_bytes(record[..HASH_LEN].try_into().unwrap());
217        walk_hashes(child_hash, depth - 1, store, live)?;
218    }
219    Ok(())
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use crate::addressing::PartitionId;
226    use crate::partition::{EncryptionMode, PartitionSpec, RetentionClass, Subject, SubjectKind};
227    use crate::store::PartitionStore;
228    use tempfile::tempdir;
229
230    fn store_for(name: &str) -> (tempfile::TempDir, PartitionStore) {
231        let dir = tempdir().unwrap();
232        let partition_id = PartitionId::for_person(name);
233        let spec = PartitionSpec {
234            subject: Subject {
235                kind: SubjectKind::Person,
236                id: name.to_string(),
237            },
238            retention_class: RetentionClass::Standard,
239            encryption_mode: EncryptionMode::Plaintext,
240            label: None,
241        };
242        let store = PartitionStore::create(dir.path(), partition_id, spec).unwrap();
243        (dir, store)
244    }
245
246    #[test]
247    fn empty_input_is_a_leaf() {
248        let (_dir, mut store) = store_for("fragment-empty");
249        let tree = build_fragment_tree(&[], &ChunkingProfile::default(), &mut store).unwrap();
250        assert_eq!(tree.root_type, RootType::Leaf);
251        assert_eq!(tree.depth, 0);
252        assert_eq!(tree.uncompressed_len, 0);
253    }
254
255    #[test]
256    fn small_input_is_a_single_leaf() {
257        let (_dir, mut store) = store_for("fragment-small");
258        let data = b"small enough to fit in one chunk";
259        let profile = ChunkingProfile::Fixed { block_size: 4096 };
260        let tree = build_fragment_tree(data, &profile, &mut store).unwrap();
261        assert_eq!(tree.root_type, RootType::Leaf);
262        assert_eq!(tree.depth, 0);
263        assert_eq!(tree.uncompressed_len, data.len() as u64);
264
265        let back = read_fragment_tree(tree.root, tree.depth, &store).unwrap();
266        assert_eq!(back, data);
267    }
268
269    #[test]
270    fn multi_chunk_input_roundtrips_through_a_list_node() {
271        let (_dir, mut store) = store_for("fragment-multi");
272        let data: Vec<u8> = (0..50_000u32).flat_map(|n| n.to_le_bytes()).collect();
273        let profile = ChunkingProfile::Fixed { block_size: 4096 };
274        let tree = build_fragment_tree(&data, &profile, &mut store).unwrap();
275        assert_eq!(tree.root_type, RootType::List);
276        assert_eq!(tree.uncompressed_len, data.len() as u64);
277
278        let back = read_fragment_tree(tree.root, tree.depth, &store).unwrap();
279        assert_eq!(back, data);
280    }
281
282    #[test]
283    fn deep_fanout_forces_multiple_list_levels() {
284        // FANOUT is 1024; force > 1024 leaves so a second fold level is
285        // required, proving `depth` tracks real tree height correctly.
286        let (_dir, mut store) = store_for("fragment-deep");
287        let block_size = 16u64;
288        let data = vec![7u8; (block_size as usize) * (FANOUT + 5)];
289        let profile = ChunkingProfile::Fixed { block_size };
290        let tree = build_fragment_tree(&data, &profile, &mut store).unwrap();
291        assert_eq!(tree.depth, 2, "expected two fold levels above the leaves");
292
293        let back = read_fragment_tree(tree.root, tree.depth, &store).unwrap();
294        assert_eq!(back, data);
295    }
296
297    #[test]
298    fn identical_bytes_same_profile_yield_identical_root_hash() {
299        let data = b"determinism is the whole point of content addressing".repeat(200);
300        let profile = ChunkingProfile::default();
301
302        let (_dir_a, mut store_a) = store_for("determinism-a");
303        let tree_a = build_fragment_tree(&data, &profile, &mut store_a).unwrap();
304
305        let (_dir_b, mut store_b) = store_for("determinism-b");
306        let tree_b = build_fragment_tree(&data, &profile, &mut store_b).unwrap();
307
308        assert_eq!(tree_a.root, tree_b.root);
309        assert_eq!(tree_a.depth, tree_b.depth);
310        assert_eq!(tree_a.root_type, tree_b.root_type);
311    }
312}