# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-lineage-when-opentelemetry-genai-span-attributes-cross-an-async-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-lineage-when-opentelemetry-genai-span-attributes-cross-an-async-agent-handoff.warrant.json
# Markdown SHA-256:   72c1bfdf2a33a3852768485bf59730f1115ee478ee7909e61e92ec2d6c1f9112
# Code AST SHA-256:   b4dda119c7c5c876d9b7e0fa6c0c497de76a8a9d3c9066f047545a8856922771
# Verified Classes:   GenAiLineageError, ToolCallHandoff
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from typing import Optional

TRACEPARENT_RE = re.compile(
    r"^(?P<version>[0-9a-f]{2})-(?P<trace_id>[0-9a-f]{32})-(?P<span_id>[0-9a-f]{16})-(?P<flags>[0-9a-f]{2})$"
)
AMBIENT_GENAI_ATTRS = ("gen_ai.request.model", "gen_ai.system", "gen_ai.conversation.id")


class GenAiLineageError(RuntimeError):
    """Raised when a deferred tool-call handoff cannot reconstruct its parent gen_ai span."""


@dataclass
class ToolCallHandoff:
    tool_name: str
    call_id: str
    traceparent: Optional[str]
    ambient_attrs: dict = field(default_factory=dict)


def build_tool_span_context(handoff: ToolCallHandoff, worker_local_model: str) -> dict:
    """Validate a deferred gen_ai tool-call handoff before span creation.

    Returns the attributes to stamp on the tool span, or raises if lineage
    cannot be reconstructed from the payload alone.
    """
    if not handoff.traceparent:
        raise GenAiLineageError(
            f"tool call {handoff.call_id!r} has no traceparent; "
            "span would be orphaned from its parent gen_ai LLM span"
        )

    match = TRACEPARENT_RE.match(handoff.traceparent)
    if not match:
        raise GenAiLineageError(
            f"malformed traceparent for tool call {handoff.call_id!r}: {handoff.traceparent!r}"
        )

    # span_id == all-zero means the parent was explicitly invalidated; a tool
    # call cannot have an invalid parent and still be a valid child.
    if match.group("span_id") == "0" * 16:
        raise GenAiLineageError(
            f"tool call {handoff.call_id!r} has a null parent span_id; "
            "cannot establish gen_ai parent-child edge"
        )

    missing = [a for a in AMBIENT_GENAI_ATTRS if a not in handoff.ambient_attrs]
    if missing:
        raise GenAiLineageError(
            f"tool call {handoff.call_id!r} missing ambient gen_ai attributes {missing}; "
            "worker-local state must not be used to fill them"
        )

    # Guard against ambient-state contamination: the payload's model must be
    # the authority, and any worker-local model is ignored by construction.
    payload_model = handoff.ambient_attrs["gen_ai.request.model"]
    if payload_model != worker_local_model:
        # Not fatal on its own, but the divergence must be recorded, not
        # silently resolved in favor of the worker's mutable state.
        handoff.ambient_attrs["gen_ai.lineage.model_divergence"] = worker_local_model

    return {
        "trace_id": match.group("trace_id"),
        "parent_span_id": match.group("span_id"),
        "gen_ai.tool.name": handoff.tool_name,
        "gen_ai.tool.call.id": handoff.call_id,
        **handoff.ambient_attrs,
    }
