# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-id-re-minting-at-a-federated-hop-as-a-silent-correlation-break-rather-than-a-benign-transport-detail.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-id-re-minting-at-a-federated-hop-as-a-silent-correlation-break-rather-than-a-benign-transport-detail.warrant.json
# Markdown SHA-256:   3d705933b44438ec2a9394fe2de2a1da81c7a8773eb0d1df7b187c41f0deb535
# Code AST SHA-256:   24bd615a16692bc5f1e96d5f977681eee8c93b2f80877e68df569f27398e8c18
# Verified Classes:   TraceCorrelationBreak, SpanContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TraceCorrelationBreak(RuntimeError):
    """Raised when a federated hop re-mints or drops the trace context,
    severing the causal join key between caller and callee spans."""
    pass


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str


def propagate_across_hop(
    outbound: SpanContext,
    received_traceparent: str | None,
    causal_attribution_required: bool,
) -> SpanContext:
    """Validate that the callee received the caller's trace context intact.

    Returns the context the callee must continue with. Raises
    TraceCorrelationBreak if continuity is required but the received
    context is missing or re-minted.
    """
    if received_traceparent is None:
        if causal_attribution_required:
            raise TraceCorrelationBreak(
                f"callee received no traceparent; caller trace "
                f"{outbound.trace_id} cannot be joined to downstream spans"
            )
        # Tolerable: observability-only hop, no causal dependency.
        return SpanContext(trace_id="0" * 32, span_id="0" * 16)

    parts = received_traceparent.split("-")
    if len(parts) != 4:
        raise TraceCorrelationBreak(
            f"malformed traceparent at federation hop: {received_traceparent!r}"
        )
    _, received_trace_id, received_span_id, _ = parts

    if received_trace_id != outbound.trace_id:
        if causal_attribution_required:
            raise TraceCorrelationBreak(
                f"trace ID re-minted at hop: caller={outbound.trace_id} "
                f"callee={received_trace_id}; causal chain severed"
            )
        # Tolerable only if a span link records the prior context.
        return SpanContext(trace_id=received_trace_id, span_id=received_span_id)

    return SpanContext(trace_id=received_trace_id, span_id=received_span_id)
