Skip to content

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

Integrate current main and retain successful checkpoint verification

Cinna Daviscddba5978c4e
diff --cc .github/workflows/checkpoint-replay.yml
index b4f6b13,0000000..16ea769
mode 100644,000000..100644
--- a/.github/workflows/checkpoint-replay.yml
+++ b/.github/workflows/checkpoint-replay.yml
@@@ -1,95 -1,0 +1,97 @@@
+name: Checkpoint methodology replay
+
+on:
+ push:
+ branches: [worker/ci-checkpoint-20261102]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: checkpoint-replay-${{ github.ref }}
+ cancel-in-progress: false
+
+env:
+ MPLBACKEND: Agg
+ PYTHONUNBUFFERED: "1"
+ OPENBLAS_NUM_THREADS: "1"
+ OMP_NUM_THREADS: "1"
+
+jobs:
+ synthetic:
+ name: Clean install, tests, and synthetic replay
+ runs-on: ubuntu-24.04
- timeout-minutes: 30
++ timeout-minutes: 40
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
+ with:
+ python-version: "3.12"
+ - name: Install runtime
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y ffmpeg
+ python -m pip install -e . pytest
+ python -m pip check
+ - name: Record clean checkout and dependency versions
+ run: |
+ mkdir -p results/ci-environment
+ git rev-parse HEAD > results/ci-environment/commit.txt
+ git status --porcelain > results/ci-environment/status-before.txt
+ python -m pip freeze --all > results/ci-environment/requirements-resolved.txt
+ ffmpeg -version > results/ci-environment/ffmpeg-version.txt
+ - name: Run repository tests
+ run: python -m pytest -q --junitxml=results/ci-environment/pytest.xml
+ - name: Replay configured synthetic methodology
+ run: python scripts/ci_checkpoint_replay.py --output results/ci-synthetic --case-timeout-s 600
+ - name: Upload evidence, including failed runs
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: synthetic-methodology-${{ github.sha }}
+ path: |
+ results/ci-environment/
+ results/ci-synthetic/
+ !results/ci-synthetic/generated/data/synthetic/*.wav
++ !results/ci-synthetic/**/__pycache__/**
+ if-no-files-found: error
+ retention-days: 30
+
+ regional:
+ name: Checksummed regional real-audio replay
+ needs: synthetic
+ runs-on: ubuntu-24.04
+ timeout-minutes: 40
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
+ with:
+ python-version: "3.12"
+ - name: Install runtime
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y ffmpeg
+ python -m pip install -e . pytest
+ python -m pip check
+ - name: Restore and verify public checkpoint assets
+ run: python scripts/restore_ci_checkpoint.py --destination . --receipt results/ci-restore.json
+ - name: Replay source-informed regional reference
+ run: python scripts/ci_checkpoint_replay.py --output results/ci-regional --real-config data/source/reproduce-local.json --case-timeout-s 900
+ - name: Upload regional evidence, including failures
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: regional-methodology-${{ github.sha }}
+ path: |
+ results/ci-restore.json
+ results/ci-regional/
++ !results/ci-regional/**/__pycache__/**
+ if-no-files-found: error
+ retention-days: 30
diff --cc docs/CI_VERIFICATION_2026-11-02.md
index 0000000,0000000..5f88e98
new file mode 100644
--- /dev/null
+++ b/docs/CI_VERIFICATION_2026-11-02.md
@@@ -1,0 -1,0 +1,109 @@@
++# CI verification, 2026-11-02
++
++This note records the configured-methodology replay at commit
++[`3bb51abc5c01d2cf27ada89740a800c9d79a28e3`](https://github.com/1337isnot1337/DOPPLERGEIST/commit/3bb51abc5c01d2cf27ada89740a800c9d79a28e3),
++from [Actions run 41553347143](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41553347143).
++The note date uses America/Chicago; the job logs use 2026-11-03 UTC.
++
++## Completed synthetic job
++
++[Job 125646110867](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41553347143/job/125646110867)
++completed successfully. Its logs show a full-history Git checkout (`fetch-depth: 0`),
++sparse checkout disabled, and the exact commit above. Installation used
++`python -m pip install -e . pytest`; `python -m pip check` reported no broken
++requirements. The test command
++`python -m pytest -q --junitxml=results/ci-environment/pytest.xml` reported
++**53 tests and 6 subtests passed in 2.23 s**.
++
++The actual replay command was:
++
++```bash
++python scripts/ci_checkpoint_replay.py --output results/ci-synthetic --case-timeout-s 600
++```
++
++Both configured cases completed through the real CLI and passed the 100 m
++horizontal WGS84 geodesic threshold. These are this commit's measured results;
++historical checkpoint results remain unchanged.
++
++| Case | Error, m | Flight IDs verified by evaluator | Clock error, s |
++| --- | ---: | --- | ---: |
++| Two events, unknown recording start | 15.395598179748822 | `true-A`, `true-B` | +0.06380653381347656 |
++| Known-time minute | 40.87444831462204 | `true-A` | +0.5 |
++
++Clock error is estimated recording start minus generator truth. The known-time
++configuration permits a ±0.5 s sweep and selected the positive endpoint; its
++clock was not recovered with zero error. The result table is printed in the
++completed job log.
++
++### Installed environment
++
++The setup/install logs record Ubuntu 24.04.5, CPython 3.12.15, pytest 9.2.0,
++and Ubuntu ffmpeg package `7:6.1.1-3ubuntu5`. Direct Python dependencies were:
++
++| Package | Version |
++| --- | --- |
++| NumPy | 2.5.4 |
++| SciPy | 1.18.1 |
++| pandas | 3.1.0 |
++| soundfile | 0.14.0 |
++| pyproj | 3.8.0 |
++| rasterio | 1.5.2 |
++| matplotlib | 3.11.2 |
++| requests | 2.34.2 |
++| pyarrow | 26.0.0 |
++
++The job saved `ci-environment/requirements-resolved.txt`, its checkout commit/status,
++ffmpeg version, JUnit report, and `ci-synthetic/acceptance.json` in
++[artifact 13191599846](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41553347143/artifacts/13191599846).
++The upload log records 77 files and a 21,674,727-byte ZIP. Both the upload log
++and artifact API report this ZIP SHA-256:
++
++```text
++38020418cefee4cd37b84b41717376b53077283d15381e912529af342dd1823f
++```
++
++This checksum was read from GitHub's records; the ZIP was not independently
++downloaded and rehashed for this note. GitHub reports expiry on 2026-12-03 UTC.
++
++## Truth separation and scope
++
++The [runner at the tested commit](https://github.com/1337isnot1337/DOPPLERGEIST/blob/3bb51abc5c01d2cf27ada89740a800c9d79a28e3/scripts/ci_checkpoint_replay.py)
++copies the synthetic generator unchanged, moves its truth file outside the search
++input directory, runs both CLI searches, and then reads truth for evaluation.
++It checks that the declared CLI input paths do not include the truth file and
++checks each report's implementation digest against its frozen source snapshot.
++This is procedural separation: the search process's account can still access
++the evaluation directory.
++
++The replay uses configured event windows and frequency bands. It does not exercise
++automatic event discovery, MP3 upload, the product API/UI, or national search.
++These synthetic results establish no independent real-recording accuracy claim.
++
++## Completed regional job
++
++[Regional job 125647085176](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41553347143/job/125647085176)
++completed successfully at the same commit. The restore logs confirm verification
++and restoration of 68 files against the committed manifest: 54 source files,
++8 ADS-B-derived files, and 6 terrain files. The commands were:
++
++```bash
++python scripts/restore_ci_checkpoint.py --destination . --receipt results/ci-restore.json
++python scripts/ci_checkpoint_replay.py --output results/ci-regional --real-config data/source/reproduce-local.json --case-timeout-s 900
++```
++
++The `reference-regional` result reports **43.85847078233993 m** horizontal WGS84
++geodesic distance from the public-platform reference and `passed: true` against
++the configured 100 m threshold. The restore receipt and replay outputs are in
++[artifact 13193708320](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41553347143/artifacts/13193708320),
++a 15,970,633-byte ZIP. The upload log and artifact API report SHA-256:
++
++```text
++5c6e5cd64c9ce8446b559607d07ad1a2453988c370f805bb07451cfaf4a3b1ac
++```
++
++This ZIP also was not independently downloaded and rehashed for this note.
++The result remains source-informed: event settings and geographic bounds were
++supplied, the mapped public-platform coordinate is not surveyed microphone truth,
++and the recording clock has not been independently established. Independent real
++and nationwide acceptance remain unverified. See [PROGRESS.md](PROGRESS.md) and
++[the final acceptance issue](https://github.com/1337isnot1337/DOPPLERGEIST/issues/13).
diff --cc scripts/ci_checkpoint_replay.py
index ee2964b,0000000..8a4270c
mode 100644,000000..100644
--- a/scripts/ci_checkpoint_replay.py
+++ b/scripts/ci_checkpoint_replay.py
@@@ -1,334 -1,0 +1,335 @@@
+#!/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
+ 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", {})
- paths.extend(config_path.parent / path for path in terrain.get("rasters", []))
++ 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 scripts/restore_ci_checkpoint.py
index 02f4c94,0000000..d07404f
mode 100644,000000..100644
--- a/scripts/restore_ci_checkpoint.py
+++ b/scripts/restore_ci_checkpoint.py
@@@ -1,122 -1,0 +1,130 @@@
+#!/usr/bin/env python3
+"""Restore public regional-replay bundles against the committed manifest."""
+from __future__ import annotations
+import argparse
+import hashlib
+import json
+import re
+import shutil
+import tarfile
+import tempfile
+import time
+import urllib.request
+from pathlib import Path, PurePosixPath
+
+ROOT = Path(__file__).resolve().parents[1]
+ASSETS = ("data-source.tar.gz", "data-adsb-derived.tar.gz", "data-terrain.tar.gz")
+TAG = "checkpoint-2026-11-02"
+
+
+def digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def validate_file(path: Path, record: dict) -> None:
+ if path.stat().st_size != record["bytes"] or digest(path) != record["sha256"]:
+ raise ValueError(f"Checksum or size mismatch: {path}")
+
+
+def restore_archive(archive: Path, asset: dict, destination: Path) -> int:
+ """Validate every archive member before writing new destination files."""
+ validate_file(archive, asset)
+ destination = destination.resolve()
+ expected = {item["path"]: item for item in asset["files"]}
+ if len(expected) != len(asset["files"]):
+ raise ValueError("Duplicate paths in manifest")
+ with tempfile.TemporaryDirectory(prefix=".checkpoint-staging-", dir=destination) as tmp:
+ staging = Path(tmp)
+ seen = set()
+ with tarfile.open(archive, "r:gz") as bundle:
+ for member in bundle:
+ relative = PurePosixPath(member.name)
+ if relative.is_absolute() or ".." in relative.parts:
+ raise ValueError(f"Invalid archive path: {member.name}")
+ if member.isdir():
+ continue
+ if not member.isfile() or member.name not in expected or member.name in seen:
+ raise ValueError(f"Unexpected archive member: {member.name}")
+ if relative.suffix.lower() == ".mp4":
+ raise ValueError("Video files are outside the replay bundle contract")
+ target = destination.joinpath(*relative.parts)
+ if target.exists() or target.is_symlink():
+ raise FileExistsError(f"Refusing to overwrite {target}")
+ if not target.resolve().is_relative_to(destination):
+ raise ValueError(f"Target leaves destination: {target}")
++ for parent in target.parents:
++ if parent == destination:
++ break
++ if (parent.exists() or parent.is_symlink()) and not parent.is_dir():
++ raise FileExistsError(f"Destination parent is not a directory: {parent}")
+ record = expected[member.name]
+ if member.size != record["bytes"]:
+ raise ValueError(f"Member size mismatch: {member.name}")
+ output = staging.joinpath(*relative.parts)
+ output.parent.mkdir(parents=True, exist_ok=True)
+ with bundle.extractfile(member) as source, output.open("xb") as sink:
+ shutil.copyfileobj(source, sink, length=1024 * 1024)
+ validate_file(output, record)
+ seen.add(member.name)
+ if seen != set(expected):
+ raise ValueError(f"Missing manifest files: {sorted(set(expected) - seen)}")
+ for name in sorted(seen):
+ target = destination / name
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with (staging / name).open("rb") as source, target.open("xb") as sink:
+ shutil.copyfileobj(source, sink, length=1024 * 1024)
+ return len(seen)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--destination", type=Path, default=ROOT)
+ parser.add_argument("--repository", default="1337isnot1337/DOPPLERGEIST")
+ parser.add_argument("--manifest", type=Path, default=ROOT / "evidence/artifact-manifest.json")
+ parser.add_argument("--receipt", type=Path, default=ROOT / "results/ci-restore.json")
+ args = parser.parse_args()
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", args.repository):
+ parser.error("repository must be owner/name")
++ if args.receipt.exists() or args.receipt.is_symlink():
++ raise FileExistsError(f"Refusing to overwrite receipt {args.receipt}")
+ args.destination.mkdir(parents=True, exist_ok=True)
+ cache = args.destination / ".artifacts-ci"
+ cache.mkdir(exist_ok=True)
+ manifest = json.loads(args.manifest.read_text())
+ indexed = {asset["name"]: asset for asset in manifest["assets"]}
+ receipt = {"release_tag": TAG, "repository": args.repository,
+ "manifest_sha256": digest(args.manifest), "assets": [],
+ "scope": "source-informed regional replay; independent clock unverified"}
+ started = time.perf_counter()
+ try:
+ for name in ASSETS:
+ record = indexed[name]
+ archive = cache / name
+ if not archive.exists():
+ url = f"https://github.com/{args.repository}/releases/download/{TAG}/{name}"
+ request = urllib.request.Request(url, headers={"User-Agent": "DOPPLERGEIST-checkpoint-verifier"})
+ partial = archive.with_suffix(archive.suffix + ".part")
+ print(f"Downloading {name} ({record['bytes']} bytes)", flush=True)
+ with urllib.request.urlopen(request, timeout=60) as response, partial.open("wb") as sink:
+ shutil.copyfileobj(response, sink, length=1024 * 1024)
+ validate_file(partial, record)
+ partial.rename(archive)
+ count = restore_archive(archive, record, args.destination)
+ receipt["assets"].append({"name": name, "sha256": record["sha256"],
+ "bytes": record["bytes"], "verified_files": count})
+ print(f"Verified and restored {name}: {count} files", flush=True)
+ receipt["status"] = "passed"
+ except Exception as exc:
+ receipt["status"] = "failed"
+ receipt["error"] = f"{type(exc).__name__}: {exc}"
+ raise
+ finally:
+ receipt["elapsed_s"] = time.perf_counter() - started
+ args.receipt.parent.mkdir(parents=True, exist_ok=True)
- args.receipt.write_text(json.dumps(receipt, indent=2) + "\n")
++ with args.receipt.open("x", encoding="utf-8") as output:
++ output.write(json.dumps(receipt, indent=2) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --cc tests/test_checkpoint_restore.py
index 4db69ed,0000000..85b22c9
mode 100644,000000..100644
--- a/tests/test_checkpoint_restore.py
+++ b/tests/test_checkpoint_restore.py
@@@ -1,62 -1,0 +1,88 @@@
+"""Offline checks of release restoration; no public download is required."""
+import hashlib
+import importlib.util
+import io
+from pathlib import Path
+import tarfile
+import tempfile
+import unittest
++from unittest.mock import patch
+
+SCRIPT = Path(__file__).resolve().parents[1] / "scripts/restore_ci_checkpoint.py"
+SPEC = importlib.util.spec_from_file_location("restore_ci_checkpoint", SCRIPT)
+RESTORE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(RESTORE)
+
+
+class CheckpointRestoreTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.destination = self.root / "checkout"
+ self.destination.mkdir()
+ self.archive = self.root / "fixture.tar.gz"
+ self.files = {"data/source/input.txt": b"reference fixture\n",
- "data/source/settings.json": b"{}\n"}
++ "data/terrain/settings.json": b"{}\n"}
+ with tarfile.open(self.archive, "w:gz") as bundle:
+ for name, content in self.files.items():
+ member = tarfile.TarInfo(name)
+ member.size = len(content)
+ bundle.addfile(member, io.BytesIO(content))
+ self.asset = {"bytes": self.archive.stat().st_size,
+ "sha256": RESTORE.digest(self.archive),
+ "files": [{"path": name, "bytes": len(content),
+ "sha256": hashlib.sha256(content).hexdigest()}
+ for name, content in self.files.items()]}
+
+ def test_verified_contents_restored_and_second_run_preserves_files(self):
+ self.assertEqual(RESTORE.restore_archive(self.archive, self.asset, self.destination), 2)
+ for name, content in self.files.items():
+ self.assertEqual((self.destination / name).read_bytes(), content)
+ target = self.destination / "data/source/input.txt"
+ target.write_bytes(b"independent evidence")
+ with self.assertRaises(FileExistsError):
+ RESTORE.restore_archive(self.archive, self.asset, self.destination)
+ self.assertEqual(target.read_bytes(), b"independent evidence")
+
+ def test_member_checksum_failure_writes_no_destination_files(self):
+ self.asset["files"][-1]["sha256"] = "0" * 64
+ with self.assertRaisesRegex(ValueError, "Checksum or size mismatch"):
+ RESTORE.restore_archive(self.archive, self.asset, self.destination)
+ self.assertEqual(list(self.destination.iterdir()), [])
+
+ def test_manifest_missing_member_is_rejected_before_writes(self):
+ self.asset["files"].append({"path": "data/source/missing.txt", "bytes": 0,
+ "sha256": hashlib.sha256(b"").hexdigest()})
+ with self.assertRaisesRegex(ValueError, "Missing manifest files"):
+ RESTORE.restore_archive(self.archive, self.asset, self.destination)
+ self.assertEqual(list(self.destination.iterdir()), [])
+
++ def test_existing_parent_file_leaves_no_partial_restoration(self):
++ blocker = self.destination / "data/terrain"
++ blocker.parent.mkdir()
++ blocker.write_bytes(b"independent evidence")
++ with self.assertRaises(FileExistsError):
++ RESTORE.restore_archive(self.archive, self.asset, self.destination)
++ self.assertFalse((self.destination / "data/source").exists())
++ self.assertEqual(blocker.read_bytes(), b"independent evidence")
++
++ def test_existing_receipt_is_rejected_before_download_or_restoration(self):
++ receipt = self.root / "prior-receipt.json"
++ receipt.write_bytes(b'{"status": "prior evidence"}\n')
++ argv = [str(SCRIPT), "--destination", str(self.destination),
++ "--manifest", str(self.root / "unused-manifest.json"),
++ "--receipt", str(receipt)]
++ with (patch("sys.argv", argv),
++ patch.object(RESTORE.urllib.request, "urlopen") as download,
++ patch.object(RESTORE, "restore_archive") as restore):
++ with self.assertRaisesRegex(FileExistsError, "receipt"):
++ RESTORE.main()
++ download.assert_not_called()
++ restore.assert_not_called()
++ self.assertEqual(receipt.read_bytes(), b'{"status": "prior evidence"}\n')
++ self.assertEqual(list(self.destination.iterdir()), [])
++
+
+if __name__ == "__main__":
+ unittest.main()
diff --cc tests/test_ci_checkpoint_replay.py
index 28da2f5,0000000..1a88f8f
mode 100644,000000..100644
--- a/tests/test_ci_checkpoint_replay.py
+++ b/tests/test_ci_checkpoint_replay.py
@@@ -1,131 -1,0 +1,133 @@@
+"""Harness failure/oracle checks, not substitutes for actual scientific replays."""
+from contextlib import redirect_stderr, redirect_stdout
+import importlib.util
+import io
+import json
+from pathlib import Path
+import tempfile
+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 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"}}))
++ "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()