# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-token-usage-schema-conformance-break-when-opentelemetry-genai-span-attributes-desynchronize-from-the-agent-s-internal-ac.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-token-usage-schema-conformance-break-when-opentelemetry-genai-span-attributes-desynchronize-from-the-agent-s-internal-ac.warrant.json
# Markdown SHA-256:   e51c9f11e662f64d5d4666f994dee00b8d2120768777ed3eacc2b031aa9e37c3
# Code AST SHA-256:   9b8507736a46f148d24429d4bd638ca793754df228cb171767c9eaf62bc113d4
# Verified Classes:   UsageSchemaDriftError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UsageSchemaDriftError(RuntimeError):
    """Raised when a GenAI span's usage attributes diverge from the ledger delta
    beyond the tokenizer/billing offset bound, making the trace inadmissible
    as evidence for budget aborts."""
    pass


# Per-turn bound on tokenizer-vs-billing convention offset.
# Measured empirically per provider; must be recalibrated on model change.
TOKEN_CONVENTION_EPSILON = 24


def close_agent_span_with_conformance(
    span,
    ledger_delta: dict,          # {"input_tokens": int, "output_tokens": int}
    span_delta: dict,            # same keys, read from span attributes
    agent_id_on_span: str,
    agent_id_in_checkpoint: str,
    cumulative_drift: int,
    remaining_budget: int,
) -> None:
    # Invariant 3: identity must persist across checkpoint/resume.
    if agent_id_on_span != agent_id_in_checkpoint:
        raise UsageSchemaDriftError(
            f"gen_ai.agent.id diverged on resume: span={agent_id_on_span!r} "
            f"checkpoint={agent_id_in_checkpoint!r}; session will fragment across traces"
        )

    # Invariant 1 & 2: span and ledger must agree within convention bound.
    drift = 0
    for key in ("input_tokens", "output_tokens"):
        d = abs(ledger_delta[key] - span_delta[key])
        drift += d
        if d > TOKEN_CONVENTION_EPSILON:
            raise UsageSchemaDriftError(
                f"usage schema drift on {key}: ledger={ledger_delta[key]} "
                f"span={span_delta[key]} delta={d} > eps={TOKEN_CONVENTION_EPSILON}"
            )

    # Decision boundary: cumulative drift vs budget headroom.
    new_cumulative = cumulative_drift + drift
    if new_cumulative > remaining_budget:
        # Trace is no longer admissible as evidence; force reconciliation event
        # and mark status so operators see the anomaly in the span tree.
        span.add_event(
            "gen_ai.usage.reconciliation",
            {
                "gen_ai.usage.drift_tokens": drift,
                "gen_ai.usage.cumulative_drift_tokens": new_cumulative,
                "gen_ai.usage.ledger_input_tokens": ledger_delta["input_tokens"],
                "gen_ai.usage.span_input_tokens": span_delta["input_tokens"],
                "gen_ai.usage.authority": "ledger",
            },
        )
        raise UsageSchemaDriftError(
            f"cumulative drift {new_cumulative} exceeds remaining budget "
            f"{remaining_budget}; abort would be unexplainable from trace alone"
        )
