# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-attribute-collapse-when-a-single-agent-span-fans-out-to-multiple-provider-llm-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-span-attribute-collapse-when-a-single-agent-span-fans-out-to-multiple-provider-llm-calls.warrant.json
# Markdown SHA-256:   a20012de616d4c462b7bdcada9382eafdd04e83bb3b3e5c80aff8b76b5c1c9aa
# Code AST SHA-256:   15eb4a866ca7150b740fed39fe91828ab1904890ee5bbc164febce29ff01ba43
# Verified Classes:   SpanAttributeCollapseError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable

LEAF_ATTRIBUTE_PREFIXES = (
    "gen_ai.request.model",
    "gen_ai.response.model",
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.tool.name",
)

ALLOWED_PARENT_AGGREGATES = frozenset(
    {
        "agent.usage.input_tokens.total",
        "agent.usage.output_tokens.total",
        "agent.usage.attempts_total",
        "agent.usage.attempts_included",
        "agent.models.requested",
        "agent.models.responded",
        "agent.llm_calls.count",
        "agent.tools.invoked",
    }
)


class SpanAttributeCollapseError(RuntimeError):
    """Raised when a parent agent span carries per-attempt leaf attributes."""


@dataclass
class Span:
    name: str
    attributes: dict = field(default_factory=dict)
    children: list["Span"] = field(default_factory=list)


def validate_parent_span(parent: Span) -> None:
    if len(parent.children) <= 1:
        return  # cardinality-one: aggregation is faithful, no violation

    offending = [
        key
        for key in parent.attributes
        if key.startswith(LEAF_ATTRIBUTE_PREFIXES) and key not in ALLOWED_PARENT_AGGREGATES
    ]
    if offending:
        raise SpanAttributeCollapseError(
            f"parent span {parent.name!r} with {len(parent.children)} children "
            f"carries per-attempt leaf attributes {sorted(offending)}; "
            f"these must live on child spans only, or be re-emitted under "
            f"the agent.* aggregate namespace"
        )

    scalar_model = parent.attributes.get("agent.models.requested")
    if scalar_model is not None and not isinstance(scalar_model, (list, tuple)):
        raise SpanAttributeCollapseError(
            "agent.models.requested must be a set/array on fan-out parents, "
            f"got scalar {scalar_model!r} which hides fallback routing"
        )


def build_parent_aggregate(children: Iterable[Span]) -> Span:
    children = list(children)
    parent = Span(name="invoke_agent")
    requested = sorted({c.attributes["gen_ai.request.model"] for c in children})
    responded = sorted({c.attributes.get("gen_ai.response.model", c.attributes["gen_ai.request.model"]) for c in children})
    parent.attributes = {
        "agent.llm_calls.count": len(children),
        "agent.models.requested": requested,
        "agent.models.responded": responded,
        "agent.usage.input_tokens.total": sum(
            c.attributes.get("gen_ai.usage.input_tokens", 0) for c in children
        ),
        "agent.usage.output_tokens.total": sum(
            c.attributes.get("gen_ai.usage.output_tokens", 0) for c in children
        ),
        "agent.tools.invoked": sorted(
            {c.attributes["gen_ai.tool.name"] for c in children if "gen_ai.tool.name" in c.attributes}
        ),
    }
    parent.children = children
    validate_parent_span(parent)
    return parent
