# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-non-replayable-multi-agent-trace-when-otel-genai-spans-lose-causal-ordering-across-batched-tool-call-fan-out.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-non-replayable-multi-agent-trace-when-otel-genai-spans-lose-causal-ordering-across-batched-tool-call-fan-out.warrant.json
# Markdown SHA-256:   a7d9886bba571de8eaf34e77fe6b14316107c524be2e92d893b72692ec5004ee
# Code AST SHA-256:   beb5b72e8ec5deacfd700f8eb542a508014a6346704248981375cb5cc46d87b2
# Verified Classes:   NonReplayableTraceError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class NonReplayableTraceError(RuntimeError):
    """Raised when a reconstructed trace cannot be replayed deterministically."""
    pass

@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    start_time: float
    end_time: float
    attributes: dict

def audit_replayability(spans: list[Span]) -> None:
    """
    Enforce the read-after-write invariant for parent attributes consumed by
    descendants. Refuse replay when timestamp order diverges from causal order.
    """
    by_id = {s.span_id: s for s in spans}
    children: dict[str, list[Span]] = {}
    for s in spans:
        if s.parent_span_id:
            children.setdefault(s.parent_span_id, []).append(s)

    for parent in spans:
        kids = children.get(parent.span_id, [])
        if not kids:
            continue
        # Parent attributes that descendants read (tool-call fan-out payload).
        consumed = "gen_ai.response.tool_calls" in parent.attributes
        if not consumed:
            continue
        earliest_child_start = min(k.start_time for k in kids)
        # Divergence: parent's end_time postdates a child's start_time,
        # so a timestamp-sorted replay evaluates the child before the
        # parent's tool_calls attribute is materialized.
        if parent.end_time > earliest_child_start:
            raise NonReplayableTraceError(
                f"span {parent.span_id}: end_time={parent.end_time} > "
                f"earliest child start={earliest_child_start}; "
                f"tool_calls attribute not materialized before child "
                f"evaluation under timestamp-sorted replay"
            )

def replay(trace: list[Span]) -> dict:
    audit_replayability(trace)
    # Safe path: bind parent attributes by parent_span_id resolution,
    # never by timestamp sort.
    by_id = {s.span_id: s for s in trace}
    result = {}
    for s in trace:
        if s.parent_span_id:
            parent = by_id[s.parent_span_id]
            result[s.span_id] = parent.attributes.get("gen_ai.response.tool_calls")
    return result
