# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-drift-between-opentelemetry-genai-tool-call-spans-and-its-own-token-ledger-during-mid-task-checkpoint-resum.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-drift-between-opentelemetry-genai-tool-call-spans-and-its-own-token-ledger-during-mid-task-checkpoint-resum.warrant.json
# Markdown SHA-256:   00256707a48f4eed78b34a8c4b792127d51c82871c57f0aeebd85274485277dc
# Code AST SHA-256:   3ccef1287a73bb2f97f29f33a3254cff55a251769002dd9eb30defab26348bfd
# Verified Classes:   BudgetLedgerDivergence
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class BudgetLedgerDivergence(RuntimeError):
    """Raised when span-derived token totals cannot be reconciled with the
    authoritative ledger after a checkpoint/resume replay."""
    pass


def reconcile_resumed_step(
    ledger_debits: list[dict],      # [{"step_id": str, "generation": int, "tokens": int}]
    span_usage: list[dict],         # [{"step_id": str, "generation": int, "input": int, "output": int}]
    budget_headroom: int,
) -> dict:
    """
    Reconcile ledger truth against span truth for a resumed agent step.

    Invariant: the ledger is authoritative for budget. Spans are read only
    after deduplication by (step_id, max generation). If a ledger debit has
    no span at or above its generation, the span log is incomplete — the
    caller MUST NOT recompute budget from spans.
    """
    ledger_by_step: dict[str, dict] = {}
    for d in ledger_debits:
        prev = ledger_by_step.get(d["step_id"])
        if prev is None or d["generation"] > prev["generation"]:
            ledger_by_step[d["step_id"]] = d

    # Deduplicate spans: keep only the highest generation per logical step.
    span_by_step: dict[str, dict] = {}
    for s in span_usage:
        prev = span_by_step.get(s["step_id"])
        if prev is None or s["generation"] > prev["generation"]:
            span_by_step[s["step_id"]] = s

    lost_spans: list[str] = []
    duplicate_spans: list[str] = []

    for step_id, debit in ledger_by_step.items():
        span = span_by_step.get(step_id)
        if span is None or span["generation"] < debit["generation"]:
            lost_spans.append(step_id)
        elif span["generation"] > debit["generation"]:
            duplicate_spans.append(step_id)

    # A ledger debit with no matching span means telemetry is incomplete.
    # Recomputing budget from spans here would restore already-spent tokens.
    if lost_spans:
        raise BudgetLedgerDivergence(
            f"ledger has debits for steps {lost_spans} with no corresponding "
            f"span at or above the recorded generation; span log is incomplete "
            f"and MUST NOT be used to recompute budget. Ledger headroom "
            f"({budget_headroom}) is authoritative."
        )

    # Duplicate spans are recoverable by dedup, but flag them so the
    # collector does not double-count cost.
    return {
        "headroom": budget_headroom,          # ledger wins, always
        "lost_spans": lost_spans,             # empty here, else we raised
        "duplicate_spans": duplicate_spans,   # deduped on read, flagged for collector
        "reconciled": True,
    }
