# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-a-tool-s-non-deterministic-output-is-captured-inside-a-memoized-sub-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-a-tool-s-non-deterministic-output-is-captured-inside-a-memoized-sub-trajectory.warrant.json
# Markdown SHA-256:   1bb5b696c3cbee5b76069ee49d35f27b45a5c21f7f7406cf3084b48576a1e13b
# Code AST SHA-256:   79555b565b39e3750eac586cb5db2b3b11351cc98a961b617e6abc7ef7710448
# Verified Classes:   ReplayDivergenceError, AmbientLeakError, ToolRecord, TrajectoryRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ReplayDivergenceError(RuntimeError):
    """Raised when a replay trajectory diverges from its recorded causal chain."""


class AmbientLeakError(ReplayDivergenceError):
    """Raised when a tool argument is sourced from ambient state at replay time."""


@dataclass
class ToolRecord:
    tool_name: str
    args: dict[str, Any]
    result: Any
    ambient_inputs: dict[str, Any] = field(default_factory=dict)


@dataclass
class TrajectoryRecord:
    steps: list[ToolRecord]
    replay_opaque_steps: set[int] = field(default_factory=set)


def replay_trajectory(record: TrajectoryRecord, tool_registry: dict) -> list[Any]:
    """
    Replay a recorded trajectory. Enforces the three-part invariant:
      1. key sufficiency  (memoization key covers all output-affecting args)
      2. key necessity    (no ambient state leaks into args at replay time)
      3. full cache hit   (every step must hit; a miss is a defect, not a fallback)
    """
    results: list[Any] = []
    for idx, step in enumerate(record.steps):
        if idx in record.replay_opaque_steps:
            # Explicitly marked non-replayable; surface, do not silently re-execute.
            results.append(step.result)
            continue

        tool = tool_registry.get(step.tool_name)
        if tool is None:
            raise ReplayDivergenceError(
                f"step {idx}: tool {step.tool_name!r} absent from registry"
            )

        # Condition 2: no ambient leak. The recorded args must be self-contained.
        leaked = set(step.ambient_inputs) & set(step.args)
        if leaked:
            raise AmbientLeakError(
                f"step {idx}: ambient inputs {sorted(leaked)} leaked into args; "
                f"replay would re-sample non-deterministic state"
            )

        # Condition 1 + 3: replay must be a pure function of the record.
        # In a real harness this consults the frozen output store; a miss is fatal.
        cache_key = (step.tool_name, tuple(sorted(step.args.items())))
        cached = tool.lookup_frozen(cache_key)
        if cached is _MISS:
            raise ReplayDivergenceError(
                f"step {idx}: cache miss for {step.tool_name!r} with args "
                f"{step.args!r} — replay coverage < 1.0, trajectory not forensically sound"
            )
        if cached != step.result:
            raise ReplayDivergenceError(
                f"step {idx}: recorded result mismatch for {step.tool_name!r}"
            )
        results.append(cached)
    return results


_MISS = object()
