# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-drift-when-opentelemetry-genai-span-attributes-are-reconciled-against-a-parent-agent-span-under-nest.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-token-accounting-drift-when-opentelemetry-genai-span-attributes-are-reconciled-against-a-parent-agent-span-under-nest.warrant.json
# Markdown SHA-256:   4cf17f70af2566c04c1b1d3e506efa32033d24860333d28be7aec9a24b6c2c67
# Code AST SHA-256:   62fb10ad038b0bb135668c71dac8f8c81a1ed7d9c19ff1e42c548f95812005f6
# Verified Classes:   TokenAggregationDriftError, LLMSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TokenAggregationDriftError(RuntimeError):
    """Raised when a parent agent span's aggregated gen_ai.usage attributes
    cannot be reconciled to a clean 1:1 partition of logical model invocations."""


@dataclass
class LLMSpan:
    span_id: str
    parent_id: str
    invocation_id: str | None          # None => conventions gave us no key
    attempt: int
    status_ok: bool
    finish_reasons: list[str]
    input_tokens: int
    output_tokens: int
    cache_read_input_tokens: int | None = None


def aggregate_parent_usage(children: list[LLMSpan]) -> dict[str, int]:
    """Sum child usage into a parent agent span, enforcing the reconciliation invariant."""
    by_invocation: dict[str, list[LLMSpan]] = {}
    unkeyed: list[LLMSpan] = []

    for c in children:
        if c.invocation_id is None:
            unkeyed.append(c)
        else:
            by_invocation.setdefault(c.invocation_id, []).append(c)

    # Signal 1: attempt multiplicity without a logical-invocation key.
    if unkeyed and len(unkeyed) > 1:
        raise TokenAggregationDriftError(
            f"{len(unkeyed)} LLM spans lack gen_ai.invocation.id; cannot "
            f"distinguish retries from distinct invocations. Spans: "
            f"{[s.span_id for s in unkeyed]}"
        )

    total_in = 0
    total_out = 0
    for inv_id, attempts in by_invocation.items():
        # Signal 2: partial-usage span with non-OK status and no terminal finish reason.
        partials = [a for a in attempts if not a.status_ok or not a.finish_reasons]
        finals = [a for a in attempts if a.status_ok and a.finish_reasons]
        if partials and not finals:
            raise TokenAggregationDriftError(
                f"invocation {inv_id} has only partial attempts "
                f"{[p.span_id for p in partials]}; no billable final attempt."
            )
        if len(finals) > 1:
            raise TokenAggregationDriftError(
                f"invocation {inv_id} has {len(finals)} terminal attempts; "
                f"logical invocation was double-billed or mis-keyed."
            )
        final = finals[0]
        # Signal 3: retry without cache_read accounting inflates input.
        if final.attempt > 1 and final.cache_read_input_tokens is None:
            raise TokenAggregationDriftError(
                f"invocation {inv_id} retried (attempt={final.attempt}) but "
                f"cache_read_input_tokens is unset; input tokens will be "
                f"double-counted against the prompt."
            )
        total_in += final.input_tokens - (final.cache_read_input_tokens or 0)
        total_out += final.output_tokens

    return {"input_tokens": total_in, "output_tokens": total_out}
