Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Validate complete trial and stage accounting (#13)
Cinna Daviscbd751aa2c56
diff --git a/scripts/verify_upload_http.py b/scripts/verify_upload_http.pyindex 83c7514..c857dc5 100644--- a/scripts/verify_upload_http.py+++ b/scripts/verify_upload_http.py@@ -211,7 +211,7 @@ def inspect_job(directory, final, wire, operator, original, implementation):"automatic_provenance_verified": True}-def complete_finite_clock_assessment(assessment):+def complete_finite_clock_assessment(assessment, *, allow_legacy=False):"""Validate a finite winner under the recorded trial-count convention."""if (not isinstance(assessment, dict) or assessment.get("complete") is not Trueor not all(type(assessment.get(key)) is int and assessment[key] >= 0@@ -224,7 +224,7 @@ def complete_finite_clock_assessment(assessment):return (assessment["scheduled_trials"] == assessment["evaluated_trials"] + assessment["rejected_trials"]and assessment.get("empty_clock_domain") is Falseand isinstance(reasons, list) and all(isinstance(reason, str) for reason in reasons))- if semantics is not None:+ if semantics is not None or not allow_legacy:return False# Historical #86 records count rejected trials inside evaluated_trials.return (assessment["scheduled_trials"] == assessment["evaluated_trials"]@@ -268,14 +268,14 @@ def model_assessment_accounted_for(search):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")+ "evaluated_trials", "rejected_trials", "unknown_trials", "unreported_trial_envelopes")if (not isinstance(support, dict)or not all(type(support.get(name)) is int and support[name] >= 0 for name in names)):return Falseif "model_assessment_complete" in search and search["model_assessment_complete"] is not True:return Falseif search.get("model_support_complete") is True:- return not any(support[name] for name in (names[0], names[1], "unknown_trials"))+ return not any(support[name] for name in (names[0], names[1], "unknown_trials", "unreported_trial_envelopes"))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@@ -328,10 +328,11 @@ def inspect_finite_search(artifact, read, search, configuration, refinement):by_id = dict(zip(identities, retained))totals, names, originals = {}, {}, {}evaluated = discarded = coarse_unknown = 0+ coarse_trials = dict(evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)bounded_count = bounded_rejections = 0bound = unknown_bound = Nonebound_fields = ("bounded_unknown_envelopes", "bounded_unknown_rejections", "best_unknown_score_upper_bound")- bound_contract = any(name in finite for name in bound_fields)+ bound_contract = any(name in finite for name in bound_fields) or "model_assessment_complete" in searchsupport_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)@@ -340,6 +341,7 @@ def inspect_finite_search(artifact, read, search, configuration, refinement):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+ bound_contract = bound_contract or has_boundsrequire(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(@@ -450,7 +452,29 @@ def inspect_finite_search(artifact, read, search, configuration, refinement):require(row["score"] == score and row.get("score_kind") == kindand 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)+ counts = payload.get("counts", {})+ if bound_contract:+ require("counts" in payload and isinstance(counts, dict), "Missing coarse model-support counts")+ empty_tile = (counts == {} and payload.get("grid_points") == 0 and count == 0+ and not payload["ranked"] and not stage_bounds)+ empty_cpa = (type(counts.get("cpa_rows")) is int and counts["cpa_rows"] == 0+ and type(counts.get("candidates")) is int and counts["candidates"] == 0+ and count == 0 and not payload["ranked"] and not stage_bounds)+ if not empty_tile:+ require(isinstance(counts.get("unsupported_cpa_tracks"), list)+ and all(isinstance(item, dict) for item in counts["unsupported_cpa_tracks"]),+ "Missing coarse unsupported-track diagnostics")+ if not (empty_tile or empty_cpa):+ require(all(type(counts.get(key)) is int and counts[key] >= 0 for key in+ ("cpa_rows", "candidates", "unclassified_score_candidates",+ "bounded_score_candidates", "unbounded_score_candidates", *coarse_trials))+ and isinstance(counts.get("unclassified_candidate_assessments"), list),+ "Coarse scoring work lacks explicit model-support counts")+ for key in coarse_trials:+ value = counts.get(key, 0)+ require(type(value) is int and value >= 0, "Invalid coarse clock-trial count")+ coarse_trials[key] += value+ unknown = counts.get("unclassified_score_candidates", 0)require(type(unknown) is int and unknown >= 0, "Invalid coarse unknown-trial count")coarse_unknown += unknownif bound_contract and phase in {"coarse", "fine"}:@@ -527,6 +551,9 @@ def inspect_finite_search(artifact, read, search, configuration, refinement):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")+ require(all(type(support.get(key)) is int and support[key] >= value+ for key, value in coarse_trials.items()),+ "Search model-support totals omit recorded coarse clock trials")all_unknown_accounted = model_assessment_accounted_for(search)require(type(search.get("model_assessment_complete")) is booland search["model_assessment_complete"] == all_unknown_accounted,@@ -549,7 +576,7 @@ def inspect_finite_search(artifact, read, search, configuration, refinement):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)+ known = complete_finite_clock_assessment(assessment, allow_legacy=not bound_contract)require(row.get("core_assessment_complete") is known, "Finite winner masks missing or unknown clock trials")unknown_retained += not knownif known:diff --git a/src/dopplergeist/finite_search.py b/src/dopplergeist/finite_search.pyindex f2ad625..8ef0816 100644--- a/src/dopplergeist/finite_search.py+++ b/src/dopplergeist/finite_search.py@@ -35,13 +35,20 @@ def classified_assessment(row):assessment = row.get("scoring_assessment")valid = (isinstance(assessment, dict) and assessment.get("complete") is Trueand all(type(assessment.get(k)) is int and assessment[k] >= 0- for k in ("evaluated_trials", "rejected_trials", "unknown_trials"))+ for k in ("scheduled_trials", "evaluated_trials", "rejected_trials", "unknown_trials"))+ and assessment["scheduled_trials"] > 0+ and assessment["scheduled_trials"] == sum(assessment[k] for k in+ ("evaluated_trials", "rejected_trials", "unknown_trials"))+ and assessment.get("trial_count_semantics") == "disjoint_evaluated_rejected_unknown"+ and assessment.get("empty_clock_domain") is Falseand 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)+ if not isinstance(score, (int, float)) or isinstance(score, bool):+ return Falsereturn (assessment["evaluated_trials"] > 0 if math.isfinite(score) elsescore == -math.inf and assessment["evaluated_trials"] == 0 and assessment["rejected_trials"] > 0)diff --git a/tests/test_finite_bridge_independent.py b/tests/test_finite_bridge_independent.pyindex ff18682..4affadb 100644--- a/tests/test_finite_bridge_independent.py+++ b/tests/test_finite_bridge_independent.py@@ -40,8 +40,10 @@ def test_actual_retention_evidence_survives_the_product_boundary(tmp_path, case,"event_indices": [0, 1], "pass_emission_times_s": [1790000010., 1790000110.],"score": score, "score_kind": "negative_robust_ridge_loss_hz","event_diagnostics": [dict(fit), dict(fit)], "sensitivity": deepcopy(profile),- "scoring_assessment": {"complete": True, "evaluated_trials": 2,- "rejected_trials": 1, "unknown_trials": 0, "reasons": []}}+ "scoring_assessment": {"complete": True, "scheduled_trials": 3, "evaluated_trials": 2,+ "rejected_trials": 1, "unknown_trials": 0, "reasons": [],+ "empty_clock_domain": False,+ "trial_count_semantics": "disjoint_evaluated_rejected_unknown"}}rows.append(row)ledger = RetentionLedger(tmp_path / "retention.sqlite", "independent-bridge", rows[0]["score_kind"])kept = merge_candidates(rows, 2, ledger=ledger, stage="coarse:0")@@ -52,7 +54,7 @@ def test_actual_retention_evidence_survives_the_product_boundary(tmp_path, case,finite = ledger.evidence(kept, complete=True, spacing_m=1000., refine_spacing_m=100.,max_event_groups=2, expected_stages={"coarse": 1, "global": 1})if case == "unassessed":- kept[1]["scoring_assessment"].update(complete=False, unknown_trials=1)+ kept[1]["scoring_assessment"].update(complete=False, scheduled_trials=4, unknown_trials=1)assessed = [r["mode_id"] for r in kept if classified_assessment(r)]search = {"ranked": kept, "status": "complete", "scoring_time_is_locked": True,"alternative_modes_exhaustively_assessed": False,diff --git a/tests/test_finite_search.py b/tests/test_finite_search.pyindex dd11b5b..fd6dbc4 100644--- a/tests/test_finite_search.py+++ b/tests/test_finite_search.py@@ -91,15 +91,29 @@ def test_ledger_rejects_wrong_run_or_score_units_and_missing_stages(tmp_path):def test_a_finite_best_score_does_not_hide_unknown_optimizer_trials():- good = {"complete": True, "evaluated_trials": 5, "rejected_trials": 2, "unknown_trials": 0}+ good = {"complete": True, "scheduled_trials": 7, "evaluated_trials": 5,+ "rejected_trials": 2, "unknown_trials": 0, "empty_clock_domain": False,+ "trial_count_semantics": "disjoint_evaluated_rejected_unknown"}assert classified_assessment({"score": .9, "scoring_assessment": good})assert not classified_assessment({"score": .9})- for change in [{"complete": False}, {"unknown_trials": 1}, {"evaluated_trials": None}, {"rejected_trials": -1}]:+ for change in [{"complete": False}, {"unknown_trials": 1}, {"evaluated_trials": None},+ {"rejected_trials": -1}, {"scheduled_trials": 8}, {"scheduled_trials": 0},+ {"empty_clock_domain": True}, {"empty_clock_domain": 0},+ {"trial_count_semantics": "evaluated_includes_rejected"}]:assert not classified_assessment({"score": .9, "scoring_assessment": dict(good, **change)})- for score in [float("nan"), float("inf"), -float("inf")]:+ for key in ("scheduled_trials", "evaluated_trials", "rejected_trials", "unknown_trials"):+ assert not classified_assessment({"score": .9, "scoring_assessment": dict(good, **{key: True})})+ for key in ("scheduled_trials", "empty_clock_domain", "trial_count_semantics"):+ missing = dict(good)+ del missing[key]+ assert not classified_assessment({"score": .9, "scoring_assessment": missing})+ for score in [float("nan"), float("inf"), -float("inf"), True, None, "0.9", []]:assert not classified_assessment({"score": score, "scoring_assessment": good})- empty = dict(good, evaluated_trials=0, rejected_trials=0)+ empty = dict(good, scheduled_trials=0, evaluated_trials=0, rejected_trials=0)assert not classified_assessment({"score": .9, "scoring_assessment": empty})assert not classified_assessment({"score": -float("inf"), "scoring_assessment": empty})- rejected = dict(empty, rejected_trials=3)+ rejected = dict(empty, scheduled_trials=3, rejected_trials=3)assert classified_assessment({"score": -float("inf"), "scoring_assessment": rejected})+ assert not classified_assessment({"score": .9, "scoring_assessment": rejected})+ assert not classified_assessment({"score": -float("inf"),+ "scoring_assessment": dict(rejected, scheduled_trials=4)})diff --git a/tests/test_tiled_search.py b/tests/test_tiled_search.pyindex 9ce08ca..c1e982c 100644--- a/tests/test_tiled_search.py+++ b/tests/test_tiled_search.py@@ -307,8 +307,11 @@ def test_successful_best_row_with_unknown_trials_has_no_optimistic_finite_bound(def incomplete(*args, **kwargs):result = original(*args, **kwargs)- result["scoring_assessment"] = {"complete": False, "evaluated_trials": 1, "rejected_trials": 0,- "unknown_trials": 1, "reasons": ["test_missing_support"]}+ result["scoring_assessment"] = {"complete": False, "scheduled_trials": 2,+ "evaluated_trials": 1, "rejected_trials": 0, "unknown_trials": 1,+ "empty_clock_domain": False,+ "trial_count_semantics": "disjoint_evaluated_rejected_unknown",+ "reasons": ["test_missing_support"]}return resultmonkeypatch.setattr(tiled_search, "score_candidate", incomplete)@@ -331,8 +334,11 @@ def test_evaluated_acoustic_rejection_is_distinct_from_unknown_support(tmp_path,def rejected(*args, **kwargs):result = original(*args, **kwargs)- result.update(score=-np.inf, scoring_assessment={"complete": True, "evaluated_trials": 0,- "rejected_trials": 1, "unknown_trials": 0, "reasons": ["test_admissible_rejection"]})+ result.update(score=-np.inf, scoring_assessment={"complete": True, "scheduled_trials": 1,+ "evaluated_trials": 0, "rejected_trials": 1, "unknown_trials": 0,+ "empty_clock_domain": False,+ "trial_count_semantics": "disjoint_evaluated_rejected_unknown",+ "reasons": ["test_admissible_rejection"]})return resultmonkeypatch.setattr(tiled_search, "score_candidate", rejected)diff --git a/tests/test_verify_bounded_search.py b/tests/test_verify_bounded_search.pyindex 1075b47..6b62eb2 100644--- a/tests/test_verify_bounded_search.py+++ b/tests/test_verify_bounded_search.py@@ -57,7 +57,9 @@ def bounded_search(tmp_path):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": {+ payload = {"ranked": rows[:2], "grid_points": 5, "tracks": 2, "retention_checksum": checksum, "counts": {+ "cpa_rows": 5, "candidates": 5, "evaluated_trials": 3, "rejected_trials": 0,+ "unknown_trials": 2, "unreported_trial_envelopes": 0,"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(@@ -148,3 +150,58 @@ def test_clock_bound_certificate_requires_every_unknown_trial(bounded_search, kedetail = json.loads(path.read_text())["unclassified_candidate_assessments"][0]detail["scoring_assessment"][key] = valueassert HTTP.bounded_finite_clock_assessment(detail, 1) is False++[email protected]("key", ["unclassified_score_candidates", "unsupported_cpa_tracks",+ "bounded_score_candidates", "unknown_trials", "unreported_trial_envelopes",+ "unclassified_candidate_assessments"])+def test_nonempty_bounded_stage_requires_explicit_support_counts(bounded_search, key):+ path = bounded_search[0] / "search/tile-0_0.json"+ value = json.loads(path.read_text())+ value["payload"]["counts"].pop(key)+ value["payload_hash"] = content_hash(value["payload"])+ path.write_text(json.dumps(value))+ with pytest.raises(ValueError, match="[Cc]oarse"):+ inspect(bounded_search)++[email protected]("key", ["evaluated_trials", "rejected_trials", "unknown_trials", "unreported_trial_envelopes"])+def test_aggregate_cannot_omit_recorded_coarse_trials(bounded_search, key):+ path = bounded_search[0] / "search/tile-0_0.json"+ value = json.loads(path.read_text())+ value["payload"]["counts"][key] += 1+ value["payload_hash"] = content_hash(value["payload"])+ path.write_text(json.dumps(value))+ with pytest.raises(ValueError, match="totals omit recorded coarse clock trials"):+ inspect(bounded_search)+++def test_new_ledger_cannot_select_historical_trial_semantics(bounded_search):+ assessment = bounded_search[1]["ranked"][0]["scoring_assessment"]+ assessment.pop("trial_count_semantics")+ assessment["unknown_reasons"] = {}+ with pytest.raises(ValueError, match="winner masks missing or unknown clock trials"):+ inspect(bounded_search)+++def test_bounds_table_requires_new_summary_fields_even_if_flags_are_removed(bounded_search):+ _, search, _, refinement = bounded_search+ for target in (search["finite_search_evidence"], refinement["matching_diagnostics"]["finite_search_evidence"]):+ for key in ("bounded_unknown_envelopes", "bounded_unknown_rejections", "best_unknown_score_upper_bound"):+ target.pop(key)+ search.pop("model_assessment_complete")+ with pytest.raises(ValueError, match="bound table or aggregate fields"):+ inspect(bounded_search)++[email protected]("value", [None, True, -1, 1])+def test_supported_model_cannot_hide_missing_trial_accounting(bounded_search, value):+ search = deepcopy(bounded_search[1])+ search["model_support_complete"] = True+ search["model_support"].update(unclassified_score_candidates=0, unknown_trials=0,+ bounded_score_candidates=0, unbounded_score_candidates=0)+ if value is None:+ search["model_support"].pop("unreported_trial_envelopes")+ else:+ search["model_support"]["unreported_trial_envelopes"] = value+ assert HTTP.model_assessment_accounted_for(search) is False