# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trace-parent-divergence-when-privacy-preserving-span-export-crosses-an-organizational-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trace-parent-divergence-when-privacy-preserving-span-export-crosses-an-organizational-boundary.warrant.json
# Markdown SHA-256:   adb28d9b2bd6f9d09d1acfc9ad71f1ac8cb0d9cf06b20856457bdd17d87f45d8
# Code AST SHA-256:   25b81030c8beb509624d22a54ff6d400ae5a9e56f1121e49a25562ac9a300c23
# Verified Classes:   TraceCorrelationError, ExportedSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass


class TraceCorrelationError(RuntimeError):
    """Raised when a cross-boundary span cannot be joined to its logical parent."""


@dataclass(frozen=True)
class ExportedSpan:
    trace_id: str
    span_id: str
    parent_span_id: str | None
    delegation_handle: str | None
    domain: str


def hmac16(key: bytes, value: str) -> str:
    return hmac.new(key, value.encode(), hashlib.sha256).hexdigest()[:16]


def correlate(
    local_spans: list[ExportedSpan],
    remote_spans: list[ExportedSpan],
    known_handles: set[str],
) -> dict[str, list[str]]:
    """
    Join remote (redacted, per-domain-hashed) spans onto local spans using the
    caller-minted delegation_handle. Never re-roots. Never trusts a hashed
    parent_span_id across the boundary.
    """
    by_handle: dict[str, str] = {}
    for s in local_spans:
        if s.delegation_handle is not None:
            by_handle[s.delegation_handle] = s.span_id

    children: dict[str, list[str]] = {s.span_id: [] for s in local_spans}

    for r in remote_spans:
        if r.delegation_handle is None:
            raise TraceCorrelationError(
                f"remote span {r.span_id} from domain={r.domain} carries no "
                f"delegation_handle; cross-boundary join is impossible and "
                f"re-rooting is forbidden"
            )
        if r.delegation_handle not in known_handles:
            raise TraceCorrelationError(
                f"remote span {r.span_id} presents unknown handle "
                f"{r.delegation_handle!r}; possible replay or handle forgery"
            )
        parent_local = by_handle.get(r.delegation_handle)
        if parent_local is None:
            raise TraceCorrelationError(
                f"remote span {r.span_id} handle {r.delegation_handle!r} does "
                f"not match any live outbound delegation; orphan must be "
                f"recorded, not re-parented under trace root"
            )
        children[parent_local].append(r.span_id)

    return children


def assert_single_root(spans: list[ExportedSpan]) -> None:
    roots = [s for s in spans if s.parent_span_id is None]
    if len(roots) != 1:
        raise TraceCorrelationError(
            f"trace has {len(roots)} roots; expected exactly 1. "
            f"Roots: {[s.span_id for s in roots]}"
        )
