Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Verify real terminal controls and guidance without hiding failures
Cinna Davisa20bd1784e65
diff --git a/docs/INCONCLUSIVE_GUIDANCE.md b/docs/INCONCLUSIVE_GUIDANCE.mdindex e1da3e6..9ac4687 100644--- a/docs/INCONCLUSIVE_GUIDANCE.md+++ b/docs/INCONCLUSIVE_GUIDANCE.md@@ -86,6 +86,16 @@ downloads stayed unchanged. Delayed guidance responses did not overwrite a laterrender of the same job. These checks did not publish the source jobs or modifytheir original directories.+The browser verifier now checks guidance on every actual upload or saved-job+readback. `--expect-guidance-code` can require a specific observation. Additional+completed real jobs verified `no_events`, `data_access_limit` and `work_limit`+at desktop and mobile widths, including a reload. The latter two came from fresh+whole-reference uploads with an empty offline cache or a 30-second worker limit.+Every cited field resolved, the visible advice matched the API, and saved evidence+bytes stayed unchanged. Both new uploads also passed HTTP service restart checks.+The runtime control ended an incomplete regional development search; it supplies+no national completion, location accuracy or measured-benefit evidence.+Issue [#63](https://github.com/1337isnot1337/DOPPLERGEIST/issues/63) remains open.Its acceptance still requires completed real jobs for the remaining reasons and bothpositive and negative controls for narrower clocks or additional independentdiff --git a/docs/PRODUCT.md b/docs/PRODUCT.mdindex f35ec9d..df24f06 100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@ -168,6 +168,69 @@ evaluate location error against an independent reference after the run. Theverifier reports operational verification and `supported_decision` separately.It counts independent harmonic groups separately from their ridge records.+### Verify runtime limits, cancellation and restart++`--timeout-s` bounds the entire verification. `--job-max-runtime-s` separately+bounds the actual worker. It defaults to `--timeout-s` for existing callers.+Allow time for service startup, upload, terminal readback and shutdown when testing+a worker limit. A verifier timeout does not count as an observed `work_limit`.++```bash+python scripts/verify_upload_http.py \+ --audio path/to/real-recording.mp3 --operator-config operator.json \+ --start-utc "$RECORDING_START_UTC_MIN" --end-utc "$RECORDING_START_UTC_MAX" \+ --expect-status inconclusive --expect-reason work_limit \+ --job-max-runtime-s 30 --timeout-s 180 --verify-restart \+ --output results/new-real-runtime-control+```++Use a recording and budget that actually reach the intended limit. A different+terminal outcome fails the declared expectation and remains in the output.+For an API cancellation control, use `--cancel-at-stage discovery` with+`--expect-status cancelled`. The verifier waits for that actual running stage+before it sends the cancellation request. It fails if the job finishes first.+The cancellation response and terminal result must both confirm `cancelled`,+even when a Python caller uses `expect_status=None`.++`--verify-restart` stops the verifier's service, starts a new service over its+completed job, and reads the result and original audio through HTTP again.+It checks unchanged saved result bytes and original audio. A cancellation control+also repeats cancellation after restart and requires the terminal result to stay+unchanged. These operations affect only the new verification directory.++To exercise unavailable data, supply a new empty cache with `offline: true` and+a recording-start window. Preserve the actual `data_unavailable` outcome;+do not replace it with a successful result. These terminal controls do not satisfy+`--require-full-pipeline` or establish a supported location.++Python callers can pass `expect_status=None` to observe any terminal outcome.+All input, artifact and stage checks still apply, including+`require_full_pipeline=True` when requested. The CLI requires `--expect-status`.+The optional Python arguments are `job_max_runtime_s=None`,+`cancel_at_stage=None` and `verify_restart=False`.++### Verify guidance in the browser++The browser verifier checks actual guidance at desktop and mobile widths. It+compares each observation, suggestion and evidence link with the API response.+Every evidence pointer must resolve in the saved result or decision artifact.+Downloaded evidence must match the saved bytes, which must remain unchanged.++```bash+python scripts/verify_real_upload_browser.py \+ --saved-job path/to/completed-real-job --source src \+ --expect-status inconclusive --expect-reason no_supported_events \+ --expect-guidance-code no_events \+ --output results/new-real-guidance-readback+```++Repeat `--expect-guidance-code` to require several observations. Use `work_limit`+for a completed runtime-limit case and `data_access_limit` for an unavailable-data+case with a recorded acquisition limit. The saved job is copied before readback.+No job is resumed and no result is manufactured. The check preserves the saved+status, candidates and scores. Issue #63 still requires real positive and negative+counterfactual controls before it can claim measured guidance benefit.+## Provider and search configuration`--online` requires no JSON configuration: it uses the per-user cache and publicdiff --git a/scripts/verify_real_upload_browser.py b/scripts/verify_real_upload_browser.pyindex 64f0d48..690ee15 100644--- a/scripts/verify_real_upload_browser.py+++ b/scripts/verify_real_upload_browser.py@@ -22,7 +22,7 @@ import signalimport subprocessimport sysimport time-from urllib.parse import quote+from urllib.parse import quote, unquotedef require(condition, message):@@ -35,6 +35,28 @@ def digest(path):return hashlib.file_digest(stream, "sha256").hexdigest()+def resolve_evidence(reference, documents):+ """Resolve the guidance contract's artifact-relative JSON pointer."""+ require(isinstance(reference, str), "Guidance evidence must be a string")+ artifact, separator, pointer = reference.partition("#")+ require(separator and artifact in {"result.json", "decision.json"}, "Unknown guidance artifact")+ require(artifact in documents, f"Missing guidance artifact: {artifact}")+ pointer = unquote(pointer)+ require(pointer == "" or pointer.startswith("/"), "Guidance evidence is not a JSON pointer")+ value = documents[artifact]+ for encoded in pointer.split("/")[1:] if pointer else []:+ require(re.search(r"~(?![01])", encoded) is None, "Invalid JSON pointer escape")+ key = encoded.replace("~1", "/").replace("~0", "~")+ if isinstance(value, list):+ require(re.fullmatch(r"0|[1-9][0-9]*", key) is not None and int(key) < len(value),+ f"Guidance array reference does not exist: {reference}")+ value = value[int(key)]+ else:+ require(isinstance(value, dict) and key in value, f"Guidance field does not exist: {reference}")+ value = value[key]+ return value++def stop_service(process):"""Signal only the process group created by this verifier."""sent = []@@ -63,6 +85,8 @@ def main():parser.add_argument("--browser-executable", type=Path, help="Use an existing Chromium executable")parser.add_argument("--expect-status", choices=("needs_input", "failed", "inconclusive", "succeeded", "cancelled"), default="needs_input")parser.add_argument("--expect-reason", default="recording_time_required", help="Expected actual reason code; an empty string expects none")+ parser.add_argument("--expect-guidance-code", action="append", default=[],+ help="Require this actual guidance code; repeat for multiple observations")parser.add_argument("--output", required=True, type=Path, help="New directory; existing paths are refused")parser.add_argument("--timeout", type=float, default=900, help="Overall verification budget in seconds")args = parser.parse_args()@@ -221,6 +245,65 @@ def main():if args.expect_reason == "recording_time_required":require("time_window" in final.get("required_fields", []), "API omitted required time_window")require(not final.get("candidates"), "Undated result contains location candidates")+ evidence_bytes = {name: (job_directory / name).read_bytes()+ for name in ("result.json", "decision.json") if (job_directory / name).is_file()}+ documents = {name: json.loads(content) for name, content in evidence_bytes.items()}+ reply = context.request.get(origin + f"/api/jobs/{job_id}/guidance", timeout=milliseconds(30))+ require(reply.status == 200, f"Guidance API returned HTTP {reply.status}")+ advice = reply.json()+ require(advice.get("schema_version") == 1 and advice.get("job_id") == job_id+ and advice.get("status") == final["status"]+ and advice.get("reason_code") == final.get("reason_code")+ and advice.get("ranked") is False and isinstance(advice.get("items"), list),+ "Guidance API does not describe the saved result")+ references = []+ for item in advice["items"]:+ require(isinstance(item, dict) and item.get("benefit") == "unmeasured"+ and all(isinstance(item.get(key), str) and item[key]+ for key in ("code", "observation", "suggestion"))+ and isinstance(item.get("evidence"), list) and item["evidence"],+ "Guidance item lacks its observation, conditional suggestion, or evidence")+ for reference in item["evidence"]:+ resolve_evidence(reference, documents)+ references.append(reference)+ for artifact in sorted({reference.split("#", 1)[0] for reference in references}):+ reply = context.request.get(origin + f"/api/jobs/{job_id}/artifacts/{artifact}", timeout=milliseconds(30))+ require(reply.status == 200 and reply.body() == evidence_bytes[artifact],+ "Guidance artifact download differs from the saved bytes")+ codes = [item["code"] for item in advice["items"]]+ require(set(args.expect_guidance_code).issubset(codes), "Required guidance code was not produced")+ summary["guidance"] = {"codes": codes, "ranked": advice["ranked"],+ "resolved_evidence": sorted(set(references)), "viewports_verified": []}++ def check_guidance(viewport):+ panel = page.locator("#guidance")+ cards = panel.locator(":scope > .candidate")+ expect(cards).to_have_count(len(advice["items"]), timeout=milliseconds(30))+ if advice["items"]:+ expect(panel).to_be_visible(timeout=milliseconds(10))+ expect(panel.locator(":scope > .help")).to_have_text(+ "These suggestions are not ranked. Their benefit has not been measured.", timeout=milliseconds(10))+ else:+ expect(panel).to_be_hidden(timeout=milliseconds(10))+ for index, item in enumerate(advice["items"]):+ card = cards.nth(index)+ expect(card).to_be_visible(timeout=milliseconds(10))+ expect(card.locator(":scope > p")).to_have_text(+ [item["observation"], item["suggestion"]], timeout=milliseconds(10))+ details = card.locator("details")+ if details.get_attribute("open") is None:+ details.locator("summary").click(timeout=milliseconds(10))+ links = details.locator("a")+ expect(links).to_have_text(item["evidence"], timeout=milliseconds(10))+ for link_index, reference in enumerate(item["evidence"]):+ link = links.nth(link_index)+ expect(link).to_be_visible(timeout=milliseconds(10))+ expect(link).to_have_attribute("href", f"/api/jobs/{job_id}/artifacts/" + reference.split("#", 1)[0])+ reply = context.request.get(origin + f"/api/jobs/{job_id}/guidance", timeout=milliseconds(30))+ require(reply.status == 200 and reply.json() == advice, "Guidance changed during browser readback")+ require(all((job_directory / name).read_bytes() == content for name, content in evidence_bytes.items()),+ "Guidance readback changed the saved evidence")+ summary["guidance"]["viewports_verified"].append(viewport)def check_display():expect(page.locator("#status")).to_have_text(args.expect_status.replace("_", " "), timeout=milliseconds(30))@@ -250,6 +333,10 @@ def main():expect(page.locator("#connection")).to_have_text("", timeout=milliseconds(10))check_display()+ check_guidance("desktop")+ if advice["items"]:+ page.locator("#guidance").screenshot(path=str(output / "guidance-desktop.png"), timeout=milliseconds(10))+ screenshots.append("guidance-desktop.png")summary["displayed_event_count"] = page.locator("#events .event").count()summary["displayed_candidate_count"] = page.locator("#candidates .candidate").count()summary["required_message"] = page.locator("#required").inner_text()@@ -304,11 +391,24 @@ def main():require(page.url == saved_url, "Saved job URL changed")page.reload(wait_until="domcontentloaded", timeout=milliseconds(30))check_display()+ check_guidance("desktop_reload")expect(original_link).to_have_count(1, timeout=milliseconds(30))check_diagnostics()expect(page.locator("#connection")).to_have_text("", timeout=milliseconds(10))require(api_result() == final, "Terminal API result changed after reload")summary["saved_job_reload_verified"] = True+ page.set_viewport_size({"width": 390, "height": 844})+ page.reload(wait_until="domcontentloaded", timeout=milliseconds(30))+ check_display()+ check_guidance("mobile")+ require(api_result() == final, "Mobile readback changed the terminal API result")+ if advice["items"]:+ page.locator("#guidance").screenshot(path=str(output / "guidance-mobile.png"), timeout=milliseconds(10))+ screenshots.append("guidance-mobile.png")+ page.locator("#status").scroll_into_view_if_needed(timeout=milliseconds(10))+ page.screenshot(path=str(output / "result-mobile.png"), timeout=milliseconds(10))+ screenshots.append("result-mobile.png")+ summary["guidance"]["saved_evidence_unchanged"] = Truerequest = json.loads((job_directory / "request.json").read_text())if saved_job is None and wire is None:require(not request.get("time_window"), "Browser unexpectedly supplied a recording time")diff --git a/scripts/verify_upload_http.py b/scripts/verify_upload_http.pyindex c17bd04..1c62af3 100644--- a/scripts/verify_upload_http.py+++ b/scripts/verify_upload_http.py@@ -6,7 +6,8 @@ The receipt separately preserves the producer's scientific status. An expectedinconclusive response is never counted as supported localization or accuracy.With --require-full-pipeline, verification also requires every pipeline stageand at least one returned candidate; an early exit cannot pass that requirement.-The existing browser verifier is independent and remains unchanged.+The browser verifier checks rendering separately. Optional runtime, cancellation,+and restart controls exercise actual terminal behavior without replacing workers."""from __future__ import annotations@@ -32,6 +33,9 @@ from dopplergeist.contracts import utc_timestamp, validate_recording, validate_rfrom dopplergeist.jobs import TERMINAL, write_json+CANCELLABLE_STAGES = ("intake", "discovery", "acquisition", "search", "refinement", "decision")++def _implementation_files(package):"""Independently cover Python sources, native C, and loaded-format binaries."""return sorted(path for path in package.iterdir()@@ -178,7 +182,8 @@ def wait_for_service(process, log_path, deadline):time.sleep(min(0.05, remaining(deadline)))-def poll_job(client, job_id, history_path, *, interval_s):+def poll_job(client, job_id, history_path, *, interval_s, cancel_at_stage=None, cancellation=None):+ cancellation = {} if cancellation is None else cancellationwith history_path.open("x") as history:previous = Nonewhile True:@@ -191,10 +196,75 @@ def poll_job(client, job_id, history_path, *, interval_s):history.flush()previous = valueif value["status"] in TERMINAL:+ if cancel_at_stage is not None and not cancellation:+ raise ValueError(f"Job ended before cancellation stage {cancel_at_stage!r} was observed")return value+ if (cancel_at_stage is not None and not cancellation+ and value["status"] == "running" and value.get("stage") == cancel_at_stage):+ cancellation.update(observed_status=value["status"], observed_stage=value["stage"],+ requested_utc=now())+ code, reply = client.request("POST", f"/api/jobs/{job_id}/cancel")+ cancellation["http_status"] = code+ if code != 200:+ raise ValueError(f"Cancellation returned HTTP {code}")+ validate_result(reply)+ if reply["job_id"] != job_id:+ raise ValueError("Cancellation returned a different job")+ cancellation["response_status"] = reply["status"]time.sleep(min(interval_s, remaining(client.deadline)))+def inspect_restart(output, command, environment, final, source_sha256, deadline,+ termination, report, *, repeat_cancel=False):+ """Restart only this verifier's service and read its completed job again."""+ directory = output / "jobs" / final["job_id"]+ result_digest = sha256(directory / "result.json")+ process = None+ report.update(passed=False, service={"shutdown_signal": None, "forced_kill": False, "returncode": None})+ try:+ with (output / "restart-service.log").open("xb") as log:+ try:+ termination.interruptible = False+ process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT,+ env=environment, start_new_session=True)+ report["service"]["pid"] = process.pid+ termination.interruptible = True+ termination.raise_if_interrupted()+ client = wait_for_service(process, output / "restart-service.log", deadline)+ report["service"]["port"] = client.port+ job_path = f"/api/jobs/{final['job_id']}"+ if client.get(job_path) != final:+ raise ValueError("Restart changed the completed API result")+ if repeat_cancel:+ code, cancelled = client.request("POST", job_path + "/cancel")+ if code != 200 or cancelled != final:+ raise ValueError("Repeated cancellation changed the completed result")+ report["terminal_cancel_idempotent"] = True+ code, _ = client.request("GET", job_path + "/artifacts/input.mp3",+ destination=output / "downloaded-original-after-restart.mp3")+ if code != 200 or sha256(output / "downloaded-original-after-restart.mp3") != source_sha256:+ raise ValueError("Restart changed the original MP3 download")+ code, _ = client.request("GET", job_path + "/artifacts/result.json",+ destination=output / "downloaded-result-after-restart.json")+ if code != 200 or sha256(output / "downloaded-result-after-restart.json") != result_digest:+ raise ValueError("Restart changed the saved result bytes")+ if client.get(job_path) != final:+ raise ValueError("Terminal API result changed during restart readback")+ report.update(terminal_readback_verified=True, original_download_verified=True,+ saved_result_bytes_verified=True)+ finally:+ termination.interruptible = False+ stop_service(process, report, termination)+ if report["service"]["returncode"] != 0 or report["service"]["forced_kill"]:+ raise ValueError("Restarted service did not stop cleanly")+ if sha256(directory / "result.json") != result_digest or sha256(directory / "input.mp3") != source_sha256:+ raise ValueError("Restart shutdown changed completed artifacts")+ report["passed"] = True+ finally:+ termination.interruptible = True+ termination.raise_if_interrupted()++def inspect_job(directory, final, wire, operator, original, implementation):"""Check actual persisted evidence without changing it or opening truth."""read = lambda path: json.loads((directory / path).read_text())@@ -1029,13 +1099,25 @@ def inspect_pipeline_evidence(directory, final, wire, operator):def verify_http(audio, output, *, request=None, operator=None, expect_status,expect_reason=None, timeout_s=600.0, poll_interval_s=0.25,- require_full_pipeline=False):- if expect_status not in TERMINAL:- raise ValueError("Declare an expected terminal status before execution")+ require_full_pipeline=False, job_max_runtime_s=None,+ cancel_at_stage=None, verify_restart=False):+ """Verify an actual upload; None observes any terminal status for callers.++ A missing job runtime preserves the original timeout_s worker allowance.+ Give the client a larger timeout to observe an intentional worker time limit.+ """+ if expect_status is not None and expect_status not in TERMINAL:+ raise ValueError("Expected status must be terminal or None for observation")if type(require_full_pipeline) is not bool:raise ValueError("require_full_pipeline must be a boolean")- for name, value in (("timeout_s", timeout_s), ("poll_interval_s", poll_interval_s)):- if not math.isfinite(value) or value <= 0:+ if type(verify_restart) is not bool:+ raise ValueError("verify_restart must be a boolean")+ if cancel_at_stage is not None and cancel_at_stage not in CANCELLABLE_STAGES:+ raise ValueError("Cancellation stage must be an actual running pipeline stage")+ job_runtime = timeout_s if job_max_runtime_s is None else job_max_runtime_s+ for name, value in (("timeout_s", timeout_s), ("poll_interval_s", poll_interval_s),+ ("job_max_runtime_s", job_runtime)):+ if isinstance(value, bool) or not math.isfinite(value) or value <= 0:raise ValueError(f"{name} must be finite and positive")audio = Path(audio).resolve(strict=True)if audio.suffix.lower() != ".mp3" or not audio.is_file():@@ -1055,7 +1137,9 @@ def verify_http(audio, output, *, request=None, operator=None, expect_status,deadline = began + timeout_sreceipt = {"schema_version": 1, "scope": "actual_local_http_upload_verification","started_utc": now(), "expected_status": expect_status, "expected_reason": expect_reason,- "timeout_s": timeout_s, "source_sha256": sha256(audio), "source_bytes": audio.stat().st_size,+ "timeout_s": timeout_s, "job_max_runtime_s": job_runtime,+ "cancel_at_stage": cancel_at_stage, "verify_restart": verify_restart,+ "source_sha256": sha256(audio), "source_bytes": audio.stat().st_size,"request": wire, "implementation_files": implementation, "verifier_sha256": sha256(__file__),"python_executable": sys.executable, "python_version": sys.version,"verification_passed": False, "http_checks_passed": False, "pipeline_evidence_passed": False,@@ -1073,7 +1157,7 @@ def verify_http(audio, output, *, request=None, operator=None, expect_status,termination.raise_if_interrupted()command = [sys.executable, "-m", "dopplergeist.cli", "serve", "--port", "0","--jobs", str(output / "jobs"), "--config", str(output / "operator.json"),- "--max-runtime", str(timeout_s)]+ "--max-runtime", str(job_runtime)]receipt["service"]["command"] = commandenv = dict(os.environ, PYTHONPATH=str(package.parent) + os.pathsep + os.environ.get("PYTHONPATH", ""),MPLBACKEND="Agg")@@ -1085,7 +1169,10 @@ def verify_http(audio, output, *, request=None, operator=None, expect_status,termination.raise_if_interrupted()client = wait_for_service(process, output / "service.log", deadline)receipt["service"]["port"] = client.port- write_json(output / "capabilities.json", client.get("/api/capabilities"))+ capabilities = client.get("/api/capabilities")+ write_json(output / "capabilities.json", capabilities)+ if capabilities.get("max_runtime_s") != job_runtime:+ raise ValueError("Service did not retain the requested job runtime")with audio.open("rb") as stream:code, queued = client.request("POST", "/api/jobs", body=stream, headers={"Content-Type": "application/octet-stream", "Content-Length": str(audio.stat().st_size),@@ -1098,11 +1185,20 @@ def verify_http(audio, output, *, request=None, operator=None, expect_status,if uuid.UUID(job_id).hex != job_id:raise ValueError("Service returned an invalid job identifier")receipt["job_id"] = job_id- final = poll_job(client, job_id, output / "history.jsonl", interval_s=poll_interval_s)+ cancellation = {}+ if cancel_at_stage is not None:+ receipt["cancellation"] = cancellation+ final = poll_job(client, job_id, output / "history.jsonl", interval_s=poll_interval_s,+ cancel_at_stage=cancel_at_stage, cancellation=cancellation)write_json(output / "result.json", final)receipt.update(status=final["status"], reason_code=final.get("reason_code"),producer_reported_success=final["status"] == "succeeded",candidate_count=len(final.get("candidates", [])), event_count=len(final.get("events", [])))+ if cancel_at_stage is not None:+ cancellation["confirmed"] = (cancellation.get("response_status") == "cancelled"+ and final["status"] == "cancelled")+ if not cancellation["confirmed"]:+ raise ValueError("Cancellation was requested, but the job did not finish cancelled")listing = client.get(f"/api/jobs/{job_id}/artifacts")write_json(output / "artifacts.json", listing)if sum(item["path"] == "input.mp3" for item in listing["artifacts"]) != 1:@@ -1116,8 +1212,18 @@ def verify_http(audio, output, *, request=None, operator=None, expect_status,receipt["checks"] = inspect_job(output / "jobs" / job_id, final, wire, operator, audio, implementation)receipt["checks"].update(downloaded_original_verified=True, downloaded_result_verified=True)receipt["http_checks_passed"] = True- receipt["expectation_matched"] = (final["status"] == expect_status+ receipt["expectation_matched"] = ((expect_status is None or final["status"] == expect_status)and (expect_reason is None or final.get("reason_code") == expect_reason))+ if verify_restart:+ termination.interruptible = False+ stop_service(process, receipt, termination)+ termination.interruptible = True+ termination.raise_if_interrupted()+ if receipt["service"]["returncode"] != 0 or receipt["service"]["forced_kill"]:+ raise ValueError("Initial service did not stop cleanly before readback")+ receipt["restart_readback"] = {}+ inspect_restart(output, command, env, final, receipt["source_sha256"], deadline,+ termination, receipt["restart_readback"], repeat_cancel=bool(cancellation))except Exception as exc:receipt["error"] = f"{type(exc).__name__}: {exc}"receipt["timed_out"] = isinstance(exc, TimeoutError)@@ -1156,7 +1262,8 @@ def verify_http(audio, output, *, request=None, operator=None, expect_status,and receipt.get("pipeline_evidence_preserved_after_inspection") and receipt["implementation_unchanged"]and receipt.get("terminal_result_preserved_after_shutdown")and receipt["service"]["returncode"] == 0 and not receipt["service"]["forced_kill"]- and not receipt.get("shutdown_error") and not receipt["interrupted"])+ and not receipt.get("shutdown_error") and not receipt["interrupted"]+ and (not verify_restart or receipt.get("restart_readback", {}).get("passed")))if require_full_pipeline and not receipt["full_pipeline_requirements_met"]:receipt["requirement_error"] = ("Full pipeline verification requires verified acquisition, search, refinement, "@@ -1193,6 +1300,12 @@ def main(argv=None):parser.add_argument("--require-full-pipeline", action="store_true",help="Fail unless every pipeline stage is verified and at least one candidate is returned")parser.add_argument("--timeout-s", type=float, default=600)+ parser.add_argument("--job-max-runtime-s", type=float,+ help="Worker time budget; defaults to --timeout-s. Use a smaller value to verify work_limit")+ parser.add_argument("--cancel-at-stage", choices=CANCELLABLE_STAGES,+ help="Request actual API cancellation after this running stage is observed")+ parser.add_argument("--verify-restart", action="store_true",+ help="Restart this verifier's service and verify unchanged completed artifacts through HTTP")parser.add_argument("--poll-interval-s", type=float, default=0.25)args = parser.parse_args(argv)if args.end_utc and not args.start_utc:@@ -1206,7 +1319,8 @@ def main(argv=None):receipt = verify_http(args.audio, args.output, request=request, operator=operator,expect_status=args.expect_status, expect_reason=args.expect_reason,timeout_s=args.timeout_s, poll_interval_s=args.poll_interval_s,- require_full_pipeline=args.require_full_pipeline)+ require_full_pipeline=args.require_full_pipeline, job_max_runtime_s=args.job_max_runtime_s,+ cancel_at_stage=args.cancel_at_stage, verify_restart=args.verify_restart)except (OSError, ValueError, TypeError) as exc:parser.error(str(exc))print(json.dumps({"report": str(args.output.resolve() / "http-verification.json"),diff --git a/tests/test_real_upload_terminal_controls.py b/tests/test_real_upload_terminal_controls.pynew file mode 100644index 0000000..d2fc631--- /dev/null+++ b/tests/test_real_upload_terminal_controls.py@@ -0,0 +1,66 @@+"""Actual upload cancellation controls; require an existing real-recording job.++The race control delays only the outgoing cancel request until the real worker+finishes. All audio, worker execution and HTTP responses remain actual inputs.+"""+import importlib.util+import json+import os+from pathlib import Path+import time++import pytest+++ROOT = Path(__file__).parents[1]+SPEC = importlib.util.spec_from_file_location("verify_real_terminal_controls",+ ROOT / "scripts/verify_upload_http.py")+HTTP = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(HTTP)++[email protected]("delay_cancel", [False, True], ids=["cancel-running", "completion-wins-race"])+def test_actual_cancellation_must_be_confirmed_even_without_expected_status(tmp_path, monkeypatch, delay_cancel):+ saved = os.environ.get("DOPPLERGEIST_REAL_UPLOAD_JOB")+ if not saved:+ pytest.skip("Set DOPPLERGEIST_REAL_UPLOAD_JOB to a real job with MP3 and recording-start window")+ source = Path(saved)+ request = json.loads((source / "request.json").read_text())+ request.pop("audio_path")+ assert request.get("time_window"), "The actual recording needs its existing recording-start window"+ audio = source / "input.mp3"+ assert HTTP.sha256(audio) == json.loads((source / "input.json").read_text())["sha256"]+ real_request = HTTP.LocalClient.request++ def request_after_real_completion(client, method, path, **kwargs):+ if delay_cancel and method == "POST" and path.endswith("/cancel"):+ while True:+ status, current = real_request(client, "GET", path.rsplit("/", 1)[0])+ assert status == 200+ if current["status"] in HTTP.TERMINAL:+ break+ time.sleep(min(0.02, HTTP.remaining(client.deadline)))+ return real_request(client, method, path, **kwargs)++ monkeypatch.setattr(HTTP.LocalClient, "request", request_after_real_completion)+ cache = tmp_path / "empty-offline-cache"+ cache.mkdir()+ output = tmp_path / "upload"+ receipt = HTTP.verify_http(audio, output, request=request,+ operator={"offline": True, "cache_root": str(cache)}, expect_status=None,+ cancel_at_stage="discovery", job_max_runtime_s=90, timeout_s=120, poll_interval_s=0.05)+ assert receipt["expected_status"] is None+ assert receipt["cancellation"]["observed_status"] == "running"+ assert receipt["cancellation"]["observed_stage"] == "discovery"+ assert receipt["cancellation"]["http_status"] == 200+ result = json.loads((output / "result.json").read_text())+ assert HTTP.sha256(output / "jobs" / result["job_id"] / "input.mp3") == HTTP.sha256(audio)+ if delay_cancel:+ assert result["status"] == "failed" and result["reason_code"] == "data_unavailable"+ assert receipt["cancellation"]["confirmed"] is False+ assert receipt["verification_passed"] is False+ assert "did not finish cancelled" in receipt["error"]+ else:+ assert result["status"] == "cancelled"+ assert receipt["cancellation"]["confirmed"] is True+ assert receipt["verification_passed"] is True