# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-correlate-a-federated-trace-span-whose-redacted-attributes-still-leak-joinable-structure.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-correlate-a-federated-trace-span-whose-redacted-attributes-still-leak-joinable-structure.warrant.json
# Markdown SHA-256:   c4f45858c899345187ee09ef0bc64b6ffcf6a66dff92b797975962efc138a8d6
# Code AST SHA-256:   5f3c1ad65677478d59ea0cb436b8efe0c0ccdaa2198844761657efb072c44b6a
# Verified Classes:   UncorrelatableSpanGap, FederatedSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional

CORRELATION_K = 5  # minimum candidate-set size for a valid structural join


class UncorrelatableSpanGap(RuntimeError):
    """Raised when a federated span cannot be safely joined to a causal chain."""


@dataclass
class FederatedSpan:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    domain: str
    salt: str
    tenant_hash: str
    latency_bucket: int
    region: str


def _keyed_hash(tenant: str, salt: str) -> str:
    return hashlib.sha256(f"{salt}:{tenant}".encode()).hexdigest()


def correlate(
    span: FederatedSpan,
    reference: list[FederatedSpan],
    agreed_salt: str,
    structural_candidate_count: int,
) -> FederatedSpan:
    # Path 1: attribute join under an agreed salt.
    expected = _keyed_hash(span.tenant_hash, agreed_salt)
    for ref in reference:
        if ref.domain != span.domain and _keyed_hash(ref.tenant_hash, agreed_salt) == expected:
            return ref

    # Path 2: attribute join failed. Structural fallback is only legal if
    # the fallback tuple is non-unique within the candidate set.
    if structural_candidate_count < CORRELATION_K:
        raise UncorrelatableSpanGap(
            f"span {span.span_id} in domain {span.domain}: attribute join empty "
            f"(salt mismatch or rotated key) and structural fallback "
            f"(parent={span.parent_span_id}, latency_bucket={span.latency_bucket}, "
            f"region={span.region}) yields only {structural_candidate_count} "
            f"candidates < k={CORRELATION_K}; refusing inferred join to avoid "
            f"graph-position re-identification"
        )

    # Path 3: structural fallback is safe — return best candidate, flagged low-confidence.
    return reference[0]
