# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-genai-span-stream-whose-tool-call-events-were-sampled-out-mid-trajectory.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-genai-span-stream-whose-tool-call-events-were-sampled-out-mid-trajectory.warrant.json
# Markdown SHA-256:   b8b7776c461525e41c2172b3a1a78e35354948972c3a74fd5b6fd2e8daed51b3
# Code AST SHA-256:   332b80fd08dc403eebeeb0c35384175b80e4b0daa4f96743eab7a9c28fe711b8
# Verified Classes:   ReplayDivergence, Span, Trace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ReplayDivergence(RuntimeError):
    """Raised when a GenAI event stream cannot deterministically reproduce a session."""
    pass


@dataclass
class Span:
    kind: str                      # "gen_ai.chat" | "gen_ai.tool.call"
    tool_call_id: Optional[str] = None
    tool_calls: list = field(default_factory=list)   # ids named by an assistant message
    has_result: bool = False
    start_time: float = 0.0


@dataclass
class Trace:
    spans: list
    closure_verified: bool = False   # set only by an exporter that guarantees no mid-trajectory sampling


def replay(trace: Trace) -> list:
    # Index tool-call spans by id, preserving only those that actually carry a result.
    tool_spans = {
        s.tool_call_id: s
        for s in trace.spans
        if s.kind == "gen_ai.tool.call" and s.tool_call_id is not None
    }

    # Causal order: emit tool calls by their requesting chat span, not by timestamp.
    ordered = sorted(trace.spans, key=lambda s: (s.kind != "gen_ai.chat", s.start_time))

    transcript = []
    for span in ordered:
        if span.kind != "gen_ai.chat":
            continue
        transcript.append({"role": "assistant", "tool_calls": list(span.tool_calls)})
        for call_id in span.tool_calls:
            match = tool_spans.get(call_id)
            if match is None or not match.has_result:
                if not trace.closure_verified:
                    # Indeterminate: either a real hallucination or a sampled-out span.
                    # We cannot tell, so we refuse rather than synthesize a result.
                    raise ReplayDivergence(
                        f"tool_call.id={call_id!r} named by chat span has no matching "
                        f"tool-call result in a non-closure-verified trace; "
                        f"deterministic replay is undefined for this session"
                    )
                # Closure verified: the model genuinely emitted a call that was never
                # dispatched. Synthetic not-found is the faithful reproduction.
                transcript.append(
                    {"role": "tool", "tool_call_id": call_id, "content": '{"error":"tool_not_found"}'}
                )
            else:
                transcript.append({"role": "tool", "tool_call_id": call_id, "content": "<result>"})
    return transcript


def replay_session(trace: Trace) -> list:
    if not trace.closure_verified:
        # Downgrade posture: allow shape-only replay, but never claim determinism.
        try:
            return replay(trace)
        except ReplayDivergence as exc:
            raise ReplayDivergence(
                f"session marked non-reproducible; use trace-only replay. cause: {exc}"
            ) from exc
    return replay(trace)
