diff --git a/pkgs/id/benches/world_bench.rs b/pkgs/id/benches/world_bench.rs index 19168d5bf5..e887e9b7cc 100644 --- a/pkgs/id/benches/world_bench.rs +++ b/pkgs/id/benches/world_bench.rs @@ -69,6 +69,10 @@ //! 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. +//! Generation materializes into a marker-verified staging sibling +//! of the output root and publishes by rename, so an interrupted +//! run is recoverable on retry and the output root only ever holds +//! a complete generation (#13181). //! - `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- @@ -121,6 +125,11 @@ use id::world_store::{FileJournal, open_world}; #[path = "../tests/common/loadgen.rs"] mod loadgen; +// The stress generator's output lifecycle (#13181): staging, +// identity verification, recovery, and atomic publication. +#[path = "../tests/common/stress_output.rs"] +mod stress_output; + /// The fixed seed of every bench run on the core: a bench run must /// be replayable from its spec (#5891, determinism before realism). const BENCH_SEED: u64 = 0x5891; @@ -2103,9 +2112,11 @@ fn generate_stress_world( /// 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. +/// root is a pure function of (seed, tier): generation materializes +/// into a staging sibling and publishes by rename (#13181), so a +/// completed generation is regenerated in place, an interrupted one +/// is recovered on retry, and anything unverifiable is refused +/// rather than deleted. fn bench_stress_gen(quick: bool) -> Result<()> { let tier = if quick { StressTier::quick() @@ -2123,14 +2134,8 @@ fn bench_stress_gen(quick: bool) -> Result<()> { |_| 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 staging = + stress_output::prepare_stress_output(&out, seed, tier.name, loadgen::GENERATOR_VERSION)?; let started = Instant::now(); // Idle worlds: durable headers only — a Created entry and nothing @@ -2138,7 +2143,7 @@ fn bench_stress_gen(quick: bool) -> Result<()> { // 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); + let dir = staging.join(&name); std::fs::create_dir_all(&dir)?; let entry = JournalEntry::Created { world_id: name, @@ -2153,7 +2158,7 @@ fn bench_stress_gen(quick: bool) -> Result<()> { for index in 0..tier.active_worlds { let name = format!("active-{index:04}"); records.push(generate_stress_world( - &out, + &staging, &name, "active", seed, @@ -2179,7 +2184,7 @@ fn bench_stress_gen(quick: bool) -> Result<()> { })); } let hot = generate_stress_world( - &out, + &staging, "hot-000", "hot", seed, @@ -2246,11 +2251,7 @@ fn bench_stress_gen(quick: bool) -> Result<()> { "events": total_events, }, }); - let manifest_path = out.join("manifest.json"); - std::fs::write( - &manifest_path, - format!("{}\n", serde_json::to_string_pretty(&manifest)?), - )?; + let manifest_path = stress_output::publish_stress_output(&out, &staging, &manifest)?; println!( "profile stress_gen tier={} seed={} worlds={} measured_worlds={} events={} hot_state_hash={} walls={} elapsed_secs={:.3} out={} manifest={}", diff --git a/pkgs/id/tests/common/mod.rs b/pkgs/id/tests/common/mod.rs index e2a609ab51..2d2c416669 100644 --- a/pkgs/id/tests/common/mod.rs +++ b/pkgs/id/tests/common/mod.rs @@ -12,6 +12,7 @@ pub mod chain; pub mod ingest; pub mod loadgen; +pub mod stress_output; /// Every network step in these tests must finish within this, so a stuck /// request fails the test instead of hanging the suite (issue #5218). diff --git a/pkgs/id/tests/common/stress_output.rs b/pkgs/id/tests/common/stress_output.rs new file mode 100644 index 0000000000..f2c1d945d9 --- /dev/null +++ b/pkgs/id/tests/common/stress_output.rs @@ -0,0 +1,173 @@ +//! The stress generator's output lifecycle (#13181): staging, +//! identity verification, recovery, and atomic publication for the +//! `stress_gen` bench profile's fixture directories. +//! +//! Shared by the bench (through a `#[path]` include) and the +//! integration tests (through `mod common;`). Unlike `loadgen` +//! this module is not std-only: it manipulates the generator's +//! on-disk JSON formats, so it uses the `serde_json` / `anyhow` +//! stack the bench and the test crates already link. +//! +//! The rules, in order: +//! +//! - Generation materializes into a staging sibling of the output +//! root, marked with an ownership marker before anything else is +//! written. A leftover staging directory is recovered (deleted) +//! only when its marker verifies it as this generator's. +//! - A completed output root is replaced only after its manifest +//! verifies as a stress manifest of the current schema. A +//! directory whose contents cannot be verified — a foreign +//! manifest, a missing manifest, an unmarked staging directory — +//! is never deleted; the run refuses and names the cleanup +//! action instead. +//! - Publication writes the manifest atomically inside the staging +//! directory (temp file, sync, rename) and then renames the +//! staging directory into place, so the output root only ever +//! holds a complete generation or nothing at all. + +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, ensure}; + +/// File name of the ownership marker a stress generation writes +/// into its staging directory before anything else. The marker is +/// what makes an interrupted generation recognizable as ours. +pub const STRESS_STAGING_MARKER: &str = ".stress-gen-staging.json"; + +/// The manifest `type` every completed stress generation carries; +/// the identity a previous output root must prove before a new +/// generation may replace it. +pub const STRESS_MANIFEST_TYPE: &str = "stress-manifest"; + +/// The staging directory a stress generation materializes into +/// before publishing: a sibling of the output root named after it, +/// so the publish rename stays on one filesystem. +pub fn stress_staging_path(out: &Path) -> Result { + let name = out + .file_name() + .context("stress output root has no final path component")?; + let mut staging = name.to_os_string(); + staging.push(".partial"); + Ok(out.with_file_name(staging)) +} + +/// Whether `dir`'s manifest identifies it as a completed stress +/// generation of this generator: the manifest must parse and carry +/// the stress manifest type and schema version. Anything else — +/// missing, unparseable, foreign — is not ours to delete. +pub fn stress_dir_is_completed_generation(dir: &Path) -> bool { + let Ok(text) = std::fs::read_to_string(dir.join("manifest.json")) else { + return false; + }; + let Ok(value) = serde_json::from_str::(&text) else { + return false; + }; + value.get("type").and_then(serde_json::Value::as_str) == Some(STRESS_MANIFEST_TYPE) + && value + .get("schema_version") + .and_then(serde_json::Value::as_u64) + == Some(1) +} + +/// Whether `dir` is a staging directory left by an interrupted +/// stress generation: its ownership marker must parse and name +/// this generator. A staging path without a verifiable marker is +/// foreign content, not a recoverable leftover. +pub fn stress_dir_is_staging(dir: &Path) -> bool { + let Ok(text) = std::fs::read_to_string(dir.join(STRESS_STAGING_MARKER)) else { + return false; + }; + let Ok(value) = serde_json::from_str::(&text) else { + return false; + }; + value.get("type").and_then(serde_json::Value::as_str) == Some("stress-gen-staging") +} + +/// Prepare a stress generation: recover the staging directory an +/// interrupted run left behind (verified ours via its ownership +/// marker), refuse unverified content at either path with the +/// cleanup action named, and create a fresh staging directory +/// carrying its marker. The completed output root, if any, is left +/// untouched here — it is replaced only at publish time, after the +/// new generation succeeds, so a failed regeneration never strands +/// a previously good fixture. +pub fn prepare_stress_output( + out: &Path, + seed: u64, + tier_name: &str, + generator_version: u64, +) -> Result { + let staging = stress_staging_path(out)?; + if staging.exists() { + ensure!( + stress_dir_is_staging(&staging), + "stress staging directory {staging:?} exists but its ownership marker is missing \ + or foreign; refusing to delete unverified content — inspect it and remove it \ + manually if it is a leftover stress generation" + ); + std::fs::remove_dir_all(&staging) + .with_context(|| format!("remove interrupted stress staging directory {staging:?}"))?; + } + if out.exists() { + ensure!( + stress_dir_is_completed_generation(out), + "stress output root {out:?} exists but does not hold a verified stress manifest \ + (type {STRESS_MANIFEST_TYPE:?}, schema_version 1); refusing to overwrite \ + unverified content — if it is a partial generation from an interrupted run, \ + remove the directory and re-run" + ); + } + std::fs::create_dir_all(&staging) + .with_context(|| format!("create stress staging directory {staging:?}"))?; + let marker = serde_json::json!({ + "type": "stress-gen-staging", + "generator_version": generator_version, + "seed": seed, + "tier": tier_name, + }); + std::fs::write( + staging.join(STRESS_STAGING_MARKER), + format!("{}\n", serde_json::to_string(&marker)?), + ) + .context("write stress staging ownership marker")?; + Ok(staging) +} + +/// Publish a completed staging directory as the output root: the +/// manifest is written atomically (temp file, sync, rename within +/// the staging directory, so no reader can observe a partial +/// manifest), the staging marker is dropped, the previous +/// completed generation — its identity re-verified here — is +/// removed, and the staging directory is renamed into place. +pub fn publish_stress_output( + out: &Path, + staging: &Path, + manifest: &serde_json::Value, +) -> Result { + let manifest_tmp = staging.join("manifest.json.tmp"); + std::fs::write( + &manifest_tmp, + format!("{}\n", serde_json::to_string_pretty(manifest)?), + ) + .context("write stress manifest temp file")?; + std::fs::File::open(&manifest_tmp) + .context("open stress manifest temp file")? + .sync_all() + .context("sync stress manifest temp file")?; + std::fs::rename(&manifest_tmp, staging.join("manifest.json")) + .context("publish stress manifest within staging directory")?; + std::fs::remove_file(staging.join(STRESS_STAGING_MARKER)) + .context("remove stress staging ownership marker")?; + if out.exists() { + ensure!( + stress_dir_is_completed_generation(out), + "stress output root {out:?} no longer holds a verified stress manifest; \ + refusing to replace unverified content" + ); + std::fs::remove_dir_all(out) + .with_context(|| format!("remove previous stress generation {out:?}"))?; + } + std::fs::rename(staging, out) + .with_context(|| format!("publish stress generation {staging:?} -> {out:?}"))?; + Ok(out.join("manifest.json")) +} diff --git a/pkgs/id/tests/stress_gen_recovery.rs b/pkgs/id/tests/stress_gen_recovery.rs new file mode 100644 index 0000000000..283f00b711 --- /dev/null +++ b/pkgs/id/tests/stress_gen_recovery.rs @@ -0,0 +1,222 @@ +//! Regression tests for the stress generator's output lifecycle +//! (#13181): a generation interrupted before its manifest is +//! published must be recoverable on retry, and no directory whose +//! contents cannot be verified as a stress generation may ever be +//! deleted to make room for one. +//! +//! The oracle throughout is identity, not presence: deletion is +//! gated on the staging ownership marker or the manifest's type + +//! schema version, both defined in `common::stress_output` — the +//! same code the `stress_gen` bench profile runs. + +mod common; + +use std::path::{Path, PathBuf}; + +use common::loadgen::GENERATOR_VERSION; +use common::stress_output::{ + prepare_stress_output, publish_stress_output, stress_dir_is_completed_generation, + stress_staging_path, +}; +use id::world::{ + JournalEntry, Participant, WorldCore, WorldEvent, WorldEventKind, WorldLimits, WorldScopes, +}; + +const SEED: u64 = 0x5891; + +fn temp_root(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "id-stress-gen-recovery-{}-{tag}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create test root"); + dir +} + +fn sample_manifest(seed: u64) -> serde_json::Value { + serde_json::json!({ + "type": "stress-manifest", + "schema_version": 1, + "generator_version": GENERATOR_VERSION, + "seed": seed, + "tier": "quick", + "worlds": [], + "totals": {"worlds": 0, "measured_worlds": 0, "events": 0}, + }) +} + +/// Write one measured world in the store's journal format under +/// `root` and prove the store restores it at the generated +/// sequence — the same verification the generator performs before +/// recording a world in the manifest. +fn write_and_verify_world(root: &Path, name: &str, events: u64) { + let mut entries = vec![ + JournalEntry::Created { + world_id: name.to_owned(), + version: 1, + }, + JournalEntry::Issued { + participant: Participant { + id: 1, + display_name: "stress-0".to_owned(), + }, + digest: "0".repeat(64), + scopes: WorldScopes::GUEST.bits(), + parent: None, + expires_at: None, + uses: None, + used: 0, + subject: None, + issued_at: None, + }, + ]; + entries.extend((1..=events).map(|sequence| JournalEntry::Committed { + event: WorldEvent { + sequence, + participant_id: 1, + kind: WorldEventKind::Chat(format!("message {sequence}")), + }, + })); + let dir = root.join(name); + std::fs::create_dir_all(&dir).expect("create world dir"); + let mut bytes = Vec::new(); + for entry in &entries { + serde_json::to_writer(&mut bytes, entry).expect("serialize journal entry"); + bytes.push(b'\n'); + } + std::fs::write(dir.join("journal.jsonl"), &bytes).expect("write journal"); + let text = String::from_utf8(bytes).expect("journal is utf-8"); + let read_back: Vec = text + .lines() + .map(serde_json::from_str) + .collect::>() + .expect("re-parse journal"); + let restored = WorldCore::restore(name, WorldLimits::default(), read_back) + .expect("restore generated world"); + assert_eq!(restored.core.current_sequence(), events); +} + +/// A generation that dies before publishing leaves a marked +/// staging directory; the retry with the same (seed, tier, output) +/// recovers it and publishes a complete fixture whose world +/// restores from the published location. +#[test] +fn interrupted_generation_recovers_on_retry() { + let root = temp_root("recover"); + let out = root.join("fixture"); + // First attempt: staging prepared, one world materialized, + // then the run dies before the manifest is published. + let staging = prepare_stress_output(&out, SEED, "quick", GENERATOR_VERSION).unwrap(); + write_and_verify_world(&staging, "active-0000", 3); + assert!( + !out.exists(), + "nothing may be published before the manifest" + ); + // Retry: the leftover staging is verified as ours, recovered, + // and the run publishes a complete, verifiable fixture. + let staging = prepare_stress_output(&out, SEED, "quick", GENERATOR_VERSION).unwrap(); + write_and_verify_world(&staging, "active-0000", 3); + let manifest_path = publish_stress_output(&out, &staging, &sample_manifest(SEED)).unwrap(); + assert!(stress_dir_is_completed_generation(&out)); + let manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap(); + assert_eq!(manifest["type"], "stress-manifest"); + assert!(!staging.exists(), "publish renames the staging directory"); + // The published world restores from its published location. + let text = std::fs::read_to_string(out.join("active-0000/journal.jsonl")).unwrap(); + let read_back: Vec = text + .lines() + .map(serde_json::from_str) + .collect::>() + .unwrap(); + let restored = WorldCore::restore("active-0000", WorldLimits::default(), read_back).unwrap(); + assert_eq!(restored.core.current_sequence(), 3); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// A completed generation is replaced in place by the next run +/// (the pre-#13181 regeneration behaviour, now at publish time). +#[test] +fn completed_generation_is_replaced_on_republish() { + let root = temp_root("replace"); + let out = root.join("fixture"); + let staging = prepare_stress_output(&out, SEED, "quick", GENERATOR_VERSION).unwrap(); + write_and_verify_world(&staging, "active-0000", 3); + publish_stress_output(&out, &staging, &sample_manifest(SEED)).unwrap(); + // Regenerate with a different seed and a longer world: the + // verified completed generation is accepted and replaced. + let staging = prepare_stress_output(&out, SEED + 1, "quick", GENERATOR_VERSION).unwrap(); + write_and_verify_world(&staging, "active-0000", 5); + publish_stress_output(&out, &staging, &sample_manifest(SEED + 1)).unwrap(); + let journal = std::fs::read_to_string(out.join("active-0000/journal.jsonl")).unwrap(); + // Created + one Issued + five events: the new generation, not + // a merge of the two. + assert_eq!(journal.lines().count(), 7); + let manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(out.join("manifest.json")).unwrap()).unwrap(); + assert_eq!(manifest["seed"], SEED + 1); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// An output root whose manifest is foreign — present, but not a +/// stress manifest — is never deleted, however it got there. +#[test] +fn foreign_output_root_is_never_deleted() { + let root = temp_root("foreign"); + let out = root.join("fixture"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("manifest.json"), "{\"type\":\"someone-else\"}\n").unwrap(); + std::fs::write(out.join("keep.txt"), "precious").unwrap(); + let err = prepare_stress_output(&out, SEED, "quick", GENERATOR_VERSION).unwrap_err(); + assert!( + format!("{err:#}").contains("refusing to overwrite unverified content"), + "{err:#}" + ); + assert_eq!( + std::fs::read_to_string(out.join("keep.txt")).unwrap(), + "precious" + ); + assert_eq!( + std::fs::read_to_string(out.join("manifest.json")).unwrap(), + "{\"type\":\"someone-else\"}\n" + ); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// A partial generation written by the pre-#13181 code (worlds but +/// no manifest, and no staging marker to verify ownership) is +/// refused with the cleanup action named, and preserved. +#[test] +fn manifestless_output_root_refuses_with_cleanup_guidance() { + let root = temp_root("manifestless"); + let out = root.join("fixture"); + let world = out.join("idle-00000"); + std::fs::create_dir_all(&world).unwrap(); + std::fs::write(world.join("journal.jsonl"), "{}\n").unwrap(); + let err = prepare_stress_output(&out, SEED, "quick", GENERATOR_VERSION).unwrap_err(); + assert!( + format!("{err:#}").contains("remove the directory and re-run"), + "{err:#}" + ); + assert!(world.join("journal.jsonl").exists(), "nothing was deleted"); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// A staging directory without a verifiable ownership marker is +/// foreign content, not a recoverable leftover. +#[test] +fn unmarked_staging_directory_is_never_deleted() { + let root = temp_root("staging-foreign"); + let out = root.join("fixture"); + let staging = stress_staging_path(&out).unwrap(); + std::fs::create_dir_all(&staging).unwrap(); + std::fs::write(staging.join("keep.txt"), "precious").unwrap(); + let err = prepare_stress_output(&out, SEED, "quick", GENERATOR_VERSION).unwrap_err(); + assert!(format!("{err:#}").contains("ownership marker"), "{err:#}"); + assert_eq!( + std::fs::read_to_string(staging.join("keep.txt")).unwrap(), + "precious" + ); + std::fs::remove_dir_all(&root).unwrap(); +}