# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-agent-turn-span-chain-when-opentelemetry-genai-semantic-conventions-silently-drop-tool-call-parentage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-agent-turn-span-chain-when-opentelemetry-genai-semantic-conventions-silently-drop-tool-call-parentage.warrant.json
# Markdown SHA-256:   66edb4d20f77e90a51e7c0e699bcd7c2569836949c370b1ac0d3d623322b2af2
# Code AST SHA-256:   c488b14cb14d973907aed9664c0a011a5f276cb5f00f0e3d1293f461feb8e5ea
# Verified Classes:   BrokenToolSpanParentage
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class BrokenToolSpanParentage(RuntimeError):
    """Raised when an execute_tool span cannot resolve a valid parent at emission time."""
    pass


def emit_tool_span(
    tool_name: str,
    trace_id: str,
    active_parent_span_id: str | None,
    active_parent_trace_id: str | None,
    active_parent_operation: str | None,
) -> dict:
    """
    Enforce the parentage invariant for GenAI execute_tool spans.

    A tool span may only be emitted as a child of an invoke_agent/chat span
    that shares its trace_id. Otherwise it must be emitted as a flagged orphan,
    never as a silent root.
    """
    valid_parent_ops = {"invoke_agent", "chat"}

    has_parent = active_parent_span_id is not None
    same_trace = active_parent_trace_id == trace_id
    valid_op = active_parent_operation in valid_parent_ops

    if has_parent and same_trace and valid_op:
        return {
            "name": "execute_tool",
            "trace_id": trace_id,
            "parent_span_id": active_parent_span_id,
            "attributes": {
                "gen_ai.operation.name": "execute_tool",
                "gen_ai.tool.name": tool_name,
            },
        }

    # Context is empty, leaked from another trace, or points at a non-agent span.
    # We refuse to emit a silent root: mark it explicitly broken.
    if has_parent and not same_trace:
        raise BrokenToolSpanParentage(
            f"tool={tool_name} trace_id={trace_id} has parent span "
            f"{active_parent_span_id} from foreign trace {active_parent_trace_id}; "
            f"context leak across turns"
        )

    if has_parent and same_trace and not valid_op:
        raise BrokenToolSpanParentage(
            f"tool={tool_name} trace_id={trace_id} parent span "
            f"{active_parent_span_id} has operation={active_parent_operation!r}, "
            f"expected one of {valid_parent_ops}"
        )

    # No active parent at all: emit flagged orphan for the dead-letter channel.
    return {
        "name": "execute_tool",
        "trace_id": trace_id,
        "parent_span_id": None,
        "attributes": {
            "gen_ai.operation.name": "execute_tool",
            "gen_ai.tool.name": tool_name,
            "gen_ai.tool.parent_link": "broken",
        },
    }


def rollup_per_turn(spans: list[dict]) -> dict:
    """Per-turn rollup that must exclude or surface broken-link spans."""
    totals: dict[str, float] = {}
    broken = 0
    for s in spans:
        if s["attributes"].get("gen_ai.tool.parent_link") == "broken":
            broken += 1
            continue
        parent = s.get("parent_span_id")
        if parent is None:
            raise BrokenToolSpanParentage(
                f"span {s['trace_id']} emitted as silent root without broken-link marker"
            )
        totals[parent] = totals.get(parent, 0.0) + s["attributes"].get("duration_ms", 0.0)
    return {"totals": totals, "link_loss_count": broken}
