# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-attribution-when-trace-ids-are-re-minted-at-the-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-attribution-when-trace-ids-are-re-minted-at-the-tool-boundary.warrant.json
# Markdown SHA-256:   0e1dba230114a730ec8ea85a2fc2599cc115cd174df99a480ccc5c6c48ae9f0a
# Code AST SHA-256:   574e46f64b7839de993b5ea0aa5b34dc337f5d4a841647dacb6e8de7cbd3d4ec
# Verified Classes:   CausalLinkSeveredError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class CausalLinkSeveredError(RuntimeError):
    """Raised when a span's parent does not logically contain it."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    name: str
    start_ms: float
    end_ms: float
    attributes: dict = field(default_factory=dict)


def assert_causal_link(child: Span, parent: Span, max_gap_ms: float = 50.0) -> None:
    """
    Enforce that `parent` logically produced `child`:
      - same trace
      - parent's window contains child's start (within max_gap_ms tolerance)
      - parent ends before child ends (no negative-duration edge)
    """
    if child.trace_id != parent.trace_id:
        raise CausalLinkSeveredError(
            f"trace mismatch: child={child.trace_id} parent={parent.trace_id} "
            f"span={child.span_id}"
        )
    if child.parent_span_id != parent.span_id:
        raise CausalLinkSeveredError(
            f"parent id mismatch: declared={child.parent_span_id} actual={parent.span_id}"
        )
    if child.start_ms < parent.start_ms - max_gap_ms:
        raise CausalLinkSeveredError(
            f"child {child.span_id} starts before parent {parent.span_id} "
            f"({child.start_ms} < {parent.start_ms})"
        )
    if child.end_ms < parent.start_ms:
        raise CausalLinkSeveredError(
            f"child {child.span_id} ends before parent {parent.span_id} begins"
        )
    if child.end_ms > parent.end_ms + max_gap_ms:
        raise CausalLinkSeveredError(
            f"child {child.span_id} outlives parent {parent.span_id} "
            f"({child.end_ms} > {parent.end_ms}) — severed edge"
        )


def validate_trace(spans: list[Span]) -> None:
    by_id = {s.span_id: s for s in spans}
    for s in spans:
        if s.parent_span_id is None:
            continue
        parent = by_id.get(s.parent_span_id)
        if parent is None:
            # Orphaned parent: re-minting boundary stripped the caller.
            raise CausalLinkSeveredError(
                f"orphaned span {s.span_id}: parent {s.parent_span_id} absent from trace"
            )
        assert_causal_link(s, parent)


# Degraded run from the record: tool.call hoisted to agent.step.
degraded = [
    Span("t1", "A1", None, "agent.step", 0, 4000),
    Span("t1", "B2", "A1", "llm.completion", 11, 830),
    Span("t1", "C3", "A1", "tool.call", 846, 2050),   # parent should be B2
    Span("t1", "D4", "A1", "llm.completion", 2060, 3880),  # parent should be C3
]

validate_trace(degraded)  # raises CausalLinkSeveredError on C3's window check
