Files
airdef/airdef-mod/tests/saturation.rs
T
chexit b796a439df
build / mod (push) Failing after 31s
Restore the saturated intercept count by uncueing the embedded radar (#145)
The heavy WASM scenario (wasm_flat_budget, 64 integrated complexes vs two
`airdef wave oreshnik 40 2600`) lost intercepts at the tick-2102 checkpoint:
522 (main) -> 302 (#133) -> 243 (#134). Decomposed by A/B on one fixture, one
host (2bcce64), one SDK, each slice built from its own commit:

- 522 -> 302 (#133): Track.vel became an estimate from noisy measured places
  (it was the target's true velocity); the forecast, the aim lead and the
  interceptor's launch Fix all read it. Forcing the class estimate to Unknown
  leaves the count unchanged (native 296 ~= 294), so class/roles is not the
  cause. The pre-#133 522 used the target's true velocity, which the #133
  contract "class and speed only from measurements" forbids; this portion is
  the intentional cost of honest measurement-only tracks and is kept.

- 302 -> 243 (#134): the network cue was extended from the separate engagement
  radar to every fire-quality radar, including each weapon's embedded radar.
  Cueing every relayed contact each tick flooded the embedded fire control with
  one-tick plots whose noisy velocity degraded guidance. Restricting the cue
  back to separate radars recovers the whole drop: 243 -> 325.

- own_fire_within / FIRE_QUALITY / channels are NOT causes here: relaxing the
  own-fire gate or the channel limit each changed nothing (243 -> 243). Embedded
  radars always measure Fire plots of quality >= 64 and have no channel limit.

- #140 does not affect this loadout, by fact: the fixture deploys no separate
  radar, so every profile is embedded with channels = 0; the channel-age bug
  binds only where a profile has channels, and the channels-off A/B was flat.

Fix: the cue looks only through a separate fire-quality radar
(sam.kind == SamKind::Radar); the embedded radar keeps its beam/revisit/lock
acquisition as before #134. All radar profiles, channel limits, own-fire
authority and the measurement-only class/speed contract are preserved; no
target truth is injected.

Measured after the fix (WASM, fuel budget 300M/tick): checkpoint 325 intercepts
/ 2011 hits, fuel max 118M; final (tick 3302, two late Smart raids) 385 / 2472,
fuel max 176M; zero fuel failures. The first late raid reports the #135 recon
flight ("Разведка противника: впереди налёта высланы разведчики"); the second
is silent (recon budget spent) — the fixture now expects exactly that instead
of the stale empty chat that stopped the scenario.

Tests:
- airdef-mod/tests/saturation.rs: deterministic native replica of the checkpoint
  (same sim, host block tracer) asserting the restored count and a regression
  threshold, plus the #140 loadout fact (no separate radar, channels = 0).
- Sim::launch_audit (why.rs): on-demand tolerance diagnostic counting why each
  (system, drone) pair holds fire — no track / stale / no authority / role /
  doctrine / reach / claimed / not ready / not aimed / terrain / ready.
- sensor_tests: a network plot cues a separate fire radar but not the embedded one.
- wasm_flat_budget baselines re-measured with provenance comments; the asserted
  fixture SHA in tools/airdef.py updated.

Verification: `python3 tools/airdef.py test-budgets` passes both stages and the
two late raids (283 steps, fuel failures = 0). airdef-core 292 + 8, mod lib 104,
mod scenarios 5, saturation 2 — all green. A/B record:
docs/measurements/issue-145-intercept-regression.json.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>

Integration note (shipped engine 8e711f969): the tick-2102 checkpoint baseline is
unchanged and passes on the shipped engine (325 intercepts / 2011 hits). The final
stats baseline was re-measured on the shipped engine with #146 integrated (one
knowledge snapshot per Smart order changes the two late raids): 414 / 2463, world
8885 sections / 420671 rays / 3442845 cells. The asserted fixture SHA in
tools/airdef.py was updated to match. python3 tools/airdef.py test-budgets passes
all 283 steps with zero fuel failures (tick max 184608537 / 300000000).
2026-11-21 10:32:11 +03:00

171 lines
8.2 KiB
Rust

//! The saturation regression (#145): a deterministic native replica of the WASM budget
//! scenario's checkpoint (`tests/budgets/wasm_flat_budget.toml`, tick 2102). 64 integrated
//! complexes stand where `/airdef deploy` puts them (8 blocks south of the player at the world
//! origin), two `airdef wave oreshnik 40 2600` orders 100 ticks apart, flat land at y=64, the
//! engine's own seed for the first morning. The render answers are produced exactly as the WASM
//! test host produces them (`horizon_mods::world_query::trace`, the same section fill), so the
//! replica replays the same fight the heavy run measures. It exists to explain and guard the
//! intercept count under saturation: the counters and `Sim::launch_audit` say why the systems
//! hold their fire, which the fuel-bound WASM run cannot afford to diagnose per tick.
//!
//! Run: `cargo test --test saturation -- --nocapture`.
use airdef::sim::world::{Fill, RayReply, SectionAnswer};
use airdef::sim::{Aim, Approach, DroneKind, Ground, Out, RaidOrder, Sam, SamKind, Sim};
use glam::DVec3;
use horizon_mods::world_query::{self, BlockProbe, Cell, Trace};
/// The seed the mod derives on the first tick of a fresh world (`open_world`, game_time 1).
const SEED: u64 = 1u64.wrapping_mul(2654435761) ^ 0x9e37;
/// Where the test player stands, and where every deploy lands (`deploy_configured`: 8 blocks ahead).
const PLAYER: DVec3 = DVec3::new(0.5, 64.0, 0.5);
const DEPLOY_AT: DVec3 = DVec3::new(0.5, 64.0, 8.5);
const GROUND_Y: i32 = 64;
/// The fixture's deploy order: nine rounds of seven kinds, then one more S-400 (64 complexes).
const KINDS: [SamKind; 7] = [SamKind::S400, SamKind::Patriot, SamKind::Pantsir, SamKind::Gepard, SamKind::Nasams, SamKind::IrisT, SamKind::Tor];
/// The checkpoint the WASM fixture asserts at step 271.
const CHECKPOINT: u64 = 2102;
/// The flat world the test host answers from: solid below `GROUND_Y`, air above.
struct Flat;
impl BlockProbe for Flat {
fn cell(&mut self, _x: i32, y: i32, _z: i32) -> Cell<'_> {
if y < GROUND_Y { Cell::Solid(None) } else { Cell::Empty }
}
}
/// A section's fill, exactly as `answer_flat_world` computes it.
fn section_fill(sec: (i32, i32, i32)) -> SectionAnswer {
let base = i64::from(sec.1) * 16;
let solid = (i64::from(GROUND_Y) - base).clamp(0, 16) as usize;
let fill = match solid {
0 => Fill::Empty,
16 => Fill::Full,
_ => {
let mut bits = [0u8; 512];
bits[..solid * 32].fill(255);
Fill::Mixed(Box::new(bits))
}
};
SectionAnswer { sec, fill }
}
/// A ray's reply, exactly as `answer_flat_world` traces it.
fn ray_reply(id: u32, a: DVec3, b: DVec3) -> RayReply {
match world_query::trace(&mut Flat, [a.x, a.y, a.z], [b.x, b.y, b.z]) {
Trace::Clear => RayReply { id, clear: true, hit: false, fraction: 1.0, normal: [0; 3], block: [0; 3] },
Trace::Hit { fraction, normal, block } => RayReply { id, clear: false, hit: true, fraction, normal, block },
Trace::Unknown { .. } => RayReply { id, clear: false, hit: false, fraction: 0.0, normal: [0; 3], block: [0; 3] },
}
}
fn order(sim: &mut Sim, out: &mut Out) -> u32 {
let o = RaidOrder { kinds: vec![(DroneKind::Oreshnik, 40)], approach: Approach::Sector, dist: 2600.0, aim: Aim::Objects };
sim.order_raid(&o, &[PLAYER], out)
}
fn deploy(sim: &mut Sim) {
for _ in 0..9 {
for kind in KINDS {
let id = sim.id();
sim.sams.push(Sam::new(id, kind, DEPLOY_AT, std::f64::consts::PI));
sim.settle(id);
}
}
let id = sim.id();
sim.sams.push(Sam::new(id, SamKind::S400, DEPLOY_AT, std::f64::consts::PI));
sim.settle(id);
assert_eq!(sim.sams.len(), 64);
}
/// Steps the replica to `ticks`, ordering the two waves and the HD effects where the fixture does,
/// and answering render queries one tick later exactly as the WASM host does.
fn run_to(ticks: u64) -> Sim {
let mut sim = Sim::new(SEED);
let mut ground = Ground::default();
let mut out = Out::default();
let mut columns: Vec<(i32, i32, i32)> = Vec::new();
let mut sections: Vec<SectionAnswer> = Vec::new();
let mut rays: Vec<RayReply> = Vec::new();
let mut changes_epoch = 0u32;
for now in 1..=ticks {
// Commands run between ticks: deploys and the first wave after tick 2, the second after
// tick 102, `airdef shader hd` after tick 1102 (effects only, but kept exact).
if now == 3 {
deploy(&mut sim);
assert!(order(&mut sim, &mut out) > 0, "the first wave was refused");
}
if now == 103 {
assert!(order(&mut sim, &mut out) > 0, "the second wave was refused (the first still planning)");
}
if now == 1103 {
sim.shader = true;
}
// The mod's tick reads the previous tick's answers at the clock it had then (sim.tick).
let now0 = sim.tick;
ground.world.changed_rev(changes_epoch, 0, false, &[]);
ground.answer(std::mem::take(&mut columns), now0);
ground.world.answer(std::mem::take(&mut sections), now0);
ground.world.answer_rays(&std::mem::take(&mut rays));
sim.day_time = Some(now);
sim.night = (13000..23000).contains(&(now % 24000));
out = Out::default();
sim.step(&mut ground, Some(PLAYER), &mut out);
// The queries this tick asks; the host answers them before the next tick.
columns = ground.take_wanted().into_iter().map(|(x, z)| (x, z, GROUND_Y)).collect();
let _chunks = ground.take_chunks();
let rq = ground.world.take_rays(now);
let sq = ground.world.take_wanted(now);
if !rq.is_empty() || !sq.is_empty() {
changes_epoch = 1;
}
rays = rq.into_iter().map(|(id, a, b)| ray_reply(id, a, b)).collect();
sections = sq.into_iter().map(section_fill).collect();
}
sim
}
/// The restored checkpoint, measured on this native replica with the #145 fix in place. The WASM
/// budget fixture measures 325 intercepts / 2011 hits at the same tick on the same fix; the replica
/// replays the same fight but answers render rays with the host tracer one tick later, and the
/// combat is chaotic, so its counters sit a few apart (314 / 2022). Both are deterministic; the
/// WASM run is the authoritative fuel/perf measurement, this one the fast fight-and-audit guard.
const REPLICA_KILLS: u32 = 314;
const REPLICA_HITS: u32 = 2022;
const REPLICA_AIRBORNE: usize = 184;
#[test]
fn checkpoint_replica_holds_the_restored_intercept_count() {
let sim = run_to(CHECKPOINT);
let airborne = sim.drones.iter().filter(|d| d.alive()).count();
eprintln!(
"checkpoint tick {}: airborne {airborne}, missiles {}, kills {}, hits {}, fired {}",
sim.tick,
sim.missiles.len(),
sim.kills,
sim.hits,
sim.sams.iter().map(|s| s.fired).sum::<u32>()
);
eprintln!("tally: {}", sim.tally.text());
eprintln!("audit: {}", sim.launch_audit().text());
assert_eq!(airborne, REPLICA_AIRBORNE, "the sky at the checkpoint");
assert_eq!(sim.kills, REPLICA_KILLS, "intercepts at the checkpoint (deterministic replica baseline)");
assert_eq!(sim.hits, REPLICA_HITS, "hits at the checkpoint");
// The regression guard: the #134 embedded-cue flood dropped this replica to 247 intercepts
// (the WASM run to 243). Restored, it must stay well above that broken count.
assert!(sim.kills >= 300, "the intercept count fell back toward the #145 regression: {}", sim.kills);
}
#[test]
fn the_saturation_loadout_has_no_separate_radar_channels_to_hold() {
// #140 (stale own fire channels held by network relays) is a separate-radar bug: it binds only
// where a profile has channels. This loadout deploys integrated complexes alone — every radar
// is the weapon's embedded one, whose profile has no channel limit — so #140 cannot affect it.
// Fact, not assumption: the A/B that relaxed the channel limit changed nothing (243 -> 243).
let sim = run_to(CHECKPOINT);
assert_eq!(sim.sams.len(), 64);
for s in &sim.sams {
assert_ne!(s.kind, SamKind::Radar, "the fixture deploys no separate radar");
assert_eq!(s.radar_profile().channels, 0, "an embedded radar has no channel limit");
}
}