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/orchestrator.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 / orchestrator.rs` 1124 lines ยท 40328 bytes Raw Blame History 1 //! Run orchestration: preflight, isolated fixture clones, one child process per cell, 2 //! and the aggregated `report.json` and `manifest.json`. 3 //! 4 //! The original fixture repository is only read: it is cloned once with 5 //! `git clone --no-checkout --no-hardlinks` into the work directory (no shared inodes), 6 //! and every cell then clones that master copy. A digest of the original's refs and 7 //! `HEAD` is recorded before and after the run. 8 9 use crate::conflict::{run_conflict_cell, ConflictResult, ConflictSpec}; 10 use crate::conformance::{run_suite, CaseOutcome, SuiteResult}; 11 use crate::energy::EnergyReading; 12 use crate::fixture::{self, clone_no_checkout, configure_bench_clone}; 13 use crate::gitcmd::{git_line, git_ok}; 14 use crate::host::{self, FsyncProbe, GitConfigValue, HostInfo, UNKNOWN}; 15 use crate::query::{run_query_cell, QueryCellResult, QuerySpec}; 16 use crate::recovery::{ 17 run_import_probe, run_recovery_cell, ImportProbeResult, ImportProbeSpec, RecoveryResult, 18 RecoverySpec, 19 }; 20 use crate::rng::SplitMix64; 21 use crate::stats::{round3, spread, Spread}; 22 use crate::write_phase::{du_total, run_write_cell, ArmKind, WriteCellResult, WriteCellSpec}; 23 use crate::{path_str, read_json, utc_timestamp, write_json}; 24 use serde::de::DeserializeOwned; 25 use serde::{Deserialize, Serialize}; 26 use sha2::{Digest, Sha256}; 27 use std::path::{Path, PathBuf}; 28 use std::process::{Command, Stdio}; 29 use std::time::Instant; 30 31 /// Report schema identifier. 32 pub const REPORT_SCHEMA: &str = "synapse-gate4-qualification-report/v1"; 33 /// Manifest schema identifier. 34 pub const MANIFEST_SCHEMA: &str = "synapse-gate4-qualification-manifest/v1"; 35 /// Default master seed (recorded in the manifest). 36 pub const DEFAULT_SEED: u64 = 0x6A7E_4000_2026_1014; 37 38 /// Full run configuration (recorded verbatim in the manifest). 39 #[derive(Debug, Clone, Serialize, Deserialize)] 40 pub struct RunConfig { 41 pub fixture_repo: PathBuf, 42 pub fixture_rev: String, 43 pub out_dir: PathBuf, 44 pub work_dir: PathBuf, 45 pub reps: usize, 46 pub tiers: Vec, 47 pub arms: Vec, 48 pub seed: u64, 49 /// Minimum operations per write cell for every arm except G1. 50 pub ops_floor: usize, 51 pub min_ops_per_agent: usize, 52 /// G1 creates one full checkout per operation; its cells are capped at 53 /// `max(2, ceil(g1_ops_cap / agents))` operations per agent. 54 pub g1_ops_cap: usize, 55 pub batch_window_records: u32, 56 pub query_agents: usize, 57 pub query_ops_per_agent: usize, 58 pub query_samples: usize, 59 pub recovery_sizes: Vec, 60 pub recovery_reopen_reps: usize, 61 pub radicle_repo: Option, 62 pub source_rev: String, 63 pub source_dirty: String, 64 pub source_digest: String, 65 pub smoke: bool, 66 pub command_line: Vec, 67 /// Run only the write cells (no query, conformance, conflict, recovery or import cells). 68 #[serde(default)] 69 pub write_only: bool, 70 /// Length of the IDLE energy window measured before the cells, seconds. 71 #[serde(default)] 72 pub idle_window_s: f64, 73 } 74 75 impl RunConfig { 76 /// Full-run defaults. 77 pub fn new( 78 fixture_repo: PathBuf, 79 fixture_rev: String, 80 out_dir: PathBuf, 81 work_dir: PathBuf, 82 ) -> Self { 83 Self { 84 fixture_repo, 85 fixture_rev, 86 out_dir, 87 work_dir, 88 reps: 3, 89 tiers: vec![1, 4, 8, 32], 90 arms: ArmKind::ALL.to_vec(), 91 seed: DEFAULT_SEED, 92 ops_floor: 400, 93 min_ops_per_agent: 8, 94 g1_ops_cap: 32, 95 batch_window_records: 64, 96 query_agents: 8, 97 query_ops_per_agent: 50, 98 query_samples: 400, 99 recovery_sizes: vec![100, 1_000, 10_000], 100 recovery_reopen_reps: 3, 101 radicle_repo: None, 102 source_rev: UNKNOWN.into(), 103 source_dirty: UNKNOWN.into(), 104 source_digest: UNKNOWN.into(), 105 smoke: false, 106 command_line: Vec::new(), 107 write_only: false, 108 idle_window_s: 10.0, 109 } 110 } 111 112 /// Shrink every dimension for a quick end-to-end check of the harness. 113 pub fn apply_smoke(&mut self) { 114 self.smoke = true; 115 self.reps = 1; 116 self.tiers = vec![1, 4]; 117 self.ops_floor = 16; 118 self.min_ops_per_agent = 4; 119 self.g1_ops_cap = 4; 120 self.query_agents = 2; 121 self.query_ops_per_agent = 8; 122 self.query_samples = 20; 123 self.recovery_sizes = vec![50]; 124 self.recovery_reopen_reps = 2; 125 } 126 127 /// Operations per agent for `arm` at `agents` concurrency. 128 pub fn ops_per_agent(&self, arm: ArmKind, agents: usize) -> usize { 129 let agents = agents.max(1); 130 if arm == ArmKind::G1 { 131 self.g1_ops_cap.div_ceil(agents).max(2) 132 } else { 133 self.ops_floor.div_ceil(agents).max(self.min_ops_per_agent) 134 } 135 } 136 } 137 138 /// Input for the conformance child. 139 #[derive(Debug, Clone, Serialize, Deserialize)] 140 pub struct ConformanceSpec { 141 pub suites: Vec, 142 pub work_dir: PathBuf, 143 pub radicle_repo: Option, 144 } 145 146 /// One planned cell, in execution order. 147 #[derive(Debug, Clone, Serialize, Deserialize)] 148 pub struct CellPlanEntry { 149 pub order: usize, 150 pub label: String, 151 pub kind: String, 152 pub arm: Option, 153 pub agents: Option, 154 pub ops_per_agent: Option, 155 pub rep: Option, 156 } 157 158 /// A cell that did not produce a result. 159 #[derive(Debug, Clone, Serialize, Deserialize)] 160 pub struct CellFailure { 161 pub label: String, 162 pub kind: String, 163 pub error: String, 164 } 165 166 /// Wall time of one executed cell (including its clone, excluded from measurements). 167 #[derive(Debug, Clone, Serialize, Deserialize)] 168 pub struct CellTiming { 169 pub label: String, 170 pub clone_ms: f64, 171 pub child_wall_ms: f64, 172 pub ok: bool, 173 } 174 175 /// Arm metadata. 176 #[derive(Debug, Clone, Serialize, Deserialize)] 177 pub struct ArmInfo { 178 pub code: String, 179 pub description: String, 180 pub durability: String, 181 } 182 183 /// Aggregate of one arm at one concurrency tier across repetitions. 184 #[derive(Debug, Clone, Serialize, Deserialize)] 185 pub struct ArmTierSummary { 186 pub arm: ArmKind, 187 pub agents: usize, 188 pub ops_per_agent: usize, 189 pub reps: usize, 190 pub ops_ok_total: usize, 191 pub ops_failed_total: usize, 192 pub latency_n_per_rep: Vec, 193 pub throughput_ops_per_s: Option, 194 pub latency_p50_ms: Option, 195 /// Present only when every repetition had at least 20 samples. 196 pub latency_p95_ms: Option, 197 /// Present only when every repetition had at least 100 samples. 198 pub latency_p99_ms: Option, 199 pub latency_max_ms: Option, 200 pub queue_wait_p50_ms: Option, 201 pub cpu_ms_per_op: Option, 202 pub peak_rss_arm_process_kib: Option, 203 pub peak_rss_largest_git_child_kib: Option, 204 pub setup_description: String, 205 pub setup_units: usize, 206 pub setup_ms_per_unit: Option, 207 pub storage_setup_apparent_bytes: Option, 208 pub storage_ops_apparent_bytes_per_op: Option, 209 pub storage_ops_allocated_bytes_per_op: Option, 210 pub mean_wire_bytes: Option, 211 pub final_sync_ms: Option, 212 /// Wall time per acknowledged change: timed window divided by acknowledged changes, ms. 213 #[serde(default)] 214 pub ms_per_change: Option, 215 /// SoC package energy per acknowledged change over the timed window, mJ. 216 #[serde(default)] 217 pub pkg_mj_per_change: Option, 218 /// As `pkg_mj_per_change` minus the idle package power times the window, mJ 219 /// (COUNTERFACTUAL: idle measured in a separate window). 220 #[serde(default)] 221 pub pkg_mj_per_change_above_idle: Option, 222 /// Mean SoC package power over the timed window, W. 223 #[serde(default)] 224 pub pkg_mean_w: Option, 225 } 226 227 /// Compact headline row (medians across repetitions). 228 #[derive(Debug, Clone, Serialize, Deserialize)] 229 pub struct HeadlineRow { 230 pub agents: usize, 231 pub arm: ArmKind, 232 pub ops_per_cell: usize, 233 pub throughput_ops_per_s_median: Option, 234 pub write_p50_ms_median: Option, 235 pub write_p99_ms_median: Option, 236 } 237 238 /// Aggregate of one query method across repetitions. 239 #[derive(Debug, Clone, Serialize, Deserialize)] 240 pub struct QuerySummaryRow { 241 pub query: String, 242 pub system: String, 243 pub method: String, 244 pub n_per_rep: Vec, 245 pub failures_total: usize, 246 pub p50_ms: Option, 247 pub p95_ms: Option, 248 pub p99_ms: Option, 249 pub api_only_p50_ms: Option, 250 pub mean_pages: Option, 251 pub mean_response_bytes: Option, 252 } 253 254 /// Conformance outcome per suite across runs. 255 #[derive(Debug, Clone, Serialize, Deserialize)] 256 pub struct ConformanceSummary { 257 pub suite: String, 258 pub runs: usize, 259 pub cases: usize, 260 pub passed_per_run: Vec, 261 pub failed_per_run: Vec, 262 pub skipped_per_run: Vec, 263 /// Every case had the same outcome in every run. 264 pub outcomes_identical_across_runs: bool, 265 } 266 267 /// `report.json`. 268 #[derive(Debug, Clone, Serialize, Deserialize)] 269 pub struct Report { 270 pub schema: String, 271 pub smoke: bool, 272 pub generated_at_utc: String, 273 pub arms: Vec, 274 pub headline: Vec, 275 pub write_summary: Vec, 276 pub write_cells: Vec, 277 pub query_summary: Vec, 278 pub query_cells: Vec, 279 pub conflict: Option, 280 pub conformance_summary: Vec, 281 pub conformance_runs: Vec>, 282 pub recovery: Option, 283 pub import_probe: Option, 284 pub failures: Vec, 285 pub scope_notes: Vec, 286 /// IDLE energy window measured before the cells (absent in Gate 4 reports). 287 #[serde(default)] 288 pub idle_energy: Option, 289 } 290 291 /// Fixture identity and read-only evidence for the original repository. 292 #[derive(Debug, Clone, Serialize, Deserialize)] 293 pub struct FixtureInfo { 294 pub original_repo: String, 295 pub requested_rev: String, 296 pub commit: String, 297 pub tree: String, 298 pub files: usize, 299 pub total_bytes: u64, 300 pub largest_file_bytes: u64, 301 pub skipped_entries: usize, 302 pub editable_files: usize, 303 pub master_clone_method: String, 304 pub master_clone_git_dir_apparent_bytes: u64, 305 pub original_head_before: String, 306 pub original_head_after: String, 307 pub original_refs_sha256_before: String, 308 pub original_refs_sha256_after: String, 309 } 310 311 /// Disk preflight. 312 #[derive(Debug, Clone, Serialize, Deserialize)] 313 pub struct DiskPlan { 314 pub free_bytes_at_start: Option, 315 pub estimated_peak_cell_bytes: u64, 316 pub required_free_bytes: u64, 317 pub min_free_bytes_observed: Option, 318 } 319 320 /// Source tree identity supplied by the run script. 321 #[derive(Debug, Clone, Serialize, Deserialize)] 322 pub struct SourceInfo { 323 pub rev: String, 324 pub dirty: String, 325 pub digest: String, 326 } 327 328 /// `manifest.json`. 329 #[derive(Debug, Clone, Serialize, Deserialize)] 330 pub struct Manifest { 331 pub schema: String, 332 pub smoke: bool, 333 pub started_at_utc: String, 334 pub finished_at_utc: String, 335 pub total_run_s: f64, 336 pub command_line: Vec, 337 pub config: RunConfig, 338 pub host: HostInfo, 339 pub fixture: FixtureInfo, 340 pub bench_clone_config: Vec<(String, String)>, 341 pub git_config: Vec, 342 pub git_config_listing: Vec, 343 pub fsync_probe: FsyncProbe, 344 pub disk: DiskPlan, 345 pub source: SourceInfo, 346 pub cell_order_seed: u64, 347 pub cell_order: Vec, 348 pub cell_timings: Vec, 349 pub trace_files: Vec, 350 } 351 352 fn ms_since(t: Instant) -> f64 { 353 round3(t.elapsed().as_secs_f64() * 1000.0) 354 } 355 356 fn tail(bytes: &[u8], max: usize) -> String { 357 let s = String::from_utf8_lossy(bytes); 358 let start = s.len().saturating_sub(max); 359 let mut idx = start; 360 while !s.is_char_boundary(idx) { 361 idx += 1; 362 } 363 s[idx..].trim().to_string() 364 } 365 366 /// Run one child cell: ` child --kind --spec --result `. 367 fn run_child( 368 exe: &Path, 369 ctl: &Path, 370 kind: &str, 371 label: &str, 372 spec: &S, 373 ) -> Result { 374 let spec_path = ctl.join(format!("{label}.spec.json")); 375 let result_path = ctl.join(format!("{label}.result.json")); 376 write_json(&spec_path, spec)?; 377 let out = Command::new(exe) 378 .args([ 379 "child", 380 "--kind", 381 kind, 382 "--spec", 383 path_str(&spec_path)?, 384 "--result", 385 path_str(&result_path)?, 386 ]) 387 .stdin(Stdio::null()) 388 .output() 389 .map_err(|e| format!("spawn child {label}: {e}"))?; 390 if !out.status.success() { 391 return Err(format!( 392 "child {label} exited {:?}: {}", 393 out.status.code(), 394 tail(&out.stderr, 2000) 395 )); 396 } 397 read_json(&result_path) 398 } 399 400 /// Child entry point: run one cell from a spec file and write its result. 401 pub fn child_main(kind: &str, spec: &Path, result: &Path) -> Result<(), String> { 402 match kind { 403 "write" => { 404 let s: WriteCellSpec = read_json(spec)?; 405 write_json(result, &run_write_cell(&s)?) 406 } 407 "query" => { 408 let s: QuerySpec = read_json(spec)?; 409 write_json(result, &run_query_cell(&s)?) 410 } 411 "conflict" => { 412 let s: ConflictSpec = read_json(spec)?; 413 write_json(result, &run_conflict_cell(&s)?) 414 } 415 "conformance" => { 416 let s: ConformanceSpec = read_json(spec)?; 417 let suites = s 418 .suites 419 .iter() 420 .map(|name| run_suite(name, &s.work_dir.join(name), s.radicle_repo.as_deref())) 421 .collect::, String>>()?; 422 write_json(result, &suites) 423 } 424 "recovery" => { 425 let s: RecoverySpec = read_json(spec)?; 426 write_json(result, &run_recovery_cell(&s)?) 427 } 428 "import-probe" => { 429 let s: ImportProbeSpec = read_json(spec)?; 430 write_json(result, &run_import_probe(&s)?) 431 } 432 other => Err(format!("unknown child kind {other}")), 433 } 434 } 435 436 /// `HEAD` and a SHA-256 over `git for-each-ref` of a repository (read-only commands). 437 fn refs_fingerprint(repo: &Path) -> Result<(String, String), String> { 438 let head = git_line(repo, &["rev-parse", "HEAD"])?; 439 let refs = git_ok( 440 repo, 441 &[], 442 &[], 443 &["for-each-ref", "--format=%(objectname) %(refname)"], 444 None, 445 )?; 446 let mut h = Sha256::new(); 447 h.update(head.as_bytes()); 448 h.update(b"\n"); 449 h.update(&refs); 450 Ok((head, hex::encode(h.finalize()))) 451 } 452 453 fn opt_all(values: &[Option]) -> Option { 454 if values.is_empty() || values.iter().any(Option::is_none) { 455 return None; 456 } 457 let v: Vec = values.iter().flatten().copied().collect(); 458 spread(&v) 459 } 460 461 fn summarize_write( 462 cells: &[WriteCellResult], 463 arms: &[ArmKind], 464 tiers: &[usize], 465 idle: Option<&EnergyReading>, 466 ) -> Vec { 467 let mut out = Vec::new(); 468 for &agents in tiers { 469 for &arm in arms { 470 let reps: Vec<&WriteCellResult> = cells 471 .iter() 472 .filter(|c| c.arm == arm && c.agents == agents) 473 .collect(); 474 if reps.is_empty() { 475 continue; 476 } 477 let f = |g: &dyn Fn(&WriteCellResult) -> Option| -> Option { 478 opt_all(&reps.iter().map(|c| g(c)).collect::>()) 479 }; 480 out.push(ArmTierSummary { 481 arm, 482 agents, 483 ops_per_agent: reps[0].ops_per_agent, 484 reps: reps.len(), 485 ops_ok_total: reps.iter().map(|c| c.ops_ok).sum(), 486 ops_failed_total: reps.iter().map(|c| c.ops_failed).sum(), 487 latency_n_per_rep: reps 488 .iter() 489 .map(|c| c.latency.as_ref().map_or(0, |l| l.n)) 490 .collect(), 491 throughput_ops_per_s: f(&|c| Some(c.throughput_ops_per_s)), 492 latency_p50_ms: f(&|c| c.latency.as_ref().map(|l| l.p50_ms)), 493 latency_p95_ms: f(&|c| c.latency.as_ref().and_then(|l| l.p95_ms)), 494 latency_p99_ms: f(&|c| c.latency.as_ref().and_then(|l| l.p99_ms)), 495 latency_max_ms: f(&|c| c.latency.as_ref().map(|l| l.max_ms)), 496 queue_wait_p50_ms: f(&|c| c.queue_wait.as_ref().map(|l| l.p50_ms)), 497 cpu_ms_per_op: f(&|c| c.cpu_ms_per_op), 498 peak_rss_arm_process_kib: f(&|c| Some(c.cpu.peak_rss_self_kib as f64)), 499 peak_rss_largest_git_child_kib: f(&|c| { 500 (!c.arm.is_synapse()).then_some(c.cpu.peak_rss_largest_child_kib as f64) 501 }), 502 setup_description: reps[0].setup.description.clone(), 503 setup_units: reps[0].setup.units, 504 setup_ms_per_unit: f(&|c| { 505 (c.setup.units > 0).then(|| c.setup.total_ms / c.setup.units as f64) 506 }), 507 storage_setup_apparent_bytes: f(&|c| Some(c.storage.setup_apparent_bytes as f64)), 508 storage_ops_apparent_bytes_per_op: f(&|c| { 509 Some(c.storage.ops_apparent_bytes_per_op) 510 }), 511 storage_ops_allocated_bytes_per_op: f(&|c| { 512 Some(c.storage.ops_allocated_bytes_per_op) 513 }), 514 mean_wire_bytes: f(&|c| c.mean_wire_bytes), 515 final_sync_ms: f(&|c| c.final_sync_ms), 516 ms_per_change: f(&|c| (c.ops_ok > 0).then(|| c.wall_ms / c.ops_ok as f64)), 517 pkg_mj_per_change: f(&|c| c.pkg_j_per_op.map(|j| j * 1000.0)), 518 pkg_mj_per_change_above_idle: f(&|c| { 519 let e = c.energy.as_ref()?; 520 let above = e.pkg_above_idle_j(idle?)?; 521 (c.ops_ok > 0).then(|| above / c.ops_ok as f64 * 1000.0) 522 }), 523 pkg_mean_w: f(&|c| c.energy.as_ref().and_then(|e| e.pkg_mean_w)), 524 }); 525 } 526 } 527 out 528 } 529 530 fn headline(summary: &[ArmTierSummary]) -> Vec { 531 summary 532 .iter() 533 .map(|s| HeadlineRow { 534 agents: s.agents, 535 arm: s.arm, 536 ops_per_cell: s.agents * s.ops_per_agent, 537 throughput_ops_per_s_median: s.throughput_ops_per_s.as_ref().map(|x| x.median), 538 write_p50_ms_median: s.latency_p50_ms.as_ref().map(|x| x.median), 539 write_p99_ms_median: s.latency_p99_ms.as_ref().map(|x| x.median), 540 }) 541 .collect() 542 } 543 544 fn summarize_queries(cells: &[QueryCellResult]) -> Vec { 545 let mut keys: Vec<(String, String, String)> = Vec::new(); 546 for c in cells { 547 for q in &c.queries { 548 let k = (q.query.clone(), q.system.clone(), q.method.clone()); 549 if !keys.contains(&k) { 550 keys.push(k); 551 } 552 } 553 } 554 keys.into_iter() 555 .map(|(query, system, method)| { 556 let rows: Vec<_> = cells 557 .iter() 558 .filter_map(|c| { 559 c.queries 560 .iter() 561 .find(|q| q.query == query && q.system == system && q.method == method) 562 }) 563 .collect(); 564 let f = |g: &dyn Fn(&crate::query::QueryKindResult) -> Option| { 565 opt_all(&rows.iter().map(|r| g(r)).collect::>()) 566 }; 567 QuerySummaryRow { 568 n_per_rep: rows 569 .iter() 570 .map(|r| r.latency.as_ref().map_or(0, |l| l.n)) 571 .collect(), 572 failures_total: rows.iter().map(|r| r.failures).sum(), 573 p50_ms: f(&|r| r.latency.as_ref().map(|l| l.p50_ms)), 574 p95_ms: f(&|r| r.latency.as_ref().and_then(|l| l.p95_ms)), 575 p99_ms: f(&|r| r.latency.as_ref().and_then(|l| l.p99_ms)), 576 api_only_p50_ms: f(&|r| r.api_only.as_ref().map(|l| l.p50_ms)), 577 mean_pages: f(&|r| r.mean_pages), 578 mean_response_bytes: f(&|r| r.mean_response_bytes), 579 query, 580 system, 581 method, 582 } 583 }) 584 .collect() 585 } 586 587 fn summarize_conformance(runs: &[Vec]) -> Vec { 588 let mut names: Vec = Vec::new(); 589 for run in runs { 590 for s in run { 591 if !names.contains(&s.suite) { 592 names.push(s.suite.clone()); 593 } 594 } 595 } 596 names 597 .into_iter() 598 .map(|suite| { 599 let per_run: Vec<&SuiteResult> = runs 600 .iter() 601 .filter_map(|r| r.iter().find(|s| s.suite == suite)) 602 .collect(); 603 let outcomes: Vec> = per_run 604 .iter() 605 .map(|s| { 606 s.cases 607 .iter() 608 .map(|c| (c.case.clone(), c.outcome)) 609 .collect() 610 }) 611 .collect(); 612 ConformanceSummary { 613 runs: per_run.len(), 614 cases: per_run.first().map_or(0, |s| s.cases.len()), 615 passed_per_run: per_run.iter().map(|s| s.passed).collect(), 616 failed_per_run: per_run.iter().map(|s| s.failed).collect(), 617 skipped_per_run: per_run.iter().map(|s| s.skipped).collect(), 618 outcomes_identical_across_runs: outcomes.windows(2).all(|w| w[0] == w[1]), 619 suite, 620 } 621 }) 622 .collect() 623 } 624 625 fn scope_notes() -> Vec { 626 [ 627 "Synapse arms call SynapseService in-process; the JSON encode/decode of each request is included as a transport approximation. No socket, daemon, or network stack is measured.", 628 "Single host, single filesystem; every cell starts from a fresh clone, but the page cache is warm (no cache drop between cells).", 629 "Edits are synthetic (generated hunks, added and deleted files on the real fixture tree); no compiler, tests, or agent reasoning time is included.", 630 "Synapse arms hold the full base tree in memory (registered during setup, excluded from per-operation latency).", 631 "Transfer sizes are estimates: Synapse JSON request bytes versus git thin-pack bytes against the base; neither is a measured network transfer.", 632 ] 633 .iter() 634 .map(|s| s.to_string()) 635 .collect() 636 } 637 638 struct Planned { 639 entry: CellPlanEntry, 640 work: Work, 641 } 642 643 enum Work { 644 Write(WriteCellSpec), 645 Query(QuerySpec), 646 Conformance(ConformanceSpec), 647 Conflict(ConflictSpec), 648 Recovery(RecoverySpec), 649 ImportProbe(ImportProbeSpec), 650 } 651 652 impl Work { 653 fn kind(&self) -> &'static str { 654 match self { 655 Work::Write(_) => "write", 656 Work::Query(_) => "query", 657 Work::Conformance(_) => "conformance", 658 Work::Conflict(_) => "conflict", 659 Work::Recovery(_) => "recovery", 660 Work::ImportProbe(_) => "import-probe", 661 } 662 } 663 664 /// Clone directory the parent prepares before the child runs, if any. 665 fn clone_dir(&self) -> Option<&Path> { 666 match self { 667 Work::Write(s) => Some(&s.clone_dir), 668 Work::Query(s) => Some(&s.clone_dir), 669 Work::Conflict(s) => Some(&s.clone_dir), 670 Work::Recovery(s) => Some(&s.clone_dir), 671 Work::ImportProbe(s) => Some(&s.clone_dir), 672 Work::Conformance(_) => None, 673 } 674 } 675 } 676 677 /// Execute a full qualification run and write `report.json` and `manifest.json`. 678 pub fn run_qualification(cfg: &RunConfig) -> Result<(), String> { 679 let started = Instant::now(); 680 let started_at = utc_timestamp(); 681 let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?; 682 let work = cfg.work_dir.clone(); 683 let traces = cfg.out_dir.join("traces"); 684 let ctl = work.join("ctl"); 685 let cells_root = work.join("cells"); 686 for d in [&work, &traces, &ctl, &cells_root] { 687 std::fs::create_dir_all(d).map_err(|e| format!("mkdir {}: {e}", d.display()))?; 688 } 689 let host_info = host::collect_host_info(&work); 690 691 // Original repository: read-only fingerprint, then one isolated master clone. 692 let (head_before, refs_before) = refs_fingerprint(&cfg.fixture_repo)?; 693 let master = work.join("master"); 694 git_ok( 695 &work, 696 &[], 697 &[], 698 &[ 699 "clone", 700 "--no-checkout", 701 "--no-hardlinks", 702 "--quiet", 703 path_str(&cfg.fixture_repo)?, 704 path_str(&master)?, 705 ], 706 None, 707 )?; 708 configure_bench_clone(&master)?; 709 let commit = git_line( 710 &master, 711 &[ 712 "rev-parse", 713 "--verify", 714 &format!("{}^{{commit}}", cfg.fixture_rev), 715 ], 716 )?; 717 git_ok( 718 &master, 719 &[], 720 &[], 721 &["update-ref", "refs/heads/gate4-base", &commit], 722 None, 723 )?; 724 let base = fixture::list_base_tree(&master, &commit)?; 725 let editable = fixture::load_editable_files(&master, &base)?.len(); 726 let master_git = du_total(&[master.join(".git")])?; 727 728 // Disk preflight: the largest cell is G1 (one checkout per op) or G2 (one per agent). 729 let max_tier = cfg.tiers.iter().copied().max().unwrap_or(1); 730 let mut checkouts = 0usize; 731 for &t in &cfg.tiers { 732 if cfg.arms.contains(&ArmKind::G1) { 733 checkouts = checkouts.max(t * cfg.ops_per_agent(ArmKind::G1, t)); 734 } 735 } 736 if cfg.arms.contains(&ArmKind::G2) { 737 checkouts = checkouts.max(max_tier); 738 } 739 let estimated_peak = 740 (checkouts as u64 + 2) * base.total_bytes() + 2 * master_git.apparent_bytes + (2u64 << 30); 741 let required_free = estimated_peak.saturating_mul(3); 742 let free_at_start = host::free_bytes(&work); 743 if free_at_start.is_some_and(|f| f < required_free) { 744 return Err(format!( 745 "insufficient free disk: {:?} bytes free, {required_free} required", 746 free_at_start 747 )); 748 } 749 750 let git_config: Vec = [ 751 "core.fsync", 752 "core.fsyncMethod", 753 "core.fsyncObjectFiles", 754 "gc.auto", 755 "maintenance.auto", 756 ] 757 .iter() 758 .map(|k| git_config_or_unknown(&master, k)) 759 .collect(); 760 let git_listing = 761 host::git_config_listing(&master).unwrap_or_else(|e| vec![format!("error: {e}")]); 762 let fsync_probe = host::probe_git_fsync(&work.join("fsync-probe")); 763 764 // Plan cells: each repetition is a shuffled block of write cells plus that 765 // repetition's query and conformance cells; single cells follow. 766 let order_seed = SplitMix64::derive(cfg.seed, &[0x0DE5]).next_u64(); 767 let mut planned: Vec = Vec::new(); 768 for rep in 0..cfg.reps { 769 let mut block: Vec = Vec::new(); 770 for &agents in &cfg.tiers { 771 for &arm in &cfg.arms { 772 let ops = cfg.ops_per_agent(arm, agents); 773 let label = format!("write-{}-a{agents:02}-r{rep}", arm.code()); 774 let root = cells_root.join(&label); 775 block.push(Planned { 776 entry: CellPlanEntry { 777 order: 0, 778 label: label.clone(), 779 kind: "write".into(), 780 arm: Some(arm), 781 agents: Some(agents), 782 ops_per_agent: Some(ops), 783 rep: Some(rep), 784 }, 785 work: Work::Write(WriteCellSpec { 786 arm, 787 agents, 788 ops_per_agent: ops, 789 rep, 790 seed: cfg.seed, 791 clone_dir: root.join("clone"), 792 base_commit: commit.clone(), 793 cell_dir: root.join("cell"), 794 trace_path: traces.join(format!("{label}.jsonl")), 795 batch_window_records: cfg.batch_window_records, 796 }), 797 }); 798 } 799 } 800 if cfg.write_only { 801 let mut rng = SplitMix64::derive(order_seed, &[rep as u64]); 802 rng.shuffle(&mut block); 803 planned.extend(block); 804 continue; 805 } 806 let label = format!("query-r{rep}"); 807 let root = cells_root.join(&label); 808 block.push(Planned { 809 entry: CellPlanEntry { 810 order: 0, 811 label: label.clone(), 812 kind: "query".into(), 813 arm: None, 814 agents: Some(cfg.query_agents), 815 ops_per_agent: Some(cfg.query_ops_per_agent), 816 rep: Some(rep), 817 }, 818 work: Work::Query(QuerySpec { 819 rep, 820 seed: cfg.seed, 821 agents: cfg.query_agents, 822 ops_per_agent: cfg.query_ops_per_agent, 823 samples: cfg.query_samples, 824 clone_dir: root.join("clone"), 825 base_commit: commit.clone(), 826 cell_dir: root.join("cell"), 827 trace_path: traces.join(format!("{label}.jsonl")), 828 }), 829 }); 830 let label = format!("conformance-r{rep}"); 831 block.push(Planned { 832 entry: CellPlanEntry { 833 order: 0, 834 label: label.clone(), 835 kind: "conformance".into(), 836 arm: None, 837 agents: None, 838 ops_per_agent: None, 839 rep: Some(rep), 840 }, 841 work: Work::Conformance(ConformanceSpec { 842 suites: vec!["wal".into(), "git".into(), "radicle".into()], 843 work_dir: cells_root.join(&label), 844 radicle_repo: cfg.radicle_repo.clone(), 845 }), 846 }); 847 let mut rng = SplitMix64::derive(order_seed, &[rep as u64]); 848 rng.shuffle(&mut block); 849 planned.extend(block); 850 } 851 let singles: [(&str, &str); 3] = [ 852 ("conflict", "conflict"), 853 ("recovery", "recovery"), 854 ("import-probe", "import-probe"), 855 ]; 856 for (label, kind) in singles { 857 if cfg.write_only { 858 break; 859 } 860 let root = cells_root.join(label); 861 let work_item = match kind { 862 "conflict" => Work::Conflict(ConflictSpec { 863 seed: cfg.seed, 864 clone_dir: root.join("clone"), 865 base_commit: commit.clone(), 866 cell_dir: root.join("cell"), 867 trace_path: traces.join("conflict.jsonl"), 868 }), 869 "recovery" => Work::Recovery(RecoverySpec { 870 seed: cfg.seed, 871 sizes: cfg.recovery_sizes.clone(), 872 reopen_reps: cfg.recovery_reopen_reps, 873 clone_dir: root.join("clone"), 874 base_commit: commit.clone(), 875 cell_dir: root.join("cell"), 876 trace_path: traces.join("recovery.jsonl"), 877 }), 878 _ => Work::ImportProbe(ImportProbeSpec { 879 seed: cfg.seed, 880 clone_dir: root.join("clone"), 881 base_commit: commit.clone(), 882 cell_dir: root.join("cell"), 883 }), 884 }; 885 planned.push(Planned { 886 entry: CellPlanEntry { 887 order: 0, 888 label: label.to_string(), 889 kind: kind.to_string(), 890 arm: None, 891 agents: None, 892 ops_per_agent: None, 893 rep: None, 894 }, 895 work: work_item, 896 }); 897 } 898 for (i, p) in planned.iter_mut().enumerate() { 899 p.entry.order = i; 900 } 901 902 // IDLE energy baseline (the harness sleeps; other tenants keep running). 903 let idle = crate::energy::idle_window(std::time::Duration::from_secs_f64( 904 cfg.idle_window_s.max(1.0), 905 )); 906 907 // Execute. 908 let total = planned.len(); 909 let mut write_cells = Vec::new(); 910 let mut query_cells = Vec::new(); 911 let mut conformance_runs = Vec::new(); 912 let mut conflict = None; 913 let mut recovery = None; 914 let mut import_probe = None; 915 let mut failures = Vec::new(); 916 let mut timings = Vec::new(); 917 let mut min_free = free_at_start; 918 for p in &planned { 919 let label = p.entry.label.as_str(); 920 let kind = p.work.kind(); 921 let free = host::free_bytes(&work); 922 min_free = match (min_free, free) { 923 (Some(a), Some(b)) => Some(a.min(b)), 924 (a, b) => a.or(b), 925 }; 926 if free.is_some_and(|f| f < estimated_peak) { 927 failures.push(CellFailure { 928 label: label.into(), 929 kind: kind.into(), 930 error: format!("skipped: free disk {free:?} below estimated peak {estimated_peak}"), 931 }); 932 continue; 933 } 934 let cell_root = cells_root.join(label); 935 let t_clone = Instant::now(); 936 let mut clone_err = None; 937 if let Some(clone) = p.work.clone_dir() { 938 if let Err(e) = 939 clone_no_checkout(&master, clone).and_then(|_| configure_bench_clone(clone)) 940 { 941 clone_err = Some(e); 942 } 943 } 944 let clone_ms = ms_since(t_clone); 945 let t_child = Instant::now(); 946 let outcome: Result<(), String> = match clone_err { 947 Some(e) => Err(format!("clone failed: {e}")), 948 None => match &p.work { 949 Work::Write(s) => { 950 run_child(&exe, &ctl, kind, label, s).map(|r| write_cells.push(r)) 951 } 952 Work::Query(s) => { 953 run_child(&exe, &ctl, kind, label, s).map(|r| query_cells.push(r)) 954 } 955 Work::Conformance(s) => { 956 run_child(&exe, &ctl, kind, label, s).map(|r| conformance_runs.push(r)) 957 } 958 Work::Conflict(s) => { 959 run_child(&exe, &ctl, kind, label, s).map(|r| conflict = Some(r)) 960 } 961 Work::Recovery(s) => { 962 run_child(&exe, &ctl, kind, label, s).map(|r| recovery = Some(r)) 963 } 964 Work::ImportProbe(s) => { 965 run_child(&exe, &ctl, kind, label, s).map(|r| import_probe = Some(r)) 966 } 967 }, 968 }; 969 let child_ms = ms_since(t_child); 970 let ok = outcome.is_ok(); 971 if let Err(e) = outcome { 972 failures.push(CellFailure { 973 label: label.into(), 974 kind: kind.into(), 975 error: e, 976 }); 977 } 978 let _ = std::fs::remove_dir_all(&cell_root); 979 eprintln!( 980 "[{}/{total}] {label} {} clone {:.1}s cell {:.1}s (elapsed {:.0}s)", 981 p.entry.order + 1, 982 if ok { "ok" } else { "FAILED" }, 983 clone_ms / 1000.0, 984 child_ms / 1000.0, 985 started.elapsed().as_secs_f64() 986 ); 987 timings.push(CellTiming { 988 label: label.into(), 989 clone_ms, 990 child_wall_ms: child_ms, 991 ok, 992 }); 993 } 994 995 let write_summary = summarize_write(&write_cells, &cfg.arms, &cfg.tiers, Some(&idle)); 996 let report = Report { 997 schema: REPORT_SCHEMA.into(), 998 smoke: cfg.smoke, 999 generated_at_utc: utc_timestamp(), 1000 arms: cfg 1001 .arms 1002 .iter() 1003 .map(|a| ArmInfo { 1004 code: a.code().into(), 1005 description: a.description().into(), 1006 durability: a.durability().into(), 1007 }) 1008 .collect(), 1009 headline: headline(&write_summary), 1010 write_summary, 1011 write_cells, 1012 query_summary: summarize_queries(&query_cells), 1013 query_cells, 1014 conflict, 1015 conformance_summary: summarize_conformance(&conformance_runs), 1016 conformance_runs, 1017 recovery, 1018 import_probe, 1019 failures, 1020 scope_notes: scope_notes(), 1021 idle_energy: Some(idle), 1022 }; 1023 write_json(&cfg.out_dir.join("report.json"), &report)?; 1024 1025 let (head_after, refs_after) = refs_fingerprint(&cfg.fixture_repo)?; 1026 let mut trace_files: Vec = std::fs::read_dir(&traces) 1027 .map_err(|e| format!("read_dir traces: {e}"))? 1028 .flatten() 1029 .map(|e| format!("traces/{}", e.file_name().to_string_lossy())) 1030 .collect(); 1031 trace_files.sort(); 1032 let largest = base.entries.iter().map(|e| e.size_bytes).max().unwrap_or(0); 1033 let manifest = Manifest { 1034 schema: MANIFEST_SCHEMA.into(), 1035 smoke: cfg.smoke, 1036 started_at_utc: started_at, 1037 finished_at_utc: utc_timestamp(), 1038 total_run_s: round3(started.elapsed().as_secs_f64()), 1039 command_line: cfg.command_line.clone(), 1040 config: cfg.clone(), 1041 host: host_info, 1042 fixture: FixtureInfo { 1043 original_repo: cfg.fixture_repo.display().to_string(), 1044 requested_rev: cfg.fixture_rev.clone(), 1045 commit: base.commit_hex.clone(), 1046 tree: base.tree_hex.clone(), 1047 files: base.entries.len(), 1048 total_bytes: base.total_bytes(), 1049 largest_file_bytes: largest, 1050 skipped_entries: base.skipped_entries, 1051 editable_files: editable, 1052 master_clone_method: "git clone --no-checkout --no-hardlinks (once); each cell: git clone --no-checkout --local of the master clone".into(), 1053 master_clone_git_dir_apparent_bytes: master_git.apparent_bytes, 1054 original_head_before: head_before, 1055 original_head_after: head_after, 1056 original_refs_sha256_before: refs_before, 1057 original_refs_sha256_after: refs_after, 1058 }, 1059 bench_clone_config: fixture::BENCH_CLONE_CONFIG 1060 .iter() 1061 .map(|(k, v)| (k.to_string(), v.to_string())) 1062 .collect(), 1063 git_config, 1064 git_config_listing: git_listing, 1065 fsync_probe, 1066 disk: DiskPlan { 1067 free_bytes_at_start: free_at_start, 1068 estimated_peak_cell_bytes: estimated_peak, 1069 required_free_bytes: required_free, 1070 min_free_bytes_observed: min_free, 1071 }, 1072 source: SourceInfo { 1073 rev: cfg.source_rev.clone(), 1074 dirty: cfg.source_dirty.clone(), 1075 digest: cfg.source_digest.clone(), 1076 }, 1077 cell_order_seed: order_seed, 1078 cell_order: planned.into_iter().map(|p| p.entry).collect(), 1079 cell_timings: timings, 1080 trace_files, 1081 }; 1082 write_json(&cfg.out_dir.join("manifest.json"), &manifest)?; 1083 let _ = std::fs::remove_dir_all(&master); 1084 Ok(()) 1085 } 1086 1087 fn git_config_or_unknown(repo: &Path, key: &str) -> GitConfigValue { 1088 host::git_config_value(repo, key).unwrap_or_else(|e| GitConfigValue { 1089 key: key.to_string(), 1090 values_with_origin: vec![format!("error: {e}")], 1091 set: false, 1092 }) 1093 } 1094 1095 #[cfg(test)] 1096 mod tests { 1097 use super::*; 1098 1099 #[test] 1100 fn ops_per_agent_respects_floor_and_g1_cap() { 1101 let cfg = RunConfig::new("a".into(), "b".into(), "c".into(), "d".into()); 1102 assert_eq!(cfg.ops_per_agent(ArmKind::S1, 1), 400); 1103 assert_eq!(cfg.ops_per_agent(ArmKind::G3, 32), 13); 1104 assert_eq!(cfg.ops_per_agent(ArmKind::G2, 8), 50); 1105 assert_eq!(cfg.ops_per_agent(ArmKind::G1, 1), 32); 1106 assert_eq!(cfg.ops_per_agent(ArmKind::G1, 32), 2); 1107 for t in [1usize, 4, 8, 32] { 1108 for a in ArmKind::ALL { 1109 if a != ArmKind::G1 { 1110 assert!(t * cfg.ops_per_agent(a, t) >= 400); 1111 } 1112 } 1113 } 1114 } 1115 1116 #[test] 1117 fn opt_all_requires_every_rep() { 1118 assert!(opt_all(&[Some(1.0), None]).is_none()); 1119 assert_eq!( 1120 opt_all(&[Some(1.0), Some(3.0), Some(2.0)]).unwrap().median, 1121 2.0 1122 ); 1123 } 1124 }