# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-genai-semantic-convention-spans-against-a-divergent-tool-call-ledger-before-emitting-cost-metrics.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-genai-semantic-convention-spans-against-a-divergent-tool-call-ledger-before-emitting-cost-metrics.warrant.json
# Markdown SHA-256:   511bf0ed896a4fd3d96dd2d6963c0499c07bbe0a9562f228c290b8d3a1eab889
# Code AST SHA-256:   4f2da3746061cdeaf9a59e7c2923445cea89c32656d07cc2889d685c68360171
# Verified Classes:   SpanLedgerDivergenceError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpanLedgerDivergenceError(RuntimeError):
    """Raised when GenAI span-derived token totals cannot be reconciled
    against the executor's dispatch ledger within tolerance."""
    pass


def reconcile_span_cost(
    span_tokens_by_call: dict[str, int],
    ledger_tokens_by_call: dict[str, int],
    tolerance_ratio: float = 0.02,
) -> dict[str, int]:
    """Join GenAI execute_tool spans to the executor ledger on call ID.

    Returns per-call reconciled token counts. Raises if the total
    divergence exceeds tolerance_ratio, because a silently wrong cost
    metric is worse than a failed reconcile.
    """
    span_total = sum(span_tokens_by_call.values())
    ledger_total = sum(ledger_tokens_by_call.values())

    span_only = set(span_tokens_by_call) - set(ledger_tokens_by_call)
    ledger_only = set(ledger_tokens_by_call) - set(span_tokens_by_call)

    # Spans with no ledger entry are cancelled intents: non-billable.
    # Ledger entries with no span are telemetry gaps: must be counted.
    gap_tokens = sum(ledger_tokens_by_call[c] for c in ledger_only)
    reconciled_total = ledger_total

    denom = max(ledger_total, 1)
    divergence = abs(span_total - reconciled_total) / denom
    if divergence > tolerance_ratio:
        raise SpanLedgerDivergenceError(
            f"span/ledger token divergence {divergence:.4f} exceeds "
            f"tolerance {tolerance_ratio:.4f}: span_total={span_total} "
            f"ledger_total={ledger_total} span_only_calls={sorted(span_only)} "
            f"ledger_only_calls={sorted(ledger_only)} "
            f"telemetry_gap_tokens={gap_tokens}"
        )
    return dict(ledger_tokens_by_call)
