# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-span-attribute-divergence-from-silently-corrupting-agent-invocation-telemetry-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-span-attribute-divergence-from-silently-corrupting-agent-invocation-telemetry-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   802b490d5de3604700027fea0e18b9f808401360eb9e8a54e6d24bb584e2dc28
# Code AST SHA-256:   48ea8718fda2c837588efc604f3b8ed5f9a8bab7a5609f63c82bd6a52ea69fed
# Verified Classes:   GenAiSpanInvariantError, GenAiSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAiSpanInvariantError(RuntimeError):
    """Raised when a GenAI span tree violates single-owner usage or identity invariants."""
    pass


@dataclass
class GenAiSpan:
    span_id: str
    operation_name: str          # gen_ai.operation.name
    agent_id: Optional[str]      # gen_ai.agent.id, None if unresolved
    input_tokens: Optional[int]  # gen_ai.usage.input_tokens
    output_tokens: Optional[int]
    parent_id: Optional[str] = None
    children: list = field(default_factory=list)


CONSUMING_OPS = {"invoke_agent", "chat", "execute_tool"}


def _has_usage(span: GenAiSpan) -> bool:
    return span.input_tokens is not None or span.output_tokens is not None


def assert_single_owner_usage(span: GenAiSpan) -> None:
    """A span that restates a child's usage corrupts aggregation. Enclosing spans
    must carry no usage, or carry only usage their own operation consumed."""
    if not _has_usage(span):
        return
    for child in span.children:
        if child.operation_name in CONSUMING_OPS and _has_usage(child):
            raise GenAiSpanInvariantError(
                f"span {span.span_id} ({span.operation_name}) restates usage "
                f"already owned by child {child.span_id} ({child.operation_name}); "
                f"token attribution is not single-owner"
            )


def assert_identity_resolvable(span: GenAiSpan, resource_agent_id: Optional[str]) -> None:
    """Every span must resolve gen_ai.agent.id locally or from a resource attribute
    fixed at creation. Ancestor-walk inference is forbidden because a sub-agent may
    declare a different id inside the parent's subtree."""
    if span.agent_id is None and resource_agent_id is None:
        raise GenAiSpanInvariantError(
            f"span {span.span_id} has no gen_ai.agent.id and no resource-level "
            f"agent identity; identity would be inferred by ancestor walk, "
            f"which is ambiguous across handoff boundaries"
        )
    for child in span.children:
        assert_identity_resolvable(child, resource_agent_id)


def validate_trace(root: GenAiSpan, resource_agent_id: Optional[str]) -> None:
    def walk(s: GenAiSpan) -> None:
        assert_single_owner_usage(s)
        for c in s.children:
            walk(c)
    walk(root)
    assert_identity_resolvable(root, resource_agent_id)


# --- trace that triggers the guardrail -------------------------------------
tool_a = GenAiSpan("s2", "execute_tool", "planner-v2", 1840, 0)
tool_b = GenAiSpan("s3", "execute_tool", "planner-v2", 1840, 0)
root = GenAiSpan(
    "s1", "invoke_agent", "planner-v2", 1840, 212,
    children=[tool_a, tool_b],
)

try:
    validate_trace(root, resource_agent_id="planner-v2")
except GenAiSpanInvariantError as e:
    # expected: root restates usage owned by its tool children
    print(f"quarantined trace: {e}")
