Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Land automatic local MP3 pipeline with physical support guards
Cinna Davis8c3c89c85e06
diff --cc docs/PRODUCT.mdindex 0000000,36e4e1f..9855cd9mode 000000,100644..100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@@ -1,0 -1,179 +1,179 @@@+ # Local upload workflow++ The current location goal accepts up to **1,000 m error**, with **100–500 m or better preferred**. True benchmark error and uncalibrated model sensitivity remain separate. Historical reports below retain their original 100 m thresholds.++ The automatic product path is separate from the historical research `run` and+ `measure` commands. Uploads supply audio, an optional defensible UTC window for+ **sample zero**, and declared CONUS search coverage. Event windows, frequency+ bands, flight IDs and ground-truth coordinates are not upload inputs.++ Launch the local interface after installing the project:++ ```bash-aircraft-geoloc serve --jobs jobs --config operator.json --port 8765++dopplergeist serve --jobs jobs --config operator.json --port 8765+ ```++ Open `http://127.0.0.1:8765`. The same persistent directory must be supplied after+ restarting. Each upload gets a new job ID and its own original file, normalized+ request, provenance, intermediate diagnostics, result and worker log. Completed+ jobs are read back without rerunning. Interrupted jobs are explicitly failed;+ they are never silently replayed. Cancelling preserves partial artifacts.++ The server binds to loopback. It runs one analysis process at a time, accepts up+ to four pending jobs, limits uploads to 100 MiB by default, and limits analysis+ to one hour by default. Set `--max-upload-mb` and `--max-runtime` to change these+ operator limits. Cancellation terminates the analysis process group, including+ decoders. No API credentials or paid service are required by the local service.+ Flight/terrain provider configuration and scientific integration are described+ below; an unconfigured backend must report+ missing data rather than invent a location.++ CLI equivalents:++ ```bash-aircraft-geoloc analyze recording.mp3 --jobs jobs --config operator.json \++dopplergeist analyze recording.mp3 --jobs jobs --config operator.json \+ --start-utc 2026-09-08T20:00:00Z --end-utc 2026-09-08T20:05:00Z \+ --time-source 'Recorder clock and recording log'-aircraft-geoloc job JOB_ID --jobs jobs++dopplergeist job JOB_ID --jobs jobs+ ```++ The UTC window bounds the recording start, not the event occurrence or upload.+ Missing time is a required-input result. Scores are ranking statistics, not+ probabilities. Sensitivity radii must not be described as calibrated confidence.+ An inconclusive result may retain candidate hypotheses for inspection.++ ## HTTP surface++ - `GET /api/capabilities`: declared coverage and upload/work limits.+ - `POST /api/jobs`: raw audio bytes with `Content-Type: application/octet-stream`,+ `Content-Length`, optional `X-Filename`, and `X-Dopplergeist-Request` containing+ the shared request JSON **without** `audio_path`. The server saves the upload+ and sets that path. Returns HTTP 202 and a shared queued `JobResult`.+ - `GET /api/jobs/{id}`: the current shared `JobResult`.+ - `POST /api/jobs/{id}/cancel`: cancel a queued/running job; terminal jobs remain.+ - `GET /api/jobs/{id}/artifacts`: relative file paths and byte counts.+ - `GET /api/jobs/{id}/artifacts/{path}`: download one artifact. Private operator+ configuration is excluded. Paths cannot escape the job directory.++ Upload example (header metadata uses actual JSON, not a string-encoded file):++ ```bash+ curl -H 'Content-Type: application/octet-stream' \+ -H 'X-Dopplergeist-Request: {"schema_version":1,"search":{"coverage":"conus"}}' \+ --data-binary @recording.mp3 http://127.0.0.1:8765/api/jobs+ ```++ `tests/test_service.py` checks HTTP transport, original preservation, state+ readback, cancellation, interrupted jobs, path restrictions and input validation.+ These transport tests do not establish scientific localization accuracy.++ ## Provider and search configuration++ An operator configures data once; users upload audio without choosing trajectory+ files. The normal acquisition path delegates to `data_access.acquire_inputs`:++ ```json+ {+ "cache_root": "/absolute/path/to/dopplergeist-cache",+ "offline": false,+ "terrain": {},+ "search_budget": {+ "spacing_m": 2000,+ "tile_cells": 32,+ "top_k": 100,+ "refine_spacing_m": 100+ }+ }+ ```++ This acquires public ADSB.lol all-type daily archives and Copernicus terrain/geoid+ inputs, then reuses their indexed cache. It can require substantial disk space and+ time. `offline` defaults to true; online retrieval is an explicit operator choice.+ No hidden account credentials or paid fallback are used. The default acquisition+ budget is three UTC archive dates, including propagation guards and the full recording (`max_acquisition_days`); wider recording windows need+ a narrower defensible input or an explicit operator budget change. Do not put+ credentials in this configuration.++ For existing offline data, supply `flight_indexes` (paths to Worker 2 FlightIndex+ SQLite files). Terrain may use the cached provider options (`geoid_path`,+ `adopt_existing`) or a declared local override: `{"rasters":["/dem.tif"],+ "geoid_raster":"/geoid.tif"}`. A `{"constant_m":0}` terrain override exists for+ synthetic/flat-ground experiments and is labelled as a limitation in the result.+ Local overrides require prebuilt indexes and retain their actual coverage.++ `search_budget.max_tiles` bounds tile work. Reaching a tile, memory, data or wall+ time limit leaves incomplete coverage and cannot produce a supported national+ location. Full search completion does not prove the archive captured every real+ aircraft. Grid finalists undergo jointly constrained position/clock refinement;+ `refine_finalists` (default 5) limits physical sensitivity refinement. Unassessed+ retained approaches prevent an affirmative confidence decision.++ For reproducible chunk-boundary checks, an operator may set+ `"discovery": {"chunk_s": 120.0, "overlap_s": 60.0}` in this private configuration.+ These are the only discovery overrides supported by the product adapter. The+ existing detector validates the overlap and chunk constraints; spectral bands,+ acceptance thresholds and other scientific settings keep their defaults. The+ actual settings and analyzed chunks are saved in `discovery/discovery.json`, and+ the operator configuration hash is retained in provenance. This configuration is+ not an upload-request field. A chunk-size comparison must rerun detection and the+ pipeline; it cannot reuse final candidates as if discovery had run again.++ Search reports with `model_support_complete` also supply explicit `model_support`+ work counters. Unsupported CPA trajectories, unclassified score candidates or+ unknown clock trials keep product search coverage incomplete. Missing/malformed+ counters cannot become zero work. Source spatial/time availability remains a+ separate `data_status`; an available archive can still have unassessed trajectory+ models. Coverage limitations expose the work counts, and per-stage support+ artifacts retain affected IDs/reasons and conservative lost-coverage envelopes.+ These counts describe work evaluations, not distinct aircraft.++ The automatic path always uses one shared clock inside the supplied start window+ and robust ridge loss. Its default association path considers every proposed+ independent group; harmonics count once and unsupported acoustic proposals remain+ explicitly unmatched. A smaller operator event cap is incomplete work and is shown+ in coverage limitations, rather than silently keeping an initial subset. Every discovered event remains in the diagnostics. A+ location requires the confidence producer's evidence checks, including independent+ events, alternative hypotheses, complete coverage, residuals and measurement/model+ sensitivity. A small altitude-only profile is insufficient. The final decision+ and full candidate/refinement diagnostics are saved as downloadable JSON.++ ## Current limits++ The application is available on `main` and remains experimental. Automatic+ synthetic runs have produced accurate hypotheses and inconclusive decisions;+ those are different outcomes. See the [README](../README.md#experimental-results)+ for the reported results.++ Independent real recordings with established recording time and location,+ reliable global hypothesis discrimination, and calibrated false-localization+ rates remain open. The acceptance goal is within 1,000 m, preferably 100–500 m;+ landing the application does not establish that goal.++ ## Accounted finite-search evidence++ The current integration consumes the optional artifact-only producer/decision+ contract in [FINITE_SEARCH_DECISION.md](FINITE_SEARCH_DECISION.md). The search+ producer assigns stable seed `mode_id` values including position, clock, event+ indices and flight/pass association, and records every lossy retention bound.+ The product relays `finite_search_evidence` unchanged, preserves seed IDs through+ refinement, and supplies `candidate_mode_ids` parallel to the wire candidates.++ For the explicitly declared evaluated-finite-grid scope, `assessed_mode_ids`+ requires the producer's explicit `core_assessed_mode_ids` mapping plus an actually+ completed finite core score with full measured-trajectory support at the original+ seed/model and a valid trusted clock. A returned fit alone does not establish+ classification of every bounded clock/optimizer trial; missing/malformed mappings+ or producer-omitted IDs remain unassessed. It does not require+ jointly optimizing every retained point. Failed, missing or unsupported core+ records are unassessed. Raw and refined representations retain their original+ mode ID and original-or-improved score; no association-only deduplication is used.+ The accepted leading estimate still needs successful full sensitivity, datum,+ optimizer, clock, actual-radius and competing-mode checks.++ Unperformed refinements and continuous locations are outside that conditional+ finite claim. Their limitations are displayed in coverage and saved in the+ artifacts. The old `alternatives_evaluated` flag keeps its older meaning and is+ not flipped to force success. An absent finite object preserves old outcomes;+ missing mappings, incomplete work or an unaccounted near-tied discard remain+ inconclusive. Producer computation, consumer agreement and an actual integrated+ run are required before this optional path is considered deployed.diff --cc scripts/check_motion_support.pyindex 0000000,97dd5b9..e2bddf9mode 000000,100644..100644--- a/scripts/check_motion_support.py+++ b/scripts/check_motion_support.py@@@ -1,0 -1,66 +1,66 @@@+ #!/usr/bin/env python3+ """Compare production support exclusions with the preserved raw-motion audit.++ This bounded source-only check reads no audio, receiver truth or search output.+ It neither alters the historical audit nor performs a localization replay.+ """+ import argparse+ import hashlib+ import json+ from pathlib import Path+ import subprocess++ import pandas as pd+-from aircraft_geoloc.data_access import _frame_track-from aircraft_geoloc.geometry import AcousticSupportError++from dopplergeist.data_access import _frame_track++from dopplergeist.geometry import AcousticSupportError+++ def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--audit", type=Path, default=Path("research/trajectory-motion/frozen"))+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ args.output.mkdir(parents=True, exist_ok=False)+ report_path = args.audit/"report.json"+ report = json.loads(report_path.read_text())+ canonical_path = args.audit/"canonical-observations.json"+ canonical = pd.read_json(canonical_path)+ inputs = [report_path, canonical_path]+ rows = []+ for aircraft in report["aircraft"]:+ identity = aircraft["identity"]+ fresh_path = args.audit/f"fresh-{identity}.json"+ fresh = pd.read_json(fresh_path)+ inputs.append(fresh_path)+ for tag, frame in (("canonical", canonical[canonical.flight_id == identity]), ("fresh", fresh)):+ for segment in aircraft[tag]["segments"]:+ intervals = segment["intervals"]+ chunk = frame[frame.time_s.between(intervals[0]["start_s"], intervals[-1]["end_s"])]+ chunk = chunk.sort_values("time_s", kind="stable").drop_duplicates("time_s")+ track = _frame_track(segment["id"], chunk)+ expected = [[i["start_s"], i["end_s"]] for i in intervals if i["exceeds_subsonic_speed"]]+ try:+ track.validate_motion_support(c=report["declaration"]["sound_speed_mps"])+ excluded = []+ except AcousticSupportError as error:+ assert error.reason == "non_subsonic_motion"+ excluded = error.emission_intervals_s+ assert excluded == expected, (tag, track.id, expected, excluded)+ rows.append({"source": tag, "track_id": track.id, "native_intervals": len(intervals),+ "excluded_intervals_s": excluded, "audit_agrees": True})+ root = Path(__file__).resolve().parents[1]- code = [Path(__file__), root/"src/aircraft_geoloc/geometry.py", root/"src/aircraft_geoloc/data_access.py"]++ code = [Path(__file__), root/"src/dopplergeist/geometry.py", root/"src/dopplergeist/data_access.py"]+ receipt = {"scope": "source_only_production_guard_comparison", "segments": rows,+ "code_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, cwd=root).strip(),+ "code_sha256": {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in code},+ "input_sha256": {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in inputs},+ "excluded_native_intervals": sum(len(r["excluded_intervals_s"]) for r in rows),+ "limitations": ["No source repair, acoustic scoring, tile replay or accuracy claim",+ "Whole native intervals are conservative model exclusions"]}+ (args.output/"receipt.json").write_text(json.dumps(receipt, indent=2, allow_nan=False)+"\n")+ print(f"{len(rows)} source segments agree; {receipt['excluded_native_intervals']} excluded native intervals")+++ if __name__ == "__main__":+ main()diff --cc scripts/check_unsupported_tiles.pyindex 0000000,04bd5de..fa355d4mode 000000,100644..100644--- a/scripts/check_unsupported_tiles.py+++ b/scripts/check_unsupported_tiles.py@@@ -1,0 -1,107 +1,107 @@@+ """Replay the three historical failed scale-fixture tiles, without audio truth.++ Compare preserved scores with a per-track oracle on the unchanged canonical+ index. This is a fault-isolation regression, not a localization benchmark.+ """+ import argparse+ import json+ from pathlib import Path+ import subprocess+ import time++ import numpy as np+-from aircraft_geoloc.audio import Spectrum-from aircraft_geoloc.data_access import FlightIndex, sha256, write_json-from aircraft_geoloc.geometry import AcousticSupportError-from aircraft_geoloc.search import cpa_table, pair_candidates, score_candidate-from aircraft_geoloc.terrain import Terrain-from aircraft_geoloc.tiled_search import SearchBudget, _expanded_bounds, _record_support, _score, _tracks, grid_tiles, merge_candidates, tile_points++from dopplergeist.audio import Spectrum++from dopplergeist.data_access import FlightIndex, sha256, write_json++from dopplergeist.geometry import AcousticSupportError++from dopplergeist.search import cpa_table, pair_candidates, score_candidate++from dopplergeist.terrain import Terrain++from dopplergeist.tiled_search import SearchBudget, _expanded_bounds, _record_support, _score, _tracks, grid_tiles, merge_candidates, tile_points+++ def signature(rows):+ return [(r["flight_ids"], r["x"], r["y"], r["score"], r["recording_start_time_s"],+ r["pass_emission_times_s"]) for r in rows]+++ def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("index")+ parser.add_argument("output")+ parser.add_argument("--manifest", default="evidence/w2-data-scale-20261102/scale-v2-manifest.json")+ args = parser.parse_args()+ output = Path(args.output)+ output.mkdir(parents=True, exist_ok=False)+ config = json.loads(Path(args.manifest).read_text())["configuration"]+ index = FlightIndex(args.index)+ assert sha256(index.path) == config["indexes"][0]["file_sha256"], "Require the unchanged historical index"+ assert index.report["input_hash"] == config["indexes"][0]["input_hash"]+ budget = SearchBudget(**config["budget"])+ event, = config["events"]+ t = np.linspace(event["start_s"], event["end_s"], 41)+ ridge = 120 * (1 - .12 * np.tanh((t - event["cpa_receive_s"]) / 12))+ spec = Spectrum(t, np.array([80., 160.]), np.zeros((2, len(t))), np.zeros((2, len(t))))+ measurements = [(spec, ridge, np.ones(len(t)), {})]+ radius, began, reports = event["slant_range_m"][1], time.monotonic(), []+ selected = {"5_13", "9_9", "7_15"}+ for name, cells in grid_tiles(config["bounds"], budget.spacing_m, budget.tile_cells):+ if name not in selected:+ continue+ points = tile_points(cells, budget.spacing_m, config["bounds"], Terrain(constant_m=0), config["crs"])+ tracks = _tracks([index], _expanded_bounds(cells, budget.spacing_m, radius, config["crs"]), config["time_range_s"], budget)+ ranked, counts = _score(points, tracks, [event], measurements, budget, config["scoring"], {})+ summary = dict(unsupported_cpa_track_evaluations=0, unclassified_score_candidates=0,+ evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)+ _record_support(output, f"coarse:{name}", counts, summary)+ # Independently enumerate/score each track. A failure cannot interrupt+ # unrelated tracks in this oracle; retain every finite result before k.+ reference, failures, source_failures, nonfinite = [], [], [], 0+ lookup = {p.point_id: p for p in points.itertuples()}+ for track in tracks:+ try:+ table = cpa_table([track], points, radius, config["scoring"].get("c", 343.), budget.cpa_step_s)+ except AcousticSupportError as error:+ source_failures.append({"flight_id": track.id, "reason": error.reason,+ "emission_intervals_s": error.emission_intervals_s,+ "receive_intervals_s": error.receive_intervals_s})+ continue+ candidates, _ = pair_candidates(table, [event], time_origin=config["scoring"]["time_origin"], time_tolerance_s=5.)+ for candidate in candidates:+ try:+ row = score_candidate(candidate, lookup[candidate["point_id"]], {track.id: track},+ [event], measurements, **config["scoring"])+ except AcousticSupportError as error:+ failures.append({"flight_id": track.id, "point_id": int(candidate["point_id"]), "reason": error.reason})+ continue+ if np.isfinite(row["score"]):+ row["pass_emission_times_s"] = [float(p["emission_time"]) for p in candidate["passes"]]+ reference.append(row)+ else:+ nonfinite += 1+ kept = merge_candidates(reference, budget.top_k)+ assert signature(ranked) == signature(kept), f"Clean candidate change at {name}"+ assert counts["unclassified_score_candidates"] == len(failures) + nonfinite+ assert len(counts["unsupported_cpa_tracks"]) == len(source_failures)+ assert (failures or source_failures) and ranked, "Each historical failure tile must preserve valid diagnostics"+ report = {"tile": name, "tracks": len(tracks), "points": len(points), "finite_oracle_rows": len(reference),+ "retained_rows": len(ranked), "typed_candidate_failures": failures, "nonfinite_oracle_rows": nonfinite,+ "unsupported_cpa_sources": source_failures,+ "model_support_complete": False, "model_support": summary, "clean_scores_equal_oracle": True,+ "ranked": ranked}+ write_json(output / f"tile-{name}.json", report)+ reports.append({k: v for k, v in report.items() if k != "ranked"})+ print(json.dumps({k: v for k, v in report.items() if k not in ("ranked", "typed_candidate_failures", "unsupported_cpa_sources")}), flush=True)+ assert {r["tile"] for r in reports} == selected+ root = Path(__file__).resolve().parents[1]+ write_json(output / "report.json", {"scope": "Historical three failed analytic-ridge scale tiles; no localization truth",+ "source_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip(),+ "index_sha256": sha256(index.path), "index_input_hash": index.report["input_hash"],- "old_manifest_sha256": sha256(args.manifest), "code_sha256": {p.name: sha256(p) for p in (root / "src/aircraft_geoloc").glob("*.py")},++ "old_manifest_sha256": sha256(args.manifest), "code_sha256": {p.name: sha256(p) for p in (root / "src/dopplergeist").glob("*.py")},+ "runner_sha256": sha256(__file__), "elapsed_s": time.monotonic()-began, "tiles": reports,+ "limitations": ["Diagnostic tiles were selected from preserved historical model failures, not recorder truth.",+ "Same legacy derivatives/altitudes and constant ground; no raw normalization repair.",+ "This does not certify continuous motion, complete national coverage or geolocation accuracy."]})+++ if __name__ == "__main__":+ main()diff --cc src/dopplergeist/automatic.pyindex 0000000,dd2d109..dd2d109mode 000000,100644..100644--- a/src/dopplergeist/automatic.py+++ b/src/dopplergeist/automatic.pydiff --cc src/dopplergeist/jobs.pyindex 0000000,29e8aa3..18ce61fmode 000000,100644..100644--- a/src/dopplergeist/jobs.py+++ b/src/dopplergeist/jobs.py@@@ -1,0 -1,233 +1,233 @@@+ """Persistent local jobs; each analysis has its own cancellable process group."""+ import argparse+ import fcntl+ import hashlib+ import json+ import math+ import os+ from pathlib import Path+ import signal+ import subprocess+ import sys+ import threading+ import uuid++ from .contracts import validate_request, validate_result++ TERMINAL = {"needs_input", "succeeded", "inconclusive", "failed", "cancelled"}+++ def write_json(path, value):+ path = Path(path)+ temporary = path.with_suffix(path.suffix + ".tmp")+ temporary.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")+ temporary.replace(path)+++ def read_json(path):+ return json.loads(Path(path).read_text())+++ def result(job_dir, status, **fields):+ value = validate_result(dict(schema_version=1, job_id=Path(job_dir).name, status=status, **fields))+ write_json(Path(job_dir) / "result.json", value)+ return value+++ def _evidence(value):+ return {key: value[key] for key in ("recording", "events", "candidates", "coverage", "artifacts") if key in value}+++ class JobManager:+ def __init__(self, root, config=None, *, max_pending=4, max_runtime_s=3600, max_upload_bytes=100*1024*1024):+ self.root = Path(root).resolve()+ self.root.mkdir(parents=True, exist_ok=True, mode=0o700)+ self.config = config or {}+ if not isinstance(self.config, dict):+ raise ValueError("Operator configuration must be a JSON object")+ self.max_pending = max_pending+ self.max_runtime_s = max_runtime_s+ self.max_upload_bytes = max_upload_bytes+ if any(not math.isfinite(value) or value <= 0 for value in (max_pending, max_runtime_s, max_upload_bytes)):+ raise ValueError("Job limits must be positive")+ self._lockfile = (self.root / ".manager.lock").open("a")+ try:+ fcntl.flock(self._lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ self._lockfile.close()+ raise ValueError("Another job manager is using this directory") from None+ self._mutex = threading.RLock()+ self._serial = threading.Semaphore(1)+ self._threads = {}+ self._processes = {}+ self._closed = False+ # Preserve terminal outputs. An interrupted process is never silently replayed.+ for path in self.root.glob("*/result.json"):+ old = read_json(path)+ if old["status"] not in TERMINAL:+ result(path.parent, "failed", reason_code="interrupted", message="Service stopped before completion; submit a new job to retry.", **_evidence(old))++ def directory(self, job_id):+ try:+ if uuid.UUID(job_id).hex != job_id:+ raise ValueError+ except (ValueError, AttributeError):+ raise KeyError("Unknown job") from None+ path = self.root / job_id+ if not (path / "result.json").is_file():+ raise KeyError("Unknown job")+ return path++ def get(self, job_id):+ return read_json(self.directory(job_id) / "result.json")++ def submit(self, metadata, source, size, *, suffix=".mp3"):+ """Copy exactly size bytes from a binary stream before launching analysis."""+ if size <= 0 or size > self.max_upload_bytes:+ raise ValueError(f"Audio size must be 1..{self.max_upload_bytes} bytes")+ request = validate_request(dict(metadata, audio_path="pending"))+ with self._mutex:+ if self._closed:+ raise ValueError("Service is shutting down")+ if sum(thread.is_alive() for thread in self._threads.values()) >= self.max_pending:+ raise OverflowError("Job queue is full; try again after a job finishes")+ job_id = uuid.uuid4().hex+ directory = self.root / job_id+ directory.mkdir(mode=0o700)+ suffix = suffix.lower() if suffix.lower() in {".mp3", ".wav", ".flac", ".m4a", ".ogg"} else ".mp3"+ audio = directory / ("input" + suffix)+ digest = hashlib.sha256()+ with audio.open("xb") as target:+ remaining = size+ while remaining:+ block = source.read(min(1024*1024, remaining))+ if not block:+ result(directory, "failed", reason_code="incomplete_upload", message="Upload ended before its declared length.")+ raise ValueError("Incomplete upload")+ target.write(block)+ digest.update(block)+ remaining -= len(block)+ request["audio_path"] = str(audio)+ write_json(directory / "request.json", request)+ write_json(directory / "operator.json", self.config)+ write_json(directory / "input.json", {"sha256": digest.hexdigest(), "bytes": size, "path": audio.name})+ queued = result(directory, "queued", stage="queued", progress=0)+ thread = threading.Thread(target=self._run, args=(directory,), daemon=True)+ self._threads[job_id] = thread+ thread.start()+ return queued++ def _run(self, directory):+ try:+ with self._serial:+ with self._mutex:+ if self.get(directory.name)["status"] in TERMINAL:+ return+ env = dict(os.environ)+ env["PYTHONPATH"] = str(Path(__file__).resolve().parents[1]) + os.pathsep + env.get("PYTHONPATH", "")+ with (directory / "worker.log").open("ab") as log:- process = subprocess.Popen([sys.executable, "-m", "aircraft_geoloc.jobs", "--execute", str(directory),++ process = subprocess.Popen([sys.executable, "-m", "dopplergeist.jobs", "--execute", str(directory),+ "--parent-pid", str(os.getpid())],+ stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True)+ self._processes[directory.name] = process+ try:+ process.wait(timeout=self.max_runtime_s)+ except subprocess.TimeoutExpired:+ self._stop(process)+ with self._mutex:+ if self.get(directory.name)["status"] not in TERMINAL:+ result(directory, "inconclusive", reason_code="work_limit", message="Analysis exceeded the configured wall-time budget; inspect partial artifacts.", **_evidence(self.get(directory.name)))+ with self._mutex:+ if self.get(directory.name)["status"] not in TERMINAL:+ result(directory, "failed", reason_code="worker_exit", message=f"Analysis process exited ({process.returncode}); inspect worker.log.", **_evidence(self.get(directory.name)))+ except Exception as exc:+ with self._mutex:+ if self.get(directory.name)["status"] not in TERMINAL:+ result(directory, "failed", reason_code="worker_launch", message=f"Could not run analysis: {exc}", **_evidence(self.get(directory.name)))+ finally:+ with self._mutex:+ self._processes.pop(directory.name, None)+ self._threads.pop(directory.name, None)++ @staticmethod+ def _stop(process):+ if process.poll() is None:+ os.killpg(process.pid, signal.SIGTERM)+ try:+ process.wait(timeout=3)+ except subprocess.TimeoutExpired:+ os.killpg(process.pid, signal.SIGKILL)+ process.wait()++ def cancel(self, job_id):+ with self._mutex:+ directory = self.directory(job_id)+ current = self.get(job_id)+ if current["status"] in TERMINAL:+ return current+ (directory / "cancel").touch()+ process = self._processes.get(job_id)+ if process:+ self._stop(process)+ return result(directory, "cancelled", message="Cancelled by the user; partial artifacts are preserved.", **_evidence(self.get(job_id)))++ def wait(self, job_id):+ thread = self._threads.get(job_id)+ if thread:+ thread.join()+ return self.get(job_id)++ def close(self):+ with self._mutex:+ self._closed = True+ for job_id, thread in list(self._threads.items()):+ if thread.is_alive():+ self.cancel(job_id)+ for thread in list(self._threads.values()):+ thread.join()+ self._lockfile.close()+++ def execute(directory, parent_pid=None):+ # On Linux, an abruptly killed server must not leave an orphan analysis or+ # decoder consuming resources and later overwriting an interrupted result.+ if parent_pid is not None and sys.platform == "linux":+ import ctypes+ def terminate_group(signum, frame):+ signal.signal(signal.SIGTERM, signal.SIG_DFL)+ os.killpg(os.getpgrp(), signal.SIGTERM)+ signal.signal(signal.SIGTERM, terminate_group)+ ctypes.CDLL(None).prctl(1, signal.SIGTERM, 0, 0, 0)+ if os.getppid() != parent_pid:+ terminate_group(signal.SIGTERM, None)+ from .automatic import analyze+ directory = Path(directory)+ request = read_json(directory / "request.json")+ config = read_json(directory / "operator.json")++ def progress(stage, fraction, **fields):+ if (directory / "cancel").exists():+ raise InterruptedError("Job cancelled")+ return result(directory, "running", stage=stage, progress=fraction, **fields)++ try:+ progress("intake", 0.02)+ final = analyze(request, directory, config, progress)+ if (directory / "cancel").exists():+ result(directory, "cancelled", message="Cancelled by the user.", **_evidence(read_json(directory / "result.json")))+ else:+ result(directory, **final)+ except InterruptedError:+ result(directory, "cancelled", message="Cancelled by the user.", **_evidence(read_json(directory / "result.json")))+ except Exception as exc:+ import traceback+ traceback.print_exc()+ result(directory, "failed", reason_code="processing_error", message=f"{type(exc).__name__}: {exc}", **_evidence(read_json(directory / "result.json")))+++ if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("--execute", required=True)+ parser.add_argument("--parent-pid", type=int)+ args = parser.parse_args()+ execute(args.execute, args.parent_pid)diff --cc src/dopplergeist/service.pyindex 0000000,67b5418..ba6258amode 000000,100644..100644--- a/src/dopplergeist/service.py+++ b/src/dopplergeist/service.py@@@ -1,0 -1,130 +1,130 @@@+ """Loopback upload/job API, sharing the automatic CLI's persistent job manager."""+ import json+ import mimetypes+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+ from importlib.resources import files+ from pathlib import Path+ from urllib.parse import unquote, urlsplit++ from .jobs import JobManager+++ class JobServer(ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, address, manager):+ if address[0] not in {"127.0.0.1", "localhost"}:+ raise ValueError("This unauthenticated local service binds to loopback only")+ self.manager = manager+ super().__init__(address, Handler)+++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, format, *args):+ pass++ def _reply(self, value, code=200):+ body = json.dumps(value, allow_nan=False).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Cache-Control", "no-store")+ self.send_header("X-Content-Type-Options", "nosniff")+ self.end_headers()+ self.wfile.write(body)++ def _check_origin(self):+ allowed = {f"127.0.0.1:{self.server.server_port}", f"localhost:{self.server.server_port}"}+ if self.headers.get("Host") not in allowed:+ raise PermissionError("Invalid local Host header")+ origin = self.headers.get("Origin")+ if origin and origin not in {"http://" + host for host in allowed}:+ raise PermissionError("Requests must originate from this local interface")++ def _route(self):+ self._check_origin()+ parts = [unquote(p) for p in urlsplit(self.path).path.strip("/").split("/")]+ manager = self.server.manager+ if self.command == "GET" and parts == ["api", "capabilities"]:+ return self._reply({"schema_version": 1, "coverage": "conus", "max_upload_bytes": manager.max_upload_bytes,+ "max_runtime_s": manager.max_runtime_s, "max_pending": manager.max_pending})+ if self.command == "POST" and parts == ["api", "jobs"]:+ if self.headers.get("Transfer-Encoding"):+ raise ValueError("Use a Content-Length upload")+ if self.headers.get_content_type() != "application/octet-stream":+ raise ValueError("Upload raw audio as application/octet-stream")+ metadata = json.loads(self.headers.get("X-Dopplergeist-Request", "{}"))+ if not isinstance(metadata, dict) or "audio_path" in metadata:+ raise ValueError("Upload metadata must be a request object without audio_path")+ size = int(self.headers.get("Content-Length", "0"))+ suffix = Path(self.headers.get("X-Filename", "input.mp3")).suffix+ self.connection.settimeout(30)+ return self._reply(manager.submit(metadata, self.rfile, size, suffix=suffix), 202)+ if len(parts) >= 3 and parts[:2] == ["api", "jobs"]:+ job_id = parts[2]+ if self.command == "GET" and len(parts) == 3:+ return self._reply(manager.get(job_id))+ if self.command == "POST" and parts[3:] == ["cancel"]:+ return self._reply(manager.cancel(job_id))+ if self.command == "GET" and parts[3:] == ["artifacts"]:+ directory = manager.directory(job_id)+ artifacts = []+ for path in sorted(directory.rglob("*")):+ if path.is_file() and not path.is_symlink() and path.name not in {"operator.json", "cancel"} and not path.name.endswith(".tmp"):+ artifacts.append({"path": path.relative_to(directory).as_posix(), "bytes": path.stat().st_size})+ return self._reply({"artifacts": artifacts})+ if self.command == "GET" and len(parts) > 4 and parts[3] == "artifacts":+ directory = manager.directory(job_id)+ relative = Path(*parts[4:])+ path = (directory / relative).resolve()+ if path == directory or directory not in path.parents or not path.is_file() or "operator.json" in relative.parts:+ raise KeyError("Unknown artifact")+ return self._file(path, download=path.suffix not in {".png", ".svg"})+ if self.command == "GET":+ asset = {"/": "index.html", "/app.js": "app.js", "/style.css": "style.css"}.get(urlsplit(self.path).path)+ if asset:- return self._file(files("aircraft_geoloc.web").joinpath(asset))++ return self._file(files("dopplergeist.web").joinpath(asset))+ raise KeyError("Unknown endpoint")++ def _file(self, path, download=False):+ self.send_response(200)+ self.send_header("Content-Type", mimetypes.guess_type(str(path))[0] or "application/octet-stream")+ self.send_header("Content-Length", str(path.stat().st_size))+ self.send_header("X-Content-Type-Options", "nosniff")+ self.send_header("Content-Security-Policy", "default-src 'self'; img-src 'self'; style-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'")+ if download:+ self.send_header("Content-Disposition", f'attachment; filename="{path.name.replace(chr(34), "")}"')+ self.end_headers()+ with path.open("rb") as source:+ while block := source.read(1024*1024):+ self.wfile.write(block)++ def _handle(self):+ try:+ self._route()+ except PermissionError as exc:+ self._reply({"error": str(exc)}, 403)+ except KeyError as exc:+ self._reply({"error": str(exc)}, 404)+ except OverflowError as exc:+ self._reply({"error": str(exc)}, 429)+ except (ValueError, TimeoutError) as exc:+ self._reply({"error": str(exc)}, 400)+ except (BrokenPipeError, ConnectionResetError):+ pass++ do_GET = _handle+ do_POST = _handle+++ def serve(root, config=None, *, port=8765, max_runtime_s=3600, max_upload_bytes=100*1024*1024):+ manager = JobManager(root, config, max_runtime_s=max_runtime_s, max_upload_bytes=max_upload_bytes)+ try:+ with JobServer(("127.0.0.1", port), manager) as server:+ print(f"DOPPLERGEIST: http://127.0.0.1:{server.server_port} (jobs: {manager.root})", flush=True)+ try:+ server.serve_forever()+ except KeyboardInterrupt:+ pass+ finally:+ manager.close()diff --cc src/dopplergeist/web/__init__.pyindex 0000000,5d6a00f..5d6a00fmode 000000,100644..100644--- a/src/dopplergeist/web/__init__.py+++ b/src/dopplergeist/web/__init__.pydiff --cc src/dopplergeist/web/app.jsindex 0000000,62c144f..62c144fmode 000000,100644..100644--- a/src/dopplergeist/web/app.js+++ b/src/dopplergeist/web/app.jsdiff --cc src/dopplergeist/web/index.htmlindex 0000000,a65147d..a65147dmode 000000,100644..100644--- a/src/dopplergeist/web/index.html+++ b/src/dopplergeist/web/index.htmldiff --cc src/dopplergeist/web/style.cssindex 0000000,68dbd8c..68dbd8cmode 000000,100644..100644--- a/src/dopplergeist/web/style.css+++ b/src/dopplergeist/web/style.cssdiff --cc tests/test_automatic.pyindex 0000000,387bcea..e62ae13mode 000000,100644..100644--- a/tests/test_automatic.py+++ b/tests/test_automatic.py@@@ -1,0 -1,269 +1,269 @@@+ """Encoded audio through the real job process, intake and automatic discovery."""+ import hashlib+ import json+ import threading+ import urllib.request+ import subprocess++ import numpy as np+ import pytest+ import soundfile as sf+-from aircraft_geoloc.jobs import JobManager-from aircraft_geoloc.service import JobServer++from dopplergeist.jobs import JobManager++from dopplergeist.service import JobServer+++ def encoded_mp3(tmp_path, *, moving=False):- pytest.importorskip("aircraft_geoloc.intake")- pytest.importorskip("aircraft_geoloc.discovery")++ pytest.importorskip("dopplergeist.intake")++ pytest.importorskip("dopplergeist.discovery")+ sr = 8000+ t = np.arange(sr * 40) / sr+ frequency = 220 - t if moving else np.full_like(t, 200)+ # Deterministic acoustic control, not aircraft/location truth.+ wave = .3*np.sin(2*np.pi*np.cumsum(frequency)/sr) + np.random.default_rng(44).normal(0, .002, len(t))+ source = tmp_path / "control.wav"+ sf.write(source, wave, sr)+ target = tmp_path / "control.mp3"+ subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", str(source), "-codec:a", "libmp3lame", str(target)], check=True)+ return target.read_bytes()+++ def submit_and_wait(tmp_path, payload, *, time_window=None, config=None):+ manager = JobManager(tmp_path / "jobs", config)+ server = JobServer(("127.0.0.1", 0), manager)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ base = f"http://127.0.0.1:{server.server_port}"+ try:+ request = {"schema_version": 1}+ if time_window:+ request["time_window"] = time_window+ upload = urllib.request.Request(base + "/api/jobs", payload,+ headers={"Content-Type": "application/octet-stream", "X-Dopplergeist-Request": json.dumps(request)})+ with urllib.request.urlopen(upload, timeout=10) as response:+ assert response.status == 202+ queued = json.load(response)+ final = manager.wait(queued["job_id"])+ directory = manager.directory(queued["job_id"])+ with urllib.request.urlopen(base + f"/api/jobs/{queued['job_id']}") as response:+ assert json.load(response) == final+ with urllib.request.urlopen(base + f"/api/jobs/{queued['job_id']}/artifacts/input.mp3") as response:+ assert response.read() == payload+ return final, directory+ finally:+ server.shutdown()+ server.server_close()+ manager.close()+ thread.join()+++ WINDOW = {"start_utc": "2026-09-08T20:00:00Z", "end_utc": "2026-09-08T20:01:00Z", "source": "user"}+++ def test_real_mp3_without_time_requests_clock_and_preserves_hash(tmp_path):+ payload = encoded_mp3(tmp_path)+ final, directory = submit_and_wait(tmp_path, payload)+ assert final["status"] == "needs_input", final+ assert final["reason_code"] == "recording_time_required"+ assert final["required_fields"] == ["time_window"]+ assert final["recording"]["source_sha256"] == hashlib.sha256(payload).hexdigest()+ assert (directory / "input.mp3").read_bytes() == payload+ assert (directory / final["artifacts"]["provenance"]).is_file()+++ def test_stationary_mp3_returns_no_events_without_search(tmp_path):+ payload = encoded_mp3(tmp_path)+ final, directory = submit_and_wait(tmp_path, payload, time_window=WINDOW)+ assert final["status"] == "inconclusive" and final["reason_code"] == "no_supported_events", final+ assert not final["events"]+ assert not (directory / "search").exists()+++ @pytest.mark.parametrize("discovery", [None, {"chunk_s": 24., "overlap_s": 16.}])+ def test_moving_tone_mp3_discovers_events_then_reports_missing_data(tmp_path, discovery):- pytest.importorskip("aircraft_geoloc.data_access")- pytest.importorskip("aircraft_geoloc.matching")- pytest.importorskip("aircraft_geoloc.tiled_search")++ pytest.importorskip("dopplergeist.data_access")++ pytest.importorskip("dopplergeist.matching")++ pytest.importorskip("dopplergeist.tiled_search")+ payload = encoded_mp3(tmp_path, moving=True)+ config = {"discovery": discovery} if discovery is not None else {}+ final, directory = submit_and_wait(tmp_path, payload, time_window=WINDOW, config=config)+ assert final["status"] == "inconclusive" and final["reason_code"] == "data_unavailable", final+ assert len(final["events"]) >= 1+ assert list((directory / "discovery").glob("event-*.png"))+ assert final["coverage"]["data_status"] == "unavailable"+ from dataclasses import asdict- from aircraft_geoloc.discovery import DiscoverySettings++ from dopplergeist.discovery import DiscoverySettings+ receipt = json.loads((directory/"discovery/discovery.json").read_text())+ assert receipt["settings"] == asdict(DiscoverySettings(**(discovery or {})))+ assert len(receipt["chunks"]) > 1 if discovery else len(receipt["chunks"]) == 1+ assert json.loads((directory/"operator.json").read_text()) == config+++ def test_corrupt_upload_returns_predictable_decode_failure(tmp_path):- pytest.importorskip("aircraft_geoloc.intake")- pytest.importorskip("aircraft_geoloc.discovery")++ pytest.importorskip("dopplergeist.intake")++ pytest.importorskip("dopplergeist.discovery")+ final, directory = submit_and_wait(tmp_path, b"not encoded audio", time_window=WINDOW)+ assert final["status"] == "failed" and final["reason_code"] == "invalid_media", final+ assert (directory / "input.mp3").read_bytes() == b"not encoded audio"+++ def test_subset_association_preserves_original_event_identity(tmp_path):+ """A middle subset must never be relabelled as the first input events."""- pytest.importorskip("aircraft_geoloc.confidence")- from aircraft_geoloc.automatic import _decide- from aircraft_geoloc.jobs import read_json++ pytest.importorskip("dopplergeist.confidence")++ from dopplergeist.automatic import _decide++ from dopplergeist.jobs import read_json+ events = [{"event_id": f"event-{i}", "start_s": i*10., "end_s": i*10.+5, "band_hz": [100., 120.],+ "ridge": [{"time_s": i*10.+t, "frequency_hz": 115.-t} for t in (1., 2., 3.)]} for i in range(3)]+ search = {"status": "complete", "scoring_time_is_locked": True, "ranked": [+ {"event_indices": [1, 2], "unmatched_event_ids": ["event-0"], "flight_ids": ["second-flight", "third-flight"], "lat": 40., "lon": -100.,+ "score": -1., "recording_start_time_s": 1788897600., "event_diagnostics": [{"rmse_hz": .1}, {"rmse_hz": .2}]}]}+ state = {"recording": {"time_window": {"start_utc": "2026-09-21T14:13:20Z", "end_utc": "2026-09-21T14:14:20Z", "source": "user"}}, "coverage": {"search_complete": True, "data_status": "available", "limitations": []}}+ def finish(status, reason_code=None, message=None, **fields):+ return dict(status=status, reason_code=reason_code, message=message, **fields)+ final = _decide(search, events, events, [None]*3, [], None, state, tmp_path,+ {"refine_finalists": 0}, finish, lambda: None)+ assert final["status"] == "inconclusive"+ assert final["candidates"][0]["event_ids"] == ["event-1", "event-2"]+ diagnostics = read_json(tmp_path / "refined-candidates.json")["matching_diagnostics"]+ assert "event-0" not in diagnostics+ assert diagnostics["unmatched_event_ids"] == ["event-0"]+ assert diagnostics["recording_start_window_s"][1] - diagnostics["recording_start_window_s"][0] == 60+ assert diagnostics["event-1"]["rmse_hz"] == .1+ assert diagnostics["event-2"]["rmse_hz"] == .2+++ def test_complete_tile_work_is_separate_from_partial_flight_coverage():- from aircraft_geoloc.automatic import _coverage++ from dopplergeist.automatic import _coverage+ coverage = _coverage({"search": {"coverage": "conus"}},+ {"status": "partial", "tiles_total": 819, "tiles_completed": 819,+ "tile_failures": [], "refinement_failure": None, "data_scope_complete": False}, {})+ assert coverage["search_complete"] is True+ assert coverage["data_status"] == "partial"+ assert "historical_flight_scope_or_audible_border_region" in coverage["missing_data"]+++ def test_acquisition_budget_counts_utc_archive_days_across_midnight(tmp_path):+ from types import SimpleNamespace- from aircraft_geoloc.automatic import MissingData, _search++ from dopplergeist.automatic import MissingData, _search+ window = {"start_utc": "2026-09-08T23:59:00Z", "end_utc": "2026-09-08T23:59:00Z", "source": "user"}+ event = {"event_id": "event-1", "start_s": 0., "end_s": 10., "band_hz": [100., 120.],+ "ridge": [{"time_s": float(t), "frequency_hz": 115.-t} for t in range(10)]}+ recording = SimpleNamespace(metadata={"time_window": window, "duration_s": 61.})+ request = {"schema_version": 1, "audio_path": "unused", "time_window": window, "search": {"coverage": "conus"}}+ with pytest.raises(MissingData, match="acquisition budget"):+ _search(request, recording, [event], tmp_path, {"cache_root": str(tmp_path), "max_acquisition_days": 1}, lambda: None)+ assert not (tmp_path/"flights").exists()+++ def test_refinement_adapter_preserves_raw_residual_and_avoids_double_normalization():- from aircraft_geoloc.automatic import _comparable_refinement- from aircraft_geoloc.matching import association_score++ from dopplergeist.automatic import _comparable_refinement++ from dopplergeist.matching import association_score+ events = [{"quality": {"frequency_sigma_hz": 1.}}]+ raw = {"score": -.6, "event_scores": [-.6], "score_kind": "negative_robust_ridge_loss_hz"}+ normalized = association_score(raw, events)+ original = dict(normalized, event_indices=[0])+ assert _comparable_refinement(raw, original, events) == normalized+ assert _comparable_refinement(normalized, original, events)["residual_score"] == -.6+ assert _comparable_refinement(normalized, original, events)["score"] == normalized["score"]+++ @pytest.mark.parametrize("second", [{"lat": 41.}, {"recording_start_time_s": 1790000010.},+ {"elev_m": 180.}, {"mode_id": "separate-seed"}])+ def test_refinement_preserves_same_association_model_modes(tmp_path, monkeypatch, second):+ from types import SimpleNamespace- from aircraft_geoloc import automatic, matching++ from dopplergeist import automatic, matching+ events = [{"event_id": f"event-{i}", "start_s": i*100., "end_s": i*100.+20., "band_hz": [90., 200.],+ "ridge": [{"time_s": i*100.+t, "frequency_hz": 140.-t} for t in (0., 10., 20.)]} for i in range(2)]+ fit = {"rmse_hz": .1, "support_fraction": 1., "outlier_fraction": 0., "drift_at_bound": False}+ seed = {"lat": 40., "lon": -100., "score": -1., "score_kind": "negative_robust_ridge_loss_hz",+ "recording_start_time_s": 1790000000., "flight_ids": ["a", "b"],+ "pass_emission_times_s": [1790000010., 1790000110.], "event_diagnostics": [dict(fit), dict(fit)]}+ raw = [seed, dict(seed, score=-2., **second)]+ seen = []+ def refine(candidate, *args, **kwargs):+ seen.append((candidate["lat"], candidate["lon"], candidate["recording_start_time_s"],+ candidate.get("elev_m"), candidate.get("mode_id")))+ return dict(candidate, score=candidate["score"]+.1)+ monkeypatch.setattr(matching, "refine_candidate", refine)+ monkeypatch.setattr(matching, "profile_candidate", lambda candidate, *args, **kwargs: dict(candidate, sensitivity={"complete": False}))+ tracks = [SimpleNamespace(id=name, time=[0., 1.], altitude_basis=["ellipsoidal"]) for name in ("a", "b")]+ index = SimpleNamespace(query=lambda *args: tracks)+ search = {"ranked": raw, "status": "complete", "scoring_time_is_locked": True, "alternative_modes_exhaustively_assessed": True}+ state = {"recording": {"time_window": {"start_utc": "2026-09-21T14:13:20Z", "end_utc": "2026-09-21T14:14:20Z", "source": "user"}},+ "coverage": {"search_complete": True, "data_status": "available", "limitations": []}}+ def finish(status, reason_code=None, message=None, **fields):+ return dict(status=status, **fields)+ final = automatic._decide(search, events, events, [None]*2, [index], None, state, tmp_path,+ {"refine_finalists": 5}, finish, lambda: None)+ assert set(seen) == {(row["lat"], row["lon"], row["recording_start_time_s"],+ row.get("elev_m"), row.get("mode_id")) for row in raw}+ assert final["status"] == "inconclusive"+ diagnostics = json.loads((tmp_path/"refined-candidates.json").read_text())["matching_diagnostics"]+ assert diagnostics["retained_hypotheses"] == 2+ assert diagnostics["refined_hypotheses"] == 2+++ def test_an_explicit_event_cap_is_incomplete_work_not_missing_flight_data():- from aircraft_geoloc.automatic import _coverage++ from dopplergeist.automatic import _coverage+ coverage = _coverage({"search": {"coverage": "conus"}},+ {"status": "partial", "tiles_total": 2, "tiles_completed": 2, "tile_failures": [],+ "refinement_failure": None, "data_scope_complete": True, "all_event_groups_considered": False,+ "event_limit_reason": "Configured limit 3 omits proposed groups from this four-group recording."}, {})+ assert coverage["search_complete"] is False+ assert coverage["data_status"] == "available"+ assert any("limit 3" in message for message in coverage["limitations"])+++ @pytest.mark.parametrize("options", [None, {"min_frequency_hz": 400.}, {"chunk_s": "bad"},+ {"chunk_s": 24., "overlap_s": 24.}])+ def test_invalid_operator_discovery_configuration_is_explicit(tmp_path, options):- from aircraft_geoloc.automatic import analyze++ from dopplergeist.automatic import analyze+ source = tmp_path/"unused.mp3"+ source.write_bytes(b"configuration must fail before decode")+ final = analyze({"schema_version": 1, "audio_path": str(source)}, tmp_path/"output",+ {"discovery": options})+ assert final["status"] == "failed"+ assert final["reason_code"] == "invalid_configuration"+ assert not (tmp_path/"output/intake").exists()+++ @pytest.mark.parametrize("flag,changes,complete", [+ (True, {}, True),+ (False, {"unsupported_cpa_track_evaluations": 1}, False),+ (False, {"unclassified_score_candidates": 2, "unknown_trials": 3}, False),+ (True, {"unknown_trials": 1}, False),+ (True, {"unknown_trials": False}, False),+ (True, {"unknown_trials": None}, False),+ (None, {}, False),+ ])+ def test_model_support_work_is_explicit_in_product_coverage(flag, changes, complete):- from aircraft_geoloc.automatic import _coverage++ from dopplergeist.automatic import _coverage+ support = {"unsupported_cpa_track_evaluations": 0, "unclassified_score_candidates": 0,+ "evaluated_trials": 4, "rejected_trials": 1, "unknown_trials": 0,+ "diagnostics_directory": "support", **changes}+ coverage = _coverage({"search": {"coverage": "conus"}},+ {"status": "complete", "tiles_total": 2, "tiles_completed": 2, "data_scope_complete": True,+ "model_support_complete": flag, "model_support": support}, {})+ assert coverage["search_complete"] is complete+ assert coverage["data_status"] == "available"+ assert any("Trajectory model" in item for item in coverage["limitations"]) is (not complete)+ if type(support["unknown_trials"]) is int and not complete:+ assert f'unknown clock trials: {support["unknown_trials"]}' in ' '.join(coverage["limitations"])+ elif not complete:+ assert "unavailable or malformed" in ' '.join(coverage["limitations"])+++ @pytest.mark.parametrize("missing", ["counters", "flag"])+ def test_missing_model_support_evidence_cannot_become_completed_work(missing):- from aircraft_geoloc.automatic import _coverage++ from dopplergeist.automatic import _coverage+ report = {"tiles_total": 1, "tiles_completed": 1, "data_scope_complete": True,+ "model_support_complete": True,+ "model_support": {"unsupported_cpa_track_evaluations": 0, "unclassified_score_candidates": 0,+ "evaluated_trials": 4, "rejected_trials": 1, "unknown_trials": 0}}+ report.pop("model_support" if missing == "counters" else "model_support_complete")+ coverage = _coverage({"search": {"coverage": "conus"}}, report, {})+ assert coverage["search_complete"] is False+ assert coverage["data_status"] == "available"+ assert "Trajectory model assessment is incomplete" in ' '.join(coverage["limitations"])+ if missing == "counters":+ assert "unavailable or malformed" in ' '.join(coverage["limitations"])diff --cc tests/test_automatic_finite.pyindex 0000000,bd0606d..36c215dmode 000000,100644..100644--- a/tests/test_automatic_finite.py+++ b/tests/test_automatic_finite.py@@@ -1,0 -1,97 +1,97 @@@+ """Finite-scope transport controls; producers are controlled, not location evidence."""+ from copy import deepcopy+ from types import SimpleNamespace++ import pytest+-from aircraft_geoloc import automatic, matching-from aircraft_geoloc.jobs import read_json++from dopplergeist import automatic, matching++from dopplergeist.jobs import read_json+++ @pytest.mark.parametrize("bad_core", [None, "partial_support", "missing_core", "missing_id", "near_cluster",+ "producer_unassessed_core", "missing_assessment_map", "malformed_assessment_map"])+ def test_finite_scope_assesses_supported_frozen_seeds_and_preserves_ids(tmp_path, monkeypatch, bad_core):+ events = [{"event_id": f"event-{i}", "start_s": i*100., "end_s": i*100.+20., "band_hz": [90., 200.],+ "ridge": [{"time_s": i*100.+t, "frequency_hz": 140.-t} for t in (0., 10., 20.)]} for i in range(2)]+ rows = []+ for identity, lat, score in (("mode-a", 40., -.1), ("mode-b", 41., -10.)):+ fit = {"score": score/2, "rmse_hz": abs(score/2), "support_fraction": 1.,+ "outlier_fraction": 0., "drift_at_bound": False}+ rows.append({"mode_id": identity, "lat": lat, "lon": -100., "score": score,+ "score_kind": "negative_robust_ridge_loss_hz", "flight_ids": ["a", "b"],+ "recording_start_time_s": 1790000000., "event_diagnostics": [dict(fit), dict(fit)]})+ if bad_core == "partial_support":+ rows[1]["event_diagnostics"][0]["support_fraction"] = .5+ elif bad_core == "missing_core":+ rows[1]["event_diagnostics"] = []+ elif bad_core == "missing_id":+ rows[1].pop("mode_id")+ elif bad_core == "near_cluster":+ rows[1].update(lat=40.001, score=-.2)+ rows[1]["event_diagnostics"] = [dict(fit, score=-.1) for fit in rows[1]["event_diagnostics"]]+ evidence = {"schema_version": 1, "scope": "evaluated_finite_grid", "complete": True,+ "score_kind": "negative_robust_ridge_loss_hz", "spacing_m": 1000., "refine_spacing_m": 100.,+ "max_event_groups": 2, "retained_modes": [{"mode_id": "mode-a", "score": -.1, "event_groups": 2},+ {"mode_id": "mode-b", "score": rows[1]["score"], "event_groups": 2}],+ "discarded_count": 0, "best_discarded_score": None, "pruning_accounted_for": True,+ "limitations": ["Evaluated points only; unperformed refinements and continuous space are not covered."]}+ search = {"ranked": rows, "status": "complete", "scoring_time_is_locked": True,+ "alternative_modes_exhaustively_assessed": False, "finite_search_evidence": evidence,+ "core_assessed_mode_ids": ["mode-a", "mode-b"]}+ if bad_core == "producer_unassessed_core":+ search["core_assessed_mode_ids"] = ["mode-a"]+ elif bad_core == "missing_assessment_map":+ search.pop("core_assessed_mode_ids")+ elif bad_core == "malformed_assessment_map":+ search["core_assessed_mode_ids"] = "mode-a"+ before = deepcopy(search)+ state = {"recording": {"time_window": {"start_utc": "2026-09-21T14:13:20Z", "end_utc": "2026-09-21T14:13:20Z", "source": "user"}},+ "coverage": {"search_complete": True, "data_status": "available", "limitations": []}}+ tracks = [SimpleNamespace(id=name, time=[0., 1.], altitude_basis=["ellipsoidal"]) for name in ("a", "b")]+ index = SimpleNamespace(query=lambda *args: tracks)+ # Deliberately omit mode_id in producer returns: the orchestrator must retain+ # the source seed identity without recomputing it from optimized coordinates.+ def refine(row, *args, **kwargs):+ return {key: value for key, value in row.items() if key != "mode_id"}+ def profile(row, *args, **kwargs):+ return dict(refine(row), sensitivity={"radius_m": 80., "kind": "sensitivity", "method": "declared_perturbation_profiles",+ "complete": True, "boundary_limited": False, "sources": ["frequency", "clock", "altitude", "sound_speed"],+ "settings": {"clock_bounds_s": [1790000000., 1790000000.]}})+ monkeypatch.setattr(matching, "refine_candidate", refine)+ monkeypatch.setattr(matching, "profile_candidate", profile)+ def finish(status, reason_code=None, message=None, **fields):+ return dict(status=status, reason_code=reason_code, **fields)+ final = automatic._decide(search, events, events, [None]*2, [index], None, state, tmp_path,+ {"refine_finalists": 1}, finish, lambda: None)+ receipt = read_json(tmp_path/"refined-candidates.json")+ diagnostics = receipt["matching_diagnostics"]+ assert search == before+ assert diagnostics["finite_search_evidence"] == evidence+ assert diagnostics["alternatives_evaluated"] is False+ assert diagnostics["unrefined_hypotheses"] == 1+ assert len(diagnostics["candidate_mode_ids"]) == len(final["candidates"])+ assert diagnostics["candidate_mode_ids"].count("mode-a") == 2+ if bad_core in (None, "near_cluster"):+ assert final["status"] == "succeeded", final+ assert diagnostics["assessed_mode_ids"] == ["mode-a", "mode-b"]+ decision = read_json(tmp_path/"decision.json")+ assert decision["diagnostics"]["finite_search"]["continuous_space_uniqueness"] == "not established"+ assert decision["candidates"] == final["candidates"]+ if bad_core == "near_cluster":+ uncertainty = final["candidates"][0]["uncertainty"]+ assert uncertainty["method"] == "finite_mode_and_tested_profile_union"+ assert 110. < uncertainty["radius_m"] < 112.+ assert final["candidates"][0]["lat"] == 40.+ assert final["candidates"][0]["score"] == -.1+ else:+ assert final["status"] == "inconclusive", final+ expected = [] if bad_core in ("missing_assessment_map", "malformed_assessment_map") else ["mode-a"]+ assert diagnostics["assessed_mode_ids"] == expected+++ def test_finite_scope_limitations_are_visible_in_coverage():+ limit = "Only evaluated parameter points, not continuous uniqueness."+ coverage = automatic._coverage({"search": {"coverage": "conus"}},+ {"tiles_total": 1, "tiles_completed": 1, "data_scope_complete": True,+ "finite_search_evidence": {"limitations": [limit]}}, {})+ assert limit in coverage["limitations"]diff --cc tests/test_automatic_profile.pyindex 0000000,30ce8c1..3b97b5fmode 000000,100644..100644--- a/tests/test_automatic_profile.py+++ b/tests/test_automatic_profile.py@@@ -1,0 -1,135 +1,135 @@@+ """Orchestration regressions for authoritative full-profile evidence.++ Physical producers are controlled here to isolate score roundoff and failures;+ the real candidate contracts, persisted receipts and confidence gates still run.+ """+ from copy import deepcopy+ from types import SimpleNamespace++ import pytest+-from aircraft_geoloc import automatic, matching-from aircraft_geoloc.jobs import read_json++from dopplergeist import automatic, matching++from dopplergeist.jobs import read_json+++ @pytest.fixture+ def run_profile(tmp_path, monkeypatch):+ events = [{"event_id": f"event-{i}", "start_s": i * 100., "end_s": i * 100. + 20,+ "band_hz": [90., 200.], "harmonic_group_id": f"group-{i}",+ "ridge": [{"time_s": i * 100. + t, "frequency_hz": 140. - t}+ for t in (0., 10., 20.)]} for i in range(2)]+ event_fit = {"rmse_hz": .1, "outlier_fraction": 0., "support_fraction": 1., "drift_at_bound": False}+ base = {"point_id": 23, "lat": 40., "lon": -100., "elev_m": 120.,+ "score": -.2720691034013313, "score_kind": "negative_robust_ridge_loss_hz",+ "recording_start_time_s": 1790000000., "flight_ids": ["a", "b"],+ "pass_emission_times_s": [1790000010., 1790000110.],+ "event_diagnostics": [dict(event_fit), dict(event_fit)]}+ # Keep another spatial mode for the same association and another association.+ raw = [base, dict(base, point_id=24, lat=41., score=-4.,+ pass_emission_times_s=[1790000030., 1790000130.]),+ dict(base, point_id=25, lat=42., score=-5., flight_ids=["c", "d"])]+ search = {"status": "complete", "scoring_time_is_locked": True,+ "alternative_modes_exhaustively_assessed": True, "ranked": raw}+ state = {"recording": {"time_window": {"start_utc": "2026-09-21T14:13:20Z",+ "end_utc": "2026-09-21T14:13:20Z", "source": "user"}},+ "coverage": {"search_complete": True, "data_status": "available", "limitations": []}}+ tracks = [SimpleNamespace(id=identity, time=[0., 1.], altitude_basis=["ellipsoidal"])+ for identity in ("a", "b", "c", "d")]+ index = SimpleNamespace(query=lambda bounds, time_range: tracks)++ def refine(candidate, *args, **kwargs):+ return dict(candidate, score=candidate["score"] + .1,+ sensitivity={"radius_m": 42.84, "method": "profiled_relative_altitude_offsets",+ "kind": "sensitivity", "complete": True, "boundary_limited": False})++ monkeypatch.setattr(matching, "refine_candidate", refine)++ def run(*, score_change=-2.99e-13, complete=True, error=None):+ before = deepcopy(search)++ def profile(candidate, *args, **kwargs):+ if error is not None:+ raise error+ failures = [] if complete else [{"source": "altitude", "scenario": "terrain",+ "reason": "Ellipsoidal terrain datum is not established"}]+ return dict(candidate, score=candidate["score"] + score_change,+ sensitivity={"radius_m": 42.83, "method": "declared_perturbation_profiles",+ "kind": "sensitivity", "complete": complete, "boundary_limited": False,+ "sources": ["frequency", "clock", "altitude", "sound_speed"],+ "failures": failures})++ monkeypatch.setattr(matching, "profile_candidate", profile)++ def finish(status, reason_code=None, message=None, **fields):+ return dict(status=status, reason_code=reason_code, message=message, **fields)++ final = automatic._decide(search, events, events, [None] * 2, [index], None,+ state, tmp_path, {"refine_finalists": 3}, finish, lambda: None)+ receipt = read_json(tmp_path / "refined-candidates.json")+ assert search == before+ # Replacing validation evidence must not remove another retained mode.+ for row in raw:+ assert row in receipt["ranked"]+ for point_id in (24, 25):+ assert any(row["point_id"] == point_id and "sensitivity" in row for row in receipt["ranked"])+ return final, receipt++ return run+++ def test_full_profile_replaces_nominal_despite_score_roundoff(run_profile):+ final, receipt = run_profile()+ assert final["status"] == "succeeded", final+ assert len(receipt["ranked"]) == 6+ assert final["candidates"][0]["uncertainty"]["method"] == "declared_perturbation_profiles"+ assert receipt["matching_diagnostics"]["sensitivity"] == receipt["ranked"][0]["sensitivity"]+++ @pytest.mark.parametrize("score_change", [-2.99e-13, 0.])+ def test_incomplete_full_profile_cannot_fall_back_to_complete_altitude_profile(run_profile, score_change):+ final, receipt = run_profile(score_change=score_change, complete=False)+ assert final["status"] == "inconclusive"+ assert final["reason_code"] == "uncertainty_not_established"+ assert "uncertainty" not in final["candidates"][0]+ assert len(receipt["ranked"]) == 6+ sensitivity = receipt["matching_diagnostics"]["sensitivity"]+ assert sensitivity["method"] == "declared_perturbation_profiles"+ assert sensitivity["complete"] is False+ assert sensitivity["failures"][0]["scenario"] == "terrain"+++ @pytest.mark.parametrize("error", [ValueError("Profile trajectory support is missing"), KeyError("profile input")])+ def test_profile_exception_invalidates_previous_uncertainty(run_profile, error):+ final, receipt = run_profile(error=error)+ assert final["status"] == "inconclusive"+ assert "uncertainty" not in final["candidates"][0]+ assert len(receipt["ranked"]) == 6+ diagnostics = receipt["matching_diagnostics"]+ assert diagnostics["sensitivity"]["complete"] is False+ assert not diagnostics["sensitivity"].get("sources")+ assert str(error) in diagnostics["sensitivity"]["failures"][0]["reason"]+ assert any(str(error) in failure for failure in diagnostics["refinement_failures"])+++ def test_reranking_does_not_transfer_full_profile_to_another_candidate(run_profile):+ final, receipt = run_profile(score_change=-1.)+ assert final["status"] == "inconclusive"+ assert final["reason_code"] == "uncertainty_not_established"+ assert not receipt["matching_diagnostics"]["sensitivity"].get("sources")+ assert any(row.get("sensitivity", {}).get("method") == "declared_perturbation_profiles"+ for row in receipt["ranked"][1:])+++ def test_decision_candidate_copy_is_preserved_for_evidence_derived_envelopes(run_profile, monkeypatch):- from aircraft_geoloc import confidence++ from dopplergeist import confidence+ original = confidence.decide_location+ def decision(events, candidates, coverage, **kwargs):+ result = original(events, candidates, coverage, **kwargs)+ returned = deepcopy(candidates)+ returned[0]["uncertainty"] = {"radius_m": 120., "method": "finite_modes_and_tested_profiles", "kind": "sensitivity"}+ result["candidates"] = returned+ return result+ monkeypatch.setattr(confidence, "decide_location", decision)+ final, _ = run_profile()+ assert final["candidates"][0]["uncertainty"]["radius_m"] == 120.+ assert final["candidates"][0]["uncertainty"]["method"] == "finite_modes_and_tested_profiles"diff --cc tests/test_decision_invariants.pyindex 0000000,189897f..16bb6edmode 000000,100644..100644--- a/tests/test_decision_invariants.py+++ b/tests/test_decision_invariants.py@@@ -1,0 -1,138 +1,138 @@@+ """Decision/refinement regression controls, not end-to-end acceptance evidence."""+ from copy import deepcopy+ from types import SimpleNamespace++ import numpy as np+ import pytest+ from pyproj import Geod, Transformer+-automatic = pytest.importorskip("aircraft_geoloc.automatic")-matching = pytest.importorskip("aircraft_geoloc.matching")-decide_location = pytest.importorskip("aircraft_geoloc.confidence").decide_location-from aircraft_geoloc.geometry import Track, ecef, straight_doppler++automatic = pytest.importorskip("dopplergeist.automatic")++matching = pytest.importorskip("dopplergeist.matching")++decide_location = pytest.importorskip("dopplergeist.confidence").decide_location++from dopplergeist.geometry import Track, ecef, straight_doppler+++ def _decision_evidence():+ events = [{"event_id": f"e{i}", "harmonic_group_id": f"g{i}",+ "start_s": i * 100, "end_s": i * 100 + 20, "band_hz": [90, 200],+ "ridge": [{"time_s": i * 100 + t, "frequency_hz": 140 - t}+ for t in (0, 10, 20)]} for i in range(2)]+ candidate = {"lat": 40., "lon": -100., "score": -1.,+ "score_kind": "negative_robust_ridge_loss_hz",+ "event_ids": ["e0", "e1"], "flight_ids": ["a", "b"],+ "recording_start_utc": "1970-01-01T00:00:00Z",+ "uncertainty": {"radius_m": 70., "kind": "sensitivity", "method": "unit_control"}}+ coverage = {"search_complete": True, "data_status": "available", "limitations": []}+ diagnostics = {"clock_locked": True, "alternatives_evaluated": True,+ "refinement_boundary_limited": False,+ "sensitivity": {"complete": True, "boundary_limited": False, "radius_m": 70.,+ "sources": ["frequency", "clock", "altitude", "sound_speed"]}}+ for event in events:+ diagnostics[event["event_id"]] = {"rmse_hz": 0.7, "outlier_fraction": 0.1,+ "support_fraction": 1., "drift_at_bound": False}+ return events, candidate, coverage, diagnostics+++ @pytest.mark.parametrize("separation_m", [90., 150.])+ def test_near_tied_mode_outside_returned_radius_cannot_be_supported(separation_m):+ events, best, coverage, diagnostics = _decision_evidence()+ assert decide_location(events, [best], coverage, matching_diagnostics=diagnostics)["status"] == "succeeded"+ alternative = deepcopy(best)+ alternative["lon"], alternative["lat"], _ = Geod(ellps="WGS84").fwd(+ best["lon"], best["lat"], 90., separation_m)+ alternative["score"] = -1.2 # A near tie under the declared per-event loss rule.+ result = decide_location(events, [best, alternative], coverage, matching_diagnostics=diagnostics)+ # 90 m escapes the returned 70 m radius; 150 m also exceeds the 100 m target.+ # The hook does not return a new center/radius, so it must abstain here.+ assert result["status"] == "inconclusive", (+ f"accepted a {best['uncertainty']['radius_m']} m envelope while retaining "+ f"a near-tied location {separation_m} m from its center: {result}"+ )+++ def _numerical_case():+ """Two nonparallel Cartesian flights with analytic Doppler observations."""+ observer = ecef(40., -100., 100.)+ inverse = Transformer.from_crs("EPSG:4978", "EPSG:4979", always_xy=True)+ tracks, events, prepared, measurements = {}, [], [], []+ for i, (center, f0, velocity, cross) in enumerate([+ (70., 120., [80., 0., 0.], [0., 1600., 800.]),+ (250., 160., [0., 80., 0.], [1700., 0., 1000.]),+ ]):+ identity = "ab"[i]+ times = np.arange(center - 120, center + 121, 2.)+ xyz = observer + (times - center)[:, None] * velocity + cross+ lon, lat, altitude = inverse.transform(*xyz.T)+ tracks[identity] = Track(identity, times, lat, lon, altitude,+ velocity=np.tile(velocity, (len(times), 1)))+ receive = np.arange(center - 30, center + 30, 2.)+ slant = np.linalg.norm(cross)+ ridge = straight_doppler(receive, f0, 80., slant, center + slant / 343.)+ event = {"event_id": f"e{i}", "harmonic_group_id": f"g{i}",+ "start_s": float(receive[0]), "end_s": float(receive[-1]), "band_hz": [50., 230.],+ "ridge": [{"time_s": float(t), "frequency_hz": float(f)}+ for t, f in zip(receive, ridge)]}+ events.append(event)+ prepared.append(dict(event, event_ids=[event["event_id"]],+ f0_range_hz=[f0 - 1, f0 + 1], quality={"source_drift_fraction": 0.}))+ measurements.append((matching.RidgeTimes(receive), ridge, np.ones(len(receive)), {}))+ terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.))+ seed = {"lat": 40.0002, "lon": -99.9998, "elev_m": 100.,+ "recording_start_time_s": 0., "flight_ids": ["a", "b"],+ "pass_emission_times_s": [70., 250.], "point_id": 0}+ return tracks, events, prepared, measurements, terrain, seed+++ def test_optimizer_exhaustion_cannot_establish_complete_sensitivity(monkeypatch):+ tracks, _, prepared, measurements, terrain, seed = _numerical_case()+ original_minimize, convergence = matching.minimize, []++ def exhausted_minimize(objective, initial, **kwargs):+ kwargs["options"] = dict(kwargs.get("options", {}), maxiter=0)+ result = original_minimize(objective, initial, **kwargs)+ convergence.append(bool(result.success))+ return result++ monkeypatch.setattr(matching, "minimize", exhausted_minimize)+ try:+ result = matching.refine_candidate(seed, tracks, prepared, measurements, terrain,+ recording_start_window_s=(0., 0.))+ except ValueError:+ # Explicit failure is acceptable after a real solver exhausts its budget.+ assert convergence and not all(convergence)+ return+ assert convergence and not all(convergence), "control must exercise actual nonconvergence"+ assert result["sensitivity"]["complete"] is not True, (+ "finite fallback profiles are not completed optimization evidence"+ )+++ def test_unrefined_distant_same_association_mode_is_not_fully_assessed(monkeypatch, tmp_path):+ tracks, events, prepared, measurements, terrain, seed = _numerical_case()+ raw = [dict(seed), dict(seed, lat=40.015, point_id=1)]+ for row in raw:+ row.update(matching.score_ridges(list(tracks.values()), prepared, measurements,+ ecef(row["lat"], row["lon"], 100.), 0.))+ raw.sort(key=lambda row: row["score"], reverse=True)+ artifacts, refined_modes = {}, set()+ original_refine = matching.refine_candidate++ def recorded_refine(candidate, *args, **kwargs):+ refined_modes.add((candidate["lat"], candidate["lon"]))+ return original_refine(candidate, *args, **kwargs)++ monkeypatch.setattr(matching, "refine_candidate", recorded_refine)+ monkeypatch.setattr(automatic, "write_json", lambda path, value: artifacts.__setitem__(path.name, deepcopy(value)))+ search = {"ranked": raw, "status": "complete", "scoring_time_is_locked": True}+ state = {"recording": {"time_window": {"start_utc": "1970-01-01T00:00:00Z",+ "end_utc": "1970-01-01T00:00:00Z"}},+ "coverage": {"search_complete": True, "data_status": "available", "limitations": []}}+ index = SimpleNamespace(query=lambda bounds, interval: list(tracks.values()))+ finish = lambda status, reason, message, **fields: {"status": status, "reason_code": reason, **fields}+ automatic._decide(search, events, prepared, measurements, [index], terrain,+ state, tmp_path, {"refine_finalists": 5}, finish, lambda: None)+ unrefined = {(row["lat"], row["lon"]) for row in raw} - refined_modes+ diagnostics = artifacts["refined-candidates.json"]["matching_diagnostics"]+ assert not unrefined or diagnostics["alternatives_evaluated"] is not True, (+ f"retained spatial modes were never refined but alternatives were certified: {unrefined}"+ )diff --cc tests/test_finite_bridge_independent.pyindex 0000000,cf8c98c..ff18682mode 000000,100644..100644--- a/tests/test_finite_bridge_independent.py+++ b/tests/test_finite_bridge_independent.py@@@ -1,0 -1,105 +1,105 @@@+ """Actual ledger -> product -> decision controls; no acoustic accuracy claim."""+ from copy import deepcopy+ import json+ import sqlite3+ import threading+ from urllib.request import urlopen++ import pytest+ from pyproj import Geod+-from aircraft_geoloc.automatic import _decide-from aircraft_geoloc.contracts import validate_result-from aircraft_geoloc.finite_search import RetentionLedger, classified_assessment-from aircraft_geoloc.jobs import JobManager-from aircraft_geoloc.service import JobServer-from aircraft_geoloc.tiled_search import merge_candidates++from dopplergeist.automatic import _decide++from dopplergeist.contracts import validate_result++from dopplergeist.finite_search import RetentionLedger, classified_assessment++from dopplergeist.jobs import JobManager++from dopplergeist.service import JobServer++from dopplergeist.tiled_search import merge_candidates+++ @pytest.mark.parametrize("case,reason", [+ ("complete", "supported_by_evidence_checks"),+ ("unassessed", "finite_modes_not_assessed"),+ ("near_discard", "retention_may_hide_alternatives"),+ ("corrupt", "finite_search_incomplete"),+ ])+ def test_actual_retention_evidence_survives_the_product_boundary(tmp_path, case, reason):+ events = [{"event_id": f"e{i}", "harmonic_group_id": f"g{i}",+ "start_s": i*100., "end_s": i*100.+20., "band_hz": [90., 200.],+ "ridge": [{"time_s": i*100.+t, "frequency_hz": 140.-t}+ for t in (0., 10., 20.)]} for i in range(2)]+ fit = {"score": -.5, "rmse_hz": .5, "outlier_fraction": 0.,+ "support_fraction": 1., "drift_at_bound": False}+ profile = {"complete": True, "boundary_limited": False, "radius_m": 70.,+ "method": "synthetic_complete_profile", "kind": "sensitivity",+ "sources": ["frequency", "clock", "altitude", "sound_speed"]}+ rows = []+ for distance, score in [(0., -1.), (90., -1.2), (2000., -1.3 if case == "near_discard" else -5.)]:+ lon, lat, _ = Geod(ellps="WGS84").fwd(-100., 40., 90., distance)+ row = {"x": distance, "y": 0., "lat": lat, "lon": lon, "elev_m": 10.,+ "recording_start_time_s": 1790000000., "flight_ids": ["a", "b"],+ "event_indices": [0, 1], "pass_emission_times_s": [1790000010., 1790000110.],+ "score": score, "score_kind": "negative_robust_ridge_loss_hz",+ "event_diagnostics": [dict(fit), dict(fit)], "sensitivity": deepcopy(profile),+ "scoring_assessment": {"complete": True, "evaluated_trials": 2,+ "rejected_trials": 1, "unknown_trials": 0, "reasons": []}}+ rows.append(row)+ ledger = RetentionLedger(tmp_path / "retention.sqlite", "independent-bridge", rows[0]["score_kind"])+ kept = merge_candidates(rows, 2, ledger=ledger, stage="coarse:0")+ kept = merge_candidates(kept, 2, ledger=ledger, stage="global:0")+ if case == "corrupt":+ with sqlite3.connect(ledger.path) as db:+ db.execute("DELETE FROM records WHERE score < -2")+ finite = ledger.evidence(kept, complete=True, spacing_m=1000., refine_spacing_m=100.,+ max_event_groups=2, expected_stages={"coarse": 1, "global": 1})+ if case == "unassessed":+ kept[1]["scoring_assessment"].update(complete=False, unknown_trials=1)+ assessed = [r["mode_id"] for r in kept if classified_assessment(r)]+ search = {"ranked": kept, "status": "complete", "scoring_time_is_locked": True,+ "alternative_modes_exhaustively_assessed": False,+ "finite_search_evidence": finite, "core_assessed_mode_ids": assessed}+ state = {"coverage": {"search_complete": True, "data_status": "available", "limitations": []},+ "recording": {"time_window": {"start_utc": "2026-09-21T14:13:20Z",+ "end_utc": "2026-09-21T14:13:20Z", "source": "user"}}}+ before = deepcopy(search)++ def finish(status, reason_code, message, **fields):+ return dict(status=status, reason_code=reason_code, message=message, **fields)++ # Profiles are controlled inputs. This tests the boundary, not their physical+ # generation; disabling refinement avoids substituting mocks for that work.+ job_id = "abb7afeffda8451ba9cb1bd6f8d95707"+ output = tmp_path / "jobs" / job_id+ output.mkdir(parents=True)+ result = _decide(search, events, events, [], [], None, state, output,+ {"refine_finalists": 0}, finish, lambda: None)+ artifact = json.loads((output / "decision.json").read_text())+ assert result["reason_code"] == reason+ assert result["status"] == ("succeeded" if case == "complete" else "inconclusive")+ assert artifact["candidates"] == result["candidates"]+ assert search == before+ if case == "complete":+ assert result["candidates"][0]["uncertainty"]["radius_m"] == pytest.approx(160.)+ assert result["candidates"][0]["uncertainty"]["method"] == "finite_mode_and_tested_profile_union"+ assert finite["discarded_count"] == 1+ assert finite["best_discarded_score"] == -5.+ assert result["candidates"][0]["lat"] == kept[0]["lat"]+ assert artifact["diagnostics"]["finite_search"]["continuous_space_uniqueness"] == "not established"+ wire = validate_result(dict(schema_version=1, job_id=job_id, status=result["status"],+ events=events, coverage=state["coverage"], candidates=result["candidates"],+ artifacts={"decision": "decision.json"}))+ (output / "result.json").write_text(json.dumps(wire))+ manager = JobManager(tmp_path / "jobs")+ server = JobServer(("127.0.0.1", 0), manager)+ thread = threading.Thread(target=server.serve_forever)+ thread.start()+ try:+ url = f"http://127.0.0.1:{server.server_port}/api/jobs/{job_id}"+ with urlopen(url) as response:+ assert json.load(response) == wire+ with urlopen(url+"/artifacts/decision.json") as response:+ assert json.load(response) == artifact+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+ manager.close()diff --cc tests/test_finite_evidence_independent.pyindex 0000000,6d87d47..9f05102mode 000000,100644..100644--- a/tests/test_finite_evidence_independent.py+++ b/tests/test_finite_evidence_independent.py@@@ -1,0 -1,121 +1,121 @@@+ """Independent decision-contract controls; these do not simulate a national run."""+ from copy import deepcopy+-from aircraft_geoloc.confidence import decide_location++from dopplergeist.confidence import decide_location+++ def bundle():+ events = [+ {"event_id": f"event-{i}", "start_s": 100.0*i, "end_s": 100.0*i+20.0,+ "band_hz": [90.0, 200.0], "harmonic_group_id": f"flyover-{i}",+ "ridge": [{"time_s": 100.0*i+t, "frequency_hz": 160.0-t}+ for t in (0.0, 10.0, 20.0)]}+ for i in range(2)+ ]+ candidates = [{"lat": 40.0, "lon": -100.0, "score": 1.8,+ "score_kind": "matched_group_support_minus_normalized_residual",+ "event_ids": ["event-0", "event-1"], "flight_ids": ["a", "b"],+ "recording_start_utc": "2026-09-21T14:13:20Z",+ "uncertainty": {"kind": "sensitivity", "radius_m": 100.0,+ "method": "independent_contract_control"}}]+ coverage = {"search_complete": True, "data_status": "available",+ "limitations": ["This is a decision-only control."]}+ diagnostics = {"clock_locked": True, "alternatives_evaluated": False,+ "refinement_boundary_limited": False,+ "sensitivity": {"complete": True, "boundary_limited": False,+ "radius_m": 100.0,+ "sources": ["frequency", "clock", "altitude", "sound_speed"]},+ "assessed_mode_ids": ["seed-a"], "candidate_mode_ids": ["seed-a"],+ "finite_search_evidence": {+ "schema_version": 1, "scope": "evaluated_finite_grid", "complete": True,+ "score_kind": candidates[0]["score_kind"],+ "spacing_m": 1000.0, "refine_spacing_m": 100.0,+ "max_event_groups": 2,+ "retained_modes": [{"mode_id": "seed-a", "score": 1.8, "event_groups": 2}],+ "discarded_count": 0, "best_discarded_score": None,+ "pruning_accounted_for": True,+ "limitations": ["Only declared evaluated finite points are compared."]}}+ for event in events:+ diagnostics[event["event_id"]] = {"rmse_hz": 0.2, "outlier_fraction": 0.0,+ "support_fraction": 1.0, "drift_at_bound": False}+ return events, candidates, coverage, diagnostics+++ def decide(case):+ return decide_location(*case[:3], matching_diagnostics=case[3])+++ def test_refinement_improvement_does_not_rewrite_immutable_seed_evidence():+ case = bundle()+ original = deepcopy(case[1][0])+ case[1][0]["score"] = 1.95+ case[1].append(original)+ case[3]["candidate_mode_ids"].append("seed-a")+ before = deepcopy(case)+ assert decide(case)["status"] == "succeeded"+ assert case == before+ assert case[3]["finite_search_evidence"]["retained_modes"][0]["score"] == 1.8+++ def test_a_worse_refinement_cannot_erase_the_better_original_seed():+ case = bundle()+ case[1][0]["score"] = 1.6+ assert decide(case)["reason_code"] == "finite_candidate_scores_inconsistent"+++ def test_full_finite_accounting_does_not_hide_same_association_distant_mode():+ case = bundle()+ alternative = dict(case[1][0], lat=45.0, score=1.7)+ case[1].append(alternative)+ case[3]["candidate_mode_ids"].append("seed-b")+ case[3]["assessed_mode_ids"].append("seed-b")+ case[3]["finite_search_evidence"]["retained_modes"].append(+ {"mode_id": "seed-b", "score": 1.7, "event_groups": 2})+ result = decide(case)+ assert result["status"] == "inconclusive"+ assert result["reason_code"] == "ambiguous_locations"+++ def test_global_group_bound_is_used_for_a_potentially_larger_discarded_subset():+ case = bundle()+ for i in range(2, 6):+ event = deepcopy(case[0][0])+ event.update(event_id=f"event-{i}", harmonic_group_id=f"flyover-{i}",+ start_s=100.0*i, end_s=100.0*i+20.0)+ for point in event["ridge"]:+ point["time_s"] += 100.0*i+ case[0].append(event)+ case[3]["unmatched_event_ids"] = [f"event-{i}" for i in range(2, 6)]+ finite = case[3]["finite_search_evidence"]+ finite.update(max_event_groups=6, discarded_count=1, best_discarded_score=0.9)+ # 0.9/2 would pass, but 0.9/6 cannot exclude a six-group competitor.+ assert decide(case)["reason_code"] == "retention_may_hide_alternatives"+++ def test_exact_declared_discard_margin_remains_competitive():+ case = bundle()+ finite = case[3]["finite_search_evidence"]+ finite.update(discarded_count=1, best_discarded_score=1.4)+ # The declared real-valued gap is (1.8-1.4)/2 == 0.2. Rounding cannot+ # promote equality across the existing strict-more-than retention gate.+ result = decide(case)+ assert result["status"] == "inconclusive"+ assert result["reason_code"] == "retention_may_hide_alternatives"+++ def test_a_resolved_discard_margin_remains_distinct_from_equality():+ case = bundle()+ case[3]["finite_search_evidence"].update(discarded_count=1, best_discarded_score=1.399999)+ assert decide(case)["status"] == "succeeded"+++ def test_exact_declared_retained_margin_remains_competitive():+ case = bundle()+ case[1].append(dict(case[1][0], lat=45.0, score=1.4))+ case[3]["candidate_mode_ids"].append("seed-b")+ case[3]["assessed_mode_ids"].append("seed-b")+ case[3]["finite_search_evidence"]["retained_modes"].append(+ {"mode_id": "seed-b", "score": 1.4, "event_groups": 2})+ result = decide(case)+ assert result["status"] == "inconclusive"+ assert result["reason_code"] == "ambiguous_locations"diff --cc tests/test_motion_support.pyindex 0000000,aa8bbd6..dd9a53emode 000000,100644..100644--- a/tests/test_motion_support.py+++ b/tests/test_motion_support.py@@@ -1,0 -1,148 +1,148 @@@+ """Physical model boundary controls independent of acoustic-fit success."""+ from types import SimpleNamespace++ import numpy as np+ import pandas as pd+ import pytest+ from pyproj import Transformer+-from aircraft_geoloc.geometry import AcousticSupportError, Track, ecef-from aircraft_geoloc.matching import RidgeTimes-from aircraft_geoloc.search import score_candidate-from aircraft_geoloc.search import cpa_table, cpa_table_dense++from dopplergeist.geometry import AcousticSupportError, Track, ecef++from dopplergeist.matching import RidgeTimes++from dopplergeist.search import score_candidate++from dopplergeist.search import cpa_table, cpa_table_dense+++ def side_view(displacement=1000):+ """Zero knot velocities hide a 1.5*displacement/2 interior peak."""+ observer = ecef(40, -100, 100)+ lat, lon = np.deg2rad([40, -100])+ east = np.array([-np.sin(lon), np.cos(lon), 0])+ north = np.array([-np.sin(lat)*np.cos(lon), -np.sin(lat)*np.sin(lon), np.cos(lat)])+ up = np.array([np.cos(lat)*np.cos(lon), np.cos(lat)*np.sin(lon), np.sin(lat)])+ x = np.array([-displacement/2-160, -displacement/2, displacement/2, displacement/2+160])+ positions = observer + x[:, None]*east + 2000*north + 1000*up+ longitude, latitude, height = Transformer.from_crs(4978, 4979, always_xy=True).transform(*positions.T)+ track = Track("side-view", [-2, 0, 2, 4], latitude, longitude, height,+ velocity=np.array([80, 0, 0, 80])[:, None]*east)+ emitted = np.linspace(.1, 1.9, 37)+ u = emitted/2+ source_x = -displacement/2 + displacement*(3*u**2-2*u**3)+ speed = 3*displacement*u*(1-u)+ distance = np.sqrt(source_x**2+2000**2+1000**2)+ received = emitted + distance/343+ factor = 343/(343+source_x*speed/distance)+ return track, observer, emitted, received, factor+++ def test_side_view_cannot_certify_unphysical_interior_motion():+ track, observer, emitted, received, factor = side_view()+ assert np.linalg.norm(track.speed_vector(1)) == pytest.approx(750)+ # Arrival remains strictly monotone, so the old radial guard accepts it.+ assert np.all(np.diff(received) > 0)+ assert np.all(np.isfinite(factor))+ with pytest.raises(AcousticSupportError) as failure:+ track.acoustic(received, observer)+ assert failure.value.reason == "non_subsonic_motion"+ assert failure.value.emission_intervals_s == [[0., 2.]]+++ def test_unsupported_motion_is_unknown_even_when_ridge_matches_its_formula():+ track, _, _, received, factor = side_view()+ point = SimpleNamespace(point_id=0, lat=40, lon=-100, elev_m=100, x=0, y=0)+ candidate = {"passes": [{"flight_id": track.id, "receive_time": 7.5}], "event_indices": [0]}+ event = {"event_id": "automatic-proposal", "cpa_receive_s": 7.5,+ "f0_range_hz": [119, 121], "quality": {"source_drift_fraction": 0}}+ measurement = (RidgeTimes(received), 120*factor, np.ones_like(factor), {})+ result = score_candidate(candidate, point, {track.id: track}, [event], [measurement],+ mode="robust_ridge", time_origin=0, time_sweep_s=0)+ assert result["score"] == -np.inf+ assert not result["scoring_assessment"]["complete"]+ assert result["scoring_assessment"]["unknown_trials"] > 0+ assert result["scoring_assessment"]["rejected_trials"] == 0+++ def test_subsonic_control_retains_original_emission_time_solution():+ track, observer, emitted, received, factor = side_view(400)+ actual, solved, _ = track.acoustic(received, observer)+ np.testing.assert_allclose(actual, factor, atol=1e-10)+ np.testing.assert_allclose(solved, emitted, atol=1e-9)+++ def test_invalid_remote_interval_does_not_erase_clean_emission_support():+ track, observer, _, _, _ = side_view()+ # Add a later stationary segment, well separated in emission/arrival time.+ xyz = np.vstack([track.xyz, track.xyz[-1], track.xyz[-1]])+ lon, lat, height = Transformer.from_crs(4978, 4979, always_xy=True).transform(*xyz.T)+ velocities = np.vstack([track.speed_vector(track.time), np.zeros((2, 3))])+ extended = Track("separated", [-2, 0, 2, 4, 30, 60], lat, lon, height, velocity=velocities)+ emitted = np.linspace(40, 50, 21)+ distance = np.linalg.norm(xyz[-1]-observer)+ factor, solved, _ = extended.acoustic(emitted+distance/343, observer)+ np.testing.assert_allclose(factor, 1, atol=1e-12)+ np.testing.assert_allclose(solved, emitted, atol=1e-9)+++ @pytest.mark.parametrize("table", [cpa_table, cpa_table_dense])+ def test_actual_unsupported_track_reaches_cpa_typed_boundary(table):+ bad, _, _, _, _ = side_view()+ clean, _, _, _, _ = side_view(400)+ points = pd.DataFrame({"point_id": [0], "lat": [40], "lon": [-100], "elev_m": [100]})+ assert len(table([clean], points, 5000, step_s=.25)) == 1+ with pytest.raises(AcousticSupportError) as failure:+ table([bad], points, 5000, step_s=.25)+ assert failure.value.track_id == bad.id+ assert failure.value.emission_intervals_s == [[0., 2.]]+ assert failure.value.receive_intervals_s is None+++ def test_sound_speed_profile_reuses_extrema_but_rechecks_physical_boundary():+ track, observer, _, received, _ = side_view(400)+ track.acoustic(received, observer)+ with pytest.raises(AcousticSupportError, match="non_subsonic_motion"):+ track.validate_motion_support(c=290)+ track.validate_motion_support(c=343)+++ def test_conservative_arrival_box_contains_all_unsupported_interval_arrivals():+ track, observer, _, received, _ = side_view()+ with pytest.raises(AcousticSupportError) as failure:+ track.acoustic(received, observer)+ emitted = np.linspace(0, 2, 1001)+ actual = emitted+np.linalg.norm(track.position(emitted)-observer, axis=1)/343+ lo, hi = failure.value.receive_intervals_s[0]+ assert lo <= actual.min() <= actual.max() <= hi+++ def test_continuous_speed_extrema_cover_independent_dense_spline_oracle():+ rng = np.random.default_rng(640311)+ inverse = Transformer.from_crs(4978, 4979, always_xy=True)+ observer = ecef(40, -100, 100)+ for _ in range(25):+ time = np.array([0., rng.uniform(.2, 5), rng.uniform(6, 10)])+ positions = observer+rng.normal(size=(3, 3))*1000+ velocities = rng.normal(size=(3, 3))*150+ lon, lat, height = inverse.transform(*positions.T)+ track = Track("oracle", time, lat, lon, height, velocity=velocities)+ track._unsupported_motion_intervals(c=1e-6)+ for i in range(2):+ sample = np.linspace(time[i], time[i+1], 8193)+ peak = np.linalg.norm(track.speed_vector(sample), axis=1).max()+ assert track._speed_peak[i] >= peak-1e-7+ assert track._speed_peak[i]-peak <= 1e-5*max(1, peak)+++ def test_finite_newton_iterate_is_not_accepted_as_a_converged_emission_solution():+ # A genuinely subsonic straight path has a unique analytic emission time.+ # Close to c, the old ten-iteration result can be ~293 s from that time.+ observer = ecef(40, -100, 100)+ speed, slant = 342.9999, 100.+ knots = np.array([-1000., 0., 1000.])+ xyz = observer+np.column_stack((speed*knots, np.full(3, slant), np.zeros(3)))+ lon, lat, height = Transformer.from_crs(4978, 4979, always_xy=True).transform(*xyz.T)+ track = Track("near-sonic", knots, lat, lon, height, velocity=np.tile([speed, 0, 0], (3, 1)))+ track.validate_motion_support()+ emitted = np.linspace(-990, 990, 1001)+ received = emitted+np.hypot(speed*emitted, slant)/343+ with pytest.raises(AcousticSupportError) as failure:+ track.acoustic(received, observer)+ assert failure.value.reason == "emission_solver_not_converged"diff --cc tests/test_service.pyindex 0000000,dcc6e9e..246de82mode 000000,100644..100644--- a/tests/test_service.py+++ b/tests/test_service.py@@@ -1,0 -1,124 +1,124 @@@+ """Transport/lifecycle checks. Scientific end-to-end checks live separately."""+ from contextlib import contextmanager+ import io+ import json+ from pathlib import Path+ import threading+ import urllib.error+ import urllib.request++ import pytest+-from aircraft_geoloc.jobs import JobManager, read_json, result-from aircraft_geoloc.service import JobServer++from dopplergeist.jobs import JobManager, read_json, result++from dopplergeist.service import JobServer+++ @contextmanager+ def running_server(tmp_path, monkeypatch):+ # Hold queued analyses to test HTTP and persistence independently of DSP.+ monkeypatch.setattr(JobManager, "_run", lambda self, directory: None)+ manager = JobManager(tmp_path)+ server = JobServer(("127.0.0.1", 0), manager)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield manager, f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ manager.close()+ thread.join()+++ def request(url, data=None, metadata=None, **headers):+ if metadata is not None:+ headers.update({"Content-Type": "application/octet-stream", "X-Dopplergeist-Request": json.dumps(metadata)})+ req = urllib.request.Request(url, data=data, headers=headers)+ with urllib.request.urlopen(req, timeout=5) as response:+ body = response.read()+ return response.status, json.loads(body) if response.headers.get_content_type() == "application/json" else body+++ def test_upload_readback_cancel_and_original_preservation(tmp_path, monkeypatch):+ with running_server(tmp_path, monkeypatch) as (manager, url):+ code, job = request(url + "/api/jobs", b"encoded audio payload", {"schema_version": 1})+ assert code == 202 and job["status"] == "queued"+ job_id = job["job_id"]+ assert request(url + f"/api/jobs/{job_id}")[1] == job+ assert request(url + f"/api/jobs/{job_id}/cancel", b"")[1]["status"] == "cancelled"+ assert request(url + f"/api/jobs/{job_id}/artifacts/input.mp3")[1] == b"encoded audio payload"+ items = request(url + f"/api/jobs/{job_id}/artifacts")[1]["artifacts"]+ assert "input.json" in [p["path"] for p in items]+ assert "operator.json" not in [p["path"] for p in items]+ restarted = JobManager(tmp_path)+ try:+ assert restarted.get(job_id)["status"] == "cancelled"+ assert (restarted.directory(job_id) / "input.mp3").read_bytes() == b"encoded audio payload"+ finally:+ restarted.close()+++ def test_terminal_result_survives_restart_and_interrupted_job_is_explicit(tmp_path, monkeypatch):+ monkeypatch.setattr(JobManager, "_run", lambda self, directory: None)+ manager = JobManager(tmp_path)+ complete = manager.submit({"schema_version": 1}, io.BytesIO(b"first"), 5)+ result(manager.directory(complete["job_id"]), "inconclusive", reason_code="no_events", message="No events.")+ pending = manager.submit({"schema_version": 1}, io.BytesIO(b"second"), 6)+ manager.close()+ # Simulate abrupt shutdown rather than the normal graceful cancellation.+ result(tmp_path / pending["job_id"], "running", stage="search")+ restarted = JobManager(tmp_path)+ try:+ assert restarted.get(complete["job_id"])["reason_code"] == "no_events"+ assert restarted.get(pending["job_id"])["reason_code"] == "interrupted"+ assert (tmp_path / complete["job_id"] / "input.mp3").read_bytes() == b"first"+ finally:+ restarted.close()+++ def test_request_validation_upload_limits_and_paths(tmp_path, monkeypatch):+ with running_server(tmp_path, monkeypatch) as (manager, url):+ for metadata in ({"schema_version": 1, "events": []}, {"schema_version": 1, "audio_path": "/etc/passwd"},+ {"schema_version": 1, "discovery": {"chunk_s": 24., "overlap_s": 16.}}):+ with pytest.raises(urllib.error.HTTPError) as error:+ request(url + "/api/jobs", b"x", metadata)+ assert error.value.code == 400+ with pytest.raises(ValueError):+ manager.submit({"schema_version": 1}, io.BytesIO(b"x"), manager.max_upload_bytes + 1)+ job = request(url + "/api/jobs", b"x", {"schema_version": 1})[1]+ for suffix in ("operator.json", "%2e%2e/%2e%2e/.manager.lock", "%2Fetc%2Fpasswd"):+ with pytest.raises(urllib.error.HTTPError) as error:+ request(url + f"/api/jobs/{job['job_id']}/artifacts/" + suffix)+ assert error.value.code == 404+ with pytest.raises(urllib.error.HTTPError) as error:+ request(url + "/api/jobs", b"x", {"schema_version": 1}, Origin="https://unrelated.example")+ assert error.value.code == 403+ assert b"DOPPLERGEIST" in request(url + "/")[1]+ assert b"upload-form" in request(url + "/app.js")[1]+++ def test_lock_and_queued_cancellation(tmp_path):+ manager = JobManager(tmp_path)+ manager._serial.acquire()+ try:+ with pytest.raises(ValueError, match="Another job manager"):+ JobManager(tmp_path)+ queued = manager.submit({"schema_version": 1}, io.BytesIO(b"x"), 1)+ assert manager.cancel(queued["job_id"])["status"] == "cancelled"+ finally:+ manager._serial.release()+ manager.close()+++ def test_analysis_wall_time_budget_is_terminal_and_persistent(tmp_path):+ # A real subprocess is stopped before importing the scientific stack. This+ # tests resource/lifecycle enforcement, not a simulated search result.+ manager = JobManager(tmp_path, max_runtime_s=0.001)+ try:+ job = manager.submit({"schema_version": 1}, io.BytesIO(b"x"), 1)+ final = manager.wait(job["job_id"])+ assert final["status"] == "inconclusive" and final["reason_code"] == "work_limit"+ assert manager.get(job["job_id"]) == final+ assert not manager._processes+ finally:+ manager.close()diff --cc tests/test_tiled_support.pyindex 0000000,52d0cf9..558d120mode 000000,100644..100644--- a/tests/test_tiled_support.py+++ b/tests/test_tiled_support.py@@@ -1,0 -1,189 +1,189 @@@+ import json++ import numpy as np+ import pandas as pd+ import pytest+ from pyproj import Transformer+-from aircraft_geoloc import tiled_search-from aircraft_geoloc.data_access import FlightIndex-from aircraft_geoloc.geometry import AcousticSupportError, Track-from aircraft_geoloc.terrain import Terrain-from aircraft_geoloc.tiled_search import SearchBudget, _score, search_national, tile_points++from dopplergeist import tiled_search++from dopplergeist.data_access import FlightIndex++from dopplergeist.geometry import AcousticSupportError, Track++from dopplergeist.terrain import Terrain++from dopplergeist.tiled_search import SearchBudget, _score, search_national, tile_points+ from test_tiled_search import compact, scenario+++ def with_bad_copy(tmp_path):+ index, tracks, events, measurements, bounds, times, origin = scenario(tmp_path)+ first = tracks[0]+ bad = Track("unsupported-source", first.time, first.lat, first.lon, first.altitude)+ frames = [pd.DataFrame({"flight_id": t.id, "time_s": t.time, "lat": t.lat, "lon": t.lon,+ "alt_m": t.altitude, "altitude_basis": "ellipsoidal"}) for t in tracks + [bad]]+ mixed = FlightIndex.build(tmp_path / "mixed.sqlite", frames, sources=[], coverage=index.report["coverage"])+ return index, mixed, tracks, bad, events, measurements, bounds, times, origin+++ def test_typed_legacy_candidate_failure_preserves_clean_rows_and_resume_diagnostics(tmp_path, monkeypatch):+ index, mixed, _, _, events, measurements, bounds, times, origin = with_bad_copy(tmp_path)+ settings = {"mode": "ridge", "time_origin": origin, "time_sweep_s": 0}+ budget = SearchBudget(spacing_m=1000, tile_cells=4, refine_spacing_m=1000)+ kwargs = dict(time_range_s=times, bounds=bounds, budget=budget, scoring=settings)+ clean = search_national([index], Terrain(constant_m=0), events, measurements,+ output_dir=tmp_path / "clean", **kwargs)+ acoustic = Track.acoustic++ def guarded(self, *args, **kwargs):+ if self.id == "unsupported-source":+ raise AcousticSupportError(self.id, "non_monotone_arrival")+ return acoustic(self, *args, **kwargs)++ monkeypatch.setattr(Track, "acoustic", guarded)+ output = tmp_path / "mixed-search"+ result = search_national([mixed], Terrain(constant_m=0), events, measurements, output_dir=output, **kwargs)+ assert compact(result["ranked"]) == compact(clean["ranked"])+ assert result["tiles_completed"] == result["tiles_total"] and not result["tile_failures"]+ assert result["data_scope_complete"] and not result["model_support_complete"]+ assert result["status"] == "partial" and not result["finite_search_evidence"]["complete"]+ assert result["finite_search_evidence"]["best_discarded_score"] is None+ assert result["model_support"]["unclassified_score_candidates"] > 0+ assert result["model_support"]["unreported_trial_envelopes"] > 0+ diagnostics = [json.loads(p.read_text()) for p in (output / "support").glob("*.json")]+ failed = [r for d in diagnostics for r in d["unclassified_candidate_assessments"]]+ assert failed and all(r["support_failure"] == {"track_id": "unsupported-source", "reason": "non_monotone_arrival"}+ for r in failed)+ assert all("unsupported-source" in r["flight_ids"] for r in failed)+ assert any(t.id == "unsupported-source" for t in mixed.query(bounds, times)), "Source is retained unchanged"+ replay = search_national([mixed], Terrain(constant_m=0), events, measurements, output_dir=output, **kwargs)+ assert replay["tiles_resumed"] == replay["tiles_total"]+ assert replay["model_support"] == result["model_support"]+ assert compact(replay["ranked"]) == compact(result["ranked"])+++ def test_cpa_support_failure_records_conservative_whole_track_loss_and_keeps_other_tracks(tmp_path, monkeypatch):+ _, _, tracks, bad, events, measurements, bounds, _, origin = with_bad_copy(tmp_path)+ points = tile_points((0, 1900, 2, 1901), 1000, bounds, Terrain(constant_m=0), "EPSG:5070")+ settings = {"mode": "ridge", "time_origin": origin, "time_sweep_s": 0}+ budget = SearchBudget(max_cpa_rows=200)+ expected, expected_counts = _score(points, tracks, events, measurements, budget, settings, {})+ original = tiled_search.cpa_table+ calls = 0++ def guarded(selected, *args, **kwargs):+ nonlocal calls+ if selected[0].id == bad.id:+ calls += 1+ if calls > 1:+ raise AcousticSupportError(bad.id, "non_monotone_arrival")+ return original(selected, *args, **kwargs)++ monkeypatch.setattr(tiled_search, "cpa_table", guarded)+ ranked, counts = _score(points, [bad]+tracks, events, measurements, budget, settings, {})+ assert compact(ranked) == compact(expected) and ranked+ assert counts["cpa_rows"] == expected_counts["cpa_rows"], "Partial rows from failed source are not counted as covered"+ failure, = counts["unsupported_cpa_tracks"]+ assert failure["track_id"] == bad.id and failure["reason"] == "non_monotone_arrival"+ assert failure["emission_time_range_s"] == [bad.time[0], bad.time[-1]]+ assert failure["receiver_point_count"] == len(points)+ assert failure["coverage_envelope"] == "whole_track_whole_stage_conservative"+ empty, counts = _score(points, [bad], events, measurements, budget, settings, {})+ assert not empty and len(counts["unsupported_cpa_tracks"]) == 1+++ def test_all_unsupported_cpa_sources_return_empty_partial_search_with_diagnostics(tmp_path, monkeypatch):+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)++ def unsupported(tracks, *args, **kwargs):+ raise AcousticSupportError(tracks[0].id, "non_monotone_arrival")++ monkeypatch.setattr(tiled_search, "cpa_table", unsupported)+ output = tmp_path / "all-unsupported"+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,+ output_dir=output, bounds=bounds, budget=SearchBudget(spacing_m=1000, tile_cells=4, refine_spacing_m=1000),+ scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})+ assert not result["ranked"] and result["status"] == "partial"+ assert result["tiles_completed"] == result["tiles_total"] and not result["tile_failures"]+ assert result["data_scope_complete"] and not result["model_support_complete"]+ assert result["model_support"]["unsupported_cpa_track_evaluations"] > 0+ assert not result["finite_search_evidence"]["complete"]+ assert list((output / "support").glob("coarse-*.json"))+++ def test_actual_classified_robust_scorer_supplies_finite_core_ids(tmp_path):+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,+ output_dir=tmp_path / "classified", bounds=bounds,+ budget=SearchBudget(spacing_m=1000, tile_cells=4, top_k=2, refine_spacing_m=1000),+ scoring={"mode": "robust_ridge", "recording_start_window_s": [origin, origin], "time_sweep_s": 0})+ assert result["ranked"] and result["status"] == "complete" and result["model_support_complete"]+ assert result["finite_search_evidence"]["complete"]+ assert result["core_assessed_mode_ids"] == [r["mode_id"] for r in result["ranked"]]+ assert result["model_support"]["evaluated_trials"] > 0+ assert result["model_support"]["unknown_trials"] == result["model_support"]["unreported_trial_envelopes"] == 0+++ def test_real_interior_supersonic_track_is_partial_before_cpa_filters_and_preserves_clean_rows(tmp_path):+ index, tracks, events, measurements, bounds, times, origin = scenario(tmp_path)+ inverse = Transformer.from_crs("EPSG:5070", "EPSG:4326", always_xy=True)+ lon, lat = inverse.transform([-1000., 0., 1000.], [1900000.]*3)+ # Measured zero knot motion hides an interior Hermite speed > 700 m/s.+ bad = pd.DataFrame({"flight_id": "actual-invalid-observations", "time_s": origin+np.array([149., 151., 153.]),+ "lat": lat, "lon": lon, "alt_m": 1200., "altitude_basis": "ellipsoidal",+ "east_mps": 0., "north_mps": 0., "up_mps": 0.})+ frames = [pd.DataFrame({"flight_id": t.id, "time_s": t.time, "lat": t.lat, "lon": t.lon,+ "alt_m": t.altitude, "altitude_basis": "ellipsoidal"}) for t in tracks]+ mixed = FlightIndex.build(tmp_path / "actual-mixed.sqlite", frames+[bad], sources=[], coverage=index.report["coverage"])+ raw = next(t for t in mixed.query(bounds, times) if t.id == "actual-invalid-observations")+ assert np.max(np.linalg.norm(raw.speed_vector(raw.time), axis=1)) == 0+ assert np.linalg.norm(raw.speed_vector(origin+150)) > 700+ kwargs = dict(time_range_s=times, bounds=bounds,+ budget=SearchBudget(spacing_m=1000, tile_cells=4, refine_spacing_m=1000),+ scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})+ clean = search_national([index], Terrain(constant_m=0), events, measurements,+ output_dir=tmp_path / "actual-clean", **kwargs)+ output = tmp_path / "actual-mixed"+ result = search_national([mixed], Terrain(constant_m=0), events, measurements, output_dir=output, **kwargs)+ assert compact(result["ranked"]) == compact(clean["ranked"])+ assert result["status"] == "partial" and not result["model_support_complete"]+ assert result["data_scope_complete"] and not result["tile_failures"]+ assert result["model_support"]["unsupported_cpa_track_evaluations"] > 0+ assert not result["finite_search_evidence"]["complete"]+ failures = [f for p in (output / "support").glob("*.json")+ for f in json.loads(p.read_text())["unsupported_cpa_tracks"]]+ assert failures and all(f["track_id"] == raw.id and f["reason"] == "non_subsonic_motion" for f in failures)+ assert all(f["emission_time_range_s"] == [raw.time[0], raw.time[-1]] for f in failures)+ assert all(f["reported_intervals"]["emission_intervals_s"] for f in failures)+ assert all("receive_intervals_s" not in f["reported_intervals"] for f in failures)+++ def test_cpa_programming_error_is_not_relabelled_as_source_support(tmp_path, monkeypatch):+ _, tracks, events, measurements, bounds, _, origin = scenario(tmp_path)+ points = tile_points((0, 1900, 1, 1901), 1000, bounds, Terrain(constant_m=0), "EPSG:5070")++ def broken(*args, **kwargs):+ raise ValueError("configuration defect")++ monkeypatch.setattr(tiled_search, "cpa_table", broken)+ with pytest.raises(ValueError, match="configuration defect"):+ _score(points, tracks, events, measurements, SearchBudget(), {"mode": "ridge", "time_origin": origin}, {})+++ def test_refinement_support_loss_is_persisted_and_cannot_be_complete(tmp_path, monkeypatch):+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)+ original = tiled_search._score++ def fine_failure(*args, **kwargs):+ rows, counts = original(*args, **kwargs)+ if kwargs.get("stage", "").startswith("fine:"):+ counts["unsupported_cpa_tracks"] = [{"track_id": "unknown-fine-competitor", "reason": "non_monotone_arrival"}]+ return rows, counts++ monkeypatch.setattr(tiled_search, "_score", fine_failure)+ output = tmp_path / "fine"+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,+ output_dir=output, bounds=bounds, budget=SearchBudget(spacing_m=1000, tile_cells=4,+ refine_spacing_m=500, refine_finalists=1), scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})+ assert result["ranked"] and result["refinement_points_searched"] > 0+ assert result["status"] == "partial" and not result["model_support_complete"]+ assert result["model_support"]["unsupported_cpa_track_evaluations"] > 0+ assert list((output / "support").glob("fine-*.json"))+ assert result["finite_search_evidence"]["best_discarded_score"] is None