# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-for-a-tool-call-graph-whose-parent-gen-ai-conversation-id-is-rebound-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-emits-opentelemetry-genai-spans-for-a-tool-call-graph-whose-parent-gen-ai-conversation-id-is-rebound-mid-flight.warrant.json
# Markdown SHA-256:   244234fdba8235ffa5189f550dfe355ec8afa95a1805a65eb69e21c50a2d3c5b
# Code AST SHA-256:   5acb86f1642fc571e981d5b837dc20a5917d00fa0d0cef5876dcaf41e0f952a3
# Verified Classes:   ConversationFractureError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ConversationFractureError(RuntimeError):
    """Raised when a trace's conversation.id partition does not match its causal graph."""


@dataclass(frozen=True)
class Span:
    span_id: str
    parent_span_id: str | None
    trace_id: str
    conversation_id: str
    operation_name: str
    agent_id: str | None = None
    attributes: dict = field(default_factory=dict)


def validate_conversation_partition(spans: Iterable[Span]) -> None:
    """
    Enforce the GenAI trace-level invariant:
      cardinality(conversation.id per trace_id) == 1
      OR every non-primary segment is introduced by an invoke_agent span
         with a distinct gen_ai.agent.id.
    Raises ConversationFractureError on violation.
    """
    by_trace: dict[str, list[Span]] = {}
    for s in spans:
        by_trace.setdefault(s.trace_id, []).append(s)

    for trace_id, trace_spans in by_trace.items():
        # Root span defines the primary conversation.
        roots = [s for s in trace_spans if s.parent_span_id is None]
        if len(roots) != 1:
            raise ConversationFractureError(
                f"trace {trace_id}: expected exactly 1 root span, found {len(roots)}"
            )
        primary_conv = roots[0].conversation_id
        primary_agent = roots[0].agent_id

        # Find every span whose conversation.id differs from primary.
        foreign = [s for s in trace_spans if s.conversation_id != primary_conv]
        if not foreign:
            continue

        # Each foreign segment must be introduced by an invoke_agent span
        # that (a) is itself the first span in its segment, and (b) names a
        # distinct agent.
        for s in foreign:
            is_boundary = (
                s.operation_name == "invoke_agent"
                and s.agent_id is not None
                and s.agent_id != primary_agent
            )
            if not is_boundary:
                parent = next(
                    (p for p in trace_spans if p.span_id == s.parent_span_id), None
                )
                raise ConversationFractureError(
                    f"trace {trace_id}: span {s.span_id} "
                    f"(op={s.operation_name}) carries conversation.id "
                    f"{s.conversation_id!r} but parent "
                    f"{s.parent_span_id!r} carries {primary_conv!r}; "
                    f"no invoke_agent boundary with distinct agent_id. "
                    f"Rebind is a continuation, not a delegation."
                )


def record_span(span: Span, ledger: list[Span]) -> None:
    """Append a span to the trace ledger, validating the partition on each write."""
    ledger.append(span)
    try:
        validate_conversation_partition(ledger)
    except ConversationFractureError:
        # Annotate the offending span so the collector can attribute the fault,
        # then re-raise: the trace must not be exported as healthy.
        span.attributes["gen_ai.conversation.fractured"] = True
        raise
