Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Support explicit resume after audio discovery
Cinna Davis0e12ab50099c
diff --git a/docs/PRODUCT.md b/docs/PRODUCT.mdindex 6d41873..64975f8 100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@ -22,7 +22,13 @@ Open `http://127.0.0.1:8765`. The same persistent directory must be supplied aftrestarting. Each upload gets a new job ID and its own original file, normalizedrequest, provenance, intermediate diagnostics, result and worker log. Completedjobs are read back without rerunning. Interrupted jobs are explicitly failed;-they are never silently replayed. Cancelling preserves partial artifacts.+they are never silently replayed. Stopping preserves partial artifacts. After+whole-recording discovery finishes, the job writes an atomic `resume.json`.+Use **Resume job** to continue a stopped job with that checkpoint. Completed+audio discovery is reused, as are valid completed search tiles; a partially+processed stage or tile is repeated. Input, detector and checkpoint integrity+are checked before reuse; incompatible search checkpoints fail explicitly.+Stopping before discovery completes cannot resume from that stage.The server binds to loopback. It runs one analysis process at a time, accepts upto four pending jobs, limits uploads to 100 MiB by default, and limits analysis@@ -42,6 +48,7 @@ dopplergeist analyze recording.mp3 --jobs jobs --online --max-runtime 14400 \--start-utc "$RECORDING_START_UTC_MIN" --end-utc "$RECORDING_START_UTC_MAX" \--time-source 'Your evidence for this recording time'dopplergeist job JOB_ID --jobs jobs+dopplergeist resume JOB_ID --jobs jobs```The UTC window bounds the recording start, not the event occurrence or upload.@@ -58,6 +65,7 @@ An inconclusive result may retain candidate hypotheses for inspection.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.+- `POST /api/jobs/{id}/resume`: explicitly continue a stopped job with a valid completed audio checkpoint.- `GET /api/jobs/{id}/artifacts`: relative file paths and byte counts.- `GET /api/jobs/{id}/artifacts/{path}`: download one artifact. Private operatorconfiguration is excluded. Paths cannot escape the job directory.diff --git a/src/dopplergeist/automatic.py b/src/dopplergeist/automatic.pyindex 5500f72..e52bdf2 100644--- a/src/dopplergeist/automatic.py+++ b/src/dopplergeist/automatic.py@@ -2,6 +2,7 @@from copy import deepcopyfrom datetime import datetime, timezoneimport hashlib+from importlib.metadata import versionimport jsonimport mathfrom pathlib import Path@@ -16,18 +17,64 @@ def _digest(path):return hashlib.file_digest(source, "sha256").hexdigest()-def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: None):+def _audio_identity(request, config):+ modules = ("intake.py", "discovery.py", "audio.py", "contracts.py")+ return {"request": request, "source_sha256": _digest(request["audio_path"]),+ "discovery_settings": config.get("discovery", {}),+ "modules": {name: _digest(Path(__file__).parent / name) for name in modules},+ "packages": {name: version(name) for name in ("numpy", "scipy")}}+++def _save_audio_checkpoint(output, request, config):+ files = ("intake/recording.f32", "intake/recording.json", "intake/intake.json", "discovery/discovery.json")+ identity = _audio_identity(request, config)+ metadata = json.loads((output / "intake/recording.json").read_text())+ discovery = json.loads((output / "discovery/discovery.json").read_text())+ if metadata["source_sha256"] != identity["source_sha256"] or discovery["source_sha256"] != identity["source_sha256"]:+ raise ValueError("Audio changed while generating the checkpoint")+ write_json(output / "resume.json", {"version": 1, "stage": "audio_complete",+ "identity": identity,+ "files": {name: _digest(output / name) for name in files}})+++def _load_audio_checkpoint(output, request, config):+ from .intake import IntakeRecording+ from .contracts import validate_recording+ try:+ checkpoint = json.loads((output / "resume.json").read_text())+ files = ("intake/recording.f32", "intake/recording.json", "intake/intake.json", "discovery/discovery.json")+ if checkpoint["version"] != 1 or checkpoint["stage"] != "audio_complete":+ raise ValueError("Unsupported audio checkpoint")+ if checkpoint["identity"] != _audio_identity(request, config):+ raise ValueError("Audio, request, discovery settings, or detector changed")+ if checkpoint["files"] != {name: _digest(output / name) for name in files}:+ raise ValueError("Saved audio checkpoint was changed")+ metadata = validate_recording(json.loads((output / "intake/recording.json").read_text()))+ diagnostics = json.loads((output / "intake/intake.json").read_text())+ discovery = json.loads((output / "discovery/discovery.json").read_text())+ if discovery["source_sha256"] != metadata["source_sha256"]:+ raise ValueError("Saved detection does not match the recording")+ events = [validate_event(event) for event in discovery["events"]]+ return IntakeRecording(output / "intake/recording.f32", metadata, diagnostics), events+ except (OSError, KeyError, TypeError, json.JSONDecodeError) as exc:+ raise ValueError("A complete, readable audio checkpoint is required to resume") from exc+++def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: None, *, resume=False):request = validate_request(request)config = config or {}output = Path(output_dir)output.mkdir(parents=True, exist_ok=True)- if (output / "provenance.json").exists():+ if (output / "provenance.json").exists() and not resume:raise FileExistsError("Analysis output exists; use a new directory")began = time.monotonic()sources = {p.name: _digest(p) for p in sorted(Path(__file__).parent.glob("*.py"))}provenance = {"request": request, "operator_configuration_sha256": hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest(),"source_sha256": _digest(request["audio_path"]), "implementation_files": sources,"ground_truth_used_by_search": False, "event_selection": "automatic_whole_recording"}+ if resume:+ recording, events = _load_audio_checkpoint(output, request, config)+ provenance["resumed_from"] = "audio_complete"write_json(output / "request.json", request)write_json(output / "provenance.json", provenance)state = {"coverage": {"search_complete": False, "data_status": "unavailable", "limitations": [], "requested_area": request["search"]}}@@ -62,14 +109,17 @@ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: Ndiscovery_settings = DiscoverySettings(**discovery_options)except (TypeError, ValueError) as exc:return finish("failed", "invalid_configuration", f"Invalid operator discovery settings: {exc}")- progress("intake", 0.05)- try:- recording = intake_recording(request["audio_path"], output / "intake", time_window=request.get("time_window"))- except AudioIntakeError as exc:- return finish("failed", exc.code, str(exc))+ if not resume:+ progress("intake", 0.05)+ try:+ recording = intake_recording(request["audio_path"], output / "intake", time_window=request.get("time_window"))+ except AudioIntakeError as exc:+ return finish("failed", exc.code, str(exc))+ state["recording"] = recording.metadata+ progress("discovery", 0.15, recording=recording.metadata)+ events = [validate_event(event) for event in discover_events(recording, output_dir=output / "discovery", settings=discovery_settings)]+ _save_audio_checkpoint(output, request, config)state["recording"] = recording.metadata- progress("discovery", 0.15, recording=recording.metadata)- events = [validate_event(event) for event in discover_events(recording, output_dir=output / "discovery", settings=discovery_settings)]state["events"] = eventsprovenance["discovered_events"] = len({event.get("harmonic_group_id", event["event_id"]) for event in events})provenance["discovered_ridges"] = len(events)diff --git a/src/dopplergeist/cli.py b/src/dopplergeist/cli.pyindex f63baef..e9b3cf7 100644--- a/src/dopplergeist/cli.py+++ b/src/dopplergeist/cli.py@@ -44,6 +44,10 @@ def main():job=sub.add_parser("job",help="Read a persisted job result without rerunning it")job.add_argument("job_id")job.add_argument("--jobs",default="jobs")+ resume=sub.add_parser("resume",help="Resume a stopped job after completed audio discovery")+ resume.add_argument("job_id")+ resume.add_argument("--jobs",default="jobs")+ resume.add_argument("--max-runtime",type=float,default=3600)args=parser.parse_args()if args.command=="run":from .pipeline import run@@ -84,6 +88,14 @@ def main():except ValueError:parser.error("job_id must be the 32-character job identifier")print(json.dumps(read_json(Path(args.jobs)/args.job_id/"result.json"),indent=2))+ elif args.command=="resume":+ from .jobs import JobManager+ manager=JobManager(args.jobs,max_runtime_s=args.max_runtime)+ try:+ manager.resume(args.job_id)+ print(json.dumps(manager.wait(args.job_id),indent=2))+ finally:+ manager.close()if __name__=="__main__":diff --git a/src/dopplergeist/jobs.py b/src/dopplergeist/jobs.pyindex 9150973..444d8ea 100644--- a/src/dopplergeist/jobs.py+++ b/src/dopplergeist/jobs.py@@ -134,7 +134,7 @@ class JobManager:self._uploads -= 1self._uploads_changed.notify_all()- def _run(self, directory):+ def _run(self, directory, resume=False):try:with self._serial:with self._mutex:@@ -143,8 +143,11 @@ class JobManager: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", "dopplergeist.jobs", "--execute", str(directory),- "--parent-pid", str(os.getpid())],+ command = [sys.executable, "-m", "dopplergeist.jobs", "--execute", str(directory),+ "--parent-pid", str(os.getpid())]+ if resume:+ command.append("--resume")+ process = subprocess.Popen(command,stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True)self._processes[directory.name] = processtry:@@ -188,6 +191,30 @@ class JobManager:self._stop(process)return result(directory, "cancelled", message="Cancelled by the user; partial artifacts are preserved.", **_evidence(self.get(job_id)))+ def resume(self, job_id):+ """Explicitly continue a stopped job after its complete audio checkpoint."""+ with self._mutex:+ directory = self.directory(job_id)+ current = self.get(job_id)+ if self._closed:+ raise ValueError("Service is shutting down")+ if current["status"] not in {"cancelled", "failed", "inconclusive"}:+ raise ValueError("Only stopped, failed, or inconclusive jobs can be resumed")+ if job_id in self._threads:+ raise ValueError("The previous worker is still stopping; try again")+ 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")+ from .automatic import _load_audio_checkpoint+ _load_audio_checkpoint(directory, read_json(directory / "request.json"), read_json(directory / "operator.json"))+ write_json(directory / f"result-before-resume-{uuid.uuid4().hex}.json", current)+ (directory / "cancel").unlink(missing_ok=True)+ saved_audio = {key: current[key] for key in ("recording", "events") if key in current}+ queued = result(directory, "queued", stage="queued", progress=0, **saved_audio)+ thread = threading.Thread(target=self._run, args=(directory, True), daemon=True)+ self._threads[job_id] = thread+ thread.start()+ return queued+def wait(self, job_id):thread = self._threads.get(job_id)if thread:@@ -208,7 +235,7 @@ class JobManager:self._lockfile.close()-def execute(directory, parent_pid=None):+def execute(directory, parent_pid=None, resume=False):# 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":@@ -232,7 +259,7 @@ def execute(directory, parent_pid=None):try:progress("intake", 0.02)- final = analyze(request, directory, config, progress)+ final = analyze(request, directory, config, progress, resume=resume)if (directory / "cancel").exists():result(directory, "cancelled", message="Cancelled by the user.", **_evidence(read_json(directory / "result.json")))else:@@ -249,5 +276,6 @@ if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument("--execute", required=True)parser.add_argument("--parent-pid", type=int)+ parser.add_argument("--resume", action="store_true")args = parser.parse_args()- execute(args.execute, args.parent_pid)+ execute(args.execute, args.parent_pid, resume=args.resume)diff --git a/src/dopplergeist/service.py b/src/dopplergeist/service.pyindex 13824e7..75d2959 100644--- a/src/dopplergeist/service.py+++ b/src/dopplergeist/service.py@@ -68,6 +68,8 @@ class Handler(BaseHTTPRequestHandler):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 == "POST" and parts[3:] == ["resume"]:+ return self._reply(manager.resume(job_id), 202)if self.command == "GET" and parts[3:] == ["artifacts"]:directory = manager.directory(job_id)artifacts = []diff --git a/src/dopplergeist/web/app.js b/src/dopplergeist/web/app.jsindex 66acc25..771ff6a 100644--- a/src/dopplergeist/web/app.js+++ b/src/dopplergeist/web/app.js@@ -31,6 +31,7 @@ function renderRecent() {async function artifacts(id) {const response = await api(`/api/jobs/${id}/artifacts`);if (id !== activeJob) return;+ $('resume').hidden = !['cancelled', 'failed', 'inconclusive'].includes($('status').textContent) || !response.artifacts.some(item => item.path === 'resume.json');$('artifacts').replaceChildren(); $('diagnostics').replaceChildren();for (const item of response.artifacts) {const href = `/api/jobs/${id}/artifacts/${item.path.split('/').map(encodeURIComponent).join('/')}`;@@ -50,6 +51,7 @@ function render(value) {$('stage').textContent = value.stage || '';$('progress').value = value.progress || (terminal.has(value.status) ? 1 : 0);$('cancel').hidden = terminal.has(value.status);+ $('resume').hidden = true;$('message').textContent = value.message || 'Analysis is running. You can return to this job using its saved link.';$('required').hidden = !value.required_fields?.length;$('required').textContent = value.required_fields?.length ? `Required input: ${value.required_fields.join(', ')}. Add the evidence to a new analysis; this run is preserved.` : '';@@ -141,6 +143,10 @@ $('cancel').addEventListener('click', async () => {try { const value = await api(`/api/jobs/${activeJob}/cancel`, {method: 'POST'}); render(value); await artifacts(activeJob); }catch (error) { $('connection').textContent = error.message; }});+$('resume').addEventListener('click', async () => {+ try { const value = await api(`/api/jobs/${activeJob}/resume`, {method: 'POST'}); render(value); poll(activeJob); }+ catch (error) { $('connection').textContent = error.message; }+});api('/api/capabilities').then(value => {maxBytes = value.max_upload_bytes;$('limits').textContent = `Up to ${(maxBytes / 1024 / 1024).toFixed(0)} MB per file. Analysis budget: ${(value.max_runtime_s / 60).toFixed(0)} minutes per job.`;diff --git a/src/dopplergeist/web/index.html b/src/dopplergeist/web/index.htmlindex da6a5e7..b499d69 100644--- a/src/dopplergeist/web/index.html+++ b/src/dopplergeist/web/index.html@@ -12,7 +12,7 @@<fieldset><legend>When did the recording start?</legend><p class="help">Enter UTC, including the date. A window is allowed. File creation and upload times do not establish recording time. Leave blank if unknown; analysis will request this evidence before searching.</p><label for="start">Earliest start (UTC)</label><input id="start" type="datetime-local" step="1"><label for="end">Latest start (UTC)</label><input id="end" type="datetime-local" step="1"><label for="time-source">How is this time known? <span class="muted">Optional</span></label><input id="time-source" type="text" maxlength="500" placeholder="For example, recorder clock synchronized before recording"></fieldset><p id="limits" class="help"></p><button id="submit" type="submit">Upload & analyze <span aria-hidden="true">→</span></button><p id="upload-error" role="alert"></p></form></section>-<section class="panel results" aria-labelledby="results-heading"><div class="section-row"><h2 id="results-heading">Analysis</h2><button id="cancel" class="secondary" hidden>Cancel job</button></div><div id="empty"><div class="wave" aria-hidden="true">∿∿∿</div><h3>Your evidence will appear here</h3><p>Detected curves, location hypotheses, uncertainty, and downloadable artifacts stay attached to each job.</p></div><div id="job" hidden><p id="job-id" class="mono"></p><div class="section-row"><strong id="status" role="status" aria-live="polite"></strong><span id="stage" class="muted"></span></div><progress id="progress" max="1" value="0" aria-label="Analysis progress"></progress><p id="message"></p><p id="required" class="notice" hidden></p><div id="coverage"></div><div id="candidates"></div><div id="events"></div><div id="diagnostics"></div><details id="downloads"><summary>Download run artifacts</summary><ul id="artifacts"></ul></details><p id="connection" role="alert"></p></div></section>+<section class="panel results" aria-labelledby="results-heading"><div class="section-row"><h2 id="results-heading">Analysis</h2><button id="cancel" class="secondary" hidden>Stop job</button><button id="resume" class="secondary" hidden>Resume job</button></div><div id="empty"><div class="wave" aria-hidden="true">∿∿∿</div><h3>Your evidence will appear here</h3><p>Detected curves, location hypotheses, uncertainty, and downloadable artifacts stay attached to each job.</p></div><div id="job" hidden><p id="job-id" class="mono"></p><div class="section-row"><strong id="status" role="status" aria-live="polite"></strong><span id="stage" class="muted"></span></div><progress id="progress" max="1" value="0" aria-label="Analysis progress"></progress><p id="message"></p><p id="required" class="notice" hidden></p><div id="coverage"></div><div id="candidates"></div><div id="events"></div><div id="diagnostics"></div><details id="downloads"><summary>Download run artifacts</summary><ul id="artifacts"></ul></details><p id="connection" role="alert"></p></div></section></div><section id="recent-panel" class="recent" hidden><h2>Recent jobs on this browser</h2><ul id="recent"></ul></section><footer>Scores rank hypotheses; they are not probabilities. An inconclusive result can include alternatives without supporting a precise location.</footer>diff --git a/tests/test_job_resume.py b/tests/test_job_resume.pynew file mode 100644index 0000000..80a65f1--- /dev/null+++ b/tests/test_job_resume.py@@ -0,0 +1,71 @@+"""Job lifecycle and audio-checkpoint integrity checks, without DSP fixtures."""+import hashlib+import io+import json++import pytest++from dopplergeist.automatic import _load_audio_checkpoint, _save_audio_checkpoint+from dopplergeist.jobs import JobManager, read_json, result, write_json+++def checkpoint(manager, job_id):+ directory = manager.directory(job_id)+ request = read_json(directory / "request.json")+ digest = hashlib.sha256((directory / "input.mp3").read_bytes()).hexdigest()+ (directory / "intake").mkdir()+ (directory / "discovery").mkdir()+ (directory / "intake/recording.f32").write_bytes(b"completed cache")+ write_json(directory / "intake/recording.json", {+ "source_sha256": digest, "duration_s": 1.0, "sample_rate_hz": 4000,+ "channels": 1, "source_format": "mp3"})+ write_json(directory / "intake/intake.json", {})+ write_json(directory / "discovery/discovery.json", {"source_sha256": digest, "events": []})+ _save_audio_checkpoint(directory, request, {})+ result(directory, "cancelled", message="Stopped after discovery")+ return directory, request+++def test_resume_reuses_completed_discovery_and_persists_result(tmp_path):+ manager = JobManager(tmp_path)+ manager._serial.acquire()+ try:+ job = manager.submit({"schema_version": 1}, io.BytesIO(b"not a media file"), 16)+ job_id = job["job_id"]+ manager.cancel(job_id)+ finally:+ manager._serial.release()+ manager.wait(job_id)+ directory, _ = checkpoint(manager, job_id)+ before = (directory / "discovery/discovery.json").read_bytes()+ try:+ assert manager.resume(job_id)["status"] == "queued"+ final = manager.wait(job_id)+ assert final["status"] == "needs_input"+ assert final["reason_code"] == "recording_time_required"+ assert (directory / "discovery/discovery.json").read_bytes() == before+ assert read_json(directory / "provenance.json")["resumed_from"] == "audio_complete"+ finally:+ manager.close()+++def test_checkpoint_rejects_changed_input_or_detection(tmp_path):+ manager = JobManager(tmp_path)+ manager._serial.acquire()+ try:+ job = manager.submit({"schema_version": 1}, io.BytesIO(b"not a media file"), 16)+ manager.cancel(job["job_id"])+ finally:+ manager._serial.release()+ manager.wait(job["job_id"])+ directory, request = checkpoint(manager, job["job_id"])+ try:+ _load_audio_checkpoint(directory, request, {})+ with pytest.raises(ValueError, match="changed"):+ _load_audio_checkpoint(directory, request, {"discovery": {"chunk_s": 180}})+ (directory / "discovery/discovery.json").write_text(json.dumps({"events": []}))+ with pytest.raises(ValueError, match="changed"):+ manager.resume(job["job_id"])+ assert manager.get(job["job_id"])["status"] == "cancelled"+ finally:+ manager.close()