Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-bench/src/c1.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-bench / src / c1.rs` 491 lines ยท 18596 bytes Raw Blame History 1 //! C1 measurement (ADR 0003 section 9 step 4): the shared Merkle tree on the Gate 4 query load. 2 //! 3 //! One process, one reader thread, no concurrent writers. The population is the Gate 4 query 4 //! cell's (`generate_write_workload(seed, 10_000 + rep, agents, ops_per_agent, ..)`, the same 5 //! proposals committed to Git through the plumbing path). Then, in order: 6 //! 7 //! 1. Parity: the base tree and every changeset's tree and diff from the signed `tree` and 8 //! `diff` APIs, per entry and in order, against `git ls-tree -r` and `git diff-tree -r`. 9 //! 2. The tree cache is replaced by an empty one bounded by `cache_bytes` (base pinned). 10 //! 3. Cold (build): every changeset root once, in a seeded shuffled order, timed around 11 //! `tree_digest` (the build reads the upserted blobs for their Git ids, edits the base tree 12 //! along the touched paths, encodes and hashes the new nodes). Bound: (upserted blob bytes 13 //! read plus new node bytes written) / memory bandwidth. 14 //! 4. Warm (paging): `samples` full listings of random changesets in pages of 256, timed at 15 //! the engine (`tree_page`) and separately at the API (`tree`, authorization included, 16 //! request signing and encoding excluded, as Gate 4's `api_only`). Bound: encoded bytes 17 //! of the tree's distinct nodes / memory bandwidth. 18 //! 5. Diff (warm): `samples` engine diffs base to changeset, timed; no bound is derived. 19 //! 20 //! The memory bound used is the physical 273 GB/s (A0, `docs/A0_HOST_BOUNDS.md`). Each sample 21 //! records whether it built a tree, so a cold rebuild after eviction is never counted as warm. 22 23 use crate::energy::{EnergyReading, EnergyWindow}; 24 use crate::fixture; 25 use crate::rng::SplitMix64; 26 use crate::rusage::sample_self; 27 use crate::stats::{round3, summarize_us, LatencySummary}; 28 use crate::synapse_arm; 29 use crate::tree_parity::{first_mismatch, ParityPair}; 30 use crate::workload::{generate_write_workload, EditOp, Proposal}; 31 use crate::{write_json, write_jsonl}; 32 use serde::{Deserialize, Serialize}; 33 use std::path::PathBuf; 34 use std::time::Instant; 35 use synapse_api::{ 36 PageRequest, TreeCacheConfig, TreeQueryPayload, TreeStoreStats, TreeTarget, 37 DEFAULT_MAX_PAGE_SIZE, 38 }; 39 use synapse_core::ChangesetId; 40 41 /// Physical memory bandwidth of the host, bytes per second (A0: NVIDIA DGX Spark, 273 GB/s). 42 pub const MEMORY_BANDWIDTH_BPS: f64 = 273e9; 43 44 /// Input of one C1 measurement. 45 #[derive(Debug, Clone, Serialize, Deserialize)] 46 pub struct C1Spec { 47 pub clone_dir: PathBuf, 48 pub base_commit: String, 49 pub seed: u64, 50 pub rep: usize, 51 pub agents: usize, 52 pub ops_per_agent: usize, 53 pub samples: usize, 54 pub cache_bytes: usize, 55 pub work_dir: PathBuf, 56 pub out_dir: PathBuf, 57 /// Skip the parity pass (a second run on the same population need not repeat it). 58 pub skip_parity: bool, 59 } 60 61 /// One timed sample. 62 #[derive(Debug, Clone, Serialize, Deserialize)] 63 pub struct C1Trace { 64 pub phase: String, 65 pub sample: usize, 66 pub changeset_index: usize, 67 pub latency_ns: u64, 68 /// Bytes the bound charges for this sample (see the module documentation). 69 pub bound_bytes: Option, 70 pub bound_ns: Option, 71 /// bound / measured. 72 pub fraction_of_bound: Option, 73 /// Changeset roots built during the sample (0 = warm). 74 pub root_builds: u64, 75 pub new_nodes: u64, 76 pub pages: Option, 77 pub entries: Option, 78 } 79 80 /// Summary of one phase. 81 #[derive(Debug, Clone, Serialize, Deserialize)] 82 pub struct C1PhaseSummary { 83 pub phase: String, 84 pub method: String, 85 pub samples: usize, 86 pub latency: Option, 87 pub samples_that_built: usize, 88 pub bound_bytes_p50: Option, 89 pub bound_ms_p50: Option, 90 /// Median of the per-sample fractions of the bound. 91 pub fraction_of_bound_p50: Option, 92 pub energy: Option, 93 } 94 95 /// Parity result. 96 #[derive(Debug, Clone, Serialize, Deserialize)] 97 pub struct C1Parity { 98 pub check: String, 99 pub compared_trees: usize, 100 pub compared_entries: usize, 101 pub mismatched_trees: usize, 102 pub first_mismatch: Option, 103 } 104 105 /// C1 report. 106 #[derive(Debug, Clone, Serialize, Deserialize)] 107 pub struct C1Report { 108 pub spec: C1Spec, 109 pub base_files: usize, 110 pub base_tree_encoded_bytes: u64, 111 pub base_tree_nodes: u64, 112 pub population_changesets: usize, 113 pub populate_s: f64, 114 pub parity: Vec, 115 pub memory_bandwidth_bps: f64, 116 pub phases: Vec, 117 pub cache_after: TreeStoreStats, 118 pub cache_bound_held: bool, 119 pub peak_rss_self_kib: u64, 120 pub loadavg_start: Option<[f64; 3]>, 121 pub loadavg_end: Option<[f64; 3]>, 122 pub notes: Vec, 123 } 124 125 fn upserted_bytes(p: &Proposal) -> u64 { 126 p.edits 127 .iter() 128 .map(|e| match &e.op { 129 EditOp::Upsert { content, .. } => content.len() as u64, 130 EditOp::Delete => 0, 131 }) 132 .sum() 133 } 134 135 /// (bound in ns, bound / measured) for `bytes` at the memory bandwidth. 136 fn bound(bytes: u64, latency_ns: u64) -> (Option, Option) { 137 let bound_ns = bytes as f64 / MEMORY_BANDWIDTH_BPS * 1e9; 138 let frac = (latency_ns > 0).then(|| bound_ns / latency_ns as f64); 139 (Some(bound_ns), frac) 140 } 141 142 fn median_u64(mut v: Vec) -> Option { 143 v.sort_unstable(); 144 crate::stats::nearest_rank(&v, 0.5) 145 } 146 147 fn median_f64(mut v: Vec) -> Option { 148 if v.is_empty() { 149 return None; 150 } 151 v.sort_by(|a, b| a.total_cmp(b)); 152 Some(v[(v.len() - 1) / 2]) 153 } 154 155 fn summarize( 156 phase: &str, 157 method: &str, 158 rows: &[C1Trace], 159 energy: Option, 160 ) -> C1PhaseSummary { 161 let lat_us: Vec = rows.iter().map(|r| r.latency_ns / 1000).collect(); 162 let bytes: Vec = rows.iter().filter_map(|r| r.bound_bytes).collect(); 163 let fractions: Vec = rows.iter().filter_map(|r| r.fraction_of_bound).collect(); 164 let bytes_p50 = median_u64(bytes); 165 C1PhaseSummary { 166 phase: phase.to_string(), 167 method: method.to_string(), 168 samples: rows.len(), 169 latency: summarize_us(&lat_us), 170 samples_that_built: rows.iter().filter(|r| r.root_builds > 0).count(), 171 bound_bytes_p50: bytes_p50, 172 bound_ms_p50: bytes_p50.map(|b| b as f64 / MEMORY_BANDWIDTH_BPS * 1e3), 173 fraction_of_bound_p50: median_f64(fractions), 174 energy, 175 } 176 } 177 178 fn trace(phase: &str, sample: usize, idx: usize, latency_ns: u64) -> C1Trace { 179 C1Trace { 180 phase: phase.to_string(), 181 sample, 182 changeset_index: idx, 183 latency_ns, 184 bound_bytes: None, 185 bound_ns: None, 186 fraction_of_bound: None, 187 root_builds: 0, 188 new_nodes: 0, 189 pages: None, 190 entries: None, 191 } 192 } 193 194 fn phase_rows(rows: &[C1Trace], phase: &str) -> Vec { 195 rows.iter().filter(|r| r.phase == phase).cloned().collect() 196 } 197 198 fn new_parity(check: &str) -> C1Parity { 199 C1Parity { 200 check: check.to_string(), 201 compared_trees: 0, 202 compared_entries: 0, 203 mismatched_trees: 0, 204 first_mismatch: None, 205 } 206 } 207 208 fn record_parity(p: &mut C1Parity, k: usize, git: &[String], syn: &[String]) { 209 p.compared_trees += 1; 210 p.compared_entries += git.len(); 211 if let Some(m) = first_mismatch(git, syn) { 212 p.mismatched_trees += 1; 213 p.first_mismatch.get_or_insert(format!("target {k}: {m:?}")); 214 } 215 } 216 217 /// Run the C1 measurement and write `report.json` plus `traces.jsonl` under `out_dir`. 218 pub fn run_c1(spec: &C1Spec) -> Result { 219 std::fs::create_dir_all(&spec.work_dir).map_err(|e| format!("mkdir work: {e}"))?; 220 let loadavg_start = crate::energy::loadavg(); 221 let clone = spec.clone_dir.as_path(); 222 let t = Instant::now(); 223 let mut pair = ParityPair::open( 224 clone, 225 &spec.base_commit, 226 &spec.work_dir, 227 spec.seed, 228 spec.agents, 229 )?; 230 let base_target = TreeTarget::BaseGitCommit(pair.base_oid); 231 let listed = fixture::list_base_tree(clone, &spec.base_commit)?; 232 let base_files = listed.entries.len(); 233 let files = { 234 let full = fixture::load_full_base(clone, &listed)?; 235 fixture::editable_from_full_base(&listed, &full) 236 }; 237 let workload = generate_write_workload( 238 spec.seed, 239 10_000 + spec.rep, 240 spec.agents, 241 spec.ops_per_agent, 242 &files, 243 ); 244 drop(files); 245 let mut pop: Vec<(ChangesetId, String, Proposal)> = Vec::new(); 246 for p in workload.iter().flatten() { 247 let (cs, commit) = pair.apply(p)?; 248 pop.push((cs, commit, p.clone())); 249 } 250 pair.svc.store_mut().sync_wal().map_err(|e| e.to_string())?; 251 let populate_s = round3(t.elapsed().as_secs_f64()); 252 let n = pop.len(); 253 if n == 0 { 254 return Err("empty population".into()); 255 } 256 257 // 1. Parity, per entry, the base tree and every changeset. 258 let mut parity = Vec::new(); 259 if !spec.skip_parity { 260 let mut tree = new_parity( 261 "tree entries (mode, type, object id, path, order) vs git ls-tree -r --full-tree", 262 ); 263 let mut diff = new_parity( 264 "diff entries (modes, object ids, status, path, order) vs git diff-tree -r --raw --no-renames, base to changeset", 265 ); 266 let (git, syn) = pair.tree_pair(base_target, &spec.base_commit)?; 267 record_parity(&mut tree, 0, &git, &syn); 268 for (k, (cs, commit, _)) in pop.iter().enumerate() { 269 let target = TreeTarget::Changeset(*cs); 270 let (git, syn) = pair.tree_pair(target, commit)?; 271 record_parity(&mut tree, k + 1, &git, &syn); 272 let (git, syn) = pair.diff_pair(target, commit)?; 273 record_parity(&mut diff, k + 1, &git, &syn); 274 } 275 parity.push(tree); 276 parity.push(diff); 277 } 278 279 // 2. Fresh bounded cache (base pinned, no changeset root memoized). 280 pair.svc 281 .set_tree_cache_config(TreeCacheConfig { 282 max_bytes: spec.cache_bytes, 283 }) 284 .map_err(|e| e.to_string())?; 285 let (base_bytes, base_nodes) = pair 286 .svc 287 .tree_encoded_bytes(base_target, None) 288 .map_err(|e| e.to_string())?; 289 let mut rng = SplitMix64::derive(spec.seed, &[spec.rep as u64, 0xC1]); 290 let mut rows: Vec = Vec::new(); 291 let mut phases = Vec::new(); 292 let mut bound_held = true; 293 let check_bound = |pair: &ParityPair, held: &mut bool| { 294 if pair.svc.tree_store().stats().total_bytes > spec.cache_bytes { 295 *held = false; 296 } 297 }; 298 299 // 3. Cold: every changeset root once, shuffled. 300 let mut order: Vec = (0..n).collect(); 301 for i in (1..n).rev() { 302 order.swap(i, rng.below(i + 1)); 303 } 304 let window = EnergyWindow::start(); 305 for (s, &i) in order.iter().enumerate() { 306 let before = pair.svc.tree_store().stats(); 307 let start = Instant::now(); 308 pair.svc 309 .tree_digest(TreeTarget::Changeset(pop[i].0), None) 310 .map_err(|e| e.to_string())?; 311 let ns = start.elapsed().as_nanos() as u64; 312 let after = pair.svc.tree_store().stats(); 313 check_bound(&pair, &mut bound_held); 314 let mut r = trace("cold_build", s, i, ns); 315 r.root_builds = after.root_builds - before.root_builds; 316 r.new_nodes = after.nodes_inserted - before.nodes_inserted; 317 let bytes = upserted_bytes(&pop[i].2) 318 + (after.encoded_bytes_inserted - before.encoded_bytes_inserted); 319 r.bound_bytes = Some(bytes); 320 (r.bound_ns, r.fraction_of_bound) = bound(bytes, ns); 321 rows.push(r); 322 } 323 let energy = window.finish(); 324 phases.push(summarize( 325 "cold_build", 326 "SynapseService::tree_digest on a changeset whose root is not memoized (engine only): read upserted blobs for Git ids, edit the touched paths, encode and SHA-256 the new nodes", 327 &phase_rows(&rows, "cold_build"), 328 Some(energy), 329 )); 330 331 // 4a. Warm paging at the engine. 332 let picks: Vec = (0..spec.samples).map(|_| rng.below(n)).collect(); 333 let window = EnergyWindow::start(); 334 for (s, &i) in picks.iter().enumerate() { 335 let target = TreeTarget::Changeset(pop[i].0); 336 let (bytes, _) = pair 337 .svc 338 .tree_encoded_bytes(target, None) 339 .map_err(|e| e.to_string())?; 340 let before = pair.svc.tree_store().stats(); 341 let start = Instant::now(); 342 let (total, first) = pair 343 .svc 344 .tree_page(target, "", 0, DEFAULT_MAX_PAGE_SIZE, None) 345 .map_err(|e| e.to_string())?; 346 let mut seen = first.len() as u64; 347 let mut pages = 1; 348 while seen < total { 349 let (_, page) = pair 350 .svc 351 .tree_page(target, "", seen, DEFAULT_MAX_PAGE_SIZE, None) 352 .map_err(|e| e.to_string())?; 353 seen += page.len() as u64; 354 pages += 1; 355 } 356 let ns = start.elapsed().as_nanos() as u64; 357 let after = pair.svc.tree_store().stats(); 358 check_bound(&pair, &mut bound_held); 359 let mut r = trace("warm_page_engine", s, i, ns); 360 r.root_builds = after.root_builds - before.root_builds; 361 r.new_nodes = after.nodes_inserted - before.nodes_inserted; 362 r.pages = Some(pages); 363 r.entries = Some(seen); 364 r.bound_bytes = Some(bytes); 365 (r.bound_ns, r.fraction_of_bound) = bound(bytes, ns); 366 rows.push(r); 367 } 368 let energy = window.finish(); 369 phases.push(summarize( 370 "warm_page_engine", 371 "SynapseService::tree_page, every page of 256 entries of a changeset tree (engine only)", 372 &phase_rows(&rows, "warm_page_engine"), 373 Some(energy), 374 )); 375 376 // 4b. Warm paging at the API (authorization included; signing excluded). 377 let reader = pair.ids.agents[0].clone(); 378 let repo_id = pair.ids.repo_id.clone(); 379 let mut counter = 0u64; 380 for (s, &i) in picks.iter().enumerate() { 381 let target = TreeTarget::Changeset(pop[i].0); 382 let (bytes, _) = pair 383 .svc 384 .tree_encoded_bytes(target, None) 385 .map_err(|e| e.to_string())?; 386 let before = pair.svc.tree_store().stats(); 387 let (mut cursor, mut snapshot) = (None, None); 388 let (mut ns, mut pages, mut entries) = (0u64, 0usize, 0u64); 389 loop { 390 counter += 1; 391 let now = crate::unix_now_ms(); 392 let payload = TreeQueryPayload { 393 target, 394 path_prefix: None, 395 page: PageRequest { 396 cursor: cursor.clone(), 397 limit: DEFAULT_MAX_PAGE_SIZE, 398 min_visible_seq: None, 399 snapshot_seq: snapshot, 400 }, 401 }; 402 let req = synapse_arm::build_read_request( 403 &reader, 404 &repo_id, 405 payload, 406 &format!("c1/warm-api/{counter}"), 407 now, 408 )?; 409 let start = Instant::now(); 410 let resp = pair.svc.tree(&req, now).map_err(|e| e.to_string())?; 411 ns += start.elapsed().as_nanos() as u64; 412 pages += 1; 413 entries += resp.items.len() as u64; 414 snapshot = Some(resp.snapshot_seq); 415 match resp.next_cursor { 416 Some(c) => cursor = Some(c), 417 None => break, 418 } 419 } 420 let after = pair.svc.tree_store().stats(); 421 check_bound(&pair, &mut bound_held); 422 let mut r = trace("warm_page_api", s, i, ns); 423 r.root_builds = after.root_builds - before.root_builds; 424 r.new_nodes = after.nodes_inserted - before.nodes_inserted; 425 r.pages = Some(pages); 426 r.entries = Some(entries); 427 r.bound_bytes = Some(bytes); 428 (r.bound_ns, r.fraction_of_bound) = bound(bytes, ns); 429 rows.push(r); 430 } 431 phases.push(summarize( 432 "warm_page_api", 433 "SynapseService::tree, every page (request authorization plus engine; client signing and wire encoding excluded, as Gate 4 api_only)", 434 &phase_rows(&rows, "warm_page_api"), 435 None, 436 )); 437 438 // 5. Warm diff at the engine (no bound derived). 439 let diff_picks: Vec = (0..spec.samples).map(|_| rng.below(n)).collect(); 440 for (s, &i) in diff_picks.iter().enumerate() { 441 let before = pair.svc.tree_store().stats(); 442 let start = Instant::now(); 443 let d = pair 444 .svc 445 .diff_trees(base_target, TreeTarget::Changeset(pop[i].0), None) 446 .map_err(|e| e.to_string())?; 447 let ns = start.elapsed().as_nanos() as u64; 448 let after = pair.svc.tree_store().stats(); 449 check_bound(&pair, &mut bound_held); 450 let mut r = trace("warm_diff_engine", s, i, ns); 451 r.root_builds = after.root_builds - before.root_builds; 452 r.new_nodes = after.nodes_inserted - before.nodes_inserted; 453 r.entries = Some(d.len() as u64); 454 rows.push(r); 455 } 456 phases.push(summarize( 457 "warm_diff_engine", 458 "SynapseService::diff_trees base to changeset (engine only; skips equal subtrees)", 459 &phase_rows(&rows, "warm_diff_engine"), 460 None, 461 )); 462 463 let cache_after = pair.svc.tree_store().stats(); 464 if cache_after.high_water_bytes > spec.cache_bytes { 465 bound_held = false; 466 } 467 let report = C1Report { 468 spec: spec.clone(), 469 base_files, 470 base_tree_encoded_bytes: base_bytes, 471 base_tree_nodes: base_nodes, 472 population_changesets: n, 473 populate_s, 474 parity, 475 memory_bandwidth_bps: MEMORY_BANDWIDTH_BPS, 476 phases, 477 cache_after, 478 cache_bound_held: bound_held, 479 peak_rss_self_kib: sample_self()?.maxrss_kib, 480 loadavg_start, 481 loadavg_end: crate::energy::loadavg(), 482 notes: vec![ 483 "Bound: physical memory bandwidth 273 GB/s (A0). Cold: (upserted blob bytes + new node encoded bytes) / bandwidth. Warm: encoded bytes of the tree's distinct nodes / bandwidth. fraction_of_bound = bound / measured.".into(), 484 "Energy windows are whole-phase SPBM readings (provisional, uncalibrated, 10 Hz; see energy.rs refusal rules); no idle baseline is subtracted. A refused window reports no joules.".into(), 485 "peak_rss_self_kib covers the whole process: the loaded base blobs, the store, the parity pass, and Git plumbing buffers, not the tree cache alone.".into(), 486 ], 487 }; 488 write_jsonl(&spec.out_dir.join("traces.jsonl"), &rows)?; 489 write_json(&spec.out_dir.join("report.json"), &report)?; 490 Ok(report) 491 }