# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-attribute-loss-when-opentelemetry-genai-semantic-conventions-are-emitted-through-a-non-conformant-exporter.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-span-attribute-loss-when-opentelemetry-genai-semantic-conventions-are-emitted-through-a-non-conformant-exporter.warrant.json
# Markdown SHA-256:   1cd98da7edb18010e4c3b40bcd22146b1674bde486ddd9424434912c167156d8
# Code AST SHA-256:   1532f5563e80a12ba3d04d854de5d8a4b6acd9dfe5e37e9c697e4734c78051e4
# Verified Classes:   GenAISpanSemanticLoss, SpanRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping, Iterable


class GenAISpanSemanticLoss(RuntimeError):
    """Raised when a gen_ai.* span is missing required attributes for its operation,
    with no dropped-attribute marker to signal degradation."""
    pass


# Required attributes per gen_ai.operation.name, per the semantic conventions.
REQUIRED_BY_OPERATION: Mapping[str, frozenset] = {
    "invoke_agent": frozenset({"gen_ai.request.model"}),
    "execute_tool": frozenset({"gen_ai.tool.name", "gen_ai.tool.call.id"}),
    "chat": frozenset({"gen_ai.request.model"}),
}


@dataclass
class SpanRecord:
    name: str
    attributes: Mapping[str, object]
    dropped_attributes_count: int = 0
    truncated_attributes: Iterable[str] = field(default_factory=tuple)


def validate_genai_span(span: SpanRecord) -> None:
    op = span.attributes.get("gen_ai.operation.name")
    if op is None:
        # Not a GenAI-semantic span; outside this invariant's scope.
        return

    required = REQUIRED_BY_OPERATION.get(str(op))
    if required is None:
        # Unknown operation: cannot validate, must not silently pass for replay.
        raise GenAISpanSemanticLoss(
            f"span {span.name!r} declares unknown gen_ai.operation.name={op!r}; "
            f"required-attribute set undefined, span non-auditable"
        )

    missing = required - set(span.attributes.keys())
    if not missing:
        return

    # Degradation path: an explicit drop marker makes the loss legible.
    if span.dropped_attributes_count > 0:
        return

    raise GenAISpanSemanticLoss(
        f"span {span.name!r} (operation={op!r}) is missing required attributes "
        f"{sorted(missing)} with dropped_attributes_count=0; "
        f"trace is structurally valid but semantically corrupt and must not be replayed"
    )


def gate_replay(spans: Iterable[SpanRecord]) -> None:
    """Call before any trace-driven replay or agent self-audit."""
    for span in spans:
        validate_genai_span(span)
