interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-bench / src / pmu_diag.rs

1454 lines · 51952 bytes Raw Blame History
1//! `synapse-bench pmu-diag`: opt-in CPU PMU diagnostics beside the existing physical-bound
2//! benchmarks (issue #64). Diagnostic only: hardware counts are supporting units, never a
3//! performance claim and never a qualification result. Seconds per operation stay the
4//! measured unit; energy is not measured here (the `run`, `floor` and `bounds` paths keep
5//! their SI and joule reporting unchanged).
6//!
7//! Evidence follows the A0 shape (`docs/A0_HOST_BOUNDS.md`):
8//! - `protocol.json` is written (and committed) before the run: legs, repetitions,
9//! affinity policies, seed, fixture revision. Nothing is tuned from these runs; any
10//! later tuning needs its own held-out runs.
11//! - `raw.json` holds integers only: per window the wall nanoseconds, getrusage CPU
12//! microseconds, operation count, and the PMU sample exactly as read (or its refusal),
13//! plus the manifest (invocation, host, compiler, kernel, `perf_event_paranoid`,
14//! PMU discovery, fixture commit, source and sibling revisions).
15//! - `report.json` is a pure function of the protocol and raw bytes; `pmu-verify`
16//! recomputes it byte for byte, re-validates every PMU reading against the discovery
17//! and the counter contract, and checks `SHA256SUMS`.
18//!
19//! Each repetition runs a control window (counters never opened) and then an
20//! instrumented window on identical input, so instrumentation overhead is measured, not
21//! assumed. Timing covers the measured work only: counters are opened before the clock
22//! starts and read after it stops.
23
24use crate::fixture::{self, BaseTree, EditableFile};
25use crate::host::{collect_host_info, HostInfo};
26use crate::pmu::{
27 apply_affinity, classify, AffinityPolicy, CoreClass, CounterState, Discovery, LinuxPerf,
28 PmuMode, PmuSample, PmuSession, UnavailableReason, EVENTS,
29};
30use crate::rng::SplitMix64;
31use crate::rusage::sample_self;
32use crate::stats::nearest_rank;
33use crate::synapse_arm::{self, AgentIdentity, BenchIdentities};
34use crate::workload::{generate_write_workload, EditOp, Proposal};
35use crate::write_phase::synapse_submit;
36use serde::de::DeserializeOwned;
37use serde::{Deserialize, Serialize};
38use sha2::{Digest, Sha256};
39use std::collections::BTreeMap;
40use std::fs;
41use std::path::{Path, PathBuf};
42use std::sync::Mutex;
43use std::time::Instant;
44use synapse_api::{
45 ChangesetAdvisoryPayload, CrumbContextQueryPayload, DiffQueryPayload, PageRequest,
46 PageResponse, SynapseService, TreeQueryPayload, TreeTarget, DEFAULT_MAX_PAGE_SIZE,
47};
48use synapse_core::{ChangesetId, FileMode, GitOid, WalSeq};
49use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, SharedStore, StoreLimits};
50
51pub const PROTOCOL_FILE: &str = "protocol.json";
52pub const RAW_FILE: &str = "raw.json";
53pub const REPORT_FILE: &str = "report.json";
54pub const SUMS_FILE: &str = "SHA256SUMS";
55pub const PROTOCOL_SCHEMA: &str = "synapse-bench/pmu-diag-protocol/v1";
56pub const RAW_SCHEMA: &str = "synapse-bench/pmu-diag-raw/v1";
57pub const REPORT_SCHEMA: &str = "synapse-bench/pmu-diag-report/v1";
58/// The only window order protocol v1 allows.
59pub const ORDER: &str = "control-then-instrumented";
60
61/// CPU-only floor operations (a subset of `floor.rs` CPU probes, same inputs).
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum FloorOp {
65 #[serde(rename = "sha256_content_12k")]
66 Sha256Content12k,
67 Ed25519Verify,
68 EnvelopeValidate,
69 JsonDecodeSubmitRequest,
70}
71
72/// Store commit path for a write leg.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum WriteArm {
76 /// `FsyncPolicy::EveryCommit` (the S1 arm).
77 EveryCommit,
78 /// WAL v2 `FsyncPolicy::GROUP_COMMIT_DEFAULT` through `SharedStore` (the S3 arm).
79 GroupCommit,
80}
81
82/// One pre-registered leg.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
85pub enum LegSpec {
86 Floor {
87 op: FloorOp,
88 iterations: u64,
89 },
90 Write {
91 arm: WriteArm,
92 agents: usize,
93 ops_per_agent: usize,
94 },
95 /// read_file, tree (all pages) and diff (all pages) against a populated service.
96 Query {
97 populate_agents: usize,
98 populate_ops_per_agent: usize,
99 samples: usize,
100 },
101 /// crumb_context and changeset_advisory (no coordination plane) on the fixture base.
102 Crumb {
103 samples: usize,
104 },
105}
106
107impl LegSpec {
108 /// Stable identifier used in raw and report rows.
109 pub fn id(&self) -> String {
110 match self {
111 Self::Floor { op, .. } => format!("floor/{}", enum_code(op)),
112 Self::Write { arm, agents, .. } => format!("write/{}/agents={agents}", enum_code(arm)),
113 Self::Query { .. } => "query/read_tree_diff".into(),
114 Self::Crumb { .. } => "crumb/context_advisory".into(),
115 }
116 }
117
118 fn needs_fixture(&self) -> bool {
119 !matches!(self, Self::Floor { .. })
120 }
121
122 fn validate(&self) -> Result<(), String> {
123 let ok = match self {
124 Self::Floor { iterations, .. } => *iterations > 0,
125 Self::Write {
126 agents,
127 ops_per_agent,
128 ..
129 } => *agents > 0 && *ops_per_agent > 0,
130 Self::Query {
131 populate_agents,
132 populate_ops_per_agent,
133 samples,
134 } => *populate_agents > 0 && *populate_ops_per_agent > 0 && *samples > 0,
135 Self::Crumb { samples } => *samples > 0,
136 };
137 if ok {
138 Ok(())
139 } else {
140 Err(format!("leg {}: every count must be positive", self.id()))
141 }
142 }
143}
144
145fn enum_code<T: Serialize>(v: &T) -> String {
146 serde_json::to_value(v)
147 .ok()
148 .and_then(|v| v.as_str().map(str::to_string))
149 .unwrap_or_default()
150}
151
152/// Pre-registered plan (`protocol.json`).
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(deny_unknown_fields)]
155pub struct Protocol {
156 pub schema: String,
157 pub purpose: String,
158 pub seed: u64,
159 /// Required when any leg needs the fixture (write, query, crumb).
160 pub fixture_rev: Option<String>,
161 /// Repetitions per (leg, affinity); each is one control plus one instrumented window.
162 pub reps: usize,
163 pub order: String,
164 pub affinity: Vec<AffinityPolicy>,
165 pub legs: Vec<LegSpec>,
166 /// Statement of what is held out (v1: nothing is tuned from these runs).
167 pub held_out: String,
168}
169
170impl Protocol {
171 pub fn validate(&self) -> Result<(), String> {
172 if self.schema != PROTOCOL_SCHEMA {
173 return Err(format!(
174 "protocol schema {:?}, expected {PROTOCOL_SCHEMA:?}",
175 self.schema
176 ));
177 }
178 if self.order != ORDER {
179 return Err(format!(
180 "protocol order {:?}, expected {ORDER:?}",
181 self.order
182 ));
183 }
184 if self.reps == 0 || self.affinity.is_empty() || self.legs.is_empty() {
185 return Err("protocol needs reps > 0, at least one affinity and one leg".into());
186 }
187 let mut ids = std::collections::BTreeSet::new();
188 for leg in &self.legs {
189 leg.validate()?;
190 if !ids.insert(leg.id()) {
191 return Err(format!("leg {} listed twice", leg.id()));
192 }
193 }
194 let mut aff = std::collections::BTreeSet::new();
195 if !self.affinity.iter().all(|a| aff.insert(*a)) {
196 return Err("affinity policy listed twice".into());
197 }
198 if self.legs.iter().any(LegSpec::needs_fixture)
199 && self.fixture_rev.as_deref().is_none_or(str::is_empty)
200 {
201 return Err("write, query and crumb legs need fixture_rev".into());
202 }
203 Ok(())
204 }
205}
206
207/// A named sibling repository revision recorded for attribution (for example the
208/// Omega PMU probe contract, issue omega#453).
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210pub struct SiblingRev {
211 pub name: String,
212 pub rev: String,
213}
214
215/// Who ran what, where, with which build.
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct Manifest {
218 pub invocation: Vec<String>,
219 pub started_at: String,
220 pub host: HostInfo,
221 /// `debug` or `release` (from `cfg!(debug_assertions)`).
222 pub build_profile: String,
223 pub target_arch: String,
224 pub source_rev: String,
225 pub fixture_repo: Option<String>,
226 /// The fixture revision resolved to a commit.
227 pub fixture_commit: Option<String>,
228 pub siblings: Vec<SiblingRev>,
229 pub clock: String,
230 pub energy: String,
231}
232
233/// One measured window, as read.
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235pub struct Window {
236 pub leg: String,
237 pub affinity: AffinityPolicy,
238 pub rep: usize,
239 pub instrumented: bool,
240 pub ops: u64,
241 pub wall_ns: u64,
242 /// getrusage(RUSAGE_SELF) deltas over the window: every thread of this process.
243 pub cpu_user_us: u64,
244 pub cpu_sys_us: u64,
245 pub error: Option<String>,
246 pub pmu: PmuSample,
247}
248
249/// A (leg, affinity) pair that produced no windows, with the reason.
250#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251pub struct NotRun {
252 pub leg: String,
253 pub affinity: AffinityPolicy,
254 pub reason: String,
255}
256
257/// `raw.json`.
258#[derive(Debug, Clone, Serialize, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub struct Raw {
261 pub schema: String,
262 pub protocol_sha256: String,
263 pub manifest: Manifest,
264 pub discovery: Discovery,
265 pub windows: Vec<Window>,
266 pub not_run: Vec<NotRun>,
267}
268
269/// Nearest-rank distribution of integer samples.
270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
271pub struct Dist {
272 pub n: usize,
273 pub min: u64,
274 pub p50: u64,
275 pub max: u64,
276}
277
278fn dist(values: &[u64]) -> Option<Dist> {
279 let mut v = values.to_vec();
280 v.sort_unstable();
281 Some(Dist {
282 n: v.len(),
283 min: *v.first()?,
284 p50: nearest_rank(&v, 0.5)?,
285 max: *v.last()?,
286 })
287}
288
289/// Timing over the successful windows of one side (control or instrumented).
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291pub struct TimingSummary {
292 pub windows: usize,
293 pub errors: usize,
294 pub wall_ns: Option<Dist>,
295 /// `wall_ns / ops` per window (integer division).
296 pub wall_ns_per_op: Option<Dist>,
297 /// User plus system CPU microseconds per window (all threads).
298 pub cpu_us: Option<Dist>,
299}
300
301/// Raw counts of one event on one core class over the windows that counted it.
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303pub struct EventSummary {
304 pub core_class: CoreClass,
305 pub event: String,
306 /// Raw count per window (never scaled).
307 pub raw_count: Dist,
308 pub raw_count_per_op: Dist,
309}
310
311/// Ratios from counts summed over windows on one core class (same event group, so the
312/// four counters share enable/run time). Integers: per mille.
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
314pub struct ClassRatios {
315 pub core_class: CoreClass,
316 pub windows: usize,
317 /// `sum(INST_RETIRED) * 1000 / sum(CPU_CYCLES)`.
318 pub instructions_per_kilocycle: Option<u64>,
319 /// `sum(BR_MIS_PRED) * 1000 / sum(BR_PRED)`.
320 pub mispredicts_per_kilo_predicted_branches: Option<u64>,
321}
322
323/// PMU outcome over the instrumented windows.
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325pub struct PmuSummary {
326 pub windows: usize,
327 pub counted_windows: usize,
328 /// `INSTRUMENT_UNAVAILABLE` windows by reason code.
329 pub unavailable: BTreeMap<String, usize>,
330 /// Counter reads by state (`COUNTED`, `MULTIPLEXED`, ...).
331 pub states: BTreeMap<String, usize>,
332 pub events: Vec<EventSummary>,
333 pub ratios: Vec<ClassRatios>,
334}
335
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337pub struct LegReport {
338 pub leg: String,
339 pub affinity: AffinityPolicy,
340 pub control: TimingSummary,
341 pub instrumented: TimingSummary,
342 /// `(instrumented p50 - control p50) * 1e6 / control p50` of wall_ns, parts per million.
343 pub overhead_ppm_p50: Option<i64>,
344 pub pmu: PmuSummary,
345}
346
347/// `report.json`.
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349pub struct Report {
350 pub schema: String,
351 pub status: String,
352 pub protocol_sha256: String,
353 pub raw_sha256: String,
354 pub legs: Vec<LegReport>,
355 pub not_run: Vec<NotRun>,
356 pub notes: Vec<String>,
357}
358
359/// Why sealed evidence was refused.
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub enum VerifyError {
362 Io(String),
363 Parse(String),
364 Protocol(String),
365 ProtocolDigest {
366 raw_says: String,
367 actual: String,
368 },
369 /// A window or reading contradicts the protocol, the discovery, or the counter contract.
370 Mismatch(String),
371 ReportMismatch {
372 first_difference_at: usize,
373 },
374 ChecksumsMissing(String),
375 ChecksumMismatch(String),
376}
377
378impl std::fmt::Display for VerifyError {
379 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380 match self {
381 Self::Io(m) => write!(f, "io: {m}"),
382 Self::Parse(m) => write!(f, "parse: {m}"),
383 Self::Protocol(m) => write!(f, "protocol: {m}"),
384 Self::ProtocolDigest { raw_says, actual } => write!(
385 f,
386 "raw.json names protocol {raw_says}, protocol.json is {actual}"
387 ),
388 Self::Mismatch(m) => write!(f, "mismatch: {m}"),
389 Self::ReportMismatch {
390 first_difference_at,
391 } => write!(
392 f,
393 "report.json differs from the recomputed report at byte {first_difference_at}"
394 ),
395 Self::ChecksumsMissing(m) => write!(f, "checksums missing: {m}"),
396 Self::ChecksumMismatch(m) => write!(f, "checksum mismatch: {m}"),
397 }
398 }
399}
400
401pub fn sha256_hex(bytes: &[u8]) -> String {
402 hex::encode(Sha256::digest(bytes))
403}
404
405fn parse<T: DeserializeOwned>(bytes: &[u8], what: &str) -> Result<T, VerifyError> {
406 serde_json::from_slice(bytes).map_err(|e| VerifyError::Parse(format!("{what}: {e}")))
407}
408
409/// Check every window and reading in `raw` against `protocol`, the recorded discovery,
410/// and the counter contract. Refuses, never repairs.
411pub fn validate_raw(protocol: &Protocol, raw: &Raw) -> Result<(), VerifyError> {
412 let mm = |m: String| Err(VerifyError::Mismatch(m));
413 if raw.schema != RAW_SCHEMA {
414 return mm(format!(
415 "raw schema {:?}, expected {RAW_SCHEMA:?}",
416 raw.schema
417 ));
418 }
419 let legs: Vec<String> = protocol.legs.iter().map(LegSpec::id).collect();
420 for n in &raw.not_run {
421 if !legs.contains(&n.leg) || !protocol.affinity.contains(&n.affinity) {
422 return mm(format!(
423 "not_run names unknown leg {} / {:?}",
424 n.leg, n.affinity
425 ));
426 }
427 }
428 // Exactly one control and one instrumented window per (leg, affinity, rep), unless
429 // that (leg, affinity) is listed in not_run, in which case none.
430 let mut seen = std::collections::BTreeSet::new();
431 for w in &raw.windows {
432 let key = (w.leg.clone(), w.affinity, w.rep, w.instrumented);
433 if !legs.contains(&w.leg) || !protocol.affinity.contains(&w.affinity) {
434 return mm(format!(
435 "window for unknown leg {} / {:?}",
436 w.leg, w.affinity
437 ));
438 }
439 if w.rep >= protocol.reps {
440 return mm(format!("{} rep {} beyond protocol reps", w.leg, w.rep));
441 }
442 if !seen.insert(key) {
443 return mm(format!("duplicate window {} rep {}", w.leg, w.rep));
444 }
445 validate_window(w, &raw.discovery)?;
446 }
447 for leg in &legs {
448 for aff in &protocol.affinity {
449 let skipped = raw
450 .not_run
451 .iter()
452 .any(|n| &n.leg == leg && n.affinity == *aff);
453 for rep in 0..protocol.reps {
454 for instrumented in [false, true] {
455 let present = seen.contains(&(leg.clone(), *aff, rep, instrumented));
456 if present == skipped {
457 return mm(format!(
458 "{leg} {aff:?} rep {rep} instrumented={instrumented}: {}",
459 if skipped {
460 "window present for a not_run leg"
461 } else {
462 "window missing"
463 }
464 ));
465 }
466 }
467 }
468 }
469 }
470 Ok(())
471}
472
473fn validate_window(w: &Window, discovery: &Discovery) -> Result<(), VerifyError> {
474 let at = format!("{} {:?} rep {}", w.leg, w.affinity, w.rep);
475 let mm = |m: String| Err(VerifyError::Mismatch(format!("{at}: {m}")));
476 match (&w.pmu, w.instrumented) {
477 (PmuSample::Disabled, false) => return Ok(()),
478 (PmuSample::Disabled, true) => return mm("instrumented window has no PMU sample".into()),
479 (_, false) => return mm("control window carries a PMU sample".into()),
480 (PmuSample::InstrumentUnavailable { .. }, true) => return Ok(()),
481 (PmuSample::Counted { .. }, true) => {}
482 }
483 let PmuSample::Counted { readings } = &w.pmu else {
484 unreachable!()
485 };
486 if discovery.devices.is_empty() {
487 return mm("counts present but discovery found no PMU".into());
488 }
489 let mut expected = std::collections::BTreeSet::new();
490 for d in &discovery.devices {
491 for spec in EVENTS {
492 expected.insert((d.name.clone(), spec.name.to_string()));
493 }
494 }
495 let mut got = std::collections::BTreeSet::new();
496 for r in readings {
497 let Some(dev) = discovery.devices.iter().find(|d| d.name == r.pmu) else {
498 return mm(format!("reading names PMU {} absent from discovery", r.pmu));
499 };
500 if dev.core_class != r.core_class {
501 return mm(format!(
502 "{} {}: core class {:?}, discovery says {:?}",
503 r.pmu, r.event, r.core_class, dev.core_class
504 ));
505 }
506 let Some(spec) = EVENTS.iter().find(|s| s.name == r.event) else {
507 return mm(format!("unknown event {}", r.event));
508 };
509 if spec.arm_event != r.arm_event {
510 return mm(format!(
511 "{} event {:#06x}, architected number is {:#06x}",
512 r.event, r.arm_event, spec.arm_event
513 ));
514 }
515 if !dev
516 .events
517 .iter()
518 .any(|e| e.name == r.event && e.verified && e.arm_event == r.arm_event)
519 {
520 return mm(format!("{} {} not verified by discovery", r.pmu, r.event));
521 }
522 let pinned = w.affinity == AffinityPolicy::Pinned(dev.core_class)
523 && dev.core_class != CoreClass::Unknown;
524 match classify(r.raw_count, r.time_enabled_ns, r.time_running_ns, pinned) {
525 Ok(state) if state == r.state => {}
526 Ok(state) => {
527 return mm(format!(
528 "{} {}: state {:?} but times say {:?}",
529 r.pmu, r.event, r.state, state
530 ))
531 }
532 Err(e) => return mm(format!("{} {}: {e}", r.pmu, r.event)),
533 }
534 if !got.insert((r.pmu.clone(), r.event.clone())) {
535 return mm(format!("{} {} read twice", r.pmu, r.event));
536 }
537 }
538 if got != expected {
539 return mm("readings do not cover every discovered PMU and event exactly once".into());
540 }
541 Ok(())
542}
543
544fn timing(windows: &[&Window]) -> TimingSummary {
545 let ok: Vec<&&Window> = windows.iter().filter(|w| w.error.is_none()).collect();
546 let wall: Vec<u64> = ok.iter().map(|w| w.wall_ns).collect();
547 let per_op: Vec<u64> = ok
548 .iter()
549 .filter(|w| w.ops > 0)
550 .map(|w| w.wall_ns / w.ops)
551 .collect();
552 let cpu: Vec<u64> = ok.iter().map(|w| w.cpu_user_us + w.cpu_sys_us).collect();
553 TimingSummary {
554 windows: windows.len(),
555 errors: windows.len() - ok.len(),
556 wall_ns: dist(&wall),
557 wall_ns_per_op: dist(&per_op),
558 cpu_us: dist(&cpu),
559 }
560}
561
562fn state_code(s: CounterState) -> String {
563 enum_code(&s)
564}
565
566fn pmu_summary(windows: &[&Window], classes: &[CoreClass]) -> PmuSummary {
567 let mut s = PmuSummary {
568 windows: windows.len(),
569 counted_windows: 0,
570 unavailable: BTreeMap::new(),
571 states: BTreeMap::new(),
572 events: Vec::new(),
573 ratios: Vec::new(),
574 };
575 let mut per: BTreeMap<(CoreClass, String), (Vec<u64>, Vec<u64>)> = BTreeMap::new();
576 let mut sums: BTreeMap<CoreClass, (BTreeMap<String, u128>, usize)> = BTreeMap::new();
577 for w in windows {
578 match &w.pmu {
579 PmuSample::InstrumentUnavailable { reason, .. } => {
580 *s.unavailable.entry(enum_code(reason)).or_default() += 1;
581 }
582 PmuSample::Counted { readings } if w.error.is_none() => {
583 s.counted_windows += 1;
584 let mut classes_here = std::collections::BTreeSet::new();
585 for r in readings {
586 *s.states.entry(state_code(r.state)).or_default() += 1;
587 if r.state == CounterState::NotScheduled {
588 continue;
589 }
590 let e = per.entry((r.core_class, r.event.clone())).or_default();
591 e.0.push(r.raw_count);
592 e.1.push(r.raw_count / w.ops.max(1));
593 let c = sums.entry(r.core_class).or_default();
594 *c.0.entry(r.event.clone()).or_default() += u128::from(r.raw_count);
595 classes_here.insert(r.core_class);
596 }
597 for c in classes_here {
598 sums.entry(c).or_default().1 += 1;
599 }
600 }
601 _ => {}
602 }
603 }
604 for class in classes {
605 for spec in EVENTS {
606 if let Some((counts, per_op)) = per.get(&(*class, spec.name.to_string())) {
607 if let (Some(raw_count), Some(raw_count_per_op)) = (dist(counts), dist(per_op)) {
608 s.events.push(EventSummary {
609 core_class: *class,
610 event: spec.name.into(),
611 raw_count,
612 raw_count_per_op,
613 });
614 }
615 }
616 }
617 if let Some((m, n)) = sums.get(class) {
618 let ratio = |num: &str, den: &str| {
619 let (a, b) = (m.get(num).copied()?, m.get(den).copied()?);
620 (b > 0).then(|| (a * 1000 / b) as u64)
621 };
622 s.ratios.push(ClassRatios {
623 core_class: *class,
624 windows: *n,
625 instructions_per_kilocycle: ratio("inst_retired", "cpu_cycles"),
626 mispredicts_per_kilo_predicted_branches: ratio("br_mis_pred", "br_pred"),
627 });
628 }
629 }
630 s
631}
632
633/// Pure function of the protocol and raw bytes; `pmu-verify` requires `report.json` to
634/// equal its pretty JSON byte for byte.
635pub fn compute_report(protocol_bytes: &[u8], raw_bytes: &[u8]) -> Result<Report, VerifyError> {
636 let protocol: Protocol = parse(protocol_bytes, PROTOCOL_FILE)?;
637 protocol.validate().map_err(VerifyError::Protocol)?;
638 let raw: Raw = parse(raw_bytes, RAW_FILE)?;
639 let actual = sha256_hex(protocol_bytes);
640 if raw.protocol_sha256 != actual {
641 return Err(VerifyError::ProtocolDigest {
642 raw_says: raw.protocol_sha256,
643 actual,
644 });
645 }
646 validate_raw(&protocol, &raw)?;
647 let mut classes: Vec<CoreClass> = raw.discovery.devices.iter().map(|d| d.core_class).collect();
648 classes.sort();
649 classes.dedup();
650 let mut legs = Vec::new();
651 for leg in &protocol.legs {
652 let id = leg.id();
653 for aff in &protocol.affinity {
654 if raw
655 .not_run
656 .iter()
657 .any(|n| n.leg == id && n.affinity == *aff)
658 {
659 continue;
660 }
661 let side = |instr: bool| -> Vec<&Window> {
662 raw.windows
663 .iter()
664 .filter(|w| w.leg == id && w.affinity == *aff && w.instrumented == instr)
665 .collect()
666 };
667 let (control, instrumented) = (side(false), side(true));
668 let (c, i) = (timing(&control), timing(&instrumented));
669 let overhead_ppm_p50 = match (&c.wall_ns, &i.wall_ns) {
670 (Some(c), Some(i)) if c.p50 > 0 => Some(
671 ((i128::from(i.p50) - i128::from(c.p50)) * 1_000_000 / i128::from(c.p50))
672 as i64,
673 ),
674 _ => None,
675 };
676 legs.push(LegReport {
677 leg: id.clone(),
678 affinity: *aff,
679 pmu: pmu_summary(&instrumented, &classes),
680 control: c,
681 instrumented: i,
682 overhead_ppm_p50,
683 });
684 }
685 }
686 Ok(Report {
687 schema: REPORT_SCHEMA.into(),
688 status: "DIAGNOSTIC_ONLY".into(),
689 protocol_sha256: actual,
690 raw_sha256: sha256_hex(raw_bytes),
691 legs,
692 not_run: raw.not_run.clone(),
693 notes: vec![
694 "Hardware counts are supporting diagnostics, not performance claims and not qualification. Seconds per operation are the measured unit.".into(),
695 "Counts are user-space only (exclude_kernel, exclude_hv) and never scaled by time_enabled/time_running; a task blocked in fdatasync is off CPU and counts nothing.".into(),
696 "INSTRUMENT_UNAVAILABLE windows carry no counts. Energy is not measured by pmu-diag.".into(),
697 ],
698 })
699}
700
701/// `SHA256SUMS` text over `names` in `dir` (sha256sum format).
702pub fn sha256sums(dir: &Path, names: &[&str]) -> Result<String, String> {
703 let mut out = String::new();
704 for name in names {
705 let bytes = fs::read(dir.join(name)).map_err(|e| format!("read {name}: {e}"))?;
706 out.push_str(&format!("{} {name}\n", sha256_hex(&bytes)));
707 }
708 Ok(out)
709}
710
711fn verify_sums(dir: &Path) -> Result<(), VerifyError> {
712 let text = fs::read_to_string(dir.join(SUMS_FILE))
713 .map_err(|e| VerifyError::ChecksumsMissing(format!("read {SUMS_FILE}: {e}")))?;
714 let mut listed = Vec::new();
715 for (i, line) in text.lines().enumerate() {
716 let (digest, name) = line
717 .split_once(" ")
718 .filter(|(d, n)| d.len() == 64 && !n.is_empty())
719 .ok_or_else(|| VerifyError::Parse(format!("{SUMS_FILE} line {}: {line:?}", i + 1)))?;
720 let bytes = fs::read(dir.join(name)).map_err(|e| {
721 VerifyError::ChecksumMismatch(format!("{name} listed but unreadable: {e}"))
722 })?;
723 let actual = sha256_hex(&bytes);
724 if actual != digest {
725 return Err(VerifyError::ChecksumMismatch(format!(
726 "{name} is {actual}, {SUMS_FILE} lists {digest}"
727 )));
728 }
729 listed.push(name.to_string());
730 }
731 let missing: Vec<&str> = [PROTOCOL_FILE, RAW_FILE, REPORT_FILE]
732 .into_iter()
733 .filter(|n| !listed.iter().any(|l| l == n))
734 .collect();
735 if missing.is_empty() {
736 Ok(())
737 } else {
738 Err(VerifyError::ChecksumsMissing(format!(
739 "{SUMS_FILE} does not list {}",
740 missing.join(", ")
741 )))
742 }
743}
744
745/// Recompute `report.json` from `protocol.json` and `raw.json`, require a byte-for-byte
746/// match, then check `SHA256SUMS`. Consistency only: authenticity comes from git history.
747pub fn verify_evidence(dir: &Path) -> Result<Report, VerifyError> {
748 let read =
749 |name: &str| fs::read(dir.join(name)).map_err(|e| VerifyError::Io(format!("{name}: {e}")));
750 let (protocol, raw, sealed) = (read(PROTOCOL_FILE)?, read(RAW_FILE)?, read(REPORT_FILE)?);
751 let report = compute_report(&protocol, &raw)?;
752 let again = serde_json::to_vec_pretty(&report)
753 .map_err(|e| VerifyError::Parse(format!("serialize report: {e}")))?;
754 if again != sealed {
755 let first_difference_at = again
756 .iter()
757 .zip(&sealed)
758 .position(|(a, b)| a != b)
759 .unwrap_or(again.len().min(sealed.len()));
760 return Err(VerifyError::ReportMismatch {
761 first_difference_at,
762 });
763 }
764 verify_sums(dir)?;
765 Ok(report)
766}
767
768/// Host-side inputs for one `pmu-diag` run.
769#[derive(Debug, Clone)]
770pub struct DiagConfig {
771 /// Holds `protocol.json`; `raw.json`, `report.json` and `SHA256SUMS` are written here.
772 pub evidence_dir: PathBuf,
773 pub fixture_repo: Option<PathBuf>,
774 /// Scratch directory on the store filesystem (removed per window).
775 pub work_dir: PathBuf,
776 pub source_rev: String,
777 pub siblings: Vec<SiblingRev>,
778 pub invocation: Vec<String>,
779 pub discovery: Discovery,
780}
781
782/// What a measured closure did.
783struct Work {
784 ops: u64,
785 error: Option<String>,
786}
787
788/// Run one window: open counters (instrumented only), start the clock and the rusage
789/// window, enable, run `work`, stop the clock, read the counters.
790fn measure(
791 discovery: &Discovery,
792 affinity: AffinityPolicy,
793 instrumented: bool,
794 work: impl FnOnce() -> Work,
795) -> (Work, u64, u64, u64, PmuSample) {
796 let mode = if instrumented {
797 PmuMode::Enabled
798 } else {
799 PmuMode::Disabled
800 };
801 let mut session = PmuSession::open(LinuxPerf, mode, discovery, affinity);
802 let ru0 = sample_self().unwrap_or_default();
803 session.start();
804 let t = Instant::now();
805 let done = work();
806 let wall_ns = t.elapsed().as_nanos() as u64;
807 let sample = session.stop();
808 let ru1 = sample_self().unwrap_or_default();
809 (
810 done,
811 wall_ns,
812 ru1.user_us.saturating_sub(ru0.user_us),
813 ru1.sys_us.saturating_sub(ru0.sys_us),
814 sample,
815 )
816}
817
818/// Loaded fixture shared by the write, query and crumb legs.
819struct FixtureData {
820 base: BaseTree,
821 full: Vec<(String, FileMode, Vec<u8>)>,
822 files: Vec<EditableFile>,
823}
824
825/// One Synapse service plus the identities that sign its requests.
826struct Svc {
827 svc: SynapseService,
828 ids: BenchIdentities,
829 base_oid: GitOid,
830 counter: u64,
831}
832
833impl Svc {
834 fn open(
835 dir: &Path,
836 seed: u64,
837 agents: usize,
838 fsync: FsyncPolicy,
839 fx: &FixtureData,
840 ) -> Result<Self, String> {
841 let ids = synapse_arm::issue_identities(seed, agents, crate::unix_now_ms())?;
842 let mut svc =
843 synapse_arm::open_service(dir, &ids, fsync, RecoveryPolicy::StrictFailClosed)?;
844 let base_oid = synapse_arm::register_base(&mut svc, &fx.base.commit_hex, fx.full.clone())?;
845 Ok(Self {
846 svc,
847 ids,
848 base_oid,
849 counter: 0,
850 })
851 }
852
853 /// Signed read request, JSON round trip both ways (as `query.rs` does).
854 fn call<P, R>(
855 &mut self,
856 payload: P,
857 api: impl FnOnce(
858 &mut SynapseService,
859 &synapse_auth::AuthenticatedRequest<P>,
860 u64,
861 ) -> synapse_core::SynapseResult<R>,
862 ) -> Result<R, String>
863 where
864 P: Serialize + DeserializeOwned,
865 R: Serialize + DeserializeOwned,
866 {
867 let resp = self.call_local(payload, api)?;
868 Ok(synapse_arm::wire_roundtrip(&resp)?.0)
869 }
870
871 /// As [`Svc::call`] for responses without a JSON form (`CrumbContext`,
872 /// `ChangesetAdvisory`): the request is signed and round-tripped, the response is not.
873 fn call_local<P, R>(
874 &mut self,
875 payload: P,
876 api: impl FnOnce(
877 &mut SynapseService,
878 &synapse_auth::AuthenticatedRequest<P>,
879 u64,
880 ) -> synapse_core::SynapseResult<R>,
881 ) -> Result<R, String>
882 where
883 P: Serialize + DeserializeOwned,
884 {
885 self.counter += 1;
886 let now = crate::unix_now_ms();
887 let label = format!("pmu-diag/read/{}", self.counter);
888 let req = synapse_arm::build_read_request(
889 &self.ids.agents[0],
890 &self.ids.repo_id,
891 payload,
892 &label,
893 now,
894 )?;
895 let (decoded, _) = synapse_arm::wire_roundtrip(&req)?;
896 api(&mut self.svc, &decoded, now).map_err(|e| e.to_string())
897 }
898
899 fn all_pages<T, P>(
900 &mut self,
901 make: impl Fn(PageRequest) -> P,
902 api: fn(
903 &mut SynapseService,
904 &synapse_auth::AuthenticatedRequest<P>,
905 u64,
906 ) -> synapse_core::SynapseResult<PageResponse<T>>,
907 ) -> Result<usize, String>
908 where
909 P: Serialize + DeserializeOwned,
910 T: Serialize + DeserializeOwned,
911 {
912 let (mut cursor, mut snapshot): (Option<String>, Option<WalSeq>) = (None, None);
913 let mut items = 0;
914 loop {
915 let page = PageRequest {
916 cursor: cursor.clone(),
917 limit: DEFAULT_MAX_PAGE_SIZE,
918 min_visible_seq: None,
919 snapshot_seq: snapshot,
920 };
921 let r = self.call(make(page), api)?;
922 items += r.items.len();
923 snapshot = Some(r.snapshot_seq);
924 match r.next_cursor {
925 Some(next) => cursor = Some(next),
926 None => return Ok(items),
927 }
928 }
929 }
930}
931
932fn floor_window(op: FloorOp, iterations: u64) -> impl FnOnce() -> Work {
933 use ed25519_dalek::{Signer, SigningKey, Verifier};
934 let req = crate::floor::typical_request();
935 let wire = serde_json::to_vec(&req).unwrap_or_default();
936 let content = vec![0x42u8; crate::floor::TYPICAL_CONTENT_BYTES];
937 let key = SigningKey::from_bytes(&[5u8; 32]);
938 let msg = vec![0x10u8; 256];
939 let sig = key.sign(&msg);
940 let vk = key.verifying_key();
941 move || {
942 for _ in 0..iterations {
943 match op {
944 FloorOp::Sha256Content12k => {
945 std::hint::black_box(Sha256::digest(std::hint::black_box(&content)));
946 }
947 FloorOp::Ed25519Verify => {
948 std::hint::black_box(vk.verify(std::hint::black_box(&msg), &sig).is_ok());
949 }
950 FloorOp::EnvelopeValidate => {
951 std::hint::black_box(req.payload.envelope.validate().ok());
952 }
953 FloorOp::JsonDecodeSubmitRequest => {
954 let r: Option<
955 synapse_auth::AuthenticatedRequest<synapse_api::SubmitChangesetPayload>,
956 > = serde_json::from_slice(std::hint::black_box(&wire)).ok();
957 std::hint::black_box(r);
958 }
959 }
960 }
961 Work {
962 ops: iterations,
963 error: None,
964 }
965 }
966}
967
968/// Prepared service and workload for one write window (setup is outside the clock).
969struct WriteSetup {
970 service: Mutex<SynapseService>,
971 group: Option<SharedStore>,
972 agents: Vec<AgentIdentity>,
973 repo_id: synapse_core::RepoId,
974 base_oid: GitOid,
975 workload: Vec<Vec<Proposal>>,
976}
977
978fn write_setup(
979 dir: &Path,
980 seed: u64,
981 rep: usize,
982 arm: WriteArm,
983 agents: usize,
984 ops_per_agent: usize,
985 fx: &FixtureData,
986) -> Result<WriteSetup, String> {
987 let store_dir = dir.join("synapse-store");
988 let (svc_dir, svc_fsync) = match arm {
989 WriteArm::EveryCommit => (store_dir.clone(), FsyncPolicy::EveryCommit),
990 // As the S3 arm: the service does admission and indexing; the measured store is
991 // the group-commit SharedStore.
992 WriteArm::GroupCommit => (dir.join("service-admission"), FsyncPolicy::EveryCommit),
993 };
994 let s = Svc::open(&svc_dir, seed, agents, svc_fsync, fx)?;
995 let group = match arm {
996 WriteArm::EveryCommit => None,
997 WriteArm::GroupCommit => Some(
998 SharedStore::open(
999 &store_dir,
1000 FsyncPolicy::GROUP_COMMIT_DEFAULT,
1001 RecoveryPolicy::StrictFailClosed,
1002 StoreLimits::default(),
1003 )
1004 .map_err(|e| e.to_string())?,
1005 ),
1006 };
1007 Ok(WriteSetup {
1008 workload: generate_write_workload(seed, rep, agents, ops_per_agent, &fx.files),
1009 service: Mutex::new(s.svc),
1010 group,
1011 agents: s.ids.agents.clone(),
1012 repo_id: s.ids.repo_id.clone(),
1013 base_oid: s.base_oid,
1014 })
1015}
1016
1017fn write_window<'a>(setup: &'a WriteSetup, label: &'a str) -> impl FnOnce() -> Work + 'a {
1018 move || {
1019 let results: Vec<Result<u64, String>> = std::thread::scope(|scope| {
1020 let handles: Vec<_> = setup
1021 .workload
1022 .iter()
1023 .enumerate()
1024 .map(|(a, props)| {
1025 scope.spawn(move || {
1026 for p in props {
1027 synapse_submit(
1028 &setup.service,
1029 setup.group.as_ref(),
1030 &setup.agents[a],
1031 &setup.repo_id,
1032 setup.base_oid,
1033 p,
1034 &format!("{label}/a{a}/p{}", p.index),
1035 )?;
1036 }
1037 Ok(props.len() as u64)
1038 })
1039 })
1040 .collect();
1041 handles
1042 .into_iter()
1043 .map(|h| {
1044 h.join()
1045 .unwrap_or_else(|_| Err("agent thread panicked".into()))
1046 })
1047 .collect()
1048 });
1049 let mut ops = 0;
1050 let mut error = None;
1051 for r in results {
1052 match r {
1053 Ok(n) => ops += n,
1054 Err(e) => error = error.or(Some(e)),
1055 }
1056 }
1057 Work { ops, error }
1058 }
1059}
1060
1061/// Populated query target: changesets and readable paths, chosen deterministically.
1062struct QueryPlan {
1063 reads: Vec<(ChangesetId, String)>,
1064 trees: Vec<ChangesetId>,
1065 diffs: Vec<ChangesetId>,
1066}
1067
1068fn query_prepare(
1069 dir: &Path,
1070 seed: u64,
1071 leg: &LegSpec,
1072 fx: &FixtureData,
1073) -> Result<(Svc, QueryPlan), String> {
1074 let LegSpec::Query {
1075 populate_agents,
1076 populate_ops_per_agent,
1077 samples,
1078 } = *leg
1079 else {
1080 return Err("not a query leg".into());
1081 };
1082 let mut s = Svc::open(
1083 dir,
1084 seed,
1085 populate_agents,
1086 FsyncPolicy::BatchWindow { max_records: 1024 },
1087 fx,
1088 )?;
1089 let workload = generate_write_workload(
1090 seed,
1091 20_000,
1092 populate_agents,
1093 populate_ops_per_agent,
1094 &fx.files,
1095 );
1096 let mut readable = Vec::new();
1097 let mut changesets = Vec::new();
1098 for (a, props) in workload.iter().enumerate() {
1099 for p in props {
1100 let now = crate::unix_now_ms();
1101 let req = synapse_arm::build_submit_request(
1102 &s.ids.agents[a],
1103 &s.ids.repo_id,
1104 s.base_oid,
1105 p,
1106 &format!("pmu-diag/query-pop/a{a}/p{}", p.index),
1107 now,
1108 )?;
1109 let (decoded, _) = synapse_arm::wire_roundtrip(&req)?;
1110 let cs = match s.svc.submit(&decoded, now).map_err(|e| e.to_string())? {
1111 IngestOutcome::Committed { changeset_id, .. }
1112 | IngestOutcome::IdempotentDuplicate { changeset_id, .. } => changeset_id,
1113 };
1114 changesets.push(cs);
1115 for e in &p.edits {
1116 if let EditOp::Upsert { .. } = e.op {
1117 readable.push((cs, e.path.clone()));
1118 }
1119 }
1120 }
1121 }
1122 s.svc.store_mut().sync_wal().map_err(|e| e.to_string())?;
1123 if readable.is_empty() || changesets.is_empty() {
1124 return Err("query population has no upserted files".into());
1125 }
1126 let mut rng = SplitMix64::derive(seed, &[0x0E_E7, 64]);
1127 let plan = QueryPlan {
1128 reads: (0..samples)
1129 .map(|_| readable[rng.below(readable.len())].clone())
1130 .collect(),
1131 trees: (0..samples)
1132 .map(|_| changesets[rng.below(changesets.len())])
1133 .collect(),
1134 diffs: (0..samples)
1135 .map(|_| changesets[rng.below(changesets.len())])
1136 .collect(),
1137 };
1138 Ok((s, plan))
1139}
1140
1141fn query_window<'a>(s: &'a mut Svc, plan: &'a QueryPlan) -> impl FnOnce() -> Work + 'a {
1142 move || {
1143 let mut ops = 0;
1144 let base = TreeTarget::BaseGitCommit(s.base_oid);
1145 let run = |s: &mut Svc, ops: &mut u64| -> Result<(), String> {
1146 for (cs, path) in &plan.reads {
1147 s.call(
1148 (TreeTarget::Changeset(*cs), path.clone(), None::<WalSeq>),
1149 |svc, req, now| svc.read_file(req, now),
1150 )?;
1151 *ops += 1;
1152 }
1153 for cs in &plan.trees {
1154 let target = TreeTarget::Changeset(*cs);
1155 s.all_pages(
1156 |page| TreeQueryPayload {
1157 target,
1158 path_prefix: None,
1159 page,
1160 },
1161 SynapseService::tree,
1162 )?;
1163 *ops += 1;
1164 }
1165 for cs in &plan.diffs {
1166 let target = TreeTarget::Changeset(*cs);
1167 s.all_pages(
1168 |page| DiffQueryPayload { base, target, page },
1169 SynapseService::diff,
1170 )?;
1171 *ops += 1;
1172 }
1173 Ok(())
1174 };
1175 let error = run(s, &mut ops).err();
1176 Work { ops, error }
1177 }
1178}
1179
1180/// Paths for crumb queries, or `None` when the fixture base has no `.crumb` file.
1181fn crumb_paths(fx: &FixtureData, seed: u64, samples: usize) -> Option<Vec<String>> {
1182 if !fx
1183 .base
1184 .entries
1185 .iter()
1186 .any(|e| e.path == ".crumb" || e.path.ends_with("/.crumb"))
1187 {
1188 return None;
1189 }
1190 let paths: Vec<&str> = fx.base.entries.iter().map(|e| e.path.as_str()).collect();
1191 let mut rng = SplitMix64::derive(seed, &[0xC2_0B, 64]);
1192 Some(
1193 (0..samples)
1194 .map(|_| paths[rng.below(paths.len())].to_string())
1195 .collect(),
1196 )
1197}
1198
1199fn crumb_window<'a>(s: &'a mut Svc, paths: &'a [String]) -> impl FnOnce() -> Work + 'a {
1200 move || {
1201 let base = TreeTarget::BaseGitCommit(s.base_oid);
1202 let mut ops = 0;
1203 let mut run = || -> Result<(), String> {
1204 for p in paths {
1205 s.call_local(
1206 CrumbContextQueryPayload {
1207 target: base,
1208 path: p.clone(),
1209 snapshot_seq: None,
1210 },
1211 |svc, req, now| svc.crumb_context(req, now),
1212 )?;
1213 ops += 1;
1214 s.call_local(
1215 ChangesetAdvisoryPayload {
1216 base,
1217 latest: None,
1218 paths: vec![p.clone()],
1219 agent: "pmu-diag".into(),
1220 snapshot_seq: None,
1221 },
1222 |svc, req, now| svc.changeset_advisory(req, None, now),
1223 )?;
1224 ops += 1;
1225 }
1226 Ok(())
1227 };
1228 let error = run().err();
1229 Work { ops, error }
1230 }
1231}
1232
1233fn record(
1234 windows: &mut Vec<Window>,
1235 leg: &str,
1236 affinity: AffinityPolicy,
1237 rep: usize,
1238 instrumented: bool,
1239 m: (Work, u64, u64, u64, PmuSample),
1240) {
1241 let (work, wall_ns, cpu_user_us, cpu_sys_us, pmu) = m;
1242 windows.push(Window {
1243 leg: leg.into(),
1244 affinity,
1245 rep,
1246 instrumented,
1247 ops: work.ops,
1248 wall_ns,
1249 cpu_user_us,
1250 cpu_sys_us,
1251 error: work.error,
1252 pmu,
1253 });
1254}
1255
1256/// Run every leg of `protocol.json` in `cfg.evidence_dir`; write raw, report, sums.
1257/// Refuses to overwrite an existing `raw.json`.
1258pub fn run_diag(cfg: &DiagConfig) -> Result<Report, String> {
1259 let protocol_bytes = fs::read(cfg.evidence_dir.join(PROTOCOL_FILE))
1260 .map_err(|e| format!("read {PROTOCOL_FILE}: {e}"))?;
1261 let protocol: Protocol =
1262 serde_json::from_slice(&protocol_bytes).map_err(|e| format!("{PROTOCOL_FILE}: {e}"))?;
1263 protocol.validate()?;
1264 let raw_path = cfg.evidence_dir.join(RAW_FILE);
1265 if raw_path.exists() {
1266 return Err(format!(
1267 "{} exists; evidence is never overwritten",
1268 raw_path.display()
1269 ));
1270 }
1271 fs::create_dir_all(&cfg.work_dir).map_err(|e| format!("mkdir work dir: {e}"))?;
1272 let needs_fixture = protocol.legs.iter().any(LegSpec::needs_fixture);
1273 let fx = if needs_fixture {
1274 let repo = cfg
1275 .fixture_repo
1276 .as_deref()
1277 .ok_or("write, query and crumb legs need --fixture-repo")?;
1278 let rev = protocol.fixture_rev.as_deref().unwrap_or_default();
1279 let base = fixture::list_base_tree(repo, rev)?;
1280 let full = fixture::load_full_base(repo, &base)?;
1281 let files = fixture::editable_from_full_base(&base, &full);
1282 Some(FixtureData { base, full, files })
1283 } else {
1284 None
1285 };
1286 let manifest = Manifest {
1287 invocation: cfg.invocation.clone(),
1288 started_at: crate::utc_timestamp(),
1289 host: collect_host_info(&cfg.work_dir),
1290 build_profile: if cfg!(debug_assertions) {
1291 "debug"
1292 } else {
1293 "release"
1294 }
1295 .into(),
1296 target_arch: std::env::consts::ARCH.into(),
1297 source_rev: cfg.source_rev.clone(),
1298 fixture_repo: cfg.fixture_repo.as_ref().map(|p| p.display().to_string()),
1299 fixture_commit: fx.as_ref().map(|f| f.base.commit_hex.clone()),
1300 siblings: cfg.siblings.clone(),
1301 clock: "std::time::Instant (CLOCK_MONOTONIC), wall nanoseconds per window".into(),
1302 energy: "NOT_MEASURED by pmu-diag (energy stays with run, floor and bounds)".into(),
1303 };
1304 let mut windows = Vec::new();
1305 let mut not_run = Vec::new();
1306 let seed = protocol.seed;
1307 let scratch = cfg.work_dir.join("pmu-diag");
1308 for leg in &protocol.legs {
1309 let id = leg.id();
1310 for &aff in &protocol.affinity {
1311 let _pin = match apply_affinity(aff, &cfg.discovery) {
1312 Ok(g) => g,
1313 Err(reason) => {
1314 not_run.push(NotRun {
1315 leg: id.clone(),
1316 affinity: aff,
1317 reason,
1318 });
1319 continue;
1320 }
1321 };
1322 let leg_dir = scratch.join(id.replace(['/', '='], "_")).join(aff.code());
1323 let _ = fs::remove_dir_all(&leg_dir);
1324 let outcome = run_leg(
1325 cfg,
1326 &protocol,
1327 leg,
1328 &id,
1329 aff,
1330 seed,
1331 fx.as_ref(),
1332 &leg_dir,
1333 &mut windows,
1334 );
1335 let _ = fs::remove_dir_all(&leg_dir);
1336 if let Err(reason) = outcome {
1337 windows.retain(|w| !(w.leg == id && w.affinity == aff));
1338 not_run.push(NotRun {
1339 leg: id.clone(),
1340 affinity: aff,
1341 reason,
1342 });
1343 }
1344 }
1345 }
1346 let raw = Raw {
1347 schema: RAW_SCHEMA.into(),
1348 protocol_sha256: sha256_hex(&protocol_bytes),
1349 manifest,
1350 discovery: cfg.discovery.clone(),
1351 windows,
1352 not_run,
1353 };
1354 let raw_bytes = serde_json::to_vec_pretty(&raw).map_err(|e| e.to_string())?;
1355 let report = compute_report(&protocol_bytes, &raw_bytes).map_err(|e| e.to_string())?;
1356 let report_bytes = serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?;
1357 fs::write(&raw_path, &raw_bytes).map_err(|e| format!("write {RAW_FILE}: {e}"))?;
1358 fs::write(cfg.evidence_dir.join(REPORT_FILE), &report_bytes)
1359 .map_err(|e| format!("write {REPORT_FILE}: {e}"))?;
1360 let sums = sha256sums(&cfg.evidence_dir, &[PROTOCOL_FILE, RAW_FILE, REPORT_FILE])?;
1361 fs::write(cfg.evidence_dir.join(SUMS_FILE), sums)
1362 .map_err(|e| format!("write {SUMS_FILE}: {e}"))?;
1363 Ok(report)
1364}
1365
1366/// Run every repetition of one (leg, affinity). A setup failure (not a window error)
1367/// returns `Err` and the caller records the pair as not run.
1368#[allow(clippy::too_many_arguments)]
1369fn run_leg(
1370 cfg: &DiagConfig,
1371 protocol: &Protocol,
1372 leg: &LegSpec,
1373 id: &str,
1374 aff: AffinityPolicy,
1375 seed: u64,
1376 fx: Option<&FixtureData>,
1377 leg_dir: &Path,
1378 windows: &mut Vec<Window>,
1379) -> Result<(), String> {
1380 let d = &cfg.discovery;
1381 let fixture = || fx.ok_or_else(|| "fixture not loaded".to_string());
1382 match leg {
1383 LegSpec::Floor { op, iterations } => {
1384 // One untimed warm-up pass so the first control window is not cold.
1385 floor_window(*op, (*iterations / 10).max(1))();
1386 for rep in 0..protocol.reps {
1387 for instrumented in [false, true] {
1388 let m = measure(d, aff, instrumented, floor_window(*op, *iterations));
1389 record(windows, id, aff, rep, instrumented, m);
1390 }
1391 }
1392 }
1393 LegSpec::Write {
1394 arm,
1395 agents,
1396 ops_per_agent,
1397 } => {
1398 let fx = fixture()?;
1399 for rep in 0..protocol.reps {
1400 for instrumented in [false, true] {
1401 let dir =
1402 leg_dir.join(format!("r{rep}-{}", if instrumented { "i" } else { "c" }));
1403 let setup = write_setup(&dir, seed, rep, *arm, *agents, *ops_per_agent, fx)?;
1404 let label = format!("pmu-diag/{id}/{}/r{rep}/{instrumented}", aff.code());
1405 let m = measure(d, aff, instrumented, write_window(&setup, &label));
1406 drop(setup);
1407 let _ = fs::remove_dir_all(&dir);
1408 record(windows, id, aff, rep, instrumented, m);
1409 }
1410 }
1411 }
1412 LegSpec::Query { .. } => {
1413 let fx = fixture()?;
1414 let (mut s, plan) = query_prepare(leg_dir, seed, leg, fx)?;
1415 // Untimed warm-up: materialize every virtual tree the windows will read.
1416 let warm = query_window(&mut s, &plan)();
1417 if let Some(e) = warm.error {
1418 return Err(format!("query warm-up: {e}"));
1419 }
1420 for rep in 0..protocol.reps {
1421 for instrumented in [false, true] {
1422 let m = measure(d, aff, instrumented, query_window(&mut s, &plan));
1423 record(windows, id, aff, rep, instrumented, m);
1424 }
1425 }
1426 }
1427 LegSpec::Crumb { samples } => {
1428 let fx = fixture()?;
1429 let paths = crumb_paths(fx, seed, *samples).ok_or(
1430 "fixture base has no .crumb file: no representative Crumb fixture (NOT_RUN)",
1431 )?;
1432 let mut s = Svc::open(leg_dir, seed, 1, FsyncPolicy::EveryCommit, fx)?;
1433 let warm = crumb_window(&mut s, &paths)();
1434 if let Some(e) = warm.error {
1435 return Err(format!("crumb warm-up: {e}"));
1436 }
1437 for rep in 0..protocol.reps {
1438 for instrumented in [false, true] {
1439 let m = measure(d, aff, instrumented, crumb_window(&mut s, &paths));
1440 record(windows, id, aff, rep, instrumented, m);
1441 }
1442 }
1443 }
1444 }
1445 Ok(())
1446}
1447
1448/// `UnavailableReason` codes as they appear in reports.
1449pub fn reason_code(r: UnavailableReason) -> String {
1450 enum_code(&r)
1451}
1452
1453#[cfg(test)]
1454mod tests;