# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-is-re-parented-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-opentelemetry-genai-token-accounting-when-a-tool-call-span-is-re-parented-mid-execution.warrant.json
# Markdown SHA-256:   13b783225624e3679503d768b5e9bd45fa9c1890ce0819f1a7622279c9fe5653
# Code AST SHA-256:   ec53f525e068f45a93304c47857413eefc449bb662322200aaad7d1608dbdaec
# Verified Classes:   GenAiSpanAttributionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAiSpanAttributionError(RuntimeError):
    """Raised when a span re-parent/re-emit would corrupt GenAI token attribution."""
    pass


USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens")


def assert_reparentable(span: dict, *, idempotency_key: str | None) -> None:
    """Guard: a span may be re-parented only if it owns no usage, or carries a dedup key."""
    owns_usage = any(k in span.get("attributes", {}) for k in USAGE_KEYS)
    op = span.get("attributes", {}).get("gen_ai.operation.name")

    if owns_usage and op == "execute_tool":
        raise GenAiSpanAttributionError(
            f"execute_tool span {span['span_id']} carries gen_ai.usage.*; "
            "usage belongs to the chat span that emitted the tool call. "
            "Strip usage before re-parenting."
        )
    if owns_usage and not idempotency_key:
        raise GenAiSpanAttributionError(
            f"span {span['span_id']} owns gen_ai.usage.* but has no idempotency key; "
            "re-parenting would double-count on aggregation. "
            "Close with status=ERROR and open a sibling instead."
        )


def reparent(span: dict, new_parent_id: str, *, idempotency_key: str | None = None) -> dict:
    assert_reparentable(span, idempotency_key=idempotency_key)
    span = dict(span)
    span["parent_span_id"] = new_parent_id
    return span


def aggregate_usage(spans: list[dict]) -> dict[str, int]:
    """Sum usage only over spans that legitimately own it, deduped by idempotency key."""
    seen: set[str] = set()
    total = {k: 0 for k in USAGE_KEYS}
    for s in spans:
        if s.get("attributes", {}).get("gen_ai.operation.name") == "execute_tool":
            continue
        key = s.get("attributes", {}).get("gen_ai.tool.call.id") or s["span_id"]
        if key in seen:
            continue
        seen.add(key)
        for k in USAGE_KEYS:
            total[k] += int(s.get("attributes", {}).get(k, 0) or 0)
    return total
