# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-fork-span-lineage-when-a-tool-call-child-span-outlives-its-parent-turn-in-opentelemetry-genai-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-fork-span-lineage-when-a-tool-call-child-span-outlives-its-parent-turn-in-opentelemetry-genai-traces.warrant.json
# Markdown SHA-256:   73bbdc4bd8464b700d7bde14ed4b05ea0c0332132ce14828e3d01c47ad086c3f
# Code AST SHA-256:   7db765beeb58a041601c3b53994dae13aae99eaa6f1413435108713b479a6523
# Verified Classes:   LineageForkError, Span
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class LineageForkError(RuntimeError):
    """Raised when a tool span's causal predecessor cannot be resolved
    unambiguously under the GenAI span-containment invariant."""


@dataclass
class Span:
    span_id: str
    parent_span_id: Optional[str]
    end_time_ms: Optional[float]  # None while open
    attributes: dict
    links: list  # list of (target_span_id, attributes)


def emit_tool_span(
    tool_span: Span,
    turn_span: Span,
    call_id: str,
    prior_call_ids: set[str],
    parent_flushed: bool,
) -> Span:
    """Decide parentage vs. fork for a GenAI execute_tool span.

    Enforces: exactly one resolvable causal predecessor, by parentage if
    contained, else by SpanLink to the originating turn.
    """
    if tool_span.end_time_ms is None:
        raise LineageForkError(
            f"tool span {tool_span.span_id} emitted without end_time; "
            "cannot evaluate containment predicate"
        )

    # C1: temporal containment
    contained = (
        turn_span.end_time_ms is not None
        and tool_span.end_time_ms <= turn_span.end_time_ms
    )
    # C2: parent liveness at export
    parent_alive = not parent_flushed
    # C3: lineage uniqueness (retry detection)
    is_retry = call_id in prior_call_ids

    fork_required = (not contained) or (not parent_alive) or is_retry

    if not fork_required:
        tool_span.parent_span_id = turn_span.span_id
        tool_span.attributes["gen_ai.tool.call.id"] = call_id
        return tool_span

    # Fork: emit a continuation span as the real-time parent, link the
    # originating turn to preserve the cross-turn causal edge.
    continuation = Span(
        span_id=f"{tool_span.span_id}.cont",
        parent_span_id=None,  # root-adjacent; sibling of turn_span
        end_time_ms=tool_span.end_time_ms,
        attributes={
            "gen_ai.tool.call.id": call_id,
            "gen_ai.lineage.forked": True,
        },
        links=[(turn_span.span_id, {"gen_ai.tool.call.id": call_id})],
    )
    tool_span.parent_span_id = continuation.span_id
    tool_span.attributes["gen_ai.tool.call.id"] = call_id
    if is_retry:
        tool_span.attributes["gen_ai.tool.retry_of"] = call_id

    # Post-export guardrail: the link must resolve, or lineage is lost.
    if not continuation.links:
        raise LineageForkError(
            f"forked tool span {tool_span.span_id} has no link to "
            f"turn {turn_span.span_id}; causal edge unresolvable"
        )
    return tool_span
