ballistics_engine/explain.rs
1//! MBA-1345: explain why two fully resolved solutions differ.
2//!
3//! For each input group the difference is attributed by a SYMMETRIC counterfactual: swap the
4//! group from B into A, and independently from A into B, and average. That makes the answer
5//! independent of replacement order, which a one-directional swap is not. Whatever the group
6//! contributions fail to explain is reported as an explicit interaction remainder and is never
7//! distributed across groups: for correlated inputs there is no unique causal attribution, and
8//! pretending otherwise is the failure this design exists to avoid.
9//!
10//! # The derived-value exclusion rule
11//!
12//! A resolved request echoes some axes as plain, independent inputs, but a few are actually
13//! COMPUTED from a different axis's value. A group swap must exclude any axis whose resolved
14//! value is computed from another axis whenever that source axis is:
15//!
16//! (a) in a DIFFERENT group, or
17//! (b) itself excluded (from the SAME group).
18//!
19//! Same-group derivation where the source is ALSO swapped normally is self-consistent and
20//! needs no special handling -- both values move together, so the pairing the derivation
21//! depends on is preserved. That is why, for instance, `Temperature`'s ICAO-standard default
22//! from `Altitude` is ordinarily harmless: swapping the whole `Atmosphere` group moves both
23//! (when `Altitude` is not itself excluded -- see the QNH case below, which is exactly the
24//! exception).
25//!
26//! Three axes are known to violate this, found one at a time by successive reviews, each
27//! documented below as its own subsection: `MuzzleAngle` (case (a): derived from
28//! `MuzzleVelocity` and `Atmosphere`, both different groups), `WindDirection` under compass
29//! wind (case (a): derived from `ShotGeometry`'s `ShotAzimuth`), and `Pressure` under a QNH
30//! atmosphere (case (b): derived from `Atmosphere`'s own `Altitude`, which is excluded rather
31//! than swapped). There is no taxonomy metadata recording "derived from" relationships -- each
32//! is handled as an explicit, documented special case in `plan_exclusions` rather than a
33//! generic mechanism, since three known instances do not justify inventing a
34//! derivation-tracking data model the taxonomy does not otherwise have. A future instance
35//! should be diagnosed against this same rule and added the same way.
36//!
37//! ## Instance 1: `MuzzleAngle` is derived, not independent, once a zero distance is present
38//!
39//! `ZeroSightGeometry` lists `MuzzleAngle` -- but on a RESOLVED request, `muzzle_angle_rad` is
40//! not an independent input whenever `zero_distance_m` is also present: it is the
41//! ALREADY-SEARCHED elevation, a function of muzzle velocity and atmosphere as much as of any
42//! sight/zero knob in this group (review C1; rule case (a) -- `MuzzleVelocity` and `Atmosphere`
43//! are different groups). Naively applying it as an ordinary axis would import muzzle-velocity's
44//! and atmosphere's own differences into `ZeroSightGeometry`'s bucket -- concretely, swapping a
45//! group in which every visible sight/zero setting is byte-identical between the two requests
46//! would still report a non-zero contribution, because the group also carried the OTHER
47//! request's fully-baked elevation. A shooter reading "5 cm of this is your zero/sight geometry"
48//! would go check a scope that never moved.
49//!
50//! `taxonomy.rs`'s `axes_in_group(ZeroSightGeometry)` lists `MuzzleAngle` FIRST specifically to
51//! fix this: `SightHeight` (always present, `requires_rezero`) is applied second, and its own
52//! re-resolve clears and re-derives the elevation for the DESTINATION's own muzzle velocity and
53//! atmosphere, overwriting whatever `MuzzleAngle`'s write introduced -- see that match arm's own
54//! comment for the full mechanism, and `every_groups_contribution_matches_an_independent_recomputation`
55//! below for the acceptance test (identical sight/zero inputs must report an EXACTLY zero
56//! `ZeroSightGeometry`, not merely a small one). For an angle-only request (no `zero_distance_m`
57//! on the destination), nothing later in the group clears the angle, so `MuzzleAngle`'s own
58//! write correctly stands: there it genuinely IS the independent input, and it must still be
59//! swapped in that case -- see `muzzle_angle_is_still_swapped_for_an_angle_only_request` (review
60//! round 3, N3): the fix above is only correct BECAUSE the later clear-gate is conditioned on
61//! `zero_distance_m` being present, not unconditionally on axis order, and there was no test
62//! pinning that down until this one.
63//!
64//! ## Instance 2: `WindDirection` is derived from `ShotAzimuth` under compass-referenced wind
65//!
66//! Under `wind_reference: "compass"`, the resolved (shooter-relative) `direction_from_rad` is
67//! `compass_bearing_to_shooter_relative_rad(bearing, shot_azimuth_rad)` =
68//! `(bearing - shot_azimuth_rad).rem_euclid(2*pi)` (`solve_v1.rs`'s `resolve_wind`, `wind.rs`) --
69//! a function of `ShotAzimuth`, which lives in `ShotGeometry`, a DIFFERENT group (review round
70//! 3, N1; rule case (a)). [`with_axis`] already refuses to swap `ShotAzimuth` itself under
71//! compass wind, protecting `ShotGeometry`'s own number, but nothing stopped `WindDirection`
72//! from moving on ITS OWN: two compass-referenced requests with an IDENTICAL raw wind bearing
73//! but different `shot_azimuth_rad` resolve to DIFFERENT `direction_from_rad` values purely
74//! because of the azimuth difference, and swapping `WindDirection` would report that as a `Wind`
75//! contribution -- the exact `MuzzleAngle` shape, relabelled onto a different pair of groups.
76//! `plan_exclusions` now excludes `WindDirection` (both legs, both directions) whenever EITHER
77//! `a` or `b` is compass-referenced, regardless of whether the raw bearing or the azimuth
78//! actually differ -- the same unconditional-on-values pattern the `Altitude`/`ShotAzimuth`
79//! guards already use. See `wind_direction_is_excluded_under_compass_wind_even_with_an_identical_raw_bearing`.
80//!
81//! ## Instance 3: `Pressure` is derived from `Altitude` under a QNH atmosphere
82//!
83//! Under `pressure_reference: "qnh"`, the resolved `pressure_pa` is
84//! `reduce_qnh_to_station_pressure(qnh_value, altitude_m)` (`solve_v1.rs`'s `resolve_atmosphere`)
85//! -- a function of `Altitude`, which lives in the SAME group, `Atmosphere` (review round 3, N2;
86//! rule case (b)). Same-group derivation is ordinarily fine (see the rule above), but `Altitude`
87//! itself is excluded whenever `pressure_reference` is QNH -- so the pairing breaks: `Pressure`
88//! would still move while its source, `Altitude`, stays fixed on both legs, leaking a value that
89//! is only physically valid at the OTHER request's (unswapped) altitude into `Atmosphere`'s
90//! contribution, in violation of the third `assumptions` entry's promise that an excluded axis's
91//! effect lands in the remainder, not partially in its group. `plan_exclusions` now excludes
92//! `Pressure` too, using the exact same QNH condition that already excludes `Altitude`. See
93//! `pressure_exclusion_does_not_leak_a_partial_effect_into_atmosphere` (a QNH-vs-QNH fixture,
94//! added alongside the existing QNH-vs-absolute `altitude_exclusion_does_not_leak_a_partial_effect_into_atmosphere`,
95//! which cannot exercise this specific hazard because a plain absolute pressure has no altitude
96//! dependency to leak in the first place).
97//!
98//! **Known limitation, not fixed:** `Temperature` has the identical hazard when it is OMITTED
99//! from the raw request under a QNH atmosphere -- its ICAO-standard default
100//! (`calculate_icao_standard_atmosphere(altitude_m)`) is ALSO a function of `Altitude`. Unlike
101//! `Pressure`'s dependency, this one is not detectable from a resolved request alone: the
102//! resolved `temperature_k` echo carries only the concrete numeric value, with no record of
103//! whether it came from an explicit input or from this default, and the assumption notice that
104//! WOULD say so is not part of `ResolvedSolveRequestV1` at all. Excluding `Temperature`
105//! unconditionally whenever `Altitude` is QNH-excluded would trade this rare, real leak for a
106//! much more common one (silently discarding a genuinely independent temperature difference on
107//! every ordinary QNH request that happens to also specify a temperature), which is a worse
108//! trade. Left undetected and undocumented anywhere else but here.
109//!
110//! # Symmetric exclusion: an axis unusable on either side must be excluded on BOTH legs
111//!
112//! [`with_axis`] can refuse an axis for a request-specific structural reason:
113//! `KernelError::AxisUnsupportedForRequest` for `Altitude` under a QNH-referenced atmosphere or
114//! `ShotAzimuth` under compass-referenced wind, and `KernelError::AxisAbsent` for the three wind
115//! axes when the request being written TO uses segmented wind (`access.rs`'s module doc).
116//! [`read_axis`] separately returns `None` for the same three wind axes when the request being
117//! read FROM is segmented, and also for a handful of ordinarily-optional scalar fields
118//! (`length_m`, `latitude_rad`, the two zero-POI offsets, the lateral sight offset, and -- true
119//! of the code though not named in `read_axis`'s own doc comment -- `zero_distance_m` on a
120//! request zeroed purely by an explicit angle) that just were not supplied on a request.
121//!
122//! An earlier revision of this module decided this PER LEG: forward excluded an axis only if
123//! `A` itself refused it (or lacked a value to read from `B`), and backward only if `B` did.
124//! That is wrong (review I1): if only ONE leg excludes an axis, the two legs stop measuring the
125//! same counterfactual. A QNH-referenced `A` compared against a non-QNH `B`, for instance, has
126//! forward keep `A`'s own altitude (refused) while backward hands `B` the whole of `A`'s
127//! altitude (not refused) -- so `contribution(Atmosphere)` ends up as the full
128//! temperature/pressure/humidity effect PLUS HALF of a completely separate altitude difference,
129//! while the report's own `assumptions` claim that effect went to the interaction remainder.
130//!
131//! `plan_exclusions` fixes this by deciding exclusions for a WHOLE group ONCE, from the two
132//! ORIGINAL requests together, before either swap direction runs: an axis is excluded from BOTH
133//! legs if EITHER `a` or `b` would refuse it as a destination, or if it is present on exactly
134//! one of `a`/`b` (review I2 -- the same splitting hazard, via `read_axis` instead of
135//! `with_axis`: an ordinarily-optional field supplied on one saved profile and omitted on the
136//! other, such as `latitude_rad`, would otherwise have forward keep `A`'s own value while
137//! backward overwrites `B` with it, again half-attributing a real difference with no record of
138//! it at all). Both cases are recorded in [`SolutionDiffReportV1::skipped_axes`] -- ALWAYS as a
139//! pair, one entry per direction, so the report always explains both legs' identical treatment
140//! of that axis -- with a `reason` reworded for this whole-group context rather than reused
141//! verbatim from `with_axis`'s own per-axis-perturbation wording (review I1's second point: a
142//! reason like "perturbing altitude would move air density without moving pressure" is
143//! misleading here, where `Pressure` is a SEPARATE axis in the same group and IS copied
144//! normally). An axis absent on BOTH `a` and `b` is not reported at all: there is nothing to
145//! attribute either way, the same as if neither request had ever mentioned it.
146//!
147//! Either way, an exclusion never aborts the comparison -- only that one axis (or, for the
148//! magnus/enhanced_spin_drift pair below, both together) is left out of that one group, on both
149//! legs. Two cross-axis conflicts are excluded this same way even though neither is a "derived
150//! value" in the sense above (F2, 0.33.0 final-review fix wave): `CoriolisEnabled` differing
151//! while either request lacks `latitude_rad` (`solve_v1` requires it whenever coriolis is
152//! enabled), and `MagnusEnabled`/`EnhancedSpinDriftEnabled` swapping between two requests with
153//! opposite flags set (`solve_v1` rejects both true on one request, `taxonomy.rs`'s Known
154//! Limitation (d)) -- see `plan_exclusions`'s own two guards for the full mechanism, and for why
155//! the magnus/ESD case excludes BOTH axes together rather than just the one whose write would
156//! fail first. A GENUINE failure -- some OTHER `solve_v1` re-resolve failure partway through
157//! applying a group, not one of the cases `plan_exclusions` already recognizes -- is NOT one of
158//! these cases and propagates as an error, uncaught, exactly as `central_difference` and
159//! `bisect_axis` already do for their own non-refusal failures.
160//!
161//! # Why exclusions are decided from the original requests, not the accumulated one
162//!
163//! `plan_exclusions` probes [`with_axis`] against `a` and `b` exactly as passed into
164//! [`explain_difference`] -- never a request `swap_group` has already partly rewritten. This
165//! matters because a group with more than one axis applies its writes one at a time,
166//! re-resolving between them (`swap_group`, via a real `solve_v1` call) so each subsequent
167//! [`with_axis`] call sees the previous write. That re-resolve goes through the reverse
168//! conversion (`request_roundtrip.rs`), which ALWAYS clears `pressure_reference` and
169//! `wind_reference` back to the omitted-field default (that module's own doc: the resolved
170//! values already have the transform baked in, so echoing the mode back would apply it a second
171//! time). That is correct for solving, but it means the very fact `with_axis`'s guards key on --
172//! "was this request originally QNH- or compass-referenced" -- would be erased by the FIRST
173//! re-resolve within a group, not preserved across it, if it were checked against that
174//! progressively-modified request instead.
175//!
176//! `ShotGeometry` lists `TargetDistance`, `ShootingAngle` and `Cant` before `ShotAzimuth`: three
177//! unrelated axes, each triggering a re-resolve, would be applied before it. Checking the
178//! compass guard against a progressively-modified request would have it silently pass by the
179//! time `ShotAzimuth` is reached, building exactly the physically-inverted counterfactual the
180//! guard exists to prevent -- with no error and no skip recorded, because from `with_axis`'s
181//! point of view at that moment the request no longer looks compass-referenced at all. Deciding
182//! every axis's exclusion up front, from `a`/`b` as originally given, makes this impossible by
183//! construction: there is no accumulated, partly-laundered request for the check to see in the
184//! first place. `swap_group` itself never re-derives a refusal at all -- it trusts the
185//! `excluded` list `plan_exclusions` already computed, safely, because a refusal can only become
186//! MORE permissive as a group's later axes are applied (round-tripping only ever clears a
187//! reference-mode echo, it never introduces one): an axis `plan_exclusions` already cleared for
188//! both `a` and `b` is guaranteed to still be writable on `swap_group`'s running request,
189//! however many earlier axes in the same group have already re-resolved it. The test
190//! `shot_azimuth_is_refused_even_when_other_shot_geometry_axes_are_applied_first` pins this down
191//! by exercising exactly that four-axis ordering.
192//!
193//! # The drag description travels with ProjectileDrag (MBA-1603)
194//!
195//! Three resolved inputs describe the projectile's drag without being taxonomy axes:
196//! `projectile.drag_table` (MBA-1597), `projectile.bc_segments` (MBA-1598) and
197//! `corrections.bc5d_table_path`. They are deliberately not axes, so `error-budget` and
198//! `tolerance` never perturb them (except that the BC axis moves a one-band ladder's band with
199//! the scalar, which it must equal), but they are projectile drag all the same. Before MBA-1603 no
200//! group swapped them: every counterfactual kept the destination's own copy, so a difference in
201//! any of them landed whole in `interaction_remainder` with nothing in `skipped_axes` to say why.
202//! Worse, when `drag_model` or the BC also differed, the swap flew one request's band BCs against
203//! the other request's reference curve, so the `ProjectileDrag` contribution described a
204//! projectile neither request had.
205//!
206//! `swap_group` therefore carries the three as one unit with `ProjectileDrag` whenever the two
207//! requests' descriptions differ (`drag_descriptions_differ`). It clears them from the
208//! destination BEFORE the scalar axes are written and writes the source's AFTER them, in one
209//! final re-resolve under `with_axis`'s re-zero rule. Clearing first keeps every intermediate
210//! re-resolve legal: a BC5D table never meets a foreign diameter, which its caliber check
211//! refuses, and no request ever pairs one side's ladder with the other side's table, which
212//! `solve_v1` refuses as `conflicting_fields` when the table is of kind `projectile` (a
213//! `reference` table would fly a foreign ladder silently). Writing last puts the ladder, the
214//! table, or both together, onto a projectile whose `drag_model`, BC, mass and diameter are
215//! already the source's, so band BCs always fly against the curve they were measured against:
216//! `drag_model`'s, or the source's own reference table. When the descriptions are equal
217//! nothing changes, and the comparison is exactly what it was before.
218//!
219//! A BC5D table is not a derived-value hazard in the sense of the rule above. The resolved
220//! request echoes only the table's path; `solve_v1` regenerates the table's ladder on every
221//! re-solve from that request's own BC, drag model, mass and muzzle velocity, and never copies a
222//! ladder from the other request.
223//!
224//! Other inputs that belong to no group are still swapped by none: `effects.aerodynamic_jump`,
225//! `effects.wind_shear_model`, `solver.*` and `shot.ground_threshold_m`. A difference in one of
226//! them lands in `interaction_remainder`.
227
228use serde::{Deserialize, Serialize};
229
230use crate::perturbation::access::{read_axis, with_axis, KernelError};
231use crate::perturbation::taxonomy::{axes_in_group, InputAxis, InputGroup};
232use crate::perturbation::{evaluate, kernel_solve_error, Observation};
233use crate::solve_json::{
234 CorrectionsV1, PressureReferenceV1, ResolvedProjectileV1, ResolvedSolveRequestV1,
235 SolveRequestV1, WindReferenceV1,
236};
237
238/// Schema version for [`SolutionDiffReportV1`].
239pub const EXPLAIN_SCHEMA_VERSION_V1: u32 = 1;
240
241/// The difference between two [`Observation`]s at one range, `b - a`. SI throughout, same sign
242/// convention as [`Observation`] itself.
243#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
244pub struct DeltaV1 {
245 pub drop_m: f64,
246 pub windage_m: f64,
247 pub time_s: f64,
248 pub velocity_mps: f64,
249}
250
251impl DeltaV1 {
252 fn between(a: &Observation, b: &Observation) -> Self {
253 DeltaV1 {
254 drop_m: b.drop_m - a.drop_m,
255 windage_m: b.windage_m - a.windage_m,
256 time_s: b.time_s - a.time_s,
257 velocity_mps: b.velocity_mps - a.velocity_mps,
258 }
259 }
260 fn mean(x: Self, y: Self) -> Self {
261 DeltaV1 {
262 drop_m: 0.5 * (x.drop_m + y.drop_m),
263 windage_m: 0.5 * (x.windage_m + y.windage_m),
264 time_s: 0.5 * (x.time_s + y.time_s),
265 velocity_mps: 0.5 * (x.velocity_mps + y.velocity_mps),
266 }
267 }
268 fn neg(self) -> Self {
269 DeltaV1 {
270 drop_m: -self.drop_m,
271 windage_m: -self.windage_m,
272 time_s: -self.time_s,
273 velocity_mps: -self.velocity_mps,
274 }
275 }
276 fn add(self, o: Self) -> Self {
277 DeltaV1 {
278 drop_m: self.drop_m + o.drop_m,
279 windage_m: self.windage_m + o.windage_m,
280 time_s: self.time_s + o.time_s,
281 velocity_mps: self.velocity_mps + o.velocity_mps,
282 }
283 }
284 fn sub(self, o: Self) -> Self {
285 DeltaV1 {
286 drop_m: self.drop_m - o.drop_m,
287 windage_m: self.windage_m - o.windage_m,
288 time_s: self.time_s - o.time_s,
289 velocity_mps: self.velocity_mps - o.velocity_mps,
290 }
291 }
292}
293
294/// Which leg of a group's symmetric counterfactual swap a [`SkippedAxisV1`] occurred on.
295#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
296#[serde(rename_all = "snake_case")]
297pub enum SwapDirectionV1 {
298 /// Building A with the group's axes replaced by B's values (measured against A).
299 Forward,
300 /// Building B with the group's axes replaced by A's values (measured against B, negated).
301 Backward,
302}
303
304/// One taxonomy axis that could not be carried across during a group's counterfactual swap, and
305/// why -- see the module doc's "Symmetric exclusion" section. Always recorded in pairs, one per
306/// [`SwapDirectionV1`], even when only one direction independently hit the refusal or absence:
307/// the OTHER direction is excluded too, to keep both legs measuring the same counterfactual.
308#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
309pub struct SkippedAxisV1 {
310 pub group: InputGroup,
311 pub axis: InputAxis,
312 pub direction: SwapDirectionV1,
313 pub reason: String,
314}
315
316#[derive(Debug, Clone, Serialize, Deserialize)]
317pub struct GroupContributionV1 {
318 pub group: InputGroup,
319 pub delta: DeltaV1,
320}
321
322#[derive(Debug, Clone, Serialize, Deserialize)]
323pub struct SolutionDiffRowV1 {
324 pub range_m: f64,
325 pub total: DeltaV1,
326 pub contributions: Vec<GroupContributionV1>,
327 pub interaction_remainder: DeltaV1,
328}
329
330#[derive(Debug, Clone, Serialize, Deserialize)]
331pub struct SolutionDiffReportV1 {
332 pub schema_version: u32,
333 pub method: String,
334 pub assumptions: Vec<String>,
335 /// Axes excluded from a group's swap because one or both requests could not carry them --
336 /// see the module doc's "Symmetric exclusion". Always excluded from BOTH swap directions,
337 /// and reported as a pair (one `SkippedAxisV1` per direction), even when only one direction
338 /// independently hit the refusal or absence. Never distributed or hidden: whatever effect a
339 /// skipped axis would have had is left inside `SolutionDiffRowV1::interaction_remainder`,
340 /// not silently absorbed into that axis's own group.
341 pub skipped_axes: Vec<SkippedAxisV1>,
342 pub rows: Vec<SolutionDiffRowV1>,
343}
344
345/// Word an axis's exclusion reason for the whole-group context, rather than reusing
346/// `with_axis`'s own per-axis-perturbation wording verbatim (review I1): `with_axis`'s own
347/// `Altitude` reason talks about perturbing altitude "without moving" pressure, which is
348/// misleading here, where `Pressure` is a SEPARATE axis in the same group that DOES get copied
349/// normally. `own_refusal` is this DIRECTION's own refusal (if any); `other_refusal` is the
350/// OTHER direction's, used to explain a "sympathetic" exclusion -- one leg that would not have
351/// refused on its own, excluded anyway to keep both legs measuring the same counterfactual.
352fn describe_refusal(
353 axis: InputAxis,
354 own_refusal: &Option<String>,
355 other_refusal: &Option<String>,
356) -> String {
357 let context = match axis {
358 InputAxis::Altitude => {
359 "altitude is tied to pressure under a QNH-referenced atmosphere; this group swap \
360 cannot re-derive that relationship for a different altitude. \
361 Temperature/RelativeHumidity/Latitude in the same group ARE copied normally; \
362 Pressure is ALSO excluded whenever the two requests' altitudes actually differ \
363 (see Pressure's own skipped_axes entry when that applies), but is copied normally \
364 alongside Altitude's exclusion when the altitudes happen to match"
365 }
366 InputAxis::ShotAzimuth => {
367 "the shot azimuth is tied to an earth-fixed wind bearing under compass-referenced \
368 wind; this group swap cannot re-derive that bearing for a different azimuth, even \
369 though TargetDistance/ShootingAngle/Cant/AimAzimuth/TargetHeight in the same group \
370 ARE copied normally"
371 }
372 _ => "this axis cannot be swapped for one of the two requests being compared",
373 };
374 match own_refusal {
375 Some(reason) => format!("{context} ({reason})"),
376 None => {
377 format!(
378 "excluded to match the other swap direction, which cannot swap this axis: {context} \
379 ({})",
380 other_refusal.as_deref().unwrap_or("no further detail available")
381 )
382 }
383 }
384}
385
386/// Word a wind axis's exclusion reason (taxonomy.rs Known Limitation (c)): `own_segmented` is
387/// whether THIS direction's destination is segmented (blocking the write); `other_segmented` is
388/// whether the OTHER direction's destination is segmented (which, as this direction's source,
389/// blocks reading a value to copy).
390fn describe_wind_absence(own_segmented: bool, other_segmented: bool) -> String {
391 match (own_segmented, other_segmented) {
392 (true, true) => "both requests being compared use segmented wind; neither has a \
393 single scalar value for this axis"
394 .to_string(),
395 (true, false) => "this request's wind is segmented, so there is no single scalar \
396 field to write this axis into"
397 .to_string(),
398 (false, true) => "the other request's wind is segmented, so there is no single \
399 scalar value to read for this axis"
400 .to_string(),
401 (false, false) => {
402 unreachable!("describe_wind_absence called when neither side is segmented")
403 }
404 }
405}
406
407/// True when `r`'s wind was entered compass-referenced. Shares `access.rs`'s own
408/// `wind_reference_of` (review round 4 -- widened to `pub(crate)` for exactly this reuse)
409/// rather than re-matching the two wind shapes a second time -- the same fact [`with_axis`]
410/// checks to refuse `ShotAzimuth` there, because `WindDirection`'s OWN resolved value depends on
411/// it too (module doc, "The derived-value exclusion rule", Instance 2).
412fn is_compass_referenced(r: &ResolvedSolveRequestV1) -> bool {
413 crate::perturbation::access::wind_reference_of(&r.wind) == Some(WindReferenceV1::Compass)
414}
415
416/// True when `r`'s atmosphere was entered as a QNH altimeter setting. Read directly from the
417/// public `ResolvedAtmosphereV1::pressure_reference` echo -- the same fact [`with_axis`] checks
418/// to refuse `Altitude` (`access.rs`) -- because `Pressure`'s OWN resolved value depends on it
419/// too (module doc, "The derived-value exclusion rule", Instance 3).
420fn is_qnh_referenced(r: &ResolvedSolveRequestV1) -> bool {
421 r.atmosphere.pressure_reference == Some(PressureReferenceV1::Qnh)
422}
423
424/// Decide, for one group, which axes must be excluded from BOTH legs of the symmetric swap
425/// between `a` and `b`, and produce the [`SkippedAxisV1`] entries explaining why -- see the
426/// module doc's "Symmetric exclusion" section for why a per-leg decision is not good enough,
427/// and "The derived-value exclusion rule" for the two checks that are not about refusal or
428/// absence at all.
429///
430/// Five structurally different reasons exclude an axis, each checked directly against `a` and
431/// `b` as originally given (see the module doc's "Why exclusions are decided from the original
432/// requests"):
433///
434/// - One of the three wind axes, where either request's wind is segmented (taxonomy.rs Known
435/// Limitation (c)) -- detected via [`read_axis`] returning `None`.
436/// - `WindDirection`, derived from `ShotGeometry`'s `ShotAzimuth` whenever either request is
437/// compass-referenced (review round 3, N1) -- the derived-value rule's case (a).
438/// - `Pressure`, derived from this SAME group's `Altitude` whenever either request is
439/// QNH-referenced, and `Altitude` is itself excluded in that case (review round 3, N2) -- the
440/// derived-value rule's case (b).
441/// - An ordinarily-optional axis present on exactly one of `a`/`b` (review I2).
442/// - [`with_axis`] refusing the axis as a destination for `a` XOR `b` (review I1) -- a
443/// QNH-referenced `Altitude` or a compass-referenced `ShotAzimuth`. Probed with each
444/// request's OWN current value for that axis (guaranteed well-typed and finite), since
445/// `with_axis`'s guards depend only on `axis` and the request's own structural fields, never
446/// on the value being written.
447///
448/// An axis absent on BOTH `a` and `b` triggers none of these and is silently left out of both
449/// the exclusion list and the report: there is nothing to attribute either way.
450///
451/// # Errors
452///
453/// Only an UNEXPECTED `with_axis` failure (not `AxisUnsupportedForRequest`) propagates -- for
454/// instance a `TypeMismatch`/`NonFinite`, which should not be reachable here at all, since every
455/// probed value came from `read_axis` for the identical axis on the identical request.
456fn plan_exclusions(
457 a: &ResolvedSolveRequestV1,
458 b: &ResolvedSolveRequestV1,
459 group: InputGroup,
460) -> Result<(Vec<InputAxis>, Vec<SkippedAxisV1>), KernelError> {
461 let mut excluded = Vec::new();
462 let mut skipped = Vec::new();
463
464 for &axis in axes_in_group(group) {
465 // F2 (0.33.0 final-review fix wave): an axis can be pre-excluded by an EARLIER axis in
466 // this same group's iteration -- currently only EnhancedSpinDriftEnabled, excluded
467 // alongside MagnusEnabled below when the two conflict -- in which case its own turn has
468 // nothing left to decide or record.
469 if excluded.contains(&axis) {
470 continue;
471 }
472
473 let a_value = read_axis(a, axis);
474 let b_value = read_axis(b, axis);
475
476 if matches!(
477 axis,
478 InputAxis::WindSpeed | InputAxis::WindDirection | InputAxis::WindVertical
479 ) {
480 if a_value.is_none() || b_value.is_none() {
481 excluded.push(axis);
482 skipped.push(SkippedAxisV1 {
483 group,
484 axis,
485 direction: SwapDirectionV1::Forward,
486 reason: describe_wind_absence(a_value.is_none(), b_value.is_none()),
487 });
488 skipped.push(SkippedAxisV1 {
489 group,
490 axis,
491 direction: SwapDirectionV1::Backward,
492 reason: describe_wind_absence(b_value.is_none(), a_value.is_none()),
493 });
494 continue;
495 }
496 // N1 (review round 3, narrowed by F1): WindDirection's resolved value is ALSO
497 // derived from ShotAzimuth -- ShotGeometry, a DIFFERENT group -- whenever either
498 // side is compass-referenced (module doc, derived-value rule, Instance 2). But the
499 // derivation only actually CONTAMINATES the swap when the azimuths differ: if
500 // a.shot.shot_azimuth_rad == b.shot.shot_azimuth_rad, the compass-to-shooter-relative
501 // shift is the SAME on both sides, so the difference between the two resolved
502 // directions is exactly the difference between the two raw bearings -- a genuine
503 // Wind-group effect, not azimuth contamination (F1: excluding unconditionally on the
504 // mode flag over-fires, under-attributing Wind on the most natural same-shot-
505 // direction compass comparison). `with_axis`'s OWN Altitude/ShotAzimuth guards do
506 // not need this refinement -- they only ever see ONE request, so they cannot compare
507 // -- but `plan_exclusions` has both and must.
508 if axis == InputAxis::WindDirection
509 && (is_compass_referenced(a) || is_compass_referenced(b))
510 && a.shot.shot_azimuth_rad != b.shot.shot_azimuth_rad
511 {
512 excluded.push(axis);
513 let reason = "the resolved wind direction is derived from shot_azimuth_rad (a \
514 ShotGeometry axis) under compass-referenced wind; swapping it \
515 here would attribute part of a shot-azimuth difference to Wind \
516 instead of leaving it in the interaction remainder"
517 .to_string();
518 skipped.push(SkippedAxisV1 {
519 group,
520 axis,
521 direction: SwapDirectionV1::Forward,
522 reason: reason.clone(),
523 });
524 skipped.push(SkippedAxisV1 {
525 group,
526 axis,
527 direction: SwapDirectionV1::Backward,
528 reason,
529 });
530 }
531 continue;
532 }
533
534 // N2 (review round 3, narrowed by F1): Pressure's resolved value is derived from
535 // Altitude -- the SAME group, but Altitude is itself excluded whenever either side is
536 // QNH-referenced, so the pairing that would ordinarily make same-group derivation
537 // harmless is broken (module doc, derived-value rule, Instance 3). But this only
538 // actually breaks the pairing when the altitudes differ: if
539 // a.atmosphere.altitude_m == b.atmosphere.altitude_m, the QNH-reduced pressures differ
540 // only by the raw altimeter setting, and the swapped value stays physically valid at
541 // the (unmoved) destination altitude -- excluding unconditionally on the mode flag
542 // over-fires, under-attributing Atmosphere on the most natural same-location QNH
543 // comparison (F1). See the WindDirection guard above for why `with_axis`'s own
544 // unconditional guards do not need (and cannot use) this same refinement.
545 if axis == InputAxis::Pressure
546 && (is_qnh_referenced(a) || is_qnh_referenced(b))
547 && a.atmosphere.altitude_m != b.atmosphere.altitude_m
548 {
549 excluded.push(axis);
550 let reason = "the resolved station pressure is derived from altitude_m under a \
551 QNH-referenced atmosphere, and Altitude is excluded from this same \
552 comparison; swapping Pressure alone would move a value that is only \
553 physically valid at the OTHER request's (unswapped) altitude"
554 .to_string();
555 skipped.push(SkippedAxisV1 {
556 group,
557 axis,
558 direction: SwapDirectionV1::Forward,
559 reason: reason.clone(),
560 });
561 skipped.push(SkippedAxisV1 {
562 group,
563 axis,
564 direction: SwapDirectionV1::Backward,
565 reason,
566 });
567 continue;
568 }
569
570 // F2 (0.33.0 final-review fix wave): magnus and enhanced_spin_drift cannot both be true
571 // on any ONE resolved request (`solve_v1`'s `validate_effects` rejects that combination
572 // outright, `taxonomy.rs`'s Known Limitation (d)), so two requests that each solve fine
573 // alone -- one with magnus on, the other with enhanced_spin_drift on -- make
574 // `swap_group`'s fixed axis-at-a-time order (`MagnusEnabled` always applied before
575 // `EnhancedSpinDriftEnabled`, `axes_in_group` above) walk straight into that conflict:
576 // writing the destination's NEW magnus value lands on a request that still carries its
577 // OWN unswapped enhanced_spin_drift (not yet overwritten), transiently combining two
578 // "true"s whenever the source's magnus and the destination's enhanced_spin_drift are
579 // both true. Excluding only ONE of the two axes does not fix this in general -- it
580 // merely relocates the identical hazard to the OTHER axis's write on the OTHER leg
581 // (confirmed by direct construction, not assumed: excluding just `MagnusEnabled` leaves
582 // `EnhancedSpinDriftEnabled`'s own later write to collide with the untouched destination
583 // magnus on whichever leg was previously safe), so both axes are excluded together
584 // whenever EITHER leg could conflict (`(b.magnus && a.esd) || (a.magnus && b.esd)`; at
585 // most one of the two can ever be true at once, since neither `a` nor `b` can have both
586 // flags true individually, but either alone is enough to require excluding both axes) --
587 // their real difference falls to the interaction remainder instead of aborting the
588 // report. Decided once, from both ORIGINALS, when the loop reaches `MagnusEnabled`
589 // (first in this group's fixed axis order); the `excluded.contains` guard at the top of
590 // this loop skips `EnhancedSpinDriftEnabled`'s own turn once this fires.
591 if axis == InputAxis::MagnusEnabled
592 && ((a.effects.magnus && b.effects.enhanced_spin_drift)
593 || (b.effects.magnus && a.effects.enhanced_spin_drift))
594 {
595 let reason = "magnus and enhanced_spin_drift cannot both be enabled on one resolved \
596 request, and one of these two requests has magnus enabled while the \
597 other has enhanced_spin_drift enabled; swapping either flag alone \
598 would transiently combine a newly-written true with the destination's \
599 own still-unswapped true on the other flag, which solve_v1 rejects as \
600 a conflict, so both effects are excluded together rather than aborting \
601 the comparison"
602 .to_string();
603 for excluded_axis in [
604 InputAxis::MagnusEnabled,
605 InputAxis::EnhancedSpinDriftEnabled,
606 ] {
607 excluded.push(excluded_axis);
608 skipped.push(SkippedAxisV1 {
609 group,
610 axis: excluded_axis,
611 direction: SwapDirectionV1::Forward,
612 reason: reason.clone(),
613 });
614 skipped.push(SkippedAxisV1 {
615 group,
616 axis: excluded_axis,
617 direction: SwapDirectionV1::Backward,
618 reason: reason.clone(),
619 });
620 }
621 continue;
622 }
623
624 // F2 (0.33.0 final-review fix wave): `with_axis` performs no cross-field validation at
625 // all -- it only ever builds the DTO -- so writing `CoriolisEnabled` onto a request that
626 // lacks `latitude_rad` does not fail HERE; it fails later, inside `swap_group`'s own
627 // re-resolve (`solve_v1`'s "latitude_rad is required when the Coriolis effect is
628 // enabled"), a genuine `KernelError::Solve`, not one of the refusal cases this function
629 // otherwise catches -- so, uncaught, it aborts `explain_difference` ENTIRELY, even when
630 // `a` and `b` each solve fine on their own. Only a risk when the flags actually DIFFER
631 // (swapping an identical flag is a no-op regardless of latitude_rad) and either side
632 // lacks `latitude_rad` -- a request that itself already has coriolis enabled is
633 // guaranteed, by its own prior validation, to already carry `latitude_rad`, so the only
634 // way this validation can newly fail is turning the flag ON for a destination that never
635 // supplied one.
636 if axis == InputAxis::CoriolisEnabled
637 && a.effects.coriolis != b.effects.coriolis
638 && (a.atmosphere.latitude_rad.is_none() || b.atmosphere.latitude_rad.is_none())
639 {
640 excluded.push(axis);
641 let reason = "the coriolis flag differs between the two requests and at least one \
642 of them has no latitude_rad; solve_v1 requires latitude_rad whenever \
643 the coriolis effect is enabled, so swapping this flag onto the request \
644 that lacks one would fail re-resolution rather than build a valid \
645 counterfactual"
646 .to_string();
647 skipped.push(SkippedAxisV1 {
648 group,
649 axis,
650 direction: SwapDirectionV1::Forward,
651 reason: reason.clone(),
652 });
653 skipped.push(SkippedAxisV1 {
654 group,
655 axis,
656 direction: SwapDirectionV1::Backward,
657 reason,
658 });
659 continue;
660 }
661
662 if a_value.is_some() != b_value.is_some() {
663 excluded.push(axis);
664 let reason = "this axis is present on only one of the two requests being compared \
665 (absent on the other), so there is no symmetric value to swap in \
666 either direction"
667 .to_string();
668 skipped.push(SkippedAxisV1 {
669 group,
670 axis,
671 direction: SwapDirectionV1::Forward,
672 reason: reason.clone(),
673 });
674 skipped.push(SkippedAxisV1 {
675 group,
676 axis,
677 direction: SwapDirectionV1::Backward,
678 reason,
679 });
680 continue;
681 }
682 let (Some(a_value), Some(b_value)) = (a_value, b_value) else {
683 continue; // absent on BOTH sides -- nothing to attribute, not reported.
684 };
685
686 let a_refusal = match with_axis(a, axis, a_value) {
687 Ok(_) => None,
688 Err(KernelError::AxisUnsupportedForRequest { reason, .. }) => Some(reason.to_string()),
689 Err(other) => return Err(other),
690 };
691 let b_refusal = match with_axis(b, axis, b_value) {
692 Ok(_) => None,
693 Err(KernelError::AxisUnsupportedForRequest { reason, .. }) => Some(reason.to_string()),
694 Err(other) => return Err(other),
695 };
696 if a_refusal.is_some() || b_refusal.is_some() {
697 excluded.push(axis);
698 skipped.push(SkippedAxisV1 {
699 group,
700 axis,
701 direction: SwapDirectionV1::Forward,
702 reason: describe_refusal(axis, &a_refusal, &b_refusal),
703 });
704 skipped.push(SkippedAxisV1 {
705 group,
706 axis,
707 direction: SwapDirectionV1::Backward,
708 reason: describe_refusal(axis, &b_refusal, &a_refusal),
709 });
710 }
711 }
712 Ok((excluded, skipped))
713}
714
715/// True when `a` and `b` describe the projectile's drag differently in a way no
716/// `ProjectileDrag` taxonomy axis carries: a caller drag curve (`projectile.drag_table`,
717/// MBA-1597), a BC ladder (`projectile.bc_segments`, MBA-1598), or an offline BC correction
718/// table (`corrections.bc5d_table_path`). `swap_group` carries these three as one unit with
719/// `ProjectileDrag` whenever this is true (MBA-1603); see the module doc.
720///
721/// The destructuring is exhaustive on purpose (no `..`): a new member of
722/// `ResolvedProjectileV1` or `CorrectionsV1` fails to compile here until someone decides
723/// whether it is part of the drag description, instead of silently landing in
724/// `interaction_remainder` the way these three did.
725fn drag_descriptions_differ(a: &ResolvedSolveRequestV1, b: &ResolvedSolveRequestV1) -> bool {
726 let ResolvedProjectileV1 {
727 mass_kg: _,
728 diameter_m: _,
729 length_m: _,
730 drag_model: _,
731 ballistic_coefficient: _,
732 drag_table: _,
733 bc_segments: _,
734 } = &a.projectile;
735 fn correction_table(r: &ResolvedSolveRequestV1) -> Option<&str> {
736 r.corrections
737 .as_ref()
738 .and_then(|CorrectionsV1 { bc5d_table_path }| bc5d_table_path.as_deref())
739 }
740 a.projectile.drag_table != b.projectile.drag_table
741 || a.projectile.bc_segments != b.projectile.bc_segments
742 || correction_table(a) != correction_table(b)
743}
744
745/// Build the [`SolveRequestV1`] representing `dst` with every NON-EXCLUDED axis of `group`
746/// copied from `src`, applying each axis one at a time and re-resolving between writes (via a
747/// real `solve_v1` call) so a later axis in the same group sees the effect of an earlier one --
748/// most importantly, so `ZeroSightGeometry`'s `SightHeight` re-derives the elevation for the
749/// destination's own physics after `MuzzleAngle` (listed first specifically for this) has
750/// written the source's (see the module doc's "`MuzzleAngle` is derived" section). Does not
751/// itself evaluate a trajectory -- the caller does that once, over the whole `ranges_m` slice,
752/// exactly as [`central_difference`](crate::perturbation::central_difference) already does for
753/// its own pair of counterfactual requests.
754///
755/// `excluded` is computed ONCE per group by `plan_exclusions`, from `a`/`b` exactly as passed
756/// into [`explain_difference`], before either swap direction runs -- never re-derived here. See
757/// the module doc's "Why exclusions are decided from the original requests" for why that
758/// ordering is required for correctness, not just convenience: every axis reaching this loop is
759/// guaranteed still writable on the running request, however many earlier axes in this same
760/// group have already re-resolved it.
761///
762/// # Errors
763///
764/// Any [`with_axis`] or `solve_v1` failure propagates via `?` unchanged: by the time an axis
765/// reaches this loop it is not supposed to be refusable -- `plan_exclusions` has already
766/// filtered out every conflict known to reach here, including the magnus/enhanced-spin-drift
767/// pair (`taxonomy.rs`'s Known Limitation (d)) and the coriolis/latitude dependency (F2, 0.33.0
768/// final-review fix wave) -- so a failure here is either a genuine bug (a `read_axis`/
769/// `with_axis` mismatch) or a new, not-yet-recognized conflict, never a structurally
770/// unrepresentable axis or one of the cases already known and excluded.
771fn swap_group(
772 dst: &ResolvedSolveRequestV1,
773 src: &ResolvedSolveRequestV1,
774 group: InputGroup,
775 excluded: &[InputAxis],
776) -> Result<SolveRequestV1, KernelError> {
777 let mut current = dst.clone();
778 // MBA-1603: the drag description travels with ProjectileDrag as one unit, cleared from the
779 // destination BEFORE the scalar axes are written and replaced by the source's AFTER them.
780 // Clearing first keeps every intermediate re-resolve legal (a BC5D table never sees a
781 // foreign diameter, which its caliber check refuses); writing last means the ladder or
782 // table arrives on a projectile whose drag_model, BC, mass and diameter are already the
783 // source's, so band BCs never fly against the wrong reference curve. Skipped entirely when
784 // the two descriptions are equal, which leaves every such comparison exactly as before.
785 let carry_drag_description =
786 group == InputGroup::ProjectileDrag && drag_descriptions_differ(dst, src);
787 if carry_drag_description {
788 current.projectile.drag_table = None;
789 current.projectile.bc_segments = None;
790 current.corrections = None;
791 }
792 for &axis in axes_in_group(group) {
793 if excluded.contains(&axis) {
794 continue;
795 }
796 let Some(v) = read_axis(src, axis) else {
797 // plan_exclusions already excludes any axis present on exactly one side; a `None`
798 // reaching here means it is absent on BOTH sides -- a plain no-op, nothing to copy.
799 continue;
800 };
801 let req = with_axis(¤t, axis, v)?;
802 current = crate::solve_v1::solve_v1(req)
803 .map_err(kernel_solve_error)?
804 .resolved_request;
805 }
806 if carry_drag_description {
807 let mut req: SolveRequestV1 = (¤t).into();
808 req.projectile.drag_table = src.projectile.drag_table.clone();
809 req.projectile.bc_segments = src.projectile.bc_segments.clone();
810 req.corrections = src.corrections.clone();
811 // The same re-zero rule `with_axis` applies to a requires_rezero axis: a new drag
812 // description invalidates the destination's searched elevation.
813 if req.shot.zero_distance_m.is_some() {
814 req.shot.muzzle_angle_rad = None;
815 }
816 current = crate::solve_v1::solve_v1(req)
817 .map_err(kernel_solve_error)?
818 .resolved_request;
819 }
820 Ok((¤t).into())
821}
822
823/// Attribute the difference between two fully resolved solve results to the seven input groups
824/// (MBA-1345).
825///
826/// For each [`InputGroup`] `g`, the forward leg replaces `g`'s axes on `a` with `b`'s values and
827/// measures the change against `a`; the backward leg replaces `g`'s axes on `b` with `a`'s
828/// values and measures the change against `b`, negated. The group's reported contribution is
829/// the MEAN of the two, which is what makes the decomposition independent of which request is
830/// treated as the "before" and which as the "after". Whatever the seven groups do not explain
831/// -- genuine nonlinear interaction between them -- is reported once per range, as
832/// `SolutionDiffRowV1::interaction_remainder`, and is never distributed across the groups: for
833/// correlated inputs there is no unique causal attribution, and pretending otherwise is the
834/// failure this design exists to avoid.
835///
836/// `ranges_m` is passed straight through to two calls to [`evaluate`] per group (one per swap
837/// direction), plus two more for `a`/`b` themselves -- 16 solves for the fixed seven-group
838/// taxonomy, each covering every range in `ranges_m` at once rather than once per range (see
839/// [`evaluate`]'s own cost note). That 16 is NOT the total, though: building each group's
840/// counterfactual (`swap_group`) re-resolves via a full `solve_v1` call after EVERY applied
841/// axis, regardless of whether that specific axis is `requires_rezero` -- not just the ones that
842/// invalidate a zero -- because [`with_axis`] always needs a freshly resolved request to apply
843/// its NEXT write onto. For a request with N present axes (up to the full 32; 5-6 are commonly
844/// absent, e.g. `length_m`/`latitude_rad`/the POI offsets, so N is often closer to 27), that is
845/// up to N solves per direction, 2N total, ON TOP of the 16 -- so a typical call costs on the
846/// order of 16 + 2*27 = 70 solves, not 16. `plan_exclusions` itself adds no solves (it only
847/// calls [`read_axis`]/[`with_axis`], never `solve_v1`), so excluding an axis only ever reduces
848/// this total, never increases it. When the two requests' drag descriptions differ (a drag
849/// table, BC ladder or correction table; see the module doc's MBA-1603 section),
850/// `ProjectileDrag`'s swap re-resolves once more per direction to write the source's
851/// description, so such a call costs 2 solves more.
852///
853/// # Axes that cannot be swapped
854///
855/// See the module doc's "Symmetric exclusion" section for the full explanation. In short:
856/// [`with_axis`] can refuse an axis for a structural reason specific to `a` or `b` (a
857/// QNH-referenced altitude, a compass-referenced shot azimuth, one of the three wind axes under
858/// segmented wind), and an ordinarily-optional axis can be present on only one of `a`/`b`. An
859/// axis affected by either is recorded in the returned report's `skipped_axes` -- one entry per
860/// swap direction, always both together, even though only one direction may have hit the
861/// refusal or absence directly -- and excluded from BOTH legs of that group's swap, so the two
862/// legs keep measuring the same counterfactual; the rest of that axis's group is still
863/// attributed normally, and a refusal never aborts the comparison. An axis absent from BOTH `a`
864/// and `b` (no `length_m` supplied on either, for instance) is skipped without being recorded:
865/// there is nothing there to attribute either way.
866///
867/// # Errors
868///
869/// Returns whatever [`evaluate`], [`with_axis`], or `plan_exclusions` error on `a`, `b`, or
870/// either swapped counterfactual, MINUS the refusal/absence cases above
871/// (`KernelError::AxisUnsupportedForRequest`, the presence-asymmetry case, which never even
872/// reaches a `KernelError`, and the two cross-axis conflicts `plan_exclusions` now also catches
873/// up front -- `CoriolisEnabled` differing while either request lacks `latitude_rad`, and
874/// `MagnusEnabled`/`EnhancedSpinDriftEnabled` swapping between requests with opposite flags,
875/// `taxonomy.rs`'s Known Limitation (d) -- both F2, 0.33.0 final-review fix wave), which are
876/// caught and recorded rather than returned. Every OTHER error -- some other `solve_v1`
877/// re-resolve failing validation partway through building a group's counterfactual, not one of
878/// the cases `plan_exclusions` already recognizes -- propagates unchanged: it is a genuine
879/// failure, not a structurally unrepresentable axis, and must not be silently absorbed into a
880/// skip or a zero contribution.
881///
882/// `a` and `b` are read-only throughout: every counterfactual request is built from a clone
883/// (`swap_group`), never a mutation of either input.
884pub fn explain_difference(
885 a: &ResolvedSolveRequestV1,
886 b: &ResolvedSolveRequestV1,
887 ranges_m: &[f64],
888) -> Result<SolutionDiffReportV1, KernelError> {
889 let obs_a = evaluate(&a.into(), ranges_m)?;
890 let obs_b = evaluate(&b.into(), ranges_m)?;
891
892 let mut skipped_axes = Vec::new();
893 let mut per_group: Vec<(InputGroup, Vec<DeltaV1>)> = Vec::with_capacity(InputGroup::ALL.len());
894 for &group in InputGroup::ALL {
895 let (excluded, mut group_skips) = plan_exclusions(a, b, group)?;
896 skipped_axes.append(&mut group_skips);
897
898 // Each swapped request is evaluated exactly ONCE over the whole `ranges_m` slice below
899 // -- never once per range -- so N ranges do not multiply the cost of a
900 // `requires_rezero` axis's zero search inside `swap_group`.
901 let fwd_req = swap_group(a, b, group, &excluded)?;
902 let bwd_req = swap_group(b, a, group, &excluded)?;
903 let fwd_obs = evaluate(&fwd_req, ranges_m)?;
904 let bwd_obs = evaluate(&bwd_req, ranges_m)?;
905
906 let mut deltas = Vec::with_capacity(ranges_m.len());
907 for i in 0..ranges_m.len() {
908 let forward = DeltaV1::between(&obs_a[i], &fwd_obs[i]); // A with g<-B, vs A
909 let backward = DeltaV1::between(&obs_b[i], &bwd_obs[i]).neg(); // B with g<-A, vs B, negated
910 deltas.push(DeltaV1::mean(forward, backward));
911 }
912 per_group.push((group, deltas));
913 }
914
915 let mut rows = Vec::with_capacity(ranges_m.len());
916 for (i, &range_m) in ranges_m.iter().enumerate() {
917 let total = DeltaV1::between(&obs_a[i], &obs_b[i]);
918 let contributions: Vec<GroupContributionV1> = per_group
919 .iter()
920 .map(|(g, d)| GroupContributionV1 {
921 group: *g,
922 delta: d[i],
923 })
924 .collect();
925 let summed = contributions
926 .iter()
927 .fold(DeltaV1::default(), |acc, c| acc.add(c.delta));
928 rows.push(SolutionDiffRowV1 {
929 range_m,
930 total,
931 contributions,
932 interaction_remainder: total.sub(summed),
933 });
934 }
935
936 Ok(SolutionDiffReportV1 {
937 schema_version: EXPLAIN_SCHEMA_VERSION_V1,
938 method: "symmetric_group_counterfactual".to_string(),
939 assumptions: vec![
940 "Group contributions are symmetric counterfactuals: the mean of swapping the group \
941 in each direction, so the result does not depend on replacement order."
942 .to_string(),
943 "Nonlinear interaction between groups is reported as an explicit interaction \
944 remainder and is NOT distributed across groups. For correlated inputs no unique \
945 causal attribution exists."
946 .to_string(),
947 "An axis that could not be swapped for one or both requests (see skipped_axes) is \
948 excluded from BOTH directions of that axis's group, so the two directions keep \
949 measuring the same counterfactual; any real effect the axis would have had is \
950 folded into the interaction remainder, not silently dropped and not partially \
951 attributed to its group."
952 .to_string(),
953 ],
954 skipped_axes,
955 rows,
956 })
957}
958
959#[cfg(test)]
960mod tests {
961 use super::*;
962
963 fn resolved(mv: f64, temp: f64) -> crate::solve_json::ResolvedSolveRequestV1 {
964 let json = serde_json::json!({
965 "schema_version": 1,
966 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
967 "ballistic_coefficient": 0.243},
968 "rifle": {"muzzle_velocity_mps": mv, "sight_height_m": 0.05},
969 "shot": {"max_range_m": 900.0, "zero_distance_m": 100.0},
970 "atmosphere": {"temperature_k": temp}, "wind": {"speed_mps": 3.0,
971 "direction_from_rad": std::f64::consts::FRAC_PI_2},
972 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
973 })
974 .to_string();
975 let req = crate::solve_json::decode_solve_request_v1(&json).unwrap();
976 crate::solve_v1::solve_v1(req).unwrap().resolved_request
977 }
978
979 /// Varies ONLY `ballistic_coefficient` (ProjectileDrag) and wind speed (Wind), holding
980 /// muzzle velocity, temperature, and every sight/zero knob identical to `resolved()`'s own
981 /// baseline -- see `every_groups_contribution_matches_an_independent_recomputation_bc_and_wind_fixture`.
982 fn resolved_with_bc_and_wind_speed(
983 ballistic_coefficient: f64,
984 wind_speed_mps: f64,
985 ) -> crate::solve_json::ResolvedSolveRequestV1 {
986 let json = serde_json::json!({
987 "schema_version": 1,
988 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
989 "ballistic_coefficient": ballistic_coefficient},
990 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
991 "shot": {"max_range_m": 900.0, "zero_distance_m": 100.0},
992 "atmosphere": {"temperature_k": 288.0},
993 "wind": {"speed_mps": wind_speed_mps,
994 "direction_from_rad": std::f64::consts::FRAC_PI_2},
995 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
996 })
997 .to_string();
998 let req = crate::solve_json::decode_solve_request_v1(&json).unwrap();
999 crate::solve_v1::solve_v1(req).unwrap().resolved_request
1000 }
1001
1002 fn resolved_with_effects(
1003 mv: f64,
1004 magnus: bool,
1005 enhanced_spin_drift: bool,
1006 ) -> crate::solve_json::ResolvedSolveRequestV1 {
1007 let json = serde_json::json!({
1008 "schema_version": 1,
1009 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1010 "ballistic_coefficient": 0.243},
1011 "rifle": {"muzzle_velocity_mps": mv, "sight_height_m": 0.05},
1012 "shot": {"max_range_m": 900.0},
1013 "atmosphere": {"temperature_k": 288.0},
1014 "wind": {},
1015 "solver": {},
1016 "effects": {"magnus": magnus, "enhanced_spin_drift": enhanced_spin_drift},
1017 "sampling": {"interval_m": 50.0}
1018 })
1019 .to_string();
1020 let req = crate::solve_json::decode_solve_request_v1(&json).unwrap();
1021 crate::solve_v1::solve_v1(req).unwrap().resolved_request
1022 }
1023
1024 /// Acceptance criterion: identical requests produce zero deltas and zero contributions, and
1025 /// nothing is reported as skipped (both requests are ordinary constant-wind, absolute-
1026 /// pressure, shooter-relative requests, so no refusal or structural absence should fire).
1027 #[test]
1028 fn identical_requests_produce_zero_everything() {
1029 let a = resolved(823.0, 288.0);
1030 let rep = explain_difference(&a, &a, &[300.0, 600.0]).unwrap();
1031 assert!(
1032 rep.skipped_axes.is_empty(),
1033 "expected no skipped axes for two ordinary, identical requests, got {:?}",
1034 rep.skipped_axes
1035 );
1036 for row in &rep.rows {
1037 assert!(
1038 row.total.drop_m.abs() < 1e-9,
1039 "total drop {}",
1040 row.total.drop_m
1041 );
1042 assert!(row.interaction_remainder.drop_m.abs() < 1e-9);
1043 for c in &row.contributions {
1044 assert!(
1045 c.delta.drop_m.abs() < 1e-9,
1046 "{:?} contributed {}",
1047 c.group,
1048 c.delta.drop_m
1049 );
1050 }
1051 }
1052 }
1053
1054 /// Swapping the two requests negates every reported quantity.
1055 #[test]
1056 fn the_decomposition_is_antisymmetric() {
1057 let a = resolved(823.0, 288.0);
1058 let b = resolved(870.0, 300.0);
1059 let ab = explain_difference(&a, &b, &[600.0]).unwrap();
1060 let ba = explain_difference(&b, &a, &[600.0]).unwrap();
1061 assert!((ab.rows[0].total.drop_m + ba.rows[0].total.drop_m).abs() < 1e-6);
1062 for (x, y) in ab.rows[0]
1063 .contributions
1064 .iter()
1065 .zip(ba.rows[0].contributions.iter())
1066 {
1067 assert_eq!(x.group, y.group);
1068 assert!(
1069 (x.delta.drop_m + y.delta.drop_m).abs() < 1e-6,
1070 "{:?} not antisymmetric",
1071 x.group
1072 );
1073 }
1074 }
1075
1076 /// Contributions plus the remainder must reconstruct the total exactly.
1077 #[test]
1078 fn contributions_plus_remainder_equal_the_total() {
1079 let a = resolved(823.0, 288.0);
1080 let b = resolved(870.0, 300.0);
1081 let rep = explain_difference(&a, &b, &[600.0]).unwrap();
1082 let row = &rep.rows[0];
1083 let sum: f64 = row.contributions.iter().map(|c| c.delta.drop_m).sum();
1084 assert!((sum + row.interaction_remainder.drop_m - row.total.drop_m).abs() < 1e-9);
1085 }
1086
1087 #[test]
1088 fn the_report_states_its_method_and_assumptions() {
1089 let a = resolved(823.0, 288.0);
1090 let rep = explain_difference(&a, &a, &[300.0]).unwrap();
1091 assert_eq!(rep.method, "symmetric_group_counterfactual");
1092 assert!(rep.assumptions.iter().any(|s| s.contains("interaction")));
1093 }
1094
1095 /// (S8, 0.33.0 final-review fix wave) `schema_version` must be the crate's declared
1096 /// constant, not a stray literal that could silently drift from it -- see
1097 /// `crate::tolerance`'s identical `schema_version_matches_the_declared_constant`.
1098 #[test]
1099 fn schema_version_matches_the_declared_constant() {
1100 let a = resolved(823.0, 288.0);
1101 let rep = explain_difference(&a, &a, &[300.0]).unwrap();
1102 assert_eq!(rep.schema_version, EXPLAIN_SCHEMA_VERSION_V1);
1103 }
1104
1105 /// The two source requests must never be mutated by the comparison -- `explain_difference`
1106 /// takes `&ResolvedSolveRequestV1`, and every counterfactual is built from a clone
1107 /// (`swap_group`), never a mutation of `a`/`b` themselves.
1108 #[test]
1109 fn source_requests_are_not_mutated_by_the_comparison() {
1110 let a = resolved(823.0, 288.0);
1111 let b = resolved(870.0, 300.0);
1112 let a_before = a.clone();
1113 let b_before = b.clone();
1114 let _ = explain_difference(&a, &b, &[300.0, 600.0]).unwrap();
1115 assert_eq!(a, a_before, "the first source request changed");
1116 assert_eq!(b, b_before, "the second source request changed");
1117 }
1118
1119 /// A forward-only (or backward-only) implementation would report either endpoint instead of
1120 /// their mean. Recompute the MuzzleVelocity group's forward and backward legs directly,
1121 /// using the same building blocks `explain_difference` uses internally, and confirm (a) they
1122 /// genuinely differ here -- or averaging them would be indistinguishable from reporting
1123 /// either alone -- and (b) the reported contribution is exactly their mean, not either one.
1124 ///
1125 /// The sanity gate below requires `|forward - backward| > 2e-6`, not `1e-6`: since
1126 /// `mean - forward == (backward - forward) / 2` (and symmetrically for `mean - backward`),
1127 /// a gate of exactly `1e-6` on `|forward - backward|` would only guarantee
1128 /// `|mean - forward| > 5e-7`, half of the `1e-6` margin the two endpoint assertions below
1129 /// actually need -- a value that just cleared the old, looser gate could still trip a
1130 /// false failure on those. `2e-6` is the smallest gate that genuinely implies both.
1131 #[test]
1132 fn contribution_is_the_mean_of_a_genuinely_different_forward_and_backward() {
1133 let a = resolved(823.0, 288.0);
1134 let b = resolved(870.0, 300.0);
1135 let ranges = [600.0];
1136
1137 let obs_a = evaluate(&(&a).into(), &ranges).unwrap();
1138 let obs_b = evaluate(&(&b).into(), &ranges).unwrap();
1139 let (excluded, _skipped) = plan_exclusions(&a, &b, InputGroup::MuzzleVelocity).unwrap();
1140 let fwd_req = swap_group(&a, &b, InputGroup::MuzzleVelocity, &excluded).unwrap();
1141 let bwd_req = swap_group(&b, &a, InputGroup::MuzzleVelocity, &excluded).unwrap();
1142 let fwd_obs = evaluate(&fwd_req, &ranges).unwrap();
1143 let bwd_obs = evaluate(&bwd_req, &ranges).unwrap();
1144 let forward = fwd_obs[0].drop_m - obs_a[0].drop_m;
1145 let backward = obs_b[0].drop_m - bwd_obs[0].drop_m;
1146
1147 assert!(
1148 (forward - backward).abs() > 2e-6,
1149 "forward ({forward}) and backward ({backward}) must genuinely differ here, or this \
1150 test cannot distinguish 'the mean of the two' from 'either endpoint alone'"
1151 );
1152
1153 let rep = explain_difference(&a, &b, &ranges).unwrap();
1154 let mv = rep.rows[0]
1155 .contributions
1156 .iter()
1157 .find(|c| c.group == InputGroup::MuzzleVelocity)
1158 .unwrap();
1159 let expected_mean = 0.5 * (forward + backward);
1160 assert!(
1161 (mv.delta.drop_m - expected_mean).abs() < 1e-9,
1162 "reported {} expected mean {}",
1163 mv.delta.drop_m,
1164 expected_mean
1165 );
1166 assert!(
1167 (mv.delta.drop_m - forward).abs() > 1e-6,
1168 "reported value must not equal the forward leg alone"
1169 );
1170 assert!(
1171 (mv.delta.drop_m - backward).abs() > 1e-6,
1172 "reported value must not equal the backward leg alone"
1173 );
1174 }
1175
1176 /// Cross-checks EVERY group's reported contribution against an independent recomputation
1177 /// (same primitives -- `plan_exclusions` + `swap_group` + `evaluate` -- but the mean is
1178 /// taken here, outside `explain_difference`'s own code path) and the remainder against the
1179 /// same total-minus-sum formula computed independently. This is the check that would fail
1180 /// under: a forward-only computation (the independent mean would disagree with a
1181 /// forward-only report), a remainder silently zeroed or redistributed into the groups (the
1182 /// independent remainder would disagree with a tampered report), or two groups'
1183 /// contributions swapped (checked BY GROUP IDENTITY). Returns the report so callers can
1184 /// layer their own fixture-specific "this group must be zero/non-negligible" assertions on
1185 /// top, since which groups should be non-negligible depends on which axes the caller's own
1186 /// fixture actually varies.
1187 fn assert_matches_independent_recomputation(
1188 a: &crate::solve_json::ResolvedSolveRequestV1,
1189 b: &crate::solve_json::ResolvedSolveRequestV1,
1190 range_m: f64,
1191 ) -> SolutionDiffReportV1 {
1192 let ranges = [range_m];
1193 let rep = explain_difference(a, b, &ranges).unwrap();
1194 let row = &rep.rows[0];
1195
1196 let obs_a = evaluate(&a.into(), &ranges).unwrap();
1197 let obs_b = evaluate(&b.into(), &ranges).unwrap();
1198
1199 let mut independent_sum = DeltaV1::default();
1200 for &group in InputGroup::ALL {
1201 let (excluded, _skipped) = plan_exclusions(a, b, group).unwrap();
1202 let fwd_req = swap_group(a, b, group, &excluded).unwrap();
1203 let bwd_req = swap_group(b, a, group, &excluded).unwrap();
1204 let fwd_obs = evaluate(&fwd_req, &ranges).unwrap();
1205 let bwd_obs = evaluate(&bwd_req, &ranges).unwrap();
1206 let forward = DeltaV1::between(&obs_a[0], &fwd_obs[0]);
1207 let backward = DeltaV1::between(&obs_b[0], &bwd_obs[0]).neg();
1208 let expected = DeltaV1::mean(forward, backward);
1209
1210 let reported = row
1211 .contributions
1212 .iter()
1213 .find(|c| c.group == group)
1214 .unwrap_or_else(|| panic!("{group:?} missing from the report"));
1215 assert!(
1216 (reported.delta.drop_m - expected.drop_m).abs() < 1e-9,
1217 "{group:?}: reported drop {} independent {}",
1218 reported.delta.drop_m,
1219 expected.drop_m
1220 );
1221 assert!(
1222 (reported.delta.windage_m - expected.windage_m).abs() < 1e-9,
1223 "{group:?}: windage mismatch"
1224 );
1225 assert!(
1226 (reported.delta.time_s - expected.time_s).abs() < 1e-9,
1227 "{group:?}: time mismatch"
1228 );
1229 assert!(
1230 (reported.delta.velocity_mps - expected.velocity_mps).abs() < 1e-9,
1231 "{group:?}: velocity mismatch"
1232 );
1233
1234 independent_sum = independent_sum.add(expected);
1235 }
1236
1237 let total = DeltaV1::between(&obs_a[0], &obs_b[0]);
1238 let expected_remainder = total.sub(independent_sum);
1239 assert!(
1240 (row.interaction_remainder.drop_m - expected_remainder.drop_m).abs() < 1e-9,
1241 "reported remainder {} independent remainder {}",
1242 row.interaction_remainder.drop_m,
1243 expected_remainder.drop_m
1244 );
1245
1246 rep
1247 }
1248
1249 /// `resolved()` only ever varies `mv` and `temp`, so a group whose axes are entirely
1250 /// independent of both -- ProjectileDrag, Wind, ShotGeometry, Effects, AND (review C1)
1251 /// ZeroSightGeometry -- must come back EXACTLY zero: nothing to swap, since every one of its
1252 /// axis VALUES is identical on `a` and `b`. Before the C1 fix, `ZeroSightGeometry` was NOT
1253 /// zero here despite that: it also carried `MuzzleAngle`, the RESOLVED elevation, which is a
1254 /// function of muzzle velocity and air density -- so it silently imported the OTHER
1255 /// request's baked-in elevation even though every explicit sight/zero knob was identical.
1256 /// `axes_in_group(ZeroSightGeometry)` now lists `MuzzleAngle` first specifically so a
1257 /// following `requires_rezero` axis re-derives the elevation for the destination's own
1258 /// physics instead (see the module doc). MuzzleVelocity and Atmosphere differ directly and
1259 /// must be non-negligible and pairwise distinguishable, so a label swap involving either
1260 /// would be an unmissable mismatch against the per-group check inside
1261 /// `assert_matches_independent_recomputation`.
1262 #[test]
1263 fn every_groups_contribution_matches_an_independent_recomputation() {
1264 let a = resolved(823.0, 288.0);
1265 let b = resolved(870.0, 300.0);
1266 let rep = assert_matches_independent_recomputation(&a, &b, 600.0);
1267 let row = &rep.rows[0];
1268
1269 for g in [
1270 InputGroup::ProjectileDrag,
1271 InputGroup::ZeroSightGeometry,
1272 InputGroup::Wind,
1273 InputGroup::ShotGeometry,
1274 InputGroup::Effects,
1275 ] {
1276 let c = row.contributions.iter().find(|x| x.group == g).unwrap();
1277 assert!(
1278 c.delta.drop_m.abs() < 1e-9,
1279 "{g:?} does not differ between a and b in this fixture at all, expected \
1280 exactly 0, got {}",
1281 c.delta.drop_m
1282 );
1283 }
1284 let mv = row
1285 .contributions
1286 .iter()
1287 .find(|c| c.group == InputGroup::MuzzleVelocity)
1288 .unwrap();
1289 let atmosphere = row
1290 .contributions
1291 .iter()
1292 .find(|c| c.group == InputGroup::Atmosphere)
1293 .unwrap();
1294 for (name, c) in [("MuzzleVelocity", mv), ("Atmosphere", atmosphere)] {
1295 assert!(
1296 c.delta.drop_m.abs() > 0.01,
1297 "{name} should have a substantial, non-negligible contribution here, got {}",
1298 c.delta.drop_m
1299 );
1300 }
1301 assert!(
1302 (mv.delta.drop_m - atmosphere.delta.drop_m).abs() > 0.01,
1303 "MuzzleVelocity ({}) and Atmosphere ({}) should be distinguishable, not just both \
1304 'non-negligible'",
1305 mv.delta.drop_m,
1306 atmosphere.delta.drop_m
1307 );
1308
1309 // The remainder itself must also be genuinely nonzero here (real second-order
1310 // interaction between muzzle velocity and temperature/elevation) -- not identically
1311 // zero, and not silently redistributed into the groups above (which would make THIS
1312 // remainder read back as zero while the groups' sum still matched `total`). Measured at
1313 // ~9.2e-4 after the C1 fix (it was ~4.9e-2 before: MuzzleVelocity's own re-zero and
1314 // Atmosphere's own "not re-zeroed" treatment now correctly explain almost all of the
1315 // elevation response themselves, instead of a chunk of it being force-fed through a
1316 // ZeroSightGeometry that should have been zero) -- 1e-4 stays comfortably below that
1317 // measured value while remaining far above floating-point noise (~1e-9-1e-12).
1318 assert!(
1319 row.interaction_remainder.drop_m.abs() > 1e-4,
1320 "expected a non-negligible interaction remainder in this fixture, got {}",
1321 row.interaction_remainder.drop_m
1322 );
1323 }
1324
1325 /// Review minor: `resolved()`'s fixture never varies `ballistic_coefficient` or wind speed,
1326 /// so a mislabeling among ProjectileDrag/Wind (or between either of them and any of the
1327 /// other always-zero groups) would be INVISIBLE to the test above -- every one of those
1328 /// groups reports zero there either way. A second fixture, varying only BC and wind speed
1329 /// (holding mv/temp/sight/zero geometry identical), exercises ProjectileDrag and Wind with a
1330 /// substantial, distinguishable value instead, closing that gap.
1331 #[test]
1332 fn every_groups_contribution_matches_an_independent_recomputation_bc_and_wind_fixture() {
1333 let a = resolved_with_bc_and_wind_speed(0.243, 3.0);
1334 let b = resolved_with_bc_and_wind_speed(0.300, 6.0);
1335 let rep = assert_matches_independent_recomputation(&a, &b, 600.0);
1336 let row = &rep.rows[0];
1337
1338 for g in [
1339 InputGroup::MuzzleVelocity,
1340 InputGroup::ZeroSightGeometry,
1341 InputGroup::Atmosphere,
1342 InputGroup::ShotGeometry,
1343 InputGroup::Effects,
1344 ] {
1345 let c = row.contributions.iter().find(|x| x.group == g).unwrap();
1346 assert!(
1347 c.delta.drop_m.abs() < 1e-9,
1348 "{g:?} does not differ between a and b in this fixture at all, expected \
1349 exactly 0, got {}",
1350 c.delta.drop_m
1351 );
1352 }
1353 let drag = row
1354 .contributions
1355 .iter()
1356 .find(|c| c.group == InputGroup::ProjectileDrag)
1357 .unwrap();
1358 let wind = row
1359 .contributions
1360 .iter()
1361 .find(|c| c.group == InputGroup::Wind)
1362 .unwrap();
1363 // ProjectileDrag (a higher BC) is measured on drop, its dominant effect; Wind (a
1364 // stronger crosswind) is measured on windage, ITS dominant effect -- checking each
1365 // group in the quantity it actually moves, rather than requiring both to be large in
1366 // the SAME quantity, so this does not depend on the two effects happening to be
1367 // comparable in magnitude.
1368 assert!(
1369 drag.delta.drop_m.abs() > 0.01,
1370 "ProjectileDrag should have a substantial drop contribution here, got {}",
1371 drag.delta.drop_m
1372 );
1373 assert!(
1374 wind.delta.windage_m.abs() > 0.01,
1375 "Wind should have a substantial windage contribution here, got {}",
1376 wind.delta.windage_m
1377 );
1378 // And each group must not be silently carrying the OTHER's signature: ProjectileDrag's
1379 // own windage move and Wind's own drop move should both be comparatively small, which
1380 // is what a labeling swap between these two specific groups would violate.
1381 assert!(
1382 drag.delta.windage_m.abs() < wind.delta.windage_m.abs(),
1383 "ProjectileDrag's windage move ({}) should be smaller than Wind's own ({})",
1384 drag.delta.windage_m,
1385 wind.delta.windage_m
1386 );
1387 assert!(
1388 wind.delta.drop_m.abs() < drag.delta.drop_m.abs(),
1389 "Wind's drop move ({}) should be smaller than ProjectileDrag's own ({})",
1390 wind.delta.drop_m,
1391 drag.delta.drop_m
1392 );
1393 }
1394
1395 /// Review round 3, N3: moving `MuzzleAngle` to the front of `ZeroSightGeometry` (C1) is
1396 /// only safe because a LATER `requires_rezero` axis's clear-gate fires and re-derives the
1397 /// angle -- and that gate is conditioned on `zero_distance_m` being present. For an
1398 /// angle-only request (`zero_distance_m == None`), the gate never fires, so `MuzzleAngle`
1399 /// genuinely IS the independent input and must still be swapped. Two angle-only requests
1400 /// with distinct `muzzle_angle_rad` values, both with no `zero_distance_m` at all, must
1401 /// still show a substantial `ZeroSightGeometry` contribution -- confirming the C1 reorder
1402 /// did not silently turn `MuzzleAngle` into a no-op for the one case it must still cover.
1403 #[test]
1404 fn muzzle_angle_is_still_swapped_for_an_angle_only_request() {
1405 let build = |muzzle_angle_rad: f64| {
1406 serde_json::json!({
1407 "schema_version": 1,
1408 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1409 "ballistic_coefficient": 0.243},
1410 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1411 "shot": {"max_range_m": 900.0, "muzzle_angle_rad": muzzle_angle_rad},
1412 "atmosphere": {"temperature_k": 288.0},
1413 "wind": {},
1414 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
1415 })
1416 .to_string()
1417 };
1418 let a = crate::solve_v1::solve_v1(
1419 crate::solve_json::decode_solve_request_v1(&build(0.010)).unwrap(),
1420 )
1421 .unwrap()
1422 .resolved_request;
1423 let b = crate::solve_v1::solve_v1(
1424 crate::solve_json::decode_solve_request_v1(&build(0.030)).unwrap(),
1425 )
1426 .unwrap()
1427 .resolved_request;
1428 assert_eq!(
1429 a.shot.zero_distance_m, None,
1430 "fixture assumption: angle-only, no zero distance at all"
1431 );
1432 assert_eq!(
1433 b.shot.zero_distance_m, None,
1434 "fixture assumption: angle-only, no zero distance at all"
1435 );
1436
1437 // Uses the shared helper (same primitives as explain_difference, mean taken outside its
1438 // own code path) so this ALSO confirms the swapped value matches an independent
1439 // recomputation, not just that it is non-zero.
1440 let rep = assert_matches_independent_recomputation(&a, &b, 600.0);
1441 let row = &rep.rows[0];
1442 let zero_sight_geometry = row
1443 .contributions
1444 .iter()
1445 .find(|c| c.group == InputGroup::ZeroSightGeometry)
1446 .unwrap();
1447 assert!(
1448 zero_sight_geometry.delta.drop_m.abs() > 0.01,
1449 "MuzzleAngle must still be swapped for an angle-only request -- expected a \
1450 substantial ZeroSightGeometry contribution, got {}",
1451 zero_sight_geometry.delta.drop_m
1452 );
1453 }
1454
1455 /// Requirement (1): `with_axis` refuses `Altitude` under a QNH-referenced atmosphere. The
1456 /// refusal must be recorded, not silently dropped, and must not abort the comparison. Per
1457 /// review I1, exclusion must apply to BOTH swap directions (`b` is not itself QNH-referenced,
1458 /// so only the Forward leg would refuse Altitude on its own -- Backward must be excluded
1459 /// anyway, to keep the two legs measuring the same counterfactual).
1460 #[test]
1461 fn altitude_is_skipped_and_recorded_under_qnh_pressure() {
1462 let qnh_json = serde_json::json!({
1463 "schema_version": 1,
1464 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1465 "ballistic_coefficient": 0.243},
1466 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1467 "shot": {"max_range_m": 900.0},
1468 "atmosphere": {"altitude_m": 500.0, "temperature_k": 288.0, "pressure_pa": 101325.0,
1469 "pressure_reference": "qnh"},
1470 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1471 })
1472 .to_string();
1473 let a = crate::solve_v1::solve_v1(
1474 crate::solve_json::decode_solve_request_v1(&qnh_json).unwrap(),
1475 )
1476 .unwrap()
1477 .resolved_request;
1478 let b = resolved(870.0, 300.0);
1479 assert_eq!(
1480 b.atmosphere.pressure_reference, None,
1481 "fixture assumption: b is NOT QNH-referenced, so only a's QNH-ness drives this test"
1482 );
1483
1484 let rep = explain_difference(&a, &b, &[300.0])
1485 .expect("a refused axis must not abort the whole comparison");
1486 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
1487 let hit = rep
1488 .skipped_axes
1489 .iter()
1490 .find(|s| {
1491 s.group == InputGroup::Atmosphere
1492 && s.axis == InputAxis::Altitude
1493 && s.direction == direction
1494 })
1495 .unwrap_or_else(|| {
1496 panic!(
1497 "expected a {direction:?}-direction Altitude skip under QNH pressure \
1498 (review I1: both directions must be excluded, not just the one that \
1499 independently refused), got {:?}",
1500 rep.skipped_axes
1501 )
1502 });
1503 assert!(
1504 hit.reason.to_lowercase().contains("qnh"),
1505 "reason should name QNH: {}",
1506 hit.reason
1507 );
1508 }
1509 }
1510
1511 /// Review I1's explicit ask: not just that Altitude is recorded as skipped, but that the
1512 /// resulting Atmosphere CONTRIBUTION is actually correct -- reflecting ONLY the other axes,
1513 /// with no partial leakage from the excluded Altitude difference. Proven by showing the
1514 /// reported contribution is UNCHANGED when b's altitude is moved from one value to ANOTHER:
1515 /// if Altitude's difference were still (even partially) leaking into the contribution,
1516 /// moving it would change the reported number; since Altitude is excluded from BOTH legs
1517 /// either way, it must not.
1518 ///
1519 /// Deliberately compares TWO altitudes that BOTH differ from `a`'s (1200 and 900), neither
1520 /// equal to `a`'s own 500 -- review round 4, F1 excludes `Pressure` only when the two
1521 /// requests' altitudes actually differ, so comparing against an altitude that happens to
1522 /// MATCH `a`'s would stop excluding `Pressure` in that one leg and confound this test with a
1523 /// second, unrelated effect (see `pressure_exclusion_does_not_leak_a_partial_effect_into_atmosphere`'s
1524 /// own doc comment for that failure mode in detail).
1525 ///
1526 /// This does NOT mean `altitude_m` is inert once the station temperature and pressure are
1527 /// both given directly (review round 5): `calculate_atmosphere` (`atmosphere.rs`) only
1528 /// skips altitude for the ONE-TIME station-level resolution in that case -- it is not the
1529 /// only channel. `TrajectorySolver::calculate_acceleration` (`cli_api.rs`, MBA-1136)
1530 /// separately recomputes a LOCAL atmosphere at every RK4/RK45 substep from the station
1531 /// altitude and the bullet's current height via `shot_frame_altitude`/
1532 /// `get_local_atmosphere_humid`, unconditionally, regardless of pressure-reference mode or
1533 /// whether temperature/pressure were explicit -- `perturbation::evaluate` goes through this
1534 /// same solver, so it is live here too. Because the geopotential-height conversion this
1535 /// lapse computation uses is mildly nonlinear, comparing two DIFFERENT absolute station
1536 /// altitudes (as this test's two `explain_difference` calls do) is not perfectly
1537 /// scale-invariant even when the seed temperature/pressure are identical. Measured directly
1538 /// (temporary, uncommitted probe) rather than assumed away: on this exact fixture (1200 m
1539 /// vs 900 m, 300 m range), the residual is `~3.7e-12` -- about 270x below the `1e-9`
1540 /// tolerance below, and about 9-10 significant digits of agreement on a ~4.3e-3 m baseline,
1541 /// consistent with ordinary floating-point accumulation through an RK4 integration rather
1542 /// than a physically resolvable effect. Pushing the gap to an unrealistic 900 m vs 5000 m
1543 /// (still the same short 300 m query range) only grows it to `~5.0e-11` -- still comfortably
1544 /// below `1e-9`. `< 1e-9` is kept as an effectively-exact bound for THIS fixture's altitude
1545 /// range, not because the channel doesn't exist.
1546 #[test]
1547 fn altitude_exclusion_does_not_leak_a_partial_effect_into_atmosphere() {
1548 let qnh_json = serde_json::json!({
1549 "schema_version": 1,
1550 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1551 "ballistic_coefficient": 0.243},
1552 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1553 "shot": {"max_range_m": 900.0},
1554 "atmosphere": {"altitude_m": 500.0, "temperature_k": 288.0, "pressure_pa": 101325.0,
1555 "pressure_reference": "qnh"},
1556 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1557 })
1558 .to_string();
1559 let a = crate::solve_v1::solve_v1(
1560 crate::solve_json::decode_solve_request_v1(&qnh_json).unwrap(),
1561 )
1562 .unwrap()
1563 .resolved_request;
1564
1565 let b_json = |altitude_m: f64| {
1566 serde_json::json!({
1567 "schema_version": 1,
1568 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1569 "ballistic_coefficient": 0.243},
1570 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1571 "shot": {"max_range_m": 900.0},
1572 "atmosphere": {"altitude_m": altitude_m, "temperature_k": 300.0,
1573 "pressure_pa": 98000.0},
1574 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1575 })
1576 .to_string()
1577 };
1578 let b_altitude_1200 = crate::solve_v1::solve_v1(
1579 crate::solve_json::decode_solve_request_v1(&b_json(1200.0)).unwrap(),
1580 )
1581 .unwrap()
1582 .resolved_request;
1583 let b_altitude_900 = crate::solve_v1::solve_v1(
1584 crate::solve_json::decode_solve_request_v1(&b_json(900.0)).unwrap(),
1585 )
1586 .unwrap()
1587 .resolved_request;
1588 // Fixture assumption: NEITHER b variant's altitude may equal a's 500 -- see the doc
1589 // comment above for why that specific coincidence would confound this test.
1590 assert_ne!(
1591 b_altitude_1200.atmosphere.altitude_m,
1592 a.atmosphere.altitude_m
1593 );
1594 assert_ne!(
1595 b_altitude_900.atmosphere.altitude_m,
1596 a.atmosphere.altitude_m
1597 );
1598
1599 let rep_1200 = explain_difference(&a, &b_altitude_1200, &[300.0]).unwrap();
1600 let rep_900 = explain_difference(&a, &b_altitude_900, &[300.0]).unwrap();
1601
1602 // Sanity: Altitude must be excluded on BOTH directions in BOTH comparisons, so this is
1603 // a fair, apples-to-apples check of the same code path (not, say, one comparison
1604 // exercising the exclusion and the other happening to skip it because the values
1605 // coincided).
1606 for rep in [&rep_1200, &rep_900] {
1607 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
1608 assert!(
1609 rep.skipped_axes
1610 .iter()
1611 .any(|s| s.group == InputGroup::Atmosphere
1612 && s.axis == InputAxis::Altitude
1613 && s.direction == direction),
1614 "expected Altitude excluded on {direction:?} in both comparisons"
1615 );
1616 }
1617 }
1618
1619 let atmosphere_1200 = rep_1200.rows[0]
1620 .contributions
1621 .iter()
1622 .find(|c| c.group == InputGroup::Atmosphere)
1623 .unwrap();
1624 let atmosphere_900 = rep_900.rows[0]
1625 .contributions
1626 .iter()
1627 .find(|c| c.group == InputGroup::Atmosphere)
1628 .unwrap();
1629 assert!(
1630 (atmosphere_1200.delta.drop_m - atmosphere_900.delta.drop_m).abs() < 1e-9,
1631 "Atmosphere's contribution changed when b's altitude changed (1200 -> 900 m) even \
1632 though Altitude is excluded from both comparisons -- {} vs {} -- a partial \
1633 altitude effect must be leaking through",
1634 atmosphere_1200.delta.drop_m,
1635 atmosphere_900.delta.drop_m
1636 );
1637 // And it must be genuinely non-zero (temperature alone is a real effect here), or the
1638 // equality above would be trivially true for the wrong reason (both sides zero).
1639 assert!(
1640 atmosphere_900.delta.drop_m.abs() > 0.001,
1641 "expected a non-negligible Atmosphere contribution from temperature alone, got {}",
1642 atmosphere_900.delta.drop_m
1643 );
1644 }
1645
1646 /// Review round 3, N2 (derived-value exclusion rule, Instance 3): the Altitude test above
1647 /// only exercises a QNH-vs-ABSOLUTE comparison, where `b`'s plain absolute pressure has no
1648 /// altitude dependency to leak in the first place -- it cannot catch Pressure itself still
1649 /// being swapped. This uses a QNH-vs-QNH comparison instead: both `b` variants share the
1650 /// SAME altitude (1200 m, always different from `a`'s 500 m -- review round 4, F1, the same
1651 /// reasoning as the Altitude test's own doc comment: comparing against an altitude that
1652 /// happens to match `a`'s would stop excluding `Pressure` in that leg and confound the
1653 /// comparison) but differ in their RAW QNH value, so their resolved `pressure_pa` differs
1654 /// too. If Pressure were still being copied (the bug this fix addresses), that resolved
1655 /// difference would move Atmosphere's contribution; since Pressure is excluded in BOTH
1656 /// comparisons here (both `b` variants sit at 1200 m, never 500 m), it must not.
1657 ///
1658 /// Unlike the Altitude test, this ONE needs a much looser tolerance, not just a non-exact
1659 /// one: `Altitude`/`Pressure` are excluded from being SWAPPED, but each `b` variant's
1660 /// baseline trajectory is still solved at ITS OWN real, unswapped (and, here,
1661 /// differing-by-QNH-value) pressure, and the swapped `Temperature` axis's effect on drop is
1662 /// itself (very slightly) a function of the ambient density it is evaluated in -- a genuine,
1663 /// small, second-order interaction between a held-fixed axis and a swapped one, not a leak.
1664 /// The Altitude test's sibling comparison has an analogous channel too (the MBA-1136 local
1665 /// altitude-lapse recompute, see that test's own doc comment, review round 5) -- it is not
1666 /// that no such channel exists there, only that it is roughly nine orders of magnitude
1667 /// smaller (measured `~3.7e-12` there vs `~1.8e-4` here), because THIS test's variation is a
1668 /// real, first-derivative pressure difference at a FIXED altitude, where that one is a
1669 /// second-derivative geopotential-conversion nonlinearity across two DIFFERENT altitudes.
1670 /// I measured both sides with a temporary, uncommitted probe before choosing this test's
1671 /// tolerance: with the fix disabled, this fixture's two comparisons differed by `~9.7e-3`
1672 /// (a first-order effect, the shape a real leak takes). With the fix applied, they differ by
1673 /// `~1.8e-4` -- over 50x
1674 /// smaller. `2e-3` sits with comfortable margin above the fixed residual and comfortably
1675 /// below the broken one.
1676 ///
1677 /// See `pressure_and_altitude_exclusion_give_an_exactly_zero_atmosphere_contribution_when_nothing_else_differs`
1678 /// below for a complementary, bit-EXACT version of this same property (the reviewer's own
1679 /// suggestion): when the two requests differ ONLY in altitude, every remaining Atmosphere
1680 /// axis is identical, so there is no second-order channel left and the contribution must be
1681 /// precisely `0.0`.
1682 #[test]
1683 fn pressure_exclusion_does_not_leak_a_partial_effect_into_atmosphere() {
1684 let qnh_json = |altitude_m: f64, temperature_k: f64, raw_qnh_pa: f64| {
1685 serde_json::json!({
1686 "schema_version": 1,
1687 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1688 "ballistic_coefficient": 0.243},
1689 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1690 "shot": {"max_range_m": 900.0},
1691 "atmosphere": {"altitude_m": altitude_m, "temperature_k": temperature_k,
1692 "pressure_pa": raw_qnh_pa, "pressure_reference": "qnh"},
1693 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1694 })
1695 .to_string()
1696 };
1697 let a = crate::solve_v1::solve_v1(
1698 crate::solve_json::decode_solve_request_v1(&qnh_json(500.0, 288.0, 101_325.0)).unwrap(),
1699 )
1700 .unwrap()
1701 .resolved_request;
1702 let b_qnh_101325 = crate::solve_v1::solve_v1(
1703 crate::solve_json::decode_solve_request_v1(&qnh_json(1200.0, 300.0, 101_325.0))
1704 .unwrap(),
1705 )
1706 .unwrap()
1707 .resolved_request;
1708 let b_qnh_105000 = crate::solve_v1::solve_v1(
1709 crate::solve_json::decode_solve_request_v1(&qnh_json(1200.0, 300.0, 105_000.0))
1710 .unwrap(),
1711 )
1712 .unwrap()
1713 .resolved_request;
1714
1715 // Fixture assumptions: both b variants sit at the SAME altitude (1200 m), which must
1716 // NOT equal a's (500 m) -- see the doc comment above -- and their resolved pressure_pa
1717 // must differ, purely from the raw QNH value, confirming this fixture actually
1718 // exercises "does the specific excluded Pressure value leak."
1719 assert_eq!(
1720 b_qnh_101325.atmosphere.altitude_m,
1721 b_qnh_105000.atmosphere.altitude_m
1722 );
1723 assert_ne!(b_qnh_101325.atmosphere.altitude_m, a.atmosphere.altitude_m);
1724 assert_ne!(
1725 b_qnh_101325.atmosphere.pressure_pa, b_qnh_105000.atmosphere.pressure_pa,
1726 "fixture assumption: different raw QNH at the same altitude must resolve to a \
1727 different station pressure"
1728 );
1729
1730 let rep_101325 = explain_difference(&a, &b_qnh_101325, &[300.0]).unwrap();
1731 let rep_105000 = explain_difference(&a, &b_qnh_105000, &[300.0]).unwrap();
1732
1733 for rep in [&rep_101325, &rep_105000] {
1734 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
1735 assert!(
1736 rep.skipped_axes
1737 .iter()
1738 .any(|s| s.group == InputGroup::Atmosphere
1739 && s.axis == InputAxis::Pressure
1740 && s.direction == direction),
1741 "expected Pressure excluded on {direction:?} under QNH-vs-QNH; got {:?}",
1742 rep.skipped_axes
1743 );
1744 }
1745 }
1746
1747 let atmosphere_101325 = rep_101325.rows[0]
1748 .contributions
1749 .iter()
1750 .find(|c| c.group == InputGroup::Atmosphere)
1751 .unwrap();
1752 let atmosphere_105000 = rep_105000.rows[0]
1753 .contributions
1754 .iter()
1755 .find(|c| c.group == InputGroup::Atmosphere)
1756 .unwrap();
1757 // See the doc comment above for exactly why this is 2e-3, not exact equality: measured
1758 // empirically at ~1.8e-4 with the fix applied vs. ~9.7e-3 with it disabled, on this
1759 // exact fixture.
1760 assert!(
1761 (atmosphere_101325.delta.drop_m - atmosphere_105000.delta.drop_m).abs() < 2e-3,
1762 "Atmosphere's contribution changed by more than the expected small second-order \
1763 residual when b's raw QNH value changed (101325 -> 105000 Pa) at the SAME altitude, \
1764 even though Pressure and Altitude are both excluded -- {} vs {} -- a first-order \
1765 pressure effect looks like it is leaking through",
1766 atmosphere_101325.delta.drop_m,
1767 atmosphere_105000.delta.drop_m
1768 );
1769 assert!(
1770 atmosphere_105000.delta.drop_m.abs() > 0.001,
1771 "expected a non-negligible Atmosphere contribution from temperature alone, got {}",
1772 atmosphere_105000.delta.drop_m
1773 );
1774 }
1775
1776 /// The reviewer's own suggestion (review round 4): a bit-EXACT complement to the tolerance
1777 /// test above. Two QNH-referenced requests differing ONLY in altitude (same explicit
1778 /// temperature, same everything else) exclude both `Altitude` and `Pressure`, leaving every
1779 /// OTHER `Atmosphere` axis byte-identical between them -- so `swap_group` reproduces the
1780 /// destination exactly, both legs are exact no-ops, and the contribution must be precisely
1781 /// `0.0`, not merely small. This is the same shape as
1782 /// `wind_direction_is_excluded_under_compass_wind_even_with_an_identical_raw_bearing` and the
1783 /// post-C1 `ZeroSightGeometry` assertion in `every_groups_contribution_matches_an_independent_recomputation`:
1784 /// a real leak would produce a large, first-order non-zero here, not a rounding-sized one.
1785 #[test]
1786 fn pressure_and_altitude_exclusion_give_an_exactly_zero_atmosphere_contribution_when_nothing_else_differs(
1787 ) {
1788 let qnh_json = |altitude_m: f64| {
1789 serde_json::json!({
1790 "schema_version": 1,
1791 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1792 "ballistic_coefficient": 0.243},
1793 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1794 "shot": {"max_range_m": 900.0},
1795 "atmosphere": {"altitude_m": altitude_m, "temperature_k": 288.0,
1796 "pressure_pa": 101_325.0, "pressure_reference": "qnh"},
1797 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1798 })
1799 .to_string()
1800 };
1801 let a = crate::solve_v1::solve_v1(
1802 crate::solve_json::decode_solve_request_v1(&qnh_json(500.0)).unwrap(),
1803 )
1804 .unwrap()
1805 .resolved_request;
1806 let b = crate::solve_v1::solve_v1(
1807 crate::solve_json::decode_solve_request_v1(&qnh_json(1200.0)).unwrap(),
1808 )
1809 .unwrap()
1810 .resolved_request;
1811 assert_ne!(
1812 a.atmosphere.altitude_m, b.atmosphere.altitude_m,
1813 "fixture assumption"
1814 );
1815 assert_eq!(
1816 a.atmosphere.temperature_k, b.atmosphere.temperature_k,
1817 "fixture assumption: temperature must be identical, or Atmosphere would have a \
1818 real, non-excluded axis to report and the contribution would not be zero"
1819 );
1820
1821 let rep = explain_difference(&a, &b, &[300.0])
1822 .expect("Altitude/Pressure exclusion must not abort the comparison");
1823 let atmosphere = rep.rows[0]
1824 .contributions
1825 .iter()
1826 .find(|c| c.group == InputGroup::Atmosphere)
1827 .unwrap();
1828 assert_eq!(
1829 atmosphere.delta.drop_m, 0.0,
1830 "Atmosphere's drop contribution must be exactly zero when altitude is the ONLY \
1831 thing that differs and both Altitude and Pressure are excluded, got {}",
1832 atmosphere.delta.drop_m
1833 );
1834 assert_eq!(
1835 atmosphere.delta.windage_m, 0.0,
1836 "Atmosphere's windage contribution must be exactly zero for the same reason, got {}",
1837 atmosphere.delta.windage_m
1838 );
1839
1840 // Non-triviality: unlike the other exact-zero tests in this file, a nonzero TOTAL isn't
1841 // the right guard here -- altitude alone, once excluded, is expected to affect nothing
1842 // at all, so a zero total is normal, not suspicious. What WOULD be suspicious is the
1843 // exclusion mechanism never actually engaging (e.g. a refactor that silently turned
1844 // plan_exclusions into a no-op, which would ALSO report an exact zero here, for the
1845 // wrong reason). Guard against that directly: both axes must actually appear in
1846 // skipped_axes.
1847 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
1848 for axis in [InputAxis::Altitude, InputAxis::Pressure] {
1849 assert!(
1850 rep.skipped_axes
1851 .iter()
1852 .any(|s| s.group == InputGroup::Atmosphere
1853 && s.axis == axis
1854 && s.direction == direction),
1855 "expected {axis:?} excluded on {direction:?}; got {:?}",
1856 rep.skipped_axes
1857 );
1858 }
1859 }
1860 }
1861
1862 /// Review round 4, F1: the Pressure exclusion must NOT fire when the two requests'
1863 /// altitudes MATCH -- only a differing altitude actually breaks the QNH-to-station-pressure
1864 /// pairing. Two QNH-referenced requests at the SAME altitude but DIFFERENT raw altimeter
1865 /// settings must attribute that difference to `Atmosphere` normally: excluding `Pressure`
1866 /// unconditionally on the QNH mode flag alone (the bug this test guards against) would
1867 /// UNDER-attribute a genuine altimeter-setting difference into the interaction remainder on
1868 /// the most natural same-location QNH comparison anyone would run.
1869 #[test]
1870 fn pressure_is_still_swapped_when_the_altitude_matches() {
1871 let build = |raw_qnh_pa: f64| {
1872 serde_json::json!({
1873 "schema_version": 1,
1874 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1875 "ballistic_coefficient": 0.243},
1876 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1877 "shot": {"max_range_m": 900.0},
1878 "atmosphere": {"altitude_m": 500.0, "temperature_k": 288.0,
1879 "pressure_pa": raw_qnh_pa, "pressure_reference": "qnh"},
1880 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1881 })
1882 .to_string()
1883 };
1884 let a = crate::solve_v1::solve_v1(
1885 crate::solve_json::decode_solve_request_v1(&build(101_325.0)).unwrap(),
1886 )
1887 .unwrap()
1888 .resolved_request;
1889 let b = crate::solve_v1::solve_v1(
1890 crate::solve_json::decode_solve_request_v1(&build(98_000.0)).unwrap(),
1891 )
1892 .unwrap()
1893 .resolved_request;
1894 assert_eq!(
1895 a.atmosphere.altitude_m, b.atmosphere.altitude_m,
1896 "fixture assumption: identical altitude on both sides"
1897 );
1898 assert_ne!(
1899 a.atmosphere.pressure_pa, b.atmosphere.pressure_pa,
1900 "fixture assumption: different raw QNH must still resolve to different station \
1901 pressure at the same altitude"
1902 );
1903
1904 let rep = explain_difference(&a, &b, &[300.0]).unwrap();
1905
1906 assert!(
1907 !rep.skipped_axes
1908 .iter()
1909 .any(|s| s.group == InputGroup::Atmosphere && s.axis == InputAxis::Pressure),
1910 "Pressure must not be excluded when altitude matches on both sides; got {:?}",
1911 rep.skipped_axes
1912 );
1913
1914 let atmosphere = rep.rows[0]
1915 .contributions
1916 .iter()
1917 .find(|c| c.group == InputGroup::Atmosphere)
1918 .unwrap();
1919 assert!(
1920 atmosphere.delta.drop_m.abs() > 0.001,
1921 "Atmosphere's contribution must be substantial and non-zero here -- the raw QNH \
1922 genuinely differs and the shared altitude means Pressure is safe to swap -- got {}",
1923 atmosphere.delta.drop_m
1924 );
1925 }
1926
1927 /// Review I2: an ordinarily-optional axis present on exactly one of the two requests splits
1928 /// the two legs exactly like a `with_axis` refusal does -- forward would keep A's own value
1929 /// (nothing to copy from B) while backward would overwrite B with A's, silently
1930 /// half-attributing whatever that value's effect is, with NO record at all. `latitude_rad`
1931 /// is a convenient example: present here on `a`, absent on `b` -- an ordinary difference
1932 /// between two saved profiles, nothing to do with Coriolis specifically (Coriolis is left
1933 /// disabled on both, so this is not entangled with `resolve_effects`'s separate requirement
1934 /// that Coriolis needs a latitude on any request that enables it).
1935 #[test]
1936 fn an_axis_present_on_only_one_side_is_skipped_and_recorded_symmetrically() {
1937 let with_latitude_json = serde_json::json!({
1938 "schema_version": 1,
1939 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1940 "ballistic_coefficient": 0.243},
1941 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1942 "shot": {"max_range_m": 900.0},
1943 "atmosphere": {"temperature_k": 288.0, "latitude_rad": 0.7},
1944 "wind": {}, "solver": {}, "effects": {}, "sampling": {"interval_m": 50.0}
1945 })
1946 .to_string();
1947 let a = crate::solve_v1::solve_v1(
1948 crate::solve_json::decode_solve_request_v1(&with_latitude_json).unwrap(),
1949 )
1950 .unwrap()
1951 .resolved_request;
1952 assert_eq!(
1953 a.atmosphere.latitude_rad,
1954 Some(0.7),
1955 "fixture assumption: a supplies latitude_rad"
1956 );
1957
1958 let b = resolved(870.0, 300.0);
1959 assert_eq!(
1960 b.atmosphere.latitude_rad, None,
1961 "fixture assumption: b omits latitude_rad entirely"
1962 );
1963
1964 let rep = explain_difference(&a, &b, &[300.0])
1965 .expect("a presence-only-on-one-side axis must not abort the whole comparison");
1966
1967 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
1968 assert!(
1969 rep.skipped_axes
1970 .iter()
1971 .any(|s| s.group == InputGroup::Atmosphere
1972 && s.axis == InputAxis::Latitude
1973 && s.direction == direction),
1974 "expected a {direction:?} Latitude skip when it is present on only one side; \
1975 got {:?}",
1976 rep.skipped_axes
1977 );
1978 }
1979 }
1980
1981 /// (F2, 0.33.0 final-review fix wave) `a` and `b` each solve fine individually -- `a` has
1982 /// coriolis enabled with a supplied `latitude_rad`, `b` has coriolis left disabled and
1983 /// omits `latitude_rad` entirely, an ordinary difference between two saved profiles. Before
1984 /// this fix, comparing them aborted the WHOLE report with a bare `solve_v1` error
1985 /// ("latitude_rad is required when the Coriolis effect is enabled") the moment the backward
1986 /// leg tried to write coriolis=true onto `b`'s clone: `with_axis` performs no cross-field
1987 /// validation, so the write itself always "succeeds," and the failure only surfaces on the
1988 /// re-resolve inside `swap_group`, well after `plan_exclusions`'s existing refusal checks
1989 /// had already passed it through. `plan_exclusions` must now catch this up front instead.
1990 #[test]
1991 fn coriolis_conflict_with_missing_latitude_is_excluded_not_a_hard_abort() {
1992 let with_coriolis_json = serde_json::json!({
1993 "schema_version": 1,
1994 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
1995 "ballistic_coefficient": 0.243},
1996 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
1997 "shot": {"max_range_m": 900.0},
1998 "atmosphere": {"temperature_k": 288.0, "latitude_rad": 0.7},
1999 "wind": {}, "solver": {}, "effects": {"coriolis": true},
2000 "sampling": {"interval_m": 50.0}
2001 })
2002 .to_string();
2003 let a = crate::solve_v1::solve_v1(
2004 crate::solve_json::decode_solve_request_v1(&with_coriolis_json).unwrap(),
2005 )
2006 .unwrap()
2007 .resolved_request;
2008 assert!(
2009 a.effects.coriolis,
2010 "fixture assumption: a has coriolis enabled"
2011 );
2012 assert_eq!(
2013 a.atmosphere.latitude_rad,
2014 Some(0.7),
2015 "fixture assumption: a supplies latitude_rad"
2016 );
2017
2018 let b = resolved(823.0, 288.0);
2019 assert!(
2020 !b.effects.coriolis,
2021 "fixture assumption: b has coriolis disabled"
2022 );
2023 assert_eq!(
2024 b.atmosphere.latitude_rad, None,
2025 "fixture assumption: b omits latitude_rad entirely"
2026 );
2027
2028 let rep = explain_difference(&a, &b, &[600.0]).expect(
2029 "a coriolis/latitude conflict must be excluded, not abort the whole comparison",
2030 );
2031
2032 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
2033 assert!(
2034 rep.skipped_axes
2035 .iter()
2036 .any(|s| s.group == InputGroup::Effects
2037 && s.axis == InputAxis::CoriolisEnabled
2038 && s.direction == direction),
2039 "expected a {direction:?} CoriolisEnabled skip when the flags differ and one \
2040 side lacks latitude_rad; got {:?}",
2041 rep.skipped_axes
2042 );
2043 }
2044 let reason = &rep
2045 .skipped_axes
2046 .iter()
2047 .find(|s| s.group == InputGroup::Effects && s.axis == InputAxis::CoriolisEnabled)
2048 .unwrap()
2049 .reason;
2050 assert!(
2051 reason.to_lowercase().contains("latitude"),
2052 "reason must name latitude_rad as the cause: {reason}"
2053 );
2054
2055 assert_eq!(rep.rows.len(), 1);
2056 }
2057
2058 /// (F2, continued) The guard above must fire on the actual CONFLICT, not blanket-exclude
2059 /// `CoriolisEnabled` whenever the flags merely differ: here both `a` and `b` supply the
2060 /// identical `latitude_rad`, so turning coriolis on for either destination is always safe,
2061 /// and the axis must still be swapped and contribute normally.
2062 #[test]
2063 fn coriolis_still_swaps_when_both_requests_have_latitude() {
2064 let build = |coriolis: bool| {
2065 serde_json::json!({
2066 "schema_version": 1,
2067 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2068 "ballistic_coefficient": 0.243},
2069 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
2070 "shot": {"max_range_m": 900.0},
2071 "atmosphere": {"temperature_k": 288.0, "latitude_rad": 0.7},
2072 "wind": {}, "solver": {}, "effects": {"coriolis": coriolis},
2073 "sampling": {"interval_m": 50.0}
2074 })
2075 .to_string()
2076 };
2077 let a = crate::solve_v1::solve_v1(
2078 crate::solve_json::decode_solve_request_v1(&build(true)).unwrap(),
2079 )
2080 .unwrap()
2081 .resolved_request;
2082 let b = crate::solve_v1::solve_v1(
2083 crate::solve_json::decode_solve_request_v1(&build(false)).unwrap(),
2084 )
2085 .unwrap()
2086 .resolved_request;
2087 assert_eq!(
2088 a.atmosphere.latitude_rad, b.atmosphere.latitude_rad,
2089 "fixture assumption: identical latitude_rad on both sides"
2090 );
2091 assert_ne!(
2092 a.effects.coriolis, b.effects.coriolis,
2093 "fixture assumption: flags differ"
2094 );
2095
2096 let rep = explain_difference(&a, &b, &[600.0]).unwrap();
2097
2098 assert!(
2099 !rep.skipped_axes
2100 .iter()
2101 .any(|s| s.group == InputGroup::Effects && s.axis == InputAxis::CoriolisEnabled),
2102 "CoriolisEnabled must not be excluded when both sides supply the same latitude_rad; \
2103 got {:?}",
2104 rep.skipped_axes
2105 );
2106
2107 let effects = rep.rows[0]
2108 .contributions
2109 .iter()
2110 .find(|c| c.group == InputGroup::Effects)
2111 .unwrap();
2112 assert!(
2113 effects.delta.drop_m.abs() > 1e-6 || effects.delta.windage_m.abs() > 1e-6,
2114 "Effects' contribution must be substantial and non-zero here -- coriolis genuinely \
2115 differs and both sides can safely carry it -- got {:?}",
2116 effects.delta
2117 );
2118 }
2119
2120 /// This fixture's shape comes from the ordering hazard documented in this module's doc
2121 /// comment: `ShotGeometry` lists `TargetDistance`, `ShootingAngle` and `Cant` before
2122 /// `ShotAzimuth`. Deciding exclusions from `a`/`b` directly (`plan_exclusions`, never a
2123 /// request `swap_group` has already partly rewritten) makes that hazard structurally
2124 /// impossible now -- there is no accumulated, partly-laundered request for a check to see,
2125 /// regardless of axis order -- so this specific fixture can no longer directly exercise an
2126 /// order-dependent failure the way an earlier, per-swap_group-call revision of this module
2127 /// could. What it still usefully pins down is review I1's symmetric-exclusion fix: `b`'s
2128 /// wind is shooter-relative, so ONLY the Forward leg independently refuses `ShotAzimuth` (a
2129 /// compass-referenced `a`), yet Backward must be excluded too, with a reason that still
2130 /// names the compass refusal that drove it.
2131 #[test]
2132 fn shot_azimuth_is_refused_even_when_other_shot_geometry_axes_are_applied_first() {
2133 let compass_json = serde_json::json!({
2134 "schema_version": 1,
2135 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2136 "ballistic_coefficient": 0.243},
2137 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
2138 "shot": {"max_range_m": 900.0, "shooting_angle_rad": 0.05, "cant_angle_rad": 0.01,
2139 "shot_azimuth_rad": 0.3},
2140 "atmosphere": {"temperature_k": 288.0},
2141 "wind": {"speed_mps": 3.0, "direction_from_rad": 1.0, "wind_reference": "compass"},
2142 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
2143 })
2144 .to_string();
2145 let a = crate::solve_v1::solve_v1(
2146 crate::solve_json::decode_solve_request_v1(&compass_json).unwrap(),
2147 )
2148 .unwrap()
2149 .resolved_request;
2150 match &a.wind {
2151 crate::solve_json::ResolvedWindV1::Constant(c) => assert_eq!(
2152 c.wind_reference,
2153 Some(crate::solve_json::WindReferenceV1::Compass),
2154 "fixture assumption: a's wind must be compass-referenced"
2155 ),
2156 crate::solve_json::ResolvedWindV1::Segmented(_) => panic!("constant wind expected"),
2157 }
2158
2159 let shooter_json = serde_json::json!({
2160 "schema_version": 1,
2161 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2162 "ballistic_coefficient": 0.243},
2163 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
2164 "shot": {"max_range_m": 950.0, "shooting_angle_rad": 0.08, "cant_angle_rad": 0.02,
2165 "shot_azimuth_rad": 0.9},
2166 "atmosphere": {"temperature_k": 288.0},
2167 "wind": {"speed_mps": 3.0, "direction_from_rad": 1.0},
2168 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
2169 })
2170 .to_string();
2171 let b = crate::solve_v1::solve_v1(
2172 crate::solve_json::decode_solve_request_v1(&shooter_json).unwrap(),
2173 )
2174 .unwrap()
2175 .resolved_request;
2176
2177 let rep = explain_difference(&a, &b, &[300.0])
2178 .expect("a refused axis must not abort the whole comparison");
2179
2180 let hit = rep
2181 .skipped_axes
2182 .iter()
2183 .find(|s| {
2184 s.group == InputGroup::ShotGeometry
2185 && s.axis == InputAxis::ShotAzimuth
2186 && s.direction == SwapDirectionV1::Forward
2187 })
2188 .unwrap_or_else(|| {
2189 panic!(
2190 "expected a Forward-direction ShotAzimuth skip under compass wind, even \
2191 though TargetDistance/ShootingAngle/Cant are applied (and each \
2192 re-resolved) first within the same ShotGeometry group; got skipped_axes = \
2193 {:?}",
2194 rep.skipped_axes
2195 )
2196 });
2197 assert!(
2198 hit.reason.to_lowercase().contains("compass"),
2199 "reason should name compass wind: {}",
2200 hit.reason
2201 );
2202 // Review I1: even though `b` is shooter-relative and would not refuse ShotAzimuth on
2203 // its own, Backward must ALSO be excluded -- otherwise forward keeps A's azimuth
2204 // (refused) while backward hands B the whole of A's azimuth (not refused), splitting
2205 // the two legs into different counterfactuals.
2206 let backward_hit = rep
2207 .skipped_axes
2208 .iter()
2209 .find(|s| {
2210 s.group == InputGroup::ShotGeometry
2211 && s.axis == InputAxis::ShotAzimuth
2212 && s.direction == SwapDirectionV1::Backward
2213 })
2214 .unwrap_or_else(|| {
2215 panic!(
2216 "expected a Backward-direction ShotAzimuth skip too (review I1: symmetric \
2217 exclusion), even though b's wind is shooter-relative; got skipped_axes = \
2218 {:?}",
2219 rep.skipped_axes
2220 )
2221 });
2222 assert!(
2223 backward_hit.reason.to_lowercase().contains("compass"),
2224 "the sympathetic Backward exclusion's reason should still explain the compass \
2225 refusal that drove it: {}",
2226 backward_hit.reason
2227 );
2228 }
2229
2230 /// Review round 3, N1 (derived-value exclusion rule, Instance 2): `with_axis` already
2231 /// refuses to swap `ShotAzimuth` under compass wind, protecting `ShotGeometry`'s own
2232 /// number, but nothing protected `WindDirection`, whose OWN resolved (shooter-relative)
2233 /// value is `(bearing - shot_azimuth_rad).rem_euclid(2*pi)` -- also a function of
2234 /// `shot_azimuth_rad`. Two compass-referenced requests with the SAME raw wind bearing but
2235 /// DIFFERENT `shot_azimuth_rad` resolve to DIFFERENT `direction_from_rad`, purely from the
2236 /// azimuth difference; `Wind`'s contribution must still be exactly zero, not a re-labelled
2237 /// azimuth effect.
2238 #[test]
2239 fn wind_direction_is_excluded_under_compass_wind_even_with_an_identical_raw_bearing() {
2240 let build = |shot_azimuth_rad: f64| {
2241 serde_json::json!({
2242 "schema_version": 1,
2243 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2244 "ballistic_coefficient": 0.243},
2245 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
2246 "shot": {"max_range_m": 900.0, "shot_azimuth_rad": shot_azimuth_rad},
2247 "atmosphere": {"temperature_k": 288.0},
2248 "wind": {"speed_mps": 3.0, "direction_from_rad": std::f64::consts::FRAC_PI_2,
2249 "wind_reference": "compass"},
2250 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
2251 })
2252 .to_string()
2253 };
2254 let a = crate::solve_v1::solve_v1(
2255 crate::solve_json::decode_solve_request_v1(&build(0.0)).unwrap(),
2256 )
2257 .unwrap()
2258 .resolved_request;
2259 let b = crate::solve_v1::solve_v1(
2260 crate::solve_json::decode_solve_request_v1(&build(std::f64::consts::FRAC_PI_4))
2261 .unwrap(),
2262 )
2263 .unwrap()
2264 .resolved_request;
2265
2266 // Sanity: the SAME raw bearing (both pi/2) must resolve to DIFFERENT shooter-relative
2267 // directions, purely from the azimuth difference -- confirming this fixture actually
2268 // exercises the hazard, not a fixture that happens to agree for an unrelated reason.
2269 let (a_dir, b_dir) = match (&a.wind, &b.wind) {
2270 (
2271 crate::solve_json::ResolvedWindV1::Constant(ca),
2272 crate::solve_json::ResolvedWindV1::Constant(cb),
2273 ) => (ca.direction_from_rad, cb.direction_from_rad),
2274 _ => panic!("constant wind expected on both sides"),
2275 };
2276 assert!(
2277 (a_dir - b_dir).abs() > 0.1,
2278 "fixture must produce genuinely different resolved wind directions from the SAME \
2279 raw bearing (a: {a_dir}, b: {b_dir}), or this test proves nothing"
2280 );
2281
2282 let rep = explain_difference(&a, &b, &[300.0])
2283 .expect("a derived-value exclusion must not abort the whole comparison");
2284
2285 // Non-triviality (small consistency note, review round 4): the total must be genuinely
2286 // non-zero, or a fixture that collapsed to two identical trajectories overall would also
2287 // report Wind == 0.0 for the wrong reason (matching the pattern the Pressure tests
2288 // already use). This fixture's total IS expected to differ: a's and b's OWN effective
2289 // (shooter-relative) wind angle differ, since the SAME raw bearing is transformed by
2290 // DIFFERENT shot azimuths -- the sanity check above already pins that resolved-direction
2291 // difference down; this confirms it actually shows up in the un-swapped baseline too.
2292 assert!(
2293 rep.rows[0].total.windage_m.abs() > 0.01,
2294 "expected a's and b's own (un-swapped) trajectories to differ meaningfully in \
2295 windage, since their effective wind angles differ -- got total windage {}",
2296 rep.rows[0].total.windage_m
2297 );
2298
2299 let wind = rep.rows[0]
2300 .contributions
2301 .iter()
2302 .find(|c| c.group == InputGroup::Wind)
2303 .unwrap();
2304 assert_eq!(
2305 wind.delta.drop_m, 0.0,
2306 "Wind's drop contribution must be exactly zero (WindDirection excluded), got {}",
2307 wind.delta.drop_m
2308 );
2309 assert_eq!(
2310 wind.delta.windage_m, 0.0,
2311 "Wind's windage contribution must be exactly zero (WindDirection excluded), got {}",
2312 wind.delta.windage_m
2313 );
2314
2315 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
2316 let hit = rep
2317 .skipped_axes
2318 .iter()
2319 .find(|s| {
2320 s.group == InputGroup::Wind
2321 && s.axis == InputAxis::WindDirection
2322 && s.direction == direction
2323 })
2324 .unwrap_or_else(|| {
2325 panic!(
2326 "expected a {direction:?} WindDirection skip under compass wind; got \
2327 {:?}",
2328 rep.skipped_axes
2329 )
2330 });
2331 assert!(
2332 hit.reason.to_lowercase().contains("shot_azimuth")
2333 || hit.reason.to_lowercase().contains("azimuth"),
2334 "reason should name the shot-azimuth dependency: {}",
2335 hit.reason
2336 );
2337 }
2338 }
2339
2340 /// Review round 4, F1: the WindDirection exclusion must NOT fire when the two requests'
2341 /// shot azimuths MATCH -- only a differing azimuth actually entangles the compass-to-
2342 /// shooter-relative transform. Two compass-referenced requests with the SAME
2343 /// `shot_azimuth_rad` but DIFFERENT raw wind bearings must attribute that difference to
2344 /// `Wind` normally: excluding `WindDirection` unconditionally on the compass mode flag
2345 /// alone (the bug this test guards against) would UNDER-attribute a genuine wind-bearing
2346 /// difference into the interaction remainder on the most natural same-shot-direction
2347 /// compass comparison anyone would run.
2348 #[test]
2349 fn wind_direction_is_still_swapped_when_the_shot_azimuth_matches() {
2350 let build = |bearing_rad: f64| {
2351 serde_json::json!({
2352 "schema_version": 1,
2353 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2354 "ballistic_coefficient": 0.243},
2355 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
2356 "shot": {"max_range_m": 900.0, "shot_azimuth_rad": 0.3},
2357 "atmosphere": {"temperature_k": 288.0},
2358 "wind": {"speed_mps": 3.0, "direction_from_rad": bearing_rad,
2359 "wind_reference": "compass"},
2360 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
2361 })
2362 .to_string()
2363 };
2364 let a = crate::solve_v1::solve_v1(
2365 crate::solve_json::decode_solve_request_v1(&build(std::f64::consts::FRAC_PI_2))
2366 .unwrap(),
2367 )
2368 .unwrap()
2369 .resolved_request;
2370 let b = crate::solve_v1::solve_v1(
2371 crate::solve_json::decode_solve_request_v1(&build(std::f64::consts::FRAC_PI_4))
2372 .unwrap(),
2373 )
2374 .unwrap()
2375 .resolved_request;
2376 assert_eq!(
2377 a.shot.shot_azimuth_rad, b.shot.shot_azimuth_rad,
2378 "fixture assumption: identical shot azimuth on both sides"
2379 );
2380
2381 let rep = explain_difference(&a, &b, &[300.0]).unwrap();
2382
2383 assert!(
2384 !rep.skipped_axes
2385 .iter()
2386 .any(|s| s.group == InputGroup::Wind && s.axis == InputAxis::WindDirection),
2387 "WindDirection must not be excluded when the shot azimuth matches on both sides; \
2388 got {:?}",
2389 rep.skipped_axes
2390 );
2391
2392 let wind = rep.rows[0]
2393 .contributions
2394 .iter()
2395 .find(|c| c.group == InputGroup::Wind)
2396 .unwrap();
2397 assert!(
2398 wind.delta.windage_m.abs() > 0.01,
2399 "Wind's windage contribution must be substantial and non-zero here -- the raw \
2400 bearing genuinely differs and the shared azimuth means WindDirection is safe to \
2401 swap -- got {}",
2402 wind.delta.windage_m
2403 );
2404 }
2405
2406 /// Requirement (1)'s third example, both detection paths at once: `a` is constant wind and
2407 /// `b` is segmented, so the Forward leg (reading FROM b) hits `read_axis` returning `None`,
2408 /// and the Backward leg (writing TO b) hits `with_axis`'s own `AxisAbsent`.
2409 #[test]
2410 fn wind_axes_are_skipped_and_recorded_under_segmented_wind_on_either_side() {
2411 let a = resolved(823.0, 288.0);
2412 let segmented_json = serde_json::json!({
2413 "schema_version": 1,
2414 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2415 "ballistic_coefficient": 0.243},
2416 "rifle": {"muzzle_velocity_mps": 850.0, "sight_height_m": 0.05},
2417 "shot": {"max_range_m": 900.0, "zero_distance_m": 100.0},
2418 "atmosphere": {"temperature_k": 295.0},
2419 "wind": {"segments": [{"until_distance_m": 900.0, "speed_mps": 4.0,
2420 "direction_from_rad": 1.2}]},
2421 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
2422 })
2423 .to_string();
2424 let b = crate::solve_v1::solve_v1(
2425 crate::solve_json::decode_solve_request_v1(&segmented_json).unwrap(),
2426 )
2427 .unwrap()
2428 .resolved_request;
2429 assert!(matches!(
2430 b.wind,
2431 crate::solve_json::ResolvedWindV1::Segmented(_)
2432 ));
2433
2434 let rep = explain_difference(&a, &b, &[300.0])
2435 .expect("segmented wind must not abort the whole comparison");
2436
2437 for axis in [
2438 InputAxis::WindSpeed,
2439 InputAxis::WindDirection,
2440 InputAxis::WindVertical,
2441 ] {
2442 assert!(
2443 rep.skipped_axes.iter().any(|s| s.group == InputGroup::Wind
2444 && s.axis == axis
2445 && s.direction == SwapDirectionV1::Forward),
2446 "{axis:?}: expected a Forward skip (the source, b, is segmented); got {:?}",
2447 rep.skipped_axes
2448 );
2449 assert!(
2450 rep.skipped_axes.iter().any(|s| s.group == InputGroup::Wind
2451 && s.axis == axis
2452 && s.direction == SwapDirectionV1::Backward),
2453 "{axis:?}: expected a Backward skip (the destination, b, is segmented); got {:?}",
2454 rep.skipped_axes
2455 );
2456 }
2457 }
2458
2459 /// (F2, 0.33.0 final-review fix wave) `Effects` lists `MagnusEnabled` before
2460 /// `EnhancedSpinDriftEnabled`; naively swapping Magnus on (from B into A) while A still
2461 /// carries its own `enhanced_spin_drift = true` from before would produce an intermediate
2462 /// request with both flags true, which `solve_v1` rejects as `ConflictingFields`
2463 /// (`taxonomy.rs`'s Known Limitation (d)) -- even though the FINAL state after the whole
2464 /// group is applied (magnus on, enhanced spin drift off) would have been perfectly valid,
2465 /// and even though `a` and `b` each solve fine individually. Before this fix,
2466 /// `explain_difference` let that intermediate failure propagate and abort the ENTIRE
2467 /// report; `plan_exclusions`'s own principle is that an exclusion never aborts the
2468 /// comparison, so this must instead exclude both conflicting axes together (see
2469 /// `plan_exclusions`'s `MagnusEnabled` guard for why BOTH, not just one) and let the
2470 /// comparison succeed.
2471 #[test]
2472 fn magnus_and_enhanced_spin_drift_conflict_is_excluded_not_a_hard_abort() {
2473 let a = resolved_with_effects(823.0, false, true); // magnus off, enhanced_spin_drift on
2474 let b = resolved_with_effects(823.0, true, false); // magnus on, enhanced_spin_drift off
2475 let rep = explain_difference(&a, &b, &[300.0]).expect(
2476 "a magnus/enhanced_spin_drift conflict must be excluded, not abort the whole report",
2477 );
2478
2479 for axis in [
2480 InputAxis::MagnusEnabled,
2481 InputAxis::EnhancedSpinDriftEnabled,
2482 ] {
2483 for direction in [SwapDirectionV1::Forward, SwapDirectionV1::Backward] {
2484 assert!(
2485 rep.skipped_axes
2486 .iter()
2487 .any(|s| s.group == InputGroup::Effects
2488 && s.axis == axis
2489 && s.direction == direction),
2490 "{axis:?} {direction:?}: expected a skip naming the magnus/\
2491 enhanced_spin_drift conflict; got {:?}",
2492 rep.skipped_axes
2493 );
2494 }
2495 }
2496 // The reason names the real conflict, not a placeholder.
2497 let reason = &rep
2498 .skipped_axes
2499 .iter()
2500 .find(|s| s.group == InputGroup::Effects && s.axis == InputAxis::MagnusEnabled)
2501 .unwrap()
2502 .reason;
2503 assert!(reason.contains("enhanced_spin_drift"), "{reason}");
2504
2505 assert_eq!(rep.rows.len(), 1);
2506 }
2507
2508 // ---- MBA-1603: the drag description beyond the scalar ProjectileDrag axes ----
2509
2510 /// The `resolved_with_bc_and_wind_speed(0.243, 3.0)` baseline with `projectile` members
2511 /// overwritten or added from `projectile_extra`. Every OTHER input stays byte-identical, so
2512 /// any difference between two of these is a ProjectileDrag difference and nothing else.
2513 fn resolved_with_projectile(
2514 projectile_extra: serde_json::Value,
2515 ) -> crate::solve_json::ResolvedSolveRequestV1 {
2516 let mut json = serde_json::json!({
2517 "schema_version": 1,
2518 "projectile": {"mass_kg": 0.0113, "diameter_m": 0.00782, "drag_model": "G7",
2519 "ballistic_coefficient": 0.243},
2520 "rifle": {"muzzle_velocity_mps": 823.0, "sight_height_m": 0.05},
2521 "shot": {"max_range_m": 900.0, "zero_distance_m": 100.0},
2522 "atmosphere": {"temperature_k": 288.0},
2523 "wind": {"speed_mps": 3.0, "direction_from_rad": std::f64::consts::FRAC_PI_2},
2524 "solver": {}, "effects": {}, "sampling": {"interval_m": 25.0}
2525 });
2526 for (key, value) in projectile_extra.as_object().unwrap() {
2527 json["projectile"][key] = value.clone();
2528 }
2529 let req = crate::solve_json::decode_solve_request_v1(&json.to_string()).unwrap();
2530 crate::solve_v1::solve_v1(req).unwrap().resolved_request
2531 }
2532
2533 fn mba1603_band(min: f64, max: f64, bc: f64) -> serde_json::Value {
2534 serde_json::json!({"velocity_min_mps": min, "velocity_max_mps": max,
2535 "ballistic_coefficient": bc})
2536 }
2537
2538 /// A five-point G1-shaped curve: far enough from G7 that flying it moves the 600 m drop by
2539 /// metres, not millimetres.
2540 fn mba1603_g1ish_points() -> serde_json::Value {
2541 serde_json::json!([
2542 {"mach": 0.0, "cd": 0.2629}, {"mach": 0.9, "cd": 0.3085},
2543 {"mach": 1.0, "cd": 0.4805}, {"mach": 1.5, "cd": 0.6573},
2544 {"mach": 3.0, "cd": 0.5250}
2545 ])
2546 }
2547
2548 /// The whole of a pure projectile-drag difference must land in ProjectileDrag: every other
2549 /// group swaps byte-identical values (exactly zero), so the remainder must be zero too, and
2550 /// nothing may be reported as skipped. Before MBA-1603 the swap never carried
2551 /// `drag_table`/`bc_segments`/`corrections`, so all of it sat in the remainder instead.
2552 fn assert_all_of_it_is_projectile_drag(
2553 a: &crate::solve_json::ResolvedSolveRequestV1,
2554 b: &crate::solve_json::ResolvedSolveRequestV1,
2555 ) {
2556 let rep = explain_difference(a, b, &[300.0, 600.0]).unwrap();
2557 assert!(rep.skipped_axes.is_empty(), "{:?}", rep.skipped_axes);
2558 for row in &rep.rows {
2559 assert!(
2560 row.total.drop_m.abs() > 1e-3,
2561 "fixture must really differ at {} m: {:?}",
2562 row.range_m,
2563 row.total
2564 );
2565 let drag = row
2566 .contributions
2567 .iter()
2568 .find(|c| c.group == InputGroup::ProjectileDrag)
2569 .unwrap()
2570 .delta;
2571 assert!(
2572 (drag.drop_m - row.total.drop_m).abs() < 1e-9
2573 && (drag.windage_m - row.total.windage_m).abs() < 1e-9,
2574 "range {}: ProjectileDrag {:?} must equal the total {:?} (remainder {:?})",
2575 row.range_m,
2576 drag,
2577 row.total,
2578 row.interaction_remainder
2579 );
2580 assert!(
2581 row.interaction_remainder.drop_m.abs() < 1e-9
2582 && row.interaction_remainder.windage_m.abs() < 1e-9,
2583 "range {}: remainder {:?}",
2584 row.range_m,
2585 row.interaction_remainder
2586 );
2587 for c in row
2588 .contributions
2589 .iter()
2590 .filter(|c| c.group != InputGroup::ProjectileDrag)
2591 {
2592 assert!(
2593 c.delta.drop_m.abs() < 1e-9,
2594 "{:?} {}",
2595 c.group,
2596 c.delta.drop_m
2597 );
2598 }
2599 }
2600 }
2601
2602 #[test]
2603 fn a_bc_ladder_difference_is_attributed_to_projectile_drag() {
2604 let a = resolved_with_projectile(serde_json::json!({}));
2605 let b = resolved_with_projectile(serde_json::json!({
2606 "bc_segments": [mba1603_band(600.0, 999.0, 0.260), mba1603_band(0.0, 600.0, 0.220)]
2607 }));
2608 assert_all_of_it_is_projectile_drag(&a, &b);
2609 }
2610
2611 #[test]
2612 fn a_drag_table_difference_is_attributed_to_projectile_drag() {
2613 let a = resolved_with_projectile(serde_json::json!({}));
2614 let b = resolved_with_projectile(serde_json::json!({
2615 "drag_table": {"kind": "reference", "points": mba1603_g1ish_points()}
2616 }));
2617 assert_all_of_it_is_projectile_drag(&a, &b);
2618 }
2619
2620 /// The reference-curve hazard: swapping `drag_model` alone flew A's G7-referenced band BCs
2621 /// against G1 (and B's G1 bands against G7), a projectile neither request describes. The
2622 /// ladder must travel with the model it is measured against.
2623 #[test]
2624 fn a_drag_model_swap_carries_the_ladder_measured_against_it() {
2625 let a = resolved_with_projectile(serde_json::json!({
2626 "drag_model": "G7",
2627 "bc_segments": [mba1603_band(600.0, 999.0, 0.260), mba1603_band(0.0, 600.0, 0.220)]
2628 }));
2629 let b = resolved_with_projectile(serde_json::json!({
2630 "drag_model": "G1",
2631 "bc_segments": [mba1603_band(600.0, 999.0, 0.500), mba1603_band(0.0, 600.0, 0.450)]
2632 }));
2633 assert_all_of_it_is_projectile_drag(&a, &b);
2634 }
2635
2636 /// A drag table on one side and a ladder on the other must swap as one unit: carrying
2637 /// either member alone onto the other request would pair one request's ladder with the
2638 /// other's table. Beside a `projectile`-kind table solve_v1 refuses that pair
2639 /// (`conflicting_fields`), aborting the whole report; beside this `reference`-kind table it
2640 /// would fly G7-measured band BCs over a G1-shaped curve, a projectile neither request has.
2641 #[test]
2642 fn a_drag_table_versus_a_bc_ladder_swaps_as_one_unit() {
2643 let a = resolved_with_projectile(serde_json::json!({
2644 "drag_table": {"kind": "reference", "points": mba1603_g1ish_points()}
2645 }));
2646 let b = resolved_with_projectile(serde_json::json!({
2647 "bc_segments": [mba1603_band(600.0, 999.0, 0.260), mba1603_band(0.0, 600.0, 0.220)]
2648 }));
2649 assert_all_of_it_is_projectile_drag(&a, &b);
2650 }
2651
2652 /// A reference table carrying a ladder is one drag description: against the same ladder on
2653 /// `drag_model`'s curve, the table travels with the ladder measured against it, and the
2654 /// whole difference is projectile drag.
2655 #[test]
2656 fn a_reference_table_carrying_a_ladder_swaps_as_one_unit() {
2657 let ladder = serde_json::json!([
2658 mba1603_band(600.0, 999.0, 0.260),
2659 mba1603_band(0.0, 600.0, 0.220)
2660 ]);
2661 let a = resolved_with_projectile(serde_json::json!({
2662 "drag_table": {"kind": "reference", "points": mba1603_g1ish_points()},
2663 "bc_segments": ladder.clone()
2664 }));
2665 let b = resolved_with_projectile(serde_json::json!({"bc_segments": ladder}));
2666 assert_all_of_it_is_projectile_drag(&a, &b);
2667 }
2668
2669 /// Equal drag descriptions keep the pre-MBA-1603 path exactly: the guard reports no
2670 /// difference, so `swap_group` never clears or rewrites the description, a scalar BC
2671 /// difference under the SAME ladder still attributes to ProjectileDrag, and the report
2672 /// matches the two legs recomputed from that swap.
2673 ///
2674 /// Carrying an equal description anyway would give the same numbers at the cost of extra
2675 /// solves, so the report alone cannot tell the two paths apart; the guard is asserted
2676 /// directly.
2677 #[test]
2678 fn equal_drag_descriptions_leave_the_existing_swap_untouched() {
2679 // An interior gap (500-700 m/s) is where the scalar BC flies under a ladder.
2680 let ladder = serde_json::json!([
2681 mba1603_band(700.0, 999.0, 0.260),
2682 mba1603_band(0.0, 500.0, 0.220)
2683 ]);
2684 let a = resolved_with_projectile(serde_json::json!({"bc_segments": ladder.clone()}));
2685 let b = resolved_with_projectile(serde_json::json!({
2686 "ballistic_coefficient": 0.300, "bc_segments": ladder
2687 }));
2688 assert!(
2689 !drag_descriptions_differ(&a, &b) && !drag_descriptions_differ(&b, &a),
2690 "a scalar BC difference under one ladder is not a drag-description difference"
2691 );
2692 let rep = explain_difference(&a, &b, &[600.0]).unwrap();
2693 let (excluded, _) = plan_exclusions(&a, &b, InputGroup::ProjectileDrag).unwrap();
2694 let fwd = evaluate(
2695 &swap_group(&a, &b, InputGroup::ProjectileDrag, &excluded).unwrap(),
2696 &[600.0],
2697 )
2698 .unwrap();
2699 let bwd = evaluate(
2700 &swap_group(&b, &a, InputGroup::ProjectileDrag, &excluded).unwrap(),
2701 &[600.0],
2702 )
2703 .unwrap();
2704 let obs_a = evaluate(&(&a).into(), &[600.0]).unwrap();
2705 let obs_b = evaluate(&(&b).into(), &[600.0]).unwrap();
2706 let expected = DeltaV1::mean(
2707 DeltaV1::between(&obs_a[0], &fwd[0]),
2708 DeltaV1::between(&obs_b[0], &bwd[0]).neg(),
2709 );
2710 let drag = rep.rows[0]
2711 .contributions
2712 .iter()
2713 .find(|c| c.group == InputGroup::ProjectileDrag)
2714 .unwrap()
2715 .delta;
2716 assert_eq!(drag, expected);
2717 assert!(drag.drop_m.abs() > 1e-4, "the gap BC must fly: {drag:?}");
2718 }
2719}