# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-carry-its-own-correlation-identity-when-a2a-hop-boundaries-sever-the-mcp-span-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-carry-its-own-correlation-identity-when-a2a-hop-boundaries-sever-the-mcp-span-tree.warrant.json
# Markdown SHA-256:   b5f5b334252b8348c1bcd011d557bcd2ee60b835d60a6ed205590945e537a2da
# Code AST SHA-256:   a9377c60c00ddfc14e9ea76d900a26c37b444fbbf31c9a7de07723b7a813d124
# Verified Classes:   CorrelationInvariantError, SpanRef
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class CorrelationInvariantError(RuntimeError):
    """Raised when a span is about to be joined without carried identity."""
    pass

@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str
    origin_instance: str
    start_ns: int
    end_ns: int
    correlation_token: Optional[str] = None  # echoed through tool args when headers unavailable

def join_span(child: SpanRef, candidate_parent: SpanRef,
              skew_budget_ns: int, allow_inference: bool = False) -> str:
    """
    Returns the join status. Refuses to emit a silent parent edge.
    """
    # Primary path: carried identity (trace_id + explicit token or parent pointer).
    if child.trace_id == candidate_parent.trace_id:
        return "carried"
    if child.correlation_token and child.correlation_token == candidate_parent.correlation_token:
        return "token_echo"

    # No carried identity. Temporal inference is annotation-only.
    gap = abs(child.start_ns - candidate_parent.end_ns)
    if gap <= skew_budget_ns and allow_inference:
        # Annotate, never edge.
        return f"inferred_candidate(confidence={1.0 - gap / skew_budget_ns:.2f})"

    if child.correlation_token is None and child.trace_id != candidate_parent.trace_id:
        # The boundary stripped identity and no echo token was smuggled through.
        raise CorrelationInvariantError(
            f"cannot join span {child.span_id} (trace {child.trace_id}) to "
            f"{candidate_parent.span_id} (trace {candidate_parent.trace_id}): "
            f"no carried identity and no correlation token; "
            f"temporal gap {gap}ns vs budget {skew_budget_ns}ns. "
            f"Report as broken_chain, do not infer."
        )
    return "broken_chain"
