# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-nondeterministic-trace-and-the-causal-chain-diverges-at-a-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-nondeterministic-trace-and-the-causal-chain-diverges-at-a-tool-boundary.warrant.json
# Markdown SHA-256:   a1b17eff5b72b7134e8914e159d32f400898837467986b542125d63602e93c91
# Code AST SHA-256:   63f066f62b39b4ae9e3879fb81b05b5702e5e973f4384dd5d34579aa565d8f0a
# Verified Classes:   CausalDivergenceError, UnpinnedPrimitiveError, Node, ReplayResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CausalDivergenceError(RuntimeError):
    """Raised when a causal replay diverges from the recorded trace at a node
    whose identity is content-addressed. Downstream counterfactuals are invalid."""


class UnpinnedPrimitiveError(RuntimeError):
    """Raised when a replay attempts to re-execute a nondeterministic primitive
    (sampling, mutable tool read, clock) that was not pinned in the trace."""


@dataclass(frozen=True)
class Node:
    step: int
    kind: str                      # "model" | "tool" | "env"
    prompt: str
    model_config: dict
    tool_name: str | None
    tool_input: Any
    tool_output: Any

    def identity(self) -> str:
        # Content-addressed identity: NOT the ordinal step.
        payload = json.dumps(
            {
                "kind": self.kind,
                "prompt": self.prompt,
                "model_config": self.model_config,
                "tool_name": self.tool_name,
                "tool_input": self.tool_input,
                "tool_output": self.tool_output,
            },
            sort_keys=True,
            default=str,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class ReplayResult:
    node_id: str
    diverged: bool
    detail: str
    conditional: bool = False


def replay_node(
    recorded: Node,
    live_model_fn,
    live_tool_fn,
    pure_tools: set[str],
    pinned_seed: int | None,
) -> ReplayResult:
    """Replay one node. Inject recorded tool outputs for impure tools; re-execute
    only pure tools. Raise on any divergence that invalidates downstream causality."""
    if recorded.kind == "model":
        if pinned_seed is None:
            raise UnpinnedPrimitiveError(
                f"step {recorded.step}: model node has no pinned seed; "
                f"replay would branch, not reconstruct. Register as new branch."
            )
        live_out = live_model_fn(recorded.prompt, recorded.model_config, pinned_seed)
        live = Node(
            step=recorded.step,
            kind="model",
            prompt=recorded.prompt,
            model_config=recorded.model_config,
            tool_name=None,
            tool_input=None,
            tool_output=live_out,
        )
    elif recorded.kind == "tool":
        if recorded.tool_name in pure_tools:
            live_out = live_tool_fn(recorded.tool_name, recorded.tool_input)
        else:
            # Impure tool: MUST inject recorded output. Re-fetching mutates the
            # causal graph silently — this is the exact failure being guarded.
            live_out = recorded.tool_output
        live = Node(
            step=recorded.step,
            kind="tool",
            prompt=recorded.prompt,
            model_config=recorded.model_config,
            tool_name=recorded.tool_name,
            tool_input=recorded.tool_input,
            tool_output=live_out,
        )
    else:
        live = recorded  # env nodes are snapshots, replayed verbatim

    if live.identity() != recorded.identity():
        raise CausalDivergenceError(
            f"step {recorded.step} ({recorded.kind} {recorded.tool_name or ''}): "
            f"content-addressed identity diverged. "
            f"recorded={recorded.identity()[:12]} live={live.identity()[:12]}. "
            f"All counterfactuals downstream of this node are conditional on a "
            f"different causal graph and must not be reported as reconstructions."
        )
    return ReplayResult(node_id=live.identity(), diverged=False, detail="match")


def run_causal_replay(
    trace: list[Node],
    live_model_fn,
    live_tool_fn,
    pure_tools: set[str],
    pinned_seed: int | None,
) -> list[ReplayResult]:
    results: list[ReplayResult] = []
    for node in trace:
        try:
            results.append(
                replay_node(node, live_model_fn, live_tool_fn, pure_tools, pinned_seed)
            )
        except CausalDivergenceError as e:
            # First divergence halts the chain: nothing downstream is a
            # reconstruction of the original run.
            results.append(
                ReplayResult(
                    node_id=node.identity(),
                    diverged=True,
                    detail=str(e),
                    conditional=True,
                )
            )
            break
    return results
