interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / evidence / a2-segment-store / measurement / main-comparison.patch

586 lines · 23057 bytes Raw Blame History
1diff --git a/crates/synapse-bench/src/lib.rs b/crates/synapse-bench/src/lib.rs
2index c6ba08a..49dc260 100644
3--- a/crates/synapse-bench/src/lib.rs
4+++ b/crates/synapse-bench/src/lib.rs
5@@ -29,6 +29,7 @@ pub mod query;
6 pub mod recovery;
7 pub mod rng;
8 pub mod rusage;
9+pub mod segments;
10 pub mod stats;
11 pub mod synapse_arm;
12 pub mod workload;
13diff --git a/crates/synapse-bench/src/main.rs b/crates/synapse-bench/src/main.rs
14index 6127f10..e176589 100644
15--- a/crates/synapse-bench/src/main.rs
16+++ b/crates/synapse-bench/src/main.rs
17@@ -12,6 +12,9 @@
18 //! [--repo-root <path>] [--source-rev R] [--hwmon-root <path>]
19 //! synapse-bench bounds-verify --evidence <dir>
20 //! synapse-bench bounds-report --evidence <dir> (prints report.json recomputed from protocol.json and raw.json)
21+//! synapse-bench segments --dir <dir on the store filesystem> --out <raw.json> [--agents 1,4,8,32]
22+//! [--changes N] [--reps N] [--blob-bytes N] [--segment-mib N] [--checkpoint-every N] [--idle-window-s S]
23+//! synapse-bench segments-report --raw <raw.json> --floor <floor.json> (prints the A2 report)
24 //! ```
25
26 use std::path::PathBuf;
27@@ -305,6 +308,68 @@ fn crypto_vectors_verify(args: &[String]) -> Result<(), String> {
28 Ok(())
29 }
30
31+/// `segments`: ADR 0003 A2 segment store measurement (raw samples to `--out`).
32+fn segments(args: &[String]) -> Result<(), String> {
33+ let opts = parse_pairs(
34+ args,
35+ &[
36+ "--dir",
37+ "--out",
38+ "--agents",
39+ "--changes",
40+ "--reps",
41+ "--blob-bytes",
42+ "--segment-mib",
43+ "--checkpoint-every",
44+ "--idle-window-s",
45+ ],
46+ )?;
47+ let get = |k: &str| {
48+ opts.iter()
49+ .rev()
50+ .find(|(key, _)| key == k)
51+ .map(|(_, v)| v.clone())
52+ };
53+ let num = |k: &str, d: u64| -> Result<u64, String> {
54+ get(k).map_or(Ok(d), |v| v.parse().map_err(|_| format!("invalid {k}")))
55+ };
56+ let cfg = synapse_bench::segments::SegmentsConfig {
57+ agents: parse_list(&get("--agents").unwrap_or_else(|| "1,4,8,32".into()), |x| {
58+ x.parse().ok().filter(|n| *n > 0)
59+ })?,
60+ changes: num("--changes", 4000)? as usize,
61+ reps: num("--reps", 3)? as usize,
62+ blob_bytes: num("--blob-bytes", 11_949)? as usize,
63+ segment_bytes: num("--segment-mib", 16)? * 1024 * 1024,
64+ checkpoint_every: num("--checkpoint-every", 1000)? as usize,
65+ idle_window_s: num("--idle-window-s", 30)?,
66+ };
67+ let dir = PathBuf::from(get("--dir").ok_or("missing --dir")?);
68+ let out = PathBuf::from(get("--out").ok_or("missing --out")?);
69+ let raw = synapse_bench::segments::run_segments(&dir, &cfg)?;
70+ synapse_bench::write_json(&out, &raw)
71+}
72+
73+/// `segments-report`: recompute the A2 report from `--raw` and a `--floor` report.
74+fn segments_report(args: &[String]) -> Result<(), String> {
75+ use std::io::Write;
76+ let opts = parse_pairs(args, &["--raw", "--floor"])?;
77+ let get = |k: &str| {
78+ opts.iter()
79+ .rev()
80+ .find(|(key, _)| key == k)
81+ .map(|(_, v)| PathBuf::from(v))
82+ .ok_or(format!("missing {k}"))
83+ };
84+ let raw: synapse_bench::segments::SegmentsRaw = synapse_bench::read_json(&get("--raw")?)?;
85+ let floor: synapse_bench::floor::FloorReport = synapse_bench::read_json(&get("--floor")?)?;
86+ let report = synapse_bench::segments::segments_report(&raw, &floor)?;
87+ let bytes = serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?;
88+ std::io::stdout()
89+ .write_all(&bytes)
90+ .map_err(|e| format!("write stdout: {e}"))
91+}
92+
93 fn main() -> ExitCode {
94 let args: Vec<String> = std::env::args().skip(1).collect();
95 let outcome = match args.first().map(String::as_str) {
96@@ -316,6 +381,8 @@ fn main() -> ExitCode {
97 Some("bounds-report") => bounds_report(&args[1..]),
98 Some("crypto-vectors-write") => crypto_vectors_write(&args[1..]),
99 Some("crypto-vectors-verify") => crypto_vectors_verify(&args[1..]),
100+ Some("segments") => segments(&args[1..]),
101+ Some("segments-report") => segments_report(&args[1..]),
102 _ => Err("usage: synapse-bench run ... | synapse-bench child ... (see crate docs)".into()),
103 };
104 match outcome {
105diff --git a/crates/synapse-bench/src/segments.rs b/crates/synapse-bench/src/segments.rs
106new file mode 100644
107index 0000000..5119dbe
108--- /dev/null
109+++ b/crates/synapse-bench/src/segments.rs
110@@ -0,0 +1,476 @@
111+//! ADR 0003 A2 measurement: seconds and joules per accepted change of the segment store,
112+//! against the section 6.2 flush bound.
113+//!
114+//! Each cell opens a fresh store with `FsyncPolicy::GROUP_COMMIT_DEFAULT` through
115+//! [`SharedStore`], starts `agents` threads that submit signed one-file changesets of
116+//! `blob_bytes` each, and records every change's time from `submit` to durable
117+//! acknowledgement. Small segments make the run rotate (new segment file, pre-write,
118+//! directory flush) inside the timed window, and a checkpoint runs every
119+//! `checkpoint_every` accepted changes (blobs stay in the segments). The whole cell is one
120+//! energy window of the `aien_spbm` package meter; a missing meter leaves joules `None`
121+//! with the reason (`INSTRUMENT_UNAVAILABLE`), never a substitute.
122+//!
123+//! Bounds (fraction of bound reached = bound / measured, at most 1):
124+//! * latency of one change: one flush plus the change's bytes moved once at memory
125+//! bandwidth;
126+//! * steady-state interval per accepted change: the largest of flush / agents (all
127+//! agents' changes sharing one flush), bytes / device write bandwidth, bytes / memory
128+//! bandwidth, and the change's SHA-256 plus one Ed25519 verification at all-core rates;
129+//! * package joules per change: the idle package power for the interval bound (the
130+//! package draws at least that while the work runs). A floor model, not physics; NVMe
131+//! energy is UNMEASURED on this host.
132+//!
133+//! The flush time is the cheapest `overwrite_*_fdatasync` p50 of a `floor.json` measured
134+//! on the same filesystem (`synapse-bench floor`).
135+
136+use crate::energy::{idle_window, EnergyReading, EnergyWindow};
137+use crate::floor::FloorReport;
138+use crate::stats::{summarize_us, LatencySummary};
139+use ed25519_dalek::SigningKey;
140+use serde::{Deserialize, Serialize};
141+use std::path::{Path, PathBuf};
142+use std::sync::atomic::{AtomicUsize, Ordering};
143+use std::sync::{Barrier, Mutex};
144+use std::time::{Duration, Instant};
145+use synapse_core::{
146+ BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey, MutationOp, PathMutation,
147+ RepoId, SYNAPSE_ENVELOPE_VERSION,
148+};
149+use synapse_store::{FsyncPolicy, IngestOutcome, RecoveryPolicy, SharedStore, StoreLimits};
150+
151+/// Memory bandwidth, bytes per second: NVIDIA DGX Spark specification, 273 GB/s (A0).
152+pub const MEMORY_BW_BPS: f64 = 273e9;
153+/// Device write bandwidth bound, bytes per second: the drive's PCIe link (A0).
154+pub const DEVICE_BW_BPS: f64 = 15.754e9;
155+/// All-core SHA-256 implementation reference, bytes per second (J3).
156+pub const SHA256_ALLCORE_BPS: f64 = 39.46e9;
157+/// All-core Ed25519 verification implementation reference, per second (J3).
158+pub const ED25519_ALLCORE_PER_S: f64 = 397_560.0;
159+
160+/// Run configuration.
161+#[derive(Debug, Clone, Serialize, Deserialize)]
162+pub struct SegmentsConfig {
163+ pub agents: Vec<usize>,
164+ pub changes: usize,
165+ pub reps: usize,
166+ pub blob_bytes: usize,
167+ pub segment_bytes: u64,
168+ pub checkpoint_every: usize,
169+ pub idle_window_s: u64,
170+}
171+
172+/// One measured cell (raw samples).
173+#[derive(Debug, Clone, Serialize, Deserialize)]
174+pub struct CellRaw {
175+ pub agents: usize,
176+ pub rep: usize,
177+ pub accepted: usize,
178+ /// Wall time of the cell from the barrier release to the last acknowledgement.
179+ pub elapsed_ns: u64,
180+ /// Every accepted change's time from `submit` to durable acknowledgement.
181+ pub latency_ns: Vec<u64>,
182+ /// Duration of every checkpoint run during the cell.
183+ pub checkpoint_ns: Vec<u64>,
184+ pub batches: u64,
185+ pub segment_files: usize,
186+ pub blob_files: usize,
187+ pub energy: EnergyReading,
188+}
189+
190+/// Figures of one cell against the bound.
191+#[derive(Debug, Clone, Serialize, Deserialize)]
192+pub struct CellReport {
193+ pub agents: usize,
194+ pub rep: usize,
195+ pub latency: Option<LatencySummary>,
196+ pub interval_s: f64,
197+ pub interval_bound_s: f64,
198+ pub interval_fraction: f64,
199+ pub latency_p50_s: f64,
200+ pub latency_bound_s: f64,
201+ pub latency_fraction: f64,
202+ pub mean_batch: f64,
203+ pub pkg_j_per_change: Option<f64>,
204+ pub pkg_j_per_change_above_idle: Option<f64>,
205+ pub pkg_mean_w: Option<f64>,
206+ pub energy_bound_j: Option<f64>,
207+ pub energy_fraction: Option<f64>,
208+ pub energy_refusal: Option<String>,
209+}
210+
211+/// Bound inputs used for the report.
212+#[derive(Debug, Clone, Serialize, Deserialize)]
213+pub struct BoundInputs {
214+ pub flush_s: f64,
215+ pub flush_probe: String,
216+ pub blob_bytes: usize,
217+ pub memory_bw_bps: f64,
218+ pub device_bw_bps: f64,
219+ pub sha256_allcore_bps: f64,
220+ pub ed25519_allcore_per_s: f64,
221+ pub idle_pkg_w: Option<f64>,
222+}
223+
224+/// Raw output of a run.
225+#[derive(Debug, Clone, Serialize, Deserialize)]
226+pub struct SegmentsRaw {
227+ pub config: SegmentsConfig,
228+ pub store_dir: String,
229+ pub idle: EnergyReading,
230+ pub cells: Vec<CellRaw>,
231+}
232+
233+/// Flush time: the cheapest overwrite-plus-`fdatasync` p50 in the floor report.
234+pub fn flush_from_floor(floor: &FloorReport) -> Result<(f64, String), String> {
235+ floor
236+ .storage
237+ .iter()
238+ .filter(|p| p.name.starts_with("overwrite_") && p.name.ends_with("_fdatasync"))
239+ .filter_map(|p| p.latency.as_ref().map(|l| (l.p50_ms / 1e3, p.name.clone())))
240+ .min_by(|a, b| a.0.total_cmp(&b.0))
241+ .ok_or_else(|| "floor report has no overwrite_*_fdatasync probe".to_string())
242+}
243+
244+/// Interval bound per accepted change at `agents` concurrent agents.
245+pub fn interval_bound_s(b: &BoundInputs, agents: usize) -> f64 {
246+ let bytes = b.blob_bytes as f64;
247+ let crypto = bytes / b.sha256_allcore_bps + 1.0 / b.ed25519_allcore_per_s;
248+ (b.flush_s / agents.max(1) as f64)
249+ .max(bytes / b.device_bw_bps)
250+ .max(bytes / b.memory_bw_bps)
251+ .max(crypto)
252+}
253+
254+/// Latency bound of one change: one flush plus its bytes moved once at memory bandwidth.
255+pub fn latency_bound_s(b: &BoundInputs) -> f64 {
256+ b.flush_s + b.blob_bytes as f64 / b.memory_bw_bps
257+}
258+
259+/// Compute the report of one cell (pure function of the raw cell and bound inputs).
260+pub fn cell_report(c: &CellRaw, b: &BoundInputs, idle: &EnergyReading) -> CellReport {
261+ let n = c.accepted.max(1) as f64;
262+ let interval_s = c.elapsed_ns as f64 / 1e9 / n;
263+ let us: Vec<u64> = c.latency_ns.iter().map(|v| v / 1000).collect();
264+ let latency = summarize_us(&us);
265+ let mut sorted = c.latency_ns.clone();
266+ sorted.sort_unstable();
267+ let p50_ns = crate::stats::nearest_rank(&sorted, 0.5).unwrap_or(0);
268+ let latency_p50_s = p50_ns as f64 / 1e9;
269+ let interval_bound = interval_bound_s(b, c.agents);
270+ let latency_bound = latency_bound_s(b);
271+ let pkg_j_per_change = c.energy.pkg_j.map(|j| j / n);
272+ let energy_bound_j = b.idle_pkg_w.map(|w| w * interval_bound);
273+ CellReport {
274+ agents: c.agents,
275+ rep: c.rep,
276+ latency,
277+ interval_s,
278+ interval_bound_s: interval_bound,
279+ interval_fraction: interval_bound / interval_s,
280+ latency_p50_s,
281+ latency_bound_s: latency_bound,
282+ latency_fraction: if latency_p50_s > 0.0 {
283+ latency_bound / latency_p50_s
284+ } else {
285+ 0.0
286+ },
287+ mean_batch: c.accepted as f64 / c.batches.max(1) as f64,
288+ pkg_j_per_change,
289+ pkg_j_per_change_above_idle: c.energy.pkg_above_idle_j(idle).map(|j| j / n),
290+ pkg_mean_w: c.energy.pkg_mean_w,
291+ energy_bound_j,
292+ energy_fraction: match (energy_bound_j, pkg_j_per_change) {
293+ (Some(bound), Some(m)) if m > 0.0 => Some(bound / m),
294+ _ => None,
295+ },
296+ energy_refusal: c.energy.refusal.clone().or_else(|| {
297+ c.energy
298+ .pkg_j
299+ .is_none()
300+ .then(|| format!("INSTRUMENT_UNAVAILABLE: {}", c.energy.sensor))
301+ }),
302+ }
303+}
304+
305+fn changeset(
306+ key: &SigningKey,
307+ label: &str,
308+ blob_bytes: usize,
309+) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) {
310+ let mut content = format!("// {label}\n").into_bytes();
311+ let mut x: u32 = label.bytes().fold(2_166_136_261u32, |a, b| {
312+ (a ^ u32::from(b)).wrapping_mul(16_777_619)
313+ });
314+ while content.len() < blob_bytes {
315+ x ^= x << 13;
316+ x ^= x >> 17;
317+ x ^= x << 5;
318+ content.push(b"abcdefghijklmnopqrstuvwxyz \n(){};"[(x % 33) as usize]);
319+ }
320+ let digest = BlobDigest::compute(&content);
321+ let path = format!("src/{label}.rs");
322+ let mut env = ChangesetEnvelope {
323+ version: SYNAPSE_ENVELOPE_VERSION,
324+ repo_id: RepoId::new("aien-spark/synapse").expect("repo id"),
325+ base_git_oid: GitOid::compute_blob(b"base"),
326+ parent_changesets: vec![],
327+ author_did: String::new(),
328+ idempotency_key: IdempotencyKey::from_label(label),
329+ created_at_ms: 1000,
330+ intent_summary: format!("Update {path}"),
331+ mutations: vec![PathMutation {
332+ path,
333+ op: MutationOp::Upsert {
334+ mode: FileMode::Regular644,
335+ blob_digest: digest,
336+ size_bytes: content.len() as u64,
337+ },
338+ }],
339+ evidence_receipts: vec![],
340+ signature: vec![],
341+ };
342+ env.sign(key);
343+ (env, vec![(digest, content)])
344+}
345+
346+fn count_files(dir: &Path, pred: &dyn Fn(&str) -> bool) -> usize {
347+ let Ok(rd) = std::fs::read_dir(dir) else {
348+ return 0;
349+ };
350+ rd.filter_map(Result::ok)
351+ .map(|e| {
352+ if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
353+ count_files(&e.path(), pred)
354+ } else {
355+ usize::from(pred(&e.file_name().to_string_lossy()))
356+ }
357+ })
358+ .sum()
359+}
360+
361+fn run_cell(
362+ dir: &Path,
363+ cfg: &SegmentsConfig,
364+ agents: usize,
365+ rep: usize,
366+) -> Result<CellRaw, String> {
367+ let _ = std::fs::remove_dir_all(dir);
368+ std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
369+ let limits = StoreLimits::default(); // main: no segments (comparison build)
370+ let shared = SharedStore::open(
371+ dir,
372+ FsyncPolicy::GROUP_COMMIT_DEFAULT,
373+ RecoveryPolicy::StrictFailClosed,
374+ limits,
375+ )
376+ .map_err(|e| format!("open store: {e:?}"))?;
377+ // Prepare every agent's changesets before timing (signing is the agent's own work).
378+ let per_agent = cfg.changes.div_ceil(agents);
379+ let work: Vec<Vec<_>> = (0..agents)
380+ .map(|a| {
381+ let key = SigningKey::from_bytes(&[(a as u8).wrapping_add(1); 32]);
382+ (0..per_agent)
383+ .map(|i| changeset(&key, &format!("a{a}-r{rep}-c{i}"), cfg.blob_bytes))
384+ .collect()
385+ })
386+ .collect();
387+ let accepted = AtomicUsize::new(0);
388+ // Agents that finished every submission and any checkpoint they triggered.
389+ let agents_done = AtomicUsize::new(0);
390+ let latencies = Mutex::new(Vec::with_capacity(cfg.changes));
391+ let checkpoints = Mutex::new(Vec::new());
392+ let errors = Mutex::new(Vec::<String>::new());
393+ let barrier = Barrier::new(agents + 1);
394+ let batches_before = shared.stats().batches;
395+ let (elapsed, energy) = std::thread::scope(|s| {
396+ for w in &work {
397+ let (shared, accepted, agents_done, latencies, checkpoints, errors, barrier) = (
398+ &shared,
399+ &accepted,
400+ &agents_done,
401+ &latencies,
402+ &checkpoints,
403+ &errors,
404+ &barrier,
405+ );
406+ s.spawn(move || {
407+ barrier.wait();
408+ for (env, blobs) in w {
409+ let t = Instant::now();
410+ match shared.submit(env.clone(), blobs) {
411+ Ok(IngestOutcome::Committed { .. }) => {
412+ let ns = t.elapsed().as_nanos() as u64;
413+ latencies.lock().unwrap().push(ns);
414+ let n = accepted.fetch_add(1, Ordering::SeqCst) + 1;
415+ if cfg.checkpoint_every > 0 && n % cfg.checkpoint_every == 0 {
416+ let t = Instant::now();
417+ match shared.with_exclusive(|st| st.checkpoint_and_compact(1000)) {
418+ Ok(_) => checkpoints
419+ .lock()
420+ .unwrap()
421+ .push(t.elapsed().as_nanos() as u64),
422+ Err(e) => {
423+ errors.lock().unwrap().push(format!("checkpoint: {e:?}"))
424+ }
425+ }
426+ }
427+ }
428+ Ok(other) => errors
429+ .lock()
430+ .unwrap()
431+ .push(format!("not committed: {other:?}")),
432+ Err(e) => errors.lock().unwrap().push(format!("submit: {e:?}")),
433+ }
434+ }
435+ agents_done.fetch_add(1, Ordering::SeqCst);
436+ });
437+ }
438+ let window = EnergyWindow::start();
439+ let t0 = Instant::now();
440+ barrier.wait();
441+ // The scope joins the agents when this closure returns; time them here instead,
442+ // up to the end of the last checkpoint an agent ran.
443+ while agents_done.load(Ordering::SeqCst) < agents {
444+ std::thread::sleep(Duration::from_micros(200));
445+ }
446+ (t0.elapsed(), window.finish())
447+ });
448+ let errors = errors.into_inner().unwrap();
449+ if !errors.is_empty() {
450+ return Err(format!(
451+ "{} failed submissions, first: {}",
452+ errors.len(),
453+ errors[0]
454+ ));
455+ }
456+ let batches = shared.stats().batches - batches_before;
457+ drop(shared);
458+ let segment_files = count_files(dir, &|n| {
459+ n.starts_with("wal.v2")
460+ });
461+ let blob_files = count_files(&dir.join("blobs"), &|_| true);
462+ Ok(CellRaw {
463+ agents,
464+ rep,
465+ accepted: accepted.into_inner(),
466+ elapsed_ns: elapsed.as_nanos() as u64,
467+ latency_ns: latencies.into_inner().unwrap(),
468+ checkpoint_ns: checkpoints.into_inner().unwrap(),
469+ batches,
470+ segment_files,
471+ blob_files,
472+ energy,
473+ })
474+}
475+
476+/// Run every cell (agents x reps, agent counts interleaved inside each repetition).
477+pub fn run_segments(store_dir: &Path, cfg: &SegmentsConfig) -> Result<SegmentsRaw, String> {
478+ let idle = idle_window(Duration::from_secs(cfg.idle_window_s));
479+ let mut cells = Vec::new();
480+ for rep in 0..cfg.reps {
481+ for &agents in &cfg.agents {
482+ let dir: PathBuf = store_dir.join(format!("cell-{agents}-{rep}"));
483+ let cell = run_cell(&dir, cfg, agents, rep)?;
484+ let _ = std::fs::remove_dir_all(&dir);
485+ eprintln!(
486+ "agents {agents} rep {rep}: {} accepted in {:.3} s, {} batches, {} segment files",
487+ cell.accepted,
488+ cell.elapsed_ns as f64 / 1e9,
489+ cell.batches,
490+ cell.segment_files
491+ );
492+ cells.push(cell);
493+ }
494+ }
495+ Ok(SegmentsRaw {
496+ config: cfg.clone(),
497+ store_dir: store_dir.display().to_string(),
498+ idle,
499+ cells,
500+ })
501+}
502+
503+/// Report of a run: bound inputs and every cell's figures.
504+#[derive(Debug, Clone, Serialize, Deserialize)]
505+pub struct SegmentsReport {
506+ pub bounds: BoundInputs,
507+ pub cells: Vec<CellReport>,
508+}
509+
510+/// Recompute the report from the raw run and the floor report.
511+pub fn segments_report(raw: &SegmentsRaw, floor: &FloorReport) -> Result<SegmentsReport, String> {
512+ let (flush_s, flush_probe) = flush_from_floor(floor)?;
513+ let bounds = BoundInputs {
514+ flush_s,
515+ flush_probe,
516+ blob_bytes: raw.config.blob_bytes,
517+ memory_bw_bps: MEMORY_BW_BPS,
518+ device_bw_bps: DEVICE_BW_BPS,
519+ sha256_allcore_bps: SHA256_ALLCORE_BPS,
520+ ed25519_allcore_per_s: ED25519_ALLCORE_PER_S,
521+ idle_pkg_w: raw.idle.pkg_mean_w,
522+ };
523+ let cells = raw
524+ .cells
525+ .iter()
526+ .map(|c| cell_report(c, &bounds, &raw.idle))
527+ .collect();
528+ Ok(SegmentsReport { bounds, cells })
529+}
530+
531+#[cfg(test)]
532+mod tests {
533+ use super::*;
534+
535+ fn inputs() -> BoundInputs {
536+ BoundInputs {
537+ flush_s: 0.0008,
538+ flush_probe: "overwrite_1m_fdatasync".into(),
539+ blob_bytes: 11_949,
540+ memory_bw_bps: MEMORY_BW_BPS,
541+ device_bw_bps: DEVICE_BW_BPS,
542+ sha256_allcore_bps: SHA256_ALLCORE_BPS,
543+ ed25519_allcore_per_s: ED25519_ALLCORE_PER_S,
544+ idle_pkg_w: Some(20.0),
545+ }
546+ }
547+
548+ #[test]
549+ fn interval_bound_is_flush_shared_by_agents_until_crypto_dominates() {
550+ let b = inputs();
551+ assert_eq!(interval_bound_s(&b, 1), 0.0008);
552+ assert_eq!(interval_bound_s(&b, 8), 0.0001);
553+ // 1000 agents: the flush share (0.8 us) is below one change's crypto (2.82 us).
554+ let crypto = 11_949.0 / SHA256_ALLCORE_BPS + 1.0 / ED25519_ALLCORE_PER_S;
555+ assert_eq!(interval_bound_s(&b, 1000), crypto);
556+ assert!(latency_bound_s(&b) > 0.0008);
557+ }
558+
559+ #[test]
560+ fn fractions_are_bound_over_measured_and_refused_energy_stays_none() {
561+ let b = inputs();
562+ let cell = CellRaw {
563+ agents: 1,
564+ rep: 0,
565+ accepted: 4,
566+ elapsed_ns: 8_000_000,
567+ latency_ns: vec![1_600_000; 4],
568+ checkpoint_ns: vec![],
569+ batches: 4,
570+ segment_files: 1,
571+ blob_files: 0,
572+ energy: EnergyReading {
573+ refusal: Some("INSTRUMENT_UNAVAILABLE: no aien_spbm device".into()),
574+ ..Default::default()
575+ },
576+ };
577+ let r = cell_report(&cell, &b, &EnergyReading::default());
578+ assert_eq!(r.interval_s, 0.002);
579+ assert!((r.interval_fraction - 0.4).abs() < 1e-12);
580+ assert!(r.pkg_j_per_change.is_none() && r.energy_fraction.is_none());
581+ assert!(r
582+ .energy_refusal
583+ .unwrap()
584+ .starts_with("INSTRUMENT_UNAVAILABLE"));
585+ }
586+}