Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat(combat): use core SimRng and join the replay gate
PR #211 added astraweave_core::SimRng and no Fixed64. Combat re-exports
the RNG, keeps the Q32.32 type, and leaves both golden hashes unchanged.
combat_resolve is a required case of determinism-replay.yml.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 15, 2026
commit f4be45931e248646b2fdd60f5582ca3d724f5011
79 changes: 0 additions & 79 deletions .github/workflows/combat-replay.yml

This file was deleted.

40 changes: 36 additions & 4 deletions .github/workflows/determinism-replay.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# Required status check on pull requests: `determinism-replay / compare`.
# Branch protection is a repository setting. This workflow is the check it must require.
# `planner_pure` (WS-D0), `perception_world` (WS-D1), `gameplay_rng` (WS-D2),
# and `fixed64` fail the compare job on any mismatch or if the case is missing.
# No path filter. cargo test has no retry loop (no-retry). Do not switch this job to nextest.
# `fixed64`, and `combat_resolve` fail the compare job on any mismatch or if
# the case is missing. No path filter. cargo test has no retry loop (no-retry).
# Do not switch this job to nextest.

name: determinism-replay

Expand Down Expand Up @@ -62,7 +63,38 @@ jobs:
esac

- name: Replay hash
run: cargo test -p astraweave-core --test replay_hash -- --nocapture
run: |
cargo test -p astraweave-core --test replay_hash -- --nocapture
cargo test -p astraweave-combat --test replay_hash -- --nocapture

- name: Merge replay hashes
run: |
node <<'JS'
const fs = require("fs");
const path = require("path");
const root = process.env.CARGO_TARGET_DIR || "target";
const core = JSON.parse(fs.readFileSync(path.join(root, "replay-hash.json"), "utf8"));
const combat = JSON.parse(fs.readFileSync(path.join(root, "replay-hash-combat.json"), "utf8"));
const seen = new Set(core.map((row) => row.case));
const merged = core.slice();
for (const row of combat) {
if (seen.has(row.case)) {
console.error(`duplicate replay case ${row.case}`);
process.exit(1);
}
merged.push(row);
}
const required = ["planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve"];
const names = new Set(merged.map((row) => row.case));
for (const name of required) {
if (!names.has(name)) {
console.error(`missing required case ${name}`);
process.exit(1);
}
}
fs.writeFileSync(path.join(root, "replay-hash.json"), JSON.stringify(merged, null, 2) + "\n");
console.log("merged", merged.map((row) => `${row.case} ${row.sha256}`).join("\n"));
JS

- name: Upload replay hash
uses: actions/upload-artifact@v4
Expand Down Expand Up @@ -91,7 +123,7 @@ jobs:
import sys
from pathlib import Path

required = {"planner_pure", "perception_world", "gameplay_rng", "fixed64"}
required = {"planner_pure", "perception_world", "gameplay_rng", "fixed64", "combat_resolve"}
root = Path("replay-artifacts")
files = sorted(root.glob("*/replay-hash.json"))
print(f"artifacts: {[str(p) for p in files]}")
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions astraweave-combat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ publish.workspace = true
description = "Deterministic Q32.32 damage dealt and damage received"

[dependencies]
astraweave-core = { path = "../astraweave-core" }
astraweave-ecs = { path = "../astraweave-ecs" }
rand = { workspace = true }
ron = "0.8"
Expand Down
2 changes: 1 addition & 1 deletion astraweave-combat/src/ecs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ impl Plugin for CombatPlugin {
app.world.insert_resource(CombatScratch::default());
app.world.insert_resource(CombatWriteGate::default());
app.world.insert_resource(LoadedTables::default());
app.add_system("simulation", combat_resolve_system);
app.add_system_known_stage("simulation", combat_resolve_system);
}
}

Expand Down
16 changes: 8 additions & 8 deletions astraweave-combat/src/fixed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
//!
//! # Seam
//!
//! This is a local copy of `astraweave-veil`'s `Fixed64` on
//! `cursor/aravath-greybox-b3de` (`fixed.rs`). That crate is not on `main`,
//! and this change does not merge it. Arithmetic is the veil contract:
//! `SCALE = 1 << 32`, multiply through `i128`, division truncates toward
//! zero, `den == 0` yields zero, overflow saturates to `i64`.
//! PR #211 (`main` `85d09a2c`) added `astraweave_core::SimRng` and did not
//! add a fixed-point type. This module remains the Q32.32 implementation.
//! Arithmetic is unchanged from the previous local copy, which matched the
//! veil contract: `SCALE = 1 << 32`, multiply through `i128`, division
//! truncates toward zero, `den == 0` yields zero, overflow saturates to `i64`.
//!
//! When one `Fixed64` exists in `astraweave-math` (or veil re-exports that
//! type), delete this module and re-export it. Do not let the two copies drift.
//! The lock tests below are the drift alarm.
//! When one `Fixed64` exists on `main`, delete this module and re-export it.
//! The golden stage hash and the battle digest are the check that the move
//! did not change a bit. The lock tests below are the drift alarm.

