# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-span-parentage-when-an-mcp-tool-call-outlives-the-a2a-task-that-spawned-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-span-parentage-when-an-mcp-tool-call-outlives-the-a2a-task-that-spawned-it.warrant.json
# Markdown SHA-256:   77e14eb14bc872328110d3ab1f8dc58d2b74c536bad718e9c8e9c688dedd16b1
# Code AST SHA-256:   c699dd4969ad1826617ae1adc6a5950b3e0ee5a057c864689c3f17a5fb347fb5
# Verified Classes:   TraceParentageError, Span, TraceCollector
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TraceParentageError(RuntimeError):
    """Raised when a span's causal edge violates the parentage invariant."""


@dataclass
class Span:
    span_id: str
    trace_id: str
    parent_span_id: str | None
    start_time: float
    end_time: float | None = None
    status: str = "open"
    open_children: int = 0
    relation: str = "child"  # "child" (ordered) or "async_child" (link only)


class TraceCollector:
    def __init__(self, idle_ttl_s: float, hard_cap_s: float):
        self.idle_ttl_s = idle_ttl_s
        self.hard_cap_s = hard_cap_s
        self.spans: dict[str, Span] = {}

    def open_child(self, parent_id: str, child: Span) -> None:
        parent = self.spans.get(parent_id)
        if parent is None:
            raise TraceParentageError(f"unknown parent {parent_id}")
        if parent.end_time is not None and child.relation == "child":
            # Ordered child dispatched after parent terminal transition.
            raise TraceParentageError(
                f"child {child.span_id} dispatched after parent {parent_id} closed"
            )
        parent.open_children += 1
        self.spans[child.span_id] = child

    def close_child(self, child_id: str) -> None:
        child = self.spans[child_id]
        child.end_time = time.time()
        child.status = "ok"
        parent = self.spans.get(child.parent_span_id or "")
        if parent is not None:
            parent.open_children -= 1
            if parent.open_children == 0 and parent.end_time is not None:
                parent.status = "completed"

    def close_parent(self, parent_id: str) -> None:
        parent = self.spans[parent_id]
        parent.end_time = time.time()
        if parent.open_children > 0:
            parent.status = "draining"  # NOT completed; deferred eviction applies
        else:
            parent.status = "completed"

    def evict_if_idle(self, trace_id: str, now: float) -> bool:
        roots = [s for s in self.spans.values()
                 if s.trace_id == trace_id and s.parent_span_id is None]
        if not roots:
            return False
        root = roots[0]
        if root.end_time is None:
            return False
        idle = now - root.end_time
        if root.status == "draining":
            if idle > self.hard_cap_s:
                # Hard cap reached: close with orphans, downgrade children to links.
                for s in self.spans.values():
                    if s.parent_span_id == root.span_id and s.end_time is None:
                        s.relation = "async_child"
                root.status = "completed_with_orphans"
                return True
            return False  # never evict a draining trace on idle TTL
        return idle > self.idle_ttl_s
