# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-genai-span-attribute-collapse-when-opentelemetry-semantic-conventions-mutate-across-collector-versions.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-genai-span-attribute-collapse-when-opentelemetry-semantic-conventions-mutate-across-collector-versions.warrant.json
# Markdown SHA-256:   abea165d50118d0d73b8af5811bb687e07c9cf0b76c013e23aa022fa763df14b
# Code AST SHA-256:   abe1391562fc1f22985f703aa9f8ce1ae3cbee2e79ab5670ee60c5282f5038c4
# Verified Classes:   SemconvSkewError, CanaryResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class SemconvSkewError(RuntimeError):
    """Raised when an emitted GenAI span's load-bearing attributes cannot be
    confirmed in the backend, indicating semconv version drift between the
    emitter and the collector/metrics pipeline."""
    pass


@dataclass
class CanaryResult:
    sentinel: str
    observed: bool
    observed_keys: set


# Keys the platform's spanmetrics/cost pipeline selects on. If the emitter's
# semconv version disagrees with the platform's, these are exactly the keys
# that get silently ignored.
LOAD_BEARING_KEYS = {
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.request.model",
}


def emit_canary_span(emitter, sentinel: str) -> None:
    # Emit under the emitter's current semconv view. Note: we deliberately do
    # NOT normalize here -- the point is to detect what the emitter actually
    # produces, not what it wishes it produced.
    emitter.emit_span(
        name="gen_ai.canary",
        attributes={
            "gen_ai.canary.sentinel": sentinel,
            "gen_ai.usage.input_tokens": 1,
            "gen_ai.usage.output_tokens": 1,
            "gen_ai.request.model": "canary-model",
        },
    )


def assert_semconv_roundtrip(emitter, backend_query, timeout_s: float = 30.0) -> CanaryResult:
    sentinel = f"canary-{int(time.time() * 1000)}"
    emit_canary_span(emitter, sentinel)

    deadline = time.time() + timeout_s
    while time.time() < deadline:
        span = backend_query.find_span_by_attribute("gen_ai.canary.sentinel", sentinel)
        if span is not None:
            observed_keys = set(span.attributes.keys())
            missing = LOAD_BEARING_KEYS - observed_keys
            if missing:
                raise SemconvSkewError(
                    f"Canary span {sentinel} ingested but load-bearing attributes "
                    f"missing in backend: {sorted(missing)}. Emitter and collector "
                    f"semconv versions have diverged; telemetry-derived decisions "
                    f"(budget, cost, SLA) are unsafe until reconciled."
                )
            return CanaryResult(sentinel=sentinel, observed=True, observed_keys=observed_keys)
        time.sleep(1.0)

    raise SemconvSkewError(
        f"Canary span {sentinel} never appeared in backend within {timeout_s}s. "
        f"Cannot confirm telemetry ingestion; refusing to trust emitted GenAI "
        f"attributes for operational decisions."
    )


def guarded_budget_check(emitter, backend_query, local_spend_usd: float, cap_usd: float) -> bool:
    # Hard precondition: never let a local counter authorize spend unless the
    # platform can actually see our usage spans.
    assert_semconv_roundtrip(emitter, backend_query)
    return local_spend_usd < cap_usd
