interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-store / src / g2_tests.rs

855 lines · 30381 bytes Raw Blame History
1//! ADR 0003 G2 content-defined chunking tests (issue #45).
2//!
3//! Acceptance under test: every blob round-trips byte for byte through chunking with an
4//! unchanged `BlobDigest`; deduplication between two revisions that share content
5//! follows the rule X6 fixed before its runs (`evidence/g2-content-defined-chunking/x6/
6//! RULE.md` section 5). The expected chunk bytes are computed here from the chunker
7//! alone ([`chunk::chunk_ranges`] and [`ChunkDigest::compute`]), never read back from
8//! the store under test.
9
10use super::a1_tests::{copy_fixture, copy_tree, expect};
11use super::tests::{make_signed_changeset, temp_store_dir};
12use super::*;
13use ed25519_dalek::SigningKey;
14use std::collections::BTreeSet;
15use std::process::Command;
16use std::sync::Barrier;
17use synapse_core::{FileMode, GitOid, PathMutation, SYNAPSE_ENVELOPE_VERSION};
18
19/// Chunk parameters of the test stores: X6 candidate K1 (T = 16 KiB, avg 4 KiB).
20const P: ChunkParams = ChunkParams::candidate(16 * 1024, 4 * 1024);
21const T: usize = 16 * 1024;
22const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed;
23const CHILD_ENV: &str = "SYNAPSE_G2_CRASH_CHILD";
24
25fn limits_with(chunking: ChunkParams) -> StoreLimits {
26 StoreLimits {
27 segment_bytes: 1024 * 1024,
28 wal_prealloc_bytes: 64 * 1024,
29 max_blob_bytes: 8 * 1024 * 1024,
30 max_total_changeset_bytes: 16 * 1024 * 1024,
31 max_wal_record_bytes: 32 * 1024 * 1024,
32 chunking,
33 ..Default::default()
34 }
35}
36
37fn open_with(dir: &Path, chunking: ChunkParams) -> SynapseStore {
38 SynapseStore::open(
39 dir,
40 FsyncPolicy::GROUP_COMMIT_DEFAULT,
41 STRICT,
42 limits_with(chunking),
43 )
44 .unwrap()
45}
46
47fn open(dir: &Path) -> SynapseStore {
48 open_with(dir, P)
49}
50
51fn key(n: u8) -> SigningKey {
52 SigningKey::from_bytes(&[n; 32])
53}
54
55/// Deterministic pseudo-random bytes (xorshift64).
56fn random(len: usize, seed: u64) -> Vec<u8> {
57 let mut x = seed | 1;
58 (0..len)
59 .map(|_| {
60 x ^= x << 13;
61 x ^= x >> 7;
62 x ^= x << 17;
63 (x >> 24) as u8
64 })
65 .collect()
66}
67
68/// A signed changeset upserting every `(path, content)` in `files`.
69fn multi(
70 key: &SigningKey,
71 label: &str,
72 files: &[(&str, &[u8])],
73) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) {
74 let mut blobs: Vec<(BlobDigest, Vec<u8>)> = Vec::new();
75 let mutations = files
76 .iter()
77 .map(|(path, content)| {
78 let digest = BlobDigest::compute(content);
79 if !blobs.iter().any(|(d, _)| *d == digest) {
80 blobs.push((digest, content.to_vec()));
81 }
82 PathMutation {
83 path: path.to_string(),
84 op: MutationOp::Upsert {
85 mode: FileMode::Regular644,
86 blob_digest: digest,
87 size_bytes: content.len() as u64,
88 },
89 }
90 })
91 .collect();
92 let mut env = ChangesetEnvelope {
93 version: SYNAPSE_ENVELOPE_VERSION,
94 repo_id: RepoId::new("aien-spark/synapse").unwrap(),
95 base_git_oid: GitOid::compute_blob(b"base"),
96 parent_changesets: vec![],
97 author_did: String::new(),
98 idempotency_key: IdempotencyKey::from_label(label),
99 created_at_ms: 1000,
100 intent_summary: format!("G2 {label}"),
101 mutations,
102 evidence_receipts: vec![],
103 signature: vec![],
104 };
105 env.sign(key);
106 (env, blobs)
107}
108
109fn commit_env(store: &mut SynapseStore, env: ChangesetEnvelope, blobs: &[(BlobDigest, Vec<u8>)]) {
110 match store.ingest_changeset(env, blobs).unwrap() {
111 IngestOutcome::Committed { .. } => {}
112 other => panic!("expected Committed, got {other:?}"),
113 }
114}
115
116/// Commit `content` as one file; returns its digest.
117fn commit_blob(
118 store: &mut SynapseStore,
119 key: &SigningKey,
120 label: &str,
121 content: &[u8],
122) -> BlobDigest {
123 let (env, blobs) =
124 make_signed_changeset(key, label, &format!("src/{label}"), content, vec![], 1000);
125 commit_env(store, env, &blobs);
126 BlobDigest::compute(content)
127}
128
129/// The distinct chunks of `data` under `p`, from the chunker alone.
130fn chunks_of(data: &[u8], p: &ChunkParams) -> BTreeMap<ChunkDigest, u64> {
131 chunk::chunk_ranges(data, p)
132 .into_iter()
133 .map(|r| (ChunkDigest::compute(&data[r.clone()]), r.len() as u64))
134 .collect()
135}
136
137/// Bytes of the chunks of `data` not in `known` (the X6 rule, section 5.3).
138fn new_chunk_bytes(data: &[u8], known: &BTreeMap<ChunkDigest, u64>) -> u64 {
139 chunks_of(data, &P)
140 .iter()
141 .filter(|(d, _)| !known.contains_key(d))
142 .map(|(_, l)| l)
143 .sum()
144}
145
146/// `blob` reads back as exactly `content`, with the storage form the X6 rule requires.
147fn assert_round_trip(store: &SynapseStore, content: &[u8], what: &str) {
148 let digest = BlobDigest::compute(content);
149 let back = store.get_blob_visible(digest, None, None).unwrap();
150 assert!(
151 back == content,
152 "{what}: bytes differ ({} vs {})",
153 back.len(),
154 content.len()
155 );
156 assert_eq!(BlobDigest::compute(&back), digest, "{what}: digest changed");
157 let m = store.blob_manifest(&digest);
158 if content.len() > T {
159 let m = m.unwrap_or_else(|| panic!("{what}: above T but not chunked"));
160 assert_eq!(m.blob, digest);
161 assert_eq!(m.len, content.len() as u64);
162 let ranges = chunk::chunk_ranges(content, &P);
163 let expect: Vec<(ChunkDigest, u32)> = ranges
164 .iter()
165 .map(|r| (ChunkDigest::compute(&content[r.clone()]), r.len() as u32))
166 .collect();
167 assert_eq!(
168 m.chunks, expect,
169 "{what}: manifest is not the chunker's cut"
170 );
171 } else {
172 assert!(m.is_none(), "{what}: at most T but chunked");
173 }
174}
175
176/// The blobs of the round-trip test: edge sizes around T, random, repetitive, zeros, text.
177fn round_trip_corpus() -> Vec<(String, Vec<u8>)> {
178 let text: Vec<u8> = (0..120_000u32)
179 .flat_map(|i| format!("line {i}: fn f{}() {{}}\n", i % 97).into_bytes())
180 .take(150_000)
181 .collect();
182 let pattern: Vec<u8> = random(1000, 5)
183 .into_iter()
184 .cycle()
185 .take(1_000_000)
186 .collect();
187 vec![
188 ("empty".into(), vec![]),
189 ("one".into(), vec![42]),
190 ("t-minus-1".into(), random(T - 1, 1)),
191 ("t".into(), random(T, 2)),
192 ("t-plus-1".into(), random(T + 1, 3)),
193 ("random-3m".into(), random(3_000_000, 4)),
194 ("repetitive-1m".into(), pattern),
195 ("zeros-500k".into(), vec![0u8; 500_000]),
196 ("text".into(), text),
197 ("max-chunk-edge".into(), random(P.max_bytes as usize * 3, 6)),
198 ]
199}
200
201// --- acceptance 1: round trip ------------------------------------------------
202
203/// Every blob, at every size class, reads back byte for byte with an unchanged
204/// `BlobDigest`: right after commit, after a checkpoint, after reopen from the
205/// checkpoint's segment index, and after reopen by replaying frames.
206#[test]
207fn g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest() {
208 let dir = temp_store_dir("g2-round-trip");
209 let k = key(120);
210 let corpus = round_trip_corpus();
211 let (first, second) = corpus.split_at(6);
212 {
213 let mut s = open(&dir);
214 for (label, content) in first {
215 commit_blob(&mut s, &k, label, content);
216 }
217 for (label, content) in first {
218 assert_round_trip(&s, content, label);
219 }
220 s.checkpoint_and_compact(1000).unwrap();
221 for (label, content) in first {
222 assert_round_trip(&s, content, &format!("{label} after checkpoint"));
223 }
224 }
225 {
226 let mut s = open(&dir);
227 for (label, content) in first {
228 assert_round_trip(&s, content, &format!("{label} after reopen (index)"));
229 }
230 for (label, content) in second {
231 commit_blob(&mut s, &k, label, content);
232 }
233 }
234 let s = open(&dir);
235 for (label, content) in &corpus {
236 assert_round_trip(&s, content, &format!("{label} after reopen (replay)"));
237 }
238 assert_eq!(s.committed_seq(), WalSeq(corpus.len() as u64));
239 let _ = fs::remove_dir_all(&dir);
240}
241
242// --- acceptance 2: deduplication under the X6 rule ---------------------------
243
244/// Two revisions that share content: the second stores exactly its chunks not already
245/// indexed (X6 rule 5.3); an identical revision and a re-provided blob add nothing; a
246/// blob of at most T is stored whole (5.1). The same holds against chunks that come
247/// from the checkpoint's segment index after reopen.
248#[test]
249fn g2_dedup_between_two_revisions_follows_the_x6_rule() {
250 let dir = temp_store_dir("g2-dedup");
251 let k = key(121);
252 let a = random(400_000, 11);
253 // B: A with 100 bytes inserted in the middle, 50 bytes changed near the start, and
254 // 30 KB appended.
255 let mut b = a.clone();
256 b.splice(200_000..200_000, random(100, 12));
257 b[10_000..10_050].copy_from_slice(&random(50, 13));
258 b.extend_from_slice(&random(30_000, 14));
259 // C (after reopen): B with its tail cut and a new middle edit.
260 let mut c = b[..380_000].to_vec();
261 c.splice(100_000..100_000, random(64, 15));
262
263 let mut known = BTreeMap::new();
264 {
265 let mut s = open(&dir);
266 commit_blob(&mut s, &k, "rev-a", &a);
267 known.extend(chunks_of(&a, &P));
268 let (n0, bytes0) = s.chunk_storage();
269 assert_eq!(n0, known.len());
270 assert_eq!(bytes0, known.values().sum::<u64>());
271
272 let expected_b = new_chunk_bytes(&b, &known);
273 assert!(
274 expected_b > 0 && expected_b < b.len() as u64 / 4,
275 "B shares most of A"
276 );
277 let log0 = s.log_bytes_written();
278 commit_blob(&mut s, &k, "rev-b", &b);
279 let (n1, bytes1) = s.chunk_storage();
280 assert_eq!(bytes1 - bytes0, expected_b, "B adds exactly its new chunks");
281 known.extend(chunks_of(&b, &P));
282 assert_eq!(n1, known.len());
283 let log_b = s.log_bytes_written() - log0;
284 assert!(
285 log_b < expected_b + 64 * 1024,
286 "log bytes of B ({log_b}) carry only the new chunks ({expected_b}) plus metadata"
287 );
288
289 // Identical content under another path, bytes provided again: nothing added.
290 commit_blob(&mut s, &k, "rev-a-again", &a);
291 assert_eq!(s.chunk_storage(), (n1, bytes1));
292 // Two files of one changeset sharing chunks with each other and with A.
293 let mut a2 = a.clone();
294 a2[300_000..300_010].copy_from_slice(&[7u8; 10]);
295 let mut a3 = a2.clone();
296 a3.extend_from_slice(&random(20_000, 16));
297 let mut both = known.clone();
298 let expected_23 = new_chunk_bytes(&a2, &both);
299 both.extend(chunks_of(&a2, &P));
300 let expected_23 = expected_23 + new_chunk_bytes(&a3, &both);
301 let (env, blobs) = multi(&k, "rev-a2-a3", &[("x/a2", &a2), ("x/a3", &a3)]);
302 commit_env(&mut s, env, &blobs);
303 assert_eq!(
304 s.chunk_storage().1 - bytes1,
305 expected_23,
306 "chunks shared inside one record"
307 );
308 known = both;
309 known.extend(chunks_of(&a3, &P));
310
311 // At most T: stored whole, never cut, also when committed twice.
312 let small = random(T, 17);
313 commit_blob(&mut s, &k, "small", &small);
314 let inline0 = s.inline_blob_bytes();
315 assert!(s.blob_manifest(&BlobDigest::compute(&small)).is_none());
316 assert_eq!(s.chunk_storage().0, known.len());
317 assert!(inline0 >= T as u64);
318 for (what, content) in [
319 ("a", &a),
320 ("b", &b),
321 ("a2", &a2),
322 ("a3", &a3),
323 ("small", &small),
324 ] {
325 assert_round_trip(&s, content, what);
326 }
327 s.checkpoint_and_compact(1000).unwrap();
328 assert_eq!(
329 s.chunk_storage().0,
330 known.len(),
331 "checkpoint keeps every chunk"
332 );
333 }
334 let mut s = open(&dir);
335 assert_eq!(
336 s.chunk_storage().0,
337 known.len(),
338 "chunk index restored from the checkpoint"
339 );
340 let before = s.chunk_storage().1;
341 let expected_c = new_chunk_bytes(&c, &known);
342 commit_blob(&mut s, &k, "rev-c", &c);
343 assert_eq!(
344 s.chunk_storage().1 - before,
345 expected_c,
346 "dedup against indexed chunks"
347 );
348 drop(s);
349 let s = open(&dir);
350 for (what, content) in [("a", &a), ("b", &b), ("c", &c)] {
351 assert_round_trip(&s, content, what);
352 }
353 let _ = fs::remove_dir_all(&dir);
354}
355
356/// Records accepted earlier in the same group-commit batch count as indexed (X6 rule
357/// 5.3): four revisions sharing content in one batch store each chunk once.
358#[test]
359fn g2_dedup_inside_one_batch_counts_earlier_records() {
360 let dir = temp_store_dir("g2-batch");
361 let k = key(122);
362 let base = random(300_000, 21);
363 let revs: Vec<Vec<u8>> = (0..4u8)
364 .map(|i| {
365 let mut r = base.clone();
366 r.extend_from_slice(&random(5000, 30 + u64::from(i)));
367 r
368 })
369 .collect();
370 let mut known = BTreeMap::new();
371 for r in &revs {
372 known.extend(chunks_of(r, &P));
373 }
374 let shared = SharedStore::open(
375 &dir,
376 FsyncPolicy::GroupCommit {
377 max_batch_records: 4,
378 max_batch_delay_us: 5_000_000,
379 },
380 STRICT,
381 limits_with(P),
382 )
383 .unwrap();
384 let inputs: Vec<_> = revs
385 .iter()
386 .enumerate()
387 .map(|(i, r)| {
388 make_signed_changeset(&k, &format!("b{i}"), &format!("b/{i}"), r, vec![], 1000)
389 })
390 .collect();
391 let barrier = Barrier::new(inputs.len());
392 std::thread::scope(|sc| {
393 for (env, blobs) in inputs {
394 let (shared, barrier) = (&shared, &barrier);
395 sc.spawn(move || {
396 barrier.wait();
397 assert!(matches!(
398 shared.submit(env, &blobs).unwrap(),
399 IngestOutcome::Committed { .. }
400 ));
401 });
402 }
403 });
404 let stats = shared.stats();
405 assert_eq!((stats.batches, stats.records), (1, 4), "one batch");
406 {
407 let st = shared.read();
408 assert_eq!(
409 st.chunk_storage(),
410 (known.len(), known.values().sum::<u64>())
411 );
412 let log = st.log_bytes_written();
413 assert!(
414 log < known.values().sum::<u64>() + 64 * 1024,
415 "the batch carries each chunk once: {log} log bytes for {} chunk bytes",
416 known.values().sum::<u64>()
417 );
418 }
419 drop(shared);
420 let s = open(&dir);
421 assert_eq!(
422 s.chunk_storage(),
423 (known.len(), known.values().sum::<u64>())
424 );
425 for (i, r) in revs.iter().enumerate() {
426 assert_round_trip(&s, r, &format!("batch rev {i}"));
427 }
428 let _ = fs::remove_dir_all(&dir);
429}
430
431/// The parameters are a storage choice only: a blob stored whole with chunking off is
432/// still read whole, and re-providing it once chunking is on adds no chunks; a store
433/// opened with other chunk parameters reads everything written with the first ones.
434#[test]
435fn g2_parameters_change_without_changing_identity() {
436 let dir = temp_store_dir("g2-params");
437 let k = key(123);
438 let a = random(200_000, 41);
439 let b = random(200_000, 42);
440 {
441 let mut s = open_with(&dir, ChunkParams::OFF);
442 commit_blob(&mut s, &k, "off-a", &a);
443 assert!(s.blob_manifest(&BlobDigest::compute(&a)).is_none());
444 }
445 {
446 let mut s = open(&dir);
447 commit_blob(&mut s, &k, "on-a", &a);
448 assert_eq!(s.chunk_storage(), (0, 0), "already stored whole: no chunks");
449 commit_blob(&mut s, &k, "on-b", &b);
450 assert!(s.blob_manifest(&BlobDigest::compute(&b)).is_some());
451 }
452 let other = ChunkParams::candidate(64 * 1024, 16 * 1024);
453 let s = open_with(&dir, other);
454 for content in [&a, &b] {
455 let d = BlobDigest::compute(content);
456 assert!(s.get_blob_visible(d, None, None).unwrap() == *content);
457 }
458 let _ = fs::remove_dir_all(&dir);
459}
460
461// --- fail closed ---------------------------------------------------------------
462
463/// Index position of a chunk of `blob` (the first one) on disk.
464fn first_chunk_loc(store: &SynapseStore, blob: &BlobDigest) -> segment::BlobLoc {
465 let m = store.blob_manifest(blob).unwrap();
466 store.chunk_locations[&m.chunks[0].0]
467}
468
469fn flip_byte(dir: &Path, loc: segment::BlobLoc, at: u64) {
470 use std::os::unix::fs::FileExt;
471 let path = dir.join(segment::segment_file_name(loc.segment));
472 let f = OpenOptions::new()
473 .read(true)
474 .write(true)
475 .open(path)
476 .unwrap();
477 let mut b = [0u8; 1];
478 f.read_exact_at(&mut b, loc.offset + at).unwrap();
479 f.write_all_at(&[b[0] ^ 0x40], loc.offset + at).unwrap();
480}
481
482/// A damaged chunk byte is never served: replay refuses the frame (its payload digest
483/// covers the chunk digests and every chunk is checked against its digest), and a chunk
484/// the checkpoint vouches for fails the blob read with `BlobDigestMismatch`.
485#[test]
486fn g2_damaged_chunk_is_refused() {
487 let k = key(124);
488 let a = random(100_000, 51);
489 let da = BlobDigest::compute(&a);
490 // Replayed frame.
491 let dir = temp_store_dir("g2-damage-replay");
492 let loc = {
493 let mut s = open(&dir);
494 commit_blob(&mut s, &k, "dmg", &a);
495 first_chunk_loc(&s, &da)
496 };
497 flip_byte(&dir, loc, 7);
498 let Err(err) = SynapseStore::open(
499 &dir,
500 FsyncPolicy::GROUP_COMMIT_DEFAULT,
501 STRICT,
502 limits_with(P),
503 ) else {
504 panic!("open must refuse");
505 };
506 assert!(
507 matches!(
508 err.code,
509 RefusalCode::BlobDigestMismatch
510 | RefusalCode::WalCrcMismatch
511 | RefusalCode::WalTornFrame
512 ),
513 "replay must refuse: {err:?}"
514 );
515 let _ = fs::remove_dir_all(&dir);
516 // Damaged chunk byte with the payload CRC and the frame digest repaired (as an
517 // adversary, or a CRC collision, would leave it): only the chunk digest catches it.
518 let dir = temp_store_dir("g2-damage-crc-repaired");
519 let (loc, first_chunk_off) = {
520 let mut s = open(&dir);
521 commit_blob(&mut s, &k, "dmg", &a);
522 let off = s.chunk_locations.values().map(|l| l.offset).min().unwrap();
523 (first_chunk_loc(&s, &da), off)
524 };
525 assert_eq!(loc.segment, 1);
526 flip_byte(&dir, loc, 7);
527 {
528 let path = dir.join(segment::segment_file_name(1));
529 let mut seg = fs::read(&path).unwrap();
530 let h0 = wal2::WAL_V2_BATCH_HEADER_LEN;
531 let p0 = h0 + WAL_HEADER_LEN;
532 let plen = u32::from_le_bytes(seg[h0 + 48..h0 + 52].try_into().unwrap()) as usize;
533 let crc = crc32c(&seg[p0..p0 + plen]);
534 seg[h0 + 52..h0 + 56].copy_from_slice(&crc.to_le_bytes());
535 let psha = wal2::chunked_payload_digest(&seg[p0..p0 + plen], first_chunk_off as usize - p0);
536 let fsha = wal2::frame_digest(&seg[h0..h0 + 56], &psha);
537 seg[h0 + 56..h0 + 88].copy_from_slice(&fsha);
538 fs::write(&path, &seg).unwrap();
539 }
540 let Err(err) = SynapseStore::open(
541 &dir,
542 FsyncPolicy::GROUP_COMMIT_DEFAULT,
543 STRICT,
544 limits_with(P),
545 ) else {
546 panic!("open must refuse a chunk whose digest does not match");
547 };
548 assert_eq!(err.code, RefusalCode::BlobDigestMismatch, "{err:?}");
549 let _ = fs::remove_dir_all(&dir);
550 // Chunk covered by the checkpoint.
551 let dir = temp_store_dir("g2-damage-index");
552 let loc = {
553 let mut s = open(&dir);
554 commit_blob(&mut s, &k, "dmg", &a);
555 s.checkpoint_and_compact(1000).unwrap();
556 first_chunk_loc(&s, &da)
557 };
558 flip_byte(&dir, loc, 7);
559 let s = open(&dir);
560 assert_eq!(
561 s.get_blob_visible(da, None, None).unwrap_err().code,
562 RefusalCode::BlobDigestMismatch
563 );
564 let _ = fs::remove_dir_all(&dir);
565}
566
567/// A frame whose manifest names a chunk that is nowhere indexed is refused at replay.
568#[test]
569fn g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay() {
570 let dir = temp_store_dir("g2-orphan-manifest");
571 let k = key(125);
572 let a = random(100_000, 61);
573 {
574 let mut s = open(&dir);
575 commit_blob(&mut s, &k, "base", &a);
576 // Forge the state of a store that already holds every chunk of A2 (it does not):
577 // the next record then carries A2's manifest without its chunk bytes.
578 let mut a2 = a.clone();
579 a2.extend_from_slice(&random(40_000, 62));
580 let fake = segment::BlobLoc {
581 segment: 1,
582 offset: 0,
583 len: 1,
584 };
585 for (d, l) in chunks_of(&a2, &P) {
586 s.chunk_locations.entry(d).or_insert(segment::BlobLoc {
587 len: l as u32,
588 ..fake
589 });
590 }
591 commit_blob(&mut s, &k, "forged", &a2);
592 }
593 let Err(err) = SynapseStore::open(
594 &dir,
595 FsyncPolicy::GROUP_COMMIT_DEFAULT,
596 STRICT,
597 limits_with(P),
598 ) else {
599 panic!("open must refuse");
600 };
601 assert_eq!(err.code, RefusalCode::BlobNotFound, "{err:?}");
602 let _ = fs::remove_dir_all(&dir);
603}
604
605/// Invalid chunk parameters are refused at open.
606#[test]
607fn g2_invalid_chunk_parameters_are_refused_at_open() {
608 let dir = temp_store_dir("g2-bad-params");
609 let bad = ChunkParams {
610 avg_bytes: 3000,
611 ..P
612 };
613 assert!(SynapseStore::open(
614 &dir,
615 FsyncPolicy::GROUP_COMMIT_DEFAULT,
616 STRICT,
617 limits_with(bad)
618 )
619 .is_err());
620 let _ = fs::remove_dir_all(&dir);
621}
622
623/// Segment index version 2 round-trips chunks and manifests and refuses an orphan chunk,
624/// a manifest naming a missing chunk, a manifest whose length disagrees, a chunk after
625/// the replay position, and a flipped bit; an index without chunks stays version 1.
626#[test]
627fn g2_segment_index_v2_round_trips_and_refuses_damage() {
628 let loc = |segment, offset, len| segment::BlobLoc {
629 segment,
630 offset,
631 len,
632 };
633 let (c1, c2) = (ChunkDigest([1u8; 32]), ChunkDigest([2u8; 32]));
634 let blob = BlobDigest([9u8; 32]);
635 let index = segment::SegmentIndex {
636 binding: [7u8; 32],
637 replay_segment: 3,
638 replay_offset: 8192,
639 entries: [(BlobDigest([3u8; 32]), loc(1, 4096, 100))]
640 .into_iter()
641 .collect(),
642 chunks: [(c1, loc(1, 100, 50)), (c2, loc(2, 0, 70))]
643 .into_iter()
644 .collect(),
645 manifests: [(
646 blob,
647 ChunkManifest {
648 blob,
649 len: 170,
650 chunks: vec![(c1, 50), (c2, 70), (c1, 50)],
651 },
652 )]
653 .into_iter()
654 .collect(),
655 };
656 let bytes = index.encode();
657 assert_eq!(&bytes[4..6], &2u16.to_le_bytes());
658 assert_eq!(segment::SegmentIndex::decode(&bytes).unwrap(), index);
659 let refused = |i: &segment::SegmentIndex, what: &str| {
660 assert_eq!(
661 segment::SegmentIndex::decode(&i.encode()).unwrap_err().code,
662 RefusalCode::CheckpointCorrupt,
663 "{what}"
664 )
665 };
666 let mut orphan = index.clone();
667 orphan.chunks.insert(ChunkDigest([4u8; 32]), loc(1, 0, 10));
668 refused(&orphan, "orphan chunk");
669 let mut missing = index.clone();
670 missing.chunks.remove(&c2);
671 refused(&missing, "missing chunk");
672 let mut short = index.clone();
673 short.manifests.get_mut(&blob).unwrap().len = 169;
674 refused(&short, "length mismatch");
675 let mut late = index.clone();
676 late.chunks.insert(c2, loc(3, 8192, 70));
677 refused(&late, "chunk after the replay position");
678 for at in [10, 70, bytes.len() - 40] {
679 let mut b = bytes.clone();
680 b[at] ^= 1;
681 assert!(
682 segment::SegmentIndex::decode(&b).is_err(),
683 "bit flip at {at}"
684 );
685 }
686 let plain = segment::SegmentIndex {
687 chunks: BTreeMap::new(),
688 manifests: BTreeMap::new(),
689 ..index.clone()
690 };
691 assert_eq!(&plain.encode()[4..6], &1u16.to_le_bytes());
692 assert_eq!(
693 segment::SegmentIndex::decode(&plain.encode()).unwrap(),
694 plain
695 );
696}
697
698/// With chunking off the store writes exactly the A2 formats (no chunk flag, segment
699/// index version 1), so builds before G2 still open it.
700#[test]
701fn g2_chunking_off_writes_the_a2_formats() {
702 let dir = temp_store_dir("g2-off");
703 let k = key(126);
704 {
705 let mut s = open_with(&dir, ChunkParams::OFF);
706 commit_blob(&mut s, &k, "big", &random(300_000, 71));
707 s.checkpoint_and_compact(1000).unwrap();
708 assert_eq!(s.chunk_storage(), (0, 0));
709 }
710 let index = fs::read_dir(&dir)
711 .unwrap()
712 .map(|e| e.unwrap().path())
713 .find(|p| {
714 p.file_name()
715 .and_then(|n| n.to_str())
716 .is_some_and(|n| n.starts_with(segment::SEGMENT_INDEX_PREFIX))
717 })
718 .unwrap();
719 assert_eq!(&fs::read(index).unwrap()[4..6], &1u16.to_le_bytes());
720 let _ = fs::remove_dir_all(&dir);
721}
722
723// --- crash ---------------------------------------------------------------------
724
725fn child_dir() -> Option<PathBuf> {
726 std::env::var(CHILD_ENV).ok().map(PathBuf::from)
727}
728
729/// A crash after a chunked batch is durable but before the in-memory index is updated
730/// keeps every acknowledged change; the pending batch is kept whole and its blob reads
731/// back byte for byte.
732#[test]
733fn g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack() {
734 let k = key(127);
735 let revs: Vec<Vec<u8>> = (0..5u64)
736 .map(|i| {
737 let mut r = random(150_000, 80);
738 r.extend_from_slice(&random(9000, 81 + i));
739 r
740 })
741 .collect();
742 if let Some(dir) = child_dir() {
743 let mut s = open(&dir);
744 for (i, r) in revs[..4].iter().enumerate() {
745 commit_blob(&mut s, &k, &format!("cr-{i}"), r);
746 if i == 1 {
747 s.checkpoint_and_compact(1000).unwrap();
748 }
749 }
750 s.set_fault_injection(FaultInjection::CrashAfterBatchSyncBeforeIndex);
751 let (env, blobs) = make_signed_changeset(&k, "cr-4", "src/cr-4", &revs[4], vec![], 1000);
752 let r = s.ingest_changeset(env, &blobs);
753 panic!("the injected fault did not end the process: {r:?}");
754 }
755 let dir = temp_store_dir("g2-crash");
756 let status = Command::new(std::env::current_exe().unwrap())
757 .arg("--exact")
758 .arg("g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack")
759 .arg("--nocapture")
760 .env(CHILD_ENV, &dir)
761 .status()
762 .unwrap();
763 assert_eq!(status.code(), Some(FAULT_CRASH_EXIT_CODE));
764 let s = open(&dir);
765 assert_eq!(s.committed_seq(), WalSeq(5));
766 let mut known = BTreeMap::new();
767 for (i, r) in revs.iter().enumerate() {
768 assert_round_trip(&s, r, &format!("rev {i}"));
769 known.extend(chunks_of(r, &P));
770 }
771 assert_eq!(
772 s.chunk_storage(),
773 (known.len(), known.values().sum::<u64>())
774 );
775 let _ = fs::remove_dir_all(&dir);
776}
777
778// --- old stores ------------------------------------------------------------------
779
780/// Stores written before G2 stay readable with chunking on: the A1 fixtures (v1 WAL,
781/// single-file WAL v2, blobs as files) and an A2 segment store written by the A2 code
782/// itself (`tests/fixtures/g2-a2/segment-store`, generator under
783/// `evidence/g2-content-defined-chunking/fixture-generator`). Their blobs read back
784/// whole, new chunked blobs land next to them, and everything survives a checkpoint and
785/// reopen.
786#[test]
787fn g2_old_stores_stay_readable() {
788 let k = key(128);
789 let big = random(120_000, 91);
790 for name in ["v1-wal-log", "v1-wal-v2-log"] {
791 let dir = copy_fixture(name);
792 let ex = expect(name);
793 old_store_case(&dir, name, ex.committed_seq, ex.state_root, &k, &big);
794 }
795 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/g2-a2/segment-store");
796 let dir = temp_store_dir("g2-a2-fixture");
797 copy_tree(&src, &dir);
798 let text = fs::read_to_string(dir.join("EXPECT")).unwrap();
799 let _ = fs::remove_file(dir.join("EXPECT"));
800 let field = |key: &str| {
801 text.lines()
802 .find_map(|l| l.strip_prefix(key).map(|v| v.trim().to_string()))
803 .unwrap()
804 };
805 let seq: u64 = field("committed_seq ").parse().unwrap();
806 let root: [u8; 32] = hex::decode(field("state_root "))
807 .unwrap()
808 .try_into()
809 .unwrap();
810 assert!(
811 segment::list_segments(&dir).unwrap().len() >= 2,
812 "fixture spans segments"
813 );
814 old_store_case(&dir, "a2-segment-store", seq, root, &k, &big);
815}
816
817fn old_store_case(dir: &Path, name: &str, seq: u64, root: [u8; 32], k: &SigningKey, big: &[u8]) {
818 let old_blobs = |s: &SynapseStore| -> Vec<BlobDigest> {
819 let mut v = BTreeSet::new();
820 for c in s.list_changesets(None, None, Some(WalSeq(seq))).unwrap() {
821 for m in &c.envelope.mutations {
822 if let MutationOp::Upsert { blob_digest, .. } = &m.op {
823 v.insert(*blob_digest);
824 }
825 }
826 }
827 v.into_iter().collect()
828 };
829 let check_old = |s: &SynapseStore, what: &str| {
830 let blobs = old_blobs(s);
831 assert!(!blobs.is_empty(), "{name}: fixture holds blobs");
832 for d in blobs {
833 let bytes = s.get_blob_visible(d, None, None).unwrap();
834 assert_eq!(BlobDigest::compute(&bytes), d, "{name} {what}");
835 assert!(
836 s.blob_manifest(&d).is_none(),
837 "{name}: old blob stays whole"
838 );
839 }
840 };
841 {
842 let mut s = open(dir);
843 assert_eq!(s.committed_seq(), WalSeq(seq), "{name}");
844 assert_eq!(s.state_root_digest(None).unwrap(), root, "{name}");
845 check_old(&s, "on open");
846 commit_blob(&mut s, k, &format!("{name}-g2"), big);
847 assert_round_trip(&s, big, name);
848 s.checkpoint_and_compact(1000).unwrap();
849 }
850 let s = open(dir);
851 assert_eq!(s.committed_seq(), WalSeq(seq + 1), "{name}");
852 check_old(&s, "after checkpoint and reopen");
853 assert_round_trip(&s, big, name);
854 let _ = fs::remove_dir_all(dir);
855}