Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Fix wheel provenance scope and use authenticated shared checkpoint restoration (#12, #13)
Cinna Davis70e9bf060a01
diff --cc .github/workflows/checkpoint-replay.ymlindex 16ea769,0000000..f156049mode 100644,000000..100644--- a/.github/workflows/checkpoint-replay.yml+++ b/.github/workflows/checkpoint-replay.yml@@@ -1,97 -1,0 +1,133 @@@+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: 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: Verify provenance from an installed wheel++ run: |++ checkpoint_wheel_dir="$RUNNER_TEMP/checkpoint-wheel"++ python -m pip wheel --no-deps --wheel-dir "$checkpoint_wheel_dir/dist" .++ python -m venv "$checkpoint_wheel_dir/venv"++ "$checkpoint_wheel_dir/venv/bin/python" -m pip install --no-deps "$checkpoint_wheel_dir"/dist/*.whl++ "$checkpoint_wheel_dir/venv/bin/python" -I - results/ci-environment/wheel-provenance.json <<'PY'++ import json++ from pathlib import Path++ import sys++ import aircraft_geoloc++ from aircraft_geoloc.provenance import implementation_provenance++ package = Path(aircraft_geoloc.__file__).resolve().parent++ assert "site-packages" in package.parts, package++ expected = implementation_provenance(Path("src"))++ observed = implementation_provenance(package.parent)++ assert observed["sha256"] == expected["sha256"]++ probe = package.parent / "unrelated_checkpoint_probe.py"++ try:++ probe.write_text("unrelated = True\n")++ assert implementation_provenance(package.parent) == observed++ finally:++ probe.unlink(missing_ok=True)++ receipt = {"passed": True, "package_path": str(package),++ "installed_wheel_matches_checkout": True,++ "unrelated_installed_file_excluded": True, "implementation": observed}++ Path(sys.argv[1]).write_text(json.dumps(receipt, indent=2) + "\n")++ print(json.dumps({"wheel_provenance_passed": True, "package_path": str(package),++ "source_files": len(observed["sources"])}))++ PY+ - 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++ - name: Check authenticated release downloader++ run: |++ sudo apt-get install -y gh++ gh --version++ - name: Restore and verify checkpoint assets with read-only authentication++ env:++ GH_TOKEN: ${{ github.token }}+ 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: 30diff --cc docs/CI_CHECKPOINT_REPLAY.mdindex 67e6828,0000000..a8da162mode 100644,000000..100644--- a/docs/CI_CHECKPOINT_REPLAY.md+++ b/docs/CI_CHECKPOINT_REPLAY.md@@@ -1,61 -1,0 +1,71 @@@+# 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.++the three regional-input release 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:++With project dependencies, pytest, ffmpeg, ffprobe and GitHub CLI 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.++additional disk space. The wrapper uses the shared `scripts/restore_artifacts.py`++downloader and extraction checks. GitHub CLI must have read access to the release++through its existing authentication or `GH_TOKEN`. The workflow supplies its++read-only GitHub token only to the restoration step. Receipts never record the++credential; they record the shared restorer's source hash.++## 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++values in the committed manifest. Shared validation runs in a temporary staging++directory before the wrapper publishes new files. 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.+++Implementation hashes cover only the `aircraft_geoloc` package's Python files.++The workflow also builds and installs a wheel in a separate virtual environment.++An isolated Python process checks that its package digest matches the checkout++and that adding an unrelated installed module cannot change the digest.+++## 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 --cc scripts/restore_ci_checkpoint.pyindex d07404f,0000000..89901b4mode 100644,000000..100644--- a/scripts/restore_ci_checkpoint.py+++ b/scripts/restore_ci_checkpoint.py@@@ -1,130 -1,0 +1,107 @@@+#!/usr/bin/env python3- """Restore public regional-replay bundles against the committed manifest."""++"""Restore regional-replay bundles through the shared release restorer."""+from __future__ import annotations+import argparse+import hashlib++import importlib.util+import json++import os+import re- import shutil- import tarfile+import tempfile+import time- import urllib.request- from pathlib import Path, PurePosixPath++from pathlib import Path++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"++SHARED_PATH = Path(__file__).with_name("restore_artifacts.py")++_SPEC = importlib.util.spec_from_file_location("checkpoint_shared_restorer", SHARED_PATH)++SHARED = importlib.util.module_from_spec(_SPEC)++_SPEC.loader.exec_module(SHARED)++TAG = SHARED.TAG+++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)++ """Use shared validation in staging, then publish only new destination files."""+ 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++ for name in expected:++ target = SHARED.destination(destination, name)++ if target.suffix.lower() == ".mp4":++ raise ValueError("Video files are outside the replay bundle contract")++ if target.exists() or target.is_symlink():++ raise FileExistsError(f"Refusing to overwrite {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}")++ with tempfile.TemporaryDirectory(prefix=".checkpoint-staging-", dir=destination) as temporary:++ staging = Path(temporary)++ shared_asset = dict(asset, name=asset.get("name", archive.name))++ restored = SHARED.restore_asset(archive, shared_asset, staging)++ # Every archive member has passed the shared hash/size/path checks.++ # Same-filesystem hard links create each destination atomically without++ # replacing an existing file, including one created after preflight.++ for name in sorted(expected):++ target = SHARED.destination(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)++ os.link(staging / name, target)++ return restored["files"]+++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("--repository", default=SHARED.REPOSITORY)+ 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"]}++ # The shared downloader invokes gh without a shell. gh receives its existing++ # authentication configuration or GH_TOKEN; no credential is recorded here.++ SHARED.REPOSITORY = args.repository+ receipt = {"release_tag": TAG, "repository": args.repository,+ "manifest_sha256": digest(args.manifest), "assets": [],++ "restoration_implementation": {"path": SHARED_PATH.name,++ "sha256": digest(SHARED_PATH), "download": "gh release download",++ "credentials_recorded": False},+ "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)++ print(f"Verifying/downloading {name} ({record['bytes']} bytes)", flush=True)++ archive = SHARED.download_asset(record, cache)+ 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)+ with args.receipt.open("x", encoding="utf-8") as output:+ output.write(json.dumps(receipt, indent=2) + "\n")+++if __name__ == "__main__":+ main()diff --cc src/aircraft_geoloc/provenance.pyindex cf37027,0000000..187ec2emode 100644,000000..100644--- a/src/aircraft_geoloc/provenance.py+++ b/src/aircraft_geoloc/provenance.py@@@ -1,125 -1,0 +1,132 @@@+"""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."""++ """Hash this package, retaining legacy paths relative to its install parent.++++ The parent can be a checkout's src directory or an installed site-packages++ directory. Unrelated installed libraries are not implementation sources.++ """+ root = Path(code_root).resolve()++ package_root = root / "aircraft_geoloc"++ if not package_root.is_dir():++ raise FileNotFoundError(f"Implementation package is absent: {package_root}")+ digest = hashlib.sha256()+ sources = []- for path in sorted(root.rglob("*.py")):++ for path in sorted(package_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 --cc tests/test_checkpoint_restore.pyindex 85b22c9,0000000..fd942famode 100644,000000..100644--- a/tests/test_checkpoint_restore.py+++ b/tests/test_checkpoint_restore.py@@@ -1,88 -1,0 +1,109 @@@+"""Offline checks of release restoration; no public download is required."""+import hashlib+import importlib.util+import io++import json+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/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,++ self.asset = {"name": self.archive.name, "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"):++ with self.assertRaisesRegex(ValueError, "Checksum/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"):++ 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.SHARED, "download_asset") 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()), [])+++ def test_failed_shared_download_retains_failure_receipt(self):++ manifest = self.root / "manifest.json"++ manifest.write_text(json.dumps({"assets": [self.asset]}))++ receipt = self.root / "download-failure.json"++ argv = [str(SCRIPT), "--destination", str(self.destination),++ "--manifest", str(manifest), "--receipt", str(receipt)]++ with (patch("sys.argv", argv),++ patch.object(RESTORE, "ASSETS", (self.archive.name,)),++ patch.object(RESTORE.SHARED, "download_asset", side_effect=RuntimeError("release access unavailable")),++ patch.object(RESTORE, "restore_archive") as restore):++ with self.assertRaisesRegex(RuntimeError, "release access unavailable"):++ RESTORE.main()++ restore.assert_not_called()++ record = json.loads(receipt.read_text())++ self.assertEqual(record["status"], "failed")++ self.assertEqual(record["assets"], [])++ self.assertEqual(record["restoration_implementation"]["download"], "gh release download")++ self.assertFalse(record["restoration_implementation"]["credentials_recorded"])++ self.assertFalse((self.destination / "data").exists())++++if __name__ == "__main__":+ unittest.main()diff --cc tests/test_provenance.pyindex 55ae197,0000000..28c7b4emode 100644,000000..100644--- a/tests/test_provenance.py+++ b/tests/test_provenance.py@@@ -1,140 -1,0 +1,168 @@@+"""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_wheel_layout_excludes_unrelated_installed_packages(self):++ roots = [self.root / "checkout/src", self.root / "venv/lib/python/site-packages"]++ files = {"aircraft_geoloc/__init__.py": b"version = 1\n",++ "aircraft_geoloc/web/__init__.py": b"assets = True\n"}++ for root in roots:++ for name, data in files.items():++ path = root / name++ path.parent.mkdir(parents=True, exist_ok=True)++ path.write_bytes(data)++ installed = roots[1]++ sibling = installed / "unrelated_package/module.py"++ sibling.parent.mkdir()++ sibling.write_bytes(b"external = 1\n")++ (installed / "unrelated.py").write_bytes(b"external = 2\n")++ checkout = implementation_provenance(roots[0])++ wheel = implementation_provenance(installed)++ self.assertEqual({row["relative_path"] for row in wheel["sources"]}, set(files))++ self.assertEqual(wheel["sha256"], checkout["sha256"])++ sibling.write_bytes(b"external = 3\n")++ self.assertEqual(implementation_provenance(installed)["sha256"], wheel["sha256"])++ (installed / "aircraft_geoloc/web/__init__.py").write_bytes(b"assets = False\n")++ self.assertNotEqual(implementation_provenance(installed)["sha256"], wheel["sha256"])++ with self.assertRaises(FileNotFoundError):++ implementation_provenance(sibling.parent)+++ 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")++ package = root / "aircraft_geoloc"++ (package / "pkg").mkdir(parents=True)++ (package / "a.py").write_bytes(b"a = 1\n")++ (package / "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()++ expected = hashlib.sha256(b"aircraft_geoloc/a.py" + b"a = 1\n" +++ b"aircraft_geoloc/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([row["relative_path"] for row in result["sources"]],++ ["aircraft_geoloc/a.py", "aircraft_geoloc/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")++ (package / "pkg/b.py").write_bytes(b"b = 3\n")+ self.assertNotEqual(implementation_provenance(root)["sha256"], expected)+++if __name__ == "__main__":+ unittest.main()