chenhuaDr's picture
Upload code/ti5_arm_scripts/cache_provenance.py
f85bc82 verified
Raw History Blame Contribute Delete
1.62 kB
"""Reject analysis caches whose inputs or implementation have changed."""
import hashlib
import json
from pathlib import Path
def digest(path):
result = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
result.update(block)
return result.hexdigest()
def provenance(inputs):
paths = [Path(path).resolve() for path in inputs]
paths.append(Path(__file__).resolve())
return {str(path): digest(path) for path in sorted(set(paths))}
def verified_cache(path, inputs):
"""An unverified legacy cache must be rebuilt in a new analysis directory.
Fail closed rather than silently mixing a new recording with archived
arrays, split identities or reports. Never delete archived evidence here.
"""
path = Path(path)
if not path.exists():
return False
manifest = Path(str(path) + '.provenance.json')
if manifest.exists():
saved = json.loads(manifest.read_text())
if (saved.get('inputs') == provenance(inputs)
and saved.get('cache_sha256') == digest(path)):
return True
raise ValueError(
f'Unverified or stale analysis cache: {path}. '
'Use a new analysis output directory and rebuild upstream stages; '
'retain the archived directory for reproducing previous reports.')
def record_cache(path, inputs):
path = Path(path)
manifest = Path(str(path) + '.provenance.json')
manifest.write_text(json.dumps(
{'inputs': provenance(inputs), 'cache_sha256': digest(path)},
indent=2) + '\n')