# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-an-agent-s-token-accounting-diverges-from-the-model-server-s-usage-report-mi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-opentelemetry-genai-span-attributes-when-an-agent-s-token-accounting-diverges-from-the-model-server-s-usage-report-mi.warrant.json
# Markdown SHA-256:   a95407ac3e04556eca8f2ceee9866d47ea150fd1fc28ff5a3b45277af21ba1a7
# Code AST SHA-256:   968345fcba01035c55d816f6704504100e964d66324dc1b898a10de0f1d772e7
# Verified Classes:   TokenLedgerReconciliationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TokenLedgerReconciliationError(RuntimeError):
    """Raised when a GenAI span's token attributes cannot be reconciled to a single authoritative source."""
    pass


def finalize_genai_span(
    span_attrs: dict,
    client_estimate_input: int,
    server_usage: dict | None,
    known_augmentation_tokens: int,
    delta_threshold_ratio: float = 0.05,
    delta_threshold_abs: int = 200,
) -> dict:
    """
    Enforce the reconciliation invariant: gen_ai.usage.input_tokens is either
    server-observed or explicitly marked estimated, never silently mixed.
    """
    if server_usage is not None and "prompt_tokens" in server_usage:
        observed = int(server_usage["prompt_tokens"])
        span_attrs["gen_ai.usage.input_tokens"] = observed
        span_attrs["gen_ai.usage.output_tokens"] = int(server_usage.get("completion_tokens", 0))
        span_attrs["agent.token.provenance"] = "server_observed"

        delta = observed - client_estimate_input
        span_attrs["reconciliation.delta"] = delta
        unexplained = delta - known_augmentation_tokens

        exceeds = (
            abs(delta) > delta_threshold_abs
            and abs(delta) > delta_threshold_ratio * max(client_estimate_input, 1)
        )
        if exceeds and abs(unexplained) > delta_threshold_abs:
            # Server billed for tokens the agent did not author and cannot account for.
            # This is a middleware-drift or prompt-injection signal, not a rounding error.
            raise TokenLedgerReconciliationError(
                f"Unreconciled token delta: observed={observed} "
                f"estimate={client_estimate_input} known_aug={known_augmentation_tokens} "
                f"unexplained={unexplained}. Refusing to emit span as authoritative."
            )
        return span_attrs

    # No server usage: error path, streaming without terminal frame, or timeout.
    # Estimate is the only number; it MUST be marked estimated and never treated as ground truth.
    span_attrs["gen_ai.usage.input_tokens"] = client_estimate_input
    span_attrs["agent.token.provenance"] = "estimated"
    span_attrs["agent.token.estimate_uncertainty"] = known_augmentation_tokens

    if known_augmentation_tokens > 0:
        # Budget guard must not consume this as ground truth when augmentation is possible.
        raise TokenLedgerReconciliationError(
            f"Emitting estimated token count ({client_estimate_input}) on a span with "
            f"possible augmentation ({known_augmentation_tokens} tokens) and no server usage. "
            f"Budget guard must apply margin or refuse; ledger is not reconcilable."
        )
    return span_attrs
