synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / floor.rs
| 1 | //! Speed-of-light probe: what the storage stack and the CPU on this host can do at |
| 2 | //! best, measured with the same filesystem the store uses. Every probe is bounded |
| 3 | //! (a few seconds at most) and writes only inside the given directory. |
| 4 | //! |
| 5 | //! Storage probes time the syscalls a durable commit needs (append plus `fsync`, |
| 6 | //! append plus `fdatasync`, overwrite of already written blocks plus `fdatasync`, |
| 7 | //! `O_DIRECT | O_DSYNC` overwrite, one blob file with `fsync`, rename and directory |
| 8 | //! `fsync`), the same with 32 threads at once, and sequential bandwidth. CPU probes |
| 9 | //! time SHA-256, Ed25519, JSON, CRC-32C, and envelope validation on a typical |
| 10 | //! proposal. Energy comes from [`crate::energy`] (SoC package only; UNMEASURED when |
| 11 | //! the sensor is absent). |
| 12 | |
| 13 | use crate::energy::{EnergyReading, EnergyWindow, Spbm}; |
| 14 | use crate::stats::{round3, summarize_us, LatencySummary}; |
| 15 | use ed25519_dalek::{Signer, SigningKey, Verifier}; |
| 16 | use serde::{Deserialize, Serialize}; |
| 17 | use sha2::{Digest, Sha256}; |
| 18 | use std::fs::{self, File, OpenOptions}; |
| 19 | use std::io::Write; |
| 20 | use std::os::unix::fs::{FileExt, OpenOptionsExt}; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | use std::sync::Barrier; |
| 23 | use std::time::{Duration, Instant}; |
| 24 | use synapse_api::SubmitChangesetPayload; |
| 25 | use synapse_auth::{AgentCapabilityGrant, AuthenticatedRequest, Capability}; |
| 26 | use synapse_core::{ |
| 27 | encode_did_key_ed25519, BlobDigest, ChangesetEnvelope, FileMode, GitOid, IdempotencyKey, |
| 28 | MutationOp, PathMutation, RepoId, SYNAPSE_ENVELOPE_VERSION, |
| 29 | }; |
| 30 | |
| 31 | /// Typical content bytes per proposal (Gate 4: 11,949 apparent bytes stored per proposal). |
| 32 | pub const TYPICAL_CONTENT_BYTES: usize = 12_000; |
| 33 | |
| 34 | /// Target length of each CPU probe window (the energy counter updates every 0.1 s). |
| 35 | pub const CPU_PROBE_SECONDS: f64 = 3.0; |
| 36 | |
| 37 | /// One timed probe. |
| 38 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 39 | pub struct Probe { |
| 40 | pub name: String, |
| 41 | pub description: String, |
| 42 | pub n: usize, |
| 43 | /// Per-operation latency (milliseconds in the summary fields). |
| 44 | pub latency: Option<LatencySummary>, |
| 45 | pub energy: EnergyReading, |
| 46 | /// SoC package joules per operation over the whole window (includes idle draw). |
| 47 | pub pkg_j_per_op: Option<f64>, |
| 48 | /// SoC package joules per operation above the idle baseline power. |
| 49 | pub pkg_j_per_op_above_idle: Option<f64>, |
| 50 | pub error: Option<String>, |
| 51 | } |
| 52 | |
| 53 | /// Sequential write bandwidth (supporting data). |
| 54 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 55 | pub struct Bandwidth { |
| 56 | pub name: String, |
| 57 | pub bytes: u64, |
| 58 | pub seconds: f64, |
| 59 | pub seconds_per_gib: f64, |
| 60 | pub error: Option<String>, |
| 61 | } |
| 62 | |
| 63 | /// How often the energy counter changes value. |
| 64 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 65 | pub struct CounterCadence { |
| 66 | pub reads: usize, |
| 67 | pub changes: usize, |
| 68 | pub median_gap_ms: Option<f64>, |
| 69 | pub min_gap_ms: Option<f64>, |
| 70 | pub max_gap_ms: Option<f64>, |
| 71 | } |
| 72 | |
| 73 | /// Full floor report. |
| 74 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 75 | pub struct FloorReport { |
| 76 | pub dir: String, |
| 77 | pub iterations: usize, |
| 78 | pub idle: EnergyReading, |
| 79 | pub counter_cadence: Option<CounterCadence>, |
| 80 | pub storage: Vec<Probe>, |
| 81 | pub bandwidth: Vec<Bandwidth>, |
| 82 | pub cpu: Vec<Probe>, |
| 83 | pub typical_request_json_bytes: usize, |
| 84 | } |
| 85 | |
| 86 | struct AlignedBuf { |
| 87 | ptr: *mut u8, |
| 88 | layout: std::alloc::Layout, |
| 89 | } |
| 90 | |
| 91 | impl AlignedBuf { |
| 92 | fn new(len: usize, fill: u8) -> Self { |
| 93 | let layout = std::alloc::Layout::from_size_align(len, 4096).expect("layout"); |
| 94 | // SAFETY: layout has non-zero size; the pointer is checked and freed in Drop. |
| 95 | let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; |
| 96 | assert!(!ptr.is_null(), "aligned allocation failed"); |
| 97 | // SAFETY: `ptr` is valid for `len` bytes. |
| 98 | unsafe { std::ptr::write_bytes(ptr, fill, len) }; |
| 99 | Self { ptr, layout } |
| 100 | } |
| 101 | fn as_slice(&self) -> &[u8] { |
| 102 | // SAFETY: `ptr` is valid for `layout.size()` initialized bytes. |
| 103 | unsafe { std::slice::from_raw_parts(self.ptr, self.layout.size()) } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | impl Drop for AlignedBuf { |
| 108 | fn drop(&mut self) { |
| 109 | // SAFETY: allocated with the same layout in `new`. |
| 110 | unsafe { std::alloc::dealloc(self.ptr, self.layout) }; |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | fn io<T>(r: std::io::Result<T>, what: &str) -> Result<T, String> { |
| 115 | r.map_err(|e| format!("{what}: {e}")) |
| 116 | } |
| 117 | |
| 118 | fn finish_probe( |
| 119 | name: &str, |
| 120 | description: &str, |
| 121 | samples: Result<Vec<u64>, String>, |
| 122 | energy: EnergyReading, |
| 123 | idle: &EnergyReading, |
| 124 | ) -> Probe { |
| 125 | let (latency, n, error) = match samples { |
| 126 | Ok(s) => (summarize_us(&s), s.len(), None), |
| 127 | Err(e) => (None, 0, Some(e)), |
| 128 | }; |
| 129 | let per_op = |j: Option<f64>| j.filter(|_| n > 0).map(|j| j / n as f64); |
| 130 | let above = energy |
| 131 | .pkg_above_idle_j(idle) |
| 132 | .filter(|_| n > 0) |
| 133 | .map(|j| j / n as f64); |
| 134 | Probe { |
| 135 | name: name.into(), |
| 136 | description: description.into(), |
| 137 | n, |
| 138 | latency, |
| 139 | pkg_j_per_op: per_op(energy.pkg_j), |
| 140 | pkg_j_per_op_above_idle: above, |
| 141 | energy, |
| 142 | error, |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn timed_loop( |
| 147 | n: usize, |
| 148 | mut op: impl FnMut(usize) -> Result<(), String>, |
| 149 | ) -> (Result<Vec<u64>, String>, EnergyReading) { |
| 150 | let w = EnergyWindow::start(); |
| 151 | let mut out = Vec::with_capacity(n); |
| 152 | let mut err = None; |
| 153 | for i in 0..n { |
| 154 | let t = Instant::now(); |
| 155 | if let Err(e) = op(i) { |
| 156 | err = Some(e); |
| 157 | break; |
| 158 | } |
| 159 | out.push(t.elapsed().as_nanos() as u64 / 1000); |
| 160 | } |
| 161 | let e = w.finish(); |
| 162 | (err.map_or(Ok(out), Err), e) |
| 163 | } |
| 164 | |
| 165 | fn storage_probes(dir: &Path, n: usize, idle: &EnergyReading) -> Vec<Probe> { |
| 166 | let mut probes = Vec::new(); |
| 167 | let block = vec![0x5au8; 4096]; |
| 168 | |
| 169 | // 1 and 2: append 4 KiB, then fsync or fdatasync. |
| 170 | for (name, data_only) in [("append_4k_fsync", false), ("append_4k_fdatasync", true)] { |
| 171 | let path = dir.join(format!("{name}.dat")); |
| 172 | let res = (|| { |
| 173 | let mut f = io( |
| 174 | OpenOptions::new().create(true).append(true).open(&path), |
| 175 | "open", |
| 176 | )?; |
| 177 | Ok(timed_loop(n, |_| { |
| 178 | io(f.write_all(&block), "write")?; |
| 179 | if data_only { |
| 180 | io(f.sync_data(), "fdatasync") |
| 181 | } else { |
| 182 | io(f.sync_all(), "fsync") |
| 183 | } |
| 184 | })) |
| 185 | })(); |
| 186 | let desc = if data_only { |
| 187 | "append 4 KiB to a growing file, then fdatasync (size change needs a journal commit)" |
| 188 | } else { |
| 189 | "append 4 KiB to a growing file, then fsync (today's WAL pattern per frame)" |
| 190 | }; |
| 191 | probes.push(match res { |
| 192 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 193 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 194 | }); |
| 195 | let _ = fs::remove_file(&path); |
| 196 | } |
| 197 | |
| 198 | // 3 and 4: overwrite blocks that were already written and synced. |
| 199 | let pre = dir.join("prewritten.dat"); |
| 200 | let prewrite = (|| { |
| 201 | let mut f = io(File::create(&pre), "create prewritten")?; |
| 202 | let chunk = vec![0u8; 1 << 20]; |
| 203 | let total = (n * 4096).div_ceil(1 << 20) + 1; |
| 204 | for _ in 0..total { |
| 205 | io(f.write_all(&chunk), "prewrite")?; |
| 206 | } |
| 207 | io(f.sync_all(), "prewrite fsync") |
| 208 | })(); |
| 209 | let name = "overwrite_4k_fdatasync"; |
| 210 | let desc = "overwrite 4 KiB inside an already written, synced file, then fdatasync (no metadata change)"; |
| 211 | probes.push( |
| 212 | match prewrite.clone().and_then(|_| { |
| 213 | let f = io(OpenOptions::new().write(true).open(&pre), "open")?; |
| 214 | Ok(timed_loop(n, |i| { |
| 215 | io(f.write_at(&block, (i * 4096) as u64), "pwrite")?; |
| 216 | io(f.sync_data(), "fdatasync") |
| 217 | })) |
| 218 | }) { |
| 219 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 220 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 221 | }, |
| 222 | ); |
| 223 | let name = "odirect_dsync_4k_overwrite"; |
| 224 | let desc = "O_DIRECT | O_DSYNC 4 KiB overwrite inside an already written file (device write with FUA or flush)"; |
| 225 | let abuf = AlignedBuf::new(4096, 0xa5); |
| 226 | probes.push( |
| 227 | match prewrite.and_then(|_| { |
| 228 | let f = io( |
| 229 | OpenOptions::new() |
| 230 | .write(true) |
| 231 | .custom_flags(libc::O_DIRECT | libc::O_DSYNC) |
| 232 | .open(&pre), |
| 233 | "open O_DIRECT", |
| 234 | )?; |
| 235 | Ok(timed_loop(n, |i| { |
| 236 | io( |
| 237 | f.write_at(abuf.as_slice(), (i * 4096) as u64), |
| 238 | "pwrite O_DIRECT", |
| 239 | ) |
| 240 | .map(|_| ()) |
| 241 | })) |
| 242 | }) { |
| 243 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 244 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 245 | }, |
| 246 | ); |
| 247 | let _ = fs::remove_file(&pre); |
| 248 | |
| 249 | // Batch-size dependence when writing into already written space (64 MiB pre-written). |
| 250 | let pre = dir.join("prewritten64.dat"); |
| 251 | let prewrite = (|| { |
| 252 | let mut f = io(File::create(&pre), "create prewritten")?; |
| 253 | let chunk = vec![0u8; 1 << 20]; |
| 254 | for _ in 0..64 { |
| 255 | io(f.write_all(&chunk), "prewrite")?; |
| 256 | } |
| 257 | io(f.sync_all(), "prewrite fsync") |
| 258 | })(); |
| 259 | for (name, size) in [ |
| 260 | ("overwrite_64k_fdatasync", 64usize << 10), |
| 261 | ("overwrite_1m_fdatasync", 1 << 20), |
| 262 | ] { |
| 263 | let desc = format!( |
| 264 | "overwrite {} KiB inside an already written, synced file, then fdatasync", |
| 265 | size >> 10 |
| 266 | ); |
| 267 | let buf = vec![0x6du8; size]; |
| 268 | let slots = (64usize << 20) / size; |
| 269 | probes.push( |
| 270 | match prewrite.clone().and_then(|_| { |
| 271 | let f = io(OpenOptions::new().write(true).open(&pre), "open")?; |
| 272 | Ok(timed_loop(n / 3, |i| { |
| 273 | io(f.write_at(&buf, ((i % slots) * size) as u64), "pwrite")?; |
| 274 | io(f.sync_data(), "fdatasync") |
| 275 | })) |
| 276 | }) { |
| 277 | Ok((s, e)) => finish_probe(name, &desc, s, e, idle), |
| 278 | Err(e) => finish_probe(name, &desc, Err(e), EnergyReading::default(), idle), |
| 279 | }, |
| 280 | ); |
| 281 | } |
| 282 | let _ = fs::remove_file(&pre); |
| 283 | |
| 284 | // fallocate leaves unwritten extents: does the first write into them cost a journal commit? |
| 285 | let name = "fallocate_4k_overwrite_fdatasync"; |
| 286 | let desc = "write 4 KiB into fallocate()d (unwritten) space, then fdatasync"; |
| 287 | let fpath = dir.join("fallocated.dat"); |
| 288 | probes.push( |
| 289 | match (|| { |
| 290 | let f = io( |
| 291 | OpenOptions::new() |
| 292 | .create(true) |
| 293 | .truncate(true) |
| 294 | .read(true) |
| 295 | .write(true) |
| 296 | .open(&fpath), |
| 297 | "create", |
| 298 | )?; |
| 299 | let len = (n * 4096) as libc::off_t; |
| 300 | // SAFETY: valid fd from `f`; mode 0 allocates blocks and extends the size. |
| 301 | let rc = unsafe { libc::fallocate(std::os::fd::AsRawFd::as_raw_fd(&f), 0, 0, len) }; |
| 302 | if rc != 0 { |
| 303 | return Err(format!("fallocate: {}", std::io::Error::last_os_error())); |
| 304 | } |
| 305 | io(f.sync_all(), "fsync after fallocate")?; |
| 306 | Ok(timed_loop(n, |i| { |
| 307 | io(f.write_at(&block, (i * 4096) as u64), "pwrite")?; |
| 308 | io(f.sync_data(), "fdatasync") |
| 309 | })) |
| 310 | })() { |
| 311 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 312 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 313 | }, |
| 314 | ); |
| 315 | let _ = fs::remove_file(&fpath); |
| 316 | |
| 317 | // Cost of pre-writing WAL space (zeros, then fsync), per 64 MiB chunk. |
| 318 | let name = "prewrite_64m_zeros_fsync"; |
| 319 | let desc = "extend a file by 64 MiB of zeros, then fsync (WAL segment pre-writing, amortized)"; |
| 320 | let zpath = dir.join("zeros.dat"); |
| 321 | let zeros = vec![0u8; 1 << 20]; |
| 322 | probes.push( |
| 323 | match (|| { |
| 324 | let mut f = io( |
| 325 | OpenOptions::new().create(true).append(true).open(&zpath), |
| 326 | "open", |
| 327 | )?; |
| 328 | Ok(timed_loop(5, |_| { |
| 329 | for _ in 0..64 { |
| 330 | io(f.write_all(&zeros), "write zeros")?; |
| 331 | } |
| 332 | io(f.sync_all(), "fsync") |
| 333 | })) |
| 334 | })() { |
| 335 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 336 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 337 | }, |
| 338 | ); |
| 339 | let _ = fs::remove_file(&zpath); |
| 340 | |
| 341 | // 5: size dependency of one append plus fdatasync. |
| 342 | for (name, size) in [ |
| 343 | ("append_64k_fdatasync", 64 << 10), |
| 344 | ("append_1m_fdatasync", 1 << 20), |
| 345 | ] { |
| 346 | let path = dir.join(format!("{name}.dat")); |
| 347 | let buf = vec![0x3cu8; size]; |
| 348 | let desc = format!("append {} KiB, then fdatasync", size >> 10); |
| 349 | let res = (|| { |
| 350 | let mut f = io( |
| 351 | OpenOptions::new().create(true).append(true).open(&path), |
| 352 | "open", |
| 353 | )?; |
| 354 | Ok(timed_loop(n / 3, |_| { |
| 355 | io(f.write_all(&buf), "write")?; |
| 356 | io(f.sync_data(), "fdatasync") |
| 357 | })) |
| 358 | })(); |
| 359 | probes.push(match res { |
| 360 | Ok((s, e)) => finish_probe(name, &desc, s, e, idle), |
| 361 | Err(e) => finish_probe(name, &desc, Err(e), EnergyReading::default(), idle), |
| 362 | }); |
| 363 | let _ = fs::remove_file(&path); |
| 364 | } |
| 365 | |
| 366 | // 6: today's per-blob durable path. |
| 367 | let blobs = dir.join("blobs"); |
| 368 | let content = vec![0x77u8; TYPICAL_CONTENT_BYTES]; |
| 369 | let name = "blob_file_create_fsync_rename_dirfsync_12k"; |
| 370 | let desc = "new 12 KB blob file: create tmp, write, fsync, rename, fsync shard directory (today's write_blob_file)"; |
| 371 | let res = (|| { |
| 372 | for s in 0..16 { |
| 373 | io( |
| 374 | fs::create_dir_all(blobs.join(format!("{s:02x}"))), |
| 375 | "mkdir shard", |
| 376 | )?; |
| 377 | } |
| 378 | Ok(timed_loop(n, |i| { |
| 379 | let shard = blobs.join(format!("{:02x}", i % 16)); |
| 380 | let tmp = shard.join(format!("b{i}.tmp")); |
| 381 | let mut f = io(File::create(&tmp), "create")?; |
| 382 | io(f.write_all(&content), "write")?; |
| 383 | io(f.sync_all(), "fsync")?; |
| 384 | drop(f); |
| 385 | io(fs::rename(&tmp, shard.join(format!("b{i}"))), "rename")?; |
| 386 | io(File::open(&shard).and_then(|d| d.sync_all()), "dir fsync") |
| 387 | })) |
| 388 | })(); |
| 389 | probes.push(match res { |
| 390 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 391 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 392 | }); |
| 393 | let _ = fs::remove_dir_all(&blobs); |
| 394 | |
| 395 | // 7: 32 threads at once, each with its own file (does the kernel merge syncs?). |
| 396 | for (name, blob_pattern) in [ |
| 397 | ("concurrent_32_append_4k_fdatasync_round", false), |
| 398 | ("concurrent_32_blob_file_create_round", true), |
| 399 | ] { |
| 400 | let threads = 32usize; |
| 401 | let rounds = (n / 10).max(10); |
| 402 | let root = dir.join(name); |
| 403 | let desc = if blob_pattern { |
| 404 | "32 threads each create one 12 KB blob file with fsync, rename, directory fsync; time per round (all 32 done)" |
| 405 | } else { |
| 406 | "32 threads each append 4 KiB to their own file and fdatasync; time per round (all 32 done)" |
| 407 | }; |
| 408 | let res = (|| -> Result<(Result<Vec<u64>, String>, EnergyReading), String> { |
| 409 | io(fs::create_dir_all(&root), "mkdir")?; |
| 410 | let start = Barrier::new(threads + 1); |
| 411 | let end = Barrier::new(threads + 1); |
| 412 | let w = EnergyWindow::start(); |
| 413 | let mut samples = Vec::with_capacity(rounds); |
| 414 | let errs: Vec<String> = std::thread::scope(|s| { |
| 415 | let handles: Vec<_> = (0..threads) |
| 416 | .map(|t| { |
| 417 | let (start, end, root, block, content) = |
| 418 | (&start, &end, &root, &block, &content); |
| 419 | s.spawn(move || -> Result<(), String> { |
| 420 | let shard = root.join(format!("{:02x}", t % 16)); |
| 421 | io(fs::create_dir_all(&shard), "mkdir")?; |
| 422 | let mut log = io( |
| 423 | OpenOptions::new() |
| 424 | .create(true) |
| 425 | .append(true) |
| 426 | .open(root.join(format!("t{t}.log"))), |
| 427 | "open", |
| 428 | )?; |
| 429 | let mut first_err = None; |
| 430 | for r in 0..rounds { |
| 431 | start.wait(); |
| 432 | let res = if blob_pattern { |
| 433 | (|| { |
| 434 | let tmp = shard.join(format!("t{t}r{r}.tmp")); |
| 435 | let mut f = io(File::create(&tmp), "create")?; |
| 436 | io(f.write_all(content), "write")?; |
| 437 | io(f.sync_all(), "fsync")?; |
| 438 | drop(f); |
| 439 | io( |
| 440 | fs::rename(&tmp, shard.join(format!("t{t}r{r}"))), |
| 441 | "rename", |
| 442 | )?; |
| 443 | io( |
| 444 | File::open(&shard).and_then(|d| d.sync_all()), |
| 445 | "dir fsync", |
| 446 | ) |
| 447 | })() |
| 448 | } else { |
| 449 | io(log.write_all(block), "write") |
| 450 | .and_then(|_| io(log.sync_data(), "fdatasync")) |
| 451 | }; |
| 452 | if let (Err(e), None) = (res, &first_err) { |
| 453 | first_err = Some(e); |
| 454 | } |
| 455 | end.wait(); |
| 456 | } |
| 457 | first_err.map_or(Ok(()), Err) |
| 458 | }) |
| 459 | }) |
| 460 | .collect(); |
| 461 | for _ in 0..rounds { |
| 462 | start.wait(); |
| 463 | let t = Instant::now(); |
| 464 | end.wait(); |
| 465 | samples.push(t.elapsed().as_nanos() as u64 / 1000); |
| 466 | } |
| 467 | handles |
| 468 | .into_iter() |
| 469 | .filter_map(|h| h.join().ok().and_then(|r| r.err())) |
| 470 | .collect() |
| 471 | }); |
| 472 | let e = w.finish(); |
| 473 | Ok((errs.into_iter().next().map_or(Ok(samples), Err), e)) |
| 474 | })(); |
| 475 | probes.push(match res { |
| 476 | Ok((s, e)) => finish_probe(name, desc, s, e, idle), |
| 477 | Err(e) => finish_probe(name, desc, Err(e), EnergyReading::default(), idle), |
| 478 | }); |
| 479 | let _ = fs::remove_dir_all(&root); |
| 480 | } |
| 481 | probes |
| 482 | } |
| 483 | |
| 484 | fn bandwidth_probes(dir: &Path) -> Vec<Bandwidth> { |
| 485 | const TOTAL: usize = 256 << 20; |
| 486 | const CHUNK: usize = 1 << 20; |
| 487 | let mut out = Vec::new(); |
| 488 | let path = dir.join("bandwidth.dat"); |
| 489 | let buffered = (|| { |
| 490 | let mut f = io(File::create(&path), "create")?; |
| 491 | let buf = vec![0x11u8; CHUNK]; |
| 492 | let t = Instant::now(); |
| 493 | for _ in 0..TOTAL / CHUNK { |
| 494 | io(f.write_all(&buf), "write")?; |
| 495 | } |
| 496 | io(f.sync_all(), "fsync")?; |
| 497 | Ok(t.elapsed().as_secs_f64()) |
| 498 | })(); |
| 499 | let _ = fs::remove_file(&path); |
| 500 | let direct = (|| { |
| 501 | let f = io( |
| 502 | OpenOptions::new() |
| 503 | .create(true) |
| 504 | .write(true) |
| 505 | .truncate(true) |
| 506 | .custom_flags(libc::O_DIRECT) |
| 507 | .open(&path), |
| 508 | "open O_DIRECT", |
| 509 | )?; |
| 510 | let buf = AlignedBuf::new(CHUNK, 0x22); |
| 511 | let t = Instant::now(); |
| 512 | for i in 0..TOTAL / CHUNK { |
| 513 | io(f.write_at(buf.as_slice(), (i * CHUNK) as u64), "pwrite")?; |
| 514 | } |
| 515 | io(f.sync_all(), "fsync")?; |
| 516 | Ok(t.elapsed().as_secs_f64()) |
| 517 | })(); |
| 518 | let _ = fs::remove_file(&path); |
| 519 | for (name, r) in [ |
| 520 | ("sequential_buffered_1m_writes_then_fsync", buffered), |
| 521 | ("sequential_odirect_1m_writes_then_fsync", direct), |
| 522 | ] { |
| 523 | let (seconds, error) = match r { |
| 524 | Ok(s) => (s, None), |
| 525 | Err(e) => (0.0, Some(e)), |
| 526 | }; |
| 527 | out.push(Bandwidth { |
| 528 | name: name.into(), |
| 529 | bytes: TOTAL as u64, |
| 530 | seconds: round3(seconds * 1000.0) / 1000.0, |
| 531 | seconds_per_gib: if seconds > 0.0 { |
| 532 | seconds * (1u64 << 30) as f64 / TOTAL as f64 |
| 533 | } else { |
| 534 | 0.0 |
| 535 | }, |
| 536 | error, |
| 537 | }); |
| 538 | } |
| 539 | out |
| 540 | } |
| 541 | |
| 542 | /// A typical signed submit request (two upserted files, 12 KB of content). |
| 543 | pub fn typical_request() -> AuthenticatedRequest<SubmitChangesetPayload> { |
| 544 | let authority = SigningKey::from_bytes(&[3u8; 32]); |
| 545 | let agent = SigningKey::from_bytes(&[4u8; 32]); |
| 546 | let agent_did = encode_did_key_ed25519(&agent.verifying_key().to_bytes()); |
| 547 | let repo = RepoId::new("aien-spark/aien-sovereign-core").expect("repo id"); |
| 548 | let grant = AgentCapabilityGrant::issue( |
| 549 | &authority, |
| 550 | [9u8; 32], |
| 551 | repo.clone(), |
| 552 | agent_did.clone(), |
| 553 | vec![Capability::Read, Capability::Propose], |
| 554 | 1 << 30, |
| 555 | u32::MAX, |
| 556 | 60_000, |
| 557 | 0, |
| 558 | u64::MAX / 2, |
| 559 | ); |
| 560 | let mut blobs = Vec::new(); |
| 561 | let mut mutations = Vec::new(); |
| 562 | for (i, path) in ["src/a.rs", "src/b.rs"].iter().enumerate() { |
| 563 | let content: Vec<u8> = (0..TYPICAL_CONTENT_BYTES / 2) |
| 564 | .map(|j| b"pub fn x() {}\n"[(j + i) % 14]) |
| 565 | .collect(); |
| 566 | let digest = BlobDigest::compute(&content); |
| 567 | mutations.push(PathMutation { |
| 568 | path: path.to_string(), |
| 569 | op: MutationOp::Upsert { |
| 570 | mode: FileMode::Regular644, |
| 571 | blob_digest: digest, |
| 572 | size_bytes: content.len() as u64, |
| 573 | }, |
| 574 | }); |
| 575 | blobs.push((digest, content)); |
| 576 | } |
| 577 | let mut envelope = ChangesetEnvelope { |
| 578 | version: SYNAPSE_ENVELOPE_VERSION, |
| 579 | repo_id: repo.clone(), |
| 580 | base_git_oid: GitOid::compute_blob(b"base"), |
| 581 | parent_changesets: vec![], |
| 582 | author_did: agent_did, |
| 583 | idempotency_key: IdempotencyKey::from_label("floor"), |
| 584 | created_at_ms: 1, |
| 585 | intent_summary: "floor probe".into(), |
| 586 | mutations, |
| 587 | evidence_receipts: vec![], |
| 588 | signature: vec![], |
| 589 | }; |
| 590 | envelope.sign(&agent); |
| 591 | AuthenticatedRequest::sign_new( |
| 592 | &agent, |
| 593 | grant, |
| 594 | repo, |
| 595 | Capability::Propose, |
| 596 | [7u8; 32], |
| 597 | 1, |
| 598 | 0, |
| 599 | SubmitChangesetPayload { envelope, blobs }, |
| 600 | ) |
| 601 | .expect("sign request") |
| 602 | } |
| 603 | |
| 604 | fn cpu_probes(n: usize, idle: &EnergyReading) -> (Vec<Probe>, usize) { |
| 605 | let mut probes = Vec::new(); |
| 606 | let req = typical_request(); |
| 607 | let wire = serde_json::to_vec(&req).expect("encode"); |
| 608 | let wire_len = wire.len(); |
| 609 | let payload_buf = vec![0x42u8; wire_len]; |
| 610 | let key = SigningKey::from_bytes(&[5u8; 32]); |
| 611 | let msg = vec![0x10u8; 256]; |
| 612 | let sig = key.sign(&msg); |
| 613 | let vk = key.verifying_key(); |
| 614 | |
| 615 | // Each CPU probe runs for about CPU_PROBE_SECONDS so the 0.1 s energy counter |
| 616 | // resolves it; `iters` only sizes the calibration pass. |
| 617 | let mut push = |name: &str, desc: &str, iters: usize, f: &mut dyn FnMut()| { |
| 618 | let calib = Instant::now(); |
| 619 | for _ in 0..iters.clamp(10, 200) { |
| 620 | f(); |
| 621 | } |
| 622 | let per = calib.elapsed().as_secs_f64() / iters.clamp(10, 200) as f64; |
| 623 | let n = ((CPU_PROBE_SECONDS / per.max(1e-9)) as usize).clamp(iters, 5_000_000); |
| 624 | let (s, e) = timed_loop(n, |_| { |
| 625 | f(); |
| 626 | Ok(()) |
| 627 | }); |
| 628 | probes.push(finish_probe(name, desc, s, e, idle)); |
| 629 | }; |
| 630 | push( |
| 631 | "sha256_request_sized", |
| 632 | "SHA-256 over a buffer the size of a typical JSON submit request", |
| 633 | n, |
| 634 | &mut || { |
| 635 | std::hint::black_box(Sha256::digest(std::hint::black_box(&payload_buf))); |
| 636 | }, |
| 637 | ); |
| 638 | push( |
| 639 | "sha256_content_12k", |
| 640 | "SHA-256 over 12 KB (typical content per proposal)", |
| 641 | n, |
| 642 | &mut || { |
| 643 | std::hint::black_box(Sha256::digest(std::hint::black_box( |
| 644 | &payload_buf[..TYPICAL_CONTENT_BYTES], |
| 645 | ))); |
| 646 | }, |
| 647 | ); |
| 648 | push( |
| 649 | "ed25519_verify", |
| 650 | "one Ed25519 signature verification (256-byte message)", |
| 651 | n, |
| 652 | &mut || { |
| 653 | std::hint::black_box(vk.verify(std::hint::black_box(&msg), &sig).is_ok()); |
| 654 | }, |
| 655 | ); |
| 656 | push( |
| 657 | "ed25519_sign", |
| 658 | "one Ed25519 signature (256-byte message)", |
| 659 | n, |
| 660 | &mut || { |
| 661 | std::hint::black_box(key.sign(std::hint::black_box(&msg))); |
| 662 | }, |
| 663 | ); |
| 664 | push( |
| 665 | "json_encode_submit_request", |
| 666 | "serde_json encode of a typical signed submit request", |
| 667 | n, |
| 668 | &mut || { |
| 669 | std::hint::black_box(serde_json::to_vec(std::hint::black_box(&req)).ok()); |
| 670 | }, |
| 671 | ); |
| 672 | push( |
| 673 | "json_decode_submit_request", |
| 674 | "serde_json decode of a typical signed submit request", |
| 675 | n, |
| 676 | &mut || { |
| 677 | let r: Option<AuthenticatedRequest<SubmitChangesetPayload>> = |
| 678 | serde_json::from_slice(std::hint::black_box(&wire)).ok(); |
| 679 | std::hint::black_box(r); |
| 680 | }, |
| 681 | ); |
| 682 | push( |
| 683 | "auth_payload_digest", |
| 684 | "synapse-auth payload digest as authorize computes it: compact JSON streamed into SHA-256 (synapse_auth::payload_digest)", |
| 685 | n, |
| 686 | &mut || { |
| 687 | std::hint::black_box( |
| 688 | synapse_auth::payload_digest(std::hint::black_box(&req.payload)).ok(), |
| 689 | ); |
| 690 | }, |
| 691 | ); |
| 692 | push( |
| 693 | "envelope_validate", |
| 694 | "ChangesetEnvelope::validate (canonical bytes, path rules, Ed25519 verify, id digest)", |
| 695 | n, |
| 696 | &mut || { |
| 697 | std::hint::black_box(req.payload.envelope.validate().ok()); |
| 698 | }, |
| 699 | ); |
| 700 | push( |
| 701 | "blob_digest_12k", |
| 702 | "BlobDigest::compute over 12 KB of content", |
| 703 | n, |
| 704 | &mut || { |
| 705 | std::hint::black_box(BlobDigest::compute(std::hint::black_box( |
| 706 | &payload_buf[..TYPICAL_CONTENT_BYTES], |
| 707 | ))); |
| 708 | }, |
| 709 | ); |
| 710 | push( |
| 711 | "crc32c_request_sized", |
| 712 | "synapse_store::crc32c over a request-sized buffer", |
| 713 | (n / 10).max(10), |
| 714 | &mut || { |
| 715 | std::hint::black_box(synapse_store::crc32c(std::hint::black_box(&payload_buf))); |
| 716 | }, |
| 717 | ); |
| 718 | (probes, wire_len) |
| 719 | } |
| 720 | |
| 721 | fn counter_cadence() -> Option<CounterCadence> { |
| 722 | let s = Spbm::find()?; |
| 723 | let start = Instant::now(); |
| 724 | let mut last = s.energy_uj("pkg")?; |
| 725 | let mut last_change = Instant::now(); |
| 726 | let mut gaps = Vec::new(); |
| 727 | let mut reads = 0usize; |
| 728 | while start.elapsed() < Duration::from_secs(1) { |
| 729 | let v = s.energy_uj("pkg")?; |
| 730 | reads += 1; |
| 731 | if v != last { |
| 732 | gaps.push(last_change.elapsed().as_micros() as u64); |
| 733 | last_change = Instant::now(); |
| 734 | last = v; |
| 735 | } |
| 736 | } |
| 737 | let changes = gaps.len(); |
| 738 | // The first gap starts at an arbitrary phase; drop it. |
| 739 | let gaps: Vec<u64> = gaps.into_iter().skip(1).collect(); |
| 740 | let sum = summarize_us(&gaps); |
| 741 | Some(CounterCadence { |
| 742 | reads, |
| 743 | changes, |
| 744 | median_gap_ms: sum.as_ref().map(|s| s.p50_ms), |
| 745 | min_gap_ms: sum.as_ref().map(|s| s.min_ms), |
| 746 | max_gap_ms: sum.as_ref().map(|s| s.max_ms), |
| 747 | }) |
| 748 | } |
| 749 | |
| 750 | /// Run every probe inside `dir` (created, then removed) and return the report. |
| 751 | pub fn run_floor(dir: &Path, iterations: usize) -> Result<FloorReport, String> { |
| 752 | let dir: PathBuf = dir.join(format!("synapse-floor-{}", std::process::id())); |
| 753 | fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?; |
| 754 | let idle = crate::energy::idle_window(Duration::from_secs(5)); |
| 755 | let counter_cadence = counter_cadence(); |
| 756 | let storage = storage_probes(&dir, iterations, &idle); |
| 757 | let bandwidth = bandwidth_probes(&dir); |
| 758 | let (cpu, typical_request_json_bytes) = cpu_probes(iterations * 4, &idle); |
| 759 | let _ = fs::remove_dir_all(&dir); |
| 760 | Ok(FloorReport { |
| 761 | dir: dir.display().to_string(), |
| 762 | iterations, |
| 763 | idle, |
| 764 | counter_cadence, |
| 765 | storage, |
| 766 | bandwidth, |
| 767 | cpu, |
| 768 | typical_request_json_bytes, |
| 769 | }) |
| 770 | } |