# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-span-parent-span-attribute-inheritance-across-a-mid-trace-model-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-emit-a-genai-span-parent-span-attribute-inheritance-across-a-mid-trace-model-swap.warrant.json
# Markdown SHA-256:   904842c2ef85e7a5fcb61f28336eb21a008478b450505b340fa7050b5a1cc947
# Code AST SHA-256:   083e40fb600037b204a0003937460dee5c6042ac7976e3e947897850ac6be18c
# Verified Classes:   GenAISpanContinuityError, SpanRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAISpanContinuityError(RuntimeError):
    """Raised when a span asserts a model identity that its subtree contradicts."""
    pass


@dataclass
class SpanRecord:
    name: str
    attributes: dict
    children: list = field(default_factory=list)

    def model_identity(self) -> Optional[str]:
        return self.attributes.get("gen_ai.request.model")

    def response_model(self) -> Optional[str]:
        return self.attributes.get("gen_ai.response.model")

    def output_tokens(self) -> int:
        return int(self.attributes.get("gen_ai.usage.output_tokens", 0))

    def descendants(self):
        for child in self.children:
            yield child
            yield from child.descendants()


def assert_model_identity_invariant(span: SpanRecord) -> None:
    """
    Enforce: a span carrying gen_ai.request.model and aggregate gen_ai.usage.*
    must not have any descendant whose gen_ai.response.model differs from it.
    """
    parent_model = span.model_identity()
    has_usage = "gen_ai.usage.output_tokens" in span.attributes

    if parent_model is None or not has_usage:
        # Structural span or leaf; invariant does not bind here.
        return

    offending = []
    for desc in span.descendants():
        desc_model = desc.response_model() or desc.model_identity()
        if desc_model is not None and desc_model != parent_model:
            offending.append((desc.name, desc_model, desc.output_tokens()))

    if offending:
        total_foreign = sum(t for _, _, t in offending)
        raise GenAISpanContinuityError(
            f"Span '{span.name}' asserts gen_ai.request.model={parent_model!r} "
            f"with aggregate gen_ai.usage.output_tokens={span.output_tokens()}, "
            f"but {len(offending)} descendant(s) executed on a different model "
            f"({total_foreign} tokens misattributed): {offending}. "
            f"Drop model/usage attributes from the parent or fragment the span "
            f"per model segment before emitting."
        )


def emit_turn_span(span: SpanRecord) -> SpanRecord:
    # Called immediately before the span is handed to the exporter.
    assert_model_identity_invariant(span)
    return span
