File size: 1,497 Bytes
ff4becd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | """SHA256 helpers for canonical-indices cache invalidation + result-record
provenance. Computing the digest of every upstream parquet a loader reads,
embedded into ``meta.attrs["data_sha256"]``, makes silent dataset drift
detectable: if a panel parquet mutates, the canonical-indices cache key
changes and any downstream ``RunRecord`` carries a different hash.
"""
from __future__ import annotations
import hashlib
from pathlib import Path
_BUF_SIZE = 1 << 20 # 1 MB
def sha256_file(path: str | Path) -> str:
"""Return the hex SHA-256 of ``path`` (full file)."""
p = Path(path)
if not p.exists():
raise FileNotFoundError(f"sha256_file: {p} does not exist")
h = hashlib.sha256()
with p.open("rb") as fh:
while chunk := fh.read(_BUF_SIZE):
h.update(chunk)
return h.hexdigest()
def sha256_dataset(paths: list[str | Path]) -> dict[str, str]:
"""Return ``{path_str: sha256}`` for every existing path in ``paths``."""
return {str(Path(p)): sha256_file(p) for p in paths}
def sha256_combined(paths: list[str | Path]) -> str:
"""Return a single hex digest combining every file in ``paths``.
Used as a cache-key suffix for canonical-indices: if ANY upstream
parquet mutates, the suffix changes and the cache regenerates.
"""
h = hashlib.sha256()
for p in sorted(str(Path(x)) for x in paths):
sub = sha256_file(p).encode()
h.update(p.encode() + b":" + sub + b"\n")
return h.hexdigest()[:16]
|