fabrilis/crates/core/tests/determinism.rs
loki5512344 878d144b77 Initial commit: Fabrilis docs, rules and deterministic core
Docs (architecture, decisions, coupling, determinism, UI, references), code rules enforced by tools/limits, deterministic core with units, time, math, sched, snapshot, vec and rng, plus smoke tests. ref/ stays out of git.
2026-11-16 23:06:29 +01:00

69 lines
1.8 KiB
Rust

//! Determinism golden test: the trajectory hash must not change between runs,
//! operating systems or versions. If it changed on purpose, update GOLDEN and explain why in the commit.
#![allow(
clippy::unwrap_used,
reason = "test helper: a failure should abort the test"
)]
use std::cell::RefCell;
use std::rc::Rc;
use fabrilis_core::fidelity::{Fidelity, Mode};
use fabrilis_core::math;
use fabrilis_core::sched::{Scheduler, Subsystem};
use fabrilis_core::snapshot::hash::StateHasher;
use fabrilis_core::time::{SimDelta, SimTime};
const GOLDEN: u64 = 0xdd62_00fc_171e_65e1;
struct Oscillator {
id: u64,
phase: f64,
hasher: Rc<RefCell<StateHasher>>,
}
impl Subsystem for Oscillator {
fn name(&self) -> &'static str {
"oscillator"
}
fn step(&mut self, now: SimTime, dt: SimDelta) {
let dt = dt.as_seconds().get();
self.phase += dt * 50.0 * math::exp(-self.phase * 0.001);
let value = math::sin(self.phase) * math::cos(self.phase * 0.5);
let mut h = self.hasher.borrow_mut();
h.write_u64(self.id);
h.write_u64(now.nanos());
h.write_f64(value);
}
}
fn run(mode: Mode, epochs: u64) -> u64 {
let fidelity = Fidelity::for_mode(mode);
let hasher = Rc::new(RefCell::new(StateHasher::new()));
let mut s = Scheduler::new(fidelity.epoch()).unwrap();
for (id, period) in [(0, fidelity.physics_step), (1, fidelity.analog_step)] {
let sub = Oscillator {
id,
phase: 0.1,
hasher: Rc::clone(&hasher),
};
s.add(Box::new(sub), period).unwrap();
}
s.run_epochs(epochs);
hasher.borrow().finish()
}
#[test]
fn repeated_runs_are_identical() {
for mode in [Mode::Bench, Mode::Lab, Mode::World] {
assert_eq!(run(mode, 50), run(mode, 50), "{mode:?}");
}
}
#[test]
fn world_trajectory_matches_golden() {
let hash = run(Mode::World, 250);
assert_eq!(hash, GOLDEN, "новый хеш: {hash:#018x}");
}