# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-parent-span-when-a-tainted-a2a-handoff-crosses-an-mcp-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-parent-span-when-a-tainted-a2a-handoff-crosses-an-mcp-tool-boundary.warrant.json
# Markdown SHA-256:   21daa67917958f5984b9f9e666353c2de495191d5a436970528b60fff9a4245a
# Code AST SHA-256:   9e72d55148c079bbb9279a2b232a863509aea12feb4adb4e220d6412560c2b33
# Verified Classes:   TaintLineageBreakError, SpanContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLineageBreakError(RuntimeError):
    """Raised when a cross-protocol boundary cannot carry taint lineage forward.

    A missing lineage attribute at a known lineage-breaking boundary is a hard
    error, NOT a default-clean state. Emitting a clean child span here is the
    silent-reparenting failure this guard exists to prevent.
    """

    def __init__(self, boundary_id: str, inbound_tokens: set[str], reason: str):
        self.boundary_id = boundary_id
        self.inbound_tokens = inbound_tokens
        self.reason = reason
        super().__init__(
            f"taint lineage break at boundary={boundary_id!r}: {reason}; "
            f"inbound_tokens={sorted(inbound_tokens)}"
        )


# Boundaries that are known to preserve or break lineage attribute propagation.
LINEAGE_PRESERVING_BOUNDARIES = frozenset({"in_process_call", "same_sdk_span"})
LINEAGE_BREAKING_BOUNDARIES = frozenset({"a2a_to_mcp", "cross_vendor_genai_sdk"})


@dataclass
class SpanContext:
    trace_id: str
    parent_span_id: Optional[str]
    taint_tokens: set[str] = field(default_factory=set)
    taint_broken_at: Optional[str] = None


def emit_child_span(
    parent: SpanContext,
    boundary: str,
    inbound_taint_tokens: set[str],
    rederived_tokens: Optional[set[str]] = None,
) -> SpanContext:
    """Emit a child span, enforcing monotonic taint propagation.

    Rules:
      - Lineage-preserving boundary: child inherits parent tokens unchanged.
      - Lineage-breaking boundary: child MUST carry the full inbound token set
        or the handoff fails closed with TaintLineageBreakError.
      - Re-derived taint is attached alongside, never replacing, propagated taint.
    """
    if boundary in LINEAGE_PRESERVING_BOUNDARIES:
        child_tokens = set(parent.taint_tokens) | set(inbound_taint_tokens)
    elif boundary in LINEAGE_BREAKING_BOUNDARIES:
        missing = parent.taint_tokens - inbound_taint_tokens
        if missing:
            # The boundary dropped lineage that the parent held. Refuse to emit
            # a clean span; fail closed so the orchestrator can surface it.
            raise TaintLineageBreakError(
                boundary_id=boundary,
                inbound_tokens=inbound_taint_tokens,
                reason=f"parent taint tokens dropped at boundary: {sorted(missing)}",
            )
        child_tokens = set(parent.taint_tokens) | set(inbound_taint_tokens)
    else:
        raise TaintLineageBreakError(
            boundary_id=boundary,
            inbound_tokens=inbound_taint_tokens,
            reason="unclassified boundary; cannot prove lineage preservation",
        )

    # Re-derivation must not sever the causal chain.
    if rederived_tokens:
        child_tokens |= {f"derived:{tok}" for tok in rederived_tokens}

    return SpanContext(
        trace_id=parent.trace_id,
        parent_span_id=f"{parent.trace_id}:child",
        taint_tokens=child_tokens,
        taint_broken_at=parent.taint_broken_at,
    )


def demo():
    root = SpanContext(
        trace_id="trace-7f3a",
        parent_span_id=None,
        taint_tokens={"retrieval:doc_4417"},
    )
    # Boundary that carries the token: fine.
    b = emit_child_span(root, "a2a_to_mcp", {"retrieval:doc_4417"})
    assert b.taint_tokens == {"retrieval:doc_4417"}

    # Boundary that drops the token: must fail closed, not emit clean.
    try:
        emit_child_span(root, "a2a_to_mcp", set())
    except TaintLineageBreakError as e:
        print(f"correctly refused: {e}")
    else:
        raise AssertionError("silent lineage break was not caught")


if __name__ == "__main__":
    demo()
