# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-opentelemetry-genai-span-accounting-silently-diverges-from-its-own-token-ledger-under-mid-tool-call-retries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-opentelemetry-genai-span-accounting-silently-diverges-from-its-own-token-ledger-under-mid-tool-call-retries.warrant.json
# Markdown SHA-256:   e65653010a1d794395de6797b69291a87846cd65fbfb30f6916179302cbb4964
# Code AST SHA-256:   e684e23ae7f928599be2d7991f6cb7b2d750b104eded4d0fe93107ed114e4de9
# Verified Classes:   TokenAccountingDivergence
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TokenAccountingDivergence(RuntimeError):
    """Raised when a parent agent span's reported usage does not reconcile
    with the runtime's authoritative token ledger for the same task."""
    pass


def close_agent_span(
    span,
    ledger_delta: int,
    parent_reported_usage: int,
    discarded_attempt_spans: list,
    tolerance: int = 0,
) -> None:
    """Reconcile span-tree usage against the ledger before closing the span.

    parent_reported_usage: gen_ai.usage.input_tokens + output_tokens on the parent.
    discarded_attempt_spans: attempts that were retried; each carries its own
    usage and MUST be exported, not dropped.
    """
    orphaned = sum(
        s.attributes.get("gen_ai.usage.input_tokens", 0)
        + s.attributes.get("gen_ai.usage.output_tokens", 0)
        for s in discarded_attempt_spans
    )
    reconciled = parent_reported_usage + orphaned
    discrepancy = ledger_delta - reconciled

    if abs(discrepancy) > tolerance:
        span.set_attribute("otel.status_code", "ERROR")
        span.set_attribute("accounting.discrepancy_tokens", discrepancy)
        span.set_attribute("accounting.orphaned_attempt_tokens", orphaned)
        span.set_attribute("accounting.ledger_delta_tokens", ledger_delta)
        span.end()
        raise TokenAccountingDivergence(
            f"Span usage {reconciled} (parent {parent_reported_usage} + "
            f"orphaned {orphaned}) does not reconcile with ledger delta "
            f"{ledger_delta}; discrepancy {discrepancy} tokens. "
            f"Discarded attempts were likely not exported."
        )

    span.set_attribute("accounting.orphaned_attempt_tokens", orphaned)
    span.set_attribute("accounting.reconciled", True)
    span.end()
