# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-span-attribute-provenance-when-a-tool-call-s-token-accounting-crosses-an-mcp-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-genai-span-attribute-provenance-when-a-tool-call-s-token-accounting-crosses-an-mcp-transport-boundary.warrant.json
# Markdown SHA-256:   d2cebc2d1ddbe6b1587a1b2728972d07fce919b9e23e597a05f522431c4283cb
# Code AST SHA-256:   a56a8fae1e6d26f9ea853220e649d1fe748eea3aa0554b13b0a9eca9ca3dcd57
# Verified Classes:   UsageProvenanceError, GenAISpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

from dataclasses import dataclass


class UsageProvenanceError(RuntimeError):
    """Raised when a GenAI span carries token usage it cannot attribute."""


@dataclass
class GenAISpan:
    name: str
    attributes: dict
    trace_id: str | None
    events: list


def close_execute_tool_span(
    span: GenAISpan,
    remote_usage: dict | None,
    remote_trace_id: str | None,
    client_estimate: int | None,
) -> GenAISpan:
    """
    Close an execute_tool span that crossed an MCP/A2A boundary.

    Invariant: usage attributes are authored only by the token authority,
    and only when the generation span is joinable by trace_id.
    """
    if remote_usage is not None:
        if remote_trace_id is None:
            # Remote counted tokens but its spans are orphaned; we cannot
            # attribute the count to a generation span. Do not copy it.
            span.events.append(
                {"name": "gen_ai.usage.unavailable",
                 "reason": "no_trace_context"}
            )
            return span
        span.attributes["gen_ai.usage.input_tokens"] = remote_usage["input_tokens"]
        span.attributes["gen_ai.usage.output_tokens"] = remote_usage["output_tokens"]
        span.attributes["gen_ai.usage.source"] = "remote_joined"
        span.attributes["gen_ai.usage.generation_trace_id"] = remote_trace_id
        return span

    if client_estimate is not None:
        # Client tokenizer over tool.call.arguments is NOT the generation
        # population. Refuse to author usage from it.
        raise UsageProvenanceError(
            f"span {span.name!r}: client-side token estimate "
            f"({client_estimate}) cannot be attributed to a remote "
            f"generation; omit usage and record unavailability instead"
        )

    span.events.append(
        {"name": "gen_ai.usage.unavailable", "reason": "remote_authority"}
    )
    return span
