# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-trace-context-when-an-mcp-tool-call-re-enters-the-agent-through-an-a2a-peer-and-the-llm-provider-strips-unknown-heade.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-trace-context-when-an-mcp-tool-call-re-enters-the-agent-through-an-a2a-peer-and-the-llm-provider-strips-unknown-heade.warrant.json
# Markdown SHA-256:   d461ee29c48e6e2cd74f8b2c501bb7f083767ec76c2befb2817876bd8ed2628b
# Code AST SHA-256:   d365a82b62f03227e60bb60804e5a3f149add1a076d162e0d041576d9a4ad79c
# Verified Classes:   TraceContextFragmentationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import logging

logger = logging.getLogger(__name__)


class TraceContextFragmentationError(RuntimeError):
    """Raised when a multi-hop agent request produces more than one root span.

    A fragmented trace means a context break occurred across an MCP, A2A, or
    LLM provider boundary. The trace tree looks valid per-hop but cannot be
    correlated end-to-end.
    """


def assert_single_root(trace_roots: list[str], hop_chain: list[str]) -> None:
    """Verify that a synthetic end-to-end request yielded exactly one root span.

    trace_roots: list of trace_ids observed as roots in the backend for the probe.
    hop_chain:   ordered list of hop names the probe traversed, for diagnostics.
    """
    if len(trace_roots) == 1:
        logger.info("trace correlation intact across %s", " -> ".join(hop_chain))
        return
    if len(trace_roots) == 0:
        raise TraceContextFragmentationError(
            f"probe produced zero root spans across {hop_chain}; "
            "instrumentation may be disabled at one or more hops"
        )
    raise TraceContextFragmentationError(
        f"probe produced {len(trace_roots)} root spans across {hop_chain}: "
        f"{trace_roots}. Context was lost at a boundary — check for "
        "header-stripping (LLM provider edge) or missing in-band carriage "
        "(A2A JSON-RPC metadata, MCP _meta)."
    )


def preflight_trace_probe(hop_chain: list[str], probe_fn) -> None:
    """Run a synthetic request through the full hop chain and assert correlation."""
    roots = probe_fn()  # returns list of trace_ids seen as roots
    assert_single_root(roots, hop_chain)
