synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / write_phase.rs
| 1 | //! Write-phase measurement cell: `agents` concurrent agents each submit their proposals |
| 2 | //! through one arm, starting together on a `std::sync::Barrier`. |
| 3 | //! |
| 4 | //! Per-operation latency starts when the agent begins submitting an already generated |
| 5 | //! proposal and ends when the arm acknowledges it: |
| 6 | //! * Synapse arms: envelope and request signing, JSON encode, JSON decode, waiting for |
| 7 | //! the single-writer service lock (queue wait, also recorded separately), and `submit`. |
| 8 | //! S3 holds the service lock only for the API admission checks and the path-index |
| 9 | //! update; the store commit runs through `SharedStore::submit` (group commit) with no |
| 10 | //! service lock held. S3's queue wait is the time spent waiting for the service lock. |
| 11 | //! * Git arms: every file write and `git` process for that proposal. |
| 12 | //! |
| 13 | //! Throughput is acknowledged operations divided by the wall time from barrier release |
| 14 | //! to the last acknowledgement (for S2 this includes one final `sync_wal`). |
| 15 | //! |
| 16 | //! Every cell also records SoC package energy over the timed window |
| 17 | //! ([`crate::energy`]; CPU package only, uncalibrated, UNMEASURED when absent). |
| 18 | |
| 19 | use crate::energy::{EnergyReading, EnergyWindow}; |
| 20 | use crate::fixture::{self, BaseTree, EditableFile}; |
| 21 | use crate::git_arm::{self, PlumbingAgent, FSYNC_ALL_CONFIG}; |
| 22 | use crate::rusage::{CpuUsage, RusageWindow}; |
| 23 | use crate::stats::{round3, summarize_us, LatencySummary}; |
| 24 | use crate::synapse_arm::{self, AgentIdentity}; |
| 25 | use crate::workload::{generate_write_workload, Proposal}; |
| 26 | use crate::write_jsonl; |
| 27 | use serde::{Deserialize, Serialize}; |
| 28 | use std::path::PathBuf; |
| 29 | use std::sync::{Barrier, Mutex}; |
| 30 | use std::time::Instant; |
| 31 | use synapse_api::{SubmitChangesetPayload, SynapseService}; |
| 32 | use synapse_auth::AuthenticatedRequest; |
| 33 | use synapse_core::{GitOid, RepoId}; |
| 34 | use synapse_store::{ |
| 35 | DurabilityGuarantee, FsyncPolicy, GroupCommitStats, IngestOutcome, RecoveryPolicy, SharedStore, |
| 36 | StoreLimits, |
| 37 | }; |
| 38 | |
| 39 | /// Measured arm. |
| 40 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
| 41 | pub enum ArmKind { |
| 42 | S1, |
| 43 | S2, |
| 44 | S3, |
| 45 | G1, |
| 46 | G2, |
| 47 | G3, |
| 48 | G3F, |
| 49 | } |
| 50 | |
| 51 | impl ArmKind { |
| 52 | pub const ALL: [ArmKind; 7] = [ |
| 53 | ArmKind::S1, |
| 54 | ArmKind::S2, |
| 55 | ArmKind::S3, |
| 56 | ArmKind::G1, |
| 57 | ArmKind::G2, |
| 58 | ArmKind::G3, |
| 59 | ArmKind::G3F, |
| 60 | ]; |
| 61 | |
| 62 | pub fn code(self) -> &'static str { |
| 63 | match self { |
| 64 | Self::S1 => "S1", |
| 65 | Self::S2 => "S2", |
| 66 | Self::S3 => "S3", |
| 67 | Self::G1 => "G1", |
| 68 | Self::G2 => "G2", |
| 69 | Self::G3 => "G3", |
| 70 | Self::G3F => "G3F", |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | pub fn parse(s: &str) -> Option<Self> { |
| 75 | Self::ALL |
| 76 | .into_iter() |
| 77 | .find(|a| a.code().eq_ignore_ascii_case(s)) |
| 78 | } |
| 79 | |
| 80 | pub fn is_synapse(self) -> bool { |
| 81 | matches!(self, Self::S1 | Self::S2 | Self::S3) |
| 82 | } |
| 83 | |
| 84 | pub fn description(self) -> &'static str { |
| 85 | match self { |
| 86 | Self::S1 => "Synapse submit, FsyncPolicy::EveryCommit (blob files, shard dirs, and WAL fsynced before ack)", |
| 87 | Self::S2 => "Synapse submit, FsyncPolicy::BatchWindow (WAL fsync every N records, blobs never fsynced; final sync_wal inside timing)", |
| 88 | Self::S3 => "Synapse submit, FsyncPolicy::GroupCommit through SharedStore (WAL v2, blobs inline, one fdatasync per batch of concurrent submitters; service lock held only for admission and path indexing)", |
| 89 | Self::G1 => "Git: fresh `git worktree add -b` checkout per proposal, then add + commit (today's hive practice)", |
| 90 | Self::G2 => "Git: one persistent worktree per agent; `checkout -B` to base, edit, add, commit per proposal", |
| 91 | Self::G3 => "Git plumbing without checkout: per-agent temporary index, hash-object, update-index, write-tree, commit-tree, update-ref", |
| 92 | Self::G3F => "G3 with `-c core.fsync=all -c core.fsyncMethod=fsync` on every git command", |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | pub fn durability(self) -> &'static str { |
| 97 | match self { |
| 98 | Self::S1 => "fsync before ack (blobs, shard directories, WAL)", |
| 99 | Self::S2 => "process-crash durable only (page cache) between WAL syncs", |
| 100 | Self::S3 => "fsync before ack (one fdatasync per batch into pre-written WAL v2 space; blobs inside the batch)", |
| 101 | Self::G1 | Self::G2 | Self::G3 => { |
| 102 | "git default core.fsync (git-config(1): committed,-loose-object), loose objects and refs not fsynced" |
| 103 | } |
| 104 | Self::G3F => "core.fsync=all, core.fsyncMethod=fsync (objects, index, refs fsynced)", |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | /// Input for one write cell (serialized to the child process). |
| 110 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 111 | pub struct WriteCellSpec { |
| 112 | pub arm: ArmKind, |
| 113 | pub agents: usize, |
| 114 | pub ops_per_agent: usize, |
| 115 | pub rep: usize, |
| 116 | pub seed: u64, |
| 117 | pub clone_dir: PathBuf, |
| 118 | pub base_commit: String, |
| 119 | pub cell_dir: PathBuf, |
| 120 | pub trace_path: PathBuf, |
| 121 | pub batch_window_records: u32, |
| 122 | } |
| 123 | |
| 124 | /// One timed operation. |
| 125 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 126 | pub struct OpTrace { |
| 127 | pub arm: String, |
| 128 | pub agents: usize, |
| 129 | pub rep: usize, |
| 130 | pub agent: usize, |
| 131 | pub index: usize, |
| 132 | pub files: usize, |
| 133 | pub content_bytes: u64, |
| 134 | /// Start offset from barrier release, microseconds. |
| 135 | pub start_us: u64, |
| 136 | pub latency_us: u64, |
| 137 | /// Synapse only: time spent waiting for the single-writer service lock. |
| 138 | pub queue_wait_us: Option<u64>, |
| 139 | /// Synapse only: JSON-encoded request size. |
| 140 | pub wire_bytes: Option<u64>, |
| 141 | /// Synapse only: durability class reported in the commit receipt. |
| 142 | pub durability: Option<String>, |
| 143 | pub ok: bool, |
| 144 | pub error: Option<String>, |
| 145 | } |
| 146 | |
| 147 | /// Setup cost (excluded from per-operation latency). |
| 148 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 149 | pub struct SetupSummary { |
| 150 | pub description: String, |
| 151 | pub units: usize, |
| 152 | pub total_ms: f64, |
| 153 | pub per_unit: Option<LatencySummary>, |
| 154 | } |
| 155 | |
| 156 | /// `du` reading over the arm's directories. |
| 157 | #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)] |
| 158 | pub struct StorageSample { |
| 159 | pub apparent_bytes: u64, |
| 160 | pub allocated_bytes: u64, |
| 161 | } |
| 162 | |
| 163 | /// Storage growth attributable to the arm. |
| 164 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 165 | pub struct StorageDelta { |
| 166 | pub measured_paths: Vec<String>, |
| 167 | pub before_setup: StorageSample, |
| 168 | pub after_setup: StorageSample, |
| 169 | pub after_ops: StorageSample, |
| 170 | pub setup_apparent_bytes: i64, |
| 171 | pub ops_apparent_bytes: i64, |
| 172 | pub ops_allocated_bytes: i64, |
| 173 | pub total_apparent_bytes: i64, |
| 174 | pub total_allocated_bytes: i64, |
| 175 | pub ops_apparent_bytes_per_op: f64, |
| 176 | pub ops_allocated_bytes_per_op: f64, |
| 177 | } |
| 178 | |
| 179 | /// Result of one write cell. |
| 180 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 181 | pub struct WriteCellResult { |
| 182 | pub arm: ArmKind, |
| 183 | pub agents: usize, |
| 184 | pub ops_per_agent: usize, |
| 185 | pub rep: usize, |
| 186 | pub ops_attempted: usize, |
| 187 | pub ops_ok: usize, |
| 188 | pub ops_failed: usize, |
| 189 | pub wall_ms: f64, |
| 190 | pub throughput_ops_per_s: f64, |
| 191 | pub latency: Option<LatencySummary>, |
| 192 | pub queue_wait: Option<LatencySummary>, |
| 193 | pub mean_wire_bytes: Option<f64>, |
| 194 | pub mean_content_bytes: f64, |
| 195 | pub setup: SetupSummary, |
| 196 | pub final_sync_ms: Option<f64>, |
| 197 | pub cpu: CpuUsage, |
| 198 | pub cpu_ms_per_op: Option<f64>, |
| 199 | pub storage: StorageDelta, |
| 200 | pub durability_receipts: Vec<(String, usize)>, |
| 201 | pub first_errors: Vec<String>, |
| 202 | /// SoC package energy over the timed window (absent in Gate 4 results). |
| 203 | #[serde(default)] |
| 204 | pub energy: Option<EnergyReading>, |
| 205 | /// SoC package joules per acknowledged change over the timed window (includes the |
| 206 | /// idle draw of the package; see the run's idle window for the counterfactual). |
| 207 | #[serde(default)] |
| 208 | pub pkg_j_per_op: Option<f64>, |
| 209 | /// S3 only: group commit counters. |
| 210 | #[serde(default)] |
| 211 | pub group_commit: Option<GroupCommitStats>, |
| 212 | } |
| 213 | |
| 214 | /// `du -s -c` (apparent with `-b`, allocated with `-B1`) over `paths`; returns the total. |
| 215 | pub fn du_total(paths: &[PathBuf]) -> Result<StorageSample, String> { |
| 216 | let existing: Vec<&PathBuf> = paths.iter().filter(|p| p.exists()).collect(); |
| 217 | if existing.is_empty() { |
| 218 | return Ok(StorageSample::default()); |
| 219 | } |
| 220 | let run = |flag: &str| -> Result<u64, String> { |
| 221 | let mut cmd = std::process::Command::new("du"); |
| 222 | cmd.arg("-s").arg("-c").arg(flag); |
| 223 | for p in &existing { |
| 224 | cmd.arg(p); |
| 225 | } |
| 226 | let out = cmd.output().map_err(|e| format!("spawn du: {e}"))?; |
| 227 | if !out.status.success() { |
| 228 | return Err(format!( |
| 229 | "du {flag} failed: {}", |
| 230 | String::from_utf8_lossy(&out.stderr).trim() |
| 231 | )); |
| 232 | } |
| 233 | let text = String::from_utf8_lossy(&out.stdout); |
| 234 | let total_line = text |
| 235 | .lines() |
| 236 | .rev() |
| 237 | .find(|l| l.trim_end().ends_with("total")) |
| 238 | .ok_or("du output has no total line")?; |
| 239 | total_line |
| 240 | .split_whitespace() |
| 241 | .next() |
| 242 | .and_then(|v| v.parse().ok()) |
| 243 | .ok_or_else(|| format!("unparsable du total: {total_line}")) |
| 244 | }; |
| 245 | Ok(StorageSample { |
| 246 | apparent_bytes: run("-b")?, |
| 247 | allocated_bytes: run("-B1")?, |
| 248 | }) |
| 249 | } |
| 250 | |
| 251 | fn storage_delta( |
| 252 | paths: &[PathBuf], |
| 253 | before: StorageSample, |
| 254 | after_setup: StorageSample, |
| 255 | after_ops: StorageSample, |
| 256 | ops_ok: usize, |
| 257 | ) -> StorageDelta { |
| 258 | let d = |a: u64, b: u64| a as i64 - b as i64; |
| 259 | let ops_apparent = d(after_ops.apparent_bytes, after_setup.apparent_bytes); |
| 260 | let ops_allocated = d(after_ops.allocated_bytes, after_setup.allocated_bytes); |
| 261 | let per = |v: i64| { |
| 262 | if ops_ok == 0 { |
| 263 | 0.0 |
| 264 | } else { |
| 265 | round3(v as f64 / ops_ok as f64) |
| 266 | } |
| 267 | }; |
| 268 | StorageDelta { |
| 269 | measured_paths: paths.iter().map(|p| p.display().to_string()).collect(), |
| 270 | before_setup: before, |
| 271 | after_setup, |
| 272 | after_ops, |
| 273 | setup_apparent_bytes: d(after_setup.apparent_bytes, before.apparent_bytes), |
| 274 | ops_apparent_bytes: ops_apparent, |
| 275 | ops_allocated_bytes: ops_allocated, |
| 276 | total_apparent_bytes: d(after_ops.apparent_bytes, before.apparent_bytes), |
| 277 | total_allocated_bytes: d(after_ops.allocated_bytes, before.allocated_bytes), |
| 278 | ops_apparent_bytes_per_op: per(ops_apparent), |
| 279 | ops_allocated_bytes_per_op: per(ops_allocated), |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | fn durability_name(d: DurabilityGuarantee) -> &'static str { |
| 284 | match d { |
| 285 | DurabilityGuarantee::FsyncBeforeAck => "FsyncBeforeAck", |
| 286 | DurabilityGuarantee::ProcessCrashPageCacheOnly => "ProcessCrashPageCacheOnly", |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | fn base_trace(spec: &WriteCellSpec, p: &Proposal) -> OpTrace { |
| 291 | OpTrace { |
| 292 | arm: spec.arm.code().to_string(), |
| 293 | agents: spec.agents, |
| 294 | rep: spec.rep, |
| 295 | agent: p.agent, |
| 296 | index: p.index, |
| 297 | files: p.edits.len(), |
| 298 | content_bytes: p.content_bytes(), |
| 299 | start_us: 0, |
| 300 | latency_us: 0, |
| 301 | queue_wait_us: None, |
| 302 | wire_bytes: None, |
| 303 | durability: None, |
| 304 | ok: false, |
| 305 | error: None, |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | struct SynapseSubmitOk { |
| 310 | queue_wait_us: u64, |
| 311 | wire_bytes: usize, |
| 312 | durability: Option<DurabilityGuarantee>, |
| 313 | } |
| 314 | |
| 315 | /// One Synapse submit through the wire approximation and the shared service lock. |
| 316 | /// With `group`, the service lock covers only admission and path indexing and the |
| 317 | /// store commit goes through group commit. |
| 318 | pub fn synapse_submit( |
| 319 | service: &Mutex<SynapseService>, |
| 320 | group: Option<&SharedStore>, |
| 321 | agent: &AgentIdentity, |
| 322 | repo_id: &RepoId, |
| 323 | base_oid: GitOid, |
| 324 | p: &Proposal, |
| 325 | label: &str, |
| 326 | ) -> Result<(u64, usize, Option<DurabilityGuarantee>), String> { |
| 327 | let now = crate::unix_now_ms(); |
| 328 | let req = synapse_arm::build_submit_request(agent, repo_id, base_oid, p, label, now)?; |
| 329 | let (decoded, wire_bytes): (AuthenticatedRequest<SubmitChangesetPayload>, usize) = |
| 330 | synapse_arm::wire_roundtrip(&req)?; |
| 331 | let lock = || { |
| 332 | let wait_start = Instant::now(); |
| 333 | let guard = service |
| 334 | .lock() |
| 335 | .map_err(|_| "synapse service mutex poisoned".to_string())?; |
| 336 | Ok::<_, String>((guard, wait_start.elapsed().as_micros() as u64)) |
| 337 | }; |
| 338 | let (mut guard, mut queue_wait_us) = lock()?; |
| 339 | let outcome = match group { |
| 340 | None => guard.submit(&decoded, now).map_err(|e| e.to_string())?, |
| 341 | Some(store) => { |
| 342 | guard |
| 343 | .admit_submit(&decoded, now) |
| 344 | .map_err(|e| e.to_string())?; |
| 345 | drop(guard); |
| 346 | let env = &decoded.payload.envelope; |
| 347 | let outcome = store |
| 348 | .submit(env.clone(), &decoded.payload.blobs) |
| 349 | .map_err(|e| e.to_string())?; |
| 350 | let (g, wait) = lock()?; |
| 351 | queue_wait_us += wait; |
| 352 | guard = g; |
| 353 | guard.index_submitted(&outcome, env); |
| 354 | outcome |
| 355 | } |
| 356 | }; |
| 357 | drop(guard); |
| 358 | let durability = match outcome { |
| 359 | IngestOutcome::Committed { durability, .. } => Some(durability), |
| 360 | IngestOutcome::IdempotentDuplicate { .. } => None, |
| 361 | }; |
| 362 | Ok((queue_wait_us, wire_bytes, durability)) |
| 363 | } |
| 364 | |
| 365 | #[allow(clippy::too_many_arguments)] |
| 366 | fn run_synapse_agent( |
| 367 | spec: &WriteCellSpec, |
| 368 | service: &Mutex<SynapseService>, |
| 369 | group: Option<&SharedStore>, |
| 370 | agent: &AgentIdentity, |
| 371 | repo_id: &RepoId, |
| 372 | base_oid: GitOid, |
| 373 | proposals: &[Proposal], |
| 374 | barrier: &Barrier, |
| 375 | epoch: Instant, |
| 376 | ) -> Vec<OpTrace> { |
| 377 | barrier.wait(); |
| 378 | let mut traces = Vec::with_capacity(proposals.len()); |
| 379 | for p in proposals { |
| 380 | let mut t = base_trace(spec, p); |
| 381 | let label = format!( |
| 382 | "gate4/{}/r{}/n{}/a{}/p{}", |
| 383 | spec.arm.code(), |
| 384 | spec.rep, |
| 385 | spec.agents, |
| 386 | p.agent, |
| 387 | p.index |
| 388 | ); |
| 389 | let start = Instant::now(); |
| 390 | let res = synapse_submit(service, group, agent, repo_id, base_oid, p, &label).map( |
| 391 | |(queue_wait_us, wire_bytes, durability)| SynapseSubmitOk { |
| 392 | queue_wait_us, |
| 393 | wire_bytes, |
| 394 | durability, |
| 395 | }, |
| 396 | ); |
| 397 | t.latency_us = start.elapsed().as_micros() as u64; |
| 398 | t.start_us = start.duration_since(epoch).as_micros() as u64; |
| 399 | match res { |
| 400 | Ok(ok) => { |
| 401 | t.ok = true; |
| 402 | t.queue_wait_us = Some(ok.queue_wait_us); |
| 403 | t.wire_bytes = Some(ok.wire_bytes as u64); |
| 404 | t.durability = ok.durability.map(|d| durability_name(d).to_string()); |
| 405 | } |
| 406 | Err(e) => t.error = Some(e), |
| 407 | } |
| 408 | traces.push(t); |
| 409 | } |
| 410 | traces |
| 411 | } |
| 412 | |
| 413 | enum GitAgentState { |
| 414 | G1 { wt_root: PathBuf }, |
| 415 | G2 { wt: PathBuf }, |
| 416 | G3 { plumbing: PlumbingAgent }, |
| 417 | } |
| 418 | |
| 419 | fn run_git_agent( |
| 420 | spec: &WriteCellSpec, |
| 421 | state: &GitAgentState, |
| 422 | proposals: &[Proposal], |
| 423 | barrier: &Barrier, |
| 424 | epoch: Instant, |
| 425 | ) -> Vec<OpTrace> { |
| 426 | barrier.wait(); |
| 427 | let clone = spec.clone_dir.as_path(); |
| 428 | let base = spec.base_commit.as_str(); |
| 429 | let config: &[(&str, &str)] = if spec.arm == ArmKind::G3F { |
| 430 | FSYNC_ALL_CONFIG |
| 431 | } else { |
| 432 | &[] |
| 433 | }; |
| 434 | let mut traces = Vec::with_capacity(proposals.len()); |
| 435 | for p in proposals { |
| 436 | let mut t = base_trace(spec, p); |
| 437 | let start = Instant::now(); |
| 438 | let res = match state { |
| 439 | GitAgentState::G1 { wt_root } => git_arm::g1_op(clone, base, wt_root, p).map(|_| ()), |
| 440 | GitAgentState::G2 { wt } => git_arm::g2_op(wt, base, p), |
| 441 | GitAgentState::G3 { plumbing } => { |
| 442 | git_arm::g3_op(clone, base, plumbing, p, config).map(|_| ()) |
| 443 | } |
| 444 | }; |
| 445 | t.latency_us = start.elapsed().as_micros() as u64; |
| 446 | t.start_us = start.duration_since(epoch).as_micros() as u64; |
| 447 | match res { |
| 448 | Ok(()) => t.ok = true, |
| 449 | Err(e) => t.error = Some(e), |
| 450 | } |
| 451 | traces.push(t); |
| 452 | } |
| 453 | traces |
| 454 | } |
| 455 | |
| 456 | fn time_units<T>( |
| 457 | n: usize, |
| 458 | mut f: impl FnMut(usize) -> Result<T, String>, |
| 459 | ) -> Result<(Vec<T>, Vec<u64>, f64), String> { |
| 460 | let total = Instant::now(); |
| 461 | let mut out = Vec::with_capacity(n); |
| 462 | let mut samples = Vec::with_capacity(n); |
| 463 | for i in 0..n { |
| 464 | let t = Instant::now(); |
| 465 | out.push(f(i)?); |
| 466 | samples.push(t.elapsed().as_micros() as u64); |
| 467 | } |
| 468 | Ok((out, samples, round3(total.elapsed().as_secs_f64() * 1000.0))) |
| 469 | } |
| 470 | |
| 471 | /// Run one write cell end to end (setup, timed phase, storage, traces, cleanup). |
| 472 | pub fn run_write_cell(spec: &WriteCellSpec) -> Result<WriteCellResult, String> { |
| 473 | std::fs::create_dir_all(&spec.cell_dir) |
| 474 | .map_err(|e| format!("mkdir {}: {e}", spec.cell_dir.display()))?; |
| 475 | let clone = spec.clone_dir.as_path(); |
| 476 | let base: BaseTree = fixture::list_base_tree(clone, &spec.base_commit)?; |
| 477 | |
| 478 | // Proposal content needs only the editable files; Synapse also needs the full base |
| 479 | // because `SynapseService` holds the base tree in memory. |
| 480 | let (files, full_base): (Vec<EditableFile>, Option<Vec<_>>) = if spec.arm.is_synapse() { |
| 481 | let full = fixture::load_full_base(clone, &base)?; |
| 482 | (fixture::editable_from_full_base(&base, &full), Some(full)) |
| 483 | } else { |
| 484 | (fixture::load_editable_files(clone, &base)?, None) |
| 485 | }; |
| 486 | let workload = |
| 487 | generate_write_workload(spec.seed, spec.rep, spec.agents, spec.ops_per_agent, &files); |
| 488 | drop(files); |
| 489 | |
| 490 | let store_dir = spec.cell_dir.join("synapse-store"); |
| 491 | let wt_root = spec.cell_dir.join("worktrees"); |
| 492 | let plumbing_root = spec.cell_dir.join("plumbing"); |
| 493 | let measured: Vec<PathBuf> = if spec.arm.is_synapse() { |
| 494 | vec![store_dir.clone()] |
| 495 | } else { |
| 496 | vec![clone.join(".git"), wt_root.clone(), plumbing_root.clone()] |
| 497 | }; |
| 498 | let before = du_total(&measured)?; |
| 499 | |
| 500 | let barrier = Barrier::new(spec.agents + 1); |
| 501 | let mut final_sync_ms = None; |
| 502 | let mut group_stats = None; |
| 503 | let (setup, after_setup, traces, wall_ms, cpu, energy) = if spec.arm.is_synapse() { |
| 504 | let setup_start = Instant::now(); |
| 505 | let ids = synapse_arm::issue_identities(spec.seed, spec.agents, crate::unix_now_ms())?; |
| 506 | let fsync = match spec.arm { |
| 507 | ArmKind::S1 => FsyncPolicy::EveryCommit, |
| 508 | ArmKind::S3 => FsyncPolicy::GROUP_COMMIT_DEFAULT, |
| 509 | _ => FsyncPolicy::BatchWindow { |
| 510 | max_records: spec.batch_window_records, |
| 511 | }, |
| 512 | }; |
| 513 | // S3: the service keeps auth, base trees and the path index; its own store (in a |
| 514 | // separate directory, never written) is unused. The measured store is the |
| 515 | // group-commit `SharedStore` in `store_dir`. |
| 516 | let (svc_dir, svc_fsync) = if spec.arm == ArmKind::S3 { |
| 517 | ( |
| 518 | spec.cell_dir.join("service-admission"), |
| 519 | FsyncPolicy::EveryCommit, |
| 520 | ) |
| 521 | } else { |
| 522 | (store_dir.clone(), fsync) |
| 523 | }; |
| 524 | let mut svc = |
| 525 | synapse_arm::open_service(&svc_dir, &ids, svc_fsync, RecoveryPolicy::StrictFailClosed)?; |
| 526 | let group = if spec.arm == ArmKind::S3 { |
| 527 | Some( |
| 528 | SharedStore::open( |
| 529 | &store_dir, |
| 530 | fsync, |
| 531 | RecoveryPolicy::StrictFailClosed, |
| 532 | StoreLimits::default(), |
| 533 | ) |
| 534 | .map_err(|e| e.to_string())?, |
| 535 | ) |
| 536 | } else { |
| 537 | None |
| 538 | }; |
| 539 | let base_oid = synapse_arm::register_base( |
| 540 | &mut svc, |
| 541 | &spec.base_commit, |
| 542 | full_base.ok_or("full base missing for Synapse arm")?, |
| 543 | )?; |
| 544 | let setup = SetupSummary { |
| 545 | description: if group.is_some() { |
| 546 | "open SynapseService (admission only) and the group-commit SharedStore (WAL v2 pre-written), register the base tree held in memory, issue grants" |
| 547 | } else { |
| 548 | "open SynapseService, register the base tree held in memory, issue grants" |
| 549 | } |
| 550 | .into(), |
| 551 | units: 1, |
| 552 | total_ms: round3(setup_start.elapsed().as_secs_f64() * 1000.0), |
| 553 | per_unit: None, |
| 554 | }; |
| 555 | let service = Mutex::new(svc); |
| 556 | let after_setup = du_total(&measured)?; |
| 557 | let energy_window = EnergyWindow::start(); |
| 558 | let window = RusageWindow::start()?; |
| 559 | let epoch = Instant::now(); |
| 560 | let traces: Vec<OpTrace> = std::thread::scope(|s| { |
| 561 | let handles: Vec<_> = ids |
| 562 | .agents |
| 563 | .iter() |
| 564 | .zip(workload.iter()) |
| 565 | .map(|(agent, props)| { |
| 566 | let (service, barrier, repo_id) = (&service, &barrier, &ids.repo_id); |
| 567 | let group = group.as_ref(); |
| 568 | s.spawn(move || { |
| 569 | run_synapse_agent( |
| 570 | spec, service, group, agent, repo_id, base_oid, props, barrier, epoch, |
| 571 | ) |
| 572 | }) |
| 573 | }) |
| 574 | .collect(); |
| 575 | barrier.wait(); |
| 576 | handles |
| 577 | .into_iter() |
| 578 | .map(|h| h.join().map_err(|_| "agent thread panicked".to_string())) |
| 579 | .collect::<Result<Vec<Vec<OpTrace>>, String>>() |
| 580 | })? |
| 581 | .into_iter() |
| 582 | .flatten() |
| 583 | .collect(); |
| 584 | if spec.arm == ArmKind::S2 { |
| 585 | let t = Instant::now(); |
| 586 | service |
| 587 | .lock() |
| 588 | .map_err(|_| "synapse service mutex poisoned")? |
| 589 | .store_mut() |
| 590 | .sync_wal() |
| 591 | .map_err(|e| e.to_string())?; |
| 592 | final_sync_ms = Some(round3(t.elapsed().as_secs_f64() * 1000.0)); |
| 593 | } |
| 594 | let wall_ms = epoch.elapsed().as_secs_f64() * 1000.0; |
| 595 | let cpu = window.finish()?; |
| 596 | let energy = energy_window.finish(); |
| 597 | group_stats = group.as_ref().map(SharedStore::stats); |
| 598 | (setup, after_setup, traces, wall_ms, cpu, energy) |
| 599 | } else { |
| 600 | let config: &[(&str, &str)] = if spec.arm == ArmKind::G3F { |
| 601 | FSYNC_ALL_CONFIG |
| 602 | } else { |
| 603 | &[] |
| 604 | }; |
| 605 | std::fs::create_dir_all(&wt_root).map_err(|e| format!("mkdir worktrees: {e}"))?; |
| 606 | std::fs::create_dir_all(&plumbing_root).map_err(|e| format!("mkdir plumbing: {e}"))?; |
| 607 | let (states, samples, total_ms, description) = match spec.arm { |
| 608 | ArmKind::G1 => ( |
| 609 | (0..spec.agents) |
| 610 | .map(|_| GitAgentState::G1 { |
| 611 | wt_root: wt_root.clone(), |
| 612 | }) |
| 613 | .collect(), |
| 614 | Vec::new(), |
| 615 | 0.0, |
| 616 | "none (each operation creates its own worktree)".to_string(), |
| 617 | ), |
| 618 | ArmKind::G2 => { |
| 619 | let (wts, samples, total) = time_units(spec.agents, |a| { |
| 620 | git_arm::g2_setup_agent(clone, &spec.base_commit, &wt_root, a) |
| 621 | })?; |
| 622 | ( |
| 623 | wts.into_iter() |
| 624 | .map(|wt| GitAgentState::G2 { wt }) |
| 625 | .collect::<Vec<_>>(), |
| 626 | samples, |
| 627 | total, |
| 628 | "one `git worktree add --detach` per agent (sequential)".to_string(), |
| 629 | ) |
| 630 | } |
| 631 | _ => { |
| 632 | let (agents, samples, total) = time_units(spec.agents, |a| { |
| 633 | git_arm::g3_setup_agent(clone, &spec.base_commit, &plumbing_root, a, config) |
| 634 | })?; |
| 635 | ( |
| 636 | agents |
| 637 | .into_iter() |
| 638 | .map(|plumbing| GitAgentState::G3 { plumbing }) |
| 639 | .collect::<Vec<_>>(), |
| 640 | samples, |
| 641 | total, |
| 642 | "one `git read-tree` into a per-agent base index (sequential)".to_string(), |
| 643 | ) |
| 644 | } |
| 645 | }; |
| 646 | let setup = SetupSummary { |
| 647 | description, |
| 648 | units: samples.len(), |
| 649 | total_ms, |
| 650 | per_unit: summarize_us(&samples), |
| 651 | }; |
| 652 | let after_setup = du_total(&measured)?; |
| 653 | let energy_window = EnergyWindow::start(); |
| 654 | let window = RusageWindow::start()?; |
| 655 | let epoch = Instant::now(); |
| 656 | let traces: Vec<OpTrace> = std::thread::scope(|s| { |
| 657 | let handles: Vec<_> = states |
| 658 | .iter() |
| 659 | .zip(workload.iter()) |
| 660 | .map(|(state, props)| { |
| 661 | let barrier = &barrier; |
| 662 | s.spawn(move || run_git_agent(spec, state, props, barrier, epoch)) |
| 663 | }) |
| 664 | .collect(); |
| 665 | barrier.wait(); |
| 666 | handles |
| 667 | .into_iter() |
| 668 | .map(|h| h.join().map_err(|_| "agent thread panicked".to_string())) |
| 669 | .collect::<Result<Vec<Vec<OpTrace>>, String>>() |
| 670 | })? |
| 671 | .into_iter() |
| 672 | .flatten() |
| 673 | .collect(); |
| 674 | let wall_ms = epoch.elapsed().as_secs_f64() * 1000.0; |
| 675 | let cpu = window.finish()?; |
| 676 | let energy = energy_window.finish(); |
| 677 | (setup, after_setup, traces, wall_ms, cpu, energy) |
| 678 | }; |
| 679 | |
| 680 | let after_ops = du_total(&measured)?; |
| 681 | let ops_ok = traces.iter().filter(|t| t.ok).count(); |
| 682 | let storage = storage_delta(&measured, before, after_setup, after_ops, ops_ok); |
| 683 | |
| 684 | write_jsonl(&spec.trace_path, &traces)?; |
| 685 | |
| 686 | if matches!(spec.arm, ArmKind::G1 | ArmKind::G2) { |
| 687 | git_arm::remove_worktrees(clone, &wt_root)?; |
| 688 | } |
| 689 | |
| 690 | let ok_lat: Vec<u64> = traces |
| 691 | .iter() |
| 692 | .filter(|t| t.ok) |
| 693 | .map(|t| t.latency_us) |
| 694 | .collect(); |
| 695 | let queue: Vec<u64> = traces |
| 696 | .iter() |
| 697 | .filter(|t| t.ok) |
| 698 | .filter_map(|t| t.queue_wait_us) |
| 699 | .collect(); |
| 700 | let wire: Vec<u64> = traces |
| 701 | .iter() |
| 702 | .filter(|t| t.ok) |
| 703 | .filter_map(|t| t.wire_bytes) |
| 704 | .collect(); |
| 705 | let mut receipts: Vec<(String, usize)> = Vec::new(); |
| 706 | for t in traces.iter().filter_map(|t| t.durability.as_ref()) { |
| 707 | match receipts.iter_mut().find(|(k, _)| k == t) { |
| 708 | Some((_, c)) => *c += 1, |
| 709 | None => receipts.push((t.clone(), 1)), |
| 710 | } |
| 711 | } |
| 712 | let first_errors: Vec<String> = traces |
| 713 | .iter() |
| 714 | .filter_map(|t| t.error.clone()) |
| 715 | .take(5) |
| 716 | .collect(); |
| 717 | let ops_attempted = traces.len(); |
| 718 | let content_total: u64 = traces.iter().map(|t| t.content_bytes).sum(); |
| 719 | Ok(WriteCellResult { |
| 720 | arm: spec.arm, |
| 721 | agents: spec.agents, |
| 722 | ops_per_agent: spec.ops_per_agent, |
| 723 | rep: spec.rep, |
| 724 | ops_attempted, |
| 725 | ops_ok, |
| 726 | ops_failed: ops_attempted - ops_ok, |
| 727 | wall_ms: round3(wall_ms), |
| 728 | throughput_ops_per_s: if wall_ms > 0.0 { |
| 729 | round3(ops_ok as f64 / (wall_ms / 1000.0)) |
| 730 | } else { |
| 731 | 0.0 |
| 732 | }, |
| 733 | latency: summarize_us(&ok_lat), |
| 734 | queue_wait: summarize_us(&queue), |
| 735 | mean_wire_bytes: if wire.is_empty() { |
| 736 | None |
| 737 | } else { |
| 738 | Some(round3(wire.iter().sum::<u64>() as f64 / wire.len() as f64)) |
| 739 | }, |
| 740 | mean_content_bytes: if ops_attempted == 0 { |
| 741 | 0.0 |
| 742 | } else { |
| 743 | round3(content_total as f64 / ops_attempted as f64) |
| 744 | }, |
| 745 | setup, |
| 746 | final_sync_ms, |
| 747 | cpu_ms_per_op: if ops_ok == 0 { |
| 748 | None |
| 749 | } else { |
| 750 | Some(round3(cpu.total_cpu_ms / ops_ok as f64)) |
| 751 | }, |
| 752 | cpu, |
| 753 | storage, |
| 754 | durability_receipts: receipts, |
| 755 | first_errors, |
| 756 | pkg_j_per_op: energy |
| 757 | .pkg_j |
| 758 | .filter(|_| ops_ok > 0) |
| 759 | .map(|j| j / ops_ok as f64), |
| 760 | energy: Some(energy), |
| 761 | group_commit: group_stats, |
| 762 | }) |
| 763 | } |