# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-genai-span-attributes-it-cannot-provenance-validate-across-a-context-compaction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-genai-span-attributes-it-cannot-provenance-validate-across-a-context-compaction-boundary.warrant.json
# Markdown SHA-256:   bdbde1c90d06872c50e5dfbfa8e0d999385d9e6c1b97df6497edf5261df9f0b0
# Code AST SHA-256:   6c49ee3e17b65a7e32fa2fbc5e2bcd2305acdac6d0857229a9439171284b6898
# Verified Classes:   UnprovenancedSpanAttributeError, RawInferenceRecord, SpanCloseContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnprovenancedSpanAttributeError(RuntimeError):
    """Raised when a GenAI span attribute cannot be traced to a raw provider response."""
    pass


@dataclass(frozen=True)
class RawInferenceRecord:
    """Immutable, captured-before-compaction record of a single provider inference."""
    model: str
    input_tokens: int
    output_tokens: int
    finish_reason: str


@dataclass
class SpanCloseContext:
    conversation_id: str
    raw_record: Optional[RawInferenceRecord]
    compaction_occurred: bool


def emit_genai_usage_attributes(ctx: SpanCloseContext) -> dict:
    """
    Returns the gen_ai.* attributes safe to emit at span close.
    Refuses to fabricate usage attributes from reconstructed context.
    """
    attrs = {"gen_ai.conversation.id": ctx.conversation_id}

    if ctx.raw_record is None:
        if ctx.compaction_occurred:
            # Abstain: we cannot provenance-validate usage after compaction.
            # Omitting is valid; fabricating is not.
            attrs["gen_ai.usage.provenance"] = "unavailable_post_compaction"
            return attrs
        raise UnprovenancedSpanAttributeError(
            f"Span for conversation {ctx.conversation_id} has no raw inference "
            "record and no documented compaction event; refusing to emit usage "
            "attributes that cannot be traced to a provider response."
        )

    rec = ctx.raw_record
    attrs.update({
        "gen_ai.request.model": rec.model,
        "gen_ai.usage.input_tokens": rec.input_tokens,
        "gen_ai.usage.output_tokens": rec.output_tokens,
        "gen_ai.response.finish_reasons": [rec.finish_reason],
        "gen_ai.usage.provenance": "raw_response",
    })
    return attrs
