From b796a439df4ed6707091c98680d73ddaddff5073 Mon Sep 17 00:00:00 2001 From: chexit Date: Sat, 21 Nov 2026 10:24:56 +0300 Subject: [PATCH] Restore the saturated intercept count by uncueing the embedded radar (#145) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 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). --- airdef-mod/Cargo.lock | 173 ++++++++++++++++++ airdef-mod/Cargo.toml | 3 + airdef-mod/src/sim/sensor_tests.rs | 35 ++++ airdef-mod/src/sim/sight.rs | 9 +- airdef-mod/src/sim/why.rs | 147 +++++++++++++++ .../tests/budgets/wasm_flat_budget.toml | 16 +- airdef-mod/tests/saturation.rs | 170 +++++++++++++++++ .../issue-145-intercept-regression.json | 58 ++++++ tools/airdef.py | 2 +- 9 files changed, 606 insertions(+), 7 deletions(-) create mode 100644 airdef-mod/tests/saturation.rs create mode 100644 docs/measurements/issue-145-intercept-regression.json diff --git a/airdef-mod/Cargo.lock b/airdef-mod/Cargo.lock index 1270314..83dbe9e 100644 --- a/airdef-mod/Cargo.lock +++ b/airdef-mod/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "airdef" version = "0.2.0" @@ -9,6 +15,7 @@ dependencies = [ "airdef-core", "glam", "horizon-mod-sdk", + "horizon-mods", ] [[package]] @@ -24,18 +31,75 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "equivalent" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + [[package]] name = "foldhash" version = "0.2.0" @@ -70,6 +134,17 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "horizon-mods" +version = "0.1.0" +dependencies = [ + "log", + "serde", + "serde_json", + "toml", + "zip", +] + [[package]] name = "id-arena" version = "2.3.0" @@ -112,6 +187,16 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "prettyplease" version = "0.2.37" @@ -153,6 +238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -188,6 +274,21 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "syn" version = "2.0.119" @@ -210,6 +311,45 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "toml" +version = "1.2.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5426cb1b964690d913f6c5c1a1ae0b42f428ec506bb4d452876d7a209c9bca3b" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -250,6 +390,12 @@ dependencies = [ "semver", ] +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + [[package]] name = "wit-bindgen" version = "0.60.0" @@ -339,8 +485,35 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap", + "memchr", + "zopfli", +] + [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/airdef-mod/Cargo.toml b/airdef-mod/Cargo.toml index 4fab4e8..7402f5b 100644 --- a/airdef-mod/Cargo.toml +++ b/airdef-mod/Cargo.toml @@ -19,6 +19,9 @@ glam = "0.30" [dev-dependencies] airdef-core = { path = "../airdef-core", features = ["test-fixtures"] } +# The host's own block tracer, so the saturation replica answers render rays exactly as the +# WASM test host does (no runtime: just `world_query`). +horizon-mods = { path = "../horizon/crates/horizon-mods", default-features = false } [profile.release] opt-level = "s" diff --git a/airdef-mod/src/sim/sensor_tests.rs b/airdef-mod/src/sim/sensor_tests.rs index a5166a7..d2fc808 100644 --- a/airdef-mod/src/sim/sensor_tests.rs +++ b/airdef-mod/src/sim/sensor_tests.rs @@ -599,6 +599,41 @@ fn network_relay_keeps_source_age_and_quality_but_not_launch_authority() { assert!(!why::radar_cue(&sim.sams[receiver], &[&sim.sams[engagement]], id, sim.tick), "a broken link still cued a launch"); } +#[test] +fn a_network_plot_cues_a_separate_fire_radar_but_not_the_embedded_one() { + // #145: a fire-quality radar is cued to look at a network contact, but the weapon's own + // embedded radar is not — cueing every relayed contact each tick flooded the embedded fire + // control with one-tick plots and degraded the intercepts. The embedded radar keeps its + // beam/revisit/lock acquisition; a separate engagement radar still takes the cue. + let mut sim = Sim::new(145); + let search = radar_with_role(&mut sim, RadarRole::Search, 0.0); + let engagement = radar_with_role(&mut sim, RadarRole::Engagement, 10.0); + let embedded = { + let id = sim.id(); + sim.sams.push(Sam::new(id, SamKind::S400, DVec3::new(20.0, 70.0, 0.0), 0.0)); + sim.sams.len() - 1 + }; + sim.add_drone(DroneKind::Shahed, DVec3::new(150.0, 120.0, 0.0), DVec3::Z, DVec3::new(150.0, 120.0, 0.0)); + let id = sim.drones[0].id; + let at = sim.drones[0].pos; + let away = DVec3::new(-600.0, 120.0, 0.0); + let mut ground = Ground::default(); + for tick in 1..=8 { + sim.tick = tick; + // The search radar measures the contact; the embedded and engagement radars look away, + // so only a cue (not the beam, a revisit or a lock) could give them an own plot. + sim.sams[search].beam = bearing(sim.sams[search].pos, at); + sim.sams[embedded].beam = bearing(sim.sams[embedded].pos, away); + sim.sams[engagement].beam = bearing(sim.sams[engagement].pos, away); + sim.update_sight(&mut ground); + } + let emb = sim.sams[embedded].track(id).expect("the embedded radar holds the network track"); + assert_eq!(emb.own_tick, 0, "the embedded radar cue-measured a relayed contact (#145)"); + assert!(!emb.own_authorizes(sim.tick), "a relayed plot gave the embedded radar fire authority"); + let eng = sim.sams[engagement].track(id).expect("the engagement radar holds the track"); + assert!(eng.own_tick > 0, "a separate fire-quality radar was not cued by the network plot"); +} + #[test] fn the_air_picture_prefers_the_better_plot_at_one_tick() { let mut sim = Sim::new(1345); diff --git a/airdef-mod/src/sim/sight.rs b/airdef-mod/src/sim/sight.rs index 3291b07..2598243 100644 --- a/airdef-mod/src/sim/sight.rs +++ b/airdef-mod/src/sim/sight.rs @@ -511,9 +511,12 @@ impl Sim { // The beam passes its bearing this tick (the angle wraps at 2π: the difference is taken round). let in_beam = swept(rel.x.atan2(-rel.z), b0, w); let revisit = scan.agile && held.is_some_and(|t| t.own_tick > 0 && now - t.own_tick >= (period / 3.0) as u64); - // A network plot cues a fire-quality radar to look, but is never itself a - // measurement: reach, terrain, probability and noise still apply. - let cue = profile.allows(battery::Measure::Fire) + // A network plot cues a *separate* fire-quality radar to look, but is never itself + // a measurement: reach, terrain, probability and noise still apply. The weapon's + // own embedded radar is not cued: measuring every relayed contact each tick flooded + // its fire control with one-tick plots whose noisy velocity degraded the intercepts + // (#145); it keeps its beam/revisit/lock acquisition, as before the profiles (#134). + let cue = sam.kind == SamKind::Radar && profile.allows(battery::Measure::Fire) && held.is_some_and(|t| t.own_tick == 0 && t.age(now) <= MISSILE_AGE); if !(in_beam || locked || revisit || cue) { continue; diff --git a/airdef-mod/src/sim/why.rs b/airdef-mod/src/sim/why.rs index 63a4712..1821bc5 100644 --- a/airdef-mod/src/sim/why.rs +++ b/airdef-mod/src/sim/why.rs @@ -272,6 +272,153 @@ pub(super) fn gun_blocks(s: &Sam, aim_id: u32, gt: u32, aim_error: f64, dist: f6 | (if s.bursts > 0 { 0 } else { NO_ROUNDS }) } +// ---------------------------------------------------------------- the saturation audit (#145) + +/// Why the armed systems hold their fire, counted over every (system, alive drone) pair at the +/// moment of the call: the same predicates `step_sams` decides with, in the decision's order, so +/// each pair lands on the first ground that stops it. On demand only — the diagnostic a +/// regression scenario reads, never per-tick work. A pair the system would launch at now counts +/// as `ready`; the interceptor outcomes (a launch that missed) are the session's [`Tally`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct LaunchAudit { + /// The system's picture holds no track of the drone at all. + pub no_track: u32, + /// Its track is older than a launcher fires on (`MISSILE_AGE`). + pub stale: u32, + /// No own confirmed fire plot: a relayed or search plot, quality below `FIRE_QUALITY`, or own + /// measurement too old — the track is there but does not authorize a launch. + pub no_authority: u32, + /// The estimated class is out of the system's roles, and no last chance applies. + pub role: u32, + /// The doctrine (sector, guarded objects, reserve) holds the shot. + pub doctrine: u32, + /// The forecast place is beyond the missile's reach, and no long shot is allowed. + pub out_of_reach: u32, + /// Enough interceptors are on it already (`doctrine.needed`). + pub claimed: u32, + /// The launcher is not ready: cooldown, reload, no rounds, failed. + pub not_ready: u32, + /// The mount is not laid on the target yet. + pub not_aimed: u32, + /// The land ruled the shot out (the cached verdict; an uncached one resolves within a tick). + pub terrain: u32, + /// Nothing stops the pair: the system would launch at it now. + pub ready: u32, +} + +impl LaunchAudit { + /// The non-zero counts as a line, for a scenario report. + pub fn text(&self) -> String { + let parts = [ + (self.no_track, "нет трассы"), + (self.stale, "трасса протухла"), + (self.no_authority, "нет права на пуск"), + (self.role, "вне ролей"), + (self.doctrine, "доктрина"), + (self.out_of_reach, "вне дальности"), + (self.claimed, "занята перехватчиками"), + (self.not_ready, "пусковая не готова"), + (self.not_aimed, "не наведена"), + (self.terrain, "рельеф"), + (self.ready, "готова стрелять"), + ]; + parts.iter().filter(|(n, _)| *n > 0).map(|(n, name)| format!("{name}: {n}")).collect::>().join(", ") + } +} + +impl Sim { + /// The saturation audit: every armed system against every alive drone, attributed to the first + /// ground that stops the shot. Reads the tracks' estimates and provenance, never the target's + /// own class or velocity (#133). + pub fn launch_audit(&self) -> LaunchAudit { + let mut a = LaunchAudit::default(); + let now = self.tick; + let (missile_on, _) = engagement_counts(&self.sams); + let radars: Vec<&Sam> = self.sams.iter().filter(|s| s.kind == SamKind::Radar).collect(); + let opts = Opts { last_chance: self.last_chance, far_shots: self.far_shots }; + for sam in &self.sams { + let Some(load) = sam.kind.spec().missile.as_ref() else { continue }; + if !sam.alive() || sam.moving() { + continue; + } + let spec = sam.kind.spec(); + let mount = sam.mount().0; + let lead_speed = spec.gun.as_ref().map_or(5.0, |g| g.shell); + let cued = |id: u32| !radars.is_empty() && radar_cue(sam, &radars, id, now); + // Long shots only while nothing of the system's roles is in its normal reach. + let role_in_reach = !radars.is_empty() + && sam.tracks.iter().any(|tr| { + self.drones.iter().find(|d| d.id == tr.id).is_some_and(|d| { + claimed(d, &missile_on, sam.target) < sam.doctrine.needed(d, tr.class) + && basis(sam, load, tr, d, now, claimed(d, &missile_on, sam.target), 1.0, opts, cued(tr.id), true) == Some(Basis::Role) + }) + }); + for d in self.drones.iter().filter(|d| d.alive()) { + let Some(tr) = sam.track(d.id) else { + a.no_track += 1; + continue; + }; + let blocks = target_blocks(sam.roles, Some(tr), now, d); + if blocks & STALE != 0 { + a.stale += 1; + continue; + } + let own = tr.own_authorizes(now); + let cue = cued(d.id); + let authorized = if sam.mode == battery::SamMode::LauncherOnly { cue } else { own || cue }; + if !authorized { + a.no_authority += 1; + continue; + } + let est = tr.class; + let free = claimed(d, &missile_on, sam.target); + let chance = blocks & ROLE != 0 && last_chance(self.last_chance, sam.roles, est, d, free); + if blocks & ROLE != 0 && !chance { + a.role += 1; + continue; + } + if blocks & ROLE == 0 && sam.doctrine.area_blocks(sam.pos, tr, now) | sam.doctrine.reserve_blocks(sam.missiles, d, est) != 0 { + a.doctrine += 1; + continue; + } + let est_at = tr.est(now); + let reach = reach_blocks(load.min, load.max, 1.0, sam.pos, est_at); + let far = reach == TOO_FAR + && reach_blocks(load.min, load.max, FAR_K, sam.pos, est_at) == 0 + && far_blocks(opts.far_shots, sam, load, cue, role_in_reach) == 0; + if reach != 0 && !(far && blocks & ROLE == 0) { + a.out_of_reach += 1; + continue; + } + if reach == 0 && !(own || sam.mode == battery::SamMode::LauncherOnly) { + a.no_authority += 1; + continue; + } + if free >= sam.doctrine.needed(d, est) { + a.claimed += 1; + continue; + } + if missile_blocks(sam) != 0 { + a.not_ready += 1; + continue; + } + let (_, want_yaw, want_pitch) = aim_wants(mount, est_at, tr.vel, lead_speed); + let err = aim_error(spec.family, sam.yaw, sam.pitch, want_yaw, want_pitch); + if !missile_aligned(spec.family, sam.yaw, mount, Some(est_at), d.id, d.id, err) { + a.not_aimed += 1; + continue; + } + if sam.terrain_verdict(d.id, now).unwrap_or(0) != 0 { + a.terrain += 1; + continue; + } + a.ready += 1; + } + } + a + } +} + // ---------------------------------------------------------------- the diagnostic /// A diagnostic condition and its structured or legacy reason. diff --git a/airdef-mod/tests/budgets/wasm_flat_budget.toml b/airdef-mod/tests/budgets/wasm_flat_budget.toml index bbaadbb..587ba20 100644 --- a/airdef-mod/tests/budgets/wasm_flat_budget.toml +++ b/airdef-mod/tests/budgets/wasm_flat_budget.toml @@ -1016,7 +1016,11 @@ frames = 10 [[step]] command = "airdef stats" -expect.feedback = "В воздухе: 184, ракет: 10, ПВО: 64, сбито: 777, поражений: 1499, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 5353 секций (250 КБ), запросов 14405, неизвестно 0, лучей 327428 (ударов 6746, неизв. 213), клеток 2282312; взрывы в блоках: 1586 (подтверждено 0, без перемен 175, нет чанка 1330), чужих ответов 0" +# Baseline re-measured after the #145 fix (engine 2bcce64): the embedded-cue flood of #134 is +# removed, restoring the intercepts. The pre-#133 522 used the target's true velocity, which the +# measurement-only contract (#133) forbids; ~325 is the restored range. See +# docs/measurements/issue-145-intercept-regression.json for the A/B decomposition. +expect.feedback = "В воздухе: 184, ракет: 4, ПВО: 64, сбито: 325, поражений: 2011, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 4672 секций (219 КБ), запросов 13570, неизвестно 0, лучей 335118 (ударов 8088, неизв. 158), клеток 2162018; взрывы в блоках: 2041 (подтверждено 0, без перемен 148, нет чанка 1754), чужих ответов 0" # The Windows #122 path: a Smart order through the UI launch function (`airdef raid` # is the wave screen's ПУСК button handler) with a fat intel log and EW up — twice. @@ -1041,7 +1045,9 @@ expect.feedback = "Готовый: Массированный удар" [[step]] command = "airdef raid" -expect.chat = [] +# A Smart order sends a recon flight ahead of the strike (#135): the wave screen's ПУСК handler +# reports it. The empty-chat expectation predates #135 and stopped the scenario here (#145). +expect.chat = ["Разведка противника: впереди налёта высланы разведчики"] [[step]] ticks = 400 @@ -1061,4 +1067,8 @@ frames = 100 [[step]] command = "airdef stats" -expect.feedback = "В воздухе: 11, ракет: 3, ПВО: 68, сбито: 936, поражений: 1853, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 6643 секций (311 КБ), запросов 17355, неизвестно 0, лучей 393828 (ударов 9283, неизв. 978), клеток 2953257; взрывы в блоках: 1961 (подтверждено 0, без перемен 234, нет чанка 1727), чужих ответов 0" +# Re-measured on the shipped engine 8e711f969 with #146 (one knowledge snapshot per Smart order) +# integrated: the two late Smart raids plan over the versioned picture, so their outcome and world +# queries differ from the #145 agent's pre-#146 measurement (385/2472 on engine 2bcce64). The +# tick-2102 checkpoint above is unaffected by #146 and matches on both engines. +expect.feedback = "В воздухе: 11, ракет: 0, ПВО: 68, сбито: 414, поражений: 2463, разбились о препятствия: 0; удары по ПУ: пущено 0, уничтожено 0, подавлено 0, промахов 0, сбито ПВО 0; мир: 8885 секций (416 КБ), запросов 19743, неизвестно 0, лучей 420671 (ударов 11121, неизв. 1124), клеток 3442845; взрывы в блоках: 2501 (подтверждено 0, без перемен 195, нет чанка 2306), чужих ответов 0" diff --git a/airdef-mod/tests/saturation.rs b/airdef-mod/tests/saturation.rs new file mode 100644 index 0000000..9f7d989 --- /dev/null +++ b/airdef-mod/tests/saturation.rs @@ -0,0 +1,170 @@ +//! 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 = Vec::new(); + let mut rays: Vec = 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::() + ); + 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"); + } +} diff --git a/docs/measurements/issue-145-intercept-regression.json b/docs/measurements/issue-145-intercept-regression.json new file mode 100644 index 0000000..36d758e --- /dev/null +++ b/docs/measurements/issue-145-intercept-regression.json @@ -0,0 +1,58 @@ +{ + "schema": 1, + "issue": 145, + "title": "Intercept regression under WASM saturation: 522 -> 302 (#133) -> 243 (#134)", + "scenario": "airdef-mod/tests/budgets/wasm_flat_budget.toml", + "checkpoint_tick": 2102, + "engine": "2bcce642362ab5d3f04de193e390d8293cd1bf30", + "fuel_budget_per_tick": 300000000, + "method": "One unchanged fixture, one WASM host (cargo-horizon-mod test --fuel-profile budget), one SDK; each slice built from its own commit against the pinned engine. The checkpoint stats line is read by a deliberate expect.feedback mismatch that prints the real line; fuel counters come from the host. Native replica: airdef-mod/tests/saturation.rs (same sim, host block tracer, deterministic).", + "ab_checkpoint": [ + {"slice": "main release v0.4.0-rc1", "commit": "c525feb", "kills": 522, "hits": 1789, "missiles_airborne": 5}, + {"slice": "parent of #133", "commit": "95739c95b", "kills": 522, "hits": 1789, "missiles_airborne": 5, "fuel_max_tick": 113866321}, + {"slice": "#133 class/speed from measurements", "commit": "ac7521936", "kills": 302, "hits": 2024, "missiles_airborne": 8, "fuel_max_tick": 114068675}, + {"slice": "#134 radar profiles", "commit": "858735a4c", "kills": 243, "hits": 2083, "missiles_airborne": 24, "fuel_max_tick": 135803282}, + {"slice": "kimi-work HEAD", "commit": "a983177d3", "kills": 243, "hits": 2083, "missiles_airborne": 24, "fuel_max_tick": 136067073} + ], + "decomposition_variants_wasm": [ + {"variant": "#133 with class estimate forced Unknown", "base": "ac7521936", "kills": 249, "hits": 2092, "note": "confounded: Unknown also disables last-chance and halves the ballistic salvo; class/roles is not the #133 cause (native class-off 296 ~= baseline 294)"}, + {"variant": "#134 cue restricted to separate radars (cue-off)", "base": "858735a4c", "kills": 325, "hits": 2011, "fuel_max_tick": 124349576, "note": "recovers the whole #134 drop: the embedded cue flood is the cause"}, + {"variant": "#134 own_fire_within relaxed to own_within (no FIRE_QUALITY/product gate)", "base": "858735a4c", "kills": 243, "hits": 2083, "fuel_max_tick": 135800131, "note": "zero effect: embedded radars always produce Fire plots of quality >= 64"}, + {"variant": "#134 channel limit never binds", "base": "858735a4c", "kills": 243, "hits": 2083, "fuel_max_tick": 135438135, "note": "zero effect: embedded profiles have channels = 0"}, + {"variant": "cue precise + carry network velocity (Fix D)", "base": "a983177d3", "kills": 260, "hits": 2051, "note": "partial: early cue authority fires with a stale carried velocity"}, + {"variant": "cue restricted to separate fire-quality radars (Fix F, chosen)", "base": "a983177d3", "kills": 325, "hits": 2011, "fuel_max_tick": 118325396, "note": "the fix; restores embedded acquisition to pre-#134 beam/revisit/lock"} + ], + "native_replica_checkpoint": { + "note": "Deterministic native replica (tests/saturation.rs); chaotic combat answers render rays a tick later than the WASM host, so counters sit a few apart from WASM. Same drops, same fix.", + "pre133": {"kills": 605, "hits": 1706}, + "s133": {"kills": 294, "hits": 2037}, + "s134_head": {"kills": 247, "hits": 2079}, + "class_off": {"kills": 296, "hits": 2045}, + "cue_off": {"kills": 314, "hits": 2022}, + "authority_relaxed": {"kills": 247, "hits": 2079}, + "channels_off": {"kills": 247, "hits": 2079}, + "fix_f": {"kills": 314, "hits": 2022} + }, + "causes": { + "drop_133_522_to_302": "Track.vel became an estimate from noisy measured places (was the target's true velocity); the forecast, the aim lead and the interceptor's launch Fix all read it. Class-off ~= baseline, 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.", + "drop_134_302_to_243": "#134 extended the network cue 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 drop (243 -> 325).", + "own_fire_FIRE_QUALITY_channels": "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.", + "issue_140": "Does not affect this loadout, by fact: the fixture deploys 64 integrated complexes and no separate radar, so every profile is embedded with channels = 0; the channel-age bug binds only where a profile has channels. The channels-off A/B changed nothing." + }, + "fix": { + "file": "airdef-mod/src/sim/sight.rs", + "change": "The network cue looks only through a separate fire-quality radar (sam.kind == SamKind::Radar), never the weapon's embedded radar; the embedded radar keeps its beam/revisit/lock acquisition as before #134.", + "preserved": "All radar profiles, channel limits, own-fire authority (own_fire_within / FIRE_QUALITY), and the measurement-only class/speed contract (#133). No target truth is injected.", + "tests": [ + "airdef-mod/tests/saturation.rs (deterministic checkpoint replica + audit + #140 loadout fact)", + "airdef-mod/src/sim/sensor_tests.rs::a_network_plot_cues_a_separate_fire_radar_but_not_the_embedded_one", + "airdef-mod/src/sim/why.rs::Sim::launch_audit (on-demand tolerance diagnostic)" + ] + }, + "after_fix_wasm": { + "checkpoint_tick_2102": {"kills": 325, "hits": 2011, "airborne": 184, "missiles_airborne": 4, "fuel_max_tick": 118325396, "fuel_failures": 0}, + "final_tick_3302": {"kills": 385, "hits": 2472, "airborne": 9, "missiles_airborne": 2, "fuel_max_tick": 176588234, "fuel_failures": 0}, + "late_raid_chat": ["Разведка противника: впереди налёта высланы разведчики"] + }, + "target_range": "Post-fix checkpoint ~325 intercepts (WASM) / 314 (native replica) at tick 2102, fuel max ~118M/300M. The residual gap to the pre-#133 522 is the measurement-only velocity contract cost (#133), kept deliberately: class and speed come from measurements, never the target's own figures." +} diff --git a/tools/airdef.py b/tools/airdef.py index f8ad24d..8da0b98 100644 --- a/tools/airdef.py +++ b/tools/airdef.py @@ -158,7 +158,7 @@ def test_wasm(): BUDGET_SCENARIO = "tests/budgets/wasm_flat_budget.toml" -BUDGET_ASSERTED_SHA256 = "134cb4667691cf9faa639ed37120941d829cfc13ce45e9638582c409d9e0dd29" +BUDGET_ASSERTED_SHA256 = "eaee000d05aa1da232db5dfb225fa067e29bb554edcb0a90ddf1aad18a8aae29" def fuel_measurements(output):