use serde::{Deserialize, Serialize};

Expand Down
6 changes: 3 additions & 3 deletions astraweave-combat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
//!
//! # Seams
//!
//! [`fixed`] copies veil `Fixed64` until that type lives in one crate.
//! [`sim_rng`] copies `astraweave_core::sim::SimRng` from PR #211 until that
//! API is on `main`. Neither branch is merged here.
//! [`sim_rng`] re-exports `astraweave_core::SimRng` (PR #211, `main` `85d09a2c`).
//! [`fixed`] is still local: that merge did not add a Q32.32 type. The
//! arithmetic is unchanged, so the golden hashes are the same bytes.

mod ecs;
mod fixed;
Expand Down
2 changes: 2 additions & 0 deletions astraweave-combat/src/logic_tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::collections::{BTreeMap, HashMap};

use rand::RngCore;

use super::*;
use crate::resolve::{AttackerView, BlockGate, DefenderView, ImmuneGate, Modifier, ModifierKind};

Expand Down
1 change: 1 addition & 0 deletions astraweave-combat/src/property_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use proptest::prelude::*;
use proptest::test_runner::{Config, RngSeed, TestRunner};
use rand::RngCore;

use super::*;
use crate::resolve::{AttackerView, BlockGate, DefenderView, ImmuneGate, Modifier, ModifierKind};
Expand Down
1 change: 1 addition & 0 deletions astraweave-combat/src/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::tables::{
USER_MOD_ID_LIMIT,
};
use crate::CombatError;
use rand::RngCore;

pub const DRAW_COUNT: usize = 4;
const STEP_CAP: usize = 20;
Expand Down
112 changes: 14 additions & 98 deletions astraweave-combat/src/sim_rng.rs
Original file line number Diff line number Diff line change
@@ -1,92 +1,16 @@
//! Local `SimRng` seam.
//! Combat hit streams on the canonical [`astraweave_core::SimRng`].
//!
//! # Seam
//! `main` at `85d09a2c` (PR #211) owns `mix_sim_seed` and `SimRng`. This
//! module does not copy them. `hit_rng` is the only extra fold: it builds a
//! `system_id` and then calls `SimRng::new`, which performs the one mix.
//!
//! `astraweave_core::sim::SimRng` lives on `cursor/engine-ws-d2-stab` (PR #211)
//! and is not on `main`. This module copies the integer mix and the
//! `StdRng` (ChaCha12) wrapper so combat does not merge that branch.
//!
//! `mix_sim_seed(1, 2, 3)` is locked to `0x5991_344E_4904_5002`, the same
//! vector as core and as `astraweave-weaving` on that branch.
//!
//! When PR #211 lands, delete this file and call `astraweave_core::sim::SimRng`.
//! `hit_rng` must stay the only extra mix: `SimRng::new` already mixes
//! `(world_seed, tick, system_id)`. Do not mix a second time in the caller.
//!
//! This copy does not expose a float draw. Combat draws `u32` only.

use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};
//! `Fixed64` is not in that merge. The combat crate still owns the Q32.32
//! type in `fixed.rs`. Its arithmetic was not changed when the RNG moved,
//! so the golden stage hash and the battle digest stay the same bytes.

/// Combat hit streams. Does not collide with the d2 system ids.
pub const SIM_SYSTEM_COMBAT: u64 = 0xC0BA_7001;

/// Mix `(world_seed, tick, system_id)` into one `StdRng` seed.
///
/// Integer-only. The same triple produces the same `u64` on every OS.
pub fn mix_sim_seed(world_seed: u64, tick: u64, system_id: u64) -> u64 {
let mut z = world_seed
.wrapping_add(0x9E37_79B9_7F4A_7C15)
.wrapping_mul(tick ^ 0xBF58_476D_1CE4_E5B9)
.wrapping_add(system_id.rotate_left(17));
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}

/// Explicit sim stream. Draws are ChaCha12 via `StdRng`.
pub struct SimRng {
inner: StdRng,
world_seed: u64,
tick: u64,
system_id: u64,
}

