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 / bin / wire-transport.rs

578 lines · 23158 bytes Raw Blame History
1//! G1 and G3 transport measurement: seconds and joules per accepted change across the wire
2//! transports (Unix socket or shared-memory ring, binary frames, have-want negotiation),
3//! against the ADR 0003 section 6 bound for one durable change
4//! (`docs/PHASE5_GROUP_COMMIT.md` section 5).
5//!
6//! ```text
7//! wire-transport --out DIR [--changes N] [--reps R] [--idle-s S] [--store-root DIR]
8//! [--arms wire,ring,direct_auth,direct] [--step G1|G3] [--rule FILE]
9//! [--echo N]
10//! ```
11//!
12//! Arms (default `wire,direct_auth,direct`, the G1 set), order rotated per repetition, each
13//! on a fresh store directory with `GROUP_COMMIT_DEFAULT` and one agent submitting one change
14//! at a time:
15//! * `wire`: client and server threads joined by a Unix socket; per change Have, Want,
16//! Chunk (only the blobs the server lacks), Submit, Accepted after durable commit.
17//! * `direct_auth`: the same chain authorisation and store admission in process, no
18//! transport (isolates framing and socket cost).
19//! * `direct`: store admission only (no chain check).
20//! * `ring` (G3): as `wire`, over a `RingStream` on a sealed shared-memory region
21//! (`RingConfig::default()`) instead of the Unix socket.
22//!
23//! `--rule FILE` (G3, experiment X5): the decision rule, which must be a file committed in
24//! git with no uncommitted change, so it is fixed before the run; its commit and SHA-256
25//! go into `spec.json`, and `result.json` gets the verdict computed by [`x5_verdict`] (the
26//! rule written as code). `--echo N`: also time N round trips of one 3,967-byte `Chunk`
27//! frame per transport per repetition, echoed back unchanged (supporting figure only).
28//!
29//! Every change upserts one new 3,967-byte blob (the Gate 4 median new content per change)
30//! and one blob shared by every change (sent once, then skipped by negotiation).
31//! Envelopes and requests are signed before timing starts. `spec.json` is written before
32//! the first change; `result.json` holds every per-change latency in nanoseconds.
33
34use serde_json::json;
35use sha2::{Digest, Sha256};
36use std::io::{Read, Write};
37use std::os::unix::net::UnixStream;
38use std::path::{Path, PathBuf};
39use std::process::ExitCode;
40use std::sync::Arc;
41use std::time::{Duration, Instant};
42use synapse_auth::{BoundaryKind, Capability, ChainedRequest, PolicyEnforcer};
43use synapse_bench::energy::{idle_window, EnergyReading, EnergyWindow};
44use synapse_core::{BlobDigest, ChangesetEnvelope, WalSeq};
45use synapse_store::{FsyncPolicy, RecoveryPolicy, SharedStore, StoreLimits};
46use synapse_wire::frame::{Chunk, Frame, FrameBody};
47use synapse_wire::session::submit_request;
48use synapse_wire::testkit::{envelope, repo, server, ChainFixture, FIXTURE_NOW_MS};
49use synapse_wire::{FrameConn, RingConfig, RingRegion, RingStream, Side, WireClient, WireLimits};
50
51/// Bound inputs, `docs/PHASE5_GROUP_COMMIT.md` section 5 (W1 floor, one agent).
52const FLUSH_FLOOR_S: f64 = 0.805e-3;
53const SEQ_WRITE_S_PER_GIB: f64 = 0.138;
54const FLOOR_BYTES_PER_CHANGE: f64 = 11_500.0;
55const IDLE_W_FLOOR: f64 = 22.731;
56const ESSENTIAL_CPU_J: f64 = 0.2766e-3;
57/// Gate 4 median new content per change, bytes.
58const NEW_BLOB_BYTES: usize = 3_967;
59
60struct Change {
61 env: ChangesetEnvelope,
62 req: ChainedRequest,
63 blobs: Vec<(BlobDigest, Vec<u8>)>,
64}
65
66fn blob(seed: u64, len: usize) -> Vec<u8> {
67 let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
68 (0..len)
69 .map(|_| {
70 x ^= x << 13;
71 x ^= x >> 7;
72 x ^= x << 17;
73 (x >> 24) as u8
74 })
75 .collect()
76}
77
78fn build_changes(fx: &ChainFixture, rep: usize, n: usize, shared: &[u8]) -> Vec<Change> {
79 (0..n)
80 .map(|i| {
81 let new = blob((rep as u64) << 32 | i as u64, NEW_BLOB_BYTES);
82 let path = format!("src/r{rep}/c{i:05}.rs");
83 let shared_path = format!("src/r{rep}/shared{i:05}.rs");
84 let (env, blobs) = envelope(
85 &fx.agent,
86 &format!("wire-{rep}-{i}"),
87 &[(&path, new), (&shared_path, shared.to_vec())],
88 &[],
89 1_000 + i as u64,
90 );
91 let mut nonce = [0u8; 32];
92 nonce[..8].copy_from_slice(&(rep as u64).to_le_bytes());
93 nonce[8..16].copy_from_slice(&(i as u64).to_le_bytes());
94 let req = submit_request(&fx.agent, fx.chain.clone(), &env, nonce, 1_000 + i as u64)
95 .expect("request");
96 Change { env, req, blobs }
97 })
98 .collect()
99}
100
101fn open(dir: &Path) -> Arc<SharedStore> {
102 let _ = std::fs::remove_dir_all(dir);
103 std::fs::create_dir_all(dir).expect("store dir");
104 Arc::new(
105 SharedStore::open(
106 dir,
107 FsyncPolicy::GROUP_COMMIT_DEFAULT,
108 RecoveryPolicy::StrictFailClosed,
109 StoreLimits::default(),
110 )
111 .expect("open store"),
112 )
113}
114
115/// Per repetition: seconds per change, package joules per change, above-idle joules.
116type RepFigures = (f64, Option<f64>, f64);
117
118struct ArmRun {
119 latencies_ns: Vec<u64>,
120 elapsed_s: f64,
121 energy: EnergyReading,
122 wire_bytes_sent: u64,
123 wire_bytes_received: u64,
124 chunks_sent: u64,
125 chunk_bytes_sent: u64,
126}
127
128/// A connected Unix socket pair: (client end, server end).
129fn socket_pair() -> (UnixStream, UnixStream) {
130 UnixStream::pair().expect("socket pair")
131}
132
133/// A shared-memory ring region (sealed memfd) with both ends in this process: (client end,
134/// server end).
135fn ring_pair() -> (RingStream, RingStream) {
136 let region = RingRegion::create_shared(RingConfig::default()).expect("ring region");
137 (region.stream(Side::Creator), region.stream(Side::Attacher))
138}
139
140fn run_wire<S: Read + Write + Send + 'static>(
141 fx: &ChainFixture,
142 dir: &Path,
143 changes: &[Change],
144 (a, b): (S, S),
145) -> ArmRun {
146 let store = open(dir);
147 let srv = server(fx, store.clone());
148 let s = srv.clone();
149 let t = std::thread::spawn(move || s.serve(b));
150 let mut client = WireClient::connect(a, WireLimits::default()).expect("connect");
151 let (s0, r0) = client.bytes();
152 let mut lat = Vec::with_capacity(changes.len());
153 let (mut chunks, mut chunk_bytes) = (0u64, 0u64);
154 let w = EnergyWindow::start();
155 let start = Instant::now();
156 for c in changes {
157 let t0 = Instant::now();
158 let rep = client.submit(&c.req, &c.blobs).expect("accepted");
159 lat.push(t0.elapsed().as_nanos() as u64);
160 assert!(!rep.accepted.duplicate);
161 chunks += rep.wanted as u64;
162 chunk_bytes += rep.chunk_bytes_sent;
163 }
164 let elapsed_s = start.elapsed().as_secs_f64();
165 let energy = w.finish();
166 let (s1, r1) = client.bytes();
167 drop(client);
168 t.join().expect("server thread").expect("server");
169 ArmRun {
170 latencies_ns: lat,
171 elapsed_s,
172 energy,
173 wire_bytes_sent: s1 - s0,
174 wire_bytes_received: r1 - r0,
175 chunks_sent: chunks,
176 chunk_bytes_sent: chunk_bytes,
177 }
178}
179
180fn run_direct(fx: &ChainFixture, dir: &Path, changes: &[Change], auth: bool) -> ArmRun {
181 let store = open(dir);
182 let mut enforcer: PolicyEnforcer = fx.enforcer();
183 let mut lat = Vec::with_capacity(changes.len());
184 let w = EnergyWindow::start();
185 let start = Instant::now();
186 for c in changes {
187 let t0 = Instant::now();
188 if auth {
189 let seq = WalSeq(store.read().committed_seq().0 + 1);
190 enforcer
191 .authorize_chain(
192 BoundaryKind::Api,
193 "wire_submit",
194 &repo(),
195 Capability::Propose,
196 &c.req,
197 seq,
198 FIXTURE_NOW_MS,
199 )
200 .expect("authorized");
201 }
202 store.submit(c.env.clone(), &c.blobs).expect("committed");
203 lat.push(t0.elapsed().as_nanos() as u64);
204 }
205 let elapsed_s = start.elapsed().as_secs_f64();
206 let energy = w.finish();
207 ArmRun {
208 latencies_ns: lat,
209 elapsed_s,
210 energy,
211 wire_bytes_sent: 0,
212 wire_bytes_received: 0,
213 chunks_sent: 0,
214 chunk_bytes_sent: 0,
215 }
216}
217
218/// Round trips of one 3,967-byte `Chunk` frame, echoed back unchanged by a server thread;
219/// nanoseconds per round trip. Supporting figure only (not part of the X5 rule).
220fn run_echo<S: Read + Write + Send + 'static>((a, b): (S, S), n: usize) -> Vec<u64> {
221 let t = std::thread::spawn(move || {
222 let mut conn = FrameConn::new(b, WireLimits::default());
223 while let Some(f) = conn.recv().expect("echo server recv") {
224 conn.send(&f).expect("echo server send");
225 }
226 });
227 let mut conn = FrameConn::new(a, WireLimits::default());
228 let frame = Frame {
229 request_id: 1,
230 body: FrameBody::Chunk(Chunk {
231 digest: BlobDigest([7; 32]),
232 bytes: blob(0xEC40, NEW_BLOB_BYTES),
233 }),
234 };
235 let mut lat = Vec::with_capacity(n);
236 for _ in 0..n {
237 let t0 = Instant::now();
238 conn.send(&frame).expect("echo send");
239 let back = conn.recv().expect("echo recv").expect("echo frame");
240 lat.push(t0.elapsed().as_nanos() as u64);
241 assert_eq!(back, frame);
242 }
243 drop(conn);
244 t.join().expect("echo server");
245 lat
246}
247
248/// The X5 decision rule of `evidence/g3-shm-ring/x5/RULE.md`, as code: adopt the ring only
249/// if it is lower than the Unix socket (`wire`) in seconds per accepted change AND in
250/// package joules per accepted change, each beyond run-to-run spread (median lower, and its
251/// worst repetition below the socket's best). Joules need a valid meter window for every
252/// repetition of both arms; otherwise they are `INSTRUMENT_UNAVAILABLE` and the ring is not
253/// adopted.
254fn x5_verdict(ring: &[RepFigures], wire: &[RepFigures]) -> serde_json::Value {
255 let max = |v: &[f64]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
256 let min = |v: &[f64]| v.iter().copied().fold(f64::INFINITY, f64::min);
257 let mut rs: Vec<f64> = ring.iter().map(|x| x.0).collect();
258 let mut ws: Vec<f64> = wire.iter().map(|x| x.0).collect();
259 let seconds_lower = median(&mut rs) < median(&mut ws) && max(&rs) < min(&ws);
260 let rj: Option<Vec<f64>> = ring.iter().map(|x| x.1).collect();
261 let wj: Option<Vec<f64>> = wire.iter().map(|x| x.1).collect();
262 let (joules, joules_lower) = match (rj, wj) {
263 (Some(mut rj), Some(mut wj)) => {
264 let lower = median(&mut rj) < median(&mut wj) && max(&rj) < min(&wj);
265 (
266 json!({"ring_j_per_change_reps": rj, "wire_j_per_change_reps": wj, "lower_beyond_spread": lower}),
267 lower,
268 )
269 }
270 _ => (json!("INSTRUMENT_UNAVAILABLE"), false),
271 };
272 let adopt = seconds_lower && joules_lower;
273 json!({
274 "rule": "evidence/g3-shm-ring/x5/RULE.md",
275 "seconds": {
276 "ring_s_per_change_reps": rs,
277 "wire_s_per_change_reps": ws,
278 "lower_beyond_spread": seconds_lower,
279 },
280 "joules": joules,
281 "verdict": if adopt { "ADOPTED" } else { "NOT_ADOPTED" },
282 })
283}
284
285/// The rule file must be tracked by git with no change against `HEAD`, so the rule was
286/// fixed (committed) before this run. Returns its path, commit and SHA-256.
287fn committed_rule(path: &Path) -> Result<serde_json::Value, String> {
288 let git = |args: &[&str]| {
289 std::process::Command::new("git")
290 .args(args)
291 .output()
292 .map_err(|e| format!("git: {e}"))
293 };
294 let p = path.to_str().ok_or("rule path is not UTF-8")?;
295 if !git(&["ls-files", "--error-unmatch", p])?.status.success() {
296 return Err(format!("{p} is not committed"));
297 }
298 if !git(&["diff", "--quiet", "HEAD", "--", p])?.status.success() {
299 return Err(format!("{p} has uncommitted changes"));
300 }
301 let log = git(&["log", "-1", "--format=%H", "--", p])?;
302 let commit = String::from_utf8_lossy(&log.stdout).trim().to_string();
303 let bytes = std::fs::read(path).map_err(|e| format!("{p}: {e}"))?;
304 Ok(json!({
305 "path": p,
306 "commit": commit,
307 "sha256": hex::encode(Sha256::digest(&bytes)),
308 }))
309}
310
311fn nearest_rank(sorted: &[u64], q: f64) -> u64 {
312 let rank = (q * sorted.len() as f64).ceil() as usize;
313 sorted[rank.clamp(1, sorted.len()) - 1]
314}
315
316fn median(v: &mut [f64]) -> f64 {
317 v.sort_by(|a, b| a.total_cmp(b));
318 v[v.len() / 2]
319}
320
321fn git_rev() -> String {
322 std::process::Command::new("git")
323 .args(["rev-parse", "HEAD"])
324 .output()
325 .ok()
326 .filter(|o| o.status.success())
327 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
328 .unwrap_or_else(|| "unknown".into())
329}
330
331fn usage() -> ExitCode {
332 eprintln!(
333 "usage: wire-transport --out DIR [--changes N] [--reps R] [--idle-s S] [--store-root DIR] \
334 [--arms wire,ring,direct_auth,direct] [--step LABEL] [--rule FILE] [--echo N]"
335 );
336 ExitCode::from(2)
337}
338
339fn main() -> ExitCode {
340 let args: Vec<String> = std::env::args().skip(1).collect();
341 let (mut out, mut changes_n, mut reps, mut idle_s) = (None, 2000usize, 3usize, 30u64);
342 let mut store_root = PathBuf::from("target/wire-transport-stores");
343 let mut arms: Vec<String> = ["wire", "direct_auth", "direct"].map(String::from).to_vec();
344 let (mut step, mut rule, mut echo_n) = (String::from("G1"), None::<PathBuf>, 0usize);
345 let mut i = 0;
346 while i < args.len() {
347 let Some(v) = args.get(i + 1) else {
348 return usage();
349 };
350 match args[i].as_str() {
351 "--out" => out = Some(PathBuf::from(v)),
352 "--changes" => match v.parse() {
353 Ok(n) => changes_n = n,
354 Err(_) => return usage(),
355 },
356 "--reps" => match v.parse() {
357 Ok(n) => reps = n,
358 Err(_) => return usage(),
359 },
360 "--idle-s" => match v.parse() {
361 Ok(n) => idle_s = n,
362 Err(_) => return usage(),
363 },
364 "--store-root" => store_root = PathBuf::from(v),
365 "--arms" => arms = v.split(',').map(String::from).collect(),
366 "--step" => step = v.clone(),
367 "--rule" => rule = Some(PathBuf::from(v)),
368 "--echo" => match v.parse() {
369 Ok(n) => echo_n = n,
370 Err(_) => return usage(),
371 },
372 _ => return usage(),
373 }
374 i += 2;
375 }
376 let Some(out) = out else { return usage() };
377 const KNOWN: [&str; 4] = ["wire", "ring", "direct_auth", "direct"];
378 if changes_n == 0
379 || reps == 0
380 || arms.is_empty()
381 || arms.iter().any(|a| !KNOWN.contains(&a.as_str()))
382 {
383 return usage();
384 }
385 // The X5 rule must be committed before the run (checked here, before any measurement).
386 let rule_info = match &rule {
387 Some(p) => match committed_rule(p) {
388 Ok(v) => Some(v),
389 Err(e) => {
390 eprintln!("refusing to run: decision rule not fixed: {e}");
391 return ExitCode::from(2);
392 }
393 },
394 None => None,
395 };
396 std::fs::create_dir_all(&out).expect("out dir");
397 std::fs::create_dir_all(&store_root).expect("store root");
398 let t_floor =
399 FLUSH_FLOOR_S + FLOOR_BYTES_PER_CHANGE * SEQ_WRITE_S_PER_GIB / (1u64 << 30) as f64;
400 let e_floor = IDLE_W_FLOOR * t_floor + ESSENTIAL_CPU_J;
401 let spec = json!({
402 "tool": "wire-transport",
403 "step": step,
404 "git_rev": git_rev(),
405 "changes_per_arm": changes_n,
406 "reps": reps,
407 "arms": arms,
408 "order": "rotated per repetition",
409 "agents": 1,
410 "fsync_policy": "GROUP_COMMIT_DEFAULT",
411 "chain_depth": 2,
412 "per_change": {"new_blob_bytes": NEW_BLOB_BYTES, "shared_blob_bytes": NEW_BLOB_BYTES, "paths": 2},
413 "transport": {
414 "wire": "std::os::unix::net::UnixStream pair, client and server threads in one process",
415 "ring": "synapse_wire::RingStream over one sealed memfd region (MAP_SHARED), client and server threads in one process",
416 },
417 "ring_config": {
418 "capacity_bytes_per_direction": RingConfig::default().capacity,
419 "max_record_bytes": RingConfig::default().max_record,
420 "spin_s": RingConfig::default().spin.as_secs_f64(),
421 "sleep": "futex on the doorbell word, 10 ms timeout",
422 },
423 "echo_round_trips_per_transport_per_rep": echo_n,
424 "rule": rule_info,
425 "store_root": store_root.display().to_string(),
426 "idle_window_s": idle_s,
427 "bound": {
428 "source": "docs/PHASE5_GROUP_COMMIT.md section 5 (ADR 0003 section 6 durable latency for one change)",
429 "t_floor_s": t_floor,
430 "t_floor_formula": "0.805 ms + 11500 B x 0.138 s/GiB",
431 "e_floor_j": e_floor,
432 "e_floor_formula": "22.731 W x t_floor + 0.2766 mJ",
433 "fraction": "floor / measured (1.0 = at the floor)",
434 },
435 "energy_sensor": "aien_spbm hwmon: SoC package only, uncalibrated; NVMe UNMEASURED",
436 "declared_before_run": true,
437 });
438 std::fs::write(
439 out.join("spec.json"),
440 serde_json::to_string_pretty(&spec).expect("json") + "\n",
441 )
442 .expect("write spec");
443 eprintln!("spec written; idle window {idle_s} s");
444 let idle = idle_window(Duration::from_secs(idle_s));
445
446 let fx = ChainFixture::new(2, None);
447 let shared = blob(0xFEED, NEW_BLOB_BYTES);
448 let mut runs: Vec<serde_json::Value> = Vec::new();
449 let mut per_arm: std::collections::BTreeMap<&str, Vec<RepFigures>> = Default::default();
450 let mut echo: std::collections::BTreeMap<&str, Vec<u64>> = Default::default();
451 for rep in 0..reps {
452 for k in 0..arms.len() {
453 let arm = arms[(k + rep) % arms.len()].as_str();
454 let changes = build_changes(&fx, rep, changes_n, &shared);
455 let dir = store_root.join(format!("{arm}-{rep}"));
456 let r = match arm {
457 "wire" => run_wire(&fx, &dir, &changes, socket_pair()),
458 "ring" => run_wire(&fx, &dir, &changes, ring_pair()),
459 "direct_auth" => run_direct(&fx, &dir, &changes, true),
460 _ => run_direct(&fx, &dir, &changes, false),
461 };
462 let _ = std::fs::remove_dir_all(&dir);
463 let mut s = r.latencies_ns.clone();
464 s.sort_unstable();
465 let n = s.len() as f64;
466 let s_per_change = r.elapsed_s / n;
467 let j_per_change = r.energy.pkg_j.map(|j| j / n);
468 let above_idle = r.energy.pkg_above_idle_j(&idle).map(|j| j / n);
469 per_arm.entry(arm).or_default().push((
470 s_per_change,
471 j_per_change,
472 above_idle.unwrap_or(f64::NAN),
473 ));
474 eprintln!(
475 "rep {rep} {arm}: {:.3} ms/change, p50 {:.3} ms, {:?} J/change",
476 s_per_change * 1e3,
477 nearest_rank(&s, 0.5) as f64 / 1e6,
478 j_per_change
479 );
480 runs.push(json!({
481 "rep": rep,
482 "arm": arm,
483 "changes": s.len(),
484 "elapsed_s": r.elapsed_s,
485 "s_per_change": s_per_change,
486 "p50_s": nearest_rank(&s, 0.50) as f64 / 1e9,
487 "p99_s": nearest_rank(&s, 0.99) as f64 / 1e9,
488 "max_s": s[s.len() - 1] as f64 / 1e9,
489 "pkg_j_per_change": j_per_change,
490 "pkg_above_idle_j_per_change": above_idle,
491 "wire_bytes_sent_per_change": r.wire_bytes_sent as f64 / n,
492 "wire_bytes_received_per_change": r.wire_bytes_received as f64 / n,
493 "chunks_sent": r.chunks_sent,
494 "chunk_bytes_sent": r.chunk_bytes_sent,
495 "energy": r.energy,
496 "latencies_ns": r.latencies_ns,
497 }));
498 }
499 if echo_n > 0 {
500 for k in 0..2 {
501 let transport = ["wire", "ring"][(k + rep) % 2];
502 let mut lat = if transport == "wire" {
503 run_echo(socket_pair(), echo_n)
504 } else {
505 run_echo(ring_pair(), echo_n)
506 };
507 let raw = lat.clone();
508 lat.sort_unstable();
509 eprintln!(
510 "rep {rep} echo {transport}: p50 {:.2} us per round trip",
511 nearest_rank(&lat, 0.5) as f64 / 1e3
512 );
513 echo.entry(transport)
514 .or_default()
515 .push(nearest_rank(&lat, 0.5));
516 runs.push(json!({
517 "rep": rep,
518 "echo": transport,
519 "round_trips": raw.len(),
520 "p50_s": nearest_rank(&lat, 0.50) as f64 / 1e9,
521 "p99_s": nearest_rank(&lat, 0.99) as f64 / 1e9,
522 "round_trip_ns": raw,
523 }));
524 }
525 }
526 }
527 let mut summary = serde_json::Map::new();
528 for (arm, v) in &per_arm {
529 let mut s: Vec<f64> = v.iter().map(|x| x.0).collect();
530 let mut j: Vec<f64> = v.iter().filter_map(|x| x.1).collect();
531 let mut a: Vec<f64> = v.iter().map(|x| x.2).filter(|x| x.is_finite()).collect();
532 let s_med = median(&mut s);
533 let j_med = (!j.is_empty()).then(|| median(&mut j));
534 summary.insert(
535 arm.to_string(),
536 json!({
537 "s_per_change_median": s_med,
538 "s_per_change_reps": v.iter().map(|x| x.0).collect::<Vec<_>>(),
539 "fraction_of_time_floor": t_floor / s_med,
540 "pkg_j_per_change_median": j_med,
541 "pkg_j_per_change_reps": v.iter().map(|x| x.1).collect::<Vec<_>>(),
542 "fraction_of_energy_floor": j_med.map(|j| e_floor / j),
543 "pkg_above_idle_j_per_change_median": (!a.is_empty()).then(|| median(&mut a)),
544 }),
545 );
546 }
547 for (transport, p50s) in &echo {
548 let mut v: Vec<f64> = p50s.iter().map(|&ns| ns as f64 / 1e9).collect();
549 summary.insert(
550 format!("echo_{transport}"),
551 json!({"p50_s_reps": v.clone(), "p50_s_median": median(&mut v), "role": "supporting only, not in the X5 rule"}),
552 );
553 }
554 let verdict = match (&rule_info, per_arm.get("ring"), per_arm.get("wire")) {
555 (Some(_), Some(ring), Some(wire)) => Some(x5_verdict(ring, wire)),
556 _ => None,
557 };
558 let result = json!({
559 "spec": spec,
560 "idle": idle,
561 "summary": summary,
562 "x5_verdict": verdict,
563 "runs": runs,
564 });
565 std::fs::write(
566 out.join("result.json"),
567 serde_json::to_string_pretty(&result).expect("json") + "\n",
568 )
569 .expect("write result");
570 eprintln!("{}", serde_json::to_string_pretty(&summary).expect("json"));
571 if let Some(v) = &verdict {
572 eprintln!(
573 "X5 verdict: {}",
574 serde_json::to_string_pretty(v).expect("json")
575 );
576 }
577 ExitCode::SUCCESS
578}