Files
airdef/airdef-mod/tests/ground_oom.rs
T
chexit 5737b47dc5
build / mod (push) Failing after 59s
record: thin track points on the caller's grid; extreme-load test; re-pin the stale budget stats
The points budget first gated on (recording tick - first) % step, but a strike
carrier's samples fall on its flight-age grid, offset from the recording's
ticks — the gate skipped them (physical_strike_track_keeps_muzzle... failed).
Count the sampling calls per track instead (Track::due): at STEP it pushes
every call exactly as before, and the thinning doubles the interval without
touching the track's phase. Track::points_len exposes the count for diagnostics.

tests/ground_oom.rs gains the continuous extreme load (eight overlapping
40-Oreshnik waves, 1118 objects airborne at once — well past the crash's >200):
peak 26.3 MiB steady + 5.5 MiB rehash transient, the flight tracks thin to
step 16 (91k points, 2.3 MiB) under their 2 MiB budget, the journal and poses
stay within theirs, and the fight still resolves (157 intercepts). The radar
picture itself (11.5 MiB at 1118 airborne) scales with the sky — it is the
simulation's state, not a cache, and is ~3 MiB at the crash's >200 load.

The WASM budget fixture's final /airdef stats pin was stale at the base commit
already: it was measured on engine 8e711f969, and the base pins acfb379aa,
whose host answers shift the two late Smart raids (417/2463, 7 in the air).
Verified identical on the pristine base and on this branch — the memory bounds
do not move that fight; the tick-2102 checkpoint (184/325/2011) is unchanged.
Re-pinned to the measured string and updated BUDGET_ASSERTED_SHA256 so the
raid/snapshot assertions stay active. test-budgets: 283 steps ok, tick fuel
max 184.7M/300M, 0 failures.

Co-Authored-By: Kimi Code <noreply@moonshot.ai>
2026-11-21 17:57:51 +03:00

242 lines
12 KiB
Rust

//! The fullscreen-map OOM replica (the `Ground::answer` rehash crash): a large raid watched
//! from all sides through a long session, with the wide ground-query pattern the command map
//! adds on top of the simulation's own. 64 integrated complexes stand where `/airdef deploy`
//! puts them; `airdef wave oreshnik 12 2600` orders come from all sides every 1500 ticks (six
//! raids, so recordings close and the kept replays pile up), and a smart raid maps its whole
//! grid. The render answers are produced exactly as the WASM test host produces them
//! (`horizon_mods::world_query::trace`, flat land at y=64). While the fight runs, a map pass
//! every other tick (the map's redraw pace) sweeps ground queries over a wide view — the
//! fullscreen map asks for the land under its whole grid, not just the flights' columns.
//!
//! The test measures what each consumer holds (`Sim::memory`) through the session, asserts the
//! peak fits the 64 MiB WASM linear memory with headroom for a hashbrown rehash transient, and
//! that the fight still resolves: intercepts happen, the sky clears, and the same seed replays
//! the same ordered combat trace.
//!
//! Run: `cargo test --test ground_oom -- --nocapture`.
use airdef::sim::world::{Fill, RayReply, SectionAnswer};
use airdef::sim::{Aim, Approach, DroneKind, Ground, MemoryReport, 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;
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;
const KINDS: [SamKind; 7] = [SamKind::S400, SamKind::Patriot, SamKind::Pantsir, SamKind::Gepard, SamKind::Nasams, SamKind::IrisT, SamKind::Tor];
/// The engine's cap on a mod's linear memory (`horizon-mods` runtime `MEMORY`).
const WASM_MEMORY: usize = 512 << 20;
/// The peak the mod's own bounds keep it under (well inside the cap): headroom for the allocator,
/// the transient query/answer vectors and save serialization on top of the measured steady state.
const PEAK_BUDGET: usize = 48 << 20;
/// Six raids fought out, recordings closed and replays kept; long enough for the caches to fill.
const TICKS: u64 = 10_000;
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 }
}
}
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 }
}
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 wave(sim: &mut Sim, out: &mut Out, count: u32, aim: Aim) -> u32 {
let o = RaidOrder { kinds: vec![(DroneKind::Oreshnik, count)], approach: Approach::AllSides, dist: 2600.0, aim };
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);
}
/// One run of the heavy session: the combat trace (ordered, for the determinism check), the
/// peak memory report and the counters at the end.
struct Run {
trace: Vec<(u64, u32, u32, usize)>,
peak: MemoryReport,
peak_total: usize,
peak_known: usize,
peak_airborne: usize,
sim: Sim,
}
fn run() -> Run {
// Six raids 1500 ticks apart: the sky clears between them, so recordings close and the
// kept replays pile up (the journal's and the poses' budgets are per recording).
run_with(&[(3, 12, Aim::Objects), (1503, 12, Aim::Objects), (3003, 12, Aim::Objects), (4503, 12, Aim::Objects), (6003, 12, Aim::Objects), (7503, 12, Aim::Objects), (1203, 10, Aim::Smart)], TICKS)
}
/// The extreme continuous load: waves overlap, the sky never clears, one recording runs long
/// and the flight tracks reach their points budget (the thinning), with over a thousand objects
/// airborne at once — well past the crash's >200.
fn run_extreme() -> Run {
run_with(&[(3, 40, Aim::Objects), (103, 40, Aim::Objects), (203, 40, Aim::Objects), (1003, 40, Aim::Objects), (2003, 40, Aim::Objects), (3003, 40, Aim::Objects), (4003, 40, Aim::Objects), (5003, 40, Aim::Objects)], 8000)
}
fn run_with(waves: &[(u64, u32, Aim)], ticks: u64) -> Run {
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;
let mut run = Run { trace: Vec::new(), peak: MemoryReport::default(), peak_total: 0, peak_known: 0, peak_airborne: 0, sim: Sim::new(SEED) };
for now in 1..=ticks {
if now == 3 {
deploy(&mut sim);
}
for &(at, count, aim) in waves {
if now == at {
assert!(wave(&mut sim, &mut out, count, aim) > 0, "wave at tick {now} was refused");
}
}
if now == 1103 {
sim.shader = true;
}
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 fullscreen map redraws every other tick and asks for the land under its grid:
// a wide walk over the view (32 fresh columns a redraw), as panning and placing do.
if now % 2 == 0 {
let t = now as f64;
let x0 = (t * 13.37).rem_euclid(8000.0) - 4000.0;
let z0 = (t * 7.91).rem_euclid(8000.0) - 4000.0;
for k in 0..32 {
let _ = ground.at(DVec3::new(x0 + k as f64 * 8.0, 0.0, z0 + k as f64 * 3.0), sim.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();
let airborne = sim.drones.iter().filter(|d| d.alive()).count();
run.peak_airborne = run.peak_airborne.max(airborne);
run.peak_known = run.peak_known.max(ground.known_len());
if now % 100 == 0 {
let m = sim.memory(&ground);
let total = m.total();
if total > run.peak_total {
run.peak_total = total;
run.peak = m;
}
run.trace.push((now, sim.kills, sim.hits, airborne));
}
}
run.sim = sim;
run
}
#[test]
fn the_heavy_map_session_fits_the_memory_budget_and_the_fight_resolves() {
let run = run();
let m = run.peak;
eprintln!("peak airborne {}, peak known columns {}", run.peak_airborne, run.peak_known);
eprintln!("peak memory at the worst sample:\n{}", m.text());
if let Some(rec) = run.sim.recording() {
let (tracks, journal, poses, misc) = rec.memory_parts();
eprintln!("live recording: tracks {:.2} MiB, journal {:.2} MiB, poses {:.2} MiB, misc {:.2} MiB", tracks as f64 / (1024.0 * 1024.0), journal as f64 / (1024.0 * 1024.0), poses as f64 / (1024.0 * 1024.0), misc as f64 / (1024.0 * 1024.0));
}
for (i, rec) in run.sim.replays.iter().enumerate() {
let (tracks, journal, poses, misc) = rec.memory_parts();
eprintln!("replay {}: len {} ticks, tracks {:.2} MiB, journal {:.2} MiB, poses {:.2} MiB, misc {:.2} MiB", i + 1, rec.len, tracks as f64 / (1024.0 * 1024.0), journal as f64 / (1024.0 * 1024.0), poses as f64 / (1024.0 * 1024.0), misc as f64 / (1024.0 * 1024.0));
}
eprintln!(
"end: tick {}, kills {}, hits {}, crashes {}, airborne {}, replays {}",
run.sim.tick,
run.sim.kills,
run.sim.hits,
run.sim.crashes,
run.sim.drones.iter().filter(|d| d.alive()).count(),
run.sim.replays.len()
);
// The load is the crash's load: a large raid, more than 200 objects in the sky at once.
assert!(run.peak_airborne > 200, "the replica never reached the crash's load: {}", run.peak_airborne);
// The fight resolves: intercepts happen and the sky clears by the end of the session.
assert!(run.sim.kills > 100, "the defence stopped intercepting: {}", run.sim.kills);
assert_eq!(run.sim.drones.iter().filter(|d| d.alive()).count(), 0, "the raid never fought out");
// The memory budget: the steady peak plus the worst rehash transient (the old and the new
// table of the biggest map held at once) stays under the headroom target, far under the cap.
let peak = run.peak_total + m.rehash_headroom();
assert!(peak < PEAK_BUDGET, "peak {} MiB (steady {} + rehash {}) over the {} MiB budget:\n{}", peak >> 20, run.peak_total >> 20, m.rehash_headroom() >> 20, PEAK_BUDGET >> 20, m.text());
assert!(peak < WASM_MEMORY, "peak {} MiB over the engine's {} MiB cap", peak >> 20, WASM_MEMORY >> 20);
}
#[test]
fn the_same_seed_replays_the_same_ordered_combat_trace() {
let a = run();
let b = run();
assert_eq!(a.trace, b.trace, "the combat trace diverged between identical runs");
assert_eq!(a.sim.kills, b.sim.kills);
assert_eq!(a.sim.hits, b.sim.hits);
assert_eq!(a.sim.tally.text(), b.sim.tally.text());
assert_eq!(a.peak_known, b.peak_known);
}
#[test]
fn the_continuous_extreme_load_stays_bounded_and_thins_its_tracks() {
let run = run_extreme();
let m = run.peak;
eprintln!("extreme: peak airborne {}, peak known columns {}", run.peak_airborne, run.peak_known);
eprintln!("extreme peak memory:\n{}", m.text());
eprintln!("extreme end: kills {}, hits {}, airborne {}", run.sim.kills, run.sim.hits, run.sim.drones.iter().filter(|d| d.alive()).count());
// Well past the crash's load: the radar picture itself scales with the sky, and the
// recording's tracks must thin under their points budget rather than grow without bound.
assert!(run.peak_airborne > 1000, "the extreme load never materialised: {}", run.peak_airborne);
assert!(run.sim.kills > 100, "the defence stopped intercepting: {}", run.sim.kills);
let rec = run.sim.recording().or_else(|| run.sim.replays.last()).expect("the raid was recorded");
let (tracks, journal, poses, misc) = rec.memory_parts();
let points: usize = rec.tracks.iter().map(|t| t.points_len()).sum();
let max_step = rec.tracks.iter().map(|t| t.step()).max().unwrap_or(0);
eprintln!("extreme recording: len {} ticks, tracks {:.2} MiB ({points} points, max step {max_step}), journal {:.2} MiB, poses {:.2} MiB, misc {:.2} MiB", rec.len, tracks as f64 / (1024.0 * 1024.0), journal as f64 / (1024.0 * 1024.0), poses as f64 / (1024.0 * 1024.0), misc as f64 / (1024.0 * 1024.0));
assert!(max_step > airdef::sim::record::STEP, "the points budget never thinned the tracks");
let peak = run.peak_total + m.rehash_headroom();
assert!(peak < PEAK_BUDGET, "extreme peak {} MiB over the {} MiB budget:\n{}", peak >> 20, PEAK_BUDGET >> 20, m.text());
}