# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-execute-a-tool-call-during-trace-replay-and-when-must-it-refuse.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-execute-a-tool-call-during-trace-replay-and-when-must-it-refuse.warrant.json
# Markdown SHA-256:   8883615c9c60b483628055afe6e266013d68dc3829ed9ba0c929718ed2a48737
# Code AST SHA-256:   05d8d5d212372d0dccd9fa9ff15022bac072dbdf973f1fedd2f2bacaa918aae5
# Verified Classes:   ReplayDivergenceError, Idempotency, RecordedCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayed tool call cannot be causally grounded."""


class Idempotency(Enum):
    IDEMPOTENT = "idempotent"
    NON_IDEMPOTENT = "non_idempotent"
    NON_DETERMINISTIC = "non_deterministic"


@dataclass(frozen=True)
class RecordedCall:
    step: int
    tool: str
    idempotency: Idempotency
    payload_complete: bool
    state_version: str | None
    output_hash: str


def replay_call(call: RecordedCall, live_invoke, pinned_state: str | None) -> str:
    """
    Decide whether a recorded tool call may be re-executed during forensic replay.
    Returns the output hash to use downstream. Raises if replay cannot stay grounded.
    """
    if call.idempotency is Idempotency.NON_IDEMPOTENT:
        if not call.payload_complete:
            raise ReplayDivergenceError(
                f"step {call.step}: non-idempotent tool {call.tool!r} has incomplete "
                f"recorded payload; replay cannot continue past this step"
            )
        return call.output_hash  # trust recorded observation, never re-fire

    if call.idempotency is Idempotency.NON_DETERMINISTIC:
        return call.output_hash  # recorded observation is the only ground truth

    # idempotent path
    if call.state_version is None or pinned_state != call.state_version:
        # cannot pin external state to incident-time version
        return call.output_hash

    fresh = live_invoke(call.tool)
    fresh_hash = hashlib.sha256(repr(fresh).encode()).hexdigest()
    if fresh_hash != call.output_hash:
        raise ReplayDivergenceError(
            f"step {call.step}: tool {call.tool!r} replayed to {fresh_hash[:12]} "
            f"but trace recorded {call.output_hash[:12]}; aborting segment"
        )
    return fresh_hash
