synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / chunk.rs
| 1 | //! Content-defined chunking (ADR 0003 step G2, section 5.9, experiment X6). |
| 2 | //! |
| 3 | //! A blob above [`ChunkParams::threshold_bytes`] is cut into content-defined chunks by a |
| 4 | //! FastCDC-style gear chunker with normalized chunking [S20], and each chunk is stored once |
| 5 | //! per [`ChunkDigest`] inside the segments. A chunk is a storage and transfer unit only: a |
| 6 | //! blob's identity stays its `BlobDigest` over the whole content, so the parameters can |
| 7 | //! change without changing any identity (a store opened with other parameters only |
| 8 | //! deduplicates less against what is already stored). |
| 9 | //! |
| 10 | //! The chunker, the candidates, and the rule that chose the default parameters are fixed in |
| 11 | //! `evidence/g2-content-defined-chunking/x6/RULE.md` (committed before the X6 runs). |
| 12 | |
| 13 | use serde::{Deserialize, Serialize}; |
| 14 | use sha2::{Digest, Sha256}; |
| 15 | use std::fmt; |
| 16 | use synapse_core::BlobDigest; |
| 17 | |
| 18 | /// Domain tag of [`ChunkDigest`]. |
| 19 | pub const DOMAIN_CHUNK_V1: &[u8] = b"SYNAPSE_CHUNK_V1\0"; |
| 20 | |
| 21 | /// Seed of the SplitMix64 sequence that fills [`GEAR`] (ASCII `SYNAPSE1`). |
| 22 | pub const GEAR_SEED: u64 = 0x5359_4E41_5053_4531; |
| 23 | |
| 24 | /// Digest of one content-defined chunk of a large blob (CONTEXT.md `ChunkDigest`): |
| 25 | /// `SHA-256("SYNAPSE_CHUNK_V1\0" || u64 LE length || bytes)`. |
| 26 | #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 27 | pub struct ChunkDigest(pub [u8; 32]); |
| 28 | |
| 29 | impl ChunkDigest { |
| 30 | pub fn compute(bytes: &[u8]) -> Self { |
| 31 | let mut h = Sha256::new(); |
| 32 | h.update(DOMAIN_CHUNK_V1); |
| 33 | h.update((bytes.len() as u64).to_le_bytes()); |
| 34 | h.update(bytes); |
| 35 | Self(h.finalize().into()) |
| 36 | } |
| 37 | |
| 38 | pub fn to_hex(self) -> String { |
| 39 | hex::encode(self.0) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | impl fmt::Debug for ChunkDigest { |
| 44 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 45 | write!(f, "ChunkDigest({})", self.to_hex()) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl fmt::Display for ChunkDigest { |
| 50 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 51 | f.write_str(&self.to_hex()) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | const fn splitmix64_table(seed: u64) -> [u64; 256] { |
| 56 | let mut t = [0u64; 256]; |
| 57 | let mut state = seed; |
| 58 | let mut i = 0; |
| 59 | while i < 256 { |
| 60 | state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 61 | let mut z = state; |
| 62 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 63 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 64 | t[i] = z ^ (z >> 31); |
| 65 | i += 1; |
| 66 | } |
| 67 | t |
| 68 | } |
| 69 | |
| 70 | /// Gear table: the first 256 outputs of SplitMix64 seeded with [`GEAR_SEED`]. |
| 71 | pub const GEAR: [u64; 256] = splitmix64_table(GEAR_SEED); |
| 72 | |
| 73 | /// Chunking parameters of a store. `min`, `avg`, `max` are chunk sizes in bytes. |
| 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 75 | pub struct ChunkParams { |
| 76 | /// A blob of at most this many bytes is stored whole; a longer one is chunked. |
| 77 | /// `u64::MAX` turns chunking off. |
| 78 | pub threshold_bytes: u64, |
| 79 | pub min_bytes: u32, |
| 80 | /// Target average chunk size; a power of two. |
| 81 | pub avg_bytes: u32, |
| 82 | pub max_bytes: u32, |
| 83 | } |
| 84 | |
| 85 | impl Default for ChunkParams { |
| 86 | /// The X6 outcome (see `evidence/g2-content-defined-chunking/x6/OUTCOME.md`). |
| 87 | fn default() -> Self { |
| 88 | Self::X6_DEFAULT |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | impl ChunkParams { |
| 93 | /// Chunking off: every blob is stored whole (the A2 behaviour, X6 control C0). |
| 94 | pub const OFF: Self = Self { |
| 95 | threshold_bytes: u64::MAX, |
| 96 | min_bytes: 4 * 1024, |
| 97 | avg_bytes: 16 * 1024, |
| 98 | max_bytes: 64 * 1024, |
| 99 | }; |
| 100 | |
| 101 | /// Parameters chosen by experiment X6 under its pre-registered rule: candidate K1 |
| 102 | /// (T = 16 KiB, min 1 KiB, avg 4 KiB, max 16 KiB), the only eligible candidate |
| 103 | /// (`evidence/g2-content-defined-chunking/x6/RESULTS.md`). |
| 104 | pub const X6_DEFAULT: Self = Self::candidate(16 * 1024, 4 * 1024); |
| 105 | |
| 106 | /// Candidate with `min = avg / 4` and `max = 4 * avg` (the X6 shape). |
| 107 | pub const fn candidate(threshold_bytes: u64, avg_bytes: u32) -> Self { |
| 108 | Self { |
| 109 | threshold_bytes, |
| 110 | min_bytes: avg_bytes / 4, |
| 111 | avg_bytes, |
| 112 | max_bytes: avg_bytes * 4, |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// True when a blob of `len` bytes is chunked. |
| 117 | pub fn is_chunked(&self, len: usize) -> bool { |
| 118 | len as u64 > self.threshold_bytes |
| 119 | } |
| 120 | |
| 121 | /// Parameters the chunker accepts: `64 <= min < avg < max`, `avg` a power of two |
| 122 | /// with at least 2^4, and `max` at most 16 MiB. |
| 123 | pub fn validate(&self) -> Result<(), String> { |
| 124 | let ok = self.min_bytes >= 64 |
| 125 | && self.min_bytes < self.avg_bytes |
| 126 | && self.avg_bytes < self.max_bytes |
| 127 | && self.avg_bytes.is_power_of_two() |
| 128 | && self.avg_bytes >= 16 |
| 129 | && self.max_bytes <= 16 * 1024 * 1024; |
| 130 | if ok { |
| 131 | Ok(()) |
| 132 | } else { |
| 133 | Err(format!("invalid chunk parameters {self:?}")) |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /// Length of the first chunk of `src` (the cut rule of the X6 rule, section 1). |
| 139 | pub fn cut(src: &[u8], p: &ChunkParams) -> usize { |
| 140 | let min = p.min_bytes as usize; |
| 141 | if src.len() <= min { |
| 142 | return src.len(); |
| 143 | } |
| 144 | let n = src.len().min(p.max_bytes as usize); |
| 145 | let normal = n.min(p.avg_bytes as usize); |
| 146 | let bits = p.avg_bytes.trailing_zeros(); |
| 147 | let mask_s = !0u64 << (64 - (bits + 2)); |
| 148 | let mask_l = !0u64 << (64 - (bits - 2)); |
| 149 | let mut h = 0u64; |
| 150 | let mut i = min; |
| 151 | while i < normal { |
| 152 | h = (h << 1).wrapping_add(GEAR[src[i] as usize]); |
| 153 | if h & mask_s == 0 { |
| 154 | return i + 1; |
| 155 | } |
| 156 | i += 1; |
| 157 | } |
| 158 | while i < n { |
| 159 | h = (h << 1).wrapping_add(GEAR[src[i] as usize]); |
| 160 | if h & mask_l == 0 { |
| 161 | return i + 1; |
| 162 | } |
| 163 | i += 1; |
| 164 | } |
| 165 | n |
| 166 | } |
| 167 | |
| 168 | /// Byte ranges of the chunks of `data`, in order; they cover `data` exactly. |
| 169 | pub fn chunk_ranges(data: &[u8], p: &ChunkParams) -> Vec<std::ops::Range<usize>> { |
| 170 | let mut out = Vec::with_capacity(data.len() / p.avg_bytes.max(1) as usize + 1); |
| 171 | let mut at = 0; |
| 172 | while at < data.len() { |
| 173 | let len = cut(&data[at..], p); |
| 174 | out.push(at..at + len); |
| 175 | at += len; |
| 176 | } |
| 177 | out |
| 178 | } |
| 179 | |
| 180 | /// One chunked blob: its identity, length, and its chunks in order (digest, length). |
| 181 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 182 | pub struct ChunkManifest { |
| 183 | pub blob: BlobDigest, |
| 184 | pub len: u64, |
| 185 | pub chunks: Vec<(ChunkDigest, u32)>, |
| 186 | } |
| 187 | |
| 188 | /// A blob cut into chunks before it is encoded: its manifest plus the distinct chunks in |
| 189 | /// first-occurrence order with their byte ranges inside the blob. |
| 190 | #[derive(Debug, Clone)] |
| 191 | pub(crate) struct ChunkedBlob { |
| 192 | pub manifest: ChunkManifest, |
| 193 | pub distinct: Vec<(ChunkDigest, std::ops::Range<usize>)>, |
| 194 | } |
| 195 | |
| 196 | /// Cut `data` (whose digest is `blob`) and digest every chunk. |
| 197 | pub(crate) fn chunk_blob(blob: BlobDigest, data: &[u8], p: &ChunkParams) -> ChunkedBlob { |
| 198 | let ranges = chunk_ranges(data, p); |
| 199 | let mut chunks = Vec::with_capacity(ranges.len()); |
| 200 | let mut distinct: Vec<(ChunkDigest, std::ops::Range<usize>)> = Vec::new(); |
| 201 | let mut seen = std::collections::BTreeSet::new(); |
| 202 | for r in ranges { |
| 203 | let d = ChunkDigest::compute(&data[r.clone()]); |
| 204 | chunks.push((d, r.len() as u32)); |
| 205 | if seen.insert(d) { |
| 206 | distinct.push((d, r)); |
| 207 | } |
| 208 | } |
| 209 | ChunkedBlob { |
| 210 | manifest: ChunkManifest { |
| 211 | blob, |
| 212 | len: data.len() as u64, |
| 213 | chunks, |
| 214 | }, |
| 215 | distinct, |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | #[cfg(test)] |
| 220 | mod tests { |
| 221 | use super::*; |
| 222 | |
| 223 | #[test] |
| 224 | fn gear_table_is_splitmix64_of_the_seed() { |
| 225 | // First SplitMix64 outputs for the seed, computed step by step. |
| 226 | let mut state = GEAR_SEED; |
| 227 | let mut next = || { |
| 228 | state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 229 | let mut z = state; |
| 230 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 231 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 232 | z ^ (z >> 31) |
| 233 | }; |
| 234 | for (i, g) in GEAR.iter().enumerate() { |
| 235 | assert_eq!(*g, next(), "gear entry {i}"); |
| 236 | } |
| 237 | let distinct: std::collections::BTreeSet<_> = GEAR.iter().collect(); |
| 238 | assert_eq!(distinct.len(), 256); |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn chunk_ranges_cover_the_data_and_respect_min_and_max() { |
| 243 | let p = ChunkParams::candidate(16 * 1024, 4 * 1024); |
| 244 | p.validate().unwrap(); |
| 245 | let mut x = 0x1234_5678u32; |
| 246 | let data: Vec<u8> = (0..300_000) |
| 247 | .map(|_| { |
| 248 | x ^= x << 13; |
| 249 | x ^= x >> 17; |
| 250 | x ^= x << 5; |
| 251 | x as u8 |
| 252 | }) |
| 253 | .collect(); |
| 254 | let ranges = chunk_ranges(&data, &p); |
| 255 | let mut at = 0; |
| 256 | for (i, r) in ranges.iter().enumerate() { |
| 257 | assert_eq!(r.start, at); |
| 258 | assert!(r.len() <= p.max_bytes as usize); |
| 259 | if i + 1 < ranges.len() { |
| 260 | assert!(r.len() > p.min_bytes as usize, "chunk {i} below min"); |
| 261 | } |
| 262 | at = r.end; |
| 263 | } |
| 264 | assert_eq!(at, data.len()); |
| 265 | // Content-defined: the average is near the target on random data. |
| 266 | let mean = data.len() / ranges.len(); |
| 267 | assert!(mean > 2 * 1024 && mean < 8 * 1024, "mean chunk {mean}"); |
| 268 | // All-zero data never matches the masks: every chunk is max long. |
| 269 | let zeros = vec![0u8; 100_000]; |
| 270 | let z = chunk_ranges(&zeros, &p); |
| 271 | assert!(z[..z.len() - 1] |
| 272 | .iter() |
| 273 | .all(|r| r.len() == p.max_bytes as usize)); |
| 274 | assert!(chunk_ranges(&[], &p).is_empty()); |
| 275 | } |
| 276 | |
| 277 | #[test] |
| 278 | fn invalid_parameters_are_refused() { |
| 279 | assert!(ChunkParams::candidate(16 * 1024, 3000).validate().is_err()); |
| 280 | assert!(ChunkParams { |
| 281 | min_bytes: 8, |
| 282 | ..ChunkParams::candidate(1, 64) |
| 283 | } |
| 284 | .validate() |
| 285 | .is_err()); |
| 286 | assert!(ChunkParams::OFF.validate().is_ok()); |
| 287 | } |
| 288 | } |