# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-attribution-when-opentelemetry-genai-spans-are-parented-across-an-async-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-attribution-when-opentelemetry-genai-spans-are-parented-across-an-async-tool-boundary.warrant.json
# Markdown SHA-256:   9eac3d8cc3aa4dcc524bd6fc90ad9ed56df779bdf570af237c8be78bb969a57f
# Code AST SHA-256:   99975f515ba014fadd85c1a6df00378e8a369f02e5b93ecb8578169c188c7b76
# Verified Classes:   GenAIAttributionError, SpanRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class GenAIAttributionError(RuntimeError):
    """Raised when a GenAI tool span violates the parentage/rollup invariant."""
    pass


@dataclass
class SpanRecord:
    span_id: str
    parent_span_id: Optional[str]
    trace_id: str
    name: str
    run_id: Optional[str]
    input_tokens: int = 0
    output_tokens: int = 0


def validate_tool_attribution(agent: SpanRecord, tool: SpanRecord) -> None:
    """
    Enforce: tool span must be a structural child of the agent span in the
    same trace, OR carry a matching run_id for reconciliation. Otherwise the
    token rollup and trace-tree replay are silently wrong.
    """
    if tool.name != "gen_ai.execute_tool":
        raise GenAIAttributionError(
            f"expected tool span, got {tool.name!r}"
        )

    structurally_linked = (
        tool.trace_id == agent.trace_id
        and tool.parent_span_id == agent.span_id
    )
    reconcilable = (
        tool.run_id is not None
        and agent.run_id is not None
        and tool.run_id == agent.run_id
    )

    if not structurally_linked and not reconcilable:
        raise GenAIAttributionError(
            "tool span orphaned: trace_id="
            f"{tool.trace_id} parent={tool.parent_span_id} "
            f"agent={agent.span_id} (trace {agent.trace_id}); "
            f"run_id tool={tool.run_id} agent={agent.run_id}. "
            "Token rollup and replay will be incorrect."
        )

    if structurally_linked and tool.trace_id != agent.trace_id:
        # Defensive: cannot both be child and cross-trace.
        raise GenAIAttributionError(
            "inconsistent span record: parent set but trace_id differs"
        )


def rollup_tokens(agent: SpanRecord, tools: list[SpanRecord]) -> int:
    """Sum agent + verified tool tokens; refuse to roll up unverified tools."""
    total = agent.input_tokens + agent.output_tokens
    for t in tools:
        validate_tool_attribution(agent, t)  # raises on orphaning
        total += t.input_tokens + t.output_tokens
    return total
