# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-mint-traceparent-when-an-mcp-server-terminates-the-inbound-trace-context-mid-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-mint-traceparent-when-an-mcp-server-terminates-the-inbound-trace-context-mid-hop.warrant.json
# Markdown SHA-256:   f64e53a6a1087007b279dfba0b04b289ba9838482616d8ba1075fe6a8b794db7
# Code AST SHA-256:   a9e77a545cb8f19aee239d1808f6beccc58334708f8a6f85ed82800b83bd429f
# Verified Classes:   TraceContinuityError
# Defensive Guards:   9 fail-closed invariants (zero external deps)

import re

TRACEPARENT_RE = re.compile(
    r"^(?P<version>[0-9a-f]{2})-"
    r"(?P<trace_id>[0-9a-f]{32})-"
    r"(?P<parent_id>[0-9a-f]{16})-"
    r"(?P<flags>[0-9a-f]{2})$"
)
ZERO_TRACE = "0" * 32
ZERO_PARENT = "0" * 16


class TraceContinuityError(RuntimeError):
    """Raised when an MCP/A2A hop breaks traceparent causal linkage."""
    pass


def parse_traceparent(header: str) -> dict:
    m = TRACEPARENT_RE.match(header.strip().lower())
    if not m:
        raise TraceContinuityError(f"malformed traceparent: {header!r}")
    tp = m.groupdict()
    if tp["trace_id"] == ZERO_TRACE or tp["parent_id"] == ZERO_PARENT:
        raise TraceContinuityError("traceparent carries all-zero id (invalid)")
    if tp["version"] == "ff":
        raise TraceContinuityError("traceparent version ff is forbidden")
    return tp


def continue_trace(inbound_header: str | None, outbound_span_id: str,
                   attempt: int, seen_parents: set[str]) -> str:
    """Mint an outbound traceparent that preserves trace-id and links per-attempt."""
    if inbound_header is None:
        # Genuine root: mint new trace-id, but this is a visible discontinuity.
        raise TraceContinuityError(
            "no inbound traceparent at MCP hop; refusing to silently root a new trace"
        )
    tp = parse_traceparent(inbound_header)
    if len(outbound_span_id) != 16 or not re.fullmatch(r"[0-9a-f]{16}", outbound_span_id):
        raise TraceContinuityError(f"bad outbound span-id: {outbound_span_id!r}")
    if outbound_span_id in seen_parents:
        raise TraceContinuityError(
            f"span-id {outbound_span_id} reused across attempts; retry would collide"
        )
    seen_parents.add(outbound_span_id)
    # trace-id is write-once: inherited verbatim from inbound context.
    return f"00-{tp['trace_id']}-{outbound_span_id}-{tp['flags']}"


def verify_hop_continuity(inbound: str, outbound: str, expected_attempt: int) -> None:
    """Assert the outbound hop is a true child of the inbound context."""
    src = parse_traceparent(inbound)
    dst = parse_traceparent(outbound)
    if dst["trace_id"] != src["trace_id"]:
        raise TraceContinuityError(
            f"trace-id mutated across hop: {src['trace_id']} -> {dst['trace_id']}"
        )
    if dst["parent_id"] == src["parent_id"]:
        raise TraceContinuityError(
            "outbound parent-id equals inbound parent-id (retry collision or flat linkage)"
        )
    if expected_attempt < 0:
        raise TraceContinuityError("attempt index must be non-negative")
