# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-deterministic-replay-of-a-poisoned-trace-the-non-idempotent-tool-call-fork-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-deterministic-replay-of-a-poisoned-trace-the-non-idempotent-tool-call-fork-invariant.warrant.json
# Markdown SHA-256:   36e6d2bb7e0e2342dd4787a068a4ea94bdf8c9b4fa1c348b7b35cb12f3dbeb91
# Code AST SHA-256:   7f54a83c8e51f1040b4f236c6aa1ead8e189cace58543a1b8c75a4331cf009ba
# Verified Classes:   UnreplayableTrace, RecordedStep, ReplayHarness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class UnreplayableTrace(RuntimeError):
    """Raised when a trace step cannot be served from the recorded log.

    Continuing past this point would fork the replay into a live execution,
    producing fabricated forensic evidence and potentially re-issuing
    side-effecting tool calls against live state.
    """


@dataclass(frozen=True)
class RecordedStep:
    step_index: int
    tool_name: str
    args: dict[str, Any]
    result: Optional[dict[str, Any]]
    side_effecting: bool


def canonical_args_hash(args: dict[str, Any]) -> str:
    blob = json.dumps(args, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


class ReplayHarness:
    def __init__(self, recorded: list[RecordedStep]):
        self._by_key: dict[tuple[int, str, str], RecordedStep] = {
            (s.step_index, s.tool_name, canonical_args_hash(s.args)): s
            for s in recorded
        }

    def serve(self, step_index: int, tool_name: str, args: dict[str, Any]) -> dict[str, Any]:
        key = (step_index, tool_name, canonical_args_hash(args))
        step = self._by_key.get(key)
        if step is None:
            # No live fallback. Ever.
            raise UnreplayableTrace(
                f"step {step_index} tool={tool_name!r} args_hash="
                f"{canonical_args_hash(args)[:12]} has no logged observation; "
                f"refusing to fork replay into live execution"
            )
        if step.result is None:
            raise UnreplayableTrace(
                f"step {step_index} tool={tool_name!r} logged without a result "
                f"(original call may have been interrupted); replay cannot "
                f"reconstruct the agent's observation"
            )
        if step.side_effecting:
            # Side-effecting calls are answered from the log, never re-issued.
            # We do not rely on backend idempotency guards; the harness boundary
            # is the only suppression point.
            pass
        return step.result


def replay_trace(
    recorded: list[RecordedStep],
    agent_step_fn,
    max_steps: int,
) -> list[dict[str, Any]]:
    harness = ReplayHarness(recorded)
    observations: list[dict[str, Any]] = []
    for i in range(max_steps):
        requested = agent_step_fn(i, observations)  # model chooses a tool call
        if requested is None:
            break
        tool_name, args = requested["tool"], requested["args"]
        try:
            result = harness.serve(i, tool_name, args)
        except UnreplayableTrace:
            raise
        observations.append({"step": i, "tool": tool_name, "result": result})
    return observations
