# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-that-drift-from-the-semantic-conventions-across-a-multi-turn-agent-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-span-attributes-that-drift-from-the-semantic-conventions-across-a-multi-turn-agent-trace.warrant.json
# Markdown SHA-256:   bff2d2d74f475807b32ed7f2ff181b795495b4c7ca30aafbb79bd571a0b6e8b7
# Code AST SHA-256:   deeb1d2cdaa48c6bceca0cc46dae776198eeedd8dbe1a4f8e64bd9714195af00
# Verified Classes:   TraceCoherenceError, ConversationState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

# Attributes a downstream consumer may legitimately group by.
GROUPING_KEYS = frozenset({
    "gen_ai.request.model",
    "gen_ai.operation.name",
    "gen_ai.system",
})

# Attributes that mark an explicit, explained transition.
TRANSITION_MARKERS = frozenset({
    "gen_ai.agent.turn.transition",
    "gen_ai.conversation.parent.id",
})


class TraceCoherenceError(RuntimeError):
    """Raised when a span would break the multi-turn reconstruction invariant."""


@dataclass
class ConversationState:
    conversation_id: str
    established: dict = field(default_factory=dict)  # grouping key -> value


def emit_span(
    state: ConversationState,
    attributes: dict,
    *,
    turn_index: int,
) -> dict:
    """Validate and stamp a GenAI span before export.

    Enforces: every grouping key either matches the conversation's established
    value, or the span carries an explicit transition marker.
    """
    if attributes.get("gen_ai.conversation.id") != state.conversation_id:
        raise TraceCoherenceError(
            f"turn {turn_index}: conversation.id mismatch "
            f"({attributes.get('gen_ai.conversation.id')!r} != "
            f"{state.conversation_id!r}); refusing cross-conversation merge"
        )

    has_marker = bool(TRANSITION_MARKERS & attributes.keys())

    for key in GROUPING_KEYS & attributes.keys():
        current = attributes[key]
        prior: Optional[str] = state.established.get(key)

        if prior is None:
            state.established[key] = current
            continue

        if current != prior and not has_marker:
            raise TraceCoherenceError(
                f"turn {turn_index}: grouping key {key!r} changed "
                f"{prior!r} -> {current!r} without a transition marker; "
                f"this trace would fragment or mis-aggregate downstream. "
                f"Emit one of {sorted(TRANSITION_MARKERS)} on this span, "
                f"or start a new conversation.id segment."
            )

        if current != prior and has_marker:
            # Transition is explained; update the established baseline.
            state.established[key] = current

    return {"turn": turn_index, **attributes}


# --- Failure trace reproduction -------------------------------------------

def replay_fallback_trace() -> None:
    state = ConversationState(conversation_id="S")
    turn6 = {"gen_ai.request.model": "primary-large",
             "gen_ai.usage.input_tokens": 18000}
    emit_span(state, {"gen_ai.conversation.id": "S", **turn6}, turn_index=6)

    # Turn 7: fallback model, truncated context, NO transition marker.
    turn7 = {"gen_ai.request.model": "fallback-small",
             "gen_ai.usage.input_tokens": 10800}
    emit_span(state, {"gen_ai.conversation.id": "S", **turn7}, turn_index=7)


if __name__ == "__main__":
    try:
        replay_fallback_trace()
    except TraceCoherenceError as e:
        print(f"BLOCKED before export: {e}")
