# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trace-correlation-collapse-when-privacy-preserving-span-linking-crosses-organizational-trust-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trace-correlation-collapse-when-privacy-preserving-span-linking-crosses-organizational-trust-boundaries.warrant.json
# Markdown SHA-256:   0c30c33b17a1afb0629a3accb918f4303462f49df7fcd48f13b54b65cd96730d
# Code AST SHA-256:   982e67117f9bf4e73b6df89506e7f8cc763aaa976de247e1ac9d84a2a2760e30
# Verified Classes:   CorrelationInvariantViolation, Span
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class CorrelationInvariantViolation(RuntimeError):
    """Raised when a federated span link cannot be trusted as causal."""
    pass


@dataclass
class Span:
    domain: str
    span_id: str
    parent_key: bytes          # derived linkage key (lossy)
    trace_id: str
    salt_epoch: int
    timestamp: float
    committed_nonce: bytes | None = None


def derive_key(span: Span, salt: bytes, trunc_bits: int) -> bytes:
    raw = hashlib.hmac_new  # placeholder; real impl uses hmac.new
    digest = hashlib.sha256(salt + span.span_id.encode()).digest()
    return digest[: trunc_bits // 8]


def link_spans(
    child: Span,
    candidates: list[Span],
    salt: bytes,
    trunc_bits: int,
    max_skew_s: float,
    live_span_count: int,
) -> Span:
    # Guard 1: truncation must beat the birthday bound for the live population.
    if trunc_bits < 2 * (live_span_count.bit_length()):
        raise CorrelationInvariantViolation(
            f"truncation {trunc_bits} bits insufficient for "
            f"{live_span_count} live spans; collision-join risk unbounded"
        )

    # Guard 2: salt epoch must be trace-scoped, not wall-clock-scoped.
    matches = [
        c for c in candidates
        if derive_key(c, salt, trunc_bits) == child.parent_key
        and c.trace_id == child.trace_id
    ]

    if len(matches) > 1:
        raise CorrelationInvariantViolation(
            f"collision cluster: {len(matches)} spans share parent_key on "
            f"trace {child.trace_id}; causal ordering ambiguous"
        )

    if not matches:
        raise CorrelationInvariantViolation(
            f"orphan: no candidate resolves parent_key for span {child.span_id} "
            f"in domain {child.domain}; correlation_degraded"
        )

    parent = matches[0]

    # Guard 3: salt epoch divergence means equality no longer implies adjacency.
    if parent.salt_epoch != child.salt_epoch:
        raise CorrelationInvariantViolation(
            f"salt epoch desync {parent.salt_epoch}->{child.salt_epoch}; "
            f"refusing fallback re-link"
        )

    # Guard 4: commit-reveal nonce must bind to trace, not rotation epoch.
    if child.committed_nonce is not None:
        if parent.committed_nonce is None:
            raise CorrelationInvariantViolation(
                f"auditor span {child.span_id} unverified_across_domains: "
                f"no pre-committed nonce in domain {parent.domain}"
            )
        if parent.committed_nonce != child.committed_nonce:
            raise CorrelationInvariantViolation(
                f"commit-reveal nonce desync on trace {child.trace_id}"
            )

    # Guard 5: timestamp fallback must never manufacture an edge.
    if abs(parent.timestamp - child.timestamp) > max_skew_s:
        raise CorrelationInvariantViolation(
            f"causal gap {abs(parent.timestamp - child.timestamp):.3f}s "
            f"exceeds skew bound; refusing proximity fallback"
        )

    return parent
