Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(provenance): make the checksum encoding injective and version it per row (#2136) (#2148)

Kevinec4cad972fe1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91a8f4cd..2dac2695 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -34,6 +34,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **Provenance checksums were not injective: two records that differed only in where a field boundary fell hashed the same** (fixes #2136) by @pkupt
+ - `compute_checksum()` pasted the 16 hashed fields together with nothing between them, so `{"entity_type": "ab", "activity_id": "c"}` and `{"entity_type": "a", "activity_id": "bc"}` produced the same digest, and a row rewritten across a field boundary still passed `verify_checksum()` and `verify_chain()`. `used_entities` had the same hole once joined: `["a,b"]` and `["a", "b"]` collided
+ - The v2 encoding writes a `prov-v2\0` header, then every value as a 1-byte type tag, a 4-byte big-endian length and the UTF-8 bytes; lists carry an element count and each element is length-prefixed in turn, so a boundary cannot move. It also settles a divergence v1 left open: a `None` field hashed as `''` through the dict path but as `'None'` through the dataclass path, so one record could hash two ways
+ - Compatibility is per row rather than a caller-facing flag. `ProvenanceEntry.checksum_version` is stamped 2 on write and persisted (new `checksum_version` column, added to already-existing tables by `_migrate_schema()`), and `verify_checksum()` dispatches on it, so rows written before this change still verify with the v1 scheme and an existing store does not report a broken chain after upgrade. `compute_checksum_legacy()` keeps the v1 body for that path. New `tests/provenance/test_checksum_encoding.py`
+ - The recorded version is trusted metadata, not an authenticated field: it is not one of the hashed values, so a writer who can update a row can relabel a v2 row as v1 and have it checked under the collision-prone encoding. Detecting a rewrite is the hash chain's job, not this field's. `compute_checksum()` no longer writes the version onto its argument; the stamp happens on write, and `verify_checksum()` treats a row with no version as "v1, else v2"
+ - `compute_checksum()` now returns the v2 digest for every input, so code that checks integrity with `compute_checksum(e) == e.checksum` reports every pre-upgrade row as tampered. Use `verify_checksum(e)`, which picks the row's encoding; the audit examples in `docs/guides/provenance.md` and `docs/reference/provenance.md` now do
+ - Verification fails closed on input it cannot encode: an unknown `checksum_version` (0, negative, or newer than this release), a non-list `used_entities` or a malformed v1 row is a mismatch, not an exception that aborts `verify_chain()`. A `NULL` confidence hashes differently from `1.0`, and non-`dict` mappings are read by key instead of hashing to a constant
+
- **Breaking: `BridgeAxiom.apply()` returned normally when its provenance record was not written** (fixes #2137) by @pkupt
- **Why**: `apply()` swallowed every provenance failure with `except Exception: pass`, and `ProvenanceManager.track_entity()` reports a storage failure by returning `None` (or a copy of the previous entry on an update) instead of raising. Either way the transform came back as if it had been recorded, so a translation could have no audit record, or a stale one showing an earlier value
- **What changed**: when a `prov_manager` is passed and the record is not written, `apply()` raises `ProvenanceRecordingError` (new in `semantica.utils`, error code `SEM007`), and `create_translation_chain()` lets it propagate. `apply()` gains `require_provenance=True`; with `False` it returns the transform instead. Every result now carries `provenance_recorded` (`bool`) and `provenance_error` (`str` or `None`). `trace_translation_chain()` no longer drops a failed `get_lineage()`: the layer gets `provenance=None` and a `provenance_error`
diff --git a/docs/guides/provenance.md b/docs/guides/provenance.md
index ee460eee..d477d16b 100644
--- a/docs/guides/provenance.md
+++ b/docs/guides/provenance.md
@@ -241,15 +241,14 @@ Every `ProvenanceEntry` carries a SHA-256 checksum computed at write time. If an
Integrity verification is critical for regulatory compliance and forensic analysis. Run integrity checks as part of any compliance audit:
```python
-from semantica.provenance.integrity import compute_checksum
+from semantica.provenance.integrity import verify_checksum
raw_entries = prov.trace_lineage("cve-2024-3400")
print("Integrity check:")
for e in raw_entries:
stored = e.checksum
- computed = compute_checksum(e)
- status = "OK" if stored == computed else "TAMPERED"
+ status = "OK" if verify_checksum(e) else "TAMPERED"
print(f" [{status}] {e.entity_id[:50]} {(stored or '')[:16]}...")
```
@@ -333,7 +332,7 @@ This summary is the starting point for a compliance attestation: you can state t
**Overusing provenance in low-value scenarios.** Recording provenance for every intermediate calculation or temporary variable creates storage overhead without compliance benefit. Focus provenance tracking on entities, relationships, and properties that have legal, regulatory, or business significance.
-**Failing to validate integrity checksums.** Cryptographic integrity verification only works if you actually check it. Include regular `compute_checksum()` validation in audit workflows and incident response procedures.
+**Failing to validate integrity checksums.** Cryptographic integrity verification only works if you actually check it. Include regular `verify_checksum()` validation in audit workflows and incident response procedures.
**Mixing provenance granularities.** Tracking some entities at the document level and others at the sentence level creates inconsistent audit trails. Establish consistent granularity standards for each data type and processing workflow.
@@ -424,7 +423,7 @@ The version chain created by repeated `track_entity()` calls on the same `entity
```python
from semantica.provenance import ProvenanceManager
from semantica.provenance.schemas import SourceReference
-from semantica.provenance.integrity import compute_checksum
+from semantica.provenance.integrity import verify_checksum
prov = ProvenanceManager(storage_path="soc_provenance.db")
@@ -466,7 +465,7 @@ print(f"Update count : {lineage['entity_count']} records")
# Integrity check before relying on the record for a patch decision
entries = prov.trace_lineage("cve-2023-44487")
for e in entries:
- ok = compute_checksum(e) == e.checksum
+ ok = verify_checksum(e)
print(f" [{('OK' if ok else 'TAMPERED')}] {e.timestamp[:19]} source={e.source_document}")
```
@@ -481,7 +480,7 @@ A clinical evidence graph tracks efficacy data from source publications through
```python
from semantica.provenance import ProvenanceManager
from semantica.provenance.schemas import SourceReference
-from semantica.provenance.integrity import compute_checksum
+from semantica.provenance.integrity import verify_checksum
prov = ProvenanceManager(storage_path="clinical_provenance.db")
@@ -534,7 +533,7 @@ for entry in lineage["lineage_chain"]:
# Integrity verification (21 CFR Part 11 requirement)
entries = prov.trace_lineage("VE_primary_BNT162b2_C4591001")
for e in entries:
- status = "OK" if compute_checksum(e) == e.checksum else "TAMPERED"
+ status = "OK" if verify_checksum(e) else "TAMPERED"
print(f" Integrity [{status}]: {e.entity_id}")
stats = prov.get_statistics()
diff --git a/docs/reference/provenance.md b/docs/reference/provenance.md
index a3d9c64c..ade9182c 100644
--- a/docs/reference/provenance.md
+++ b/docs/reference/provenance.md
@@ -349,7 +349,9 @@ if not is_valid:
raise RuntimeError("Provenance record has been tampered with.")
```
-The checksum covers `entity_id`, `entity_type`, `activity_id`, `source_document`, `timestamp`, and `confidence`.
+The checksum covers `entity_type`, `activity_id`, the agent, `source_document`, `timestamp`, `confidence`, the lineage links (`parent_entity_id`, `previous_version_id`, `derived_from_id`, `used_entities`), `previous_checksum` and the invalidation fields. `entity_id` is deliberately excluded so an archival relabel does not break the chain.
+
+Compare with `verify_checksum(entry)`, not `compute_checksum(entry) == entry.checksum`. `compute_checksum()` always returns the current (v2) encoding, while rows written before the encoding changed carry a v1 digest; `verify_checksum()` checks each row against the encoding it was written with.
<Tip>
**Run `verify_checksum(entry)` before any compliance export.** Pass the `ProvenanceEntry` object returned by `trace_lineage()` directly. If the stored checksum no longer matches, raise an error before the export proceeds.
diff --git a/semantica/provenance/integrity.py b/semantica/provenance/integrity.py
index bedaaf0e..98c6564c 100644
--- a/semantica/provenance/integrity.py
+++ b/semantica/provenance/integrity.py
@@ -20,10 +20,140 @@ License: MIT
"""
import hashlib
-from typing import Any, Dict, Optional
+from collections.abc import Mapping
+from typing import Any, Callable, Dict, List, Optional
from .schemas import ProvenanceEntry
+# Checksum encoding version (issue #2136).
+#
+# v1 pasted the 16 field strings together with nothing between them, so two
+# records that differ only in where a field boundary falls hashed the same.
+# v2 length-prefixes every value and tags lists with their element count, so a
+# boundary cannot move. The version is recorded per row
+# (ProvenanceEntry.checksum_version) instead of being a caller-facing flag:
+# defaulting a flag to False would report every existing store as a broken
+# chain on upgrade while nothing had been tampered with, and defaulting it to
+# True would leave the collision open for good.
+CHECKSUM_VERSION = 2
+LEGACY_CHECKSUM_VERSION = 1
+
+# The hashed fields, in the fixed order both encodings use. entity_id is
+# deliberately absent; see compute_checksum().
+_CHECKSUM_FIELDS = (
+ ("entity_type", "text"),
+ ("activity_id", "text"),
+ ("agent_id", "text"),
+ ("agent_type", "text"),
+ ("source_document", "text"),
+ ("timestamp", "text"),
+ ("confidence", "float"),
+ ("parent_entity_id", "text"),
+ ("previous_version_id", "text"),
+ ("derived_from_id", "text"),
+ ("used_entities", "list"),
+ ("previous_checksum", "text"),
+ ("invalidated", "bool"),
+ ("invalidated_at_time", "text"),
+ ("invalidated_by", "text"),
+ ("invalidation_reason", "text"),
+)
+
+# Encoding tags. Every value is written as <tag><4-byte big-endian length>
+# <utf-8 bytes>; a list is written as <tag><count> then each element in the
+# same length-prefixed form, so ["a,b"] and ["a", "b"] cannot collide either.
+# A null is the tag alone, so a NULL confidence cannot hash like 1.0.
+_TAG_SCALAR = b"\x01"
+_TAG_LIST = b"\x02"
+_TAG_NULL = b"\x03"
+_V2_HEADER = b"prov-v2\x00"
+
+_MISSING = object()
+
+
+def _get(entry: Any, name: str) -> Any:
+ """Read a field from a mapping or an object; ``_MISSING`` when absent."""
+ if isinstance(entry, Mapping):
+ return entry.get(name, _MISSING)
+ return getattr(entry, name, _MISSING)
+
+
+def _raw_field(entry: Any, name: str, default: Any) -> Any:
+ """Read a field from a mapping or a dataclass, treating None as absent."""
+ value = _get(entry, name)
+ return default if value is _MISSING or value is None else value
+
+
+def _checksum_field_values(entry: Any) -> List[Any]:
+ """
+ Return the hashed values in ``_CHECKSUM_FIELDS`` order.
+
+ Both the dict and the dataclass path go through this function, so the same
+ content always produces the same value vector. v1 did not: a None field
+ hashed as ``''`` through ``entry.get('x') or ''`` but as ``'None'`` through
+ ``f"{entry.x}"``, so identical records hashed differently depending on how
+ they were passed in.
+ """
+ values: List[Any] = []
+ for name, kind in _CHECKSUM_FIELDS:
+ if kind == "list":
+ raw = _raw_field(entry, name, [])
+ if isinstance(raw, (list, tuple)):
+ values.append([str(item) for item in raw])
+ else:
+ # A non-list value (a corrupted row, or a bare string) is
+ # hashed as a scalar: the tag keeps it from colliding with any
+ # list, so "ab" cannot pass for ["a", "b"], and it is a
+ # mismatch rather than a TypeError mid-verify_chain().
+ values.append(str(raw))
+ elif kind == "float":
+ raw = _get(entry, name)
+ if raw is _MISSING:
+ # An absent confidence is the dataclass default, so a dict
+ # without the key hashes like a ProvenanceEntry with 1.0.
+ raw = 1.0
+ if raw is None:
+ # An explicit NULL is not 1.0: hashing it as the default would
+ # let `SET confidence = NULL` pass verification.
+ values.append(None)
+ continue
+ try:
+ values.append(str(float(raw)))
+ except (TypeError, ValueError, OverflowError):
+ # A row whose confidence is not numeric must fail verification,
+ # not raise while verifying it: verify_checksum() answers a
+ # question, and a malformed row is a "no", not an exception.
+ # Falling back to the raw text keeps the value hashable and
+ # still changes the digest if someone edits it.
+ values.append(str(raw))
+ elif kind == "bool":
+ values.append(str(bool(_raw_field(entry, name, False))))
+ else:
+ values.append(str(_raw_field(entry, name, "")))
+ return values
+
+
+def _encode_fields(values: List[Any]) -> bytes:
+ """Encode a value vector so no two distinct vectors collide (issue #2136)."""
+ out = bytearray(_V2_HEADER)
+ for value in values:
+ if value is None:
+ out += _TAG_NULL
+ elif isinstance(value, list):
+ out += _TAG_LIST
+ out += len(value).to_bytes(4, "big")
+ for item in value:
+ encoded = item.encode("utf-8")
+ out += len(encoded).to_bytes(4, "big")
+ out += encoded
+ else:
+ encoded = value.encode("utf-8")
+ out += _TAG_SCALAR
+ out += len(encoded).to_bytes(4, "big")
+ out += encoded
+ return bytes(out)
+
+
def compute_checksum(entry: Any) -> str:
"""
Compute SHA-256 checksum for a provenance entry.
@@ -54,6 +184,15 @@ def compute_checksum(entry: Any) -> str:
verify_chain() (it requires a delete+insert, which breaks the chain for
whatever the deleted row's successor was).
+ The encoding version is recorded on the row when it is written
+ (``ProvenanceManager._save_entry``), not here: computing a digest should
+ not write to the value it was given, and a read-only comparison on a
+ legacy row must not relabel that row in memory. A caller who assigns the
+ digest by hand (``entry.checksum = compute_checksum(entry)``, as the
+ example below does) never reaches that path, so ``verify_checksum()``
+ treats a row with no recorded version as "v2, else v1" rather than
+ assuming the old scheme.
+
Args:
entry: ProvenanceEntry or dict to compute checksum for
@@ -71,7 +210,51 @@ def compute_checksum(entry: Any) -> str:
>>> print(checksum)
'a3b2c1d4e5f6...'
"""
- # Concatenate critical fields for checksum (entity_id intentionally excluded, see docstring)
+ return hashlib.sha256(_encode_fields(_checksum_field_values(entry))).hexdigest()
+
+
+def _recorded_checksum_version(entry: Any) -> Optional[int]:
+ """Return the version recorded on ``entry``, or None when it carries none."""
+ raw = _raw_field(entry, "checksum_version", None)
+ if raw is None:
+ return None
+ try:
+ return int(raw)
+ except (TypeError, ValueError, OverflowError):
+ return None
+
+
+def checksum_version(entry: Any) -> int:
+ """
+ Return the checksum encoding version recorded on ``entry``.
+
+ Rows written before issue #2136 carry no version and report v1, so an
+ existing store keeps verifying after upgrade without being re-hashed and
+ without a caller-facing flag. A digest assigned by hand from
+ ``compute_checksum()`` carries no version either, so ``verify_checksum()``
+ accepts either encoding on an unversioned row; this helper reports what
+ was recorded, not which encoding matched.
+
+ The recorded version is trusted metadata, not an authenticated field: it is
+ not one of the hashed values, so a writer who can update a row can relabel a
+ v2 row as v1 and have it checked under the collision-prone encoding. That is
+ outside what a per-row digest claims to protect — detecting a rewrite is the
+ chain's job (``previous_checksum``), not this field's.
+ """
+ recorded = _recorded_checksum_version(entry)
+ return LEGACY_CHECKSUM_VERSION if recorded is None else recorded
+
+
+def compute_checksum_legacy(entry: Any) -> str:
+ """
+ Compute the v1 (field-concatenation) checksum, for rows written before
+ issue #2136.
+
+ That encoding is not injective — two records that differ only in where a
+ field boundary falls hash the same — so it is used only to verify rows
+ whose ``checksum_version`` is 1 or absent. New rows always get the v2
+ encoding from ``compute_checksum()``.
+ """
if isinstance(entry, dict):
used_entities = entry.get("used_entities") or []
data = (
@@ -138,16 +321,51 @@ def verify_checksum(entry: Any, expected_checksum: Optional[str] = None) -> bool
True
"""
if expected_checksum is None:
- if isinstance(entry, dict):
- expected_checksum = entry.get("checksum")
- else:
- expected_checksum = getattr(entry, "checksum", None)
-
+ expected_checksum = _raw_field(entry, "checksum", None)
+
if expected_checksum is None:
return False
-
- current_checksum = compute_checksum(entry)
- return current_checksum == expected_checksum
+
+ recorded = _recorded_checksum_version(entry)
+ if recorded is None:
+ # No version on the row: either it predates the migration (v1) or the
+ # digest was assigned by hand from compute_checksum() (v2). The two
+ # encodings cannot produce the same digest, so trying both detects
+ # exactly what dispatching would. v1 goes first because every row of
+ # an unmigrated store is v1.
+ return _matches(
+ compute_checksum_legacy, entry, expected_checksum
+ ) or _matches(compute_checksum, entry, expected_checksum)
+
+ # An unknown version (0, negative, or newer than this code) is a mismatch,
+ # not a guess at the nearest encoding.
+ compute = _ENCODERS.get(recorded)
+ return compute is not None and _matches(compute, entry, expected_checksum)
+
+
+def _matches(
+ compute: Callable[[Any], str], entry: Any, expected_checksum: str
+) -> bool:
+ """
+ True when ``compute(entry)`` equals the expected digest.
+
+ A row too malformed to encode (the v1 encoder raises on non-string
+ ``used_entities`` or an object without ``entity_type``) is a "no", so one
+ corrupted row is reported by verify_chain() instead of aborting it.
+ """
+ try:
+ return compute(entry) == expected_checksum
+ except (TypeError, ValueError, AttributeError, OverflowError):
+ return False
+
+
+# One encoder per recorded version. A new encoding adds an entry here and
+# bumps CHECKSUM_VERSION; existing rows keep dispatching to the encoder they
+# were written with.
+_ENCODERS: Dict[int, Callable[[Any], str]] = {
+ LEGACY_CHECKSUM_VERSION: compute_checksum_legacy,
+ CHECKSUM_VERSION: compute_checksum,
+}
def compute_data_checksum(data: str) -> str:
diff --git a/semantica/provenance/manager.py b/semantica/provenance/manager.py
index b28f7f8c..a60fe2b6 100644
--- a/semantica/provenance/manager.py
+++ b/semantica/provenance/manager.py
@@ -35,7 +35,7 @@ import threading
from .schemas import ProvenanceEntry, SourceReference, AgentRecord, ActivityRecord
from .storage import ProvenanceStorage, InMemoryStorage, SQLiteStorage
-from .integrity import compute_checksum, verify_checksum
+from .integrity import CHECKSUM_VERSION, compute_checksum, verify_checksum
from ..utils.helpers import to_utc_datetime, utc_now_iso
from ..utils.logging import get_logger
@@ -168,6 +168,11 @@ class ProvenanceManager:
entry.sequence_id = (head[0] + 1) if head else 1
entry.previous_checksum = head[1] if head else None
+ # Stamp the encoding version alongside the checksum so verification can
+ # dispatch per row instead of taking a caller-facing allow-legacy flag
+ # (issue #2136): rows written before this change carry no version, and
+ # verify_checksum() accepts either encoding on such a row.
+ entry.checksum_version = CHECKSUM_VERSION
entry.checksum = compute_checksum(entry)
try:
diff --git a/semantica/provenance/schemas.py b/semantica/provenance/schemas.py
index 1847b341..92563e9a 100644
--- a/semantica/provenance/schemas.py
+++ b/semantica/provenance/schemas.py
@@ -164,6 +164,14 @@ class ProvenanceEntry:
metadata: Dict[str, Any] = field(default_factory=dict)
version: str = "1.0"
+ # Checksum encoding version (issue #2136). Rows written before the
+ # injective encoding existed have no value, and verification accepts
+ # either encoding on them (a v1 digest cannot match v2); new rows are
+ # stamped 2 and verified with the length-prefixed scheme only. Kept per row so an existing store keeps
+ # verifying after upgrade without a global allow-legacy flag, and no
+ # caller has to know which format it is looking at.
+ checksum_version: Optional[int] = None
+
def to_dict(self) -> Dict[str, Any]:
"""
Convert provenance entry to dictionary.
@@ -211,6 +219,7 @@ class ProvenanceEntry:
"credibility": self.credibility,
"metadata": self.metadata,
"version": self.version,
+ "checksum_version": self.checksum_version,
}
@classmethod
diff --git a/semantica/provenance/storage.py b/semantica/provenance/storage.py
index 6eedca77..c2fb1401 100644
--- a/semantica/provenance/storage.py
+++ b/semantica/provenance/storage.py
@@ -562,6 +562,7 @@ class SQLiteStorage(ProvenanceStorage):
("revision_type", "TEXT"),
("supersedes", "TEXT"),
("bundle_id", "TEXT"),
+ ("checksum_version", "INTEGER"),
]
def _migrate_schema(self, conn: sqlite3.Connection) -> None:
@@ -623,7 +624,8 @@ class SQLiteStorage(ProvenanceStorage):
valid_until TEXT,
revision_type TEXT,
supersedes TEXT,
- bundle_id TEXT
+ bundle_id TEXT,
+ checksum_version INTEGER
)
""")
@@ -694,7 +696,7 @@ class SQLiteStorage(ProvenanceStorage):
INSERT OR REPLACE INTO provenance VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
- ?, ?, ?, ?, ?, ?, ?, ?, ?
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
""", (
entry.entity_id,
@@ -736,6 +738,7 @@ class SQLiteStorage(ProvenanceStorage):
entry.revision_type,
entry.supersedes,
entry.bundle_id,
+ entry.checksum_version,
))
def retrieve(self, entity_id: str) -> Optional[ProvenanceEntry]:
@@ -1036,4 +1039,10 @@ class SQLiteStorage(ProvenanceStorage):
revision_type=row[36],
supersedes=row[37],
bundle_id=row[38],
+ # Every caller of this method uses SELECT *, so the trailing
+ # columns are always present. Guarding the length keeps a future
+ # subset query from silently shifting the version onto the wrong
+ # field, and a NULL column reads as "no version recorded", which
+ # is what a row written before the migration looks like.
+ checksum_version=row[39] if len(row) > 39 else None,
)
diff --git a/tests/provenance/test_checksum_encoding.py b/tests/provenance/test_checksum_encoding.py
new file mode 100644
index 00000000..4f37917a
--- /dev/null
+++ b/tests/provenance/test_checksum_encoding.py
@@ -0,0 +1,392 @@
+"""Checksum encoding tests (issue #2136).
+
+`compute_checksum()` used to paste the 16 hashed fields together with nothing
+between them, so two records differing only in where a field boundary falls
+produced the same hash. These tests pin the injective encoding, the per-row
+version dispatch that keeps pre-existing stores verifiable, and the end-to-end
+detection path through `verify_chain()`.
+"""
+
+import sqlite3
+
+from semantica.provenance.integrity import (
+ CHECKSUM_VERSION,
+ LEGACY_CHECKSUM_VERSION,
+ checksum_version,
+ compute_checksum,
+ compute_checksum_legacy,
+ verify_checksum,
+)
+from semantica.provenance.manager import ProvenanceManager
+from semantica.provenance.schemas import ProvenanceEntry
+
+
+class TestInjectiveEncoding:
+ def test_field_boundary_move_changes_checksum(self):
+ """`ab` + `c` must not hash like `a` + `bc`."""
+ a = {"entity_type": "ab", "activity_id": "c"}
+ b = {"entity_type": "a", "activity_id": "bc"}
+ assert compute_checksum(a) != compute_checksum(b)
+
+ def test_field_boundary_move_collides_under_legacy(self):
+ """Documents the v1 hole the fix closes, so a regression to plain
+ concatenation fails here rather than silently passing."""
+ a = {"entity_type": "ab", "activity_id": "c"}
+ b = {"entity_type": "a", "activity_id": "bc"}
+ assert compute_checksum_legacy(a) == compute_checksum_legacy(b)
+
+ def test_list_element_boundary_move_changes_checksum(self):
+ """One element containing a comma must not hash like two elements."""
+ a = {"used_entities": ["a,b"]}
+ b = {"used_entities": ["a", "b"]}
+ assert compute_checksum(a) != compute_checksum(b)
+
+ def test_list_element_boundary_collides_under_legacy(self):
+ a = {"used_entities": ["a,b"]}
+ b = {"used_entities": ["a", "b"]}
+ assert compute_checksum_legacy(a) == compute_checksum_legacy(b)
+
+ def test_list_order_is_significant(self):
+ a = {"used_entities": ["x", "y"]}
+ b = {"used_entities": ["y", "x"]}
+ assert compute_checksum(a) != compute_checksum(b)
+
+ def test_empty_list_and_absent_field_agree(self):
+ """An absent list field defaults to an empty list, so both spellings
+ hash the same — the collision to fix is between a comma inside one
+ element and two elements, not between absent and empty."""
+ a = {"used_entities": [], "entity_type": "t"}
+ b = {"entity_type": "t"}
+ assert compute_checksum(a) == compute_checksum(b)
+
+ def test_dict_and_dataclass_agree(self):
+ """v1 hashed `None` as `''` through the dict path and as `'None'`
+ through the dataclass path. v2 normalises both."""
+ entry = ProvenanceEntry(
+ entity_id="e1",
+ entity_type="entity",
+ activity_id="extraction",
+ source_document="DOI:10.1/x",
+ )
+ assert compute_checksum(entry) == compute_checksum(entry.to_dict())
+
+ def test_checksum_is_stable(self):
+ entry = {"entity_type": "entity", "activity_id": "a", "used_entities": ["u1"]}
+ assert compute_checksum(entry) == compute_checksum(dict(entry))
+
+
+class TestVersionDispatch:
+ def test_new_entry_verifies_without_a_flag(self):
+ entry = {"entity_type": "entity", "checksum_version": CHECKSUM_VERSION}
+ entry["checksum"] = compute_checksum(entry)
+ assert verify_checksum(entry) is True
+
+ def test_legacy_entry_still_verifies(self):
+ """A row written before the fix has no version and must keep verifying,
+ otherwise every existing store reports a broken chain on upgrade."""
+ entry = {"entity_type": "entity", "activity_id": "a"}
+ entry["checksum"] = compute_checksum_legacy(entry)
+ assert "checksum_version" not in entry
+ assert verify_checksum(entry) is True
+
+ def test_legacy_checksum_fails_once_stamped_v2(self):
+ entry = {"entity_type": "entity", "activity_id": "a"}
+ entry["checksum"] = compute_checksum_legacy(entry)
+ entry["checksum_version"] = CHECKSUM_VERSION
+ assert verify_checksum(entry) is False
+
+ def test_missing_version_reads_as_legacy(self):
+ assert checksum_version({}) == LEGACY_CHECKSUM_VERSION
+ assert checksum_version({"checksum_version": None}) == LEGACY_CHECKSUM_VERSION
+ assert checksum_version({"checksum_version": "2"}) == CHECKSUM_VERSION
+
+ def test_no_checksum_is_not_valid(self):
+ assert verify_checksum({"entity_type": "entity"}) is False
+
+ def test_hand_assigned_checksum_verifies_on_a_dict(self):
+ """The documented usage assigns the digest by hand, never passing
+ through the manager's stamping path. The row then carries no version,
+ so verification has to try v2 as well, or it reads a digest it just
+ produced as v1 and rejects it."""
+ entry = {"entity_type": "entity", "activity_id": "a"}
+ entry["checksum"] = compute_checksum(entry)
+ assert "checksum_version" not in entry
+ assert verify_checksum(entry) is True
+
+ def test_hand_assigned_checksum_verifies_on_a_dataclass(self):
+ entry = ProvenanceEntry(
+ entity_id="e1",
+ entity_type="entity",
+ activity_id="a",
+ agent_id="agent",
+ agent_type="human",
+ source_document="doc",
+ )
+ entry.checksum = compute_checksum(entry)
+ assert entry.checksum_version is None
+ assert verify_checksum(entry) is True
+
+ def test_computing_does_not_write_to_the_entry(self):
+ """compute_checksum() used to stamp the version onto its argument. A
+ function that returns a digest should not modify the value it read,
+ and a read-only comparison on a legacy row would relabel it."""
+ entry = {"entity_type": "entity", "activity_id": "a"}
+ first = compute_checksum(entry)
+ second = compute_checksum(entry)
+ assert first == second
+ assert entry == {"entity_type": "entity", "activity_id": "a"}
+
+ def test_an_unrecorded_version_still_verifies_a_legacy_digest(self):
+ entry = {"entity_type": "ab", "activity_id": "c"}
+ entry["checksum"] = compute_checksum_legacy(entry)
+ assert verify_checksum(entry) is True
+
+ def test_a_non_numeric_confidence_fails_verification_instead_of_raising(self):
+ """A malformed row is a "no", not an exception: verification answers a
+ question, and a ValueError escaping it turns one bad row into a crash
+ for the whole chain walk."""
+ entry = {"entity_type": "entity", "activity_id": "a", "confidence": "high"}
+ entry["checksum"] = compute_checksum(entry)
+ assert verify_checksum(entry) is True
+
+ entry["confidence"] = "low"
+ assert verify_checksum(entry) is False
+
+
+class TestStorageRoundTrip:
+ def test_checksum_version_survives_sqlite(self, tmp_path):
+ db_path = str(tmp_path / "roundtrip.db")
+ mgr = ProvenanceManager(storage_path=db_path)
+ mgr.track_entity("E1", source="doc1")
+
+ reloaded = ProvenanceManager(storage_path=db_path)
+ entry = reloaded.storage.retrieve("E1")
+ assert entry.checksum_version == CHECKSUM_VERSION
+ assert verify_checksum(entry) is True
+
+ def test_verify_chain_passes_on_a_fresh_store(self, tmp_path):
+ db_path = str(tmp_path / "clean.db")
+ mgr = ProvenanceManager(storage_path=db_path)
+ mgr.track_entity("E1", source="doc1")
+ mgr.track_entity("E2", source="doc1")
+ assert mgr.verify_chain()["valid"] is True
+
+ def test_verify_chain_passes_with_a_legacy_row_next_to_a_new_one(self, tmp_path):
+ """The upgrade path: a row written before issue #2136 keeps its v1
+ digest and no version, rows appended after it are v2, and the chain
+ across the two still verifies. Without this the migration is only
+ argued for in prose."""
+ db_path = str(tmp_path / "mixed.db")
+ mgr = ProvenanceManager(storage_path=db_path)
+ mgr.track_entity("OLD", source="doc1")
+
+ # Rewrite the first row as the pre-migration code would have left it.
+ legacy = mgr.storage.retrieve("OLD")
+ legacy_digest = compute_checksum_legacy(legacy)
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ "UPDATE provenance SET checksum = ?, checksum_version = NULL "
+ "WHERE entity_id = 'OLD'",
+ (legacy_digest,),
+ )
+ conn.commit()
+ conn.close()
+
+ # A row appended after the upgrade chains onto the legacy digest.
+ mgr.track_entity("NEW", source="doc1")
+
+ reopened = ProvenanceManager(storage_path=db_path)
+ old_entry = reopened.storage.retrieve("OLD")
+ new_entry = reopened.storage.retrieve("NEW")
+ assert old_entry.checksum_version is None
+ assert new_entry.checksum_version == CHECKSUM_VERSION
+ assert new_entry.previous_checksum == legacy_digest
+ assert reopened.verify_chain()["valid"] is True
+
+
+class TestEndToEndDetection:
+ def test_verify_chain_detects_a_char_moved_across_a_field_boundary(self, tmp_path):
+ """The attack from issue #2136: move one character from the end of
+ `entity_type` to the start of `activity_id`, leave the stored checksum
+ alone, and the concatenation is byte-identical. v2 must notice."""
+ db_path = str(tmp_path / "boundary.db")
+ mgr = ProvenanceManager(storage_path=db_path)
+ mgr.track_entity("E1", source="doc1")
+
+ conn = sqlite3.connect(db_path)
+ entity_type, activity_id = conn.execute(
+ "SELECT entity_type, activity_id FROM provenance WHERE entity_id = 'E1'"
+ ).fetchone()
+ assert entity_type and activity_id
+ conn.execute(
+ "UPDATE provenance SET entity_type = ?, activity_id = ? WHERE entity_id = 'E1'",
+ (entity_type[:-1], entity_type[-1] + activity_id),
+ )
+ conn.commit()
+ conn.close()
+
+ result = ProvenanceManager(storage_path=db_path).verify_chain()
+ assert result["valid"] is False
+ assert any(
+ link["reason"] == "checksum_mismatch" for link in result["broken_links"]
+ )
+
+ def test_verify_chain_still_detects_a_plain_field_edit(self, tmp_path):
+ db_path = str(tmp_path / "edit.db")
+ mgr = ProvenanceManager(storage_path=db_path)
+ mgr.track_entity("E1", source="doc1")
+
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ "UPDATE provenance SET source_document = 'doc2' WHERE entity_id = 'E1'"
+ )
+ conn.commit()
+ conn.close()
+
+ result = ProvenanceManager(storage_path=db_path).verify_chain()
+ assert result["valid"] is False
+
+
+# Every hashed field set to a non-default value, so a reordered, added or
+# re-tagged field changes the digest.
+_GOLDEN_ENTRY = {
+ "entity_type": "entity",
+ "activity_id": "extraction",
+ "agent_id": "agent-1",
+ "agent_type": "software",
+ "source_document": "DOI:10.1/x",
+ "timestamp": "2026-01-02T03:04:05+00:00",
+ "confidence": 0.75,
+ "parent_entity_id": "p",
+ "previous_version_id": "pv",
+ "derived_from_id": "d",
+ "used_entities": ["u1", "u2"],
+ "previous_checksum": "abc",
+ "invalidated": True,
+ "invalidated_at_time": "2026-02-01T00:00:00+00:00",
+ "invalidated_by": "rev",
+ "invalidation_reason": "retracted",
+}
+
+
+class TestGoldenDigests:
+ """Stored rows carry these digests, so they are a format, not an output:
+ changing either encoding without bumping CHECKSUM_VERSION would report
+ every existing row as tampered."""
+
+ def test_v2_digest_is_pinned(self):
+ assert compute_checksum(_GOLDEN_ENTRY) == (
+ "a39d79d05d6fbd1f2f4d4ef0f39a68076cd3ebbcadafb64c2b34d53274b24dd6"
+ )
+
+ def test_v1_digest_matches_the_pre_2136_encoder(self):
+ """The value main's compute_checksum() produced before the fix."""
+ assert compute_checksum_legacy(_GOLDEN_ENTRY) == (
+ "6af44d3f102ab3e2a5df99a3a4f2ac903e3180a7cdca6b1894d7b6ea2bd1c471"
+ )
+
+
+class TestMalformedInput:
+ def test_null_confidence_does_not_hash_like_the_default(self):
+ """v1's dataclass path hashed a NULL confidence as 'None', so
+ `SET confidence = NULL` was caught; defaulting it to 1.0 would not."""
+ base = {"entity_type": "entity", "activity_id": "a"}
+ assert compute_checksum({**base, "confidence": None}) != compute_checksum(
+ {**base, "confidence": 1.0}
+ )
+
+ def test_absent_confidence_still_hashes_like_the_default(self):
+ base = {"entity_type": "entity", "activity_id": "a"}
+ assert compute_checksum(base) == compute_checksum({**base, "confidence": 1.0})
+
+ def test_verify_chain_detects_confidence_set_to_null(self, tmp_path):
+ db_path = str(tmp_path / "null_confidence.db")
+ ProvenanceManager(storage_path=db_path).track_entity("E1", source="doc1")
+
+ conn = sqlite3.connect(db_path)
+ conn.execute("UPDATE provenance SET confidence = NULL WHERE entity_id = 'E1'")
+ conn.commit()
+ conn.close()
+
+ assert ProvenanceManager(storage_path=db_path).verify_chain()["valid"] is False
+
+ def test_a_string_used_entities_does_not_hash_like_a_list(self):
+ assert compute_checksum({"used_entities": "ab"}) != compute_checksum(
+ {"used_entities": ["a", "b"]}
+ )
+
+ def test_a_non_iterable_used_entities_fails_instead_of_raising(self):
+ entry = {"entity_type": "entity", "used_entities": ["u1"]}
+ entry["checksum"] = compute_checksum(entry)
+ entry["used_entities"] = 5
+ assert verify_checksum(entry) is False
+
+ def test_an_unversioned_row_the_v1_encoder_rejects_fails_instead_of_raising(self):
+ """The v1 encoder joins used_entities as strings; non-string items
+ would raise out of the legacy fallback."""
+ entry = {"entity_type": "entity", "used_entities": [1, 2]}
+ entry["checksum"] = "0" * 64
+ assert verify_checksum(entry) is False
+
+ def test_verify_chain_reports_a_tampered_unversioned_row_instead_of_raising(
+ self, tmp_path
+ ):
+ db_path = str(tmp_path / "int_items.db")
+ mgr = ProvenanceManager(storage_path=db_path)
+ mgr.track_entity("E1", source="doc1", used_entities=[1, 2])
+ assert mgr.verify_chain()["valid"] is True
+
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ "UPDATE provenance SET checksum_version = NULL, source_document = 'doc2' "
+ "WHERE entity_id = 'E1'"
+ )
+ conn.commit()
+ conn.close()
+
+ assert ProvenanceManager(storage_path=db_path).verify_chain()["valid"] is False
+
+ def test_an_object_without_the_fields_fails_instead_of_raising(self):
+ class Bare:
+ checksum = "0" * 64
+
+ assert verify_checksum(Bare()) is False
+
+ def test_overflowing_values_fail_instead_of_raising(self):
+ assert (
+ verify_checksum(
+ {"entity_type": "x", "checksum": "abc", "checksum_version": float("inf")}
+ )
+ is False
+ )
+ assert verify_checksum({"confidence": 10**400, "checksum": "abc"}) is False
+
+ def test_a_non_dict_mapping_is_read_by_key(self):
+ """A Mapping that is not a dict used to be read with getattr, so every
+ such entry hashed to the same digest of defaults."""
+ from types import MappingProxyType
+
+ a = MappingProxyType({"entity_type": "x", "activity_id": "y"})
+ b = MappingProxyType({"entity_type": "other", "activity_id": "z"})
+ assert compute_checksum(a) != compute_checksum(b)
+ assert compute_checksum(a) == compute_checksum(dict(a))
+
+
+class TestUnknownVersions:
+ def test_an_unknown_version_fails_instead_of_using_the_nearest_encoder(self):
+ entry = {"entity_type": "entity", "activity_id": "a"}
+ v2_digest = compute_checksum(entry)
+ v1_digest = compute_checksum_legacy(entry)
+ for version in (0, -1, CHECKSUM_VERSION + 1):
+ for digest in (v1_digest, v2_digest):
+ assert (
+ verify_checksum(
+ {**entry, "checksum": digest, "checksum_version": version}
+ )
+ is False
+ )
+
+ def test_an_explicit_v1_row_verifies_with_the_legacy_encoder(self):
+ entry = {"entity_type": "ab", "activity_id": "c", "checksum_version": 1}
+ entry["checksum"] = compute_checksum_legacy(entry)
+ assert verify_checksum(entry) is True