# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-orphaning-from-silently-corrupting-tool-call-latency-attribution-in-agent-trajectory-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-orphaning-from-silently-corrupting-tool-call-latency-attribution-in-agent-trajectory-traces.warrant.json
# Markdown SHA-256:   e0ebc3bba1fc103d6fc5a8df816ac9e70227179692d759049fa6c93ccf70659a
# Code AST SHA-256:   88fef4daacc975d749c681aa9ef94acf04fed49d418ff383ef08b158f4f1acec
# Verified Classes:   SpanContainmentViolation, Span
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class SpanContainmentViolation(RuntimeError):
    """Raised when a tool-call span escapes its parent turn span's interval."""
    pass


@dataclass
class Span:
    span_id: str
    parent_id: str | None
    start: float
    end: float | None = None
    children: list = field(default_factory=list)

    def duration(self) -> float:
        if self.end is None:
            raise SpanContainmentViolation(f"span {self.span_id} never closed")
        return self.end - self.start


def attribute_turn_latency(turn: Span, tool_spans: list[Span]) -> dict:
    """
    Conservative latency decomposition. Enforces the containment invariant:
    every tool span must be a child of `turn` and lie within its interval.
    Orphans are rejected, never re-parented.
    """
    if turn.end is None:
        raise SpanContainmentViolation(f"turn {turn.span_id} is still open")

    tool_total = 0.0
    for c in tool_spans:
        if c.parent_id != turn.span_id:
            # Do NOT re-parent. Reject and surface as a trace defect.
            raise SpanContainmentViolation(
                f"tool span {c.span_id} parent={c.parent_id} "
                f"expected={turn.span_id}; refusing to re-parent"
            )
        if c.start < turn.start or (c.end or 0) > turn.end:
            raise SpanContainmentViolation(
                f"tool span {c.span_id} [{c.start:.3f},{c.end:.3f}] "
                f"escapes turn [{turn.start:.3f},{turn.end:.3f}]"
            )
        tool_total += c.duration()

    residual = turn.duration() - tool_total
    if residual < -1e-9:
        # Negative residual means double-count or containment breach upstream.
        raise SpanContainmentViolation(
            f"negative residual {residual:.6f}s for turn {turn.span_id}: "
            f"attribution is non-conservative"
        )
    return {
        "turn_wall_s": turn.duration(),
        "tool_s": tool_total,
        "model_residual_s": residual,
    }


def simulate_orphan_race() -> None:
    t0 = time.monotonic()
    turn = Span("turn-1", parent_id="loop-1", start=t0)
    # Runtime closes the turn span at model-call return (the bug).
    turn.end = t0 + 0.120
    # Tool dispatched afterward, capturing dead parent context.
    tool = Span("tool-1", parent_id="turn-1", start=t0 + 0.130, end=t0 + 0.900)

    # Under the buggy exporter this would be re-parented to loop-1 and vanish.
    # Under the invariant it is caught here:
    attribute_turn_latency(turn, [tool])


if __name__ == "__main__":
    try:
        simulate_orphan_race()
    except SpanContainmentViolation as e:
        print(f"REJECTED (correct): {e}")
