Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

Preserve valid candidates and explicit model-support loss (#64)

Cinna Davisc97242ee6846
diff --git a/docs/MODEL_SUPPORT_COVERAGE.md b/docs/MODEL_SUPPORT_COVERAGE.md
new file mode 100644
index 0000000..4afe3f2
--- /dev/null
+++ b/docs/MODEL_SUPPORT_COVERAGE.md
@@ -0,0 +1,42 @@
+# Model-support loss in the tiled search
+
+The source data's spatial/time availability and the model's usable support are
+separate. The search report retains `data_scope_complete` for the former and adds
+`model_support_complete` for the latter. Any typed unsupported CPA trajectory or
+unclassified scoring envelope makes model support false, search status partial
+and finite-search evidence incomplete. Its unknown competitors have no optimistic
+maximum discarded score. A completed tile does not establish complete evidence.
+
+The additive `model_support` report contains these integer work counts:
+
+- `unsupported_cpa_track_evaluations`: trajectory/stage CPA failures, including
+ repeated evaluations in different coarse/refinement stages.
+- `unclassified_score_candidates`: candidate envelopes whose work is unknown.
+- `evaluated_trials`, `rejected_trials`, `unknown_trials`: totals explicitly
+ reported by robust scorer assessments.
+- `unreported_trial_envelopes`: interrupted or missing/malformed trial accounting;
+ its unknown trial count must not be inferred as zero.
+
+`diagnostics_directory` points to `support/`. Per-stage JSON files preserve every
+affected track ID/reason and every unclassified candidate's receiver, event/flight
+assignments, pass times, available clock bounds and scoring assessment. Coarse
+checkpoints also retain these diagnostics; resumed counts replace work rather
+than inflating it. Refinement failures use separate stage files. Per-stage lists
+are bounded by the existing track/candidate budgets; the report aggregates counts
+without collecting a national diagnostic list in memory.
+
+Only `geometry.AcousticSupportError` is isolated. A CPA error conservatively
+excludes that entire track's work for the receiver stage, including partial rows
+from earlier chunks, and keeps valid other-track rows. The diagnostic labels the
+whole track time span and receiver extent as a conservative loss envelope: this
+narrow exception does not identify the exact unsupported interval. Original index
+payloads are retained. Robust scoring classifies typed failures per clock trial;
+the outer handler also preserves other candidates if a legacy scorer raises the
+same typed error. An interrupted scorer's unreported trial count stays unknown.
+Generic programming/configuration errors retain the existing explicit tile-failure
+behavior.
+
+This handling does not certify continuous total speed or Newton convergence,
+repair historical missing derivatives or altitude clipping, identify the cause of
+bad observations, or establish complete real-flight coverage. Issue #64 retains
+those open gates and the historical 855/858 result. No old outcome is promoted.
diff --git a/scripts/check_unsupported_tiles.py b/scripts/check_unsupported_tiles.py
new file mode 100644
index 0000000..08bc386
--- /dev/null
+++ b/scripts/check_unsupported_tiles.py
@@ -0,0 +1,99 @@
+"""Replay the three historical failed scale-fixture tiles, without audio truth.
+
+Compare preserved scores with a per-track oracle on the unchanged canonical
+index. This is a fault-isolation regression, not a localization benchmark.
+"""
+import argparse
+import json
+from pathlib import Path
+import subprocess
+import time
+
+import numpy as np
+
+from aircraft_geoloc.audio import Spectrum
+from aircraft_geoloc.data_access import FlightIndex, sha256, write_json
+from aircraft_geoloc.geometry import AcousticSupportError
+from aircraft_geoloc.search import cpa_table, pair_candidates, score_candidate
+from aircraft_geoloc.terrain import Terrain
+from aircraft_geoloc.tiled_search import SearchBudget, _expanded_bounds, _record_support, _score, _tracks, grid_tiles, merge_candidates, tile_points
+
+
+def signature(rows):
+ return [(r["flight_ids"], r["x"], r["y"], r["score"], r["recording_start_time_s"],
+ r["pass_emission_times_s"]) for r in rows]
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("index")
+ parser.add_argument("output")
+ parser.add_argument("--manifest", default="evidence/w2-data-scale-20261102/scale-v2-manifest.json")
+ args = parser.parse_args()
+ output = Path(args.output)
+ output.mkdir(parents=True, exist_ok=False)
+ config = json.loads(Path(args.manifest).read_text())["configuration"]
+ index = FlightIndex(args.index)
+ assert sha256(index.path) == config["indexes"][0]["file_sha256"], "Require the unchanged historical index"
+ assert index.report["input_hash"] == config["indexes"][0]["input_hash"]
+ budget = SearchBudget(**config["budget"])
+ event, = config["events"]
+ t = np.linspace(event["start_s"], event["end_s"], 41)
+ ridge = 120 * (1 - .12 * np.tanh((t - event["cpa_receive_s"]) / 12))
+ spec = Spectrum(t, np.array([80., 160.]), np.zeros((2, len(t))), np.zeros((2, len(t))))
+ measurements = [(spec, ridge, np.ones(len(t)), {})]
+ radius, began, reports = event["slant_range_m"][1], time.monotonic(), []
+ selected = {"5_13", "9_9", "7_15"}
+ for name, cells in grid_tiles(config["bounds"], budget.spacing_m, budget.tile_cells):
+ if name not in selected:
+ continue
+ points = tile_points(cells, budget.spacing_m, config["bounds"], Terrain(constant_m=0), config["crs"])
+ tracks = _tracks([index], _expanded_bounds(cells, budget.spacing_m, radius, config["crs"]), config["time_range_s"], budget)
+ ranked, counts = _score(points, tracks, [event], measurements, budget, config["scoring"], {})
+ summary = dict(unsupported_cpa_track_evaluations=0, unclassified_score_candidates=0,
+ evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)
+ _record_support(output, f"coarse:{name}", counts, summary)
+ # Independently enumerate/score each track. A failure cannot interrupt
+ # unrelated tracks in this oracle; retain every finite result before k.
+ reference, failures, nonfinite = [], [], 0
+ lookup = {p.point_id: p for p in points.itertuples()}
+ for track in tracks:
+ table = cpa_table([track], points, radius, config["scoring"].get("c", 343.), budget.cpa_step_s)
+ candidates, _ = pair_candidates(table, [event], time_origin=config["scoring"]["time_origin"], time_tolerance_s=5.)
+ for candidate in candidates:
+ try:
+ row = score_candidate(candidate, lookup[candidate["point_id"]], {track.id: track},
+ [event], measurements, **config["scoring"])
+ except AcousticSupportError as error:
+ failures.append({"flight_id": track.id, "point_id": int(candidate["point_id"]), "reason": error.reason})
+ continue
+ if np.isfinite(row["score"]):
+ row["pass_emission_times_s"] = [float(p["emission_time"]) for p in candidate["passes"]]
+ reference.append(row)
+ else:
+ nonfinite += 1
+ kept = merge_candidates(reference, budget.top_k)
+ assert signature(ranked) == signature(kept), f"Clean candidate change at {name}"
+ assert counts["unclassified_score_candidates"] == len(failures) + nonfinite
+ assert failures and ranked, "Each historical failure tile must preserve valid diagnostics"
+ report = {"tile": name, "tracks": len(tracks), "points": len(points), "finite_oracle_rows": len(reference),
+ "retained_rows": len(ranked), "typed_candidate_failures": failures, "nonfinite_oracle_rows": nonfinite,
+ "model_support_complete": False, "model_support": summary, "clean_scores_equal_oracle": True,
+ "ranked": ranked}
+ write_json(output / f"tile-{name}.json", report)
+ reports.append({k: v for k, v in report.items() if k != "ranked"})
+ print(json.dumps({k: v for k, v in report.items() if k not in ("ranked", "typed_candidate_failures")}), flush=True)
+ assert {r["tile"] for r in reports} == selected
+ root = Path(__file__).resolve().parents[1]
+ write_json(output / "report.json", {"scope": "Historical three failed analytic-ridge scale tiles; no localization truth",
+ "source_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip(),
+ "index_sha256": sha256(index.path), "index_input_hash": index.report["input_hash"],
+ "old_manifest_sha256": sha256(args.manifest), "code_sha256": {p.name: sha256(p) for p in (root / "src/aircraft_geoloc").glob("*.py")},
+ "runner_sha256": sha256(__file__), "elapsed_s": time.monotonic()-began, "tiles": reports,
+ "limitations": ["Diagnostic tiles were selected from preserved historical model failures, not recorder truth.",
+ "Same legacy derivatives/altitudes and constant ground; no raw normalization repair.",
+ "This does not certify continuous motion, complete national coverage or geolocation accuracy."]})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/aircraft_geoloc/finite_search.py b/src/aircraft_geoloc/finite_search.py
index f4df1da..673feef 100644
--- a/src/aircraft_geoloc/finite_search.py
+++ b/src/aircraft_geoloc/finite_search.py
@@ -33,10 +33,17 @@ def identify_mode(row):
def classified_assessment(row):
assessment = row.get("scoring_assessment")
- return (isinstance(assessment, dict) and assessment.get("complete") is True
+ valid = (isinstance(assessment, dict) and assessment.get("complete") is True
and all(type(assessment.get(k)) is int and assessment[k] >= 0
for k in ("evaluated_trials", "rejected_trials", "unknown_trials"))
and assessment["unknown_trials"] == 0)
+ if not valid:
+ return False
+ # No trials is unknown work. A finite best needs an evaluated trial; a
+ # wholly rejected envelope cannot have discarded an evaluated finite best.
+ score = row.get("score", math.nan)
+ return (assessment["evaluated_trials"] > 0 if math.isfinite(score) else
+ score == -math.inf and assessment["evaluated_trials"] == 0 and assessment["rejected_trials"] > 0)
class RetentionLedger:
diff --git a/src/aircraft_geoloc/tiled_search.py b/src/aircraft_geoloc/tiled_search.py
index 2d5ffef..cbad0ef 100644
--- a/src/aircraft_geoloc/tiled_search.py
+++ b/src/aircraft_geoloc/tiled_search.py
@@ -19,6 +19,7 @@ from pyproj import Transformer
from .data_access import CONUS, DataUnavailable, content_hash, sha256, write_json
from .finite_search import RetentionLedger, classified_assessment, identify_mode, mode_seed
+from .geometry import AcousticSupportError
from .search import cpa_table, filter_event, pair_candidates, score_candidate
@@ -132,6 +133,7 @@ def _tracks(indexes, bounds, time_range, budget):
def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None, *, ledger=None, stage=None):
radius = max(e["slant_range_m"][1] for e in events)
tables, count = [], 0
+ unsupported = []
# Bound materialized CPA rows before pairing; one track at a time keeps the
# national traffic count out of the CPA tensor/list allocation.
for track in tracks:
@@ -141,17 +143,31 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, st
# Even a pathological looping track cannot allocate an unbounded list
# of minima before we inspect the returned table.
chunk_points = max(1, budget.max_cpa_rows // samples)
- for first in range(0, len(points), chunk_points):
- table = cpa_table([track], points.iloc[first:first + chunk_points], radius, parameters.get("c", 343.0), budget.cpa_step_s)
- count += len(table)
- if count > budget.max_cpa_rows:
- raise DataUnavailable("Tile CPA-row memory budget exceeded")
- if len(table):
- tables.append(table)
+ track_tables, track_rows = [], 0
+ try:
+ for first in range(0, len(points), chunk_points):
+ table = cpa_table([track], points.iloc[first:first + chunk_points], radius, parameters.get("c", 343.0), budget.cpa_step_s)
+ track_rows += len(table)
+ if count + track_rows > budget.max_cpa_rows:
+ raise DataUnavailable("Tile CPA-row memory budget exceeded")
+ if len(table):
+ track_tables.append(table)
+ except AcousticSupportError as error:
+ # The typed failure does not identify an exact bad interval. Keep
+ # the entire track/stage as explicitly unassessed, and retain rows
+ # from other tracks. Never repair or clip the source payload here.
+ unsupported.append({"track_id": track.id, "reported_track_id": error.track_id, "reason": error.reason,
+ "emission_time_range_s": [float(track.time[0]), float(track.time[-1])],
+ "receiver_bounds_wsen": [float(points.lon.min()), float(points.lat.min()),
+ float(points.lon.max()), float(points.lat.max())],
+ "receiver_point_count": len(points), "coverage_envelope": "whole_track_whole_stage_conservative"})
+ continue
+ count += track_rows
+ tables.extend(track_tables)
if not tables:
if ledger is not None:
ledger.record(stage, [], [], 0)
- return [], {"cpa_rows": 0, "candidates": 0}
+ return [], {"cpa_rows": 0, "candidates": 0, "unsupported_cpa_tracks": unsupported}
table = pd.concat(tables, ignore_index=True)
kwargs = dict(offset_tolerance_s=filters.get("offset_tolerance_s", 5.0),
time_origin=parameters.get("time_origin"), time_tolerance_s=filters.get("time_tolerance_s", 5.0),
@@ -170,6 +186,8 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, st
candidates, counts = pair_candidates(table, events, **kwargs)
# Attach approach identities before scoring, since legacy rank drops passes.
ranked, unclassified, rejected = [], 0, 0
+ trial_counts = dict(evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)
+ unclassified_assessments = []
lookup = {row.point_id: row for row in points.itertuples()}
track_lookup = {track.id: track for track in tracks}
for candidate in candidates:
@@ -194,20 +212,58 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, st
settings.update(time_origin=None, time_sweep_s=0)
else:
settings.update(time_origin=(lo + hi) / 2, time_sweep_s=(hi - lo) / 2)
- row = score_candidate(scoring_candidate, lookup[candidate["point_id"]], track_lookup, events, measurements, **settings)
+ point = lookup[candidate["point_id"]]
+ try:
+ row = score_candidate(scoring_candidate, point, track_lookup, events, measurements, **settings)
+ except AcousticSupportError as error:
+ # Legacy scorers may stop before reporting their trial counts. Do
+ # not invent an exact count for an interrupted clock envelope.
+ row = dict(score=-np.inf, **{k: float(getattr(point, k)) for k in ("x", "y", "lat", "lon", "elev_m")},
+ flight_ids=[p["flight_id"] for p in candidate["passes"]],
+ event_indices=candidate.get("event_indices", list(range(len(events)))),
+ support_failure={"track_id": error.track_id, "reason": error.reason})
row["pass_emission_times_s"] = [float(p["emission_time"]) for p in candidate["passes"]]
known = (classified_assessment(row) if settings.get("mode") == "robust_ridge" else
settings.get("time_origin") is not None and settings.get("time_sweep_s", 5) == 0 and math.isfinite(row["score"]))
row["core_assessment_complete"] = bool(known and math.isfinite(row["score"]))
+ if settings.get("mode") == "robust_ridge":
+ assessment = row.get("scoring_assessment")
+ if isinstance(assessment, dict) and all(type(assessment.get(k)) is int and assessment[k] >= 0
+ for k in ("evaluated_trials", "rejected_trials", "unknown_trials")):
+ for key in ("evaluated_trials", "rejected_trials", "unknown_trials"):
+ trial_counts[key] += assessment[key]
+ else:
+ trial_counts["unreported_trial_envelopes"] += 1
+ elif not known:
+ trial_counts["unreported_trial_envelopes"] += 1
if not known:
unclassified += 1
+ unclassified_assessments.append({"point_id": int(candidate["point_id"]),
+ "receiver": {k: float(row[k]) for k in ("x", "y", "lat", "lon", "elev_m")},
+ "event_indices": row.get("event_indices", list(range(len(events)))), "flight_ids": row["flight_ids"],
+ "pass_emission_times_s": row["pass_emission_times_s"],
+ "recording_start_bounds_s": scoring_candidate.get("recording_start_bounds_s"),
+ "scoring_assessment": row.get("scoring_assessment"), "support_failure": row.get("support_failure"),
+ "finite_best": math.isfinite(row["score"])})
if math.isfinite(row["score"]):
ranked.append(row)
elif known:
rejected += 1
kept = merge_candidates(ranked, budget.top_k, ledger=ledger, stage=stage)
return kept, dict(counts, cpa_rows=count, candidates=len(candidates), unclassified_score_candidates=unclassified,
- evaluated_rejections=rejected)
+ evaluated_rejections=rejected, unsupported_cpa_tracks=unsupported,
+ unclassified_candidate_assessments=unclassified_assessments, **trial_counts)
+
+
+def _record_support(output, stage, counts, summary):
+ summary["unsupported_cpa_track_evaluations"] += len(counts.get("unsupported_cpa_tracks", []))
+ for key in ("unclassified_score_candidates", "evaluated_trials", "rejected_trials", "unknown_trials", "unreported_trial_envelopes"):
+ summary[key] += counts.get(key, 0)
+ if counts.get("unsupported_cpa_tracks") or counts.get("unclassified_candidate_assessments"):
+ (output / "support").mkdir(exist_ok=True)
+ write_json(output / "support" / (stage.replace(":", "-") + ".json"),
+ {"stage": stage, "unsupported_cpa_tracks": counts.get("unsupported_cpa_tracks", []),
+ "unclassified_candidate_assessments": counts.get("unclassified_candidate_assessments", [])})
def search_national(indexes, terrain, events, measurements, *, time_range_s, output_dir,
@@ -277,7 +333,8 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
"brightness": "summed_spectral_contrast"}[mode])
ledger = RetentionLedger(output / "retention.sqlite", run_hash, score_kind)
began, ranked, failures, done, resumed, points_searched = time.monotonic(), [], [], 0, 0, 0
- unclassified_scores = 0
+ support = dict(unsupported_cpa_track_evaluations=0, unclassified_score_candidates=0,
+ evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)
xmin, ymin, xmax, ymax = _grid_extent(bounds, budget.spacing_m, crs)
total = (xmax // budget.tile_cells - xmin // budget.tile_cells + 1) * (ymax // budget.tile_cells - ymin // budget.tile_cells + 1)
radius = max(e["slant_range_m"][1] for e in events)
@@ -316,7 +373,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
write_json(checkpoint, {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload})
done += 1
points_searched += payload["grid_points"]
- unclassified_scores += payload["counts"].get("unclassified_score_candidates", 0)
+ _record_support(output, stage, payload["counts"], support)
ranked = merge_candidates(itertools.chain(ranked, payload["ranked"]), budget.top_k,
ledger=ledger, stage=f"global:{tile_id}")
except (DataUnavailable, ValueError, OSError) as error:
@@ -358,7 +415,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
stage = f"fine:{seed_index}:{x0}:{y0}"
rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,
ledger=ledger, stage=stage)
- unclassified_scores += counts.get("unclassified_score_candidates", 0)
+ _record_support(output, stage, counts, support)
fine_stages += 1
refinement_points_searched += len(points)
ranked = merge_candidates(itertools.chain(ranked, rows), budget.top_k,
@@ -382,12 +439,14 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
if lo <= covered_until:
covered_until = max(covered_until, hi)
data_complete = bool(covered_until >= time_range_s[1])
- complete = done == total and not failures and not refinement_failure and data_complete and not event_limit_applied
- finite = ledger.evidence(ranked, complete=complete and not unclassified_scores, spacing_m=budget.spacing_m,
+ model_complete = not (support["unsupported_cpa_track_evaluations"] or support["unclassified_score_candidates"])
+ complete = done == total and not failures and not refinement_failure and data_complete and not event_limit_applied and model_complete
+ finite = ledger.evidence(ranked, complete=complete, spacing_m=budget.spacing_m,
refine_spacing_m=min(budget.spacing_m, budget.refine_spacing_m), max_event_groups=len(events),
expected_stages={"coarse": done, "global": done, "fine": fine_stages, "fine-global": fine_stages})
- finite["unclassified_score_candidates"] = unclassified_scores
- if unclassified_scores:
+ finite["unclassified_score_candidates"] = support["unclassified_score_candidates"]
+ finite["unsupported_cpa_track_evaluations"] = support["unsupported_cpa_track_evaluations"]
+ if not model_complete:
finite["best_discarded_score"] = None
finite["discarded_bound_status"] = "unknown_model_or_trial_support"
finite["limitations"].append("Unclassified or unsupported optimizer trials have no known upper score bound.")
@@ -404,6 +463,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
"coarse_ranked": coarse, "tiles_total": total, "tiles_completed": done, "tiles_resumed": resumed,
"tile_failures": failures, "unsearched_tiles": total - done, "grid_points_searched": points_searched,
"data_coverage": coverage, "data_scope_complete": data_complete, "refinement_failure": refinement_failure,
+ "model_support_complete": model_complete, "model_support": dict(support, diagnostics_directory="support"),
"refinement_points_searched": refinement_points_searched, "refinement_points_skipped": refinement_points_skipped,
"required_flight_bounds": flight_bounds,
"candidate_retention_limit": budget.top_k, "alternative_modes_exhaustively_assessed": False,
diff --git a/tests/test_finite_search.py b/tests/test_finite_search.py
index f6657a7..58c43f5 100644
--- a/tests/test_finite_search.py
+++ b/tests/test_finite_search.py
@@ -96,3 +96,10 @@ def test_a_finite_best_score_does_not_hide_unknown_optimizer_trials():
assert not classified_assessment({"score": .9})
for change in [{"complete": False}, {"unknown_trials": 1}, {"evaluated_trials": None}, {"rejected_trials": -1}]:
assert not classified_assessment({"score": .9, "scoring_assessment": dict(good, **change)})
+ for score in [float("nan"), float("inf"), -float("inf")]:
+ assert not classified_assessment({"score": score, "scoring_assessment": good})
+ empty = dict(good, evaluated_trials=0, rejected_trials=0)
+ assert not classified_assessment({"score": .9, "scoring_assessment": empty})
+ assert not classified_assessment({"score": -float("inf"), "scoring_assessment": empty})
+ rejected = dict(empty, rejected_trials=3)
+ assert classified_assessment({"score": -float("inf"), "scoring_assessment": rejected})
diff --git a/tests/test_tiled_search.py b/tests/test_tiled_search.py
index 7dd2a2f..dbf7783 100644
--- a/tests/test_tiled_search.py
+++ b/tests/test_tiled_search.py
@@ -316,7 +316,8 @@ def test_successful_best_row_with_unknown_trials_has_no_optimistic_finite_bound(
output_dir=tmp_path / "unknown", bounds=bounds,
budget=SearchBudget(spacing_m=1000, tile_cells=4, top_k=1, refine_spacing_m=1000),
scoring={"mode": "robust_ridge", "time_origin": origin, "time_sweep_s": 0})
- assert result["ranked"] and result["status"] == "complete"
+ assert result["ranked"] and result["status"] == "partial"
+ assert not result["model_support_complete"]
finite = result["finite_search_evidence"]
assert not finite["complete"] and finite["unclassified_score_candidates"] > 0
assert finite["best_discarded_score"] is None and finite["discarded_count"] > 0
@@ -330,7 +331,7 @@ def test_evaluated_acoustic_rejection_is_distinct_from_unknown_support(tmp_path,
def rejected(*args, **kwargs):
result = original(*args, **kwargs)
- result.update(score=-np.inf, scoring_assessment={"complete": True, "evaluated_trials": 1,
+ result.update(score=-np.inf, scoring_assessment={"complete": True, "evaluated_trials": 0,
"rejected_trials": 1, "unknown_trials": 0, "reasons": ["test_admissible_rejection"]})
return result
diff --git a/tests/test_tiled_support.py b/tests/test_tiled_support.py
new file mode 100644
index 0000000..c30501a
--- /dev/null
+++ b/tests/test_tiled_support.py
@@ -0,0 +1,153 @@
+import json
+
+import pandas as pd
+import pytest
+
+from aircraft_geoloc import tiled_search
+from aircraft_geoloc.data_access import FlightIndex
+from aircraft_geoloc.geometry import AcousticSupportError, Track
+from aircraft_geoloc.terrain import Terrain
+from aircraft_geoloc.tiled_search import SearchBudget, _score, search_national, tile_points
+from test_tiled_search import compact, scenario
+
+
+def with_bad_copy(tmp_path):
+ index, tracks, events, measurements, bounds, times, origin = scenario(tmp_path)
+ first = tracks[0]
+ bad = Track("unsupported-source", first.time, first.lat, first.lon, first.altitude)
+ frames = [pd.DataFrame({"flight_id": t.id, "time_s": t.time, "lat": t.lat, "lon": t.lon,
+ "alt_m": t.altitude, "altitude_basis": "ellipsoidal"}) for t in tracks + [bad]]
+ mixed = FlightIndex.build(tmp_path / "mixed.sqlite", frames, sources=[], coverage=index.report["coverage"])
+ return index, mixed, tracks, bad, events, measurements, bounds, times, origin
+
+
+def test_typed_legacy_candidate_failure_preserves_clean_rows_and_resume_diagnostics(tmp_path, monkeypatch):
+ index, mixed, _, _, events, measurements, bounds, times, origin = with_bad_copy(tmp_path)
+ settings = {"mode": "ridge", "time_origin": origin, "time_sweep_s": 0}
+ budget = SearchBudget(spacing_m=1000, tile_cells=4, refine_spacing_m=1000)
+ kwargs = dict(time_range_s=times, bounds=bounds, budget=budget, scoring=settings)
+ clean = search_national([index], Terrain(constant_m=0), events, measurements,
+ output_dir=tmp_path / "clean", **kwargs)
+ acoustic = Track.acoustic
+
+ def guarded(self, *args, **kwargs):
+ if self.id == "unsupported-source":
+ raise AcousticSupportError(self.id, "non_monotone_arrival")
+ return acoustic(self, *args, **kwargs)
+
+ monkeypatch.setattr(Track, "acoustic", guarded)
+ output = tmp_path / "mixed-search"
+ result = search_national([mixed], Terrain(constant_m=0), events, measurements, output_dir=output, **kwargs)
+ assert compact(result["ranked"]) == compact(clean["ranked"])
+ assert result["tiles_completed"] == result["tiles_total"] and not result["tile_failures"]
+ assert result["data_scope_complete"] and not result["model_support_complete"]
+ assert result["status"] == "partial" and not result["finite_search_evidence"]["complete"]
+ assert result["finite_search_evidence"]["best_discarded_score"] is None
+ assert result["model_support"]["unclassified_score_candidates"] > 0
+ assert result["model_support"]["unreported_trial_envelopes"] > 0
+ diagnostics = [json.loads(p.read_text()) for p in (output / "support").glob("*.json")]
+ failed = [r for d in diagnostics for r in d["unclassified_candidate_assessments"]]
+ assert failed and all(r["support_failure"] == {"track_id": "unsupported-source", "reason": "non_monotone_arrival"}
+ for r in failed)
+ assert all("unsupported-source" in r["flight_ids"] for r in failed)
+ assert any(t.id == "unsupported-source" for t in mixed.query(bounds, times)), "Source is retained unchanged"
+ replay = search_national([mixed], Terrain(constant_m=0), events, measurements, output_dir=output, **kwargs)
+ assert replay["tiles_resumed"] == replay["tiles_total"]
+ assert replay["model_support"] == result["model_support"]
+ assert compact(replay["ranked"]) == compact(result["ranked"])
+
+
+def test_cpa_support_failure_records_conservative_whole_track_loss_and_keeps_other_tracks(tmp_path, monkeypatch):
+ _, _, tracks, bad, events, measurements, bounds, _, origin = with_bad_copy(tmp_path)
+ points = tile_points((0, 1900, 2, 1901), 1000, bounds, Terrain(constant_m=0), "EPSG:5070")
+ settings = {"mode": "ridge", "time_origin": origin, "time_sweep_s": 0}
+ budget = SearchBudget(max_cpa_rows=200)
+ expected, expected_counts = _score(points, tracks, events, measurements, budget, settings, {})
+ original = tiled_search.cpa_table
+ calls = 0
+
+ def guarded(selected, *args, **kwargs):
+ nonlocal calls
+ if selected[0].id == bad.id:
+ calls += 1
+ if calls > 1:
+ raise AcousticSupportError(bad.id, "non_monotone_arrival")
+ return original(selected, *args, **kwargs)
+
+ monkeypatch.setattr(tiled_search, "cpa_table", guarded)
+ ranked, counts = _score(points, [bad]+tracks, events, measurements, budget, settings, {})
+ assert compact(ranked) == compact(expected) and ranked
+ assert counts["cpa_rows"] == expected_counts["cpa_rows"], "Partial rows from failed source are not counted as covered"
+ failure, = counts["unsupported_cpa_tracks"]
+ assert failure["track_id"] == bad.id and failure["reason"] == "non_monotone_arrival"
+ assert failure["emission_time_range_s"] == [bad.time[0], bad.time[-1]]
+ assert failure["receiver_point_count"] == len(points)
+ assert failure["coverage_envelope"] == "whole_track_whole_stage_conservative"
+ empty, counts = _score(points, [bad], events, measurements, budget, settings, {})
+ assert not empty and len(counts["unsupported_cpa_tracks"]) == 1
+
+
+def test_all_unsupported_cpa_sources_return_empty_partial_search_with_diagnostics(tmp_path, monkeypatch):
+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)
+
+ def unsupported(tracks, *args, **kwargs):
+ raise AcousticSupportError(tracks[0].id, "non_monotone_arrival")
+
+ monkeypatch.setattr(tiled_search, "cpa_table", unsupported)
+ output = tmp_path / "all-unsupported"
+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,
+ output_dir=output, bounds=bounds, budget=SearchBudget(spacing_m=1000, tile_cells=4, refine_spacing_m=1000),
+ scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})
+ assert not result["ranked"] and result["status"] == "partial"
+ assert result["tiles_completed"] == result["tiles_total"] and not result["tile_failures"]
+ assert result["data_scope_complete"] and not result["model_support_complete"]
+ assert result["model_support"]["unsupported_cpa_track_evaluations"] > 0
+ assert not result["finite_search_evidence"]["complete"]
+ assert list((output / "support").glob("coarse-*.json"))
+
+
+def test_actual_classified_robust_scorer_supplies_finite_core_ids(tmp_path):
+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)
+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,
+ output_dir=tmp_path / "classified", bounds=bounds,
+ budget=SearchBudget(spacing_m=1000, tile_cells=4, top_k=2, refine_spacing_m=1000),
+ scoring={"mode": "robust_ridge", "recording_start_window_s": [origin, origin], "time_sweep_s": 0})
+ assert result["ranked"] and result["status"] == "complete" and result["model_support_complete"]
+ assert result["finite_search_evidence"]["complete"]
+ assert result["core_assessed_mode_ids"] == [r["mode_id"] for r in result["ranked"]]
+ assert result["model_support"]["evaluated_trials"] > 0
+ assert result["model_support"]["unknown_trials"] == result["model_support"]["unreported_trial_envelopes"] == 0
+
+
+def test_cpa_programming_error_is_not_relabelled_as_source_support(tmp_path, monkeypatch):
+ _, tracks, events, measurements, bounds, _, origin = scenario(tmp_path)
+ points = tile_points((0, 1900, 1, 1901), 1000, bounds, Terrain(constant_m=0), "EPSG:5070")
+
+ def broken(*args, **kwargs):
+ raise ValueError("configuration defect")
+
+ monkeypatch.setattr(tiled_search, "cpa_table", broken)
+ with pytest.raises(ValueError, match="configuration defect"):
+ _score(points, tracks, events, measurements, SearchBudget(), {"mode": "ridge", "time_origin": origin}, {})
+
+
+def test_refinement_support_loss_is_persisted_and_cannot_be_complete(tmp_path, monkeypatch):
+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)
+ original = tiled_search._score
+
+ def fine_failure(*args, **kwargs):
+ rows, counts = original(*args, **kwargs)
+ if kwargs.get("stage", "").startswith("fine:"):
+ counts["unsupported_cpa_tracks"] = [{"track_id": "unknown-fine-competitor", "reason": "non_monotone_arrival"}]
+ return rows, counts
+
+ monkeypatch.setattr(tiled_search, "_score", fine_failure)
+ output = tmp_path / "fine"
+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,
+ output_dir=output, bounds=bounds, budget=SearchBudget(spacing_m=1000, tile_cells=4,
+ refine_spacing_m=500, refine_finalists=1), scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})
+ assert result["ranked"] and result["refinement_points_searched"] > 0
+ assert result["status"] == "partial" and not result["model_support_complete"]
+ assert result["model_support"]["unsupported_cpa_track_evaluations"] > 0
+ assert list((output / "support").glob("fine-*.json"))
+ assert result["finite_search_evidence"]["best_discarded_score"] is None