# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-trace-context-is-silently-re-parented-across-an-mcp-a2a-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-trace-context-is-silently-re-parented-across-an-mcp-a2a-boundary.warrant.json
# Markdown SHA-256:   0f09491da45c55f8c5b9cca5887ee362d891522d1031ca9f26a108f04bb83244
# Code AST SHA-256:   4c702cae1d6388396131560bde78b7e9be70dd03eb3b1bbaeeab826dfde926fc
# Verified Classes:   TraceContinuityError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class TraceContinuityError(RuntimeError):
    """Raised when a span's asserted parent cannot be proven from inbound context."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]


def assert_parent_was_asserted(
    child: SpanContext,
    inbound_traceparent_span_id: Optional[str],
    locally_opened_active_span_id: Optional[str],
) -> None:
    """
    Enforce the cross-protocol invariant: a child span's parent must be either
    the span_id carried in the inbound traceparent, or a span this process
    opened itself and holds active. Anything else is a synthesized (false) edge.
    """
    if child.parent_span_id is None:
        return  # explicit root: allowed, but must be flagged by the emitter

    proven = {inbound_traceparent_span_id, locally_opened_active_span_id}
    proven.discard(None)

    if child.parent_span_id not in proven:
        raise TraceContinuityError(
            "re-parented span detected: "
            f"span {child.span_id} in trace {child.trace_id} claims parent "
            f"{child.parent_span_id}, but inbound traceparent carried "
            f"{inbound_traceparent_span_id!r} and local active span was "
            f"{locally_opened_active_span_id!r}. Refusing to emit; this edge "
            "was synthesized by a join heuristic, not asserted by W3C context."
        )


def emit_delegation_span(
    active_span: Optional[SpanContext],
    inbound_traceparent_span_id: Optional[str],
    trace_id: str,
    new_span_id: str,
) -> SpanContext:
    """Fail closed at the MCP->A2A boundary rather than silently starting a new root."""
    if active_span is None and inbound_traceparent_span_id is None:
        raise TraceContinuityError(
            "no active span and no inbound traceparent at delegation boundary; "
            "refusing to emit an unflagged new root across an A2A hop"
        )
    parent = active_span.span_id if active_span is not None else inbound_traceparent_span_id
    child = SpanContext(trace_id=trace_id, span_id=new_span_id, parent_span_id=parent)
    assert_parent_was_asserted(child, inbound_traceparent_span_id, active_span.span_id if active_span else None)
    return child
