# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-an-opentelemetry-genai-agent-span-from-a-tool-call-span-when-a-tool-invocation-is-itself-implemented-as-an-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-an-opentelemetry-genai-agent-span-from-a-tool-call-span-when-a-tool-invocation-is-itself-implemented-as-an-agent.warrant.json
# Markdown SHA-256:   05f27aee2e61079afc097d4831ba05ea2f03faeb993d258c09773b639062a937
# Code AST SHA-256:   a1f52e7688fadec5abd65a8acc0da6dcc0e0865d2213088ba92a0503949cf886
# Verified Classes:   AgentToolBoundaryError, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AgentToolBoundaryError(RuntimeError):
    """Raised when an agent span is emitted as a tool delegation without an explicit tool boundary."""


@dataclass
class GenAISpan:
    operation_name: str
    parent_operation_name: str | None
    agent_id: str | None = None
    tool_name: str | None = None
    tool_call_id: str | None = None
    input_tokens: int = 0
    output_tokens: int = 0


def validate_delegation_boundary(span: GenAISpan, enclosing_tool_span: GenAISpan | None) -> None:
    """Enforce that an agent-implemented tool invocation carries an explicit execute_tool boundary.

    The OpenTelemetry GenAI conventions do not distinguish an agent span emitted
    on behalf of a tool from a top-level agent span. If we cannot prove the
    boundary, we must fail closed rather than emit a span that downstream
    tool-call counters and token rollups will silently misclassify.
    """
    if span.operation_name != "invoke_agent":
        return

    if span.parent_operation_name not in ("invoke_agent", "chat"):
        return

    if enclosing_tool_span is None:
        raise AgentToolBoundaryError(
            f"agent span {span.agent_id!r} has agent/chat parent "
            f"{span.parent_operation_name!r} but no enclosing execute_tool span; "
            "tool-call counters will undercount and token rollups will double-count"
        )

    if enclosing_tool_span.operation_name != "execute_tool":
        raise AgentToolBoundaryError(
            f"enclosing span has operation {enclosing_tool_span.operation_name!r}, "
            "expected 'execute_tool'"
        )

    if enclosing_tool_span.tool_call_id is None:
        raise AgentToolBoundaryError(
            f"execute_tool span for tool {enclosing_tool_span.tool_name!r} "
            "is missing gen_ai.tool.call.id; delegation is uncorrelatable"
        )

    if span.tool_call_id != enclosing_tool_span.tool_call_id:
        raise AgentToolBoundaryError(
            f"agent span tool_call_id {span.tool_call_id!r} does not match "
            f"enclosing execute_tool {enclosing_tool_span.tool_call_id!r}"
        )
