# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-genai-agent-span-because-tool-call-child-spans-outlive-the-parent-s-context-deadline.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-genai-agent-span-because-tool-call-child-spans-outlive-the-parent-s-context-deadline.warrant.json
# Markdown SHA-256:   11981a631fd96278d5b34a607e682a0c675669474a3496b5a264857fea01fbbc
# Code AST SHA-256:   3969947d0e11ee7ec3576481ba31bbc05e1e6b4ab7715fec0ff4aa918630ad50
# Verified Classes:   UnjoinedSpanError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class UnjoinedSpanError(RuntimeError):
    """Raised when a parent agent span would close before its tool children."""
    pass


@dataclass
class Span:
    name: str
    start: float
    end: Optional[float] = None
    status: str = "UNSET"
    children: list = field(default_factory=list)
    cancelled: bool = False

    def end_span(self, status: str = "OK") -> None:
        self.end = time.monotonic()
        self.status = status


def close_agent_span(parent: Span, grace_window_s: float = 0.5) -> None:
    """Close a gen_ai.agent span only after all gen_ai.tool children have ended.

    Enforces the invariant: parent.end >= max(child.end for child in children).
    If a non-cooperative child outlives the grace window, the parent must be
    re-parented rather than closed with a temporally inverted tree.
    """
    deadline = time.monotonic() + grace_window_s
    while time.monotonic() < deadline:
        if all(c.end is not None for c in parent.children):
            break
        time.sleep(0.01)

    unjoined = [c for c in parent.children if c.end is None]
    if unjoined:
        names = ", ".join(c.name for c in unjoined)
        # Do NOT call parent.end_span(); that would emit an inverted trace.
        raise UnjoinedSpanError(
            f"agent span {parent.name!r} cannot close: "
            f"tool children still open after {grace_window_s}s grace: {names}. "
            f"Re-parent to adoption span instead of ending parent."
        )

    latest_child_end = max(c.end for c in parent.children) if parent.children else parent.start
    parent.end = max(time.monotonic(), latest_child_end)
    parent.status = "ERROR" if any(c.status == "ERROR" for c in parent.children) else "OK"


def demo() -> None:
    parent = Span("gen_ai.agent:planner", start=time.monotonic())
    fast = Span("gen_ai.tool:retrieval", start=time.monotonic())
    slow = Span("gen_ai.tool:web_fetch", start=time.monotonic())
    parent.children = [fast, slow]

    fast.end_span("OK")
    # slow is non-cooperative: never ends within grace window
    try:
        close_agent_span(parent, grace_window_s=0.1)
    except UnjoinedSpanError as exc:
        print(f"correctly refused to close parent: {exc}")
        # adoption path: re-parent slow to a synthetic cancelled-agent span
        slow.cancelled = True


if __name__ == "__main__":
    demo()
