# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-token-accounting-attributes-were-derived-from-a-different-model-than-the-one-named-in.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-genai-span-whose-token-accounting-attributes-were-derived-from-a-different-model-than-the-one-named-in.warrant.json
# Markdown SHA-256:   c0734b7e3116f79c52e8aa984f2a90efcd154956106024cc82bc111c1cafc607
# Code AST SHA-256:   8892c844d5103a327575edd57f8dd6347d5e60b62e946f0a442d0f3329bb96c8
# Verified Classes:   GenAISpanProvenanceError, Attempt, GenAISpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

class GenAISpanProvenanceError(RuntimeError):
    """Raised when a GenAI span's token-accounting provenance cannot be
    reconciled with its model identity."""
    pass

@dataclass
class Attempt:
    model: str
    input_tokens: int
    output_tokens: int

@dataclass
class GenAISpan:
    request_model: str
    response_model: Optional[str] = None
    input_tokens: Optional[int] = None
    output_tokens: Optional[int] = None
    routing_fallback: bool = False
    routing_attempts: int = 1

def validate_and_emit(span: GenAISpan, attempts: list[Attempt]) -> list[GenAISpan]:
    """Enforce the conjunctive provenance invariant.

    Returns the list of spans that should actually be emitted. May be the
    original span (accept), a set of per-attempt child spans (split), or a
    relabeled span (relabel). Raises if the tuple is incoherent and
    undecomposable.
    """
    # Case 1: single-model, single-attempt -> accept as-is.
    if len(attempts) <= 1 and (span.routing_attempts <= 1):
        if span.input_tokens is None or span.output_tokens is None:
            raise GenAISpanProvenanceError(
                f"single-attempt span for {span.request_model!r} is missing "
                f"usage attributes; cannot emit a partial measurement"
            )
        return [span]

    # Case 2: multiple attempts observed -> split into per-attempt children.
    distinct_models = {a.model for a in attempts}
    if len(distinct_models) > 1:
        emitted = []
        for i, a in enumerate(attempts):
            emitted.append(GenAISpan(
                request_model=a.model,
                response_model=a.model,
                input_tokens=a.input_tokens,
                output_tokens=a.output_tokens,
                routing_fallback=True,
                routing_attempts=len(attempts),
            ))
        # Parent/aggregate span must NOT carry usage attributes.
        parent = GenAISpan(
            request_model=span.request_model,
            response_model=span.response_model,
            input_tokens=None,
            output_tokens=None,
            routing_fallback=True,
            routing_attempts=len(attempts),
        )
        emitted.append(parent)
        return emitted

    # Case 3: multiple attempts, single model -> relabel is safe only if
    # the aggregate count actually matches the per-attempt sum.
    total_in = sum(a.input_tokens for a in attempts)
    total_out = sum(a.output_tokens for a in attempts)
    if (span.input_tokens, span.output_tokens) != (total_in, total_out):
        raise GenAISpanProvenanceError(
            f"aggregate usage ({span.input_tokens},{span.output_tokens}) does "
            f"not match per-attempt sum ({total_in},{total_out}) for model "
            f"{span.request_model!r}; provenance is unreconcilable"
        )
    span.routing_fallback = True
    span.routing_attempts = len(attempts)
    return [span]
