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