# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-replay-because-a-tool-call-graph-is-causally-ambiguous.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-replay-because-a-tool-call-graph-is-causally-ambiguous.warrant.json
# Markdown SHA-256:   8725ae85fd251c2614952d858bb92770c6c78492ea2c1f552f740cc7b01f5e34
# Code AST SHA-256:   5344c740ae49e34dd1e03b2242007623ffa4ca49c97bddda822efee905a48cb5
# Verified Classes:   CausalAmbiguityError, Node, Edge, ExecutionGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalAmbiguityError(RuntimeError):
    """Raised when a replay divergence cannot be explained by declared inputs."""


@dataclass
class Node:
    node_id: str
    declared_inputs: frozenset
    output: bytes
    stochastic: bool = False
    resources_touched: frozenset = field(default_factory=frozenset)


@dataclass
class Edge:
    src: str
    dst: str


@dataclass
class ExecutionGraph:
    nodes: dict
    edges: list

    def incoming_outputs(self, node_id: str) -> frozenset:
        srcs = {e.src for e in self.edges if e.dst == node_id}
        return frozenset(self.nodes[s].output for s in srcs)

    def assert_input_closure(self) -> None:
        for nid, n in self.nodes.items():
            available = self.incoming_outputs(nid) | n.declared_inputs
            if not n.declared_inputs <= available:
                raise CausalAmbiguityError(
                    f"node {nid} reads undeclared state: "
                    f"{n.declared_inputs - available!r}"
                )

    def assert_effect_serialization(self) -> None:
        for a_id, a in self.nodes.items():
            for b_id, b in self.nodes.items():
                if a_id >= b_id:
                    continue
                shared = a.resources_touched & b.resources_touched
                if not shared:
                    continue
                connected = any(
                    (e.src == a_id and e.dst == b_id)
                    or (e.src == b_id and e.dst == a_id)
                    for e in self.edges
                )
                if not connected:
                    raise CausalAmbiguityError(
                        f"nodes {a_id} and {b_id} share {shared!r} "
                        f"without a serialization edge"
                    )


def attribute_failure(
    graph: ExecutionGraph,
    replay_outputs: dict,
    attribution_path: set,
) -> str:
    """Return blamed node_id, or raise if replay is causally ambiguous."""
    graph.assert_input_closure()
    graph.assert_effect_serialization()

    for nid, replayed in replay_outputs.items():
        original = graph.nodes[nid]
        if replayed == original.output:
            continue
        if nid not in attribution_path:
            continue
        if original.stochastic:
            # genuine non-determinism: caller must widen confidence
            continue
        # identical declared inputs, deterministic node, on the blame path,
        # yet diverged -> an undeclared dependency leaked into this node.
        raise CausalAmbiguityError(
            f"unexplained divergence at deterministic node {nid} on "
            f"attribution path; graph is not replayable, refusing to attribute"
        )

    return max(attribution_path, key=lambda n: len(graph.nodes[n].resources_touched))
