Fix the UI-event fuel trap on a second large raid order
build / mod (push) Failing after 22s

The Windows log for #122 showed the mod stopping in the UI event
(fuel budget 1e9, remaining 0) with known_units <- order_raid <-
launch_wave <- ui_select: order_raid recomputed the planner snapshot
known_units() for every drone, and the snapshot itself rescanned the
whole force and the dedup list per intel entry. A second big Smart
order cost drones x intel-log x force-size inside one event.

Reproduced in actual WASM with measured per-callback fuel through the
exact ui_select(BTN_LAUNCH) handler (diagnostic guest, trigger.patch):
before, a 111-drone second order at revealed=13172/known=144 exhausted
exactly 1e9 and stopped the mod (an 11-drone order at the same state:
247805865); after, the same scenario passes with max command fuel
32946177/1e9, failures=0, and /stats at tick 2602 byte-identical.
A stacked single-point layout dies to one warhead (known=0, cheap
order), so the scenario deploys spread clusters with a moved player.

Fix: one known_units snapshot per order_raid passed to radar_strikes
and choose_target; known_units is a single O(log + force) set pass;
price_grid_on reuses its snapshot. Emitter/network targeting and
carrier choice semantics are unchanged (native equivalence test
against the former predicate; WASM checkpoint counters equal).
Limits unchanged; HD/recording untouched; wave size unrestricted.

Committed regressions: native snapshot-equivalence and
second-smart-order tests; the heavy WASM fixture now orders two Smart
raids through the wave screen's launch function (airdef preset +
airdef raid) with EW and a combat intel log, four accepted orders
asserted; the light contract covers preset and the empty-wave refusal.

Core release 195 + 8 scenarios; adapter 65 + 1 boundary + 5 scenarios;
light WASM 30 steps; heavy WASM 283 steps (tick max 182413686/300M,
command max 6939810/1e9, failures 0). Windows GUI acceptance remains
external and is not claimed.

