Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Add exact finite-mode identities and disk-backed retention accounting (#7)
Cinna Davisfda484f2f1f0
diff --git a/docs/FINITE_SEARCH_PRODUCER.md b/docs/FINITE_SEARCH_PRODUCER.mdnew file mode 100644index 0000000..097a70b--- /dev/null+++ b/docs/FINITE_SEARCH_PRODUCER.md@@ -0,0 +1,54 @@+# Finite receiver-grid evidence producer++This is the W2 side of the agreed+[finite-search contract](https://github.com/1337isnot1337/DOPPLERGEIST/discussions/39#discussioncomment-19363838).+It does not change the strict request, candidate or JobResult dictionaries.+W4 interprets the artifact and W5 forwards it with ID mappings.++Each finite core row carries `mode_id` and its original `mode_seed`. Identity+contains exact event indices, flight IDs and pass emission times, receiver+coordinates/elevation and the best shared recording clock. No approximate+coordinate/time rounding or association-only collapse is an exact duplicate.+Refinement/profile may preserve the seed ID while returning a new representation;+the original seed remains explicit. A mismatched ID/seed fails validation.++`retention.sqlite` is an input/code/run-bound disk ledger. Before every tile,+global, coarse or fine top-k truncation, it records each distinct finite scored+seed, units and maximum score. Exact duplicate IDs retain their maximum and are+counted separately. The final distinct discarded count and maximum discarded+score include modes removed at any level, excluding IDs still retained at the end.+Per-phase occurrence/dedup/retention/drop counts are in the report; individual+stage records remain on disk. Writes and audits use bounded stage buffers,+SQLite's file-backed temporary storage and streaming stage checks rather than an+in-memory national list. A missing ledger causes affected cached tiles to be+rescored; changed/corrupt/unaccounted stages cannot become zero discards.++The report exposes `finite_search_evidence` with the agreed version-one fields:+scope `evaluated_finite_grid`, completion/pruning flags, score kind, resolutions,+maximum independent-group count, retained ID/score/group records, distinct drop+count, best discarded bound and limitations. It also records the exact optimizer+inputs and pinned implementation hashes, plus `core_assessed_mode_ids`.+W5 provides `candidate_mode_ids` parallel to wire candidates and actually assessed+IDs in matching diagnostics; it must retain all seed identities and baseline+scores, including distinct spatial/clock competitors with the same flights.++The point score is an envelope over the declared bounded shared-clock and+frequency/drift evaluations at that fixed location/pass association. Lower known+clock trials there need not be separate geolocation rows. This does not establish+a unique clock, continuous optimum, off-grid uniqueness, or a bound under another+context/scoring model. Unperformed refinements and profiles have no inferred+upper score. The leading result still needs the complete declared sensitivity,+datum, support and boundary evidence required by W4.++W3's `scoring_assessment` must distinguish complete evaluated/admissibly rejected+trials from unknown model/support/optimizer work. Missing or malformed metadata,+or any unknown trial, makes that envelope unassessed even if its best returned row+is finite. W2 withholds its assessed ID and any optimistic discarded bound and+marks finite evidence incomplete. A fully classified poor fit may be rejected+without pretending an unknown failure was measured. The old+`alternative_modes_exhaustively_assessed` flag stays false and old outcomes remain+frozen.++Tests compare the tiled discard bound with a full untiled reference, verify+resume/missing/corrupt-ledger behavior, exercise exact identity and repeated+approaches, and prevent a successful best row from hiding unknown clock trials.diff --git a/src/aircraft_geoloc/finite_search.py b/src/aircraft_geoloc/finite_search.pynew file mode 100644index 0000000..f4df1da--- /dev/null+++ b/src/aircraft_geoloc/finite_search.py@@ -0,0 +1,170 @@+"""Exact finite-seed identity and disk-backed scored-retention accounting."""+import hashlib+import json+import math+from contextlib import contextmanager+from pathlib import Path+import sqlite3++from .data_access import DataUnavailable, content_hash+++def mode_seed(row):+ def number(value):+ value = float(value)+ if not math.isfinite(value):+ raise ValueError("Finite mode seeds require finite coordinates and times")+ return 0.0 if value == 0 else value+ return {"event_indices": [int(i) for i in row.get("event_indices", range(len(row["flight_ids"])))],+ "flight_ids": list(row["flight_ids"]),+ "pass_emission_times_s": [number(t) for t in row.get("pass_emission_times_s", [])],+ "position": [number(row.get(k, 0)) for k in ("x", "y", "lat", "lon", "elev_m")],+ "recording_start_time_s": number(row["recording_start_time_s"])}+++def identify_mode(row):+ seed = row.get("mode_seed") or mode_seed(row)+ identifier = "mode-" + content_hash(seed)+ if row.get("mode_id", identifier) != identifier:+ raise DataUnavailable("Mode ID does not match its original seed identity")+ row["mode_seed"], row["mode_id"] = seed, identifier+ return identifier+++def classified_assessment(row):+ assessment = row.get("scoring_assessment")+ return (isinstance(assessment, dict) and assessment.get("complete") is True+ and all(type(assessment.get(k)) is int and assessment[k] >= 0+ for k in ("evaluated_trials", "rejected_trials", "unknown_trials"))+ and assessment["unknown_trials"] == 0)+++class RetentionLedger:+ """One immutable-input run; bounded per-stage writes and streaming audits.++ Store every finite scored mode before top-k pruning. Stage rows are replaced+ on deterministic replay, so resumed work cannot inflate counts. Exact IDs+ appearing at several stages are aggregated by their maximum scored value.+ """+ def __init__(self, path, run_hash, score_kind):+ self.path, self.run_hash, self.score_kind = Path(path), run_hash, score_kind+ self.path.parent.mkdir(parents=True, exist_ok=True)+ try:+ with self.connect() as db:+ db.executescript("""+ PRAGMA cache_size=-8192; PRAGMA temp_store=FILE;+ CREATE TABLE IF NOT EXISTS run(identity TEXT, score_kind TEXT);+ CREATE TABLE IF NOT EXISTS stages(name TEXT PRIMARY KEY, checksum TEXT,+ occurrences INTEGER, duplicates INTEGER, kept TEXT);+ 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);+ """)+ if db.execute("PRAGMA quick_check").fetchone()[0] != "ok":+ raise DataUnavailable("Corrupt finite retention ledger")+ identity = db.execute("SELECT identity,score_kind FROM run").fetchone()+ if identity is None:+ db.execute("INSERT INTO run VALUES(?,?)", (run_hash, score_kind))+ elif identity != (run_hash, score_kind):+ raise DataUnavailable("Finite ledger input/score identity mismatch")+ except sqlite3.DatabaseError as error:+ raise DataUnavailable("Cannot read finite retention ledger") from error++ @contextmanager+ def connect(self):+ db = sqlite3.connect(self.path)+ db.execute("PRAGMA cache_size=-8192")+ db.execute("PRAGMA temp_store=FILE")+ try:+ with db:+ yield db+ finally:+ db.close()++ @staticmethod+ def _checksum(records, kept, occurrences, duplicates):+ 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())+ return digest.hexdigest()++ def record(self, stage, rows, kept, occurrences):+ records = []+ for row in rows:+ identifier = identify_mode(row)+ kind = row.get("score_kind", self.score_kind)+ if kind != self.score_kind:+ raise DataUnavailable("Finite retention mixed incompatible score units")+ records.append((identifier, float(row["score"]), len(row["mode_seed"]["event_indices"]), kind,+ json.dumps(row["mode_seed"], sort_keys=True, separators=(",", ":"))))+ records.sort()+ kept_ids = [identify_mode(row) for row in kept]+ checksum = self._checksum(records, kept_ids, occurrences, occurrences-len(records))+ with self.connect() as db:+ db.execute("DELETE FROM records WHERE stage=?", (stage,))+ db.executemany("INSERT INTO records VALUES(?,?,?,?,?,?)", [(stage, *r) for r in records])+ db.execute("INSERT OR REPLACE INTO stages VALUES(?,?,?,?,?)",+ (stage, checksum, occurrences, occurrences-len(records), json.dumps(sorted(kept_ids))))+ return checksum++ def checksum(self, stage):+ with self.connect() as db:+ row = db.execute("SELECT checksum FROM stages WHERE name=?", (stage,)).fetchone()+ return row[0] if row else None++ def stage_valid(self, stage, expected):+ try:+ with self.connect() as db:+ record = db.execute("SELECT checksum,kept,occurrences,duplicates FROM stages WHERE name=?", (stage,)).fetchone()+ if record is None or record[0] != expected:+ return False+ rows = 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+ except (sqlite3.DatabaseError, ValueError, TypeError) as error:+ raise DataUnavailable("Corrupt finite retention stage") from error++ def evidence(self, retained, *, complete, spacing_m, refine_spacing_m, max_event_groups, expected_stages=None):+ ids = [identify_mode(row) for row in retained]+ accounted = True+ totals = {}+ with self.connect() as db:+ stages = db.execute("SELECT name,checksum,occurrences,duplicates,kept FROM stages ORDER BY name")+ for name, checksum, occurrences, duplicates, kept in stages:+ if not self.stage_valid(name, checksum):+ accounted = False+ phase = name.split(":", 1)[0]+ total = totals.setdefault(phase, {"stages": 0, "input_occurrences": 0, "exact_duplicates": 0,+ "retained": 0, "discarded": 0})+ retained_count = len(json.loads(kept))+ for key, value in (("stages", 1), ("input_occurrences", occurrences), ("exact_duplicates", duplicates),+ ("retained", retained_count), ("discarded", occurrences-duplicates-retained_count)):+ total[key] += value+ db.execute("CREATE TEMP TABLE retained_ids(id TEXT PRIMARY KEY)")+ db.executemany("INSERT INTO retained_ids VALUES(?)", [(i,) for i in ids])+ distinct = "SELECT mode_id,MAX(score) AS score FROM records GROUP BY mode_id"+ discarded, bound = db.execute(f"SELECT count(*),max(score) FROM ({distinct}) WHERE mode_id NOT IN (SELECT id FROM retained_ids)").fetchone()+ 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)")}+ if set(original) != set(ids):+ accounted = False+ if expected_stages is not None:+ actual = {phase: totals.get(phase, {}).get("stages", 0) for phase in expected_stages}+ if actual != expected_stages or set(totals)-set(expected_stages):+ accounted = False+ if not accounted:+ discarded, bound, evaluated, original = None, None, None, {}+ return {"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,+ "retained_modes": [{"mode_id": row["mode_id"], "score": original.get(row["mode_id"], row["score"]),+ "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,+ "stages": totals,+ "limitations": ["Evaluated grids and recorded refinements only; continuous-space uniqueness is not established.",+ "Unvisited positions and unperformed refinements have no inferred score bound.",+ "Proposal envelopes, CPA tolerances, grouping, clock bounds and physical model are declared assumptions."]}diff --git a/src/aircraft_geoloc/tiled_search.py b/src/aircraft_geoloc/tiled_search.pyindex 96d9a91..6203e70 100644--- a/src/aircraft_geoloc/tiled_search.py+++ b/src/aircraft_geoloc/tiled_search.py@@ -16,6 +16,7 @@ import pandas as pdfrom pyproj import Transformerfrom .data_access import CONUS, DataUnavailable, content_hash, sha256, write_json+from .finite_search import RetentionLedger, classified_assessment, identify_mode, mode_seedfrom .search import cpa_table, filter_event, pair_candidates, score_candidate@@ -47,20 +48,26 @@ class SearchBudget:def _key(row):# Distinct approaches remain distinct even when they share flight IDs.- return (tuple(row.get("event_indices", range(len(row["flight_ids"])))), tuple(row["flight_ids"]),- tuple(round(t, 3) for t in row.get("pass_emission_times_s", [])),- round(row["x"], 6), round(row["y"], 6), round(row["recording_start_time_s"], 6))+ seed = row.get("mode_seed") or mode_seed(row)+ return (tuple(seed["event_indices"]), tuple(seed["flight_ids"]), tuple(seed["pass_emission_times_s"]),+ tuple(seed["position"]), seed["recording_start_time_s"])-def merge_candidates(rows, top_k):- unique = {}+def merge_candidates(rows, top_k, *, ledger=None, stage=None):+ unique, occurrences = {}, 0for row in rows:if not math.isfinite(row["score"]):continue- key = _key(row)+ occurrences += 1+ key = identify_mode(row)if key not in unique or row["score"] > unique[key]["score"]:unique[key] = row- return sorted(unique.values(), key=lambda row: (-row["score"], _key(row)))[:top_k]+ kept = sorted(unique.values(), key=lambda row: (-row["score"], _key(row)))[:top_k]+ 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)+ return keptdef _grid_extent(bounds, spacing_m, crs):@@ -120,7 +127,7 @@ def _tracks(indexes, bounds, time_range, budget):return tracks-def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None):+def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None, *, ledger=None, stage=None):radius = max(e["slant_range_m"][1] for e in events)tables, count = [], 0# Bound materialized CPA rows before pairing; one track at a time keeps the@@ -140,6 +147,8 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, stif len(table):tables.append(table)if not tables:+ if ledger is not None:+ ledger.record(stage, [], [], 0)return [], {"cpa_rows": 0, "candidates": 0}table = pd.concat(tables, ignore_index=True)kwargs = dict(offset_tolerance_s=filters.get("offset_tolerance_s", 5.0),@@ -158,7 +167,7 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, straise DataUnavailable("Tile candidate memory budget exceeded; reduce tile_cells")candidates, counts = pair_candidates(table, events, **kwargs)# Attach approach identities before scoring, since legacy rank drops passes.- ranked = []+ ranked, unclassified, rejected = [], 0, 0lookup = {row.point_id: row for row in points.itertuples()}track_lookup = {track.id: track for track in tracks}for candidate in candidates:@@ -185,8 +194,18 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, stsettings.update(time_origin=(lo + hi) / 2, time_sweep_s=(hi - lo) / 2)row = score_candidate(scoring_candidate, lookup[candidate["point_id"]], track_lookup, events, measurements, **settings)row["pass_emission_times_s"] = [float(p["emission_time"]) for p in candidate["passes"]]- ranked.append(row)- return merge_candidates(ranked, budget.top_k), dict(counts, cpa_rows=count, candidates=len(candidates))+ known = (classified_assessment(row) if settings.get("mode") == "robust_ridge" else+ settings.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 not known:+ unclassified += 1+ if math.isfinite(row["score"]):+ ranked.append(row)+ elif known:+ rejected += 1+ kept = merge_candidates(ranked, budget.top_k, ledger=ledger, stage=stage)+ return kept, dict(counts, cpa_rows=count, candidates=len(candidates), unclassified_score_candidates=unclassified,+ evaluated_rejections=rejected)def search_national(indexes, terrain, events, measurements, *, time_range_s, output_dir,@@ -248,7 +267,13 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif manifest.exists() and json.loads(manifest.read_text())["run_hash"] != run_hash:raise DataUnavailable("Checkpoint configuration/input/implementation mismatch; use a new output directory")write_json(manifest, {"run_hash": run_hash, "configuration": identity})+ mode = parameters.get("mode", "brightness")+ score_kind = ("matched_group_support_minus_normalized_residual" if mode == "robust_ridge" and filters["association"] == "subsets"+ else {"robust_ridge": "negative_robust_ridge_loss_hz", "ridge": "negative_ridge_rmse_hz",+ "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 = 0xmin, 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)@@ -256,34 +281,47 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif budget.max_tiles is not None and number >= budget.max_tiles:breakcheckpoint = output / f"tile-{tile_id}.json"+ stage = f"coarse:{tile_id}"try:+ payload = Noneif checkpoint.exists():record = json.loads(checkpoint.read_text())if record["run_hash"] != run_hash or record["payload_hash"] != content_hash(record["payload"]):raise DataUnavailable("Corrupt tile checkpoint")- payload = record["payload"]- for source in payload.get("terrain_files", []):+ cached = record["payload"]+ for source in cached.get("terrain_files", []):if sha256(source["path"]) != source["sha256"]:raise DataUnavailable("Terrain changed since tile checkpoint")- resumed += 1- else:+ if ledger.stage_valid(stage, cached.get("retention_checksum")):+ payload = cached+ resumed += 1+ if payload is None:tracks = _tracks(indexes, _expanded_bounds(cells, budget.spacing_m, radius, crs), time_range_s, budget)points = tile_points(cells, budget.spacing_m, bounds, terrain, crs) if tracks else pd.DataFrame()- rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window) if len(points) else ([], {})+ if len(points):+ rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,+ ledger=ledger, stage=stage)+ else:+ rows, counts = [], {}+ ledger.record(stage, [], [], 0)used = getattr(terrain, "last_sample_files", set()) if len(points) else set()terrain_files = [terrain.files[name] for name in sorted(used)] if used else []payload = {"ranked": rows, "counts": counts, "grid_points": len(points), "tracks": len(tracks),- "cells": list(cells), "terrain_files": terrain_files}+ "cells": list(cells), "terrain_files": terrain_files,+ "retention_checksum": ledger.checksum(stage)}write_json(checkpoint, {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload})done += 1points_searched += payload["grid_points"]- ranked = merge_candidates(itertools.chain(ranked, payload["ranked"]), budget.top_k)+ unclassified_scores += payload["counts"].get("unclassified_score_candidates", 0)+ ranked = merge_candidates(itertools.chain(ranked, payload["ranked"]), budget.top_k,+ ledger=ledger, stage=f"global:{tile_id}")except (DataUnavailable, ValueError, OSError) as error:failures.append({"tile": tile_id, "reason": str(error)})coarse = list(ranked)# Refine only global finalists; tile selection never controls refinement rank.refinement_failure = Nonerefinement_points_searched, refinement_points_skipped = 0, 0+ fine_stages = 0if ranked and budget.refine_spacing_m < budget.spacing_m:chosen, seen = [], set()for row in ranked:@@ -297,7 +335,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outfine = budget.refine_spacing_mwidth = math.ceil(budget.spacing_m / fine)completed_rectangles = []- for row in chosen:+ for seed_index, row in enumerate(chosen):# Subdivide the refinement square as well, retaining hard grid limits.cx, cy = round(row["x"] / fine), round(row["y"] / fine)for y0 in range(cy - width, cy + width + 1, budget.tile_cells):@@ -313,9 +351,14 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif not len(points):continuetracks = _tracks(indexes, _expanded_bounds(cells, fine, radius, crs), time_range_s, budget)- rows, _ = _score(points, tracks, events, measurements, budget, parameters, filters, start_window)+ stage = f"fine:{seed_index}:{x0}:{y0}"+ rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,+ ledger=ledger, stage=stage)+ unclassified_scores += counts.get("unclassified_score_candidates", 0)+ fine_stages += 1refinement_points_searched += len(points)- ranked = merge_candidates(itertools.chain(ranked, rows), budget.top_k)+ ranked = merge_candidates(itertools.chain(ranked, rows), budget.top_k,+ ledger=ledger, stage=f"fine-global:{seed_index}:{x0}:{y0}")completed_rectangles.append((cx - width, cy - width, cx + width + 1, cy + width + 1))except (DataUnavailable, ValueError, OSError) as error:refinement_failure = str(error)@@ -336,6 +379,23 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outcovered_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,+ 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:+ finite["best_discarded_score"] = None+ finite["discarded_bound_status"] = "unknown_model_or_trial_support"+ finite["limitations"].append("Unclassified or unsupported optimizer trials have no known upper score bound.")+ 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",+ "event_settings": [{"event_index": i, "f0_range_hz": e["f0_range_hz"], "quality": e.get("quality", {}),+ "source_drift_fraction": e.get("quality", {}).get("source_drift_fraction", .02)}+ for i, e in enumerate(events)], "assumptions_manifest": "manifest.json",+ "run_hash": run_hash, "source_fit_code_sha256": modules.get("matching.py"), "score_code_sha256": modules["search.py"]}+ finite["limitations"].append("Clock/frequency/drift are optimized at each fixed receiver/pass-association seed; clock uniqueness is not established.")+ finite["ledger_artifact"] = "retention.sqlite"report = {"run_hash": run_hash, "status": "complete" if complete else "partial", "ranked": ranked,"coarse_ranked": coarse, "tiles_total": total, "tiles_completed": done, "tiles_resumed": resumed,"tile_failures": failures, "unsearched_tiles": total - done, "grid_points_searched": points_searched,@@ -343,6 +403,8 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out"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,+ "finite_search_evidence": finite,+ "core_assessed_mode_ids": [row["mode_id"] for row in ranked if row.get("core_assessment_complete")],"event_groups_proposed": len(events), "association_event_limit": event_limit,"all_event_groups_considered": not event_limit_applied,"event_limit_reason": "Configured event cap prevents assessing every independent group" if event_limit_applied else None,diff --git a/tests/test_finite_search.py b/tests/test_finite_search.pynew file mode 100644index 0000000..f6657a7--- /dev/null+++ b/tests/test_finite_search.py@@ -0,0 +1,98 @@+from copy import deepcopy+import sqlite3++import pytest++from aircraft_geoloc.data_access import DataUnavailable+from aircraft_geoloc.finite_search import RetentionLedger, classified_assessment, identify_mode+from aircraft_geoloc.tiled_search import merge_candidates+++KIND = "matched_group_support_minus_normalized_residual"+++def row(x, score, clock=100., groups=1):+ return {"x": x, "y": 0., "lat": 40., "lon": -100., "elev_m": 10., "score": score,+ "score_kind": KIND, "recording_start_time_s": clock,+ "event_indices": list(range(groups)), "flight_ids": [f"flight{i}" for i in range(groups)],+ "pass_emission_times_s": [90.+i*50 for i in range(groups)]}+++def evidence(ledger, kept, **kwargs):+ return ledger.evidence(kept, complete=True, spacing_m=1000, refine_spacing_m=100, max_event_groups=4, **kwargs)+++def test_mode_identity_is_exact_spatial_clock_pass_and_group_seed():+ original = row(1., .4)+ identity = identify_mode(original)+ duplicate = deepcopy(original); duplicate.update(point_id=999, score=.5)+ assert identify_mode(duplicate) == identity+ for alternate in [row(1.+1e-8, .4), row(1., .4, clock=100.+1e-8), row(1., .4, groups=2)]:+ assert identify_mode(alternate) != identity+ alternate = row(1., .4); alternate["pass_emission_times_s"] = [90.+1e-8]+ assert identify_mode(alternate) != identity+ # A continuous refinement remains a representation of the original seed.+ refined = deepcopy(original); refined.update(x=2., recording_start_time_s=101.)+ assert identify_mode(refined) == identity+++def test_every_retention_stage_contributes_to_distinct_discard_bound(tmp_path):+ ledger = RetentionLedger(tmp_path / "retention.sqlite", "run", KIND)+ a, b, c, d = row(0, .90), row(1, .89), row(2, .895), row(3, .8)+ first = merge_candidates([a, b], 1, ledger=ledger, stage="coarse:a")+ second = merge_candidates([c, d], 1, ledger=ledger, stage="coarse:b")+ kept = merge_candidates(first+second, 1, ledger=ledger, stage="global:a")+ improved = deepcopy(kept[0]); improved["score"] = .92+ kept = merge_candidates(kept+[improved], 1, ledger=ledger, stage="fine:a")+ result = evidence(ledger, kept)+ assert result["complete"] and result["pruning_accounted_for"]+ assert result["evaluated_modes"] == 4 and result["discarded_count"] == 3+ assert result["best_discarded_score"] == .895+ assert result["retained_modes"][0]["score"] == .92+ assert result["stages"]["fine"]["exact_duplicates"] == 1+ # Deterministic stage replay replaces its rows, without inflating totals.+ checksum = ledger.checksum("coarse:a")+ merge_candidates([a, b], 1, ledger=ledger, stage="coarse:a")+ assert ledger.stage_valid("coarse:a", checksum)+ assert evidence(ledger, kept)["discarded_count"] == 3+++def test_exact_duplicates_are_not_competing_discarded_modes(tmp_path):+ ledger = RetentionLedger(tmp_path / "retention.sqlite", "run", KIND)+ a = row(0, 1.)+ kept = merge_candidates([a, deepcopy(a)], 1, ledger=ledger, stage="coarse:a")+ result = evidence(ledger, kept)+ assert result["discarded_count"] == 0 and result["best_discarded_score"] is None+ assert result["stages"]["coarse"]["exact_duplicates"] == 1+++def test_missing_or_corrupt_accounting_cannot_become_zero_discards(tmp_path):+ ledger = RetentionLedger(tmp_path / "retention.sqlite", "run", KIND)+ kept = merge_candidates([row(0, 1.), row(1, .99)], 1, ledger=ledger, stage="coarse:a")+ with sqlite3.connect(ledger.path) as db:+ db.execute("DELETE FROM records WHERE mode_id<>?", (kept[0]["mode_id"],))+ result = evidence(ledger, kept)+ assert not result["complete"] and not result["pruning_accounted_for"]+ assert result["discarded_count"] is None and result["best_discarded_score"] is None+ assert not ledger.stage_valid("coarse:a", ledger.checksum("coarse:a"))+++def test_ledger_rejects_wrong_run_or_score_units_and_missing_stages(tmp_path):+ path = tmp_path / "retention.sqlite"+ ledger = RetentionLedger(path, "run", KIND)+ kept = merge_candidates([row(0, 1.)], 1, ledger=ledger, stage="coarse:a")+ with pytest.raises(DataUnavailable, match="identity mismatch"):+ RetentionLedger(path, "different-run", KIND)+ wrong = row(1, 2.); wrong["score_kind"] = "negative_robust_ridge_loss_hz"+ with pytest.raises(DataUnavailable, match="score units"):+ merge_candidates([wrong], 1, ledger=ledger, stage="global:a")+ result = evidence(ledger, kept, expected_stages={"coarse": 1, "global": 1})+ assert not result["pruning_accounted_for"] and result["discarded_count"] is None+++def test_a_finite_best_score_does_not_hide_unknown_optimizer_trials():+ good = {"complete": True, "evaluated_trials": 5, "rejected_trials": 2, "unknown_trials": 0}+ 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}]:+ assert not classified_assessment({"score": .9, "scoring_assessment": dict(good, **change)})diff --git a/tests/test_tiled_search.py b/tests/test_tiled_search.pyindex 43cfd47..442c58f 100644--- a/tests/test_tiled_search.py+++ b/tests/test_tiled_search.py@@ -215,6 +215,75 @@ def test_narrow_trusted_window_near_sweep_edge_is_not_shrunk_again(tmp_path):assert ranked[0]["event_indices"] == [0, 1]+def test_finite_retention_bound_matches_untiled_and_recovers_missing_ledger(tmp_path):+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)+ terrain = Terrain(constant_m=0)+ settings = {"mode": "ridge", "time_origin": origin, "time_sweep_s": 0}+ points = pd.concat([tile_points(cells, 1000, bounds, terrain, "EPSG:5070")+ for _, cells in grid_tiles(bounds, 1000, 2)], ignore_index=True)+ points["point_id"] = np.arange(len(points))+ all_rows, _ = _score(points, list(index.query(bounds, times)), events, measurements,+ SearchBudget(top_k=10000), settings, {})+ assert len(all_rows) > 1+ budget = SearchBudget(spacing_m=1000, tile_cells=2, top_k=1, refine_spacing_m=1000)+ kwargs = dict(time_range_s=times, output_dir=tmp_path / "finite", bounds=bounds, budget=budget, scoring=settings)+ first = search_national([index], terrain, events, measurements, **kwargs)+ finite = first["finite_search_evidence"]+ assert finite["complete"] and finite["pruning_accounted_for"]+ assert finite["evaluated_modes"] == len(all_rows)+ assert finite["discarded_count"] == len(all_rows)-1+ assert finite["best_discarded_score"] == pytest.approx(all_rows[1]["score"], abs=1e-8)+ assert first["core_assessed_mode_ids"] == [first["ranked"][0]["mode_id"]]+ # Completed tile JSON alone is not enough to reconstruct discarded modes.+ (tmp_path / "finite/retention.sqlite").unlink()+ repaired = search_national([index], terrain, events, measurements, **kwargs)+ assert repaired["tiles_resumed"] == 0+ assert repaired["finite_search_evidence"]["discarded_count"] == finite["discarded_count"]+ assert repaired["core_assessed_mode_ids"] == first["core_assessed_mode_ids"]+++def test_successful_best_row_with_unknown_trials_has_no_optimistic_finite_bound(tmp_path, monkeypatch):+ from aircraft_geoloc import tiled_search+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)+ original = tiled_search.score_candidate++ 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"]}+ return result++ monkeypatch.setattr(tiled_search, "score_candidate", incomplete)+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,+ output_dir=tmp_path / "unknown", bounds=bounds,+ budget=SearchBudget(spacing_m=1000, tile_cells=4, top_k=1, refine_spacing_m=1000),+ scoring={"mode": "robust_ridge", "time_origin": origin, "time_sweep_s": 0})+ assert result["ranked"] and result["status"] == "complete"+ finite = result["finite_search_evidence"]+ assert not finite["complete"] and finite["unclassified_score_candidates"] > 0+ assert finite["best_discarded_score"] is None and finite["discarded_count"] > 0+ assert result["core_assessed_mode_ids"] == []+++def test_evaluated_acoustic_rejection_is_distinct_from_unknown_support(tmp_path, monkeypatch):+ from aircraft_geoloc import tiled_search+ _, tracks, events, measurements, bounds, _, origin = scenario(tmp_path)+ original = tiled_search.score_candidate++ def rejected(*args, **kwargs):+ result = original(*args, **kwargs)+ result.update(score=-np.inf, scoring_assessment={"complete": True, "evaluated_trials": 1,+ "rejected_trials": 1, "unknown_trials": 0, "reasons": ["test_admissible_rejection"]})+ return result++ monkeypatch.setattr(tiled_search, "score_candidate", rejected)+ points = tile_points((0, 1900, 1, 1901), 1000, bounds, Terrain(constant_m=0), "EPSG:5070")+ ranked, counts = _score(points, tracks, events, measurements, SearchBudget(),+ {"mode": "robust_ridge", "time_origin": origin, "time_sweep_s": 0}, {})+ assert not ranked and counts["evaluated_rejections"] == counts["candidates"] > 0+ assert counts["unclassified_score_candidates"] == 0++def test_overlapping_refinement_scores_the_complete_grid_union_once(tmp_path, monkeypatch):from aircraft_geoloc import tiled_search