# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-token-accounting-diverge-from-its-trace-when-a-tool-call-is-retried-across-a-span-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-token-accounting-diverge-from-its-trace-when-a-tool-call-is-retried-across-a-span-boundary.warrant.json
# Markdown SHA-256:   a9088573ebcdc6bd1be0c1004f97d0922a59afcce56a05584e8dbd33d60d3fae
# Code AST SHA-256:   f70c6bb3f4aafa310b2de7a78202b0d0bab1d791db9c113e17b9132d0dd4d15a
# Verified Classes:   TraceTokenReconciliationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TraceTokenReconciliationError(RuntimeError):
    """Raised when trace-summed GenAI token usage cannot be reconciled with provider billing."""
    pass


def reconcile_trace_tokens(spans: list[dict], provider_billed_input_tokens: int, tolerance: int = 0) -> int:
    """
    Reconcile OTel GenAI span usage against provider billing.

    Invariant enforced:
      - usage attributes appear only on leaf spans with gen_ai.operation.name == "chat"
      - no ancestor span carries gen_ai.usage.* (would cause double-count)
      - retry-injected prompt tokens are subtracted before comparison
    """
    usage_spans = [s for s in spans if "gen_ai.usage.input_tokens" in s.get("attributes", {})]
    non_chat_usage = [s for s in usage_spans if s["attributes"].get("gen_ai.operation.name") != "chat"]
    if non_chat_usage:
        raise TraceTokenReconciliationError(
            f"{len(non_chat_usage)} non-chat span(s) carry gen_ai.usage.*; "
            f"double-counting risk. Offending span ids: {[s['span_id'] for s in non_chat_usage]}"
        )

    # Detect parent spans that also carry usage (condition 3 violation).
    span_ids = {s["span_id"] for s in spans}
    for s in usage_spans:
        parent = s.get("parent_span_id")
        if parent in span_ids and any(p["span_id"] == parent and "gen_ai.usage.input_tokens" in p.get("attributes", {}) for p in spans):
            raise TraceTokenReconciliationError(
                f"span {s['span_id']} and its parent {parent} both carry gen_ai.usage.input_tokens; "
                f"trace sum is ambiguous"
            )

    trace_sum = sum(s["attributes"]["gen_ai.usage.input_tokens"] for s in usage_spans)

    # Subtract tokens attributable to retry-injected error messages.
    retry_overhead = 0
    for s in spans:
        if s["attributes"].get("gen_ai.operation.name") == "execute_tool":
            retries = s["attributes"].get("gen_ai.tool.retry_count", 0)
            if retries > 0:
                # each retry injects one synthetic tool-error message into the next chat prompt
                retry_overhead += retries * s["attributes"].get("gen_ai.tool.error_message_tokens", 0)

    reconciled = trace_sum - retry_overhead
    if abs(reconciled - provider_billed_input_tokens) > tolerance:
        raise TraceTokenReconciliationError(
            f"token divergence: trace_sum={trace_sum} retry_overhead={retry_overhead} "
            f"reconciled={reconciled} provider_billed={provider_billed_input_tokens} "
            f"delta={reconciled - provider_billed_input_tokens}"
        )
    return reconciled
