# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-otlp-spans-whose-gen-ai-semantic-convention-attributes-are-computed-after-the-span-has-already-been-closed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-otlp-spans-whose-gen-ai-semantic-convention-attributes-are-computed-after-the-span-has-already-been-closed.warrant.json
# Markdown SHA-256:   10889079061fe19506829f649b6b1689aeb4e4cac1267b4bb4724560e11cb11b
# Code AST SHA-256:   ec9a154b6dff572f14c1d5f778d960d16f3ba1247cf94ea68fd9288f68b0f84f
# Verified Classes:   GenAiUsageAttributionError, SpanProto, ProviderUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


SENTINEL = 0


class GenAiUsageAttributionError(RuntimeError):
    """Raised when a gen_ai.usage.* attribute was written after span serialization
    or carries a sentinel value while the provider response reports real usage."""


@dataclass
class SpanProto:
    name: str
    attributes: list[tuple[str, object]] = field(default_factory=list)
    closed: bool = False


@dataclass
class ProviderUsage:
    input_tokens: int
    output_tokens: int


def encode_span(span: SpanProto) -> SpanProto:
    # Serialization snapshots the attribute list; later mutations do not appear
    # in the exported proto. This mirrors the Python/Go SDK behavior.
    return SpanProto(name=span.name, attributes=list(span.attributes), closed=True)


def enrich_after_close(span: SpanProto, usage: ProviderUsage) -> SpanProto:
    # Post-hoc enricher: mutates the ReadableSpan, not the exported proto.
    span.attributes.append(("gen_ai.usage.input_tokens", usage.input_tokens))
    span.attributes.append(("gen_ai.usage.output_tokens", usage.output_tokens))
    return span


def validate_before_export(proto: SpanProto, usage: ProviderUsage | None) -> None:
    keys = [k for k, _ in proto.attributes]
    if len(keys) != len(set(keys)):
        dupes = {k for k in keys if keys.count(k) > 1}
        raise GenAiUsageAttributionError(
            f"duplicate gen_ai attribute keys after enrichment: {sorted(dupes)}"
        )
    if usage is None:
        return
    reported = dict(proto.attributes)
    for key, expected in (
        ("gen_ai.usage.input_tokens", usage.input_tokens),
        ("gen_ai.usage.output_tokens", usage.output_tokens),
    ):
        actual = reported.get(key)
        if actual is None:
            raise GenAiUsageAttributionError(
                f"{key} missing from exported span; usage lost during serialization"
            )
        if actual == SENTINEL and expected != SENTINEL:
            raise GenAiUsageAttributionError(
                f"{key} exported as sentinel {SENTINEL} but provider reported {expected}; "
                "attribute was set after span.end() and did not survive serialization"
            )


def export_path(span: SpanProto, usage: ProviderUsage) -> SpanProto:
    proto = encode_span(span)              # snapshots attributes
    enrich_after_close(span, usage)       # mutates the wrong object
    validate_before_export(proto, usage)  # catches the loss
    return proto


if __name__ == "__main__":
    live = SpanProto(
        name="gen_ai.chat",
        attributes=[
            ("gen_ai.request.model", "gpt-4o-mini"),
            ("gen_ai.usage.input_tokens", SENTINEL),
            ("gen_ai.usage.output_tokens", SENTINEL),
        ],
    )
    usage = ProviderUsage(input_tokens=1841, output_tokens=212)
    export_path(live, usage)  # raises GenAiUsageAttributionError
