# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-genai-span-whose-gen-ai-usage-input-tokens-was-derived-from-a-provider-reported-counter-rathe.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-close-a-genai-span-whose-gen-ai-usage-input-tokens-was-derived-from-a-provider-reported-counter-rathe.warrant.json
# Markdown SHA-256:   1e89fa13318dfb4d6191dbd587061393bc1b54c66a912ce53e8c54cca219bec6
# Code AST SHA-256:   c32e0e0bce4ecf2e75999cfe7a193bd0ddcba0d573d3f474ddff16b414b58cde
# Verified Classes:   TokenProvenanceViolation, ChildUsage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TokenProvenanceViolation(RuntimeError):
    """Raised when a turn span would close with an aggregate token total
    that has no single tokenizer provenance."""
    pass


@dataclass(frozen=True)
class ChildUsage:
    model: str
    tokenizer: str
    input_tokens: int
    source: str  # "provider" | "local_tokenizer"


def close_turn_span(
    parent_model: str | None,
    parent_tokenizer: str | None,
    children: list[ChildUsage],
) -> dict:
    if not children:
        return {}

    provenances = {(c.model, c.tokenizer) for c in children}

    if len(provenances) == 1:
        model, tokenizer = next(iter(provenances))
        total = sum(c.input_tokens for c in children)
        if parent_model is not None and parent_model != model:
            # Single provenance but parent mislabels the model.
            raise TokenProvenanceViolation(
                f"parent model {parent_model!r} != child provenance {model!r}; "
                f"aggregate would be misattributed"
            )
        if parent_model is None:
            return {
                "gen_ai.usage.input_tokens": total,
                "gen_ai.usage.aggregate_provenance": tokenizer,
            }
        return {"gen_ai.usage.input_tokens": total}

    # Multiple provenances.
    provider_sourced = [c for c in children if c.source == "provider"]
    local_sourced = [c for c in children if c.source == "local_tokenizer"]

    if parent_model is not None and provider_sourced and local_sourced:
        raise TokenProvenanceViolation(
            f"turn span declares model {parent_model!r} but aggregates "
            f"{len(provider_sourced)} provider-counter and "
            f"{len(local_sourced)} local-tokenizer children; "
            f"total is not attributable to a single tokenizer"
        )

    if parent_model is not None and len({c.model for c in children}) > 1:
        raise TokenProvenanceViolation(
            f"turn span declares model {parent_model!r} but children span "
            f"models {sorted({c.model for c in children})}; "
            f"refusing to emit model-scoped aggregate"
        )

    # Container span: no model declared, mixed provenance.
    # Drop the model-scoped aggregate; retain children for query-time sum.
    return {"gen_ai.usage.aggregate_dropped": "mixed_provenance"}
