# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-sever-a-trace-parent-to-prevent-cross-server-causality-laundering-in-mcp-a2a-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-sever-a-trace-parent-to-prevent-cross-server-causality-laundering-in-mcp-a2a-observability.warrant.json
# Markdown SHA-256:   0fe5797c98a26b650d25f189b37661fe5170245b246dfcc6ee6e619fe24ea71e
# Code AST SHA-256:   67d9d80e079ff2f4be3ed213982556489eb9249e7f41b77a7a4fd384697f8014
# Verified Classes:   CausalityLaunderingError, InboundContext, ReceiverProfile
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CausalityLaunderingError(RuntimeError):
    """Raised when a span would be parented across an unprovable boundary."""


@dataclass
class InboundContext:
    trace_id: str
    parent_span_id: str
    request_id_echo: Optional[str]  # nonce echoed by receiver, if any


@dataclass
class ReceiverProfile:
    single_flight: bool
    echoes_request_id: bool


def decide_parenting(ctx: InboundContext, receiver: ReceiverProfile, used_for_attribution: bool) -> str:
    """
    Returns 'parent' if ancestry is provable, 'sever' if the parent must be
    downgraded to a link. Raises if a caller tries to force parenting across
    an unprovable boundary.
    """
    binding_provable = receiver.single_flight and (
        not receiver.echoes_request_id or ctx.request_id_echo is not None
    )
    if binding_provable:
        return "parent"
    if used_for_attribution and ctx.parent_span_id:
        # Honest severing is required; do not silently keep the parent.
        return "sever"
    return "sever"


def emit_span(ctx: InboundContext, receiver: ReceiverProfile, used_for_attribution: bool, force_parent: bool = False) -> dict:
    decision = decide_parenting(ctx, receiver, used_for_attribution)
    if force_parent and decision == "sever":
        raise CausalityLaunderingError(
            f"Refusing to parent span under trace {ctx.trace_id}: receiver "
            f"single_flight={receiver.single_flight}, echo={ctx.request_id_echo!r}. "
            "Downgrade to link with causality.claim=unverified."
        )
    if decision == "parent":
        return {"trace_id": ctx.trace_id, "parent_span_id": ctx.parent_span_id, "kind": "child"}
    return {
        "trace_id": ctx.trace_id,
        "parent_span_id": None,
        "kind": "root",
        "link": {"trace_id": ctx.trace_id, "span_id": ctx.parent_span_id},
        "attributes": {"causality.claim": "unverified"},
    }


# Example: a pooled MCP server that does not echo a request id.
ctx = InboundContext(trace_id="T", parent_span_id="spanA", request_id_echo=None)
pooled = ReceiverProfile(single_flight=False, echoes_request_id=False)

span = emit_span(ctx, pooled, used_for_attribution=True)
assert span["kind"] == "root" and span["attributes"]["causality.claim"] == "unverified"

# A caller that insists on parenting anyway is stopped.
try:
    emit_span(ctx, pooled, used_for_attribution=True, force_parent=True)
except CausalityLaunderingError as e:
    print("blocked:", e)
