# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-tool-call-span-to-the-wrong-genai-semantic-convention-schema-version-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attributes-a-tool-call-span-to-the-wrong-genai-semantic-convention-schema-version-mid-run.warrant.json
# Markdown SHA-256:   295346aa37d4775f70d5e51dd64ebf16e5fad99611f50397e61748ef933f77b6
# Code AST SHA-256:   a3c2d9b2139b63f028022bd8b1b3cb0ac8c2f109f8d26553b563c4825d2c19e5
# Verified Classes:   SemconvVersionMismatchError, ToolCallSpan, CollectorProcessor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

REQUIRED_KEYS_BY_VERSION = {
    "1.27.0": {"gen_ai.system", "gen_ai.operation.name", "gen_ai.tool.name",
               "gen_ai.usage.prompt_tokens", "gen_ai.usage.completion_tokens"},
    "1.31.0": {"gen_ai.provider.name", "gen_ai.operation.name", "gen_ai.tool.name",
               "gen_ai.tool.call.id", "gen_ai.usage.input_tokens",
               "gen_ai.usage.output_tokens"},
}
# operation.name value space tightened in 1.31.0 to include "execute_tool"
VALID_OPERATIONS_1_31 = {"chat", "execute_tool", "generate_content"}


class SemconvVersionMismatchError(RuntimeError):
    """Raised when a tool-call span's declared semconv version does not match
    the collector processor's configured version, or when a span claims a
    version it does not fully satisfy. Must NOT be swallowed as a passthrough."""


@dataclass
class ToolCallSpan:
    attributes: dict
    declared_semconv_version: Optional[str] = None


@dataclass
class CollectorProcessor:
    configured_version: str
    quarantine: list = field(default_factory=list)
    mismatch_count: int = 0

    def validate(self, span: ToolCallSpan) -> None:
        if span.declared_semconv_version is None:
            raise SemconvVersionMismatchError(
                "tool-call span has no declared semconv version; refusing to "
                "guess a transform direction"
            )
        if span.declared_semconv_version not in REQUIRED_KEYS_BY_VERSION:
            raise SemconvVersionMismatchError(
                f"unknown semconv version {span.declared_semconv_version!r}"
            )
        if span.declared_semconv_version != self.configured_version:
            # loud quarantine, never silent passthrough
            self.mismatch_count += 1
            self.quarantine.append(span)
            raise SemconvVersionMismatchError(
                f"emitter version {span.declared_semconv_version!r} != "
                f"processor version {self.configured_version!r}; "
                f"span quarantined, mismatch_count={self.mismatch_count}"
            )
        required = REQUIRED_KEYS_BY_VERSION[self.configured_version]
        missing = required - span.attributes.keys()
        if missing:
            raise SemconvVersionMismatchError(
                f"span claims {self.configured_version!r} but is missing "
                f"required keys: {sorted(missing)}"
            )
        if (self.configured_version == "1.31.0"
                and span.attributes.get("gen_ai.operation.name")
                not in VALID_OPERATIONS_1_31):
            raise SemconvVersionMismatchError(
                f"gen_ai.operation.name={span.attributes.get('gen_ai.operation.name')!r} "
                f"not in {sorted(VALID_OPERATIONS_1_31)} for version "
                f"{self.configured_version!r}"
            )

    def ingest(self, span: ToolCallSpan) -> dict:
        self.validate(span)
        # safe to apply directional renames only after version match is proven
        return dict(span.attributes)


# Reproduces the observed silent-exclusion failure: legacy emitter, new collector.
legacy_span = ToolCallSpan(
    attributes={
        "gen_ai.system": "openai",
        "gen_ai.operation.name": "execute_tool",  # legacy emitter omitted this
        "gen_ai.tool.name": "search",
        "gen_ai.usage.prompt_tokens": 8120,
        "gen_ai.usage.completion_tokens": 240,
    },
    declared_semconv_version="1.27.0",
)
processor = CollectorProcessor(configured_version="1.31.0")
try:
    processor.ingest(legacy_span)
except SemconvVersionMismatchError as e:
    # correct behavior: alert, do not let the span reach the success-rate dashboard
    print(f"ALERT: {e}")
    assert processor.mismatch_count == 1
