Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 9.4 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Chunked blobs (codec 4): blobs of 4 MiB or more, cut into chunks that are
5//! stored as blobs of their own.
6//!
7//! Cut points come from FastCDC (the 2020 algorithm, normalisation level 1,
8//! the standard gear table) and depend only on the content, so a few bytes
9//! changed in the middle of a large file change one or two chunks, and every
10//! other chunk is shared with the previous version, or with any file that
11//! holds the same bytes.
12//!
13//! | Blob size | Smallest chunk | Average | Largest |
14//! |---|---|---|---|
15//! | 4 MiB to 256 MiB | 16 KiB | 64 KiB | 256 KiB |
16//! | 256 MiB or more | 256 KiB | 1 MiB | 4 MiB |
17//!
18//! The record of a chunked blob holds its chunk list:
19//!
20//! ```text
21//! uv n | n × ([32] chunk id | uv chunk size)
22//! ```
23//!
24//! The chunks, in order, make up the blob: their sizes add up to the
25//! record's raw length, and the blob's id is the hash of the whole content,
26//! checked on every read. A chunk is a blob whose id is the hash of its own
27//! bytes, stored whole: raw when a sample of it does not compress below 0.9
28//! of its size, else compressed when that is smaller.
29
30use braid_format::codec::{Reader, put_id, put_uv};
31use braid_format::{Kind, ObjectId};
32
33use crate::record::{self, Encoded, ZSTD_LEVEL};
34
35/// Blobs of this size or more are stored in chunks.
36pub const CHUNKED_MIN: u64 = 4 << 20;
37
38/// Blobs of this size or more are cut into larger chunks.
39const LARGE_MIN: u64 = 256 << 20;
40
41/// Bytes of a chunk compressed to tell whether the rest is worth trying.
42const SAMPLE: usize = 64 << 10;
43
44/// The FastCDC sizes for one blob.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub(crate) struct Params {
47 /// No chunk is smaller, except the last one.
48 pub min: usize,
49 /// The size chunks tend to.
50 pub avg: usize,
51 /// No chunk is larger.
52 pub max: usize,
53}
54
55/// Chunks of blobs under [`LARGE_MIN`].
56const SMALL: Params = Params {
57 min: 16 << 10,
58 avg: 64 << 10,
59 max: 256 << 10,
60};
61
62/// Chunks of blobs of [`LARGE_MIN`] or more.
63const LARGE: Params = Params {
64 min: 256 << 10,
65 avg: 1 << 20,
66 max: 4 << 20,
67};
68
69/// The chunk sizes for a blob of `size` bytes.
70pub(crate) fn params(size: u64) -> Params {
71 if size >= LARGE_MIN { LARGE } else { SMALL }
72}
73
74/// Cuts a whole blob into chunks: the byte ranges, in order.
75pub(crate) fn cut(blob: &[u8]) -> impl Iterator<Item = &[u8]> {
76 let params = params(blob.len() as u64);
77 fastcdc::v2020::FastCDC::new(blob, params.min, params.avg, params.max)
78 .map(move |chunk| &blob[chunk.offset..chunk.offset + chunk.length])
79}
80
81/// Cuts a stream into chunks, sized for a blob of `size` bytes.
82pub(crate) fn cut_stream<R: std::io::Read>(reader: R, size: u64) -> fastcdc::v2020::StreamCDC<R> {
83 let params = params(size);
84 fastcdc::v2020::StreamCDC::new(reader, params.min, params.avg, params.max)
85}
86
87/// One chunk of a chunked blob.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub(crate) struct ChunkRef {
90 /// The chunk's id: the hash of its bytes as a blob.
91 pub id: ObjectId,
92 /// Its size in bytes.
93 pub size: u64,
94}
95
96/// Encodes a chunk list.
97pub(crate) fn encode_list(chunks: &[ChunkRef]) -> Vec<u8> {
98 let mut out = Vec::with_capacity(4 + chunks.len() * 36);
99 put_uv(&mut out, chunks.len() as u64);
100 for chunk in chunks {
101 put_id(&mut out, &chunk.id);
102 put_uv(&mut out, chunk.size);
103 }
104 out
105}
106
107/// Decodes the chunk list of a blob of `raw_len` bytes, checking that its
108/// sizes add up.
109pub(crate) fn decode_list(stored: &[u8], raw_len: u64) -> Result<Vec<ChunkRef>, &'static str> {
110 let bad = |_| "bad chunk list";
111 let mut reader = Reader::new(stored);
112 // An entry takes at least 33 bytes.
113 let n = reader.count(33).map_err(bad)?;
114 if n == 0 {
115 return Err("empty chunk list");
116 }
117 let mut chunks = Vec::with_capacity(n);
118 let mut total = 0u64;
119 for _ in 0..n {
120 let id = reader.id().map_err(bad)?;
121 let size = reader.uv().map_err(bad)?;
122 if size == 0 {
123 return Err("empty chunk in a chunk list");
124 }
125 total = total.checked_add(size).ok_or("chunk sizes overflow")?;
126 chunks.push(ChunkRef { id, size });
127 }
128 reader.finish().map_err(bad)?;
129 if total != raw_len {
130 return Err("chunk sizes do not add up to the blob's size");
131 }
132 Ok(chunks)
133}
134
135/// Whether a chunk is worth compressing: its first 64 KiB must compress
136/// below 0.9 of their size. Returns the compressed chunk when the sample was
137/// the whole chunk.
138fn sample(chunk: &[u8]) -> (bool, Option<Vec<u8>>) {
139 let part = &chunk[..chunk.len().min(SAMPLE)];
140 match zstd::bulk::compress(part, ZSTD_LEVEL) {
141 Ok(compressed) if compressed.len() * 10 < part.len() * 9 => {
142 let whole = (part.len() == chunk.len()).then_some(compressed);
143 (true, whole)
144 }
145 _ => (false, None),
146 }
147}
148
149/// The record of a chunk: raw when a sample of it does not compress well
150/// enough, else whichever of raw and compressed is smaller.
151pub(crate) fn encode_chunk(id: ObjectId, chunk: &[u8]) -> Result<Encoded, u64> {
152 match sample(chunk) {
153 (false, _) => record::encode_raw(Kind::Blob, id, chunk),
154 (true, Some(compressed)) => record::assemble(
155 Kind::Blob,
156 id,
157 record::CODEC_ZSTD,
158 chunk.len() as u64,
159 None,
160 &compressed,
161 ),
162 (true, None) => record::encode(Kind::Blob, id, chunk),
163 }
164}
165
166/// The record of a chunked blob.
167pub(crate) fn encode_chunked(id: ObjectId, size: u64, chunks: &[ChunkRef]) -> Result<Encoded, u64> {
168 record::assemble(
169 Kind::Blob,
170 id,
171 record::CODEC_CHUNKED,
172 size,
173 None,
174 &encode_list(chunks),
175 )
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use crate::record::{CODEC_CHUNKED, CODEC_RAW, CODEC_ZSTD, check};
182
183 fn noise(seed: u64, len: usize) -> Vec<u8> {
184 let mut state = seed | 1;
185 (0..len)
186 .map(|_| {
187 state ^= state << 13;
188 state ^= state >> 7;
189 state ^= state << 17;
190 (state >> 24) as u8
191 })
192 .collect()
193 }
194
195 #[test]
196 fn sizes_follow_the_blob() {
197 assert_eq!(params(CHUNKED_MIN), SMALL);
198 assert_eq!(params(LARGE_MIN - 1), SMALL);
199 assert_eq!(params(LARGE_MIN), LARGE);
200 let blob = noise(3, 5 << 20);
201 let chunks: Vec<&[u8]> = cut(&blob).collect();
202 assert_eq!(chunks.concat(), blob);
203 assert!(chunks.len() > 20, "{} chunks", chunks.len());
204 for chunk in &chunks[..chunks.len() - 1] {
205 assert!(
206 (SMALL.min..=SMALL.max).contains(&chunk.len()),
207 "{}",
208 chunk.len()
209 );
210 }
211 }
212
213 #[test]
214 fn streaming_cuts_the_same_chunks() {
215 let blob = noise(4, (6 << 20) + 12_345);
216 let whole: Vec<Vec<u8>> = cut(&blob).map(<[u8]>::to_vec).collect();
217 let streamed: Vec<Vec<u8>> = cut_stream(&blob[..], blob.len() as u64)
218 .map(|chunk| chunk.unwrap().data)
219 .collect();
220 assert_eq!(whole, streamed);
221 }
222
223 #[test]
224 fn chunk_lists_round_trip_and_are_checked() {
225 let chunks: Vec<ChunkRef> = (0..300u64)
226 .map(|i| ChunkRef {
227 id: ObjectId::hash(Kind::Blob, &i.to_le_bytes()),
228 size: 1000 + i * 77,
229 })
230 .collect();
231 let total: u64 = chunks.iter().map(|c| c.size).sum();
232 let list = encode_list(&chunks);
233 assert_eq!(decode_list(&list, total).unwrap(), chunks);
234 assert!(decode_list(&list, total + 1).is_err());
235 assert!(decode_list(&list[..list.len() - 1], total).is_err());
236 let mut longer = list.clone();
237 longer.push(0);
238 assert!(decode_list(&longer, total).is_err());
239 assert_eq!(decode_list(&[0], 0), Err("empty chunk list"));
240 // A count larger than the bytes could hold is refused up front.
241 assert!(decode_list(&[0xff, 0xff, 0x03], 1).is_err());
242 }
243
244 #[test]
245 fn chunks_that_do_not_compress_stay_raw() {
246 let random = noise(5, 100_000);
247 let id = ObjectId::hash(Kind::Blob, &random);
248 assert_eq!(encode_chunk(id, &random).unwrap().header.codec, CODEC_RAW);
249 for len in [1000, 50_000, 200_000] {
250 let text = b"0123456789 compressible text\n".repeat(len / 29);
251 let id = ObjectId::hash(Kind::Blob, &text);
252 let encoded = encode_chunk(id, &text).unwrap();
253 assert_eq!(encoded.header.codec, CODEC_ZSTD, "{len}");
254 let checked = check(&encoded.bytes).unwrap();
255 assert_eq!(
256 record::decode(&checked.header, checked.stored).unwrap(),
257 text
258 );
259 }
260 }
261
262 #[test]
263 fn a_chunked_record_holds_the_list() {
264 let chunks = [
265 ChunkRef {
266 id: ObjectId::hash(Kind::Blob, b"a"),
267 size: 3,
268 },
269 ChunkRef {
270 id: ObjectId::hash(Kind::Blob, b"b"),
271 size: 4,
272 },
273 ];
274 let id = ObjectId::hash(Kind::Blob, b"whole");
275 let encoded = encode_chunked(id, 7, &chunks).unwrap();
276 assert_eq!(encoded.header.codec, CODEC_CHUNKED);
277 assert_eq!(encoded.header.raw_len, 7);
278 let checked = check(&encoded.bytes).unwrap();
279 assert_eq!(checked.stored, encode_list(&chunks));
280 assert_eq!(decode_list(checked.stored, 7).unwrap(), chunks);
281 }
282}