# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-reports-tool-call-spans-without-a-parent-invoke-agent-span-orphaned-genai-telemetry-and-the-span-link-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-reports-tool-call-spans-without-a-parent-invoke-agent-span-orphaned-genai-telemetry-and-the-span-link-invariant.warrant.json
# Markdown SHA-256:   9588fb9a584c43625bd8999e335aafdd55a154e1d56bd23250446b8cf9ffb470
# Code AST SHA-256:   7a0c427095b4220d53380164c78669e095994617b4e150baa3590ff473f77e5d
# Verified Classes:   OrphanedToolSpanError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable, Mapping, Optional


class OrphanedToolSpanError(RuntimeError):
    """Raised when an execute_tool span cannot be attributed to an invoking agent span."""


@dataclass(frozen=True)
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    operation_name: str          # gen_ai.operation.name
    tool_call_id: Optional[str]  # gen_ai.tool.call.id
    attributes: Mapping[str, str]


def validate_tool_attribution(
    spans: Iterable[Span],
    *,
    require_join_key: bool = True,
) -> dict[str, str]:
    """
    Return a mapping of execute_tool span_id -> resolved invoking span_id.
    Raise OrphanedToolSpanError when a tool span cannot be attributed.

    The invariant: every execute_tool span must either (a) have a parent that is
    an invoke_agent span in the same trace, or (b) carry a gen_ai.tool.call.id
    that also appears on exactly one invoke_agent/chat span in the same trace.
    """
    by_trace: dict[str, list[Span]] = {}
    for s in spans:
        by_trace.setdefault(s.trace_id, []).append(s)

    resolved: dict[str, str] = {}

    for trace_id, trace_spans in by_trace.items():
        invoking_by_call_id: dict[str, list[Span]] = {}
        for s in trace_spans:
            if s.operation_name in ("invoke_agent", "chat") and s.tool_call_id:
                invoking_by_call_id.setdefault(s.tool_call_id, []).append(s)

        span_ids = {s.span_id for s in trace_spans}

        for s in trace_spans:
            if s.operation_name != "execute_tool":
                continue

            parent_ok = (
                s.parent_span_id is not None
                and s.parent_span_id in span_ids
                and any(
                    p.span_id == s.parent_span_id and p.operation_name == "invoke_agent"
                    for p in trace_spans
                )
            )
            if parent_ok:
                resolved[s.span_id] = s.parent_span_id  # type: ignore[assignment]
                continue

            if not require_join_key:
                continue

            candidates = invoking_by_call_id.get(s.tool_call_id or "", [])
            if len(candidates) == 1:
                resolved[s.span_id] = candidates[0].span_id
                continue

            raise OrphanedToolSpanError(
                "execute_tool span {span} in trace {trace} has parent {parent!r} "
                "which is not an invoke_agent span, and gen_ai.tool.call.id {call!r} "
                "resolved to {n} invoking spans (expected exactly 1). "
                "Quarantine this span; do not re-parent by timestamp.".format(
                    span=s.span_id,
                    trace=trace_id,
                    parent=s.parent_span_id,
                    call=s.tool_call_id,
                    n=len(candidates),
                )
            )

    return resolved
