Coverage for app / util / fingerprint.py: 97%
30 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2A fingerprint of the code a service runs.
4The platform benchmark re-runs CHAINR Bot only when something that shapes its
5answers has changed. A deploy id changes on every deploy, a front-end fix
6included, so keying on it re-ran the bot (and paid for it) when nothing that
7decides an answer had moved. The source cannot be wrong about itself: hash the
8files that decide the answer, and a deploy that leaves them byte-identical
9leaves the fingerprint unchanged.
11svc-core and svc-ai each carry this file, byte for byte
12(``tools/test_shared_modules.py``): svc-core hashes the files that build the
13bot's request, svc-ai the code that answers it.
14"""
16from __future__ import annotations
18import hashlib
19from collections.abc import Iterable
20from pathlib import Path
22#: Not source: caches that differ between two builds of the same code.
23_SKIPPED_PARTS = frozenset(
24 {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache"}
25)
26_SKIPPED_SUFFIXES = frozenset({".pyc", ".pyo"})
29def _files(root: Path, paths: Iterable[str]) -> list[Path]:
30 found: set[Path] = set()
31 for rel in paths:
32 target = root / rel
33 if target.is_file():
34 found.add(target)
35 continue
36 if not target.is_dir():
37 continue
38 for path in target.rglob("*"):
39 if not path.is_file() or path.suffix in _SKIPPED_SUFFIXES:
40 continue
41 if _SKIPPED_PARTS & set(path.relative_to(root).parts):
42 continue
43 found.add(path)
44 return sorted(found)
47def code_fingerprint(root: Path, paths: Iterable[str] = (".",)) -> str:
48 """A short hash of every file under ``paths`` (relative to ``root``): each
49 file's path relative to ``root`` and its bytes, in a fixed order. The same
50 source gives the same fingerprint on any machine; a path that does not
51 exist contributes nothing."""
52 digest = hashlib.sha256()
53 for path in _files(root, paths):
54 digest.update(path.relative_to(root).as_posix().encode())
55 digest.update(b"\0")
56 digest.update(path.read_bytes())
57 digest.update(b"\0")
58 return digest.hexdigest()[:16]