# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-divergence-in-multi-agent-speculative-branch-replay-the-read-set-drift-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-divergence-in-multi-agent-speculative-branch-replay-the-read-set-drift-invariant.warrant.json
# Markdown SHA-256:   e6e5859d487ad6da941534048b1a8e240dc037c8a81c4ec9262ec92e0bdefab2
# Code AST SHA-256:   e6ce6fb9c9c97ddcb6b87ac5c35f28fd8a8388ea9f07b6bcad8f086a63265ba6
# Verified Classes:   ReadSetDriftError, BranchTrace
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ReadSetDriftError(RuntimeError):
    """Raised when replay reconstructs a branch whose read-set differs from
    execution-time read-set, even if outputs match (coincidental reproduction)."""
    pass


@dataclass(frozen=True)
class BranchTrace:
    branch_id: str
    read_fingerprint: str   # hash of (context, resolved tool versions, peer msgs)
    write_fingerprint: str  # hash of emitted output tokens


def fingerprint(read_context: dict) -> str:
    # read_context MUST include resolved version ids for stateful tool results
    canonical = repr(sorted(read_context.items()))
    return hashlib.sha256(canonical.encode()).hexdigest()


def verify_replay(recorded: BranchTrace, replayed: BranchTrace) -> str:
    read_match = recorded.read_fingerprint == replayed.read_fingerprint
    write_match = recorded.write_fingerprint == replayed.write_fingerprint

    if read_match and write_match:
        return "causally_faithful"
    if read_match and not write_match:
        return "generation_nondeterminism"
    if not read_match and write_match:
        # The silent failure: outputs agree, causal path does not.
        raise ReadSetDriftError(
            f"branch {recorded.branch_id}: coincidental reproduction — "
            f"outputs match but read-set drifted "
            f"(exec={recorded.read_fingerprint[:12]}, "
            f"replay={replayed.read_fingerprint[:12]})"
        )
    raise ReadSetDriftError(
        f"branch {recorded.branch_id}: invalid replay on both axes; "
        f"rebuild from pinned raw inputs before attributing cause"
    )


def audit_incident(recorded_traces: list[BranchTrace],
                   replayed_traces: list[BranchTrace]) -> dict:
    by_id = {t.branch_id: t for t in replayed_traces}
    results = {}
    for rec in recorded_traces:
        rep = by_id.get(rec.branch_id)
        if rep is None:
            raise ReadSetDriftError(
                f"branch {rec.branch_id}: missing from replay; "
                f"causal graph incomplete, refuse to explain"
            )
        results[rec.branch_id] = verify_replay(rec, rep)
    return results
