# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-trace-context-is-silently-rewritten-by-an-mcp-server-during-a-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-trace-context-is-silently-rewritten-by-an-mcp-server-during-a-tool-call.warrant.json
# Markdown SHA-256:   7cbf3effd91cd1e1244c2d91bf9fc4fdf003b073d0e56c2bdaf8c384369d7b32
# Code AST SHA-256:   666fd04c4c00a71953f65de2db6d69476f6c85f9cf84224e90b49cde4d636b94
# Verified Classes:   TraceContinuityViolation, SpanContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class TraceContinuityViolation(RuntimeError):
    """Raised when a span crosses an MCP/A2A hop with a broken causal link."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    tracestate: str  # comma-separated vendor=value pairs, order-significant


def _tracestate_is_suffix_consistent(parent: str, child: str) -> bool:
    # A child tracestate must preserve the parent's entries as an ordered suffix
    # (vendors may prepend, never reorder or drop without a declared link).
    p = [kv.strip() for kv in parent.split(",") if kv.strip()]
    c = [kv.strip() for kv in child.split(",") if kv.strip()]
    if not p:
        return True
    return c[-len(p):] == p


def assert_hop_continuity(
    upstream: SpanContext,
    downstream: SpanContext,
    *,
    synchronous: bool,
    declared_link: str | None,
) -> None:
    """
    Enforce the cross-hop invariant for one MCP tool call or A2A task handoff.

    synchronous=True means the agent consumes the downstream result before its
    next reasoning step, so the trace must be continuous. Detached async work
    may re-root ONLY with an explicit declared_link back to the upstream span.
    """
    if downstream.trace_id != upstream.trace_id:
        if synchronous:
            raise TraceContinuityViolation(
                f"sync hop re-rooted trace: upstream {upstream.trace_id} "
                f"-> downstream {downstream.trace_id} (span {downstream.span_id}); "
                "retry/fan-out path likely reset context"
            )
        if declared_link != upstream.span_id:
            raise TraceContinuityViolation(
                f"async hop {downstream.span_id} re-rooted to {downstream.trace_id} "
                f"without a link to upstream span {upstream.span_id}; "
                "causal edge is unrecoverable"
            )

    if downstream.parent_span_id is not None and downstream.parent_span_id != upstream.span_id:
        raise TraceContinuityViolation(
            f"span {downstream.span_id} claims parent {downstream.parent_span_id}, "
            f"expected {upstream.span_id}; graph will attach to wrong node"
        )

    if not _tracestate_is_suffix_consistent(upstream.tracestate, downstream.tracestate):
        raise TraceContinuityViolation(
            f"tracestate at {downstream.span_id} is not a suffix-consistent "
            f"transform of upstream; half-linked span detected "
            f"(upstream='{upstream.tracestate}', downstream='{downstream.tracestate}')"
        )
