# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-genai-tool-call-span-has-become-an-orphaned-causal-island-under-opentelemetry-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-genai-tool-call-span-has-become-an-orphaned-causal-island-under-opentelemetry-semantic-conventions.warrant.json
# Markdown SHA-256:   92648b3ac3ef31c591808d44d7df2e5f8cf899e4db99873e5ef742cbe0ca4464
# Code AST SHA-256:   38c4ba96e4341a08204d989da6cd73ddd97658d1650d6243238558d944d0efc0
# Verified Classes:   OrphanedToolSpanError, SpanHandle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import contextvars
from dataclasses import dataclass


class OrphanedToolSpanError(RuntimeError):
    """Raised when a tool-call span's trace_id diverges from its invoking agent span,
    indicating context was not propagated across an async dispatch boundary."""


@dataclass(frozen=True)
class SpanHandle:
    trace_id: str
    span_id: str
    tool_call_id: str


def start_tool_span(
    tracer,
    invoker: SpanHandle,
    tool_name: str,
    tool_call_id: str,
    dispatch_ctx: contextvars.Context | None,
) -> SpanHandle:
    """Start a tool span inside the invoker's context and verify causal continuity.

    dispatch_ctx must be a copy of the context captured at the agent span, passed
    explicitly across the executor/queue boundary. If None, the boundary dropped it.
    """
    if dispatch_ctx is None:
        raise OrphanedToolSpanError(
            f"tool '{tool_name}' dispatched without a copied context; "
            f"invoker trace_id={invoker.trace_id} would be severed"
        )

    def _start() -> SpanHandle:
        span = tracer.start_span(
            name=f"execute_tool {tool_name}",
            attributes={
                "gen_ai.operation.name": "execute_tool",
                "gen_ai.tool.name": tool_name,
                "gen_ai.tool.call.id": tool_call_id,
            },
        )
        ctx = span.get_span_context()
        return SpanHandle(
            trace_id=format(ctx.trace_id, "032x"),
            span_id=format(ctx.span_id, "016x"),
            tool_call_id=tool_call_id,
        )

    child = dispatch_ctx.run(_start)

    if child.trace_id != invoker.trace_id:
        raise OrphanedToolSpanError(
            f"tool '{tool_name}' (call={tool_call_id}) started a new trace "
            f"{child.trace_id}; expected invoker trace {invoker.trace_id}. "
            f"Context was not propagated across the dispatch boundary."
        )
    return child
