# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-tool-call-latency-when-opentelemetry-genai-spans-collapse-a-multi-turn-agent-trajectory-into-a-single-parent-span.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-tool-call-latency-when-opentelemetry-genai-spans-collapse-a-multi-turn-agent-trajectory-into-a-single-parent-span.warrant.json
# Markdown SHA-256:   dd5c07181eae6f9778f941415b49ea2b6a6271586e7509bbd46c6140329b8cae
# Code AST SHA-256:   457f309e2daa0ab57600c95330f4136521afe4760c53d6e586d45040f4f03c27
# Verified Classes:   TrajectoryAttributionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TrajectoryAttributionError(RuntimeError):
    """Raised when an aggregate agent span violates the per-turn child invariant."""
    pass


def validate_trajectory_span(span: dict) -> None:
    """
    Enforce: an invoke_agent span covering N>1 model invocations must have
    N child chat spans, and parent usage must equal the sum of child usage.
    """
    op = span.get("attributes", {}).get("gen_ai.operation.name")
    if op != "invoke_agent":
        return

    children = span.get("children", [])
    chat_children = [
        c for c in children
        if c.get("attributes", {}).get("gen_ai.operation.name") == "chat"
    ]
    tool_children = [
        c for c in children
        if c.get("attributes", {}).get("gen_ai.operation.name") == "execute_tool"
    ]

    # Heuristic for multi-turn: more than one tool call, or explicit turn count.
    turn_count = span.get("attributes", {}).get("gen_ai.agent.turn_count")
    if turn_count is None:
        turn_count = max(1, len(tool_children))

    if turn_count > 1 and len(chat_children) != turn_count:
        raise TrajectoryAttributionError(
            f"invoke_agent span {span.get('name')!r} covers {turn_count} turns "
            f"but emitted {len(chat_children)} chat children; tool-call latency "
            f"cannot be attributed to a turn. Emit one chat span per invocation "
            f"or mark the span non-atomic."
        )

    parent_in = span["attributes"].get("gen_ai.usage.input_tokens", 0)
    child_in = sum(
        c["attributes"].get("gen_ai.usage.input_tokens", 0) for c in chat_children
    )
    if chat_children and parent_in != child_in:
        raise TrajectoryAttributionError(
            f"usage sum invariant violated: parent input_tokens={parent_in} "
            f"!= sum(chat children)={child_in}. Parent aggregates must be "
            f"exactly reconstructible from per-turn children."
        )
