Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Add clean checkpoint replay CI and auditable input provenance
Cinna Davis3bb51abc5c01
diff --git a/.github/workflows/checkpoint-replay.yml b/.github/workflows/checkpoint-replay.ymlnew file mode 100644index 0000000..b4f6b13--- /dev/null+++ b/.github/workflows/checkpoint-replay.yml@@ -0,0 +1,95 @@+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+ 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+ 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/+ if-no-files-found: error+ retention-days: 30diff --git a/docs/CI_CHECKPOINT_REPLAY.md b/docs/CI_CHECKPOINT_REPLAY.mdnew file mode 100644index 0000000..67e6828--- /dev/null+++ b/docs/CI_CHECKPOINT_REPLAY.md@@ -0,0 +1,61 @@+# Checkpoint replay in a clean runner++The `Checkpoint methodology replay` workflow installs the project in a fresh+Ubuntu/Python 3.12 GitHub Actions runner, runs the tests, generates independent+synthetic audio and executes both configured CLI cases. A dependent job restores+the three public regional-input bundles and repeats the real regional case.+Logs and receipts are preserved when a step fails.++This verifies the configured methodology. Automatic event discovery, MP3 upload+acceptance, independently timed real-audio accuracy and national coverage remain+separate acceptance gates.++## Commands++With project dependencies, pytest, ffmpeg and ffprobe installed:++```bash+python -m pytest -q+python scripts/ci_checkpoint_replay.py --output results/new-synthetic-replay+python scripts/restore_ci_checkpoint.py --destination . --receipt results/new-restoration.json+python scripts/ci_checkpoint_replay.py --output results/new-regional-replay --real-config data/source/reproduce-local.json+```++Each replay output directory must be new. Restoration refuses to overwrite any+existing destination file. Use a fresh checkout to restore regional data. The+three archives total 1,517,171,699 compressed bytes; extraction and staging require+additional disk space. Downloads are public and use no credentials.++## Checks and limits++The independent synthetic generator is copied unchanged into a new fixture tree.+Both configured cases run through the actual CLI. Evaluation truth is moved out+of that tree without parsing it and read only after both searches finish. This+is procedural truth separation, not an operating-system access boundary.+Each synthetic case must locate within 100 m and select the expected flights.+Every requested case, including failures, appears in the receipt.++Regional archives and every contained file must match their sizes and SHA256+values in the committed manifest. No source MP4 is restored. After search, the+regional result is compared with the checked-in public-platform reference.+Source-informed windows/bounds and the unverified independent recording clock+remain explicit. Passing this case does not establish blind real-world accuracy.++Receipts record the fixed source snapshot, configuration/input hashes, package+versions, ffmpeg versions, commands, return codes and sampled memory. A report+file alone does not count as a successful CLI run. The pipeline report also hashes+the exact parsed configuration, ridge files, type database and configured+DEM/geoid files. `provenance.truth_separation` is `not_assessed`: hashes cannot+establish how event windows or search bounds were selected. Used Copernicus tile+hashes are explicitly incomplete when the provider does not expose those paths.++## Evidence and execution++Artifacts contain acceptance receipts, per-case reports/plots, logs, source+snapshots and environment records. The generated synthetic WAV is excluded. The+restored reference WAV and source MP4 are never uploaded. GitHub retains the+artifacts for 30 days.++The initial push trigger is restricted to `worker/ci-checkpoint-20261102` to avoid+large downloads on unrelated development pushes. After merge, use GitHub's+**Run workflow** action. Lightweight general CI remains a separate concern.diff --git a/scripts/ci_checkpoint_replay.py b/scripts/ci_checkpoint_replay.pynew file mode 100644index 0000000..ee2964b--- /dev/null+++ b/scripts/ci_checkpoint_replay.py@@ -0,0 +1,334 @@+#!/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 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 --git a/scripts/restore_ci_checkpoint.py b/scripts/restore_ci_checkpoint.pynew file mode 100644index 0000000..02f4c94--- /dev/null+++ b/scripts/restore_ci_checkpoint.py@@ -0,0 +1,122 @@+#!/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}")+ 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")+ 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")+++if __name__ == "__main__":+ main()diff --git a/src/aircraft_geoloc/pipeline.py b/src/aircraft_geoloc/pipeline.pyindex 6b0bab2..962c0f9 100644--- a/src/aircraft_geoloc/pipeline.py+++ b/src/aircraft_geoloc/pipeline.py@@ -1,5 +1,4 @@"""One command from recording + flight data to ranked, plotted locations."""-import hashlibimport jsonimport timefrom pathlib import Path@@ -9,6 +8,7 @@ import pandas as pdfrom .audio import measurefrom .geometry import ecef+from .provenance import RunProvenance,implementation_provenancefrom .search import cpa_table,pair_candidates,rank_candidatesfrom .terrain import Terrain,CopernicusTerrain,corridor_grid,refine_gridfrom .tracks import load_tracks,unix_time@@ -21,12 +21,12 @@ def dump(path,value):def run(config_path,output_dir):began=time.monotonic()code_root=Path(__file__).resolve().parents[1]- code_digest=hashlib.sha256()- for source in sorted(code_root.rglob("*.py")):- code_digest.update(str(source.relative_to(code_root)).encode())- code_digest.update(source.read_bytes())+ implementation=implementation_provenance(code_root)config_path=Path(config_path).resolve()- config=json.loads(config_path.read_text())+ config_bytes=config_path.read_bytes()+ config=json.loads(config_bytes)+ provenance=RunProvenance(config_path,config_bytes)+ provenance.collect_declared_inputs(config)output=Path(output_dir).resolve()output.mkdir(parents=True,exist_ok=True)def local(path):@@ -54,7 +54,6 @@ def run(config_path,output_dir):raise ValueError("Events must be in chronological recording order")tracks=[]imports=[]- source_paths=[audio]origin=unix_time(config["recording_start_utc"]) if config.get("recording_start_utc") is not None else Nonebounds=config.get("grid",{}).get("bounds")track_bounds=None@@ -71,7 +70,6 @@ def run(config_path,output_dir):bounds=track_bounds,time_range=time_range)tracks.extend(imported)imports.append(dict(report,path=str(path)))- source_paths.append(path)if len({t.id for t in tracks})!=len(tracks):raise ValueError("Flight IDs must identify unique imported trajectory segments")if not tracks:@@ -136,17 +134,14 @@ def run(config_path,output_dir):best_pairs.setdefault(tuple(row["flight_ids"]),row)dump(output/"ranked.json",ranked)dump(output/"flight-combinations.json",list(best_pairs.values()))- provenance=[]- for path in source_paths:- with path.open("rb") as f:- digest=hashlib.file_digest(f,"sha256").hexdigest()- provenance.append({"path":str(path.resolve()),"sha256":digest})- report={"config":config,"measured_events":events,"imports":imports,"sources":provenance,- "implementation_sha256":code_digest.hexdigest(),+ provenance.collect_terrain_inputs(ground,terrain)+ report={"config":config,"measured_events":events,"imports":imports,"sources":provenance.sources,+ "implementation_sha256":implementation["sha256"],+ "implementation_sources":implementation["sources"],"provenance":provenance.declaration(),"coarse_filter_counts":counts,"scoring_filter_counts":fine_counts,"ranked_points":len(ranked),"flight_combinations":len(best_pairs),"best":ranked[0],"elapsed_s":time.monotonic()-began,- "scoring_time_is_locked":True,"ground_truth_used_by_search":False}+ "scoring_time_is_locked":True}dump(output/"report.json",report)plot_results(output,ranked,tracks,measurements,c)print("Best:",json.dumps(ranked[0]),flush=True)diff --git a/src/aircraft_geoloc/provenance.py b/src/aircraft_geoloc/provenance.pynew file mode 100644index 0000000..cf37027--- /dev/null+++ b/src/aircraft_geoloc/provenance.py@@ -0,0 +1,125 @@+"""File provenance for the configured research pipeline, using only the stdlib.++Hashes identify supplied inputs. They do not establish that a caller chose event+windows, physical bounds, or a search area independently of a known location.+"""+import hashlib+from pathlib import Path+++def implementation_provenance(code_root):+ """Retain the legacy code digest and list its individual Python sources."""+ root = Path(code_root).resolve()+ digest = hashlib.sha256()+ sources = []+ for path in sorted(root.rglob("*.py")):+ relative = str(path.relative_to(root))+ data = path.read_bytes()+ # Preserve the existing aggregate digest format for downstream readers.+ digest.update(relative.encode())+ digest.update(data)+ sources.append({"path": str(path), "relative_path": relative,+ "sha256": hashlib.sha256(data).hexdigest()})+ return {"sha256": digest.hexdigest(), "sources": sources}+++class RunProvenance:+ """Capture declared inputs before use and late-discovered terrain inputs.++ The configuration digest uses the exact bytes parsed by the caller. Other+ inputs are hashed when registered; no source files are copied or locked.+ """++ def __init__(self, config_path, config_bytes):+ self.config_path = Path(config_path).resolve()+ self._sources = {}+ self._limitations = [+ "Input hashes do not establish that event windows, physical bounds, "+ "or search bounds were chosen independently of ground truth.",+ "Input and code files are hashed at run startup, but are not copied "+ "or locked. Their contents could change during execution. "+ "Copernicus catalogue and exposed used-tile paths are captured "+ "after terrain sampling.",+ ]+ self.config_sha256 = hashlib.sha256(config_bytes).hexdigest()+ self._register(self.config_path, self.config_sha256, "configuration",+ "parsed_configuration")++ def local(self, value):+ path = Path(value)+ return path if path.is_absolute() else self.config_path.parent / path++ def _register(self, path, digest, role, captured_at):+ key = str(Path(path).resolve())+ previous = self._sources.get(key)+ if previous is not None:+ if previous["sha256"] != digest:+ raise ValueError(f"Input changed between provenance captures: {key}")+ if role not in previous["roles"]:+ previous["roles"].append(role)+ previous["roles"].sort()+ return+ self._sources[key] = {"path": key, "sha256": digest, "roles": [role],+ "captured_at": captured_at}++ def add_file(self, path, role, captured_at="before_execution"):+ path = Path(path).resolve()+ with path.open("rb") as stream:+ digest = hashlib.file_digest(stream, "sha256").hexdigest()+ self._register(path, digest, role, captured_at)++ def collect_declared_inputs(self, config):+ self.add_file(self.local(config["audio"]), "audio")+ for path in config["tracks"]:+ self.add_file(self.local(path), "tracks")+ for event in config["events"]:+ if event.get("ridge_csv"):+ self.add_file(self.local(event["ridge_csv"]), "ridge_csv")+ if config.get("type_database"):+ self.add_file(self.local(config["type_database"]), "type_database")+ ground = config["terrain"]+ if ground.get("geoid_raster"):+ self.add_file(self.local(ground["geoid_raster"]), "geoid")+ # The research pipeline ignores explicit rasters when a Copernicus+ # provider is selected. Do not present those inactive paths as inputs.+ if not ground.get("copernicus_cache"):+ for path in ground.get("rasters", []):+ self.add_file(self.local(path), "terrain")++ def collect_terrain_inputs(self, ground, terrain):+ """Record only a provider's explicitly exposed used Copernicus tiles.++ Current CopernicusTerrain does not expose used_tile_paths. That absence+ is recorded rather than substituting every file in its shared cache.+ A future provider may expose an iterable of actual used tile paths.+ """+ if not ground.get("copernicus_cache"):+ return+ catalogue = self.local(ground["copernicus_cache"]) / "tileList.txt"+ if catalogue.is_file():+ self.add_file(catalogue, "terrain_catalogue", "after_terrain_sampling")+ else:+ self._limitations.append("The Copernicus tile catalogue was not available for hashing.")+ used_paths = getattr(terrain, "used_tile_paths", None)+ if used_paths is None:+ self._limitations.append(+ "The terrain provider does not expose the Copernicus tiles "+ "actually used. Their hashes are absent; cache contents were "+ "not treated as a record of used tiles."+ )+ return+ if isinstance(used_paths, (str, bytes, Path)):+ raise TypeError("used_tile_paths must be an iterable of tile paths")+ for path in used_paths:+ self.add_file(path, "terrain_tile", "after_terrain_sampling")++ @property+ def sources(self):+ # Return independent records so a report consumer cannot mutate the ledger.+ return [dict(entry, roles=list(entry["roles"]))+ for _, entry in sorted(self._sources.items())]++ def declaration(self):+ return {"schema_version": 1, "configuration_sha256": self.config_sha256,+ "truth_separation": "not_assessed",+ "limitations": list(self._limitations)}diff --git a/tests/test_checkpoint_restore.py b/tests/test_checkpoint_restore.pynew file mode 100644index 0000000..4db69ed--- /dev/null+++ b/tests/test_checkpoint_restore.py@@ -0,0 +1,62 @@+"""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++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"}+ 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()), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_ci_checkpoint_replay.py b/tests/test_ci_checkpoint_replay.pynew file mode 100644index 0000000..28da2f5--- /dev/null+++ b/tests/test_ci_checkpoint_replay.py@@ -0,0 +1,131 @@+"""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"}}))+ 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)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_provenance.py b/tests/test_provenance.pynew file mode 100644index 0000000..55ae197--- /dev/null+++ b/tests/test_provenance.py@@ -0,0 +1,140 @@+"""Stdlib-only regression checks, also collected by pytest."""+import hashlib+import json+from pathlib import Path+import tempfile+from types import SimpleNamespace+import unittest++from aircraft_geoloc.provenance import RunProvenance, implementation_provenance+++class ProvenanceTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.config_path = self.root / "config.json"+ self.config = {+ "audio": "recording.wav", "tracks": ["tracks.csv", "tracks.csv"],+ "events": [{"ridge_csv": "ridge.csv"}, {}],+ "type_database": "types.csv",+ "terrain": {"rasters": ["ground.tif"], "geoid_raster": "geoid.tif"},+ }+ self.input_bytes = {+ "recording.wav": b"audio bytes", "tracks.csv": b"track bytes",+ "ridge.csv": b"time_s,frequency_hz\n0,100\n", "types.csv": b"types",+ "ground.tif": b"ground raster", "geoid.tif": b"geoid raster",+ }+ for name, data in self.input_bytes.items():+ (self.root / name).write_bytes(data)++ def recorder(self):+ raw = (json.dumps(self.config, indent=3) + "\n\n").encode()+ self.config_path.write_bytes(raw)+ return RunProvenance(self.config_path, raw), raw++ def test_all_declared_input_kinds_are_recorded_once_with_exact_config_bytes(self):+ recorder, raw = self.recorder()+ recorder.collect_declared_inputs(self.config)+ entries = {Path(row["path"]).name: row for row in recorder.sources}+ expected = dict(self.input_bytes, **{"config.json": raw})+ self.assertEqual(set(entries), set(expected))+ for name, data in expected.items():+ self.assertEqual(entries[name]["sha256"], hashlib.sha256(data).hexdigest())+ self.assertEqual(entries["ridge.csv"]["roles"], ["ridge_csv"])+ self.assertEqual(entries["types.csv"]["roles"], ["type_database"])+ self.assertEqual(entries["ground.tif"]["roles"], ["terrain"])+ self.assertEqual(entries["geoid.tif"]["roles"], ["geoid"])+ self.assertEqual(recorder.declaration()["configuration_sha256"], hashlib.sha256(raw).hexdigest())+ json.dumps({"sources": recorder.sources, "provenance": recorder.declaration()}, allow_nan=False)++ def test_configuration_digest_is_not_replaced_by_a_later_file_read(self):+ recorder, raw = self.recorder()+ self.config_path.write_text('{"different": true}\n')+ recorder.collect_declared_inputs(self.config)+ config_entry = next(row for row in recorder.sources if "configuration" in row["roles"])+ self.assertEqual(config_entry["sha256"], hashlib.sha256(raw).hexdigest())+ self.assertEqual(config_entry["captured_at"], "parsed_configuration")++ def test_resolved_duplicates_accumulate_roles_without_duplicate_entries(self):+ recorder, _ = self.recorder()+ (self.root / "subdir").mkdir()+ recorder.add_file(self.root / "tracks.csv", "tracks")+ recorder.add_file(self.root / "subdir/../tracks.csv", "another_role")+ entries = [row for row in recorder.sources if Path(row["path"]).name == "tracks.csv"]+ self.assertEqual(len(entries), 1)+ self.assertEqual(entries[0]["roles"], ["another_role", "tracks"])+ entries[0]["roles"].append("external mutation")+ current = next(row for row in recorder.sources if Path(row["path"]).name == "tracks.csv")+ self.assertNotIn("external mutation", current["roles"])++ def test_changed_input_is_rejected_if_registered_again(self):+ recorder, _ = self.recorder()+ path = self.root / "tracks.csv"+ recorder.add_file(path, "tracks")+ path.write_bytes(b"changed track bytes")+ with self.assertRaisesRegex(ValueError, "Input changed"):+ recorder.add_file(path, "tracks")++ def test_missing_declared_file_is_not_silently_omitted(self):+ recorder, _ = self.recorder()+ (self.root / "ridge.csv").unlink()+ with self.assertRaises(FileNotFoundError):+ recorder.collect_declared_inputs(self.config)++ def test_missing_tile_usage_is_explicit_and_unused_cache_files_are_not_hashed(self):+ recorder, _ = self.recorder()+ cache = self.root / "tiles"+ cache.mkdir()+ (cache / "tileList.txt").write_text("used\nunused\n")+ (cache / "unused.tif").write_bytes(b"unrelated cached raster")+ recorder.collect_terrain_inputs({"copernicus_cache": "tiles"}, SimpleNamespace(cache=cache))+ names = {Path(row["path"]).name for row in recorder.sources}+ self.assertIn("tileList.txt", names)+ self.assertNotIn("unused.tif", names)+ self.assertTrue(any("tiles actually used" in text for text in recorder.declaration()["limitations"]))++ def test_exposed_used_tiles_are_hashed_without_inactive_rasters_or_cache_sweep(self):+ self.config["terrain"] = {"copernicus_cache": "tiles", "geoid_raster": "geoid.tif",+ "rasters": ["inactive-and-missing.tif"]}+ recorder, _ = self.recorder()+ cache = self.root / "tiles"+ cache.mkdir()+ (cache / "tileList.txt").write_text("used\nunused\n")+ used, unused = cache / "used.tif", cache / "unused.tif"+ used.write_bytes(b"used raster")+ unused.write_bytes(b"unused raster")+ recorder.collect_declared_inputs(self.config)+ recorder.collect_terrain_inputs(self.config["terrain"], SimpleNamespace(used_tile_paths=[used]))+ entries = {Path(row["path"]).name: row for row in recorder.sources}+ self.assertNotIn("unused.tif", entries)+ self.assertNotIn("inactive-and-missing.tif", entries)+ self.assertEqual(entries["used.tif"]["sha256"], hashlib.sha256(b"used raster").hexdigest())+ self.assertEqual(entries["used.tif"]["captured_at"], "after_terrain_sampling")+ self.assertEqual(entries["used.tif"]["roles"], ["terrain_tile"])++ def test_hashes_do_not_assert_truth_separation(self):+ recorder, _ = self.recorder()+ declaration = recorder.declaration()+ self.assertEqual(declaration["truth_separation"], "not_assessed")+ self.assertNotIn("ground_truth_used_by_search", declaration)+ self.assertTrue(any("ground truth" in text for text in declaration["limitations"]))++ def test_code_manifest_preserves_legacy_digest_and_detects_code_changes(self):+ root = self.root / "src"+ (root / "pkg").mkdir(parents=True)+ (root / "a.py").write_bytes(b"a = 1\n")+ (root / "pkg/b.py").write_bytes(b"b = 2\n")+ (root / "ignored.txt").write_bytes(b"not Python source")+ result = implementation_provenance(root)+ expected = hashlib.sha256(b"a.py" + b"a = 1\n" + b"pkg/b.py" + b"b = 2\n").hexdigest()+ self.assertEqual(result["sha256"], expected)+ self.assertEqual([row["relative_path"] for row in result["sources"]], ["a.py", "pkg/b.py"])+ self.assertEqual(result["sources"][1]["sha256"], hashlib.sha256(b"b = 2\n").hexdigest())+ (root / "pkg/b.py").write_bytes(b"b = 3\n")+ self.assertNotEqual(implementation_provenance(root)["sha256"], expected)+++if __name__ == "__main__":+ unittest.main()