# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-an-agent-span-fail-the-genai-semantic-convention-when-tool-call-telemetry-crosses-the-parent-child-boundary-mid-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-an-agent-span-fail-the-genai-semantic-convention-when-tool-call-telemetry-crosses-the-parent-child-boundary-mid-turn.warrant.json
# Markdown SHA-256:   1624ebca6bd3a351d92ad910ad54234b64396e9a16ec5adf2187a63694af1573
# Code AST SHA-256:   8d2b8c910c365aa9b07d69f6c21d8a4881515566182d607be8cd29bc1983827e
# Verified Classes:   GenAIUsageInvariantError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAIUsageInvariantError(RuntimeError):
    """Raised when a span's gen_ai.usage.* attributes violate the per-operation invariant."""

    def __init__(self, span_name: str, reason: str) -> None:
        super().__init__(f"span={span_name!r}: {reason}")
        self.span_name = span_name
        self.reason = reason


def validate_agent_span(span: dict) -> None:
    """
    Enforce: a span carrying gen_ai.operation.name == 'invoke_agent'
    must NOT carry gen_ai.usage.* unless the turn had exactly one model invocation.
    """
    attrs = span.get("attributes", {})
    op = attrs.get("gen_ai.operation.name")

    carries_usage = any(
        k.startswith("gen_ai.usage.") for k in attrs
    )
    child_model_spans = [
        c for c in span.get("children", [])
        if c.get("attributes", {}).get("gen_ai.operation.name")
        in {"chat", "text_completion", "generate_content"}
    ]

    if op == "invoke_agent" and carries_usage and len(child_model_spans) > 1:
        raise GenAIUsageInvariantError(
            span.get("name", "<unnamed>"),
            f"agent span carries aggregate gen_ai.usage.* across "
            f"{len(child_model_spans)} child model spans; move usage to leaf spans",
        )

    if op == "invoke_agent" and carries_usage and len(child_model_spans) == 1:
        # Redundant but harmless; warn by returning without raising.
        return

    for child in span.get("children", []):
        validate_agent_span(child)


def validate_tool_call_id(model_span: dict, tool_span: dict) -> None:
    """
    Enforce: tool span's gen_ai.tool.call.id must equal the id the model issued.
    """
    issued = {
        tc["id"]
        for tc in model_span.get("attributes", {}).get("gen_ai.response.tool_calls", [])
    }
    used = tool_span.get("attributes", {}).get("gen_ai.tool.call.id")
    if used not in issued:
        raise GenAIUsageInvariantError(
            tool_span.get("name", "<unnamed>"),
            f"gen_ai.tool.call.id={used!r} not present in issuing model span ids={sorted(issued)}",
        )
