# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-without-a-turn-scoped-parent-orphaned-tool-call-links-and-silent-trace-fragmentation-under-opentelemet.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-genai-spans-without-a-turn-scoped-parent-orphaned-tool-call-links-and-silent-trace-fragmentation-under-opentelemet.warrant.json
# Markdown SHA-256:   e97f8f9e2a770371230a096e9cb63093957eaf8fcd1a79482da7ca5fa474a7fd
# Code AST SHA-256:   367bcf9ca1afb133e6d87a2a0a4195cad9c1780c31fbbb831c39979137a869bb
# Verified Classes:   TraceContinuityViolation, Span, ConversationAudit
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict


class TraceContinuityViolation(RuntimeError):
    """Raised when an agent's GenAI span set violates the chosen
    multi-turn continuity invariant (single-trace OR attribute-reconstructable)."""


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    conversation_id: str
    turn_index: int | None = None
    turn_attempt: int | None = None
    operation: str = "chat"


@dataclass
class ConversationAudit:
    spans: list[Span] = field(default_factory=list)

    def validate(self, require_single_trace: bool) -> None:
        by_conv: dict[str, list[Span]] = defaultdict(list)
        for s in self.spans:
            by_conv[s.conversation_id].append(s)

        for conv_id, conv_spans in by_conv.items():
            trace_ids = {s.trace_id for s in conv_spans}
            roots = [s for s in conv_spans if s.parent_span_id is None]

            if require_single_trace:
                # Invariant A: all turns of a conversation share one trace,
                # and exactly one root exists per (conversation, attempt).
                if len(trace_ids) > 1:
                    raise TraceContinuityViolation(
                        f"conversation {conv_id!r} fragmented across "
                        f"{len(trace_ids)} trace_ids under single-trace invariant"
                    )
                attempts = {(s.turn_index, s.turn_attempt) for s in roots}
                if len(attempts) != len(roots):
                    raise TraceContinuityViolation(
                        f"conversation {conv_id!r} has duplicate turn roots "
                        f"not collapsible by (turn_index, turn_attempt)"
                    )
            else:
                # Invariant B: fragmentation allowed, but every span must be
                # reconstructable by conversation.id + turn.index + turn.attempt.
                for s in conv_spans:
                    if s.turn_index is None or s.turn_attempt is None:
                        raise TraceContinuityViolation(
                            f"span {s.span_id} in conversation {conv_id!r} "
                            f"lacks turn.index/turn.attempt; cross-trace "
                            f"reconstruction impossible"
                        )
                keys = [(s.turn_index, s.turn_attempt) for s in roots]
                if len(set(keys)) != len(keys):
                    raise TraceContinuityViolation(
                        f"conversation {conv_id!r} retry roots not disambiguated "
                        f"by attempt; duplicate turn roots will double-count usage"
                    )


def emit_turn(audit: ConversationAudit, *, conversation_id: str,
              trace_id: str, turn_index: int, turn_attempt: int,
              single_trace: bool, prior_trace_id: str | None) -> Span:
    # Enforce invariant at emission time: a cold-started worker that fails to
    # reattach to the conversation's trace silently fragments the chain.
    if single_trace and prior_trace_id is not None and trace_id != prior_trace_id:
        raise TraceContinuityViolation(
            f"turn {turn_index} of {conversation_id!r} opened new trace "
            f"{trace_id} while prior turn used {prior_trace_id}; "
            f"checkpoint trace state was not resumed"
        )
    span = Span(
        trace_id=trace_id,
        span_id=f"sp-{conversation_id}-{turn_index}-{turn_attempt}",
        parent_span_id=None,
        conversation_id=conversation_id,
        turn_index=turn_index,
        turn_attempt=turn_attempt,
    )
    audit.spans.append(span)
    return span
