Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions .github/workflows/aravath-determinism.yml
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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
48 changes: 48 additions & 0 deletions aravath_runtime/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Comment on lines +539 to +540

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Rebuild terrain when restoring an empty checkpoint

When a pristine checkpoint is loaded into the already-running Greybox after place_sphere or another edit that does not change the demolition log, this condition is true even though self.ground.edits is nonempty. Returning here skips restore_dug and sync_dirty, so the loaded game retains the newer voxel edits, meshes, and collision bodies instead of restoring the saved terrain; only skip rebuilding after also confirming the current edit log is empty/equivalent. .github/copilot-instructions.mdL32-L32

Useful? React with 👍 / 👎.

}
self.ground
.restore_dug(checkpoint.edits, &checkpoint.demolition)?;
let uploads = self.ground.sync_dirty(&mut self.physics);
Expand Down Expand Up @@ -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 {
Expand Down
189 changes: 163 additions & 26 deletions astraweave-persistence-ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<CPersistenceManager>(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;
Expand Down Expand Up @@ -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::<CReplayState>(entity) {
if replay.current_tick < replay.total_ticks {
let now = replay.current_tick;
let mut due: Vec<ReplayEvent> = 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::<CReplayState>(entity) else {
continue;
};
if replay.current_tick >= replay.total_ticks {
replay.is_replaying = false;
continue;
}
let now = replay.current_tick;
let mut due: Vec<ReplayEvent> = 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::<AppliedReplay>();
if let Some(log) = log {
Expand All @@ -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::<CHealth>(entity) {
health.hp = hp;
}
}

fn replay_log(world: &World) -> Vec<ReplayEvent> {
let query = Query::<CReplayState>::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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve per-entity replay targets

When more than one entity owns a CReplayState, this conversion discards the entity ID after sorting, so the saved metadata cannot associate events with their original actors. start_replay then returns one flattened CReplayState, and apply_replay_event writes every due health event to whichever entity carries that state, causing multi-actor replays to produce incorrect health state; persist a target identifier and remap it during restoration instead of dropping it here. .github/copilot-instructions.mdL40-L40

Useful? React with 👍 / 👎.

}

fn encode_replay_events(events: &[ReplayEvent]) -> String {
events
.iter()
.map(|event| {
format!(
"{}\t{}\t{}",
event.tick,
event.event_type,
hex_encode(&event.data)
)
})
.collect::<Vec<_>>()
.join("\n")
}

fn decode_replay_events(encoded: Option<&str>) -> Vec<ReplayEvent> {
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<Vec<u8>> {
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<u8> {
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) {
Expand All @@ -192,21 +298,35 @@ impl CPersistenceManager {
world_hash: u64,
ecs_blob: Vec<u8>,
) -> Result<PathBuf> {
// 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<u8>,
replay_events: &[ReplayEvent],
) -> Result<PathBuf> {
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)
Expand Down Expand Up @@ -241,11 +361,12 @@ impl CPersistenceManager {
pub fn start_replay(&self, slot: u8) -> Result<CReplayState> {
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,
})
}

Expand Down Expand Up @@ -439,9 +560,13 @@ pub fn serialize_ecs_world(world: &World) -> Result<Vec<u8>> {
entities.push(serialized);
}

let world_tick = world
.get_resource::<CSimClock>()
.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
Expand Down Expand Up @@ -585,6 +710,18 @@ pub fn deserialize_ecs_world(ecs_blob: &[u8], world: &mut World) -> Result<()> {
}
}

if let Some(clock) = world.get_resource_mut::<CSimClock>() {
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(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
);
}

Expand Down
Loading
Loading