# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-context-provenance-graphs-before-an-audit-replay-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-context-provenance-graphs-before-an-audit-replay-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   3f0d88d4d9257e9eda55d5604ca29e12376090d39c5dd0f6c2347c3a96e9e70b
# Code AST SHA-256:   6d547549d7aaa1567dec97d0f86462b95dab42ed5e897677e40ad92115de801a
# Verified Classes:   ProvenanceResolutionError, ProvenanceEdge, DecisionRecord, MemoryStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceResolutionError(RuntimeError):
    """Raised when a decision's provenance closure cannot be resolved to
    snapshot-consistent content at replay time."""
    pass


@dataclass(frozen=True)
class ProvenanceEdge:
    node_id: str
    content_hash: str
    read_rank: int


@dataclass
class DecisionRecord:
    decision_id: str
    committed_at: str
    store_snapshot: str
    closure: list[ProvenanceEdge] = field(default_factory=list)


class MemoryStore:
    def __init__(self) -> None:
        # node_id -> current content hash (mutated by distiller/sweeper)
        self._live: dict[str, str] = {}
        # (node_id, content_hash) -> tombstone flag
        self._tombstones: set[tuple[str, str]] = set()

    def write(self, node_id: str, content: str) -> str:
        h = hashlib.sha256(content.encode()).hexdigest()
        self._live[node_id] = h
        return h

    def distill(self, node_id: str, new_content: str) -> str:
        # Reuses the UUID; content hash changes. Live pointer now diverges
        # from any provenance edge that recorded the pre-distillation hash.
        return self.write(node_id, new_content)

    def sweep(self, node_id: str) -> None:
        h = self._live.pop(node_id, None)
        if h is not None:
            self._tombstones.add((node_id, h))


def snapshot_closure(store: MemoryStore, reads: list[tuple[str, int]]) -> list[ProvenanceEdge]:
    edges = []
    for node_id, rank in reads:
        h = store._live.get(node_id)
        if h is None:
            raise ProvenanceResolutionError(
                f"cannot snapshot read of {node_id}: not present in live store"
            )
        edges.append(ProvenanceEdge(node_id=node_id, content_hash=h, read_rank=rank))
    return edges


def replay(record: DecisionRecord, store: MemoryStore) -> list[str]:
    resolved = []
    for edge in record.closure:
        live_hash = store._live.get(edge.node_id)
        if live_hash is None:
            if (edge.node_id, edge.content_hash) in store._tombstones:
                # Tombstoned: content is gone but the edge was real. Fail closed.
                raise ProvenanceResolutionError(
                    f"decision {record.decision_id}: edge {edge.node_id} "
                    f"({edge.content_hash[:8]}) tombstoned; replay would drop a "
                    f"live-at-decision-time node"
                )
            raise ProvenanceResolutionError(
                f"decision {record.decision_id}: dangling edge {edge.node_id}; "
                f"refusing partial closure replay"
            )
        if live_hash != edge.content_hash:
            raise ProvenanceResolutionError(
                f"decision {record.decision_id}: content drift on {edge.node_id}; "
                f"snapshot hash {edge.content_hash[:8]} != live {live_hash[:8]}; "
                f"store mutated after commit at {record.committed_at}"
            )
        resolved.append(edge.node_id)
    return resolved


# Demonstration of the boundary failure.
store = MemoryStore()
store.write("ep-1", "customer reports billing loop")
store.write("ep-2", "refund already issued on 2025-05-01")

decision = DecisionRecord(
    decision_id="d-001",
    committed_at="2025-06-01T10:00:00Z",
    store_snapshot="lsn-4412",
    closure=snapshot_closure(store, [("ep-1", 1), ("ep-2", 2)]),
)

# Distiller rewrites ep-2 under the same UUID after the decision.
store.distill("ep-2", "refund issued, date unknown (distilled)")

try:
    replay(decision, store)
except ProvenanceResolutionError as e:
    # This is the correct, fail-closed behavior. Lazy reconstruction that
    # resolved by node_id alone would have silently replayed the new content.
    print(f"audit refused: {e}")
