diff --git a/.github/workflows/aravath-determinism.yml b/.github/workflows/aravath-determinism.yml index 16a21900c3..c438675755 100644 --- a/.github/workflows/aravath-determinism.yml +++ b/.github/workflows/aravath-determinism.yml @@ -1,8 +1,8 @@ name: Aravath determinism -# The recorded replay must land on the same state hash on Linux and Windows. -# Baseline x86-64, no FMA, no target-cpu=native. rustc does not contract -# `a * b + c` into an FMA unless the code calls `mul_add`. +# The recorded replay must land on the same state hash on Linux, Windows, and macOS. +# x86-64 uses the baseline CPU with FMA off. aarch64 uses the default baseline +# CPU. rustc does not contract `a * b + c` into an FMA unless the code calls `mul_add`. on: push: @@ -25,7 +25,6 @@ env: CARGO_TERM_COLOR: always CARGO_NET_RETRY: 10 RUST_BACKTRACE: short - RUSTFLAGS: "-C target-cpu=x86-64 -C target-feature=-fma" jobs: golden: @@ -35,7 +34,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-latest] + os: [ubuntu-latest, windows-latest, macos-latest] steps: - name: Checkout uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 @@ -56,5 +55,21 @@ jobs: key: aravath-det-${{ matrix.os }}-v1 cache-all-crates: true + - name: Pin baseline CPU + run: | + host=$(rustc -vV | sed -n 's/^host: //p') + case "$host" in + x86_64-*) + echo "RUSTFLAGS=-C target-cpu=x86-64 -C target-feature=-fma" >> "$GITHUB_ENV" + ;; + aarch64-*) + echo "aarch64 uses the default baseline CPU (target-cpu=native is forbidden)." + ;; + *) + echo "unsupported host $host" >&2 + exit 1 + ;; + esac + - name: Replay against the golden hash run: cargo test -p aravath_runtime --lib replay_matches_golden_hash -- --nocapture diff --git a/aravath_runtime/src/sim.rs b/aravath_runtime/src/sim.rs index 67249a4aa0..4bd310b4d3 100644 --- a/aravath_runtime/src/sim.rs +++ b/aravath_runtime/src/sim.rs @@ -536,6 +536,9 @@ impl Greybox { self.physics .set_body_position(self.player.body, checkpoint.position); self.camera.pivot = checkpoint.position; + if checkpoint.edits.is_empty() && checkpoint.demolition == self.ground.demolition_log() { + return Ok(Vec::new()); + } self.ground .restore_dug(checkpoint.edits, &checkpoint.demolition)?; let uploads = self.ground.sync_dirty(&mut self.physics); @@ -1104,6 +1107,51 @@ mod tests { assert_eq!(loaded.state_hash(), expected); } + #[test] + fn restored_fight_hashes_like_the_source() { + let mut source = Greybox::open(0); + source.spawn_enemy(Vec3::new(4.0, 2.0, 6.0)); + source.tick = 40; + source.motor.mode = crate::motor::MotorMode::Roll; + source.motor.stamina = 61.0; + source.player.facing_yaw = 0.4; + source.combat.player_hp = 80.0; + source.combat.attack.time = 0.12; + source.combat.attack.swinging = true; + source.combat.attack.hit_landed = true; + source.combat.lock = Some(0); + source.combat.cover_broken = true; + source.combat.enemies[0].health = 17.0; + let before = source.state_hash(); + let checkpoint = source.checkpoint(); + let dir = tempfile::tempdir().unwrap(); + crate::save::save_checkpoint(dir.path(), &checkpoint).unwrap(); + let loaded = crate::save::load_checkpoint(dir.path()).unwrap(); + assert_eq!( + crate::save::gameplay_hash(&loaded), + crate::save::gameplay_hash(&checkpoint) + ); + let mut restored = Greybox::open(0); + restored.restore(loaded).unwrap(); + assert_eq!(restored.tick, 40); + assert_eq!(restored.motor.mode, crate::motor::MotorMode::Roll); + assert_eq!(restored.combat.attack.time.to_bits(), 0.12f32.to_bits()); + assert!(restored.combat.attack.swinging); + assert!(restored.combat.attack.hit_landed); + assert_eq!(restored.combat.lock, Some(0)); + assert!(restored.combat.cover_broken); + assert_eq!(restored.combat.enemies.len(), 1); + assert_eq!( + restored.combat.enemies[0].health.to_bits(), + 17.0f32.to_bits() + ); + assert_eq!( + crate::save::gameplay_hash(&restored.checkpoint()), + crate::save::gameplay_hash(&checkpoint) + ); + assert_eq!(restored.state_hash(), before); + } + #[test] fn frame_schedule_does_not_change_fixed_ticks() { let held = TickInput { diff --git a/astraweave-persistence-ecs/src/lib.rs b/astraweave-persistence-ecs/src/lib.rs index 3c8caa0fa8..f39bd027ae 100644 --- a/astraweave-persistence-ecs/src/lib.rs +++ b/astraweave-persistence-ecs/src/lib.rs @@ -98,13 +98,14 @@ fn auto_save_system(world: &mut World) { let Ok(blob) = serialize_ecs_world(world) else { return; }; + let events = replay_log(world); let hash = fnv64(&blob); for entity in managers { let Some(manager) = world.get::(entity) else { continue; }; if manager - .save_game(clock.slot, clock.tick, hash, blob.clone()) + .save_game_with_replay(clock.slot, clock.tick, hash, blob.clone(), &events) .is_err() { return; @@ -149,26 +150,33 @@ fn replay_system(world: &mut World) { let mut applied = Vec::new(); for entity in entities_to_update { - if let Some(replay) = world.get_mut::(entity) { - if replay.current_tick < replay.total_ticks { - let now = replay.current_tick; - let mut due: Vec = replay - .events - .iter() - .filter(|event| event.tick == now) - .cloned() - .collect(); - due.sort_by(|a, b| { - a.event_type - .cmp(&b.event_type) - .then_with(|| a.data.cmp(&b.data)) - }); - applied.extend(due); - replay.current_tick += 1; - } else { + let due = { + let Some(replay) = world.get_mut::(entity) else { + continue; + }; + if replay.current_tick >= replay.total_ticks { replay.is_replaying = false; + continue; } + let now = replay.current_tick; + let mut due: Vec = replay + .events + .iter() + .filter(|event| event.tick == now) + .cloned() + .collect(); + due.sort_by(|a, b| { + a.event_type + .cmp(&b.event_type) + .then_with(|| a.data.cmp(&b.data)) + }); + replay.current_tick += 1; + due + }; + for event in &due { + apply_replay_event(world, entity, event); } + applied.extend(due); } let log = world.get_resource_mut::(); if let Some(log) = log { @@ -178,6 +186,104 @@ fn replay_system(world: &mut World) { } } +/// `health` writes the first four little-endian bytes into `CHealth.hp`. +fn apply_replay_event(world: &mut World, entity: Entity, event: &ReplayEvent) { + if event.event_type.as_str() != "health" || event.data.len() < 4 { + return; + } + let hp = i32::from_le_bytes([event.data[0], event.data[1], event.data[2], event.data[3]]); + if let Some(health) = world.get_mut::(entity) { + health.hp = hp; + } +} + +fn replay_log(world: &World) -> Vec { + let query = Query::::new(world); + let mut rows = Vec::new(); + for (entity, replay) in query { + for event in &replay.events { + rows.push((entity.to_raw(), event.clone())); + } + } + rows.sort_by(|left, right| { + left.0 + .cmp(&right.0) + .then_with(|| left.1.tick.cmp(&right.1.tick)) + .then_with(|| left.1.event_type.cmp(&right.1.event_type)) + .then_with(|| left.1.data.cmp(&right.1.data)) + }); + rows.into_iter().map(|(_, event)| event).collect() +} + +fn encode_replay_events(events: &[ReplayEvent]) -> String { + events + .iter() + .map(|event| { + format!( + "{}\t{}\t{}", + event.tick, + event.event_type, + hex_encode(&event.data) + ) + }) + .collect::>() + .join("\n") +} + +fn decode_replay_events(encoded: Option<&str>) -> Vec { + let Some(encoded) = encoded else { + return Vec::new(); + }; + encoded + .lines() + .filter_map(|line| { + let mut parts = line.split('\t'); + let tick = parts.next()?.parse().ok()?; + let event_type = parts.next()?.to_string(); + let data = hex_decode(parts.next()?)?; + Some(ReplayEvent { + tick, + event_type, + data, + }) + }) + .collect() +} + +fn hex_encode(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + out.push(HEX[(byte >> 4) as usize] as char); + out.push(HEX[(byte & 0x0f) as usize] as char); + } + out +} + +fn hex_decode(text: &str) -> Option> { + if text.len() % 2 != 0 { + return None; + } + let raw = text.as_bytes(); + let mut out = Vec::with_capacity(text.len() / 2); + let mut index = 0; + while index < raw.len() { + let hi = hex_nibble(raw[index])?; + let lo = hex_nibble(raw[index + 1])?; + out.push((hi << 4) | lo); + index += 2; + } + Some(out) +} + +fn hex_nibble(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + _ => None, + } +} + impl CPersistenceManager { /// Set the current player for save operations pub fn set_player(&mut self, player_id: &str) { @@ -192,21 +298,35 @@ impl CPersistenceManager { world_hash: u64, ecs_blob: Vec, ) -> Result { - // Create companion profiles from ECS data - let companions = Vec::new(); // TODO: Query ECS for companion data + self.save_game_with_replay(slot, world_tick, world_hash, ecs_blob, &[]) + } - // Create inventory from ECS data + /// Save game state and the replay events that produced it. + pub fn save_game_with_replay( + &self, + slot: u8, + world_tick: u64, + world_hash: u64, + ecs_blob: Vec, + replay_events: &[ReplayEvent], + ) -> Result { + let companions = Vec::new(); + // `PlayerInventory` is the example slot on the bundle. No component + // stores a credit balance, so this stays zero rather than borrowing + // another field. let inventory = aw_save::PlayerInventory { - credits: 1000, // TODO: Get from ECS - items: Vec::new(), // TODO: Get from ECS + credits: 0, + items: Vec::new(), }; - // Create metadata let mut meta = HashMap::new(); meta.insert( "engine_version".to_string(), env!("CARGO_PKG_VERSION").to_string(), ); + if !replay_events.is_empty() { + meta.insert("replay".to_string(), encode_replay_events(replay_events)); + } let player_seed = self.current_player.bytes().fold(0u64, |acc, byte| { acc.wrapping_mul(0x1000_0000_01B3) @@ -241,11 +361,12 @@ impl CPersistenceManager { pub fn start_replay(&self, slot: u8) -> Result { let (bundle, _) = self.load_game(slot)?; + let events = decode_replay_events(bundle.meta.get("replay").map(String::as_str)); Ok(CReplayState { is_replaying: true, current_tick: 0, total_ticks: bundle.world.tick, - events: Vec::new(), // TODO: Load replay events from save data + events, }) } @@ -439,9 +560,13 @@ pub fn serialize_ecs_world(world: &World) -> Result> { entities.push(serialized); } + let world_tick = world + .get_resource::() + .map(|clock| clock.tick) + .unwrap_or(0); let serialized_world = SerializedWorld { entities, - world_tick: 0, // TODO: Get from world state when available + world_tick, }; // Use postcard for compact binary serialization @@ -585,6 +710,18 @@ pub fn deserialize_ecs_world(ecs_blob: &[u8], world: &mut World) -> Result<()> { } } + if let Some(clock) = world.get_resource_mut::() { + clock.tick = serialized.world_tick; + } else { + world.insert_resource(CSimClock { + world_seed: 0, + tick: serialized.world_tick, + save_every: 0, + last_saved_tick: None, + slot: 0, + }); + } + Ok(()) } diff --git a/astraweave-persistence-ecs/tests/mutation_resistant_comprehensive_tests.rs b/astraweave-persistence-ecs/tests/mutation_resistant_comprehensive_tests.rs index 293a593e44..eaddcb4360 100644 --- a/astraweave-persistence-ecs/tests/mutation_resistant_comprehensive_tests.rs +++ b/astraweave-persistence-ecs/tests/mutation_resistant_comprehensive_tests.rs @@ -981,8 +981,8 @@ fn persistence_manager_save_has_credits() { pm.save_game(0, 0, 0, vec![]).unwrap(); let (bundle, _) = pm.load_game(0).unwrap(); assert_eq!( - bundle.inventory.credits, 1000, - "hardcoded credits must be 1000" + bundle.inventory.credits, 0, + "no component stores a credit balance" ); } diff --git a/astraweave-persistence-ecs/tests/persist_replay.rs b/astraweave-persistence-ecs/tests/persist_replay.rs index f43155b0f0..5c6375c503 100644 --- a/astraweave-persistence-ecs/tests/persist_replay.rs +++ b/astraweave-persistence-ecs/tests/persist_replay.rs @@ -2,9 +2,11 @@ use std::path::PathBuf; +use astraweave_core::ecs_components::{CAmmo, CHealth}; use astraweave_ecs::{App, Plugin, Schedule, World}; use astraweave_persistence_ecs::{ - AppliedReplay, CPersistenceManager, CReplayState, CSimClock, PersistencePlugin, ReplayEvent, + deserialize_ecs_world, serialize_ecs_world, AppliedReplay, CPersistenceManager, CReplayState, + CSimClock, PersistencePlugin, ReplayEvent, SerializedWorld, }; use aw_save::{sim_save_id, SaveManager}; use sha2::{Digest, Sha256}; @@ -120,6 +122,97 @@ fn persist_replay_is_stable_and_written() { println!("persist_replay {digest}"); } +fn payload_hash(world: &SerializedWorld) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325u64; + let mix = |hash: &mut u64, bytes: &[u8]| { + for byte in bytes { + *hash ^= u64::from(*byte); + *hash = hash.wrapping_mul(0x1000_0000_01B3); + } + }; + mix(&mut hash, &world.world_tick.to_le_bytes()); + for entity in &world.entities { + if let Some(health) = entity.health { + mix(&mut hash, &health.hp.to_le_bytes()); + } + if let Some(ammo) = entity.ammo { + mix(&mut hash, &ammo.rounds.to_le_bytes()); + } + } + hash +} + +#[test] +fn restored_health_hashes_like_the_source() { + let dir = tempfile::tempdir().expect("tempdir"); + let mut app = app(); + let plugin = PersistencePlugin::new(dir.path().to_path_buf()); + plugin.build(&mut app); + let actor = app.world.spawn(); + app.world.insert(actor, CHealth { hp: 100 }); + app.world.insert(actor, CAmmo { rounds: 7 }); + app.world.insert( + actor, + CReplayState { + is_replaying: true, + current_tick: 0, + total_ticks: 1, + events: vec![ReplayEvent { + tick: 0, + event_type: "health".into(), + data: 40i32.to_le_bytes().to_vec(), + }], + }, + ); + let saver = app.world.spawn(); + app.world.insert( + saver, + CPersistenceManager { + save_manager: SaveManager::new(dir.path()), + current_player: "aravath".into(), + }, + ); + app.world.insert_resource(CSimClock { + world_seed: 0xA2A7, + tick: 8, + save_every: 1, + last_saved_tick: None, + slot: 0, + }); + app.schedule.run(&mut app.world); + assert_eq!(app.world.get::(actor).expect("health").hp, 40); + + let (bundle, _) = SaveManager::new(dir.path()) + .load_latest_slot("aravath", 0) + .expect("autosave"); + let replay = CPersistenceManager { + save_manager: SaveManager::new(dir.path()), + current_player: "aravath".into(), + } + .start_replay(0) + .expect("replay"); + assert_eq!(replay.events.len(), 1); + assert_eq!(replay.events[0].event_type, "health"); + + let source: SerializedWorld = postcard::from_bytes(&bundle.world.ecs_blob).expect("blob"); + let mut fresh = World::new(); + deserialize_ecs_world(&bundle.world.ecs_blob, &mut fresh).expect("restore"); + let again = serialize_ecs_world(&fresh).expect("reserialize"); + let restored: SerializedWorld = postcard::from_bytes(&again).expect("restored blob"); + assert_eq!(source.world_tick, 8); + assert_eq!(payload_hash(&source), payload_hash(&restored)); + assert_eq!( + restored + .entities + .iter() + .filter_map(|entity| entity.health) + .next() + .expect("hp") + .hp, + 40 + ); +} + fn hex_encode(bytes: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut out = String::with_capacity(bytes.len() * 2); diff --git a/docs/architecture/persistence_ecs.md b/docs/architecture/persistence_ecs.md index c8d6fe751f..02a2b7958e 100644 --- a/docs/architecture/persistence_ecs.md +++ b/docs/architecture/persistence_ecs.md @@ -9,7 +9,7 @@ lifecycle_status: unknown integration_status: unknown summary: "Save ids and timestamps come from the sim tick. replay_system applies due events in order. auto_save runs on CSimClock. persistence_ecs.md §1" owns: [astraweave-persistence-ecs, aw-save] -doc_version: "1.4" +doc_version: "1.5" last_verified_commit: a2474c5b7 --- @@ -25,12 +25,12 @@ last_verified_commit: a2474c5b7 |---|---| | **System name** | Persistence-ECS (save / load / migrate / replay) | | **Primary crates** | `astraweave-persistence-ecs` (ECS Plugin + world serialization + hashing); `persistence/aw-save` (file format, atomic I/O, versioning, migration) | -| **Document version** | 1.4 | +| **Document version** | 1.5 | | **Last verified against commit** | `a2474c5b7` | | **Last verified date** | 2026-05-12 | -| **Status** | Active. File format is production-shaped. `replay_system` applies due events into `AppliedReplay`. `auto_save_system` writes when `CSimClock` hits its interval. Inventory and companion extraction are still placeholders. | +| **Status** | Active. File format is production-shaped. `replay_system` applies due `health` events onto `CHealth` and records them in `AppliedReplay`. `auto_save_system` writes when `CSimClock` hits its interval and stores the replay log. `PlayerInventory.credits` stays 0: no component stores a credit balance. Companions are still empty. | | **Revision history** | 1.3 (2026-10-15): `.awsv` load rejects a declared compressed length above 4 MiB before allocation, and an LZ4 uncompressed prefix above 16 MiB. Schema stays 2. `postcard_and_lz4_bytes_are_stable` locks the postcard 1.1 and lz4_flex 0.11 bytes. 1.2 (2026-05-12): Deep investigation pass. **Closed Open Question 13** (CLI tools location) — purely factual question, comprehensively answered (`tools/aw_save_cli/` exists, was created in the same commit as `aw-save` itself). Resolution moved to §4 / §6. **New emergent finding**: a separate sibling crate `crates/astraweave-persistence-player` exists for player-profile persistence (TOML-based, distinct data model). Has zero dependency relationship with this subsystem; only a single doc-comment reference. Added to §6 as a coexisting-but-disjoint abstraction so future agents don't conflate them. Enriched §11 Q1, Q2, Q11 with commit-date provenance: the `astraweave-stress-test` declaration of both `astraweave-net-ecs` and `astraweave-persistence-ecs` and the `astraweave-memory` declaration in `astraweave-persistence-ecs/Cargo.toml` all landed in the **same commit** `08befc6ec` (2025-10-01, "phase 6 implementation"); test artifacts (`slot*.awsv`, `savegame.bin`) were committed in unrelated subsequent commits with misleading titles.

