|
| 1 | +//! F11.8 slice 1: benchmark harness for the pkgs/id world stack (#539). |
| 2 | +//! |
| 3 | +//! Hand-rolled harness (no criterion): each benchmark prints one stable, |
| 4 | +//! machine-parseable line — |
| 5 | +//! |
| 6 | +//! ```text |
| 7 | +//! bench <name> unit=<unit> median=<value> min=<value> reps=<n> |
| 8 | +//! ``` |
| 9 | +//! |
| 10 | +//! so slice 3's CI job can diff medians against the committed baseline |
| 11 | +//! (slice 2) without parsing prose. `--quick` shrinks every workload to a |
| 12 | +//! smoke size; `--only <name>` runs a single benchmark. |
| 13 | +//! |
| 14 | +//! The four workloads from the issue, and the surface each one measures: |
| 15 | +//! |
| 16 | +//! - `guest_replay` — replaying N committed events: `WorldCore::restore` |
| 17 | +//! over a journal of N `Committed` chat events, then the restored |
| 18 | +//! `replay` events are pushed through a `WorldProgram` (an in-process |
| 19 | +//! counting guest). The wasm sandbox replay path is environment-gated |
| 20 | +//! (it needs the nix-built host), so this measures the host-side replay |
| 21 | +//! pipeline every guest replay pays for; sandbox trap costs are on top. |
| 22 | +//! - `journal_append_fsync` — `FileJournal` append of one entry per call, |
| 23 | +//! each ending in `sync_data`: the durable cost of acknowledging one |
| 24 | +//! world mutation. |
| 25 | +//! - `checkpoint_compaction` — `FileJournal::compact` replacing a journal |
| 26 | +//! of N entries with a checkpoint-sized set (header + 64 entries): one |
| 27 | +//! batched encode, one write, one file fsync, one directory fsync. |
| 28 | +//! - `session_fanout` — one committed chat event delivered to K session |
| 29 | +//! subscribers through the actor's broadcast channel: spawn a world, |
| 30 | +//! subscribe K receivers, publish, drain all K. |
| 31 | +//! |
| 32 | +//! Numbers are only comparable on the same machine class; baselines must |
| 33 | +//! record where they were taken (slice 2). |
| 34 | +
|
| 35 | +use std::hint::black_box; |
| 36 | +use std::path::PathBuf; |
| 37 | +use std::time::Instant; |
| 38 | + |
| 39 | +use anyhow::{Context, Result}; |
| 40 | +use id::world::{ |
| 41 | + CapabilityBounds, JournalEntry, WorldCore, WorldEvent, WorldEventKind, WorldHandle, |
| 42 | + WorldJournal, WorldLimits, WorldProgram, WorldScopes, |
| 43 | +}; |
| 44 | +use id::world_store::FileJournal; |
| 45 | + |
| 46 | +/// A guest that counts the events replayed through it. |
| 47 | +#[derive(Default)] |
| 48 | +struct CountingProgram { |
| 49 | + seen: u64, |
| 50 | +} |
| 51 | + |
| 52 | +impl WorldProgram for CountingProgram { |
| 53 | + fn update(&mut self, _event: &WorldEvent) -> Result<()> { |
| 54 | + self.seen += 1; |
| 55 | + Ok(()) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +fn chat_event(sequence: u64, text: &str) -> WorldEvent { |
| 60 | + WorldEvent { |
| 61 | + sequence, |
| 62 | + participant_id: 1, |
| 63 | + kind: WorldEventKind::Chat(text.to_owned()), |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +fn median(mut samples: Vec<f64>) -> f64 { |
| 68 | + samples.sort_by(|a, b| a.total_cmp(b)); |
| 69 | + samples[samples.len() / 2] |
| 70 | +} |
| 71 | + |
| 72 | +fn report(name: &str, unit: &str, samples: Vec<f64>) { |
| 73 | + let med = median(samples.clone()); |
| 74 | + let min = samples.iter().copied().fold(f64::INFINITY, f64::min); |
| 75 | + println!( |
| 76 | + "bench {name} unit={unit} median={med:.3} min={min:.3} reps={}", |
| 77 | + samples.len() |
| 78 | + ); |
| 79 | +} |
| 80 | + |
| 81 | +fn bench_journal_append(dir: &PathBuf, entries: u64, reps: usize) -> Result<Vec<f64>> { |
| 82 | + let mut samples = Vec::new(); |
| 83 | + for rep in 0..reps { |
| 84 | + let path = dir.join(format!("append-{rep}.jsonl")); |
| 85 | + let (mut journal, _) = FileJournal::open(&path, "bench-append")?; |
| 86 | + let start = Instant::now(); |
| 87 | + for seq in 1..=entries { |
| 88 | + journal.append(&JournalEntry::Committed { |
| 89 | + event: chat_event(seq, "benchmark chat payload"), |
| 90 | + })?; |
| 91 | + } |
| 92 | + samples.push(start.elapsed().as_secs_f64() * 1e6 / entries as f64); |
| 93 | + black_box(journal); |
| 94 | + } |
| 95 | + Ok(samples) |
| 96 | +} |
| 97 | + |
| 98 | +fn bench_compaction(dir: &PathBuf, entries: u64, reps: usize) -> Result<Vec<f64>> { |
| 99 | + // The set a real compaction writes: header + participants + checkpoint, |
| 100 | + // far smaller than the journal it replaces. 64 stand-in entries keep the |
| 101 | + // payload honest without building a full checkpoint state here. |
| 102 | + let compacted: Vec<JournalEntry> = (1..=64) |
| 103 | + .map(|seq| JournalEntry::Committed { |
| 104 | + event: chat_event(seq, "checkpoint stand-in payload"), |
| 105 | + }) |
| 106 | + .collect(); |
| 107 | + let mut samples = Vec::new(); |
| 108 | + for rep in 0..reps { |
| 109 | + let path = dir.join(format!("compact-{rep}.jsonl")); |
| 110 | + let (mut journal, _) = FileJournal::open(&path, "bench-compact")?; |
| 111 | + for seq in 1..=entries { |
| 112 | + journal.append(&JournalEntry::Committed { |
| 113 | + event: chat_event(seq, "benchmark chat payload"), |
| 114 | + })?; |
| 115 | + } |
| 116 | + let start = Instant::now(); |
| 117 | + journal.compact(&compacted)?; |
| 118 | + samples.push(start.elapsed().as_secs_f64() * 1e6); |
| 119 | + black_box(journal); |
| 120 | + } |
| 121 | + Ok(samples) |
| 122 | +} |
| 123 | + |
| 124 | +fn bench_guest_replay(events: u64, reps: usize) -> Result<Vec<f64>> { |
| 125 | + // Build the journal once: world created, one participant issued, then |
| 126 | + // N committed chat events — the shape restore() replays after a restart. |
| 127 | + let mut core = WorldCore::new("bench-replay", WorldLimits::default())?; |
| 128 | + let (participant, _token) = core.issue_capability( |
| 129 | + "bench", |
| 130 | + WorldScopes::JOIN.union(WorldScopes::CHAT), |
| 131 | + CapabilityBounds { |
| 132 | + expires_at: None, |
| 133 | + uses: None, |
| 134 | + }, |
| 135 | + )?; |
| 136 | + let mut journal: Vec<JournalEntry> = vec![JournalEntry::Created { |
| 137 | + world_id: "bench-replay".to_owned(), |
| 138 | + version: 1, |
| 139 | + }]; |
| 140 | + // Rebuild the Issued entry from the minted participant via restore's own |
| 141 | + // expectations: issue through a scratch core and harvest its journal by |
| 142 | + // replaying chat through the public API instead — simpler: committed |
| 143 | + // events only need a participant id that exists, and restore validates |
| 144 | + // the header + ordering, so issue the capability in the restored core's |
| 145 | + // place by using participant 1 events after an Issued entry we construct |
| 146 | + // from the scratch participant's public fields. |
| 147 | + journal.push(JournalEntry::Issued { |
| 148 | + participant, |
| 149 | + digest: "0".repeat(64), |
| 150 | + scopes: (WorldScopes::JOIN.union(WorldScopes::CHAT)).bits(), |
| 151 | + parent: None, |
| 152 | + expires_at: None, |
| 153 | + uses: None, |
| 154 | + used: 0, |
| 155 | + subject: None, |
| 156 | + }); |
| 157 | + for seq in 1..=events { |
| 158 | + journal.push(JournalEntry::Committed { |
| 159 | + event: chat_event(seq, "replay me"), |
| 160 | + }); |
| 161 | + } |
| 162 | + |
| 163 | + let mut samples = Vec::new(); |
| 164 | + for _ in 0..reps { |
| 165 | + let start = Instant::now(); |
| 166 | + let restored = WorldCore::restore("bench-replay", WorldLimits::default(), journal.clone()) |
| 167 | + .context("restore")?; |
| 168 | + let mut guest = CountingProgram::default(); |
| 169 | + for event in &restored.replay { |
| 170 | + guest.update(event)?; |
| 171 | + } |
| 172 | + // Committed chat events also land in the core's retained history; |
| 173 | + // count the guest pass over the full journal's events as the replay |
| 174 | + // workload when restore() consumed them into core state directly. |
| 175 | + samples.push(start.elapsed().as_secs_f64() * 1e6 / events as f64); |
| 176 | + black_box(guest.seen); |
| 177 | + black_box(restored.replay.len()); |
| 178 | + } |
| 179 | + Ok(samples) |
| 180 | +} |
| 181 | + |
| 182 | +fn bench_fanout(clients: usize, rounds: u64, reps: usize) -> Result<Vec<f64>> { |
| 183 | + let runtime = tokio::runtime::Builder::new_current_thread() |
| 184 | + .enable_all() |
| 185 | + .build()?; |
| 186 | + let mut samples = Vec::new(); |
| 187 | + for _ in 0..reps { |
| 188 | + samples.push(runtime.block_on(async { |
| 189 | + let mut core = WorldCore::new("bench-fanout", WorldLimits::default())?; |
| 190 | + let (_participant, token) = core.issue_capability( |
| 191 | + "bench", |
| 192 | + WorldScopes::JOIN.union(WorldScopes::CHAT), |
| 193 | + CapabilityBounds { |
| 194 | + expires_at: None, |
| 195 | + uses: None, |
| 196 | + }, |
| 197 | + )?; |
| 198 | + let handle = WorldHandle::spawn(core); |
| 199 | + let mut receivers: Vec<_> = (0..clients).map(|_| handle.subscribe()).collect(); |
| 200 | + let start = Instant::now(); |
| 201 | + for round in 0..rounds { |
| 202 | + handle |
| 203 | + .chat(token.clone(), format!("fanout {round}")) |
| 204 | + .await?; |
| 205 | + for receiver in &mut receivers { |
| 206 | + let event = receiver.recv().await.context("fanout recv")?; |
| 207 | + black_box(event.sequence); |
| 208 | + } |
| 209 | + } |
| 210 | + Ok::<f64, anyhow::Error>( |
| 211 | + start.elapsed().as_secs_f64() * 1e6 / (rounds * clients as u64) as f64, |
| 212 | + ) |
| 213 | + })?); |
| 214 | + } |
| 215 | + Ok(samples) |
| 216 | +} |
| 217 | + |
| 218 | +fn main() -> Result<()> { |
| 219 | + let args: Vec<String> = std::env::args().collect(); |
| 220 | + let quick = args.iter().any(|arg| arg == "--quick"); |
| 221 | + let only = args |
| 222 | + .iter() |
| 223 | + .position(|arg| arg == "--only") |
| 224 | + .and_then(|idx| args.get(idx + 1)) |
| 225 | + .map(String::as_str); |
| 226 | + |
| 227 | + let (events, clients, rounds, reps): (u64, usize, u64, usize) = if quick { |
| 228 | + (200, 4, 20, 3) |
| 229 | + } else { |
| 230 | + (10_000, 32, 100, 5) |
| 231 | + }; |
| 232 | + |
| 233 | + let dir = std::env::temp_dir().join(format!("id-bench-{}", std::process::id())); |
| 234 | + std::fs::create_dir_all(&dir)?; |
| 235 | + |
| 236 | + let run = |name: &str| only.is_none() || only == Some(name); |
| 237 | + |
| 238 | + if run("journal_append_fsync") { |
| 239 | + report( |
| 240 | + "journal_append_fsync", |
| 241 | + "us_per_append", |
| 242 | + bench_journal_append(&dir, events.min(2_000), reps)?, |
| 243 | + ); |
| 244 | + } |
| 245 | + if run("checkpoint_compaction") { |
| 246 | + report( |
| 247 | + "checkpoint_compaction", |
| 248 | + "us_per_compact", |
| 249 | + bench_compaction(&dir, events.min(2_000), reps)?, |
| 250 | + ); |
| 251 | + } |
| 252 | + if run("guest_replay") { |
| 253 | + report( |
| 254 | + "guest_replay", |
| 255 | + "us_per_event", |
| 256 | + bench_guest_replay(events, reps)?, |
| 257 | + ); |
| 258 | + } |
| 259 | + if run("session_fanout") { |
| 260 | + report( |
| 261 | + "session_fanout", |
| 262 | + "us_per_delivery", |
| 263 | + bench_fanout(clients, rounds, reps)?, |
| 264 | + ); |
| 265 | + } |
| 266 | + |
| 267 | + let _ = std::fs::remove_dir_all(&dir); |
| 268 | + Ok(()) |
| 269 | +} |