# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-a-span-whose-semantic-convention-attributes-drift-from-the-schema-the-trace-stitcher-was-compiled-against.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-a-span-whose-semantic-convention-attributes-drift-from-the-schema-the-trace-stitcher-was-compiled-against.warrant.json
# Markdown SHA-256:   c941e65311d6f3f80a0c9eb980d12d77ec3a352eb600bd0898a6b50f810a2447
# Code AST SHA-256:   41e96e3ef7fb47288a8d292c841f1ae11481d1899f4f821f92352130514265b2
# Verified Classes:   SchemaDriftError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

"""Stitcher-side guard: refuse to join a span whose conversation identity
is carried under a key the stitcher's alias table does not recognize."""

from dataclasses import dataclass
from typing import Mapping, Sequence


class SchemaDriftError(RuntimeError):
    """Raised when a span's identity attributes are not addressable by the
    stitcher's alias table. This is a fail-closed signal, not a drop."""


# Alias table: any key an emitter might use -> canonical join key.
CONVERSATION_ALIASES = {
    "gen_ai.conversation.id": "gen_ai.conversation.id",
    "gen_ai.session.id": "gen_ai.conversation.id",
    "session.id": "gen_ai.conversation.id",
}

AGENT_ALIASES = {
    "gen_ai.agent.id": "gen_ai.agent.id",
    "gen_ai.agent.name": "gen_ai.agent.id",
    "agent.name": "gen_ai.agent.id",
}


@dataclass(frozen=True)
class Span:
    name: str
    attributes: Mapping[str, str]


def resolve(span: Span, aliases: Mapping[str, str], canonical: str) -> str:
    found = [k for k in span.attributes if aliases.get(k) == canonical]
    if not found:
        raise SchemaDriftError(
            f"span {span.name!r} carries no attribute resolving to {canonical!r}; "
            f"attributes={dict(span.attributes)}"
        )
    # Multiple aliases resolving to the same canonical key must agree.
    values = {span.attributes[k] for k in found}
    if len(values) > 1:
        raise SchemaDriftError(
            f"span {span.name!r} carries conflicting {canonical!r} values "
            f"across aliases {found}: {values}"
        )
    return values.pop()


def stitch_key(span: Span) -> tuple[str, str]:
    return (
        resolve(span, AGENT_ALIASES, "gen_ai.agent.id"),
        resolve(span, CONVERSATION_ALIASES, "gen_ai.conversation.id"),
    )


def assert_replay_complete(
    conversation_id: str,
    replay_span_count: int,
    all_partitions: Sequence[Sequence[Span]],
) -> None:
    """Verifier gate: a pass verdict is only legal if the replay set covers
    every span in the conversation, including quarantined partitions."""
    total = 0
    for partition in all_partitions:
        for span in partition:
            if resolve(span, CONVERSATION_ALIASES, "gen_ai.conversation.id") == conversation_id:
                total += 1
    if replay_span_count != total:
        raise SchemaDriftError(
            f"replay set for {conversation_id!r} has {replay_span_count} spans "
            f"but {total} exist across partitions; refusing to render verdict"
        )
