Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Integrate exact fit reuse with main and verify a matched real HTTP workload
Cinna Davis66146714c6c2
diff --cc .github/workflows/real-performance.ymlindex 2794633,2794633..e7a813c--- a/.github/workflows/real-performance.yml+++ b/.github/workflows/real-performance.yml@@@ -7,19 -7,19 +7,26 @@@ ondefault: d7cc1dd2e8089768253492b3269dfae97b3ad1a4required: truepush:-- branches: [perf/measured-hotpath-20261103]++ branches: [perf/measured-hotpath-20261103, perf/real-pipeline-throughput-20261103]paths:- .github/workflows/real-performance.yml-- - src/dopplergeist/geometry.py-- - src/dopplergeist/matching.py-- - src/dopplergeist/batch_ridge.py-- - src/dopplergeist/search.py++ - src/dopplergeist/**- scripts/benchmark_prepared_measurements.py++ - scripts/benchmark_real_bounded_upload.py++ - scripts/prepare_reference_upload.py++ - scripts/restore_artifacts.py++ - scripts/compare_real_upload_performance.py++ - scripts/check_real_upload_arrays.py++ - pyproject.toml- tests/test_real_*.py++ - tests/data/real-ridge-batch-arithmetic.json++ - tests/data/reference-empty-tiles-real.json++ - tests/data/reference-retention-real.jsonpermissions:contents: readjobs:compare:++ if: github.event_name != 'push' || github.ref != 'refs/heads/perf/real-pipeline-throughput-20261103'runs-on: ubuntu-latesttimeout-minutes: 20env:@@@ -76,3 -76,3 +83,172 @@@path: results/performance-*if-no-files-found: ignoreretention-days: 3++++ bounded-http:++ if: github.event_name == 'push' && github.ref == 'refs/heads/perf/real-pipeline-throughput-20261103'++ runs-on: ubuntu-latest++ timeout-minutes: 45++ env:++ OPENBLAS_NUM_THREADS: '1'++ OMP_NUM_THREADS: '1'++ MKL_NUM_THREADS: '1'++ NUMEXPR_NUM_THREADS: '1'++ PYTHONPATH: src++ BASELINE_REF: aa3dff686c989524daa20c081a816b792d9c8890++ steps:++ - uses: actions/checkout@v4++ with:++ fetch-depth: 0++ - uses: actions/setup-python@v5++ with:++ python-version: '3.12'++ - name: Install matched runtime++ run: |++ python -m pip install '.[test]' 'numpy==2.3.5' 'scipy==1.17.0' 'pandas==2.2.3' 'pyarrow==26.0.1' 'pyproj==3.8.0' 'matplotlib==3.10.8'++ sudo apt-get update++ sudo apt-get install -y ffmpeg++ - name: Restore public recording and observed inputs++ env:++ GH_TOKEN: ${{ github.token }}++ run: python scripts/restore_artifacts.py --bundle data-source --bundle data-adsb-derived --bundle data-terrain++ - name: Prepare one shared workload++ run: |++ python scripts/prepare_reference_upload.py --data-root data --output benchmark-http-inputs++ git worktree add --detach "$RUNNER_TEMP/http-baseline-source" "$BASELINE_REF"++ python - <<'PY'++ import json++ from pathlib import Path++ root = Path("benchmark-http-inputs")++ request = json.loads((root / "request.json").read_text())++ request["search"]["bounds_wsen"] = [-73.545, 40.865, -73.505, 40.895]++ request["time_window"]["source_detail"] = (++ "Source-informed integration replay around the historical fitted recording "++ "start and benchmark receiver region; not independently measured recording "++ "time or a location-accuracy evaluation."++ )++ operator = json.loads((root / "operator.json").read_text())++ operator["search_workers"] = 1++ for name, value in (("request.json", request), ("operator.json", operator)):++ (root / name).write_text(json.dumps(value, indent=2) + "\n")++ PY++ ffmpeg -n -nostdin -v error -i data/source/reference-recording.wav -map 0:a:0 -vn -map_metadata -1 -ac 1 -ar 48000 -c:a libmp3lame -b:a 96k benchmark-http-inputs/recording.mp3++ python scripts/benchmark_prepared_measurements.py prepare --discovery evidence/audio/w1-sensitivity-20261102/reference/discovery.json --index benchmark-http-inputs/reference-region.sqlite --clock-half-width-s 120 --output benchmark-http-inputs/point-120.json++ - name: Recorded-input regression checks++ id: real_checks++ env:++ DOPPLERGEIST_REAL_CPA_FIXTURE: benchmark-http-inputs/point-120.json++ run: |++ mkdir -p results++ python -m pytest -q \++ tests/test_real_prepared_measurements.py \++ tests/test_real_geometry_kinematics.py \++ tests/test_real_batch_scalar_parity.py \++ tests/test_real_complete_batch_cache.py \++ tests/test_real_legacy_batch_cache.py \++ tests/test_real_refinement_lookup.py \++ tests/test_real_track_cache.py \++ tests/test_real_retention_batch.py \++ tests/test_real_retention_floor.py \++ tests/test_real_performance_helpers.py::test_cached_raster_transform_preserves_actual_candidate_heights \++ --junitxml=results/ci-real-tests.xml++ python - <<'CHECKS'++ import json++ from pathlib import Path++ import xml.etree.ElementTree as ET++ cases = ET.parse(Path("results/ci-real-tests.xml")).getroot().findall(".//testcase")++ skipped = [case.attrib.get("name") for case in cases if case.find("skipped") is not None]++ print(json.dumps({"selected_real_tests": len(cases), "skipped": skipped}))++ if not cases or skipped:++ raise SystemExit("Selected real-input checks must execute without skips")++ CHECKS++ - name: Record this new workload and runtime++ id: context++ run: |++ python - <<'PY'++ import hashlib++ import importlib.metadata++ import json++ import os++ from pathlib import Path++ import platform++ import subprocess++ output = Path("results")++ output.mkdir(exist_ok=True)++ audio = Path("benchmark-http-inputs/recording.mp3")++ with audio.open("rb") as stream:++ digest = hashlib.file_digest(stream, "sha256").hexdigest()++ record = {++ "scope": "One fresh sequential matched HTTP pair on a new MP3 encoding of the public real WAV. Timings and event counts do not inherit the earlier original-MP3 measurements. Source-informed region/time; not independent location accuracy.",++ "baseline": os.environ["BASELINE_REF"],++ "current": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),++ "python": platform.python_version(),++ "packages": {name: importlib.metadata.version(name) for name in ("numpy", "scipy", "pandas", "pyarrow", "pyproj", "rasterio", "matplotlib")},++ "ffmpeg": subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0],++ "encoding": {"codec": "libmp3lame", "bitrate": "96k", "sample_rate_hz": 48000, "channels": 1},++ "source_sha256": digest,++ "source_bytes": audio.stat().st_size,++ "request": json.loads(Path("benchmark-http-inputs/request.json").read_text()),++ "operator": json.loads(Path("benchmark-http-inputs/operator.json").read_text()),++ }++ (output / "http-comparison-context.json").write_text(json.dumps(record, indent=2, allow_nan=False) + "\n")++ PY++ - name: Fresh baseline HTTP arm++ id: baseline++ run: python scripts/benchmark_real_bounded_upload.py --source "$RUNNER_TEMP/http-baseline-source/src" --inputs benchmark-http-inputs --output results/http-baseline --timeout-s 900++ - name: Fresh integrated HTTP arm++ id: current++ if: ${{ !cancelled() && steps.context.outcome == 'success' }}++ run: python scripts/benchmark_real_bounded_upload.py --source "$GITHUB_WORKSPACE/src" --inputs benchmark-http-inputs --output results/http-current --timeout-s 900++ - name: Compare complete scientific JSON and SQLite++ if: always() && steps.baseline.outcome == 'success' && steps.current.outcome == 'success'++ run: python scripts/compare_real_upload_performance.py --baseline results/http-baseline --current results/http-current --output results/http-science-comparison.json++ - name: Compare intake, decoded PCM, arrays, and PNG pixels++ if: always() && steps.baseline.outcome == 'success' && steps.current.outcome == 'success'++ run: python scripts/check_real_upload_arrays.py --baseline results/http-baseline --current results/http-current --output results/http-array-comparison.json++ - name: Print compact comparison results++ if: always()++ run: |++ python - <<'REPORT'++ import json++ from pathlib import Path++ def read(name):++ path = Path("results") / name++ if not path.is_file():++ return {"missing": str(path)}++ try:++ return json.loads(path.read_text())++ except (OSError, ValueError) as error:++ return {"read_error": str(error), "path": str(path)}++ def select(value, fields):++ if "missing" in value or "read_error" in value:++ return value++ return {key: value[key] for key in fields if key in value}++ science = read("http-science-comparison.json")++ arrays = read("http-array-comparison.json")++ passed = science.get("passed") is True and arrays.get("passed") is True++ result = {++ "both_parity_checks_passed": passed,++ "matched_pair_wall_speedup": science.get("verified_full_workflow_speedup") if passed else None,++ "scientific_comparison": select(science, ("passed", "scientific_payloads_exact", "run_kinds", "full_pipeline_verified", "checked_artifacts", "retention_ledgers", "outcomes", "differences")),++ "intake_array_comparison": select(arrays, ("passed", "checked", "manifest_verified_artifacts", "difference_count", "differences")),++ "http_receipts": {name: select(read(f"http-{name}/http-verification.json"), ("verification_passed", "implementation_unchanged", "full_pipeline_observed", "full_pipeline_requirements_met", "elapsed_s", "status", "reason_code", "event_count", "candidate_count", "source_sha256", "source_bytes", "service")) for name in ("baseline", "current")},++ "context": read("http-comparison-context.json"),++ }++ print("BOUNDED_HTTP_COMPARISON_BEGIN")++ print(json.dumps(result, indent=2, allow_nan=False))++ print("BOUNDED_HTTP_COMPARISON_END")++ REPORT++ - uses: actions/upload-artifact@v4++ if: always()++ with:++ name: bounded-http-comparison++ path: |++ results/ci-real-tests.xml++ results/http-comparison-context.json++ results/http-science-comparison.json++ results/http-array-comparison.json++ results/http-*/http-verification.json++ results/http-*/pipeline-evidence.json++ results/http-*/service.log++ if-no-files-found: ignore++ retention-days: 14diff --cc README.mdindex 827aa2f,f154fa9..8edae87--- a/README.md+++ b/README.md@@@ -88,11 -92,7 +92,13 @@@ Recording-time evidence matters: audio-The automatic search uses conservative score ceilings before completing every fit: incompatible residuals and an established Top-K cutoff can stop further group fitting at a shared clock. It batches eligible clock fits, reuses exact acoustic calculations in dense tiles, and divides overloaded areas or single-cell clock ranges into checkpointed pieces. [Search screening and real-data timing](docs/DATA_AND_SCALE.md#search) describe the bounds and their measured limits.- The latest changes reduced median scoring time at one source-informed receiver point from **28.80 to 15.57 CPU seconds**, a **1.85×** incremental speedup. A narrower clock workload improved from **4.39 to 2.21 CPU seconds**, or **1.98×**. Each comparison used three alternating pairs on actual recorded ridges and observed flight trajectories. All 3,905 broad-window associations and 1,055 narrow-window associations matched exactly across 16 independent groups, including diagnostics and retention records.-At one source-informed receiver point, median scoring time fell from **68.92 to 25.59 CPU seconds**, a **2.69×** speedup. All 3,905 associations across 16 event groups matched the scalar-corrected baseline in three alternating pairs. The [performance report](docs/PERFORMANCE.md) describes this bounded test, which does not establish nationwide runtime or independent location accuracy.++The original PR225 comparison used source `5699a657` against baseline `aa3dff6`. Median scoring time at one source-informed receiver point fell from **28.80 to 15.57 CPU seconds**, a **1.85×** speedup. A narrower clock workload improved from **4.39 to 2.21 CPU seconds**, or **1.98×**. Each comparison used three alternating pairs on actual recorded ridges and observed flight trajectories. All 3,905 broad-window associations and 1,055 narrow-window associations matched exactly across 16 independent groups, including diagnostics and retention records.++++That recorded implementation used a 32 MiB object cache and avoided decoding unrelated finalist trajectories. Separate measurements cover refinement, optional plots, and compact checkpoint encoding. The [performance report](docs/PERFORMANCE.md) gives the methodology, reproduction commands, memory tradeoff, and earlier historical results. Point timings use NumPy 2.5.4, while complete HTTP checks use NumPy 2.3.5. The full CONUS baseline reached its runtime limit, so these measurements do not establish nationwide completion time or independent location accuracy.+- The implementation reuses exact fits within a bounded 32 MiB cache and avoids decoding unrelated finalist trajectories. Separate measurements cover refinement, optional plots, and compact checkpoint encoding. The [performance report](docs/PERFORMANCE.md) gives the methodology, reproduction commands, memory tradeoff, and earlier historical results. Point timings use NumPy 2.5.4, while complete HTTP checks use NumPy 2.3.5. The full CONUS baseline reached its runtime limit, so these measurements do not establish nationwide completion time or independent location accuracy.++A separate bounded HTTP pair compared the same two source revisions. It processed the complete original recording in **264.81 → 188.32 wall seconds**, an observed **1.41×** speedup. Both runs passed the full-pipeline checks and returned 23 candidates with `inconclusive / search_incomplete`. Scientific outputs, the retention ledger, decoded audio, and diagnostics matched without numerical tolerance after the declared run-metadata normalization. This is one sequential pair on a shared host, with source-informed regional bounds and a fitted recording clock. The [HTTP measurement record](benchmarks/results/bounded-http-20261103.json) preserves the settings and equality checks.+- A separate bounded HTTP pair processed the complete original recording in **264.81 → 188.32 wall seconds**, an observed **1.41×** speedup. Both runs passed the full-pipeline checks and returned 23 candidates with `inconclusive / search_incomplete`. Scientific outputs, the retention ledger, decoded audio, and diagnostics matched without numerical tolerance after the declared run-metadata normalization. This is one sequential pair on a shared host, with source-informed regional bounds and a fitted recording clock. The [HTTP measurement record](benchmarks/results/bounded-http-20261103.json) preserves the settings and equality checks.++Main `21262e0` includes PR222's overlapping cache improvements, merged at `0d6a923`, and later checkpoint compatibility changes. The combined implementation selects its serialized cache, whose **4 MiB cap covers digest keys and serialized payloads**. Python object headers and dictionary bookkeeping require additional memory. One instrumented broad-clock pair used **13.08% less CPU** than the 32 MiB object-cache variant, with all 3,905 associations and retention outputs equal. This cache-selection comparison uses otherwise identical main-based code and NumPy 2.3.5. Fresh integrated HTTP validation remains pending. The earlier speedups do not measure an incremental gain over `21262e0`; see [integration scope and cache selection](docs/PERFORMANCE.md#integration-with-main-pending).Recent search work makes omitted alternatives and failed model evaluations visible. For more detail see [finite-search evidence](docs/FINITE_SEARCH_PRODUCER.md) and [clock-trial accounting](docs/SCORING_ASSESSMENT.md).diff --cc benchmarks/results/cache-integration-20261103.jsonindex 0000000,0000000..483cda7new file mode 100644--- /dev/null+++ b/benchmarks/results/cache-integration-20261103.json@@@ -1,0 -1,0 +1,79 @@@++{++ "schema_version": 1,++ "date": "2026-11-03",++ "scope": "Isolated complete-batch cache comparison on the actual broad point workload; no end-to-end or location-accuracy claim.",++ "common_source": "0d6a92377af0f00b84dff9fa7966326d0014c20c",++ "object_variant": "Same main source, replacing only matching.py and batch_ridge.py with frozen files equivalent to public 5699a657d57dc4f66b74ef000e20d3ba88f84704.",++ "main_blobs": {++ "matching.py": "aed8035a3c69c19455a2fa5f0299bdc6a823305f",++ "batch_ridge.py": "71be78bcab6621675fac80b98a50dc17dac1f421"++ },++ "uncached_kernel_ast_equal": true,++ "runtime": {++ "python": "3.12.14",++ "numpy": "2.3.5",++ "scipy": "1.17.0",++ "interpreter": "/workspace/scratch/1e88d5469ed3/perf-venv/bin/python",++ "numerical_library_threads": 1++ },++ "method": {++ "pairs": 1,++ "order": [++ "serialized_4MiB",++ "objects_32MiB"++ ],++ "processes": "Fresh separate interpreters on the shared host.",++ "instrumentation": "Both arms counted batch and uncached-kernel calls and recorded cache size after each batch. Cache implementation unchanged.",++ "timing": "Point scoring and retention writes; excludes imports, input loading and result JSON serialization.",++ "fixture": "point-120s.json: actual recorded ridges and observed trajectories, source-informed point and clock.",++ "index_input_hash": "ed0ab12af801d1451edea17f1212740758569338dd601f9eb4a82c763b291955"++ },++ "workload": {++ "scored_associations": 3905,++ "retained_associations": 100,++ "independent_groups": 16,++ "scalar_fit_calls": 72,++ "acoustic_calls": 850++ },++ "runs": {++ "serialized_4MiB": {++ "cpu_seconds": 12.822287035,++ "wall_seconds": 12.825721274999523,++ "load_seconds_excluded": 1.2063405540011445,++ "reported_peak_rss_mib": 285.34765625,++ "batch_calls": 7351,++ "kernel_calls": 1071,++ "cache_hits": 6280,++ "peak_entries": 884,++ "peak_accounted_bytes": 4194233,++ "peak_retained_object_bytes": 4333666,++ "limit_bytes": 4194304++ },++ "objects_32MiB": {++ "cpu_seconds": 14.751674511,++ "wall_seconds": 14.768337736999456,++ "load_seconds_excluded": 1.2944369119995827,++ "reported_peak_rss_mib": 310.859375,++ "batch_calls": 7351,++ "kernel_calls": 1070,++ "cache_hits": 6281,++ "peak_entries": 1057,++ "peak_accounted_bytes": 33553167,++ "peak_retained_object_bytes": 33553167,++ "limit_bytes": 33554432++ }++ },++ "exact_outputs": true,++ "comparison": "Complete canonical result JSON including every scored association, diagnostics, support counts, ranked rows and retention records; no tolerance.",++ "serialized_cpu_speedup": 1.1504713995821103,++ "serialized_cpu_reduction_percent": 13.079108236568649,++ "selection": "One serialized 4 MiB cache; lower CPU and memory in this pair.",++ "memory_note": "Serialized limit counts digest-key and pickle-payload bytes only. Estimated retained objects add bytes headers and OrderedDict storage. The object variant uses its conservative retained-object charge. Reported ru_maxrss includes setup and diagnostics and can retain an inherited pre-exec peak; neither cache charge is a total-process or allocator bound.",++ "raw_artifacts": "Full outputs were written and compared before the cloud runner reset. Raw temporary artifacts are now lost. This record reconstructs only the returned summaries, counters and successful equality assertion from tool history.",++ "integration_followup": {++ "main_revision": "b7be4330c37eb9ec2bfca23a55d840bf9bb3acab",++ "note": "The timed pair tested 0d6a923 only. The later legacy-arithmetic API and uncached kernel are preserved unchanged, with strict custom-input bypass and fitter-identity clearing added around the single serialized cache.",++ "local_validation": "All changed Python files compile. The uncached fitter AST is identical to public blob 4250d9800747805f376c51206f771c1d8bfcb640. Runtime checks await CI because the reset runner lacks required dependencies.",++ "fitting_source_revision": "21262e031388b3a5a8dd75979b2dc851608499b2"++ }++}diff --cc docs/PERFORMANCE.mdindex 4c114b4,f137283..2087c8b--- a/docs/PERFORMANCE.md+++ b/docs/PERFORMANCE.md@@@ -1,423 -1,6 +1,474 @@@-# Measured scoring performance+# Measured pipeline performance- The latest changes reduce median CPU time for complete point scoring by **45.94%** on the broad-clock workload.-The 2026-11-03 implementation reduces median CPU time by **62.87%** on the broad-clock workload described here.++The original PR225 point and HTTP comparisons use baseline `aa3dff686c989524daa20c081a816b792d9c8890` and the implementation published at `5699a657d57dc4f66b74ef000e20d3ba88f84704`.++The integration section separates validation of the combined implementation from these original comparisons.++++The recorded PR225 implementation reduces median CPU time for complete point scoring by **45.94%** on the broad-clock workload.+The narrow-clock workload uses **49.56%** less CPU time.+Both comparisons preserve every scored association and its diagnostics exactly.+The changes reuse calculations and reduce data decoding without reducing the search domain, event coverage, solver iterations, or numerical precision.++These are incremental improvements over an already optimized baseline.+The earlier **2.69×** scorer result appears in the [historical comparison](#historical-scorer-comparison-2026-11-03).+The measurements cover different stages and environments, so their speedups do not combine into a complete-pipeline ratio.+- ## Exact fit reuse: current point-scoring comparison++## Integration with main: pending++++Main commit [`0d6a92377af0f00b84dff9fa7966326d0014c20c`](https://github.com/1337isnot1337/DOPPLERGEIST/commit/0d6a92377af0f00b84dff9fa7966326d0014c20c) merged [PR222](https://github.com/1337isnot1337/DOPPLERGEIST/pull/222).++That work independently adds batch-fit reuse and improvements to audio, terrain, trajectory decoding, and retention transactions.++Some changes overlap the original PR225 implementation.++The [PR222 report](PIPELINE_PERFORMANCE_2026-11-03.md) preserves its separate measurements.++The combined implementation also includes main commit [`21262e031388b3a5a8dd75979b2dc851608499b2`](https://github.com/1337isnot1337/DOPPLERGEIST/commit/21262e031388b3a5a8dd75979b2dc851608499b2) and its checkpoint compatibility changes.++++The earlier PR225 timings do not isolate an incremental gain over `0d6a923` or `21262e0`.++A fresh comparison will validate the frozen combined implementation separately.++Results against `aa3dff6` describe the combined changes.++Results against `0d6a923` describe the additional changes after PR222.++Results against `21262e0` describe the additional changes after that later main revision.++++<!-- PERFORMANCE_INTEGRATION_PENDING: fill after source freeze and the fresh HTTP comparison. -->++++| Integration item | Status |++| --- | --- |++| Integrated main source | `21262e031388b3a5a8dd75979b2dc851608499b2` |++| Frozen combined source | Pending |++| Batch-cache selection | Serialized cache from main; 4 MiB digest-key and payload cap |++| Fresh bounded HTTP result and baseline | Pending |++| Exact JSON, SQLite, and array comparison | Pending |++++### Cache selection for the combined implementation++++One isolated, instrumented pair compared two cache implementations in otherwise identical code based on main `0d6a923`.++The pair used NumPy 2.3.5 and the same real broad-clock workload.++All 3,905 scored associations and retention outputs matched exactly.++++| Cache implementation | CPU time | Estimated retained Python objects | Process peak RSS |++| --- | ---: | ---: | ---: |++| Serialized cache from main, 4 MiB key/payload cap | 12.822287035 s | 4,333,666 bytes | 285.35 MiB |++| Previous object-cache variant, 32 MiB accounted-object cap | 14.751674511 s | 33,553,167 bytes | 310.86 MiB |++++The serialized cache used **13.08% less CPU time** in this pair and is selected for integration.++Its 4 MiB cap covers SHA-256 digest bytes and serialized snapshots.++The observed key and payload bytes peaked at 4,194,233 bytes.++Python object headers and ordered-dictionary bookkeeping require additional memory, so 4 MiB is not a total-heap cap.++The estimated retained-object figures describe cache memory; RSS describes the entire process.++Reported RSS includes setup and diagnostics; `ru_maxrss` can retain an inherited peak.++++The [cache-selection record](../benchmarks/results/cache-integration-20261103.json) preserves this single sequential pair and its scope.++The execution environment was reset after this comparison.++The record retains returned measurements and the successful equality check; the temporary full outputs were lost.++This experiment does not measure a whole-pipeline speedup or the final integrated source.++The historical 32 MiB measurements below remain measurements of their original implementation.++++## Exact fit reuse: recorded PR225 point-scoring comparison++Each workload used three alternating baseline/current pairs in separate Python processes.+The order was baseline/current, current/baseline, then baseline/current.+Each source used the same frozen recorded ridges, observed trajectories, candidate budgets, and receiver point.++| Recording-start window | Baseline median CPU | Current median CPU | CPU speedup | Scored associations |+| --- | ---: | ---: | ---: | ---: |+| ±120 seconds | 28.803255077 s | 15.571095273 s | **1.84979×** | 3,905 |+| ±10 seconds | 4.386338558 s | 2.212487520 s | **1.98254×** | 1,055 |++The timed operation includes complete point scoring and retention writes.+It excludes imports, input loading, fixture preparation, acquisition, discovery, nationwide search, refinement, and result JSON serialization.+The receiver point and recording clock come from a historical fit.+This experiment measures computation on actual observations, without an independent location-accuracy claim.++All six outputs within each workload match exactly, with no numerical tolerance.+The comparison includes every scored association, fitted diagnostic, support count, ranked row, and retention record, bound, and stage.+Both workloads supply all 16 independent groups, and both sources retain the same 100 associations.+The narrow workload checks that the improvement also applies to fewer clock trials.+Changing the clock window itself is not a code speedup and requires independent time evidence.++### Workload and runtime++Both fixtures contain 16 recorded ridge records and 724 ridge samples.+The broad fixture contains 452 observed trajectories, 91,889 trajectory samples, and 100 CPA rows.+The narrow fixture contains 426 observed trajectories, 87,206 trajectory samples, and 97 CPA rows.+Both retain four unsupported CPA tracks in their accounting.+The preparation command rejects a budget excess instead of silently truncating inputs.++The point timings used Python 3.12.14, **NumPy 2.5.4**, SciPy 1.17.0, pandas 2.2.3, pyarrow 26.0.1, and pyproj 3.8.0.+The host used Linux 6.18.57 and an AMD EPYC 9V74 processor.+OpenBLAS, OpenMP, MKL, and NumExpr each used one thread.+A full upload ran on the shared host during these measurements, so process CPU time is the primary metric.++| Window | Baseline median wall time | Current median wall time | Reported peak RSS, baseline → current |+| --- | ---: | ---: | ---: |+| ±120 seconds | 28.816586 s | 15.579372 s | 260.46 → 293.25 MiB |+| ±10 seconds | 4.393367 s | 2.215673 s | 210.37 → 211.93 MiB |++These wall times describe a shared host, without exclusive CPU access.+Reported RSS includes imports, input loading, and captured diagnostics through scoring.+The measurement uses `getrusage(RUSAGE_SELF).ru_maxrss`, which can retain an inherited peak across execution.+Separate `VmHWM` readings were not recorded.+These figures describe process memory, without an isolated measurement of the cache heap.++The baseline commit is `aa3dff686c989524daa20c081a816b792d9c8890`.+The measured scoring implementation is local commit `5ca480f8678ca1ed31a765768324f623a44f0da8` plus the 32 MiB batch-cache patch.+That worktree patch changed `_RidgeFitCache.batch_limit` from 16 MiB to 32 MiB and clarified the cache-limit docstring.+The harness did not record HEAD separately for each worker.+Concurrent terrain/ENF integration at local commit `5420163f026b6c2621226add88cfa05fda326b46` did not change the exercised FlightIndex or scoring paths.- Published commit `5699a657d57dc4f66b74ef000e20d3ba88f84704` contains the same exercised scoring paths and the final 32 MiB limit.++Published commit `5699a657d57dc4f66b74ef000e20d3ba88f84704` contains the same exercised scoring paths and the measured 32 MiB limit.+Its additional compact-checkpoint change does not affect this point-scoring measurement.+The [exact-fit measurement record](../benchmarks/results/exact-fit-reuse-20261103.json) contains all twelve final runs, source details, input hashes, and workload counts.++The complete HTTP runtime uses **NumPy 2.3.5**.+The seven selected real-input tests and all 50 cache checks also passed in that runtime, with `PYTHONPATH=src` only.+Those checks cover scalar parity, prepared measurements, cache mutation, eviction, layout, and nested scope restoration.+They provide a separate correctness check, without another point-timing measurement.+The two NumPy environments remain separate in the recorded results.++### Why exact reuse reduces work++Dense candidate traversal repeats complete batches of identical ridge fits.- The new scoped cache reuses successful batches with the same fitter, parameters, and array contents.++The measured scoped cache reuses successful batches with the same fitter, parameters, and array contents.+Its keys preserve input order, shape, dtype, strides, and alignment.+They also preserve the frequency bounds, frequency scale, and drift fraction without rounding.+Memory layout matters because existing NumPy reductions can differ by one ULP between contiguous layouts.++Each cache hit returns separate diagnostic dictionaries.+Mutations cannot alter a later cached result.+Unsupported representations use the original path, and the cache does not retain failed or unsupported results.+The cache lifetime follows the existing scoring context, including nested-scope restoration.+The scorer also reuses validated event ceilings with their complete diagnostic dependencies.+The fitting equations, six IRLS iterations, conservative screens, tie behavior, and candidate accounting remain unchanged.+- ### Why the batch-cache limit is 32 MiB++### Why the recorded batch-cache limit was 32 MiB+- The batch cache holds at most 4,096 entries and 32 MiB per active scoring context.++The recorded implementation holds at most 4,096 batch entries and 32 MiB per active scoring context.+The byte limit accounts for keys, diagnostic values, and dictionary storage.+This allocation grows with demand and is separate from the acoustic and prepared-measurement caches.++An instrumented capacity comparison used the same broad fixture in four sequential runs: 16 MiB, 32 MiB, 32 MiB, then 16 MiB.+All outputs matched exactly.+Each run made 7,351 batch lookups.++| Batch-cache limit | Median CPU, two runs | Hits per run | Fits executed per run | Evictions per run | Maximum retained bytes |+| --- | ---: | ---: | ---: | ---: | ---: |+| 16 MiB | 18.937758264 s | 5,403 | 1,948 | 1,443 | 16,777,214 |+| 32 MiB | 17.334247567 s | 6,281 | 1,070 | 17 | 33,553,175 |++The 32 MiB limit reduced CPU time by **8.47%** relative to 16 MiB in this capacity comparison.+Median reported process RSS increased from 276.97 MiB to 293.20 MiB.+The larger limit retains more repeated fits and avoids repeated eviction on this workload.+The final point-scoring table uses fresh runs with this selected limit.+The capacity runs include instrumentation and remain separate from the final speedup calculation.+The exact-fit measurement record preserves both capacities and every counter.++## Other measured stages++These comparisons use actual recorded-audio jobs and observed flight data.+Each row has its own scope and repetition count.++| Stage | Baseline CPU | Current CPU | Repetitions | Equality check |+| --- | ---: | ---: | --- | --- |+| Refinement and decision | 83.7084 s | 77.4870 s | One unprofiled pair | Complete refined candidates and final JSON |+| Optional event plots | 4.383 s | 3.277 s | Three alternating pairs | Every PNG pixel |+| Checkpoint JSON encoding | 1.32042 s | 0.28718 s | Five alternating pairs | Complete decoded payload and identifiers |++### Refinement and decision++The replay starts from fixed archived finalists, without repeating discovery or search.+The trajectory lookup now selects the named finalist IDs within the same space/time envelope before decompressing tracks.+Decoded tracks decreased from **881 to 18**, and decoded samples decreased from 233,165 to 5,303.+The fitter still receives the same required complete tracks, with the original validation and sample-budget checks.+The single unprofiled pair used **7.43%** less CPU time.+Both timed arms included the same decode counter.+It returned the same 23 candidates and the same `inconclusive / search_incomplete` result.+This is a phase observation, without a repeated-run estimate of total pipeline speed.+The [refinement measurement record](../benchmarks/results/decision-refinement-20261103.json) preserves the observations and their scope.++### Optional event plots++The plot comparison rendered all 18 event images from a complete 3,600.1845-second real recording with 16 independent groups.+The renderer computes the same full spectral normalization and passes only visible frequency bins to the plotting library.+The median CPU speedup was **1.34×**, with identical pixels in every image.+Diagnostic plots are off by default, so this gain applies only when plots are requested.+It excludes audio intake and acoustic discovery.+The [plot measurement record](../benchmarks/results/real-discovery-plots-20261103.json) preserves all three pairs, the recorded input, and the NumPy 2.3.5 environment.++### Compact internal checkpoints++The encoding comparison used one completed real tile with 19,977 candidate associations.+Compact JSON reduced its encoded size from **39,363,929 to 23,490,375 bytes**, a **40.33%** reduction.+Median encoding CPU time improved by **4.60×** across five alternating pairs.+Every decoded value, payload hash, and retention checksum remained identical.+The production change preserves checkpoint filenames, atomic writes, and resume identifiers.+Human-facing reports retain their readable formatting.++The timer covers JSON encoding only.+It excludes file writes, reads, scoring, and complete checkpoint or resume operations.+The [checkpoint measurement record](../benchmarks/results/checkpoint-encoding-20261103.json) preserves all ten runs and the decoded-output checks.+- ## Current complete-recording HTTP comparison++## Recorded PR225 complete-recording HTTP comparison++One sequential baseline/current pair completed the entire bounded HTTP workflow on the original 3,600.1845-second MP3.+It used the separate **NumPy 2.3.5** runtime on a shared host.++| Measurement | Baseline | Current |+| --- | ---: | ---: |+| HTTP verification elapsed wall time | 264.809609269 s | 188.323150374 s |+| Event records | 18 | 18 |+| Returned candidates | 23 | 23 |+| Full pipeline requirements met | Yes | Yes |++The observed elapsed-time speedup is **1.40614×**, or **28.88%** less wall time.+This is one pair, without a repeated-run estimate or a process CPU comparison.+Both runs passed the HTTP and full-pipeline verification checks.+Both returned `inconclusive / search_incomplete`.+The 18 event records form 16 independent groups.+Optional event plots remained disabled during both HTTP runs.++The request used the source-informed bounds `[-73.545, 40.865, -73.505, 40.895]` and recording-start window `2026-09-08T20:17:20Z` through `20:17:40Z`.+Both sources used the same observed flight index, terrain, one search worker, 2 km coarse spacing, and 500 m refinement spacing.+The top-K limit remained 20, with three refinement finalists.+Both searches processed four coarse points across two tiles, plus the same 40 existing refinement points.+Both skipped 80 refinement points under the existing rules.+These explicit regional bounds define the comparison workload and do not establish national completion or independent location accuracy.++The scientific comparison found zero differences across 23 job JSON artifacts, three root JSON artifacts, and the logical SQLite ledger.+It normalizes declared implementation hashes, run and job identities, performance fields, and local paths.+It excludes declared resume and worker metadata.+The performance fields are elapsed time and reported process peak RSS.+It compares the full operator configuration separately from its digest.+SQLite comparison covers all logical tables, columns, and rows, except `run.identity` and physical storage layout.+Decoded scientific values, numeric types, and signed zeros compare exactly, with no numerical tolerance.+The [pinned comparison script](https://github.com/1337isnot1337/DOPPLERGEIST/blob/a3ba35342e491556973be34022f3e0a10ac1f6f4/scripts/compare_real_upload_performance.py) defines the complete normalization rules.+The ledger preserves 48,226 bounds, 958 records, and 18 stages.+Supplementary checks also matched one intake diagnostic, one decoded PCM file, 18 CSV files, and the decoded pixels of one PNG exactly.+This workload contains no NPZ files.+The intake comparison replaces only the exact input path in the recorded decoder command.++The [bounded HTTP measurement record](../benchmarks/results/bounded-http-20261103.json) preserves the timings, settings, source identities, and equality results.+Published commit `5699a657d57dc4f66b74ef000e20d3ba88f84704` matches all 34 production source files in the frozen HTTP checkout.++A full CONUS baseline reached its declared 1,800-second limit before completion (1,800.23 seconds of wall time).+That unfinished search provides no nationwide speed ratio.+Regional source data do not establish national flight coverage or independent location accuracy.+The historical HTTP checks below describe their own revisions and workloads.+- ## Reproduce the current comparisons++## Reproduce the recorded PR225 comparisons++Use Python 3.12.14 to match the recorded point-timing runtime.+Use Git and the GitHub CLI `gh` with access to the public checkpoint assets.+Run these commands from the repository root.+Use a fresh output directory for each comparison.++Install the point-timing environment and restore the observed inputs:++```bash+python3.12 -m venv .venv-point+.venv-point/bin/python -m pip install '.[test]' \+ 'numpy==2.5.4' 'scipy==1.17.0' 'pandas==2.2.3' \+ 'pyarrow==26.0.1' 'pyproj==3.8.0'+.venv-point/bin/python scripts/restore_artifacts.py \+ --bundle data-adsb-derived --bundle data-terrain+PYTHONPATH=src .venv-point/bin/python scripts/prepare_reference_upload.py \+ --data-root data --output results/incremental-inputs+```++Create separate source trees from the public baseline and optimized commits:++```bash+git fetch origin+git worktree add --detach ../dopplergeist-incremental-baseline \+ aa3dff686c989524daa20c081a816b792d9c8890+git worktree add --detach ../dopplergeist-timing-current \+ 5699a657d57dc4f66b74ef000e20d3ba88f84704+```+- The public optimized commit contains the final 32 MiB limit.++The public optimized commit contains the recorded 32 MiB limit.+The source disclosure above identifies the local commit and worktree patch used during measurement.++Freeze and compare both workloads:++```bash+export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1+for width in 120 10; do+ PYTHONPATH=src .venv-point/bin/python scripts/benchmark_prepared_measurements.py prepare \+ --discovery evidence/audio/w1-sensitivity-20261102/reference/discovery.json \+ --index results/incremental-inputs/reference-region.sqlite \+ --clock-half-width-s "$width" \+ --output "results/incremental-inputs/point-${width}s.json"++ PYTHONPATH=src .venv-point/bin/python scripts/benchmark_prepared_measurements.py compare \+ --fixture "results/incremental-inputs/point-${width}s.json" \+ --baseline-source ../dopplergeist-incremental-baseline/src \+ --current-source ../dopplergeist-timing-current/src \+ --repeats 3 --timeout-s 600 \+ --output "results/incremental-${width}s"+done+```++The comparison rejects changed inputs, missing trajectories, invalid retention ledgers, or any complete-output mismatch.+Both arms use the same interpreter and library versions.++Run the seven selected real-input tests and the cache checks:++```bash+DOPPLERGEIST_REAL_CPA_FIXTURE=results/incremental-inputs/point-120s.json \+PYTHONPATH=src .venv-point/bin/python -m pytest -q \+ tests/test_real_batch_scalar_parity.py \+ tests/test_real_batch_ridge.py \+ tests/test_real_prepared_measurements.py++PYTHONPATH=src .venv-point/bin/python scripts/check_real_batch_cache.py \+ --tracks data/adsb/2026-09-08/reference-region.parquet \+ --discovery evidence/audio/w1-sensitivity-20261102/reference/discovery.json \+ --candidate evidence/results/reference-local/report.json+```++The separate HTTP-runtime correctness check used the same commands with NumPy 2.3.5 and no additional dependency directory on `PYTHONPATH`.+It passed all seven tests and all 50 cache checks.++For the other stage comparisons, use a separate NumPy 2.3.5 environment:++```bash+python3.12 -m venv .venv-stages+.venv-stages/bin/python -m pip install '.[test]' \+ 'numpy==2.3.5' 'scipy==1.17.0' 'pandas==2.2.3' \+ 'pyarrow==26.0.1' 'pyproj==3.8.0' 'matplotlib==3.10.8'+```++The original refinement and plot comparisons used NumPy 2.3.5.+The checkpoint encoding helper uses the Python standard library.+To repeat the separate runtime checks, use `.venv-stages/bin/python` in the previous test and cache commands.++For refinement, use a completed real job with saved finalists, flight indexes, and terrain:++```bash+PYTHONPATH=src .venv-stages/bin/python scripts/benchmark_real_decision.py \+ --source ../dopplergeist-incremental-baseline/src \+ --job /path/to/real-job --output results/decision-baseline+PYTHONPATH=src .venv-stages/bin/python scripts/benchmark_real_decision.py \+ --source ../dopplergeist-timing-current/src \+ --job /path/to/real-job --output results/decision-current \+ --compare-to results/decision-baseline+```++The script compares every refined candidate, sensitivity result, and decision after the timed operation.+It omits the exploratory decode counter from the original pair.+For repeated measurements, alternate the source order and use new output directories.++For optional plots, use saved intake and discovery outputs from a real recording:++```bash+PYTHONPATH=../dopplergeist-timing-current/src \+.venv-stages/bin/python scripts/benchmark_real_discovery_plots.py \+ /path/to/real-job --baseline ../dopplergeist-incremental-baseline \+ --repeats 3 --output results/plot-comparison+```++For checkpoint encoding and compatibility, use the original filename of a completed real tile:++```bash+.venv-stages/bin/python scripts/benchmark_real_checkpoint_encoding.py \+ --checkpoint /path/to/real-job/search/tile-ID.json --repeats 5 \+ --output results/checkpoint-encoding.json++DOPPLERGEIST_REAL_TILE_CHECKPOINT=/path/to/real-job/search/tile-ID.json \+PYTHONPATH=src .venv-stages/bin/python -m pytest -q \+ tests/test_real_compact_checkpoints.py+```++The encoding helper compares readable and compact JSON, including one trailing newline in both timed operations.+Input decoding, output decoding, file writes, and equality checks remain outside the timer.+The compatibility tests also exercise atomic replacement and saved support-accounting parity.++### Complete bounded HTTP replay++Use the NumPy 2.3.5 environment and public source worktrees from the preceding commands.+Install FFmpeg so that `ffmpeg` and `ffprobe` are on `PATH`.+The [bounded upload helper](../scripts/benchmark_real_bounded_upload.py) starts each source in a fresh HTTP service.+It uses the same input file, request, operator configuration, and interpreter for both arms.++Restore the recorded inputs and prepare the shared index:++```bash+.venv-stages/bin/python scripts/restore_artifacts.py \+ --bundle data-source --bundle data-adsb-derived --bundle data-terrain+PYTHONPATH=../dopplergeist-timing-current/src \+.venv-stages/bin/python scripts/prepare_reference_upload.py \+ --data-root data --output results/bounded-inputs++.venv-stages/bin/python - <<'PY'+import json+from pathlib import Path+root = Path('results/bounded-inputs')+request = json.loads((root / 'request.json').read_text())+request['search']['bounds_wsen'] = [-73.545, 40.865, -73.505, 40.895]+request['time_window']['source_detail'] = (+ 'Source-informed integration replay around the historical fitted recording '+ 'start and benchmark receiver region; not independently measured recording '+ 'time or a location-accuracy evaluation.'+)+operator = json.loads((root / 'operator.json').read_text())+operator['search_workers'] = 1+for name, value in (('request.json', request), ('operator.json', operator)):+ (root / name).write_text(json.dumps(value, indent=2) + '\n')+PY+```++The helper preserves the recorded 20:17:20–20:17:40 UTC window, search budgets, and refinement settings.+The public `data-source` bundle contains `reference-recording.wav`, not the original timed MP3.+For the original workload, supply the archived complete MP3:++```bash+cp /path/to/archived/reference-complete.mp3 results/bounded-inputs/recording.mp3+sha256sum results/bounded-inputs/recording.mp3+```++The measured MP3 contains 42,085,293 bytes and has SHA-256 `e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0`.+If only the published WAV is available, use this command instead of the copy command:++```bash+ffmpeg -n -nostdin -i data/source/reference-recording.wav \+ -map 0:a:0 -vn -map_metadata -1 -ac 1 -ar 48000 \+ -c:a libmp3lame -b:a 96k results/bounded-inputs/recording.mp3+```++This conversion creates a new encoding of the real recording.+It defines a new comparison workload and requires fresh results.+The original hash, event counts, candidate counts, and timings do not apply automatically.+Both arms must use the same resulting MP3 file.++Run the two fresh HTTP arms sequentially:++```bash+export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1+.venv-stages/bin/python scripts/benchmark_real_bounded_upload.py \+ --source ../dopplergeist-incremental-baseline/src \+ --inputs results/bounded-inputs --output results/http-baseline --timeout-s 900+.venv-stages/bin/python scripts/benchmark_real_bounded_upload.py \+ --source ../dopplergeist-timing-current/src \+ --inputs results/bounded-inputs --output results/http-current --timeout-s 900+```++Fetch the pinned comparison tools and run both equality checks:++```bash+git fetch origin a3ba35342e491556973be34022f3e0a10ac1f6f4+git worktree add --detach ../dopplergeist-comparison-tools \+ a3ba35342e491556973be34022f3e0a10ac1f6f4+.venv-stages/bin/python \+ ../dopplergeist-comparison-tools/scripts/compare_real_upload_performance.py \+ --baseline results/http-baseline --current results/http-current \+ --output results/http-science-comparison.json+.venv-stages/bin/python scripts/check_real_upload_arrays.py \+ --baseline results/http-baseline --current results/http-current \+ --output results/http-array-comparison.json+```++The comparator pin contains the exact comparison implementation used for the recorded pair.+The separate tools worktree preserves its source identity without changing either measured production source.+The array check covers the saved artifacts that actually exist in each workload.++## Historical scorer comparison (2026-11-03)++The earlier scorer implementation reduced median CPU time by **62.87%** on its broad-clock workload.The same workload takes **68.92 → 25.59 CPU seconds**, a **2.69× speedup**.Every scored candidate, diagnostic, support count, and retention record matches the scalar-consistent baseline exactly.diff --cc scripts/check_real_batch_cache.pyindex 39ce95d,0000000..8904969mode 100644,000000..100644--- a/scripts/check_real_batch_cache.py+++ b/scripts/check_real_batch_cache.py@@@ -1,204 -1,0 +1,221 @@@+"""Check exact batch-cache behavior using recorded ridges and flight tracks.++This is a software regression check, not a location-accuracy experiment. Input+mutation checks change copies by one ULP solely to test cache invalidation.+No recording or trajectory is generated.+"""+import argparse+from copy import deepcopy+import json+from pathlib import Path- import sys+from types import SimpleNamespace++import numpy as np+++from dopplergeist import batch_ridge+from dopplergeist.batch_ridge import first_event_fits+from dopplergeist.geometry import AcousticSupportError, ecef+from dopplergeist.matching import (- _cache_batch_ridge_fits, _cache_ridge_fits, _frequency_scale,++ _cache_ridge_fits, _frequency_scale,+ _iter_acoustic_trials, _ridge_fit_cache, prepare_events,+)+from dopplergeist.tracks import load_tracks+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--discovery", required=True, type=Path)+ parser.add_argument("--tracks", required=True, type=Path)+ parser.add_argument("--candidate", required=True, type=Path)+ args = parser.parse_args()+ events, measurements = prepare_events(json.loads(args.discovery.read_text())["events"])+ saved = json.loads(args.candidate.read_text())+ point = saved.get("best", saved)+ start = point["recording_start_time_s"]+ tracks, _ = load_tracks(args.tracks, time_range=(start - 120, start + max(e["end_s"] for e in events) + 120))+ aircraft = {identifier.split(":")[0] for identifier in point["flight_ids"]}+ chosen = [track for track in tracks if track.id.split(":")[0] in aircraft]+ observer = ecef(point["lat"], point["lon"], point["elev_m"])+ starts = start + np.linspace(-5, 5, 21)- uncached = first_event_fits.__wrapped__++ uncached = batch_ridge._first_event_fits_uncached+ inputs = None+ for event, measurement in zip(events, measurements):+ for track in chosen:+ try:+ batch = next(_iter_acoustic_trials([track], [measurement], observer, starts))+ except AcousticSupportError:+ continue+ if batch is not None and uncached(measurement, event, *batch) is not None:+ inputs = measurement, event, *batch+ break+ if inputs is not None:+ break+ if inputs is None:+ raise RuntimeError("No supported batch exists for the supplied real receiver/flight hypotheses")++ calls = 0+ checks = []+- def counted(*values):++ def counted(*values, **options):+ nonlocal calls+ calls += 1- return uncached(*values)++ return uncached(*values, **options)++++ def cached_for(function):++ # Exercise the production cache through its private fitter hook. No++ # second cache or compatibility storage is introduced by this checker.++ def call(*values, **options):++ previous = batch_ridge._first_event_fits_uncached++ batch_ridge._first_event_fits_uncached = function++ try:++ return first_event_fits(*values, **options)++ finally:++ batch_ridge._first_event_fits_uncached = previous++ return call+- cached = _cache_batch_ridge_fits(counted)++ cached = cached_for(counted)++ def check(name, condition):+ if not condition:+ raise AssertionError(name)+ checks.append(name)++ expected = uncached(*inputs)+ check("no_context_result", cached(*inputs) == expected)+ check("no_context_bypass", calls == 1 and _ridge_fit_cache.get() is None)++ @_cache_ridge_fits+ def check_context():+ outer = _ridge_fit_cache.get()+ initial = calls+ first = cached(*inputs)+ second = cached(*deepcopy(inputs))+ check("equal_copies_hit", calls == initial + 1 and first == second == expected)+ first[0]["score"] = 12345.0+ second[0]["f0_hz"] = 0.0+ check("diagnostic_copies_are_independent", cached(*inputs) == expected)- check("memory_bound", 0 < outer.batch_bytes + sys.getsizeof(outer.batch_entries) <= outer.batch_limit)++ check("serialized_byte_bound", 0 < outer.batch_fit_bytes <= outer.batch_fit_limit)++ check("serialized_byte_accounting", outer.batch_fit_bytes == sum(++ len(key) + len(snapshot) for key, snapshot in outer.batch_fit_entries.items()))+- def alternate(*values):- return counted(*values)++ def alternate(*values, **options):++ return counted(*values, **options)++ before = calls- check("different_function_result", _cache_batch_ridge_fits(alternate)(*inputs) == expected)++ check("different_function_result", cached_for(alternate)(*inputs) == expected)+ check("different_function_misses", calls == before + 1)++ before = calls++ check("restored_function_recomputes", cached(*inputs) == expected and calls == before + 1)++ check("restored_function_warm_hit", cached(*inputs) == expected and calls == before + 1)++ for index, name in enumerate(("times", "ridge", "weights", "factors", "emissions")):+ changed = deepcopy(inputs)+ array = ((changed[0][0].time, changed[0][1], changed[0][2], changed[2], changed[3])[index])+ array.flat[0] = np.nextafter(array.flat[0], np.inf)+ before = calls+ check(name + "_mutation_result", cached(*changed) == uncached(*changed))+ check(name + "_mutation_misses", calls == before + 1)++ for name in ("bounds", "sigma", "fraction"):+ changed = deepcopy(inputs)+ event = changed[1]+ if name == "bounds":+ event["f0_range_hz"] = list(event["f0_range_hz"])+ event["f0_range_hz"][0] = float(np.nextafter(event["f0_range_hz"][0], np.inf))+ elif name == "sigma":+ event.setdefault("quality", {})["frequency_loss_scale_hz"] = float(np.nextafter(_frequency_scale(event), np.inf))+ else:+ event.setdefault("quality", {})["source_drift_fraction"] = float(np.nextafter(event["quality"].get("source_drift_fraction", 0.02), np.inf))+ before = calls+ check(name + "_mutation_result", cached(*changed) == uncached(*changed))+ check(name + "_mutation_misses", calls == before + 1)++ changed = list(deepcopy(inputs))+ changed[2] = changed[2].astype(changed[2].dtype.newbyteorder(">"))+ before = calls+ check("dtype_result", cached(*changed) == uncached(*changed))+ check("dtype_misses", calls == before + 1)+ changed = [*inputs[:2], inputs[2][::-1], inputs[3][::-1]]+ before = calls+ check("row_order_result", cached(*changed) == uncached(*changed))+ check("row_order_misses", calls == before + 1)+ changed = [*inputs[:2], np.asfortranarray(inputs[2]), np.asfortranarray(inputs[3])]+ before = calls+ check("fortran_layout_result", cached(*changed) == uncached(*changed))+ check("fortran_layout_misses", calls == before + 1)+ changed = [*inputs[:2], inputs[2].tolist(), inputs[3].tolist()]+ before = calls+ check("custom_representation_result", cached(*changed) == cached(*changed) == expected)+ check("custom_representation_bypasses", calls == before + 2)+ before = calls+ check("measurement_iterator_result", cached(iter(inputs[0]), *inputs[1:]) == expected)+ check("measurement_iterator_bypasses", calls == before + 1)+ changed = list(deepcopy(inputs))+ measurement = list(changed[0])+ measurement[0] = SimpleNamespace(time=measurement[0].time)+ changed[0] = measurement+ before = calls+ check("custom_time_container_result", cached(*changed) == cached(*changed) == expected)+ check("custom_time_container_bypasses", calls == before + 2)++ missing = [*inputs[:2], inputs[2][:0], inputs[3][:0]]+ before = calls- entries = len(outer.batch_entries)++ entries = len(outer.batch_fit_entries)+ check("fallback_none", cached(*missing) is None and cached(*missing) is None)- check("fallback_not_cached", calls == before + 2 and len(outer.batch_entries) == entries)++ check("fallback_not_cached", calls == before + 2 and len(outer.batch_fit_entries) == entries)+ malformed = deepcopy(inputs)+ malformed[0][0].time = malformed[0][0].time[:2]+ before = calls+ for _ in range(2):+ try:+ cached(*malformed)+ except ValueError:+ pass+ else:+ raise AssertionError("Malformed measurement did not raise")- check("exceptions_not_cached", calls == before + 2 and len(outer.batch_entries) == entries)++ check("exceptions_not_cached", calls == before + 2 and len(outer.batch_fit_entries) == entries)++ @_cache_ridge_fits+ def nested():+ check("nested_context_is_independent", _ridge_fit_cache.get() is not outer)+ before = calls+ check("nested_fit_result", cached(*inputs) == expected)+ check("nested_fit_misses", calls == before + 1)+ raise RuntimeError("Check context restoration after an exception")++ try:+ nested()+ except RuntimeError:+ pass+ check("nested_context_restored", _ridge_fit_cache.get() is outer)+ before = calls+ check("outer_fit_survives", cached(*inputs) == expected and calls == before)++ check_context()+ check("context_reset", _ridge_fit_cache.get() is None)++ def eviction():+ cache = _ridge_fit_cache.get()+ first = deepcopy(inputs)+ second = deepcopy(inputs)+ second[2][0, 0] = np.nextafter(second[2][0, 0], np.inf)+ check("eviction_first_result", cached(*first) == uncached(*first))+ check("eviction_second_result", cached(*second) == uncached(*second))- check("entry_limit", len(cache.batch_entries) == 1)++ check("entry_limit", len(cache.batch_fit_entries) == 1)+ before = calls+ check("evicted_fit_recomputed", cached(*first) == uncached(*first) and calls == before + 1)- cache.batch_entries.clear()- cache.batch_bytes = 0- cache.batch_limit = 1++ cache.batch_fit_entries.clear()++ cache.batch_fit_bytes = 0++ cache.batch_fit_limit = 1+ before = calls+ check("oversized_fits_bypass", cached(*first) == cached(*first) == expected and calls == before + 2)- check("oversized_fits_not_stored", len(cache.batch_entries) == cache.batch_bytes == 0)++ check("oversized_fits_not_stored", len(cache.batch_fit_entries) == cache.batch_fit_bytes == 0)++ _cache_ridge_fits(eviction, max_entries=1)()+ print(json.dumps({"checks": checks, "passed": len(checks), "recorded_groups": len(events),+ "selected_event": inputs[1].get("event_id"), "clock_rows": len(inputs[2]),+ "scope": "real-input cache regression; no location-accuracy claim"}, indent=2))+++if __name__ == "__main__":+ main()diff --cc src/dopplergeist/batch_ridge.pyindex 010f715,4250d98..1434448--- a/src/dopplergeist/batch_ridge.py+++ b/src/dopplergeist/batch_ridge.py@@@ -1,11 -1,69 +1,81 @@@"""Batched robust ridge fits with the scalar model's arithmetic order."""+ import hashlib+ import pickle+import numpy as np- from .matching import _cache_batch_ridge_fits, _frequency_scale, _ridge_fit_inputs-from .matching import _fit_argument_key, _fit_ridge_uncached, _frequency_scale, _ridge_fit_cache, _ridge_fit_inputs++from .audio import Spectrum++from .matching import (RidgeTimes, _fit_argument_key, _fit_ridge_uncached,++ _frequency_scale, _ridge_fit_cache, _ridge_fit_inputs)+++ def _batch_fit_key(measurement, event, factors, emissions):+ """Identify a complete batch without retaining its input arrays.++ Reduction layout is part of the input: equal values with different strides+ need not follow the same floating-point summation order.+ """+ if type(measurement) not in (tuple, list) or len(measurement) != 4:+ raise TypeError("Uncached custom measurement container")++ if type(measurement[0]) not in (RidgeTimes, Spectrum):++ raise TypeError("Uncached custom measurement time container")++ if type(event) is not dict or type(event.get("quality", {})) is not dict:++ raise TypeError("Uncached custom event container")+ digest = hashlib.sha256()+ settings = tuple(_fit_argument_key(value) for value in+ (_frequency_scale(event), event.get("quality", {}).get("source_drift_fraction", .02),+ event["f0_range_hz"]))+ digest.update(pickle.dumps(settings, protocol=5))+ for array in (measurement[0].time, measurement[1], measurement[2], factors, emissions):+ if type(array) is not np.ndarray or array.dtype.kind not in "biuf":+ raise TypeError("Uncached custom batch input")+ layout = (array.dtype.str, array.shape, array.strides, array.flags.aligned)+ digest.update(pickle.dumps(layout, protocol=5))+ digest.update(array.tobytes(order="C"))+ return digest.digest()++ def first_event_fits(measurement, event, factors, emissions, *, legacy_arithmetic=False):+ """Reuse an identical complete fit batch within the current scoring call."""+ options = {"legacy_arithmetic": True} if legacy_arithmetic else {}+ cache = _ridge_fit_cache.get()++ kernel = _first_event_fits_uncached+ if cache is None or cache.max_entries < 1 or cache.batch_fit_limit <= 0:- return _first_event_fits_uncached(measurement, event, factors, emissions, **options)++ return kernel(measurement, event, factors, emissions, **options)++ # A changed fitter must not reuse its predecessor's snapshots.++ if cache.batch_fit_function is not kernel:++ cache.batch_fit_entries.clear()++ cache.batch_fit_bytes = 0++ cache.batch_fit_function = kernel+ try:+ key = _batch_fit_key(measurement, event, factors, emissions)+ if legacy_arithmetic:+ key = hashlib.sha256(b"legacy-array-v1" + key).digest()+ except (TypeError, ValueError, KeyError, AttributeError):- return _first_event_fits_uncached(measurement, event, factors, emissions, **options)++ return kernel(measurement, event, factors, emissions, **options)+ entries = cache.batch_fit_entries+ if key in entries:+ entries.move_to_end(key)+ # Only snapshots produced below from our own scalar-valued diagnostics+ # enter this private memory cache. No files or external pickles are read.+ return pickle.loads(entries[key])- result = _first_event_fits_uncached(measurement, event, factors, emissions, **options)++ result = kernel(measurement, event, factors, emissions, **options)+ if result is not None:+ snapshot = pickle.dumps(result, protocol=5)+ size = len(key) + len(snapshot)+ if size <= cache.batch_fit_limit:+ while entries and (cache.batch_fit_bytes + size > cache.batch_fit_limit+ or len(entries) >= cache.max_entries):+ old_key, old_snapshot = entries.popitem(last=False)+ cache.batch_fit_bytes -= len(old_key) + len(old_snapshot)+ entries[key] = snapshot+ cache.batch_fit_bytes += size+ # None fallbacks and exceptions are never cached. The first caller also+ # owns its diagnostics: later mutations cannot change the stored bytes.+ return result- @_cache_batch_ridge_fits- def first_event_fits(measurement, event, factors, emissions):++ def _first_event_fits_uncached(measurement, event, factors, emissions, *, legacy_arithmetic=False):"""Fit supported clocks together, or return None for the ordinary fitter.This uses the same six iterations, box constraints, and diagnostics as thediff --cc src/dopplergeist/data_access.pyindex 95fef82,8f2ea7c..c77ed07--- a/src/dopplergeist/data_access.py+++ b/src/dopplergeist/data_access.py@@@ -520,18 -572,26 +590,16 @@@ class FlightIndexCallers expand receiver bounds for acoustic range and event duration.An R-tree rectangle can return harmless extra tracks, never clipped ones."""- west, south, east, north = bounds- start, end = time_range+ join, predicate, params = self._query_scope(bounds, 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.id- WHERE r.west<=? AND r.east>=? AND r.south<=? AND r.north>=?- AND s.start<=? AND s.end>=? ORDER BY s.name"""- params = (east, west, north, south, end, start)- current_normalizer = sha256(Path(__file__).with_name("tracks.py"))- compatible = (current_normalizer, *_EQUIVALENT_NORMALIZERS.get(current_normalizer, ()))- if (not self.report.get("continuous_geometry_bounds") or- self.report.get("normalizer_sha256") not in compatible):- # Old indexes used sample-only bounds or different derivatives.- # Disable unsafe spatial pruning, preserving explicit budgets.- sql = "SELECT name,payload,payload_hash FROM segments WHERE start<=? AND end>=? ORDER BY name"- params = (end, start)+ sql = ("SELECT s.name,s.payload,s.payload_hash FROM segments s" + join+ + " WHERE " + predicate + " ORDER BY s.name")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):+ def lookup(self, identifiers, *, max_tracks=2000, max_samples=500000,+ bounds=None, time_range=None):"""Yield named whole segments without scanning unrelated trajectories.Missing names are omitted; callers must compare requested and returned@@@ -552,25 -608,19 +620,23 @@@if len(names) > max_tracks:raise DataUnavailable("Flight lookup identifier budget exceeded")names, samples = sorted(names), 0+ join, predicate, scope_params = ("", "", ())+ if bounds is not None:+ join, predicate, scope_params = self._query_scope(bounds, time_range)+ 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):batch = names[first:first+500]placeholders = ",".join("?" for _ in batch)- sql = ("SELECT name,payload,payload_hash FROM segments WHERE name IN ("- + placeholders + ") ORDER BY name")- for name, payload, expected in db.execute(sql, batch):+ sql = ("SELECT s.name,s.payload,s.payload_hash FROM segments s" + join+ + " WHERE s.name IN (" + placeholders + ")"+ + (" AND " + predicate if predicate else "") + " ORDER BY s.name")+ for name, payload, expected in db.execute(sql, (*batch, *scope_params)):- 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 --cc src/dopplergeist/matching.pyindex 3ccfeed,aed8035..b17cfa2--- a/src/dopplergeist/matching.py+++ b/src/dopplergeist/matching.py@@@ -55,10 -53,9 +53,11 @@@ class _RidgeFitCacheself.measurement_entries = OrderedDict()self.measurement_bytes = 0self.measurement_limit = 4 * 1024 * 1024- self.batch_entries = OrderedDict()- self.batch_bytes = 0- self.batch_limit = 32 * 1024 * 1024+ self.batch_fit_entries = OrderedDict()+ self.batch_fit_bytes = 0+ self.batch_fit_limit = 4 * 1024 * 1024++ self.batch_fit_function = None+ self.ceiling_entries = OrderedDict()def prepared_measurement(self, measurement, sigma_hz, drift_fraction, key):"""Reuse selected samples only after checking their current content key."""@@@ -151,11 -148,11 +150,12 @@@def _cache_ridge_fits(function, *, max_entries=4096):"""Reuse fits only while this batch's tracks stay unchanged.- Scalar fits, batched fits, measurements and validated ceilings each retain- at most 4,096 entries by default. Batched fits and stored arrays also have- byte limits. Context-local state prevents reuse between concurrent jobs,- nested batches or later calls. Cached results are copied so candidate- diagnostics remain independently mutable.- Each fit cache has at most 4,096 entries by default. Complete-batch snapshots- and keys are additionally bounded to 4 MiB; prepared measurements use their- own 4 MiB bound and acoustic arrays use 32 MiB. Context-local state prevents++ Each fit cache has at most 4,096 entries by default. Serialized batch++ snapshots and digest bytes are bounded to 4 MiB; Python object/container++ overhead is additional. Prepared measurements use their own 4 MiB bound++ and acoustic arrays use 32 MiB. Context-local state prevents+ reuse between concurrent jobs, nested batches or later calls. Cached results+ are copied so candidate diagnostics remain independently mutable."""if type(max_entries) is not int or max_entries < 1:raise ValueError("Fit-cache capacity must be a positive integer")diff --cc tests/test_real_complete_batch_cache.pyindex 0000000,9d13231..3e71b2cmode 000000,100644..100644--- a/tests/test_real_complete_batch_cache.py+++ b/tests/test_real_complete_batch_cache.py@@@ -1,0 -1,146 +1,224 @@@+ """Bounded whole-batch reuse on actual recorded ridge/trajectory inputs."""+ import json+ from pathlib import Path++ import numpy as np+ import pytest++ from dopplergeist import batch_ridge, matching+++ def recorded():+ fixture = json.loads((Path(__file__).parent/'data/real-ridge-batch-arithmetic.json').read_text())+ measurement = (matching.RidgeTimes(np.asarray(fixture['times'])),+ np.asarray(fixture['ridge']), np.asarray(fixture['weight']), {})+ return measurement, fixture['event'], np.asarray(fixture['factors']), np.asarray(fixture['emissions'])+++ def counted_kernel(monkeypatch):+ calls = []+ original = batch_ridge._first_event_fits_uncached+- def run(*args):++ def run(*args, **options):+ calls.append(1)- return original(*args)++ return original(*args, **options)++ monkeypatch.setattr(batch_ridge, '_first_event_fits_uncached', run)+ return calls, original+++ def test_recorded_complete_batch_cache_preserves_values_and_caller_ownership(monkeypatch):+ measurement, event, factors, emissions = recorded()+ calls, original = counted_kernel(monkeypatch)+ expected = original(measurement, event, factors, emissions)+ assert expected is not None++ @matching._cache_ridge_fits+ def run():+ before = len(calls)+ first = batch_ridge.first_event_fits(measurement, event, factors, emissions)+ assert first == expected and len(calls) == before+1+ first[0]['f0_hz'] = -123.+ first.append({'caller_only': True})+ second = batch_ridge.first_event_fits(measurement, event, factors.copy(), emissions.copy())+ assert second == expected and len(calls) == before+1+ second[1].clear()+ third = batch_ridge.first_event_fits(measurement, event, factors, emissions)+ assert third == expected and len(calls) == before+1+ cache = matching._ridge_fit_cache.get()+ assert len(cache.batch_fit_entries) == 1+ assert cache.batch_fit_bytes == sum(len(key)+len(value) for key, value in cache.batch_fit_entries.items())+ assert 0 < cache.batch_fit_bytes <= cache.batch_fit_limit++ run()+ run()+ assert len(calls) == 2+++ def test_recorded_batch_layout_and_changed_inputs_do_not_share_results(monkeypatch):+ measurement, event, factors, emissions = recorded()+ calls, original = counted_kernel(monkeypatch)++ @matching._cache_ridge_fits+ def run():+ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == original(+ measurement, event, factors, emissions)+ assert len(calls) == 1+ # Fortran layout keeps every observed value but changes reduction+ # strides. Each layout must reproduce its own unchanged kernel result.+ column_factors, column_emissions = np.asfortranarray(factors), np.asfortranarray(emissions)+ expected = original(measurement, event, column_factors, column_emissions)+ assert batch_ridge.first_event_fits(measurement, event, column_factors, column_emissions) == expected+ assert len(calls) == 2+ assert batch_ridge.first_event_fits(measurement, event, column_factors.copy(order='F'),+ column_emissions.copy(order='F')) == expected+ assert len(calls) == 2+ # Use a shorter portion of the recorded ridge, without manufacturing+ # samples. Its normalization and acoustic arrays require another key.+ shorter = (matching.RidgeTimes(measurement[0].time[:-1]),+ measurement[1][:-1], measurement[2][:-1], {})+ assert batch_ridge.first_event_fits(shorter, event, factors[:, :-1], emissions[:, :-1]) == original(+ shorter, event, factors[:, :-1], emissions[:, :-1])+ assert len(calls) == 3+ quality = dict(event.get('quality', {}), frequency_loss_scale_hz=matching._frequency_scale(event)*1.01)+ changed_model = dict(event, quality=quality)+ assert batch_ridge.first_event_fits(measurement, changed_model, factors, emissions) == original(+ measurement, changed_model, factors, emissions)+ assert len(calls) == 4++ run()+++ def test_recorded_batch_cache_respects_byte_and_entry_limits(monkeypatch):+ measurement, event, factors, emissions = recorded()+ calls, original = counted_kernel(monkeypatch)++ def run():+ cache = matching._ridge_fit_cache.get()+ expected = original(measurement, event, factors, emissions)+ batch_ridge.first_event_fits(measurement, event, factors, emissions)+ batch_ridge.first_event_fits(measurement, event, factors[::-1], emissions[::-1])+ assert len(cache.batch_fit_entries) == 1+ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == expected+ assert len(calls) == 3+ cache.batch_fit_entries.clear()+ cache.batch_fit_bytes = 0+ cache.batch_fit_limit = 1+ for _ in range(2):+ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == expected+ assert not cache.batch_fit_entries and cache.batch_fit_bytes == 0+ assert len(calls) == 5++ matching._cache_ridge_fits(run, max_entries=1)()+++ def test_recorded_zero_drift_fallback_is_not_cached(monkeypatch):+ measurement, event, factors, emissions = recorded()+ calls, _ = counted_kernel(monkeypatch)+ no_drift = dict(event, quality=dict(event.get('quality', {}), source_drift_fraction=0.))++ @matching._cache_ridge_fits+ def run():+ for _ in range(2):+ assert batch_ridge.first_event_fits(measurement, no_drift, factors, emissions) is None+ assert len(calls) == 2+ cache = matching._ridge_fit_cache.get()+ assert not cache.batch_fit_entries and cache.batch_fit_bytes == 0++ run()+++ def test_recorded_warm_cache_does_not_hide_invalid_measurement_arity():+ measurement, event, factors, emissions = recorded()++ class DifferentIteration(list):+ def __iter__(self):+ return iter(measurement[:3])++ @matching._cache_ridge_fits+ def run():+ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) is not None+ for invalid in (measurement[:3], measurement+(None,), DifferentIteration(measurement)):+ with pytest.raises(ValueError, match='unpack'):+ batch_ridge.first_event_fits(invalid, event, factors, emissions)+ assert len(matching._ridge_fit_cache.get().batch_fit_entries) == 1++ run()++++++def test_recorded_fitter_replacement_clears_previous_snapshots(monkeypatch):++ measurement, event, factors, emissions = recorded()++ original = batch_ridge._first_event_fits_uncached++ expected = original(measurement, event, factors, emissions)++ calls = []++++ def first(*args, **options):++ calls.append('first')++ return original(*args, **options)++++ def second(*args, **options):++ calls.append('second')++ return original(*args, **options)++++ @matching._cache_ridge_fits++ def run():++ for kernel, expected_calls in ((first, ['first']),++ (second, ['first', 'second']),++ (first, ['first', 'second', 'first'])):++ monkeypatch.setattr(batch_ridge, '_first_event_fits_uncached', kernel)++ for _ in range(2):++ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == expected++ assert calls == expected_calls++ assert len(matching._ridge_fit_cache.get().batch_fit_entries) == 1++++ run()++++++def test_recorded_custom_inputs_bypass_a_warm_cache(monkeypatch):++ from types import SimpleNamespace++++ measurement, event, factors, emissions = recorded()++ calls, original = counted_kernel(monkeypatch)++ expected = original(measurement, event, factors, emissions)++++ class CustomEvent(dict):++ pass++++ custom_time = (SimpleNamespace(time=measurement[0].time), *measurement[1:])++ cases = ((custom_time, event), (measurement, CustomEvent(event)),++ (measurement, dict(event, quality=CustomEvent(event.get('quality', {})))))++++ @matching._cache_ridge_fits++ def run():++ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == expected++ for custom_measurement, custom_event in cases:++ before = len(calls)++ for _ in range(2):++ assert batch_ridge.first_event_fits(custom_measurement, custom_event, factors, emissions) == expected++ assert len(calls) == before + 2++ assert len(matching._ridge_fit_cache.get().batch_fit_entries) == 1++++ run()++++++def test_recorded_cache_separates_legacy_arithmetic(monkeypatch):++ measurement, event, factors, emissions = recorded()++ calls, original = counted_kernel(monkeypatch)++ ordinary = original(measurement, event, factors, emissions)++ legacy = original(measurement, event, factors, emissions, legacy_arithmetic=True)++ assert ordinary is not None++++ @matching._cache_ridge_fits++ def run():++ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == ordinary++ assert len(calls) == 1++ assert batch_ridge.first_event_fits(measurement, event, factors, emissions,++ legacy_arithmetic=True) == legacy++ assert len(calls) == 2++ assert batch_ridge.first_event_fits(measurement, event, factors, emissions) == ordinary++ assert len(calls) == 2++ assert batch_ridge.first_event_fits(measurement, event, factors, emissions,++ legacy_arithmetic=True) == legacy++ assert len(calls) == (3 if legacy is None else 2)++++ run()