# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-non-monotonic-span-timestamps-before-deterministic-replay-of-an-agentic-session-from-opentelemetry-genai-logs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-non-monotonic-span-timestamps-before-deterministic-replay-of-an-agentic-session-from-opentelemetry-genai-logs.warrant.json
# Markdown SHA-256:   5e4f6a3b098912a5fdea104586dd6d2ecc41c0258996fcf94f5d3c4dcb2363f0
# Code AST SHA-256:   e876e6e9d9911f013bb9498e29a12eb5769d7b3179650405715ec134e2396bd4
# Verified Classes:   ReplayOrderViolation, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class ReplayOrderViolation(RuntimeError):
    """Raised when the span tree cannot be linearized into a valid causal order."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    start_ns: int
    end_ns: int
    kind: str  # "agent" | "chat" | "tool" | "memory"
    memory_key: str | None = None
    memory_op: str | None = None  # "read" | "write"
    links: tuple[str, ...] = field(default_factory=tuple)
    tool_call_id: str | None = None
    tool_result_for: str | None = None


def linearize(spans: Iterable[Span]) -> list[Span]:
    """Return spans in a causal order, or raise if the order is ambiguous.

    Ordering rules, in priority:
      1. parent -> child (only when containment holds)
      2. explicit SpanLink edges
      3. tool_call_id -> tool_result_for pairing
      4. memory write -> read on the same key (write must precede read)
    Timestamps are used ONLY as a tiebreak among spans with no causal edge
    between them. A timestamp tiebreak across a causal edge is a violation.
    """
    spans = list(spans)
    by_id = {s.span_id: s for s in spans}
    edges: dict[str, set[str]] = {s.span_id: set() for s in spans}

    for s in spans:
        if s.parent_id and s.parent_id in by_id:
            p = by_id[s.parent_id]
            if p.start_ns <= s.start_ns and s.end_ns <= p.end_ns:
                edges[p.span_id].add(s.span_id)
        for link in s.links:
            if link in by_id:
                edges[link].add(s.span_id)
        if s.tool_result_for and s.tool_result_for in by_id:
            edges[s.tool_result_for].add(s.span_id)

    writes = {s.memory_key: s for s in spans if s.memory_op == "write" and s.memory_key}
    for s in spans:
        if s.memory_op == "read" and s.memory_key in writes:
            w = writes[s.memory_key]
            if w.span_id != s.span_id:
                edges[w.span_id].add(s.span_id)

    indeg = {sid: 0 for sid in edges}
    for src, dsts in edges.items():
        for d in dsts:
            indeg[d] += 1

    ready = [sid for sid, d in indeg.items() if d == 0]
    ready.sort(key=lambda sid: (by_id[sid].start_ns, sid))
    order: list[Span] = []
    while ready:
        sid = ready.pop(0)
        order.append(by_id[sid])
        for d in edges[sid]:
            indeg[d] -= 1
            if indeg[d] == 0:
                ready.append(d)
        ready.sort(key=lambda x: (by_id[x].start_ns, x))

    if len(order) != len(spans):
        unresolved = [by_id[sid] for sid, d in indeg.items() if d > 0]
        raise ReplayOrderViolation(
            "cycle or unresolved causal edge among spans: "
            + ", ".join(s.span_id for s in unresolved)
        )

    # Verify no causal edge is reversed by the timestamp tiebreak.
    pos = {s.span_id: i for i, s in enumerate(order)}
    for src, dsts in edges.items():
        for d in dsts:
            if pos[src] >= pos[d]:
                raise ReplayOrderViolation(
                    f"causal edge {src}->{d} reversed by linearization"
                )
    return order


def replay(step_fn, spans: Iterable[Span]) -> None:
    try:
        order = linearize(spans)
    except ReplayOrderViolation as exc:
        raise ReplayOrderViolation(f"refusing to replay: {exc}") from exc
    for span in order:
        step_fn(span)
