# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-silent-trace-correlation-collapse-when-privacy-preserving-span-export-redacts-the-very-attributes-cross-tenant-aggregati.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-silent-trace-correlation-collapse-when-privacy-preserving-span-export-redacts-the-very-attributes-cross-tenant-aggregati.warrant.json
# Markdown SHA-256:   6bc8e847cae901dbcbbffa2cbb0cecc0a1d06b6c7b058330a408814318c81a54
# Code AST SHA-256:   2ca8cb501c9f3fdd9cc7a4b371b59af93c0777ae3302246b57bc80f91b1dfdab
# Verified Classes:   CorrelationCollapseError, ParentStatus, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class CorrelationCollapseError(RuntimeError):
    """Raised when a span export would silently break cross-tenant join topology."""


class ParentStatus(Enum):
    ROOT = "root"
    RESOLVED = "resolved"
    UNRESOLVED = "unresolved"
    REDACTED = "redacted"


@dataclass(frozen=True)
class Span:
    tenant: str
    trace_id: str
    span_id: str
    parent_span_id: str | None
    handoff_token: str | None
    salt_epoch: str | None
    parent_status: ParentStatus


JOIN_KEYS = {"handoff_token", "agent.instance_id"}


def apply_privacy_transform(span: Span, tenant_salt: str, shared_salt: str) -> Span:
    """Apply redaction. Refuse to per-tenant-hash a join key."""
    if span.handoff_token is not None:
        # Join key: must use shared salt, never tenant salt.
        if tenant_salt and tenant_salt != shared_salt:
            raise CorrelationCollapseError(
                f"tenant {span.tenant} attempted per-tenant transform on join key "
                f"'handoff_token' for span {span.span_id}; this would drop the "
                f"cross-tenant edge silently"
            )
        transformed = hashlib.sha256(
            f"{shared_salt}:{span.handoff_token}".encode()
        ).hexdigest()
        return Span(
            tenant=span.tenant,
            trace_id=span.trace_id,
            span_id=span.span_id,
            parent_span_id=span.parent_span_id,
            handoff_token=transformed,
            salt_epoch=shared_salt,
            parent_status=span.parent_status,
        )
    return span


def aggregate_join(spans: list[Span], known_span_ids: set[str]) -> list[tuple[Span, Span]]:
    """Join children to parents; refuse to emit null-parent as root."""
    edges: list[tuple[Span, Span]] = []
    by_id = {s.span_id: s for s in spans}
    for child in spans:
        if child.parent_span_id is None:
            if child.parent_status is not ParentStatus.ROOT:
                raise CorrelationCollapseError(
                    f"span {child.span_id} has no parent but is not marked ROOT; "
                    f"parent_status={child.parent_status}"
                )
            continue
        parent = by_id.get(child.parent_span_id)
        if parent is None:
            if child.parent_status is not ParentStatus.UNRESOLVED:
                raise CorrelationCollapseError(
                    f"span {child.span_id} references parent "
                    f"{child.parent_span_id} absent from aggregate but is not "
                    f"flagged UNRESOLVED; silent edge loss"
                )
            continue
        if (child.salt_epoch is not None and parent.salt_epoch is not None
                and child.salt_epoch != parent.salt_epoch):
            raise CorrelationCollapseError(
                f"handoff edge {parent.span_id}->{child.span_id} spans salt epochs "
                f"{parent.salt_epoch} vs {child.salt_epoch}; re-derive under both "
                f"or mark UNRESOLVED"
            )
        edges.append((parent, child))
    return edges
