Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Reuse trajectory preparation and batch empty-tile transactions
Cinna Davis1d045b366464
diff --git a/scripts/benchmark_real_audio_performance.py b/scripts/benchmark_real_audio_performance.pynew file mode 100644index 0000000..a9927d0--- /dev/null+++ b/scripts/benchmark_real_audio_performance.py@@ -0,0 +1,121 @@+"""Compare audio performance against another checkout on a real recording.++The full recording is decoded once and both implementations receive identical+samples and discovery settings. All event fields must match exactly. Optional+configured ridge windows check every frequency and weight as well. This measures+runtime and software equivalence, not aircraft identity or localization accuracy.+"""+import argparse+import importlib.util+import json+from pathlib import Path+import statistics+import subprocess+import sys+import time++import numpy as np++from dopplergeist import audio, discovery+from dopplergeist.intake import intake_recording+++def _module(path, name):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return module+++def _timed(function):+ wall, cpu = time.perf_counter(), time.process_time()+ result = function()+ return result, {"wall_s": time.perf_counter() - wall,+ "cpu_s": time.process_time() - cpu}+++def _summary(samples):+ result = {name: {"trials": values,+ "median_wall_s": statistics.median(row["wall_s"] for row in values),+ "median_cpu_s": statistics.median(row["cpu_s"] for row in values)}+ for name, values in samples.items()}+ result["wall_speedup"] = result["baseline"]["median_wall_s"] / result["current"]["median_wall_s"]+ result["cpu_speedup"] = result["baseline"]["median_cpu_s"] / result["current"]["median_cpu_s"]+ return result+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("audio", help="Actual recorded audio, never a generated fixture")+ parser.add_argument("--baseline", required=True, help="Unmodified baseline checkout")+ parser.add_argument("--output", required=True, help="New output directory")+ parser.add_argument("--repeats", type=int, default=3)+ parser.add_argument("--diagnostics", action="store_true", help="Include diagnostic JSON/CSV/PNG writes")+ parser.add_argument("--ridge-config", help="Existing real-recording configuration with event windows")+ args = parser.parse_args()+ if args.repeats < 1:+ parser.error("--repeats must be positive")+ output, baseline = Path(args.output), Path(args.baseline).resolve()+ baseline_audio = _module(baseline / "src/dopplergeist/audio.py", "dopplergeist._baseline_audio")+ baseline_discovery = _module(baseline / "src/dopplergeist/discovery.py", "dopplergeist._baseline_discovery")+ output.mkdir(parents=True, exist_ok=False)+ recording, intake_time = _timed(lambda: intake_recording(args.audio, output / "intake"))+ implementations = {"baseline": baseline_discovery, "current": discovery}+ samples = {name: [] for name in implementations}+ reference = None+ events = []+ for trial in range(args.repeats):+ order = ("baseline", "current") if trial % 2 == 0 else ("current", "baseline")+ for name in order:+ directory = output / f"{name}-{trial + 1}" if args.diagnostics else None+ events, timing = _timed(lambda: implementations[name].discover_events(+ recording, output_dir=directory))+ payload = json.dumps(events, sort_keys=True, allow_nan=False)+ if reference is None:+ reference = payload+ if payload != reference:+ (output / f"mismatch-{name}-{trial + 1}.json").write_text(payload + "\n")+ raise AssertionError("Full discovery event payload changed")+ samples[name].append(timing)+ print(json.dumps({"stage": "discovery", "implementation": name,+ "trial": trial + 1, "events": len(events), **timing}), flush=True)+ (output / "events.json").write_text(reference + "\n")+ result = {"source": recording.metadata, "intake": intake_time,+ "baseline_commit": subprocess.check_output(+ ["git", "-C", str(baseline), "rev-parse", "HEAD"], text=True).strip(),+ "diagnostics_included": args.diagnostics,+ "discovery": {**_summary(samples), "exact_event_payload_match": True,+ "ridge_count": len(events),+ "independent_group_count": len({e["harmonic_group_id"] for e in events})},+ "scope": "Real-recording runtime/equivalence only; no aircraft or location validation"}+ if args.ridge_config:+ configured = json.loads(Path(args.ridge_config).read_text())+ result["configured_ridges"] = []+ for index, event in enumerate(configured["events"]):+ data, sr = audio.decode(args.audio, event["start_s"], event["end_s"] - event["start_s"])+ spectrum = audio.spectrogram(data, sr, event["band_hz"], event["start_s"],+ event.get("window_s", 2.0), event.get("hop_s", 0.25))+ ridge_samples = {"baseline": [], "current": []}+ reference_ridge = None+ for trial in range(args.repeats):+ order = ("baseline", "current") if trial % 2 == 0 else ("current", "baseline")+ for name in order:+ implementation = baseline_audio if name == "baseline" else audio+ ridge, timing = _timed(lambda: implementation.trace_ridge(+ spectrum, event.get("max_slope_hz_s", 12),+ max_up_slope=event.get("max_up_slope_hz_s", 1.0)))+ if reference_ridge is None:+ reference_ridge = ridge+ if not all(np.array_equal(before, after) for before, after in zip(reference_ridge, ridge)):+ raise AssertionError(f"Configured ridge {index + 1} changed")+ ridge_samples[name].append(timing)+ result["configured_ridges"].append({"event": index + 1,+ "spectrum_shape": list(spectrum.contrast.shape),+ "exact_frequency_and_weight_match": True, **_summary(ridge_samples)})+ (output / "summary.json").write_text(json.dumps(result, indent=2, allow_nan=False) + "\n")+ print(json.dumps(result, indent=2, allow_nan=False))+++if __name__ == "__main__":+ main()diff --git a/scripts/benchmark_real_empty_tiles.py b/scripts/benchmark_real_empty_tiles.pynew file mode 100644index 0000000..7fda696--- /dev/null+++ b/scripts/benchmark_real_empty_tiles.py@@ -0,0 +1,130 @@+"""Replay recorded empty tiles, comparing ordinary commits with bounded batches.++Supply an existing real search directory and its original native flight index.+Every timed path queries the original data and must reproduce each saved tile.+This measures empty coarse tiles only, not complete search or location accuracy.+"""+import argparse+from contextlib import nullcontext+import json+from pathlib import Path+import platform+import sqlite3+import statistics+import time++from dopplergeist.data_access import FlightIndex, content_hash, sha256, write_json+from dopplergeist.finite_search import RetentionLedger+from dopplergeist.tiled_search import (SearchBudget, _expanded_bounds, _tile_coordinates,+ _tracks, grid_tiles, merge_candidates)+++def ledger_contents(ledger):+ with ledger.connect() as db:+ return {table: db.execute(f"SELECT * FROM {table} ORDER BY 1,2").fetchall()+ for table in ("run", "stages", "records", "bounds")}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--search", type=Path, required=True)+ parser.add_argument("--index", type=Path, action="append", required=True)+ parser.add_argument("--tiles", type=int, default=256)+ parser.add_argument("--batch-size", type=int, default=32)+ parser.add_argument("--passes", type=int, default=3)+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ if min(args.tiles, args.batch_size, args.passes) <= 0:+ parser.error("tile, batch and pass counts must be positive")+ args.output.mkdir(parents=True, exist_ok=False)+ manifest = json.loads((args.search / "manifest.json").read_text())+ config, run_hash = manifest["configuration"], manifest["run_hash"]+ if content_hash(config) != run_hash:+ raise ValueError("Saved manifest identity mismatch")+ indexes = [FlightIndex(path) for path in args.index]+ identities = [{"input_hash": index.report["input_hash"], "file_sha256": sha256(index.path)}+ for index in indexes]+ if identities != config["indexes"]:+ raise ValueError("Indexes differ from the saved real search")+ budget = SearchBudget(**config["budget"])+ bounds, crs = config["bounds"], config["crs"]+ radius = max(event["slant_range_m"][1] for event in config["events"])+ mode = config["scoring"].get("mode", "brightness")+ score_kind = ("matched_group_support_minus_normalized_residual"+ if mode == "robust_ridge" and config["filters"]["association"] == "subsets"+ else {"robust_ridge": "negative_robust_ridge_loss_hz", "ridge": "negative_ridge_rmse_hz",+ "brightness": "summed_spectral_contrast"}[mode])+ tiles = []+ for tile_id, cells in grid_tiles(bounds, budget.spacing_m, budget.tile_cells, crs):+ path = args.search / f"tile-{tile_id}.json"+ if not path.exists():+ continue+ saved = json.loads(path.read_text())+ payload = saved["payload"]+ if saved["run_hash"] != run_hash or saved["payload_hash"] != content_hash(payload):+ raise ValueError(f"Invalid recorded tile: {path}")+ if payload["ranked"] or payload["counts"] or payload["tracks"]:+ continue+ if not len(_tile_coordinates(cells, budget.spacing_m, bounds, crs)):+ continue+ tiles.append((tile_id, cells, saved))+ if len(tiles) == args.tiles:+ break+ if len(tiles) != args.tiles:+ raise ValueError(f"Only {len(tiles)} recorded empty tiles with receiver cells were available")++ expected_contents = None+ results = {"ordinary": [], "batched": []}+ for pass_number in range(args.passes):+ order = ("ordinary", "batched") if pass_number % 2 == 0 else ("batched", "ordinary")+ for name in order:+ output = args.output / f"{name}-{pass_number + 1}"+ output.mkdir()+ ledger = RetentionLedger(output / "retention.sqlite", run_hash, score_kind)+ batch_size = 1 if name == "ordinary" else args.batch_size+ started, cpu_started = time.perf_counter(), time.process_time()+ for first in range(0, len(tiles), batch_size):+ with ledger.batch() if batch_size > 1 else nullcontext():+ for tile_id, cells, saved in tiles[first:first + batch_size]:+ points = _tile_coordinates(cells, budget.spacing_m, bounds, crs)+ tracks = _tracks(indexes, _expanded_bounds(cells, budget.spacing_m, radius, crs),+ config["time_range_s"], budget) if len(points) else []+ if tracks:+ raise AssertionError(f"Recorded empty tile now has tracks: {tile_id}")+ stage = f"coarse:{tile_id}"+ ledger.record(stage, [], [], 0)+ payload = {"ranked": [], "counts": {}, "grid_points": 0, "tracks": 0,+ "cells": list(cells), "terrain_files": [], "terrain_ocean_tiles": [],+ "terrain_failures": [], "retention_checksum": ledger.checksum(stage)}+ checkpoint = {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload}+ if checkpoint != saved:+ raise AssertionError(f"Recorded tile changed: {tile_id}")+ write_json(output / f"tile-{tile_id}.json", checkpoint)+ merge_candidates([], budget.top_k, ledger=ledger, stage=f"global:{tile_id}")+ results[name].append({"wall_s": time.perf_counter() - started,+ "cpu_s": time.process_time() - cpu_started})+ contents = ledger_contents(ledger)+ if expected_contents is None:+ expected_contents = contents+ if contents != expected_contents:+ raise AssertionError("Retention tables changed between runs")+ for tile_id, _, saved in tiles:+ for phase in ("coarse", "global"):+ if not ledger.stage_valid(f"{phase}:{tile_id}", saved["payload"]["retention_checksum"]):+ raise AssertionError("Committed stage fails normal resume validation")+ medians = {name: statistics.median(row["wall_s"] for row in rows) for name, rows in results.items()}+ summary = {"scope": "Recorded empty coarse tiles with receiver cells; includes geometry, real index queries, "+ "coarse/global stages, checksums and checkpoint writes; excludes progress/resume reads",+ "source_search": str(args.search), "indexes": identities, "tiles": len(tiles),+ "batch_size": args.batch_size, "passes": args.passes,+ "runtime": {"python": platform.python_version(), "sqlite": sqlite3.sqlite_version},+ "timings": results, "median_wall_s": medians,+ "speedup": medians["ordinary"] / medians["batched"],+ "all_checkpoints_match_recorded_tiles": True, "all_ledger_tables_match": True,+ "all_committed_stages_valid": True, "stage_count": len(expected_contents["stages"])}+ write_json(args.output / "summary.json", summary)+ print(json.dumps(summary, indent=2))+++if __name__ == "__main__":+ main()diff --git a/scripts/benchmark_real_performance_helpers.py b/scripts/benchmark_real_performance_helpers.pynew file mode 100644index 0000000..60a1cb9--- /dev/null+++ b/scripts/benchmark_real_performance_helpers.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Compare identity/terrain helpers on restored observations and candidate rows.++This is a component benchmark. Both duplicate-query variants use the same+current, cache-disabled FlightIndex so the identity change is measured alone.+No observations, receiver results, or timing evidence are generated artificially.+"""+import argparse+import importlib.util+import json+import os+from pathlib import Path+from statistics import median+import sys+import time++import numpy as np++from dopplergeist import terrain, tiled_search+from dopplergeist.data_access import FlightIndex, content_hash+++def load_module(name, path):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return module+++def json_geometry_digest(track):+ return content_hash([track.id, track.time.tolist(), track.xyz.tolist(), track.spline.c.tolist()])+++def identity_partition(values):+ groups = {}+ for index, value in enumerate(values):+ groups.setdefault(value, []).append(index)+ return sorted(groups.values())+++def assert_tracks_equal(actual, expected):+ assert [track.id for track in actual] == [track.id for track in expected]+ for got, want in zip(actual, expected):+ for name in ("time", "xyz"):+ np.testing.assert_array_equal(getattr(got, name), getattr(want, name))+ np.testing.assert_array_equal(got.spline.c, want.spline.c)+++def timed(function):+ wall, cpu = time.perf_counter(), time.process_time()+ result = function()+ return result, {"wall_s": time.perf_counter() - wall, "cpu_s": time.process_time() - cpu}+++def compare(functions, repeats, verify):+ trials = {name: [] for name in functions}+ names = list(functions)+ for iteration in range(repeats):+ for name in names if iteration % 2 == 0 else reversed(names):+ result, elapsed = timed(functions[name])+ verify(name, result)+ trials[name].append(elapsed)+ medians = {name: {metric: median(row[metric] for row in rows)+ for metric in ("wall_s", "cpu_s")}+ for name, rows in trials.items()}+ return {"trials": trials, "median": medians,+ "wall_speedup": medians["baseline"]["wall_s"] / medians["current"]["wall_s"],+ "cpu_speedup": medians["baseline"]["cpu_s"] / medians["current"]["cpu_s"]}+++def close_terrain(sampler):+ for raster in sampler.rasters:+ raster.close()+ if sampler.geoid:+ close_terrain(sampler.geoid)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--fixture", type=Path, required=True,+ help="Real search fixture containing index path and query bounds/time")+ parser.add_argument("--baseline", type=Path, required=True)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--repeats", type=int, default=3)+ args = parser.parse_args()+ if args.repeats < 1:+ parser.error("--repeats must be positive")+ args.output.mkdir(parents=True, exist_ok=False)+ root = Path(__file__).resolve().parents[1]+ fixture = json.loads(args.fixture.read_text())+ index_path = fixture["real_index"]+ query_args = fixture["query_bounds"], fixture["query_time_s"]+ baseline_tiles = load_module("dopplergeist._reference_helper_tiles",+ args.baseline / "src/dopplergeist/tiled_search.py")+ baseline_terrain = load_module("dopplergeist._reference_helper_terrain",+ args.baseline / "src/dopplergeist/terrain.py")++ def decode():+ return list(FlightIndex(index_path, track_cache_bytes=0).query(*query_args))++ first, second = decode(), decode()+ assert first and all(a is not b for a, b in zip(first, second))+ assert_tracks_equal(first, second)+ old = [json_geometry_digest(track) for track in first + second]+ new = [tiled_search._track_geometry_digest(track) for track in first + second]+ assert identity_partition(old) == identity_partition(new)+ expected_digests = {"baseline": old[:len(first)], "current": new[:len(first)]}++ def verify_digests(name, result):+ assert result == expected_digests[name]++ digest_results = compare({+ "baseline": lambda: [json_geometry_digest(track) for track in first],+ "current": lambda: [tiled_search._track_geometry_digest(track) for track in first],+ }, args.repeats, verify_digests)+ print(json.dumps({"stage": "identity_digest", **digest_results["median"]}), flush=True)++ def duplicate_query(module):+ indexes = [FlightIndex(index_path, track_cache_bytes=0) for _ in range(2)]+ return module._tracks(indexes, *query_args, tiled_search.SearchBudget())++ duplicate_results = compare({+ "baseline": lambda: duplicate_query(baseline_tiles),+ "current": lambda: duplicate_query(tiled_search),+ }, args.repeats, lambda name, result: assert_tracks_equal(result, first))+ print(json.dumps({"stage": "duplicate_query", **duplicate_results["median"]}), flush=True)++ rows = json.loads((root / "evidence/results/reference-local-fast/ranked.json").read_text())+ lat, lon = [np.asarray([row[key] for row in rows]) for key in ("lat", "lon")]+ dem = root / "data/terrain/Copernicus_DSM_COG_10_N40_00_W074_00_DEM.tif"+ geoid = root / "data/terrain/us_nga_egm96_15.tif"+ samplers = {name: module.Terrain([dem], geoid_path=geoid)+ for name, module in (("baseline", baseline_terrain), ("current", terrain))}+ terrain._raster_transformer.cache_clear()+ try:+ expected = samplers["baseline"].sample(lat, lon)+ np.testing.assert_array_equal(samplers["current"].sample(lat, lon), expected)++ def scalar_samples(name):+ return np.asarray([samplers[name].sample(a, b).item() for a, b in zip(lat, lon)])++ scalar_results = compare({name: lambda name=name: scalar_samples(name) for name in samplers},+ args.repeats, lambda name, result: np.testing.assert_array_equal(result, expected))+ vector_results = compare({name: lambda name=name: samplers[name].sample(lat, lon) for name in samplers},+ args.repeats, lambda name, result: np.testing.assert_array_equal(result, expected))+ cache_info = terrain._raster_transformer.cache_info()._asdict()+ finally:+ for sampler in samplers.values():+ close_terrain(sampler)++ summary = {"scope": "Real observations and archived candidate coordinates; component timings only",+ "fixture": str(args.fixture.resolve()), "baseline": str(args.baseline.resolve()),+ "cpu_affinity": sorted(os.sched_getaffinity(0)),+ "threads": {key: os.environ.get(key) for key in+ ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS")},+ "tracks": len(first), "samples": sum(len(track.time) for track in first),+ "independent_decodes_exact": True, "old_new_identity_relation_exact": True,+ "duplicate_track_geometry_exact": True, "terrain_arrays_exact": True,+ "candidate_rows": len(rows), "unique_candidate_coordinates": len(set(zip(lat, lon))),+ "identity_digest": digest_results, "duplicate_index_query": duplicate_results,+ "terrain_scalar_queries": scalar_results, "terrain_vector_query": vector_results,+ "terrain_transform_cache": cache_info}+ (args.output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")+ print(json.dumps({"output": str(args.output / "summary.json"),+ "speedups": {name: summary[name]["wall_speedup"] for name in+ ("identity_digest", "duplicate_index_query", "terrain_scalar_queries",+ "terrain_vector_query")}}), flush=True)+++if __name__ == "__main__":+ main()diff --git a/scripts/benchmark_real_track_cache.py b/scripts/benchmark_real_track_cache.pynew file mode 100644index 0000000..abb5aa1--- /dev/null+++ b/scripts/benchmark_real_track_cache.py@@ -0,0 +1,87 @@+"""Measure repeated whole-segment queries against a supplied real flight index.++This measures trajectory loading, including integrity checks and output+fingerprints. It is not an audio/search runtime or location-accuracy benchmark.+The first pass has a cold decoded-track cache; subsequent passes reuse it.+"""+import argparse+import hashlib+import json+from pathlib import Path+import statistics+import time++import numpy as np++from dopplergeist.data_access import FlightIndex+++def measure(index, bounds, time_range, max_tracks, max_samples):+ digest = hashlib.sha256()+ tracks = samples = 0+ started = time.perf_counter()+ started_cpu = time.process_time()+ for track in index.query(bounds, time_range):+ tracks += 1+ samples += len(track.time)+ if tracks > max_tracks or samples > max_samples:+ raise ValueError("Real query exceeds the benchmark track/sample budget")+ digest.update(json.dumps([track.id, track.typecode, track.altitude_basis,+ track.aircraft_class, track.velocity_inferred_components],+ sort_keys=True, allow_nan=False).encode())+ for values in (track.time, track.lat, track.lon, track.altitude, track.xyz,+ track.spline.c, track.derivative.c):+ array = np.asarray(values, dtype="<f8")+ digest.update(str(array.shape).encode())+ digest.update(array.tobytes(order="C"))+ return {"wall_s": time.perf_counter() - started, "cpu_s": time.process_time() - started_cpu, "tracks": tracks,+ "samples": samples, "geometry_and_labels_sha256": digest.hexdigest(),+ "cached_tracks": len(index._track_cache),+ "serialized_cache_bytes": index._track_cache_bytes}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--index", type=Path, required=True)+ parser.add_argument("--bounds", type=float, nargs=4, required=True, metavar=("W", "S", "E", "N"))+ parser.add_argument("--time-range", type=float, nargs=2, required=True, metavar=("START", "END"))+ parser.add_argument("--passes", type=int, default=4)+ parser.add_argument("--cache-bytes", type=int, default=32 * 1024 * 1024)+ parser.add_argument("--max-tracks", type=int, default=2000)+ parser.add_argument("--max-samples", type=int, default=500000)+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ if args.output.exists():+ parser.error("Use a new output path to preserve earlier measurements")+ if args.passes < 2 or min(args.cache_bytes, args.max_tracks, args.max_samples) < 1:+ parser.error("Use at least two passes and positive cache/track/sample limits")+ instances = {"uncached": FlightIndex(args.index, track_cache_bytes=0),+ "cached": FlightIndex(args.index, track_cache_bytes=args.cache_bytes)}+ runs = {name: [] for name in instances}+ for trial in range(args.passes):+ for name in (("uncached", "cached") if trial % 2 == 0 else ("cached", "uncached")):+ runs[name].append(measure(instances[name], args.bounds, args.time_range,+ args.max_tracks, args.max_samples))+ signatures = {(run["tracks"], run["samples"], run["geometry_and_labels_sha256"])+ for group in runs.values() for run in group}+ if len(signatures) != 1 or not runs["uncached"][0]["tracks"]:+ raise AssertionError("Queries differ or contain no real tracks")+ medians = {name: statistics.median(run["wall_s"] for run in group[1:]) for name, group in runs.items()}+ totals = {name: sum(run["wall_s"] for run in group) for name, group in runs.items()}+ report = {"scope": "Repeated real trajectory query; excludes acquisition, audio and scoring",+ "index": str(args.index.resolve()), "input_hash": instances["cached"].report["input_hash"],+ "bounds": args.bounds, "time_range_s": args.time_range, "passes": runs,+ "same_geometry_and_labels": True, "median_warm_query_s": medians,+ "warm_query_speedup": medians["uncached"] / medians["cached"],+ "first_query_s": {name: group[0]["wall_s"] for name, group in runs.items()},+ "all_query_passes_s": totals,+ "all_passes_speedup_including_cold_cache": totals["uncached"] / totals["cached"]}+ args.output.parent.mkdir(parents=True, exist_ok=True)+ with args.output.open("x") as output:+ json.dump(report, output, indent=2, allow_nan=False)+ output.write("\n")+ print(json.dumps(report, indent=2, allow_nan=False), flush=True)+++if __name__ == "__main__":+ main()diff --git a/scripts/compare_real_upload_performance.py b/scripts/compare_real_upload_performance.pynew file mode 100644index 0000000..860a51e--- /dev/null+++ b/scripts/compare_real_upload_performance.py@@ -0,0 +1,295 @@+#!/usr/bin/env python3+"""Compare two completed real verify_upload_http.py runs without rerunning fits.++Exit zero requires verified full workflows and exact scientific parity. JSON+numbers have no tolerance. Search checkpoints and logical retention rows are+included. The existing verifier owns input and artifact integrity checks.+"""+from __future__ import annotations++import argparse+from collections import Counter+from contextlib import ExitStack+from datetime import datetime+import hashlib+from itertools import zip_longest+import json+import math+from pathlib import Path+import sqlite3+++IMPLEMENTATION_FIELDS = {"implementation_files", "run_hash", "search_run_hash",+ "source_fit_code_sha256", "score_code_sha256", "verifier_sha256"}+PERFORMANCE_FIELDS = {"elapsed_s", "process_peak_rss_mib"}+ROOT_JSON = ("upload-request.json", "operator.json", "result.json")+REQUIRED_STAGES = {"automatic_provenance", "intake", "discovery", "acquisition",+ "search", "refinement", "decision"}+MISSING = object()+++def read_json(path):+ def reject(value):+ raise ValueError(f"Nonfinite JSON constant in {path}: {value}")+ return json.loads(path.read_text(), parse_constant=reject)+++def encoded(value):+ return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()+++def summary_value(value):+ if value is MISSING:+ return {"missing": True}+ if isinstance(value, (dict, list)) or (isinstance(value, str) and len(value) > 500):+ return {"type": type(value).__name__, "length": len(value),+ "sha256": hashlib.sha256(encoded(value)).hexdigest()}+ return value+++class Differences:+ def __init__(self, limit):+ self.limit, self.count = limit, 0+ self.examples, self.categories, self.files = [], Counter(), set()+ self.numeric_count, self.maximum_absolute_numeric_difference = 0, 0.0++ def add(self, artifact, path, left, right):+ self.count += 1+ self.files.add(artifact)+ category = "job/search/tile-*.json" if artifact.startswith("job/search/tile-") else artifact+ self.categories[category] += 1+ detail = {"artifact": artifact, "path": "/" + "/".join(map(str, path)),+ "baseline": summary_value(left), "current": summary_value(right)}+ if type(left) in (int, float) and type(right) in (int, float):+ absolute = abs(right - left)+ self.numeric_count += 1+ self.maximum_absolute_numeric_difference = max(self.maximum_absolute_numeric_difference, absolute)+ detail["absolute_difference"] = absolute+ if len(self.examples) < self.limit:+ self.examples.append(detail)++ def compare(self, artifact, left, right, path=()):+ if type(left) is not type(right):+ self.add(artifact, path, left, right)+ elif isinstance(left, dict):+ for key in sorted(left.keys() | right.keys()):+ if key not in left or key not in right:+ self.add(artifact, path + (key,), left.get(key, MISSING), right.get(key, MISSING))+ else:+ self.compare(artifact, left[key], right[key], path + (key,))+ elif isinstance(left, list):+ if len(left) != len(right):+ self.add(artifact, path + ("length",), len(left), len(right))+ for index, (a, b) in enumerate(zip_longest(left, right, fillvalue=MISSING)):+ if a is MISSING or b is MISSING:+ self.add(artifact, path + (index,), a, b)+ else:+ self.compare(artifact, a, b, path + (index,))+ elif left != right or (isinstance(left, float) and left == 0+ and math.copysign(1, left) != math.copysign(1, right)):+ self.add(artifact, path, left, right)++ def report(self):+ return {"count": self.count, "changed_artifact_count": len(self.files),+ "counts_by_artifact": dict(sorted(self.categories.items())),+ "numeric_difference_count": self.numeric_count,+ "maximum_absolute_numeric_difference": self.maximum_absolute_numeric_difference,+ "examples": self.examples, "examples_truncated": self.count > len(self.examples)}+++class Run:+ def __init__(self, directory):+ self.directory = directory.resolve()+ # This receipt is committed after service shutdown and verifier checks.+ # Refuse to inspect any job or SQLite database before it exists.+ receipt = self.directory / "http-verification.json"+ if not receipt.is_file():+ raise ValueError(f"Run has no completed HTTP verification receipt: {directory}")+ self.receipt = read_json(receipt)+ if "finished_utc" not in self.receipt or "elapsed_s" not in self.receipt:+ raise ValueError(f"HTTP verification receipt is unfinished: {directory}")+ if self.receipt.get("service", {}).get("returncode") is None:+ raise ValueError(f"Service termination is not established; refusing to inspect its ledger: {directory}")+ self.job = self.directory / "jobs" / self.receipt["job_id"]+ self.ignored = Counter()++ def normalize(self, value, relative, root=False, path=()):+ if isinstance(value, dict):+ result = {}+ for key, item in value.items():+ here = path + (key,)+ reason = None+ if key in IMPLEMENTATION_FIELDS:+ reason = f"field:{key}"+ elif key in PERFORMANCE_FIELDS:+ reason = f"performance:{key}"+ elif not root and relative == "provenance.json" and here == ("operator_configuration_sha256",):+ reason = "operator configuration digest; full normalized operator.json is compared"+ elif not root and relative == "search/manifest.json" and here == ("configuration", "code"):+ reason = "search implementation files"+ if reason:+ self.ignored[reason] += 1+ continue+ normalized_key = self.normalize(key, relative, root, path)+ result[normalized_key] = self.normalize(item, relative, root, here)+ return result+ if isinstance(value, list):+ return [self.normalize(item, relative, root, path + (index,)) for index, item in enumerate(value)]+ if isinstance(value, str):+ return (value.replace(str(self.job), "<job>")+ .replace(str(self.directory), "<run>")+ .replace(self.receipt["job_id"], "<job-id>"))+ return value++ def json(self, relative, *, root=False):+ return self.normalize(read_json((self.directory if root else self.job) / relative), relative, root)++ def full_pipeline(self):+ evidence = read_json(self.directory / "pipeline-evidence.json")+ return (all(self.receipt.get(key) is True for key in+ ("verification_passed", "http_checks_passed", "pipeline_evidence_passed",+ "full_pipeline_observed", "full_pipeline_requirements_met"))+ and self.receipt.get("candidate_count", 0) > 0+ and evidence.get("passed") is True and evidence.get("full_pipeline_observed") is True+ and REQUIRED_STAGES.issubset(evidence.get("stages_verified", [])))++ def timing(self):+ rows = [json.loads(line) for line in (self.directory / "history.jsonl").read_text().splitlines()]+ timestamp = lambda value: datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()+ transitions = []+ for row in rows:+ result = row["result"]+ stage = result.get("stage") if result["status"] in ("running", "queued") else "terminal:" + result["status"]+ if not transitions or transitions[-1]["stage"] != stage:+ transitions.append({"stage": stage, "observed_utc": row["observed_utc"]})+ totals = Counter()+ for current, following in zip(transitions, transitions[1:]):+ duration = timestamp(following["observed_utc"]) - timestamp(current["observed_utc"])+ current["until_next_transition_s"] = duration+ totals[current["stage"]] += duration+ return {"receipt_elapsed_s": self.receipt["elapsed_s"], "poll_records": len(rows),+ "observed_stage_seconds": dict(totals), "transitions": transitions,+ "note": "Stage durations use first observed HTTP transitions and include polling uncertainty; unobserved short stages have no inferred duration."}+++def ignored_artifact(relative):+ return relative in {"resume.json", "intake/intake.json"} or relative.startswith("search/.tile-workers/")+++def quote_identifier(value):+ return '"' + value.replace('"', '""') + '"'+++def compare_ledger(left, right, relative, differences):+ artifact = "job/" + relative+ with ExitStack() as stack:+ databases = []+ for run in (left, right):+ connection = sqlite3.connect((run.job / relative).as_uri() + "?mode=ro", uri=True)+ stack.callback(connection.close)+ databases.append(connection)+ table_sets = [{row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}+ for db in databases]+ differences.compare(artifact, sorted(table_sets[0]), sorted(table_sets[1]), ("tables",))+ counts = [{}, {}]+ for table in sorted(table_sets[0] & table_sets[1]):+ schemas = [db.execute(f"PRAGMA table_info({quote_identifier(table)})").fetchall() for db in databases]+ differences.compare(artifact, schemas[0], schemas[1], (table, "schema"))+ cursors, columns = [], []+ for db, schema in zip(databases, schemas):+ names = [row[1] for row in schema]+ columns.append(names)+ keys = [row[1] for row in sorted(schema, key=lambda row: row[5]) if row[5]] or names+ order = ",".join(map(quote_identifier, keys))+ cursors.append(db.execute(f"SELECT * FROM {quote_identifier(table)} ORDER BY {order}"))+ for number, rows in enumerate(zip_longest(*cursors, fillvalue=MISSING)):+ normalized = []+ for side, row in enumerate(rows):+ if row is MISSING:+ normalized.append(MISSING)+ continue+ record = dict(zip(columns[side], row))+ if table == "run":+ record.pop("identity", None)+ for field in ({"stages": ("kept",), "records": ("seed",), "bounds": ("detail",)}.get(table, ())):+ record[field] = json.loads(record[field])+ counts[side][table] = counts[side].get(table, 0) + 1+ normalized.append(record)+ if any(row is MISSING for row in normalized):+ differences.add(artifact, (table, number), *normalized)+ else:+ differences.compare(artifact, *normalized, (table, number))+ return {"baseline_rows": counts[0], "current_rows": counts[1]}+++def compare_runs(baseline, current, max_examples=40):+ left, right = Run(baseline), Run(current)+ differences, checked, ledgers = Differences(max_examples), Counter(), {}+ selected = [{path.relative_to(run.job).as_posix() for path in run.job.rglob("*")+ if path.is_file() and path.suffix in {".json", ".sqlite"}+ and not ignored_artifact(path.relative_to(run.job).as_posix())} for run in (left, right)]+ differences.compare("job inventory", sorted(selected[0]), sorted(selected[1]))+ for name in sorted(selected[0] & selected[1]):+ try:+ if name.endswith(".json"):+ differences.compare("job/" + name, left.json(name), right.json(name))+ checked["json"] += 1+ elif name.endswith(".sqlite"):+ ledgers[name] = compare_ledger(left, right, name, differences)+ checked["sqlite"] += 1+ except (OSError, ValueError, sqlite3.DatabaseError) as error:+ differences.add("job/" + name, ("comparison_error",), str(error), MISSING)+ for name in ROOT_JSON:+ differences.compare("root/" + name, left.json(name, root=True), right.json(name, root=True))+ checked["root_json"] += 1+ differences.compare("HTTP source identity", {key: left.receipt.get(key) for key in ("source_sha256", "source_bytes")},+ {key: right.receipt.get(key) for key in ("source_sha256", "source_bytes")})+ full = {name: run.full_pipeline() for name, run in (("baseline", left), ("current", right))}+ passed = differences.count == 0 and all(full.values())+ timings = {name: run.timing() for name, run in (("baseline", left), ("current", right))}+ return {"scope": "Exact semantic comparison of completed actual HTTP upload workflows",+ "baseline": str(left.directory), "current": str(right.directory),+ "passed": passed, "scientific_payloads_exact": differences.count == 0,+ "full_pipeline_verified": full,+ "checked_artifacts": dict(checked), "retention_ledgers": ledgers,+ "outcomes": {name: {key: run.receipt.get(key) for key in+ ("status", "reason_code", "candidate_count", "event_count", "supported_decision")}+ for name, run in (("baseline", left), ("current", right))},+ "differences": differences.report(), "timings": timings,+ "verified_full_workflow_speedup": (left.receipt["elapsed_s"] / right.receipt["elapsed_s"] if passed else None),+ "normalization": {"implementation_fields": sorted(IMPLEMENTATION_FIELDS),+ "performance_fields": sorted(PERFORMANCE_FIELDS),+ "path_rule": "Only each run directory, job directory and exact job identifier are replaced.",+ "sqlite_rule": "Compare all logical tables, columns and rows; ignore only run.identity and physical SQLite/index layout.",+ "excluded_metadata": ["resume.json", "intake/intake.json", "search/.tile-workers/**"],+ "scope": "Scientific JSON and logical ledger contents. Existing HTTP verification owns integrity checks; real-audio validation separately checks measured arrays.",+ "observed_ignored_counts": {"baseline": dict(left.ignored), "current": dict(right.ignored)}},+ "limitations": ["Exact parity establishes consistency with the baseline, not geolocation accuracy.",+ "No withheld-location comparison or synthetic observations are used.",+ "All semantic differences fail the gate, including floating-point roundoff; examples alone are bounded."]}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--baseline", type=Path, required=True)+ parser.add_argument("--current", type=Path, required=True)+ parser.add_argument("--output", type=Path, required=True, help="New JSON report path")+ parser.add_argument("--max-examples", type=int, default=40)+ args = parser.parse_args()+ if args.max_examples < 1:+ parser.error("--max-examples must be positive")+ report = compare_runs(args.baseline, args.current, args.max_examples)+ args.output.parent.mkdir(parents=True, exist_ok=True)+ with args.output.open("x") as stream:+ json.dump(report, stream, indent=2, allow_nan=False)+ stream.write("\n")+ print(json.dumps({"report": str(args.output), "passed": report["passed"],+ "scientific_payloads_exact": report["scientific_payloads_exact"],+ "semantic_differences": report["differences"]["count"],+ "full_pipeline_verified": report["full_pipeline_verified"],+ "verified_full_workflow_speedup": report["verified_full_workflow_speedup"]}))+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/dopplergeist/audio.py b/src/dopplergeist/audio.pyindex da3878f..bd3811d 100644--- a/src/dopplergeist/audio.py+++ b/src/dopplergeist/audio.py@@ -67,18 +67,27 @@ def trace_ridge(spectrum, max_slope=12.0, smoothness=0.12, max_up_slope=1.0):history = np.zeros((nt, nf), dtype=np.int16)state = strength[:, 0].copy()frequency_index = np.arange(nf)+ up_width = max(0, int(np.floor(max_up_slope * dt / df)))+ transitions = []+ for shift in range(-up_width, width + 1):+ first, last = max(0, -shift), min(nf, nf - shift)+ if first >= last:+ continue+ destination = slice(first, last)+ source = slice(first + shift, last + shift)+ penalty = smoothness * (shift * df / dt) ** 2 * dt+ transitions.append((destination, source, frequency_index[source], penalty))for j in range(1, nt):best = np.full(nf, -np.inf)parent = np.zeros(nf, dtype=np.int16)- up_width = max(0, int(np.floor(max_up_slope * dt / df)))- for shift in range(-up_width, width + 1):- previous = frequency_index + shift- valid = (previous >= 0) & (previous < nf)- score = np.full(nf, -np.inf)- score[valid] = state[previous[valid]] - smoothness * (shift * df / dt) ** 2 * dt- better = score > best- best[better] = score[better]- parent[better] = previous[better]+ # Valid predecessors are contiguous slices. Reuse their bounds and+ # penalties instead of allocating masks and full score arrays per shift.+ # Shift order and strict improvement preserve the original tie rule.+ for destination, source, previous, penalty in transitions:+ score = state[source] - penalty+ better = score > best[destination]+ np.copyto(best[destination], score, where=better)+ np.copyto(parent[destination], previous, where=better, casting="unsafe")state = best + strength[:, j]history[j] = parentpath = np.empty(nt, dtype=int)diff --git a/src/dopplergeist/data_access.py b/src/dopplergeist/data_access.pyindex eee6dfd..96688fc 100644--- a/src/dopplergeist/data_access.py+++ b/src/dopplergeist/data_access.py@@ -16,8 +16,10 @@ import jsonimport multiprocessingimport osfrom pathlib import Path+import pickleimport sqlite3import tarfile+from threading import Lockimport numpy as npimport pandas as pd@@ -363,9 +365,22 @@ def _parallel_flight_segments(db, max_flight_samples, max_gap_s, namespace, workclass FlightIndex:- """SQLite R-tree of complete, gap-split flight segments; lazy payload reads."""- def __init__(self, path):+ """SQLite R-tree of whole segments with an optional per-instance track cache.++ ``track_cache_bytes`` bounds serialized snapshot bytes retained until this+ instance is released; zero disables reuse. At most 2,048 entries are kept.+ The limit excludes returned tracks, temporary serialization and map overhead.+ Concurrent queries use separate SQLite connections and return independent+ tracks, even when they reuse the same verified snapshot.+ """+ def __init__(self, path, *, track_cache_bytes=32 * 1024 * 1024):+ if type(track_cache_bytes) is not int or track_cache_bytes < 0:+ raise ValueError("Track cache size must be a nonnegative integer")self.path = Path(path)+ self._track_cache = OrderedDict()+ self._track_cache_bytes = 0+ self._track_cache_limit = track_cache_bytes+ self._track_cache_lock = Lock()if not self.path.exists():raise DataUnavailable(f"Missing flight index: {path}")try:@@ -379,6 +394,61 @@ class FlightIndex:def connect(self):return sqlite3.connect(f"{self.path.resolve().as_uri()}?mode=ro", uri=True)+ def _decode_track(self, name, payload, expected, *, max_samples=None, cache_scan=None):+ # Verify every fetched payload, including hits. A cached track must not+ # conceal damage to an index that was changed after the previous query.+ if hashlib.sha256(payload).hexdigest() != expected:+ raise DataUnavailable(f"Corrupt flight payload: {name}")+ key = (name, expected)+ with self._track_cache_lock:+ entry = self._track_cache.get(key)+ if entry is not None:+ count, cached = entry+ if max_samples is not None and count > max_samples:+ raise DataUnavailable("Flight lookup sample budget exceeded")+ self._track_cache.move_to_end(key)+ if cache_scan is not None:+ cache_scan["used"].add(key)+ if entry is not None:+ return pickle.loads(cached)+ frame = pd.DataFrame(json.loads(gzip.decompress(payload)))+ if max_samples is not None and len(frame) > max_samples:+ raise DataUnavailable("Flight lookup sample budget exceeded")+ track = _frame_track(name, frame)+ if self._track_cache_limit and (cache_scan is None or cache_scan["admit"]):+ # These bytes are produced here, never read from a file/request.+ # Restoring them returns independent arrays and mutable diagnostics,+ # while reusing JSON decoding, velocity inference and spline setup.+ cached = pickle.dumps(track, protocol=pickle.HIGHEST_PROTOCOL)+ if len(cached) <= self._track_cache_limit:+ with self._track_cache_lock:+ # Another query can fill this key while decoding runs+ # outside the lock. Never count the same entry twice.+ if key in self._track_cache:+ self._track_cache.move_to_end(key)+ if cache_scan is not None:+ cache_scan["used"].add(key)+ return track+ # Bound serialized values and entry count separately so many+ # tiny segments cannot grow the key/container overhead forever.+ while self._track_cache and (self._track_cache_bytes + len(cached) > self._track_cache_limit+ or len(self._track_cache) >= 2048):+ # A query larger than the cache must not evict entries it+ # just used. Otherwise repeated ordered scans thrash with+ # zero hits. Older entries unused by this query can go.+ if cache_scan is not None and next(iter(self._track_cache)) in cache_scan["used"]:+ # Further misses still decode normally, but do not pay+ # serialization costs after admission stops.+ cache_scan["admit"] = False+ return track+ _, (_, previous) = self._track_cache.popitem(last=False)+ self._track_cache_bytes -= len(previous)+ self._track_cache[key] = (len(frame), cached)+ self._track_cache_bytes += len(cached)+ if cache_scan is not None:+ cache_scan["used"].add(key)+ return track+@classmethoddef build(cls, path, frames, *, sources, coverage, max_gap_s=30.0, max_flight_samples=250000, class_map=None,prepared=False):@@ -504,6 +574,7 @@ class FlightIndex:"""west, south, east, north = boundsstart, end = time_range+ cache_scan = {"used": set(), "admit": True}with self.connect() as db:sql = """SELECT s.name,s.payload,s.payload_hash FROM segments s JOIN spatial r ON s.id=r.idWHERE r.west<=? AND r.east>=? AND r.south<=? AND r.north>=?@@ -518,10 +589,7 @@ class FlightIndex:sql = "SELECT name,payload,payload_hash FROM segments WHERE start<=? AND end>=? ORDER BY name"params = (end, start)for name, payload, expected in db.execute(sql, params):- if hashlib.sha256(payload).hexdigest() != expected:- raise DataUnavailable(f"Corrupt flight payload: {name}")- frame = pd.DataFrame(json.loads(gzip.decompress(payload)))- yield _frame_track(name, frame)+ yield self._decode_track(name, payload, expected, cache_scan=cache_scan)def lookup(self, identifiers, *, max_tracks=2000, max_samples=500000):"""Yield named whole segments without scanning unrelated trajectories.@@ -540,6 +608,7 @@ class FlightIndex:if len(names) > max_tracks:raise DataUnavailable("Flight lookup identifier budget exceeded")names, samples = sorted(names), 0+ cache_scan = {"used": set(), "admit": True}with self.connect() as db:# Stay below SQLite's conservative bound on bound SQL parameters.for first in range(0, len(names), 500):@@ -548,13 +617,10 @@ class FlightIndex:sql = ("SELECT name,payload,payload_hash FROM segments WHERE name IN ("+ placeholders + ") ORDER BY name")for name, payload, expected in db.execute(sql, batch):- if hashlib.sha256(payload).hexdigest() != expected:- raise DataUnavailable(f"Corrupt flight payload: {name}")- frame = pd.DataFrame(json.loads(gzip.decompress(payload)))- samples += len(frame)- if samples > max_samples:- raise DataUnavailable("Flight lookup sample budget exceeded")- yield _frame_track(name, frame)+ track = self._decode_track(name, payload, expected, max_samples=max_samples - samples,+ cache_scan=cache_scan)+ samples += len(track.time)+ yield trackdef coverage_for(self, bounds, time_range):source = self.report["coverage"]diff --git a/src/dopplergeist/discovery.py b/src/dopplergeist/discovery.pyindex ee75eda..acdc173 100644--- a/src/dopplergeist/discovery.py+++ b/src/dopplergeist/discovery.py@@ -6,6 +6,7 @@ aircraft identity. No straight-pass speed/slant fit is required for acceptance.from dataclasses import asdict, dataclassimport jsonfrom pathlib import Path+from statistics import medianimport numpy as npfrom scipy import ndimage, optimize, signal@@ -61,6 +62,20 @@ def _spectrum(data, sr, start, settings):return Spectrum(t + start, f, db, contrast)+def _path_slope(path):+ """Median of the last seven measured increments, using scalar arithmetic.++ Paths contain Python floats. Converting each short tail to three NumPy+ arrays at every frame costs more than its at-most-seven differences.+ Keep the same eight-point window and the same even-count median.+ """+ tail = path[-8:]+ if len(tail) < 3:+ return 0.0+ return median((right[1] - left[1]) / (right[0] - left[0])+ for left, right in zip(tail, tail[1:]))++def _paths(spec, settings):"""Link local spectral maxima with bounded motion and short missing spans."""active, completed = [], []@@ -90,10 +105,7 @@ def _paths(spec, settings):dt = time - last[:, 0]delta = frequencies[None, :] - last[:, 1, None]speed = delta / dt[:, None]- slopes = []- for path in active:- tail = np.asarray(path[-8:])- slopes.append(float(np.median(np.diff(tail[:, 1]) / np.diff(tail[:, 0]))) if len(tail) >= 3 else 0.0)+ slopes = [_path_slope(path) for path in active]allowed = (speed >= -np.maximum(8, last[:, 1, None] * 0.08)) & (speed <= np.maximum(1.0, last[:, 1, None] * 0.008))predicted_delta = np.asarray(slopes)[:, None] * dt[:, None]costs = np.abs(delta - predicted_delta) / np.maximum(1.0, last[:, 1, None] * 0.01)diff --git a/src/dopplergeist/finite_search.py b/src/dopplergeist/finite_search.pyindex 8373f6b..b817f46 100644--- a/src/dopplergeist/finite_search.py+++ b/src/dopplergeist/finite_search.py@@ -5,6 +5,7 @@ import mathfrom contextlib import contextmanagerfrom pathlib import Pathimport sqlite3+from threading import localfrom .data_access import DataUnavailable, content_hash@@ -120,6 +121,7 @@ class RetentionLedger:"""def __init__(self, path, run_hash, score_kind):self.path, self.run_hash, self.score_kind = Path(path), run_hash, score_kind+ self._batch_state = local()self.path.parent.mkdir(parents=True, exist_ok=True)try:with self.connect() as db:@@ -145,11 +147,50 @@ class RetentionLedger:except sqlite3.DatabaseError as error:raise DataUnavailable("Cannot read finite retention ledger") from error+ def _open_connection(self):+ db = sqlite3.connect(self.path)+ try:+ db.execute("PRAGMA cache_size=-8192")+ db.execute("PRAGMA temp_store=FILE")+ except BaseException:+ db.close()+ raise+ return db++ @contextmanager+ def batch(self):+ """Commit a caller-bounded group of stages in one transaction.++ Nested ``connect()`` calls on this thread share the connection. Other+ threads and ledger instances see only committed stages. Checkpoints+ written before a rollback therefore fail the ordinary resume check.+ Nested batches are rejected; callers must bound their work per batch.+ """+ if getattr(self._batch_state, "active", None) is not None:+ raise RuntimeError("Nested retention batches are not supported")+ db = self._open_connection()+ active = {"db": db, "failed": False}+ self._batch_state.active = active+ try:+ with db:+ yield self+ if active["failed"]:+ raise DataUnavailable("Retention batch failed; its stages were not committed")+ finally:+ del self._batch_state.active+ db.close()+@contextmanagerdef connect(self):- db = sqlite3.connect(self.path)- db.execute("PRAGMA cache_size=-8192")- db.execute("PRAGMA temp_store=FILE")+ active = getattr(self._batch_state, "active", None)+ if active is not None:+ try:+ yield active["db"]+ except BaseException:+ active["failed"] = True+ raise+ return+ db = self._open_connection()try:with db:yield dbdiff --git a/src/dopplergeist/terrain.py b/src/dopplergeist/terrain.pyindex 026b166..608a803 100644--- a/src/dopplergeist/terrain.py+++ b/src/dopplergeist/terrain.py@@ -1,10 +1,17 @@"""Terrain sampling and common projected grids."""+from functools import lru_cachefrom pathlib import Pathimport numpy as npfrom pyproj import Transformer+@lru_cache(maxsize=32)+def _raster_transformer(crs):+ """Reuse a raster's unchanged coordinate operation across refinement calls."""+ return Transformer.from_crs("EPSG:4326", crs, always_xy=True)++class Terrain:def __init__(self, paths=None, constant_m=None, geoid_path=None):import rasterio@@ -20,7 +27,7 @@ class Terrain:lat, lon = np.broadcast_arrays(lat, lon)elevation = np.full(lat.shape, np.nan)for raster in self.rasters:- transform = Transformer.from_crs("EPSG:4326", raster.crs, always_xy=True)+ transform = _raster_transformer(raster.crs)x, y = transform.transform(lon.ravel(), lat.ravel())col,row=(~raster.transform) @ (np.asarray(x),np.asarray(y))col,row=np.floor(col).astype(int),np.floor(row).astype(int)diff --git a/src/dopplergeist/tiled_search.py b/src/dopplergeist/tiled_search.pyindex f3e5a4d..920d8d4 100644--- a/src/dopplergeist/tiled_search.py+++ b/src/dopplergeist/tiled_search.py@@ -7,6 +7,7 @@ partition association anchors without narrowing the physical fit intervals.from dataclasses import asdict, dataclassfrom functools import lru_cachefrom importlib.metadata import version+import hashlibimport itertoolsimport jsonimport math@@ -200,13 +201,30 @@ def _expanded_bounds(cells, spacing, radius, crs):return _to_geographic(crs).transform_bounds(*box, densify_pts=101)+def _track_geometry_digest(track):+ """Compare complete geometry without converting every float to JSON text.++ Track geometry uses binary64 arrays. Canonical byte order and explicit shapes+ preserve exact identities (including signed zero) across array layouts. This+ digest is private to duplicate detection; persisted evidence hashes retain+ their existing representation.+ """+ arrays = [np.asarray(values, dtype="<f8")+ for values in (track.time, track.xyz, track.spline.c)]+ if not all(np.all(np.isfinite(values)) for values in arrays):+ # The previous allow_nan=False JSON signature also rejected this case.+ raise ValueError("Nonfinite flight geometry cannot establish an identity")+ digest = hashlib.sha256(json.dumps([track.id, [a.shape for a in arrays]],+ allow_nan=False).encode())+ for values in arrays:+ digest.update(values.tobytes(order="C"))+ return digest.hexdigest()++def _tracks(indexes, bounds, time_range, budget, *, observers=None, radius=None, c=343.0):tracks, identities, samples = [], {}, 0queried, queried_samples = 0, 0- def signature(track):- return content_hash([track.id, track.time.tolist(), track.xyz.tolist(), track.spline.c.tolist()])-for index in indexes:for track in index.query(bounds, time_range):if observers is not None:@@ -221,8 +239,8 @@ def _tracks(indexes, bounds, time_range, budget, *, observers=None, radius=None,# silently dropping different geometry would change the physics.if track.id in identities:previous = identities[track.id]- previous_signature = previous if isinstance(previous, str) else signature(previous)- if signature(track) != previous_signature:+ previous_signature = previous if isinstance(previous, str) else _track_geometry_digest(previous)+ if _track_geometry_digest(track) != previous_signature:raise DataUnavailable(f"Conflicting flight segment identity: {track.id}")continueif observers is not None:@@ -233,7 +251,7 @@ def _tracks(indexes, bounds, time_range, budget, *, observers=None, radius=None,# their missing support, even when they appear distant.distant = Falseif distant:- identities[track.id] = signature(track)+ identities[track.id] = _track_geometry_digest(track)continueidentities[track.id] = tracktracks.append(track)@@ -602,7 +620,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outevent_limit = len(events)event_limit_applied = filters["association"] == "subsets" and event_limit < len(events)import os- from contextlib import nullcontext+ from contextlib import ExitStack, nullcontextfrom .data_access import CachedTerrain, _index_poolfrom .parallel_retention import import_retention_stagefrom .parallel_tiles import TileFailure, initialize_tile_worker, ordered_tile_results@@ -766,7 +784,16 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif coarse_cells:report_search_progress(0.8 * processed_cells / coarse_cells)- with context as pool:+ with context as pool, ExitStack() as empty_batches:+ empty_batch_tiles = 0++ def flush_empty_tiles():+ nonlocal empty_batch_tiles+ try:+ empty_batches.close()+ finally:+ empty_batch_tiles = 0+roots = grid_tiles(bounds, budget.spacing_m, budget.tile_cells, crs)wave = itertools.islice(roots, budget.max_tiles) if budget.max_tiles is not None else rootswhile wave is not None:@@ -778,6 +805,8 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outtile_id = stage[len("coarse:"):]checkpoint = output / f"tile-{tile_id}.json"terminal = True+ if prepared is not None:+ flush_empty_tiles()try:if isinstance(prepared, BaseException):raise prepared@@ -799,6 +828,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif not tracks:points = pd.DataFrame()if len(points):+ flush_empty_tiles()anchor = _tile_anchor_window(tile_id, start_window, parameters, filters, events)rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,ledger=ledger, stage=stage,@@ -807,6 +837,13 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif floor_policy == "global_and_per_tile" else None))else:rows, counts = [], {}+ # Keep all coarse/global stage records, but amortize+ # durable commits across at most 32 empty tiles.+ # A crash can leave uncommitted checkpoint files;+ # tile_request rejects those through stage_valid.+ if empty_batch_tiles == 0:+ empty_batches.enter_context(ledger.batch())+ empty_batch_tiles += 1ledger.record(stage, [], [], 0)used = getattr(terrain, "last_sample_files", set()) if sampled else set()terrain_files = [terrain.files[name] for name in sorted(used)] if used else []@@ -841,9 +878,12 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outnext_wave.extend((child_id, tuple(child_cells)) for child_id, child_cells in children)else:failures.append({"tile": tile_id, "reason": str(error)})+ if empty_batch_tiles >= 32:+ flush_empty_tiles()if terminal and (pool is None or was_cached or isinstance(prepared, BaseException)):advance_progress(stage, cells)wave = sorted(next_wave, key=tile_order) if next_wave else None+ flush_empty_tiles()report_search_progress(0.8, force=True)coarse = list(ranked)# Refine only global finalists; tile selection never controls refinement rank.diff --git a/tests/data/reference-empty-tiles-real.json b/tests/data/reference-empty-tiles-real.jsonnew file mode 100644index 0000000..48f3a9a--- /dev/null+++ b/tests/data/reference-empty-tiles-real.json@@ -0,0 +1,195 @@+{+ "source": "Actual empty checkpoints from the complete public reference recording and historical ADS-B replay. Used for transaction correctness, not location accuracy.",+ "source_revision": "7a8dd27979bd9a984c8675c38a00dfbf98a5b01e",+ "recording_start_window_s": [+ 1788898640.0,+ 1788898660.0+ ],+ "score_kind": "matched_group_support_minus_normalized_residual",+ "tiles": [+ {+ "tile_id": "-10_3",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "e21f99a39a4aef3a04c7cd02f26b8ca0eae32c8089bc44213177d8bd97d36017",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -160,+ 54,+ -144,+ 64+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-10_4",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "e5b611f7f6d32bd15ff3dbedb6ca64d51d13090aa5c1feea048be2226d0a8922",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -160,+ 64,+ -144,+ 80+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-10_5",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "f309036be0e755701ecb90e5cd5b73c911d371b0d77def7f003eab09864f1344",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -160,+ 80,+ -144,+ 96+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-10_6",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "14b90a810587f5bab178db7fb8671f169bb56b8a166da11f959285a803bdc7a5",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -160,+ 96,+ -144,+ 112+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-11_3",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "7bdf3f9bb725f6de7cfff5aa7d4787db28ef1218b4b3ccdfd2ad8ff43ffbc74a",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -176,+ 54,+ -160,+ 64+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-11_4",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "a5b4df960a0ef7b085118a015c99c2eff09fecadfe15e8f8900dd3253e54b700",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -176,+ 64,+ -160,+ 80+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-11_5",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "dc2ed459e3805c09247de35dee3da42d5357d017102dd4a7914ddc4c3524d7c8",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -176,+ 80,+ -160,+ 96+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ },+ {+ "tile_id": "-11_6",+ "checkpoint": {+ "run_hash": "325db0284c070f24313517f8b8c0dcfde7e7baa79283c23a20f2c0f3250d2e24",+ "payload_hash": "702f9c1e50070f396c2f60734b918e2fa523d69542200a7e49c48445ff186ec4",+ "payload": {+ "ranked": [],+ "counts": {},+ "grid_points": 0,+ "tracks": 0,+ "cells": [+ -176,+ 96,+ -160,+ 112+ ],+ "terrain_files": [],+ "terrain_ocean_tiles": [],+ "terrain_failures": [],+ "retention_checksum": "d0edf5f14ccc1f891ccc12df579f8761517f5f41b207dede78db05ec223b257a"+ }+ }+ }+ ]+}diff --git a/tests/test_real_performance_helpers.py b/tests/test_real_performance_helpers.pynew file mode 100644index 0000000..735f924--- /dev/null+++ b/tests/test_real_performance_helpers.py@@ -0,0 +1,145 @@+"""Exact helper checks using archived observations and real restored rasters."""+from copy import copy+import json+from pathlib import Path+from types import SimpleNamespace++import numpy as np+import pandas as pd+import pytest+from pyproj import Transformer++from dopplergeist import terrain, tiled_search+from dopplergeist.data_access import DataUnavailable, FlightIndex, content_hash+from dopplergeist.geometry import ecef+++ROOT = Path(__file__).resolve().parents[1]+++def _json_geometry_digest(track):+ return content_hash([track.id, track.time.tolist(), track.xyz.tolist(), track.spline.c.tolist()])++[email protected](scope="module")+def independent_real_tracks(tmp_path_factory):+ source = ROOT / "research/trajectory-motion/frozen/canonical-observations.json"+ frame = pd.DataFrame(json.loads(source.read_text()))+ coverage = {"bounds": [-180, -90, 180, 90],+ "time_range_s": [float(frame.time_s.min()), float(frame.time_s.max())],+ "all_aircraft": False,+ "source_note": "Archived real trajectory-motion observations; incomplete excerpt"}+ path = tmp_path_factory.mktemp("real-helper-index") / "real.sqlite"+ FlightIndex.build(path, [frame], sources=[], coverage=coverage)+ decoded = [list(FlightIndex(path, track_cache_bytes=0).query(+ coverage["bounds"], coverage["time_range_s"])) for _ in range(2)]+ assert len(decoded[0]) >= 2+ return decoded+++def test_geometry_identity_matches_old_json_for_independent_decodes(independent_real_tracks):+ first, second = independent_real_tracks+ assert [track.id for track in first] == [track.id for track in second]+ all_tracks = first + second+ old = [_json_geometry_digest(track) for track in all_tracks]+ new = [tiled_search._track_geometry_digest(track) for track in all_tracks]+ # The encoding changes; its equality relation must remain identical.+ assert [[a == b for b in old] for a in old] == [[a == b for b in new] for a in new]+ for left, right in zip(first, second):+ assert left is not right+ np.testing.assert_array_equal(left.time, right.time)+ np.testing.assert_array_equal(left.xyz, right.xyz)+ np.testing.assert_array_equal(left.spline.c, right.spline.c)++[email protected]("layout", ["fortran", "big_endian", "strided"])+def test_geometry_identity_preserves_values_across_storage_layouts(independent_real_tracks, layout):+ def rearrange(values):+ if layout == "fortran":+ return np.asfortranarray(values)+ if layout == "big_endian":+ return np.asarray(values, dtype=">f8")+ # Repeat storage, then view every other element: no observation changes.+ return np.repeat(values, 2, axis=-1)[..., ::2]++ for track in independent_real_tracks[0]:+ other = SimpleNamespace(id=track.id, time=rearrange(track.time),+ xyz=rearrange(track.xyz),+ spline=SimpleNamespace(c=rearrange(track.spline.c)))+ assert _json_geometry_digest(other) == _json_geometry_digest(track)+ assert tiled_search._track_geometry_digest(other) == tiled_search._track_geometry_digest(track)+++class _DecodedIndex:+ def __init__(self, tracks):+ self.tracks = tracks++ def query(self, bounds, time_range):+ return iter(self.tracks)++[email protected]("use_observer", [False, True])+def test_duplicate_track_selection_matches_json_identity(independent_real_tracks, monkeypatch, use_observer):+ indexes = [_DecodedIndex(tracks) for tracks in independent_real_tracks]+ kwargs = {}+ if use_observer:+ row = json.loads((ROOT / "evidence/results/reference-local-fast/ranked.json").read_text())[0]+ kwargs = {"observers": ecef([row["lat"]], [row["lon"]], [row["elev_m"]]), "radius": 25000.0}+ args = (indexes, [-180, -90, 180, 90], [-np.inf, np.inf], tiled_search.SearchBudget())+ actual = tiled_search._tracks(*args, **kwargs)+ with monkeypatch.context() as patch:+ patch.setattr(tiled_search, "_track_geometry_digest", _json_geometry_digest)+ expected = tiled_search._tracks(*args, **kwargs)+ assert [id(track) for track in actual] == [id(track) for track in expected]+ assert len({track.id for track in actual}) == len(actual)+ if use_observer:+ # Exercise identities stored as digests after a real distant-track skip.+ assert len(actual) < len(independent_real_tracks[0])+ else:+ assert len(actual) == len(independent_real_tracks[0])+++def test_conflicting_real_track_identity_is_still_rejected(independent_real_tracks, monkeypatch):+ first, second = independent_real_tracks[0][:2]+ conflict = copy(second)+ conflict.id = first.id # A metadata collision; both observed geometries stay intact.+ assert _json_geometry_digest(first) != _json_geometry_digest(conflict)+ args = ([_DecodedIndex([first]), _DecodedIndex([conflict])],+ [-180, -90, 180, 90], [-np.inf, np.inf], tiled_search.SearchBudget())+ with pytest.raises(DataUnavailable, match="Conflicting flight segment identity"):+ tiled_search._tracks(*args)+ with monkeypatch.context() as patch:+ patch.setattr(tiled_search, "_track_geometry_digest", _json_geometry_digest)+ with pytest.raises(DataUnavailable, match="Conflicting flight segment identity"):+ tiled_search._tracks(*args)++[email protected]("with_geoid", [False, True])+def test_cached_raster_transform_preserves_actual_candidate_heights(monkeypatch, with_geoid):+ dem = ROOT / "data/terrain/Copernicus_DSM_COG_10_N40_00_W074_00_DEM.tif"+ geoid = ROOT / "data/terrain/us_nga_egm96_15.tif"+ if not dem.exists() or (with_geoid and not geoid.exists()):+ pytest.skip("Restore the actual reference DEM/geoid to exercise terrain sampling")+ rows = json.loads((ROOT / "evidence/results/reference-local-fast/ranked.json").read_text())+ lat = np.asarray([row["lat"] for row in rows])+ lon = np.asarray([row["lon"] for row in rows])+ sampler = terrain.Terrain([dem], geoid_path=geoid if with_geoid else None)+ terrain._raster_transformer.cache_clear()+ try:+ actual = sampler.sample(lat, lon)+ actual_scalar = np.asarray([sampler.sample(a, b).item() for a, b in zip(lat[:16], lon[:16])])+ assert terrain._raster_transformer.cache_info().hits > 0+ with monkeypatch.context() as patch:+ patch.setattr(terrain, "_raster_transformer",+ lambda crs: Transformer.from_crs("EPSG:4326", crs, always_xy=True))+ expected = sampler.sample(lat, lon)+ expected_scalar = np.asarray([sampler.sample(a, b).item()+ for a, b in zip(lat[:16], lon[:16])])+ np.testing.assert_array_equal(actual, expected)+ np.testing.assert_array_equal(actual_scalar, expected_scalar)+ finally:+ for raster in sampler.rasters:+ raster.close()+ if sampler.geoid:+ for raster in sampler.geoid.rasters:+ raster.close()diff --git a/tests/test_real_retention_batch.py b/tests/test_real_retention_batch.pynew file mode 100644index 0000000..499d92f--- /dev/null+++ b/tests/test_real_retention_batch.py@@ -0,0 +1,125 @@+"""Transaction checks against recorded empty tiles from the real reference run."""+import json+from pathlib import Path+import sqlite3++import pytest++from dopplergeist.data_access import DataUnavailable, write_json+from dopplergeist.finite_search import RetentionLedger+from dopplergeist.tiled_search import merge_candidates+++def real_tiles():+ path = Path(__file__).parent / "data/reference-empty-tiles-real.json"+ fixture = json.loads(path.read_text())+ assert fixture["tiles"]+ for tile in fixture["tiles"]:+ payload = tile["checkpoint"]["payload"]+ assert payload["tracks"] == 0 and payload["ranked"] == [] and payload["counts"] == {}+ return fixture+++def ledger(path, fixture):+ return RetentionLedger(path, fixture["tiles"][0]["checkpoint"]["run_hash"], fixture["score_kind"])+++def record_tile(target, tile):+ checksum = tile["checkpoint"]["payload"]["retention_checksum"]+ for phase in ("coarse", "global"):+ stage = f"{phase}:{tile['tile_id']}"+ assert target.record(stage, [], [], 0) == checksum+ assert target.checksum(stage) == checksum+++def contents(target):+ with target.connect() as db:+ return {table: db.execute(f"SELECT * FROM {table} ORDER BY 1,2").fetchall()+ for table in ("run", "stages", "records", "bounds")}+++def test_recorded_empty_stage_rows_and_checksums_match_in_batches(real_tiles, tmp_path):+ serial = ledger(tmp_path / "serial.sqlite", real_tiles)+ batched = ledger(tmp_path / "batched.sqlite", real_tiles)+ for tile in real_tiles["tiles"]:+ record_tile(serial, tile)+ for first in range(0, len(real_tiles["tiles"]), 3):+ with batched.batch():+ for tile in real_tiles["tiles"][first:first + 3]:+ record_tile(batched, tile)+ assert contents(batched) == contents(serial)+ for tile in real_tiles["tiles"]:+ expected = tile["checkpoint"]["payload"]["retention_checksum"]+ for phase in ("coarse", "global"):+ assert batched.stage_valid(f"{phase}:{tile['tile_id']}", expected)+++def test_empty_tile_batches_preserve_previous_real_retained_modes(real_tiles, tmp_path):+ # Empty tiles can still write nonempty global stages after a supported tile.+ # These are archived fits from the original recording, not invented scores.+ rows = json.loads((Path(__file__).parent / "data/reference-retention-real.json").read_text())["rows"]+ serial = ledger(tmp_path / "retained-serial.sqlite", real_tiles)+ batched = ledger(tmp_path / "retained-batched.sqlite", real_tiles)++ def replay(target):+ ranked = merge_candidates(rows, 3, ledger=target, stage="recorded-fits")+ for tile in real_tiles["tiles"]:+ target.record(f"coarse:{tile['tile_id']}", [], [], 0)+ ranked = merge_candidates(ranked, 3, ledger=target, stage=f"global:{tile['tile_id']}")+ return ranked++ expected = replay(serial)+ with batched.batch():+ actual = replay(batched)+ assert actual == expected+ assert contents(batched) == contents(serial)+ for tile in real_tiles["tiles"]:+ stage = f"global:{tile['tile_id']}"+ assert batched.stage_valid(stage, serial.checksum(stage))+++def test_interrupted_batch_invalidates_checkpoint_until_replayed(real_tiles, tmp_path):+ writer = ledger(tmp_path / "resume.sqlite", real_tiles)+ reader = ledger(writer.path, real_tiles)+ tile = real_tiles["tiles"][0]+ stage = f"coarse:{tile['tile_id']}"+ expected = tile["checkpoint"]["payload"]["retention_checksum"]+ checkpoint = tmp_path / f"tile-{tile['tile_id']}.json"+ with pytest.raises(RuntimeError, match="interrupted"):+ with writer.batch():+ record_tile(writer, tile)+ write_json(checkpoint, tile["checkpoint"])+ assert writer.stage_valid(stage, expected)+ assert not reader.stage_valid(stage, expected)+ raise RuntimeError("interrupted batch")+ assert checkpoint.exists()+ assert not reader.stage_valid(stage, expected)+ with writer.batch():+ record_tile(writer, tile)+ assert reader.stage_valid(stage, expected)+++def test_caught_connection_error_does_not_commit_partial_batch(real_tiles, tmp_path):+ target = ledger(tmp_path / "caught.sqlite", real_tiles)+ tile = real_tiles["tiles"][0]+ with pytest.raises(DataUnavailable, match="not committed"):+ with target.batch():+ record_tile(target, tile)+ try:+ with target.connect() as db:+ db.execute("SELECT * FROM nonexistent_batch_test_table")+ except sqlite3.OperationalError:+ pass+ assert not target.stage_valid(f"coarse:{tile['tile_id']}", tile["checkpoint"]["payload"]["retention_checksum"])+++def test_nested_batch_is_rejected_and_outer_work_rolls_back(real_tiles, tmp_path):+ target = ledger(tmp_path / "nested.sqlite", real_tiles)+ tile = real_tiles["tiles"][0]+ with pytest.raises(RuntimeError, match="Nested retention batches"):+ with target.batch():+ record_tile(target, tile)+ with target.batch():+ pass+ assert not target.stage_valid(f"coarse:{tile['tile_id']}", tile["checkpoint"]["payload"]["retention_checksum"])diff --git a/tests/test_real_track_cache.py b/tests/test_real_track_cache.pynew file mode 100644index 0000000..5060349--- /dev/null+++ b/tests/test_real_track_cache.py@@ -0,0 +1,208 @@+"""Track reuse checks using archived ADS-B observations, never generated tracks."""+from concurrent.futures import ThreadPoolExecutor+import gzip+import hashlib+import json+from pathlib import Path+import pickle+import sqlite3+from threading import Barrier++import numpy as np+import pandas as pd+import pytest++from dopplergeist import data_access+from dopplergeist.data_access import DataUnavailable, FlightIndex+++def snapshot_size(track):+ return len(pickle.dumps(track, protocol=pickle.HIGHEST_PROTOCOL))+++def real_index(tmp_path):+ source = Path(__file__).resolve().parents[1] / "research/trajectory-motion/frozen/canonical-observations.json"+ frame = pd.DataFrame(json.loads(source.read_text()))+ coverage = {"bounds": [-180, -90, 180, 90],+ "time_range_s": [float(frame.time_s.min()), float(frame.time_s.max())],+ "all_aircraft": False, "source_note": "Archived real trajectory-motion observations; incomplete excerpt"}+ index = FlightIndex.build(tmp_path / "real.sqlite", [frame], sources=[], coverage=coverage)+ return index.path, coverage+++def assert_tracks_equal(actual, expected):+ assert [track.id for track in actual] == [track.id for track in expected]+ for got, want in zip(actual, expected):+ assert got is not want+ for name in ("time", "lat", "lon", "altitude", "velocity", "xyz", "_xyz_min", "_xyz_max",+ "relative_time", "_speed_upper", "_speed_peak"):+ if getattr(want, name) is None:+ assert getattr(got, name) is None+ else:+ np.testing.assert_array_equal(getattr(got, name), getattr(want, name))+ for name in ("spline", "derivative"):+ np.testing.assert_array_equal(getattr(got, name).c, getattr(want, name).c)+ np.testing.assert_array_equal(getattr(got, name).x, getattr(want, name).x)+ for name in ("typecode", "origin", "_max_sample_gap", "aircraft_class", "altitude_basis",+ "velocity_inferred_components"):+ assert getattr(got, name) == getattr(want, name)+++def test_real_query_and_lookup_reuse_track_setup(real_index, monkeypatch):+ path, coverage = real_index+ expected = list(FlightIndex(path, track_cache_bytes=0).query(coverage["bounds"], coverage["time_range_s"]))+ original, calls = data_access._frame_track, []++ def decode(name, frame):+ calls.append(name)+ return original(name, frame)++ monkeypatch.setattr(data_access, "_frame_track", decode)+ cached = FlightIndex(path)+ first = list(cached.query(coverage["bounds"], coverage["time_range_s"]))+ assert_tracks_equal(first, expected)+ assert len(calls) == len(expected) > 0+ second = list(cached.query(coverage["bounds"], coverage["time_range_s"]))+ looked_up = list(cached.lookup(track.id for track in expected))+ assert_tracks_equal(second, expected)+ assert_tracks_equal(looked_up, expected)+ assert len(calls) == len(expected)+ assert cached._track_cache_bytes <= cached._track_cache_limit+++def test_real_cached_tracks_do_not_share_caller_mutations(real_index):+ path, coverage = real_index+ expected = list(FlightIndex(path, track_cache_bytes=0).query(coverage["bounds"], coverage["time_range_s"]))+ cached = FlightIndex(path)+ for _ in range(2): # Exercise both the initial return and a cache hit.+ got = list(cached.query(coverage["bounds"], coverage["time_range_s"]))+ assert_tracks_equal(got, expected)+ got[0].time[0] += 1+ got[0].spline.c[0, 0, 0] += 1+ got[0]._speed_peak[:] = 0+ got[0].altitude_basis[0] = "caller changed label"+ got[0].velocity_inferred_components["east_mps"] = -1+ assert_tracks_equal(list(cached.lookup(track.id for track in expected)), expected)+++def test_real_cache_hit_still_checks_payload_integrity(real_index):+ path, coverage = real_index+ cached = FlightIndex(path)+ track = next(cached.query(coverage["bounds"], coverage["time_range_s"]))+ with sqlite3.connect(path) as db:+ db.execute("UPDATE segments SET payload=? WHERE name=?", (b"corrupted index payload", track.id))+ with pytest.raises(DataUnavailable, match="Corrupt flight payload"):+ list(cached.lookup([track.id]))+++def test_real_cache_observes_replaced_payload(real_index, monkeypatch):+ path, coverage = real_index+ cached = FlightIndex(path)+ expected = next(cached.query(coverage["bounds"], coverage["time_range_s"]))+ with sqlite3.connect(path) as db:+ old = db.execute("SELECT payload FROM segments WHERE name=?", (expected.id,)).fetchone()[0]+ # Change only the gzip header; every archived observation is unchanged.+ payload = gzip.compress(gzip.decompress(old), compresslevel=6, mtime=1)+ assert payload != old+ db.execute("UPDATE segments SET payload=?,payload_hash=? WHERE name=?",+ (payload, hashlib.sha256(payload).hexdigest(), expected.id))+ original, calls = data_access._frame_track, []++ def decode(name, frame):+ calls.append(name)+ return original(name, frame)++ monkeypatch.setattr(data_access, "_frame_track", decode)+ assert_tracks_equal(list(cached.lookup([expected.id])), [expected])+ assert calls == [expected.id]+++def test_real_cache_evicts_and_skips_oversized_tracks(real_index, monkeypatch):+ path, coverage = real_index+ tracks = list(FlightIndex(path, track_cache_bytes=0).query(coverage["bounds"], coverage["time_range_s"]))+ first, second = tracks[:2]+ sizes = [snapshot_size(track) for track in (first, second)]+ cached = FlightIndex(path, track_cache_bytes=max(sizes))+ original, calls = data_access._frame_track, []++ def decode(name, frame):+ calls.append(name)+ return original(name, frame)++ monkeypatch.setattr(data_access, "_frame_track", decode)+ for track in (first, second, first):+ assert_tracks_equal(list(cached.lookup([track.id])), [track])+ assert len(cached._track_cache) == 1+ assert cached._track_cache_bytes <= max(sizes)+ assert calls == [first.id, second.id, first.id]+ too_small = FlightIndex(path, track_cache_bytes=min(sizes) - 1)+ assert_tracks_equal(list(too_small.lookup([first.id])), [first])+ assert not too_small._track_cache+ assert too_small._track_cache_bytes == 0+++def test_real_query_larger_than_cache_keeps_a_reusable_subset(real_index, monkeypatch):+ path, coverage = real_index+ expected = list(FlightIndex(path, track_cache_bytes=0).query(coverage["bounds"], coverage["time_range_s"]))+ size = snapshot_size(expected[0])+ cached = FlightIndex(path, track_cache_bytes=size)+ original, calls = data_access._frame_track, []+ serialize, snapshots = data_access.pickle.dumps, []++ def decode(name, frame):+ calls.append(name)+ return original(name, frame)++ def snapshot(track, **kwargs):+ snapshots.append(track.id)+ return serialize(track, **kwargs)++ monkeypatch.setattr(data_access, "_frame_track", decode)+ monkeypatch.setattr(data_access.pickle, "dumps", snapshot)+ assert_tracks_equal(list(cached.query(coverage["bounds"], coverage["time_range_s"])), expected)+ assert len(calls) == len(expected)+ assert len(cached._track_cache) == 1+ assert next(iter(cached._track_cache))[0] == expected[0].id+ assert_tracks_equal(list(cached.query(coverage["bounds"], coverage["time_range_s"])), expected)+ assert len(calls) == 2 * len(expected) - 1+ assert cached._track_cache_bytes == size+ assert len(snapshots) < len(calls) # Admission failure avoids work on later misses.+++def test_real_lookup_sample_budget_precedes_track_allocation(real_index, monkeypatch):+ path, coverage = real_index+ cached = FlightIndex(path)+ track = next(cached.query(coverage["bounds"], coverage["time_range_s"]))++ def must_not_decode(*args, **kwargs):+ raise AssertionError("Over-budget lookup allocated a Track")++ monkeypatch.setattr(data_access, "_frame_track", must_not_decode)+ monkeypatch.setattr(data_access.pickle, "loads", must_not_decode)+ for index in (cached, FlightIndex(path, track_cache_bytes=0)):+ with pytest.raises(DataUnavailable, match="Flight lookup sample budget exceeded"):+ list(index.lookup([track.id], max_samples=len(track.time) - 1))+++def test_real_concurrent_cache_misses_do_not_double_count(real_index, monkeypatch):+ path, coverage = real_index+ expected = next(FlightIndex(path, track_cache_bytes=0).query(coverage["bounds"], coverage["time_range_s"]))+ cached = FlightIndex(path)+ original, ready = data_access._frame_track, Barrier(4)++ def concurrent_decode(name, frame):+ track = original(name, frame)+ # Force concurrent misses for one real payload. This also checks that+ # expensive decoding is outside the cache lock, rather than serializing it.+ ready.wait(timeout=10)+ return track++ monkeypatch.setattr(data_access, "_frame_track", concurrent_decode)+ with ThreadPoolExecutor(max_workers=4) as pool:+ results = list(pool.map(lambda _: list(cached.lookup([expected.id])), range(4)))+ for result in results:+ assert_tracks_equal(result, [expected])+ assert len(cached._track_cache) == 1+ assert cached._track_cache_bytes == sum(len(value[1]) for value in cached._track_cache.values())+ assert cached._track_cache_bytes <= cached._track_cache_limit