synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
GitHub aien-dev/synapse#85 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/synapse/patches/70a50f727edbb43d.bundle -o 70a50f727edbb43d.bundle git fetch 70a50f727edbb43d.bundle refs/pull/85/head
Provenance
github-import 1
aien-dev/synapse
85
040c21afeec1a68f3ab349df50cdf2c218a55766
{"kind":"github-import","owner":"aien-dev","repo":"synapse","number":85,"url":"https://github.com/aien-dev/synapse/pull/85","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:19Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/synapse-bench/src/lib.rs b/crates/synapse-bench/src/lib.rs index 793c80b..0755b39 100644 --- a/crates/synapse-bench/src/lib.rs +++ b/crates/synapse-bench/src/lib.rs @@ -38,6 +38,7 @@ pub mod synapse_arm; pub mod tree_parity; pub mod workload; pub mod write_phase; +pub mod x6; use std::path::Path; diff --git a/crates/synapse-bench/src/main.rs b/crates/synapse-bench/src/main.rs index 4246fce..2801b4e 100644 --- a/crates/synapse-bench/src/main.rs +++ b/crates/synapse-bench/src/main.rs @@ -601,6 +601,65 @@ fn segments_report(args: &[String]) -> Result<(), String> { .map_err(|e| format!("write stdout: {e}")) } +/// ADR 0003 X6 (G2): `x6 --corpus <dir of bare clones> --out <raw.json> [--dir <scratch>] +/// [--reps 3] [--idle-window-s 10] [--only K1,C0]`. Progress goes to stderr. +fn x6(args: &[String]) -> Result<(), String> { + let opts = parse_pairs( + args, + &[ + "--corpus", + "--out", + "--dir", + "--reps", + "--idle-window-s", + "--only", + ], + )?; + let get = |k: &str| { + opts.iter() + .rev() + .find(|(key, _)| key == k) + .map(|(_, v)| v.clone()) + }; + let corpus = PathBuf::from(get("--corpus").ok_or("missing --corpus")?); + let out = PathBuf::from(get("--out").ok_or("missing --out")?); + let scratch = get("--dir") + .map(PathBuf::from) + .unwrap_or_else(synapse_bench::x6::default_scratch); + let reps: usize = get("--reps") + .map_or(Ok(3), |v| v.parse()) + .map_err(|_| "invalid --reps")?; + let idle: u64 = get("--idle-window-s") + .map_or(Ok(10), |v| v.parse()) + .map_err(|_| "invalid --idle-window-s")?; + let only: Option<Vec<String>> = get("--only").map(|v| v.split(',').map(String::from).collect()); + std::fs::create_dir_all(&scratch).map_err(|e| format!("create {}: {e}", scratch.display()))?; + let raw = + synapse_bench::x6::run_x6(&corpus, &scratch, reps, idle, only.as_deref(), &mut |m| { + eprintln!("{m}") + })?; + let bytes = serde_json::to_vec(&raw).map_err(|e| e.to_string())?; + std::fs::write(&out, bytes).map_err(|e| format!("write {}: {e}", out.display())) +} + +/// `x6-report --raw <raw.json>`: the RULE.md section 6 decision as JSON on stdout. +fn x6_report(args: &[String]) -> Result<(), String> { + use std::io::Write; + let opts = parse_pairs(args, &["--raw"])?; + let raw_path = opts + .iter() + .rev() + .find(|(k, _)| k == "--raw") + .map(|(_, v)| PathBuf::from(v)) + .ok_or("missing --raw")?; + let raw: synapse_bench::x6::X6Raw = synapse_bench::read_json(&raw_path)?; + let report = synapse_bench::x6::decide(&raw); + let bytes = serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?; + std::io::stdout() + .write_all(&bytes) + .map_err(|e| format!("write stdout: {e}")) +} + fn main() -> ExitCode { let args: Vec<String> = std::env::args().skip(1).collect(); let outcome = match args.first().map(String::as_str) { @@ -617,6 +676,8 @@ fn main() -> ExitCode { Some("crypto-vectors-verify") => crypto_vectors_verify(&args[1..]), Some("segments") => segments(&args[1..]), Some("segments-report") => segments_report(&args[1..]), + Some("x6") => x6(&args[1..]), + Some("x6-report") => x6_report(&args[1..]), Some("store-repair") => store_repair(&args[1..]), _ => Err("usage: synapse-bench run ... | synapse-bench child ... (see crate docs)".into()), }; diff --git a/crates/synapse-bench/src/x6.rs b/crates/synapse-bench/src/x6.rs new file mode 100644 index 0000000..52d7193 --- /dev/null +++ b/crates/synapse-bench/src/x6.rs @@ -0,0 +1,800 @@ +//! ADR 0003 experiment X6 (step G2, issue #45): content-defined chunking threshold and +//! chunk sizes on real AIEN repository histories. +//! +//! Everything this module does is fixed in `evidence/g2-content-defined-chunking/x6/ +//! RULE.md`, committed before the runs: the eight configurations, the corpus (one +//! accepted change per first-parent commit that adds or modifies a regular file, bytes +//! provided the first time a blob appears), the measurements (ingest phase: per-change +//! latency, wall time, one energy window, log bytes; read phase: every distinct blob once +//! with a byte comparison, per-read time, one energy window), three repetitions with the +//! configuration order rotated by one per repetition, and the decision criterion +//! ([`decide`]). Joules come only from the `aien_spbm` package meter; a refused window +//! leaves them `None` with the reason (`INSTRUMENT_UNAVAILABLE`), never a substitute. + +use crate::energy::{idle_window, EnergyReading, EnergyWindow}; +use crate::stats::{summarize_us, LatencySummary}; +use ed25519_dalek::SigningKey; +use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, HashMap}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; +use synapse_core::{ + BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey, MutationOp, PathMutation, + RepoId, SYNAPSE_ENVELOPE_VERSION, +}; +use synapse_store::{ + ChunkParams, FsyncPolicy, IngestOutcome, RecoveryPolicy, SharedStore, StoreLimits, +}; + +/// A2 flush bound, seconds: `evidence/a2-segment-store/measurement/floor.json`, cheapest +/// `overwrite_*_fdatasync` p50 (`overwrite_64k_fdatasync`), as fixed in RULE.md section 4. +pub const A2_FLUSH_BOUND_S: f64 = 1.006e-3; +/// Memory bandwidth, bytes per second (NVIDIA DGX Spark specification, A0). +pub const MEMORY_BW_BPS: f64 = 273e9; + +/// The corpus repositories and commits of RULE.md section 3, in order. +pub const CORPUS: [(&str, &str); 4] = [ + ( + "aien-architecture", + "d2768e9b8730af5f13c0fbbdfbfa4ba788f7605a", + ), + ("aienos", "b7ebf7cde234e1ddcc91eb8fcaf378d060cfb3a2"), + ("omega", "43d8d20da2f64319bcf6196ac7204021c3f280eb"), + ("synapse", "b9f46b16aa74301f0b330cfb5fa2e06f07d60b43"), +]; + +/// The eight configurations of RULE.md section 2. +pub fn configurations() -> Vec<(&'static str, ChunkParams)> { + const K: u64 = 1024; + vec![ + ("C0", ChunkParams::OFF), + ("K1", ChunkParams::candidate(16 * K, 4 * 1024)), + ("K2", ChunkParams::candidate(16 * K, 8 * 1024)), + ("K3", ChunkParams::candidate(64 * K, 8 * 1024)), + ("K4", ChunkParams::candidate(64 * K, 16 * 1024)), + ("K5", ChunkParams::candidate(64 * K, 32 * 1024)), + ("K6", ChunkParams::candidate(256 * K, 16 * 1024)), + ("K7", ChunkParams::candidate(256 * K, 64 * 1024)), + ] +} + +/// A signed changeset and the blob bytes it provides. +pub type SignedChange = (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>); + +/// One file revision of a change: synthetic path, blob index, executable bit. +#[derive(Debug, Clone)] +pub struct FileRev { + pub path: String, + pub blob: usize, + pub exec: bool, +} + +/// The corpus in memory: changes in order and the distinct blobs they name. +#[derive(Debug)] +pub struct Corpus { + pub changes: Vec<(String, String, Vec<FileRev>)>, + pub blobs: Vec<Vec<u8>>, + pub digests: Vec<BlobDigest>, + pub revisions: usize, + pub revision_bytes: u64, +} + +fn git(dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .map_err(|e| format!("git: {e}"))?; + if !out.status.success() { + return Err(format!( + "git {args:?} in {}: {}", + dir.display(), + String::from_utf8_lossy(&out.stderr) + )); + } + Ok(out.stdout) +} + +/// Read the corpus from bare clones `<root>/<name>.git` (RULE.md section 3). +pub fn load_corpus(root: &Path) -> Result<Corpus, String> { + let mut changes = Vec::new(); + let mut oid_index: HashMap<String, usize> = HashMap::new(); + let mut oids: Vec<String> = Vec::new(); + let mut paths: HashMap<(usize, String), usize> = HashMap::new(); + let mut revisions = 0usize; + for (r, (name, commit)) in CORPUS.iter().enumerate() { + let dir = root.join(format!("{name}.git")); + let head = git(&dir, &["rev-parse", &format!("{commit}^{{commit}}")])?; + if String::from_utf8_lossy(&head).trim() != *commit { + return Err(format!("{name}: commit {commit} not found")); + } + let log = git( + &dir, + &[ + "log", + "--reverse", + "--first-parent", + "--raw", + "--no-renames", + "--no-abbrev", + "--format=commit %H", + commit, + ], + )?; + let mut current: Option<(String, Vec<FileRev>)> = None; + let flush = |cur: Option<(String, Vec<FileRev>)>, changes: &mut Vec<_>| { + if let Some((h, files)) = cur { + if !files.is_empty() { + changes.push((name.to_string(), h, files)); + } + } + }; + for line in String::from_utf8_lossy(&log).lines() { + if let Some(h) = line.strip_prefix("commit ") { + flush(current.take(), &mut changes); + current = Some((h.to_string(), Vec::new())); + continue; + } + let Some(rest) = line.strip_prefix(':') else { + continue; + }; + let (meta, path) = rest.split_once('\t').ok_or("raw line without path")?; + let f: Vec<&str> = meta.split(' ').collect(); + if f.len() != 5 { + return Err(format!("unexpected raw line {line}")); + } + let (mode, oid, status) = (f[1], f[3], f[4]); + if !(status.starts_with('A') || status.starts_with('M')) { + continue; + } + if mode != "100644" && mode != "100755" { + continue; + } + let next = paths.len(); + let pid = *paths.entry((r, path.to_string())).or_insert(next); + let next = oids.len(); + let blob = *oid_index.entry(oid.to_string()).or_insert_with(|| { + oids.push(oid.to_string()); + next + }); + let files = &mut current.as_mut().ok_or("raw line before commit")?.1; + files.push(FileRev { + path: format!("p{pid}"), + blob, + exec: mode == "100755", + }); + revisions += 1; + } + flush(current.take(), &mut changes); + } + // Blob contents through one `git cat-file --batch` per repository. + let mut blobs: Vec<Option<Vec<u8>>> = vec![None; oids.len()]; + for (name, _) in CORPUS.iter() { + let dir = root.join(format!("{name}.git")); + let wanted: Vec<usize> = changes + .iter() + .filter(|(n, _, _)| n == name) + .flat_map(|(_, _, f)| f.iter().map(|x| x.blob)) + .filter(|&b| blobs[b].is_none()) + .collect::<std::collections::BTreeSet<_>>() + .into_iter() + .collect(); + let mut child = Command::new("git") + .arg("-C") + .arg(&dir) + .args(["cat-file", "--batch"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .map_err(|e| format!("git cat-file: {e}"))?; + let mut stdin = child.stdin.take().expect("piped"); + let list: String = wanted.iter().map(|&b| format!("{}\n", oids[b])).collect(); + let writer = std::thread::spawn(move || stdin.write_all(list.as_bytes())); + let mut out = BufReader::new(child.stdout.take().expect("piped")); + for &b in &wanted { + let mut header = String::new(); + out.read_line(&mut header).map_err(|e| e.to_string())?; + let h: Vec<&str> = header.trim_end().split(' ').collect(); + if h.len() != 3 || h[0] != oids[b] || h[1] != "blob" { + return Err(format!("cat-file header {header:?} for {}", oids[b])); + } + let len: usize = h[2].parse().map_err(|_| "cat-file size")?; + let mut bytes = vec![0u8; len + 1]; + out.read_exact(&mut bytes).map_err(|e| e.to_string())?; + if bytes.pop() != Some(b'\n') { + return Err("cat-file record without newline".into()); + } + if GitOid::compute_blob(&bytes).to_hex() != oids[b] { + return Err(format!("blob {} does not hash to its oid", oids[b])); + } + blobs[b] = Some(bytes); + } + writer.join().expect("writer").map_err(|e| e.to_string())?; + child.wait().map_err(|e| e.to_string())?; + } + let blobs: Vec<Vec<u8>> = blobs + .into_iter() + .map(|b| b.ok_or("blob not read")) + .collect::<Result<_, _>>()?; + let revision_bytes = changes + .iter() + .flat_map(|(_, _, f)| f.iter().map(|x| blobs[x.blob].len() as u64)) + .sum(); + let digests = blobs.iter().map(|b| BlobDigest::compute(b)).collect(); + Ok(Corpus { + changes, + blobs, + digests, + revisions, + revision_bytes, + }) +} + +/// Signed changesets of the corpus, with the bytes of each blob attached only the first +/// time its `BlobDigest` appears (RULE.md section 3). Built once, outside every timed phase. +pub fn build_changesets(c: &Corpus) -> Vec<SignedChange> { + let key = SigningKey::from_bytes(&[0x56; 32]); + let mut seen = std::collections::HashSet::new(); + c.changes + .iter() + .map(|(repo, hash, files)| { + let mut provided = Vec::new(); + // Envelopes require mutations in path order. + let mut files: Vec<&FileRev> = files.iter().collect(); + files.sort_by(|a, b| a.path.cmp(&b.path)); + let mutations = files + .into_iter() + .map(|f| { + let d = c.digests[f.blob]; + if seen.insert(d) { + provided.push((d, c.blobs[f.blob].clone())); + } + PathMutation { + path: f.path.clone(), + op: MutationOp::Upsert { + mode: if f.exec { + FileMode::Executable755 + } else { + FileMode::Regular644 + }, + blob_digest: d, + size_bytes: c.blobs[f.blob].len() as u64, + }, + } + }) + .collect(); + let mut env = ChangesetEnvelope { + version: SYNAPSE_ENVELOPE_VERSION, + repo_id: RepoId::new(format!("aien-spark/{repo}")).expect("repo id"), + base_git_oid: GitOid::compute_blob(hash.as_bytes()), + parent_changesets: vec![], + author_did: String::new(), + idempotency_key: IdempotencyKey::from_label(&format!("x6-{repo}-{hash}")), + created_at_ms: 1000, + intent_summary: format!("{repo} {hash}"), + mutations, + evidence_receipts: vec![], + signature: vec![], + }; + env.sign(&key); + (env, provided) + }) + .collect() +} + +/// Raw samples of one configuration in one repetition. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct RunRaw { + pub config: String, + pub params: ChunkParams, + pub rep: usize, + pub position_in_rep: usize, + pub accepted: usize, + pub ingest_elapsed_ns: u64, + pub ingest_latency_ns: Vec<u64>, + pub ingest_energy: EnergyReading, + /// Bytes appended to the segments during the ingest phase. + pub log_bytes: u64, + /// Whole blobs stored inline plus distinct chunks. + pub content_bytes: u64, + pub inline_blob_bytes: u64, + pub chunks: usize, + pub chunk_bytes: u64, + pub chunked_blobs: usize, + pub batches: u64, + pub reads: usize, + pub read_bytes: u64, + pub read_elapsed_ns: u64, + pub read_ns: Vec<u64>, + pub read_energy: EnergyReading, +} + +/// Raw output of an X6 run. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct X6Raw { + pub corpus: Vec<(String, String)>, + pub changes: usize, + pub revisions: usize, + pub revision_bytes: u64, + pub distinct_blobs: usize, + pub distinct_blob_bytes: u64, + /// Limits raised so that no commit is refused (the largest commit decides). + pub max_paths_per_changeset: usize, + pub max_total_changeset_bytes: u64, + pub idle: EnergyReading, + pub runs: Vec<RunRaw>, +} + +fn run_one( + dir: &Path, + corpus: &Corpus, + sets: &[SignedChange], + limits: &StoreLimits, + order: &[usize], +) -> Result<RunRaw, String> { + let _ = std::fs::remove_dir_all(dir); + let shared = SharedStore::open( + dir, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + RecoveryPolicy::StrictFailClosed, + limits.clone(), + ) + .map_err(|e| format!("open: {e:?}"))?; + let mut latency = Vec::with_capacity(sets.len()); + let window = EnergyWindow::start(); + let t0 = Instant::now(); + for (env, blobs) in sets { + let s = Instant::now(); + match shared.submit(env.clone(), blobs) { + Ok(IngestOutcome::Committed { .. }) => {} + other => return Err(format!("change not committed: {other:?}")), + } + latency.push(s.elapsed().as_nanos() as u64); + } + let ingest_elapsed_ns = t0.elapsed().as_nanos() as u64; + let ingest_energy = window.finish(); + let stats = shared.stats(); + let st = shared.read(); + let log_bytes = st.log_bytes_written(); + let (chunks, chunk_bytes) = st.chunk_storage(); + let inline_blob_bytes = st.inline_blob_bytes(); + let chunked_blobs = corpus + .digests + .iter() + .filter(|d| st.blob_manifest(d).is_some()) + .count(); + // Read phase: every distinct committed blob once, in commit order. + let mut read_ns = Vec::with_capacity(order.len()); + let mut read_bytes = 0u64; + let window = EnergyWindow::start(); + let t0 = Instant::now(); + for &b in order { + let s = Instant::now(); + let got = st + .get_blob_visible(corpus.digests[b], None, None) + .map_err(|e| format!("read: {e:?}"))?; + read_ns.push(s.elapsed().as_nanos() as u64); + if got != corpus.blobs[b] { + return Err(format!( + "blob {} read back different bytes", + corpus.digests[b] + )); + } + read_bytes += got.len() as u64; + } + let read_elapsed_ns = t0.elapsed().as_nanos() as u64; + let read_energy = window.finish(); + drop(st); + drop(shared); + let _ = std::fs::remove_dir_all(dir); + Ok(RunRaw { + config: String::new(), + params: limits.chunking, + rep: 0, + position_in_rep: 0, + accepted: sets.len(), + ingest_elapsed_ns, + ingest_latency_ns: latency, + ingest_energy, + log_bytes, + content_bytes: inline_blob_bytes + chunk_bytes, + inline_blob_bytes, + chunks, + chunk_bytes, + chunked_blobs, + batches: stats.batches, + reads: order.len(), + read_bytes, + read_elapsed_ns, + read_ns, + read_energy, + }) +} + +/// Run X6: `reps` repetitions of every configuration (order rotated by one per +/// repetition) on stores under `scratch`. `only` restricts the configurations (smoke runs). +pub fn run_x6( + corpus_root: &Path, + scratch: &Path, + reps: usize, + idle_s: u64, + only: Option<&[String]>, + log: &mut dyn FnMut(&str), +) -> Result<X6Raw, String> { + let corpus = load_corpus(corpus_root)?; + log(&format!( + "corpus: {} changes, {} revisions, {} bytes, {} distinct blobs", + corpus.changes.len(), + corpus.revisions, + corpus.revision_bytes, + corpus.blobs.len() + )); + let sets = build_changesets(&corpus); + let max_paths = sets + .iter() + .map(|(e, _)| e.mutations.len()) + .max() + .unwrap_or(1); + let max_total = sets + .iter() + .map(|(_, b)| b.iter().map(|(_, x)| x.len() as u64).sum::<u64>()) + .max() + .unwrap_or(0); + let mut order = Vec::new(); + let mut seen = std::collections::HashSet::new(); + for (_, _, files) in &corpus.changes { + for f in files { + if seen.insert(f.blob) { + order.push(f.blob); + } + } + } + let base = StoreLimits { + max_paths_per_changeset: max_paths.max(StoreLimits::default().max_paths_per_changeset), + max_total_changeset_bytes: max_total.max(StoreLimits::default().max_total_changeset_bytes), + ..Default::default() + }; + let configs: Vec<_> = configurations() + .into_iter() + .filter(|(id, _)| only.is_none_or(|o| o.iter().any(|x| x == id))) + .collect(); + let idle = idle_window(Duration::from_secs(idle_s)); + let mut runs = Vec::new(); + for rep in 0..reps { + for pos in 0..configs.len() { + let (id, params) = configs[(pos + rep) % configs.len()]; + let limits = StoreLimits { + chunking: params, + ..base.clone() + }; + let dir = scratch.join(format!("x6-{id}-rep{rep}")); + let mut r = run_one(&dir, &corpus, &sets, &limits, &order)?; + r.config = id.to_string(); + r.rep = rep; + r.position_in_rep = pos; + log(&format!( + "rep {rep} {id}: ingest {:.3} s, log {} B, content {} B, read {:.3} s", + r.ingest_elapsed_ns as f64 / 1e9, + r.log_bytes, + r.content_bytes, + r.read_elapsed_ns as f64 / 1e9 + )); + runs.push(r); + } + } + Ok(X6Raw { + corpus: CORPUS + .iter() + .map(|(n, c)| (n.to_string(), c.to_string())) + .collect(), + changes: corpus.changes.len(), + revisions: corpus.revisions, + revision_bytes: corpus.revision_bytes, + distinct_blobs: corpus.blobs.len(), + distinct_blob_bytes: corpus.blobs.iter().map(|b| b.len() as u64).sum(), + max_paths_per_changeset: base.max_paths_per_changeset, + max_total_changeset_bytes: base.max_total_changeset_bytes, + idle, + runs, + }) +} + +/// Figures of one configuration (medians over the repetitions). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConfigReport { + pub config: String, + pub params: ChunkParams, + pub reps: usize, + /// `W_k`: median over repetitions of ingest wall time / accepted changes, seconds. + pub w_s_per_change: f64, + /// `R_k`: median of read wall time / reads, seconds. + pub r_s_per_read: f64, + /// `S_k`: log bytes of the ingest phase (equal in every repetition, else invalid). + pub s_log_bytes: u64, + pub content_bytes: u64, + pub chunks: usize, + pub chunked_blobs: usize, + pub deterministic: bool, + pub latency: Option<LatencySummary>, + pub read_latency: Option<LatencySummary>, + /// A2 flush bound / `W_k` (fraction of the bound reached, at most 1). + pub flush_bound_fraction: f64, + /// Mean read bytes / 273 GB/s per read, seconds (the index lookup term is not + /// modelled, so this bound is lower than the RULE's), and bound / `R_k`. + pub read_bound_s: f64, + pub read_bound_fraction: f64, + pub ingest_j_per_change: Option<f64>, + pub ingest_j_per_change_above_idle: Option<f64>, + pub read_j_per_read: Option<f64>, + pub read_j_per_read_above_idle: Option<f64>, + pub energy_refusals: Vec<String>, + pub w_ratio: f64, + pub r_ratio: f64, + pub s_ratio: f64, + pub eligible: bool, +} + +/// The decision of RULE.md section 6. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct X6Report { + pub configs: Vec<ConfigReport>, + pub valid: bool, + pub invalid_reasons: Vec<String>, + pub eligible: Vec<String>, + /// Winner id, or `None` (chunking off by default). + pub winner: Option<String>, + pub winner_params: ChunkParams, + pub flush_bound_s: f64, +} + +fn median(mut v: Vec<f64>) -> f64 { + v.sort_by(|a, b| a.total_cmp(b)); + let n = v.len(); + if n % 2 == 1 { + v[n / 2] + } else { + (v[n / 2 - 1] + v[n / 2]) / 2.0 + } +} + +fn median_opt(v: Vec<Option<f64>>) -> Option<f64> { + let v: Option<Vec<f64>> = v.into_iter().collect(); + v.filter(|v| !v.is_empty()).map(median) +} + +/// Apply the decision criterion of RULE.md section 6 to the raw runs. +pub fn decide(raw: &X6Raw) -> X6Report { + let mut by: BTreeMap<String, Vec<&RunRaw>> = BTreeMap::new(); + for r in &raw.runs { + by.entry(r.config.clone()).or_default().push(r); + } + let mut invalid = Vec::new(); + let mut configs = Vec::new(); + for (id, params) in configurations() { + let Some(runs) = by.get(id) else { continue }; + let det = runs + .iter() + .all(|r| (r.log_bytes, r.content_bytes) == (runs[0].log_bytes, runs[0].content_bytes)); + if !det { + invalid.push(format!( + "{id}: log or content bytes differ between repetitions" + )); + } + let w = median( + runs.iter() + .map(|r| r.ingest_elapsed_ns as f64 / 1e9 / r.accepted as f64) + .collect(), + ); + let rr = median( + runs.iter() + .map(|r| r.read_elapsed_ns as f64 / 1e9 / r.reads as f64) + .collect(), + ); + let lat: Vec<u64> = runs + .iter() + .flat_map(|r| r.ingest_latency_ns.iter().map(|n| n / 1000)) + .collect(); + let rlat: Vec<u64> = runs + .iter() + .flat_map(|r| r.read_ns.iter().map(|n| n / 1000)) + .collect(); + let read_bound_s = runs[0].read_bytes as f64 / runs[0].reads as f64 / MEMORY_BW_BPS; + let mut refusals = Vec::new(); + for r in runs { + for e in [&r.ingest_energy, &r.read_energy] { + if let Some(x) = &e.refusal { + refusals.push(format!("rep {}: {x}", r.rep)); + } + } + } + configs.push(ConfigReport { + config: id.to_string(), + params, + reps: runs.len(), + w_s_per_change: w, + r_s_per_read: rr, + s_log_bytes: runs[0].log_bytes, + content_bytes: runs[0].content_bytes, + chunks: runs[0].chunks, + chunked_blobs: runs[0].chunked_blobs, + deterministic: det, + latency: summarize_us(&lat), + read_latency: summarize_us(&rlat), + flush_bound_fraction: (A2_FLUSH_BOUND_S / w).min(1.0), + read_bound_s, + read_bound_fraction: (read_bound_s / rr).min(1.0), + ingest_j_per_change: median_opt( + runs.iter() + .map(|r| r.ingest_energy.pkg_j.map(|j| j / r.accepted as f64)) + .collect(), + ), + ingest_j_per_change_above_idle: median_opt( + runs.iter() + .map(|r| { + r.ingest_energy + .pkg_above_idle_j(&raw.idle) + .map(|j| j / r.accepted as f64) + }) + .collect(), + ), + read_j_per_read: median_opt( + runs.iter() + .map(|r| r.read_energy.pkg_j.map(|j| j / r.reads as f64)) + .collect(), + ), + read_j_per_read_above_idle: median_opt( + runs.iter() + .map(|r| { + r.read_energy + .pkg_above_idle_j(&raw.idle) + .map(|j| j / r.reads as f64) + }) + .collect(), + ), + energy_refusals: refusals, + w_ratio: 0.0, + r_ratio: 0.0, + s_ratio: 0.0, + eligible: false, + }); + } + let c0 = configs.iter().find(|c| c.config == "C0").cloned(); + if c0.is_none() { + invalid.push("control C0 missing".into()); + } + if let Some(c0) = &c0 { + for c in configs.iter_mut() { + c.w_ratio = c.w_s_per_change / c0.w_s_per_change; + c.r_ratio = c.r_s_per_read / c0.r_s_per_read; + c.s_ratio = c.s_log_bytes as f64 / c0.s_log_bytes as f64; + c.eligible = c.config != "C0" + && c.w_s_per_change <= 1.10 * c0.w_s_per_change + && c.r_s_per_read <= 1.25 * c0.r_s_per_read + && (c.s_log_bytes as f64) <= 0.95 * c0.s_log_bytes as f64; + } + } + let valid = invalid.is_empty(); + let eligible: Vec<&ConfigReport> = configs.iter().filter(|c| c.eligible).collect(); + let winner = if valid { + eligible + .iter() + .map(|c| c.s_log_bytes) + .min() + .and_then(|best| { + eligible + .iter() + .filter(|c| (c.s_log_bytes as f64) <= best as f64 * 1.01) + .max_by_key(|c| (c.params.avg_bytes, c.params.threshold_bytes)) + .map(|c| (*c).clone()) + }) + } else { + None + }; + X6Report { + eligible: eligible.iter().map(|c| c.config.clone()).collect(), + winner_params: winner.as_ref().map_or(ChunkParams::OFF, |c| c.params), + winner: winner.map(|c| c.config), + configs, + valid, + invalid_reasons: invalid, + flush_bound_s: A2_FLUSH_BOUND_S, + } +} + +/// Default scratch directory for the stores of a run. +pub fn default_scratch() -> PathBuf { + std::env::temp_dir().join("synapse-x6") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(config: &str, rep: usize, w_ns: u64, r_ns: u64, s: u64) -> RunRaw { + RunRaw { + config: config.into(), + params: configurations() + .into_iter() + .find(|(i, _)| *i == config) + .unwrap() + .1, + rep, + position_in_rep: 0, + accepted: 1000, + ingest_elapsed_ns: w_ns * 1000, + ingest_latency_ns: vec![w_ns; 4], + ingest_energy: EnergyReading::default(), + log_bytes: s, + content_bytes: s / 2, + inline_blob_bytes: 0, + chunks: 0, + chunk_bytes: 0, + chunked_blobs: 0, + batches: 1000, + reads: 100, + read_bytes: 100 * 4096, + read_elapsed_ns: r_ns * 100, + read_ns: vec![r_ns; 4], + read_energy: EnergyReading::default(), + } + } + + fn raw(runs: Vec<RunRaw>) -> X6Raw { + X6Raw { + corpus: vec![], + changes: 1000, + revisions: 0, + revision_bytes: 0, + distinct_blobs: 100, + distinct_blob_bytes: 0, + max_paths_per_changeset: 1, + max_total_changeset_bytes: 1, + idle: EnergyReading::default(), + runs, + } + } + + #[test] + fn x6_decision_follows_the_rule() { + let mut runs = Vec::new(); + for rep in 0..3 { + runs.push(run("C0", rep, 1_000_000, 10_000, 1000)); + // Eligible, smallest S. + runs.push(run("K1", rep, 1_050_000, 11_000, 800)); + // Within 1 % of K1 with a larger avg: wins the tie. + runs.push(run("K4", rep, 1_090_000, 12_000, 805)); + // Too slow to ingest. + runs.push(run("K2", rep, 1_200_000, 10_000, 700)); + // Too slow to read. + runs.push(run("K3", rep, 1_000_000, 13_000, 700)); + // Saves under 5 %. + runs.push(run("K7", rep, 1_000_000, 10_000, 960)); + } + let r = decide(&raw(runs.clone())); + assert!(r.valid); + assert_eq!(r.eligible, vec!["K1".to_string(), "K4".to_string()]); + assert_eq!(r.winner.as_deref(), Some("K4")); + assert_eq!( + r.winner_params, + ChunkParams::candidate(64 * 1024, 16 * 1024) + ); + + // Repetitions that disagree on log bytes make the run invalid: no winner. + let mut bad = runs.clone(); + bad[1].log_bytes += 1; + let r = decide(&raw(bad)); + assert!(!r.valid && r.winner.is_none()); + + // Nothing eligible: chunking stays off. + let only: Vec<RunRaw> = runs + .into_iter() + .filter(|r| r.config == "C0" || r.config == "K7") + .collect(); + let r = decide(&raw(only)); + assert!(r.valid && r.winner.is_none()); + assert_eq!(r.winner_params, ChunkParams::OFF); + } +} diff --git a/crates/synapse-store/src/chunk.rs b/crates/synapse-store/src/chunk.rs new file mode 100644 index 0000000..5cad0a5 --- /dev/null +++ b/crates/synapse-store/src/chunk.rs @@ -0,0 +1,288 @@ +//! Content-defined chunking (ADR 0003 step G2, section 5.9, experiment X6). +//! +//! A blob above [`ChunkParams::threshold_bytes`] is cut into content-defined chunks by a +//! FastCDC-style gear chunker with normalized chunking [S20], and each chunk is stored once +//! per [`ChunkDigest`] inside the segments. A chunk is a storage and transfer unit only: a +//! blob's identity stays its `BlobDigest` over the whole content, so the parameters can +//! change without changing any identity (a store opened with other parameters only +//! deduplicates less against what is already stored). +//! +//! The chunker, the candidates, and the rule that chose the default parameters are fixed in +//! `evidence/g2-content-defined-chunking/x6/RULE.md` (committed before the X6 runs). + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::fmt; +use synapse_core::BlobDigest; + +/// Domain tag of [`ChunkDigest`]. +pub const DOMAIN_CHUNK_V1: &[u8] = b"SYNAPSE_CHUNK_V1\0"; + +/// Seed of the SplitMix64 sequence that fills [`GEAR`] (ASCII `SYNAPSE1`). +pub const GEAR_SEED: u64 = 0x5359_4E41_5053_4531; + +/// Digest of one content-defined chunk of a large blob (CONTEXT.md `ChunkDigest`): +/// `SHA-256("SYNAPSE_CHUNK_V1\0" || u64 LE length || bytes)`. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ChunkDigest(pub [u8; 32]); + +impl ChunkDigest { + pub fn compute(bytes: &[u8]) -> Self { + let mut h = Sha256::new(); + h.update(DOMAIN_CHUNK_V1); + h.update((bytes.len() as u64).to_le_bytes()); + h.update(bytes); + Self(h.finalize().into()) + } + + pub fn to_hex(self) -> String { + hex::encode(self.0) + } +} + +impl fmt::Debug for ChunkDigest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ChunkDigest({})", self.to_hex()) + } +} + +impl fmt::Display for ChunkDigest { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + +const fn splitmix64_table(seed: u64) -> [u64; 256] { + let mut t = [0u64; 256]; + let mut state = seed; + let mut i = 0; + while i < 256 { + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + t[i] = z ^ (z >> 31); + i += 1; + } + t +} + +/// Gear table: the first 256 outputs of SplitMix64 seeded with [`GEAR_SEED`]. +pub const GEAR: [u64; 256] = splitmix64_table(GEAR_SEED); + +/// Chunking parameters of a store. `min`, `avg`, `max` are chunk sizes in bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChunkParams { + /// A blob of at most this many bytes is stored whole; a longer one is chunked. + /// `u64::MAX` turns chunking off. + pub threshold_bytes: u64, + pub min_bytes: u32, + /// Target average chunk size; a power of two. + pub avg_bytes: u32, + pub max_bytes: u32, +} + +impl Default for ChunkParams { + /// The X6 outcome (see `evidence/g2-content-defined-chunking/x6/OUTCOME.md`). + fn default() -> Self { + Self::X6_DEFAULT + } +} + +impl ChunkParams { + /// Chunking off: every blob is stored whole (the A2 behaviour, X6 control C0). + pub const OFF: Self = Self { + threshold_bytes: u64::MAX, + min_bytes: 4 * 1024, + avg_bytes: 16 * 1024, + max_bytes: 64 * 1024, + }; + + /// Parameters chosen by experiment X6 under its pre-registered rule: candidate K1 + /// (T = 16 KiB, min 1 KiB, avg 4 KiB, max 16 KiB), the only eligible candidate + /// (`evidence/g2-content-defined-chunking/x6/RESULTS.md`). + pub const X6_DEFAULT: Self = Self::candidate(16 * 1024, 4 * 1024); + + /// Candidate with `min = avg / 4` and `max = 4 * avg` (the X6 shape). + pub const fn candidate(threshold_bytes: u64, avg_bytes: u32) -> Self { + Self { + threshold_bytes, + min_bytes: avg_bytes / 4, + avg_bytes, + max_bytes: avg_bytes * 4, + } + } + + /// True when a blob of `len` bytes is chunked. + pub fn is_chunked(&self, len: usize) -> bool { + len as u64 > self.threshold_bytes + } + + /// Parameters the chunker accepts: `64 <= min < avg < max`, `avg` a power of two + /// with at least 2^4, and `max` at most 16 MiB. + pub fn validate(&self) -> Result<(), String> { + let ok = self.min_bytes >= 64 + && self.min_bytes < self.avg_bytes + && self.avg_bytes < self.max_bytes + && self.avg_bytes.is_power_of_two() + && self.avg_bytes >= 16 + && self.max_bytes <= 16 * 1024 * 1024; + if ok { + Ok(()) + } else { + Err(format!("invalid chunk parameters {self:?}")) + } + } +} + +/// Length of the first chunk of `src` (the cut rule of the X6 rule, section 1). +pub fn cut(src: &[u8], p: &ChunkParams) -> usize { + let min = p.min_bytes as usize; + if src.len() <= min { + return src.len(); + } + let n = src.len().min(p.max_bytes as usize); + let normal = n.min(p.avg_bytes as usize); + let bits = p.avg_bytes.trailing_zeros(); + let mask_s = !0u64 << (64 - (bits + 2)); + let mask_l = !0u64 << (64 - (bits - 2)); + let mut h = 0u64; + let mut i = min; + while i < normal { + h = (h << 1).wrapping_add(GEAR[src[i] as usize]); + if h & mask_s == 0 { + return i + 1; + } + i += 1; + } + while i < n { + h = (h << 1).wrapping_add(GEAR[src[i] as usize]); + if h & mask_l == 0 { + return i + 1; + } + i += 1; + } + n +} + +/// Byte ranges of the chunks of `data`, in order; they cover `data` exactly. +pub fn chunk_ranges(data: &[u8], p: &ChunkParams) -> Vec<std::ops::Range<usize>> { + let mut out = Vec::with_capacity(data.len() / p.avg_bytes.max(1) as usize + 1); + let mut at = 0; + while at < data.len() { + let len = cut(&data[at..], p); + out.push(at..at + len); + at += len; + } + out +} + +/// One chunked blob: its identity, length, and its chunks in order (digest, length). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChunkManifest { + pub blob: BlobDigest, + pub len: u64, + pub chunks: Vec<(ChunkDigest, u32)>, +} + +/// A blob cut into chunks before it is encoded: its manifest plus the distinct chunks in +/// first-occurrence order with their byte ranges inside the blob. +#[derive(Debug, Clone)] +pub(crate) struct ChunkedBlob { + pub manifest: ChunkManifest, + pub distinct: Vec<(ChunkDigest, std::ops::Range<usize>)>, +} + +/// Cut `data` (whose digest is `blob`) and digest every chunk. +pub(crate) fn chunk_blob(blob: BlobDigest, data: &[u8], p: &ChunkParams) -> ChunkedBlob { + let ranges = chunk_ranges(data, p); + let mut chunks = Vec::with_capacity(ranges.len()); + let mut distinct: Vec<(ChunkDigest, std::ops::Range<usize>)> = Vec::new(); + let mut seen = std::collections::BTreeSet::new(); + for r in ranges { + let d = ChunkDigest::compute(&data[r.clone()]); + chunks.push((d, r.len() as u32)); + if seen.insert(d) { + distinct.push((d, r)); + } + } + ChunkedBlob { + manifest: ChunkManifest { + blob, + len: data.len() as u64, + chunks, + }, + distinct, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gear_table_is_splitmix64_of_the_seed() { + // First SplitMix64 outputs for the seed, computed step by step. + let mut state = GEAR_SEED; + let mut next = || { + state = state.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = state; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + }; + for (i, g) in GEAR.iter().enumerate() { + assert_eq!(*g, next(), "gear entry {i}"); + } + let distinct: std::collections::BTreeSet<_> = GEAR.iter().collect(); + assert_eq!(distinct.len(), 256); + } + + #[test] + fn chunk_ranges_cover_the_data_and_respect_min_and_max() { + let p = ChunkParams::candidate(16 * 1024, 4 * 1024); + p.validate().unwrap(); + let mut x = 0x1234_5678u32; + let data: Vec<u8> = (0..300_000) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x as u8 + }) + .collect(); + let ranges = chunk_ranges(&data, &p); + let mut at = 0; + for (i, r) in ranges.iter().enumerate() { + assert_eq!(r.start, at); + assert!(r.len() <= p.max_bytes as usize); + if i + 1 < ranges.len() { + assert!(r.len() > p.min_bytes as usize, "chunk {i} below min"); + } + at = r.end; + } + assert_eq!(at, data.len()); + // Content-defined: the average is near the target on random data. + let mean = data.len() / ranges.len(); + assert!(mean > 2 * 1024 && mean < 8 * 1024, "mean chunk {mean}"); + // All-zero data never matches the masks: every chunk is max long. + let zeros = vec![0u8; 100_000]; + let z = chunk_ranges(&zeros, &p); + assert!(z[..z.len() - 1] + .iter() + .all(|r| r.len() == p.max_bytes as usize)); + assert!(chunk_ranges(&[], &p).is_empty()); + } + + #[test] + fn invalid_parameters_are_refused() { + assert!(ChunkParams::candidate(16 * 1024, 3000).validate().is_err()); + assert!(ChunkParams { + min_bytes: 8, + ..ChunkParams::candidate(1, 64) + } + .validate() + .is_err()); + assert!(ChunkParams::OFF.validate().is_ok()); + } +} diff --git a/crates/synapse-store/src/g2_tests.rs b/crates/synapse-store/src/g2_tests.rs new file mode 100644 index 0000000..78ba264 --- /dev/null +++ b/crates/synapse-store/src/g2_tests.rs @@ -0,0 +1,855 @@ +//! ADR 0003 G2 content-defined chunking tests (issue #45). +//! +//! Acceptance under test: every blob round-trips byte for byte through chunking with an +//! unchanged `BlobDigest`; deduplication between two revisions that share content +//! follows the rule X6 fixed before its runs (`evidence/g2-content-defined-chunking/x6/ +//! RULE.md` section 5). The expected chunk bytes are computed here from the chunker +//! alone ([`chunk::chunk_ranges`] and [`ChunkDigest::compute`]), never read back from +//! the store under test. + +use super::a1_tests::{copy_fixture, copy_tree, expect}; +use super::tests::{make_signed_changeset, temp_store_dir}; +use super::*; +use ed25519_dalek::SigningKey; +use std::collections::BTreeSet; +use std::process::Command; +use std::sync::Barrier; +use synapse_core::{FileMode, GitOid, PathMutation, SYNAPSE_ENVELOPE_VERSION}; + +/// Chunk parameters of the test stores: X6 candidate K1 (T = 16 KiB, avg 4 KiB). +const P: ChunkParams = ChunkParams::candidate(16 * 1024, 4 * 1024); +const T: usize = 16 * 1024; +const STRICT: RecoveryPolicy = RecoveryPolicy::StrictFailClosed; +const CHILD_ENV: &str = "SYNAPSE_G2_CRASH_CHILD"; + +fn limits_with(chunking: ChunkParams) -> StoreLimits { + StoreLimits { + segment_bytes: 1024 * 1024, + wal_prealloc_bytes: 64 * 1024, + max_blob_bytes: 8 * 1024 * 1024, + max_total_changeset_bytes: 16 * 1024 * 1024, + max_wal_record_bytes: 32 * 1024 * 1024, + chunking, + ..Default::default() + } +} + +fn open_with(dir: &Path, chunking: ChunkParams) -> SynapseStore { + SynapseStore::open( + dir, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + STRICT, + limits_with(chunking), + ) + .unwrap() +} + +fn open(dir: &Path) -> SynapseStore { + open_with(dir, P) +} + +fn key(n: u8) -> SigningKey { + SigningKey::from_bytes(&[n; 32]) +} + +/// Deterministic pseudo-random bytes (xorshift64). +fn random(len: usize, seed: u64) -> Vec<u8> { + let mut x = seed | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 24) as u8 + }) + .collect() +} + +/// A signed changeset upserting every `(path, content)` in `files`. +fn multi( + key: &SigningKey, + label: &str, + files: &[(&str, &[u8])], +) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) { + let mut blobs: Vec<(BlobDigest, Vec<u8>)> = Vec::new(); + let mutations = files + .iter() + .map(|(path, content)| { + let digest = BlobDigest::compute(content); + if !blobs.iter().any(|(d, _)| *d == digest) { + blobs.push((digest, content.to_vec())); + } + PathMutation { + path: path.to_string(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: digest, + size_bytes: content.len() as u64, + }, + } + }) + .collect(); + let mut env = ChangesetEnvelope { + version: SYNAPSE_ENVELOPE_VERSION, + repo_id: RepoId::new("aien-spark/synapse").unwrap(), + base_git_oid: GitOid::compute_blob(b"base"), + parent_changesets: vec![], + author_did: String::new(), + idempotency_key: IdempotencyKey::from_label(label), + created_at_ms: 1000, + intent_summary: format!("G2 {label}"), + mutations, + evidence_receipts: vec![], + signature: vec![], + }; + env.sign(key); + (env, blobs) +} + +fn commit_env(store: &mut SynapseStore, env: ChangesetEnvelope, blobs: &[(BlobDigest, Vec<u8>)]) { + match store.ingest_changeset(env, blobs).unwrap() { + IngestOutcome::Committed { .. } => {} + other => panic!("expected Committed, got {other:?}"), + } +} + +/// Commit `content` as one file; returns its digest. +fn commit_blob( + store: &mut SynapseStore, + key: &SigningKey, + label: &str, + content: &[u8], +) -> BlobDigest { + let (env, blobs) = + make_signed_changeset(key, label, &format!("src/{label}"), content, vec![], 1000); + commit_env(store, env, &blobs); + BlobDigest::compute(content) +} + +/// The distinct chunks of `data` under `p`, from the chunker alone. +fn chunks_of(data: &[u8], p: &ChunkParams) -> BTreeMap<ChunkDigest, u64> { + chunk::chunk_ranges(data, p) + .into_iter() + .map(|r| (ChunkDigest::compute(&data[r.clone()]), r.len() as u64)) + .collect() +} + +/// Bytes of the chunks of `data` not in `known` (the X6 rule, section 5.3). +fn new_chunk_bytes(data: &[u8], known: &BTreeMap<ChunkDigest, u64>) -> u64 { + chunks_of(data, &P) + .iter() + .filter(|(d, _)| !known.contains_key(d)) + .map(|(_, l)| l) + .sum() +} + +/// `blob` reads back as exactly `content`, with the storage form the X6 rule requires. +fn assert_round_trip(store: &SynapseStore, content: &[u8], what: &str) { + let digest = BlobDigest::compute(content); + let back = store.get_blob_visible(digest, None, None).unwrap(); + assert!( + back == content, + "{what}: bytes differ ({} vs {})", + back.len(), + content.len() + ); + assert_eq!(BlobDigest::compute(&back), digest, "{what}: digest changed"); + let m = store.blob_manifest(&digest); + if content.len() > T { + let m = m.unwrap_or_else(|| panic!("{what}: above T but not chunked")); + assert_eq!(m.blob, digest); + assert_eq!(m.len, content.len() as u64); + let ranges = chunk::chunk_ranges(content, &P); + let expect: Vec<(ChunkDigest, u32)> = ranges + .iter() + .map(|r| (ChunkDigest::compute(&content[r.clone()]), r.len() as u32)) + .collect(); + assert_eq!( + m.chunks, expect, + "{what}: manifest is not the chunker's cut" + ); + } else { + assert!(m.is_none(), "{what}: at most T but chunked"); + } +} + +/// The blobs of the round-trip test: edge sizes around T, random, repetitive, zeros, text. +fn round_trip_corpus() -> Vec<(String, Vec<u8>)> { + let text: Vec<u8> = (0..120_000u32) + .flat_map(|i| format!("line {i}: fn f{}() {{}}\n", i % 97).into_bytes()) + .take(150_000) + .collect(); + let pattern: Vec<u8> = random(1000, 5) + .into_iter() + .cycle() + .take(1_000_000) + .collect(); + vec![ + ("empty".into(), vec![]), + ("one".into(), vec![42]), + ("t-minus-1".into(), random(T - 1, 1)), + ("t".into(), random(T, 2)), + ("t-plus-1".into(), random(T + 1, 3)), + ("random-3m".into(), random(3_000_000, 4)), + ("repetitive-1m".into(), pattern), + ("zeros-500k".into(), vec![0u8; 500_000]), + ("text".into(), text), + ("max-chunk-edge".into(), random(P.max_bytes as usize * 3, 6)), + ] +} + +// --- acceptance 1: round trip ------------------------------------------------ + +/// Every blob, at every size class, reads back byte for byte with an unchanged +/// `BlobDigest`: right after commit, after a checkpoint, after reopen from the +/// checkpoint's segment index, and after reopen by replaying frames. +#[test] +fn g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest() { + let dir = temp_store_dir("g2-round-trip"); + let k = key(120); + let corpus = round_trip_corpus(); + let (first, second) = corpus.split_at(6); + { + let mut s = open(&dir); + for (label, content) in first { + commit_blob(&mut s, &k, label, content); + } + for (label, content) in first { + assert_round_trip(&s, content, label); + } + s.checkpoint_and_compact(1000).unwrap(); + for (label, content) in first { + assert_round_trip(&s, content, &format!("{label} after checkpoint")); + } + } + { + let mut s = open(&dir); + for (label, content) in first { + assert_round_trip(&s, content, &format!("{label} after reopen (index)")); + } + for (label, content) in second { + commit_blob(&mut s, &k, label, content); + } + } + let s = open(&dir); + for (label, content) in &corpus { + assert_round_trip(&s, content, &format!("{label} after reopen (replay)")); + } + assert_eq!(s.committed_seq(), WalSeq(corpus.len() as u64)); + let _ = fs::remove_dir_all(&dir); +} + +// --- acceptance 2: deduplication under the X6 rule --------------------------- + +/// Two revisions that share content: the second stores exactly its chunks not already +/// indexed (X6 rule 5.3); an identical revision and a re-provided blob add nothing; a +/// blob of at most T is stored whole (5.1). The same holds against chunks that come +/// from the checkpoint's segment index after reopen. +#[test] +fn g2_dedup_between_two_revisions_follows_the_x6_rule() { + let dir = temp_store_dir("g2-dedup"); + let k = key(121); + let a = random(400_000, 11); + // B: A with 100 bytes inserted in the middle, 50 bytes changed near the start, and + // 30 KB appended. + let mut b = a.clone(); + b.splice(200_000..200_000, random(100, 12)); + b[10_000..10_050].copy_from_slice(&random(50, 13)); + b.extend_from_slice(&random(30_000, 14)); + // C (after reopen): B with its tail cut and a new middle edit. + let mut c = b[..380_000].to_vec(); + c.splice(100_000..100_000, random(64, 15)); + + let mut known = BTreeMap::new(); + { + let mut s = open(&dir); + commit_blob(&mut s, &k, "rev-a", &a); + known.extend(chunks_of(&a, &P)); + let (n0, bytes0) = s.chunk_storage(); + assert_eq!(n0, known.len()); + assert_eq!(bytes0, known.values().sum::<u64>()); + + let expected_b = new_chunk_bytes(&b, &known); + assert!( + expected_b > 0 && expected_b < b.len() as u64 / 4, + "B shares most of A" + ); + let log0 = s.log_bytes_written(); + commit_blob(&mut s, &k, "rev-b", &b); + let (n1, bytes1) = s.chunk_storage(); + assert_eq!(bytes1 - bytes0, expected_b, "B adds exactly its new chunks"); + known.extend(chunks_of(&b, &P)); + assert_eq!(n1, known.len()); + let log_b = s.log_bytes_written() - log0; + assert!( + log_b < expected_b + 64 * 1024, + "log bytes of B ({log_b}) carry only the new chunks ({expected_b}) plus metadata" + ); + + // Identical content under another path, bytes provided again: nothing added. + commit_blob(&mut s, &k, "rev-a-again", &a); + assert_eq!(s.chunk_storage(), (n1, bytes1)); + // Two files of one changeset sharing chunks with each other and with A. + let mut a2 = a.clone(); + a2[300_000..300_010].copy_from_slice(&[7u8; 10]); + let mut a3 = a2.clone(); + a3.extend_from_slice(&random(20_000, 16)); + let mut both = known.clone(); + let expected_23 = new_chunk_bytes(&a2, &both); + both.extend(chunks_of(&a2, &P)); + let expected_23 = expected_23 + new_chunk_bytes(&a3, &both); + let (env, blobs) = multi(&k, "rev-a2-a3", &[("x/a2", &a2), ("x/a3", &a3)]); + commit_env(&mut s, env, &blobs); + assert_eq!( + s.chunk_storage().1 - bytes1, + expected_23, + "chunks shared inside one record" + ); + known = both; + known.extend(chunks_of(&a3, &P)); + + // At most T: stored whole, never cut, also when committed twice. + let small = random(T, 17); + commit_blob(&mut s, &k, "small", &small); + let inline0 = s.inline_blob_bytes(); + assert!(s.blob_manifest(&BlobDigest::compute(&small)).is_none()); + assert_eq!(s.chunk_storage().0, known.len()); + assert!(inline0 >= T as u64); + for (what, content) in [ + ("a", &a), + ("b", &b), + ("a2", &a2), + ("a3", &a3), + ("small", &small), + ] { + assert_round_trip(&s, content, what); + } + s.checkpoint_and_compact(1000).unwrap(); + assert_eq!( + s.chunk_storage().0, + known.len(), + "checkpoint keeps every chunk" + ); + } + let mut s = open(&dir); + assert_eq!( + s.chunk_storage().0, + known.len(), + "chunk index restored from the checkpoint" + ); + let before = s.chunk_storage().1; + let expected_c = new_chunk_bytes(&c, &known); + commit_blob(&mut s, &k, "rev-c", &c); + assert_eq!( + s.chunk_storage().1 - before, + expected_c, + "dedup against indexed chunks" + ); + drop(s); + let s = open(&dir); + for (what, content) in [("a", &a), ("b", &b), ("c", &c)] { + assert_round_trip(&s, content, what); + } + let _ = fs::remove_dir_all(&dir); +} + +/// Records accepted earlier in the same group-commit batch count as indexed (X6 rule +/// 5.3): four revisions sharing content in one batch store each chunk once. +#[test] +fn g2_dedup_inside_one_batch_counts_earlier_records() { + let dir = temp_store_dir("g2-batch"); + let k = key(122); + let base = random(300_000, 21); + let revs: Vec<Vec<u8>> = (0..4u8) + .map(|i| { + let mut r = base.clone(); + r.extend_from_slice(&random(5000, 30 + u64::from(i))); + r + }) + .collect(); + let mut known = BTreeMap::new(); + for r in &revs { + known.extend(chunks_of(r, &P)); + } + let shared = SharedStore::open( + &dir, + FsyncPolicy::GroupCommit { + max_batch_records: 4, + max_batch_delay_us: 5_000_000, + }, + STRICT, + limits_with(P), + ) + .unwrap(); + let inputs: Vec<_> = revs + .iter() + .enumerate() + .map(|(i, r)| { + make_signed_changeset(&k, &format!("b{i}"), &format!("b/{i}"), r, vec![], 1000) + }) + .collect(); + let barrier = Barrier::new(inputs.len()); + std::thread::scope(|sc| { + for (env, blobs) in inputs { + let (shared, barrier) = (&shared, &barrier); + sc.spawn(move || { + barrier.wait(); + assert!(matches!( + shared.submit(env, &blobs).unwrap(), + IngestOutcome::Committed { .. } + )); + }); + } + }); + let stats = shared.stats(); + assert_eq!((stats.batches, stats.records), (1, 4), "one batch"); + { + let st = shared.read(); + assert_eq!( + st.chunk_storage(), + (known.len(), known.values().sum::<u64>()) + ); + let log = st.log_bytes_written(); + assert!( + log < known.values().sum::<u64>() + 64 * 1024, + "the batch carries each chunk once: {log} log bytes for {} chunk bytes", + known.values().sum::<u64>() + ); + } + drop(shared); + let s = open(&dir); + assert_eq!( + s.chunk_storage(), + (known.len(), known.values().sum::<u64>()) + ); + for (i, r) in revs.iter().enumerate() { + assert_round_trip(&s, r, &format!("batch rev {i}")); + } + let _ = fs::remove_dir_all(&dir); +} + +/// The parameters are a storage choice only: a blob stored whole with chunking off is +/// still read whole, and re-providing it once chunking is on adds no chunks; a store +/// opened with other chunk parameters reads everything written with the first ones. +#[test] +fn g2_parameters_change_without_changing_identity() { + let dir = temp_store_dir("g2-params"); + let k = key(123); + let a = random(200_000, 41); + let b = random(200_000, 42); + { + let mut s = open_with(&dir, ChunkParams::OFF); + commit_blob(&mut s, &k, "off-a", &a); + assert!(s.blob_manifest(&BlobDigest::compute(&a)).is_none()); + } + { + let mut s = open(&dir); + commit_blob(&mut s, &k, "on-a", &a); + assert_eq!(s.chunk_storage(), (0, 0), "already stored whole: no chunks"); + commit_blob(&mut s, &k, "on-b", &b); + assert!(s.blob_manifest(&BlobDigest::compute(&b)).is_some()); + } + let other = ChunkParams::candidate(64 * 1024, 16 * 1024); + let s = open_with(&dir, other); + for content in [&a, &b] { + let d = BlobDigest::compute(content); + assert!(s.get_blob_visible(d, None, None).unwrap() == *content); + } + let _ = fs::remove_dir_all(&dir); +} + +// --- fail closed --------------------------------------------------------------- + +/// Index position of a chunk of `blob` (the first one) on disk. +fn first_chunk_loc(store: &SynapseStore, blob: &BlobDigest) -> segment::BlobLoc { + let m = store.blob_manifest(blob).unwrap(); + store.chunk_locations[&m.chunks[0].0] +} + +fn flip_byte(dir: &Path, loc: segment::BlobLoc, at: u64) { + use std::os::unix::fs::FileExt; + let path = dir.join(segment::segment_file_name(loc.segment)); + let f = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .unwrap(); + let mut b = [0u8; 1]; + f.read_exact_at(&mut b, loc.offset + at).unwrap(); + f.write_all_at(&[b[0] ^ 0x40], loc.offset + at).unwrap(); +} + +/// A damaged chunk byte is never served: replay refuses the frame (its payload digest +/// covers the chunk digests and every chunk is checked against its digest), and a chunk +/// the checkpoint vouches for fails the blob read with `BlobDigestMismatch`. +#[test] +fn g2_damaged_chunk_is_refused() { + let k = key(124); + let a = random(100_000, 51); + let da = BlobDigest::compute(&a); + // Replayed frame. + let dir = temp_store_dir("g2-damage-replay"); + let loc = { + let mut s = open(&dir); + commit_blob(&mut s, &k, "dmg", &a); + first_chunk_loc(&s, &da) + }; + flip_byte(&dir, loc, 7); + let Err(err) = SynapseStore::open( + &dir, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + STRICT, + limits_with(P), + ) else { + panic!("open must refuse"); + }; + assert!( + matches!( + err.code, + RefusalCode::BlobDigestMismatch + | RefusalCode::WalCrcMismatch + | RefusalCode::WalTornFrame + ), + "replay must refuse: {err:?}" + ); + let _ = fs::remove_dir_all(&dir); + // Damaged chunk byte with the payload CRC and the frame digest repaired (as an + // adversary, or a CRC collision, would leave it): only the chunk digest catches it. + let dir = temp_store_dir("g2-damage-crc-repaired"); + let (loc, first_chunk_off) = { + let mut s = open(&dir); + commit_blob(&mut s, &k, "dmg", &a); + let off = s.chunk_locations.values().map(|l| l.offset).min().unwrap(); + (first_chunk_loc(&s, &da), off) + }; + assert_eq!(loc.segment, 1); + flip_byte(&dir, loc, 7); + { + let path = dir.join(segment::segment_file_name(1)); + let mut seg = fs::read(&path).unwrap(); + let h0 = wal2::WAL_V2_BATCH_HEADER_LEN; + let p0 = h0 + WAL_HEADER_LEN; + let plen = u32::from_le_bytes(seg[h0 + 48..h0 + 52].try_into().unwrap()) as usize; + let crc = crc32c(&seg[p0..p0 + plen]); + seg[h0 + 52..h0 + 56].copy_from_slice(&crc.to_le_bytes()); + let psha = wal2::chunked_payload_digest(&seg[p0..p0 + plen], first_chunk_off as usize - p0); + let fsha = wal2::frame_digest(&seg[h0..h0 + 56], &psha); + seg[h0 + 56..h0 + 88].copy_from_slice(&fsha); + fs::write(&path, &seg).unwrap(); + } + let Err(err) = SynapseStore::open( + &dir, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + STRICT, + limits_with(P), + ) else { + panic!("open must refuse a chunk whose digest does not match"); + }; + assert_eq!(err.code, RefusalCode::BlobDigestMismatch, "{err:?}"); + let _ = fs::remove_dir_all(&dir); + // Chunk covered by the checkpoint. + let dir = temp_store_dir("g2-damage-index"); + let loc = { + let mut s = open(&dir); + commit_blob(&mut s, &k, "dmg", &a); + s.checkpoint_and_compact(1000).unwrap(); + first_chunk_loc(&s, &da) + }; + flip_byte(&dir, loc, 7); + let s = open(&dir); + assert_eq!( + s.get_blob_visible(da, None, None).unwrap_err().code, + RefusalCode::BlobDigestMismatch + ); + let _ = fs::remove_dir_all(&dir); +} + +/// A frame whose manifest names a chunk that is nowhere indexed is refused at replay. +#[test] +fn g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay() { + let dir = temp_store_dir("g2-orphan-manifest"); + let k = key(125); + let a = random(100_000, 61); + { + let mut s = open(&dir); + commit_blob(&mut s, &k, "base", &a); + // Forge the state of a store that already holds every chunk of A2 (it does not): + // the next record then carries A2's manifest without its chunk bytes. + let mut a2 = a.clone(); + a2.extend_from_slice(&random(40_000, 62)); + let fake = segment::BlobLoc { + segment: 1, + offset: 0, + len: 1, + }; + for (d, l) in chunks_of(&a2, &P) { + s.chunk_locations.entry(d).or_insert(segment::BlobLoc { + len: l as u32, + ..fake + }); + } + commit_blob(&mut s, &k, "forged", &a2); + } + let Err(err) = SynapseStore::open( + &dir, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + STRICT, + limits_with(P), + ) else { + panic!("open must refuse"); + }; + assert_eq!(err.code, RefusalCode::BlobNotFound, "{err:?}"); + let _ = fs::remove_dir_all(&dir); +} + +/// Invalid chunk parameters are refused at open. +#[test] +fn g2_invalid_chunk_parameters_are_refused_at_open() { + let dir = temp_store_dir("g2-bad-params"); + let bad = ChunkParams { + avg_bytes: 3000, + ..P + }; + assert!(SynapseStore::open( + &dir, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + STRICT, + limits_with(bad) + ) + .is_err()); + let _ = fs::remove_dir_all(&dir); +} + +/// Segment index version 2 round-trips chunks and manifests and refuses an orphan chunk, +/// a manifest naming a missing chunk, a manifest whose length disagrees, a chunk after +/// the replay position, and a flipped bit; an index without chunks stays version 1. +#[test] +fn g2_segment_index_v2_round_trips_and_refuses_damage() { + let loc = |segment, offset, len| segment::BlobLoc { + segment, + offset, + len, + }; + let (c1, c2) = (ChunkDigest([1u8; 32]), ChunkDigest([2u8; 32])); + let blob = BlobDigest([9u8; 32]); + let index = segment::SegmentIndex { + binding: [7u8; 32], + replay_segment: 3, + replay_offset: 8192, + entries: [(BlobDigest([3u8; 32]), loc(1, 4096, 100))] + .into_iter() + .collect(), + chunks: [(c1, loc(1, 100, 50)), (c2, loc(2, 0, 70))] + .into_iter() + .collect(), + manifests: [( + blob, + ChunkManifest { + blob, + len: 170, + chunks: vec![(c1, 50), (c2, 70), (c1, 50)], + }, + )] + .into_iter() + .collect(), + }; + let bytes = index.encode(); + assert_eq!(&bytes[4..6], &2u16.to_le_bytes()); + assert_eq!(segment::SegmentIndex::decode(&bytes).unwrap(), index); + let refused = |i: &segment::SegmentIndex, what: &str| { + assert_eq!( + segment::SegmentIndex::decode(&i.encode()).unwrap_err().code, + RefusalCode::CheckpointCorrupt, + "{what}" + ) + }; + let mut orphan = index.clone(); + orphan.chunks.insert(ChunkDigest([4u8; 32]), loc(1, 0, 10)); + refused(&orphan, "orphan chunk"); + let mut missing = index.clone(); + missing.chunks.remove(&c2); + refused(&missing, "missing chunk"); + let mut short = index.clone(); + short.manifests.get_mut(&blob).unwrap().len = 169; + refused(&short, "length mismatch"); + let mut late = index.clone(); + late.chunks.insert(c2, loc(3, 8192, 70)); + refused(&late, "chunk after the replay position"); + for at in [10, 70, bytes.len() - 40] { + let mut b = bytes.clone(); + b[at] ^= 1; + assert!( + segment::SegmentIndex::decode(&b).is_err(), + "bit flip at {at}" + ); + } + let plain = segment::SegmentIndex { + chunks: BTreeMap::new(), + manifests: BTreeMap::new(), + ..index.clone() + }; + assert_eq!(&plain.encode()[4..6], &1u16.to_le_bytes()); + assert_eq!( + segment::SegmentIndex::decode(&plain.encode()).unwrap(), + plain + ); +} + +/// With chunking off the store writes exactly the A2 formats (no chunk flag, segment +/// index version 1), so builds before G2 still open it. +#[test] +fn g2_chunking_off_writes_the_a2_formats() { + let dir = temp_store_dir("g2-off"); + let k = key(126); + { + let mut s = open_with(&dir, ChunkParams::OFF); + commit_blob(&mut s, &k, "big", &random(300_000, 71)); + s.checkpoint_and_compact(1000).unwrap(); + assert_eq!(s.chunk_storage(), (0, 0)); + } + let index = fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap().path()) + .find(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with(segment::SEGMENT_INDEX_PREFIX)) + }) + .unwrap(); + assert_eq!(&fs::read(index).unwrap()[4..6], &1u16.to_le_bytes()); + let _ = fs::remove_dir_all(&dir); +} + +// --- crash --------------------------------------------------------------------- + +fn child_dir() -> Option<PathBuf> { + std::env::var(CHILD_ENV).ok().map(PathBuf::from) +} + +/// A crash after a chunked batch is durable but before the in-memory index is updated +/// keeps every acknowledged change; the pending batch is kept whole and its blob reads +/// back byte for byte. +#[test] +fn g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack() { + let k = key(127); + let revs: Vec<Vec<u8>> = (0..5u64) + .map(|i| { + let mut r = random(150_000, 80); + r.extend_from_slice(&random(9000, 81 + i)); + r + }) + .collect(); + if let Some(dir) = child_dir() { + let mut s = open(&dir); + for (i, r) in revs[..4].iter().enumerate() { + commit_blob(&mut s, &k, &format!("cr-{i}"), r); + if i == 1 { + s.checkpoint_and_compact(1000).unwrap(); + } + } + s.set_fault_injection(FaultInjection::CrashAfterBatchSyncBeforeIndex); + let (env, blobs) = make_signed_changeset(&k, "cr-4", "src/cr-4", &revs[4], vec![], 1000); + let r = s.ingest_changeset(env, &blobs); + panic!("the injected fault did not end the process: {r:?}"); + } + let dir = temp_store_dir("g2-crash"); + let status = Command::new(std::env::current_exe().unwrap()) + .arg("--exact") + .arg("g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack") + .arg("--nocapture") + .env(CHILD_ENV, &dir) + .status() + .unwrap(); + assert_eq!(status.code(), Some(FAULT_CRASH_EXIT_CODE)); + let s = open(&dir); + assert_eq!(s.committed_seq(), WalSeq(5)); + let mut known = BTreeMap::new(); + for (i, r) in revs.iter().enumerate() { + assert_round_trip(&s, r, &format!("rev {i}")); + known.extend(chunks_of(r, &P)); + } + assert_eq!( + s.chunk_storage(), + (known.len(), known.values().sum::<u64>()) + ); + let _ = fs::remove_dir_all(&dir); +} + +// --- old stores ------------------------------------------------------------------ + +/// Stores written before G2 stay readable with chunking on: the A1 fixtures (v1 WAL, +/// single-file WAL v2, blobs as files) and an A2 segment store written by the A2 code +/// itself (`tests/fixtures/g2-a2/segment-store`, generator under +/// `evidence/g2-content-defined-chunking/fixture-generator`). Their blobs read back +/// whole, new chunked blobs land next to them, and everything survives a checkpoint and +/// reopen. +#[test] +fn g2_old_stores_stay_readable() { + let k = key(128); + let big = random(120_000, 91); + for name in ["v1-wal-log", "v1-wal-v2-log"] { + let dir = copy_fixture(name); + let ex = expect(name); + old_store_case(&dir, name, ex.committed_seq, ex.state_root, &k, &big); + } + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/g2-a2/segment-store"); + let dir = temp_store_dir("g2-a2-fixture"); + copy_tree(&src, &dir); + let text = fs::read_to_string(dir.join("EXPECT")).unwrap(); + let _ = fs::remove_file(dir.join("EXPECT")); + let field = |key: &str| { + text.lines() + .find_map(|l| l.strip_prefix(key).map(|v| v.trim().to_string())) + .unwrap() + }; + let seq: u64 = field("committed_seq ").parse().unwrap(); + let root: [u8; 32] = hex::decode(field("state_root ")) + .unwrap() + .try_into() + .unwrap(); + assert!( + segment::list_segments(&dir).unwrap().len() >= 2, + "fixture spans segments" + ); + old_store_case(&dir, "a2-segment-store", seq, root, &k, &big); +} + +fn old_store_case(dir: &Path, name: &str, seq: u64, root: [u8; 32], k: &SigningKey, big: &[u8]) { + let old_blobs = |s: &SynapseStore| -> Vec<BlobDigest> { + let mut v = BTreeSet::new(); + for c in s.list_changesets(None, None, Some(WalSeq(seq))).unwrap() { + for m in &c.envelope.mutations { + if let MutationOp::Upsert { blob_digest, .. } = &m.op { + v.insert(*blob_digest); + } + } + } + v.into_iter().collect() + }; + let check_old = |s: &SynapseStore, what: &str| { + let blobs = old_blobs(s); + assert!(!blobs.is_empty(), "{name}: fixture holds blobs"); + for d in blobs { + let bytes = s.get_blob_visible(d, None, None).unwrap(); + assert_eq!(BlobDigest::compute(&bytes), d, "{name} {what}"); + assert!( + s.blob_manifest(&d).is_none(), + "{name}: old blob stays whole" + ); + } + }; + { + let mut s = open(dir); + assert_eq!(s.committed_seq(), WalSeq(seq), "{name}"); + assert_eq!(s.state_root_digest(None).unwrap(), root, "{name}"); + check_old(&s, "on open"); + commit_blob(&mut s, k, &format!("{name}-g2"), big); + assert_round_trip(&s, big, name); + s.checkpoint_and_compact(1000).unwrap(); + } + let s = open(dir); + assert_eq!(s.committed_seq(), WalSeq(seq + 1), "{name}"); + check_old(&s, "after checkpoint and reopen"); + assert_round_trip(&s, big, name); + let _ = fs::remove_dir_all(dir); +} diff --git a/crates/synapse-store/src/lib.rs b/crates/synapse-store/src/lib.rs index 1d3cb83..f48956f 100644 --- a/crates/synapse-store/src/lib.rs +++ b/crates/synapse-store/src/lib.rs @@ -34,8 +34,11 @@ pub mod blockdev; mod blockdev_a2_suite; #[cfg(test)] mod blockdev_tests; +pub mod chunk; pub mod codec; #[cfg(test)] +mod g2_tests; +#[cfg(test)] mod group_tests; #[cfg(test)] mod j1_corpus; @@ -49,6 +52,7 @@ pub mod wal2; use blockdev::Medium; pub use blockdev::{BlockDeviceConfig, FormatPolicy}; +pub use chunk::{ChunkDigest, ChunkManifest, ChunkParams}; pub use codec::{CheckpointChain, CheckpointState, CodecRefusal, RecordCodec}; pub use revision::{ verify_revision_log, AdmissionAuthority, ChangeStatus, RecordedMarker, RevisionOutcome, @@ -201,6 +205,11 @@ pub struct StoreLimits { /// still goes into one segment on its own. #[serde(default = "default_segment_bytes")] pub segment_bytes: u64, + /// Content-defined chunking of large blobs (ADR 0003 G2): blobs above + /// `chunking.threshold_bytes` are stored as chunks, each once per `ChunkDigest`. + /// Applies to segment stores (group commit) only; the default is the X6 outcome. + #[serde(default)] + pub chunking: ChunkParams, } fn default_segment_bytes() -> u64 { @@ -226,6 +235,7 @@ impl Default for StoreLimits { wal_prealloc_bytes: default_wal_prealloc_bytes(), max_wal_record_bytes: default_max_wal_record_bytes(), segment_bytes: default_segment_bytes(), + chunking: ChunkParams::default(), } } } @@ -526,6 +536,12 @@ pub struct SynapseStore { wal_v2_recovered_end: (u64, u64), /// The blob index: digest to its location inside a segment. blob_locations: BTreeMap<BlobDigest, segment::BlobLoc>, + /// The chunk index (ADR 0003 G2): chunk digest to its location inside a segment. + chunk_locations: BTreeMap<ChunkDigest, segment::BlobLoc>, + /// Chunked blobs: blob digest to its manifest (chunks in order). + blob_chunks: BTreeMap<BlobDigest, ChunkManifest>, + /// Bytes of batches this store appended to its segments since it was opened. + log_bytes_written: u64, /// Set when a failed batch could not be rolled back: every write is refused until reopen. poisoned: Option<String>, /// Codec new WAL records are written with (ADR 0003 A1). @@ -609,6 +625,10 @@ struct BatchOverlay { idempotency: BTreeMap<(RepoId, IdempotencyKey), (WalSeq, ChangesetId)>, changesets: BTreeMap<ChangesetId, RepoId>, blobs: BTreeSet<BlobDigest>, + /// Chunks carried by records accepted earlier in this batch (ADR 0003 G2). + chunks: BTreeSet<ChunkDigest>, + /// Blobs stored as chunks by records accepted earlier in this batch. + chunked_blobs: BTreeSet<BlobDigest>, } /// Result of the stateful half of an ingest. @@ -636,6 +656,8 @@ pub(crate) struct V2Ticket { fault: FaultInjection, base_seq: WalSeq, prev_sha: [u8; 32], + /// Length of the batch written (set by `v2_write`). + batch_len: u64, } impl SynapseStore { @@ -770,6 +792,11 @@ impl SynapseStore { ) -> SynapseResult<Self> { let blobs_dir = root_dir.join("blobs"); let wal_path = root_dir.join("wal.log"); + // ADR 0003 G2: chunk parameters the chunker cannot use are refused, never guessed. + limits + .chunking + .validate() + .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e))?; let mut store = Self { medium, @@ -795,6 +822,9 @@ impl SynapseStore { segment_readers: BTreeMap::new(), wal_v2_recovered_end: (1, 0), blob_locations: BTreeMap::new(), + chunk_locations: BTreeMap::new(), + blob_chunks: BTreeMap::new(), + log_bytes_written: 0, poisoned: None, codec: RecordCodec::BinaryV2, checkpoint_chain: None, @@ -844,6 +874,36 @@ impl SynapseStore { self.checkpoint_chain } + /// Manifest of `blob` when the store holds it as chunks (ADR 0003 G2). + pub fn blob_manifest(&self, blob: &BlobDigest) -> Option<&ChunkManifest> { + self.blob_chunks.get(blob) + } + + /// Chunk storage of the store: (indexed chunks, their total content bytes). + pub fn chunk_storage(&self) -> (usize, u64) { + let bytes = self + .chunk_locations + .values() + .map(|l| u64::from(l.len)) + .sum(); + (self.chunk_locations.len(), bytes) + } + + /// Total content bytes of the whole blobs stored inline in segments. + pub fn inline_blob_bytes(&self) -> u64 { + self.blob_locations.values().map(|l| u64::from(l.len)).sum() + } + + /// Bytes of batches this store appended to its segments since it was opened. + pub fn log_bytes_written(&self) -> u64 { + self.log_bytes_written + } + + /// The chunk parameters in force (invalid parameters were refused at open). + pub fn chunk_params(&self) -> ChunkParams { + self.limits.chunking + } + /// True when this store writes WAL v2 (group commit). pub fn is_wal_v2(&self) -> bool { self.v2_mode @@ -1056,13 +1116,50 @@ impl SynapseStore { }; if let Some(codec) = wal_v2_codec { if clean { + // ADR 0003 G2: a blob above the chunk threshold is cut into chunks; each + // distinct chunk is carried once per record (the store drops the chunks it + // already holds at commit, `conform_v2`). + let params = if limits.chunking.validate().is_ok() { + limits.chunking + } else { + ChunkParams::OFF + }; let mut inline: Vec<(BlobDigest, &[u8])> = Vec::new(); + let mut manifests: Vec<ChunkManifest> = Vec::new(); + let mut chunks: Vec<(ChunkDigest, &[u8])> = Vec::new(); + let mut seen_chunks = BTreeSet::new(); for d in &prepared.new_blobs { - if !inline.iter().any(|(x, _)| x == d) { - inline.push((*d, provided_map[d])); + if inline.iter().any(|(x, _)| x == d) || manifests.iter().any(|m| m.blob == *d) + { + continue; + } + let bytes = provided_map[d]; + if params.is_chunked(bytes.len()) { + let cb = chunk::chunk_blob(*d, bytes, ¶ms); + for (cd, r) in cb.distinct { + if seen_chunks.insert(cd) { + chunks.push((cd, &bytes[r])); + } + } + manifests.push(cb.manifest); + } else { + inline.push((*d, bytes)); } } - prepared.encoded = Some(wal2::encode_record(&prepared.record(), &inline, codec)?); + let record = prepared.record(); + prepared.encoded = Some(if manifests.is_empty() { + wal2::encode_record(&record, &inline, codec)? + } else { + let meta = codec::encode_record_with(&record, codec)?; + wal2::encode_parts( + record.kind_byte(), + codec, + &meta, + &inline, + &manifests, + &chunks, + )? + }); } } else { prepared.provided = provided_map @@ -1098,12 +1195,12 @@ impl SynapseStore { let record = prepared.record(); if self.v2_mode { - self.conform_v2(&mut prepared)?; + self.conform_v2(&mut prepared, &mut BatchOverlay::default())?; let encoded = prepared.encoded.expect("conform_v2 checked it"); let mut ticket = self.v2_begin()?; let result = Self::v2_write(&mut ticket, &[&encoded]); let placed = self.v2_finish(ticket, result)?; - self.apply_v2_ingest(&placed[0], record, &encoded.inline); + self.apply_v2_ingest(&placed[0], record, &encoded); return Ok(IngestOutcome::Committed { wal_seq: placed[0].seq, changeset_id, @@ -1263,6 +1360,7 @@ impl SynapseStore { fault: std::mem::replace(&mut self.fault_injection, FaultInjection::None), base_seq: self.committed_seq, prev_sha: self.last_frame_sha256, + batch_len: 0, }) } @@ -1345,6 +1443,7 @@ impl SynapseStore { // The finished batch is padded to the next 4 KiB after its 8-byte trailer. let batch_len = wal2::align_up((capacity + wal2::WAL_V2_BATCH_TRAILER.len()) as u64); let (segment, base) = ticket.writer.reserve(batch_len, rotation_fault)?; + ticket.batch_len = batch_len; let mut builder = wal2::BatchBuilder::new(segment, base, capacity); let mut seq = ticket.base_seq; let mut prev = ticket.prev_sha; @@ -1390,6 +1489,7 @@ impl SynapseStore { self.committed_seq = last.seq; self.last_frame_sha256 = last.frame_sha256; } + self.log_bytes_written += ticket.batch_len; Ok(placed) } Err(wal2::BatchFailure::RolledBack(e)) => Err(e), @@ -1405,20 +1505,92 @@ impl SynapseStore { &mut self, placed: &wal2::PlacedFrame, record: WalRecord, - inline: &[(BlobDigest, u32, u32)], + enc: &wal2::EncodedRecord, ) { - for &(digest, off, len) in inline { - self.blob_locations - .entry(digest) - .or_insert(segment::BlobLoc { - segment: placed.segment, - offset: placed.payload_offset + u64::from(off), - len, - }); + let loc = |off: u32, len: u32| segment::BlobLoc { + segment: placed.segment, + offset: placed.payload_offset + u64::from(off), + len, + }; + for &(digest, off, len) in &enc.inline { + self.blob_locations.entry(digest).or_insert(loc(off, len)); + } + for &(digest, off, len) in &enc.chunks { + self.chunk_locations.entry(digest).or_insert(loc(off, len)); + } + for m in &enc.manifests { + self.blob_chunks.entry(m.blob).or_insert_with(|| m.clone()); } self.apply_record(placed.seq, record); } + /// Read a chunked blob (ADR 0003 G2): its chunks in manifest order, contiguous chunk + /// runs of one segment in one read, then the `BlobDigest` over the whole content. + fn read_chunked_blob(&self, m: &ChunkManifest) -> SynapseResult<Vec<u8>> { + let digest = m.blob; + let len = usize::try_from(m.len).map_err(|_| { + SynapseError::new(RefusalCode::QuotaPayloadTooLarge, "chunked blob too large") + })?; + let mut out = vec![0u8; len]; + let mut at = 0usize; + // Pending run: (segment, file offset, start in `out`, length). + let mut run: Option<(u64, u64, usize, usize)> = None; + let flush = |run: (u64, u64, usize, usize), out: &mut [u8]| -> SynapseResult<()> { + let (seg, off, start, n) = run; + let f = self.segment_readers.get(&seg).ok_or_else(|| { + SynapseError::new( + RefusalCode::BlobNotFound, + format!("segment {seg} is not open for reads"), + ) + })?; + f.read_into(off, &mut out[start..start + n]).map_err(|e| { + SynapseError::new( + RefusalCode::BlobNotFound, + format!("read chunks of blob {digest} from segment {seg}: {e}"), + ) + }) + }; + for (cd, clen) in &m.chunks { + let loc = self.chunk_locations.get(cd).copied().ok_or_else(|| { + SynapseError::new( + RefusalCode::BlobNotFound, + format!("chunk {cd} of blob {digest} is not indexed"), + ) + })?; + let n = *clen as usize; + if loc.len != *clen || at + n > len { + return Err(SynapseError::new( + RefusalCode::BlobDigestMismatch, + format!("chunk {cd} of blob {digest} has inconsistent length"), + )); + } + run = match run { + Some((seg, off, start, rn)) + if seg == loc.segment && off + rn as u64 == loc.offset => + { + Some((seg, off, start, rn + n)) + } + Some(r) => { + flush(r, &mut out)?; + Some((loc.segment, loc.offset, at, n)) + } + None => Some((loc.segment, loc.offset, at, n)), + }; + at += n; + } + if let Some(r) = run { + flush(r, &mut out)?; + } + let computed = BlobDigest::compute(&out); + if at != len || computed != digest { + return Err(SynapseError::new( + RefusalCode::BlobDigestMismatch, + format!("on-disk chunked blob corruption for {digest}: computed {computed}"), + )); + } + Ok(out) + } + fn read_inline_blob( &self, digest: BlobDigest, @@ -1471,6 +1643,8 @@ impl SynapseStore { replay_segment: 1, replay_offset: 0, entries: BTreeMap::new(), + chunks: BTreeMap::new(), + manifests: BTreeMap::new(), }; let keep = index.write(&self.medium)?; if let Medium::Block(_) = &self.medium { @@ -1758,6 +1932,9 @@ impl SynapseStore { if let Some(&loc) = self.blob_locations.get(&digest) { return self.read_inline_blob(digest, loc); } + if let Some(m) = self.blob_chunks.get(&digest) { + return self.read_chunked_blob(m); + } let path = self.blob_path(digest); let bytes = fs::read(&path).map_err(|_| { SynapseError::new( @@ -1965,7 +2142,27 @@ impl SynapseStore { .filter(|(d, _)| retained_blobs.contains(d)) .map(|(d, l)| (*d, *l)) .collect(), + chunks: BTreeMap::new(), + manifests: self + .blob_chunks + .iter() + .filter(|(d, _)| retained_blobs.contains(d)) + .map(|(d, m)| (*d, m.clone())) + .collect(), }; + // ADR 0003 G2: the chunks the retained chunked blobs name. + let mut index = index; + for m in index.manifests.values() { + for (cd, _) in &m.chunks { + let loc = self.chunk_locations.get(cd).copied().ok_or_else(|| { + SynapseError::new( + RefusalCode::CheckpointCorrupt, + format!("chunk {cd} of retained blob {} is not indexed", m.blob), + ) + })?; + index.chunks.insert(*cd, loc); + } + } let name = index.write(&self.medium)?; if self.fault_injection == FaultInjection::CrashAfterSegmentIndexBeforeCheckpoint { std::process::exit(FAULT_CRASH_EXIT_CODE); @@ -1998,6 +2195,8 @@ impl SynapseStore { self.replace_wal_log_with_segment_marker()?; segment::remove_other_indexes(&self.medium, &name)?; self.blob_locations = index.entries; + self.chunk_locations = index.chunks; + self.blob_chunks = index.manifests; } else { let f = OpenOptions::new() .create(true) @@ -2177,19 +2376,49 @@ impl SynapseStore { } /// Bring a prepared WAL v2 payload to this store's codec (it changes once, at the - /// migration checkpoint, possibly between prepare and commit) and check the cap. - pub(crate) fn conform_v2(&self, p: &mut PreparedIngest) -> SynapseResult<()> { + /// migration checkpoint, possibly between prepare and commit), drop what the store + /// already holds (ADR 0003 G2: a manifest of a blob already stored, a chunk already + /// indexed, counting the records accepted earlier in this batch), and check the cap. + /// On success the record's chunks and chunked blobs join `overlay`. + pub(crate) fn conform_v2( + &self, + p: &mut PreparedIngest, + overlay: &mut BatchOverlay, + ) -> SynapseResult<()> { let enc = p.encoded.as_ref().ok_or_else(|| { SynapseError::new( RefusalCode::IoFailure, "changeset was prepared for WAL v1 but the store writes WAL v2", ) })?; - if enc.codec() != self.codec { + let blob_held = |d: &BlobDigest| { + self.blob_chunks.contains_key(d) + || self.blob_locations.contains_key(d) + || overlay.blobs.contains(d) + }; + let chunk_held = + |d: &ChunkDigest| self.chunk_locations.contains_key(d) || overlay.chunks.contains(d); + let drops = enc.manifests.iter().any(|m| blob_held(&m.blob)) + || enc.chunks.iter().any(|(d, _, _)| chunk_held(d)); + if drops { + let rebuilt = enc.rebuild( + &p.record(), + self.codec, + |m| !blob_held(&m.blob), + |d| !chunk_held(d), + )?; + p.encoded = Some(rebuilt); + } else if enc.codec() != self.codec { let recoded = enc.recode(&p.record(), self.codec)?; p.encoded = Some(recoded); } - self.check_frame_cap(p.encoded.as_ref().map_or(0, |e| e.payload.len())) + let enc = p.encoded.as_ref().expect("set above"); + self.check_frame_cap(enc.payload.len())?; + overlay.chunks.extend(enc.chunks.iter().map(|(d, _, _)| *d)); + overlay + .chunked_blobs + .extend(enc.manifests.iter().map(|m| m.blob)); + Ok(()) } fn append_wal_record( @@ -2822,6 +3051,8 @@ impl SynapseStore { let binding = segment::checkpoint_binding_on(&self.medium)?; let index = segment::SegmentIndex::load_from(&self.medium, &binding)?; self.blob_locations = index.entries.clone(); + self.chunk_locations = index.chunks.clone(); + self.blob_chunks = index.manifests.clone(); if (index.replay_segment, index.replay_offset) != (1, 0) { // The index vouches for every segment byte before its replay position: // those frames are covered by the checkpoint it is bound to. @@ -2972,7 +3203,12 @@ impl SynapseStore { for blob_digest in &fr.record.upsert_blobs() { { let inline = fr.inline.iter().any(|(d, _, _)| d == blob_digest); - if inline || self.blob_locations.contains_key(blob_digest) { + let inline = inline + || fr.manifests.iter().any(|m| m.blob == *blob_digest); + if inline + || self.blob_locations.contains_key(blob_digest) + || self.blob_chunks.contains_key(blob_digest) + { continue; } let raw = fs::read(self.blob_path(*blob_digest)).map_err(|_| { @@ -2997,6 +3233,32 @@ impl SynapseStore { len, }); } + // ADR 0003 G2: the frame's chunks join the chunk index; every chunk a + // manifest names must then be indexed (in this frame or earlier). + for &(d, rel, len) in &fr.chunks { + self.chunk_locations.entry(d).or_insert(segment::BlobLoc { + segment: id, + offset: base + rel, + len, + }); + } + for m in fr.manifests { + for (cd, clen) in &m.chunks { + match self.chunk_locations.get(cd) { + Some(loc) if loc.len == *clen => {} + _ => { + return Err(SynapseError::new( + RefusalCode::BlobNotFound, + format!( + "chunk {cd} of blob {} missing during WAL v2 replay at {}", + m.blob, fr.seq + ), + )) + } + } + } + self.blob_chunks.entry(m.blob).or_insert(m); + } self.committed_seq = fr.seq; self.last_frame_sha256 = fr.frame_sha256; self.apply_record(fr.seq, fr.record); diff --git a/crates/synapse-store/src/revision.rs b/crates/synapse-store/src/revision.rs index b39a192..cb27da4 100644 --- a/crates/synapse-store/src/revision.rs +++ b/crates/synapse-store/src/revision.rs @@ -1308,7 +1308,7 @@ impl crate::SynapseStore { let placed = self.v2_finish(ticket, result)?; let seq = placed[0].seq; self.refuse_misplaced(checked_at, seq)?; - self.apply_v2_ingest(&placed[0], record, &encoded.inline); + self.apply_v2_ingest(&placed[0], record, &encoded); return Ok(seq); } if let Some(err) = diff --git a/crates/synapse-store/src/segment.rs b/crates/synapse-store/src/segment.rs index 9d14765..8df6dd4 100644 --- a/crates/synapse-store/src/segment.rs +++ b/crates/synapse-store/src/segment.rs @@ -25,6 +25,15 @@ //! `"SYNAPSE_SEGMENT_INDEX_V1\0" || every preceding byte`. `binding` is the digest of the //! checkpoint file the index belongs to ([`checkpoint_binding`]), so an index written //! just before a crash that kept the older checkpoint is never used with it. +//! * Chunks (ADR 0003 G2): an index whose checkpoint retains chunked blobs has version 2: +//! the version 1 layout up to the blob entries, then `u64 chunk_count | chunk_count x +//! (chunk_digest[32] | u64 segment | u64 offset | u32 len) | u64 manifest_count | +//! manifest_count x (blob_digest[32] | u64 len | u32 n | n x (chunk_digest[32] | u32 len))` +//! before the trailing digest; chunks and manifests in strictly increasing digest order, +//! every chunk named by a manifest and before the replay position, every manifest length +//! the sum of its chunks. An index without chunks stays version 1, so a store that never +//! chunked stays readable by builds before G2; builds before G2 refuse one that did +//! (`CheckpointCorrupt` for the index, `WalFlagsNonZero` for its chunked frames). use super::*; use std::os::unix::fs::FileExt; @@ -40,6 +49,8 @@ pub const SEGMENT_INDEX_PREFIX: &str = "wal.v2.index."; pub const SEGMENT_INDEX_MAGIC: [u8; 4] = *b"SSX1"; /// Segment index format version. pub const SEGMENT_INDEX_VERSION: u16 = 1; +/// Segment index format version with chunks and manifests (ADR 0003 G2). +pub const SEGMENT_INDEX_VERSION_CHUNKS: u16 = 2; /// Domain tag of the segment index trailer digest. pub const DOMAIN_SEGMENT_INDEX: &[u8] = b"SYNAPSE_SEGMENT_INDEX_V1\0"; /// Domain tag of the checkpoint binding digest. @@ -141,6 +152,10 @@ pub(crate) struct SegmentIndex { /// Locations of the blobs the checkpoint retains that live in segment bytes before /// the replay position. pub entries: BTreeMap<BlobDigest, BlobLoc>, + /// Locations of the chunks the retained chunked blobs name (ADR 0003 G2; version 2). + pub chunks: BTreeMap<ChunkDigest, BlobLoc>, + /// Manifests of the retained chunked blobs (version 2). + pub manifests: BTreeMap<BlobDigest, ChunkManifest>, } fn index_corrupt(what: &str) -> SynapseError { @@ -163,21 +178,48 @@ impl SegmentIndex { format!("{SEGMENT_INDEX_PREFIX}{}", hex::encode(&binding[..8])) } + /// Encoded index: version 1 when it holds no chunks (readable by pre-G2 builds), + /// version 2 otherwise. pub fn encode(&self) -> Vec<u8> { + let v2 = !self.chunks.is_empty() || !self.manifests.is_empty(); let mut b = Vec::with_capacity(INDEX_HEADER_LEN + self.entries.len() * INDEX_ENTRY_LEN + 32); b.extend_from_slice(&SEGMENT_INDEX_MAGIC); - b.extend_from_slice(&SEGMENT_INDEX_VERSION.to_le_bytes()); + let version = if v2 { + SEGMENT_INDEX_VERSION_CHUNKS + } else { + SEGMENT_INDEX_VERSION + }; + b.extend_from_slice(&version.to_le_bytes()); b.extend_from_slice(&0u16.to_le_bytes()); b.extend_from_slice(&self.binding); b.extend_from_slice(&self.replay_segment.to_le_bytes()); b.extend_from_slice(&self.replay_offset.to_le_bytes()); b.extend_from_slice(&(self.entries.len() as u64).to_le_bytes()); - for (d, loc) in &self.entries { - b.extend_from_slice(&d.0); + let put_loc = |b: &mut Vec<u8>, d: &[u8; 32], loc: &BlobLoc| { + b.extend_from_slice(d); b.extend_from_slice(&loc.segment.to_le_bytes()); b.extend_from_slice(&loc.offset.to_le_bytes()); b.extend_from_slice(&loc.len.to_le_bytes()); + }; + for (d, loc) in &self.entries { + put_loc(&mut b, &d.0, loc); + } + if v2 { + b.extend_from_slice(&(self.chunks.len() as u64).to_le_bytes()); + for (d, loc) in &self.chunks { + put_loc(&mut b, &d.0, loc); + } + b.extend_from_slice(&(self.manifests.len() as u64).to_le_bytes()); + for m in self.manifests.values() { + b.extend_from_slice(&m.blob.0); + b.extend_from_slice(&m.len.to_le_bytes()); + b.extend_from_slice(&(m.chunks.len() as u32).to_le_bytes()); + for (d, l) in &m.chunks { + b.extend_from_slice(&d.0); + b.extend_from_slice(&l.to_le_bytes()); + } + } } let sha = index_digest(&b); b.extend_from_slice(&sha); @@ -196,7 +238,13 @@ impl SegmentIndex { if body[0..4] != SEGMENT_INDEX_MAGIC { return Err(index_corrupt("bad magic")); } - if u16::from_le_bytes([body[4], body[5]]) != SEGMENT_INDEX_VERSION || body[6..8] != [0, 0] { + let version = u16::from_le_bytes([body[4], body[5]]); + let v2 = match version { + SEGMENT_INDEX_VERSION => false, + SEGMENT_INDEX_VERSION_CHUNKS => true, + _ => return Err(index_corrupt("unsupported version or reserved bytes")), + }; + if body[6..8] != [0, 0] { return Err(index_corrupt("unsupported version or reserved bytes")); } let u64_at = |at: usize| u64::from_le_bytes(body[at..at + 8].try_into().expect("8")); @@ -204,21 +252,19 @@ impl SegmentIndex { let replay_segment = u64_at(40); let replay_offset = u64_at(48); let count = u64_at(56); - let expected = (count as u128) * INDEX_ENTRY_LEN as u128 + INDEX_HEADER_LEN as u128; - if expected != body.len() as u128 { - return Err(index_corrupt("entry count does not match the length")); - } if replay_segment == 0 || replay_offset % wal2::WAL_V2_ALIGN != 0 { return Err(index_corrupt("invalid replay position")); } - let mut entries = BTreeMap::new(); - let mut prev: Option<BlobDigest> = None; - for e in body[INDEX_HEADER_LEN..].as_chunks::<INDEX_ENTRY_LEN>().0 { - let d = BlobDigest(e[0..32].try_into().expect("32")); - if prev.is_some_and(|p| p >= d) { - return Err(index_corrupt("entries not in strictly increasing order")); + let mut at = INDEX_HEADER_LEN; + let take = |at: &mut usize, n: u128| -> SynapseResult<&[u8]> { + if n > (body.len() - *at) as u128 { + return Err(index_corrupt("entry count does not match the length")); } - prev = Some(d); + let s = &body[*at..*at + n as usize]; + *at += n as usize; + Ok(s) + }; + let check_loc = |e: &[u8]| -> SynapseResult<BlobLoc> { let loc = BlobLoc { segment: u64::from_le_bytes(e[32..40].try_into().expect("8")), offset: u64::from_le_bytes(e[40..48].try_into().expect("8")), @@ -230,13 +276,87 @@ impl SegmentIndex { if loc.segment == 0 || end.is_none() || !before_replay { return Err(index_corrupt("entry outside the covered segment bytes")); } - entries.insert(d, loc); + Ok(loc) + }; + let region = take(&mut at, count as u128 * INDEX_ENTRY_LEN as u128)?; + let mut entries = BTreeMap::new(); + let mut prev: Option<BlobDigest> = None; + for e in region.as_chunks::<INDEX_ENTRY_LEN>().0 { + let d = BlobDigest(e[0..32].try_into().expect("32")); + if prev.is_some_and(|p| p >= d) { + return Err(index_corrupt("entries not in strictly increasing order")); + } + prev = Some(d); + entries.insert(d, check_loc(e)?); + } + let mut chunks = BTreeMap::new(); + let mut manifests = BTreeMap::new(); + if v2 { + let n = u64::from_le_bytes(take(&mut at, 8)?.try_into().expect("8")); + let region = take(&mut at, n as u128 * INDEX_ENTRY_LEN as u128)?; + let mut prev: Option<ChunkDigest> = None; + for e in region.as_chunks::<INDEX_ENTRY_LEN>().0 { + let d = ChunkDigest(e[0..32].try_into().expect("32")); + if prev.is_some_and(|p| p >= d) { + return Err(index_corrupt("chunks not in strictly increasing order")); + } + prev = Some(d); + chunks.insert(d, check_loc(e)?); + } + let n = u64::from_le_bytes(take(&mut at, 8)?.try_into().expect("8")); + let mut prev: Option<BlobDigest> = None; + let mut referenced = BTreeSet::new(); + for _ in 0..n { + let h = take(&mut at, 44)?; + let blob = BlobDigest(h[0..32].try_into().expect("32")); + let len = u64::from_le_bytes(h[32..40].try_into().expect("8")); + let k = u32::from_le_bytes(h[40..44].try_into().expect("4")); + if prev.is_some_and(|p| p >= blob) { + return Err(index_corrupt("manifests not in strictly increasing order")); + } + prev = Some(blob); + let region = take(&mut at, k as u128 * 36)?; + let mut list = Vec::with_capacity(k as usize); + let mut sum = 0u64; + for e in region.as_chunks::<36>().0 { + let d = ChunkDigest(e[0..32].try_into().expect("32")); + let l = u32::from_le_bytes(e[32..36].try_into().expect("4")); + if chunks.get(&d).is_none_or(|loc: &BlobLoc| loc.len != l) || l == 0 { + return Err(index_corrupt("manifest names a chunk the index lacks")); + } + referenced.insert(d); + sum += u64::from(l); + list.push((d, l)); + } + if k == 0 || sum != len { + return Err(index_corrupt("manifest length does not match its chunks")); + } + manifests.insert( + blob, + ChunkManifest { + blob, + len, + chunks: list, + }, + ); + } + if referenced.len() != chunks.len() { + return Err(index_corrupt("chunk named by no manifest")); + } + if chunks.is_empty() { + return Err(index_corrupt("version 2 index without chunks")); + } + } + if at != body.len() { + return Err(index_corrupt("entry count does not match the length")); } Ok(Self { binding, replay_segment, replay_offset, entries, + chunks, + manifests, }) } @@ -550,4 +670,18 @@ impl SegReader { SegReader::Block(dev, id) => dev.read_segment_at(*id, offset, len), } } + + /// Fill `buf` from `offset` of the segment (ADR 0003 G2 chunk runs). + pub fn read_into(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { + match self { + SegReader::File(f) => f.read_exact_at(buf, offset), + SegReader::Block(dev, id) => { + let len = u32::try_from(buf.len()).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "chunk run too large") + })?; + buf.copy_from_slice(&dev.read_segment_at(*id, offset, len)?); + Ok(()) + } + } + } } diff --git a/crates/synapse-store/src/segment_tests.rs b/crates/synapse-store/src/segment_tests.rs index 971cb15..3dc67f6 100644 --- a/crates/synapse-store/src/segment_tests.rs +++ b/crates/synapse-store/src/segment_tests.rs @@ -679,6 +679,8 @@ fn a2_segment_index_round_trips_and_refuses_damage() { ] .into_iter() .collect(), + chunks: BTreeMap::new(), + manifests: BTreeMap::new(), }; let bytes = index.encode(); assert_eq!(segment::SegmentIndex::decode(&bytes).unwrap(), index); diff --git a/crates/synapse-store/src/shared.rs b/crates/synapse-store/src/shared.rs index 923ff53..14e769c 100644 --- a/crates/synapse-store/src/shared.rs +++ b/crates/synapse-store/src/shared.rs @@ -379,7 +379,7 @@ impl SharedStore { for (i, p) in batch.iter_mut().enumerate() { let mut pl = st.plan_ingest(&p.prepared, &overlay); if matches!(pl, Planned::Accept) { - if let Err(error) = st.conform_v2(&mut p.prepared) { + if let Err(error) = st.conform_v2(&mut p.prepared, &mut overlay) { pl = Planned::Refused { error, depends_on_batch: false, @@ -454,7 +454,7 @@ impl SharedStore { for (k, &i) in accepted.iter().enumerate() { let p = &batch[i].prepared; let enc = p.encoded.as_ref().expect("checked above"); - st.apply_v2_ingest(&placed[k], p.record(), &enc.inline); + st.apply_v2_ingest(&placed[k], p.record(), enc); outcomes.push(IngestOutcome::Committed { wal_seq: placed[k].seq, changeset_id: p.changeset_id, diff --git a/crates/synapse-store/src/wal2.rs b/crates/synapse-store/src/wal2.rs index b163102..35b99b8 100644 --- a/crates/synapse-store/src/wal2.rs +++ b/crates/synapse-store/src/wal2.rs @@ -25,6 +25,12 @@ //! SHA-256("SYNAPSE_WAL_FRAME_V2\0" || header[0..56] || payload_sha256)` with //! `payload_sha256 = SHA-256("SYNAPSE_WAL_PAYLOAD_V2\0" || payload)`, so the payload //! digest is computed by the submitter in parallel and the writer hashes 120 bytes. +//! * Chunked frames (ADR 0003 G2, flag [`WAL_FLAG_CHUNKED`]): after the inline blobs the +//! payload carries the manifests of its chunked blobs, a chunk table, and the chunk +//! bytes (layout at [`encode_parts`]). Its `payload_sha256` is +//! `SHA-256("SYNAPSE_WAL_PAYLOAD_CHUNKED_V1\0" || u64 LE payload length || payload up to +//! the chunk bytes)`: the chunk bytes are bound through the chunk digests in the table, +//! and recovery verifies every chunk against its digest before the frame digest. //! * `seq`, `prev_frame_sha256` and the hash chain continue across v1 and v2 frames. //! //! Recovery applies a batch only when every frame in it validates (all or nothing). @@ -62,17 +68,35 @@ pub(crate) fn align_up(x: u64) -> u64 { x.div_ceil(WAL_V2_ALIGN) * WAL_V2_ALIGN } +/// Frame flags bit: the payload carries content-defined chunks and chunk manifests (ADR +/// 0003 G2). The other flag bits still name the record codec. Binaries that predate G2 +/// refuse the bit (`WalFlagsNonZero`) instead of misreading the payload. +pub const WAL_FLAG_CHUNKED: u8 = 0x02; +/// Domain tag of the payload digest of a chunked payload. +pub const DOMAIN_WAL_PAYLOAD_CHUNKED_V1: &[u8] = b"SYNAPSE_WAL_PAYLOAD_CHUNKED_V1\0"; + +/// Codec and chunk flag declared by a v2 frame header flags byte. +pub(crate) fn parse_frame_flags(flags: u8) -> Option<(RecordCodec, bool)> { + let chunked = flags & WAL_FLAG_CHUNKED != 0; + RecordCodec::from_frame_flags(flags & !WAL_FLAG_CHUNKED).map(|c| (c, chunked)) +} + /// A record encoded for WAL v2 before the critical section (payload, its digest, CRC). #[derive(Debug, Clone)] pub(crate) struct EncodedRecord { pub kind: u8, - /// Frame header flags byte: the codec of the record metadata. + /// Frame header flags byte: the codec of the record metadata, plus + /// [`WAL_FLAG_CHUNKED`] when the payload carries chunk manifests. pub flags: u8, pub payload: Vec<u8>, pub payload_sha256: [u8; 32], pub payload_crc32c: u32, /// Inline blobs: (digest, byte offset inside the payload, length). pub inline: Vec<(BlobDigest, u32, u32)>, + /// Manifests of the chunked blobs this record stores (ADR 0003 G2). + pub manifests: Vec<ChunkManifest>, + /// Chunks carried by this record: (digest, byte offset inside the payload, length). + pub chunks: Vec<(ChunkDigest, u32, u32)>, } pub(crate) fn payload_digest(payload: &[u8]) -> [u8; 32] { @@ -82,6 +106,18 @@ pub(crate) fn payload_digest(payload: &[u8]) -> [u8; 32] { h.finalize().into() } +/// Payload digest of a chunked payload: the prefix before the chunk bytes, which holds +/// the chunk table (every chunk's `ChunkDigest` and length), is hashed; the chunk bytes +/// themselves are bound through their digests (verified on decode and on every read), +/// so dropping an already stored chunk never re-hashes the others. +pub(crate) fn chunked_payload_digest(payload: &[u8], prefix_len: usize) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(DOMAIN_WAL_PAYLOAD_CHUNKED_V1); + h.update((payload.len() as u64).to_le_bytes()); + h.update(&payload[..prefix_len]); + h.finalize().into() +} + fn too_large(what: &str) -> SynapseError { SynapseError::new( RefusalCode::QuotaPayloadTooLarge, @@ -89,83 +125,148 @@ fn too_large(what: &str) -> SynapseError { ) } -/// Encode `record` with `blobs` stored inline. +fn len32(n: usize, what: &str) -> SynapseResult<[u8; 4]> { + Ok(u32::try_from(n).map_err(|_| too_large(what))?.to_le_bytes()) +} + +/// Encode `record` with `blobs` stored inline (no chunks). pub(crate) fn encode_record( record: &WalRecord, blobs: &[(BlobDigest, &[u8])], codec: RecordCodec, ) -> SynapseResult<EncodedRecord> { let meta = codec::encode_record_with(record, codec)?; + encode_parts(record.kind_byte(), codec, &meta, blobs, &[], &[]) +} + +/// Encode a record whose metadata is `meta`: whole blobs inline, then (when `manifests` +/// is not empty, with [`WAL_FLAG_CHUNKED`]) the manifests, the chunk table, and the chunk +/// bytes. Layout of a chunked payload, little-endian: +/// `u32 meta_len | meta | u32 blob_count | (digest[32] | u32 len | bytes)* | +/// u32 manifest_count | (blob_digest[32] | u64 blob_len | u32 n | n x (chunk_digest[32] | +/// u32 len))* | u32 chunk_count | chunk_count x (chunk_digest[32] | u32 len) | +/// chunk bytes in table order`. +pub(crate) fn encode_parts( + kind: u8, + codec: RecordCodec, + meta: &[u8], + blobs: &[(BlobDigest, &[u8])], + manifests: &[ChunkManifest], + chunks: &[(ChunkDigest, &[u8])], +) -> SynapseResult<EncodedRecord> { + let chunked = !manifests.is_empty(); + debug_assert!(chunked || chunks.is_empty(), "chunks without a manifest"); let blob_bytes: usize = blobs.iter().map(|(_, b)| 36 + b.len()).sum(); - let mut payload = Vec::with_capacity(8 + meta.len() + blob_bytes); - payload.extend_from_slice( - &u32::try_from(meta.len()) - .map_err(|_| too_large("record metadata"))? - .to_le_bytes(), - ); - payload.extend_from_slice(&meta); - payload.extend_from_slice( - &u32::try_from(blobs.len()) - .map_err(|_| too_large("blob count"))? - .to_le_bytes(), - ); + let manifest_bytes: usize = manifests.iter().map(|m| 44 + 36 * m.chunks.len()).sum(); + let chunk_bytes: usize = chunks.iter().map(|(_, b)| 36 + b.len()).sum(); + let mut payload = + Vec::with_capacity(16 + meta.len() + blob_bytes + manifest_bytes + chunk_bytes); + payload.extend_from_slice(&len32(meta.len(), "record metadata")?); + payload.extend_from_slice(meta); + payload.extend_from_slice(&len32(blobs.len(), "blob count")?); let mut inline = Vec::with_capacity(blobs.len()); for (digest, bytes) in blobs { - let len = u32::try_from(bytes.len()).map_err(|_| too_large("blob"))?; payload.extend_from_slice(&digest.0); - payload.extend_from_slice(&len.to_le_bytes()); + payload.extend_from_slice(&len32(bytes.len(), "blob")?); let off = u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; payload.extend_from_slice(bytes); - inline.push((*digest, off, len)); + inline.push((*digest, off, bytes.len() as u32)); } + let mut placed_chunks = Vec::with_capacity(chunks.len()); + let prefix_len = if chunked { + payload.extend_from_slice(&len32(manifests.len(), "manifest count")?); + for m in manifests { + payload.extend_from_slice(&m.blob.0); + payload.extend_from_slice(&m.len.to_le_bytes()); + payload.extend_from_slice(&len32(m.chunks.len(), "manifest length")?); + for (d, l) in &m.chunks { + payload.extend_from_slice(&d.0); + payload.extend_from_slice(&l.to_le_bytes()); + } + } + payload.extend_from_slice(&len32(chunks.len(), "chunk count")?); + for (d, b) in chunks { + payload.extend_from_slice(&d.0); + payload.extend_from_slice(&len32(b.len(), "chunk")?); + } + let prefix_len = payload.len(); + for (d, b) in chunks { + let off = u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; + payload.extend_from_slice(b); + placed_chunks.push((*d, off, b.len() as u32)); + } + Some(prefix_len) + } else { + None + }; u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; Ok(EncodedRecord { - kind: record.kind_byte(), - flags: codec.frame_flags(), - payload_sha256: payload_digest(&payload), + kind, + flags: codec.frame_flags() | if chunked { WAL_FLAG_CHUNKED } else { 0 }, + payload_sha256: match prefix_len { + Some(p) => chunked_payload_digest(&payload, p), + None => payload_digest(&payload), + }, payload_crc32c: crc32c(&payload), payload, inline, + manifests: manifests.to_vec(), + chunks: placed_chunks, }) } impl EncodedRecord { /// Codec of the record metadata. pub fn codec(&self) -> RecordCodec { - RecordCodec::from_frame_flags(self.flags).expect("encoded with a known codec") + parse_frame_flags(self.flags) + .expect("encoded with a known codec") + .0 + } + + /// The same record with its metadata encoded as `codec`, keeping only the manifests + /// `keep_manifest` accepts and the chunks `keep_chunk` accepts. Used when a store + /// migrates between prepare and commit, and to drop chunks (or whole manifests) the + /// store already holds (ADR 0003 G2). + pub fn rebuild( + &self, + record: &WalRecord, + codec: RecordCodec, + keep_manifest: impl Fn(&ChunkManifest) -> bool, + keep_chunk: impl Fn(&ChunkDigest) -> bool, + ) -> SynapseResult<Self> { + let meta = codec::encode_record_with(record, codec)?; + let slice = |off: u32, len: u32| &self.payload[off as usize..(off + len) as usize]; + let blobs: Vec<(BlobDigest, &[u8])> = self + .inline + .iter() + .map(|&(d, o, l)| (d, slice(o, l))) + .collect(); + let manifests: Vec<ChunkManifest> = self + .manifests + .iter() + .filter(|m| keep_manifest(m)) + .cloned() + .collect(); + let referenced: BTreeSet<ChunkDigest> = manifests + .iter() + .flat_map(|m| m.chunks.iter().map(|(d, _)| *d)) + .collect(); + let chunks: Vec<(ChunkDigest, &[u8])> = self + .chunks + .iter() + .filter(|(d, _, _)| referenced.contains(d) && keep_chunk(d)) + .map(|&(d, o, l)| (d, slice(o, l))) + .collect(); + encode_parts(self.kind, codec, &meta, &blobs, &manifests, &chunks) } - /// The same record with its metadata re-encoded as `codec` (inline blobs kept, their - /// offsets shifted). Used when a store migrates between prepare and commit. + /// The same record with its metadata re-encoded as `codec` (inline blobs, manifests, + /// and chunks kept). pub fn recode(&self, record: &WalRecord, codec: RecordCodec) -> SynapseResult<Self> { if self.codec() == codec { return Ok(self.clone()); } - let old_meta = u32::from_le_bytes(self.payload[0..4].try_into().expect("4 bytes")) as usize; - let meta = codec::encode_record_with(record, codec)?; - let rest = &self.payload[4 + old_meta..]; - let mut payload = Vec::with_capacity(4 + meta.len() + rest.len()); - payload.extend_from_slice( - &u32::try_from(meta.len()) - .map_err(|_| too_large("record metadata"))? - .to_le_bytes(), - ); - payload.extend_from_slice(&meta); - payload.extend_from_slice(rest); - u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; - let shift = |off: u32| (off as usize - 4 - old_meta + 4 + meta.len()) as u32; - Ok(Self { - kind: self.kind, - flags: codec.frame_flags(), - payload_sha256: payload_digest(&payload), - payload_crc32c: crc32c(&payload), - inline: self - .inline - .iter() - .map(|(d, o, l)| (*d, shift(*o), *l)) - .collect(), - payload, - }) + self.rebuild(record, codec, |_| true, |_| true) } } @@ -174,6 +275,12 @@ pub(crate) struct DecodedPayload { pub record: WalRecord, /// Inline blobs: (digest, byte offset inside the payload, length). pub inline: Vec<(BlobDigest, u32, u32)>, + /// Chunk manifests (chunked payloads only). + pub manifests: Vec<ChunkManifest>, + /// Chunks carried by the payload: (digest, byte offset inside the payload, length). + pub chunks: Vec<(ChunkDigest, u32, u32)>, + /// Length of the hashed prefix of a chunked payload (`None` for a plain one). + pub prefix_len: Option<usize>, } fn corrupt(seq: WalSeq, what: &str) -> SynapseError { @@ -183,11 +290,15 @@ fn corrupt(seq: WalSeq, what: &str) -> SynapseError { ) } -/// Decode a v2 payload, verifying every inline blob digest. +/// Decode a v2 payload, verifying every inline blob digest and every chunk digest. A +/// chunked payload must list each carried chunk once, carry only chunks its manifests +/// name, and state manifests whose chunk lengths add up to the blob length. Manifest +/// chunks the payload does not carry must already be stored (the caller checks). pub(crate) fn decode_payload( seq: WalSeq, payload: &[u8], codec: RecordCodec, + chunked: bool, cap: u64, ) -> SynapseResult<DecodedPayload> { let rd_u32 = |at: usize| -> SynapseResult<u32> { @@ -196,6 +307,13 @@ pub(crate) fn decode_payload( .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) .ok_or_else(|| corrupt(seq, "truncated length field")) }; + let rd_digest = |at: usize, what: &str| -> SynapseResult<[u8; 32]> { + Ok(payload + .get(at..at + 32) + .ok_or_else(|| corrupt(seq, what))? + .try_into() + .expect("32 bytes")) + }; let meta_len = rd_u32(0)? as usize; let meta = payload .get(4..4 + meta_len) @@ -216,17 +334,12 @@ pub(crate) fn decode_payload( at += 4; let mut inline = Vec::with_capacity(count.min(4096)); for _ in 0..count { - let digest_bytes: [u8; 32] = payload - .get(at..at + 32) - .ok_or_else(|| corrupt(seq, "truncated blob digest"))? - .try_into() - .expect("32 bytes"); + let digest = BlobDigest(rd_digest(at, "truncated blob digest")?); let len = rd_u32(at + 32)? as usize; let start = at + 36; let bytes = payload .get(start..start + len) .ok_or_else(|| corrupt(seq, "truncated blob bytes"))?; - let digest = BlobDigest(digest_bytes); if BlobDigest::compute(bytes) != digest { return Err(SynapseError::new( RefusalCode::BlobDigestMismatch, @@ -236,10 +349,106 @@ pub(crate) fn decode_payload( inline.push((digest, start as u32, len as u32)); at = start + len; } + let mut manifests = Vec::new(); + let mut chunks = Vec::new(); + let mut prefix_len = None; + if chunked { + let malformed = |what: &str| { + SynapseError::new( + RefusalCode::WalRecordMalformed, + format!("chunked WAL v2 payload at {seq}: {what}"), + ) + }; + let m_count = rd_u32(at)? as usize; + at += 4; + if m_count == 0 { + return Err(malformed("chunk flag set without a manifest")); + } + let mut named = BTreeSet::new(); + for _ in 0..m_count { + let blob = BlobDigest(rd_digest(at, "truncated manifest")?); + let blob_len = u64::from_le_bytes( + payload + .get(at + 32..at + 40) + .ok_or_else(|| corrupt(seq, "truncated manifest length"))? + .try_into() + .expect("8 bytes"), + ); + let n = rd_u32(at + 40)? as usize; + at += 44; + if n == 0 || n > payload.len() / 36 + 1 { + return Err(malformed("manifest chunk count out of range")); + } + let mut list = Vec::with_capacity(n); + let mut total = 0u64; + for _ in 0..n { + let d = ChunkDigest(rd_digest(at, "truncated manifest entry")?); + let l = rd_u32(at + 32)?; + if l == 0 { + return Err(malformed("empty chunk in a manifest")); + } + total += u64::from(l); + named.insert(d); + list.push((d, l)); + at += 36; + } + if total != blob_len { + return Err(malformed( + "manifest chunk lengths do not add up to the blob", + )); + } + manifests.push(ChunkManifest { + blob, + len: blob_len, + chunks: list, + }); + } + let c_count = rd_u32(at)? as usize; + at += 4; + if c_count > payload.len() / 36 + 1 { + return Err(malformed("chunk count out of range")); + } + let mut table = Vec::with_capacity(c_count); + let mut carried = BTreeSet::new(); + for _ in 0..c_count { + let d = ChunkDigest(rd_digest(at, "truncated chunk table")?); + let l = rd_u32(at + 32)?; + if l == 0 || !carried.insert(d) || !named.contains(&d) { + return Err(malformed( + "chunk table entry empty, repeated, or named by no manifest", + )); + } + table.push((d, l)); + at += 36; + } + prefix_len = Some(at); + for (d, l) in table { + let bytes = payload + .get(at..at + l as usize) + .ok_or_else(|| corrupt(seq, "truncated chunk bytes"))?; + if ChunkDigest::compute(bytes) != d { + return Err(SynapseError::new( + RefusalCode::BlobDigestMismatch, + format!("chunk {d} corrupt in WAL v2 frame {seq}"), + )); + } + chunks.push((d, at as u32, l)); + at += l as usize; + } + } if at != payload.len() { - return Err(corrupt(seq, "trailing bytes after the last inline blob")); + return Err(corrupt( + seq, + "trailing bytes after the last inline blob or chunk", + )); } - Ok(DecodedPayload { record, inline }) + Ok(DecodedPayload { + record, + inline, + manifests, + chunks, + prefix_len, + }) } /// Build the 88-byte v2 frame header and its chain digest. @@ -694,6 +903,10 @@ pub(crate) struct RecoveredFrame { pub record: WalRecord, /// Inline blobs: (digest, absolute file offset, length). pub inline: Vec<(BlobDigest, u64, u32)>, + /// Chunk manifests (ADR 0003 G2). + pub manifests: Vec<ChunkManifest>, + /// Chunks carried by the frame: (digest, absolute file offset, length). + pub chunks: Vec<(ChunkDigest, u64, u32)>, } /// Validate the batch at `off`; on success return its frames and the aligned next offset. @@ -752,7 +965,7 @@ pub(crate) fn validate_batch( format!("frame version {version} inside a WAL v2 batch at offset {at}"), )); } - let codec = RecordCodec::from_frame_flags(h[7]).ok_or_else(|| { + let (codec, chunked) = parse_frame_flags(h[7]).ok_or_else(|| { SynapseError::new( RefusalCode::WalFlagsNonZero, format!("unknown WAL flags {} at offset {at}", h[7]), @@ -798,13 +1011,27 @@ pub(crate) fn validate_batch( ), )); } - if frame_digest(&h[0..56], &payload_digest(payload)) != stored_sha { + // A chunked payload's digest covers the prefix before its chunk bytes, so it is + // decoded (every chunk digest verified) before the chain digest is checked. + let decoded = if chunked { + Some(decode_payload(seq, payload, codec, true, cap)?) + } else { + None + }; + let payload_sha = match decoded.as_ref().and_then(|d| d.prefix_len) { + Some(p) => chunked_payload_digest(payload, p), + None => payload_digest(payload), + }; + if frame_digest(&h[0..56], &payload_sha) != stored_sha { return Err(SynapseError::new( RefusalCode::WalChainMismatch, format!("WAL frame_sha256 mismatch at {seq}"), )); } - let decoded = decode_payload(seq, payload, codec, cap)?; + let decoded = match decoded { + Some(d) => d, + None => decode_payload(seq, payload, codec, false, cap)?, + }; if decoded.record.kind_byte() != h[6] { return Err(match codec { RecordCodec::JsonV1 => corrupt(seq, "record kind byte does not match payload"), @@ -824,6 +1051,12 @@ pub(crate) fn validate_batch( .into_iter() .map(|(d, o, l)| (d, (p_start + o as usize) as u64, l)) .collect(), + manifests: decoded.manifests, + chunks: decoded + .chunks + .into_iter() + .map(|(d, o, l)| (d, (p_start + o as usize) as u64, l)) + .collect(), }); expected_seq = seq.next(); prev_sha = stored_sha; diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/EXPECT b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/EXPECT new file mode 100644 index 0000000..3ef469f --- /dev/null +++ b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/EXPECT @@ -0,0 +1,3 @@ +committed_seq 12 +state_root 106012bf1eb901fc53a33fead0ee97cbf5f4335978d03731f5bb0a270d437366 +written_by A2 commit 6431fcf (synapse-store segment store) diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/checkpoint.v1 b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/checkpoint.v1 new file mode 100644 index 0000000..728ddac --- /dev/null +++ b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/checkpoint.v1 @@ -0,0 +1 @@ +{"version":2,"checkpoint_seq":0,"anchor_frame_sha256":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"changesets":{},"idempotency_index":{},"blob_first_visible_seq":{},"github_projections":{},"canonical_heads":{}} \ No newline at end of file diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/checkpoint.v2 b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/checkpoint.v2 new file mode 100644 index 0000000..b333127 Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/checkpoint.v2 differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.log new file mode 100644 index 0000000..bd77c1f Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000002.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000002.log new file mode 100644 index 0000000..aa7aad6 Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000002.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000003.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000003.log new file mode 100644 index 0000000..b5f086e Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000003.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000004.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000004.log new file mode 100644 index 0000000..03f78aa Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000004.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000005.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000005.log new file mode 100644 index 0000000..b14ff58 Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000005.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000006.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000006.log new file mode 100644 index 0000000..636b64f Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000006.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000007.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000007.log new file mode 100644 index 0000000..18198da Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000007.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000008.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000008.log new file mode 100644 index 0000000..cb5dadf Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.000008.log differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.index.16b4b4c99057b8af b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.index.16b4b4c99057b8af new file mode 100644 index 0000000..92e3a25 Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.index.16b4b4c99057b8af differ diff --git a/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.log b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.log new file mode 100644 index 0000000..9e75eb1 Binary files /dev/null and b/crates/synapse-store/tests/fixtures/g2-a2/segment-store/wal.v2.log differ diff --git a/docs/G2_CONTENT_DEFINED_CHUNKING.md b/docs/G2_CONTENT_DEFINED_CHUNKING.md new file mode 100644 index 0000000..c2ec94f --- /dev/null +++ b/docs/G2_CONTENT_DEFINED_CHUNKING.md @@ -0,0 +1,94 @@ +# G2: Content-Defined Chunking + +ADR 0003 section 9 step G2 (issue #45), design in section 5.9, parameters chosen by experiment X6 +(section 6.4). A blob above a threshold is cut into content-defined chunks by a FastCDC-style gear +chunker and stored in the segments as chunks, one copy per `ChunkDigest`. A blob's identity stays its +`BlobDigest` over the whole content (CONTEXT.md), so changing the parameters never changes an identity. + +Based on A2 (PR #77, merged) and B1 (PR #81, merged); revision records (B1) still store their blobs whole. + +## 1. Design + +- **Chunker** (`crates/synapse-store/src/chunk.rs`, fixed by `evidence/g2-content-defined-chunking/x6/ + RULE.md` before its runs): gear table from SplitMix64 (seed `SYNAPSE1`), rolling hash + `h = (h << 1) + G[byte]`, normalized cut (`bits + 2` mask below the average, `bits - 2` above), skip to + `min`, cut at `max`. `ChunkDigest = SHA-256("SYNAPSE_CHUNK_V1\0" || u64 LE length || bytes)`. + Written in-house; no new crates. +- **Parameters** `StoreLimits.chunking` (`ChunkParams`): a blob of at most `threshold_bytes` is stored + whole, a longer one is chunked. Invalid parameters are refused at open. Default is the X6 winner K1: + T = 16 KiB, min 1 KiB, avg 4 KiB, max 16 KiB. `ChunkParams::OFF` turns chunking off. +- **Chunked WAL v2 frames** (frame flag `0x02`, `wal2.rs`): after the inline blobs the payload carries + manifests (blob digest, length, chunk list), a chunk table, and the chunk bytes. The payload digest + covers everything before the chunk bytes; the chunk bytes are bound through their digests, and + recovery verifies every chunk against its `ChunkDigest` before the frame digest. +- **Commit** (`conform_v2`): chunks already in the chunk index, or carried by an earlier record of the + same batch, are dropped from the frame; a manifest of a blob already stored is dropped. A frame holds + only new chunk bytes (RULE.md section 5.3). +- **Reads**: the blob's chunks in manifest order, contiguous runs of one segment in a single read, then + the `BlobDigest` over the reassembled bytes (`BlobDigestMismatch` on any difference). +- **Index**: replay rebuilds the chunk index and manifests (and refuses a manifest naming a chunk that + is nowhere indexed). The checkpoint segment index is version 2 only when it holds chunks; otherwise it + stays version 1. +- **Old stores**: whole-blob stores (A1 files, A2 segments) read as before; a blob already stored whole + is never re-chunked. + +## 2. Acceptance and Tests + +Tests in `crates/synapse-store/src/g2_tests.rs`; expected chunk bytes are computed from the chunker alone. + +| Acceptance item | Test | What it shows | +| :--- | :--- | :--- | +| Every blob round-trips byte for byte with unchanged `BlobDigest` | `g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest` | Sizes 0, 1, T-1, T, T+1, 3 MB random, repetitive, zeros, text; read back after commit, checkpoint, reopen from the index, reopen by replay; manifest equals the chunker's cut, blobs at most T stay whole | +| Dedup between two revisions follows the X6 rule | `g2_dedup_between_two_revisions_follows_the_x6_rule` | Revision B stores exactly its chunks not already indexed; an identical revision adds nothing; chunks shared inside one record; a blob of at most T is not cut; same after checkpoint and reopen | +| Dedup inside a batch | `g2_dedup_inside_one_batch_counts_earlier_records` | Four revisions in one group-commit batch store each chunk once | +| Parameters change without changing identity | `g2_parameters_change_without_changing_identity` | OFF-then-K1 stores and a store opened with other parameters read everything | +| Fail closed | `g2_damaged_chunk_is_refused`, `g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay`, `g2_invalid_chunk_parameters_are_refused_at_open`, `g2_segment_index_v2_round_trips_and_refuses_damage` | A damaged chunk byte (also with CRC and frame digest repaired) is refused at replay or read; orphan manifests, bad parameters and malformed index v2 are refused | +| Crash | `g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack` | Process crash after a chunked batch is durable: every acknowledged change survives, the pending one reads back | +| Old stores readable | `g2_old_stores_stay_readable`, `g2_chunking_off_writes_the_a2_formats` | A1 fixtures and an A2 segment store written by the A2 code (`tests/fixtures/g2-a2`, generator in `evidence/.../fixture-generator`); OFF writes the A2 formats | + +### 2.1 Red before green + +`evidence/g2-content-defined-chunking/red-green/`: `red-a2-compile.txt` (the G2 tests do not build on +A2 `6431fcf`), `red-a2-behaviour.txt` (on A2, revision B of a 430 KB blob sharing all but about 30 KB +with A appends 434,176 log bytes), `mutation-M1.txt` to `mutation-M8.txt` (`run-mutations.sh`: each +defect put back makes at least one test fail; `green.txt` is the clean run): + +| Mutation | Defect put back | Tests that fail | +| :--- | :--- | :--- | +| M1 | No dedup against the chunk index | 4 | +| M2 | Checkpoint index drops chunks and manifests | 6 | +| M3 | Replay accepts manifests with unindexed chunks | 1 | +| M4 | Threshold off by one (T bytes chunked) | 2 | +| M5 | Chunked read skips the `BlobDigest` check | 1 | +| M6 | Earlier records of a batch do not count as indexed | 1 | +| M7 | Replay forgets manifests | 5 | +| M8 | WAL decode skips the chunk digest check | 1 | + +## 3. Experiment X6 and Measurement + +Rule: `evidence/g2-content-defined-chunking/x6/RULE.md`, committed alone before any run. Results and +decision: `x6/RESULTS.md`. Real AIEN histories (1,037 changes, 24,093 revisions, 433.8 MB); eight +configurations, three repetitions, order rotated. **K1 wins** (the only eligible candidate): 20.7 % fewer +log bytes than no chunking (329,252,864 vs 415,395,840), 1.095 times the seconds per accepted change +(2.133 ms vs 1.947 ms; the limit was 1.10, a thin margin on a shared host), 1.068 times the seconds per +read. Against the A2 flush bound of 1.006 ms, K1 reaches 0.471 of the bound at one agent (no chunking: +0.516). Joules per change from the SoC package meter are inside the noise above idle (RESULTS.md). + +## 4. Deviations from ADR Section 5.9 + +- `ChunkDigest` lives in `synapse-store`, not `synapse-core`, to keep this change out of the envelope + work (B1) running in parallel; it can move later. +- A small blob (at most T) that is provided again is stored again, as in A2 (the rule applies dedup to + blobs above T and to blobs already stored by `BlobDigest`). +- No format marker bump: builds before G2 fail closed on chunked frames (`WalFlagsNonZero`) and chunked + segment indexes (`CheckpointCorrupt`); a store that never chunked stays readable by them. +- Chunked payload digest covers the prefix and the chunk digests, not every chunk byte, so that + recovery can name the damaged chunk (`BlobDigestMismatch`). + +## 5. Limits + +- X6 is one agent, warm page cache, shared host, single run of three repetitions; K1 vs the ingest limit + is within host noise (UNVERIFIED on a quiet host). +- Chunk bytes are not reclaimed (no garbage collection before K1). +- No cold-read or multi-agent measurement with chunking; energy is SoC package only, NVMe UNMEASURED. +- Power-loss behaviour is UNVERIFIED (as A2). diff --git a/evidence/g2-content-defined-chunking/fixture-generator/Cargo.lock b/evidence/g2-content-defined-chunking/fixture-generator/Cargo.lock new file mode 100644 index 0000000..d2988dd --- /dev/null +++ b/evidence/g2-content-defined-chunking/fixture-generator/Cargo.lock @@ -0,0 +1,437 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "g2-a2-fixture-generator" +version = "0.1.0" +dependencies = [ + "ed25519-dalek", + "hex", + "synapse-core", + "synapse-store", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", + "sha2-asm", +] + +[[package]] +name = "sha2-asm" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b845214d6175804686b2bd482bcffe96651bb2d1200742b712003504a2dac1ab" +dependencies = [ + "cc", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synapse-core" +version = "0.1.0" +dependencies = [ + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha1", + "sha2", +] + +[[package]] +name = "synapse-store" +version = "0.1.0" +dependencies = [ + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha2", + "synapse-core", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/evidence/g2-content-defined-chunking/fixture-generator/Cargo.toml b/evidence/g2-content-defined-chunking/fixture-generator/Cargo.toml new file mode 100644 index 0000000..4f721e6 --- /dev/null +++ b/evidence/g2-content-defined-chunking/fixture-generator/Cargo.toml @@ -0,0 +1,21 @@ +# Generator of the A2 segment-store fixture used by `g2_old_stores_stay_readable` +# (crates/synapse-store/tests/fixtures/g2-a2/segment-store). It links the A2 store code +# itself, not the G2 code: before running, check out the A2 commit (6431fcf, "docs(store): +# A2 segment store design ...") as a git worktree named `a2` next to this clone: +# git worktree add ../a2 <A2 commit> +# cargo run --offline --manifest-path evidence/g2-content-defined-chunking/fixture-generator/Cargo.toml -- <out dir> +# Not a workspace member (it has its own [workspace] table). +[package] +name = "g2-a2-fixture-generator" +version = "0.1.0" +edition = "2021" +license = "AGPL-3.0-or-later" +publish = false + +[workspace] + +[dependencies] +ed25519-dalek = { version = "2.2", default-features = false, features = ["std", "fast"] } +hex = "0.4" +synapse-core = { path = "../../../../a2/crates/synapse-core" } +synapse-store = { path = "../../../../a2/crates/synapse-store" } diff --git a/evidence/g2-content-defined-chunking/fixture-generator/src/main.rs b/evidence/g2-content-defined-chunking/fixture-generator/src/main.rs new file mode 100644 index 0000000..fc635a4 --- /dev/null +++ b/evidence/g2-content-defined-chunking/fixture-generator/src/main.rs @@ -0,0 +1,90 @@ +//! Writes an A2 segment store (64 KiB segments, blobs of 20 to 40 KB stored whole in the +//! segments, a checkpoint with its version 1 segment index, then frames after it) with +//! the A2 store code, plus `EXPECT` (committed sequence and state root). + +use ed25519_dalek::SigningKey; +use std::path::PathBuf; +use synapse_core::{ + BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey, MutationOp, PathMutation, + RepoId, SYNAPSE_ENVELOPE_VERSION, +}; +use synapse_store::{FsyncPolicy, RecoveryPolicy, StoreLimits, SynapseStore}; + +fn bytes(len: usize, seed: u64) -> Vec<u8> { + let mut x = seed | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + b'a' + ((x >> 24) % 26) as u8 + }) + .collect() +} + +fn main() { + let out = PathBuf::from(std::env::args().nth(1).expect("usage: generator <out dir>")); + assert!(!out.exists(), "{} exists", out.display()); + let limits = StoreLimits { + segment_bytes: 64 * 1024, + wal_prealloc_bytes: 16 * 1024, + ..Default::default() + }; + let mut store = SynapseStore::open( + &out, + FsyncPolicy::GROUP_COMMIT_DEFAULT, + RecoveryPolicy::StrictFailClosed, + limits, + ) + .unwrap(); + let key = SigningKey::from_bytes(&[0xA2; 32]); + for i in 0..12u64 { + let files: Vec<(String, Vec<u8>)> = (0..1 + i % 2) + .map(|f| (format!("src/f{i}-{f}.rs"), bytes(20_000 + (i as usize * 1700) % 20_000, 100 * i + f))) + .collect(); + let blobs: Vec<(BlobDigest, Vec<u8>)> = files + .iter() + .map(|(_, c)| (BlobDigest::compute(c), c.clone())) + .collect(); + let mut env = ChangesetEnvelope { + version: SYNAPSE_ENVELOPE_VERSION, + repo_id: RepoId::new("aien-spark/synapse").unwrap(), + base_git_oid: GitOid::compute_blob(b"base"), + parent_changesets: vec![], + author_did: String::new(), + idempotency_key: IdempotencyKey::from_label(&format!("a2-fixture-{i}")), + created_at_ms: 1000 + i, + intent_summary: format!("A2 fixture change {i}"), + mutations: files + .iter() + .map(|(p, c)| PathMutation { + path: p.clone(), + op: MutationOp::Upsert { + mode: FileMode::Regular644, + blob_digest: BlobDigest::compute(c), + size_bytes: c.len() as u64, + }, + }) + .collect(), + evidence_receipts: vec![], + signature: vec![], + }; + env.sign(&key); + store.ingest_changeset(env, &blobs).unwrap(); + if i == 7 { + store.checkpoint_and_compact(1000).unwrap(); + } + } + let root = store.state_root_digest(None).unwrap(); + let seq = store.committed_seq(); + drop(store); + std::fs::write( + out.join("EXPECT"), + format!( + "committed_seq {}\nstate_root {}\nwritten_by A2 commit 6431fcf (synapse-store segment store)\n", + seq.0, + hex::encode(root) + ), + ) + .unwrap(); +} diff --git a/evidence/g2-content-defined-chunking/red-green/green.txt b/evidence/g2-content-defined-chunking/red-green/green.txt new file mode 100644 index 0000000..ece2888 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/green.txt @@ -0,0 +1,14 @@ +# Green: the G2 tests on feat/adr0003-g2 (implementation in this branch). +# cargo test --locked -p synapse-store --lib g2_tests +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... ok +test g2_tests::g2_damaged_chunk_is_refused ... ok +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... ok +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... ok +test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 56 filtered out; finished in 1.02s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M1.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M1.txt new file mode 100644 index 0000000..491acd0 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M1.txt @@ -0,0 +1,21 @@ +## mutation M1: commit keeps every chunk (no deduplication against the chunk index) +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... FAILED +test g2_tests::g2_parameters_change_without_changing_identity ... FAILED +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... FAILED +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... FAILED +test g2_tests::g2_damaged_chunk_is_refused ... ok +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... ok +thread 'g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay' (1255908) panicked at crates/synapse-store/src/g2_tests.rs:599:9: +open must refuse +thread 'g2_tests::g2_parameters_change_without_changing_identity' (1255910) panicked at crates/synapse-store/src/g2_tests.rs:448:9: +assertion `left == right` failed: already stored whole: no chunks +thread 'g2_tests::g2_dedup_inside_one_batch_counts_earlier_records' (1255905) panicked at crates/synapse-store/src/g2_tests.rs:413:9: +the batch carries each chunk once: 1245184 log bytes for 313525 chunk bytes +thread 'g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule' (1255904) panicked at crates/synapse-store/src/g2_tests.rs:284:9: +log bytes of B (438272) carry only the new chunks (43960) plus metadata +test result: FAILED. 7 passed; 4 failed; 0 ignored; 0 measured; 56 filtered out; finished in 1.05s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M2.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M2.txt new file mode 100644 index 0000000..71a5f12 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M2.txt @@ -0,0 +1,20 @@ +## mutation M2: the checkpoint segment index drops chunks and manifests +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... FAILED +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_old_stores_stay_readable ... FAILED +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... ok +test g2_tests::g2_damaged_chunk_is_refused ... FAILED +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... FAILED +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... FAILED +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... FAILED +thread 'g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage' (1256359) panicked at crates/synapse-store/src/g2_tests.rs:657:5: +thread 'g2_tests::g2_old_stores_stay_readable' (1256357) panicked at crates/synapse-store/src/g2_tests.rs:149:59: +thread 'g2_tests::g2_damaged_chunk_is_refused' (1256351) panicked at crates/synapse-store/src/g2_tests.rs:560:5: +thread 'g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack' (1256350) panicked at crates/synapse-store/src/g2_tests.rs:44:6: +thread 'g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule' (1256352) panicked at crates/synapse-store/src/g2_tests.rs:335:5: +assertion `left == right` failed: chunk index restored from the checkpoint +thread 'g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest' (1256354) panicked at crates/synapse-store/src/g2_tests.rs:149:59: +test result: FAILED. 5 passed; 6 failed; 0 ignored; 0 measured; 56 filtered out; finished in 0.57s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M3.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M3.txt new file mode 100644 index 0000000..fe8e3b6 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M3.txt @@ -0,0 +1,15 @@ +## mutation M3: replay accepts a manifest whose chunks are not indexed +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... FAILED +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... ok +test g2_tests::g2_damaged_chunk_is_refused ... ok +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... ok +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... ok +thread 'g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay' (1257286) panicked at crates/synapse-store/src/g2_tests.rs:599:9: +open must refuse +test result: FAILED. 10 passed; 1 failed; 0 ignored; 0 measured; 56 filtered out; finished in 1.02s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M4.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M4.txt new file mode 100644 index 0000000..85884bc --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M4.txt @@ -0,0 +1,16 @@ +## mutation M4: a blob of exactly T bytes is chunked (threshold off by one) +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... ok +test g2_tests::g2_damaged_chunk_is_refused ... ok +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... FAILED +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... FAILED +test g2_tests::g2_old_stores_stay_readable ... ok +thread 'g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule' (1257660) panicked at crates/synapse-store/src/g2_tests.rs:315:9: +thread 'g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest' (1257662) panicked at crates/synapse-store/src/g2_tests.rs:172:9: +t: at most T but chunked +test result: FAILED. 9 passed; 2 failed; 0 ignored; 0 measured; 56 filtered out; finished in 0.38s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M5.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M5.txt new file mode 100644 index 0000000..bf17dfe --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M5.txt @@ -0,0 +1,14 @@ +## mutation M5: a chunked read skips the BlobDigest check +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... ok +test g2_tests::g2_damaged_chunk_is_refused ... FAILED +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... ok +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... ok +thread 'g2_tests::g2_damaged_chunk_is_refused' (1260184) panicked at crates/synapse-store/src/g2_tests.rs:561:44: +test result: FAILED. 10 passed; 1 failed; 0 ignored; 0 measured; 56 filtered out; finished in 1.03s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M6.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M6.txt new file mode 100644 index 0000000..3332515 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M6.txt @@ -0,0 +1,15 @@ +## mutation M6: chunks of records earlier in the same batch do not count as indexed +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... FAILED +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_damaged_chunk_is_refused ... ok +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... ok +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... ok +thread 'g2_tests::g2_dedup_inside_one_batch_counts_earlier_records' (1261868) panicked at crates/synapse-store/src/g2_tests.rs:413:9: +the batch carries each chunk once: 622592 log bytes for 313525 chunk bytes +test result: FAILED. 10 passed; 1 failed; 0 ignored; 0 measured; 56 filtered out; finished in 1.04s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M7.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M7.txt new file mode 100644 index 0000000..f2568fc --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M7.txt @@ -0,0 +1,18 @@ +## mutation M7: replay forgets the manifests of replayed frames +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... FAILED +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... FAILED +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... FAILED +test g2_tests::g2_damaged_chunk_is_refused ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... FAILED +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... FAILED +thread 'g2_tests::g2_dedup_inside_one_batch_counts_earlier_records' (1264919) panicked at crates/synapse-store/src/g2_tests.rs:44:6: +thread 'g2_tests::g2_parameters_change_without_changing_identity' (1264924) panicked at crates/synapse-store/src/g2_tests.rs:456:51: +thread 'g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack' (1264916) panicked at crates/synapse-store/src/g2_tests.rs:44:6: +thread 'g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule' (1264918) panicked at crates/synapse-store/src/g2_tests.rs:149:59: +thread 'g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest' (1264920) panicked at crates/synapse-store/src/g2_tests.rs:149:59: +test result: FAILED. 6 passed; 5 failed; 0 ignored; 0 measured; 56 filtered out; finished in 0.94s diff --git a/evidence/g2-content-defined-chunking/red-green/mutation-M8.txt b/evidence/g2-content-defined-chunking/red-green/mutation-M8.txt new file mode 100644 index 0000000..7ffb40e --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/mutation-M8.txt @@ -0,0 +1,15 @@ +## mutation M8: WAL v2 decode skips the chunk digest check +test g2_tests::g2_invalid_chunk_parameters_are_refused_at_open ... ok +test g2_tests::g2_segment_index_v2_round_trips_and_refuses_damage ... ok +test g2_tests::g2_manifest_naming_an_unindexed_chunk_is_refused_at_replay ... ok +test g2_tests::g2_parameters_change_without_changing_identity ... ok +test g2_tests::g2_damaged_chunk_is_refused ... FAILED +test g2_tests::g2_chunking_off_writes_the_a2_formats ... ok +test g2_tests::g2_dedup_inside_one_batch_counts_earlier_records ... ok +test g2_tests::g2_crash_after_chunked_batch_sync_before_index_keeps_every_ack ... ok +test g2_tests::g2_old_stores_stay_readable ... ok +test g2_tests::g2_dedup_between_two_revisions_follows_the_x6_rule ... ok +test g2_tests::g2_every_blob_round_trips_byte_for_byte_with_unchanged_blob_digest ... ok +thread 'g2_tests::g2_damaged_chunk_is_refused' (1269061) panicked at crates/synapse-store/src/g2_tests.rs:546:9: +open must refuse a chunk whose digest does not match +test result: FAILED. 10 passed; 1 failed; 0 ignored; 0 measured; 56 filtered out; finished in 1.00s diff --git a/evidence/g2-content-defined-chunking/red-green/red-a2-behaviour.txt b/evidence/g2-content-defined-chunking/red-green/red-a2-behaviour.txt new file mode 100644 index 0000000..9925c4b --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/red-a2-behaviour.txt @@ -0,0 +1,9 @@ +# Red 1: behaviour of A2 (6431fcf). A probe with the same name and core assertion as +# g2_dedup_between_two_revisions_follows_the_x6_rule (A = 400,000 random bytes, B = A with a +# 100-byte insert, a 50-byte edit and 30 KB appended), run in an A2 worktree (not committed): +# A2 stores B whole, so B costs as many log bytes as its full length. +# cargo test -p synapse-store --lib g2_probe +test g2_probe::g2_dedup_between_two_revisions_follows_the_x6_rule ... FAILED +thread 'g2_probe::g2_dedup_between_two_revisions_follows_the_x6_rule' (1191437) panicked at crates/synapse-store/src/g2_probe.rs:27:5: +revision B appended 434176 log bytes for a 430100 byte blob sharing all but ~30 KB with A +test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 53 filtered out; finished in 0.09s diff --git a/evidence/g2-content-defined-chunking/red-green/red-a2-compile.txt b/evidence/g2-content-defined-chunking/red-green/red-a2-compile.txt new file mode 100644 index 0000000..1b197f3 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/red-a2-compile.txt @@ -0,0 +1,15 @@ +# Red 2: the G2 tests (crates/synapse-store/src/g2_tests.rs) compiled against A2 6431fcf in a +# worktree (not committed): A2 has no chunk module, chunk parameters, or chunk index. +# cargo test -p synapse-store --lib g2_tests (first error lines, count) + 13 error[E0599]: no method named `chunk_storage` found for struct `SynapseStore` in the current scope + 4 error[E0433]: cannot find type `ChunkParams` in this scope + 4 error[E0425]: cannot find type `ChunkParams` in this scope + 3 error[E0609]: no field `chunks` on type `SegmentIndex` + 3 error[E0599]: no method named `blob_manifest` found for struct `SynapseStore` in the current scope + 3 error[E0599]: no method named `blob_manifest` found for reference `&SynapseStore` in the current scope + 3 error[E0425]: cannot find type `ChunkDigest` in this scope + 3 error[E0425]: cannot find function, tuple struct or tuple variant `ChunkDigest` in this scope + 2 error[E0599]: no method named `log_bytes_written` found for struct `SynapseStore` in the current scope + 2 error[E0560]: struct `SegmentIndex` has no field named `manifests` + 2 error[E0560]: struct `SegmentIndex` has no field named `chunks` + 2 error[E0433]: cannot find type `ChunkDigest` in this scope diff --git a/evidence/g2-content-defined-chunking/red-green/run-mutations.sh b/evidence/g2-content-defined-chunking/red-green/run-mutations.sh new file mode 100755 index 0000000..e1c2538 --- /dev/null +++ b/evidence/g2-content-defined-chunking/red-green/run-mutations.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Mutation runs for ADR 0003 G2 (issue #45): each mutation breaks one rule of the chunk +# store, the G2 tests run, the output excerpt is saved, and the source is restored. +# Run from the repository root on a clean tree: evidence/g2-content-defined-chunking/red-green/run-mutations.sh +set -u +out=evidence/g2-content-defined-chunking/red-green +src=crates/synapse-store/src +run() { # id file perl-substitution description + local id=$1 file=$2 subst=$3 desc=$4 + cp "$src/$file" "/tmp/g2-mut-$file.bak" + perl -0pi -e "$subst" "$src/$file" + if cmp -s "$src/$file" "/tmp/g2-mut-$file.bak"; then echo "mutation $id did not apply" >&2; exit 1; fi + { + echo "## mutation $id: $desc" + cargo test --locked -p synapse-store --lib g2_tests 2>&1 \ + | grep -E '^test .* \.\.\. |panicked at|^[a-z].*(assertion|must|differ|adds|chunk|refuse)|test result' \ + | grep -v '^test result: ok. 0' | head -40 + } > "$out/mutation-$id.txt" + cp "/tmp/g2-mut-$file.bak" "$src/$file" + grep -c 'FAILED$' "$out/mutation-$id.txt" | sed "s/^/$id failed tests: /" +} +run M1 lib.rs 's/ if drops \{\n let rebuilt/ if false && drops {\n let rebuilt/' \ + "commit keeps every chunk (no deduplication against the chunk index)" +run M2 segment.rs 's/let v2 = !self.chunks.is_empty\(\) \|\| !self.manifests.is_empty\(\);/let v2 = false;/' \ + "the checkpoint segment index drops chunks and manifests" +run M3 lib.rs 's/Some\(loc\) if loc.len == \*clen => \{\}/Some(_) | None if true => {}/' \ + "replay accepts a manifest whose chunks are not indexed" +run M4 chunk.rs 's/len as u64 > self.threshold_bytes/len as u64 >= self.threshold_bytes/' \ + "a blob of exactly T bytes is chunked (threshold off by one)" +run M5 lib.rs 's/if at != len \|\| computed != digest \{/if at != len {/' \ + "a chunked read skips the BlobDigest check" +run M6 lib.rs 's/overlay\.chunks\.extend\(enc\.chunks\.iter\(\)\.map\(\|\(d, _, _\)\| \*d\)\);/let _ = &enc.chunks;/' \ + "chunks of records earlier in the same batch do not count as indexed" +run M7 lib.rs 's/self\.blob_chunks\.entry\(m\.blob\)\.or_insert\(m\);/let _ = m;/' \ + "replay forgets the manifests of replayed frames" +run M8 wal2.rs 's/if ChunkDigest::compute\(bytes\) != d \{/if false \&\& ChunkDigest::compute(bytes) != d {/' \ + "WAL v2 decode skips the chunk digest check" diff --git a/evidence/g2-content-defined-chunking/x6/RESULTS.md b/evidence/g2-content-defined-chunking/x6/RESULTS.md new file mode 100644 index 0000000..a0a9034 --- /dev/null +++ b/evidence/g2-content-defined-chunking/x6/RESULTS.md @@ -0,0 +1,63 @@ +# X6 Results: Content-Defined Chunking Threshold and Chunk Sizes + +Decision per the rule committed before the runs (`RULE.md`, sha256 +`dd4ed8f936fdbeadb05fc12278fb05448e63dc44b8e8fb8bb006e0729b3f3935`, commit ab9ccc0, unchanged). +Raw samples: `raw.json`. Decision: `report.json` (`synapse-bench x6-report --raw raw.json`, the rule +applied by `crates/synapse-bench/src/x6.rs::decide`, unit-tested on constructed runs). + +**Result: PASS. Winner K1 (T = 16 KiB, min 1 KiB, avg 4 KiB, max 16 KiB), the only eligible candidate. +`ChunkParams::X6_DEFAULT` is K1.** The run is valid: log and content bytes agree in all three +repetitions of every configuration, and every blob read back byte for byte. + +## Run + +Binary built from commit 7145a26 (`synapse-bench x6 --corpus ../corpus --out raw.json --dir <scratch> +--reps 3 --idle-window-s 10`), started 2026-10-16T09:01:04Z, load average 5.7 4.97 4.5 at start. +Host: DGX Spark, 20 CPUs, kernel 7.0.0-1019-nvidia, store on `/dev/nvme0n1p2` ext4. Shared host (other +agent sessions ran). Corpus (host-observed): 1,037 accepted changes, 24,093 file revisions, 433,805,920 +bytes, 19,618 distinct blobs. Limits raised to `max_paths_per_changeset` = 2,184 and +`max_total_changeset_bytes` = 67,108,864 so that no commit is refused. Ingest is one agent, strict +recovery, `GROUP_COMMIT_DEFAULT`; each change is a durable group-commit batch (1,037 batches). + +## Numbers (host-observed; medians of 3 repetitions) + +| Config | W ms/change | W/W0 | R us/read | R/R0 | S log bytes | S/S0 | Eligible | +| :--- | ---: | ---: | ---: | ---: | ---: | ---: | :--- | +| C0 | 1.947 | 1.000 | 12.31 | 1.000 | 415,395,840 | 1.000 | control | +| K1 | 2.133 | 1.095 | 13.16 | 1.068 | 329,252,864 | 0.793 | yes | +| K2 | 2.186 | 1.122 | 12.81 | 1.040 | 343,347,200 | 0.827 | no (W) | +| K3 | 2.189 | 1.124 | 12.71 | 1.032 | 375,672,832 | 0.904 | no (W) | +| K4 | 2.171 | 1.115 | 12.51 | 1.016 | 385,204,224 | 0.927 | no (W) | +| K5 | 2.144 | 1.100 | 12.37 | 1.004 | 390,643,712 | 0.940 | no (W just above 1.10) | +| K6 | 1.984 | 1.019 | 12.45 | 1.011 | 410,193,920 | 0.987 | no (S) | +| K7 | 2.067 | 1.061 | 12.33 | 1.001 | 410,808,320 | 0.989 | no (S) | + +Eligibility: W <= 1.10 W0, R <= 1.25 R0, S <= 0.95 S0. K1 is eligible with W/W0 = 1.095, a margin of +0.5 percentage points on a shared host; K5 misses the same limit by a similar margin. The rule decides, +and it was fixed before the runs, so the margin does not change the outcome, but the ranking of K1 +against the W limit is within host noise (UNVERIFIED that K1 would pass again on a quiet host). The +smallest log is K1 (20.7 % fewer log bytes than C0; 4,512 blobs chunked into 54,731 distinct chunks, +258,659,059 chunk bytes). + +## Seconds per accepted change against the A2 flush bound + +Flush bound 1.006 ms (A2 `floor.json`, `overwrite_64k_fdatasync` p50). Median seconds per accepted +change K1: 2.133 ms (C0: 1.947 ms), so K1 reaches 0.471 of the bound (C0 0.516). Per-change latency +(raw samples in `raw.json`, `ingest_latency_ns`): K1 p50 1.5 ms, p99 18.5 ms; C0 p50 1.4 ms, p99 17.3 ms. +Reads: 12.3 to 13.2 us per read; the fraction of the 273 GB/s memory bound is in `report.json` +(`read_bound_fraction`; the index lookup term is not modelled there). This experiment measures one +agent, so the 1.006 ms figure is the single-flush floor of one change, not a multi-agent bound. + +## Joules + +From the `aien_spbm` SoC package counter (uncalibrated, 1 mJ step, 10 Hz; NVMe and memory outside the +SoC are UNMEASURED). Idle package power over 10 s: 34.6 W. Package joules per accepted change: C0 +0.0773, K1 0.0762; above idle: C0 0.0099, K1 0.0017, with K2 and K4 reading below idle (negative). The +above-idle figures are inside the measurement noise on this shared host, which is why RULE.md section 6 +does not use joules in the decision. No window was refused. + +## Not run / limits + +- No quiet-host rerun; no external energy meter (INSTRUMENT_UNAVAILABLE for anything but the SoC package). +- Reads measured through `get_blob_visible` in memory-warm state (page cache), not cold from the device. +- One agent only; group-commit batch sizes were 1 (1,037 batches for 1,037 changes). diff --git a/evidence/g2-content-defined-chunking/x6/RULE.md b/evidence/g2-content-defined-chunking/x6/RULE.md new file mode 100644 index 0000000..04b4334 --- /dev/null +++ b/evidence/g2-content-defined-chunking/x6/RULE.md @@ -0,0 +1,121 @@ +# X6 Rule: Content-Defined Chunking Threshold and Chunk Sizes + +ADR 0003 section 6.4 row X6, for step G2 (issue #45). This file fixes the candidates, the corpus, +the measurements, the deduplication rule, and the decision criterion BEFORE any X6 run. It is +committed on its own; the runs, the raw samples, and the outcome are added in later commits and +must not change anything below. + +## 1. The Chunker (fixed for every candidate) + +A FastCDC-style gear chunker [S20] with normalized chunking, written in `synapse-store`: + +- **Gear table.** `G[i]`, `i = 0..255`, is the `i`-th output (first output is `G[0]`) of SplitMix64 + seeded with `0x5359_4E41_5053_4531` (ASCII `SYNAPSE1`): `state += 0x9E37_79B9_7F4A_7C15; + z = state; z = (z ^ (z >> 30)) * 0xBF58_476D_1CE4_E5B9; z = (z ^ (z >> 27)) * 0x94D0_49BB_1331_11EB; + out = z ^ (z >> 31)` (wrapping arithmetic on `u64`). +- **Rolling hash.** `h = (h << 1) + G[byte]` (wrapping), reset to 0 at the start of every chunk. +- **Cut rule** for the remaining bytes `src` of a blob, with `bits = log2(avg)`, `mask_s` = the top + `bits + 2` bits of a `u64` set, `mask_l` = the top `bits - 2` bits set: + if `len(src) <= min` the rest is one chunk; otherwise `n = min(len(src), max)`, hashing starts at + byte `min` (bytes before it are skipped), the cut is after byte `i` at the first `i` with + `h & mask_s == 0` while `i < min(avg, n)`, else the first `i` with `h & mask_l == 0` while `i < n`, + else at `n`. +- **Threshold.** A blob of `len <= T` bytes is stored whole (one copy per `BlobDigest`, as before + G2). A blob of `len > T` bytes is cut into chunks; each chunk is stored once per `ChunkDigest`. +- **Chunk identity.** `ChunkDigest = SHA-256("SYNAPSE_CHUNK_V1\0" || u64 LE length || bytes)`. A + blob's identity stays its `BlobDigest` over the whole content (CONTEXT.md). + +## 2. Candidates + +`min = avg / 4`, `max = 4 * avg` for every chunked candidate. + +| Id | Threshold T | min | avg | max | +| :--- | ---: | ---: | ---: | ---: | +| C0 | no chunking (control: every blob whole, the A2 behaviour) | | | | +| K1 | 16 KiB | 1 KiB | 4 KiB | 16 KiB | +| K2 | 16 KiB | 2 KiB | 8 KiB | 32 KiB | +| K3 | 64 KiB | 2 KiB | 8 KiB | 32 KiB | +| K4 | 64 KiB | 4 KiB | 16 KiB | 64 KiB | +| K5 | 64 KiB | 8 KiB | 32 KiB | 128 KiB | +| K6 | 256 KiB | 4 KiB | 16 KiB | 64 KiB | +| K7 | 256 KiB | 16 KiB | 64 KiB | 256 KiB | + +## 3. Corpus: Real AIEN Repository Histories + +Bare clones of four AIEN repositories at these commits (fetched 2026-10-16): + +| Repository | Commit | +| :--- | :--- | +| `aien-spark/aien-architecture` | `d2768e9b8730af5f13c0fbbdfbfa4ba788f7605a` | +| `aien-spark/aienos` | `b7ebf7cde234e1ddcc91eb8fcaf378d060cfb3a2` | +| `aien-spark/omega` | `43d8d20da2f64319bcf6196ac7204021c3f280eb` | +| `aien-spark/synapse` | `b9f46b16aa74301f0b330cfb5fa2e06f07d60b43` | + +- History: `git log --reverse --first-parent --raw --no-renames` of each commit, repositories in the + order of the table. Survey before the runs (from `git cat-file --batch-check`, not a run): + 24,093 added or modified regular-file revisions, 434 MB of content, 4,676 revisions above 16 KiB. +- **One accepted change per commit** that adds or modifies at least one regular file (mode `100644` + or `100755`): one signed changeset with one `Upsert` per such file. Deletions, symlinks, and + submodules store no content and are left out. Paths are replaced by a stable synthetic path per + repository path (`p<n>`), since paths do not affect storage. +- The client provides a blob's bytes only the first time its `BlobDigest` appears in the run (as a + client that asks which blobs the server lacks would); later references name the committed blob. +- Store limits for the run: `max_paths_per_changeset` and `max_total_changeset_bytes` raised so that + no commit is refused (the largest commit decides; the value is recorded in the raw output); every + other limit at its default; group commit (`GROUP_COMMIT_DEFAULT`), one agent, strict recovery. + +## 4. Measurements + +Per candidate and repetition, on a fresh store on the same ext4/NVMe filesystem as the A2 runs: + +1. **Ingest phase:** submit every change in order, one agent; record each change's time from submit + to durable acknowledgement (raw samples) and the phase wall time. Energy: one `aien_spbm` package + window around the phase (`INSTRUMENT_UNAVAILABLE` when the meter refuses, never a substitute). +2. **Log bytes:** bytes the store appended to its segments during the ingest phase (4 KiB-padded + batches, so frame headers, metadata, chunk tables, manifests, and padding all count), and the + content bytes stored (whole blobs plus distinct chunks). Both are deterministic for a sequential + run; if repetitions of one candidate disagree, the run is invalid. +3. **Read phase:** read every distinct committed blob once, in commit order, through + `get_blob_visible`; each read is compared byte for byte with the corpus bytes (any difference makes + the run invalid); record each read's time (raw samples), the phase wall time, and one energy window. + +Three repetitions; inside each repetition all eight configurations run once, in an order rotated by +one position per repetition. Bounds (ADR section 6.2): seconds per accepted change against the A2 flush +bound (1.006 ms, `evidence/a2-segment-store/measurement/floor.json`, cheapest +`overwrite_*_fdatasync` p50); a read of `n` bytes against `n` / 273 GB/s plus one index lookup. + +## 5. Deduplication Rule (the G2 acceptance) + +For a store with chunk parameters `(T, min, avg, max)`: + +1. A blob of `len <= T` is stored whole and is never cut. +2. A blob of `len > T` is cut by the chunker of section 1; reading it returns exactly its bytes, and + its `BlobDigest` is unchanged. +3. The store keeps one copy of every `ChunkDigest` it indexes. Committing a revision `B` of a blob + above `T` after a committed revision `A` whose chunks are still indexed stores exactly the distinct + chunks of `B` whose `ChunkDigest` is not already indexed (chunks committed earlier in the same batch + count as indexed): content bytes added = the sum of their lengths, nothing for the shared chunks. + A revision whose `BlobDigest` is already stored adds no chunk. + +## 6. Decision Criterion + +Let, for configuration `k`: `W_k` = median over the three repetitions of (ingest phase wall time / +accepted changes); `R_k` = median of (read phase wall time / reads); `S_k` = log bytes of the ingest +phase. + +1. A chunked candidate is **eligible** when all three hold: `W_k <= 1.10 * W_C0` (seconds per accepted + change at most 10 % above the control), `R_k <= 1.25 * R_C0` (seconds per read at most 25 % above), + and `S_k <= 0.95 * S_C0` (at least 5 % fewer log bytes). +2. The **winner** is the eligible candidate with the smallest `S_k`. Candidates within 1 % of that + smallest `S_k` are ties; among ties the larger `avg` wins, then the larger `T` (fewer chunks to + index and fewer reads). +3. If no candidate is eligible, G2 ships the chunk store with chunking off by default + (`T` = unlimited) and reports that outcome; the round-trip and deduplication tests still run with + explicit parameters. +4. Joules per accepted change and per read are measured and reported for every configuration but do + not enter the decision: on this shared host the A2 package energy above idle was inside the noise + (some A2 cells read below idle), so a joule criterion would decide on noise. + +## Sources + +- [S20] Xia et al., "FastCDC", USENIX ATC 2016 (ADR 0003 section 12). diff --git a/evidence/g2-content-defined-chunking/x6/SHA256SUMS b/evidence/g2-content-defined-chunking/x6/SHA256SUMS new file mode 100644 index 0000000..7397217 --- /dev/null +++ b/evidence/g2-content-defined-chunking/x6/SHA256SUMS @@ -0,0 +1,5 @@ +dd4ed8f936fdbeadb05fc12278fb05448e63dc44b8e8fb8bb006e0729b3f3935 RULE.md +b5baea10252fc5955c4f1ee33b60398f1a6cbe8c5e38215330e264d4ef6642e8 raw.json +296813cd4128930902cf330c44884543d6efdc90003388e22926b7cd256f4744 report.json +ae5cbb31437bf42128fbc43e215b3a5674cfd4c023db0a8b3c942e75fdbcb89b manifest.json +8ebc61b1ec414cffd74a651eb823bb09082fb0c1ba22380103f92aa3fc9385a4 RESULTS.md diff --git a/evidence/g2-content-defined-chunking/x6/manifest.json b/evidence/g2-content-defined-chunking/x6/manifest.json new file mode 100644 index 0000000..e05bfaa --- /dev/null +++ b/evidence/g2-content-defined-chunking/x6/manifest.json @@ -0,0 +1,15 @@ +{ + "step": "ADR 0003 G2 (issue #45), experiment X6: content-defined chunking threshold and chunk sizes", + "host": "DGX Spark, 20 CPUs, kernel 7.0.0-1019-nvidia, store on /dev/nvme0n1p2 ext4 (shared host)", + "binary_commit": "7145a26d937dc43ed44bfe31b36c7c2c1ccf5232", + "rule_sha256": "dd4ed8f936fdbeadb05fc12278fb05448e63dc44b8e8fb8bb006e0729b3f3935", + "commands": [ + "synapse-bench x6 --corpus <bare clones> --out raw.json --dir <scratch> --reps 3 --idle-window-s 10", + "synapse-bench x6-report --raw raw.json > report.json" + ], + "run_start_utc": "2026-10-16T09:01:04Z", + "loadavg_start": "5.69 4.97 4.53", + "clock": "std::time::Instant (CLOCK_MONOTONIC), ns", + "energy": "aien_spbm hwmon, SoC package only, 1 mJ step, 10 Hz sampling, uncalibrated; NVMe UNMEASURED", + "corpus": "see RULE.md section 3 (bare clones at the recorded commits)" +} diff --git a/evidence/g2-content-defined-chunking/x6/raw.json b/evidence/g2-content-defined-chunking/x6/raw.json new file mode 100644 index 0000000..424ce0a --- /dev/null +++ b/evidence/g2-content-defined-chunking/x6/raw.json @@ -0,0 +1 @@