impl SimRng {
pub fn new(world_seed: u64, tick: u64, system_id: u64) -> Self {
Self {
inner: StdRng::seed_from_u64(mix_sim_seed(world_seed, tick, system_id)),
world_seed,
tick,
system_id,
}
}

pub fn world_seed(&self) -> u64 {
self.world_seed
}

pub fn tick(&self) -> u64 {
self.tick
}

pub fn system_id(&self) -> u64 {
self.system_id
}

pub fn next_u32(&mut self) -> u32 {
RngCore::next_u32(&mut self.inner)
}
}

impl RngCore for SimRng {
fn next_u32(&mut self) -> u32 {
self.inner.next_u32()
}

fn next_u64(&mut self) -> u64 {
self.inner.next_u64()
}

fn fill_bytes(&mut self, dest: &mut [u8]) {
self.inner.fill_bytes(dest)
}
}
pub use astraweave_core::{mix_sim_seed, SimRng, SIM_SYSTEM_COMBAT};

/// One stream per hit. Ordinal is the index in the sorted batch.
///
/// `SimRng::new` performs the only mix. `system_id` folds the combat id,
/// the ordinal, and the attack id so two hits in one tick do not share draws.
pub fn hit_rng(world_seed: u64, tick: u64, ordinal: u64, attack_id: u64) -> SimRng {
let system = SIM_SYSTEM_COMBAT
.wrapping_add(ordinal.wrapping_mul(0x9E37_79B9_7F4A_7C15))
Expand All @@ -97,25 +21,17 @@ pub fn hit_rng(world_seed: u64, tick: u64, ordinal: u64, attack_id: u64) -> SimR
#[cfg(test)]
mod tests {
use super::*;
use rand::RngCore;

#[test]
fn mix_matches_core_contract() {
fn reexport_matches_the_core_mix_vector() {
assert_eq!(mix_sim_seed(1, 2, 3), 0x5991_344E_4904_5002);
}

#[test]
fn same_triple_same_bits() {
let mut a = SimRng::new(9, 4, SIM_SYSTEM_COMBAT);
let mut b = SimRng::new(9, 4, SIM_SYSTEM_COMBAT);
assert_eq!(a.next_u32(), b.next_u32());
}

#[test]
fn streams_diverge() {
let a = SimRng::new(1, 0, SIM_SYSTEM_COMBAT).next_u32();
let b = hit_rng(1, 0, 0, 1).next_u32();
let c = hit_rng(1, 0, 1, 1).next_u32();
assert_ne!(b, c);
let _ = a;
fn streams_diverge_across_ordinal() {
let mut a = hit_rng(1, 0, 0, 1);
let mut b = hit_rng(1, 0, 1, 1);
assert_ne!(a.next_u32(), b.next_u32());
}
}
7 changes: 4 additions & 3 deletions astraweave-combat/tests/replay_hash.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Seeded multi-entity battle. The digest is SHA-256 of little-endian
//! Q32.32 raw bits (the integer form of `to_bits`) after entity ids are sorted.
//!
//! Writes `target/replay-hash.json` for the three-OS compare job.
//! Writes `target/replay-hash-combat.json`. The determinism-replay job
//! merges that file with core's `replay-hash.json` before the three-OS compare.

use std::path::PathBuf;

Expand Down Expand Up @@ -169,12 +170,12 @@ fn digest(fighters: &[Fighter]) -> String {

fn replay_path() -> PathBuf {
if let Ok(dir) = std::env::var("CARGO_TARGET_DIR") {
return PathBuf::from(dir).join("replay-hash.json");
return PathBuf::from(dir).join("replay-hash-combat.json");
}
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.pop();
path.push("target");
path.push("replay-hash.json");
path.push("replay-hash-combat.json");
path
}

Expand Down
2 changes: 2 additions & 0 deletions astraweave-core/src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub const SIM_SYSTEM_ENEMY_PATROL: u64 = 0xAE11_7002;
pub const SIM_SYSTEM_SPAWNER: u64 = 0xAE11_7003;
/// Terrain solver distance rolls. The solver stores the mixed `u64`.
pub const SIM_SYSTEM_TERRAIN_SOLVER: u64 = 0x7E22_7001;
/// Combat hit streams. `astraweave-combat` folds ordinal and attack id into this.
pub const SIM_SYSTEM_COMBAT: u64 = 0xC0BA_7001;

/// Mix `(world_seed, tick, system_id)` into one `StdRng` seed.
///
Expand Down
Loading