synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / x6.rs
| 1 | //! ADR 0003 experiment X6 (step G2, issue #45): content-defined chunking threshold and |
| 2 | //! chunk sizes on real AIEN repository histories. |
| 3 | //! |
| 4 | //! Everything this module does is fixed in `evidence/g2-content-defined-chunking/x6/ |
| 5 | //! RULE.md`, committed before the runs: the eight configurations, the corpus (one |
| 6 | //! accepted change per first-parent commit that adds or modifies a regular file, bytes |
| 7 | //! provided the first time a blob appears), the measurements (ingest phase: per-change |
| 8 | //! latency, wall time, one energy window, log bytes; read phase: every distinct blob once |
| 9 | //! with a byte comparison, per-read time, one energy window), three repetitions with the |
| 10 | //! configuration order rotated by one per repetition, and the decision criterion |
| 11 | //! ([`decide`]). Joules come only from the `aien_spbm` package meter; a refused window |
| 12 | //! leaves them `None` with the reason (`INSTRUMENT_UNAVAILABLE`), never a substitute. |
| 13 | |
| 14 | use crate::energy::{idle_window, EnergyReading, EnergyWindow}; |
| 15 | use crate::stats::{summarize_us, LatencySummary}; |
| 16 | use ed25519_dalek::SigningKey; |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | use std::collections::{BTreeMap, HashMap}; |
| 19 | use std::io::{BufRead, BufReader, Read, Write}; |
| 20 | use std::path::{Path, PathBuf}; |
| 21 | use std::process::{Command, Stdio}; |
| 22 | use std::time::{Duration, Instant}; |
| 23 | use synapse_core::{ |
| 24 | BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey, MutationOp, PathMutation, |
| 25 | RepoId, SYNAPSE_ENVELOPE_VERSION, |
| 26 | }; |
| 27 | use synapse_store::{ |
| 28 | ChunkParams, FsyncPolicy, IngestOutcome, RecoveryPolicy, SharedStore, StoreLimits, |
| 29 | }; |
| 30 | |
| 31 | /// A2 flush bound, seconds: `evidence/a2-segment-store/measurement/floor.json`, cheapest |
| 32 | /// `overwrite_*_fdatasync` p50 (`overwrite_64k_fdatasync`), as fixed in RULE.md section 4. |
| 33 | pub const A2_FLUSH_BOUND_S: f64 = 1.006e-3; |
| 34 | /// Memory bandwidth, bytes per second (NVIDIA DGX Spark specification, A0). |
| 35 | pub const MEMORY_BW_BPS: f64 = 273e9; |
| 36 | |
| 37 | /// The corpus repositories and commits of RULE.md section 3, in order. |
| 38 | pub const CORPUS: [(&str, &str); 4] = [ |
| 39 | ( |
| 40 | "aien-architecture", |
| 41 | "d2768e9b8730af5f13c0fbbdfbfa4ba788f7605a", |
| 42 | ), |
| 43 | ("aienos", "b7ebf7cde234e1ddcc91eb8fcaf378d060cfb3a2"), |
| 44 | ("omega", "43d8d20da2f64319bcf6196ac7204021c3f280eb"), |
| 45 | ("synapse", "b9f46b16aa74301f0b330cfb5fa2e06f07d60b43"), |
| 46 | ]; |
| 47 | |
| 48 | /// The eight configurations of RULE.md section 2. |
| 49 | pub fn configurations() -> Vec<(&'static str, ChunkParams)> { |
| 50 | const K: u64 = 1024; |
| 51 | vec![ |
| 52 | ("C0", ChunkParams::OFF), |
| 53 | ("K1", ChunkParams::candidate(16 * K, 4 * 1024)), |
| 54 | ("K2", ChunkParams::candidate(16 * K, 8 * 1024)), |
| 55 | ("K3", ChunkParams::candidate(64 * K, 8 * 1024)), |
| 56 | ("K4", ChunkParams::candidate(64 * K, 16 * 1024)), |
| 57 | ("K5", ChunkParams::candidate(64 * K, 32 * 1024)), |
| 58 | ("K6", ChunkParams::candidate(256 * K, 16 * 1024)), |
| 59 | ("K7", ChunkParams::candidate(256 * K, 64 * 1024)), |
| 60 | ] |
| 61 | } |
| 62 | |
| 63 | /// A signed changeset and the blob bytes it provides. |
| 64 | pub type SignedChange = (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>); |
| 65 | |
| 66 | /// One file revision of a change: synthetic path, blob index, executable bit. |
| 67 | #[derive(Debug, Clone)] |
| 68 | pub struct FileRev { |
| 69 | pub path: String, |
| 70 | pub blob: usize, |
| 71 | pub exec: bool, |
| 72 | } |
| 73 | |
| 74 | /// The corpus in memory: changes in order and the distinct blobs they name. |
| 75 | #[derive(Debug)] |
| 76 | pub struct Corpus { |
| 77 | pub changes: Vec<(String, String, Vec<FileRev>)>, |
| 78 | pub blobs: Vec<Vec<u8>>, |
| 79 | pub digests: Vec<BlobDigest>, |
| 80 | pub revisions: usize, |
| 81 | pub revision_bytes: u64, |
| 82 | } |
| 83 | |
| 84 | fn git(dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> { |
| 85 | let out = Command::new("git") |
| 86 | .arg("-C") |
| 87 | .arg(dir) |
| 88 | .args(args) |
| 89 | .output() |
| 90 | .map_err(|e| format!("git: {e}"))?; |
| 91 | if !out.status.success() { |
| 92 | return Err(format!( |
| 93 | "git {args:?} in {}: {}", |
| 94 | dir.display(), |
| 95 | String::from_utf8_lossy(&out.stderr) |
| 96 | )); |
| 97 | } |
| 98 | Ok(out.stdout) |
| 99 | } |
| 100 | |
| 101 | /// Read the corpus from bare clones `<root>/<name>.git` (RULE.md section 3). |
| 102 | pub fn load_corpus(root: &Path) -> Result<Corpus, String> { |
| 103 | let mut changes = Vec::new(); |
| 104 | let mut oid_index: HashMap<String, usize> = HashMap::new(); |
| 105 | let mut oids: Vec<String> = Vec::new(); |
| 106 | let mut paths: HashMap<(usize, String), usize> = HashMap::new(); |
| 107 | let mut revisions = 0usize; |
| 108 | for (r, (name, commit)) in CORPUS.iter().enumerate() { |
| 109 | let dir = root.join(format!("{name}.git")); |
| 110 | let head = git(&dir, &["rev-parse", &format!("{commit}^{{commit}}")])?; |
| 111 | if String::from_utf8_lossy(&head).trim() != *commit { |
| 112 | return Err(format!("{name}: commit {commit} not found")); |
| 113 | } |
| 114 | let log = git( |
| 115 | &dir, |
| 116 | &[ |
| 117 | "log", |
| 118 | "--reverse", |
| 119 | "--first-parent", |
| 120 | "--raw", |
| 121 | "--no-renames", |
| 122 | "--no-abbrev", |
| 123 | "--format=commit %H", |
| 124 | commit, |
| 125 | ], |
| 126 | )?; |
| 127 | let mut current: Option<(String, Vec<FileRev>)> = None; |
| 128 | let flush = |cur: Option<(String, Vec<FileRev>)>, changes: &mut Vec<_>| { |
| 129 | if let Some((h, files)) = cur { |
| 130 | if !files.is_empty() { |
| 131 | changes.push((name.to_string(), h, files)); |
| 132 | } |
| 133 | } |
| 134 | }; |
| 135 | for line in String::from_utf8_lossy(&log).lines() { |
| 136 | if let Some(h) = line.strip_prefix("commit ") { |
| 137 | flush(current.take(), &mut changes); |
| 138 | current = Some((h.to_string(), Vec::new())); |
| 139 | continue; |
| 140 | } |
| 141 | let Some(rest) = line.strip_prefix(':') else { |
| 142 | continue; |
| 143 | }; |
| 144 | let (meta, path) = rest.split_once('\t').ok_or("raw line without path")?; |
| 145 | let f: Vec<&str> = meta.split(' ').collect(); |
| 146 | if f.len() != 5 { |
| 147 | return Err(format!("unexpected raw line {line}")); |
| 148 | } |
| 149 | let (mode, oid, status) = (f[1], f[3], f[4]); |
| 150 | if !(status.starts_with('A') || status.starts_with('M')) { |
| 151 | continue; |
| 152 | } |
| 153 | if mode != "100644" && mode != "100755" { |
| 154 | continue; |
| 155 | } |
| 156 | let next = paths.len(); |
| 157 | let pid = *paths.entry((r, path.to_string())).or_insert(next); |
| 158 | let next = oids.len(); |
| 159 | let blob = *oid_index.entry(oid.to_string()).or_insert_with(|| { |
| 160 | oids.push(oid.to_string()); |
| 161 | next |
| 162 | }); |
| 163 | let files = &mut current.as_mut().ok_or("raw line before commit")?.1; |
| 164 | files.push(FileRev { |
| 165 | path: format!("p{pid}"), |
| 166 | blob, |
| 167 | exec: mode == "100755", |
| 168 | }); |
| 169 | revisions += 1; |
| 170 | } |
| 171 | flush(current.take(), &mut changes); |
| 172 | } |
| 173 | // Blob contents through one `git cat-file --batch` per repository. |
| 174 | let mut blobs: Vec<Option<Vec<u8>>> = vec![None; oids.len()]; |
| 175 | for (name, _) in CORPUS.iter() { |
| 176 | let dir = root.join(format!("{name}.git")); |
| 177 | let wanted: Vec<usize> = changes |
| 178 | .iter() |
| 179 | .filter(|(n, _, _)| n == name) |
| 180 | .flat_map(|(_, _, f)| f.iter().map(|x| x.blob)) |
| 181 | .filter(|&b| blobs[b].is_none()) |
| 182 | .collect::<std::collections::BTreeSet<_>>() |
| 183 | .into_iter() |
| 184 | .collect(); |
| 185 | let mut child = Command::new("git") |
| 186 | .arg("-C") |
| 187 | .arg(&dir) |
| 188 | .args(["cat-file", "--batch"]) |
| 189 | .stdin(Stdio::piped()) |
| 190 | .stdout(Stdio::piped()) |
| 191 | .spawn() |
| 192 | .map_err(|e| format!("git cat-file: {e}"))?; |
| 193 | let mut stdin = child.stdin.take().expect("piped"); |
| 194 | let list: String = wanted.iter().map(|&b| format!("{}\n", oids[b])).collect(); |
| 195 | let writer = std::thread::spawn(move || stdin.write_all(list.as_bytes())); |
| 196 | let mut out = BufReader::new(child.stdout.take().expect("piped")); |
| 197 | for &b in &wanted { |
| 198 | let mut header = String::new(); |
| 199 | out.read_line(&mut header).map_err(|e| e.to_string())?; |
| 200 | let h: Vec<&str> = header.trim_end().split(' ').collect(); |
| 201 | if h.len() != 3 || h[0] != oids[b] || h[1] != "blob" { |
| 202 | return Err(format!("cat-file header {header:?} for {}", oids[b])); |
| 203 | } |
| 204 | let len: usize = h[2].parse().map_err(|_| "cat-file size")?; |
| 205 | let mut bytes = vec![0u8; len + 1]; |
| 206 | out.read_exact(&mut bytes).map_err(|e| e.to_string())?; |
| 207 | if bytes.pop() != Some(b'\n') { |
| 208 | return Err("cat-file record without newline".into()); |
| 209 | } |
| 210 | if GitOid::compute_blob(&bytes).to_hex() != oids[b] { |
| 211 | return Err(format!("blob {} does not hash to its oid", oids[b])); |
| 212 | } |
| 213 | blobs[b] = Some(bytes); |
| 214 | } |
| 215 | writer.join().expect("writer").map_err(|e| e.to_string())?; |
| 216 | child.wait().map_err(|e| e.to_string())?; |
| 217 | } |
| 218 | let blobs: Vec<Vec<u8>> = blobs |
| 219 | .into_iter() |
| 220 | .map(|b| b.ok_or("blob not read")) |
| 221 | .collect::<Result<_, _>>()?; |
| 222 | let revision_bytes = changes |
| 223 | .iter() |
| 224 | .flat_map(|(_, _, f)| f.iter().map(|x| blobs[x.blob].len() as u64)) |
| 225 | .sum(); |
| 226 | let digests = blobs.iter().map(|b| BlobDigest::compute(b)).collect(); |
| 227 | Ok(Corpus { |
| 228 | changes, |
| 229 | blobs, |
| 230 | digests, |
| 231 | revisions, |
| 232 | revision_bytes, |
| 233 | }) |
| 234 | } |
| 235 | |
| 236 | /// Signed changesets of the corpus, with the bytes of each blob attached only the first |
| 237 | /// time its `BlobDigest` appears (RULE.md section 3). Built once, outside every timed phase. |
| 238 | pub fn build_changesets(c: &Corpus) -> Vec<SignedChange> { |
| 239 | let key = SigningKey::from_bytes(&[0x56; 32]); |
| 240 | let mut seen = std::collections::HashSet::new(); |
| 241 | c.changes |
| 242 | .iter() |
| 243 | .map(|(repo, hash, files)| { |
| 244 | let mut provided = Vec::new(); |
| 245 | // Envelopes require mutations in path order. |
| 246 | let mut files: Vec<&FileRev> = files.iter().collect(); |
| 247 | files.sort_by(|a, b| a.path.cmp(&b.path)); |
| 248 | let mutations = files |
| 249 | .into_iter() |
| 250 | .map(|f| { |
| 251 | let d = c.digests[f.blob]; |
| 252 | if seen.insert(d) { |
| 253 | provided.push((d, c.blobs[f.blob].clone())); |
| 254 | } |
| 255 | PathMutation { |
| 256 | path: f.path.clone(), |
| 257 | op: MutationOp::Upsert { |
| 258 | mode: if f.exec { |
| 259 | FileMode::Executable755 |
| 260 | } else { |
| 261 | FileMode::Regular644 |
| 262 | }, |
| 263 | blob_digest: d, |
| 264 | size_bytes: c.blobs[f.blob].len() as u64, |
| 265 | }, |
| 266 | } |
| 267 | }) |
| 268 | .collect(); |
| 269 | let mut env = ChangesetEnvelope { |
| 270 | version: SYNAPSE_ENVELOPE_VERSION, |
| 271 | repo_id: RepoId::new(format!("aien-spark/{repo}")).expect("repo id"), |
| 272 | base_git_oid: GitOid::compute_blob(hash.as_bytes()), |
| 273 | parent_changesets: vec![], |
| 274 | author_did: String::new(), |
| 275 | idempotency_key: IdempotencyKey::from_label(&format!("x6-{repo}-{hash}")), |
| 276 | created_at_ms: 1000, |
| 277 | intent_summary: format!("{repo} {hash}"), |
| 278 | mutations, |
| 279 | evidence_receipts: vec![], |
| 280 | signature: vec![], |
| 281 | }; |
| 282 | env.sign(&key); |
| 283 | (env, provided) |
| 284 | }) |
| 285 | .collect() |
| 286 | } |
| 287 | |
| 288 | /// Raw samples of one configuration in one repetition. |
| 289 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 290 | pub struct RunRaw { |
| 291 | pub config: String, |
| 292 | pub params: ChunkParams, |
| 293 | pub rep: usize, |
| 294 | pub position_in_rep: usize, |
| 295 | pub accepted: usize, |
| 296 | pub ingest_elapsed_ns: u64, |
| 297 | pub ingest_latency_ns: Vec<u64>, |
| 298 | pub ingest_energy: EnergyReading, |
| 299 | /// Bytes appended to the segments during the ingest phase. |
| 300 | pub log_bytes: u64, |
| 301 | /// Whole blobs stored inline plus distinct chunks. |
| 302 | pub content_bytes: u64, |
| 303 | pub inline_blob_bytes: u64, |
| 304 | pub chunks: usize, |
| 305 | pub chunk_bytes: u64, |
| 306 | pub chunked_blobs: usize, |
| 307 | pub batches: u64, |
| 308 | pub reads: usize, |
| 309 | pub read_bytes: u64, |
| 310 | pub read_elapsed_ns: u64, |
| 311 | pub read_ns: Vec<u64>, |
| 312 | pub read_energy: EnergyReading, |
| 313 | } |
| 314 | |
| 315 | /// Raw output of an X6 run. |
| 316 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 317 | pub struct X6Raw { |
| 318 | pub corpus: Vec<(String, String)>, |
| 319 | pub changes: usize, |
| 320 | pub revisions: usize, |
| 321 | pub revision_bytes: u64, |
| 322 | pub distinct_blobs: usize, |
| 323 | pub distinct_blob_bytes: u64, |
| 324 | /// Limits raised so that no commit is refused (the largest commit decides). |
| 325 | pub max_paths_per_changeset: usize, |
| 326 | pub max_total_changeset_bytes: u64, |
| 327 | pub idle: EnergyReading, |
| 328 | pub runs: Vec<RunRaw>, |
| 329 | } |
| 330 | |
| 331 | fn run_one( |
| 332 | dir: &Path, |
| 333 | corpus: &Corpus, |
| 334 | sets: &[SignedChange], |
| 335 | limits: &StoreLimits, |
| 336 | order: &[usize], |
| 337 | ) -> Result<RunRaw, String> { |
| 338 | let _ = std::fs::remove_dir_all(dir); |
| 339 | let shared = SharedStore::open( |
| 340 | dir, |
| 341 | FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 342 | RecoveryPolicy::StrictFailClosed, |
| 343 | limits.clone(), |
| 344 | ) |
| 345 | .map_err(|e| format!("open: {e:?}"))?; |
| 346 | let mut latency = Vec::with_capacity(sets.len()); |
| 347 | let window = EnergyWindow::start(); |
| 348 | let t0 = Instant::now(); |
| 349 | for (env, blobs) in sets { |
| 350 | let s = Instant::now(); |
| 351 | match shared.submit(env.clone(), blobs) { |
| 352 | Ok(IngestOutcome::Committed { .. }) => {} |
| 353 | other => return Err(format!("change not committed: {other:?}")), |
| 354 | } |
| 355 | latency.push(s.elapsed().as_nanos() as u64); |
| 356 | } |
| 357 | let ingest_elapsed_ns = t0.elapsed().as_nanos() as u64; |
| 358 | let ingest_energy = window.finish(); |
| 359 | let stats = shared.stats(); |
| 360 | let st = shared.read(); |
| 361 | let log_bytes = st.log_bytes_written(); |
| 362 | let (chunks, chunk_bytes) = st.chunk_storage(); |
| 363 | let inline_blob_bytes = st.inline_blob_bytes(); |
| 364 | let chunked_blobs = corpus |
| 365 | .digests |
| 366 | .iter() |
| 367 | .filter(|d| st.blob_manifest(d).is_some()) |
| 368 | .count(); |
| 369 | // Read phase: every distinct committed blob once, in commit order. |
| 370 | let mut read_ns = Vec::with_capacity(order.len()); |
| 371 | let mut read_bytes = 0u64; |
| 372 | let window = EnergyWindow::start(); |
| 373 | let t0 = Instant::now(); |
| 374 | for &b in order { |
| 375 | let s = Instant::now(); |
| 376 | let got = st |
| 377 | .get_blob_visible(corpus.digests[b], None, None) |
| 378 | .map_err(|e| format!("read: {e:?}"))?; |
| 379 | read_ns.push(s.elapsed().as_nanos() as u64); |
| 380 | if got != corpus.blobs[b] { |
| 381 | return Err(format!( |
| 382 | "blob {} read back different bytes", |
| 383 | corpus.digests[b] |
| 384 | )); |
| 385 | } |
| 386 | read_bytes += got.len() as u64; |
| 387 | } |
| 388 | let read_elapsed_ns = t0.elapsed().as_nanos() as u64; |
| 389 | let read_energy = window.finish(); |
| 390 | drop(st); |
| 391 | drop(shared); |
| 392 | let _ = std::fs::remove_dir_all(dir); |
| 393 | Ok(RunRaw { |
| 394 | config: String::new(), |
| 395 | params: limits.chunking, |
| 396 | rep: 0, |
| 397 | position_in_rep: 0, |
| 398 | accepted: sets.len(), |
| 399 | ingest_elapsed_ns, |
| 400 | ingest_latency_ns: latency, |
| 401 | ingest_energy, |
| 402 | log_bytes, |
| 403 | content_bytes: inline_blob_bytes + chunk_bytes, |
| 404 | inline_blob_bytes, |
| 405 | chunks, |
| 406 | chunk_bytes, |
| 407 | chunked_blobs, |
| 408 | batches: stats.batches, |
| 409 | reads: order.len(), |
| 410 | read_bytes, |
| 411 | read_elapsed_ns, |
| 412 | read_ns, |
| 413 | read_energy, |
| 414 | }) |
| 415 | } |
| 416 | |
| 417 | /// Run X6: `reps` repetitions of every configuration (order rotated by one per |
| 418 | /// repetition) on stores under `scratch`. `only` restricts the configurations (smoke runs). |
| 419 | pub fn run_x6( |
| 420 | corpus_root: &Path, |
| 421 | scratch: &Path, |
| 422 | reps: usize, |
| 423 | idle_s: u64, |
| 424 | only: Option<&[String]>, |
| 425 | log: &mut dyn FnMut(&str), |
| 426 | ) -> Result<X6Raw, String> { |
| 427 | let corpus = load_corpus(corpus_root)?; |
| 428 | log(&format!( |
| 429 | "corpus: {} changes, {} revisions, {} bytes, {} distinct blobs", |
| 430 | corpus.changes.len(), |
| 431 | corpus.revisions, |
| 432 | corpus.revision_bytes, |
| 433 | corpus.blobs.len() |
| 434 | )); |
| 435 | let sets = build_changesets(&corpus); |
| 436 | let max_paths = sets |
| 437 | .iter() |
| 438 | .map(|(e, _)| e.mutations.len()) |
| 439 | .max() |
| 440 | .unwrap_or(1); |
| 441 | let max_total = sets |
| 442 | .iter() |
| 443 | .map(|(_, b)| b.iter().map(|(_, x)| x.len() as u64).sum::<u64>()) |
| 444 | .max() |
| 445 | .unwrap_or(0); |
| 446 | let mut order = Vec::new(); |
| 447 | let mut seen = std::collections::HashSet::new(); |
| 448 | for (_, _, files) in &corpus.changes { |
| 449 | for f in files { |
| 450 | if seen.insert(f.blob) { |
| 451 | order.push(f.blob); |
| 452 | } |
| 453 | } |
| 454 | } |
| 455 | let base = StoreLimits { |
| 456 | max_paths_per_changeset: max_paths.max(StoreLimits::default().max_paths_per_changeset), |
| 457 | max_total_changeset_bytes: max_total.max(StoreLimits::default().max_total_changeset_bytes), |
| 458 | ..Default::default() |
| 459 | }; |
| 460 | let configs: Vec<_> = configurations() |
| 461 | .into_iter() |
| 462 | .filter(|(id, _)| only.is_none_or(|o| o.iter().any(|x| x == id))) |
| 463 | .collect(); |
| 464 | let idle = idle_window(Duration::from_secs(idle_s)); |
| 465 | let mut runs = Vec::new(); |
| 466 | for rep in 0..reps { |
| 467 | for pos in 0..configs.len() { |
| 468 | let (id, params) = configs[(pos + rep) % configs.len()]; |
| 469 | let limits = StoreLimits { |
| 470 | chunking: params, |
| 471 | ..base.clone() |
| 472 | }; |
| 473 | let dir = scratch.join(format!("x6-{id}-rep{rep}")); |
| 474 | let mut r = run_one(&dir, &corpus, &sets, &limits, &order)?; |
| 475 | r.config = id.to_string(); |
| 476 | r.rep = rep; |
| 477 | r.position_in_rep = pos; |
| 478 | log(&format!( |
| 479 | "rep {rep} {id}: ingest {:.3} s, log {} B, content {} B, read {:.3} s", |
| 480 | r.ingest_elapsed_ns as f64 / 1e9, |
| 481 | r.log_bytes, |
| 482 | r.content_bytes, |
| 483 | r.read_elapsed_ns as f64 / 1e9 |
| 484 | )); |
| 485 | runs.push(r); |
| 486 | } |
| 487 | } |
| 488 | Ok(X6Raw { |
| 489 | corpus: CORPUS |
| 490 | .iter() |
| 491 | .map(|(n, c)| (n.to_string(), c.to_string())) |
| 492 | .collect(), |
| 493 | changes: corpus.changes.len(), |
| 494 | revisions: corpus.revisions, |
| 495 | revision_bytes: corpus.revision_bytes, |
| 496 | distinct_blobs: corpus.blobs.len(), |
| 497 | distinct_blob_bytes: corpus.blobs.iter().map(|b| b.len() as u64).sum(), |
| 498 | max_paths_per_changeset: base.max_paths_per_changeset, |
| 499 | max_total_changeset_bytes: base.max_total_changeset_bytes, |
| 500 | idle, |
| 501 | runs, |
| 502 | }) |
| 503 | } |
| 504 | |
| 505 | /// Figures of one configuration (medians over the repetitions). |
| 506 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 507 | pub struct ConfigReport { |
| 508 | pub config: String, |
| 509 | pub params: ChunkParams, |
| 510 | pub reps: usize, |
| 511 | /// `W_k`: median over repetitions of ingest wall time / accepted changes, seconds. |
| 512 | pub w_s_per_change: f64, |
| 513 | /// `R_k`: median of read wall time / reads, seconds. |
| 514 | pub r_s_per_read: f64, |
| 515 | /// `S_k`: log bytes of the ingest phase (equal in every repetition, else invalid). |
| 516 | pub s_log_bytes: u64, |
| 517 | pub content_bytes: u64, |
| 518 | pub chunks: usize, |
| 519 | pub chunked_blobs: usize, |
| 520 | pub deterministic: bool, |
| 521 | pub latency: Option<LatencySummary>, |
| 522 | pub read_latency: Option<LatencySummary>, |
| 523 | /// A2 flush bound / `W_k` (fraction of the bound reached, at most 1). |
| 524 | pub flush_bound_fraction: f64, |
| 525 | /// Mean read bytes / 273 GB/s per read, seconds (the index lookup term is not |
| 526 | /// modelled, so this bound is lower than the RULE's), and bound / `R_k`. |
| 527 | pub read_bound_s: f64, |
| 528 | pub read_bound_fraction: f64, |
| 529 | pub ingest_j_per_change: Option<f64>, |
| 530 | pub ingest_j_per_change_above_idle: Option<f64>, |
| 531 | pub read_j_per_read: Option<f64>, |
| 532 | pub read_j_per_read_above_idle: Option<f64>, |
| 533 | pub energy_refusals: Vec<String>, |
| 534 | pub w_ratio: f64, |
| 535 | pub r_ratio: f64, |
| 536 | pub s_ratio: f64, |
| 537 | pub eligible: bool, |
| 538 | } |
| 539 | |
| 540 | /// The decision of RULE.md section 6. |
| 541 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 542 | pub struct X6Report { |
| 543 | pub configs: Vec<ConfigReport>, |
| 544 | pub valid: bool, |
| 545 | pub invalid_reasons: Vec<String>, |
| 546 | pub eligible: Vec<String>, |
| 547 | /// Winner id, or `None` (chunking off by default). |
| 548 | pub winner: Option<String>, |
| 549 | pub winner_params: ChunkParams, |
| 550 | pub flush_bound_s: f64, |
| 551 | } |
| 552 | |
| 553 | fn median(mut v: Vec<f64>) -> f64 { |
| 554 | v.sort_by(|a, b| a.total_cmp(b)); |
| 555 | let n = v.len(); |
| 556 | if n % 2 == 1 { |
| 557 | v[n / 2] |
| 558 | } else { |
| 559 | (v[n / 2 - 1] + v[n / 2]) / 2.0 |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | fn median_opt(v: Vec<Option<f64>>) -> Option<f64> { |
| 564 | let v: Option<Vec<f64>> = v.into_iter().collect(); |
| 565 | v.filter(|v| !v.is_empty()).map(median) |
| 566 | } |
| 567 | |
| 568 | /// Apply the decision criterion of RULE.md section 6 to the raw runs. |
| 569 | pub fn decide(raw: &X6Raw) -> X6Report { |
| 570 | let mut by: BTreeMap<String, Vec<&RunRaw>> = BTreeMap::new(); |
| 571 | for r in &raw.runs { |
| 572 | by.entry(r.config.clone()).or_default().push(r); |
| 573 | } |
| 574 | let mut invalid = Vec::new(); |
| 575 | let mut configs = Vec::new(); |
| 576 | for (id, params) in configurations() { |
| 577 | let Some(runs) = by.get(id) else { continue }; |
| 578 | let det = runs |
| 579 | .iter() |
| 580 | .all(|r| (r.log_bytes, r.content_bytes) == (runs[0].log_bytes, runs[0].content_bytes)); |
| 581 | if !det { |
| 582 | invalid.push(format!( |
| 583 | "{id}: log or content bytes differ between repetitions" |
| 584 | )); |
| 585 | } |
| 586 | let w = median( |
| 587 | runs.iter() |
| 588 | .map(|r| r.ingest_elapsed_ns as f64 / 1e9 / r.accepted as f64) |
| 589 | .collect(), |
| 590 | ); |
| 591 | let rr = median( |
| 592 | runs.iter() |
| 593 | .map(|r| r.read_elapsed_ns as f64 / 1e9 / r.reads as f64) |
| 594 | .collect(), |
| 595 | ); |
| 596 | let lat: Vec<u64> = runs |
| 597 | .iter() |
| 598 | .flat_map(|r| r.ingest_latency_ns.iter().map(|n| n / 1000)) |
| 599 | .collect(); |
| 600 | let rlat: Vec<u64> = runs |
| 601 | .iter() |
| 602 | .flat_map(|r| r.read_ns.iter().map(|n| n / 1000)) |
| 603 | .collect(); |
| 604 | let read_bound_s = runs[0].read_bytes as f64 / runs[0].reads as f64 / MEMORY_BW_BPS; |
| 605 | let mut refusals = Vec::new(); |
| 606 | for r in runs { |
| 607 | for e in [&r.ingest_energy, &r.read_energy] { |
| 608 | if let Some(x) = &e.refusal { |
| 609 | refusals.push(format!("rep {}: {x}", r.rep)); |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | configs.push(ConfigReport { |
| 614 | config: id.to_string(), |
| 615 | params, |
| 616 | reps: runs.len(), |
| 617 | w_s_per_change: w, |
| 618 | r_s_per_read: rr, |
| 619 | s_log_bytes: runs[0].log_bytes, |
| 620 | content_bytes: runs[0].content_bytes, |
| 621 | chunks: runs[0].chunks, |
| 622 | chunked_blobs: runs[0].chunked_blobs, |
| 623 | deterministic: det, |
| 624 | latency: summarize_us(&lat), |
| 625 | read_latency: summarize_us(&rlat), |
| 626 | flush_bound_fraction: (A2_FLUSH_BOUND_S / w).min(1.0), |
| 627 | read_bound_s, |
| 628 | read_bound_fraction: (read_bound_s / rr).min(1.0), |
| 629 | ingest_j_per_change: median_opt( |
| 630 | runs.iter() |
| 631 | .map(|r| r.ingest_energy.pkg_j.map(|j| j / r.accepted as f64)) |
| 632 | .collect(), |
| 633 | ), |
| 634 | ingest_j_per_change_above_idle: median_opt( |
| 635 | runs.iter() |
| 636 | .map(|r| { |
| 637 | r.ingest_energy |
| 638 | .pkg_above_idle_j(&raw.idle) |
| 639 | .map(|j| j / r.accepted as f64) |
| 640 | }) |
| 641 | .collect(), |
| 642 | ), |
| 643 | read_j_per_read: median_opt( |
| 644 | runs.iter() |
| 645 | .map(|r| r.read_energy.pkg_j.map(|j| j / r.reads as f64)) |
| 646 | .collect(), |
| 647 | ), |
| 648 | read_j_per_read_above_idle: median_opt( |
| 649 | runs.iter() |
| 650 | .map(|r| { |
| 651 | r.read_energy |
| 652 | .pkg_above_idle_j(&raw.idle) |
| 653 | .map(|j| j / r.reads as f64) |
| 654 | }) |
| 655 | .collect(), |
| 656 | ), |
| 657 | energy_refusals: refusals, |
| 658 | w_ratio: 0.0, |
| 659 | r_ratio: 0.0, |
| 660 | s_ratio: 0.0, |
| 661 | eligible: false, |
| 662 | }); |
| 663 | } |
| 664 | let c0 = configs.iter().find(|c| c.config == "C0").cloned(); |
| 665 | if c0.is_none() { |
| 666 | invalid.push("control C0 missing".into()); |
| 667 | } |
| 668 | if let Some(c0) = &c0 { |
| 669 | for c in configs.iter_mut() { |
| 670 | c.w_ratio = c.w_s_per_change / c0.w_s_per_change; |
| 671 | c.r_ratio = c.r_s_per_read / c0.r_s_per_read; |
| 672 | c.s_ratio = c.s_log_bytes as f64 / c0.s_log_bytes as f64; |
| 673 | c.eligible = c.config != "C0" |
| 674 | && c.w_s_per_change <= 1.10 * c0.w_s_per_change |
| 675 | && c.r_s_per_read <= 1.25 * c0.r_s_per_read |
| 676 | && (c.s_log_bytes as f64) <= 0.95 * c0.s_log_bytes as f64; |
| 677 | } |
| 678 | } |
| 679 | let valid = invalid.is_empty(); |
| 680 | let eligible: Vec<&ConfigReport> = configs.iter().filter(|c| c.eligible).collect(); |
| 681 | let winner = if valid { |
| 682 | eligible |
| 683 | .iter() |
| 684 | .map(|c| c.s_log_bytes) |
| 685 | .min() |
| 686 | .and_then(|best| { |
| 687 | eligible |
| 688 | .iter() |
| 689 | .filter(|c| (c.s_log_bytes as f64) <= best as f64 * 1.01) |
| 690 | .max_by_key(|c| (c.params.avg_bytes, c.params.threshold_bytes)) |
| 691 | .map(|c| (*c).clone()) |
| 692 | }) |
| 693 | } else { |
| 694 | None |
| 695 | }; |
| 696 | X6Report { |
| 697 | eligible: eligible.iter().map(|c| c.config.clone()).collect(), |
| 698 | winner_params: winner.as_ref().map_or(ChunkParams::OFF, |c| c.params), |
| 699 | winner: winner.map(|c| c.config), |
| 700 | configs, |
| 701 | valid, |
| 702 | invalid_reasons: invalid, |
| 703 | flush_bound_s: A2_FLUSH_BOUND_S, |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | /// Default scratch directory for the stores of a run. |
| 708 | pub fn default_scratch() -> PathBuf { |
| 709 | std::env::temp_dir().join("synapse-x6") |
| 710 | } |
| 711 | |
| 712 | #[cfg(test)] |
| 713 | mod tests { |
| 714 | use super::*; |
| 715 | |
| 716 | fn run(config: &str, rep: usize, w_ns: u64, r_ns: u64, s: u64) -> RunRaw { |
| 717 | RunRaw { |
| 718 | config: config.into(), |
| 719 | params: configurations() |
| 720 | .into_iter() |
| 721 | .find(|(i, _)| *i == config) |
| 722 | .unwrap() |
| 723 | .1, |
| 724 | rep, |
| 725 | position_in_rep: 0, |
| 726 | accepted: 1000, |
| 727 | ingest_elapsed_ns: w_ns * 1000, |
| 728 | ingest_latency_ns: vec![w_ns; 4], |
| 729 | ingest_energy: EnergyReading::default(), |
| 730 | log_bytes: s, |
| 731 | content_bytes: s / 2, |
| 732 | inline_blob_bytes: 0, |
| 733 | chunks: 0, |
| 734 | chunk_bytes: 0, |
| 735 | chunked_blobs: 0, |
| 736 | batches: 1000, |
| 737 | reads: 100, |
| 738 | read_bytes: 100 * 4096, |
| 739 | read_elapsed_ns: r_ns * 100, |
| 740 | read_ns: vec![r_ns; 4], |
| 741 | read_energy: EnergyReading::default(), |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | fn raw(runs: Vec<RunRaw>) -> X6Raw { |
| 746 | X6Raw { |
| 747 | corpus: vec![], |
| 748 | changes: 1000, |
| 749 | revisions: 0, |
| 750 | revision_bytes: 0, |
| 751 | distinct_blobs: 100, |
| 752 | distinct_blob_bytes: 0, |
| 753 | max_paths_per_changeset: 1, |
| 754 | max_total_changeset_bytes: 1, |
| 755 | idle: EnergyReading::default(), |
| 756 | runs, |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | #[test] |
| 761 | fn x6_decision_follows_the_rule() { |
| 762 | let mut runs = Vec::new(); |
| 763 | for rep in 0..3 { |
| 764 | runs.push(run("C0", rep, 1_000_000, 10_000, 1000)); |
| 765 | // Eligible, smallest S. |
| 766 | runs.push(run("K1", rep, 1_050_000, 11_000, 800)); |
| 767 | // Within 1 % of K1 with a larger avg: wins the tie. |
| 768 | runs.push(run("K4", rep, 1_090_000, 12_000, 805)); |
| 769 | // Too slow to ingest. |
| 770 | runs.push(run("K2", rep, 1_200_000, 10_000, 700)); |
| 771 | // Too slow to read. |
| 772 | runs.push(run("K3", rep, 1_000_000, 13_000, 700)); |
| 773 | // Saves under 5 %. |
| 774 | runs.push(run("K7", rep, 1_000_000, 10_000, 960)); |
| 775 | } |
| 776 | let r = decide(&raw(runs.clone())); |
| 777 | assert!(r.valid); |
| 778 | assert_eq!(r.eligible, vec!["K1".to_string(), "K4".to_string()]); |
| 779 | assert_eq!(r.winner.as_deref(), Some("K4")); |
| 780 | assert_eq!( |
| 781 | r.winner_params, |
| 782 | ChunkParams::candidate(64 * 1024, 16 * 1024) |
| 783 | ); |
| 784 | |
| 785 | // Repetitions that disagree on log bytes make the run invalid: no winner. |
| 786 | let mut bad = runs.clone(); |
| 787 | bad[1].log_bytes += 1; |
| 788 | let r = decide(&raw(bad)); |
| 789 | assert!(!r.valid && r.winner.is_none()); |
| 790 | |
| 791 | // Nothing eligible: chunking stays off. |
| 792 | let only: Vec<RunRaw> = runs |
| 793 | .into_iter() |
| 794 | .filter(|r| r.config == "C0" || r.config == "K7") |
| 795 | .collect(); |
| 796 | let r = decide(&raw(only)); |
| 797 | assert!(r.valid && r.winner.is_none()); |
| 798 | assert_eq!(r.winner_params, ChunkParams::OFF); |
| 799 | } |
| 800 | } |