# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-attribution-when-otel-genai-spans-cross-an-agent-handoff-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-attribution-when-otel-genai-spans-cross-an-agent-handoff-boundary.warrant.json
# Markdown SHA-256:   aae715d3a1cdc5b39a89a3f5e3a86f674f4805e1e1307c5d653c939a00ab16e1
# Code AST SHA-256:   5bef0cab08c14863a5b17834d5f2bd5e05a0c57597c55f106e497f36f6c14daf
# Verified Classes:   HandoffAttributionError, HandoffEnvelope, ChildRootSpan
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class HandoffAttributionError(RuntimeError):
    """Raised when a cross-instance agent handoff would emit spans whose
    GenAI attributes cannot be joined to the delegating agent's accounting."""
    pass


@dataclass
class HandoffEnvelope:
    traceparent: str                      # W3C trace context: trace_id-span_id-flags
    agent_name: Optional[str] = None      # gen_ai.agent.name of the DELEGATING agent
    tool_call_id: Optional[str] = None    # gen_ai.tool.call.id of the delegating tool span
    upstream_input_tokens: int = 0        # gen_ai.usage.input_tokens already spent upstream
    upstream_output_tokens: int = 0       # gen_ai.usage.output_tokens already spent upstream


@dataclass
class ChildRootSpan:
    agent_name: str
    parent_span_id: str
    attributes: dict = field(default_factory=dict)


REQUIRED_ATTRS = ("gen_ai.agent.name", "gen_ai.tool.call.id")


def build_child_root_span(env: HandoffEnvelope, child_agent_name: str) -> ChildRootSpan:
    """Construct the child instance's root invoke_agent span.

    Invariant: the child root span MUST carry the delegating agent's identity
    and tool-call correlation id as ATTRIBUTES, not merely as a parent link,
    so that per-task token accounting and tool-call verification survive
    span sampling and delegation retries.
    """
    if not env.traceparent:
        raise HandoffAttributionError(
            "handoff envelope missing traceparent; cannot establish even topology"
        )

    missing = [
        name
        for name, val in (
            ("gen_ai.agent.name", env.agent_name),
            ("gen_ai.tool.call.id", env.tool_call_id),
        )
        if not val
    ]
    if missing:
        raise HandoffAttributionError(
            f"handoff from parent agent to '{child_agent_name}' is context-only; "
            f"missing attribute-bearing identity {missing}. Token totals and tool-call "
            f"attribution will be non-reconstructible from attributes alone."
        )

    # traceparent format: 00-<trace_id>-<parent_span_id>-<flags>
    parts = env.traceparent.split("-")
    if len(parts) != 4:
        raise HandoffAttributionError(
            f"malformed traceparent '{env.traceparent}': expected 4 dash-delimited fields"
        )
    parent_span_id = parts[2]

    child = ChildRootSpan(agent_name=child_agent_name, parent_span_id=parent_span_id)
    child.attributes = {
        "gen_ai.operation.name": "invoke_agent",
        "gen_ai.agent.name": child_agent_name,
        # propagated identity — the point of the whole guardrail
        "gen_ai.agent.parent.name": env.agent_name,
        "gen_ai.tool.call.id": env.tool_call_id,
        "gen_ai.tool.call.parent_id": env.tool_call_id,
        # upstream baseline so child spend is reported as incremental
        "gen_ai.usage.input_tokens.upstream": env.upstream_input_tokens,
        "gen_ai.usage.output_tokens.upstream": env.upstream_output_tokens,
    }

    for required in REQUIRED_ATTRS:
        if required not in child.attributes:
            raise HandoffAttributionError(
                f"child root span for '{child_agent_name}' missing required attribute {required}"
            )

    return child


def verify_task_token_reconstructible(spans: list[ChildRootSpan]) -> int:
    """Sum incremental token spend across a delegated task tree.

    Raises if any span lacks the propagated baseline needed to attribute
    its spend to the originating task rather than only to its emitting agent.
    """
    total = 0
    for span in spans:
        if "gen_ai.tool.call.parent_id" not in span.attributes:
            raise HandoffAttributionError(
                f"agent '{span.agent_name}' emitted a root span without a propagated "
                f"tool-call parent id; per-task token sum is unsound"
            )
        total += span.attributes.get("gen_ai.usage.input_tokens.upstream", 0)
    return total
