Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Add direct CLI job cancellation (#245)
Cinna Davisfec518e51f14
diff --git a/README.md b/README.mdindex 99d9686..973167a 100644--- a/README.md+++ b/README.md@@ -54,6 +54,9 @@ The command prints a job ID when queued. In another terminal, runprogress, checkpoint rate, and the age of the latest tile and job status update.Stop a running service-managed job with `.venv/bin/dopplergeist cancel JOB_ID`;pass `--server-url` when the service uses a non-default port.+For a directly managed `analyze` or `resume --jobs` job, request cooperative+cancellation with `.venv/bin/dopplergeist cancel JOB_ID --jobs jobs`; the active+worker stops at its next cancellation check.Resume a stopped job while its service remains active with`.venv/bin/dopplergeist resume JOB_ID --server-url http://127.0.0.1:8765`, thenmonitor it using `job JOB_ID --jobs jobs --watch`. If the service is stopped,diff --git a/docs/PRODUCT.md b/docs/PRODUCT.mdindex 5883ba8..17050d2 100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@ -56,6 +56,7 @@ dopplergeist analyze recording.mp3 --jobs jobs --online --max-runtime 14400 \dopplergeist job JOB_ID --jobs jobsdopplergeist job JOB_ID --jobs jobs --watch --interval 10dopplergeist cancel JOB_ID+dopplergeist cancel JOB_ID --jobs jobsdopplergeist resume JOB_ID --jobs jobs# If the upload service still owns the job store:dopplergeist resume JOB_ID --server-url http://127.0.0.1:8765@@ -73,6 +74,12 @@ Ctrl-C stops the watcher without cancelling the analysis.`cancel` sends the cancellation request to the local service at`http://127.0.0.1:8765`. If `serve` uses a different port, pass its base URL with`--server-url`. The service must be running and managing the job directory.+For a job started by direct `analyze` or `resume --jobs`, use+`cancel JOB_ID --jobs PATH`. It writes the cooperative cancellation marker+without opening a second manager; the active worker stops at its next+cancellation check, so it may finish its current tile first. This path requires+an active manager to own the job directory. The service API path instead stops+the worker process group promptly and returns the terminal job result.When `serve` owns the job-store lock, use the same `--server-url` option with`resume`; it prints the queued result after the service accepts the request.Monitor it with `job --watch` and the service's `--jobs` directory. Withoutdiff --git a/src/dopplergeist/cli.py b/src/dopplergeist/cli.pyindex d0418b0..201a40e 100644--- a/src/dopplergeist/cli.py+++ b/src/dopplergeist/cli.py@@ -95,10 +95,12 @@ def main():job.add_argument("--jobs",default="jobs")job.add_argument("--watch",action="store_true",help="Watch local checkpoints until the job stops")job.add_argument("--interval",type=positive_runtime,default=10,help="Watch interval in seconds")- cancel=sub.add_parser("cancel",help="Cancel a job managed by the local upload service")+ cancel=sub.add_parser("cancel",help="Request cancellation of a managed job")cancel.add_argument("job_id",type=job_identifier)- cancel.add_argument("--server-url",default="http://127.0.0.1:8765",- help="Base URL of the service managing this job")+ cancel_target=cancel.add_mutually_exclusive_group()+ cancel_target.add_argument("--server-url",default="http://127.0.0.1:8765",+ help="Base URL of the service managing this job")+ cancel_target.add_argument("--jobs",help="Persistent job directory for cooperative cancellation")resume=sub.add_parser("resume",help="Resume a stopped job after completed audio discovery")resume.add_argument("job_id",type=job_identifier)resume.add_argument("--jobs",default="jobs")@@ -184,7 +186,14 @@ def main():raise SystemExit(130)print(json.dumps(value,indent=2))elif args.command=="cancel":- value=post_job_action(args.server_url,args.job_id,"cancel",parser)+ if args.jobs is not None:+ from .jobs import request_local_cancel+ try:+ value=request_local_cancel(args.jobs,args.job_id)+ except (KeyError,OSError,ValueError) as exc:+ parser.error(f"Could not request cancellation for job {args.job_id}: {exc}")+ else:+ value=post_job_action(args.server_url,args.job_id,"cancel",parser)print(json.dumps(value,indent=2))elif args.command=="resume":if args.server_url:diff --git a/src/dopplergeist/jobs.py b/src/dopplergeist/jobs.pyindex 62c1025..30f0d94 100644--- a/src/dopplergeist/jobs.py+++ b/src/dopplergeist/jobs.py@@ -38,6 +38,41 @@ def _evidence(value):return {key: value[key] for key in ("recording", "events", "candidates", "coverage", "artifacts") if key in value}+def request_local_cancel(root, job_id):+ """Request cancellation through an active manager's cooperative marker."""+ root = Path(root).resolve()+ try:+ if uuid.UUID(job_id).hex != job_id:+ raise ValueError+ except (AttributeError, ValueError):+ raise KeyError("Unknown job") from None+ directory = root / job_id+ result_path = directory / "result.json"+ if not result_path.is_file():+ raise KeyError("Unknown job")+ current = read_json(result_path)+ if current["status"] in TERMINAL:+ return current+ lock_path = root / ".manager.lock"+ try:+ with lock_path.open("rb") as lockfile:+ try:+ fcntl.flock(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ manager_active = True+ else:+ fcntl.flock(lockfile.fileno(), fcntl.LOCK_UN)+ manager_active = False+ except FileNotFoundError:+ manager_active = False+ if not manager_active:+ raise ValueError("No active job manager owns this job directory")+ (directory / "cancel").touch(mode=0o600, exist_ok=True)+ return {"job_id": job_id, "status": current["status"], "stage": current.get("stage"),+ "cancellation_requested": True,+ "message": "The job will stop at its next cancellation check."}++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()diff --git a/tests/test_local_cancel.py b/tests/test_local_cancel.pynew file mode 100644index 0000000..be5e70b--- /dev/null+++ b/tests/test_local_cancel.py@@ -0,0 +1,38 @@+import uuid++import pytest++from dopplergeist.jobs import JobManager, read_json, request_local_cancel, result+++def make_running_job(root):+ job_id = uuid.uuid4().hex+ directory = root / job_id+ directory.mkdir()+ result(directory, "running", stage="search", progress=0.5)+ return job_id, directory+++def test_local_cancel_sets_marker_without_rewriting_job_result(tmp_path):+ manager = JobManager(tmp_path)+ try:+ job_id, directory = make_running_job(tmp_path)+ previous = read_json(directory / "result.json")+ requested = request_local_cancel(tmp_path, job_id)+ assert requested["cancellation_requested"] is True+ assert requested["status"] == "running"+ assert (directory / "cancel").is_file()+ assert read_json(directory / "result.json") == previous+ finally:+ manager.close()+++def test_local_cancel_requires_live_manager_and_preserves_terminal_jobs(tmp_path):+ job_id, directory = make_running_job(tmp_path)+ with pytest.raises(ValueError, match="No active job manager"):+ request_local_cancel(tmp_path, job_id)+ assert not (directory / "cancel").exists()++ previous = result(directory, "inconclusive", reason_code="no_events", message="No events.")+ assert request_local_cancel(tmp_path, job_id) == previous+ assert not (directory / "cancel").exists()