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 / segments.rs

691 lines · 26462 bytes Raw Blame History
1//! ADR 0003 A2 measurement: seconds and joules per accepted change of the segment store,
2//! against the section 6.2 flush bound.
3//!
4//! Each cell opens a fresh store with `FsyncPolicy::GROUP_COMMIT_DEFAULT` through
5//! [`SharedStore`], starts `agents` threads that submit signed one-file changesets of
6//! `blob_bytes` each, and records every change's time from `submit` to durable
7//! acknowledgement. Small segments make the run rotate (new segment file, pre-write,
8//! directory flush) inside the timed window, and a checkpoint runs every
9//! `checkpoint_every` accepted changes (blobs stay in the segments). The whole cell is one
10//! energy window of the `aien_spbm` package meter; a missing meter leaves joules `None`
11//! with the reason (`INSTRUMENT_UNAVAILABLE`), never a substitute.
12//!
13//! Bounds (fraction of bound reached = bound / measured, at most 1):
14//! * latency of one change: one flush plus the change's bytes moved once at memory
15//! bandwidth;
16//! * steady-state interval per accepted change: the largest of flush / agents (all
17//! agents' changes sharing one flush), bytes / device write bandwidth, bytes / memory
18//! bandwidth, and the change's SHA-256 plus one Ed25519 verification at all-core rates;
19//! * package joules per change: the idle package power for the interval bound (the
20//! package draws at least that while the work runs). A floor model, not physics; NVMe
21//! energy is UNMEASURED on this host.
22//!
23//! The flush time is the cheapest `overwrite_*_fdatasync` p50 of a `floor.json` measured
24//! on the same filesystem (`synapse-bench floor`).
25
26use crate::energy::{idle_window, EnergyReading, EnergyWindow};
27use crate::floor::FloorReport;
28use crate::stats::{summarize_us, LatencySummary};
29use ed25519_dalek::SigningKey;
30use serde::{Deserialize, Serialize};
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicUsize, Ordering};
33use std::sync::{Barrier, Mutex};
34use std::time::{Duration, Instant};
35use synapse_core::{
36 BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey, MutationOp, PathMutation,
37 RepoId, SYNAPSE_ENVELOPE_VERSION,
38};
39use synapse_core::{RefusalCode, SynapseError};
40use synapse_store::blockdev::BlockDevice;
41use synapse_store::{
42 BlockDeviceConfig, FormatPolicy, FsyncPolicy, IngestOutcome, RecoveryPolicy, SharedStore,
43 StoreLimits,
44};
45
46/// Memory bandwidth, bytes per second: NVIDIA DGX Spark specification, 273 GB/s (A0).
47pub const MEMORY_BW_BPS: f64 = 273e9;
48/// Device write bandwidth bound, bytes per second: the drive's PCIe link (A0).
49pub const DEVICE_BW_BPS: f64 = 15.754e9;
50/// All-core SHA-256 implementation reference, bytes per second (J3).
51pub const SHA256_ALLCORE_BPS: f64 = 39.46e9;
52/// All-core Ed25519 verification implementation reference, per second (J3).
53pub const ED25519_ALLCORE_PER_S: f64 = 397_560.0;
54
55/// Run configuration.
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct SegmentsConfig {
58 pub agents: Vec<usize>,
59 pub changes: usize,
60 pub reps: usize,
61 pub blob_bytes: usize,
62 pub segment_bytes: u64,
63 pub checkpoint_every: usize,
64 pub idle_window_s: u64,
65 /// R1 (issue #47): run every cell on a raw block store device at this absolute path
66 /// instead of a store directory. The path must not exist: for each cell the bench
67 /// creates a regular file there (preallocated, `block_device_bytes`), formats it,
68 /// and removes it afterwards. It never writes to a file it did not create.
69 #[serde(default)]
70 pub block_device: Option<String>,
71 /// Size of that device file.
72 #[serde(default = "default_block_device_bytes")]
73 pub block_device_bytes: u64,
74 /// Metadata region size of that device.
75 #[serde(default = "default_block_meta_bytes")]
76 pub block_meta_bytes: u64,
77}
78
79/// One measured cell (raw samples).
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct CellRaw {
82 pub agents: usize,
83 pub rep: usize,
84 pub accepted: usize,
85 /// Wall time of the cell from the barrier release to the last acknowledgement.
86 pub elapsed_ns: u64,
87 /// Every accepted change's time from `submit` to durable acknowledgement.
88 pub latency_ns: Vec<u64>,
89 /// Duration of every checkpoint run during the cell.
90 pub checkpoint_ns: Vec<u64>,
91 pub batches: u64,
92 pub segment_files: usize,
93 pub blob_files: usize,
94 pub energy: EnergyReading,
95}
96
97/// Figures of one cell against the bound.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct CellReport {
100 pub agents: usize,
101 pub rep: usize,
102 pub latency: Option<LatencySummary>,
103 pub interval_s: f64,
104 pub interval_bound_s: f64,
105 pub interval_fraction: f64,
106 pub latency_p50_s: f64,
107 pub latency_bound_s: f64,
108 pub latency_fraction: f64,
109 pub mean_batch: f64,
110 pub pkg_j_per_change: Option<f64>,
111 pub pkg_j_per_change_above_idle: Option<f64>,
112 pub pkg_mean_w: Option<f64>,
113 pub energy_bound_j: Option<f64>,
114 pub energy_fraction: Option<f64>,
115 pub energy_refusal: Option<String>,
116}
117
118/// Bound inputs used for the report.
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct BoundInputs {
121 pub flush_s: f64,
122 pub flush_probe: String,
123 pub blob_bytes: usize,
124 pub memory_bw_bps: f64,
125 pub device_bw_bps: f64,
126 pub sha256_allcore_bps: f64,
127 pub ed25519_allcore_per_s: f64,
128 pub idle_pkg_w: Option<f64>,
129}
130
131/// Raw output of a run.
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct SegmentsRaw {
134 pub config: SegmentsConfig,
135 pub store_dir: String,
136 pub idle: EnergyReading,
137 pub cells: Vec<CellRaw>,
138}
139
140/// Flush time: the cheapest overwrite-plus-`fdatasync` p50 in the floor report.
141pub fn flush_from_floor(floor: &FloorReport) -> Result<(f64, String), String> {
142 floor
143 .storage
144 .iter()
145 .filter(|p| p.name.starts_with("overwrite_") && p.name.ends_with("_fdatasync"))
146 .filter_map(|p| p.latency.as_ref().map(|l| (l.p50_ms / 1e3, p.name.clone())))
147 .min_by(|a, b| a.0.total_cmp(&b.0))
148 .ok_or_else(|| "floor report has no overwrite_*_fdatasync probe".to_string())
149}
150
151/// Interval bound per accepted change at `agents` concurrent agents.
152pub fn interval_bound_s(b: &BoundInputs, agents: usize) -> f64 {
153 let bytes = b.blob_bytes as f64;
154 let crypto = bytes / b.sha256_allcore_bps + 1.0 / b.ed25519_allcore_per_s;
155 (b.flush_s / agents.max(1) as f64)
156 .max(bytes / b.device_bw_bps)
157 .max(bytes / b.memory_bw_bps)
158 .max(crypto)
159}
160
161/// Latency bound of one change: one flush plus its bytes moved once at memory bandwidth.
162pub fn latency_bound_s(b: &BoundInputs) -> f64 {
163 b.flush_s + b.blob_bytes as f64 / b.memory_bw_bps
164}
165
166/// Compute the report of one cell (pure function of the raw cell and bound inputs).
167pub fn cell_report(c: &CellRaw, b: &BoundInputs, idle: &EnergyReading) -> CellReport {
168 let n = c.accepted.max(1) as f64;
169 let interval_s = c.elapsed_ns as f64 / 1e9 / n;
170 let us: Vec<u64> = c.latency_ns.iter().map(|v| v / 1000).collect();
171 let latency = summarize_us(&us);
172 let mut sorted = c.latency_ns.clone();
173 sorted.sort_unstable();
174 let p50_ns = crate::stats::nearest_rank(&sorted, 0.5).unwrap_or(0);
175 let latency_p50_s = p50_ns as f64 / 1e9;
176 let interval_bound = interval_bound_s(b, c.agents);
177 let latency_bound = latency_bound_s(b);
178 let pkg_j_per_change = c.energy.pkg_j.map(|j| j / n);
179 let energy_bound_j = b.idle_pkg_w.map(|w| w * interval_bound);
180 CellReport {
181 agents: c.agents,
182 rep: c.rep,
183 latency,
184 interval_s,
185 interval_bound_s: interval_bound,
186 interval_fraction: interval_bound / interval_s,
187 latency_p50_s,
188 latency_bound_s: latency_bound,
189 latency_fraction: if latency_p50_s > 0.0 {
190 latency_bound / latency_p50_s
191 } else {
192 0.0
193 },
194 mean_batch: c.accepted as f64 / c.batches.max(1) as f64,
195 pkg_j_per_change,
196 pkg_j_per_change_above_idle: c.energy.pkg_above_idle_j(idle).map(|j| j / n),
197 pkg_mean_w: c.energy.pkg_mean_w,
198 energy_bound_j,
199 energy_fraction: match (energy_bound_j, pkg_j_per_change) {
200 (Some(bound), Some(m)) if m > 0.0 => Some(bound / m),
201 _ => None,
202 },
203 energy_refusal: c.energy.refusal.clone().or_else(|| {
204 c.energy
205 .pkg_j
206 .is_none()
207 .then(|| format!("INSTRUMENT_UNAVAILABLE: {}", c.energy.sensor))
208 }),
209 }
210}
211
212fn changeset(
213 key: &SigningKey,
214 label: &str,
215 blob_bytes: usize,
216) -> (ChangesetEnvelope, Vec<(BlobDigest, Vec<u8>)>) {
217 let mut content = format!("// {label}\n").into_bytes();
218 let mut x: u32 = label.bytes().fold(2_166_136_261u32, |a, b| {
219 (a ^ u32::from(b)).wrapping_mul(16_777_619)
220 });
221 while content.len() < blob_bytes {
222 x ^= x << 13;
223 x ^= x >> 17;
224 x ^= x << 5;
225 content.push(b"abcdefghijklmnopqrstuvwxyz \n(){};"[(x % 33) as usize]);
226 }
227 let digest = BlobDigest::compute(&content);
228 let path = format!("src/{label}.rs");
229 let mut env = ChangesetEnvelope {
230 version: SYNAPSE_ENVELOPE_VERSION,
231 repo_id: RepoId::new("aien-spark/synapse").expect("repo id"),
232 base_git_oid: GitOid::compute_blob(b"base"),
233 parent_changesets: vec![],
234 author_did: String::new(),
235 idempotency_key: IdempotencyKey::from_label(label),
236 created_at_ms: 1000,
237 intent_summary: format!("Update {path}"),
238 mutations: vec![PathMutation {
239 path,
240 op: MutationOp::Upsert {
241 mode: FileMode::Regular644,
242 blob_digest: digest,
243 size_bytes: content.len() as u64,
244 },
245 }],
246 evidence_receipts: vec![],
247 signature: vec![],
248 };
249 env.sign(key);
250 (env, vec![(digest, content)])
251}
252
253fn count_files(dir: &Path, pred: &dyn Fn(&str) -> bool) -> usize {
254 let Ok(rd) = std::fs::read_dir(dir) else {
255 return 0;
256 };
257 rd.filter_map(Result::ok)
258 .map(|e| {
259 if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
260 count_files(&e.path(), pred)
261 } else {
262 usize::from(pred(&e.file_name().to_string_lossy()))
263 }
264 })
265 .sum()
266}
267
268/// Default size of the device file the bench creates for each R1 cell.
269pub const DEFAULT_BLOCK_DEVICE_BYTES: u64 = 512 << 20;
270/// Default metadata region size of that device.
271pub const DEFAULT_BLOCK_META_BYTES: u64 = 64 << 20;
272
273fn default_block_device_bytes() -> u64 {
274 DEFAULT_BLOCK_DEVICE_BYTES
275}
276
277fn default_block_meta_bytes() -> u64 {
278 DEFAULT_BLOCK_META_BYTES
279}
280
281/// The R1 device of one cell: a regular file the bench creates itself at the configured
282/// path, preallocated with zeros, and removes after the cell. The bench formats only
283/// a file it created: an existing path (a file, a symbolic link, anything) is refused
284/// before a byte is written, and it never opens a block device.
285struct BenchDevice {
286 path: PathBuf,
287 dev: u64,
288 ino: u64,
289}
290
291impl BenchDevice {
292 fn create(path: &str, bytes: u64) -> Result<Self, String> {
293 use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
294 let p = PathBuf::from(path);
295 if !p.is_absolute() {
296 return Err(format!("--block-device {path}: must be an absolute path"));
297 }
298 if bytes == 0 || !bytes.is_multiple_of(4096) {
299 return Err(format!(
300 "block device size {bytes} is not a positive multiple of 4096"
301 ));
302 }
303 // create_new (O_CREAT | O_EXCL) fails on any existing path, a dangling symbolic
304 // link included; O_NOFOLLOW as well.
305 let f = std::fs::OpenOptions::new()
306 .write(true)
307 .create_new(true)
308 .custom_flags(libc::O_NOFOLLOW)
309 .open(&p)
310 .map_err(|e| match e.kind() {
311 std::io::ErrorKind::AlreadyExists => format!(
312 "--block-device {path}: refusing, it already exists; the bench formats \
313 only a device file it creates itself (name a path that does not exist)"
314 ),
315 _ => format!("create {path}: {e}"),
316 })?;
317 let m = f.metadata().map_err(|e| format!("stat {path}: {e}"))?;
318 let device = Self {
319 path: p,
320 dev: m.dev(),
321 ino: m.ino(),
322 };
323 // Preallocate: every block written once (no sparse holes), then synced.
324 let zeros = vec![0u8; 1 << 20];
325 let mut at = 0u64;
326 while at < bytes {
327 let n = (bytes - at).min(zeros.len() as u64) as usize;
328 f.write_all_at(&zeros[..n], at)
329 .map_err(|e| format!("preallocate {path}: {e}"))?;
330 at += n as u64;
331 }
332 f.sync_all().map_err(|e| format!("sync {path}: {e}"))?;
333 Ok(device)
334 }
335}
336
337impl Drop for BenchDevice {
338 /// Remove the device file, only if the path still is the file this bench created.
339 fn drop(&mut self) {
340 use std::os::unix::fs::MetadataExt;
341 if let Ok(m) = std::fs::symlink_metadata(&self.path) {
342 if m.file_type().is_file() && m.dev() == self.dev && m.ino() == self.ino {
343 let _ = std::fs::remove_file(&self.path);
344 }
345 }
346 }
347}
348
349fn run_cell(
350 dir: &Path,
351 cfg: &SegmentsConfig,
352 agents: usize,
353 rep: usize,
354) -> Result<CellRaw, String> {
355 let _ = std::fs::remove_dir_all(dir);
356 std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
357 let limits = StoreLimits {
358 segment_bytes: cfg.segment_bytes,
359 ..Default::default()
360 };
361 let device = match cfg.block_device.as_deref() {
362 Some(p) => Some(BenchDevice::create(p, cfg.block_device_bytes)?),
363 None => None,
364 };
365 let block = device.as_ref().map(|d| BlockDeviceConfig {
366 path: d.path.clone(),
367 format: FormatPolicy::FormatIfBlank,
368 meta_region_bytes: cfg.block_meta_bytes,
369 allow_foreign_signature: false,
370 });
371 let shared = match &block {
372 Some(bc) => SharedStore::open_block_device(
373 bc,
374 FsyncPolicy::GROUP_COMMIT_DEFAULT,
375 RecoveryPolicy::StrictFailClosed,
376 limits,
377 ),
378 None => SharedStore::open(
379 dir,
380 FsyncPolicy::GROUP_COMMIT_DEFAULT,
381 RecoveryPolicy::StrictFailClosed,
382 limits,
383 ),
384 }
385 .map_err(|e| format!("open store: {e:?}"))?;
386 // Prepare every agent's changesets before timing (signing is the agent's own work).
387 let per_agent = cfg.changes.div_ceil(agents);
388 let work: Vec<Vec<_>> = (0..agents)
389 .map(|a| {
390 let key = SigningKey::from_bytes(&[(a as u8).wrapping_add(1); 32]);
391 (0..per_agent)
392 .map(|i| changeset(&key, &format!("a{a}-r{rep}-c{i}"), cfg.blob_bytes))
393 .collect()
394 })
395 .collect();
396 let accepted = AtomicUsize::new(0);
397 // Agents that finished every submission and any checkpoint they triggered.
398 let agents_done = AtomicUsize::new(0);
399 let latencies = Mutex::new(Vec::with_capacity(cfg.changes));
400 let checkpoints = Mutex::new(Vec::new());
401 let errors = Mutex::new(Vec::<String>::new());
402 let barrier = Barrier::new(agents + 1);
403 let batches_before = shared.stats().batches;
404 let (elapsed, energy) = std::thread::scope(|s| {
405 for w in &work {
406 let (shared, accepted, agents_done, latencies, checkpoints, errors, barrier) = (
407 &shared,
408 &accepted,
409 &agents_done,
410 &latencies,
411 &checkpoints,
412 &errors,
413 &barrier,
414 );
415 s.spawn(move || {
416 barrier.wait();
417 for (env, blobs) in w {
418 let t = Instant::now();
419 match shared.submit(env.clone(), blobs) {
420 Ok(IngestOutcome::Committed { .. }) => {
421 let ns = t.elapsed().as_nanos() as u64;
422 latencies.lock().unwrap().push(ns);
423 let n = accepted.fetch_add(1, Ordering::SeqCst) + 1;
424 if cfg.checkpoint_every > 0 && n % cfg.checkpoint_every == 0 {
425 let t = Instant::now();
426 match shared.with_exclusive(|st| st.checkpoint_and_compact(1000)) {
427 Ok(_) => checkpoints
428 .lock()
429 .unwrap()
430 .push(t.elapsed().as_nanos() as u64),
431 Err(e) => {
432 errors.lock().unwrap().push(format!("checkpoint: {e:?}"))
433 }
434 }
435 }
436 }
437 Ok(other) => errors
438 .lock()
439 .unwrap()
440 .push(format!("not committed: {other:?}")),
441 Err(e) => errors.lock().unwrap().push(format!("submit: {e:?}")),
442 }
443 }
444 agents_done.fetch_add(1, Ordering::SeqCst);
445 });
446 }
447 let window = EnergyWindow::start();
448 let t0 = Instant::now();
449 barrier.wait();
450 // The scope joins the agents when this closure returns; time them here instead,
451 // up to the end of the last checkpoint an agent ran.
452 while agents_done.load(Ordering::SeqCst) < agents {
453 std::thread::sleep(Duration::from_micros(200));
454 }
455 (t0.elapsed(), window.finish())
456 });
457 let errors = errors.into_inner().unwrap();
458 if !errors.is_empty() {
459 return Err(format!(
460 "{} failed submissions, first: {}",
461 errors.len(),
462 errors[0]
463 ));
464 }
465 let batches = shared.stats().batches - batches_before;
466 drop(shared);
467 let segment_files = match &block {
468 Some(bc) => {
469 let cfg = BlockDeviceConfig {
470 format: FormatPolicy::OpenExisting,
471 ..bc.clone()
472 };
473 // The store was just dropped, but its exclusive device lock can outlive the drop
474 // for a moment: a child process spawned concurrently (other tests in this process
475 // run commands) holds a copy of the descriptor until its exec closes it, and the
476 // lock stays while any copy is open. Retry a bounded number of times on "in use";
477 // any other refusal is returned at once.
478 let mut opened = BlockDevice::open_path(&cfg, 0);
479 for _ in 0..100 {
480 match &opened {
481 Err(e) if format!("{e:?}").contains("is in use") => {
482 std::thread::sleep(std::time::Duration::from_millis(20));
483 opened = BlockDevice::open_path(&cfg, 0);
484 }
485 _ => break,
486 }
487 }
488 opened
489 .and_then(|d| {
490 d.list_segments()
491 .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))
492 })
493 .map_err(|e| format!("reopen device: {e:?}"))?
494 .len()
495 }
496 None => count_files(dir, &|n| {
497 synapse_store::segment::parse_segment_file_name(n).is_some()
498 }),
499 };
500 let blob_files = count_files(&dir.join("blobs"), &|_| true);
501 Ok(CellRaw {
502 agents,
503 rep,
504 accepted: accepted.into_inner(),
505 elapsed_ns: elapsed.as_nanos() as u64,
506 latency_ns: latencies.into_inner().unwrap(),
507 checkpoint_ns: checkpoints.into_inner().unwrap(),
508 batches,
509 segment_files,
510 blob_files,
511 energy,
512 })
513}
514
515/// Run every cell (agents x reps, agent counts interleaved inside each repetition).
516pub fn run_segments(store_dir: &Path, cfg: &SegmentsConfig) -> Result<SegmentsRaw, String> {
517 let idle = idle_window(Duration::from_secs(cfg.idle_window_s));
518 let mut cells = Vec::new();
519 for rep in 0..cfg.reps {
520 for &agents in &cfg.agents {
521 let dir: PathBuf = store_dir.join(format!("cell-{agents}-{rep}"));
522 let cell = run_cell(&dir, cfg, agents, rep)?;
523 let _ = std::fs::remove_dir_all(&dir);
524 eprintln!(
525 "agents {agents} rep {rep}: {} accepted in {:.3} s, {} batches, {} segment files",
526 cell.accepted,
527 cell.elapsed_ns as f64 / 1e9,
528 cell.batches,
529 cell.segment_files
530 );
531 cells.push(cell);
532 }
533 }
534 Ok(SegmentsRaw {
535 config: cfg.clone(),
536 store_dir: store_dir.display().to_string(),
537 idle,
538 cells,
539 })
540}
541
542/// Report of a run: bound inputs and every cell's figures.
543#[derive(Debug, Clone, Serialize, Deserialize)]
544pub struct SegmentsReport {
545 pub bounds: BoundInputs,
546 pub cells: Vec<CellReport>,
547}
548
549/// Recompute the report from the raw run and the floor report.
550pub fn segments_report(raw: &SegmentsRaw, floor: &FloorReport) -> Result<SegmentsReport, String> {
551 let (flush_s, flush_probe) = flush_from_floor(floor)?;
552 let bounds = BoundInputs {
553 flush_s,
554 flush_probe,
555 blob_bytes: raw.config.blob_bytes,
556 memory_bw_bps: MEMORY_BW_BPS,
557 device_bw_bps: DEVICE_BW_BPS,
558 sha256_allcore_bps: SHA256_ALLCORE_BPS,
559 ed25519_allcore_per_s: ED25519_ALLCORE_PER_S,
560 idle_pkg_w: raw.idle.pkg_mean_w,
561 };
562 let cells = raw
563 .cells
564 .iter()
565 .map(|c| cell_report(c, &bounds, &raw.idle))
566 .collect();
567 Ok(SegmentsReport { bounds, cells })
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573
574 fn inputs() -> BoundInputs {
575 BoundInputs {
576 flush_s: 0.0008,
577 flush_probe: "overwrite_1m_fdatasync".into(),
578 blob_bytes: 11_949,
579 memory_bw_bps: MEMORY_BW_BPS,
580 device_bw_bps: DEVICE_BW_BPS,
581 sha256_allcore_bps: SHA256_ALLCORE_BPS,
582 ed25519_allcore_per_s: ED25519_ALLCORE_PER_S,
583 idle_pkg_w: Some(20.0),
584 }
585 }
586
587 /// B1 (review of PR #103): `--block-device` never writes to a file the bench did not
588 /// create itself, and never follows a symbolic link to one.
589 #[test]
590 fn block_device_bench_never_writes_to_a_file_it_did_not_create() {
591 let dir = crate::fixture::test_support::temp_dir("r1-bench-victim");
592 let victim = dir.join("victim.img");
593 let mut bytes: Vec<u8> = (0..4u32 << 20).map(|i| (i % 251) as u8).collect();
594 bytes[1080..1082].copy_from_slice(&[0x53, 0xEF]);
595 std::fs::write(&victim, &bytes).unwrap();
596 let link = dir.join("link.img");
597 std::os::unix::fs::symlink(&victim, &link).unwrap();
598 for target in [&victim, &link] {
599 let cfg = SegmentsConfig {
600 agents: vec![1],
601 changes: 4,
602 reps: 1,
603 blob_bytes: 64,
604 segment_bytes: 1 << 20,
605 checkpoint_every: 2,
606 idle_window_s: 0,
607 block_device: Some(target.display().to_string()),
608 block_device_bytes: 8 << 20,
609 block_meta_bytes: 1 << 20,
610 };
611 assert!(
612 run_cell(&dir.join("store"), &cfg, 1, 0).is_err(),
613 "{}",
614 target.display()
615 );
616 assert_eq!(
617 std::fs::read(&victim).unwrap(),
618 bytes,
619 "{}: victim changed",
620 target.display()
621 );
622 }
623 let _ = std::fs::remove_dir_all(&dir);
624 }
625
626 /// The bench creates its own device file for a cell, formats it, and removes it.
627 #[test]
628 fn block_device_bench_creates_formats_and_removes_its_own_device() {
629 let dir = crate::fixture::test_support::temp_dir("r1-bench-own");
630 let path = dir.join("device.img");
631 let cfg = SegmentsConfig {
632 agents: vec![2],
633 changes: 6,
634 reps: 1,
635 blob_bytes: 64,
636 segment_bytes: 1 << 20,
637 checkpoint_every: 3,
638 idle_window_s: 0,
639 block_device: Some(path.display().to_string()),
640 block_device_bytes: 8 << 20,
641 block_meta_bytes: 1 << 20,
642 };
643 let cell = run_cell(&dir.join("store"), &cfg, 2, 0).unwrap();
644 assert_eq!(cell.accepted, 6);
645 assert_eq!(cell.segment_files, 1);
646 assert!(
647 !path.exists(),
648 "the bench removes the device file it created"
649 );
650 let _ = std::fs::remove_dir_all(&dir);
651 }
652
653 #[test]
654 fn interval_bound_is_flush_shared_by_agents_until_crypto_dominates() {
655 let b = inputs();
656 assert_eq!(interval_bound_s(&b, 1), 0.0008);
657 assert_eq!(interval_bound_s(&b, 8), 0.0001);
658 // 1000 agents: the flush share (0.8 us) is below one change's crypto (2.82 us).
659 let crypto = 11_949.0 / SHA256_ALLCORE_BPS + 1.0 / ED25519_ALLCORE_PER_S;
660 assert_eq!(interval_bound_s(&b, 1000), crypto);
661 assert!(latency_bound_s(&b) > 0.0008);
662 }
663
664 #[test]
665 fn fractions_are_bound_over_measured_and_refused_energy_stays_none() {
666 let b = inputs();
667 let cell = CellRaw {
668 agents: 1,
669 rep: 0,
670 accepted: 4,
671 elapsed_ns: 8_000_000,
672 latency_ns: vec![1_600_000; 4],
673 checkpoint_ns: vec![],
674 batches: 4,
675 segment_files: 1,
676 blob_files: 0,
677 energy: EnergyReading {
678 refusal: Some("INSTRUMENT_UNAVAILABLE: no aien_spbm device".into()),
679 ..Default::default()
680 },
681 };
682 let r = cell_report(&cell, &b, &EnergyReading::default());
683 assert_eq!(r.interval_s, 0.002);
684 assert!((r.interval_fraction - 0.4).abs() < 1e-12);
685 assert!(r.pkg_j_per_change.is_none() && r.energy_fraction.is_none());
686 assert!(r
687 .energy_refusal
688 .unwrap()
689 .starts_with("INSTRUMENT_UNAVAILABLE"));
690 }
691}