# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-fidelity-when-opentelemetry-genai-spans-are-re-emitted-across-checkpoint-resume-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-token-accounting-fidelity-when-opentelemetry-genai-spans-are-re-emitted-across-checkpoint-resume-boundaries.warrant.json
# Markdown SHA-256:   2862e6ce691e8eb83430cf00c2ed2b43f7811393e40feecd2949af90d5395866
# Code AST SHA-256:   43b5f24c4eb1e21e975385d45a877f388570dad3094d1b4ecd37f99b565530fd
# Verified Classes:   UsageAccountingDivergence
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class UsageAccountingDivergence(RuntimeError):
    """Raised when a resumed GenAI span's usage attributes violate cumulative-per-span semantics."""
    pass


def reconcile_resumed_span_usage(
    checkpointed: dict,
    resumed_call: dict,
    written: dict,
) -> dict:
    """
    checkpointed: usage.* persisted at checkpoint time (base).
    resumed_call: usage measured for the continuation call only (delta).
    written: usage.* the instrumentation actually wrote onto the resumed span.
    Returns the reconciled usage dict, or raises if the write diverged.
    """
    for field in ("input_tokens", "output_tokens", "total_tokens"):
        if field not in checkpointed or field not in written:
            raise UsageAccountingDivergence(
                f"missing {field} in checkpointed or written usage; cannot reconcile"
            )

    # total_tokens must be merged additively, never recomputed from input+output,
    # because providers may fold cached/reasoning tokens into total only.
    expected = {
        "input_tokens": checkpointed["input_tokens"] + resumed_call.get("input_tokens", 0),
        "output_tokens": checkpointed["output_tokens"] + resumed_call.get("output_tokens", 0),
        "total_tokens": checkpointed["total_tokens"] + resumed_call.get("total_tokens", 0),
    }

    for field, exp in expected.items():
        got = written[field]
        if got == exp:
            continue
        if got == resumed_call.get(field, 0):
            raise UsageAccountingDivergence(
                f"overwrite-resume detected on {field}: wrote delta {got}, "
                f"expected cumulative {exp} (base {checkpointed[field]} + delta)"
            )
        if got == checkpointed[field] + resumed_call.get(field, 0) * 2:
            raise UsageAccountingDivergence(
                f"append-resume double-count on {field}: wrote {got}, expected {exp}"
            )
        raise UsageAccountingDivergence(
            f"unreconcilable {field}: wrote {got}, expected {exp} "
            f"(base {checkpointed[field]}, delta {resumed_call.get(field, 0)})"
        )

    # Monotonicity invariant: a resumed span may never report less than its base.
    if written["total_tokens"] < checkpointed["total_tokens"]:
        raise UsageAccountingDivergence(
            "non-monotonic total_tokens across resume boundary"
        )

    return expected
