File size: 1,621 Bytes
f85bc82 | 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 46 47 48 | """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')
|