# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-tool-call-span-has-silently-lost-its-parent-link-across-an-async-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-genai-tool-call-span-has-silently-lost-its-parent-link-across-an-async-agent-handoff.warrant.json
# Markdown SHA-256:   82faf0d87fd9aa6d5d26b4d6197d8db23d0c1f0e1e0b1d815db74098344912cc
# Code AST SHA-256:   f2eccc1569ac2c4ad56a52e5b73dfbb0824ea3eb369fc7f81b1d5768ce83dbd3
# Verified Classes:   StaleParentSpanError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleParentSpanError(RuntimeError):
    """Raised when a tool-call span's parent closed before the child started,
    indicating a serialized-context handoff that outlived its originating turn."""
    pass


def validate_tool_span_parentage(
    child: dict,
    parent: dict,
    turn_id_attribute: str = "gen_ai.conversation.turn",
    max_gap_seconds: float = 30.0,
) -> None:
    """Enforce the parent-freshness invariant before a gen_ai execute_tool span is exported.

    child/parent are span dicts with keys: span_id, parent_span_id, start_time,
    end_time (None if open), and attributes (dict).
    """
    if child.get("parent_span_id") != parent.get("span_id"):
        raise StaleParentSpanError(
            f"child {child['span_id']} does not reference parent {parent['span_id']}"
        )

    parent_end = parent.get("end_time")
    if parent_end is None:
        return  # parent still open: fresh by construction

    gap = child["start_time"] - parent_end
    if gap <= max_gap_seconds:
        return  # within turn-latency bound: acceptable

    child_turn = child["attributes"].get(turn_id_attribute)
    parent_turn = parent["attributes"].get(turn_id_attribute)
    if child_turn != parent_turn:
        raise StaleParentSpanError(
            f"tool span {child['span_id']} started {gap:.1f}s after parent "
            f"{parent['span_id']} closed, and turn ids disagree "
            f"(child={child_turn!r}, parent={parent_turn!r}): "
            f"serialized context outlived its originating turn"
        )

    raise StaleParentSpanError(
        f"tool span {child['span_id']} started {gap:.1f}s after parent "
        f"{parent['span_id']} closed despite matching turn id; "
        f"re-parent to live turn or emit as SpanLink"
    )
