# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-token-accounting-from-silently-misattributing-cached-prompt-tokens-across-tool-call-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-opentelemetry-genai-span-token-accounting-from-silently-misattributing-cached-prompt-tokens-across-tool-call-retries.warrant.json
# Markdown SHA-256:   d095b1b7be188c0a79b967161f69e9dda8ef4aebbc30aaa030d6062da2b701bb
# Code AST SHA-256:   03435cff59203f303f67fd802c2b38e4b8a3e83611c57957e9793d2d05246f34
# Verified Classes:   GenAIUsageInvariantError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GenAIUsageInvariantError(RuntimeError):
    """Raised when an aggregated GenAI span violates cached ⊆ input containment."""
    pass


def validate_agent_span_usage(span: dict) -> None:
    attrs = span.get("attributes", {})
    input_tokens = attrs.get("gen_ai.usage.input_tokens")
    cached_tokens = attrs.get("gen_ai.usage.cached_input_tokens")
    child_count = attrs.get("gen_ai.agent.child_span_count", 1)

    if input_tokens is None or cached_tokens is None:
        return  # nothing to reconcile

    # Invariant: cached tokens are a subset of input tokens.
    if cached_tokens > input_tokens:
        raise GenAIUsageInvariantError(
            f"span={span.get('name')} cached_input_tokens={cached_tokens} "
            f"exceeds input_tokens={input_tokens} (child_count={child_count}); "
            f"likely summed across retry fan-out sharing a cached prefix. "
            f"Collapse to max() over children with identical prefix_hash, "
            f"or emit per-child usage without aggregation."
        )

    # Guard against aggregated spans that should never carry a summed cache count.
    if child_count > 1 and attrs.get("gen_ai.prompt.prefix_hash") is None:
        raise GenAIUsageInvariantError(
            f"span={span.get('name')} aggregates {child_count} children but "
            f"lacks gen_ai.prompt.prefix_hash; cached token de-duplication is "
            f"undefined. Emit per-child usage or add prefix_hash."
        )


def reconcile(span: dict) -> dict:
    validate_agent_span_usage(span)
    attrs = span["attributes"]
    uncached = attrs["gen_ai.usage.input_tokens"] - attrs["gen_ai.usage.cached_input_tokens"]
    if uncached < 0:  # defensive: should be unreachable post-validation
        raise GenAIUsageInvariantError("negative uncached token count after validation")
    return {"uncached_input_tokens": uncached}
