# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-level-genai-span-be-split-before-opentelemetry-export-the-multi-step-agent-trace-invariant-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-level-genai-span-be-split-before-opentelemetry-export-the-multi-step-agent-trace-invariant-failure.warrant.json
# Markdown SHA-256:   61f42cf078dfe3f61e96b2d7a69ffe835fe10a3b0cb97bed437cad272226984e
# Code AST SHA-256:   987552166a1c23857015dd2fb6198a469ff90fc023f564b2353afb7e542a7a84
# Verified Classes:   GenAISpanModelBoundaryError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class GenAISpanModelBoundaryError(RuntimeError):
    """Raised when a span carries GenAI usage/model attributes that do not
    describe the single operation the span names. Exporting such a span
    corrupts cost attribution and response-cardinality metrics downstream."""
    pass


GENAI_USAGE_ATTRS = (
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.request.model",
    "gen_ai.response.finish_reasons",
)


def validate_genai_span(span_name: str, attributes: dict, child_genai_usage_sums: dict | None) -> None:
    """Enforce the attribution invariant before export.

    A span may carry GenAI usage attributes only if those attributes describe
    the single operation the span names. If the span has GenAI children whose
    summed usage equals this span's usage, the span is an aggregate and must
    be stripped to a structural parent.
    """
    present = {k: attributes[k] for k in GENAI_USAGE_ATTRS if k in attributes}

    if not present:
        return  # structural parent or non-GenAI span: fine

    if child_genai_usage_sums is None:
        return  # leaf operation span: usage is authoritative

    span_input = present.get("gen_ai.usage.input_tokens")
    child_input = child_genai_usage_sums.get("gen_ai.usage.input_tokens")

    if span_input is not None and child_input is not None and span_input == child_input:
        raise GenAISpanModelBoundaryError(
            f"span {span_name!r} carries gen_ai.usage.input_tokens={span_input} "
            f"equal to the sum of its GenAI children ({child_input}). "
            "This span is an aggregate, not an operation span. Strip "
            "gen_ai.usage.*, gen_ai.request.model, and gen_ai.response.finish_reasons "
            "and re-export as a structural parent; let children carry the facts."
        )

    if "gen_ai.response.finish_reasons" in present:
        reasons = present["gen_ai.response.finish_reasons"]
        if isinstance(reasons, (list, tuple)) and len(reasons) > 1:
            raise GenAISpanModelBoundaryError(
                f"span {span_name!r} has finish_reasons={reasons!r} with cardinality "
                f"{len(reasons)}. finish_reasons models one response's candidates, "
                "not a sequence of steps. Split into per-step child spans."
            )


def export_span(span_name: str, attributes: dict, child_genai_usage_sums: dict | None, exporter) -> None:
    validate_genai_span(span_name, attributes, child_genai_usage_sums)
    exporter(span_name, attributes)
