# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-opentelemetry-genai-span-attributes-as-untrusted-input-rather-than-as-telemetry-metadata.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-opentelemetry-genai-span-attributes-as-untrusted-input-rather-than-as-telemetry-metadata.warrant.json
# Markdown SHA-256:   74cb9c17478b09d0117854b197f6446dc88bbcc17785ae41834556b076cc90df
# Code AST SHA-256:   dfa585f96423411642bb7aaa0ccb46e766a6a7a04ff2a537f2cd963858cd38b2
# Verified Classes:   UntrustedGenAIAttributeError, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class UntrustedGenAIAttributeError(RuntimeError):
    """Raised when a gen_ai.* attribute is used for control flow without provenance/type validation."""
    pass


@dataclass(frozen=True)
class Span:
    trace_id: str
    emitter_service: str          # resource attribute: service.name
    attrs: dict[str, object]      # includes gen_ai.* keys, possibly coerced to str


TRUSTED_USAGE_EMITTERS = frozenset({"model-gateway"})


def _as_nonneg_int(span: Span, key: str) -> int:
    raw = span.attrs.get(key)
    # OTel collectors frequently coerce to str; reject, do not coerce.
    if isinstance(raw, bool) or not isinstance(raw, int):
        raise UntrustedGenAIAttributeError(
            f"{key}={raw!r} on trace {span.trace_id} is not an int; "
            f"refusing to use it in budget arithmetic"
        )
    if raw < 0:
        raise UntrustedGenAIAttributeError(
            f"{key}={raw} on trace {span.trace_id} is negative; "
            f"sign-flip or forged usage rejected"
        )
    return raw


def project_usage(spans: Iterable[Span], trace_id: str) -> int:
    """Compute decision-bearing output-token usage for a trace.

    Only spans emitted by a trusted usage emitter may contribute.
    Any usage-bearing span from an untrusted emitter is a hard error:
    the trace's budget is unverifiable and admission must fail closed.
    """
    total = 0
    seen_usage = False
    for span in spans:
        if span.trace_id != trace_id:
            continue
        if "gen_ai.usage.output_tokens" not in span.attrs:
            continue
        seen_usage = True
        if span.emitter_service not in TRUSTED_USAGE_EMITTERS:
            raise UntrustedGenAIAttributeError(
                f"trace {trace_id}: usage emitted by untrusted service "
                f"{span.emitter_service!r}; cannot reconcile budget"
            )
        total += _as_nonneg_int(span, "gen_ai.usage.output_tokens")
    if not seen_usage:
        raise UntrustedGenAIAttributeError(
            f"trace {trace_id}: no trusted usage span found; "
            f"budget cannot be computed, failing closed"
        )
    return total
