# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-span-link-parent-when-a-nested-agent-to-agent-handoff-rewrites-its-trace-context-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-span-link-parent-when-a-nested-agent-to-agent-handoff-rewrites-its-trace-context-mid-execution.warrant.json
# Markdown SHA-256:   341f1c8668133d9bc60033619d83f04dca3d3d73e4544a78b3e184d009e0c063
# Code AST SHA-256:   c8a345dad06a3dc2ad83278660531abe04ffa3521a9bb8a813e768554036723a
# Verified Classes:   SpanLineageError, SpanContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SpanLineageError(RuntimeError):
    """Raised when a returned span context breaks the causal link to its caller."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str      # 32 hex chars
    span_id: str       # 16 hex chars
    parent_span_id: str | None
    tracestate: str = ""

    def is_reroot_marked(self) -> bool:
        return "a2a=reroot" in self.tracestate.split(",")


def assert_span_continuity(
    sent: SpanContext,
    returned: SpanContext,
    caller_span_id: str,
) -> None:
    """
    Enforce the lineage invariant at a nested agent-to-agent handoff boundary.

    Must be called by the CALLER on the context RETURNED by the callee, before
    closing the caller's span or forwarding the context upward. The callee
    cannot perform this check: from its local view a fresh trace is valid.
    """
    if returned.trace_id == sent.trace_id:
        # Continuous lineage: parent must point at the caller's span.
        if returned.parent_span_id != caller_span_id:
            raise SpanLineageError(
                f"same trace_id {sent.trace_id!r} but parent_span_id "
                f"{returned.parent_span_id!r} != caller_span_id {caller_span_id!r}"
            )
        return

    # trace_id changed: legitimate only if explicitly re-root marked.
    if returned.is_reroot_marked():
        return  # record as cross-trace link; do not claim parent-child

    raise SpanLineageError(
        "broken span link at handoff: returned trace_id "
        f"{returned.trace_id!r} != sent trace_id {sent.trace_id!r} "
        f"with no re-root marker (tracestate={returned.tracestate!r}); "
        "caller must not forward this context upward"
    )


def close_handoff(sent: SpanContext, returned: SpanContext, caller_span_id: str) -> str:
    assert_span_continuity(sent, returned, caller_span_id)
    return returned.trace_id
