# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-trace-parent-during-a-cross-org-a2a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-trace-parent-during-a-cross-org-a2a-handoff.warrant.json
# Markdown SHA-256:   c0e18bd6d67449e25f0c040ea180ac7077c2ffe464008b5af772200646345dad
# Code AST SHA-256:   e35e1ded59bc53960d6eaccce49f1c8323a73c33cd8f1a14f0d566616c4ae86c
# Verified Classes:   TraceForkError, SpanContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceForkError(RuntimeError):
    """Raised when a federated handoff reparents an inbound span, forking the trace."""
    pass


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: str | None


def emit_handoff_span(
    inbound: SpanContext,
    local_span_id: str,
    local_registry: set[str],
    strict: bool = True,
) -> SpanContext:
    """
    Emit the receiving org's first span for an inbound A2A/MCP handoff.

    Invariant: the emitted parent_span_id MUST equal the inbound span_id.
    A receiver may NOT reparent to a locally minted placeholder, because that
    forks the federated trace into two valid-looking but causally disjoint trees.
    """
    if inbound.span_id is None or inbound.trace_id is None:
        raise TraceForkError(
            f"inbound handoff missing trace context: {inbound!r}"
        )

    # The receiving store has never seen the caller's span. That is EXPECTED
    # across an org boundary and is not a reason to reparent.
    parent_is_local = inbound.span_id in local_registry

    if not parent_is_local and strict:
        # Correct federated behavior: preserve the foreign parent verbatim.
        # The local store will hold a dangling parent reference; auditors
        # resolve it against the sender's store via trace_id + span_id.
        return SpanContext(
            trace_id=inbound.trace_id,
            span_id=local_span_id,
            parent_span_id=inbound.span_id,
        )

    if not parent_is_local and not strict:
        # The defect path: SDK renormalizes to a local placeholder.
        # We refuse to emit silently; the caller must opt in to a marked fork.
        minted = "external-root-" + inbound.span_id[:8]
        raise TraceForkError(
            "refusing silent reparent of foreign span "
            f"{inbound.span_id} -> {minted}; emit a span tagged "
            "reparented=true instead, so auditors can detect the fork"
        )

    # Parent is local (intra-org hop): normal case.
    return SpanContext(
        trace_id=inbound.trace_id,
        span_id=local_span_id,
        parent_span_id=inbound.span_id,
    )


def verify_chain_reachable(spans: list[SpanContext]) -> None:
    """Audit replay: every span's parent must be reachable within the union of stores."""
    ids = {s.span_id for s in spans}
    for s in spans:
        if s.parent_span_id is not None and s.parent_span_id not in ids:
            raise TraceForkError(
                f"span {s.span_id} (trace {s.trace_id}) has unreachable parent "
                f"{s.parent_span_id}: federated trace is forked, not merely partial"
            )
