# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-dissociation-at-the-federated-span-boundary-in-cross-vendor-multi-agent-workflows.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-context-dissociation-at-the-federated-span-boundary-in-cross-vendor-multi-agent-workflows.warrant.json
# Markdown SHA-256:   75341438061fe53edb6272639bb775375b8df0b1f2d4c60d4bec4cb189680d5d
# Code AST SHA-256:   6a2b2ac33758b80e1d02da998616dc84d1de2a55d20b6d5437949b322269e6b1
# Verified Classes:   TraceContextDissociationError, SpanContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TraceContextDissociationError(RuntimeError):
    """Raised when a federated span boundary re-seeds or strips trace context,
    producing a second root for a single logical transaction."""
    pass


@dataclass
class SpanContext:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    tracestate_vendors: list[str] = field(default_factory=list)
    inbound_header_seen: bool = False
    inbound_header_parsed: bool = False


def propagate_span(
    inbound: SpanContext,
    callee_vendor: str,
    caller_vendor: str,
    supported_formats: set[str],
    inbound_format: str,
) -> SpanContext:
    # The callee saw a header but could not parse it: this is a correlation
    # failure, NOT a legitimate root request. Re-seeding here is the bug.
    if inbound.inbound_header_seen and not inbound.inbound_header_parsed:
        raise TraceContextDissociationError(
            f"callee '{callee_vendor}' saw inbound span header ({inbound_format}) "
            f"from '{caller_vendor}' but could not parse it; refusing to re-seed "
            f"trace_id — this would create a second root for the transaction."
        )

    if inbound_format not in supported_formats:
        raise TraceContextDissociationError(
            f"propagator mismatch: caller '{caller_vendor}' emitted '{inbound_format}', "
            f"callee '{callee_vendor}' supports {sorted(supported_formats)}; "
            f"context would be silently dropped."
        )

    # Guard the tracestate vendor list: a stripped tracestate breaks attribution
    # even when trace_id survives.
    if caller_vendor not in inbound.tracestate_vendors:
        raise TraceContextDissociationError(
            f"tracestate at '{callee_vendor}' lacks caller vendor '{caller_vendor}'; "
            f"vendor attribution is broken across the boundary."
        )

    return SpanContext(
        trace_id=inbound.trace_id,
        span_id=f"{callee_vendor}-child",
        parent_span_id=inbound.span_id,
        tracestate_vendors=inbound.tracestate_vendors + [callee_vendor],
        inbound_header_seen=True,
        inbound_header_parsed=True,
    )


def assert_single_root(transaction_id: str, roots: list[str]) -> None:
    if len(roots) != 1:
        raise TraceContextDissociationError(
            f"transaction '{transaction_id}' has {len(roots)} trace roots "
            f"{roots}; invariant root-cardinality==1 violated — trace is dissociated, "
            f"verdict is non-authoritative."
        )
