# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-propagate-a-trace-parent-across-a-federated-trust-boundary-when-the-w3c-traceparent-flags-field-disag.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-propagate-a-trace-parent-across-a-federated-trust-boundary-when-the-w3c-traceparent-flags-field-disag.warrant.json
# Markdown SHA-256:   a3faf84debc2175835d89ae6ddf158cbb741ebe30a758816c2ae1486030ba445
# Code AST SHA-256:   3f85f94f902f5b20ebf5f6eb317c6d59e2723cf3c4cd2274496d56ae7318ccc9
# Verified Classes:   TracePropagationRefused, TraceParent, LocalDecision
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TracePropagationRefused(RuntimeError):
    """Raised when an instance must not propagate an inherited parent link."""
    pass


@dataclass(frozen=True)
class TraceParent:
    trace_id: str
    parent_span_id: str
    flags: int          # 0x00 = not sampled, 0x01 = sampled
    tracestate: Optional[str]
    hop_count: int


@dataclass(frozen=True)
class LocalDecision:
    sample: bool


MAX_FEDERATION_HOPS = 8


def decide_propagation(
    inbound: TraceParent,
    local: LocalDecision,
    origin_authenticated: bool,
) -> str:
    """Return 'inherit' or 'reparent', or raise TracePropagationRefused.

    Enforces the invariant: sampling-decision inheritance and identity
    inheritance must travel together, or neither.
    """
    if inbound.trace_id == "0" * 32 or inbound.trace_id == "":
        raise TracePropagationRefused(
            f"invalid trace_id {inbound.trace_id!r}; cannot propagate parent link"
        )
    if inbound.hop_count > MAX_FEDERATION_HOPS:
        raise TracePropagationRefused(
            f"hop_count {inbound.hop_count} exceeds federation max "
            f"{MAX_FEDERATION_HOPS}; suspected loop or replay"
        )
    if not origin_authenticated:
        # Cannot verify the inbound sampling decision; do not make a claim about it.
        raise TracePropagationRefused(
            "origin domain not authenticated via tracestate; "
            "refusing to inherit sampling decision"
        )

    inbound_sampled = bool(inbound.flags & 0x01)

    if inbound_sampled and not local.sample:
        # Honor the parent's committed decision even against local sampler.
        return "inherit"
    if not inbound_sampled and local.sample:
        # Local upgrade of an unsampled parent would create a phantom-sampled
        # child. Reparent instead: new trace_id, local root.
        return "reparent"
    # Decisions agree; inherit identity and decision together.
    return "inherit"


def emit_child_span(
    inbound: TraceParent,
    local: LocalDecision,
    origin_authenticated: bool,
    new_trace_id_factory,
) -> dict:
    mode = decide_propagation(inbound, local, origin_authenticated)
    if mode == "inherit":
        return {
            "trace_id": inbound.trace_id,
            "parent_span_id": inbound.parent_span_id,
            "flags": inbound.flags,
        }
    # reparent: sever cross-domain link, become local root
    new_trace = new_trace_id_factory()
    if new_trace == inbound.trace_id:
        raise TracePropagationRefused(
            "reparenting produced identical trace_id; identity inheritance "
            "cannot be severed while decision inheritance is overridden"
        )
    return {"trace_id": new_trace, "parent_span_id": None, "flags": 0x01}
