# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-replay-a-multi-agent-trace-when-the-original-run-consumed-non-idempotent-tool-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-replay-a-multi-agent-trace-when-the-original-run-consumed-non-idempotent-tool-side-effects.warrant.json
# Markdown SHA-256:   f4115e0741729bbcdb65d271b0eeba70276ce45c0dbfcbf27d5253df25325c92
# Code AST SHA-256:   4e8006e3df8657757bb83915a972289c0ef12ce6d45b398745e15a095efe9b68
# Verified Classes:   SideEffectClass, ReplayContaminationError, RecordedCall, ReplayLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SideEffectClass(Enum):
    READ = "read"
    WRITE = "write"
    CHARGE = "charge"
    NOTIFY = "notify"
    DELETE = "delete"
    DISPATCH = "dispatch"


EFFECTFUL = {
    SideEffectClass.WRITE,
    SideEffectClass.CHARGE,
    SideEffectClass.NOTIFY,
    SideEffectClass.DELETE,
    SideEffectClass.DISPATCH,
}


class ReplayContaminationError(RuntimeError):
    """Raised when a replay would re-apply a non-idempotent side effect."""


@dataclass
class RecordedCall:
    trace_id: str
    call_index: int
    tool_name: str
    side_effect_class: Optional[SideEffectClass]
    recorded_response: Optional[bytes]


@dataclass
class ReplayLedger:
    applied: set = field(default_factory=set)

    def key(self, trace_id: str, call_index: int) -> tuple:
        return (trace_id, call_index)

    def is_applied(self, trace_id: str, call_index: int) -> bool:
        return self.key(trace_id, call_index) in self.applied

    def mark_applied(self, trace_id: str, call_index: int) -> None:
        self.applied.add(self.key(trace_id, call_index))


def replay_call(call: RecordedCall, ledger: ReplayLedger, live_executor) -> bytes:
    if call.side_effect_class is None:
        raise ReplayContaminationError(
            f"tool {call.tool_name!r} at call_index {call.call_index} has no "
            f"declared side-effect class; trace {call.trace_id} is not safely replayable"
        )

    key_applied = ledger.is_applied(call.trace_id, call.call_index)

    if call.side_effect_class in EFFECTFUL:
        if key_applied:
            if call.recorded_response is None:
                raise ReplayContaminationError(
                    f"effectful call {call.tool_name!r} at call_index "
                    f"{call.call_index} was applied but has no recorded response; "
                    f"cannot satisfy replay from ledger"
                )
            return call.recorded_response
        # Not yet applied in this trace: refuse to execute live.
        raise ReplayContaminationError(
            f"refusing to execute effectful call {call.tool_name!r} "
            f"(class={call.side_effect_class.value}) at call_index "
            f"{call.call_index} of trace {call.trace_id}: no ledger entry, "
            f"live execution would contaminate the trace under forensic replay"
        )

    # READ-class: safe to serve recorded response, or re-execute if absent.
    if call.recorded_response is not None:
        return call.recorded_response
    return live_executor(call)


def replay_trace(calls, ledger: ReplayLedger, live_executor):
    results = []
    for call in calls:
        results.append(replay_call(call, ledger, live_executor))
    return results
