From a05ff6d3cfe84b161b96f2d633ac5500d12a2ad9 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 03:33:31 -0600 Subject: [PATCH] feat(id): seeded stress-world generator in world_bench (#13083) Add the stress_gen profile to the pkgs/id bench harness: a deterministic generator for the #6304 scale tiers (quick smoke, 1x, 10x, 100x) that materializes a world directory set (idle header-only worlds, active worlds, one hot world with the tier's member count) plus a manifest.json recording the seed, tier, event mix (chat / doc-edit / program-install at the codified shapes), per-world event counts, and each measured world's expected final state hash (FNV-1a over the journal bytes plus the restored sequence). Every measured world is verified through WorldCore::restore before its hash is recorded. The 10x tier's 320-member hot world meets a codified wall: WorldLimits::default().participants is 256. The generator caps the hot world at the limit and records the wall in the manifest; the design doc's limits table gains the participants row and the entities/programs gap row is narrowed accordingly. Verified on the reference laptop: quick tier runs, two same-seed runs produce byte-identical trees and manifests, a different seed changes every hash, and the 10x tier generates 11,001 worlds / 200,000 events with all 1,001 measured worlds restore-verified. --- ...3T07-53-00Z_design_scale_perf_stress_v1.md | 3 +- pkgs/id/benches/world_bench.rs | 537 +++++++++++++++++- 2 files changed, 538 insertions(+), 2 deletions(-) diff --git a/doc/2026-11-23T07-53-00Z_design_scale_perf_stress_v1/2026-11-23T07-53-00Z_design_scale_perf_stress_v1.md b/doc/2026-11-23T07-53-00Z_design_scale_perf_stress_v1/2026-11-23T07-53-00Z_design_scale_perf_stress_v1.md index 4eb5bf2bf0..3d0bb45e83 100644 --- a/doc/2026-11-23T07-53-00Z_design_scale_perf_stress_v1/2026-11-23T07-53-00Z_design_scale_perf_stress_v1.md +++ b/doc/2026-11-23T07-53-00Z_design_scale_perf_stress_v1/2026-11-23T07-53-00Z_design_scale_perf_stress_v1.md @@ -202,7 +202,8 @@ derived rows with measured-at-tier rows; the 100x run | Documents | 64 KiB each / 512 list items | codified | #6281 findings, limits inventory | | Compile inputs | 8 files / 256 KiB total | codified | #6281 findings, limits inventory | | SSH surface | 64 connections / 16 tunnel streams | codified | #6281 findings, limits inventory | -| Per-world caps on entities / members / programs | **none codified** | gap | #6281 findings, Finding 1 | +| Participants per world | 256 | codified | `WorldLimits::default().participants`, `crates/id-worlds/src/world/mod.rs` — found by the #13083 generator's restore verification (the 10x tier's 320-member hot world is refused); the generator caps the hot world at 256 and records the wall in its manifest | +| Per-world caps on entities / programs | **none codified** | gap | #6281 findings, Finding 1 (the members part of that finding is superseded by the row above) | ## Host classes diff --git a/pkgs/id/benches/world_bench.rs b/pkgs/id/benches/world_bench.rs index 90ef397dc6..19168d5bf5 100644 --- a/pkgs/id/benches/world_bench.rs +++ b/pkgs/id/benches/world_bench.rs @@ -55,6 +55,20 @@ //! `ID_BENCH_GUEST_BURN_CONCURRENCY` runs the workload's guests on a //! dedicated budget of that size instead of the shared default, for //! sizing experiments. +//! - `stress_gen` — the #6304 scale & performance stress program's +//! seeded world generator (#13083): materializes a world directory +//! set for a scale tier (quick smoke, 1x, 10x, 100x — the design's +//! tier table) plus a `manifest.json` recording the seed, tier, +//! event mix, per-world event counts, and each measured world's +//! expected final state hash, so the join/replay/memory slices +//! (#13084–#13086) measure against a verifiable fixture instead of +//! generating their own. Generation bulk-writes journal files in +//! the store's on-disk format (it is a fixture producer, not the +//! measured append path) and verifies every measured world by +//! restoring it through `WorldCore::restore` before recording its +//! hash. Tier, seed, output root, and per-axis sizes are +//! overridable via `ID_BENCH_STRESS_TIER`, `ID_BENCH_STRESS_SEED`, +//! `ID_BENCH_STRESS_OUT`, and the `ID_BENCH_STRESS_*` axis knobs. //! - `bot_battle` (design only, not runnable yet) — a deterministic, mixed- //! strategy territory workload for N=2/4/8 users is specified in //! `../../../doc/2026-11-06T00-50-21Z_design_dynamic_world_tick_cost/`; its current- @@ -1738,6 +1752,522 @@ fn bench_fanout(clients: usize, rounds: u64, reps: usize) -> Result> { Ok(samples) } +/// The codified document shape the stress mix's document edits are +/// stated against: 64 KiB per document, 512 list items (design +/// limits inventory, #6281 findings). An edit event names a document +/// and a list item inside those bounds; it does not embed a whole +/// document snapshot. +const STRESS_DOC_BYTES: u64 = 65_536; +const STRESS_DOC_LIST_ITEMS: u64 = 512; +/// The codified compile-input cap the mix's program installs are +/// stated against: 8 files / 256 KiB total per install. +const STRESS_INSTALL_FILES: u64 = 8; +const STRESS_INSTALL_BYTES: u64 = 262_144; + +/// The stress event mix, as counts per 1,000 events in the same +/// discipline as the loadgen core's mix tables: the shape at stream +/// position `i` is a pure function of `i % 1000`, never sampled, so +/// the same (seed, tier) always produces the same stream. +const STRESS_MIX_CHAT: u64 = 700; +const STRESS_MIX_DOC_EDIT: u64 = 200; +const STRESS_MIX_PROGRAM_INSTALL: u64 = 100; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum StressShape { + Chat, + DocEdit, + ProgramInstall, +} + +impl StressShape { + fn name(self) -> &'static str { + match self { + StressShape::Chat => "chat", + StressShape::DocEdit => "doc_edit", + StressShape::ProgramInstall => "program_install", + } + } +} + +fn stress_shape_at(index: u64) -> StressShape { + let at = index % 1_000; + if at < STRESS_MIX_CHAT { + StressShape::Chat + } else if at < STRESS_MIX_CHAT + STRESS_MIX_DOC_EDIT { + StressShape::DocEdit + } else { + StressShape::ProgramInstall + } +} + +/// One `ID_BENCH_STRESS_*` axis override, falling back to the tier's +/// committed value when the variable is unset or unparseable (the +/// `ManyWorldsConfig` profiling-override pattern). +fn stress_env(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(default) +} + +/// A scale tier of the #6304 stress program: the design's tier table +/// (idle worlds / active worlds / single-world history / members on +/// the hot world), plus the per-active-world history the generator +/// gives every active world. A tier is a measurement target, not a +/// promise: a tier whose set cannot be generated or held is a +/// measured limit, recorded as such by the run that hits it. The +/// members axis meets such a wall today: the design targets 320 +/// members at 10x, but a world refuses more participants than the +/// codified `WorldLimits::default().participants` (256), so the +/// generator caps the hot world there and records the wall in the +/// manifest rather than emitting a world the store rejects. +#[derive(Clone, Copy)] +struct StressTier { + name: &'static str, + idle_worlds: usize, + active_worlds: usize, + hot_events: u64, + active_events: u64, + hot_members: usize, +} + +impl StressTier { + fn with_env_overrides(mut self) -> Self { + self.idle_worlds = stress_env("ID_BENCH_STRESS_IDLE_WORLDS", self.idle_worlds); + self.active_worlds = stress_env("ID_BENCH_STRESS_ACTIVE_WORLDS", self.active_worlds); + self.hot_events = stress_env("ID_BENCH_STRESS_HOT_EVENTS", self.hot_events as usize) as u64; + self.active_events = + stress_env("ID_BENCH_STRESS_ACTIVE_EVENTS", self.active_events as usize) as u64; + self.hot_members = stress_env("ID_BENCH_STRESS_HOT_MEMBERS", self.hot_members); + self + } + + fn quick() -> Self { + Self { + name: "quick", + idle_worlds: 10, + active_worlds: 4, + hot_events: 200, + active_events: 20, + hot_members: 4, + } + .with_env_overrides() + } + + fn tier_1x() -> Self { + Self { + name: "1x", + idle_worlds: 1_000, + active_worlds: 100, + hot_events: 10_000, + active_events: 100, + hot_members: 32, + } + .with_env_overrides() + } + + fn tier_10x() -> Self { + Self { + name: "10x", + idle_worlds: 10_000, + active_worlds: 1_000, + hot_events: 100_000, + active_events: 100, + hot_members: 320, + } + .with_env_overrides() + } + + fn tier_100x() -> Self { + Self { + name: "100x", + idle_worlds: 100_000, + active_worlds: 10_000, + hot_events: 1_000_000, + active_events: 100, + hot_members: 3_200, + } + .with_env_overrides() + } + + fn named(name: &str) -> Result { + match name { + "quick" => Ok(Self::quick()), + "1x" => Ok(Self::tier_1x()), + "10x" => Ok(Self::tier_10x()), + "100x" => Ok(Self::tier_100x()), + other => anyhow::bail!( + "unknown stress tier '{other}' in ID_BENCH_STRESS_TIER (valid: quick, 1x, 10x, 100x)" + ), + } + } +} + +/// FNV-1a (64-bit) over a byte stream: the manifest's expected state +/// hash. A change-detection hash, not a cryptographic one — its job +/// is to make two runs of the same (seed, tier) comparable and a +/// fast-but-wrong replay visible, cheaply and with no dependency. +struct Fnv1a(u64); + +impl Fnv1a { + fn new() -> Self { + Self(0xcbf2_9ce4_8422_2325) + } + + fn write(&mut self, bytes: &[u8]) { + for &byte in bytes { + self.0 ^= u64::from(byte); + self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3); + } + } + + fn finish(&self) -> String { + format!("{:016x}", self.0) + } +} + +/// One generated measured world, as recorded in the manifest. +struct StressWorldRecord { + name: String, + role: &'static str, + members: usize, + events: u64, + chat: u64, + doc_edits: u64, + program_installs: u64, + expected_state_hash: String, +} + +/// The deterministic event for one stream position of one generated +/// world. Every choice derives from the run seed through the loadgen +/// corpus / SplitMix64, so the event stream is a pure function of +/// (seed, world, position). +fn stress_event( + seed: u64, + world_index: u32, + sequence: u64, + participant_id: u64, +) -> (WorldEvent, StressShape) { + let shape = stress_shape_at(sequence - 1); + let corpus = loadgen::Corpus::new(seed); + let kind = match shape { + StressShape::Chat => WorldEventKind::Chat(corpus.text(world_index, sequence, 48)), + StressShape::DocEdit => { + let mut rng = loadgen::SplitMix64::new( + seed ^ (u64::from(world_index) << 32) + ^ sequence.wrapping_mul(0x9E37_79B9_7F4A_7C15), + ); + let doc = rng.next_u64() % 64; + let item = rng.next_u64() % STRESS_DOC_LIST_ITEMS; + WorldEventKind::Input( + format!( + "doc-edit doc={doc} item={item} doc_bytes={STRESS_DOC_BYTES} \ + list_items={STRESS_DOC_LIST_ITEMS} fill={}", + corpus.text(world_index, sequence, 96) + ) + .into_bytes(), + ) + } + StressShape::ProgramInstall => { + let mut rng = loadgen::SplitMix64::new( + seed ^ (u64::from(world_index) << 32) + ^ sequence.wrapping_mul(0xBF58_476D_1CE4_E5B9), + ); + let files = 1 + rng.next_u64() % STRESS_INSTALL_FILES; + let total_bytes = files * 4_096 + rng.next_u64() % (STRESS_INSTALL_BYTES / 4); + WorldEventKind::Input( + format!( + "program-install files={files} total_bytes={total_bytes} bundle={}", + corpus.text(world_index, sequence, 96) + ) + .into_bytes(), + ) + } + }; + ( + WorldEvent { + sequence, + participant_id, + kind, + }, + shape, + ) +} + +/// Generate one measured world directory (`//journal.jsonl`) +/// and verify it by restoring the written journal through the real +/// restore path. The expected state hash is FNV-1a over the journal +/// file's exact bytes followed by the restored core's current +/// sequence (u64 little-endian): the journal determines the state, +/// and the restore proves the journal is one the store accepts, at +/// the sequence the manifest claims. +fn generate_stress_world( + out: &Path, + name: &str, + role: &'static str, + seed: u64, + world_index: u32, + events: u64, + members: usize, +) -> Result { + ensure!( + members >= 1, + "stress world {name} needs at least one member" + ); + let mut entries: Vec = Vec::with_capacity((events + members as u64 + 1) as usize); + entries.push(JournalEntry::Created { + world_id: name.to_owned(), + version: 1, + }); + for member in 0..members { + entries.push(JournalEntry::Issued { + participant: id::world::Participant { + id: member as u64 + 1, + display_name: format!("stress-{member}"), + }, + digest: "0".repeat(64), + scopes: WorldScopes::GUEST.bits(), + parent: None, + expires_at: None, + uses: None, + used: 0, + subject: None, + issued_at: None, + }); + } + let (mut chat, mut doc_edits, mut program_installs) = (0_u64, 0_u64, 0_u64); + for sequence in 1..=events { + let participant_id = (sequence - 1) % members as u64 + 1; + let (event, shape) = stress_event(seed, world_index, sequence, participant_id); + match shape { + StressShape::Chat => chat += 1, + StressShape::DocEdit => doc_edits += 1, + StressShape::ProgramInstall => program_installs += 1, + } + entries.push(JournalEntry::Committed { event }); + } + + let dir = out.join(name); + std::fs::create_dir_all(&dir)?; + let path = dir.join("journal.jsonl"); + let mut bytes: Vec = Vec::new(); + for entry in &entries { + serde_json::to_writer(&mut bytes, entry).context("serialize stress journal entry")?; + bytes.push(b'\n'); + } + std::fs::write(&path, &bytes).with_context(|| format!("write stress journal {path:?}"))?; + + // Verify before recording: read the journal back in the store's + // own line format and restore it. A generator that emits worlds + // the store cannot open is worse than no generator. + let text = std::fs::read_to_string(&path)?; + let read_back: Vec = text + .lines() + .map(serde_json::from_str) + .collect::>() + .context("re-parse generated stress journal")?; + ensure!( + read_back.len() == entries.len(), + "{name}: read back {} entries, wrote {}", + read_back.len(), + entries.len() + ); + let restored = WorldCore::restore(name, WorldLimits::default(), read_back) + .map_err(|e| anyhow::anyhow!("restore generated stress world {name}: {e:#}"))?; + ensure!( + restored.core.current_sequence() == events, + "{name}: restored at sequence {}, generated {events} events", + restored.core.current_sequence() + ); + ensure!( + restored.replay.len() as u64 == doc_edits + program_installs, + "{name}: restored replay holds {} inputs, generated {}", + restored.replay.len(), + doc_edits + program_installs + ); + + let mut hash = Fnv1a::new(); + hash.write(&bytes); + hash.write(&restored.core.current_sequence().to_le_bytes()); + Ok(StressWorldRecord { + name: name.to_owned(), + role, + members, + events, + chat, + doc_edits, + program_installs, + expected_state_hash: hash.finish(), + }) +} + +/// The `stress_gen` profile (#13083): materialize the tier's world +/// directory set plus its manifest under the output root. The output +/// root is a pure function of (seed, tier): if it already holds a +/// stress manifest it is regenerated in place; if it holds anything +/// else the run refuses rather than deleting foreign content. +fn bench_stress_gen(quick: bool) -> Result<()> { + let tier = if quick { + StressTier::quick() + } else { + match std::env::var("ID_BENCH_STRESS_TIER") { + Ok(name) => StressTier::named(&name)?, + Err(_) => StressTier::tier_1x(), + } + }; + let seed = std::env::var("ID_BENCH_STRESS_SEED") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(BENCH_SEED); + let out = std::env::var("ID_BENCH_STRESS_OUT").map_or_else( + |_| std::env::temp_dir().join(format!("id-stress-{}-{}", tier.name, seed)), + PathBuf::from, + ); + if out.exists() { + ensure!( + out.join("manifest.json").exists(), + "stress output root {out:?} exists and holds no stress manifest; refusing to overwrite it" + ); + std::fs::remove_dir_all(&out)?; + } + std::fs::create_dir_all(&out)?; + let started = Instant::now(); + + // Idle worlds: durable headers only — a Created entry and nothing + // else, matching what the many-worlds workload leaves on disk for + // a world that was opened and evicted without a guest. + for index in 0..tier.idle_worlds { + let name = format!("idle-{index:05}"); + let dir = out.join(&name); + std::fs::create_dir_all(&dir)?; + let entry = JournalEntry::Created { + world_id: name, + version: 1, + }; + let mut line = serde_json::to_vec(&entry).context("serialize idle world header")?; + line.push(b'\n'); + std::fs::write(dir.join("journal.jsonl"), line)?; + } + + let mut records: Vec = Vec::with_capacity(tier.active_worlds + 1); + for index in 0..tier.active_worlds { + let name = format!("active-{index:04}"); + records.push(generate_stress_world( + &out, + &name, + "active", + seed, + index as u32, + tier.active_events, + 1, + )?); + } + // The members wall (see StressTier): generate at the codified + // participant cap when the tier targets more, and record the + // wall in the manifest — a wall is a result, per the design's + // run protocol, not a silent clamp. + let participant_cap = WorldLimits::default().participants; + let hot_members = tier.hot_members.min(participant_cap); + let mut walls: Vec = Vec::new(); + if hot_members < tier.hot_members { + walls.push(serde_json::json!({ + "axis": "hot_members", + "tier_target": tier.hot_members, + "generated": hot_members, + "limit": "codified: WorldLimits::default().participants", + "limit_value": participant_cap, + })); + } + let hot = generate_stress_world( + &out, + "hot-000", + "hot", + seed, + u32::MAX, + tier.hot_events, + hot_members, + )?; + let hot_hash = hot.expected_state_hash.clone(); + records.push(hot); + + let wall_count = walls.len(); + let total_events: u64 = records.iter().map(|record| record.events).sum(); + let worlds_json: Vec = records + .iter() + .map(|record| { + serde_json::json!({ + "name": record.name, + "role": record.role, + "members": record.members, + "events": record.events, + "counts": { + "chat": record.chat, + "doc_edit": record.doc_edits, + "program_install": record.program_installs, + }, + "expected_state_hash": record.expected_state_hash, + }) + }) + .collect(); + let mut mix = serde_json::Map::new(); + mix.insert(StressShape::Chat.name().to_owned(), STRESS_MIX_CHAT.into()); + mix.insert( + StressShape::DocEdit.name().to_owned(), + STRESS_MIX_DOC_EDIT.into(), + ); + mix.insert( + StressShape::ProgramInstall.name().to_owned(), + STRESS_MIX_PROGRAM_INSTALL.into(), + ); + let manifest = serde_json::json!({ + "type": "stress-manifest", + "schema_version": 1, + "generator_version": loadgen::GENERATOR_VERSION, + "seed": seed, + "tier": tier.name, + "mix_per_1000": serde_json::Value::Object(mix), + "shapes": { + "doc_bytes": STRESS_DOC_BYTES, + "doc_list_items": STRESS_DOC_LIST_ITEMS, + "install_files_max": STRESS_INSTALL_FILES, + "install_bytes_max": STRESS_INSTALL_BYTES, + }, + "hash": { + "algorithm": "fnv1a64", + "input": "journal.jsonl bytes in order, then the restored current_sequence as u64 little-endian", + "format": "16 lowercase hex digits", + }, + "idle_worlds": {"count": tier.idle_worlds, "events_per_world": 0}, + "walls": walls, + "worlds": worlds_json, + "totals": { + "worlds": tier.idle_worlds + tier.active_worlds + 1, + "measured_worlds": records.len(), + "events": total_events, + }, + }); + let manifest_path = out.join("manifest.json"); + std::fs::write( + &manifest_path, + format!("{}\n", serde_json::to_string_pretty(&manifest)?), + )?; + + println!( + "profile stress_gen tier={} seed={} worlds={} measured_worlds={} events={} hot_state_hash={} walls={} elapsed_secs={:.3} out={} manifest={}", + tier.name, + seed, + tier.idle_worlds + tier.active_worlds + 1, + records.len(), + total_events, + hot_hash, + wall_count, + started.elapsed().as_secs_f64(), + out.display(), + manifest_path.display(), + ); + Ok(()) +} + fn main() -> Result<()> { let args: Vec = std::env::args().collect(); let quick = args.iter().any(|arg| arg == "--quick"); @@ -1756,13 +2286,14 @@ fn main() -> Result<()> { let dir = std::env::temp_dir().join(format!("id-bench-{}", std::process::id())); std::fs::create_dir_all(&dir)?; - const BENCHMARKS: [&str; 6] = [ + const BENCHMARKS: [&str; 7] = [ "journal_append_fsync", "checkpoint_compaction", "guest_replay", "session_fanout", "many_worlds", "fuel_spin_isolation", + "stress_gen", ]; if let Some(name) = only && !BENCHMARKS.contains(&name) @@ -1829,6 +2360,10 @@ fn main() -> Result<()> { runtime.block_on(bench_fuel_spin_isolation(worker_threads, quick))?; } + if run("stress_gen") { + bench_stress_gen(quick)?; + } + if !cells.is_empty() { write_results_jsonl(&cells, quick)?; }