# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-usage-spans-when-a-retried-tool-call-double-counts-completion-tokens-across-parent-and-chil.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-token-usage-spans-when-a-retried-tool-call-double-counts-completion-tokens-across-parent-and-chil.warrant.json
# Markdown SHA-256:   d15b21596815d9833a0d80bf4973649c8cfa28a029b2e2fab685cf47da6bf1cc
# Code AST SHA-256:   2ee8bf8093bf96a80ee4a09c9ec9cee7e7413be164613c7f966256d1d14cbba8
# Verified Classes:   UsageReconciliationError, ChatSpan, AgentSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UsageReconciliationError(RuntimeError):
    """Raised when a parent agent span cannot reconcile child GenAI usage."""
    pass


@dataclass
class ChatSpan:
    response_id: Optional[str]
    output_tokens: int
    finish_reasons: list[str]
    status: str  # "OK" | "ERROR"


@dataclass
class AgentSpan:
    children: list[ChatSpan] = field(default_factory=list)

    def reconciled_output_tokens(self) -> tuple[int, int]:
        """Return (delivered_tokens, discarded_tokens).

        delivered = sum over distinct response_ids of the tokens from the
        attempt that actually contributed to the returned result.
        discarded = tokens billed on attempts whose output was thrown away
        (truncated by client deadline, or errored after partial generation).
        """
        if not self.children:
            return 0, 0

        # Invariant 1: retries must be linkable via response_id.
        ids = [c.response_id for c in self.children]
        if any(rid is None for rid in ids):
            raise UsageReconciliationError(
                "child chat span missing gen_ai.response.id; retries are "
                "indistinguishable from parallel calls, cannot reconcile"
            )
        if len(set(ids)) != len(ids):
            raise UsageReconciliationError(
                f"duplicate gen_ai.response.id across children: {ids}; "
                "same logical call emitted twice without attempt marker"
            )

        delivered = 0
        discarded = 0
        for c in self.children:
            partial = "length" in c.finish_reasons and c.status == "ERROR"
            if partial:
                # Client deadline fired after provider generated tokens.
                # Billed, but not part of the delivered answer.
                discarded += c.output_tokens
            elif c.status == "ERROR":
                discarded += c.output_tokens
            else:
                delivered += c.output_tokens

        # Invariant 2: delivered must not exceed any single successful attempt.
        ok_attempts = [c.output_tokens for c in self.children if c.status == "OK"]
        if ok_attempts and delivered > max(ok_attempts):
            raise UsageReconciliationError(
                f"delivered={delivered} exceeds max successful attempt "
                f"({max(ok_attempts)}); aggregation double-counted a retry"
            )
        return delivered, discarded


def emit_parent_usage(span: AgentSpan) -> dict:
    try:
        delivered, discarded = span.reconciled_output_tokens()
    except UsageReconciliationError:
        # Refuse to emit a conflated total; mark as unavailable instead.
        return {
            "gen_ai.usage.output_tokens": None,
            "gen_ai.usage.reconciliation": "unavailable",
        }
    return {
        "gen_ai.usage.output_tokens": delivered,
        "gen_ai.usage.discarded_output_tokens": discarded,
        "gen_ai.usage.attempts": len(span.children),
        "gen_ai.usage.reconciliation": "ok",
    }
