# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-loss-at-the-agent-to-tool-span-boundary-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-loss-at-the-agent-to-tool-span-boundary-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   3781d14b61b41ea8dfe1f633b9512bb9c7d059a36b420f6ecdda3be2c446c28e
# Code AST SHA-256:   4829732e99fcf86f91ae711893e4762098023676d5f068f378bb8ba24973bab9
# Verified Classes:   TraceContextContinuityError, SpanContext
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceContextContinuityError(RuntimeError):
    """Raised when a non-root GenAI operation span is created without a parent."""


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: str | None


def assert_tool_span_continuity(
    ctx: SpanContext,
    gen_ai_operation_name: str,
    synchronous: bool,
) -> None:
    # execute_tool is, by the GenAI causal model, always a child of an
    # invoke_agent/chat span. A missing parent means traceparent was dropped
    # at the transport boundary and the SDK silently re-rooted the trace.
    if gen_ai_operation_name == "execute_tool" and synchronous:
        if not ctx.parent_span_id:
            raise TraceContextContinuityError(
                "execute_tool span created with no parent (trace_id="
                f"{ctx.trace_id}, span_id={ctx.span_id}); traceparent was "
                "not propagated across the tool transport boundary. "
                "Refusing to emit a re-rooted span that severs the "
                "invoke_agent -> execute_tool causal chain."
            )
    # Non-synchronous tools may legitimately be correlated by business key
    # rather than shared trace ID; that case is out of scope for this check.


def emit_tool_span(
    ctx: SpanContext,
    tool_name: str,
    synchronous: bool = True,
) -> None:
    assert_tool_span_continuity(ctx, "execute_tool", synchronous)
    # ... actual span emission with gen_ai.tool.name, gen_ai.operation.name ...
    _ = tool_name
