# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-accounting-from-silently-diverging-when-an-agent-retries-a-tool-call-after-a-partial-token-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-accounting-from-silently-diverging-when-an-agent-retries-a-tool-call-after-a-partial-token-stream.warrant.json
# Markdown SHA-256:   0819adb08d6d97cafe3de20fbcea01c8a08a8177330ebdb5a972b5ec5c2ce2cb
# Code AST SHA-256:   4a58d2760a60955c8dafd158783b77100ae7eeffe7b2754c83a12dd18a0dcd77
# Verified Classes:   GenAISpanAccountingError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class GenAISpanAccountingError(RuntimeError):
    """Raised when a retried/resumed GenAI tool span would break logical-call accounting."""
    pass


def close_tool_span(span, logical_call_id, attempt, usage, prior_attempts):
    """
    Enforce: one logical call -> one accounting owner; retries are attempt-local children.
    prior_attempts: list of dicts with keys {attempt, output_tokens, executed_server_side}
    """
    if span.attributes.get("gen_ai.tool.call.id") is None:
        raise GenAISpanAccountingError("tool span missing gen_ai.tool.call.id")

    if attempt > 0:
        # Retry: must be a child of the logical call, must not re-own accounting.
        if span.parent is None or span.parent.attributes.get("logical.call.id") != logical_call_id:
            raise GenAISpanAccountingError(
                f"retry attempt {attempt} for {logical_call_id} is not parented to the "
                f"logical call span; token aggregate will double-count"
            )
        if not span.attributes.get("retry.attempt"):
            raise GenAISpanAccountingError(
                "retry span missing retry.attempt; aggregation cannot exclude it"
            )
        # If a prior attempt may have executed server-side, retry must be idempotency-gated.
        if any(p.get("executed_server_side") for p in prior_attempts):
            if not span.attributes.get("idempotency.key"):
                raise GenAISpanAccountingError(
                    f"prior attempt for {logical_call_id} may have executed server-side; "
                    f"retry lacks idempotency.key and risks duplicate side effect"
                )

    # Mixed cumulative/delta usage in one attribute is unrecoverable.
    if usage.get("cumulative") and attempt > 0:
        raise GenAISpanAccountingError(
            "resumed stream reported cumulative usage on a retry span; "
            "would mix delta and cumulative semantics under gen_ai.usage.*"
        )

    span.set_attribute("logical.call.id", logical_call_id)
    span.set_attribute("gen_ai.usage.output_tokens", usage["output_tokens"])
    span.set_attribute("accounting.owner", attempt == 0)
    return span


def reconcile(logical_calls, spans):
    """Sum only accounting-owner spans; assert one owner per logical call."""
    owners = {}
    for s in spans:
        if s.attributes.get("accounting.owner"):
            lc = s.attributes["logical.call.id"]
            if lc in owners:
                raise GenAISpanAccountingError(
                    f"multiple accounting owners for {lc}: "
                    f"{owners[lc]} and {s.span_id}"
                )
            owners[lc] = s.span_id
    missing = set(logical_calls) - set(owners)
    if missing:
        raise GenAISpanAccountingError(f"logical calls with no accounting owner: {missing}")
    return sum(s.attributes["gen_ai.usage.output_tokens"]
               for s in spans if s.attributes.get("accounting.owner"))
