Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

Define versioned automatic-workflow contracts and validated examples

Cinna Davis50d6fb145aac
diff --git a/docs/INTERFACES.md b/docs/INTERFACES.md
new file mode 100644
index 0000000..6a96d83
--- /dev/null
+++ b/docs/INTERFACES.md
@@ -0,0 +1,160 @@
+# Automatic workflow contracts, version 1
+
+Issue: [DG-01 / #2](https://github.com/1337isnot1337/DOPPLERGEIST/issues/2).
+Implementation: `src/aircraft_geoloc/contracts.py`. The wire objects are plain JSON
+dictionaries, described by Python `TypedDict` types and explicit validators. They
+do not require a particular HTTP framework, UI library or worker executor.
+
+Use `validate_request`, `validate_recording`, `validate_event`,
+`validate_candidate` and `validate_result` at component boundaries. They return
+copies, normalize absolute timestamps to UTC, and raise `ValueError` on invalid
+input. They validate shape and semantics, not the truth of a measurement or the
+correctness of a location. Unknown fields are rejected; coordinate additive changes
+through issue #2 before consumers depend on them. A future incompatible wire shape
+needs a new schema version.
+
+## Request and recording clock
+
+[Example request](examples/analysis-request.json): `schema_version: 1`, local
+`audio_path`, optional `time_window`, optional `search` (defaults to CONUS).
+The upload service creates the local audio path after storing the file; the browser
+must not be given arbitrary access to server paths. Upload/HTTP handling belongs
+to DG-09, not this validator.
+
+`time_window.start_utc` and `end_utc` bound the **start of the recording**, including
+both endpoints. Equal endpoints mean one stated start time. They are not event
+times or the interval containing all audio samples. Both require ISO 8601 strings
+with an explicit timezone; offsets are normalized to UTC. `source` is `user` or
+`recording_metadata`, with an optional `source_detail` describing the evidence.
+File modification, download and upload timestamps are not recording metadata.
+
+No time window is a valid intake request. After probing metadata, the orchestrator
+returns `needs_input` with `required_fields: ["time_window"]` if a defensible window
+is still unavailable. Do not fabricate a timestamp. A derived best recording start
+is a result field and must not be mislabeled independent timestamp evidence.
+
+`search.coverage` is `conus` in version 1. Optional `bounds_wsen` further restrict
+the requested search to `[west, south, east, north]` in longitude/latitude degrees.
+Actual data availability may be smaller and must be reported in provenance and
+the decision. Bounds must increase; antimeridian crossing is not supported here.
+The automatic national acceptance test omits any truth-derived bounding box.
+
+The request has no event windows, bands, known flight IDs or ground-truth location.
+Those remain available in the separate research configuration interface.
+
+## Intake metadata
+
+`RecordingMetadata` records the original file's lowercase `source_sha256`, decoded
+`duration_s`, decoded `sample_rate_hz`, decoded `channels`, original `source_format`
+(e.g. `mp3`), and optional trustworthy `time_window`. Sample rates/channels describe
+the samples handed to discovery, not an earlier source stream. Their first sample
+is audio-relative time zero. If decoding introduces an offset, DG-03 must account
+for it and record the transformation in its provenance artifact.
+
+## Detected events
+
+[Example event](examples/detected-event.json): a stable `event_id`, audio-relative
+`start_s`/`end_s`, positive `[low, high]` `band_hz`, and at least three ordered ridge
+points. Each point has `time_s`, `frequency_hz` and an optional nonnegative `weight`
+(default 1). Point times lie within the event and increase strictly; frequencies
+lie within its band. Times are relative to the beginning of the decoded recording,
+not to the beginning of an analysis chunk. Chunked discovery must add its offset.
+
+Optional `harmonic_group_id` identifies ridges believed to come from the same
+flyover. Harmonics must not become independent time constraints. Optional
+`cpa_receive_s` is an estimated received CPA time, in audio-relative seconds, and
+may lie outside a truncated observed event. Optional positive increasing ranges
+`f0_range_hz`, `speed_range_mps` and `slant_range_m` are measured proposal bounds.
+They are not guaranteed true geometry; the matcher must account for uncertainty.
+
+`quality` maps diagnostic names to finite numbers. Name their units where relevant
+(e.g. `ridge_rmse_hz`). A diagnostic score is not a calibrated probability.
+There is no blanket `confidence` float whose semantics different workers can guess.
+
+## Location candidates
+
+A `LocationCandidate` contains `lat`, `lon`, finite `score`, a descriptive
+`score_kind`, paired `event_ids`/`flight_ids`, and fitted `recording_start_utc`.
+Flight IDs identify imported trajectory segments. Event IDs are distinct; the same
+flight may legitimately have multiple approaches. Every event gets one flight
+segment at that candidate, and all share the same fitted recording start.
+
+Scores are **higher is better**. Existing brightness scores can use
+`spectral_contrast`; existing negative ridge residuals can use
+`negative_ridge_rmse_hz`. Candidate lists use one comparable score kind and descend
+by score. The tiled search must preserve the same scoring normalization across
+tiles. Do not compare unlike statistics without a documented common score.
+
+Optional `uncertainty` contains `radius_m`, `method` and `kind`. `sensitivity` is
+an uncalibrated model/measurement sensitivity envelope. It cannot carry a coverage
+probability. `calibrated` additionally requires `coverage_probability` in [0, 1]
+and a `calibration_reference` to independent evaluation evidence. Providing these
+fields does not itself establish that the claimed calibration is valid.
+
+## Jobs, decisions and artifacts
+
+[Example result](examples/job-result.json) and
+[missing-time example](examples/job-needs-input.json) are illustrative wire data,
+not measured benchmark outcomes.
+
+`JobResult` requires `schema_version: 1`, `job_id` and one status:
+
+| Status | Meaning |
+| --- | --- |
+| `queued` | Request accepted; analysis not started |
+| `running` | Work is in progress |
+| `needs_input` | Explicit user information is required; include required_fields |
+| `succeeded` | A location is supported by the decision stage; candidates required |
+| `inconclusive` | Processing completed but evidence does not support a location |
+| `failed` | An execution, input-processing or data-access error prevented completion |
+| `cancelled` | Requested cancellation completed |
+
+`needs_input`, `inconclusive` and `failed` require a stable `reason_code` and a
+human-readable `message`. Suggested codes include `recording_time_required`,
+`no_supported_events`, `insufficient_coverage`, `ambiguous_locations`,
+`decode_failed` and `data_unavailable`. Reason codes may expand without a schema
+change. An unavailable provider and a noise-only recording are different outcomes.
+
+Optional `stage` is a producer-chosen stable string, e.g. `intake`, `discovery`,
+`acquisition`, `search`, `refinement`, `decision`, `complete`. Optional `progress`
+is a measured/estimated fraction in [0, 1]; omit it when the total work is unknown.
+Optional `recording`, `events` and `candidates` carry the objects above. Event IDs
+must be unique. If events are included, candidate event references must resolve.
+An inconclusive job may retain ranked alternatives for diagnostics; its status
+must prevent the UI from presenting them as an accepted location.
+
+Optional `coverage` has `search_complete` (boolean), `data_status` (`available`,
+`partial`, `unavailable`), and a list of known `limitations`. Optional
+`requested_area` uses the request SearchArea shape; optional `missing_data` lists
+known missing provider/date/tile identifiers. Search completion means the algorithm
+finished the requested scope. Data availability means requested provider inputs
+were obtained; it does not assert that every real aircraft broadcast or was captured.
+Document that limitation even when all archive files were downloaded. A missing
+coverage report must never be interpreted as complete coverage by the decision
+stage. Detailed tile counts and coverage maps belong in a linked artifact.
+
+`artifacts` maps names to paths relative to that job's output directory, without
+absolute paths or `..` traversal. Suggested names are `report`, `provenance`, and
+event-specific plots/arrays. The provenance artifact should record input/data/code
+hashes, configuration, time/altitude assumptions, searched/missing coverage and
+runtime. The service must independently enforce output-directory containment when
+serving files, including symlink handling. Do not embed huge spectra in job JSON.
+
+## Compatibility and ownership
+
+The existing `aircraft-geoloc run CONFIG --output DIR` and `measure` commands keep
+their current behavior. `event_measure_settings(event)` maps a discovered event to
+the existing measurement-setting field names. It deliberately does not pretend to
+select flights or invent missing event geometry. Re-measuring a discovered window
+through the legacy API is optional; DG-09 can pass measured ridges directly to an
+adapted search path.
+
+For a legacy replay, a point time window can populate `recording_start_utc`.
+An interval must be searched as an interval; do not substitute its midpoint as a
+known clock. DG-05 selects sufficient trajectory support around all possible
+recording starts and events, including propagation/interpolation margins.
+
+DG-03 produces recording metadata. DG-04 produces events. DG-05 supplies flight
+and terrain data/provenance. DG-06/DG-07 produce compatible ranked candidates.
+DG-08 decides whether a location is supported. DG-09 assembles jobs; DG-10 consumes
+them. Preserve these shared shapes and coordinate extensions before merging.
diff --git a/docs/examples/analysis-request.json b/docs/examples/analysis-request.json
new file mode 100644
index 0000000..ccaaf7d
--- /dev/null
+++ b/docs/examples/analysis-request.json
@@ -0,0 +1,13 @@
+{
+ "schema_version": 1,
+ "audio_path": "uploads/recording.mp3",
+ "time_window": {
+ "start_utc": "2026-09-08T00:00:00Z",
+ "end_utc": "2026-09-09T00:00:00Z",
+ "source": "user",
+ "source_detail": "User supplied the recording date; start within this UTC interval is unknown."
+ },
+ "search": {
+ "coverage": "conus"
+ }
+}
diff --git a/docs/examples/detected-event.json b/docs/examples/detected-event.json
new file mode 100644
index 0000000..b231fd3
--- /dev/null
+++ b/docs/examples/detected-event.json
@@ -0,0 +1,38 @@
+{
+ "event_id": "event-1",
+ "start_s": 10.0,
+ "end_s": 70.0,
+ "band_hz": [
+ 80.0,
+ 180.0
+ ],
+ "ridge": [
+ {
+ "time_s": 12.0,
+ "frequency_hz": 170.0,
+ "weight": 1.0
+ },
+ {
+ "time_s": 40.0,
+ "frequency_hz": 130.0,
+ "weight": 0.8
+ },
+ {
+ "time_s": 68.0,
+ "frequency_hz": 90.0,
+ "weight": 0.9
+ }
+ ],
+ "harmonic_group_id": "flyover-1",
+ "quality": {
+ "ridge_rmse_hz": 1.5
+ },
+ "speed_range_mps": [
+ 40.0,
+ 180.0
+ ],
+ "slant_range_m": [
+ 500.0,
+ 10000.0
+ ]
+}
diff --git a/docs/examples/job-needs-input.json b/docs/examples/job-needs-input.json
new file mode 100644
index 0000000..0161e65
--- /dev/null
+++ b/docs/examples/job-needs-input.json
@@ -0,0 +1,11 @@
+{
+ "schema_version": 1,
+ "job_id": "illustrative-job",
+ "status": "needs_input",
+ "stage": "intake",
+ "reason_code": "recording_time_required",
+ "message": "Supply the recording date or a bounded UTC window for the recording start.",
+ "required_fields": [
+ "time_window"
+ ]
+}
diff --git a/docs/examples/job-result.json b/docs/examples/job-result.json
new file mode 100644
index 0000000..c73f38b
--- /dev/null
+++ b/docs/examples/job-result.json
@@ -0,0 +1,72 @@
+{
+ "schema_version": 1,
+ "job_id": "illustrative-job",
+ "status": "succeeded",
+ "stage": "complete",
+ "progress": 1.0,
+ "events": [
+ {
+ "event_id": "event-1",
+ "start_s": 10.0,
+ "end_s": 70.0,
+ "band_hz": [
+ 80.0,
+ 180.0
+ ],
+ "ridge": [
+ {
+ "time_s": 12.0,
+ "frequency_hz": 170.0,
+ "weight": 1.0
+ },
+ {
+ "time_s": 40.0,
+ "frequency_hz": 130.0,
+ "weight": 0.8
+ },
+ {
+ "time_s": 68.0,
+ "frequency_hz": 90.0,
+ "weight": 0.9
+ }
+ ],
+ "harmonic_group_id": "flyover-1",
+ "quality": {
+ "ridge_rmse_hz": 1.5
+ },
+ "speed_range_mps": [
+ 40.0,
+ 180.0
+ ],
+ "slant_range_m": [
+ 500.0,
+ 10000.0
+ ]
+ }
+ ],
+ "candidates": [
+ {
+ "lat": 40.0,
+ "lon": -100.0,
+ "score": -1.5,
+ "score_kind": "negative_ridge_rmse_hz",
+ "event_ids": [
+ "event-1"
+ ],
+ "flight_ids": [
+ "illustrative-flight:1"
+ ],
+ "recording_start_utc": "2026-09-08T20:17:30Z",
+ "uncertainty": {
+ "radius_m": 250.0,
+ "kind": "sensitivity",
+ "method": "Illustrative parameter-perturbation envelope; not calibrated."
+ }
+ }
+ ],
+ "artifacts": {
+ "report": "report.json",
+ "provenance": "provenance.json",
+ "spectrogram": "events/event-1.png"
+ }
+}
diff --git a/src/aircraft_geoloc/contracts.py b/src/aircraft_geoloc/contracts.py
new file mode 100644
index 0000000..c2c3295
--- /dev/null
+++ b/src/aircraft_geoloc/contracts.py
@@ -0,0 +1,333 @@
+"""Version-one JSON contracts for the automatic workflow.
+
+These are plain dictionaries, independent of a web framework. Validators return
+copies and normalize absolute timestamps to UTC. Legacy research configurations
+are unchanged. See docs/INTERFACES.md for semantics and producer ownership.
+"""
+from copy import deepcopy
+from datetime import datetime, timezone
+import math
+from pathlib import PurePosixPath
+from typing import Literal, NotRequired, TypedDict
+
+
+class RecordingTimeWindow(TypedDict):
+ start_utc: str
+ end_utc: str
+ source: Literal["user", "recording_metadata"]
+ source_detail: NotRequired[str]
+
+
+class SearchArea(TypedDict):
+ coverage: Literal["conus"]
+ bounds_wsen: NotRequired[list[float]]
+
+
+class AnalysisRequest(TypedDict):
+ schema_version: Literal[1]
+ audio_path: str
+ time_window: NotRequired[RecordingTimeWindow | None]
+ search: NotRequired[SearchArea]
+
+
+class RecordingMetadata(TypedDict):
+ source_sha256: str
+ duration_s: float
+ sample_rate_hz: int
+ channels: int
+ source_format: str
+ time_window: NotRequired[RecordingTimeWindow | None]
+
+
+class RidgePoint(TypedDict):
+ time_s: float
+ frequency_hz: float
+ weight: NotRequired[float]
+
+
+class DetectedEvent(TypedDict):
+ event_id: str
+ start_s: float
+ end_s: float
+ band_hz: list[float]
+ ridge: list[RidgePoint]
+ harmonic_group_id: NotRequired[str]
+ cpa_receive_s: NotRequired[float]
+ f0_range_hz: NotRequired[list[float]]
+ speed_range_mps: NotRequired[list[float]]
+ slant_range_m: NotRequired[list[float]]
+ quality: NotRequired[dict[str, float]]
+
+
+class LocationUncertainty(TypedDict):
+ radius_m: float
+ method: str
+ kind: Literal["sensitivity", "calibrated"]
+ coverage_probability: NotRequired[float]
+ calibration_reference: NotRequired[str]
+
+
+class LocationCandidate(TypedDict):
+ lat: float
+ lon: float
+ score: float
+ score_kind: str
+ event_ids: list[str]
+ flight_ids: list[str]
+ recording_start_utc: str
+ uncertainty: NotRequired[LocationUncertainty]
+
+
+JobStatus = Literal["queued", "running", "needs_input", "succeeded", "inconclusive", "failed", "cancelled"]
+
+
+class CoverageReport(TypedDict):
+ search_complete: bool
+ data_status: Literal["available", "partial", "unavailable"]
+ limitations: list[str]
+ requested_area: NotRequired[SearchArea]
+ missing_data: NotRequired[list[str]]
+
+
+class JobResult(TypedDict):
+ schema_version: Literal[1]
+ job_id: str
+ status: JobStatus
+ stage: NotRequired[str]
+ progress: NotRequired[float]
+ recording: NotRequired[RecordingMetadata]
+ coverage: NotRequired[CoverageReport]
+ events: NotRequired[list[DetectedEvent]]
+ candidates: NotRequired[list[LocationCandidate]]
+ reason_code: NotRequired[str]
+ message: NotRequired[str]
+ required_fields: NotRequired[list[str]]
+ artifacts: NotRequired[dict[str, str]]
+
+
+def _record(value, required, optional=()):
+ if not isinstance(value, dict):
+ raise ValueError("Expected a JSON object")
+ missing = set(required) - value.keys()
+ extra = value.keys() - set(required) - set(optional)
+ if missing or extra:
+ raise ValueError(f"Missing fields: {sorted(missing)}; unknown fields: {sorted(extra)}")
+ return deepcopy(value)
+
+
+def _text(value, name):
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f"{name} must be a nonempty string")
+
+
+def _number(value, name, low=-math.inf, high=math.inf):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError(f"{name} must be a finite number")
+ if not math.isfinite(value) or not low <= value <= high:
+ raise ValueError(f"{name} must be finite and between {low} and {high}")
+
+
+def _interval(value, name, low=0):
+ if not isinstance(value, list) or len(value) != 2:
+ raise ValueError(f"{name} must contain two endpoints")
+ for number in value:
+ _number(number, name, low)
+ if value[0] >= value[1]:
+ raise ValueError(f"{name} must be strictly increasing")
+
+
+def utc_timestamp(value):
+ """Parse an explicit ISO timestamp; naive timestamps and epoch guesses fail."""
+ _text(value, "UTC timestamp")
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError as exc:
+ raise ValueError("Timestamp must be ISO 8601 with an explicit timezone") from exc
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
+ raise ValueError("Timestamp requires an explicit timezone")
+ return parsed.astimezone(timezone.utc)
+
+
+def _utc(value):
+ return utc_timestamp(value).isoformat().replace("+00:00", "Z")
+
+
+def validate_request(value):
+ request = _record(value, ("schema_version", "audio_path"), ("time_window", "search"))
+ if type(request["schema_version"]) is not int or request["schema_version"] != 1:
+ raise ValueError("Unsupported schema_version")
+ _text(request["audio_path"], "audio_path")
+ window = request.get("time_window")
+ if window is not None:
+ window = _record(window, ("start_utc", "end_utc", "source"), ("source_detail",))
+ window["start_utc"], window["end_utc"] = _utc(window["start_utc"]), _utc(window["end_utc"])
+ if utc_timestamp(window["end_utc"]) < utc_timestamp(window["start_utc"]):
+ raise ValueError("Recording-start window is reversed")
+ if window["source"] not in ("user", "recording_metadata"):
+ raise ValueError("Time source must be user or recording_metadata")
+ if "source_detail" in window:
+ _text(window["source_detail"], "source_detail")
+ request["time_window"] = window
+ search = _record(request.get("search", {"coverage": "conus"}), ("coverage",), ("bounds_wsen",))
+ if search["coverage"] != "conus":
+ raise ValueError("Version one supports declared CONUS coverage only")
+ if "bounds_wsen" in search:
+ bounds = search["bounds_wsen"]
+ if not isinstance(bounds, list) or len(bounds) != 4:
+ raise ValueError("bounds_wsen must contain west, south, east, north")
+ for i, number in enumerate(bounds):
+ _number(number, "bounds_wsen", -180 if i % 2 == 0 else -90, 180 if i % 2 == 0 else 90)
+ if bounds[0] >= bounds[2] or bounds[1] >= bounds[3]:
+ raise ValueError("Bounds must be increasing; antimeridian crossing is unsupported")
+ request["search"] = search
+ return request
+
+
+def validate_event(value):
+ optional = ("harmonic_group_id", "cpa_receive_s", "f0_range_hz", "speed_range_mps", "slant_range_m", "quality")
+ event = _record(value, ("event_id", "start_s", "end_s", "band_hz", "ridge"), optional)
+ _text(event["event_id"], "event_id")
+ _interval([event["start_s"], event["end_s"]], "event time")
+ _interval(event["band_hz"], "band_hz", low=1e-12)
+ if "harmonic_group_id" in event:
+ _text(event["harmonic_group_id"], "harmonic_group_id")
+ if "cpa_receive_s" in event:
+ _number(event["cpa_receive_s"], "cpa_receive_s", 0)
+ for name in ("f0_range_hz", "speed_range_mps", "slant_range_m"):
+ if name in event:
+ _interval(event[name], name, low=1e-12)
+ if not isinstance(event["ridge"], list) or len(event["ridge"]) < 3:
+ raise ValueError("A measured ridge requires at least three points")
+ previous = -math.inf
+ for point in event["ridge"]:
+ _record(point, ("time_s", "frequency_hz"), ("weight",))
+ _number(point["time_s"], "ridge time_s", event["start_s"], event["end_s"])
+ _number(point["frequency_hz"], "ridge frequency_hz", *event["band_hz"])
+ _number(point.get("weight", 1), "ridge weight", 0)
+ if point["time_s"] <= previous:
+ raise ValueError("Ridge times must be strictly increasing")
+ previous = point["time_s"]
+ quality = event.get("quality", {})
+ if not isinstance(quality, dict):
+ raise ValueError("quality must be a mapping of diagnostic names to numbers")
+ for name, number in quality.items():
+ _text(name, "quality name")
+ _number(number, name)
+ return event
+
+
+def validate_recording(value):
+ recording = _record(value, ("source_sha256", "duration_s", "sample_rate_hz", "channels", "source_format"), ("time_window",))
+ checksum = recording["source_sha256"]
+ if not isinstance(checksum, str) or len(checksum) != 64 or any(c not in "0123456789abcdef" for c in checksum):
+ raise ValueError("source_sha256 must be a lowercase SHA256 hex digest")
+ _number(recording["duration_s"], "duration_s", 1e-12)
+ for name in ("sample_rate_hz", "channels"):
+ if type(recording[name]) is not int or recording[name] <= 0:
+ raise ValueError(f"{name} must be a positive integer")
+ _text(recording["source_format"], "source_format")
+ if "time_window" in recording:
+ request = validate_request({"schema_version": 1, "audio_path": "metadata-validation", "time_window": recording["time_window"]})
+ recording["time_window"] = request["time_window"]
+ return recording
+
+
+def validate_candidate(value):
+ candidate = _record(value, ("lat", "lon", "score", "score_kind", "event_ids", "flight_ids", "recording_start_utc"), ("uncertainty",))
+ _number(candidate["lat"], "lat", -90, 90)
+ _number(candidate["lon"], "lon", -180, 180)
+ _number(candidate["score"], "score")
+ _text(candidate["score_kind"], "score_kind")
+ for name in ("event_ids", "flight_ids"):
+ if not isinstance(candidate[name], list) or not candidate[name]:
+ raise ValueError(f"{name} must be a nonempty list")
+ for item in candidate[name]:
+ _text(item, name)
+ if len(candidate["event_ids"]) != len(candidate["flight_ids"]) or len(set(candidate["event_ids"])) != len(candidate["event_ids"]):
+ raise ValueError("Each distinct event must map to exactly one flight segment")
+ candidate["recording_start_utc"] = _utc(candidate["recording_start_utc"])
+ if "uncertainty" in candidate:
+ uncertainty = _record(candidate["uncertainty"], ("radius_m", "method", "kind"), ("coverage_probability", "calibration_reference"))
+ _number(uncertainty["radius_m"], "radius_m", 0)
+ _text(uncertainty["method"], "uncertainty method")
+ if uncertainty["kind"] == "calibrated":
+ _number(uncertainty.get("coverage_probability"), "coverage_probability", 0, 1)
+ _text(uncertainty.get("calibration_reference"), "calibration_reference")
+ elif uncertainty["kind"] != "sensitivity" or "coverage_probability" in uncertainty or "calibration_reference" in uncertainty:
+ raise ValueError("Uncalibrated sensitivity must not carry a probability")
+ candidate["uncertainty"] = uncertainty
+ return candidate
+
+
+def validate_result(value):
+ optional = ("stage", "progress", "recording", "coverage", "events", "candidates", "reason_code", "message", "required_fields", "artifacts")
+ result = _record(value, ("schema_version", "job_id", "status"), optional)
+ if type(result["schema_version"]) is not int or result["schema_version"] != 1:
+ raise ValueError("Unsupported schema_version")
+ _text(result["job_id"], "job_id")
+ status = result["status"]
+ if status not in ("queued", "running", "needs_input", "succeeded", "inconclusive", "failed", "cancelled"):
+ raise ValueError("Unknown job status")
+ for name in ("stage", "reason_code", "message"):
+ if name in result:
+ _text(result[name], name)
+ if "progress" in result:
+ _number(result["progress"], "progress", 0, 1)
+ if "recording" in result:
+ result["recording"] = validate_recording(result["recording"])
+ if "coverage" in result:
+ coverage = _record(result["coverage"], ("search_complete", "data_status", "limitations"), ("requested_area", "missing_data"))
+ if type(coverage["search_complete"]) is not bool or coverage["data_status"] not in ("available", "partial", "unavailable"):
+ raise ValueError("Coverage must state search completion and data availability")
+ for name in ("limitations", "missing_data"):
+ if not isinstance(coverage.get(name, []), list):
+ raise ValueError(f"{name} must be a list")
+ for description in coverage.get(name, []):
+ _text(description, name)
+ if "requested_area" in coverage:
+ coverage["requested_area"] = validate_request({"schema_version": 1, "audio_path": "coverage-validation", "search": coverage["requested_area"]})["search"]
+ result["coverage"] = coverage
+ for name, validator in (("events", validate_event), ("candidates", validate_candidate)):
+ if not isinstance(result.get(name, []), list):
+ raise ValueError(f"{name} must be a list")
+ if name in result:
+ result[name] = [validator(item) for item in result[name]]
+ ids = [event["event_id"] for event in result.get("events", [])]
+ if len(set(ids)) != len(ids):
+ raise ValueError("Event IDs must be unique")
+ if "events" in result:
+ if any(set(candidate["event_ids"]) - set(ids) for candidate in result.get("candidates", [])):
+ raise ValueError("Candidate references an absent event")
+ if status == "succeeded" and not result.get("candidates"):
+ raise ValueError("A successful location result requires a candidate")
+ candidates = result.get("candidates", [])
+ if len({candidate["score_kind"] for candidate in candidates}) > 1:
+ raise ValueError("Ranked candidates must use comparable score kinds")
+ if any(left["score"] < right["score"] for left, right in zip(candidates, candidates[1:])):
+ raise ValueError("Candidates must be ranked in descending score order")
+ if status in ("needs_input", "inconclusive", "failed"):
+ _text(result.get("reason_code"), "reason_code")
+ _text(result.get("message"), "message")
+ if "required_fields" in result:
+ if not isinstance(result["required_fields"], list):
+ raise ValueError("required_fields must be a list")
+ for name in result["required_fields"]:
+ _text(name, "required field")
+ if status == "needs_input" and not result.get("required_fields"):
+ raise ValueError("needs_input must identify required_fields")
+ artifacts = result.get("artifacts", {})
+ if not isinstance(artifacts, dict):
+ raise ValueError("artifacts must map names to job-relative paths")
+ for name, path in artifacts.items():
+ _text(name, "artifact name")
+ _text(path, "artifact path")
+ if PurePosixPath(path).is_absolute() or ".." in PurePosixPath(path).parts or "\\" in path or ":" in path:
+ raise ValueError("Artifact paths must stay relative to their job directory")
+ return result
+
+
+def event_measure_settings(value):
+ """Map an already discovered event into the unchanged research measure API."""
+ event = validate_event(value)
+ names = ("start_s", "end_s", "band_hz", "cpa_receive_s", "f0_range_hz", "speed_range_mps", "slant_range_m")
+ return {name: event[name] for name in names if name in event}
diff --git a/tests/test_contracts.py b/tests/test_contracts.py
new file mode 100644
index 0000000..1b48de9
--- /dev/null
+++ b/tests/test_contracts.py
@@ -0,0 +1,157 @@
+from copy import deepcopy
+import json
+from pathlib import Path
+
+import pytest
+
+from aircraft_geoloc.contracts import (
+ event_measure_settings, validate_candidate, validate_event, validate_recording,
+ validate_request, validate_result,
+)
+
+
+EXAMPLES = Path(__file__).resolve().parents[1] / "docs/examples"
+
+
+def example(name):
+ return json.loads((EXAMPLES / f"{name}.json").read_text())
+
+
+def test_examples_roundtrip_without_mutating_inputs():
+ for name, validator in (("analysis-request", validate_request), ("detected-event", validate_event),
+ ("job-result", validate_result), ("job-needs-input", validate_result)):
+ original = example(name)
+ before = deepcopy(original)
+ clean = validator(original)
+ assert validator(json.loads(json.dumps(clean, allow_nan=False))) == clean
+ assert original == before
+ request = {"schema_version": 1, "audio_path": "clip.mp3"}
+ assert validate_request(request)["search"] == {"coverage": "conus"}
+ assert "time_window" not in validate_request(request)
+
+
+def test_time_window_is_recording_start_with_explicit_timezone():
+ request = example("analysis-request")
+ request["time_window"].update(start_utc="2026-09-08T12:00:00+02:00", end_utc="2026-09-08T10:00:00Z")
+ assert validate_request(request)["time_window"]["start_utc"] == "2026-09-08T10:00:00Z"
+ for invalid in ("2026-09-08", "2026-09-08T12:00:00", 1788861600):
+ request["time_window"]["start_utc"] = invalid
+ with pytest.raises(ValueError):
+ validate_request(request)
+
+
[email protected]("change", [
+ {"schema_version": True}, {"schema_version": 2}, {"audio_path": ""},
+ {"true_lat": 40.0}, {"events": []}, {"search": {"coverage": "global"}},
+ {"search": {"coverage": "conus", "bounds_wsen": [-100, 40, -110, 45]}},
+ {"search": {"coverage": "conus", "bounds_wsen": [-110, 40, float("nan"), 45]}},
+])
+def test_invalid_request_and_truth_fields_rejected(change):
+ request = example("analysis-request")
+ request.update(change)
+ with pytest.raises(ValueError):
+ validate_request(request)
+
+
+def test_untrusted_time_source_and_reversed_window_rejected():
+ request = example("analysis-request")
+ request["time_window"]["source"] = "file_mtime"
+ with pytest.raises(ValueError, match="Time source"):
+ validate_request(request)
+ request["time_window"]["source"] = "user"
+ request["time_window"]["start_utc"] = "2026-09-10T00:00:00Z"
+ with pytest.raises(ValueError, match="reversed"):
+ validate_request(request)
+
+
+def test_ridge_time_and_frequency_are_recording_relative():
+ event = example("detected-event")
+ event["start_s"] = 100
+ event["end_s"] = 160
+ with pytest.raises(ValueError):
+ validate_event(event) # Chunk-local points were not shifted by +90 s.
+ for point in event["ridge"]:
+ point["time_s"] += 90
+ validate_event(event)
+ settings = event_measure_settings(event)
+ assert settings["start_s"] == 100
+ assert settings["band_hz"] == [80.0, 180.0]
+ assert "ridge" not in settings and "quality" not in settings
+ assert "f0_range_hz" not in settings # No invented rest-frequency bounds.
+
+
[email protected]("field,value", [("time_s", 40.0), ("frequency_hz", float("inf")), ("weight", -1)])
+def test_invalid_ridge_samples_rejected(field, value):
+ event = example("detected-event")
+ event["ridge"][0][field] = value
+ with pytest.raises(ValueError):
+ validate_event(event)
+
+
+def test_recording_metadata_labels_decoded_samples_and_source_hash():
+ metadata = {"source_sha256": "a" * 64, "duration_s": 60, "sample_rate_hz": 4000,
+ "channels": 1, "source_format": "mp3"}
+ assert validate_recording(metadata) == metadata
+ for change in ({"source_sha256": "missing"}, {"duration_s": 0}, {"channels": True}):
+ with pytest.raises(ValueError):
+ validate_recording(dict(metadata, **change))
+
+
+def test_uncalibrated_radius_is_not_a_probability():
+ candidate = example("job-result")["candidates"][0]
+ candidate["uncertainty"]["coverage_probability"] = 0.95
+ with pytest.raises(ValueError, match="Uncalibrated"):
+ validate_candidate(candidate)
+ candidate["uncertainty"]["kind"] = "calibrated"
+ with pytest.raises(ValueError, match="calibration_reference"):
+ validate_candidate(candidate)
+ candidate["uncertainty"]["calibration_reference"] = "evaluation/heldout-report.json"
+ validate_candidate(candidate)
+
+
+def test_job_decisions_require_support_or_explanations():
+ result = {"schema_version": 1, "job_id": "job", "status": "succeeded"}
+ with pytest.raises(ValueError, match="requires a candidate"):
+ validate_result(result)
+ for status in ("inconclusive", "failed", "needs_input"):
+ result["status"] = status
+ with pytest.raises(ValueError):
+ validate_result(result)
+ result = example("job-needs-input")
+ del result["required_fields"]
+ with pytest.raises(ValueError, match="required_fields"):
+ validate_result(result)
+
+
+def test_ranked_candidates_must_be_comparable_and_reference_real_events():
+ result = example("job-result")
+ result["candidates"][0]["event_ids"] = ["absent-event"]
+ with pytest.raises(ValueError, match="absent event"):
+ validate_result(result)
+ result = example("job-result")
+ result["candidates"].append(deepcopy(result["candidates"][0]))
+ result["candidates"][1]["score_kind"] = "unrelated_score"
+ with pytest.raises(ValueError, match="comparable"):
+ validate_result(result)
+ result["candidates"][1]["score_kind"] = result["candidates"][0]["score_kind"]
+ result["candidates"][1]["score"] = 100
+ with pytest.raises(ValueError, match="descending"):
+ validate_result(result)
+
+
+def test_coverage_distinguishes_finished_search_from_available_data():
+ result = example("job-result")
+ result["coverage"] = {"search_complete": False, "data_status": "available",
+ "limitations": ["Only one tile searched; ADS-B capture can miss aircraft."]}
+ assert validate_result(result)["coverage"]["search_complete"] is False
+ result["coverage"]["search_complete"] = "yes"
+ with pytest.raises(ValueError, match="Coverage"):
+ validate_result(result)
+
+
[email protected]("path", ["../other-job/file.json", "/etc/passwd", "C:\\private\\file", "nested/../../file"])
+def test_artifact_paths_cannot_leave_job_directory(path):
+ result = example("job-result")
+ result["artifacts"]["report"] = path
+ with pytest.raises(ValueError, match="relative"):
+ validate_result(result)