# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-the-causal-parent-link-when-opentelemetry-genai-spans-cross-an-async-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-the-causal-parent-link-when-opentelemetry-genai-spans-cross-an-async-tool-call-boundary.warrant.json
# Markdown SHA-256:   acee990b5e7b9e586292c342c1b49cf71ba98b0cfeb9755bef9752e3c583ad93
# Code AST SHA-256:   03ed465833ef672c60720d17166948723f61ce776c93400b89ef25d53315663b
# Verified Classes:   CausalParentCorruption, SpanContext, ToolDispatch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalParentCorruption(RuntimeError):
    """Raised when a gen_ai.tool.call span's parent resolves to a synthetic
    executor hop despite a serialized decision-context being available."""
    pass


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


@dataclass(frozen=True)
class ToolDispatch:
    tool_name: str
    # Context captured at the moment the tool-call was parsed from model output.
    decision_context: Optional[SpanContext]
    # Context ambient at execution time (may be a synthetic executor hop).
    ambient_context: Optional[SpanContext]


def resolve_tool_call_parent(dispatch: ToolDispatch, synthetic_hop_ids: set[str]) -> SpanContext:
    """Enforce the invariant: the tool.call parent must be the originating
    gen_ai.chat span, never a synthetic executor hop, when a decision context exists."""
    if dispatch.decision_context is None:
        # No model-reasoning parent: executor hop is legitimately the parent.
        if dispatch.ambient_context is None:
            raise CausalParentCorruption(
                f"tool {dispatch.tool_name!r} has neither decision nor ambient context"
            )
        return dispatch.ambient_context

    decision = dispatch.decision_context
    ambient = dispatch.ambient_context

    # If ambient agrees with decision, nothing to override.
    if ambient is not None and ambient.span_id == decision.span_id:
        return decision

    # Ambient disagrees. If ambient is a synthetic executor hop, it must NOT win.
    if ambient is not None and ambient.span_id in synthetic_hop_ids:
        # Decision context is authoritative; override the ambient hop.
        return decision

    # Ambient disagrees and is not a known synthetic hop: ambiguous, refuse to guess.
    if ambient is not None and ambient.span_id != decision.span_id:
        raise CausalParentCorruption(
            f"tool {dispatch.tool_name!r}: ambient parent {ambient.span_id} "
            f"conflicts with decision parent {decision.span_id} and is not a "
            f"registered synthetic hop; causal edge cannot be resolved safely"
        )

    return decision


def emit_tool_call_span(dispatch: ToolDispatch, synthetic_hop_ids: set[str]) -> SpanContext:
    parent = resolve_tool_call_parent(dispatch, synthetic_hop_ids)
    # Span creation would use `parent` as parent_span_id here.
    return parent
