# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-emit-a-genai-span-that-passes-schema-validation-yet-carries-no-usable-parent-child-causal-chain-across-an-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-emit-a-genai-span-that-passes-schema-validation-yet-carries-no-usable-parent-child-causal-chain-across-an-agent-handoff.warrant.json
# Markdown SHA-256:   0c47709e9e790844c86e7fdb6677368e39e4f7f174fbe906c5c26a096b19e798
# Code AST SHA-256:   a45166fe8c88eb6663696356544ef0bff3dbf794f8c13c9a9708824ce69fe017
# Verified Classes:   ContextContinuityError, ExtractedContext, DispatchRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ContextContinuityError(RuntimeError):
    """Raised when an agent ingress opens a GenAI span without a valid causal parent."""
    pass


@dataclass
class ExtractedContext:
    trace_id: Optional[str]
    span_id: Optional[str]


@dataclass
class DispatchRecord:
    # Recorded by the dispatching agent in the request payload, so the callee
    # can verify continuity even if the traceparent header is lost in transit.
    trace_id: str
    parent_span_id: str
    attempt: int


def open_genai_span(extracted: ExtractedContext, dispatch: DispatchRecord, op_name: str):
    """
    Enforce the causal-chain invariant before opening a gen_ai.* span at agent B.

    Invariant: extracted.trace_id must equal dispatch.trace_id, and the new span's
    parent must be dispatch.parent_span_id (the dispatching execute_tool span).
    """
    if extracted.trace_id is None or extracted.span_id is None:
        # Propagation was lost (uninstrumented client, propagator mismatch, etc.).
        # Do NOT silently mint a new root -- that produces an orphan.
        raise ContextContinuityError(
            f"no trace context extracted for op={op_name!r}; "
            f"dispatch trace_id={dispatch.trace_id} attempt={dispatch.attempt}. "
            f"Fall back to an explicit span link, not a fresh root."
        )

    if extracted.trace_id != dispatch.trace_id:
        raise ContextContinuityError(
            f"trace_id mismatch for op={op_name!r}: extracted={extracted.trace_id} "
            f"dispatch={dispatch.trace_id}. Propagator mismatch or header rewrite."
        )

    if extracted.span_id != dispatch.parent_span_id:
        raise ContextContinuityError(
            f"parent span mismatch for op={op_name!r}: extracted={extracted.span_id} "
            f"expected={dispatch.parent_span_id}. Context was overwritten mid-handoff."
        )

    # Invariant holds: open the span as a child of the dispatch span.
    return {
        "name": op_name,
        "trace_id": extracted.trace_id,
        "parent_span_id": dispatch.parent_span_id,
        "attributes": {
            "gen_ai.operation.name": op_name,
            "agent.handoff.attempt": dispatch.attempt,
        },
    }
