# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-otel-genai-replay-when-non-deterministic-tool-spans-collapse-the-causal-timeline.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-otel-genai-replay-when-non-deterministic-tool-spans-collapse-the-causal-timeline.warrant.json
# Markdown SHA-256:   562104e1cb056936a1793878735cffa899db7af7fdf63c9b4abe671fdcc26738
# Code AST SHA-256:   cc7a20479156639dd518e60597b9f70f4cf6420b087525ea75ccc4b0d9676b42
# Verified Classes:   ReplayCausalityError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ReplayCausalityError(RuntimeError):
    """Raised when a replay step depends on a tool output whose causal
    availability is inferred from wall-clock ordering rather than an
    explicit link, making the reconstructed pre-state untrustworthy."""


@dataclass
class Span:
    name: str
    start_ms: float
    end_ms: float
    tool_call_id: Optional[str] = None      # set on consumer spans that link a tool
    tool_result_ref: Optional[str] = None   # set on consumer spans carrying result
    truncated: Optional[bool] = None


def assert_replay_step_is_causal(consumer: Span, producers: list[Span]) -> None:
    """Verify that every tool output the consumer depends on is causally
    available via an explicit link, not merely via timestamp ordering."""
    if consumer.tool_call_id is None and consumer.tool_result_ref is None:
        # No explicit link: any producer that overlaps or precedes by clock
        # is an inferred dependency. Refuse to trust the replay.
        overlapping = [
            p for p in producers
            if p.end_ms > consumer.start_ms and p.start_ms < consumer.end_ms
        ]
        if overlapping:
            raise ReplayCausalityError(
                f"consumer span {consumer.name!r} at [{consumer.start_ms},"
                f"{consumer.end_ms}] overlaps producer(s) "
                f"{[p.name for p in overlapping]} with no explicit tool link; "
                "causal availability is inferred from wall-clock and replay "
                "pre-state may omit the tool result."
            )
        return

    # Explicit link present: confirm the linked producer actually exists and
    # that truncation of the result was recorded on the consumer.
    linked = [p for p in producers if p.tool_call_id == consumer.tool_call_id]
    if not linked:
        raise ReplayCausalityError(
            f"consumer {consumer.name!r} references tool_call_id="
            f"{consumer.tool_call_id!r} but no producer span carries it; "
            "replay cannot resolve the tool output."
        )
    if consumer.truncated is None:
        raise ReplayCausalityError(
            f"consumer {consumer.name!r} consumed tool output without recording "
            "truncation state; reconstructed context may differ from model input."
        )


def replay_step(consumer: Span, producers: list[Span]) -> str:
    assert_replay_step_is_causal(consumer, producers)
    return f"replayed {consumer.name} with verified causal pre-state"
