# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-orphans-its-causal-parent-span-during-genai-semantic-convention-emission.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-orphans-its-causal-parent-span-during-genai-semantic-convention-emission.warrant.json
# Markdown SHA-256:   efd96dc5ab10f8b428516dcca1c08ede3b9889f15ce2de981b6f0bbf6077078c
# Code AST SHA-256:   aa13459ff166447ce485788b189da7b2ee8ccb0b00d596c96861b6d02f808104
# Verified Classes:   OrphanedCausalParentError, SpanRef
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedCausalParentError(RuntimeError):
    """Raised when a tool/child span's causal parent cannot be structurally
    validated against the completion that emitted its tool_call.id."""


@dataclass
class SpanRef:
    span_id: str
    parent_span_id: Optional[str]
    operation: str          # gen_ai.operation.name
    tool_call_id: Optional[str] = None   # set on execute_tool spans
    emitted_tool_call_ids: tuple = ()    # set on chat spans


def open_tool_span(
    tool_call_id: str,
    causal_parent_span_id: str,
    trace: dict[str, SpanRef],
    orchestration_root_id: str,
) -> SpanRef:
    """Open an execute_tool span with explicit causal linkage.

    The causal parent MUST be the chat span whose completion emitted
    tool_call_id. Implicit context propagation is rejected: by the time a
    tool span opens, the chat span has already ended.
    """
    parent = trace.get(causal_parent_span_id)
    if parent is None:
        raise OrphanedCausalParentError(
            f"causal parent {causal_parent_span_id} for tool_call {tool_call_id} "
            f"not present in trace; cannot reconstruct edge"
        )
    if parent.operation != "chat":
        raise OrphanedCausalParentError(
            f"causal parent {parent.span_id} has operation {parent.operation!r}, "
            f"expected 'chat'; tool call {tool_call_id} would be misattributed"
        )
    if tool_call_id not in parent.emitted_tool_call_ids:
        raise OrphanedCausalParentError(
            f"tool_call {tool_call_id} was not emitted by chat span {parent.span_id}; "
            f"emitted={parent.emitted_tool_call_ids}"
        )
    if causal_parent_span_id == orchestration_root_id:
        raise OrphanedCausalParentError(
            f"tool span for {tool_call_id} parented directly to orchestration root; "
            f"this is the async-fan-out failure signature, not a valid causal edge"
        )
    child = SpanRef(
        span_id=f"tool-{tool_call_id}",
        parent_span_id=causal_parent_span_id,
        operation="execute_tool",
        tool_call_id=tool_call_id,
    )
    trace[child.span_id] = child
    return child