1.1 (2026-05-12): Verification pass. **Major corrections**: (1) The §4 `[INFERRED]` claim that CLI tools "may live elsewhere or be planned" was wrong — `tools/aw_save_cli/src/main.rs` (110 lines, clap-based) is a real binary that consumes `aw-save`. Added to §4 downstream table; resolved the marker. (2) Discovered second `aw-save` consumer not previously documented: `examples/save_integration/src/main.rs` (234 lines) imports `aw-save` types directly. Added to §4. (3) Resolved §9 `[INFERRED]` about auto-pruning absence — direct grep `fs::remove\|remove_file\|tokio::fs::remove persistence/aw-save/src` returns zero matches, conclusively confirming no auto-prune path exists. (4) Verified `Entity::to_raw()` layout claim in §3 against actual source at `astraweave-ecs/src/entity_allocator.rs:95-103` — claim is exact. | -| **Owner notes** | `aw-save` (file format and SaveManager) is fully production-shaped: atomic writes via tmp+fsync+rename, CRC32 + LZ4, explicit V1→V2 migration, 256 slots per player. Save ids and timestamps come from the sim (`sim_save_id`, `sim_timestamp`). `auto_save_system` writes when `CSimClock` hits its interval. `replay_system` copies due events into `AppliedReplay` in canonical order. `CPersistenceManager::save_game` still hardcodes inventory (`credits: 1000`, `items: []`) and emits zero companions. **`astraweave-stress-test/Cargo.toml:21` declares `astraweave-persistence-ecs` as a dep but no source file imports anything from it** — same pattern as `net-ecs` (declared-but-unused). The companion `astraweave-memory` workspace dep declared at `astraweave-persistence-ecs/Cargo.toml:20` is also never imported in the crate's source. | +| **Owner notes** | `aw-save` (file format and SaveManager) is fully production-shaped: atomic writes via tmp+fsync+rename, CRC32 + LZ4, explicit V1→V2 migration, 256 slots per player. Save ids and timestamps come from the sim (`sim_save_id`, `sim_timestamp`). `auto_save_system` writes when `CSimClock` hits its interval. `replay_system` copies due events into `AppliedReplay` in canonical order. `CPersistenceManager::save_game` writes `PlayerInventory.credits` as 0 because no component stores a credit balance, and still emits zero companions. **`astraweave-stress-test/Cargo.toml:21` declares `astraweave-persistence-ecs` as a dep but no source file imports anything from it** — same pattern as `net-ecs` (declared-but-unused). The companion `astraweave-memory` workspace dep declared at `astraweave-persistence-ecs/Cargo.toml:20` is also never imported in the crate's source. | --- @@ -623,7 +623,7 @@ Auto-save path (scaffolded, empty body): | 13 | Atomic write uses tmp file + sync_all + rename | Yes | `aw-save/lib.rs:275-286`. | | 14 | `index.json` is sorted by `(slot, created_at)` after each save | Yes | `aw-save/lib.rs:225`. | | 15 | Sanitized player_id only contains `[A-Za-z0-9_-]` | Yes | `aw-save/lib.rs:342-352` — all other characters become `_`. | -| 16 | Save bundle's `save_id` is unique per save call (new `Uuid::v4()`) | Yes (probabilistic) | `persistence-ecs/lib.rs:138`, `aw-save/lib.rs:186` (migration). Uuid v4 collision probability is negligible. | +| 16 | Save bundle's `save_id` and `created_at` come from `sim_save_id` / `sim_timestamp` | Yes | `aw-save` `sim_save_id`, `persistence-ecs` `save_game_with_replay`. The same seed, tick, and slot rewrite the same id. | --- @@ -715,6 +715,8 @@ Auto-save path (scaffolded, empty body): ## 12. Maintenance Notes +**Revision 1.5 (2026-10-18):** `replay_system` writes due `health` events onto `CHealth`. `SerializedWorld.world_tick` comes from `CSimClock`. Autosave stores the replay log, and `start_replay` loads it. `PlayerInventory.credits` stays 0 because no component stores a credit balance. + **Revision 1.4 (2026-10-16):** save filenames use `bundle.created_at`. `sim_save_id` / `sim_timestamp` replace `Uuid::new_v4` and `OffsetDateTime::now_utc` on the persistence and greybox paths. `replay_system` applies due events. `auto_save_system` follows `CSimClock`. Entity blobs are sorted by `Entity::to_raw`. **Update this doc when:**