# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-link-breakage-when-a-parent-agent-s-reasoning-span-closes-before-its-subagent-s-tool-call-spans-are-attri.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-span-link-breakage-when-a-parent-agent-s-reasoning-span-closes-before-its-subagent-s-tool-call-spans-are-attri.warrant.json
# Markdown SHA-256:   eea90f2705d4b3a499daa9915478ba1e90f94a979dcf4c34a3cda437c15b1522
# Code AST SHA-256:   b31b9df5bdb95de4124a297a152b5b3d870ea582a18a5dc253c2c42319ae97e2
# Verified Classes:   CausalLinkBroken, Span, CausalScopeGuard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class CausalLinkBroken(RuntimeError):
    """Raised when a parent reasoning span closes while dispatched children remain unattributed."""
    pass


@dataclass
class Span:
    span_id: str
    parent_span_id: str | None
    start_time: float
    end_time: float | None = None
    dispatched_children: int = 0
    completed_children: int = 0


class CausalScopeGuard:
    """Enforces: a parent span may not close until its causal frontier is drained."""

    def __init__(self, drain_timeout_s: float = 60.0):
        self.drain_timeout_s = drain_timeout_s

    def dispatch_child(self, parent: Span) -> None:
        parent.dispatched_children += 1

    def complete_child(self, parent: Span) -> None:
        parent.completed_children += 1

    def close_parent(self, parent: Span) -> None:
        deadline = time.monotonic() + self.drain_timeout_s
        while parent.completed_children < parent.dispatched_children:
            if time.monotonic() > deadline:
                outstanding = parent.dispatched_children - parent.completed_children
                raise CausalLinkBroken(
                    f"parent span {parent.span_id} closing with {outstanding} "
                    f"unattributed child span(s); causal frontier not drained "
                    f"within {self.drain_timeout_s}s"
                )
            time.sleep(0.01)
        parent.end_time = time.monotonic()

    def assert_linkable(self, child: Span, store_has_parent: bool) -> None:
        if child.parent_span_id is not None and not store_has_parent:
            raise CausalLinkBroken(
                f"child span {child.span_id} references parent "
                f"{child.parent_span_id} that is absent from the trace store; "
                f"distinguish early-parent-close from propagation loss before remediating"
            )
