# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-propagate-a-traceparent-across-a-federation-boundary-that-strips-attributes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-propagate-a-traceparent-across-a-federation-boundary-that-strips-attributes.warrant.json
# Markdown SHA-256:   e664dee312e9692fdb921d1ed7101ba89d5063fdb1d6aec992b1b5535022cd95
# Code AST SHA-256:   3877af7dfa6a884a2712173da6725b5b67883064e207375c81b02f889e47e014
# Verified Classes:   FederationPropagationError, ExportContract
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class FederationPropagationError(RuntimeError):
    """Raised when a hop cannot legally forward an inherited traceparent."""
    pass


@dataclass(frozen=True)
class ExportContract:
    allowed_attributes: frozenset
    fanout_multiplicity: int


def _injective_survivors(upstream: ExportContract, local: ExportContract) -> frozenset:
    # Attributes both hops export are candidates; injectivity over fan-out
    # is assumed only for keys the upstream marks as branch-distinguishing.
    return upstream.allowed_attributes & local.allowed_attributes


def propagate_or_derive(
    traceparent: str,
    upstream: ExportContract,
    local: ExportContract,
    branch_keys: frozenset,
) -> str:
    survivors = _injective_survivors(upstream, local)
    distinguishing = survivors & branch_keys

    if upstream.fanout_multiplicity > 1 and not distinguishing:
        # Cannot reconstruct the parent-child edge after reduction.
        # Refuse to forward; caller must emit a link + fresh trace_id.
        token = hashlib.sha256(traceparent.encode()).hexdigest()[:16]
        raise FederationPropagationError(
            f"no injective attribute survives reduction "
            f"(upstream_fanout={upstream.fanout_multiplicity}, "
            f"survivors={sorted(survivors)}, token={token}); "
            f"emit span.links and mint local trace_id instead of forwarding traceparent"
        )

    return traceparent  # safe to forward unchanged
