Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Account for bounded unknown competitors and verify installed real audio intake
Cinna Davisb7bfa99408b2
diff --cc .github/workflows/checkpoint-replay.ymlindex f156049,d4a11b2..1515f5e--- a/.github/workflows/checkpoint-replay.yml+++ b/.github/workflows/checkpoint-replay.yml@@@ -1,8 -1,8 +1,6 @@@--name: Checkpoint methodology replay++name: Historical real regional replay (manual)on:-- push:-- branches: [worker/ci-checkpoint-20261102]workflow_dispatch:permissions:@@@ -20,7 -20,7 +18,9 @@@ envjobs:synthetic:-- name: Clean install, tests, and synthetic replay++ name: Historical synthetic replay (disabled by owner directive)++ # Preserve the historical lane without executing prohibited synthetic work.++ if: ${{ false }}runs-on: ubuntu-24.04timeout-minutes: 40steps:@@@ -92,8 -92,8 +92,7 @@@retention-days: 30regional:-- name: Checksummed regional real-audio replay-- needs: synthetic++ name: Source-informed real regional replay; no independent accuracy claimruns-on: ubuntu-24.04timeout-minutes: 40steps:diff --cc .github/workflows/tests.ymlindex 04d03f4,74b9b48..3a0d11e--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@@ -1,4 -1,4 +1,4 @@@--name: Tests++name: Installation and static checkson:push:branches: [main]@@@ -14,6 -14,6 +14,7 @@@ concurrencyjobs:test:++ name: Python ${{ matrix.python }} installation and static checksruns-on: ubuntu-24.04strategy:fail-fast: false@@@ -26,12 -26,12 +27,31 @@@python-version: ${{ matrix.python }}cache: pipcache-dependency-path: pyproject.toml-- - name: Install ffmpeg and package++ - name: Install runtime and packagerun: |sudo apt-get updatesudo apt-get install -y ffmpeg-- python -m pip install '.[test]'-- - name: Test-- run: python -m pytest -q++ python -m pip install .++ python -m pip check++ # The owner requires real recordings for further validation. The historical++ # pytest suite generates synthetic inputs, so this workflow does not run it.++ - name: Compile source without executing experiments++ run: python -m compileall -q src scripts- name: CLI smoke check- run: aircraft-geoloc --help+ run: dopplergeist --help++ - name: Check installed modules and packaged browser assets++ run: |++ python -I - <<'PY'++ from importlib import resources++ from pathlib import Path++ import dopplergeist++ from dopplergeist import automatic, jobs, service++++ package = Path(dopplergeist.__file__).resolve().parent++ assert "site-packages" in package.parts, package++ web = resources.files("dopplergeist.web")++ for name in ("index.html", "app.js", "style.css"):++ assert web.joinpath(name).is_file(), name++ assert web.joinpath(name).read_bytes(), name++ print("Installed package imports and browser assets passed; no audio or tracks generated.")++ PYdiff --cc AGENTS.mdindex 5c5748c,76c2a6b..3984825--- a/AGENTS.md+++ b/AGENTS.md@@@ -94,6 -95,22 +95,28 @@@ documentation that asks for exhaustivenames once active work and downstream dependencies are accounted for. Neverdiscard unique useful changes or interfere with another worker's active checkout.+ ## Real-world data only++ **The owner requires REAL recordings and real-world geolocation tests. NO MORE+ SYNTHETIC DATA.** Stop synthetic benchmark and data-generation work. Do not launch+ new generated flyover recordings, aircraft-track fixtures, synthetic baselines,+ null recordings or artificial benchmark corpora. Existing synthetic results are+ historical; they do not satisfy the current validation requirement.++ - Use actual audio and historical aircraft observations for empirical evaluation.+ Establish a defensible recording time and independent location reference; report+ uncertainty or missing ground truth honestly.+ - Prioritize obtaining usable real recordings and making the pipeline work on them.+ Do not substitute another simulated success or detection-only fixture for this.+ - Existing unit tests remain software checks, not real-world validation. Do not+ expand them into more fake field data or use their counts as accuracy evidence.++- Do not launch suites that generate or use synthetic data. This restriction++ applies to automatic CI and manual checks. Stop active synthetic runs and++ preserve their interrupted outputs.++- The planned canonical synthetic three-event baseline and 3/4/6-event sweeps are++ cancelled. Do not replace them with another synthetic fixture. Preserve existing++ synthetic code, data and results as historical material.+## Scientific and product boundaries- Audio-relative seconds and absolute UTC are distinct. File modification/upload@@@ -125,8 -142,8 +148,9 @@@- Preserve `evidence/` and historical `results/`. Use a new output directory foreach actual experiment so failures are not overwritten. A short note of thesource version, settings and result is enough; exhaustive hashes are not required.--- Standard check: `.venv/bin/python -m pytest -q` after installing the project and-- pytest. Run additional checks appropriate to the changed behavior.++- Standard checks cover installation, source compilation, CLI help and packaged++ assets without generated data. Use real recordings for pipeline verification.++ Older blanket pytest instructions do not override the real-world data policy.- Final PR/task handoff: concrete change, relevant test command/result and remaininglimits. Link necessary outputs rather than creating another receipt package.Do not claim unrun checks.diff --cc README.mdindex 70e732a,f563e70..0c6572f--- a/README.md+++ b/README.md@@@ -17,16 -30,9 +30,9 @@@ git clone https://github.com/1337isnot1cd DOPPLERGEISTpython -m venv .venv.venv/bin/python -m pip install -e '.[test]'-- .venv/bin/python scripts/make_synthetic_cases.py- .venv/bin/aircraft-geoloc run \- data/synthetic/known-time-minute.json \- --output results/known-time-demo```- This generates deterministic audio and flight tracks, then runs a **configured synthetic localization experiment** with a known recording clock and a selected 60-second event. It needs no external datasets or data-service credentials. Inspect `results/known-time-demo/report.json` for the leading hypothesis, `ranked.json` for alternatives, and the PNG plots for diagnostic comparisons. The historical checkpoint identified the correct flight with **40.87 m error**; this is a synthetic result, not a real-world accuracy claim.---Use a new output directory for each experiment. Run the tests with `.venv/bin/python -m pytest -q`. For pinned environments and clean-install evidence, see [Setup](docs/SETUP.md); native Windows execution has not been verified.++Use a new output directory for each experiment. Automatic CI checks installation, source compilation, CLI help and packaged assets without generated data. The [real-world data policy](AGENTS.md#real-world-data-only) supersedes older blanket pytest instructions. For pinned environments and historical clean-install evidence, see [Setup](docs/SETUP.md). Native Windows execution remains unverified.### Discover events in a recordingdiff --cc docs/FINITE_SEARCH_DECISION.mdindex 0000000,005d4ce..abbee53mode 000000,100644..100644--- a/docs/FINITE_SEARCH_DECISION.md+++ b/docs/FINITE_SEARCH_DECISION.md@@@ -1,0 -1,132 +1,157 @@@+ # Proposed finite-search decision evidence++ This additive consumer implements the conditional scope agreed in+ [the finite-search topic](https://github.com/1337isnot1337/DOPPLERGEIST/discussions/39#discussioncomment-19363838).+ W2 owns computing search/retention evidence, W5 owns stable mode mappings and+ actual assessment completion, and W4 owns this interpretation. It does not change+ the version-one request/candidate/JobResult contract or flip the old exhaustion+ flag. Existing runs remain frozen.++ The distinction is deliberate: the complete evaluated grid and its recorded+ refinements can support a qualified finite-search estimate. They do not prove+ uniqueness across continuous space or calibrated coverage. The normal residual,+ clock, input-coverage, association, actual-radius, all-supported-event and full+ sensitivity checks still apply.++ ## Producer object++ W5 forwards W2's object verbatim as `matching_diagnostics.finite_search_evidence`:++ ```json+ {+ "schema_version": 1,+ "scope": "evaluated_finite_grid",+ "complete": true,+ "score_kind": "matched_group_support_minus_normalized_residual",+ "spacing_m": 1000.0,+ "refine_spacing_m": 100.0,+ "max_event_groups": 4,+ "retained_modes": [{"mode_id": "stable-mode-id", "score": 3.8, "event_groups": 4}],+ "discarded_count": 0,+ "best_discarded_score": null,+ "pruning_accounted_for": true,+ "limitations": ["Evaluated grids and refinements only; continuous-space uniqueness is not established."]+ }+ ```++ Every retained spatial/clock/event-subset/association seed has one unique stable ID. Preserve+ that ID through its refinement. `event_groups` counts independent flyovers,+ including all supported later events; harmonics/fragments count once.+ `max_event_groups` bounds every retained or discarded evaluated hypothesis.++ `complete` requires the declared finite work to finish without unresolved budgets+ or missing scope. `pruning_accounted_for` requires every pruning/retention step to+ have recorded its limits. `discarded_count` covers all scored retention drops,+ including tile, global, coarse and fine merges; `best_discarded_score` is their+ maximum higher-is-better score. It is null exactly when no candidate was discarded.+ Exact duplicate stable IDs merged while retaining their highest score are not+ competing retention drops. Count deduplications separately if needed; association-+ only or approximate spatial collapse cannot be treated as exact duplication.+ The receiver-grid/pass-association score may be the best over the declared bounded+ clock/frequency/drift evaluations at that same location/association. Its domain+ must be recorded. Every trial must be classified: evaluated admissible rejection+ is distinct from unknown support/model/optimizer work, including all-negative-+ infinite outcomes. Unknown trials cannot be hidden behind one successful trial+ or assigned an optimistic discard bound. W2 exposes completed core seed IDs as+ `core_assessed_mode_ids`; W5 forwards only those classified assessments.++ The bound applies to evaluated parameter points only, not unvisited positions or unperformed+ refinements. Missing accounting cannot become zero discards or complete evidence.++ ## Assessment mappings++ W5 also supplies `assessed_mode_ids` for actual completed comparable assessments,+ and `candidate_mode_ids` parallel to the returned candidate array. Raw and refined+ representations may share a stable ID. Association-only deduplication cannot drop+ a distant spatial or clock mode. Failed or unvisited modes remain unassessed.++ Every retained mode must be assessed and represented in the candidate array; all+ candidate mappings must resolve. Group counts must agree. At least one returned+ representation must retain or improve each mode's original score, within numerical+ tolerance. These checks prevent a mapping or normalization error from hiding a+ better original grid hypothesis.++ For this narrow scope, a completed, fully supported core score at the frozen+ position/shared-clock/association/event subset and declared model counts as an+ assessment. Joint refinement of every retained point is not required. Failed,+ unvisited or unsupported core evaluations are unassessed. Unperformed refinements+ are explicit limitations, not an inferred continuous score bound. The leading+ estimate still needs successful complete measurement/model sensitivity profiles;+ all retained seeds remain in the ambiguity comparison. Do not turn on the old+ exhaustion/refinement boolean using this narrower meaning.++ ## Decision interpretation+++### Bounds for incomplete acoustic trials++++For the normalized subset score, a shared-clock trial with `k` independent groups++has score `sum(1 - loss_i / limit_i)`, where every robust loss is nonnegative.++Each unavailable fit therefore contributes at most one unit. Fully validated++event fits retain their computed contribution. If any validated event exceeds++its existing residual limit, that association is rejected at the trial's clock.++The candidate-envelope bound is the maximum across all scheduled shared-clock++trials. Positive floating-point accumulations are rounded upward.++++These bounds are stored in a separate `bounds` table in the retention ledger.++They do not count as measured fits or restore `model_support_complete`.++`bounded_unknown_envelopes` counts persisted work envelopes across stages,++including `bounded_unknown_rejections`; possible alternatives are the difference.++Their maximum ceiling is included in `best_discarded_score`, and possible++envelopes are included in `discarded_count`. Resume checks cover the bounds as++well as the measured modes. Unbounded trials and unreported clock envelopes++still make finite accounting incomplete.++++The bounds apply only to the declared finite receivers, associations, and clocks.++They say nothing about unperformed refinements, unseen aircraft, or continuous++location uniqueness. No score margin or location threshold changes.++++### Existing decision gates+++ A supplied finite object takes precedence over an optimistic legacy boolean.+ Incomplete scope, lost pruning accounting, omitted modes, inconsistent mappings or+ an unbounded near-tied discard yield explicit inconclusive outcomes. Malformed+ producer metadata yields `failed / invalid_evidence`.++ For a nonempty discard set, the normalized gap is+ `(best_final_score - best_discarded_score) / max_event_groups`. It must exceed the+ predeclared policy margin: 0.2 support units for the subset score, or 0.5 Hz for+ the declared raw robust loss. These engineering margins are not probabilities or+ empirical calibration. Score kinds must agree. Every retained candidate also+ undergoes the existing position/association near-tie checks against the actual+ returned radius. Full measurement/model sensitivity and optimizer/boundary guards+ remain mandatory.++ ## Same-association finite envelope++ After valid finite accounting and successful complete leading refinement/model+ sensitivity, near-tied same-association points may require a wider honest radius+ than the local leading profile. Keep the fitted point, clock, score, association+ and order fixed. Form the union of those evaluated points and every actually+ reported applicable uncertainty envelope:++ `radius = max(leading tested radius, distance to each near-tied point + its reported radius if present)`.++ An absent competitor profile contributes only its evaluated point, never an+ imputed profile. Unknown off-grid/profile behavior remains an explicit limitation.+ A different flight/event association still vetoes. Discarded near ties still veto.+ If the union exceeds the precision target, abstain. Incomplete, clipped or failed+ leading profiles cannot be repaired by this enlargement. Calls without the finite+ object keep the original returned-radius containment behavior, including #36.++ The hook returns copied `candidates` with the leading uncertainty method+ `finite_mode_and_tested_profile_union`, kind `sensitivity`, and computed radius.+ W5 must preserve that returned array (`setdefault` fallback only). The API/UI must+ read back the computed radius, not overwrite it with the smaller input profile.+ Diagnostics preserve the base profile radius, finite extent, included candidate+ indices/mode IDs and limitations. No test set, fitting parameter or historical+ outcome is revised.++ An accepted finite object uses policy version `engineering-v5-finite-envelope` and+ records its grid resolutions, counts, bound, limitations+ and `continuous_space_uniqueness: not established` in the decision artifact. A+ passing result supports only these declared assumptions. There is no new claim+ that an uncalibrated radius guarantees the 1,000 m benchmark target.++ Without the new object, the existing compatibility gate stays in force. No old+ inconclusive result is silently promoted. Producer agreement and actual integrated+ execution remain required before this proposal is considered deployed.diff --cc docs/MODEL_SUPPORT_COVERAGE.mdindex 0000000,473a5ed..a038cdfmode 000000,100644..100644--- a/docs/MODEL_SUPPORT_COVERAGE.md+++ b/docs/MODEL_SUPPORT_COVERAGE.md@@@ -1,0 -1,53 +1,71 @@@+ # Model-support loss in the tiled search++ The source data's spatial/time availability and the model's usable support are+ separate. The search report retains `data_scope_complete` for the former and adds+ `model_support_complete` for the latter. Any typed unsupported CPA trajectory or-unclassified scoring envelope makes model support false, search status partial-and finite-search evidence incomplete. Its unknown competitors have no optimistic-maximum discarded score. A completed tile does not establish complete evidence.++unclassified scoring envelope makes model support false. Separately,++`model_assessment_complete` records whether every finite scoring envelope is++evaluated, rejected, or covered by a validated score bound. Unsupported CPA++trajectories, unreported clock trials, and unbounded alternatives keep the search++partial. A completed tile does not establish complete evidence.++ The additive `model_support` report contains these integer work counts:++ - `unsupported_cpa_track_evaluations`: trajectory/stage CPA failures, including+ repeated evaluations in different coarse/refinement stages.+ - `unclassified_score_candidates`: candidate envelopes whose work is unknown.+ - `evaluated_trials`, `rejected_trials`, `unknown_trials`: totals explicitly+ reported by robust scorer assessments.+ - `unreported_trial_envelopes`: interrupted or missing/malformed trial accounting;+ its unknown trial count must not be inferred as zero.++- `bounded_score_candidates`, `unbounded_score_candidates`: the partition of++ unclassified scoring envelopes by whether every scheduled clock trial has a++ validated score ceiling or a supported-event rejection.++++For the normalized subset score, an unknown event contributes at most one unit++because its robust loss is nonnegative. A validated complete event can tighten++that ceiling; an event exceeding its unchanged residual limit rejects that++association at that clock. The maximum bound across every scheduled clock is++persisted separately from measured scores. Raw missing-support diagnostics remain++unchanged. See [the finite-search decision](FINITE_SEARCH_DECISION.md).++++The product accepts this accounting only when the raw counts, persisted bound++counts, completion flags, and combined discarded-score bound agree. It still++defers competitive bounds to the existing confidence decision. No bound repairs++missing flight coverage, invalid motion, omitted tiles, event caps, or an++incomplete sensitivity profile.++ `diagnostics_directory` points to `support/`. Per-stage JSON files preserve every+ affected track ID/reason and every unclassified candidate's receiver, event/flight+ assignments, pass times, available clock bounds and scoring assessment. Coarse+ checkpoints also retain these diagnostics; resumed counts replace work rather+ than inflating it. Refinement failures use separate stage files. Per-stage lists+ are bounded by the existing track/candidate budgets; the report aggregates counts+ without collecting a national diagnostic list in memory.++ Only `geometry.AcousticSupportError` is isolated. A CPA error conservatively+ excludes that entire track's work for the receiver stage, including partial rows+ from earlier chunks, and keeps valid other-track rows. The diagnostic labels the+ whole track time span and receiver extent as a conservative loss envelope: this+ narrow exception need not identify the exact unsupported interval. Optional+ emission/receive intervals reported by the physical validator are preserved in+ `reported_intervals`; they do not narrow the conservative coverage envelope. Original index+ payloads are retained. Robust scoring classifies typed failures per clock trial;+ the outer handler also preserves other candidates if a legacy scorer raises the+ same typed error. An interrupted scorer's unreported trial count stays unknown.+ Generic programming/configuration errors retain the existing explicit tile-failure+ behavior.++ This handling does not certify continuous total speed or Newton convergence,+ repair historical missing derivatives or altitude clipping, identify the cause of+ bad observations, or establish complete real-flight coverage. Issue #64 retains+ those open gates and the historical 855/858 result. No old outcome is promoted.++ The integrated W3 physical guard validates whole-source continuous motion at both+ actual CPA call sites and time-local motion/convergence in direct acoustic+ scoring. A real constructed indexed source with zero knot speeds and a >700 m/s+ interior peak now reaches this outer typed boundary without a monkeypatch.+ The mixed-source regression preserves the clean candidate identities/scores,+ retains the original malformed source, and reports partial model coverage. This+ verified connection does not repair source observations or establish real-data+ acceptance; W3 documents the numerical support assumptions in MOTION_SUPPORT.md.diff --cc docs/PRODUCT.mdindex 0000000,9855cd9..83f41damode 000000,100644..100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@@ -1,0 -1,179 +1,203 @@@+ # Local upload workflow++ The current location goal accepts up to **1,000 m error**, with **100–500 m or better preferred**. True benchmark error and uncalibrated model sensitivity remain separate. Historical reports below retain their original 100 m thresholds.+++The [real-world data policy](../AGENTS.md#real-world-data-only) stops new synthetic++data generation, tests, benchmarks, and replays. New validation uses real++recordings and measured trajectories. Historical results retain their original++scope and limitations.+++ The automatic product path is separate from the historical research `run` and+ `measure` commands. Uploads supply audio, an optional defensible UTC window for+ **sample zero**, and declared CONUS search coverage. Event windows, frequency+ bands, flight IDs and ground-truth coordinates are not upload inputs.++ Launch the local interface after installing the project:++ ```bash+ dopplergeist serve --jobs jobs --config operator.json --port 8765+ ```++ Open `http://127.0.0.1:8765`. The same persistent directory must be supplied after+ restarting. Each upload gets a new job ID and its own original file, normalized+ request, provenance, intermediate diagnostics, result and worker log. Completed+ jobs are read back without rerunning. Interrupted jobs are explicitly failed;+ they are never silently replayed. Cancelling preserves partial artifacts.++ The server binds to loopback. It runs one analysis process at a time, accepts up+ to four pending jobs, limits uploads to 100 MiB by default, and limits analysis+ to one hour by default. Set `--max-upload-mb` and `--max-runtime` to change these+ operator limits. Cancellation terminates the analysis process group, including+ decoders. No API credentials or paid service are required by the local service.-Flight/terrain provider configuration and scientific integration are described-below; an unconfigured backend must report-missing data rather than invent a location.++The provider configuration below connects flight and terrain acquisition to the++automatic search. An unconfigured backend reports missing data.++ CLI equivalents:++ ```bash+ dopplergeist analyze recording.mp3 --jobs jobs --config operator.json \+ --start-utc 2026-09-08T20:00:00Z --end-utc 2026-09-08T20:05:00Z \+ --time-source 'Recorder clock and recording log'+ dopplergeist job JOB_ID --jobs jobs+ ```++ The UTC window bounds the recording start, not the event occurrence or upload.+ Missing time is a required-input result. Scores are ranking statistics, not+ probabilities. Sensitivity radii must not be described as calibrated confidence.+ An inconclusive result may retain candidate hypotheses for inspection.++ ## HTTP surface++ - `GET /api/capabilities`: declared coverage and upload/work limits.+ - `POST /api/jobs`: raw audio bytes with `Content-Type: application/octet-stream`,+ `Content-Length`, optional `X-Filename`, and `X-Dopplergeist-Request` containing+ the shared request JSON **without** `audio_path`. The server saves the upload+ and sets that path. Returns HTTP 202 and a shared queued `JobResult`.+ - `GET /api/jobs/{id}`: the current shared `JobResult`.+ - `POST /api/jobs/{id}/cancel`: cancel a queued/running job; terminal jobs remain.+ - `GET /api/jobs/{id}/artifacts`: relative file paths and byte counts.+ - `GET /api/jobs/{id}/artifacts/{path}`: download one artifact. Private operator+ configuration is excluded. Paths cannot escape the job directory.++ Upload example (header metadata uses actual JSON, not a string-encoded file):++ ```bash+ curl -H 'Content-Type: application/octet-stream' \+ -H 'X-Dopplergeist-Request: {"schema_version":1,"search":{"coverage":"conus"}}' \+ --data-binary @recording.mp3 http://127.0.0.1:8765/api/jobs+ ```+-`tests/test_service.py` checks HTTP transport, original preservation, state-readback, cancellation, interrupted jobs, path restrictions and input validation.-These transport tests do not establish scientific localization accuracy.++The historical checks in `tests/test_service.py` cover HTTP transport, original++preservation, state readback, cancellation, interrupted jobs, path restrictions,++and input validation. They do not establish scientific localization accuracy.++Automatic CI checks installation, source compilation, CLI help, and packaged++assets without generated data.++ ## Provider and search configuration++ An operator configures data once; users upload audio without choosing trajectory+ files. The normal acquisition path delegates to `data_access.acquire_inputs`:++ ```json+ {+ "cache_root": "/absolute/path/to/dopplergeist-cache",+ "offline": false,+ "terrain": {},+ "search_budget": {+ "spacing_m": 2000,+ "tile_cells": 32,+ "top_k": 100,+ "refine_spacing_m": 100+ }+ }+ ```++ This acquires public ADSB.lol all-type daily archives and Copernicus terrain/geoid+ inputs, then reuses their indexed cache. It can require substantial disk space and+ time. `offline` defaults to true; online retrieval is an explicit operator choice.+ No hidden account credentials or paid fallback are used. The default acquisition+ budget is three UTC archive dates, including propagation guards and the full recording (`max_acquisition_days`); wider recording windows need+ a narrower defensible input or an explicit operator budget change. Do not put+ credentials in this configuration.++ For existing offline data, supply `flight_indexes` (paths to Worker 2 FlightIndex+ SQLite files). Terrain may use the cached provider options (`geoid_path`,+ `adopt_existing`) or a declared local override: `{"rasters":["/dem.tif"],-"geoid_raster":"/geoid.tif"}`. A `{"constant_m":0}` terrain override exists for-synthetic/flat-ground experiments and is labelled as a limitation in the result.++"geoid_raster":"/geoid.tif"}`. The historical `{"constant_m":0}` terrain override++does not establish real terrain or altitude-datum accuracy. Its result retains++that limitation for real recordings.+ Local overrides require prebuilt indexes and retain their actual coverage.++ `search_budget.max_tiles` bounds tile work. Reaching a tile, memory, data or wall+ time limit leaves incomplete coverage and cannot produce a supported national+ location. Full search completion does not prove the archive captured every real+ aircraft. Grid finalists undergo jointly constrained position/clock refinement;+ `refine_finalists` (default 5) limits physical sensitivity refinement. Unassessed+ retained approaches prevent an affirmative confidence decision.+-For reproducible chunk-boundary checks, an operator may set++For chunk-boundary checks on real recordings, an operator can set+ `"discovery": {"chunk_s": 120.0, "overlap_s": 60.0}` in this private configuration.+ These are the only discovery overrides supported by the product adapter. The+ existing detector validates the overlap and chunk constraints; spectral bands,+ acceptance thresholds and other scientific settings keep their defaults. The+ actual settings and analyzed chunks are saved in `discovery/discovery.json`, and+ the operator configuration hash is retained in provenance. This configuration is+ not an upload-request field. A chunk-size comparison must rerun detection and the+ pipeline; it cannot reuse final candidates as if discovery had run again.+-Search reports with `model_support_complete` also supply explicit `model_support`-work counters. Unsupported CPA trajectories, unclassified score candidates or-unknown clock trials keep product search coverage incomplete. Missing/malformed-counters cannot become zero work. Source spatial/time availability remains a-separate `data_status`; an available archive can still have unassessed trajectory-models. Coverage limitations expose the work counts, and per-stage support-artifacts retain affected IDs/reasons and conservative lost-coverage envelopes.-These counts describe work evaluations, not distinct aircraft.++Search reports distinguish raw model support from finite assessment. If any++trajectory or scoring envelope lacks support, `model_support_complete` stays false.++`model_support` retains the raw work counts, unknown trials, and reasons. Missing++or malformed counters cannot become zero work. These counts describe work++evaluations, not distinct aircraft.++++If every unknown finite scoring envelope has a validated ceiling or rejection,++`model_assessment_complete` can be true. An unavailable event fit contributes at++most one unit to the normalized support score. A fully validated event that++exceeds its residual limit rejects that association at that clock. The producer++retains the greatest ceiling across all scheduled clock trials in the retention++ledger. This accounting does not create a measured fit or restore missing support.++++The product requires agreement between raw counters, persisted bounds, completion++flags, and finite discard accounting. The confidence decision compares the combined++discard bound with the leading score under the existing margin. Unsupported CPA++trajectories, unreported trials, and unbounded alternatives keep assessment++incomplete. Missing tiles, data gaps, event caps, and incomplete sensitivity++evidence still prevent a supported location.++++Source availability remains a separate `data_status`. An available archive can++still have unassessed trajectory models. Per-stage artifacts retain affected IDs,++reasons, and conservative coverage envelopes. See++[model-support coverage](MODEL_SUPPORT_COVERAGE.md) for the complete contract.++ The automatic path always uses one shared clock inside the supplied start window+ and robust ridge loss. Its default association path considers every proposed+ independent group; harmonics count once and unsupported acoustic proposals remain+ explicitly unmatched. A smaller operator event cap is incomplete work and is shown+ in coverage limitations, rather than silently keeping an initial subset. Every discovered event remains in the diagnostics. A+ location requires the confidence producer's evidence checks, including independent+ events, alternative hypotheses, complete coverage, residuals and measurement/model+ sensitivity. A small altitude-only profile is insufficient. The final decision+ and full candidate/refinement diagnostics are saved as downloadable JSON.++ ## Current limits++ The application is available on `main` and remains experimental. Automatic+ synthetic runs have produced accurate hypotheses and inconclusive decisions;+ those are different outcomes. See the [README](../README.md#experimental-results)+ for the reported results.++ Independent real recordings with established recording time and location,+ reliable global hypothesis discrimination, and calibrated false-localization+ rates remain open. The acceptance goal is within 1,000 m, preferably 100–500 m;+ landing the application does not establish that goal.++ ## Accounted finite-search evidence++ The current integration consumes the optional artifact-only producer/decision+ contract in [FINITE_SEARCH_DECISION.md](FINITE_SEARCH_DECISION.md). The search+ producer assigns stable seed `mode_id` values including position, clock, event+ indices and flight/pass association, and records every lossy retention bound.+ The product relays `finite_search_evidence` unchanged, preserves seed IDs through+ refinement, and supplies `candidate_mode_ids` parallel to the wire candidates.++ For the explicitly declared evaluated-finite-grid scope, `assessed_mode_ids`+ requires the producer's explicit `core_assessed_mode_ids` mapping plus an actually+ completed finite core score with full measured-trajectory support at the original+ seed/model and a valid trusted clock. A returned fit alone does not establish+ classification of every bounded clock/optimizer trial; missing/malformed mappings+ or producer-omitted IDs remain unassessed. It does not require+ jointly optimizing every retained point. Failed, missing or unsupported core+ records are unassessed. Raw and refined representations retain their original+ mode ID and original-or-improved score; no association-only deduplication is used.+ The accepted leading estimate still needs successful full sensitivity, datum,+ optimizer, clock, actual-radius and competing-mode checks.++ Unperformed refinements and continuous locations are outside that conditional+ finite claim. Their limitations are displayed in coverage and saved in the+ artifacts. The old `alternatives_evaluated` flag keeps its older meaning and is+ not flipped to force success. An absent finite object preserves old outcomes;+ missing mappings, incomplete work or an unaccounted near-tied discard remain-inconclusive. Producer computation, consumer agreement and an actual integrated-run are required before this optional path is considered deployed.++inconclusive. Validated bounds account for unknown discarded trials without adding++them to `assessed_mode_ids`. The adapter and decision code consume this finite++contract. An accepted real-recording location through this path remains unverified.diff --cc docs/verification/WORKER_E2E_2026-11-03.mdindex 0000000,0000000..e43ff20new file mode 100644--- /dev/null+++ b/docs/verification/WORKER_E2E_2026-11-03.md@@@ -1,0 -1,0 +1,208 @@@++# Worker verification results — 2026-11-03 UTC++++**Experimental software. The complete real-recording localization goal remains open.**++++The real HTTP run verified upload, intake, automatic discovery, persistence and shutdown.++It returned `needs_input / recording_time_required`, with no location result.++The NASA real-recording localization experiment remains in progress.++This record does not close [#13](https://github.com/1337isnot1337/DOPPLERGEIST/issues/13)++or [#53](https://github.com/1337isnot1337/DOPPLERGEIST/issues/53).++++The [owner directive](https://github.com/1337isnot1337/DOPPLERGEIST/issues/1#issuecomment-6595095639)++stopped new synthetic experiments.++All completed synthetic runs in this record preceded that directive.++This documentation change ran no experiment or test.++++## Repository checkout++++The primary imported the complete Git history from++[run 41577235564](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41577235564),++artifact `13204415457`.++The downloaded archive SHA-256 was `cd0267f186d384fa52a8484101f82917f3d6b9723032bd0805c2ba4b6d73e067`.++The primary imported all branch references under `live/*`.++The primary created `/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-current`++at `6670d74b1f6c41c3a655e219f91908ed7fbe7182`.++The primary reported `git fsck --full --no-reflogs` exit code 0, with only dangling historical objects and no corruption.++The application results in this record retain their own earlier source revisions.++++## Real recording through HTTP++++The input was the complete reference recording from++[the original video](https://www.youtube.com/watch?v=4CxVxuMVkMc).++The worker converted its retained WAV to MP3 without a time selection or frequency selection.++The conversion removed metadata and supplied no sample-zero UTC or recorder location.++The [source record](../../evidence/e2e-worker-20261103/real-source-provenance.json)++preserves the original WAV identity, artifact ID, conversion command and MP3 identity.++++| Input | SHA-256 |++| --- | --- |++| Original complete WAV | `262d9c4eba1c80657813c604140ba2afbbaabed2b3aebc833cba7cafdc005e9f` |++| Uploaded complete MP3 | `e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0` |++++The MP3 contained 42,085,293 bytes.++The request selected `coverage: conus`, with an empty operator configuration and no recording clock.++The HTTP run started at `2026-11-03T04:14:50.484869Z`.++++| Observation | Result |++| --- | --- |++| Job | `dcf5816d3d0f4a1a9a551b7269f27ec8` |++| Decoded recording | 3,600.1845 seconds, mono, 4,000 Hz |++| Automatic discovery | 60 overlapping chunks, 18 ridges, 16 acoustic proposals |++| Terminal status | `needs_input` |++| Reason | `recording_time_required` |++| Required input | A defensible UTC window for the first decoded sample |++| Candidate output | Zero candidates |++| Total verifier time | 20.433066061001227 seconds |++| Service shutdown | SIGINT, return code 0, no forced kill |++++The [result summary](../../evidence/e2e-worker-20261103/real-result-summary.json)++contains the complete recording metadata and discovery settings.++The proposals are acoustic candidates. Their aircraft identities remain unconfirmed.++++The [HTTP receipt](../../evidence/e2e-worker-20261103/real-http-verification.json)++records successful preservation checks for the input, request, operator configuration and result.++Downloads matched the original upload and stored result.++The terminal result remained unchanged after shutdown.++The [stage receipt](../../evidence/e2e-worker-20261103/real-pipeline-evidence.json)++verified `automatic_provenance`, `intake` and `discovery`.++++These three checks establish stage consistency for this actual run.++They do not independently reproduce the decoder or establish a scientific decision.++The receipts explicitly record `full_pipeline_observed: false`, `supported_decision: false`,++`location_accuracy_evaluated: false` and `browser_verified: false`.++No geographic search or location-error claim follows from this result.++++### Source revision and retained artifacts++++The invocation started from integration commit `6497540f15a05af142e88dd34c67ee76d4ea583b`.++The recorded implementation hashes identify the code independently of later documentation commits.++The HTTP receipt preserves all 21 backend file hashes and the verifier hash.++Those implementation hashes match the frozen backend at `317b0d3fc93ec9cd50ca88c336bb771b26bf5b1e`.++The receipt also records that the implementation remained unchanged during verification.++++Full local artifacts remain under:++++```text++/workspace/scratch/e8a2a58f21d0/real-inputs/data/source/reference-recording.wav++/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/++```++++The compact evidence directory contains the existing source and HTTP receipts without media or numerical arrays.++It also contains a summary extracted from the original result and discovery files.++The recorded `aircraft_geoloc` package and command names are historical names.++The separate installed-package replay below verifies the renamed `dopplergeist` package.++Related implementation sources are [product integration #19](https://github.com/1337isnot1337/DOPPLERGEIST/pull/19),++[finite retention #71](https://github.com/1337isnot1337/DOPPLERGEIST/pull/71)++and [trajectory support #91](https://github.com/1337isnot1337/DOPPLERGEIST/pull/91).++++## Current installed package and real upload++++The current main branch incorporated product, support and finite-search work and++renamed the package to `dopplergeist`. The worker ported only the additional++bounded-score accounting and verification changes onto main `6670d74`.++The resulting runtime was frozen at `db9db65aad7a6fe6fa9fc5fd31a9c45c72f4f68d`.++Geometry, acoustic discovery, confidence thresholds and browser assets were unchanged.++++An offline build produced `dopplergeist-0.1.0-py3-none-any.whl`. A separate virtual++environment installed the wheel and its dependencies without using the editable++checkout or system packages. All 25 packaged source/browser files matched the++checkout byte for byte. Dependency consistency, installed imports, all five CLI++commands in help, and readable browser assets passed.++See [installed-package receipt](../../evidence/e2e-worker-20261103/installed-package.json).++++The standalone HTTP verifier then ran with that environment's isolated Python++against the same complete real MP3. It again found 16 proposals over++3,600.1845 seconds and returned `needs_input / recording_time_required`.++The verifier completed in 20.41445216200009 seconds; input/result persistence,++artifact downloads, source fingerprints and graceful service shutdown passed.++It verified the same three stages and made no location claim.++See the [installed HTTP receipt](../../evidence/e2e-worker-20261103/installed-real-http-verification.json)++and [installed stage receipt](../../evidence/e2e-worker-20261103/installed-real-pipeline-evidence.json).++++This is a real installed-package run of the current namespace. It does not turn++the missing-clock response into a successful scientific localization.++++## Historical bound verification on six failed tiles++++This work preceded the owner directive.++It replayed six archived tiles from the earlier synthetic four-event HTTP run at source `134f617`.++The production bound source was `7a96fdb33fb787a9376432b2086f3673a4f4dc37`.++The replay used the archived discovery, flight index, tracks and terrain.++It did not load location truth or change scores.++++For an association with `k` matched groups, the declared score is:++++\[++S=\sum_{i=1}^{k}\left(1-\frac{\ell_i}{L_i}\right),\qquad L_i>0,\quad \ell_i\geq0.++\]++++A validated event loss greater than its limit rejects the entire association.++For each unknown event loss, its score contribution cannot exceed one.++Validated supported losses can therefore tighten the general bound `S ≤ k`.++The candidate bound covers every scheduled clock trial.++The implementation rounds contributions and sums upward to protect the floating-point bound.++++The code requires the declared score kind and validates the event diagnostics before it uses a loss.++It also validates disjoint trial counts and their sum against the scheduled count.++Unsupported motion errors remain unbounded.++Missing support remains unknown despite a finite score bound.++The bound applies to the enumerated grid and scheduled clocks, without a continuous-space claim.++++| Tile | Unknown candidates | Rejected by a supported event | Largest remaining upper bound |++| --- | ---: | ---: | ---: |++| `-5_29` | 2 | 1 | 1 |++| `-20_36` | 96 | 7 | 2 |++| `-21_36` | 756 | 389 | 3 |++| `-6_29` | 177 | 64 | 2 |++| `8_20` | 304 | 201 | 2 |++| `8_21` | 177 | 53 | 2 |++| **Total** | **1,512** | **715** | **3** |++++All 1,512 unknown candidates acquired valid bounds. None became an evaluated fit.++The other 797 candidates had upper bounds of at most three.++Forty-four unknown candidates matched four groups, so group count alone did not settle every case.++All six replays reproduced the archived counts.++Their ledger evidence remained identical after each database reopened.++The [six-tile summary](../../evidence/e2e-worker-20261103/historical-six-tile-bounds.json)++preserves the counts and persistence results.++++The full diagnostics remain at++`/workspace/scratch/e8a2a58f21d0/integration-audit/production-bound-replays-7a96fdb/`.++The archived input is `integration-audit/http-four-event-134f617.zip` in the same workspace.++This result verifies a finite-search correction. It does not establish real-recording localization accuracy.++++## Historical tests and interrupted positive run++++Before the directive, the primary ran this command at integration commit++`317b0d3fc93ec9cd50ca88c336bb771b26bf5b1e`:++++```bash++PYTHONPATH=src OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \++ ../.venv/bin/python -m pytest -q++```++++Observed terminal result: **620 passed, 1 skipped, 17 subtests in 77.82 seconds**.++The observation came from terminal session `45606`. No separate raw log accompanies this record.++This historical command is not a current instruction to run synthetic tests.++++Earlier actual CLI and HTTP negative controls used source `91f2684f70eac7fecfe7810f09eecdb38cc839a7`.++Undated audio returned `needs_input`, corrupt input returned `failed`, and silence returned `inconclusive`.++Input preservation, stored results, restart persistence and graceful shutdown passed.++The [negative-control summary](../../evidence/e2e-worker-20261103/historical-negative-paths.json)++identifies these controls as synthetic and makes no accuracy claim.++++When the owner directive arrived, the primary stopped the later positive synthetic run at `317b0d3`.++Terminal session `84810` ended with exit code 130.++Its retained job `2575b2f261db4c128a39e71c643d0704` still records `running / search`, with `search_complete: false`.++It produced no terminal HTTP verification receipt or accepted location result.++The partial artifacts remain in `results/e2e-bounded-four-20261103/` in the integration worktree.++**This interrupted run is not a successful end-to-end verification.**++++## Pending: NASA real-recording localization++++**Status: in progress. No final localization result is recorded here.**++++The final record must identify the actual recording, measured trajectory, clock evidence, independent recorder location and source revision.++It must report the terminal decision and measured errors at 100, 500 and 1,000 meters.++An incomplete search or missing timing evidence remains explicit.++The results in this document do not establish completion of that experiment or the overall goal.diff --cc evidence/e2e-worker-20261103/historical-negative-paths.jsonindex 0000000,0000000..c639bd7new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/historical-negative-paths.json@@@ -1,0 -1,0 +1,93 @@@++{++ "source_commit": "91f2684f70eac7fecfe7810f09eecdb38cc839a7",++ "scope": "actual synthetic negative paths; no location accuracy claim",++ "http": [++ {++ "case": "undated-chirp",++ "status": "needs_input",++ "reason_code": "recording_time_required",++ "job_id": "ef92b1797be04b979da106179e7e0702",++ "events": 1,++ "uploaded_bytes_preserved": true,++ "no_candidate_output": true,++ "persisted_result_matches": true,++ "http_download_preserves_input": true,++ "observed_states": [++ "queued",++ "running",++ "needs_input"++ ]++ },++ {++ "case": "corrupt",++ "status": "failed",++ "reason_code": "invalid_media",++ "job_id": "6ee469dee7194fb196c4d9154f08b394",++ "events": 0,++ "uploaded_bytes_preserved": true,++ "no_candidate_output": true,++ "persisted_result_matches": true,++ "http_download_preserves_input": true,++ "observed_states": [++ "queued",++ "running",++ "failed"++ ]++ },++ {++ "case": "silence",++ "status": "inconclusive",++ "reason_code": "no_supported_events",++ "job_id": "f8509b3744ee406fa40e0a8a1024b067",++ "events": 0,++ "uploaded_bytes_preserved": true,++ "no_candidate_output": true,++ "persisted_result_matches": true,++ "http_download_preserves_input": true,++ "observed_states": [++ "queued",++ "running",++ "inconclusive"++ ]++ }++ ],++ "cli": [++ {++ "case": "undated-chirp",++ "status": "needs_input",++ "reason_code": "recording_time_required",++ "job_id": "41469ecc10bb4c85923a62513c02e541",++ "events": 1,++ "uploaded_bytes_preserved": true,++ "no_candidate_output": true,++ "persisted_result_matches": true,++ "exit_code": 0++ },++ {++ "case": "corrupt",++ "status": "failed",++ "reason_code": "invalid_media",++ "job_id": "2c68781a09664b179a221567b705ceb4",++ "events": 0,++ "uploaded_bytes_preserved": true,++ "no_candidate_output": true,++ "persisted_result_matches": true,++ "exit_code": 0++ },++ {++ "case": "silence",++ "status": "inconclusive",++ "reason_code": "no_supported_events",++ "job_id": "86f42111eb374a769828fda5ce30a506",++ "events": 0,++ "uploaded_bytes_preserved": true,++ "no_candidate_output": true,++ "persisted_result_matches": true,++ "exit_code": 0++ }++ ],++ "http_graceful_shutdown": true,++ "terminal_results_unchanged_after_restart": true,++ "restart_graceful_shutdown": true,++ "passed": true++}diff --cc evidence/e2e-worker-20261103/historical-six-tile-bounds.jsonindex 0000000,0000000..cd437d4new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/historical-six-tile-bounds.json@@@ -1,0 -1,0 +1,320 @@@++[++ {++ "tile": "-5_29",++ "counts_reproduced": true,++ "unknown_cardinalities": {++ "2": 1,++ "1": 1++ },++ "unknown_reasons": {++ "incomplete_ridge_or_trajectory_support": 2++ },++ "unknown_with_certified_rejecting_event": 1,++ "max_unknown_score_upper_bound": 1.0,++ "production_bounded_rows": 2,++ "elapsed_s": 0.07777830099985295,++ "counts": {++ "per_event_survivors": [++ 0,++ 4,++ 0,++ 7++ ],++ "survivors": 13,++ "hypotheses_examined": 13,++ "work_units": 65,++ "max_matched_events": 4,++ "event_cap_limited": false,++ "unmatched_proposals_allowed": true,++ "cpa_rows": 13,++ "candidates": 13,++ "unclassified_score_candidates": 2,++ "bounded_score_candidates": 2,++ "unbounded_score_candidates": 0,++ "evaluated_rejections": 9,++ "unsupported_cpa_tracks": [],++ "evaluated_trials": 0,++ "rejected_trials": 18,++ "unknown_trials": 4,++ "unreported_trial_envelopes": 0++ },++ "persisted_bound_check": {++ "stage_valid_after_reopen": true,++ "evidence_equal_after_reopen": true++ },++ "ledger_evidence": {++ "complete": true,++ "pruning_accounted_for": true,++ "bounded_unknown_envelopes": 2,++ "bounded_unknown_rejections": 1,++ "best_unknown_score_upper_bound": 1.0,++ "best_discarded_score": 1.0++ }++ },++ {++ "tile": "-20_36",++ "counts_reproduced": true,++ "unknown_cardinalities": {++ "1": 76,++ "2": 20++ },++ "unknown_reasons": {++ "incomplete_ridge_or_trajectory_support": 96++ },++ "unknown_with_certified_rejecting_event": 7,++ "max_unknown_score_upper_bound": 2.0,++ "production_bounded_rows": 96,++ "elapsed_s": 0.5357038039983308,++ "counts": {++ "per_event_survivors": [++ 0,++ 69,++ 7,++ 34++ ],++ "survivors": 131,++ "hypotheses_examined": 131,++ "work_units": 645,++ "max_matched_events": 4,++ "event_cap_limited": false,++ "unmatched_proposals_allowed": true,++ "cpa_rows": 142,++ "candidates": 131,++ "unclassified_score_candidates": 96,++ "bounded_score_candidates": 96,++ "unbounded_score_candidates": 0,++ "evaluated_rejections": 30,++ "unsupported_cpa_tracks": [],++ "evaluated_trials": 0,++ "rejected_trials": 60,++ "unknown_trials": 192,++ "unreported_trial_envelopes": 0++ },++ "persisted_bound_check": {++ "stage_valid_after_reopen": true,++ "evidence_equal_after_reopen": true++ },++ "ledger_evidence": {++ "complete": true,++ "pruning_accounted_for": true,++ "bounded_unknown_envelopes": 96,++ "bounded_unknown_rejections": 7,++ "best_unknown_score_upper_bound": 2.0,++ "best_discarded_score": 2.0++ }++ },++ {++ "tile": "-21_36",++ "counts_reproduced": true,++ "unknown_cardinalities": {++ "1": 251,++ "2": 331,++ "3": 148,++ "4": 26++ },++ "unknown_reasons": {++ "incomplete_ridge_or_trajectory_support": 756++ },++ "unknown_with_certified_rejecting_event": 389,++ "max_unknown_score_upper_bound": 3.0,++ "production_bounded_rows": 756,++ "elapsed_s": 7.120768543998565,++ "counts": {++ "per_event_survivors": [++ 122,++ 147,++ 162,++ 122++ ],++ "survivors": 1211,++ "hypotheses_examined": 1211,++ "work_units": 5777,++ "max_matched_events": 4,++ "event_cap_limited": false,++ "unmatched_proposals_allowed": true,++ "cpa_rows": 729,++ "candidates": 1211,++ "unclassified_score_candidates": 756,++ "bounded_score_candidates": 756,++ "unbounded_score_candidates": 0,++ "evaluated_rejections": 378,++ "unsupported_cpa_tracks": [],++ "evaluated_trials": 14,++ "rejected_trials": 756,++ "unknown_trials": 1512,++ "unreported_trial_envelopes": 0++ },++ "persisted_bound_check": {++ "stage_valid_after_reopen": true,++ "evidence_equal_after_reopen": true++ },++ "ledger_evidence": {++ "complete": true,++ "pruning_accounted_for": true,++ "bounded_unknown_envelopes": 756,++ "bounded_unknown_rejections": 389,++ "best_unknown_score_upper_bound": 3.0,++ "best_discarded_score": 3.0++ }++ },++ {++ "tile": "-6_29",++ "counts_reproduced": true,++ "unknown_cardinalities": {++ "1": 109,++ "2": 66,++ "3": 2++ },++ "unknown_reasons": {++ "incomplete_ridge_or_trajectory_support": 177++ },++ "unknown_with_certified_rejecting_event": 64,++ "max_unknown_score_upper_bound": 2.0,++ "production_bounded_rows": 177,++ "elapsed_s": 8.250739074001103,++ "counts": {++ "per_event_survivors": [++ 123,++ 168,++ 192,++ 192++ ],++ "survivors": 1452,++ "hypotheses_examined": 1452,++ "work_units": 6927,++ "max_matched_events": 4,++ "event_cap_limited": false,++ "unmatched_proposals_allowed": true,++ "cpa_rows": 861,++ "candidates": 1452,++ "unclassified_score_candidates": 177,++ "bounded_score_candidates": 177,++ "unbounded_score_candidates": 0,++ "evaluated_rejections": 1216,++ "unsupported_cpa_tracks": [],++ "evaluated_trials": 46,++ "rejected_trials": 2432,++ "unknown_trials": 354,++ "unreported_trial_envelopes": 0++ },++ "persisted_bound_check": {++ "stage_valid_after_reopen": true,++ "evidence_equal_after_reopen": true++ },++ "ledger_evidence": {++ "complete": true,++ "pruning_accounted_for": true,++ "bounded_unknown_envelopes": 177,++ "bounded_unknown_rejections": 64,++ "best_unknown_score_upper_bound": 2.0,++ "best_discarded_score": 2.0++ }++ },++ {++ "tile": "8_20",++ "counts_reproduced": true,++ "unknown_cardinalities": {++ "2": 124,++ "1": 90,++ "3": 72,++ "4": 18++ },++ "unknown_reasons": {++ "incomplete_ridge_or_trajectory_support": 304++ },++ "unknown_with_certified_rejecting_event": 201,++ "max_unknown_score_upper_bound": 2.0,++ "production_bounded_rows": 304,++ "elapsed_s": 4.174735940001483,++ "counts": {++ "per_event_survivors": [++ 74,++ 93,++ 79,++ 57++ ],++ "survivors": 643,++ "hypotheses_examined": 643,++ "work_units": 3108,++ "max_matched_events": 4,++ "event_cap_limited": false,++ "unmatched_proposals_allowed": true,++ "cpa_rows": 414,++ "candidates": 643,++ "unclassified_score_candidates": 304,++ "bounded_score_candidates": 304,++ "unbounded_score_candidates": 0,++ "evaluated_rejections": 316,++ "unsupported_cpa_tracks": [],++ "evaluated_trials": 2,++ "rejected_trials": 632,++ "unknown_trials": 608,++ "unreported_trial_envelopes": 0++ },++ "persisted_bound_check": {++ "stage_valid_after_reopen": true,++ "evidence_equal_after_reopen": true++ },++ "ledger_evidence": {++ "complete": true,++ "pruning_accounted_for": true,++ "bounded_unknown_envelopes": 304,++ "bounded_unknown_rejections": 201,++ "best_unknown_score_upper_bound": 2.0,++ "best_discarded_score": 2.0++ }++ },++ {++ "tile": "8_21",++ "counts_reproduced": true,++ "unknown_cardinalities": {++ "1": 106,++ "2": 66,++ "3": 5++ },++ "unknown_reasons": {++ "incomplete_ridge_or_trajectory_support": 177++ },++ "unknown_with_certified_rejecting_event": 53,++ "max_unknown_score_upper_bound": 2.0,++ "production_bounded_rows": 177,++ "elapsed_s": 5.583626887999344,++ "counts": {++ "per_event_survivors": [++ 55,++ 100,++ 108,++ 120++ ],++ "survivors": 825,++ "hypotheses_examined": 825,++ "work_units": 3911,++ "max_matched_events": 4,++ "event_cap_limited": false,++ "unmatched_proposals_allowed": true,++ "cpa_rows": 458,++ "candidates": 825,++ "unclassified_score_candidates": 177,++ "bounded_score_candidates": 177,++ "unbounded_score_candidates": 0,++ "evaluated_rejections": 614,++ "unsupported_cpa_tracks": [],++ "evaluated_trials": 16,++ "rejected_trials": 1228,++ "unknown_trials": 354,++ "unreported_trial_envelopes": 0++ },++ "persisted_bound_check": {++ "stage_valid_after_reopen": true,++ "evidence_equal_after_reopen": true++ },++ "ledger_evidence": {++ "complete": true,++ "pruning_accounted_for": true,++ "bounded_unknown_envelopes": 177,++ "bounded_unknown_rejections": 53,++ "best_unknown_score_upper_bound": 2.0,++ "best_discarded_score": 2.0++ }++ }++]diff --cc evidence/e2e-worker-20261103/installed-package.jsonindex 0000000,0000000..4d30a82new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/installed-package.json@@@ -1,0 -1,0 +1,11 @@@++{++ "wheel": "dopplergeist-0.1.0-py3-none-any.whl",++ "wheel_sha256": "42310bafaa89af9ff3a4d152b36dcfa5439d9be80d0ad299fd347e012aca5c6b",++ "source_commit": "db9db65aad7a6fe6fa9fc5fd31a9c45c72f4f68d",++ "installed_package_files_matching_source": 25,++ "pip_check": true,++ "cli_help": true,++ "browser_assets": true,++ "source_package": "dopplergeist",++ "scope": "offline installed-package verification; no data generation"++}diff --cc evidence/e2e-worker-20261103/installed-real-http-verification.jsonindex 0000000,0000000..cb92268new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/installed-real-http-verification.json@@@ -1,0 -1,0 +1,102 @@@++{++ "schema_version": 1,++ "scope": "actual_local_http_upload_verification",++ "started_utc": "2026-11-03T04:20:57.593668Z",++ "expected_status": "needs_input",++ "expected_reason": "recording_time_required",++ "timeout_s": 900.0,++ "source_sha256": "e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0",++ "source_bytes": 42085293,++ "request": {++ "schema_version": 1,++ "search": {++ "coverage": "conus"++ }++ },++ "implementation_files": {++ "__init__.py": "01428b7938817c1cfe7eb3cf7e186f35b3fa7bc2d85f14204d07e0aa251d2c88",++ "audio.py": "f9248876059f7f05f3f3db8575e43b9c12f96c536c70b8afc298cfdebcb977a0",++ "automatic.py": "ae0c182d26bb7867aacc758855a6de978532974044df332f8cb26b88e036d07a",++ "cli.py": "91f62e955aa3a343ae2f916cff83ef7f58bc3b55e13dc5f40ff795bb6bd7e447",++ "confidence.py": "fe45e81d9dd026d1eae093eeca41c42238eb117a3919c68b1d6cbc637de162f6",++ "contracts.py": "66e311197e69fc6636dea33e25ae2acccfeba2845b0561963f33112c932a969f",++ "data_access.py": "de2e000afd87c7718fb67b965c7cdceea7a90378b8cdcdf0f7226ea8ca94f080",++ "discovery.py": "6a44c1728e8c1b0f282ca2751db050ac4bdf53998b1d8336d213ec790a83f6f7",++ "evaluation.py": "2186f839677883a3095a5d233921b4323d054f2c9101f7ee0c2773b10b2323fd",++ "finite_search.py": "9e86e5324905a5702fdd2523c308d3b4484661a65e8d72619b72b4ba66be90da",++ "geometry.py": "1508ff56d9f52f94cd1916db1c77045462dd2271930362883fec6bfd69bda2c9",++ "intake.py": "c88f51f8c7edd6abb74fca830a839d0bbce758beb9a582a7791a8a174b603781",++ "jobs.py": "bb20ff6d9e656a050231bbc9f30b9dd1d7b986039259a408cba3504648fd81b7",++ "matching.py": "b735cdc0fcb38632b16309a44dfaffce5937a8e1b6d2c9946d6f77a30c97f8ce",++ "pipeline.py": "7e4e1f2c3bb37421e4ad8e9a35f52fadbc8dde3025e6c93938a91a21b7ae247d",++ "provenance.py": "e4a995ab3d140a6860f96a3402c6e2c8b17e5b0f7c8e36cfda3273a435b099d5",++ "search.py": "c45a1abdc61972e65f2d6ca1062b2967d7c59296bada79d7cee983c0f22fc2fe",++ "service.py": "f8b0d72c83241963e4a7372bdfd7d2fe9041b968c4cb03d242bfb42028f8a283",++ "terrain.py": "b8258fa2d950c2348c78e019f9e97ce9fe6c760cf7fd47a81d1a21d23362948a",++ "tiled_search.py": "cbfe898fd447e8aec1cf8b9d29e0d981808dc0304d20ae8e9b6a6b70af2c2df6",++ "tracks.py": "523b9d629083ba2792a1da2cd34d8b89ef57236febcc284f62886ba103ef20ec"++ },++ "verifier_sha256": "9724265d1a4da12a6117717c95b258e71afcff9fbdf145c4ade689be51a3eb2f",++ "python_executable": "/workspace/scratch/e8a2a58f21d0/integration-audit/current-package/venv/bin/python",++ "python_version": "3.12.14 (main, Aug 25 2026, 14:00:49) [Clang 22.1.3 ]",++ "verification_passed": true,++ "http_checks_passed": true,++ "pipeline_evidence_passed": true,++ "full_pipeline_observed": false,++ "supported_decision": false,++ "location_accuracy_evaluated": false,++ "browser_verified": false,++ "interrupted": false,++ "interruption_signal": null,++ "limitations": [++ "HTTP verification does not establish location accuracy or browser behavior.",++ "Expected inconclusive or failed responses are preserved, not promoted to localization success.",++ "This verifier accepts no evaluation labels and performs no ground-truth comparison."++ ],++ "service": {++ "shutdown_signal": "SIGINT",++ "forced_kill": false,++ "returncode": 0,++ "command": [++ "/workspace/scratch/e8a2a58f21d0/integration-audit/current-package/venv/bin/python",++ "-m",++ "dopplergeist.cli",++ "serve",++ "--port",++ "0",++ "--jobs",++ "/workspace/scratch/e8a2a58f21d0/integration-audit/current-package/real-reference-http/jobs",++ "--config",++ "/workspace/scratch/e8a2a58f21d0/integration-audit/current-package/real-reference-http/operator.json",++ "--max-runtime",++ "900.0"++ ],++ "pid": 66,++ "port": 45349,++ "shutdown_requested_utc": "2026-11-03T04:21:17.852187Z",++ "stopped_utc": "2026-11-03T04:21:17.867788Z"++ },++ "sigterm_cleanup_handler_installed": true,++ "job_id": "ea78eaf66fd449b8ad0bc77888949908",++ "status": "needs_input",++ "reason_code": "recording_time_required",++ "producer_reported_success": false,++ "candidate_count": 0,++ "event_count": 16,++ "checks": {++ "original_preserved": true,++ "request_preserved": true,++ "operator_preserved": true,++ "result_preserved": true,++ "automatic_provenance_verified": true,++ "downloaded_original_verified": true,++ "downloaded_result_verified": true++ },++ "expectation_matched": true,++ "implementation_unchanged": true,++ "terminal_result_preserved_after_shutdown": true,++ "pipeline_evidence_errors": [],++ "pipeline_evidence_preserved_after_inspection": true,++ "finished_utc": "2026-11-03T04:21:18.008099Z",++ "elapsed_s": 20.41445216200009++}diff --cc evidence/e2e-worker-20261103/installed-real-pipeline-evidence.jsonindex 0000000,0000000..6bfc64dnew file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/installed-real-pipeline-evidence.json@@@ -1,0 -1,0 +1,47 @@@++{++ "schema_version": 1,++ "passed": true,++ "full_pipeline_observed": false,++ "scientific_decision_expected": false,++ "stages_verified": [++ "automatic_provenance",++ "intake",++ "discovery"++ ],++ "artifacts": {++ "provenance.json": {++ "bytes": 2644,++ "sha256": "8c09ef37a4ccb9877deb89b65cd3f667da6a769ea1ff4def9a888b403eb62d28"++ },++ "input.json": {++ "bytes": 127,++ "sha256": "db0949139f5fd8793b829984fc677356c7c1e25e3e55764ebb703d2bd112c625"++ },++ "request.json": {++ "bytes": 222,++ "sha256": "47ebd63809d5f4d732cf80a41f614177c7928b865af63f48f99b219d26d3bc4b"++ },++ "intake/recording.json": {++ "bytes": 209,++ "sha256": "5d8d0859914e461985ac0f5a14effcdaaf757e3ec78f13e3a04f22c0a4fc8b86"++ },++ "intake/intake.json": {++ "bytes": 933,++ "sha256": "8070bd68f80e502f51a4eecfbeb3d35e3ab2d29d7a734a16c5cdad331385919d"++ },++ "intake/recording.f32": {++ "bytes": 57602952,++ "sha256": "b6de3046a361c67c1096208b16123187b0c9ad1d0b2b6116358f884ffcb51e5f"++ },++ "discovery/discovery.json": {++ "bytes": 201228,++ "sha256": "6718303e2aacfa76121b9096a45d9810f215e7bab50851a8b1c071e7a782cea6"++ }++ },++ "errors": [],++ "location_accuracy_evaluated": false,++ "limitations": [++ "Stage consistency does not independently reproduce decoding or scientific fitting.",++ "No withheld-location comparison or accuracy evaluation is performed."++ ]++}diff --cc evidence/e2e-worker-20261103/real-http-verification.jsonindex 0000000,0000000..ebd4f30new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/real-http-verification.json@@@ -1,0 -1,0 +1,102 @@@++{++ "schema_version": 1,++ "scope": "actual_local_http_upload_verification",++ "started_utc": "2026-11-03T04:14:50.484869Z",++ "expected_status": "needs_input",++ "expected_reason": "recording_time_required",++ "timeout_s": 900.0,++ "source_sha256": "e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0",++ "source_bytes": 42085293,++ "request": {++ "schema_version": 1,++ "search": {++ "coverage": "conus"++ }++ },++ "implementation_files": {++ "__init__.py": "01428b7938817c1cfe7eb3cf7e186f35b3fa7bc2d85f14204d07e0aa251d2c88",++ "audio.py": "f9248876059f7f05f3f3db8575e43b9c12f96c536c70b8afc298cfdebcb977a0",++ "automatic.py": "ae0c182d26bb7867aacc758855a6de978532974044df332f8cb26b88e036d07a",++ "cli.py": "91f62e955aa3a343ae2f916cff83ef7f58bc3b55e13dc5f40ff795bb6bd7e447",++ "confidence.py": "fe45e81d9dd026d1eae093eeca41c42238eb117a3919c68b1d6cbc637de162f6",++ "contracts.py": "66e311197e69fc6636dea33e25ae2acccfeba2845b0561963f33112c932a969f",++ "data_access.py": "de2e000afd87c7718fb67b965c7cdceea7a90378b8cdcdf0f7226ea8ca94f080",++ "discovery.py": "6a44c1728e8c1b0f282ca2751db050ac4bdf53998b1d8336d213ec790a83f6f7",++ "evaluation.py": "2186f839677883a3095a5d233921b4323d054f2c9101f7ee0c2773b10b2323fd",++ "finite_search.py": "9e86e5324905a5702fdd2523c308d3b4484661a65e8d72619b72b4ba66be90da",++ "geometry.py": "1508ff56d9f52f94cd1916db1c77045462dd2271930362883fec6bfd69bda2c9",++ "intake.py": "c88f51f8c7edd6abb74fca830a839d0bbce758beb9a582a7791a8a174b603781",++ "jobs.py": "b493140edabde20674d46022d683a462002bb336a30e2db4fde6f65890a8e0d9",++ "matching.py": "b735cdc0fcb38632b16309a44dfaffce5937a8e1b6d2c9946d6f77a30c97f8ce",++ "pipeline.py": "7e4e1f2c3bb37421e4ad8e9a35f52fadbc8dde3025e6c93938a91a21b7ae247d",++ "provenance.py": "b5183cb9ceaf4bb0c654cbd5d7e67c8cd42cdd2f156bcb8425abc8e2fc5792ea",++ "search.py": "c45a1abdc61972e65f2d6ca1062b2967d7c59296bada79d7cee983c0f22fc2fe",++ "service.py": "0a5c81b6c88a7bf83a487272019e14a102dccc8fe27b823ad4f3335a28476f4d",++ "terrain.py": "b8258fa2d950c2348c78e019f9e97ce9fe6c760cf7fd47a81d1a21d23362948a",++ "tiled_search.py": "cbfe898fd447e8aec1cf8b9d29e0d981808dc0304d20ae8e9b6a6b70af2c2df6",++ "tracks.py": "523b9d629083ba2792a1da2cd34d8b89ef57236febcc284f62886ba103ef20ec"++ },++ "verifier_sha256": "959167ae4374d162fc62306d9038110d429d3b1c2a109550e5a77dafd45c8309",++ "python_executable": "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/../.venv/bin/python",++ "python_version": "3.12.14 (main, Aug 25 2026, 14:00:49) [Clang 22.1.3 ]",++ "verification_passed": true,++ "http_checks_passed": true,++ "pipeline_evidence_passed": true,++ "full_pipeline_observed": false,++ "supported_decision": false,++ "location_accuracy_evaluated": false,++ "browser_verified": false,++ "interrupted": false,++ "interruption_signal": null,++ "limitations": [++ "HTTP verification does not establish location accuracy or browser behavior.",++ "Expected inconclusive or failed responses are preserved, not promoted to localization success.",++ "This verifier accepts no evaluation labels and performs no ground-truth comparison."++ ],++ "service": {++ "shutdown_signal": "SIGINT",++ "forced_kill": false,++ "returncode": 0,++ "command": [++ "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/../.venv/bin/python",++ "-m",++ "aircraft_geoloc.cli",++ "serve",++ "--port",++ "0",++ "--jobs",++ "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/http/jobs",++ "--config",++ "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/http/operator.json",++ "--max-runtime",++ "900.0"++ ],++ "pid": 20,++ "port": 41139,++ "shutdown_requested_utc": "2026-11-03T04:15:10.744126Z",++ "stopped_utc": "2026-11-03T04:15:10.775700Z"++ },++ "sigterm_cleanup_handler_installed": true,++ "job_id": "dcf5816d3d0f4a1a9a551b7269f27ec8",++ "status": "needs_input",++ "reason_code": "recording_time_required",++ "producer_reported_success": false,++ "candidate_count": 0,++ "event_count": 16,++ "checks": {++ "original_preserved": true,++ "request_preserved": true,++ "operator_preserved": true,++ "result_preserved": true,++ "automatic_provenance_verified": true,++ "downloaded_original_verified": true,++ "downloaded_result_verified": true++ },++ "expectation_matched": true,++ "implementation_unchanged": true,++ "terminal_result_preserved_after_shutdown": true,++ "pipeline_evidence_errors": [],++ "pipeline_evidence_preserved_after_inspection": true,++ "finished_utc": "2026-11-03T04:15:10.917913Z",++ "elapsed_s": 20.433066061001227++}diff --cc evidence/e2e-worker-20261103/real-pipeline-evidence.jsonindex 0000000,0000000..be177d4new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/real-pipeline-evidence.json@@@ -1,0 -1,0 +1,47 @@@++{++ "schema_version": 1,++ "passed": true,++ "full_pipeline_observed": false,++ "scientific_decision_expected": false,++ "stages_verified": [++ "automatic_provenance",++ "intake",++ "discovery"++ ],++ "artifacts": {++ "provenance.json": {++ "bytes": 2659,++ "sha256": "75afc3e73db9364ebc3277d32796f0f00202ab92792e1d3e8ee0293b439f0368"++ },++ "input.json": {++ "bytes": 127,++ "sha256": "db0949139f5fd8793b829984fc677356c7c1e25e3e55764ebb703d2bd112c625"++ },++ "request.json": {++ "bytes": 237,++ "sha256": "d923198140f158d2a94cb57164221c8982314edeb9e9f4178de8748e93fb39be"++ },++ "intake/recording.json": {++ "bytes": 209,++ "sha256": "5d8d0859914e461985ac0f5a14effcdaaf757e3ec78f13e3a04f22c0a4fc8b86"++ },++ "intake/intake.json": {++ "bytes": 948,++ "sha256": "a2efdf7ab7fbc5aa3100016735f86c4d5f6d85c91eea81165b32a6c05a2a08c9"++ },++ "intake/recording.f32": {++ "bytes": 57602952,++ "sha256": "b6de3046a361c67c1096208b16123187b0c9ad1d0b2b6116358f884ffcb51e5f"++ },++ "discovery/discovery.json": {++ "bytes": 201228,++ "sha256": "6718303e2aacfa76121b9096a45d9810f215e7bab50851a8b1c071e7a782cea6"++ }++ },++ "errors": [],++ "location_accuracy_evaluated": false,++ "limitations": [++ "Stage consistency does not independently reproduce decoding or scientific fitting.",++ "No withheld-location comparison or accuracy evaluation is performed."++ ]++}diff --cc evidence/e2e-worker-20261103/real-result-summary.jsonindex 0000000,0000000..ed65678new file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/real-result-summary.json@@@ -1,0 -1,0 +1,50 @@@++{++ "scope": "Compact extraction from existing real-input artifacts; no experiment or model rerun.",++ "full_result_local_path": "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/http/result.json",++ "full_discovery_local_path": "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/http/jobs/dcf5816d3d0f4a1a9a551b7269f27ec8/discovery/discovery.json",++ "job_id": "dcf5816d3d0f4a1a9a551b7269f27ec8",++ "status": "needs_input",++ "reason_code": "recording_time_required",++ "required_fields": [++ "time_window"++ ],++ "message": "Supply a defensible UTC window for the start of this recording. File creation and upload times are not recording clocks.",++ "recording": {++ "source_sha256": "e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0",++ "duration_s": 3600.1845,++ "sample_rate_hz": 4000,++ "channels": 1,++ "source_format": "mp3",++ "time_window": null++ },++ "coverage": {++ "search_complete": false,++ "data_status": "unavailable",++ "limitations": [],++ "requested_area": {++ "coverage": "conus"++ }++ },++ "discovery": {++ "event_count": 16,++ "chunk_count": 60,++ "ridge_count": 18,++ "settings": {++ "chunk_s": 120.0,++ "overlap_s": 60.0,++ "min_frequency_hz": 40.0,++ "max_frequency_hz": 1600.0,++ "window_s": 2.0,++ "hop_s": 0.5,++ "min_contrast": 2.5,++ "min_duration_s": 12.0,++ "min_support": 0.65,++ "min_drop_hz": 4.0,++ "min_fractional_drop": 0.03,++ "max_gap_s": 2.0,++ "max_fragment_gap_s": 20.0,++ "max_peaks_per_frame": 60++ },++ "scope": "automatic acoustic moving-tone proposals; aircraft identity unconfirmed"++ }++}diff --cc evidence/e2e-worker-20261103/real-source-provenance.jsonindex 0000000,0000000..cb9251cnew file mode 100644--- /dev/null+++ b/evidence/e2e-worker-20261103/real-source-provenance.json@@@ -1,0 -1,0 +1,30 @@@++{++ "source_kind": "real_field_recording",++ "source_url": "https://www.youtube.com/watch?v=4CxVxuMVkMc",++ "source_artifact_id": 13201030184,++ "source_wav_sha256": "262d9c4eba1c80657813c604140ba2afbbaabed2b3aebc833cba7cafdc005e9f",++ "mp3_sha256": "e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0",++ "mp3_bytes": 42085293,++ "ffmpeg_command": [++ "ffmpeg",++ "-nostdin",++ "-v",++ "error",++ "-i",++ "/workspace/scratch/e8a2a58f21d0/real-inputs/data/source/reference-recording.wav",++ "-map",++ "0:a:0",++ "-vn",++ "-map_metadata",++ "-1",++ "-codec:a",++ "libmp3lame",++ "-q:a",++ "2",++ "/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/reference-complete.mp3"++ ],++ "selection": "complete recording, no time or frequency selection",++ "recording_sample_zero_utc": null,++ "recorder_truth_used": false,++ "scope": "real whole-recording intake and HTTP response; no location-accuracy claim"++}diff --cc scripts/verify_upload_http.pyindex 0000000,0000000..83c7514new file mode 100644--- /dev/null+++ b/scripts/verify_upload_http.py@@@ -1,0 -1,0 +1,1008 @@@++#!/usr/bin/env python3++"""Verify an actual local MP3 upload without a browser.++++Exit zero means HTTP, persistence, stage evidence, and outcome checks passed.++The receipt separately preserves the producer's scientific status. An expected++inconclusive response is never counted as supported localization or accuracy.++The existing browser verifier is independent and remains unchanged.++"""++from __future__ import annotations++++import argparse++from datetime import datetime, timezone++import hashlib++import http.client++import json++import math++import os++from pathlib import Path++import re++import signal++import subprocess++import sys++import threading++import time++import uuid++++import dopplergeist++from dopplergeist.contracts import utc_timestamp, validate_recording, validate_request, validate_result++from dopplergeist.jobs import TERMINAL, write_json++++++def sha256(path):++ with Path(path).open("rb") as stream:++ return hashlib.file_digest(stream, "sha256").hexdigest()++++++def now():++ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")++++++def remaining(deadline):++ value = deadline - time.monotonic()++ if value <= 0:++ raise TimeoutError("HTTP verification exceeded its declared time budget")++ return value++++++class VerificationInterrupted(InterruptedError):++ """An outer termination request must unwind through service cleanup."""++++++class TerminationGuard:++ def __init__(self, receipt):++ self.receipt = receipt++ self.received_monotonic = None++ self.interruptible = False++ self.previous = None++ self.installed = False++++ def __enter__(self):++ # Only the main thread can install handlers. The CLI always uses it.++ if threading.current_thread() is threading.main_thread():++ self.previous = signal.signal(signal.SIGTERM, self.handle)++ self.installed = True++ self.receipt["sigterm_cleanup_handler_installed"] = self.installed++ return self++++ def __exit__(self, *_):++ if self.installed:++ signal.signal(signal.SIGTERM, self.previous)++++ def handle(self, signum, _frame):++ if self.received_monotonic is not None:++ return # Repeated signals must not interrupt teardown.++ self.received_monotonic = time.monotonic()++ self.receipt.update(interrupted=True, interruption_signal=signal.Signals(signum).name,++ interruption_received_utc=now(), verification_passed=False,++ supported_decision=False)++ if self.interruptible:++ self.raise_if_interrupted()++++ def raise_if_interrupted(self):++ if self.received_monotonic is not None:++ raise VerificationInterrupted("HTTP verification interrupted by SIGTERM")++++++def stop_service(process, receipt, termination):++ """Leave time to write a receipt before the outer helper's 5 s kill grace."""++ if process is None:++ return++ service = receipt["service"]++ if process.poll() is None:++ service.update(shutdown_signal="SIGINT", shutdown_requested_utc=now())++ try:++ process.send_signal(signal.SIGINT)++ except ProcessLookupError:++ pass++ deadline = time.monotonic() + 10++ while process.poll() is None:++ # JobManager allows 3 s to stop its active worker. A SIGTERM can++ # arrive during ordinary shutdown, so reconsider this bound often.++ if termination.received_monotonic is not None:++ deadline = min(deadline, termination.received_monotonic + 3.5)++ left = deadline - time.monotonic()++ if left <= 0:++ service["forced_kill"] = True++ process.kill()++ killed = time.monotonic()++ reap_deadline = killed + 5++ while process.poll() is None:++ if termination.received_monotonic is not None:++ reap_deadline = min(reap_deadline, killed + 0.5,++ termination.received_monotonic + 4.0)++ reap_left = reap_deadline - time.monotonic()++ if reap_left <= 0:++ raise subprocess.TimeoutExpired(process.args, max(0, reap_deadline - killed))++ try:++ process.wait(timeout=min(0.05, reap_left))++ except subprocess.TimeoutExpired:++ pass++ break++ try:++ process.wait(timeout=min(0.05, left))++ except subprocess.TimeoutExpired:++ pass++ service.update(returncode=process.returncode, stopped_utc=now())++++++class LocalClient:++ """Direct loopback HTTP; proxy environment variables are not consulted."""++++ def __init__(self, port, deadline):++ self.port, self.deadline = port, deadline++++ def request(self, method, path, *, body=None, headers=None, destination=None):++ connection = http.client.HTTPConnection("127.0.0.1", self.port,++ timeout=min(30, remaining(self.deadline)))++ try:++ connection.request(method, path, body=body, headers=headers or {})++ response = connection.getresponse()++ if destination is not None:++ with Path(destination).open("xb") as target:++ while block := response.read(1024 * 1024):++ remaining(self.deadline)++ target.write(block)++ return response.status, None++ payload = response.read(64 * 1024 * 1024 + 1)++ if len(payload) > 64 * 1024 * 1024:++ raise ValueError("HTTP JSON response exceeds the verifier's 64 MiB limit")++ return response.status, json.loads(payload)++ finally:++ connection.close()++++ def get(self, path):++ code, value = self.request("GET", path)++ if code != 200:++ raise RuntimeError(f"GET {path} returned HTTP {code}")++ return value++++++def wait_for_service(process, log_path, deadline):++ while True:++ if process.poll() is not None:++ raise RuntimeError("Upload service exited during startup; inspect service.log")++ match = re.search(r"DOPPLERGEIST: http://127\.0\.0\.1:(\d+) ", log_path.read_text())++ if match:++ return LocalClient(int(match.group(1)), deadline)++ time.sleep(min(0.05, remaining(deadline)))++++++def poll_job(client, job_id, history_path, *, interval_s):++ with history_path.open("x") as history:++ previous = None++ while True:++ value = client.get(f"/api/jobs/{job_id}")++ validate_result(value)++ if value["job_id"] != job_id:++ raise ValueError("Polled result belongs to a different job")++ if value != previous:++ history.write(json.dumps({"observed_utc": now(), "result": value}, allow_nan=False) + "\n")++ history.flush()++ previous = value++ if value["status"] in TERMINAL:++ return value++ time.sleep(min(interval_s, remaining(client.deadline)))++++++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())++ input_record, stored_request = read("input.json"), read("request.json")++ if input_record != {"sha256": sha256(original), "bytes": original.stat().st_size, "path": "input.mp3"}:++ raise ValueError("Persisted input receipt does not describe the submitted bytes")++ if sha256(directory / "input.mp3") != input_record["sha256"]:++ raise ValueError("Persisted original differs from the submitted MP3")++ uploaded = Path(stored_request.pop("audio_path"))++ if uploaded != directory / "input.mp3" or stored_request != wire:++ raise ValueError("Persisted request differs from the submitted request")++ if read("operator.json") != operator:++ raise ValueError("Persisted operator configuration differs from the submitted configuration")++ if read("result.json") != final:++ raise ValueError("Persisted terminal result differs from the HTTP result")++ provenance = read("provenance.json")++ if (provenance.get("source_sha256") != input_record["sha256"]++ or provenance.get("implementation_files") != implementation):++ raise ValueError("Automatic provenance does not identify the submitted input and executed source")++ if final.get("recording", {}).get("source_sha256", input_record["sha256"]) != input_record["sha256"]:++ raise ValueError("Decoded recording identifies a different source")++ return {"original_preserved": True, "request_preserved": True,++ "operator_preserved": True, "result_preserved": True,++ "automatic_provenance_verified": True}++++++def complete_finite_clock_assessment(assessment):++ """Validate a finite winner under the recorded trial-count convention."""++ if (not isinstance(assessment, dict) or assessment.get("complete") is not True++ or not all(type(assessment.get(key)) is int and assessment[key] >= 0++ for key in ("scheduled_trials", "evaluated_trials", "rejected_trials", "unknown_trials"))++ or assessment["unknown_trials"] != 0 or assessment["evaluated_trials"] == 0):++ return False++ semantics = assessment.get("trial_count_semantics")++ if semantics == "disjoint_evaluated_rejected_unknown":++ reasons = assessment.get("reasons")++ return (assessment["scheduled_trials"] == assessment["evaluated_trials"] + assessment["rejected_trials"]++ and assessment.get("empty_clock_domain") is False++ and isinstance(reasons, list) and all(isinstance(reason, str) for reason in reasons))++ if semantics is not None:++ return False++ # Historical #86 records count rejected trials inside evaluated_trials.++ return (assessment["scheduled_trials"] == assessment["evaluated_trials"]++ and assessment["rejected_trials"] <= assessment["evaluated_trials"]++ and assessment.get("unknown_reasons") == {}++ and assessment.get("empty_clock_domain") is False)++++++def bounded_finite_clock_assessment(detail, max_groups):++ """Check persisted association ceilings without recomputing physical fits."""++ if not isinstance(detail, dict):++ return False++ kind = "matched_group_support_minus_normalized_residual"++ assessment, indices = detail.get("scoring_assessment"), detail.get("event_indices")++ if (not isinstance(assessment, dict) or detail.get("score_kind") != kind++ or assessment.get("complete") is not False++ or assessment.get("unknown_score_bound_kind") != kind++ or assessment.get("unknown_score_bound_method") != "nonnegative_loss_and_validated_event_fits"++ or not isinstance(indices, list) or not indices++ or any(type(index) is not int or not 0 <= index < max_groups for index in indices)++ or indices != sorted(set(indices))):++ return False++ names = ("scheduled_trials", "evaluated_trials", "rejected_trials", "unknown_trials",++ "bounded_unknown_trials", "bounded_unknown_rejections")++ if not all(type(assessment.get(name)) is int and assessment[name] >= 0 for name in names):++ return False++ unknown, bounded, rejected = (assessment[name] for name in names[3:])++ if (not 0 < unknown == bounded or rejected > bounded++ or assessment.get("trial_count_semantics") != "disjoint_evaluated_rejected_unknown"++ or assessment.get("empty_clock_domain") is not False++ or assessment["scheduled_trials"] != sum(assessment[name] for name in names[1:4])):++ return False++ upper = assessment.get("unknown_score_upper_bound")++ return (upper is None if rejected == bounded else++ type(upper) in (int, float) and math.isfinite(upper) and 0 <= upper <= len(indices))++++++def model_assessment_accounted_for(search):++ """Require explicit model accounting when the producer reports that contract."""++ if not any(name in search for name in ("model_support", "model_support_complete", "model_assessment_complete")):++ return True # Historical reports predate this separate coverage contract.++ support = search.get("model_support")++ names = ("unsupported_cpa_track_evaluations", "unclassified_score_candidates",++ "evaluated_trials", "rejected_trials", "unknown_trials")++ if (not isinstance(support, dict)++ or not all(type(support.get(name)) is int and support[name] >= 0 for name in names)):++ return False++ if "model_assessment_complete" in search and search["model_assessment_complete"] is not True:++ return False++ if search.get("model_support_complete") is True:++ return not any(support[name] for name in (names[0], names[1], "unknown_trials"))++ finite = search.get("finite_search_evidence")++ bounded_names = ("bounded_score_candidates", "unbounded_score_candidates", "unreported_trial_envelopes")++ return (search.get("model_support_complete") is False and search.get("model_assessment_complete") is True++ and isinstance(finite, dict)++ and finite.get("score_kind") == "matched_group_support_minus_normalized_residual"++ and all(type(support.get(name)) is int and support[name] >= 0 for name in bounded_names)++ and not any(support[name] for name in (names[0], bounded_names[1], bounded_names[2]))++ and 0 < support["bounded_score_candidates"] == support["unclassified_score_candidates"]++ and support["unknown_trials"] >= support["bounded_score_candidates"]++ and type(finite.get("bounded_unknown_envelopes")) is int++ and finite["bounded_unknown_envelopes"] == support["bounded_score_candidates"])++++++def inspect_finite_search(artifact, read, search, configuration, refinement):++ """Audit recorded retention read-only; physical trials are not recomputed."""++ import sqlite3++++ def require(condition, message):++ if not condition:++ raise ValueError(message)++++ def digest(value):++ return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest()++++ finite = search["finite_search_evidence"]++ diagnostics, rows = refinement["matching_diagnostics"], refinement["ranked"]++ require(isinstance(finite, dict) and finite == diagnostics.get("finite_search_evidence"),++ "Search and refinement finite evidence differ")++ require(finite.get("schema_version") == 1 and finite.get("scope") == "evaluated_finite_grid"++ and finite.get("ledger_artifact") == "retention.sqlite", "Unsupported finite retention evidence")++ require(finite.get("max_event_groups") == len(configuration["events"]), "Finite group bound differs from search")++ budget, scoring = configuration["budget"], configuration["scoring"]++ require(finite.get("spacing_m") == budget["spacing_m"]++ and finite.get("refine_spacing_m") == min(budget["spacing_m"], budget["refine_spacing_m"]),++ "Finite resolutions differ from the recorded search budget")++ domain = finite.get("optimizer_domain", {})++ require(domain.get("run_hash") == search["run_hash"]++ and domain.get("source_fit_code_sha256") == configuration["code"].get("matching.py")++ and domain.get("score_code_sha256") == configuration["code"].get("search.py")++ and domain.get("clock_window_s") == scoring.get("recording_start_window_s")++ and domain.get("time_step_s") == scoring.get("time_step_s", .5)++ and domain.get("declared_sweep_s") == scoring.get("time_sweep_s", 5.),++ "Finite optimizer domain differs from the recorded source or shared clock")++ path = artifact("search/retention.sqlite")++ retained = search.get("ranked")++ require(isinstance(retained, list), "Finite search lacks its original retained rows")++ identities = [row.get("mode_id") for row in retained]++ require(all(isinstance(identity, str) and identity for identity in identities)++ and len(identities) == len(set(identities)), "Original retained mode IDs are invalid")++ by_id = dict(zip(identities, retained))++ totals, names, originals = {}, {}, {}++ evaluated = discarded = coarse_unknown = 0++ bounded_count = bounded_rejections = 0++ bound = unknown_bound = None++ bound_fields = ("bounded_unknown_envelopes", "bounded_unknown_rejections", "best_unknown_score_upper_bound")++ bound_contract = any(name in finite for name in bound_fields)++ support_totals = dict(unsupported_cpa_track_evaluations=0, unclassified_score_candidates=0,++ bounded_score_candidates=0, unbounded_score_candidates=0, unknown_trials=0, unreported_trial_envelopes=0)++ db = sqlite3.connect(path.as_uri() + "?mode=ro&immutable=1", uri=True)++ try:++ require(db.execute("PRAGMA quick_check").fetchall() == [("ok",)], "Corrupt finite retention ledger")++ require(db.execute("SELECT identity,score_kind FROM run").fetchall() ==++ [(search["run_hash"], finite["score_kind"])], "Finite ledger identifies another run or score kind")++ has_bounds = db.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='bounds'").fetchone()[0] == 1++ require(not bound_contract or (has_bounds and all(name in finite for name in bound_fields)),++ "Finite bound evidence lacks its persisted bound table or aggregate fields")++ for name, checksum, occurrences, duplicates, encoded_kept in db.execute(++ "SELECT name,checksum,occurrences,duplicates,kept FROM stages ORDER BY name"):++ phase, suffix = name.split(":", 1)++ require(phase in {"coarse", "global", "fine", "fine-global"} and suffix,++ "Unknown finite retention stage")++ names.setdefault(phase, set()).add(suffix)++ kept = json.loads(encoded_kept)++ require(isinstance(kept, list) and all(isinstance(identity, str) for identity in kept)++ and len(kept) == len(set(kept)), "Invalid retained IDs in a ledger stage")++ kept_set, seen_kept, count, stage_digest = set(kept), set(), 0, hashlib.sha256()++ for record in db.execute("SELECT mode_id,score,groups_count,kind,seed FROM records WHERE stage=? ORDER BY mode_id", (name,)):++ identity, score, groups, kind, encoded_seed = record++ seed = json.loads(encoded_seed)++ require(isinstance(seed, dict) and set(seed) == {"event_indices", "flight_ids",++ "pass_emission_times_s", "position", "recording_start_time_s"}++ and isinstance(seed["position"], list) and len(seed["position"]) == 5++ and isinstance(seed["pass_emission_times_s"], list)++ and isinstance(seed["event_indices"], list) and isinstance(seed["flight_ids"], list)++ and all(isinstance(flight, str) and flight for flight in seed["flight_ids"])++ and all(type(value) in (int, float) and math.isfinite(value)++ for value in [*seed["position"], *seed["pass_emission_times_s"], seed["recording_start_time_s"]]),++ "Finite ledger seed has invalid physical fields")++ require(type(score) in (int, float) and math.isfinite(score) and kind == finite["score_kind"],++ "Finite ledger contains an invalid score or mixed units")++ require(type(groups) is int and 1 <= groups <= finite["max_event_groups"]++ and groups == len(seed["event_indices"]) == len(seed["flight_ids"]) == len(seed["pass_emission_times_s"])++ and all(type(i) is int and 0 <= i < finite["max_event_groups"] for i in seed["event_indices"])++ and seed["event_indices"] == sorted(set(seed["event_indices"])),++ "Finite ledger group or association counts are inconsistent")++ require(identity == "mode-" + digest(seed), "Finite mode ID differs from its exact seed")++ if identity in by_id:++ row = by_id[identity]++ expected_seed = {"event_indices": row.get("event_indices", list(range(len(row["flight_ids"])))),++ "flight_ids": row["flight_ids"], "pass_emission_times_s": row.get("pass_emission_times_s", []),++ "position": [float(row.get(key, 0)) for key in ("x", "y", "lat", "lon", "elev_m")],++ "recording_start_time_s": float(row["recording_start_time_s"])}++ require(seed == row.get("mode_seed") == expected_seed,++ "Original retained row differs from its physical seed")++ stage_digest.update(json.dumps(record, separators=(",", ":"), allow_nan=False).encode() + b"\n")++ count += 1++ if identity in kept_set:++ seen_kept.add(identity)++ require(type(occurrences) is int and type(duplicates) is int and occurrences >= count++ and duplicates == occurrences-count and seen_kept == kept_set,++ "Finite ledger occurrence, duplicate or retained counts differ")++ stage_digest.update(json.dumps(sorted(kept), separators=(",", ":")).encode())++ stage_digest.update(json.dumps([occurrences, duplicates]).encode())++ stage_bounds = {}++ if has_bounds:++ for record in db.execute("SELECT bound_id,upper_score,groups_count,detail FROM bounds WHERE stage=? ORDER BY bound_id", (name,)):++ identity, upper, groups, encoded_detail = record++ detail = json.loads(encoded_detail)++ require(bound_contract and phase in {"coarse", "fine"}++ and finite["score_kind"] == "matched_group_support_minus_normalized_residual"++ and bounded_finite_clock_assessment(detail, finite["max_event_groups"]),++ "Finite bound has no complete association-trial accounting")++ receiver, flights, times = (detail.get(key) for key in ("receiver", "flight_ids", "pass_emission_times_s"))++ require(isinstance(receiver, dict) and set(receiver) == {"x", "y", "lat", "lon", "elev_m"}++ and all(type(value) in (int, float) and math.isfinite(value) for value in receiver.values())++ and isinstance(flights, list) and all(isinstance(flight, str) and flight for flight in flights)++ and isinstance(times, list) and all(type(value) in (int, float) and math.isfinite(value) for value in times)++ and type(groups) is int and groups == len(detail["event_indices"]) == len(flights) == len(times)++ and type(detail.get("point_id")) is int and type(detail.get("envelope_index")) is int++ and detail["envelope_index"] > 0 and type(detail.get("finite_best")) is bool++ and detail.get("support_failure") is None,++ "Finite bound has invalid physical association fields")++ clocks, interval = detail.get("clock_settings"), detail.get("recording_start_bounds_s")++ require(isinstance(clocks, dict) and set(clocks) == {"time_origin", "time_sweep_s", "time_step_s"}++ and all(value is None or type(value) in (int, float) and math.isfinite(value) for value in clocks.values())++ and (clocks["time_sweep_s"] is None or clocks["time_sweep_s"] >= 0)++ and (clocks["time_step_s"] is None or clocks["time_step_s"] > 0)++ and (interval is None or isinstance(interval, list) and len(interval) == 2++ and all(type(value) in (int, float) and math.isfinite(value) for value in interval)++ and interval[0] <= interval[1]),++ "Finite bound has invalid shared-clock fields")++ require(identity == "bound-" + digest(detail)++ and upper == detail["scoring_assessment"]["unknown_score_upper_bound"],++ "Finite bound differs from its recorded assessment or identity")++ stage_bounds[identity] = detail++ bounded_count += 1++ bounded_rejections += upper is None++ if upper is not None:++ unknown_bound = upper if unknown_bound is None else max(unknown_bound, upper)++ stage_digest.update(json.dumps(record, separators=(",", ":"), allow_nan=False).encode() + b"\n")++ require(stage_digest.hexdigest() == checksum, "Finite ledger stage checksum differs")++ total = totals.setdefault(phase, {"stages": 0, "input_occurrences": 0, "exact_duplicates": 0,++ "retained": 0, "discarded": 0})++ for key, value in (("stages", 1), ("input_occurrences", occurrences), ("exact_duplicates", duplicates),++ ("retained", len(kept)), ("discarded", count-len(kept))):++ total[key] += value++ if phase == "coarse":++ tile = read(f"search/tile-{suffix}.json")++ payload = tile["payload"]++ require(tile.get("run_hash") == search["run_hash"] and tile.get("payload_hash") == digest(payload)++ and payload.get("retention_checksum") == checksum++ and sorted(row["mode_id"] for row in payload["ranked"]) == sorted(kept),++ "Coarse checkpoint differs from its retention stage")++ for row in payload["ranked"]:++ score, kind, encoded_seed = db.execute(++ "SELECT score,kind,seed FROM records WHERE stage=? AND mode_id=?", (name, row["mode_id"])).fetchone()++ seed = json.loads(encoded_seed)++ physical = {"event_indices": row.get("event_indices", list(range(len(row["flight_ids"])))),++ "flight_ids": row["flight_ids"], "pass_emission_times_s": row.get("pass_emission_times_s", []),++ "position": [float(row.get(key, 0)) for key in ("x", "y", "lat", "lon", "elev_m")],++ "recording_start_time_s": float(row["recording_start_time_s"])}++ require(row["score"] == score and row.get("score_kind") == kind++ and row.get("mode_seed") == seed == physical,++ "Coarse checkpoint score or physical seed differs from its ledger")++ unknown = payload.get("counts", {}).get("unclassified_score_candidates", 0)++ require(type(unknown) is int and unknown >= 0, "Invalid coarse unknown-trial count")++ coarse_unknown += unknown++ if bound_contract and phase in {"coarse", "fine"}:++ support_path = path.parent / "support" / (name.replace(":", "-") + ".json")++ details, unsupported = [], []++ if support_path.exists():++ support_record = read("search/support/" + support_path.name)++ details, unsupported = (support_record.get(key) for key in++ ("unclassified_candidate_assessments", "unsupported_cpa_tracks"))++ require(support_record.get("stage") == name and isinstance(details, list)++ and all(isinstance(detail, dict) for detail in details) and isinstance(unsupported, list),++ "Finite support artifact has invalid stage or candidate evidence")++ certificates = {"bound-" + digest(detail): detail for detail in details++ if bounded_finite_clock_assessment(detail, finite["max_event_groups"])}++ require(stage_bounds == certificates, "Finite bound ledger omits or invents a recorded candidate assessment")++ if phase == "coarse":++ counts = payload.get("counts", {})++ require(counts.get("unclassified_candidate_assessments", []) == details++ and counts.get("unsupported_cpa_tracks", []) == unsupported++ and counts.get("unclassified_score_candidates", 0) == len(details)++ and counts.get("bounded_score_candidates", 0) == len(stage_bounds)++ and counts.get("unbounded_score_candidates", 0) == len(details)-len(stage_bounds),++ "Coarse support counts differ from persisted candidate assessments")++ support_totals["unsupported_cpa_track_evaluations"] += len(unsupported)++ support_totals["unclassified_score_candidates"] += len(details)++ support_totals["bounded_score_candidates"] += len(stage_bounds)++ support_totals["unbounded_score_candidates"] += len(details)-len(stage_bounds)++ for detail in details:++ assessment = detail.get("scoring_assessment")++ if isinstance(assessment, dict) and all(type(assessment.get(key)) is int and assessment[key] >= 0++ for key in ("evaluated_trials", "rejected_trials", "unknown_trials")):++ support_totals["unknown_trials"] += assessment["unknown_trials"]++ else:++ support_totals["unreported_trial_envelopes"] += 1++ require(db.execute("SELECT count(*) FROM records WHERE stage NOT IN (SELECT name FROM stages)").fetchone()[0] == 0,++ "Finite ledger contains records without a stage")++ require(not has_bounds or db.execute("SELECT count(*) FROM bounds WHERE stage NOT IN (SELECT name FROM stages)").fetchone()[0] == 0,++ "Finite ledger contains bounds without a stage")++ for identity, score in db.execute("SELECT mode_id,MAX(score) FROM records GROUP BY mode_id"):++ evaluated += 1++ if identity in by_id:++ originals[identity] = score++ else:++ discarded += 1++ bound = score if bound is None else max(bound, score)++ finally:++ db.close()++ require(names.get("coarse", set()) == names.get("global", set())++ and len(names.get("coarse", set())) == search["tiles_completed"]++ and names.get("fine", set()) == names.get("fine-global", set()),++ "Finite ledger stage coverage is incomplete")++ fine_points = search.get("refinement_points_searched", 0)++ require(type(fine_points) is int and fine_points >= 0++ and bool(names.get("fine")) == (fine_points > 0), "Finite refinement stage records are missing")++ require(finite.get("stages") == totals and set(originals) == set(identities),++ "Finite stage totals or original retained records differ")++ discarded += bounded_count-bounded_rejections++ if unknown_bound is not None:++ bound = unknown_bound if bound is None else max(bound, unknown_bound)++ require(finite.get("pruning_accounted_for") is True and finite.get("discarded_count") == discarded++ and finite.get("evaluated_modes") == evaluated, "Finite distinct retention counts differ")++ unknown = finite.get("unclassified_score_candidates")++ require(type(unknown) is int and unknown >= coarse_unknown, "Finite unknown-trial count is inconsistent")++ all_unknown_accounted = unknown == 0++ if bound_contract:++ require(type(finite["bounded_unknown_envelopes"]) is int++ and type(finite["bounded_unknown_rejections"]) is int++ and finite["bounded_unknown_envelopes"] == bounded_count++ and finite["bounded_unknown_rejections"] == bounded_rejections++ and finite["best_unknown_score_upper_bound"] == unknown_bound,++ "Finite bound aggregates differ from the persisted association ceilings")++ support = search.get("model_support")++ require(isinstance(support, dict) and all(type(support.get(key)) is int and support[key] == value++ for key, value in support_totals.items()) and unknown == support_totals["unclassified_score_candidates"]++ and finite.get("unsupported_cpa_track_evaluations") == support_totals["unsupported_cpa_track_evaluations"],++ "Finite model-support totals differ from persisted candidate assessments")++ all_unknown_accounted = model_assessment_accounted_for(search)++ require(type(search.get("model_assessment_complete")) is bool++ and search["model_assessment_complete"] == all_unknown_accounted,++ "Model assessment completeness contradicts its bound evidence")++ expected_bound = bound if all_unknown_accounted else None++ require(finite.get("best_discarded_score") == expected_bound,++ "Finite discarded score bound differs from all recorded distinct modes")++ if not all_unknown_accounted:++ require(finite.get("discarded_bound_status") == "unknown_model_or_trial_support",++ "Unknown trials have no explicit unbounded status")++ require(type(finite.get("complete")) is bool++ and finite["complete"] == (search["status"] == "complete" and all_unknown_accounted),++ "Finite completeness contradicts search or unknown trial evidence")++ require(finite.get("retained_modes") == [{"mode_id": identity, "score": originals[identity],++ "event_groups": len(by_id[identity]["mode_seed"]["event_indices"])} for identity in identities],++ "Finite retained original scores or groups differ")++ core_ids, assessed, unknown_retained = [], [], 0++ window = diagnostics["recording_start_window_s"]++ for identity, row in by_id.items():++ require(row["score"] == originals[identity] and row.get("score_kind") == finite["score_kind"],++ "Retained original row has a different score or score kind")++ assessment = row.get("scoring_assessment", {})++ known = complete_finite_clock_assessment(assessment)++ require(row.get("core_assessment_complete") is known, "Finite winner masks missing or unknown clock trials")++ unknown_retained += not known++ if known:++ core_ids.append(identity)++ fits = row.get("event_diagnostics", [])++ if (window[0] <= row["recording_start_time_s"] <= window[1]++ and len(fits) == len(row["flight_ids"]) > 0++ and all(isinstance(fit, dict) and type(fit.get("support_fraction")) in (int, float)++ and fit["support_fraction"] == 1. and type(fit.get("score")) in (int, float)++ and math.isfinite(fit["score"]) for fit in fits)):++ assessed.append(identity)++ require(unknown >= unknown_retained, "Finite aggregate omits unclassified retained clock trials")++ require(search.get("core_assessed_mode_ids") == core_ids++ and diagnostics.get("core_assessment_mapping_status") == "present"++ and diagnostics.get("assessed_mode_ids") == sorted(assessed),++ "Finite assessed IDs differ from supported producer assessments")++ mapped = [row.get("mode_id") for row in rows]++ require(diagnostics.get("candidate_mode_ids") == mapped and set(mapped) == set(identities),++ "Finite wire candidates omit or invent retained modes")++ for row, identity in zip(rows, mapped):++ seed = by_id[identity]["mode_seed"]++ require(row.get("mode_seed") == seed and row.get("event_indices") == seed["event_indices"]++ and row["flight_ids"] == seed["flight_ids"]++ and row.get("pass_emission_times_s") == seed["pass_emission_times_s"],++ "Refinement borrowed another mode's event-to-flight identity")++ original_fields = ("mode_id", "mode_seed", "pass_emission_times_s", "event_indices", "flight_ids",++ "lat", "lon", "recording_start_time_s", "score", "score_kind")++ for identity, original in by_id.items():++ require(any(all(row.get(key) == original.get(key) for key in original_fields)++ and row.get("elev_m", 0) == original.get("elev_m", 0) for row in rows),++ "Refinement omitted an original retained physical point")++ result = {"ledger_verified": True, "complete": finite["complete"] and set(assessed) == set(identities),++ "retained_modes": len(identities), "evaluated_modes": evaluated, "discarded_count": discarded,++ "best_discarded_score": expected_bound, "unclassified_score_candidates": unknown,++ "physical_trials_independently_recomputed": False}++ if bound_contract:++ result.update(unknown_score_bounds_verified=True, bounded_unknown_envelopes=bounded_count,++ bounded_unknown_rejections=bounded_rejections, best_unknown_score_upper_bound=unknown_bound)++ return result++++++def inspect_pipeline_evidence(directory, final, wire, operator):++ """Check stage receipts, separately from HTTP success or location accuracy.++++ A completed scientific decision needs every upstream stage. Early exits need++ the stages they reached; a work limit must not pretend to be a complete run.++ This checks persisted evidence and repeats the decision policy, not decoding,++ trajectory fitting, data acquisition, or comparison with withheld truth.++ """++ directory = Path(directory).resolve()++ scientific = (final.get("status") == "succeeded" or "candidates" in final++ or (final.get("status") == "inconclusive" and final.get("reason_code")++ not in {"no_supported_events", "data_unavailable", "work_limit"}))++ report = {"schema_version": 1, "passed": False, "full_pipeline_observed": False,++ "scientific_decision_expected": scientific, "stages_verified": [], "artifacts": {},++ "errors": [], "location_accuracy_evaluated": False,++ "limitations": ["Stage consistency does not independently reproduce decoding or scientific fitting.",++ "No withheld-location comparison or accuracy evaluation is performed."]}++++ def require(condition, message):++ if not condition:++ raise ValueError(message)++++ def artifact(name):++ path = directory / name++ require(path.is_file() and not any(p.is_symlink() for p in (path, *path.parents)++ if p != directory and directory in p.parents), f"Missing or unsafe stage artifact: {name}")++ require(path.resolve().is_relative_to(directory), f"Stage artifact leaves the job: {name}")++ report["artifacts"][name] = {"bytes": path.stat().st_size, "sha256": sha256(path)}++ return path++++ def read(name):++ def reject_constant(value):++ raise ValueError(f"Nonfinite JSON constant in {name}: {value}")++ value = json.loads(artifact(name).read_text(), parse_constant=reject_constant)++ require(isinstance(value, dict), f"Stage artifact must be a JSON object: {name}")++ return value++++ try:++ validate_result(final)++ provenance, input_record = read("provenance.json"), read("input.json")++ request = dict(wire, audio_path=str(directory / "input.mp3"))++ require(read("request.json") == request and provenance.get("request") == request,++ "Automatic provenance does not preserve the submitted request")++ operator_hash = hashlib.sha256(json.dumps(operator, sort_keys=True, allow_nan=False).encode()).hexdigest()++ require(provenance.get("operator_configuration_sha256") == operator_hash,++ "Automatic provenance has a different operator configuration")++ require(provenance.get("source_sha256") == input_record.get("sha256"),++ "Automatic provenance has a different source hash")++ require(provenance.get("ground_truth_used_by_search") is False++ and provenance.get("event_selection") == "automatic_whole_recording",++ "Automatic event selection and truth separation are not recorded")++ interrupted = (final["status"] == "cancelled" or final.get("reason_code") in++ {"work_limit", "worker_exit", "worker_launch", "processing_error"})++ if not interrupted:++ require(provenance.get("status") == final["status"]++ and provenance.get("coverage") == final.get("coverage"),++ "Automatic provenance does not match the terminal status and coverage")++ report["stages_verified"].append("automatic_provenance")++++ recording = None++ if scientific or "recording" in final:++ recording = validate_recording(read("intake/recording.json"))++ intake = read("intake/intake.json")++ require(recording == final.get("recording"), "Intake recording differs from the terminal recording")++ require(recording["source_sha256"] == input_record["sha256"], "Intake identifies a different source")++ require(recording.get("time_window") == wire.get("time_window"), "Intake changed the recording clock")++ count = intake.get("sample_count")++ require(type(count) is int and count > 0 and recording["channels"] == 1,++ "Intake sample count or mono channel evidence is invalid")++ require(artifact("intake/recording.f32").stat().st_size == 4 * count,++ "Decoded cache size does not match the intake sample count")++ require(math.isclose(recording["duration_s"], count / recording["sample_rate_hz"],++ rel_tol=1e-12, abs_tol=1e-12), "Intake duration does not match its sample count")++ require(intake.get("time_status") == ("ready" if wire.get("time_window") else "needs_input"),++ "Intake time status does not match the submitted clock")++ require(intake.get("decode", {}).get("sample_format") == "f32le", "Decoded cache format is unrecorded")++ report["stages_verified"].append("intake")++++ events = final.get("events")++ if scientific or events is not None:++ require(recording is not None, "Discovery has no completed intake evidence")++ discovery = read("discovery/discovery.json")++ require(discovery.get("source_sha256") == input_record["sha256"]++ and discovery.get("events") == events, "Discovery source or events differ from the terminal result")++ if not interrupted:++ require(provenance.get("discovered_events") == len(events), "Provenance has a different discovered-event count")++ chunks = discovery.get("chunks")++ require(isinstance(chunks, list) and chunks, "Discovery has no whole-recording chunk evidence")++ covered = 0.0++ tolerance = 1 / recording["sample_rate_hz"]++ for chunk in sorted(chunks, key=lambda item: item["start_s"]):++ start, duration = chunk["start_s"], chunk["duration_s"]++ require(all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)++ for v in (start, duration)) and start >= 0 and duration > 0,++ "Discovery chunk bounds are invalid")++ require(start <= covered + tolerance and start + duration <= recording["duration_s"] + tolerance,++ "Discovery chunk evidence has a gap or exceeds the recording")++ covered = max(covered, start + duration)++ require(covered >= recording["duration_s"] - tolerance, "Discovery did not cover the complete recording")++ report["stages_verified"].append("discovery")++++ if final.get("reason_code") == "recording_time_required":++ require(recording is not None and events is not None and not wire.get("time_window")++ and final["status"] == "needs_input" and final.get("required_fields") == ["time_window"],++ "Recording-time early exit contradicts its intake evidence")++ if final.get("reason_code") == "no_supported_events":++ require(recording is not None and events == [] and wire.get("time_window") is not None,++ "No-event early exit contradicts its discovery evidence")++++ if scientific:++ require(recording.get("time_window") is not None, "Scientific decision has no recording clock")++ acquisition = read("data-provenance.json")++ manifest, search = read("search/manifest.json"), read("search/search-report.json")++ configuration = manifest["configuration"]++ run_hash = hashlib.sha256(json.dumps(configuration, sort_keys=True, allow_nan=False).encode()).hexdigest()++ require(manifest.get("run_hash") == search.get("run_hash") == provenance.get("search_run_hash") == run_hash,++ "Search manifest, report, and automatic provenance have different run identities")++ require(configuration.get("code") == provenance.get("implementation_files"),++ "Search manifest identifies a different implementation")++ bounds = wire["search"].get("bounds_wsen", [-125.0, 24.0, -66.0, 50.0])++ require(configuration.get("bounds") == search.get("scope") == bounds,++ "Search scope differs from the submitted request")++ window = [utc_timestamp(wire["time_window"][key]).timestamp() for key in ("start_utc", "end_utc")]++ require(configuration.get("scoring", {}).get("recording_start_window_s") == window++ and search.get("scoring_time_is_locked") is True++ and search.get("ground_truth_used_by_search") is False,++ "Search does not preserve one truth-separated recording clock")++ indexes = acquisition.get("flight_indexes")++ require(isinstance(indexes, list) and indexes and isinstance(acquisition.get("terrain"), dict)++ and acquisition["terrain"], "Acquisition lacks flight-index or terrain evidence")++ require([index["input_hash"] for index in indexes] ==++ [index["input_hash"] for index in configuration["indexes"]] ==++ [item["input_hash"] for item in search["data_coverage"]],++ "Acquisition and search use different flight inputs")++ require([index["coverage"] for index in indexes] ==++ [item["source"] for item in search["data_coverage"]],++ "Acquisition and search disagree about flight coverage")++ require(all(item.get("requested_bounds") == bounds and item.get("requested_time_range_s") ==++ configuration.get("time_range_s") for item in search["data_coverage"]),++ "Flight-coverage receipts describe another search area or time interval")++ if "terrain_configuration" in acquisition["terrain"]:++ require(acquisition["terrain"] == configuration.get("additional_input_hashes"),++ "Acquisition and search use different terrain inputs")++ report["stages_verified"].append("acquisition")++++ total, completed = search["tiles_total"], search["tiles_completed"]++ require(type(total) is int and type(completed) is int and 0 <= completed <= total and total > 0,++ "Search tile counts are invalid")++ require(search.get("unsearched_tiles") == total - completed, "Search unsearched-tile count is inconsistent")++ work_complete = (completed == total and not search["tile_failures"] and not search.get("refinement_failure")++ and search["all_event_groups_considered"] is True and model_assessment_accounted_for(search))++ coverage = final["coverage"]++ require(coverage["search_complete"] == work_complete++ and coverage["data_status"] == ("available" if search["data_scope_complete"] else "partial")++ and coverage.get("requested_area") == wire["search"],++ "Terminal coverage differs from the search report")++ expected_complete = work_complete and search["data_scope_complete"] and search["all_event_groups_considered"]++ require(search["status"] == ("complete" if expected_complete else "partial"),++ "Search completion status contradicts its work and coverage evidence")++ prepared = configuration["events"]++ groups = [event.get("event_ids", [event["event_id"]]) for event in prepared]++ flattened = [event_id for group in groups for event_id in group]++ require(len(flattened) == len(set(flattened)) and set(flattened) == {event["event_id"] for event in events},++ "Search grouping omits or duplicates discovered events")++ require(search.get("event_groups_proposed") == len(groups), "Search reports a different event-group count")++ report["stages_verified"].append("search")++++ refinement = read("refined-candidates.json")++ candidates, rows = final.get("candidates"), refinement.get("ranked")++ require(isinstance(candidates, list) and isinstance(rows, list) and len(rows) == len(candidates),++ "Refinement and terminal candidate counts differ")++ pre_decision_candidates = []++ for row, candidate in zip(rows, candidates):++ require(all(row.get(key) == candidate[key] for key in ("lat", "lon", "score"))++ and row.get("score_kind", "negative_robust_ridge_loss_hz") == candidate["score_kind"],++ "Refinement and terminal candidate coordinates or scores differ")++ require(math.isclose(row["recording_start_time_s"], utc_timestamp(candidate["recording_start_utc"]).timestamp(),++ rel_tol=0, abs_tol=1e-6), "Refinement and terminal candidate clocks differ")++ indices = row.get("event_indices", list(range(len(groups))))++ require(isinstance(indices, list) and all(type(i) is int and 0 <= i < len(groups) for i in indices)++ and len(indices) == len(set(indices)) == len(row["flight_ids"]),++ "Refinement event-to-flight association is invalid")++ associated = [(event_id, flight) for i, flight in zip(indices, row["flight_ids"]) for event_id in groups[i]]++ require(associated == list(zip(candidate["event_ids"], candidate["flight_ids"])),++ "Refinement and terminal event-to-flight associations differ")++ sensitivity = row.get("sensitivity", {})++ uncertainty = ({key: sensitivity[key] for key in ("radius_m", "method", "kind")}++ if sensitivity.get("complete") and not sensitivity.get("boundary_limited") else None)++ original = dict(candidate)++ original.pop("uncertainty", None)++ if uncertainty is not None:++ original["uncertainty"] = uncertainty++ pre_decision_candidates.append(original)++ diagnostics = refinement["matching_diagnostics"]++ require(diagnostics.get("recording_start_window_s") == window++ and diagnostics.get("clock_locked") == search["scoring_time_is_locked"],++ "Refinement changed the shared recording clock")++ require(diagnostics.get("sensitivity") == (rows[0].get("sensitivity", {}) if rows else {}),++ "Leading matching diagnostics use another candidate's sensitivity")++ if rows:++ best = rows[0]++ selected = best.get("event_indices", list(range(len(groups))))++ fits = best.get("event_diagnostics", [])++ require(len(fits) == len(selected), "Leading refinement lacks per-event fit evidence")++ require(all(diagnostics.get(event_id) == fit for i, fit in zip(selected, fits) for event_id in groups[i]),++ "Matching diagnostics differ from the leading candidate's event fits")++ require(set(diagnostics.get("unmatched_event_ids", [])) ==++ {event["event_id"] for event in events} - set(candidates[0]["event_ids"]),++ "Matching diagnostics do not account for unmatched acoustic proposals")++ if "finite_search_evidence" in search:++ report["finite_search"] = inspect_finite_search(artifact, read, search, configuration, refinement)++ report["finite_search_verified"] = report["finite_search"]["complete"]++ else:++ require("finite_search_evidence" not in diagnostics, "Refinement invented finite-search evidence")++ report["stages_verified"].append("refinement")++++ decision = read("decision.json")++ require(all(decision.get(key) == final.get(key) for key in ("status", "reason_code", "message", "candidates")),++ "Persisted scientific decision differs from the terminal result")++ from dopplergeist import confidence++ require(sha256(confidence.__file__) == provenance["implementation_files"].get("confidence.py"),++ "Cannot recheck the decision with a different confidence implementation")++ expected = confidence.decide_location(events, pre_decision_candidates, coverage, matching_diagnostics=diagnostics)++ expected.setdefault("candidates", pre_decision_candidates)++ require(decision == expected,++ "Saved scientific evidence does not reproduce the persisted decision")++ report["stages_verified"].append("decision")++ report["full_pipeline_observed"] = True++ report["passed"] = True++ except Exception as exc:++ report["errors"].append(f"{type(exc).__name__}: {exc}")++ return report++++++def verify_http(audio, output, *, request=None, operator=None, expect_status,++ expect_reason=None, timeout_s=600.0, poll_interval_s=0.25):++ if expect_status not in TERMINAL:++ raise ValueError("Declare an expected terminal status before execution")++ for name, value in (("timeout_s", timeout_s), ("poll_interval_s", poll_interval_s)):++ if 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():++ raise ValueError("Supply a local MP3 file")++ wire = dict(validate_request(dict(request or {"schema_version": 1}, audio_path=str(audio))))++ wire.pop("audio_path")++ operator = {} if operator is None else operator++ if not isinstance(operator, dict):++ raise ValueError("Operator configuration must be a JSON object")++ output = Path(output).resolve()++ output.mkdir(parents=True, exist_ok=False)++ write_json(output / "upload-request.json", wire)++ write_json(output / "operator.json", operator)++ package = Path(dopplergeist.__file__).resolve().parent++ implementation = {path.name: sha256(path) for path in sorted(package.glob("*.py"))}++ began, process, final, log = time.monotonic(), None, None, None++ deadline = began + timeout_s++ receipt = {"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,++ "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,++ "full_pipeline_observed": False, "supported_decision": False,++ "location_accuracy_evaluated": False, "browser_verified": False,++ "interrupted": False, "interruption_signal": None,++ "limitations": ["HTTP verification does not establish location accuracy or browser behavior.",++ "Expected inconclusive or failed responses are preserved, not promoted to localization success.",++ "This verifier accepts no evaluation labels and performs no ground-truth comparison."],++ "service": {"shutdown_signal": None, "forced_kill": False, "returncode": None}}++ with TerminationGuard(receipt) as termination:++ try:++ termination.interruptible = True++ 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)]++ receipt["service"]["command"] = command++ env = dict(os.environ, PYTHONPATH=str(package.parent) + os.pathsep + os.environ.get("PYTHONPATH", ""),++ MPLBACKEND="Agg")++ log = (output / "service.log").open("wb")++ termination.interruptible = False++ process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=env, start_new_session=True)++ receipt["service"]["pid"] = process.pid++ termination.interruptible = True++ 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"))++ 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),++ "X-Filename": "input.mp3", "X-Dopplergeist-Request": json.dumps(wire)})++ write_json(output / "submission.json", {"http_status": code, "response": queued})++ if code != 202:++ raise RuntimeError(f"Upload returned HTTP {code}")++ validate_result(queued)++ job_id = queued["job_id"]++ 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)++ 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", [])))++ 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:++ raise ValueError("Artifact listing does not expose exactly one original MP3")++ code, _ = client.request("GET", f"/api/jobs/{job_id}/artifacts/input.mp3",++ destination=output / "downloaded-original.mp3")++ if code != 200 or sha256(output / "downloaded-original.mp3") != receipt["source_sha256"]:++ raise ValueError("Downloaded original differs from the submitted MP3")++ if client.get(f"/api/jobs/{job_id}/artifacts/result.json") != final:++ raise ValueError("Downloaded result artifact differs from the terminal HTTP result")++ 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++ and (expect_reason is None or final.get("reason_code") == expect_reason))++ except Exception as exc:++ receipt["error"] = f"{type(exc).__name__}: {exc}"++ receipt["timed_out"] = isinstance(exc, TimeoutError)++ finally:++ termination.interruptible = False++ try:++ stop_service(process, receipt, termination)++ except Exception as exc:++ receipt["shutdown_error"] = f"{type(exc).__name__}: {exc}"++ finally:++ if log is not None:++ log.close()++ try:++ if not receipt["interrupted"]:++ termination.interruptible = True++ termination.raise_if_interrupted()++ receipt["implementation_unchanged"] = implementation == {++ path.name: sha256(path) for path in sorted(package.glob("*.py"))}++ if final is not None:++ directory = output / "jobs" / final["job_id"]++ receipt["terminal_result_preserved_after_shutdown"] = json.loads((directory / "result.json").read_text()) == final++ evidence = inspect_pipeline_evidence(directory, final, wire, operator)++ termination.raise_if_interrupted()++ write_json(output / "pipeline-evidence.json", evidence)++ receipt["pipeline_evidence_passed"] = evidence["passed"]++ receipt["full_pipeline_observed"] = evidence["full_pipeline_observed"]++ receipt["pipeline_evidence_errors"] = evidence["errors"]++ files = {path.relative_to(directory).as_posix(): {"bytes": path.stat().st_size, "sha256": sha256(path)}++ for path in sorted(directory.rglob("*")) if path.is_file() and not path.is_symlink()}++ receipt["pipeline_evidence_preserved_after_inspection"] = all(++ files.get(name) == record for name, record in evidence["artifacts"].items())++ write_json(output / "job-manifest.json", {"job_id": final["job_id"], "files": files})++ verified = bool(receipt["http_checks_passed"] and receipt["pipeline_evidence_passed"]++ 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"])++ receipt["verification_passed"] = verified and bool(receipt.get("expectation_matched"))++ receipt["supported_decision"] = (verified and receipt["full_pipeline_observed"]++ and receipt.get("status") == "succeeded")++ except Exception as exc:++ receipt["finalization_error"] = f"{type(exc).__name__}: {exc}"++ termination.interruptible = False++ # The bounded cleanup attempt precedes this handler handoff. Signals handled++ # above are committed below; later signals use the caller's disposition.++ # In the CLI, a later default SIGTERM cannot yield a successful process exit.++ if receipt["interrupted"]:++ receipt.update(verification_passed=False, supported_decision=False,++ finalization_skipped_reason="verification_interrupted")++ receipt.setdefault("error", "VerificationInterrupted: HTTP verification interrupted by SIGTERM")++ receipt.update(finished_utc=now(), elapsed_s=time.monotonic() - began)++ write_json(output / "http-verification.json", receipt)++ return receipt++++++def main(argv=None):++ parser = argparse.ArgumentParser(description=__doc__)++ parser.add_argument("--audio", type=Path, required=True)++ parser.add_argument("--output", type=Path, required=True, help="New directory; existing evidence is never overwritten")++ parser.add_argument("--operator-config", type=Path)++ parser.add_argument("--start-utc")++ parser.add_argument("--end-utc")++ parser.add_argument("--time-source", default="Explicit verification recording-start window")++ parser.add_argument("--expect-status", choices=sorted(TERMINAL), required=True)++ parser.add_argument("--expect-reason")++ parser.add_argument("--timeout-s", type=float, default=600)++ 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:++ parser.error("--end-utc requires --start-utc")++ request = {"schema_version": 1, "search": {"coverage": "conus"}}++ if args.start_utc:++ request["time_window"] = {"start_utc": args.start_utc, "end_utc": args.end_utc or args.start_utc,++ "source": "user", "source_detail": args.time_source}++ try:++ operator = json.loads(args.operator_config.read_text()) if args.operator_config else {}++ 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)++ except (OSError, ValueError, TypeError) as exc:++ parser.error(str(exc))++ print(json.dumps({"report": str(args.output.resolve() / "http-verification.json"),++ "verification_passed": receipt["verification_passed"], "status": receipt.get("status"),++ "http_checks_passed": receipt["http_checks_passed"],++ "pipeline_evidence_passed": receipt["pipeline_evidence_passed"],++ "full_pipeline_observed": receipt["full_pipeline_observed"],++ "reason_code": receipt.get("reason_code"), "supported_decision": receipt["supported_decision"],++ "location_accuracy_evaluated": False, "interrupted": receipt["interrupted"],++ "interruption_signal": receipt["interruption_signal"], "error": receipt.get("error")}))++ return 0 if receipt["verification_passed"] else 1++++++if __name__ == "__main__":++ raise SystemExit(main())diff --cc src/dopplergeist/automatic.pyindex 0000000,dd2d109..81e0c4dmode 000000,100644..100644--- a/src/dopplergeist/automatic.py+++ b/src/dopplergeist/automatic.py@@@ -1,0 -1,350 +1,403 @@@+ """Automatic stage orchestration; scientific producers own their algorithms."""+ from copy import deepcopy+ from datetime import datetime, timezone+ import hashlib+ import json+ import math+ from pathlib import Path+ import time++ from .contracts import utc_timestamp, validate_candidate, validate_event, validate_request+ from .jobs import write_json+++ def _digest(path):+ with Path(path).open("rb") as source:+ return hashlib.file_digest(source, "sha256").hexdigest()+++ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: None):+ request = validate_request(request)+ config = config or {}+ output = Path(output_dir)+ output.mkdir(parents=True, exist_ok=True)+ if (output / "provenance.json").exists():+ 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"}+ 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"]}}++ def finish(status, reason_code=None, message=None, **fields):+ provenance["elapsed_s"] = time.monotonic() - began+ provenance["status"] = status+ provenance["coverage"] = fields.get("coverage", state["coverage"])+ write_json(output / "provenance.json", provenance)+ artifacts = {"provenance": "provenance.json", "request": "request.json"}+ for name, path in (("intake", "intake/intake.json"), ("recording", "intake/recording.json"),+ ("discovery", "discovery/discovery.json"), ("discovery_plot", "discovery/discovery.png"),+ ("search_report", "search/search-report.json"), ("refinement", "refined-candidates.json"), ("data_provenance", "data-provenance.json"), ("decision", "decision.json")):+ if (output / path).is_file():+ artifacts[name] = path+ for path in sorted((output / "discovery").glob("event-*.png")):+ artifacts[path.stem] = path.relative_to(output).as_posix()+ value = dict(state, status=status, stage="complete", progress=1, artifacts=artifacts, **fields)+ if reason_code:+ value.update(reason_code=reason_code, message=message)+ return value++ try:+ from .intake import AudioIntakeError, intake_recording+ from .discovery import DiscoverySettings, discover_events+ except ImportError as exc:+ return finish("failed", "component_unavailable", f"Automatic audio components are not installed: {exc}")+ discovery_options = config.get("discovery", {})+ if not isinstance(discovery_options, dict) or discovery_options.keys() - {"chunk_s", "overlap_s"}:+ return finish("failed", "invalid_configuration", "Operator discovery settings support only chunk_s and overlap_s.")+ try:+ discovery_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))+ 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"] = events+ provenance["discovered_events"] = len(events)+ if recording.time_status == "needs_input":+ return finish("needs_input", "recording_time_required", "Supply a defensible UTC window for the start of this recording. File creation and upload times are not recording clocks.", required_fields=["time_window"])+ if not events:+ return finish("inconclusive", "no_supported_events", "No supported moving-tone Doppler events were discovered in the recording.")+ progress("acquisition", 0.35, **state)+ try:+ from .data_access import DataUnavailable+ search, prepared_events, measurements, indexes, terrain = _search(request, recording, events, output, config, lambda: progress("search", 0.55, **state))+ except ImportError as exc:+ return finish("failed", "component_unavailable", f"Automatic matching/data components are not installed: {exc}")+ except MissingData as exc:+ state["coverage"]["limitations"].append(str(exc))+ return finish("inconclusive", "data_unavailable", str(exc))+ except DataUnavailable as exc:+ state["coverage"]["limitations"].append(str(exc))+ return finish("failed", "data_unavailable", str(exc))+ state["coverage"] = _coverage(request, search, config)+ provenance["search_run_hash"] = search.get("run_hash")+ progress("refinement", 0.85, **state)+ return _decide(search, events, prepared_events, measurements, indexes, terrain, state, output, config, finish, lambda: progress("decision", 0.95, **state))+++ class MissingData(ValueError):+ pass+++ def _search(request, recording, events, output, config, search_progress):+ from .data_access import CONUS, FlightIndex, acquire_inputs+ from .matching import prepare_events+ from .terrain import Terrain+ from .tiled_search import SearchBudget, search_national+ c = float(config.get("sound_speed_mps", 343.0))+ max_distance = float(config.get("max_distance_m", 20000.0))+ prepared, measurements = prepare_events(events, c=c, max_distance_m=max_distance)+ window = recording.metadata["time_window"]+ lo, hi = (utc_timestamp(window[name]).timestamp() for name in ("start_utc", "end_utc"))+ if not config.get("flight_indexes") and not config.get("cache_root"):+ raise MissingData("Historical flight/terrain data are not configured. The operator must provide cache_root or prebuilt flight indexes with a terrain model.")+ first_day = datetime.fromtimestamp(lo-max_distance/300-30, timezone.utc).date()+ last_day = datetime.fromtimestamp(hi+recording.metadata["duration_s"]+30, timezone.utc).date()+ acquisition_days = (last_day-first_day).days+1+ if not config.get("flight_indexes") and acquisition_days > config.get("max_acquisition_days", 3):+ raise MissingData("Recording time window exceeds the configured historical-data acquisition budget. Supply a narrower defensible window.")+ ground = config.get("terrain", {})+ hashes = {"terrain_configuration": ground}+ if ground.get("rasters") or "constant_m" in ground:+ # Explicit offline/test terrain override; normal provider acquisition stays+ # in the data owner's adapter. Never infer flight coverage from this model.+ if not config.get("flight_indexes"):+ raise MissingData("A declared local terrain model requires prebuilt flight indexes.")+ indexes = [FlightIndex(path) for path in config["flight_indexes"]]+ terrain = Terrain(ground.get("rasters", []), ground.get("constant_m"), ground.get("geoid_raster"))+ time_range = (lo-max_distance/300-30, hi+recording.metadata["duration_s"]+30)+ bounds = request["search"].get("bounds_wsen", CONUS)+ hashes["terrain_rasters"] = {str(path): _digest(path) for path in ground.get("rasters", [])}+ else:+ bundle = acquire_inputs(request, recording.metadata, cache_root=config.get("cache_root", output / "cache"),+ index_paths=config.get("flight_indexes"), offline=config.get("offline", True),+ terrain_options=ground, max_sound_range_m=max_distance)+ indexes, terrain, time_range, bounds = bundle.indexes, bundle.terrain, bundle.time_range_s, bundle.bounds+ if ground.get("geoid_raster"):+ hashes["geoid_sha256"] = _digest(ground["geoid_raster"])+ search_progress()+ # A supplied interval is never collapsed to its midpoint. Every event/tile+ # uses the same recording-start clock and globally comparable score units.+ scoring = {"mode": "robust_ridge", "c": c, "time_origin": lo if lo == hi else None,+ "time_sweep_s": 0 if lo == hi else 5, "time_step_s": 0.5,+ "recording_start_window_s": [lo, hi]}+ filters = {"association": "subsets", **config.get("filters", {})}+ filters.setdefault("max_events", len(prepared))+ report = search_national(indexes, terrain, prepared, measurements, time_range_s=time_range, output_dir=output / "search",+ bounds=bounds, budget=SearchBudget(**config.get("search_budget", {})),+ scoring=scoring, filters=filters, input_hashes=hashes)+ write_json(output / "data-provenance.json", {"flight_indexes": [index.report for index in indexes],+ "terrain": terrain.provenance() if hasattr(terrain, "provenance") else hashes})+ return report, prepared, measurements, indexes, terrain++++def _bounded_model_assessment(search, support):++ """Validate accounting of missing fits without claiming full model support.++++ The confidence decision still compares the certified upper score bound with++ the winner. This only distinguishes bounded finite trials from omitted work.++ """++ if (search.get("model_support_complete") is not False++ or search.get("model_assessment_complete") is not True++ or search.get("status") != "complete" or not isinstance(support, dict)):++ return False++ names = ("unsupported_cpa_track_evaluations", "unclassified_score_candidates", "unknown_trials",++ "unreported_trial_envelopes", "bounded_score_candidates", "unbounded_score_candidates")++ if not all(type(support.get(name)) is int and support[name] >= 0 for name in names):++ return False++ bounded = support["bounded_score_candidates"]++ if (bounded == 0 or bounded != support["unclassified_score_candidates"]++ or support["unknown_trials"] < bounded or support["unsupported_cpa_track_evaluations"]++ or support["unreported_trial_envelopes"] or support["unbounded_score_candidates"]):++ return False++ finite = search.get("finite_search_evidence")++ if (not isinstance(finite, dict) or type(finite.get("schema_version")) is not int++ or finite["schema_version"] != 1 or finite.get("scope") != "evaluated_finite_grid"++ or finite.get("score_kind") != "matched_group_support_minus_normalized_residual"++ or finite.get("complete") is not True or finite.get("pruning_accounted_for") is not True):++ return False++ counts = ("bounded_unknown_envelopes", "bounded_unknown_rejections", "discarded_count",++ "max_event_groups", "unclassified_score_candidates", "unsupported_cpa_track_evaluations")++ if not all(type(finite.get(name)) is int and finite[name] >= 0 for name in counts):++ return False++ if (finite["bounded_unknown_envelopes"] != bounded++ or finite["unclassified_score_candidates"] != bounded++ or finite["bounded_unknown_rejections"] > bounded++ or finite["unsupported_cpa_track_evaluations"] != 0 or finite["max_event_groups"] < 1):++ return False++ possible = bounded - finite["bounded_unknown_rejections"]++ upper = finite.get("best_unknown_score_upper_bound")++ discarded = finite["discarded_count"]++ overall = finite.get("best_discarded_score")++ number = lambda value: type(value) in (int, float) and math.isfinite(value)++ if discarded < possible or (discarded and not number(overall)) or (not discarded and overall is not None):++ return False++ if possible:++ return (number(upper) and 0 <= upper <= finite["max_event_groups"]++ and overall >= upper)++ return upper is None+++++ def _coverage(request, search, config):+ limitations = ["Historical receiver archives may omit aircraft or trajectory samples."]+ search_complete = (search.get("tiles_total", 0) > 0 and search.get("tiles_completed") == search.get("tiles_total")+ and not search.get("tile_failures") and not search.get("refinement_failure")+ and search.get("all_event_groups_considered") is not False)- if "model_support_complete" in search or "model_support" in search:++ if any(name in search for name in ("model_support_complete", "model_support", "model_assessment_complete")):+ support = search.get("model_support")+ count_names = ("unsupported_cpa_track_evaluations", "unclassified_score_candidates",+ "evaluated_trials", "rejected_trials", "unknown_trials")+ valid_counts = (isinstance(support, dict) and+ all(type(support.get(name)) is int and support[name] >= 0 for name in count_names))+ model_complete = (search.get("model_support_complete") is True and valid_counts and+ all(support[name] == 0 for name in (count_names[0], count_names[1], "unknown_trials")))- if not model_complete:++ if "model_assessment_complete" in search and search["model_assessment_complete"] is not True:++ model_complete = False++ bounded_assessment = valid_counts and _bounded_model_assessment(search, support)++ if not model_complete and not bounded_assessment:+ search_complete = False+ limitations.append("Trajectory model assessment is incomplete; unsupported competitors remain unassessed. See the search support diagnostics.")++ elif bounded_assessment:++ limitations.append("Some finite acoustic trials lack full trajectory support. Their certified score bounds or rejections are accounted for; the decision still checks whether any bound could compete with the leading location.")++ if not model_complete:+ if valid_counts:+ limitations.append(f"Unsupported CPA track evaluations: {support[count_names[0]]}; unclassified score candidates: {support[count_names[1]]}; unknown clock trials: {support['unknown_trials']}. Counts describe work evaluations, not distinct aircraft.")+ else:+ limitations.append("Trajectory model support counts are unavailable or malformed; missing work is not treated as zero.")+ if not search_complete:+ limitations.append("The search did not assess the complete requested scope within its work or physical model limits.")+ if search.get("all_event_groups_considered") is False:+ limitations.append(search.get("event_limit_reason") or "Not every proposed flyover group was considered within the configured budget.")+ if "constant_m" in config.get("terrain", {}):+ limitations.append("A constant terrain model was supplied; real terrain and altitude-datum accuracy are not established.")+ finite = search.get("finite_search_evidence")+ if finite is not None:+ descriptions = finite.get("limitations") if isinstance(finite, dict) else None+ if isinstance(descriptions, list) and descriptions and all(isinstance(item, str) for item in descriptions):+ limitations.extend(descriptions)+ else:+ limitations.append("Only evaluated grid points and bounded refinements are covered; continuous-space uniqueness is not established.")+ elif search.get("alternative_modes_exhaustively_assessed") is not True:+ limitations.append("Candidate retention is bounded; exhaustive alternative-location assessment is not established.")+ missing = [str(item) for item in search.get("tile_failures", [])]+ if not search.get("data_scope_complete"):+ missing.append("historical_flight_scope_or_audible_border_region")+ limitations.append("Flight inputs do not establish complete coverage of the required emission-time interval and audible border region.")+ return {"search_complete": search_complete, "data_status": "available" if search.get("data_scope_complete") else "partial",+ "limitations": limitations, "requested_area": request["search"], "missing_data": missing}+++ def _comparable_refinement(candidate, original, prepared_events):+ """Preserve newer normalized results; adapt only older raw-loss producers."""+ if (original.get("score_kind") == "matched_group_support_minus_normalized_residual"+ and candidate.get("score_kind") != "matched_group_support_minus_normalized_residual"):+ from .matching import association_score+ chosen = [prepared_events[i] for i in original["event_indices"]]+ candidate = association_score(candidate, chosen)+ if not math.isfinite(candidate["score"]):+ raise ValueError("Refinement no longer supports the matched event association")+ if "mode_id" in original:+ candidate = dict(candidate, mode_id=original["mode_id"])+ return candidate+++ def _decide(search, events, prepared_events, measurements, indexes, terrain, state, output, config, finish, decision_progress):+ # The confidence producer supplies this adapter; missing decision machinery+ # can never turn the highest raw score into a supported location.+ from .confidence import decide_location+ from .matching import profile_candidate, refine_candidate+ raw = list(search.get("ranked", []))+ refined, refinement_failures = [], []+ window = state["recording"]["time_window"]+ start_window = tuple(utc_timestamp(window[key]).timestamp() for key in ("start_utc", "end_utc"))+ finite = search.get("finite_search_evidence")+ assessed_ids = set()+ producer_ids = search.get("core_assessed_mode_ids")+ valid_core_mapping = (isinstance(producer_ids, list)+ and all(isinstance(identity, str) and identity for identity in producer_ids))+ if isinstance(finite, dict) and valid_core_mapping:+ producer_ids = set(producer_ids)+ for row in raw:+ identity = row.get("mode_id")+ groups = row.get("event_indices", range(len(prepared_events)))+ core = row.get("event_diagnostics", [])+ if (isinstance(identity, str) and identity in producer_ids and row.get("score_kind") == finite.get("score_kind")+ and math.isfinite(row["score"]) and start_window[0] <= row["recording_start_time_s"] <= start_window[1]+ and len(groups) == len(row["flight_ids"]) == len(core) and len(core) > 0+ and all(isinstance(fit, dict) and fit.get("support_fraction") == 1.+ and not isinstance(fit.get("support_fraction"), bool)+ and isinstance(fit.get("score"), (int, float)) and not isinstance(fit["score"], bool)+ and math.isfinite(fit["score"]) for fit in core)):+ assessed_ids.add(identity)+ # Refine global competing approaches with their original whole trajectories.+ # The index iterator is bounded by the same local acoustic support envelope.+ def mode_key(row):+ return (tuple(row.get("event_indices", range(len(prepared_events)))), tuple(row["flight_ids"]),+ tuple(row.get("pass_emission_times_s", [])), row["lat"], row["lon"], row["recording_start_time_s"],+ row.get("elev_m"), row.get("mode_id"))++ retained_keys = {mode_key(row) for row in raw}+ refined_keys = set()+ seen, track_sets = set(), {}+ best_refined_score = -math.inf+ for row in raw:+ key = mode_key(row)+ if key in seen:+ continue+ seen.add(key)+ if len(seen) > config.get("refine_finalists", 5):+ break+ try:+ max_range = float(config.get("max_distance_m", 20000.0))+ margin = max_range / 60000.0 + 0.3+ bounds = (row["lon"]-margin, row["lat"]-margin, row["lon"]+margin, row["lat"]+margin)+ needed = set(row["flight_ids"])+ tracks = {}+ lo = start_window[0] + min(e["start_s"] for e in prepared_events) - max_range / 300 - 120+ hi = start_window[1] + max(e["end_s"] for e in prepared_events) + 120+ for index in indexes:+ for track in index.query(bounds, (lo, hi)):+ if track.id in needed:+ tracks[track.id] = track+ sample_limit = config.get("search_budget", {}).get("max_track_samples_per_tile", 500000)+ if sum(len(item.time) for item in tracks.values()) > sample_limit:+ raise ValueError("Refinement trajectory sample budget exceeded")+ if needed - tracks.keys():+ raise ValueError("Candidate flight segments are unavailable for refinement")+ row = dict(row, altitude_basis={flight: sorted(set(getattr(track, "altitude_basis", ["unspecified"]))) for flight, track in tracks.items()})+ candidate = refine_candidate(row, tracks, prepared_events, measurements, terrain,+ radius_m=config.get("refine_radius_m", 500.0),+ recording_start_window_s=start_window, c=config.get("sound_speed_mps", 343.0))+ candidate = _comparable_refinement(candidate, row, prepared_events)+ refined.append(candidate)+ refined_keys.add(key)+ if candidate["score"] > best_refined_score:+ best_refined_score = candidate["score"]+ track_sets = {mode_key(candidate): tracks}+ except (ValueError, KeyError) as exc:+ refinement_failures.append(str(exc))+ raw.extend(refined)+ order = lambda row: (row["score"], bool(row.get("sensitivity", {}).get("complete")), len(row.get("sensitivity", {}).get("sources", [])))+ raw.sort(key=order, reverse=True)+ if raw and mode_key(raw[0]) in track_sets:+ leading = raw[0]+ try:+ profiled = profile_candidate(leading, track_sets[mode_key(leading)], prepared_events, measurements, terrain,+ radius_m=config.get("refine_radius_m", 500.0), recording_start_window_s=start_window,+ c=config.get("sound_speed_mps", 343.0))+ # Full profiling updates this exact hypothesis. Its earlier, limited+ # envelope must not compete with incomplete evidence or score roundoff.+ raw[0] = _comparable_refinement(profiled, leading, prepared_events)+ except (ValueError, KeyError) as exc:+ refinement_failures.append(f"Sensitivity profiling: {exc}")+ raw[0] = dict(leading, sensitivity={"complete": False, "sources": [],+ "failures": [{"source": "profiling", "reason": str(exc)}]})+ # Preserve other modes; a different leader must satisfy its own full+ # sensitivity gate, without borrowing this hypothesis's profile.+ raw.sort(key=order, reverse=True)+ candidates, rows = [], []+ for row in raw:+ event_ids, flight_ids = [], []+ selected_events = [prepared_events[i] for i in row.get("event_indices", range(len(prepared_events)))]+ for event, flight in zip(selected_events, row["flight_ids"]):+ ids = event.get("event_ids", [event["event_id"]])+ event_ids.extend(ids)+ flight_ids.extend([flight]*len(ids))+ candidate = {"lat": float(row["lat"]), "lon": float(row["lon"]), "score": float(row["score"]),+ "score_kind": row.get("score_kind", "negative_robust_ridge_loss_hz"), "event_ids": event_ids,+ "flight_ids": flight_ids, "recording_start_utc": datetime.fromtimestamp(row["recording_start_time_s"], timezone.utc).isoformat().replace("+00:00", "Z")}+ sensitivity = row.get("sensitivity")+ if sensitivity and sensitivity.get("complete") and not sensitivity.get("boundary_limited"):+ candidate["uncertainty"] = {key: sensitivity[key] for key in ("radius_m", "method", "kind")}+ candidates.append(validate_candidate(candidate))+ rows.append(row)+ best = rows[0] if rows else {}+ original_ids = {event["event_id"]: event.get("event_ids", [event["event_id"]]) for event in prepared_events}+ unmatched_groups = best.get("unmatched_event_ids", list(original_ids) if not rows else [])+ unmatched_ids = [event_id for group in unmatched_groups for event_id in original_ids.get(group, [group])]+ diagnostics = {"recording_start_window_s": list(start_window), "unmatched_event_ids": unmatched_ids, "clock_locked": search.get("scoring_time_is_locked", False), "refinement_failures": refinement_failures,+ "refinement_boundary_limited": best.get("sensitivity", {}).get("boundary_limited", True),+ "sensitivity": best.get("sensitivity", {}),+ "altitude_basis": best.get("altitude_basis", {}),+ "retained_hypotheses": len(retained_keys), "refined_hypotheses": len(refined_keys),+ "unrefined_hypotheses": len(retained_keys-refined_keys),+ "alternatives_evaluated": search.get("alternative_modes_exhaustively_assessed") is True and search.get("status") == "complete" and not refinement_failures and not retained_keys-refined_keys}+ matched_events = [prepared_events[i] for i in best.get("event_indices", range(len(prepared_events)))]+ for event, evidence in zip(matched_events, best.get("event_diagnostics", [])):+ for event_id in event.get("event_ids", [event["event_id"]]):+ diagnostics[event_id] = evidence+ if finite is not None:+ diagnostics["finite_search_evidence"] = deepcopy(finite)+ diagnostics["core_assessment_mapping_status"] = "present" if valid_core_mapping else "missing_or_invalid"+ diagnostics["assessed_mode_ids"] = sorted(assessed_ids)+ diagnostics["candidate_mode_ids"] = [row.get("mode_id") for row in rows]+ write_json(output / "refined-candidates.json", {"ranked": rows, "matching_diagnostics": diagnostics})+ decision_progress()+ decision = decide_location(events, candidates, state["coverage"], matching_diagnostics=diagnostics)+ decision.setdefault("candidates", candidates)++ write_json(output / "decision.json", decision)+ fields = {key: value for key, value in decision.items() if key not in {"schema_version", "job_id", "status", "stage", "progress", "artifacts", "recording", "events", "diagnostics"}}+ status = decision["status"]+ reason = fields.pop("reason_code", None)+ message = fields.pop("message", None)+ return finish(status, reason, message, **fields)diff --cc src/dopplergeist/finite_search.pyindex f4df1da,673feef..f2ad625--- a/src/dopplergeist/finite_search.py+++ b/src/dopplergeist/finite_search.py@@@ -37,8 -37,15 +37,48 @@@ def classified_assessment(row)and all(type(assessment.get(k)) is int and assessment[k] >= 0for k in ("evaluated_trials", "rejected_trials", "unknown_trials"))and assessment["unknown_trials"] == 0)+ if not valid:+ return False+ # No trials is unknown work. A finite best needs an evaluated trial; a+ # wholly rejected envelope cannot have discarded an evaluated finite best.+ score = row.get("score", math.nan)+ return (assessment["evaluated_trials"] > 0 if math.isfinite(score) else+ score == -math.inf and assessment["evaluated_trials"] == 0 and assessment["rejected_trials"] > 0)++++def bounded_assessment(row):++ """Validate a score ceiling without calling missing support a core fit."""++ assessment = row.get("scoring_assessment")++ kind = "matched_group_support_minus_normalized_residual"++ indices = row.get("event_indices")++ if (not isinstance(assessment, dict) or assessment.get("complete") is not False++ or assessment.get("unknown_score_bound_kind") != kind++ or row.get("score_kind") != kind++ or assessment.get("unknown_score_bound_method") != "nonnegative_loss_and_validated_event_fits"++ or not isinstance(indices, list) or not indices++ or any(type(i) is not int or i < 0 for i in indices) or indices != sorted(set(indices))++ or len(row.get("flight_ids", [])) != len(indices)):++ return False++ fields = ("evaluated_trials", "rejected_trials", "unknown_trials",++ "bounded_unknown_trials", "bounded_unknown_rejections")++ if not all(type(assessment.get(k)) is int and assessment[k] >= 0 for k in fields):++ return False++ scheduled = assessment.get("scheduled_trials")++ if (type(scheduled) is not int or scheduled <= 0++ or assessment.get("trial_count_semantics") != "disjoint_evaluated_rejected_unknown"++ or assessment.get("empty_clock_domain") is not False++ or scheduled != sum(assessment[k] for k in fields[:3])):++ return False++ unknown, bounded, rejected = (assessment[k] for k in fields[2:])++ if not 0 < unknown == bounded or rejected > bounded:++ return False++ upper = assessment.get("unknown_score_upper_bound")++ if rejected == bounded:++ return upper is None++ return (isinstance(upper, (int, float)) and not isinstance(upper, bool)++ and math.isfinite(upper) and 0 <= upper <= len(indices))++class RetentionLedger:"""One immutable-input run; bounded per-stage writes and streaming audits.@@@ -59,6 -66,6 +99,9 @@@CREATE TABLE IF NOT EXISTS records(stage TEXT, mode_id TEXT, score REAL,groups_count INTEGER, kind TEXT, seed TEXT, PRIMARY KEY(stage,mode_id));CREATE INDEX IF NOT EXISTS mode_index ON records(mode_id);++ CREATE TABLE IF NOT EXISTS bounds(stage TEXT, bound_id TEXT, upper_score REAL,++ groups_count INTEGER, detail TEXT, PRIMARY KEY(stage,bound_id));++ CREATE INDEX IF NOT EXISTS bound_index ON bounds(bound_id);""")if db.execute("PRAGMA quick_check").fetchone()[0] != "ok":raise DataUnavailable("Corrupt finite retention ledger")@@@ -82,16 -89,16 +125,19 @@@db.close()@staticmethod-- def _checksum(records, kept, occurrences, duplicates):++ def _checksum(records, kept, occurrences, duplicates, bounds=()):digest = hashlib.sha256()for record in records:digest.update(json.dumps(record, separators=(",", ":"), allow_nan=False).encode())digest.update(b"\n")digest.update(json.dumps(sorted(kept), separators=(",", ":")).encode())digest.update(json.dumps([occurrences, duplicates]).encode())++ for bound in bounds:++ digest.update(json.dumps(bound, separators=(",", ":"), allow_nan=False).encode())++ digest.update(b"\n")return digest.hexdigest()-- def record(self, stage, rows, kept, occurrences):++ def record(self, stage, rows, kept, occurrences, *, bounds=()):records = []for row in rows:identifier = identify_mode(row)@@@ -101,11 -108,11 +147,25 @@@records.append((identifier, float(row["score"]), len(row["mode_seed"]["event_indices"]), kind,json.dumps(row["mode_seed"], sort_keys=True, separators=(",", ":"))))records.sort()++ bound_records = []++ for bound in bounds:++ detail = bound["detail"]++ if (self.score_kind != "matched_group_support_minus_normalized_residual"++ or not bounded_assessment(detail)++ or bound["groups_count"] != len(detail["event_indices"])++ or bound["upper_score"] != detail["scoring_assessment"]["unknown_score_upper_bound"]++ or bound["bound_id"] != "bound-" + content_hash(detail)):++ raise DataUnavailable("Invalid finite association-score bound")++ bound_records.append((bound["bound_id"], bound["upper_score"], bound["groups_count"],++ json.dumps(detail, sort_keys=True, separators=(",", ":"))))++ bound_records.sort()kept_ids = [identify_mode(row) for row in kept]-- checksum = self._checksum(records, kept_ids, occurrences, occurrences-len(records))++ checksum = self._checksum(records, kept_ids, occurrences, occurrences-len(records), bound_records)with self.connect() as db:db.execute("DELETE FROM records WHERE stage=?", (stage,))++ db.execute("DELETE FROM bounds WHERE stage=?", (stage,))db.executemany("INSERT INTO records VALUES(?,?,?,?,?,?)", [(stage, *r) for r in records])++ db.executemany("INSERT INTO bounds VALUES(?,?,?,?,?)", [(stage, *r) for r in bound_records])db.execute("INSERT OR REPLACE INTO stages VALUES(?,?,?,?,?)",(stage, checksum, occurrences, occurrences-len(records), json.dumps(sorted(kept_ids))))return checksum@@@ -122,7 -129,7 +182,8 @@@if record is None or record[0] != expected:return Falserows = db.execute("SELECT mode_id,score,groups_count,kind,seed FROM records WHERE stage=? ORDER BY mode_id", (stage,))-- return self._checksum(rows, json.loads(record[1]), record[2], record[3]) == expected++ bounds = db.execute("SELECT bound_id,upper_score,groups_count,detail FROM bounds WHERE stage=? ORDER BY bound_id", (stage,))++ return self._checksum(rows, json.loads(record[1]), record[2], record[3], bounds) == expectedexcept (sqlite3.DatabaseError, ValueError, TypeError) as error:raise DataUnavailable("Corrupt finite retention stage") from error@@@ -149,6 -156,6 +210,11 @@@evaluated = db.execute(f"SELECT count(*) FROM ({distinct})").fetchone()[0]original = {mode_id: score for mode_id, score in db.execute(f"SELECT mode_id,score FROM ({distinct}) WHERE mode_id IN (SELECT id FROM retained_ids)")}++ bounded_count, bounded_rejections, bounded_max = db.execute(++ "SELECT count(*),coalesce(sum(upper_score IS NULL),0),max(upper_score) FROM bounds").fetchone()++ discarded += bounded_count - bounded_rejections++ if bounded_max is not None:++ bound = bounded_max if bound is None else max(bound, bounded_max)if set(original) != set(ids):accounted = Falseif expected_stages is not None:@@@ -157,6 -164,6 +223,7 @@@accounted = Falseif not accounted:discarded, bound, evaluated, original = None, None, None, {}++ bounded_count, bounded_rejections, bounded_max = None, None, Nonereturn {"schema_version": 1, "scope": "evaluated_finite_grid", "complete": bool(complete and accounted),"score_kind": self.score_kind, "spacing_m": float(spacing_m), "refine_spacing_m": float(refine_spacing_m),"max_event_groups": max_event_groups,@@@ -164,7 -171,7 +231,11 @@@"event_groups": len(row["mode_seed"]["event_indices"])} for row in retained],"discarded_count": discarded, "best_discarded_score": bound, "pruning_accounted_for": accounted,"evaluated_modes": evaluated,++ "bounded_unknown_envelopes": bounded_count,++ "bounded_unknown_rejections": bounded_rejections,++ "best_unknown_score_upper_bound": bounded_max,"stages": totals,"limitations": ["Evaluated grids and recorded refinements only; continuous-space uniqueness is not established.",++ "Unknown association trials remain unknown; their persisted score ceilings join the discarded-alternative bound.","Unvisited positions and unperformed refinements have no inferred score bound.","Proposal envelopes, CPA tolerances, grouping, clock bounds and physical model are declared assumptions."]}diff --cc src/dopplergeist/search.pyindex 228ae12,30c2b46..6dcb790--- a/src/dopplergeist/search.py+++ b/src/dopplergeist/search.py@@@ -214,6 -216,6 +216,124 @@@ def event_score(track, observer, spectrreturn float(scores[best]),float(frequencies[best])++def _ridge_trial_classification(result, events, association):++ """Classify recorded core fits, without changing their score or rejection rule.++++ Missing support and numerical failures are unknown. A supported finite fit++ can be rejected only by the existing association residual thresholds.++ """++ def finite(value):++ return (isinstance(value, (int, float, np.integer, np.floating))++ and not isinstance(value, (bool, np.bool_)) and np.isfinite(value))++++ diagnostics = result.get("event_diagnostics")++ scores, frequencies = result.get("event_scores"), result.get("f0_hz")++ if (not isinstance(diagnostics, list) or not isinstance(scores, list) or not isinstance(frequencies, list)++ or not len(diagnostics) == len(scores) == len(frequencies) == len(events)):++ return "unknown", "missing_event_fit_evidence"++ fields = ("score", "f0_hz", "source_drift_hz", "source_drift_hz_s",++ "source_reference_emission_time_s", "source_span_s", "drift_bound_hz", "rmse_hz", "outlier_fraction")++ for diagnostic, score, frequency, event in zip(diagnostics, scores, frequencies, events):++ if (not isinstance(diagnostic, dict) or not finite(diagnostic.get("support_fraction"))++ or diagnostic["support_fraction"] != 1.0):++ return "unknown", "incomplete_acoustic_support"++ if (not all(finite(diagnostic.get(name)) for name in fields)++ or not finite(score) or not finite(frequency)):++ return "unknown", "nonfinite_fit_evidence"++ count, independent = diagnostic.get("sample_count"), diagnostic.get("independent_sample_count")++ if (type(count) is not int or type(independent) is not int or not 1 <= independent <= count++ or count < 10 or diagnostic["source_span_s"] <= 0 or diagnostic["drift_bound_hz"] < 0++ or diagnostic["rmse_hz"] < 0 or not 0 <= diagnostic["outlier_fraction"] <= 1++ or diagnostic["f0_hz"] <= 0 or diagnostic["score"] > 0):++ return "unknown", "invalid_fit_evidence"++ if "optimizer_success" in diagnostic and diagnostic["optimizer_success"] is not True:++ return "unknown", "failed_optimizer"++ if score != diagnostic["score"] or frequency != diagnostic["f0_hz"]:++ return "unknown", "inconsistent_event_fit_evidence"++ bounds = event.get("f0_range_hz")++ fraction = event.get("quality", {}).get("source_drift_fraction", 0.02)++ if (not isinstance(bounds, (list, tuple)) or len(bounds) != 2++ or not all(finite(value) for value in bounds) or not 0 < bounds[0] <= bounds[1]++ or not bounds[0] <= frequency <= bounds[1]++ or not finite(fraction) or not 0 <= fraction <= 0.1):++ return "unknown", "fit_outside_declared_frequency_domain"++ drift, cap = diagnostic["source_drift_hz"], diagnostic["drift_bound_hz"]++ if not bounds[0] * fraction <= cap <= bounds[1] * fraction or abs(drift) > cap:++ return "unknown", "fit_outside_declared_drift_domain"++ if not np.isclose(diagnostic["source_drift_hz_s"] * diagnostic["source_span_s"], drift,++ rtol=1e-12, atol=1e-12):++ return "unknown", "inconsistent_source_drift"++ if "optimizer_success" in result and result["optimizer_success"] is not True:++ return "unknown", "failed_optimizer"++ residual = float(sum(scores))++ if not finite(residual):++ return "unknown", "nonfinite_residual_score"++ if not association:++ if (result.get("score_kind") == "negative_robust_ridge_loss_hz"++ and finite(result.get("score")) and result["score"] == residual):++ return "evaluated", None++ return "unknown", "inconsistent_residual_score"++ from .matching import _frequency_scale++ limits = [3 * _frequency_scale(event) for event in events]++ if (result.get("score_kind") != "matched_group_support_minus_normalized_residual"++ or not finite(result.get("residual_score")) or result["residual_score"] != residual++ or not all(finite(v) and v > 0 for v in limits)):++ return "unknown", "inconsistent_association_evidence"++ supported = all(-score <= limit for score, limit in zip(scores, limits))++ if supported:++ expected = float(sum(1 - (-score) / limit for score, limit in zip(scores, limits)))++ if finite(result.get("score")) and result["score"] == expected:++ return "evaluated", None++ elif result.get("score") == -np.inf:++ return "rejected", "association_residual_limit"++ return "unknown", "unexplained_association_score"++++++++def _association_trial_bound(result, events):++ """Bound an incompletely supported association at one shared clock.++++ The declared score is sum(1 - loss_i / limit_i), or -inf if any event++ fails its residual limit. Each nonnegative unknown loss contributes at++ most one. Only a fully validated core fit can tighten that ceiling or++ establish a residual rejection. Missing support is still unknown.++ """++ kind = "matched_group_support_minus_normalized_residual"++ if not events or not isinstance(result, dict) or result.get("score_kind") != kind:++ return None++ from .matching import _frequency_scale++ try:++ limits = [3 * _frequency_scale(event) for event in events]++ except (TypeError, ValueError, KeyError):++ return None++ if not all(np.isfinite(value) and value > 0 for value in limits):++ return None++ maximum = float(len(events))++ diagnostics, scores, frequencies = (result.get(name) for name in ("event_diagnostics", "event_scores", "f0_hz"))++ if (not all(isinstance(values, list) and len(values) == len(events)++ for values in (diagnostics, scores, frequencies))++ or result.get("optimizer_success", True) is not True):++ return maximum++ contributions = []++ for diagnostic, score, frequency, event, limit in zip(diagnostics, scores, frequencies, events, limits):++ single = {"score_kind": "negative_robust_ridge_loss_hz", "score": score,++ "event_scores": [score], "f0_hz": [frequency], "event_diagnostics": [diagnostic]}++ classification, _ = _ridge_trial_classification(single, [event], False)++ if classification != "evaluated":++ contributions.append(1.0)++ continue++ if -score > limit:++ return -np.inf++ # Use the scorer's per-event arithmetic, then round every contribution++ # and positive accumulation upward. Subtracting losses from k instead++ # changes the operation order and can understate a floating-point score.++ contributions.append(float(np.nextafter(1 - (-score) / limit, np.inf)))++ upper = 0.0++ for contribution in contributions:++ upper = float(np.nextafter(upper + contribution, np.inf))++ return min(maximum, upper)++++def score_candidate(candidate, point, tracks, events, measurements, mode="brightness",time_origin=None, time_sweep_s=5.0, time_step_s=0.5, c=343.0):association = "event_indices" in candidate@@@ -251,9 -253,9 +371,15 @@@else:shifts = np.linspace(lower-anchor,upper-anchor,max(1,int(np.ceil((upper-lower)/time_step_s)))+1)best = {"score":-np.inf}++ if mode == "robust_ridge":++ best["score_kind"] = ("matched_group_support_minus_normalized_residual" if association++ else "negative_robust_ridge_loss_hz")assessment = {"complete": False, "evaluated_trials": 0, "rejected_trials": 0,-- "unknown_trials": 0, "reasons": []}++ "unknown_trials": 0, "reasons": [], "scheduled_trials": len(shifts),++ "trial_count_semantics": "disjoint_evaluated_rejected_unknown",++ "empty_clock_domain": len(shifts) == 0}reasons = set()++ unknown_bounds = []for shift in shifts:if mode == "robust_ridge":from .matching import score_ridges@@@ -263,16 -265,16 +389,17 @@@except AcousticSupportError as error:assessment["unknown_trials"] += 1reasons.add(str(error))++ unknown_bounds.append(None)continue-- supported = all(d.get("support_fraction") == 1 and np.isfinite(d["score"])-- for d in result["event_diagnostics"])if association:from .matching import association_scoreresult = association_score(result, events)-- if not supported or np.isnan(result["score"]) or result["score"] == np.inf:++ classification, reason = _ridge_trial_classification(result, events, association)++ if classification == "unknown":assessment["unknown_trials"] += 1-- reasons.add("incomplete_ridge_or_trajectory_support")-- elif result["score"] == -np.inf:++ reasons.add("incomplete_ridge_or_trajectory_support" if reason == "incomplete_acoustic_support" else reason)++ unknown_bounds.append(_association_trial_bound(result, events) if association else None)++ elif classification == "rejected":assessment["rejected_trials"] += 1reasons.add("acoustic_loss_exceeds_limit")else:@@@ -293,10 -295,10 +420,17 @@@"recording_start_time_s":float(anchor+shift),"time_adjustment_s":float(shift)}if mode == "robust_ridge":if not len(shifts):-- assessment["unknown_trials"] = 1reasons.add("no_clock_trials")-- assessment["complete"] = assessment["unknown_trials"] == 0++ assessment["complete"] = bool(len(shifts) and assessment["unknown_trials"] == 0)assessment["reasons"] = sorted(reasons)++ if association and assessment["unknown_trials"]:++ finite_bounds = [value for value in unknown_bounds if value is not None and np.isfinite(value)]++ assessment.update(++ bounded_unknown_trials=sum(value is not None for value in unknown_bounds),++ bounded_unknown_rejections=sum(value == -np.inf for value in unknown_bounds if value is not None),++ unknown_score_upper_bound=max(finite_bounds) if finite_bounds else None,++ unknown_score_bound_kind="matched_group_support_minus_normalized_residual",++ unknown_score_bound_method="nonnegative_loss_and_validated_event_fits")best["scoring_assessment"] = assessmentreturn dict(best,**association_fields,point_id=int(point.point_id),lat=float(point.lat),lon=float(point.lon),elev_m=float(point.elev_m),x=float(point.x),y=float(point.y),flight_ids=[p["flight_id"] for p in candidate["passes"]])diff --cc src/dopplergeist/tiled_search.pyindex 2d5ffef,de24cab..5d15919--- a/src/dopplergeist/tiled_search.py+++ b/src/dopplergeist/tiled_search.py@@@ -18,7 -18,8 +18,8 @@@ import pandas as pfrom pyproj import Transformerfrom .data_access import CONUS, DataUnavailable, content_hash, sha256, write_json--from .finite_search import RetentionLedger, classified_assessment, identify_mode, mode_seed++from .finite_search import RetentionLedger, bounded_assessment, classified_assessment, identify_mode, mode_seed+ from .geometry import AcousticSupportErrorfrom .search import cpa_table, filter_event, pair_candidates, score_candidate@@@ -55,7 -65,7 +65,7 @@@ def _key(row)tuple(seed["position"]), seed["recording_start_time_s"])--def merge_candidates(rows, top_k, *, ledger=None, stage=None):++def merge_candidates(rows, top_k, *, ledger=None, stage=None, bounds=()):unique, occurrences = {}, 0for row in rows:if not math.isfinite(row["score"]):@@@ -68,7 -78,7 +78,7 @@@if ledger is not None:if stage is None:raise ValueError("Retention accounting requires a stage identity")-- ledger.record(stage, list(unique.values()), kept, occurrences)++ ledger.record(stage, list(unique.values()), kept, occurrences, bounds=bounds)return kept@@@ -170,6 -196,8 +196,9 @@@ def _score(points, tracks, events, meascandidates, counts = pair_candidates(table, events, **kwargs)# Attach approach identities before scoring, since legacy rank drops passes.ranked, unclassified, rejected = [], 0, 0++ bounds = []+ trial_counts = dict(evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)+ unclassified_assessments = []lookup = {row.point_id: row for row in points.itertuples()}track_lookup = {track.id: track for track in tracks}for candidate in candidates:@@@ -199,15 -236,44 +237,53 @@@known = (classified_assessment(row) if settings.get("mode") == "robust_ridge" elsesettings.get("time_origin") is not None and settings.get("time_sweep_s", 5) == 0 and math.isfinite(row["score"]))row["core_assessment_complete"] = bool(known and math.isfinite(row["score"]))+ if settings.get("mode") == "robust_ridge":+ assessment = row.get("scoring_assessment")+ if isinstance(assessment, dict) and all(type(assessment.get(k)) is int and assessment[k] >= 0+ for k in ("evaluated_trials", "rejected_trials", "unknown_trials")):+ for key in ("evaluated_trials", "rejected_trials", "unknown_trials"):+ trial_counts[key] += assessment[key]+ else:+ trial_counts["unreported_trial_envelopes"] += 1+ elif not known:+ trial_counts["unreported_trial_envelopes"] += 1if not known:unclassified += 1- unclassified_assessments.append({"point_id": int(candidate["point_id"]),++ detail = {"point_id": int(candidate["point_id"]), "envelope_index": unclassified,++ "score_kind": row.get("score_kind"),+ "receiver": {k: float(row[k]) for k in ("x", "y", "lat", "lon", "elev_m")},+ "event_indices": row.get("event_indices", list(range(len(events)))), "flight_ids": row["flight_ids"],+ "pass_emission_times_s": row["pass_emission_times_s"],+ "recording_start_bounds_s": scoring_candidate.get("recording_start_bounds_s"),++ "clock_settings": {k: settings.get(k) for k in ("time_origin", "time_sweep_s", "time_step_s")},+ "scoring_assessment": row.get("scoring_assessment"), "support_failure": row.get("support_failure"),- "finite_best": math.isfinite(row["score"])})++ "finite_best": math.isfinite(row["score"])}++ unclassified_assessments.append(detail)++ if bounded_assessment(row):++ bounds.append({"bound_id": "bound-" + content_hash(detail), "detail": detail,++ "groups_count": len(detail["event_indices"]),++ "upper_score": detail["scoring_assessment"]["unknown_score_upper_bound"]})if math.isfinite(row["score"]):ranked.append(row)elif known:rejected += 1-- kept = merge_candidates(ranked, budget.top_k, ledger=ledger, stage=stage)++ kept = merge_candidates(ranked, budget.top_k, ledger=ledger, stage=stage, bounds=bounds)return kept, dict(counts, cpa_rows=count, candidates=len(candidates), unclassified_score_candidates=unclassified,- evaluated_rejections=rejected)++ bounded_score_candidates=len(bounds), unbounded_score_candidates=unclassified-len(bounds),+ evaluated_rejections=rejected, unsupported_cpa_tracks=unsupported,+ unclassified_candidate_assessments=unclassified_assessments, **trial_counts)+++ def _record_support(output, stage, counts, summary):+ summary["unsupported_cpa_track_evaluations"] += len(counts.get("unsupported_cpa_tracks", []))- for key in ("unclassified_score_candidates", "evaluated_trials", "rejected_trials", "unknown_trials", "unreported_trial_envelopes"):++ for key in ("unclassified_score_candidates", "bounded_score_candidates", "unbounded_score_candidates",++ "evaluated_trials", "rejected_trials", "unknown_trials", "unreported_trial_envelopes"):+ summary[key] += counts.get(key, 0)+ if counts.get("unsupported_cpa_tracks") or counts.get("unclassified_candidate_assessments"):+ (output / "support").mkdir(exist_ok=True)+ write_json(output / "support" / (stage.replace(":", "-") + ".json"),+ {"stage": stage, "unsupported_cpa_tracks": counts.get("unsupported_cpa_tracks", []),+ "unclassified_candidate_assessments": counts.get("unclassified_candidate_assessments", [])})def search_national(indexes, terrain, events, measurements, *, time_range_s, output_dir,@@@ -277,7 -343,8 +353,9 @@@"brightness": "summed_spectral_contrast"}[mode])ledger = RetentionLedger(output / "retention.sqlite", run_hash, score_kind)began, ranked, failures, done, resumed, points_searched = time.monotonic(), [], [], 0, 0, 0- unclassified_scores = 0+ support = dict(unsupported_cpa_track_evaluations=0, unclassified_score_candidates=0,++ bounded_score_candidates=0, unbounded_score_candidates=0,+ evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)xmin, ymin, xmax, ymax = _grid_extent(bounds, budget.spacing_m, crs)total = (xmax // budget.tile_cells - xmin // budget.tile_cells + 1) * (ymax // budget.tile_cells - ymin // budget.tile_cells + 1)radius = max(e["slant_range_m"][1] for e in events)@@@ -382,15 -449,17 +460,26 @@@if lo <= covered_until:covered_until = max(covered_until, hi)data_complete = bool(covered_until >= time_range_s[1])- complete = done == total and not failures and not refinement_failure and data_complete and not event_limit_applied- finite = ledger.evidence(ranked, complete=complete and not unclassified_scores, spacing_m=budget.spacing_m,+ model_complete = not (support["unsupported_cpa_track_evaluations"] or support["unclassified_score_candidates"])- complete = done == total and not failures and not refinement_failure and data_complete and not event_limit_applied and model_complete++ model_assessed = not (support["unsupported_cpa_track_evaluations"] or support["unbounded_score_candidates"]++ or support["unreported_trial_envelopes"])++ model_assessed &= support["bounded_score_candidates"] == support["unclassified_score_candidates"]++ complete = done == total and not failures and not refinement_failure and data_complete and not event_limit_applied and model_assessed+ finite = ledger.evidence(ranked, complete=complete, spacing_m=budget.spacing_m,refine_spacing_m=min(budget.spacing_m, budget.refine_spacing_m), max_event_groups=len(events),expected_stages={"coarse": done, "global": done, "fine": fine_stages, "fine-global": fine_stages})- finite["unclassified_score_candidates"] = unclassified_scores- if unclassified_scores:++ if finite["bounded_unknown_envelopes"] != support["bounded_score_candidates"]:++ model_assessed = complete = False++ finite["complete"] = finite["pruning_accounted_for"] = False+ finite["unclassified_score_candidates"] = support["unclassified_score_candidates"]+ finite["unsupported_cpa_track_evaluations"] = support["unsupported_cpa_track_evaluations"]- if not model_complete:++ if not model_assessed:finite["best_discarded_score"] = Nonefinite["discarded_bound_status"] = "unknown_model_or_trial_support"-- finite["limitations"].append("Unclassified or unsupported optimizer trials have no known upper score bound.")++ finite["limitations"].append("Some unclassified trials or unsupported CPA tracks remain without a score bound.")++ else:++ finite["discarded_bound_status"] = ("includes_bounded_unknown_trials" if support["bounded_score_candidates"]++ else "evaluated_scores")finite["optimizer_domain"] = {"clock_window_s": start_window, "time_origin_s": parameters.get("time_origin"),"time_step_s": parameters.get("time_step_s", .5), "declared_sweep_s": parameters.get("time_sweep_s", 5.),"clock_rule": "shared CPA-consistency interval plus declared sweep, intersected with trusted window",@@@ -404,6 -473,7 +493,8 @@@"coarse_ranked": coarse, "tiles_total": total, "tiles_completed": done, "tiles_resumed": resumed,"tile_failures": failures, "unsearched_tiles": total - done, "grid_points_searched": points_searched,"data_coverage": coverage, "data_scope_complete": data_complete, "refinement_failure": refinement_failure,+ "model_support_complete": model_complete, "model_support": dict(support, diagnostics_directory="support"),++ "model_assessment_complete": model_assessed,"refinement_points_searched": refinement_points_searched, "refinement_points_skipped": refinement_points_skipped,"required_flight_bounds": flight_bounds,"candidate_retention_limit": budget.top_k, "alternative_modes_exhaustively_assessed": False,diff --cc tests/test_bounded_model_coverage.pyindex 0000000,0000000..b21cc9dnew file mode 100644--- /dev/null+++ b/tests/test_bounded_model_coverage.py@@@ -1,0 -1,0 +1,138 @@@++"""A bound accounts for a trial; it does not fabricate a supported trajectory."""++from copy import deepcopy++++import pytest++++from dopplergeist.automatic import _coverage++++++def report():++ return {++ "status": "complete", "tiles_total": 2, "tiles_completed": 2,++ "data_scope_complete": True, "all_event_groups_considered": True,++ "model_support_complete": False, "model_assessment_complete": True,++ "model_support": {++ "unsupported_cpa_track_evaluations": 0, "unclassified_score_candidates": 2,++ "evaluated_trials": 4, "rejected_trials": 1, "unknown_trials": 3,++ "unreported_trial_envelopes": 0, "bounded_score_candidates": 2,++ "unbounded_score_candidates": 0,++ },++ "finite_search_evidence": {++ "schema_version": 1, "scope": "evaluated_finite_grid",++ "score_kind": "matched_group_support_minus_normalized_residual",++ "complete": True, "pruning_accounted_for": True, "max_event_groups": 4,++ "bounded_unknown_envelopes": 2, "bounded_unknown_rejections": 1,++ "best_unknown_score_upper_bound": 1.0, "discarded_count": 1,++ "best_discarded_score": 1.0, "unclassified_score_candidates": 2,++ "unsupported_cpa_track_evaluations": 0,++ },++ }++++++def coverage(value):++ return _coverage({"search": {"coverage": "conus"}}, value, {})++++++def test_certified_bounds_account_for_work_without_relabeling_missing_support():++ value = report()++ original = deepcopy(value)++ result = coverage(value)++ assert result["search_complete"] is True++ assert result["data_status"] == "available"++ assert "certified score bounds" in " ".join(result["limitations"])++ assert "unknown clock trials: 3" in " ".join(result["limitations"])++ assert value == original++ assert value["model_support_complete"] is False++++++def test_competitive_bounds_are_left_for_the_unchanged_confidence_decision():++ value = report()++ value["finite_search_evidence"].update(best_unknown_score_upper_bound=4., best_discarded_score=4.)++ assert coverage(value)["search_complete"] is True++++++def test_every_missing_fit_may_have_a_certified_rejecting_event():++ value = report()++ value["finite_search_evidence"].update(bounded_unknown_rejections=2,++ best_unknown_score_upper_bound=None, discarded_count=0, best_discarded_score=None)++ assert coverage(value)["search_complete"] is True++++[email protected]("section,key,value", [++ (None, "model_assessment_complete", False),++ (None, "model_assessment_complete", 1),++ (None, "model_support_complete", True),++ (None, "status", "partial"),++ ("model_support", "bounded_score_candidates", 1),++ ("model_support", "bounded_score_candidates", True),++ ("model_support", "unclassified_score_candidates", 3),++ ("model_support", "unknown_trials", 1),++ ("model_support", "unknown_trials", True),++ ("model_support", "unsupported_cpa_track_evaluations", 1),++ ("model_support", "unreported_trial_envelopes", 1),++ ("model_support", "unbounded_score_candidates", 1),++ ("finite_search_evidence", "complete", False),++ ("finite_search_evidence", "pruning_accounted_for", False),++ ("finite_search_evidence", "scope", "continuous_space"),++ ("finite_search_evidence", "schema_version", True),++ ("finite_search_evidence", "score_kind", "negative_robust_ridge_loss_hz"),++ ("finite_search_evidence", "bounded_unknown_envelopes", 1),++ ("finite_search_evidence", "bounded_unknown_rejections", 3),++ ("finite_search_evidence", "bounded_unknown_rejections", True),++ ("finite_search_evidence", "unclassified_score_candidates", 1),++ ("finite_search_evidence", "unsupported_cpa_track_evaluations", 1),++ ("finite_search_evidence", "max_event_groups", 0),++ ("finite_search_evidence", "discarded_count", 0),++ ("finite_search_evidence", "best_discarded_score", .5),++ ("finite_search_evidence", "best_unknown_score_upper_bound", None),++ ("finite_search_evidence", "best_unknown_score_upper_bound", float("nan")),++ ("finite_search_evidence", "best_unknown_score_upper_bound", -1.),++ ("finite_search_evidence", "best_unknown_score_upper_bound", 5.),++])++def test_incomplete_or_inconsistent_bound_accounting_does_not_restore_coverage(section, key, value):++ source = report()++ (source if section is None else source[section])[key] = value++ assert coverage(source)["search_complete"] is False++++[email protected]("section,key", [++ (None, "model_assessment_complete"), (None, "model_support_complete"),++ ("model_support", "unreported_trial_envelopes"),++ ("finite_search_evidence", "bounded_unknown_envelopes"),++])++def test_missing_new_evidence_cannot_silently_default_to_complete(section, key):++ source = report()++ del (source if section is None else source[section])[key]++ assert coverage(source)["search_complete"] is False++++[email protected]("changes", [++ {"tiles_completed": 1}, {"tile_failures": [{"tile": "missing"}]},++ {"refinement_failure": "budget exhausted"}, {"all_event_groups_considered": False},++])++def test_certified_scoring_bounds_do_not_cover_other_missing_work(changes):++ source = report()++ source.update(changes)++ assert coverage(source)["search_complete"] is False++++++def test_flight_coverage_stays_partial_despite_complete_scoring_accounting():++ source = report()++ source["data_scope_complete"] = False++ result = coverage(source)++ assert result["data_status"] == "partial"++ assert "historical_flight_scope_or_audible_border_region" in result["missing_data"]++++++def test_declared_incomplete_assessment_overrides_legacy_complete_support():++ source = report()++ source.update(model_support_complete=True, model_assessment_complete=False)++ source["model_support"].update(unclassified_score_candidates=0, unknown_trials=0,++ bounded_score_candidates=0)++ assert coverage(source)["search_complete"] is False++++++def test_assessment_flag_without_raw_support_evidence_is_incomplete():++ source = report()++ del source["model_support_complete"], source["model_support"]++ assert coverage(source)["search_complete"] is Falsediff --cc tests/test_scoring_assessment.pyindex 52d0b6d,dcf9122..7445942--- a/tests/test_scoring_assessment.py+++ b/tests/test_scoring_assessment.py@@@ -4,11 -4,11 +4,14 @@@ from types import SimpleNamespacimport numpy as npimport pytest- from aircraft_geoloc import geometry- from aircraft_geoloc.matching import RidgeTimes- from aircraft_geoloc.search import score_candidate+ from dopplergeist import geometry+ from dopplergeist.matching import RidgeTimes+ from dopplergeist.search import score_candidate++SCHEDULE = {"scheduled_trials": 3, "empty_clock_domain": False,++ "trial_count_semantics": "disjoint_evaluated_rejected_unknown"}++class Model:def __init__(self, last_supported=np.inf, error=None):self.last_supported, self.error = last_supported, error@@@ -38,7 -38,7 +41,7 @@@ def score(model, *, ridge_hz=120.0, assdef test_all_declared_clock_trials_are_evaluated():result = score(Model())assert result["score"] == pytest.approx(0)-- assert result["scoring_assessment"] == {"complete": True, "evaluated_trials": 3,++ assert result["scoring_assessment"] == {**SCHEDULE, "complete": True, "evaluated_trials": 3,"rejected_trials": 0, "unknown_trials": 0, "reasons": []}@@@ -54,7 -54,7 +57,7 @@@ def test_finite_best_does_not_hide_unkndef test_completed_acoustic_rejection_is_classified_without_a_finite_best():result = score(Model(), ridge_hz=200, association=True)assert result["score"] == -np.inf-- assert result["scoring_assessment"] == {"complete": True, "evaluated_trials": 0,++ assert result["scoring_assessment"] == {**SCHEDULE, "complete": True, "evaluated_trials": 0,"rejected_trials": 3, "unknown_trials": 0, "reasons": ["acoustic_loss_exceeds_limit"]}@@@ -62,7 -62,7 +65,7 @@@ def test_typed_emission_failure_stays_uerror = geometry.AcousticSupportError("test-flight", "non_monotone_arrival")result = score(Model(error=error))assert result["score"] == -np.inf-- assert result["scoring_assessment"] == {"complete": False, "evaluated_trials": 0,++ assert result["scoring_assessment"] == {**SCHEDULE, "complete": False, "evaluated_trials": 0,"rejected_trials": 0, "unknown_trials": 3,"reasons": ["test-flight: non_monotone_arrival"]}@@@ -84,5 -84,5 +87,6 @@@ def test_unrelated_value_error_is_not_rdef test_empty_clock_domain_is_not_a_vacuous_completed_assessment():result = score(Model(), bounds=[5, 6])assert result["score"] == -np.inf-- assert result["scoring_assessment"] == {"complete": False, "evaluated_trials": 0,-- "rejected_trials": 0, "unknown_trials": 1, "reasons": ["no_clock_trials"]}++ assert result["scoring_assessment"] == {**SCHEDULE, "scheduled_trials": 0,++ "empty_clock_domain": True, "complete": False, "evaluated_trials": 0,++ "rejected_trials": 0, "unknown_trials": 0, "reasons": ["no_clock_trials"]}diff --cc tests/test_unknown_score_bounds.pyindex 0000000,0000000..fe0d695new file mode 100644--- /dev/null+++ b/tests/test_unknown_score_bounds.py@@@ -1,0 -1,0 +1,167 @@@++"""Unknown trajectory support stays unknown; finite score ceilings can exclude it."""++from copy import deepcopy++from types import SimpleNamespace++import sqlite3++++import numpy as np++import pytest++++from dopplergeist import matching++from dopplergeist.data_access import DataUnavailable, content_hash++from dopplergeist.finite_search import RetentionLedger, bounded_assessment, classified_assessment++from dopplergeist.matching import RidgeTimes, association_score, score_ridges++from dopplergeist.search import _association_trial_bound, score_candidate++from dopplergeist.tiled_search import merge_candidates++from test_scoring_assessment import Model++from test_finite_search import row++++++KIND = "matched_group_support_minus_normalized_residual"++++++def inputs(models, frequencies=None):++ times = np.arange(0., 20., .5)++ frequencies = frequencies or [120.] * len(models)++ events = [{"event_id": f"e{i}", "cpa_receive_s": 10., "f0_range_hz": [119., 121.]}++ for i in range(len(models))]++ measurements = [(RidgeTimes(times), np.full_like(times, value), np.ones_like(times), {})++ for value in frequencies]++ return events, measurements++++++def core(models, frequencies=None):++ events, measurements = inputs(models, frequencies)++ return association_score(score_ridges(models, events, measurements, np.zeros(3), 0.), events), events++++++def envelope(models, frequencies=None):++ events, measurements = inputs(models, frequencies)++ point = SimpleNamespace(point_id=0, lat=40., lon=-100., elev_m=0., x=0., y=0.)++ tracks = {str(i): model for i, model in enumerate(models)}++ candidate = {"event_indices": list(range(len(models))),++ "passes": [{"flight_id": identity, "receive_time": 10.} for identity in tracks]}++ return score_candidate(candidate, point, tracks, events, measurements, mode="robust_ridge",++ time_origin=0., time_sweep_s=1., time_step_s=1.)++++++def persisted_bound(result):++ detail = {key: deepcopy(result[key]) for key in ("event_indices", "flight_ids", "score_kind", "scoring_assessment")}++ return {"bound_id": "bound-" + content_hash(detail), "detail": detail,++ "groups_count": len(result["event_indices"]),++ "upper_score": result["scoring_assessment"]["unknown_score_upper_bound"]}++++++def test_actual_missing_support_has_group_count_ceiling_without_claiming_a_fit():++ result = envelope([Model(last_supported=-10)] * 4)++ assessment = result["scoring_assessment"]++ assert result["score"] == -np.inf++ assert not assessment["complete"] and not classified_assessment(result)++ assert assessment["unknown_trials"] == assessment["bounded_unknown_trials"] == 3++ assert assessment["unknown_score_upper_bound"] == 4.++ assert assessment["reasons"] == ["incomplete_ridge_or_trajectory_support"]++ assert bounded_assessment(result)++++++def test_supported_event_rejects_an_association_but_missing_support_is_preserved():++ result = envelope([Model(), Model(last_supported=-10)], [200., 120.])++ assessment = result["scoring_assessment"]++ assert result["score"] == -np.inf and not assessment["complete"]++ assert assessment["unknown_trials"] == assessment["bounded_unknown_rejections"] == 3++ assert assessment["unknown_score_upper_bound"] is None++ assert assessment["rejected_trials"] == 0, "Missing core fits must not be relabelled as complete fits"++ assert bounded_assessment(result)++++++def test_supported_loss_tightens_bound_for_every_unknown_event_completion():++ partial, events = core([Model(), Model(last_supported=-10)], [122., 120.])++ upper = _association_trial_bound(partial, events)++ assert 1. < upper < 2.++ for frequency in np.linspace(100., 150., 21):++ completed, _ = core([Model(), Model()], [122., frequency])++ assert completed["score"] <= upper++++[email protected]("change", [{"support_fraction": .5}, {"optimizer_success": False},++ {"source_span_s": 0.}, {"f0_hz": np.nan}, {"source_drift_hz": 1000.}, {"rmse_hz": -1.}])++def test_invalid_supported_fit_cannot_tighten_or_reject(change):++ result, events = core([Model(), Model(last_supported=-10)], [200., 120.])++ assert _association_trial_bound(result, events) == -np.inf++ result["event_diagnostics"][0].update(change)++ assert _association_trial_bound(result, events) == 2.++++[email protected]("kind", [None, "summed_spectral_contrast", "negative_robust_ridge_loss_hz"])++def test_no_missing_fit_bound_for_another_score_definition(kind):++ result, events = core([Model(last_supported=-10)])++ result["score_kind"] = kind++ assert _association_trial_bound(result, events) is None++++++def test_maximum_bound_includes_every_scheduled_shared_clock(monkeypatch):++ models = [Model(), Model(last_supported=-10)]++ calls = 0++ original = matching.score_ridges++++ def different_clock(*args, **kwargs):++ nonlocal calls++ calls += 1++ result = original(*args, **kwargs)++ if calls != 2:++ result["event_diagnostics"][0]["optimizer_success"] = False++ return result++++ monkeypatch.setattr(matching, "score_ridges", different_clock)++ result = envelope(models, [200., 120.])++ assessment = result["scoring_assessment"]++ assert calls == assessment["scheduled_trials"] == 3++ assert assessment["bounded_unknown_rejections"] == 1++ assert assessment["unknown_score_upper_bound"] == 2.++++[email protected]("change", [{"scheduled_trials": 2}, {"scheduled_trials": None},++ {"trial_count_semantics": "other"}, {"empty_clock_domain": True},++ {"bounded_unknown_trials": 2}, {"unknown_score_upper_bound": -1.},++ {"unknown_score_upper_bound": 2.}, {"bounded_unknown_rejections": 4}])++def test_persisted_bound_requires_complete_valid_counter_accounting(change):++ result = envelope([Model(last_supported=-10)])++ result["scoring_assessment"].update(change)++ assert not bounded_assessment(result)++++++def test_ledger_preserves_bounds_across_resume_and_the_existing_competitive_margin(tmp_path):++ ledger = RetentionLedger(tmp_path / "retention.sqlite", "run", KIND)++ winner = row(0., 3.8075341081656915, groups=4)++ small = persisted_bound(envelope([Model(last_supported=-10)]))++ rejected = persisted_bound(envelope([Model(), Model(last_supported=-10)], [200., 120.]))++ kept = merge_candidates([winner], 1, ledger=ledger, stage="coarse:a", bounds=[small, rejected])++ saved = ledger.checksum("coarse:a")++ options = dict(complete=True, spacing_m=1000, refine_spacing_m=100, max_event_groups=4)++ result = ledger.evidence(kept, **options)++ assert result["bounded_unknown_envelopes"] == 2++ assert result["bounded_unknown_rejections"] == 1 and result["discarded_count"] == 1++ assert result["best_unknown_score_upper_bound"] == result["best_discarded_score"] == 1.++ assert (winner["score"] - result["best_discarded_score"]) / 4 > .2++ resumed = RetentionLedger(ledger.path, "run", KIND)++ assert resumed.stage_valid("coarse:a", saved)++ assert resumed.evidence(kept, **options) == result++ large = persisted_bound(envelope([Model(last_supported=-10)] * 4))++ merge_candidates([], 1, ledger=resumed, stage="coarse:b", bounds=[large])++ competitive = resumed.evidence(kept, **options)++ assert competitive["best_discarded_score"] == 4.++ assert (winner["score"] - competitive["best_discarded_score"]) / 4 <= .2++ assert not resumed.evidence(kept, **dict(options, complete=False))["complete"]++ with sqlite3.connect(ledger.path) as db:++ db.execute("DELETE FROM bounds WHERE stage='coarse:b'")++ assert not resumed.evidence(kept, **options)["pruning_accounted_for"]++++++def test_ledger_refuses_wrong_score_kind_and_invalid_bound_detail(tmp_path):++ bound = persisted_bound(envelope([Model(last_supported=-10)]))++ wrong = RetentionLedger(tmp_path / "wrong.sqlite", "run", "summed_spectral_contrast")++ with pytest.raises(DataUnavailable, match="association-score bound"):++ wrong.record("coarse:a", [], [], 0, bounds=[bound])++ ledger = RetentionLedger(tmp_path / "correct.sqlite", "run", KIND)++ del bound["detail"]["scoring_assessment"]["scheduled_trials"]++ bound["bound_id"] = "bound-" + content_hash(bound["detail"])++ with pytest.raises(DataUnavailable, match="association-score bound"):++ ledger.record("coarse:a", [], [], 0, bounds=[bound])diff --cc tests/test_verify_bounded_search.pyindex 0000000,0000000..1075b47new file mode 100644--- /dev/null+++ b/tests/test_verify_bounded_search.py@@@ -1,0 -1,0 +1,150 @@@++"""Recorded score ceilings must survive the independent retention audit."""++from copy import deepcopy++import importlib.util++import json++from pathlib import Path++import sqlite3++++import pytest++++from dopplergeist.data_access import content_hash++from dopplergeist.finite_search import RetentionLedger, identify_mode++++++ROOT = Path(__file__).parents[1]++SPEC = importlib.util.spec_from_file_location("verify_bounded_http", ROOT / "scripts/verify_upload_http.py")++HTTP = importlib.util.module_from_spec(SPEC)++SPEC.loader.exec_module(HTTP)++KIND = "matched_group_support_minus_normalized_residual"++++++def bounded_search(tmp_path):++ directory = tmp_path / "job"++ (directory / "search/support").mkdir(parents=True)++ configuration = {"events": [{"event_id": "e0"}], "budget": {"spacing_m": 1000., "refine_spacing_m": 100.},++ "scoring": {"recording_start_window_s": [100., 100.], "time_step_s": .5, "time_sweep_s": 0.},++ "code": {"matching.py": "fit-code", "search.py": "score-code"}}++ rows = []++ for index, score in enumerate((.95, .94, .1)):++ row = {"point_id": index, "x": float(index), "y": 0., "lat": 40. + index*.001,++ "lon": -100., "elev_m": 0., "recording_start_time_s": 100., "score": score, "score_kind": KIND,++ "event_indices": [0], "flight_ids": ["flight-0"], "pass_emission_times_s": [104.],++ "scoring_assessment": {"complete": True, "scheduled_trials": 1, "evaluated_trials": 1,++ "rejected_trials": 0, "unknown_trials": 0, "empty_clock_domain": False, "reasons": [],++ "trial_count_semantics": "disjoint_evaluated_rejected_unknown"},++ "core_assessment_complete": True, "event_diagnostics": [{"support_fraction": 1., "score": -.1}]}++ identify_mode(row)++ rows.append(row)++ certificates = []++ for index, upper in enumerate((.5, None)):++ detail = {"point_id": index + 3, "envelope_index": index + 1, "score_kind": KIND,++ "receiver": {"x": float(index+3), "y": 0., "lat": 41., "lon": -100., "elev_m": 0.},++ "event_indices": [0], "flight_ids": ["flight-1"], "pass_emission_times_s": [104.],++ "recording_start_bounds_s": [100., 100.],++ "clock_settings": {"time_origin": None, "time_sweep_s": 0., "time_step_s": .5},++ "support_failure": None, "finite_best": False,++ "scoring_assessment": {"complete": False, "scheduled_trials": 1, "evaluated_trials": 0,++ "rejected_trials": 0, "unknown_trials": 1, "empty_clock_domain": False,++ "trial_count_semantics": "disjoint_evaluated_rejected_unknown",++ "reasons": ["incomplete_ridge_or_trajectory_support"], "bounded_unknown_trials": 1,++ "bounded_unknown_rejections": int(upper is None), "unknown_score_upper_bound": upper,++ "unknown_score_bound_kind": KIND,++ "unknown_score_bound_method": "nonnegative_loss_and_validated_event_fits"}}++ certificates.append({"bound_id": "bound-" + content_hash(detail), "upper_score": upper,++ "groups_count": 1, "detail": detail})++ ledger = RetentionLedger(directory / "search/retention.sqlite", "run-control", KIND)++ checksum = ledger.record("coarse:0_0", rows, rows[:2], len(rows), bounds=certificates)++ ledger.record("global:0_0", rows[:2], rows[:2], 2)++ details = [item["detail"] for item in certificates]++ payload = {"ranked": rows[:2], "retention_checksum": checksum, "counts": {++ "unclassified_score_candidates": 2, "bounded_score_candidates": 2, "unbounded_score_candidates": 0,++ "unclassified_candidate_assessments": details, "unsupported_cpa_tracks": []}}++ (directory / "search/tile-0_0.json").write_text(json.dumps(++ {"run_hash": "run-control", "payload": payload, "payload_hash": content_hash(payload)}))++ (directory / "search/support/coarse-0_0.json").write_text(json.dumps({"stage": "coarse:0_0",++ "unclassified_candidate_assessments": details, "unsupported_cpa_tracks": []}))++ finite = ledger.evidence(rows[:2], complete=True, spacing_m=1000., refine_spacing_m=100., max_event_groups=1)++ finite.update(ledger_artifact="retention.sqlite", unclassified_score_candidates=2,++ unsupported_cpa_track_evaluations=0, discarded_bound_status="includes_bounded_unknown_trials",++ optimizer_domain={"run_hash": "run-control", "source_fit_code_sha256": "fit-code",++ "score_code_sha256": "score-code", "clock_window_s": [100., 100.],++ "time_step_s": .5, "declared_sweep_s": 0.})++ ids = [row["mode_id"] for row in rows[:2]]++ search = {"run_hash": "run-control", "status": "complete", "ranked": rows[:2], "tiles_completed": 1,++ "refinement_points_searched": 0, "core_assessed_mode_ids": ids, "finite_search_evidence": finite,++ "model_support_complete": False, "model_assessment_complete": True,++ "model_support": {"unsupported_cpa_track_evaluations": 0, "unclassified_score_candidates": 2,++ "bounded_score_candidates": 2, "unbounded_score_candidates": 0, "unknown_trials": 2,++ "evaluated_trials": 3, "rejected_trials": 0, "unreported_trial_envelopes": 0}}++ refinement = {"ranked": deepcopy(rows[:2]), "matching_diagnostics": {++ "finite_search_evidence": deepcopy(finite), "recording_start_window_s": [100., 100.],++ "assessed_mode_ids": sorted(ids), "candidate_mode_ids": ids, "core_assessment_mapping_status": "present"}}++ return directory, search, configuration, refinement++++++def inspect(fixture):++ directory, search, configuration, refinement = fixture++ return HTTP.inspect_finite_search(lambda name: directory / name,++ lambda name: json.loads((directory / name).read_text()), search, configuration, refinement)++++++def test_persisted_bounds_account_for_unknowns_without_claiming_supported_fits(bounded_search):++ directory, search, _, _ = bounded_search++ before = (directory / "search/retention.sqlite").read_bytes()++ report = inspect(bounded_search)++ assert report["complete"] is True++ assert report["unknown_score_bounds_verified"] is True++ assert report["bounded_unknown_envelopes"] == 2++ assert report["bounded_unknown_rejections"] == 1++ assert report["best_unknown_score_upper_bound"] == .5++ assert report["best_discarded_score"] == .5 and report["discarded_count"] == 2++ assert report["unclassified_score_candidates"] == 2++ assert report["physical_trials_independently_recomputed"] is False++ assert search["model_support_complete"] is False++ assert (directory / "search/retention.sqlite").read_bytes() == before++++[email protected]("defect", ["missing_support", "changed_support", "missing_bound", "changed_bound",++ "wrong_maximum", "wrong_rejections", "wrong_unknown_total", "wrong_unknown_trials", "false_support",++ "unbounded_model", "invented_core_id"])++def test_bounded_acceptance_rejects_missing_or_inconsistent_evidence(bounded_search, defect):++ directory, search, _, refinement = bounded_search++ finite = search["finite_search_evidence"]++ if defect == "missing_support":++ (directory / "search/support/coarse-0_0.json").unlink()++ elif defect == "changed_support":++ path = directory / "search/support/coarse-0_0.json"++ value = json.loads(path.read_text())++ value["unclassified_candidate_assessments"][0]["receiver"]["lat"] += .1++ path.write_text(json.dumps(value))++ elif defect in {"missing_bound", "changed_bound"}:++ with sqlite3.connect(directory / "search/retention.sqlite") as db:++ db.execute("DELETE FROM bounds" if defect == "missing_bound" else "UPDATE bounds SET upper_score=0.1 WHERE upper_score IS NOT NULL")++ elif defect in {"wrong_maximum", "wrong_rejections", "wrong_unknown_total"}:++ key, value = {"wrong_maximum": ("best_unknown_score_upper_bound", .1),++ "wrong_rejections": ("bounded_unknown_rejections", 2),++ "wrong_unknown_total": ("unclassified_score_candidates", 1)}[defect]++ finite[key] = value++ refinement["matching_diagnostics"]["finite_search_evidence"][key] = value++ elif defect == "wrong_unknown_trials":++ search["model_support"]["unknown_trials"] = 1++ elif defect == "false_support":++ search["model_support_complete"] = True++ elif defect == "unbounded_model":++ search["model_support"]["unbounded_score_candidates"] = 1++ else:++ search["core_assessed_mode_ids"].append("bound-is-not-a-mode")++ with pytest.raises(ValueError):++ inspect(bounded_search)++++[email protected]("key,value", [("scheduled_trials", 0), ("scheduled_trials", True),++ ("bounded_unknown_trials", 0), ("bounded_unknown_rejections", 2),++ ("unknown_score_upper_bound", 1.1), ("unknown_score_upper_bound", float("nan")),++ ("empty_clock_domain", True), ("complete", True)])++def test_clock_bound_certificate_requires_every_unknown_trial(bounded_search, key, value):++ path = bounded_search[0] / "search/support/coarse-0_0.json"++ detail = json.loads(path.read_text())["unclassified_candidate_assessments"][0]++ detail["scoring_assessment"][key] = value++ assert HTTP.bounded_finite_clock_assessment(detail, 1) is Falsediff --cc tests/test_verify_upload_http.pyindex 0000000,0000000..8293873new file mode 100644--- /dev/null+++ b/tests/test_verify_upload_http.py@@@ -1,0 -1,0 +1,983 @@@++"""Real MP3 uploads through the actual HTTP service and analysis subprocess."""++import hashlib++import importlib.util++import json++import os++from pathlib import Path++import select++import shutil++import signal++import subprocess++import sys++import threading++import time++from copy import deepcopy++import sqlite3++++import numpy as np++import pytest++import soundfile as sf++++++SPEC = importlib.util.spec_from_file_location("verify_upload_http",++ Path(__file__).parents[1] / "scripts/verify_upload_http.py")++HTTP = importlib.util.module_from_spec(SPEC)++SPEC.loader.exec_module(HTTP)++CLOCK = "2026-09-21T14:13:20Z"++++[email protected](scope="module")++def mp3(tmp_path_factory):++ if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:++ pytest.skip("The real MP3 test requires ffmpeg and ffprobe")++ root = tmp_path_factory.mktemp("http-audio")++ rate = 8000++ time = np.arange(rate * 8) / rate++ wave = 0.2 * np.sin(2 * np.pi * 200 * time)++ sf.write(root / "stationary.wav", wave, rate)++ target = root / "stationary.mp3"++ subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", str(root / "stationary.wav"),++ "-codec:a", "libmp3lame", str(target)], check=True)++ return target++++++def test_actual_mp3_missing_clock_preserves_exact_bytes_and_stops_cleanly(tmp_path, mp3):++ previous_handler = signal.getsignal(signal.SIGTERM)++ receipt = HTTP.verify_http(mp3, tmp_path / "run", expect_status="needs_input",++ expect_reason="recording_time_required", timeout_s=60, poll_interval_s=0.05)++ assert signal.getsignal(signal.SIGTERM) == previous_handler++ assert receipt["interrupted"] is False++ assert receipt["verification_passed"], receipt++ assert receipt["pipeline_evidence_passed"] is True++ assert receipt["full_pipeline_observed"] is False++ assert receipt["status"] == "needs_input"++ assert receipt["supported_decision"] is False++ assert receipt["location_accuracy_evaluated"] is False++ assert receipt["browser_verified"] is False++ assert receipt["service"]["shutdown_signal"] == "SIGINT"++ assert receipt["service"]["returncode"] == 0++ assert receipt["service"]["forced_kill"] is False++ assert (tmp_path / "run/downloaded-original.mp3").read_bytes() == mp3.read_bytes()++ result = json.loads((tmp_path / "run/result.json").read_text())++ assert result["recording"]["source_sha256"] == hashlib.sha256(mp3.read_bytes()).hexdigest()++ manifest = json.loads((tmp_path / "run/job-manifest.json").read_text())++ assert manifest["files"]["input.mp3"]["sha256"] == receipt["source_sha256"]++ assert "intake/recording.json" in manifest["files"]++ assert "discovery/discovery.json" in manifest["files"]++ history = [json.loads(line) for line in (tmp_path / "run/history.jsonl").read_text().splitlines()]++ assert history[-1]["result"] == result++++++def test_actual_dated_mp3_abstention_remains_inconclusive(tmp_path, mp3):++ request = {"schema_version": 1, "time_window": {++ "start_utc": CLOCK, "end_utc": CLOCK, "source": "user"}}++ receipt = HTTP.verify_http(mp3, tmp_path / "run", request=request,++ expect_status="inconclusive", expect_reason="no_supported_events", timeout_s=60)++ assert receipt["verification_passed"], receipt++ assert receipt["pipeline_evidence_passed"] is True++ assert receipt["full_pipeline_observed"] is False++ assert receipt["status"] == "inconclusive"++ assert receipt["reason_code"] == "no_supported_events"++ assert receipt["supported_decision"] is False++ assert receipt["event_count"] == 0++ directory = tmp_path / "run/jobs" / receipt["job_id"]++ assert not (directory / "search").exists()++ assert json.loads((directory / "result.json").read_text())["status"] == "inconclusive"++++++def test_unexpected_actual_outcome_fails_verification_without_rewriting_result(tmp_path, mp3):++ receipt = HTTP.verify_http(mp3, tmp_path / "run", expect_status="succeeded", timeout_s=60)++ assert receipt["http_checks_passed"] is True, receipt++ assert receipt["verification_passed"] is False++ assert receipt["expectation_matched"] is False++ assert receipt["status"] == "needs_input"++ assert receipt["supported_decision"] is False++ result = json.loads((tmp_path / "run/result.json").read_text())++ assert result["status"] == "needs_input"++ assert receipt["terminal_result_preserved_after_shutdown"] is True++++++def test_existing_output_is_not_overwritten(tmp_path, mp3):++ output = tmp_path / "preserved"++ output.mkdir()++ evidence = output / "http-verification.json"++ evidence.write_text("preserve this exact evidence")++ with pytest.raises(FileExistsError):++ HTTP.verify_http(mp3, output, expect_status="needs_input")++ assert evidence.read_text() == "preserve this exact evidence"++++++def test_manual_event_hints_are_rejected_before_service_start(tmp_path, mp3):++ with pytest.raises(ValueError):++ HTTP.verify_http(mp3, tmp_path / "run", expect_status="needs_input",++ request={"schema_version": 1, "events": []})++ assert not (tmp_path / "run").exists()++++++def test_cli_preserves_actual_invalid_media_failure(tmp_path):++ if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:++ pytest.skip("The real decoder test requires ffmpeg and ffprobe")++ source = tmp_path / "invalid.mp3"++ source.write_bytes(b"This is deliberately not encoded audio.")++ output = tmp_path / "run"++ process = subprocess.run([sys.executable, str(Path(HTTP.__file__)),++ "--audio", str(source), "--output", str(output), "--expect-status", "failed",++ "--expect-reason", "invalid_media", "--timeout-s", "60"],++ capture_output=True, text=True, timeout=75)++ assert process.returncode == 0, (process.stdout, process.stderr)++ summary = json.loads(process.stdout)++ assert summary["verification_passed"] is True++ assert summary["pipeline_evidence_passed"] is True++ assert summary["full_pipeline_observed"] is False++ assert summary["status"] == "failed"++ assert summary["reason_code"] == "invalid_media"++ assert summary["supported_decision"] is False++ assert json.loads((output / "result.json").read_text())["status"] == "failed"++ assert (output / "downloaded-original.mp3").read_bytes() == source.read_bytes()++++++def test_sigterm_handler_restored_after_launch_failure(tmp_path, monkeypatch):++ source = tmp_path / "input.mp3"++ source.write_bytes(b"No decoder starts in this launch-failure control.")++ previous = signal.getsignal(signal.SIGTERM)++ caller_handler = lambda *_: None++ signal.signal(signal.SIGTERM, caller_handler)++ try:++ def launch_failure(*_, **__):++ raise OSError("deliberate launch failure")++ monkeypatch.setattr(HTTP.subprocess, "Popen", launch_failure)++ receipt = HTTP.verify_http(source, tmp_path / "run", expect_status="needs_input")++ assert signal.getsignal(signal.SIGTERM) is caller_handler++ assert receipt["verification_passed"] is False++ assert receipt["interrupted"] is False++ assert "deliberate launch failure" in receipt["error"]++ finally:++ signal.signal(signal.SIGTERM, previous)++++[email protected](os.name != "posix", reason="The service uses POSIX process groups")++def test_sigterm_during_shutdown_bounds_forced_cleanup_and_ignores_repeats():++ process = subprocess.Popen([sys.executable, "-c",++ "import signal,time; signal.signal(signal.SIGINT, signal.SIG_IGN); "++ "print('ready', flush=True); time.sleep(30)"],++ stdout=subprocess.PIPE, text=True, start_new_session=True)++ receipt = {"service": {"forced_kill": False, "returncode": None}, "interrupted": False}++ try:++ assert process.stdout.readline().strip() == "ready"++ with HTTP.TerminationGuard(receipt) as termination:++ timers = [threading.Timer(delay, os.kill, (os.getpid(), signal.SIGTERM))++ for delay in (0.1, 3.0)]++ began = time.monotonic()++ try:++ for timer in timers:++ timer.start()++ HTTP.stop_service(process, receipt, termination)++ finally:++ for timer in timers:++ timer.cancel()++ timer.join()++ assert time.monotonic() - began < 4.8++ assert receipt["interrupted"] is True++ assert receipt["interruption_signal"] == "SIGTERM"++ assert receipt["service"]["forced_kill"] is True++ assert receipt["service"]["returncode"] == -signal.SIGKILL++ finally:++ if process.poll() is None:++ process.kill()++ process.wait(timeout=5)++ process.stdout.close()++++[email protected](sys.platform != "linux" or not hasattr(os, "pidfd_open")++ or not hasattr(signal, "pidfd_send_signal"),++ reason="This control verifies Linux worker cleanup with stable PID handles")++def test_actual_outer_sigterm_stops_service_worker_and_decoder(tmp_path, mp3):++ decoder_marker, service_marker = tmp_path / "decoder.json", tmp_path / "service.pid"++ bin_path = tmp_path / "bin"++ bin_path.mkdir()++ decoder = bin_path / "ffmpeg"++ decoder.write_text(f"#!{sys.executable}\nimport json,os,time\nfrom pathlib import Path\n"++ f"Path({str(decoder_marker)!r}).write_text(json.dumps({{'pid':os.getpid(), 'parent_pid':os.getppid()}}))\n"++ "time.sleep(60)\n")++ decoder.chmod(0o755)++ # Observe the real service handle without replacing its implementation.++ entry = tmp_path / "observed_verifier.py"++ entry.write_text("import importlib.util,sys\nfrom pathlib import Path\n"++ f"spec=importlib.util.spec_from_file_location('verifier', {str(Path(HTTP.__file__).resolve())!r})\n"++ "module=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\n"++ "launch=module.subprocess.Popen\n"++ "def observed_launch(*args, **kwargs):\n"++ " process=launch(*args, **kwargs)\n"++ f" Path({str(service_marker)!r}).write_text(str(process.pid))\n"++ " return process\n"++ "module.subprocess.Popen=observed_launch\nraise SystemExit(module.main())\n")++ output = tmp_path / "run"++ env = dict(os.environ, PATH=str(bin_path) + os.pathsep + os.environ.get("PATH", ""))++ process = subprocess.Popen([sys.executable, str(entry), "--audio", str(mp3),++ "--output", str(output), "--expect-status", "needs_input", "--timeout-s", "60"],++ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, start_new_session=True)++ handles = []++ try:++ deadline = time.monotonic() + 20++ while not (decoder_marker.is_file() and (output / "history.jsonl").is_file()):++ if process.poll() is not None or time.monotonic() >= deadline:++ pytest.fail("The actual verifier did not reach the held decoder")++ time.sleep(0.02)++ decoder_state = json.loads(decoder_marker.read_text())++ handles = [os.pidfd_open(pid) for pid in++ (int(service_marker.read_text()), decoder_state["parent_pid"], decoder_state["pid"])]++ began = time.monotonic()++ process.send_signal(signal.SIGTERM)++ stdout, stderr = process.communicate(timeout=4.8)++ assert time.monotonic() - began < 5++ assert process.returncode == 1, (stdout, stderr)++ receipt = json.loads((output / "http-verification.json").read_text())++ assert receipt["interrupted"] is True++ assert receipt["interruption_signal"] == "SIGTERM"++ assert receipt["sigterm_cleanup_handler_installed"] is True++ assert receipt["verification_passed"] is False++ assert receipt["supported_decision"] is False++ assert receipt["finalization_skipped_reason"] == "verification_interrupted"++ assert receipt["service"]["returncode"] == 0++ assert receipt["service"]["forced_kill"] is False++ assert not (output / "pipeline-evidence.json").exists()++ assert not (output / "job-manifest.json").exists()++ for handle in handles:++ poller = select.poll()++ poller.register(handle, select.POLLIN)++ assert poller.poll(1000), "Service, worker, or decoder remained alive after interruption"++ finally:++ if not handles:++ pids = [int(service_marker.read_text())] if service_marker.is_file() else []++ if decoder_marker.is_file():++ state = json.loads(decoder_marker.read_text())++ pids.extend([state["parent_pid"], state["pid"]])++ for pid in pids:++ try:++ handles.append(os.pidfd_open(pid))++ except ProcessLookupError:++ pass++ if process.poll() is None:++ process.send_signal(signal.SIGTERM)++ try:++ process.wait(timeout=4.8)++ except subprocess.TimeoutExpired:++ process.kill()++ process.wait(timeout=5)++ for handle in handles:++ try:++ signal.pidfd_send_signal(handle, signal.SIGKILL)++ except ProcessLookupError:++ pass++ finally:++ os.close(handle)++++++def test_sigterm_after_terminal_result_skips_finalization(tmp_path, mp3, monkeypatch):++ stop = HTTP.stop_service++ def interrupt_after_shutdown(process, receipt, termination):++ stop(process, receipt, termination)++ os.kill(os.getpid(), signal.SIGTERM)++ monkeypatch.setattr(HTTP, "stop_service", interrupt_after_shutdown)++ receipt = HTTP.verify_http(mp3, tmp_path / "run", expect_status="needs_input", timeout_s=60)++ assert receipt["http_checks_passed"] is True++ assert receipt["status"] == "needs_input"++ assert receipt["interrupted"] is True++ assert receipt["verification_passed"] is False++ assert receipt["supported_decision"] is False++ assert receipt["pipeline_evidence_passed"] is False++ assert not (tmp_path / "run/pipeline-evidence.json").exists()++ assert not (tmp_path / "run/job-manifest.json").exists()++++++def test_sigterm_at_handler_handoff_is_persisted_as_interrupted(tmp_path, mp3, monkeypatch):++ original_exit = HTTP.TerminationGuard.__exit__++ def interrupt_before_restoration(guard, *args):++ os.kill(os.getpid(), signal.SIGTERM)++ return original_exit(guard, *args)++ monkeypatch.setattr(HTTP.TerminationGuard, "__exit__", interrupt_before_restoration)++ receipt = HTTP.verify_http(mp3, tmp_path / "run", expect_status="needs_input", timeout_s=60)++ persisted = json.loads((tmp_path / "run/http-verification.json").read_text())++ assert persisted == receipt++ assert persisted["http_checks_passed"] is True++ assert persisted["interrupted"] is True++ assert persisted["interruption_signal"] == "SIGTERM"++ assert persisted["verification_passed"] is False++ assert persisted["supported_decision"] is False++ assert persisted["finalization_skipped_reason"] == "verification_interrupted"++++[email protected](os.name != "posix", reason="This control requires POSIX signal exit codes")++def test_sigterm_after_serialization_cannot_commit_a_successful_cli_receipt(tmp_path, mp3):++ entry, marker = tmp_path / "interrupt_commit.py", tmp_path / "restored-handler.txt"++ entry.write_text("import importlib.util,os,signal\nfrom pathlib import Path\n"++ f"spec=importlib.util.spec_from_file_location('verifier', {str(Path(HTTP.__file__).resolve())!r})\n"++ "module=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\n"++ "from dopplergeist import jobs\nserialize=jobs.json.dumps\n"++ "def interrupt_commit(value, *args, **kwargs):\n"++ " encoded=serialize(value, *args, **kwargs)\n"++ " if isinstance(value, dict) and value.get('scope') == 'actual_local_http_upload_verification' and 'finished_utc' in value:\n"++ f" Path({str(marker)!r}).write_text(str(signal.getsignal(signal.SIGTERM)))\n"++ " os.kill(os.getpid(), signal.SIGTERM)\n"++ " return encoded\n"++ "jobs.json.dumps=interrupt_commit\nraise SystemExit(module.main())\n")++ output = tmp_path / "run"++ process = subprocess.run([sys.executable, str(entry), "--audio", str(mp3),++ "--output", str(output), "--expect-status", "needs_input", "--timeout-s", "60"],++ capture_output=True, text=True, timeout=20)++ assert process.returncode == -signal.SIGTERM, (process.stdout, process.stderr)++ assert marker.read_text() == str(signal.SIG_DFL)++ assert not (output / "http-verification.json").exists()++ assert json.loads((output / "result.json").read_text())["status"] == "needs_input"++++++STAGE_FILES = ["intake/recording.json", "intake/intake.json", "intake/recording.f32",++ "discovery/discovery.json", "data-provenance.json", "search/manifest.json",++ "search/search-report.json", "refined-candidates.json", "decision.json"]++++++def save_json(path, value):++ path.parent.mkdir(parents=True, exist_ok=True)++ path.write_text(json.dumps(value, allow_nan=False))++++++def stage_evidence(tmp_path):++ """Small consistency fixture, not generated audio or a localization benchmark."""++ from dopplergeist import confidence++ directory = tmp_path / "job"++ directory.mkdir()++ request = HTTP.validate_request({"schema_version": 1, "audio_path": str(directory / "input.mp3"),++ "time_window": {"start_utc": CLOCK, "end_utc": CLOCK, "source": "user"}})++ wire = {key: value for key, value in request.items() if key != "audio_path"}++ source_hash = hashlib.sha256(b"metadata consistency fixture only").hexdigest()++ implementation = {path.name: HTTP.sha256(path) for path in sorted(Path(HTTP.dopplergeist.__file__).parent.glob("*.py"))}++ recording = {"source_sha256": source_hash, "duration_s": 8.0, "sample_rate_hz": 4000,++ "channels": 1, "source_format": "mp3", "time_window": wire["time_window"]}++ event = {"event_id": "event-0001", "start_s": 1.0, "end_s": 7.0, "band_hz": [100.0, 200.0],++ "ridge": [{"time_s": t, "frequency_hz": f} for t, f in ((1., 180.), (4., 150.), (7., 120.))]}++ bounds = [-125.0, 24.0, -66.0, 50.0]++ start = HTTP.utc_timestamp(CLOCK).timestamp()++ window = [start, start]++ coverage = {"search_complete": True, "data_status": "available", "limitations": [],++ "requested_area": wire["search"], "missing_data": []}++ flight_coverage = {"bounds": [-180., -90., 180., 90.], "time_range_s": [start-300, start+300],++ "all_aircraft": True, "synthetic": True}++ flight_index = {"input_hash": "1" * 64, "coverage": flight_coverage}++ terrain = {"terrain_configuration": {"constant_m": 0}}++ configuration = {"code": implementation, "bounds": bounds, "scoring": {"recording_start_window_s": window},++ "events": [dict(event, event_ids=[event["event_id"]])], "time_range_s": [start-30, start+38],++ "indexes": [{"input_hash": flight_index["input_hash"], "file_sha256": "2" * 64}],++ "additional_input_hashes": terrain}++ run_hash = hashlib.sha256(json.dumps(configuration, sort_keys=True).encode()).hexdigest()++ candidate = {"lat": 40.0, "lon": -100.0, "score": -1.0, "score_kind": "negative_robust_ridge_loss_hz",++ "event_ids": [event["event_id"]], "flight_ids": ["fixture-flight"], "recording_start_utc": CLOCK}++ fit = {"rmse_hz": 1.0, "outlier_fraction": 0.0, "support_fraction": 1.0, "drift_at_bound": False}++ row = {key: candidate[key] for key in ("lat", "lon", "score", "score_kind", "flight_ids")}++ row.update(recording_start_time_s=start, event_indices=[0], event_diagnostics=[fit])++ diagnostics = {"recording_start_window_s": window, "clock_locked": True, "sensitivity": {},++ "unmatched_event_ids": [], event["event_id"]: fit}++ decision = dict(confidence.decide_location([event], [candidate], coverage, matching_diagnostics=diagnostics),++ candidates=[candidate])++ final = {"schema_version": 1, "job_id": "metadata-consistency-fixture", "recording": recording,++ "events": [event], "coverage": coverage,++ **{key: value for key, value in decision.items() if key != "diagnostics"}}++ values = {++ "input.json": {"sha256": source_hash, "bytes": 33, "path": "input.mp3"},++ "request.json": request,++ "provenance.json": {"source_sha256": source_hash, "request": request, "implementation_files": implementation,++ "operator_configuration_sha256": hashlib.sha256(b"{}").hexdigest(), "ground_truth_used_by_search": False,++ "event_selection": "automatic_whole_recording", "status": final["status"], "coverage": coverage,++ "discovered_events": 1, "search_run_hash": run_hash},++ "intake/recording.json": recording,++ "intake/intake.json": {"sample_count": 32000, "time_status": "ready", "decode": {"sample_format": "f32le"}},++ "discovery/discovery.json": {"source_sha256": source_hash, "events": [event],++ "chunks": [{"start_s": 0.0, "duration_s": 8.0}]},++ "data-provenance.json": {"flight_indexes": [flight_index], "terrain": terrain},++ "search/manifest.json": {"run_hash": run_hash, "configuration": configuration},++ "search/search-report.json": {"run_hash": run_hash, "scope": bounds, "scoring_time_is_locked": True,++ "ground_truth_used_by_search": False, "data_coverage": [{"input_hash": flight_index["input_hash"],++ "source": flight_coverage, "requested_bounds": bounds, "requested_time_range_s": configuration["time_range_s"]}],++ "tiles_total": 1, "tiles_completed": 1, "unsearched_tiles": 0, "tile_failures": [],++ "data_scope_complete": True, "all_event_groups_considered": True, "status": "complete", "event_groups_proposed": 1},++ "refined-candidates.json": {"ranked": [row], "matching_diagnostics": diagnostics},++ "decision.json": decision,++ }++ for name, value in values.items():++ save_json(directory / name, value)++ (directory / "intake/recording.f32").write_bytes(b"\0" * (32000 * 4))++ return directory, final, wire, {}++++++def test_complete_stage_evidence_keeps_inconclusive_decision(stage_evidence):++ directory, final, wire, operator = stage_evidence++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"], report++ assert report["full_pipeline_observed"] is True++ assert report["stages_verified"] == ["automatic_provenance", "intake", "discovery", "acquisition", "search", "refinement", "decision"]++ assert final["status"] == "inconclusive"++ assert report["location_accuracy_evaluated"] is False++ assert all(name in report["artifacts"] for name in STAGE_FILES)++++++def fixture_digest(value):++ return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest()++++++def write_fixture_ledger(path, run_hash, rows):++ """Write the documented retention format without calling the verifier or producer."""++ kind = rows[0]["score_kind"]++ checksums = {}++ with sqlite3.connect(path) as db:++ db.executescript("""++ CREATE TABLE run(identity TEXT, score_kind TEXT);++ CREATE TABLE stages(name TEXT PRIMARY KEY, checksum TEXT,++ occurrences INTEGER, duplicates INTEGER, kept TEXT);++ CREATE TABLE records(stage TEXT, mode_id TEXT, score REAL,++ groups_count INTEGER, kind TEXT, seed TEXT, PRIMARY KEY(stage,mode_id));++ """)++ db.execute("INSERT INTO run VALUES(?,?)", (run_hash, kind))++ for stage, values in (("coarse:0_0", rows), ("global:0_0", rows[:2])):++ records = sorted((row["mode_id"], float(row["score"]), 1, kind,++ json.dumps(row["mode_seed"], sort_keys=True, separators=(",", ":"))) for row in values)++ kept = sorted(row["mode_id"] for row in rows[:2])++ encoded = b"".join(json.dumps(record, separators=(",", ":"), allow_nan=False).encode() + b"\n"++ for record in records)++ encoded += json.dumps(kept, separators=(",", ":")).encode()++ encoded += json.dumps([len(records), 0]).encode()++ checksums[stage] = hashlib.sha256(encoded).hexdigest()++ db.executemany("INSERT INTO records VALUES(?,?,?,?,?,?)", [(stage, *record) for record in records])++ db.execute("INSERT INTO stages VALUES(?,?,?,?,?)",++ (stage, checksums[stage], len(records), 0, json.dumps(kept)))++ return checksums++++++def finite_stage_evidence(stage_evidence):++ """A finite metadata contract fixture, not a physical localization benchmark."""++ from dopplergeist import confidence++++ directory, final, wire, operator = stage_evidence++ manifest = json.loads((directory / "search/manifest.json").read_text())++ configuration = manifest["configuration"]++ configuration["budget"] = {"spacing_m": 1000.0, "refine_spacing_m": 100.0}++ configuration["scoring"].update(time_step_s=0.5, time_sweep_s=5.0)++ run_hash = fixture_digest(configuration)++ manifest["run_hash"] = run_hash++ save_json(directory / "search/manifest.json", manifest)++++ refinement = json.loads((directory / "refined-candidates.json").read_text())++ window = refinement["matching_diagnostics"]["recording_start_window_s"]++ sensitivity = {"complete": True, "boundary_limited": False, "radius_m": 50.0,++ "method": "fixture_full_perturbation", "kind": "sensitivity",++ "sources": ["frequency", "clock", "altitude", "sound_speed"],++ "settings": {"clock_bounds_s": window}}++ rows = []++ for latitude, score in ((40.0, -1.0), (40.003, -1.1), (45.0, -10.0)):++ row = deepcopy(refinement["ranked"][0])++ row.update(lat=latitude, score=score, pass_emission_times_s=[window[0] + 4.0],++ scoring_assessment={"complete": True, "scheduled_trials": 1, "evaluated_trials": 1,++ "rejected_trials": 0, "unknown_trials": 0, "unknown_reasons": {}, "empty_clock_domain": False},++ core_assessment_complete=True)++ row["event_diagnostics"][0]["score"] = score++ seed = {"event_indices": [0], "flight_ids": row["flight_ids"], "pass_emission_times_s": [window[0] + 4.0],++ "position": [0.0, 0.0, latitude, -100.0, 0.0], "recording_start_time_s": window[0]}++ row.update(mode_seed=seed, mode_id="mode-" + fixture_digest(seed))++ rows.append(row)++ rows[0]["sensitivity"] = sensitivity++ ids = [row["mode_id"] for row in rows[:2]]++ checksums = write_fixture_ledger(directory / "search/retention.sqlite", run_hash, rows)++ payload = {"ranked": rows[:2], "counts": {"unclassified_score_candidates": 0},++ "retention_checksum": checksums["coarse:0_0"]}++ save_json(directory / "search/tile-0_0.json",++ {"run_hash": run_hash, "payload": payload, "payload_hash": fixture_digest(payload)})++ finite = {"schema_version": 1, "scope": "evaluated_finite_grid", "ledger_artifact": "retention.sqlite",++ "complete": True, "pruning_accounted_for": True, "score_kind": rows[0]["score_kind"],++ "spacing_m": 1000.0, "refine_spacing_m": 100.0, "max_event_groups": 1,++ "retained_modes": [{"mode_id": row["mode_id"], "score": row["score"], "event_groups": 1} for row in rows[:2]],++ "evaluated_modes": 3, "discarded_count": 1, "best_discarded_score": -10.0,++ "discarded_bound_status": "finite", "unclassified_score_candidates": 0,++ "stages": {++ "coarse": {"stages": 1, "input_occurrences": 3, "exact_duplicates": 0, "retained": 2, "discarded": 1},++ "global": {"stages": 1, "input_occurrences": 2, "exact_duplicates": 0, "retained": 2, "discarded": 0}},++ "optimizer_domain": {"run_hash": run_hash, "source_fit_code_sha256": configuration["code"]["matching.py"],++ "score_code_sha256": configuration["code"]["search.py"], "clock_window_s": window,++ "time_step_s": 0.5, "declared_sweep_s": 5.0},++ "limitations": ["Finite metadata fixture; no physical trials independently reproduced."]}++ search = json.loads((directory / "search/search-report.json").read_text())++ search.update(run_hash=run_hash, ranked=rows[:2], core_assessed_mode_ids=ids,++ finite_search_evidence=finite, refinement_points_searched=0)++ save_json(directory / "search/search-report.json", search)++ diagnostics = refinement["matching_diagnostics"]++ diagnostics.update(sensitivity=sensitivity, refinement_boundary_limited=False, alternatives_evaluated=False,++ finite_search_evidence=finite, core_assessment_mapping_status="present",++ assessed_mode_ids=sorted(ids), candidate_mode_ids=ids)++ diagnostics[final["events"][0]["event_id"]] = rows[0]["event_diagnostics"][0]++ refinement["ranked"] = rows[:2]++ save_json(directory / "refined-candidates.json", refinement)++ candidates = []++ for row in rows[:2]:++ candidate = dict(final["candidates"][0], lat=row["lat"], score=row["score"])++ if "sensitivity" in row:++ candidate["uncertainty"] = {key: row["sensitivity"][key] for key in ("radius_m", "method", "kind")}++ candidates.append(candidate)++ decision = confidence.decide_location(final["events"], candidates, final["coverage"], matching_diagnostics=diagnostics)++ assert decision["status"] == "succeeded", decision++ final.update({key: value for key, value in decision.items() if key != "diagnostics"})++ save_json(directory / "decision.json", decision)++ provenance = json.loads((directory / "provenance.json").read_text())++ provenance.update(status=final["status"], search_run_hash=run_hash)++ save_json(directory / "provenance.json", provenance)++ return directory, final, wire, operator++++++def change_fixture_json(directory, name, change):++ path = directory / name++ value = json.loads(path.read_text())++ change(value)++ save_json(path, value)++++++def change_finite_claim(directory, change):++ change_fixture_json(directory, "search/search-report.json", lambda value: change(value["finite_search_evidence"]))++ change_fixture_json(directory, "refined-candidates.json",++ lambda value: change(value["matching_diagnostics"]["finite_search_evidence"]))++++++def test_finite_stage_reconstructs_predecision_union_and_preserves_ledger(finite_stage_evidence):++ directory, final, wire, operator = finite_stage_evidence++ ledger = directory / "search/retention.sqlite"++ before = ledger.read_bytes()++ decision = json.loads((directory / "decision.json").read_text())++ assert decision["diagnostics"]["finite_envelope"]["base_reported_radius_m"] == 50.0++ assert 333.0 < final["candidates"][0]["uncertainty"]["radius_m"] < 334.0++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"], report++ assert report["full_pipeline_observed"] is True++ assert report["finite_search_verified"] is True++ assert report["finite_search"] == {"ledger_verified": True, "complete": True,++ "retained_modes": 2, "evaluated_modes": 3, "discarded_count": 1,++ "best_discarded_score": -10.0, "unclassified_score_candidates": 0,++ "physical_trials_independently_recomputed": False}++ assert "search/retention.sqlite" in report["artifacts"]++ assert ledger.read_bytes() == before++++[email protected]("change,expected", [++ ({}, True),++ ({"scheduled_trials": 2}, False),++ ({"evaluated_trials": 0, "rejected_trials": 3}, False),++ ({"unknown_trials": 1, "scheduled_trials": 4}, False),++ ({"evaluated_trials": True}, False),++ ({"trial_count_semantics": "unknown_convention"}, False),++])++def test_finite_stage_checks_explicit_disjoint_trial_counts(finite_stage_evidence, change, expected):++ directory, final, wire, operator = finite_stage_evidence++ def change_assessment(search):++ assessment = search["ranked"][0]["scoring_assessment"]++ assessment.pop("unknown_reasons")++ assessment.update({"trial_count_semantics": "disjoint_evaluated_rejected_unknown",++ "scheduled_trials": 3, "evaluated_trials": 2, "rejected_trials": 1,++ "reasons": ["acoustic_loss_exceeds_limit"], **change})++ change_fixture_json(directory, "search/search-report.json", change_assessment)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is expected, report++ if not expected:++ assert "winner masks missing or unknown clock trials" in " ".join(report["errors"])++++[email protected]("kind,error", [++ ("missing", "search/retention.sqlite"), ("corrupt", "DatabaseError"),++ ("wrong_run", "another run"), ("checksum", "stage checksum"),++ ("groups", "group or association"), ("units", "mixed units"),++])++def test_finite_stage_rejects_unusable_or_inconsistent_ledger(finite_stage_evidence, kind, error):++ directory, final, wire, operator = finite_stage_evidence++ path = directory / "search/retention.sqlite"++ if kind == "missing":++ path.unlink()++ elif kind == "corrupt":++ path.write_bytes(b"not a sqlite retention database")++ else:++ statements = {"wrong_run": ("UPDATE run SET identity=?", ("0" * 64,)),++ "checksum": ("UPDATE stages SET checksum=?", ("0" * 64,)),++ "groups": ("UPDATE records SET groups_count=2", ()),++ "units": ("UPDATE records SET kind=?", ("incompatible_score_units",))}++ with sqlite3.connect(path) as db:++ db.execute(*statements[kind])++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert report["full_pipeline_observed"] is False++ assert error in " ".join(report["errors"])++++[email protected]("kind,error", [++ ("extra_field", "invalid physical fields"),++ ("nonfinite_position", "invalid physical fields"),++ ("boolean_clock", "invalid physical fields"),++ ("empty_flight", "invalid physical fields"),++ ("missing_pass", "group or association counts"),++])++def test_finite_stage_validates_discarded_physical_seeds(finite_stage_evidence, kind, error):++ directory, final, wire, operator = finite_stage_evidence++ with sqlite3.connect(directory / "search/retention.sqlite") as db:++ identity, encoded = db.execute(++ "SELECT mode_id,seed FROM records WHERE stage='coarse:0_0' ORDER BY score LIMIT 1").fetchone()++ seed = json.loads(encoded)++ if kind == "extra_field":++ seed["undeclared_origin"] = "not part of the seed contract"++ elif kind == "nonfinite_position":++ seed["position"][2] = float("inf")++ elif kind == "boolean_clock":++ seed["recording_start_time_s"] = True++ elif kind == "empty_flight":++ seed["flight_ids"] = [""]++ else:++ seed["pass_emission_times_s"] = []++ db.execute("UPDATE records SET seed=? WHERE mode_id=?", (json.dumps(seed), identity))++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert error in " ".join(report["errors"])++++[email protected]("kind", ["score", "score_kind", "physical_point", "copied_seed"])++def test_finite_coarse_payload_cannot_disagree_with_its_ledger(finite_stage_evidence, kind):++ directory, final, wire, operator = finite_stage_evidence++ def corrupt_payload(tile):++ row = tile["payload"]["ranked"][0]++ if kind == "score":++ row["score"] += 0.25++ elif kind == "score_kind":++ row["score_kind"] = "matched_group_support_minus_normalized_residual"++ elif kind == "physical_point":++ row["lat"] += 0.001++ else:++ row["mode_seed"]["position"][2] += 0.001++ tile["payload_hash"] = fixture_digest(tile["payload"])++ change_fixture_json(directory, "search/tile-0_0.json", corrupt_payload)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "Coarse checkpoint score or physical seed differs from its ledger" in " ".join(report["errors"])++++++def test_finite_refinement_work_requires_recorded_fine_stages(finite_stage_evidence):++ directory, final, wire, operator = finite_stage_evidence++ change_fixture_json(directory, "search/search-report.json", lambda search: search.update(refinement_points_searched=1))++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "fine" in " ".join(report["errors"]).lower()++++[email protected]("key,value,error", [++ ("best_discarded_score", -11.0, "discarded score bound"),++ ("discarded_count", 0, "distinct retention counts"),++ ("evaluated_modes", 2, "distinct retention counts"),++ ("max_event_groups", 2, "Finite group bound"),++ ("score_kind", "matched_group_support_minus_normalized_residual", "another run or score kind"),++ ("unclassified_score_candidates", 1, "discarded score bound"),++])++def test_finite_stage_recomputes_claims_from_recorded_modes(finite_stage_evidence, key, value, error):++ directory, final, wire, operator = finite_stage_evidence++ change_finite_claim(directory, lambda finite: finite.__setitem__(key, value))++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert error in " ".join(report["errors"])++++[email protected]("kind,error", [++ ("retained", "retained original scores or groups"),++ ("candidate", "wire candidates omit or invent"),++ ("assessed", "assessed IDs differ"),++ ("core", "assessed IDs differ"),++])++def test_finite_stage_rejects_omitted_mode_identities(finite_stage_evidence, kind, error):++ directory, final, wire, operator = finite_stage_evidence++ if kind == "retained":++ change_finite_claim(directory, lambda finite: finite["retained_modes"].pop())++ elif kind == "core":++ change_fixture_json(directory, "search/search-report.json", lambda search: search["core_assessed_mode_ids"].pop())++ else:++ key = "candidate_mode_ids" if kind == "candidate" else "assessed_mode_ids"++ change_fixture_json(directory, "refined-candidates.json",++ lambda refinement: refinement["matching_diagnostics"][key].pop())++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert error in " ".join(report["errors"])++++[email protected]("kind", ["swap_same_association_ids", "change_pass_emission_times"])++def test_finite_refinement_preserves_its_original_mode_lineage(finite_stage_evidence, kind):++ directory, final, wire, operator = finite_stage_evidence++ def change_lineage(refinement):++ first, second = refinement["ranked"]++ assert first["flight_ids"] == second["flight_ids"]++ assert first["event_indices"] == second["event_indices"]++ if kind == "swap_same_association_ids":++ first["mode_id"], second["mode_id"] = second["mode_id"], first["mode_id"]++ refinement["matching_diagnostics"]["candidate_mode_ids"] = [first["mode_id"], second["mode_id"]]++ else:++ first["pass_emission_times_s"] = [first["recording_start_time_s"] + 2.0]++ change_fixture_json(directory, "refined-candidates.json", change_lineage)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "borrowed another mode's event-to-flight identity" in " ".join(report["errors"])++++++def test_finite_refinement_cannot_replace_an_original_point_with_a_shifted_copy(finite_stage_evidence):++ from dopplergeist import confidence++++ directory, final, wire, operator = finite_stage_evidence++ refinement = json.loads((directory / "refined-candidates.json").read_text())++ shifted = refinement["ranked"][1]++ assert shifted["mode_seed"]["position"][2] == 40.003++ shifted["lat"] = 40.0001++ save_json(directory / "refined-candidates.json", refinement)++ candidates = deepcopy(final["candidates"])++ candidates[1]["lat"] = shifted["lat"]++ diagnostics = refinement["matching_diagnostics"]++ candidates[0]["uncertainty"] = {key: diagnostics["sensitivity"][key] for key in ("radius_m", "method", "kind")}++ decision = confidence.decide_location(final["events"], candidates, final["coverage"], matching_diagnostics=diagnostics)++ assert decision["status"] == "succeeded", decision++ assert decision["candidates"][0]["uncertainty"]["radius_m"] == 50.0++ final.update({key: value for key, value in decision.items() if key != "diagnostics"})++ save_json(directory / "decision.json", decision)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "omitted an original retained physical point" in " ".join(report["errors"])++++++def test_finite_winner_cannot_mask_an_unknown_scheduled_trial(finite_stage_evidence):++ directory, final, wire, operator = finite_stage_evidence++ def add_unknown(search):++ search["ranked"][0]["scoring_assessment"].update(complete=False, scheduled_trials=2,++ unknown_trials=1, unknown_reasons={"insufficient_track_support": 1})++ assert search["ranked"][0]["core_assessment_complete"] is True++ change_fixture_json(directory, "search/search-report.json", add_unknown)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "winner masks missing or unknown clock trials" in " ".join(report["errors"])++++++def test_finite_aggregate_cannot_omit_an_explicitly_unclassified_retained_mode(finite_stage_evidence):++ directory, final, wire, operator = finite_stage_evidence++ def hide_unknown_from_aggregate(search):++ search["ranked"][0]["scoring_assessment"].update(complete=False, scheduled_trials=2,++ unknown_trials=1, unknown_reasons={"insufficient_track_support": 1})++ search["ranked"][0]["core_assessment_complete"] = False++ search["core_assessed_mode_ids"] = [search["ranked"][1]["mode_id"]]++ assert search["finite_search_evidence"]["complete"] is True++ assert search["finite_search_evidence"]["unclassified_score_candidates"] == 0++ change_fixture_json(directory, "search/search-report.json", hide_unknown_from_aggregate)++ change_fixture_json(directory, "refined-candidates.json", lambda refinement:++ refinement["matching_diagnostics"].update(assessed_mode_ids=[refinement["ranked"][1]["mode_id"]]))++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "aggregate omits unclassified retained clock trials" in " ".join(report["errors"])++++[email protected]("change", [++ {"scheduled_trials": 2},++ {"evaluated_trials": True},++ {"rejected_trials": 2},++ {"unknown_reasons": {"unavailable_model": 1}},++ {"empty_clock_domain": True},++])++def test_finite_known_claim_requires_accounted_nonempty_clock_trials(finite_stage_evidence, change):++ directory, final, wire, operator = finite_stage_evidence++ change_fixture_json(directory, "search/search-report.json",++ lambda search: search["ranked"][0]["scoring_assessment"].update(change))++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "winner masks missing or unknown clock trials" in " ".join(report["errors"])++++++def test_honest_unknown_finite_trial_preserves_an_inconclusive_decision(finite_stage_evidence):++ from dopplergeist import confidence++++ directory, final, wire, operator = finite_stage_evidence++ change_finite_claim(directory, lambda finite: finite.update(complete=False, unclassified_score_candidates=1,++ best_discarded_score=None, discarded_bound_status="unknown_model_or_trial_support"))++ search = json.loads((directory / "search/search-report.json").read_text())++ best = search["ranked"][0]++ best["scoring_assessment"].update(complete=False, scheduled_trials=2, unknown_trials=1,++ unknown_reasons={"insufficient_track_support": 1})++ best["core_assessment_complete"] = False++ search["core_assessed_mode_ids"] = [search["ranked"][1]["mode_id"]]++ save_json(directory / "search/search-report.json", search)++ refinement = json.loads((directory / "refined-candidates.json").read_text())++ refinement["ranked"][0].update(scoring_assessment=best["scoring_assessment"], core_assessment_complete=False)++ diagnostics = refinement["matching_diagnostics"]++ diagnostics["assessed_mode_ids"] = search["core_assessed_mode_ids"]++ save_json(directory / "refined-candidates.json", refinement)++ tile = json.loads((directory / "search/tile-0_0.json").read_text())++ tile["payload"]["ranked"] = search["ranked"]++ tile["payload"]["counts"]["unclassified_score_candidates"] = 1++ tile["payload_hash"] = fixture_digest(tile["payload"])++ save_json(directory / "search/tile-0_0.json", tile)++ candidates = deepcopy(final["candidates"])++ candidates[0]["uncertainty"] = {key: diagnostics["sensitivity"][key] for key in ("radius_m", "method", "kind")}++ decision = confidence.decide_location(final["events"], candidates, final["coverage"], matching_diagnostics=diagnostics)++ decision.setdefault("candidates", candidates)++ assert decision["status"] == "inconclusive"++ assert decision["reason_code"] == "finite_search_incomplete"++ final.update({key: value for key, value in decision.items() if key != "diagnostics"})++ save_json(directory / "decision.json", decision)++ change_fixture_json(directory, "provenance.json", lambda provenance: provenance.update(status=final["status"]))++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"], report++ assert report["full_pipeline_observed"] is True++ assert report["finite_search_verified"] is False++ assert report["finite_search"]["ledger_verified"] is True++ assert report["finite_search"]["best_discarded_score"] is None++ assert report["finite_search"]["unclassified_score_candidates"] == 1++++++def test_finite_completeness_cannot_erase_a_coarse_unknown_trial(finite_stage_evidence):++ directory, final, wire, operator = finite_stage_evidence++ def add_unknown(tile):++ tile["payload"]["counts"]["unclassified_score_candidates"] = 1++ tile["payload_hash"] = fixture_digest(tile["payload"])++ change_fixture_json(directory, "search/tile-0_0.json", add_unknown)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "unknown-trial count is inconsistent" in " ".join(report["errors"])++++[email protected]("forged_radius", [50.0, 999.0])++def test_finite_stage_rejects_forged_union_in_consistent_terminal_copies(finite_stage_evidence, forged_radius):++ directory, final, wire, operator = finite_stage_evidence++ final["candidates"][0]["uncertainty"]["radius_m"] = forged_radius++ def forge(decision):++ decision["candidates"] = deepcopy(final["candidates"])++ decision["diagnostics"]["radius_m"] = forged_radius++ decision["diagnostics"]["finite_envelope"]["radius_m"] = forged_radius++ change_fixture_json(directory, "decision.json", forge)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "does not reproduce the persisted decision" in " ".join(report["errors"])++++[email protected]("null_finite", [False, True])++def test_legacy_supported_stage_evidence_requires_absent_finite_field(finite_stage_evidence, null_finite):++ from dopplergeist import confidence++++ directory, final, wire, operator = finite_stage_evidence++ search = json.loads((directory / "search/search-report.json").read_text())++ search.pop("finite_search_evidence")++ search["alternative_modes_exhaustively_assessed"] = True++ if null_finite:++ search["finite_search_evidence"] = None++ search.pop("core_assessed_mode_ids")++ search["ranked"] = search["ranked"][:1]++ save_json(directory / "search/search-report.json", search)++ refinement = json.loads((directory / "refined-candidates.json").read_text())++ refinement["ranked"] = refinement["ranked"][:1]++ diagnostics = refinement["matching_diagnostics"]++ for key in ("finite_search_evidence", "core_assessment_mapping_status", "candidate_mode_ids", "assessed_mode_ids"):++ diagnostics.pop(key)++ diagnostics["alternatives_evaluated"] = True++ save_json(directory / "refined-candidates.json", refinement)++ candidate = deepcopy(final["candidates"][0])++ candidate["uncertainty"] = {key: diagnostics["sensitivity"][key] for key in ("radius_m", "method", "kind")}++ decision = confidence.decide_location(final["events"], [candidate], final["coverage"], matching_diagnostics=diagnostics)++ decision.setdefault("candidates", [candidate])++ assert decision["status"] == "succeeded", decision++ final.update({key: value for key, value in decision.items() if key != "diagnostics"})++ save_json(directory / "decision.json", decision)++ (directory / "search/retention.sqlite").unlink()++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ if null_finite:++ assert report["passed"] is False++ assert "Search and refinement finite evidence differ" in " ".join(report["errors"])++ return++ assert report["passed"], report++ assert report["full_pipeline_observed"] is True++ assert "finite_search" not in report++ assert "finite_search_verified" not in report++++[email protected]("name", STAGE_FILES)++def test_scientific_result_requires_each_stage_artifact(stage_evidence, name):++ directory, final, wire, operator = stage_evidence++ (directory / name).unlink()++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert report["full_pipeline_observed"] is False++ assert name in " ".join(report["errors"])++++[email protected]("name", [name for name in STAGE_FILES if name.endswith(".json")])++def test_corrupt_stage_json_fails_closed(stage_evidence, name):++ directory, final, wire, operator = stage_evidence++ (directory / name).write_text('{"unfinished":')++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert any("JSONDecodeError" in error for error in report["errors"])++++[email protected]("name,key,value,error", [++ ("provenance.json", "operator_configuration_sha256", "0" * 64, "operator configuration"),++ ("intake/recording.json", "source_sha256", "0" * 64, "terminal recording"),++ ("intake/intake.json", "sample_count", 31999, "cache size"),++ ("discovery/discovery.json", "events", [], "source or events"),++ ("discovery/discovery.json", "chunks", [{"start_s": 1.0, "duration_s": 7.0}], "gap"),++ ("data-provenance.json", "flight_indexes", [{"input_hash": "0" * 64, "coverage": {}}], "flight inputs"),++ ("search/manifest.json", "run_hash", "0" * 64, "run identities"),++ ("search/search-report.json", "tiles_completed", 0, "unsearched-tile"),++ ("refined-candidates.json", "ranked", [], "candidate counts"),++ ("decision.json", "status", "succeeded", "terminal result"),++])++def test_stage_cross_links_reject_valid_but_inconsistent_json(stage_evidence, name, key, value, error):++ directory, final, wire, operator = stage_evidence++ path = directory / name++ changed = json.loads(path.read_text())++ changed[key] = value++ save_json(path, changed)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert error in " ".join(report["errors"])++++++def test_forged_success_cannot_reuse_an_inconclusive_scientific_decision(stage_evidence):++ directory, final, wire, operator = stage_evidence++ final["status"] = "succeeded"++ final["reason_code"] = "supported_by_evidence_checks"++ for name in ("provenance.json", "decision.json"):++ path = directory / name++ changed = json.loads(path.read_text())++ changed["status"] = final["status"]++ if name == "decision.json":++ changed["reason_code"] = final["reason_code"]++ save_json(path, changed)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "does not reproduce" in " ".join(report["errors"])++++++def test_symlinked_stage_artifact_is_rejected(stage_evidence, tmp_path):++ directory, final, wire, operator = stage_evidence++ target = directory / "decision.json"++ other = tmp_path / "outside-decision.json"++ target.rename(other)++ target.symlink_to(other)++ report = HTTP.inspect_pipeline_evidence(directory, final, wire, operator)++ assert report["passed"] is False++ assert "unsafe stage artifact" in " ".join(report["errors"])++++++def test_actual_http_success_does_not_mask_missing_pipeline_evidence(tmp_path, mp3, monkeypatch):++ inspect = HTTP.inspect_pipeline_evidence++ def remove_discovery_before_inspection(directory, final, wire, operator):++ (directory / "discovery/discovery.json").unlink()++ return inspect(directory, final, wire, operator)++ monkeypatch.setattr(HTTP, "inspect_pipeline_evidence", remove_discovery_before_inspection)++ receipt = HTTP.verify_http(mp3, tmp_path / "run", expect_status="needs_input",++ expect_reason="recording_time_required", timeout_s=60)++ assert receipt["http_checks_passed"] is True++ assert receipt["expectation_matched"] is True++ assert receipt["pipeline_evidence_passed"] is False++ assert receipt["verification_passed"] is False++ assert receipt["supported_decision"] is False++ assert receipt["service"]["returncode"] == 0++ report = json.loads((tmp_path / "run/pipeline-evidence.json").read_text())++ assert "discovery/discovery.json" in " ".join(report["errors"])