# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-replayed-multi-agent-conversation-as-non-replayable-the-wall-clock-causality-break-in-forensic-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-replayed-multi-agent-conversation-as-non-replayable-the-wall-clock-causality-break-in-forensic-replay.warrant.json
# Markdown SHA-256:   7f3627c586298e24fec029fae8fedfc14b7ae4f9e95b8090285938759ea38201
# Code AST SHA-256:   bc8412ef44f562d890bd38c28ada0429074873144eb6d86b6046e2adf3c9a1f2
# Verified Classes:   CausalAttributionError, Observation, CausalEdge, ReplayLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CausalAttributionError(RuntimeError):
    """Raised when a replay attempts to attribute a decision to an upstream
    message through a tool observation whose value diverged from the recorded
    value. This is the wall-clock causality break: the replay silently rewrote
    the happens-before graph by reading a different world than the original."""
    pass


@dataclass
class Observation:
    tool: str
    args: dict[str, Any]
    value: Any
    read_set_hash: str
    t_orig: float


@dataclass
class CausalEdge:
    src: str          # upstream message / event id
    dst: str          # downstream decision id
    via_tool: str | None
    faithful: bool = True


@dataclass
class ReplayLedger:
    recorded: dict[str, Observation] = field(default_factory=dict)
    edges: list[CausalEdge] = field(default_factory=list)

    def record(self, call_id: str, obs: Observation) -> None:
        self.recorded[call_id] = obs

    def replay_call(self, call_id: str, replayed_value: Any,
                    current_read_set_hash: str) -> Observation:
        orig = self.recorded[call_id]
        if replayed_value != orig.value:
            # A write intersected the read-set between original and replay.
            if current_read_set_hash != orig.read_set_hash:
                # Genuine world change: sever every edge through this call.
                for edge in self.edges:
                    if edge.via_tool == call_id:
                        edge.faithful = False
                return orig  # return recorded value; do NOT adopt replayed
            # Same read-set, different value => tool is non-deterministic.
            raise CausalAttributionError(
                f"tool {orig.tool} returned {replayed_value!r} on replay but "
                f"{orig.value!r} originally with identical read-set hash "
                f"{current_read_set_hash!r}; replay cannot vouch for causality"
            )
        return orig

    def attribute(self, decision_id: str) -> list[str]:
        """Return upstream event ids that may be cited as causes of a decision.
        Raises if any consumed observation was non-faithful and no faithful
        alternative exists, forcing the caller to report an evidence gap."""
        causes, gaps = [], []
        for edge in self.edges:
            if edge.dst != decision_id:
                continue
            if edge.faithful:
                causes.append(edge.src)
            else:
                gaps.append(edge.src)
        if gaps and not causes:
            raise CausalAttributionError(
                f"decision {decision_id!r} has no faithful causal edges; "
                f"all {len(gaps)} upstream candidates consumed divergent "
                f"observations. Report as evidence gap, not as attribution."
            )
        return causes
