# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-genai-span-tree-as-forensically-invalid-rather-than-merely-lossy.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-replayed-genai-span-tree-as-forensically-invalid-rather-than-merely-lossy.warrant.json
# Markdown SHA-256:   533b35bd5d92927ca4a6d36492929c706de2a9fe773955472c02e65c152954f4
# Code AST SHA-256:   20628253ba3dd8db5f331b4ec6e5ada2001b754e0e8bec97665bbf7aac0fc246
# Verified Classes:   ReplayOrderingIndeterminate, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


class ReplayOrderingIndeterminate(RuntimeError):
    """Raised when causal order cannot be certified under the observed clock-skew envelope."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    start_ns: int
    end_ns: int
    tool_call_id: str | None = None
    consumed_tool_call_id: str | None = None


def certify_causal_order(spans: Iterable[Span], skew_envelope_ns: int) -> list[str]:
    """Return span_ids in certified causal order, or raise if order is skew-dependent."""
    spans = list(spans)
    by_id = {s.span_id: s for s in spans}

    # Guard 1: no dangling parents (would force silent re-parenting).
    for s in spans:
        if s.parent_span_id is not None and s.parent_span_id not in by_id:
            raise ReplayOrderingIndeterminate(
                f"span {s.span_id} references missing parent {s.parent_span_id}; "
                "re-parenting would fabricate a transition"
            )

    # Guard 2: explicit linkage edges must exist wherever a tool result is consumed.
    tool_producers = {s.tool_call_id: s for s in spans if s.tool_call_id}
    for s in spans:
        if s.consumed_tool_call_id is not None:
            producer = tool_producers.get(s.consumed_tool_call_id)
            if producer is None:
                raise ReplayOrderingIndeterminate(
                    f"span {s.span_id} consumes tool call {s.consumed_tool_call_id} "
                    "with no producing span; result provenance is unrecoverable"
                )
            # Causal gap must exceed skew envelope, else order is timestamp-fragile.
            gap = s.start_ns - producer.end_ns
            if gap < skew_envelope_ns:
                raise ReplayOrderingIndeterminate(
                    f"causal gap {gap}ns between {producer.span_id} and {s.span_id} "
                    f"is within skew envelope {skew_envelope_ns}ns; ordering is indeterminate"
                )

    # Topological order over parent + explicit-link edges.
    edges: dict[str, set[str]] = {s.span_id: set() for s in spans}
    for s in spans:
        if s.parent_span_id is not None:
            edges[s.parent_span_id].add(s.span_id)
        if s.consumed_tool_call_id is not None:
            producer = tool_producers[s.consumed_tool_call_id]
            edges[producer.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 = sorted([sid for sid, d in indeg.items() if d == 0])
    order: list[str] = []
    while ready:
        sid = ready.pop(0)
        order.append(sid)
        for d in sorted(edges[sid]):
            indeg[d] -= 1
            if indeg[d] == 0:
                ready.append(d)
    if len(order) != len(spans):
        raise ReplayOrderingIndeterminate(
            "causal graph contains a cycle; no valid replay order exists"
        )
    return order


def replay_turn(spans: Iterable[Span], skew_envelope_ns: int) -> list[str]:
    order = certify_causal_order(spans, skew_envelope_ns)
    return order


if __name__ == "__main__":
    turn = [
        Span("t", None, 0, 1000),
        Span("m1", "t", 100, 300),
        Span("tool", "t", 310, 500, tool_call_id="c1"),
        Span("m2", "t", 505, 700, consumed_tool_call_id="c1"),
    ]
    print(replay_turn(turn, skew_envelope_ns=50))  # ok

    skewed = [
        Span("t", None, 0, 1000),
        Span("m1", "t", 100, 300),
        Span("tool", "t", 310, 500, tool_call_id="c1"),
        Span("m2", "t", 320, 700, consumed_tool_call_id="c1"),  # gap 20 < 50
    ]
    try:
        replay_turn(skewed, skew_envelope_ns=50)
    except ReplayOrderingIndeterminate as e:
        print("refused:", e)
