# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-diverges-mid-trace-causal-replay-failure-under-non-deterministic-sampling-and-the-counterfactual-logging-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-diverges-mid-trace-causal-replay-failure-under-non-deterministic-sampling-and-the-counterfactual-logging-invariant.warrant.json
# Markdown SHA-256:   9f4119d4f27c2d3728bc895c7c9af346e45b1f0e017d6ab8670f499338917073
# Code AST SHA-256:   b5c384ae81f888fb475bb18fa2f756bf7c3cc8fcc575f215e2f903ed34378c61
# Verified Classes:   UnpinnedNonDeterministicNode, ReplayDivergence, TraceNode
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class UnpinnedNonDeterministicNode(RuntimeError):
    """Raised when causal replay would cross a node that is neither pinned
    nor attested-deterministic. Crossing it would silently produce a
    counterfactual branch mislabeled as a faithful replay."""
    pass


class ReplayDivergence(RuntimeError):
    """Raised when a pinned or attested-deterministic node produces output
    that does not byte-match the recorded output. Indicates trace corruption
    or a model/registry version change under the pin."""
    pass


@dataclass
class TraceNode:
    step: int
    kind: str                      # "llm" | "tool" | "retrieval"
    recorded_output: Any
    pinned: bool = False           # recorded output injected on replay
    deterministic_attested: bool = False
    attestation_hash: str | None = None
    registry_hash: str | None = None
    reexecute_fn: Any = None       # callable for deterministic re-exec


def _hash(obj: Any) -> str:
    return hashlib.sha256(repr(obj).encode()).hexdigest()


def causal_replay(nodes: list[TraceNode], mode: str = "causal") -> list[dict]:
    """Replay a trace under the pinned-output invariant.

    mode="causal": every node must be pinned or attested-deterministic;
                   unpinned nodes raise UnpinnedNonDeterministicNode.
    mode="counterfactual": unpinned nodes are re-executed and the branch
                   point is logged as a counterfactual event.
    """
    if mode not in ("causal", "counterfactual"):
        raise ValueError(f"unknown replay mode: {mode}")

    events: list[dict] = []
    for node in nodes:
        if node.pinned:
            events.append({"step": node.step, "mode": "pinned",
                           "output": node.recorded_output, "faithful": True})
            continue

        if node.deterministic_attested:
            if node.attestation_hash != node.registry_hash:
                raise ReplayDivergence(
                    f"step {node.step}: attestation hash {node.attestation_hash} "
                    f"!= registry hash {node.registry_hash}"
                )
            actual = node.reexecute_fn()
            if _hash(actual) != _hash(node.recorded_output):
                raise ReplayDivergence(
                    f"step {node.step}: deterministic re-exec diverged from "
                    f"recorded output"
                )
            events.append({"step": node.step, "mode": "attested",
                           "output": actual, "faithful": True})
            continue

        # Unpinned, non-attested non-deterministic node.
        if mode == "causal":
            raise UnpinnedNonDeterministicNode(
                f"step {node.step} ({node.kind}) is unpinned and not "
                f"attested-deterministic; causal replay would silently "
                f"diverge. Pin the output or switch to counterfactual mode."
            )

        # Counterfactual mode: re-execute, log the branch explicitly.
        alt = node.reexecute_fn()
        events.append({
            "step": node.step,
            "mode": "counterfactual",
            "recorded": node.recorded_output,
            "alternative": alt,
            "faithful": False,
            "branch_point": True,
        })

    return events


def assert_faithful(events: list[dict]) -> None:
    """Downstream audit guard: refuse to emit a causal claim if any event
    is a counterfactual branch."""
    for e in events:
        if not e.get("faithful", False):
            raise UnpinnedNonDeterministicNode(
                f"step {e['step']} is a counterfactual branch; "
                f"cannot be cited as causal evidence"
            )
