# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-a-tool-call-span-and-its-parent-agent-span-under-opentelemetry-genai-semantic-conventions.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causal-linkage-between-a-tool-call-span-and-its-parent-agent-span-under-opentelemetry-genai-semantic-conventions.warrant.json
# Markdown SHA-256:   1686407987ad123011695618e5b4b397f971ca29c3f9a874a0ffbc3ce0303d45
# Code AST SHA-256:   ab62dc6afc828ef0ca77448881eedc8e111e2729fd5776237c3fc2f1cbe21308
# Verified Classes:   CausalLinkageError, SpanContext, ToolDispatch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CausalLinkageError(RuntimeError):
    """Raised when a tool-call span is not correctly parented to its dispatching agent span."""


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


@dataclass(frozen=True)
class ToolDispatch:
    agent_context: SpanContext          # active agent span at dispatch time
    injected_traceparent: str | None    # what was actually put on the wire
    extracted_context: SpanContext | None  # what the receiver reconstructed
    tool_span_context: SpanContext      # the context the tool span was actually started with


def verify_causal_linkage(dispatch: ToolDispatch) -> None:
    """
    Enforce the GenAI hierarchy invariant: a tool-call span must be a child of the
    agent span that was active at dispatch, in the same trace.

    This must be called after the tool span is started and before it is ended.
    """
    agent = dispatch.agent_context
    tool = dispatch.tool_span_context

    if dispatch.injected_traceparent is None:
        raise CausalLinkageError(
            f"no traceparent injected at dispatch for agent span {agent.span_id}; "
            "tool span will be orphaned or mis-parented"
        )

    if dispatch.extracted_context is None:
        raise CausalLinkageError(
            f"receiver failed to extract traceparent {dispatch.injected_traceparent!r}; "
            "start_span() will use the receiver's root context"
        )

    if tool.trace_id != agent.trace_id:
        raise CausalLinkageError(
            f"trace mismatch: tool span trace_id={tool.trace_id} "
            f"!= agent span trace_id={agent.trace_id}; "
            "likely a cached or stale traceparent on a long-lived tool server"
        )

    if tool.span_id != agent.span_id and tool.span_id != dispatch.extracted_context.span_id:
        # The tool span must either be the extracted parent itself (unlikely) or a
        # child whose parent is the agent span. We check the parent linkage below.
        pass

    # The decisive check: the tool span's parent must be the agent span, not a
    # sibling, not a prior turn's agent span, and not the receiver's root.
    if dispatch.extracted_context.span_id != agent.span_id:
        raise CausalLinkageError(
            f"parent mismatch: extracted parent span_id={dispatch.extracted_context.span_id} "
            f"!= active agent span_id={agent.span_id}; "
            "tool span will be attributed to the wrong agent turn"
        )


def dispatch_tool_call(
    agent_context: SpanContext,
    inject,
    transport,
    extract,
    start_span,
) -> ToolDispatch:
    """
    Reference dispatch path that preserves the GenAI causal invariant across an
    out-of-process boundary (MCP stdio, subprocess, HTTP).
    """
    # 1. Inject from the ACTIVE agent span — never from a cached/module-level value.
    traceparent = inject(agent_context)
    if traceparent is None:
        raise CausalLinkageError(
            f"propagator returned no traceparent for agent span {agent_context.span_id}"
        )

    # 2. Transport intact across the boundary.
    wire_payload = transport(traceparent)

    # 3. Extract on the receiving side from the INBOUND payload.
    extracted = extract(wire_payload)
    if extracted is None:
        raise CausalLinkageError(
            "receiver could not reconstruct a SpanContext from the inbound traceparent"
        )

    # 4. Pass the extracted context EXPLICITLY to start_span — do not rely on
    #    contextvars surviving the process/async boundary.
    tool_span = start_span(context=extracted)

    dispatch = ToolDispatch(
        agent_context=agent_context,
        injected_traceparent=traceparent,
        extracted_context=extracted,
        tool_span_context=tool_span,
    )

    # 5. Enforce the invariant before the span is ended.
    verify_causal_linkage(dispatch)
    return dispatch