Co-Authored-By: Kimi Code (Moonshot AI) <noreply@moonshot.cn>
This commit is contained in:
2026-11-04 21:49:25 +03:00
parent 61aaa0bf35
commit d45629ae29
19 changed files with 1907 additions and 43 deletions
+8 -3
View File
@@ -8,6 +8,7 @@
//! stations jammed (its next drones go for them), and from which bearings its
//! raids were shot down or got through (its next raid comes from the best).
use super::*;
use std::collections::HashSet;
/// How far a station jams.
pub const EW_RADIUS: f64 = 350.0;
@@ -135,13 +136,17 @@ impl Sim {
}
/// Units the enemy knows of and would go for, newest first: (id, where).
/// One pass over the log: aliveness and duplicates by set, not by rescanning
/// the lists for every entry — a big log with many systems must not make the
/// planner's snapshot quadratic (#122).
pub(super) fn known_units(&self) -> Vec<(u32, DVec3)> {
let alive: HashSet<u32> = self.sams.iter().filter(|s| s.alive()).map(|s| s.id).collect();
let mut seen: HashSet<u32> = HashSet::new();
let mut out: Vec<(u32, DVec3)> = Vec::new();
for &(id, at, observed) in self.intel.revealed.iter().rev() {
if self.tick.saturating_sub(observed) >= 6000 { continue; }
if !out.iter().any(|o| o.0 == id) && self.sams.iter().any(|s| s.id == id && s.alive()) {
out.push((id, at));
}
if !seen.insert(id) { continue; }
if alive.contains(&id) { out.push((id, at)); }
}
out
}
+113 -13
View File
@@ -278,6 +278,10 @@ impl Sim {
return 0;
}
let smart = order.aim == Aim::Smart;
// The planner's picture of the layout: one snapshot for the whole order. It is
// read-only while the plan is built, and recomputing it per drone made a big
// second order quadratic in the intel log and the force's size (#122).
let known = self.known_units();
// A smart enemy comes from where its raids got through best.
let bearing = if smart { self.best_bearing() } else { self.rng.f() * TAU };
// The raid's sides (1, 2, or 4-5): its launch sites go there (#100).
@@ -290,7 +294,7 @@ impl Sim {
let grid = Grid { min: centre - DVec3::new(span, 0.0, span), cell, size: (2.0 * span / cell) as i32 + 1 };
let mut items = Vec::new();
// A smart raid goes for the radars too (a few strikers each); the others pick as they always did.
let radar_jobs = if smart { self.radar_strikes(&order.kinds) } else { Vec::new() };
let radar_jobs = if smart { self.radar_strikes(&order.kinds, &known) } else { Vec::new() };
let mut index = 0usize;
for (group, &(kind, count)) in order.kinds.iter().enumerate() {
let spec = kind.spec();
@@ -306,7 +310,7 @@ impl Sim {
index += 1;
let (target, at_sam) = match job {
Some((at, id)) => (at, Some(id)),
None => self.choose_target(kind, object, order.aim),
None => self.choose_target(kind, object, order.aim, &known),
};
let aim = target + DVec3::new(self.rng.s() * 4.0, 0.0, self.rng.s() * 4.0);
let dist = spec.ballistic.map_or(order.dist, |far| far.max(order.dist)) + self.rng.f() * 50.0;
@@ -542,8 +546,8 @@ impl Sim {
/// The strikes a smart raid sends at observed radars: for drones of `kinds` in order,
/// the last observed place and id for those that go for one. Each radar
/// gets two or three, the fast strikers first, and all together no more than about a quarter of the raid.
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = self.known_units().into_iter()
pub(super) fn radar_strikes(&self, kinds: &[(DroneKind, u32)], known: &[(u32, DVec3)]) -> Vec<Option<(DVec3, u32)>> {
let mut radars: Vec<(u32, DVec3)> = known.iter().copied()
.filter(|(id, _)| self.sams.iter().any(|s| s.id == *id && s.alive() && s.kind == SamKind::Radar))
.collect();
radars.sort_by_key(|(id, _)| *id);
@@ -568,7 +572,7 @@ impl Sim {
/// What a drone goes for: an object, or (by its kind and the raid's aim) a system. Returns the
/// point and the system's id.
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim) -> (DVec3, Option<u32>) {
fn choose_target(&mut self, kind: DroneKind, object: DVec3, aim: Aim, known: &[(u32, DVec3)]) -> (DVec3, Option<u32>) {
let alive: Vec<&Sam> = self.sams.iter().filter(|s| s.alive()).collect();
if alive.is_empty() || kind.spec().decoy || aim == Aim::Objects {
return (object, None);
@@ -588,8 +592,7 @@ impl Sim {
// station, a radar, a system that fired).
// The planner has only what the enemy knows (#93): the radars (they emit) and the units that gave
// themselves away; the rest of the player's layout is not in its hands.
let known = self.known_units();
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, &known)).collect();
let alive: Vec<&Sam> = alive.iter().copied().filter(|s| Self::enemy_knows(s, known)).collect();
let pick_known = |list: &[&Sam], r: f64| -> Option<(DVec3, u32)> {
let s = *list.get((r * list.len() as f64) as usize)?;
known.iter().find(|(id, _)| *id == s.id).map(|(_, pos)| (*pos, s.id))
@@ -631,9 +634,8 @@ impl Sim {
let mut prices = vec![1.0f32; (n * n) as usize];
// Known jamming stations: drones that navigate by satellite keep away.
if kind.jammable() {
let known = self.known_units();
for s in self.sams.iter().filter(|s| s.kind == SamKind::Ew && s.alive() && known.iter().any(|k| k.0 == s.id)) {
let pos = known.iter().find(|(id, _)| *id == s.id).unwrap().1;
for s in self.sams.iter().filter(|s| s.kind == SamKind::Ew && s.alive() && known_now.iter().any(|k| k.0 == s.id)) {
let pos = known_now.iter().find(|(id, _)| *id == s.id).unwrap().1;
let (ci, cj) = grid.index(pos);
let r = (EW_RADIUS / grid.cell).ceil() as i32;
for i in (ci - r).max(0)..=(ci + r).min(n - 1) {
@@ -979,16 +981,19 @@ mod tests {
radar.radar_on = false;
sim.sams.push(radar);
let kinds = [(DroneKind::Kh22, 8)];
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
let none = Vec::new();
assert!(sim.radar_strikes(&kinds, &none).iter().all(Option::is_none));
sim.tick = 20;
sim.intel.revealed.push((1, old, sim.tick));
sim.sams[0].pos = DVec3::new(900.0, 70.0, 900.0);
sim.tick = 40;
let jobs = sim.radar_strikes(&kinds);
let known = sim.known_units();
let jobs = sim.radar_strikes(&kinds, &known);
assert_eq!(jobs.iter().flatten().count(), 2);
assert!(jobs.iter().flatten().all(|job| *job == (old, 1)));
sim.tick = 6020;
assert!(sim.radar_strikes(&kinds).iter().all(Option::is_none));
let known = sim.known_units();
assert!(sim.radar_strikes(&kinds, &known).iter().all(Option::is_none));
}
#[test]
@@ -1044,6 +1049,101 @@ mod tests {
check(&sim, "after adapting");
}
/// The snapshot the planner works from must not depend on how it is computed:
/// the set-based pass is checked here against the former per-entry rescan, over
/// duplicates, the dead, the aged-out, ids the force never had, and ordering.
#[test]
fn known_units_matches_the_naive_reference_on_a_fat_log() {
let mut sim = Sim::new(9);
let mut places = Vec::new();
for (i, kind) in [SamKind::S400, SamKind::Ew, SamKind::Radar, SamKind::Tor, SamKind::Patriot].into_iter().enumerate() {
let id = sim.id();
let mut sam = Sam::new(id, kind, DVec3::new(i as f64 * 100.0, 70.0, -50.0), 0.0);
// The second system is dead: known only while it lived.
if i == 1 { sam.health = 0.0; }
sim.sams.push(sam);
places.push((id, DVec3::new(i as f64 * 100.0, 70.0, -50.0)));
}
let naive = |sim: &Sim| {
let mut out: Vec<(u32, DVec3)> = Vec::new();
for &(id, at, observed) in sim.intel.revealed.iter().rev() {
if sim.tick.saturating_sub(observed) >= 6000 { continue; }
if !out.iter().any(|o| o.0 == id) && sim.sams.iter().any(|s| s.id == id && s.alive()) {
out.push((id, at));
}
}
out
};
sim.tick = 7000;
let dead = places[1].0;
let (a, b, c, d, e) = (places[0].0, places[1].0, places[2].0, places[3].0, places[4].0);
// A long log: repeated observations (newest wins), one dead system, one never-seen
// system, one id the force does not have, and an entry that aged out.
for t in 0..200u64 {
sim.intel.revealed.push((a, DVec3::new(11.0, 70.0, t as f64), 1000 + t));
sim.intel.revealed.push((c, DVec3::new(13.0, 70.0, t as f64), 1000 + t));
if t % 7 == 0 { sim.intel.revealed.push((b, DVec3::new(12.0, 70.0, t as f64), 1000 + t)); }
if t % 11 == 0 { sim.intel.revealed.push((d, DVec3::new(14.0, 70.0, t as f64), 1000 + t)); }
if t % 13 == 0 { sim.intel.revealed.push((999_999, DVec3::new(1.0, 70.0, 0.0), 1000 + t)); }
}
sim.intel.revealed.push((e, DVec3::new(15.0, 70.0, 0.0), 2)); // aged out at tick 7000
let expected = naive(&sim);
assert_eq!(sim.known_units(), expected);
assert_eq!(expected.iter().map(|k| k.0).collect::<Vec<_>>(), vec![c, a, d]);
assert!(expected.iter().all(|k| k.0 != dead && k.0 != e && k.0 != 999_999));
// The newest observation's place is the one kept.
assert_eq!(expected.iter().find(|k| k.0 == a).unwrap().1, DVec3::new(11.0, 70.0, 199.0));
}
/// The reported Windows stop (#122): the second big order from the UI path, with a fat
/// intel log and a large surviving force, must be accepted and launched like the first.
/// (The old per-drone planner snapshot was correct but quadratic; its cost is pinned by
/// the actual-WASM fuel measurements in docs/measurements/issue-122-ui-fuel.)
#[test]
fn a_second_smart_order_with_a_fat_intel_log_is_accepted_and_launched() {
let mut sim = Sim::new(31);
let mut ids = Vec::new();
for i in 0..48 {
let id = sim.id();
sim.sams.push(Sam::new(id, [SamKind::S400, SamKind::Patriot, SamKind::Nasams, SamKind::Pantsir][i % 4], DVec3::new((i % 8 * 40) as f64, 70.0, (i / 8 * 40) as f64), 0.0));
ids.push(id);
}
// A fought-off first raid leaves a long log: launches, emitting radars, stations.
// Its entries sit in the past of the sim clock, like real ones.
sim.tick = 4000;
for t in 0..3000u64 {
sim.intel.revealed.push((ids[(t as usize) % ids.len()], DVec3::new(10.0, 70.0, t as f64), 1001 + t));
}
sim.targets.push(DVec3::new(160.0, 70.0, 160.0));
sim.target_health.push(100.0);
let mut ground = Ground::default();
let land = Land(|_, _| 64);
let mut out = Out::default();
for _ in 0..20 {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
let mut order = RaidOrder::mix(36, 300.0);
order.aim = Aim::Smart;
order.approach = Approach::AllSides;
let total: u32 = order.kinds.iter().map(|k| k.1).sum();
let first = sim.order_raid(&order, &sim.targets.clone(), &mut out);
assert_eq!(first, total);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert!(sim.queue.len() + sim.launched as usize >= total as usize, "the first order queued or launched every drone (queue {}, launched {})", sim.queue.len(), sim.launched);
// The second order — the path that stopped the mod on Windows — is accepted too.
let second = sim.order_raid(&order, &sim.targets.clone(), &mut out);
assert_eq!(second, total);
while sim.planning() {
serve(&mut ground, &land, sim.tick);
sim.step(&mut ground, None, &mut out);
}
assert!(sim.queue.len() + sim.launched as usize >= 2 * total as usize, "both orders queued or launched their drones (queue {}, launched {})", sim.queue.len(), sim.launched);
}
#[test]
fn systems_ready_together_send_one_missile_at_a_drone() {
let mut sim = Sim::new(3);