# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-drift-when-opentelemetry-genai-spans-are-emitted-by-a-sub-agent-whose-tool-calls-were-retried-after-a-tra.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-token-accounting-drift-when-opentelemetry-genai-spans-are-emitted-by-a-sub-agent-whose-tool-calls-were-retried-after-a-tra.warrant.json
# Markdown SHA-256:   71f8d446cd1b64420625a5dab003aa0f6e04f61d512908f79cc033c29bbae6a7
# Code AST SHA-256:   54fd77fa6a651af672a0c396d0e6f6e642c88525363cc78ad4c7f3f160366b0f
# Verified Classes:   TokenAccountingDriftError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TokenAccountingDriftError(RuntimeError):
    """Raised when span-derived token accounting cannot be reconciled with the ledger
    under retry or checkpoint-replay conditions in OTel GenAI agent spans."""
    pass


def reconcile_chat_spans(chat_spans, ledger_billed_tokens, max_retries):
    """
    chat_spans: list of dicts with keys:
        span_id, status_code, input_tokens (may be None), retry_of (may be None),
        retry_attempt (may be None)
    ledger_billed_tokens: authoritative billed input tokens for the conversation window.
    max_retries: the runtime's configured retry budget (bounds the drift window).
    """
    span_sum = 0
    ok_spans = 0
    untagged_replays = []

    for s in chat_spans:
        tokens = s.get("input_tokens")
        if tokens is None:
            # Pre-token abort: span exists but no usage chunk arrived.
            # Counts toward cardinality, contributes zero to token sum.
            continue
        span_sum += tokens
        if s.get("status_code") == "OK":
            ok_spans += 1
            if s.get("retry_attempt") and not s.get("retry_of"):
                untagged_replays.append(s["span_id"])

    # Invariant 1: an OK chat span that is a retry must carry retry_of.
    # Without it, the replay is indistinguishable from a legitimate turn.
    if untagged_replays:
        raise TokenAccountingDriftError(
            f"untagged retry spans {untagged_replays}: cannot deduplicate against "
            f"pre-checkpoint or pre-retry invocation; ledger reconciliation impossible"
        )

    # Invariant 2: span sum must not exceed ledger by more than the retry budget
    # times the largest single prompt (the drift window).
    if chat_spans:
        max_prompt = max((s.get("input_tokens") or 0) for s in chat_spans)
    else:
        max_prompt = 0
    drift_window = max_retries * max_prompt
    if span_sum - ledger_billed_tokens > drift_window:
        raise TokenAccountingDriftError(
            f"span_sum={span_sum} exceeds ledger={ledger_billed_tokens} by "
            f"{span_sum - ledger_billed_tokens} > drift_window={drift_window}; "
            f"probable checkpoint replay without span-identity persistence"
        )

    # Invariant 3: cardinality mismatch without a corresponding token mismatch
    # indicates pre-token aborts (benign) or replays (must be tagged).
    if ok_spans > 1 and ledger_billed_tokens == 0:
        raise TokenAccountingDriftError(
            f"{ok_spans} OK chat spans but ledger shows zero billed tokens; "
            f"ledger join key (conversation.id) likely broken"
        )

    return {"span_sum": span_sum, "ledger": ledger_billed_tokens,
            "drift": span_sum - ledger_billed_tokens}
