Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

fix: keep read-only flight indexes usable without digest sidecars

Cinna Davisdabbb61f53df
diff --git a/src/dopplergeist/data_access.py b/src/dopplergeist/data_access.py
index 749e387..6847566 100644
--- a/src/dopplergeist/data_access.py
+++ b/src/dopplergeist/data_access.py
@@ -5,7 +5,7 @@ Coverage describes the *source query*, never receiver/network completeness.
"""
from collections import Counter, OrderedDict, deque
from concurrent.futures import ProcessPoolExecutor
-from contextlib import contextmanager
+from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from functools import lru_cache
@@ -254,33 +254,57 @@ def cache_lock(path):
yield
+def _file_stat_identity(info):
+ return [info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns]
+
+
+def _checked_sha256(path, identity=None):
+ """Hash the opened file, rejecting source mutation or path replacement."""
+ with path.open("rb") as stream:
+ before = _file_stat_identity(os.fstat(stream.fileno()))
+ if identity is not None and before != identity:
+ raise OSError(f"File changed while hashing: {path}")
+ digest = hashlib.file_digest(stream, "sha256").hexdigest()
+ after = _file_stat_identity(os.fstat(stream.fileno()))
+ if before != after or before != _file_stat_identity(path.stat()):
+ raise OSError(f"File changed while hashing: {path}")
+ return digest
+
+
def cached_sha256(path):
- """Reuse a digest receipt for an immutable cache file while its stat identity holds."""
+ """Reuse a stat-validated digest, falling back to hashing read-only inputs.
+
+ Receipt and lock files are optional acceleration. Their I/O failures must
+ not prevent reading an otherwise usable index or weaken source-change checks.
+ """
path = Path(path)
receipt = path.with_name(path.name + ".sha256.json")
lock = receipt.with_name(receipt.name + ".lock")
- with cache_lock(lock):
- info = path.stat()
- identity = [info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns]
+ with ExitStack() as stack:
+ try:
+ stack.enter_context(cache_lock(lock))
+ except OSError:
+ return _checked_sha256(path)
+ identity = _file_stat_identity(path.stat())
try:
saved = json.loads(receipt.read_text())
digest = saved.get("sha256")
if (saved.get("version") == 1 and saved.get("identity") == identity and
isinstance(digest, str) and len(digest) == 64 and
all(char in "0123456789abcdef" for char in digest)):
- current = path.stat()
- current_identity = [current.st_dev, current.st_ino, current.st_size,
- current.st_mtime_ns, current.st_ctime_ns]
+ current_identity = _file_stat_identity(path.stat())
if identity == current_identity:
return digest
identity = current_identity
except (OSError, UnicodeError, AttributeError, json.JSONDecodeError):
pass
- digest = sha256(path)
- after = path.stat()
- if identity != [after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns]:
- raise OSError(f"File changed while hashing: {path}")
- write_json(receipt, {"version": 1, "identity": identity, "sha256": digest})
+ digest = _checked_sha256(path, identity)
+ try:
+ write_json(receipt, {"version": 1, "identity": identity, "sha256": digest})
+ except OSError:
+ # The digest already passed the same source checks. Cache metadata
+ # may be unwritable even when an existing lock could be acquired.
+ pass
return digest
diff --git a/src/dopplergeist/index_compatibility.py b/src/dopplergeist/index_compatibility.py
index f752971..391280e 100644
--- a/src/dopplergeist/index_compatibility.py
+++ b/src/dopplergeist/index_compatibility.py
@@ -3,6 +3,13 @@
# The cache-size-only change and this exact compatibility check do not change
# decoded observations or normalization. Any source edit disables this mapping.
PREPARED_DATA_ACCESS_EQUIVALENCE = {
+ # Read-only digest fallback changes no observation decoding or normalization.
+ "77da0d39e1e95476fdf02e29e9a345914545af7e62227a93b4cb6786edb37a71": (
+ "ddd77e9734fff6a70cc9195bd1305002f9f78e39ea601f27e0f596dcb336033a",
+ "275e38a37f82993b609b6b78c113d35c4da269083ceb3afcb1d94ada48bdc0d4",
+ "dad02d09d89ad9d267cd8d0424b8e018d0399a28d6b43903b5a55867290b3957",
+ "d664caf4b496599d29a81360c4a9d9736a3248c157e71d885463b349aad6dd36",
+ ),
# The native collector only replaces canonical Python column extraction.
"ddd77e9734fff6a70cc9195bd1305002f9f78e39ea601f27e0f596dcb336033a": (
"275e38a37f82993b609b6b78c113d35c4da269083ceb3afcb1d94ada48bdc0d4",
diff --git a/tests/test_real_index_hash_cache.py b/tests/test_real_index_hash_cache.py
new file mode 100644
index 0000000..80cfeee
--- /dev/null
+++ b/tests/test_real_index_hash_cache.py
@@ -0,0 +1,132 @@
+"""Digest-cache controls on an index built from archived aircraft observations."""
+from contextlib import contextmanager
+import json
+import os
+from pathlib import Path
+import shutil
+import sqlite3
+
+import pandas as pd
+import pytest
+
+from dopplergeist import data_access
+from dopplergeist.data_access import FlightIndex, cached_sha256, sha256
+
+
+def observed_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 observations; incomplete excerpt"}
+ index = FlightIndex.build(tmp_path / "observed.sqlite", [frame], sources=[], coverage=coverage)
+ assert index.report["segments"] > 0
+ return index.path
+
+
+def test_unchanged_real_index_reuses_verified_digest(observed_index, monkeypatch):
+ expected = sha256(observed_index)
+ original, calls = data_access.hashlib.file_digest, []
+
+ def count(stream, algorithm):
+ calls.append(stream.name)
+ return original(stream, algorithm)
+
+ monkeypatch.setattr(data_access.hashlib, "file_digest", count)
+ assert cached_sha256(observed_index) == expected
+ assert cached_sha256(observed_index) == expected
+ assert calls == [str(observed_index)]
+
+
[email protected]("failure", ["lock", "receipt"])
+def test_real_index_remains_readable_when_sidecars_are_unwritable(observed_index, monkeypatch, failure):
+ expected = sha256(observed_index)
+ receipt = observed_index.with_name(observed_index.name + ".sha256.json")
+
+ @contextmanager
+ def blocked_lock(path):
+ raise PermissionError("read-only index directory")
+ yield
+
+ def blocked_receipt(path, value):
+ raise PermissionError("read-only digest receipt")
+
+ # Exercise both failures even under accounts that bypass chmod restrictions.
+ monkeypatch.setattr(data_access, "cache_lock" if failure == "lock" else "write_json",
+ blocked_lock if failure == "lock" else blocked_receipt)
+ assert cached_sha256(observed_index) == expected
+ assert not receipt.exists()
+ assert FlightIndex(observed_index).report["segments"] > 0
+
+
+def test_modified_real_index_is_rehashed_despite_restored_mtime(observed_index):
+ before = observed_index.stat()
+ old_digest = cached_sha256(observed_index)
+ # Modify metadata only in this disposable index. Observations stay intact.
+ with sqlite3.connect(observed_index) as database:
+ metadata = json.loads(database.execute("SELECT value FROM metadata").fetchone()[0])
+ metadata["digest_cache_test"] = "updated metadata"
+ database.execute("UPDATE metadata SET value=?", (json.dumps(metadata),))
+ os.utime(observed_index, ns=(before.st_atime_ns, before.st_mtime_ns))
+ expected = sha256(observed_index)
+ assert expected != old_digest
+ assert cached_sha256(observed_index) == expected
+
+
[email protected]("sidecar_unavailable", [False, True])
+def test_real_index_mutation_during_hash_is_rejected(observed_index, monkeypatch, sidecar_unavailable):
+ original = data_access.hashlib.file_digest
+
+ def change_during_hash(stream, algorithm):
+ digest = original(stream, algorithm)
+ # Deliberately corrupt only the disposable copy after its bytes were read.
+ with observed_index.open("ab") as changed:
+ changed.write(b"\0")
+ return digest
+
+ @contextmanager
+ def blocked_lock(path):
+ raise PermissionError("read-only index directory")
+ yield
+
+ monkeypatch.setattr(data_access.hashlib, "file_digest", change_during_hash)
+ if sidecar_unavailable:
+ monkeypatch.setattr(data_access, "cache_lock", blocked_lock)
+ with pytest.raises(OSError, match="File changed while hashing"):
+ cached_sha256(observed_index)
+ assert not observed_index.with_name(observed_index.name + ".sha256.json").exists()
+
+
+def test_real_index_replacement_during_hash_is_rejected(observed_index, monkeypatch):
+ replacement = observed_index.with_name("replacement.sqlite")
+ shutil.copyfile(observed_index, replacement)
+ original = data_access.hashlib.file_digest
+
+ def replace_during_hash(stream, algorithm):
+ digest = original(stream, algorithm)
+ replacement.replace(observed_index)
+ return digest
+
+ monkeypatch.setattr(data_access.hashlib, "file_digest", replace_during_hash)
+ with pytest.raises(OSError, match="File changed while hashing"):
+ cached_sha256(observed_index)
+
+
+def test_change_during_receipt_hit_rehashes_current_bytes(observed_index, monkeypatch):
+ old_digest = cached_sha256(observed_index)
+ original, calls = Path.stat, 0
+
+ def stat(path, *args, **kwargs):
+ nonlocal calls
+ if path == observed_index:
+ calls += 1
+ if calls == 2:
+ with observed_index.open("ab") as changed:
+ changed.write(b"\0")
+ return original(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "stat", stat)
+ current = cached_sha256(observed_index)
+ assert current != old_digest
+ assert current == sha256(observed_index)
diff --git a/tests/test_real_prepared_compatibility.py b/tests/test_real_prepared_compatibility.py
index b5b07fd..da26e81 100644
--- a/tests/test_real_prepared_compatibility.py
+++ b/tests/test_real_prepared_compatibility.py
@@ -9,7 +9,8 @@ from test_real_prepared_index import signature
@pytest.mark.parametrize("variable", ["DOPPLERGEIST_REAL_PREPARED_BEFORE_CACHE", "DOPPLERGEIST_REAL_PREPARED_AFTER_CACHE",
- "DOPPLERGEIST_REAL_PREPARED_AFTER_COMPAT"])
+ "DOPPLERGEIST_REAL_PREPARED_AFTER_COMPAT",
+ "DOPPLERGEIST_REAL_PREPARED_BEFORE_DIGEST"])
def test_prior_prepared_index_is_reused_only_for_pinned_sources(variable, monkeypatch):
value = os.environ.get(variable)
if not value: