Skip to content

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

Merge current main and count workers spawned by nonleader threads

Cinna Davis2ff113cf4574
diff --cc scripts/ci_checkpoint_replay.py
index 8a4270c,0000000..04aa4fb
mode 100644,000000..100644
--- a/scripts/ci_checkpoint_replay.py
+++ b/scripts/ci_checkpoint_replay.py
@@@ -1,335 -1,0 +1,344 @@@
+#!/usr/bin/env python3
+"""Replay the configured methodology checkpoint; this is not product acceptance.
+
+Default: copy the independent synthetic generator unchanged into a fresh fixture
+tree, run BOTH configured cases through the real CLI, then open evaluation truth.
+--real-config: run only that restored regional configuration, then compare its
+result with the checked-in public-platform reference. Restore real inputs first.
+"""
+from __future__ import annotations
+
+import argparse
+from datetime import datetime, timezone
+import hashlib
+import importlib.metadata
+import json
+import math
+import os
+from pathlib import Path
+import platform
+import shutil
+import signal
+import subprocess
+import sys
+import time
+
+
+TARGET_ERROR_M = 100.0
+THREAD_ENV = {name: "1" for name in (
+ "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS")}
+LIMITATIONS = [
+ "Configured event windows and frequency bands; automatic discovery is not exercised.",
+ "The MP3 upload interface and automatic product pipeline are not exercised.",
+ "No independent nationwide real-recording accuracy claim is established.",
+]
+
+
+def utc_now():
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def read_json(path):
+ return json.loads(Path(path).read_text(encoding="utf-8"))
+
+
+def write_json(path, value):
+ Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + "\n", encoding="utf-8")
+
+
+def file_record(path):
+ path = Path(path).resolve()
+ with path.open("rb") as stream:
+ checksum = hashlib.file_digest(stream, "sha256").hexdigest()
+ return {"path": str(path), "bytes": path.stat().st_size, "sha256": checksum}
+
+
+def pipeline_source_digest(source_root):
+ """Match the existing pipeline's implementation digest byte for byte."""
+ source_root = Path(source_root)
+ checksum = hashlib.sha256()
+ for source in sorted(source_root.rglob("*.py")):
+ checksum.update(str(source.relative_to(source_root)).encode())
+ checksum.update(source.read_bytes())
+ return checksum.hexdigest()
+
+
+def runtime_record():
+ versions = {}
+ for name in ("numpy", "scipy", "pandas", "soundfile", "pyproj", "rasterio",
+ "matplotlib", "requests", "pyarrow", "pytest", "setuptools", "pip"):
+ try:
+ versions[name] = importlib.metadata.version(name)
+ except importlib.metadata.PackageNotFoundError:
+ versions[name] = None
+ external = {}
+ for name in ("ffmpeg", "ffprobe"):
+ try:
+ completed = subprocess.run([name, "-version"], capture_output=True, text=True, timeout=10)
+ external[name] = {"returncode": completed.returncode,
+ "version": (completed.stdout or completed.stderr).splitlines()[:1]}
+ except (OSError, subprocess.SubprocessError) as exc:
+ external[name] = {"error": str(exc)}
+ return {"python": sys.version, "executable": sys.executable,
+ "implementation": platform.python_implementation(), "platform": platform.platform(),
+ "machine": platform.machine(), "packages": versions, "external_tools": external,
+ "subprocess_thread_settings": THREAD_ENV}
+
+
+def code_snapshot(repo, output):
+ """Use one fixed source snapshot even if another worker edits the checkout."""
+ destination = output / "implementation"
+ destination.mkdir()
+ shutil.copytree(repo / "src", destination / "src", ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
+ shutil.copy2(repo / "pyproject.toml", destination / "pyproject.toml")
+ shutil.copy2(Path(__file__), destination / "ci_checkpoint_replay.py")
+ records = {}
+ combined = hashlib.sha256()
+ for path in sorted(destination.rglob("*")):
+ if not path.is_file():
+ continue
+ name = path.relative_to(destination).as_posix()
+ record = file_record(path)
+ records[name] = record
+ combined.update(name.encode() + b"\0" + record["sha256"].encode() + b"\0")
+ git = {"commit": None, "status": "no_git_metadata"}
+ if (repo / ".git").exists():
+ for field, args in (("commit", ["rev-parse", "HEAD"]), ("status", ["status", "--porcelain"])):
+ try:
+ result = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, text=True, timeout=10)
+ git[field] = result.stdout.strip() if result.returncode == 0 else result.stderr.strip()
+ except (OSError, subprocess.SubprocessError) as exc:
+ git[field] = str(exc)
+ return destination, {"checkout": str(repo), "git": git,
+ "snapshot_sha256": combined.hexdigest(), "files": records,
+ "expected_pipeline_implementation_sha256": pipeline_source_digest(destination / "src")}
+
+
+def sampled_tree_rss(pid):
+ """Linux process-tree RSS sample, not a kernel high-water-mark measurement."""
+ if sys.platform != "linux":
+ return None
+ total, pending, seen = 0, [pid], set()
+ while pending:
+ current = pending.pop()
+ if current in seen:
+ continue
+ seen.add(current)
+ try:
+ total += int(Path(f"/proc/{current}/statm").read_text().split()[1]) * os.sysconf("SC_PAGE_SIZE")
- children = Path(f"/proc/{current}/task/{current}/children").read_text().split()
- pending.extend(int(child) for child in children)
+ except (OSError, ValueError, IndexError):
+ continue
++ # A child belongs to the thread that spawned it. Count process RSS once,
++ # then inspect every task, including nonleader threads used by JobManager.
++ try:
++ tasks = list(Path(f"/proc/{current}/task").iterdir())
++ except OSError:
++ continue
++ for task in tasks:
++ try:
++ pending.extend(int(child) for child in (task / "children").read_text().split())
++ except (OSError, ValueError):
++ continue
+ return total
+
+
+def execute(command, cwd, log_path, env, timeout_s):
+ result = {"command": [str(part) for part in command], "cwd": str(cwd),
+ "log": str(log_path), "started_utc": utc_now(), "timeout_s": timeout_s}
+ began = time.monotonic()
+ peak = None
+ try:
+ with Path(log_path).open("w", encoding="utf-8") as log:
+ process = subprocess.Popen(command, cwd=cwd, env=env, stdout=log,
+ stderr=subprocess.STDOUT, start_new_session=(os.name == "posix"))
+ while process.poll() is None:
+ sample = sampled_tree_rss(process.pid)
+ if sample is not None:
+ peak = max(peak or 0, sample)
+ if time.monotonic() - began > timeout_s:
+ result["timed_out"] = True
+ if os.name == "posix":
+ os.killpg(process.pid, signal.SIGTERM)
+ else:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ if os.name == "posix":
+ os.killpg(process.pid, signal.SIGKILL)
+ else:
+ process.kill()
+ process.wait()
+ break
+ time.sleep(0.2)
+ result["returncode"] = process.returncode
+ except OSError as exc:
+ result.update(returncode=None, error=f"{type(exc).__name__}: {exc}")
+ result.update(elapsed_s=time.monotonic() - began, finished_utc=utc_now(),
+ peak_sampled_process_tree_rss_bytes=peak,
+ memory_measurement="Linux process-tree RSS sampled every 0.2 s; may miss peaks; shared pages may be counted twice")
+ return result
+
+
+def config_inputs(config_path):
+ config_path = Path(config_path).resolve()
+ config = read_json(config_path)
+ paths = [config_path, config_path.parent / config["audio"]]
+ paths.extend(config_path.parent / path for path in config["tracks"])
+ if config.get("type_database"):
+ paths.append(config_path.parent / config["type_database"])
+ terrain = config.get("terrain", {})
+ if not terrain.get("copernicus_cache"):
+ paths.extend(config_path.parent / path for path in terrain.get("rasters", []))
+ if terrain.get("geoid_raster"):
+ paths.append(config_path.parent / terrain["geoid_raster"])
+ if terrain.get("copernicus_cache"):
+ cache = config_path.parent / terrain["copernicus_cache"]
+ paths.append(cache / "tileList.txt")
+ paths.extend(config_path.parent / event["ridge_csv"] for event in config["events"] if event.get("ridge_csv"))
+ return [file_record(path) for path in dict.fromkeys(path.resolve() for path in paths)]
+
+
+def evaluate_best(best, truth, expected_flights=None):
+ """Evaluation-only oracle. Caller must finish every search before calling."""
+ from pyproj import Geod
+
+ for field in ("lat", "lon"):
+ if not isinstance(best.get(field), (int, float)) or not math.isfinite(best[field]):
+ raise ValueError(f"Best candidate lacks a finite {field}")
+ error_m = abs(Geod(ellps="WGS84").inv(truth["lon"], truth["lat"], best["lon"], best["lat"])[2])
+ if not math.isfinite(error_m):
+ raise ValueError("Non-finite location error")
+ result = {"error_m": error_m, "distance_metric": "horizontal WGS84 geodesic",
+ "threshold_m": TARGET_ERROR_M, "meets_threshold": error_m < TARGET_ERROR_M}
+ if expected_flights is not None:
+ result["expected_flight_ids"] = expected_flights
+ result["flight_ids_correct"] = best.get("flight_ids") == expected_flights
+ if "recording_start_time_s" in truth and "recording_start_time_s" in best:
+ result["clock_error_s"] = best["recording_start_time_s"] - truth["recording_start_time_s"]
+ result["passed"] = result["meets_threshold"] and result.get("flight_ids_correct", True)
+ return result
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--output", type=Path, required=True, help="New directory; existing paths are refused")
+ parser.add_argument("--real-config", type=Path, help="Run only this restored source-informed regional config")
+ parser.add_argument("--case-timeout-s", type=float, default=1800, help="Per CLI case timeout (default: 1800)")
+ args = parser.parse_args(argv)
+ if not math.isfinite(args.case_timeout_s) or args.case_timeout_s <= 0:
+ parser.error("--case-timeout-s must be finite and positive")
+ repo = Path(__file__).resolve().parents[1]
+ output = args.output.resolve()
+ if output.exists():
+ parser.error(f"Refusing to overwrite existing output: {output}")
+ if output.is_relative_to(repo / "src"):
+ parser.error("Output must be outside src so the source snapshot cannot copy itself")
+ output.mkdir(parents=True)
+ (output / "logs").mkdir()
+ began = time.monotonic()
+ receipt = {"schema_version": 1, "started_utc": utc_now(),
+ "scope": "configured_methodology_checkpoint_replay", "runtime": runtime_record(),
+ "limitations": list(LIMITATIONS), "automatic_upload_verified": False,
+ "independent_real_accuracy_verified": False, "nationwide_search_verified": False,
+ "evaluation_truth_loaded_after_all_searches": False, "cases": [], "passed": False}
+ try:
+ snapshot, receipt["implementation"] = code_snapshot(repo, output)
+ env = os.environ.copy()
+ env.update(THREAD_ENV)
+ env["PYTHONPATH"] = str(snapshot / "src")
+ env["MPLBACKEND"] = "Agg"
+ if args.real_config:
+ config = args.real_config.resolve()
+ cases = [("reference-regional", config)]
+ truth_path = repo / "evidence/results/reference-local/evaluation.json"
+ receipt["limitations"].extend([
+ "Real replay uses source-informed event settings and regional geographic bounds.",
+ "The published public-platform coordinate is not surveyed ground truth.",
+ "The real recording clock is not independently established.",
+ "Only the supplied regional configuration is evaluated, not the full real benchmark corpus."])
+ else:
+ generator = output / "generated/scripts/make_synthetic_cases.py"
+ generator.parent.mkdir(parents=True)
+ shutil.copy2(repo / "scripts/make_synthetic_cases.py", generator)
+ receipt["generator_source"] = file_record(generator)
+ receipt["original_generator_source"] = file_record(repo / "scripts/make_synthetic_cases.py")
+ receipt["generation"] = execute([sys.executable, str(generator)], output,
+ output / "logs/generator.log", env, min(args.case_timeout_s, 600))
+ fixture = generator.parent.parent / "data/synthetic"
+ cases = [("synthetic-two-events", fixture / "two-events.json"),
+ ("synthetic-known-minute", fixture / "known-time-minute.json")]
+ truth_path = output / "evaluation/truth.json"
+ truth_path.parent.mkdir()
+ # Move bytes without opening/parsing truth. Search configs do not point here.
+ if (fixture / "truth.json").exists():
+ (fixture / "truth.json").replace(truth_path)
+ receipt["requested_cases"] = [name for name, _ in cases]
+ for name, config in cases:
+ case = {"case_id": name, "config": str(config), "passed": False}
+ receipt["cases"].append(case)
+ try:
+ case["inputs"] = config_inputs(config)
+ if read_json(config).get("terrain", {}).get("copernicus_cache"):
+ case["input_provenance_limitations"] = [
+ "Copernicus catalogue and configured geoid are hashed; actual sampled DEM tile identities and hashes are not captured by the legacy pipeline. Cache contents are not asserted to be used inputs."]
+ if any(Path(item["path"]) == truth_path.resolve() for item in case["inputs"]):
+ raise ValueError("Evaluation truth cannot be a CLI data input")
+ case_output = output / "cases" / name
+ case_output.parent.mkdir(exist_ok=True)
+ case["report_path"] = str(case_output / "report.json")
+ case["execution"] = execute(
+ [sys.executable, "-m", "aircraft_geoloc.cli", "run", str(config),
+ "--output", str(case_output)], snapshot,
+ output / "logs" / f"{name}.log", env, args.case_timeout_s)
+ if case["execution"].get("returncode") != 0 or case["execution"].get("timed_out"):
+ case["error"] = "CLI execution failed; inspect the retained log"
+ except Exception as exc:
+ case["error"] = f"{type(exc).__name__}: {exc}"
+ # Intermediate receipts contain execution facts only, never evaluation truth.
+ write_json(output / "acceptance.json", receipt)
+ receipt["all_searches_finished_utc"] = utc_now()
+ # No truth contents have been opened above. Evaluate only after ALL cases ran.
+ raw_truth = read_json(truth_path)
+ receipt["evaluation_truth_loaded_after_all_searches"] = True
+ receipt["evaluation_truth_loaded_utc"] = utc_now()
+ receipt["evaluation_reference"] = file_record(truth_path)
+ truth = ({"lat": raw_truth["reference_coordinate"][0],
+ "lon": raw_truth["reference_coordinate"][1]} if args.real_config else raw_truth)
+ if args.real_config:
+ receipt["reference_qualifications"] = raw_truth
+ for case in receipt["cases"]:
+ if case.get("error"):
+ continue
+ try:
+ report = read_json(case["report_path"])
+ case["report_sha256"] = file_record(case["report_path"])["sha256"]
+ case["best"] = report["best"]
+ case["pipeline_elapsed_s"] = report.get("elapsed_s")
+ case["pipeline_implementation_sha256"] = report.get("implementation_sha256")
+ case["expected_pipeline_implementation_sha256"] = receipt["implementation"]["expected_pipeline_implementation_sha256"]
+ if case["pipeline_implementation_sha256"] != case["expected_pipeline_implementation_sha256"]:
+ raise ValueError("CLI implementation digest does not match the frozen source snapshot")
+ expected = None if args.real_config else truth["flight_ids"][:1 if case["case_id"] == "synthetic-known-minute" else 2]
+ case["evaluation"] = evaluate_best(case["best"], truth, expected)
+ case["passed"] = case["evaluation"]["passed"]
+ except Exception as exc:
+ case["error"] = f"{type(exc).__name__}: {exc}"
+ generation_ok = (args.real_config is not None or
+ (receipt["generation"].get("returncode") == 0 and not receipt["generation"].get("timed_out")))
+ receipt["passed"] = generation_ok and all(case["passed"] for case in receipt["cases"])
+ except Exception as exc:
+ receipt["error"] = f"{type(exc).__name__}: {exc}"
+ finally:
+ receipt.update(finished_utc=utc_now(), elapsed_s=time.monotonic() - began)
+ write_json(output / "acceptance.json", receipt)
+ print(json.dumps({"acceptance": str(output / "acceptance.json"), "passed": receipt["passed"],
+ "scope": receipt["scope"], "cases": [
+ {"case_id": case["case_id"], "passed": case["passed"],
+ "evaluation": case.get("evaluation"), "error": case.get("error")}
+ for case in receipt["cases"]]}, indent=2))
+ return 0 if receipt["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --cc tests/test_ci_checkpoint_replay.py
index 1a88f8f,0000000..50067ec
mode 100644,000000..100644
--- a/tests/test_ci_checkpoint_replay.py
+++ b/tests/test_ci_checkpoint_replay.py
@@@ -1,133 -1,0 +1,219 @@@
+"""Harness failure/oracle checks, not substitutes for actual scientific replays."""
+from contextlib import redirect_stderr, redirect_stdout
+import importlib.util
+import io
+import json
++import os
+from pathlib import Path
++import selectors
++import signal
++import subprocess
++import sys
+import tempfile
++import textwrap
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+
+
+SCRIPT = Path(__file__).resolve().parents[1] / "scripts/ci_checkpoint_replay.py"
+SPEC = importlib.util.spec_from_file_location("ci_checkpoint_replay", SCRIPT)
+REPLAY = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(REPLAY)
+
+
+class CheckpointReplayTests(unittest.TestCase):
++ def test_rss_visits_all_thread_children_and_counts_each_process_once(self):
++ with tempfile.TemporaryDirectory() as temporary:
++ root = Path(temporary)
++ def process(pid, resident_pages, threads):
++ directory = root / str(pid)
++ directory.mkdir()
++ (directory / "statm").write_text(f"100 {resident_pages} 0 0 0 0 0\n")
++ for tid, children in threads.items():
++ task = directory / "task" / str(tid)
++ task.mkdir(parents=True)
++ if children is not None:
++ (task / "children").write_text(children)
++ # A disappearing task/process and a duplicate observed PID must not
++ # hide siblings or count the same process more than once.
++ process(1000, 3, {1000: "2000 9000", 1001: None, 1002: "3000 2000"})
++ process(2000, 5, {2000: "", 2001: "4000"})
++ process(3000, 7, {3000: ""})
++ process(4000, 11, {4000: ""})
++ def proc_path(value):
++ return root / Path(value).relative_to("/proc")
++ with patch.object(REPLAY, "Path", side_effect=proc_path), \
++ patch.object(REPLAY.sys, "platform", "linux"):
++ actual = REPLAY.sampled_tree_rss(1000)
++ self.assertEqual(actual, (3 + 5 + 7 + 11) * os.sysconf("SC_PAGE_SIZE"))
++
++ @unittest.skipUnless(sys.platform == "linux" and Path("/proc/thread-self/children").is_file(),
++ "Requires Linux per-thread /proc children interfaces")
++ def test_rss_includes_child_spawned_by_background_thread(self):
++ child_program = """import time
++memory = bytearray(64 * 1024 * 1024)
++for offset in range(0, len(memory), 4096):
++ memory[offset] = 1
++print('ready', flush=True)
++time.sleep(30)
++"""
++ controller_program = textwrap.dedent(f"""
++ import json, subprocess, sys, threading
++ stop = threading.Event()
++ def worker():
++ child = subprocess.Popen([sys.executable, '-c', {child_program!r}],
++ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
++ try:
++ assert child.stdout.readline().strip() == 'ready'
++ print(json.dumps({{'child_pid': child.pid, 'thread_id': threading.get_native_id()}}), flush=True)
++ stop.wait(20)
++ finally:
++ child.terminate()
++ child.wait(timeout=5)
++ child.stdout.close()
++ thread = threading.Thread(target=worker)
++ thread.start()
++ try:
++ sys.stdin.read(1)
++ finally:
++ stop.set()
++ thread.join()
++ """)
++ controller = subprocess.Popen([sys.executable, "-c", controller_program],
++ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
++ text=True, start_new_session=True)
++ try:
++ with selectors.DefaultSelector() as selector:
++ selector.register(controller.stdout, selectors.EVENT_READ)
++ self.assertTrue(selector.select(timeout=10), "Threaded child did not become ready")
++ identity = json.loads(controller.stdout.readline())
++ parent, child, thread = controller.pid, identity["child_pid"], identity["thread_id"]
++ leader_children = Path(f"/proc/{parent}/task/{parent}/children").read_text().split()
++ worker_children = Path(f"/proc/{parent}/task/{thread}/children").read_text().split()
++ self.assertNotIn(str(child), leader_children)
++ self.assertIn(str(child), worker_children)
++ child_rss = REPLAY.sampled_tree_rss(child)
++ self.assertGreater(child_rss, 48 * 1024 * 1024)
++ self.assertGreaterEqual(REPLAY.sampled_tree_rss(parent), child_rss)
++ finally:
++ try:
++ controller.communicate(input="\n", timeout=5)
++ except subprocess.TimeoutExpired:
++ os.killpg(controller.pid, signal.SIGKILL)
++ controller.communicate(timeout=5)
++
+ def run_orchestration(self, first_failure=None):
+ """Fake child results isolate sequencing and fail-closed receipt behavior."""
+ attempts = []
+ truth_reads = []
+ actual_read = REPLAY.read_json
+
+ def read_json(path):
+ if Path(path).name == "truth.json":
+ self.assertEqual(attempts, ["two-events.json", "known-time-minute.json"])
+ truth_reads.append(str(path))
+ return actual_read(path)
+
+ def execute(command, cwd, log_path, env, timeout_s):
+ Path(log_path).write_text("Harness control fixture; no scientific run.\n")
+ if str(command[1]).endswith("make_synthetic_cases.py"):
+ root = Path(command[1]).parent.parent / "data/synthetic"
+ root.mkdir(parents=True)
+ (root / "recording.wav").write_bytes(b"fixture")
+ (root / "tracks.csv").write_text("fixture")
+ config = {"audio": "recording.wav", "tracks": ["tracks.csv"], "events": []}
+ for name in ("two-events.json", "known-time-minute.json"):
+ (root / name).write_text(json.dumps(config))
+ (root / "truth.json").write_text(json.dumps({
+ "lat": 40, "lon": -100, "flight_ids": ["a", "b"]}))
+ return {"returncode": 0}
+ self.assertEqual(command[1:4], ["-m", "aircraft_geoloc.cli", "run"])
+ name = Path(command[4]).name
+ attempts.append(name)
+ destination = Path(command[-1])
+ destination.mkdir()
+ if not (len(attempts) == 1 and first_failure == "missing_report"):
+ (destination / "report.json").write_text(json.dumps({
+ "best": {"lat": 40, "lon": -100, "flight_ids": ["a", "b"]},
+ "implementation_sha256": ("wrong" if len(attempts) == 1 and first_failure == "wrong_code"
+ else REPLAY.pipeline_source_digest(Path(env["PYTHONPATH"])))}))
+ return {"returncode": 7 if len(attempts) == 1 and first_failure == "exit" else 0}
+
+ with tempfile.TemporaryDirectory() as temporary:
+ output = Path(temporary) / "run"
+ with patch.object(REPLAY, "runtime_record", return_value={}), \
+ patch.object(REPLAY, "execute", side_effect=execute), \
+ patch.object(REPLAY, "read_json", side_effect=read_json), \
+ patch.object(REPLAY, "evaluate_best", return_value={"passed": True}), \
+ redirect_stdout(io.StringIO()):
+ code = REPLAY.main(["--output", str(output)])
+ receipt = actual_read(output / "acceptance.json")
+ self.assertEqual(len(truth_reads), 1)
+ self.assertTrue(receipt["evaluation_truth_loaded_after_all_searches"])
+ self.assertEqual(len(receipt["cases"]), 2)
+ self.assertTrue(receipt["cases"][1]["passed"])
+ self.assertFalse(receipt["automatic_upload_verified"])
+ self.assertFalse(receipt["independent_real_accuracy_verified"])
+ self.assertFalse(receipt["nationwide_search_verified"])
+ return code, receipt
+
+ def test_truth_is_opened_only_after_both_cli_cases(self):
+ code, receipt = self.run_orchestration()
+ self.assertEqual(code, 0)
+ self.assertTrue(receipt["passed"])
+
+ def test_failed_case_is_not_hidden_by_later_success(self):
+ for failure in ("exit", "missing_report", "wrong_code"):
+ with self.subTest(failure=failure):
+ code, receipt = self.run_orchestration(failure)
+ self.assertEqual(code, 1)
+ self.assertFalse(receipt["passed"])
+ self.assertFalse(receipt["cases"][0]["passed"])
+ self.assertIn("error", receipt["cases"][0])
+
+ def test_existing_output_is_preserved(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ marker = Path(temporary) / "keep.txt"
+ marker.write_text("keep")
+ with redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as error:
+ REPLAY.main(["--output", temporary])
+ self.assertEqual(error.exception.code, 2)
+ self.assertEqual(marker.read_text(), "keep")
+
+ def test_oracle_requires_correct_flights_and_strict_distance_bound(self):
+ best = {"lat": 40, "lon": -100, "flight_ids": ["wrong"]}
+ truth = {"lat": 40, "lon": -100}
+ for distance, flights, passed in ((1, ["right"], False), (99.9, ["wrong"], True), (100, ["wrong"], False)):
+ with self.subTest(distance=distance, flights=flights):
+ geod = SimpleNamespace(inv=lambda *args: (0, 0, distance))
+ with patch.dict("sys.modules", {"pyproj": SimpleNamespace(Geod=lambda **kwargs: geod)}):
+ result = REPLAY.evaluate_best(best, truth, flights)
+ self.assertEqual(result["passed"], passed)
+
+ def test_nonfinite_best_candidate_cannot_pass(self):
+ with patch.dict("sys.modules", {"pyproj": SimpleNamespace(Geod=object)}):
+ with self.assertRaisesRegex(ValueError, "finite lat"):
+ REPLAY.evaluate_best({"lat": float("nan"), "lon": -100}, {"lat": 40, "lon": -100})
+
+ def test_cache_inventory_does_not_claim_every_tile_was_used(self):
+ with tempfile.TemporaryDirectory() as temporary:
+ root = Path(temporary)
+ cache = root / "cache"
+ cache.mkdir()
+ for path in (root / "audio.wav", root / "tracks.csv", root / "geoid.tif",
+ cache / "tileList.txt", cache / "unrelated.tif"):
+ path.write_bytes(b"fixture")
+ config = root / "config.json"
+ config.write_text(json.dumps({"audio": "audio.wav", "tracks": ["tracks.csv"],
+ "events": [], "terrain": {"copernicus_cache": "cache", "geoid_raster": "geoid.tif",
+ "rasters": ["inactive-and-absent.tif"]}}))
+ names = {Path(item["path"]).name for item in REPLAY.config_inputs(config)}
+ self.assertIn("tileList.txt", names)
+ self.assertIn("geoid.tif", names)
+ self.assertNotIn("unrelated.tif", names)
+ self.assertNotIn("inactive-and-absent.tif", names)
+
+
+if __name__ == "__main__":
+ unittest.main()