# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-correlation-identifier-collapse-when-federated-audit-logs-cross-a-trust-domain-clock-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-correlation-identifier-collapse-when-federated-audit-logs-cross-a-trust-domain-clock-boundary.warrant.json
# Markdown SHA-256:   91aee3c8d0edb56ff981a504d11201267ab8f92080b788b2b1ede5e5155cf55b
# Code AST SHA-256:   41d59b4b756aed3273fdfc9c33b8fa976d25404b42780071c74f18fbc0a79001
# Verified Classes:   CorrelationCollapseError, AuditRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CorrelationCollapseError(RuntimeError):
    """Raised when a federated audit join fuses distinct causal chains."""
    pass


@dataclass(frozen=True)
class AuditRecord:
    domain: str
    local_id: str
    causal_root: str | None
    warrant_id: str
    resource: str


def join_federated_trace(records: list[AuditRecord]) -> dict[str, list[AuditRecord]]:
    """
    Join records into traces keyed by causal_root.
    Rejects records lacking a causal_root (unattributable) and
    rejects any causal_root whose records disagree on warrant_id
    (the signature of identifier collapse).
    """
    traces: dict[str, list[AuditRecord]] = {}
    unattributable: list[AuditRecord] = []

    for rec in records:
        if rec.causal_root is None:
            unattributable.append(rec)
            continue
        traces.setdefault(rec.causal_root, []).append(rec)

    for root, group in traces.items():
        warrants = {r.warrant_id for r in group}
        if len(warrants) > 1:
            raise CorrelationCollapseError(
                f"causal_root={root!r} spans multiple warrants {sorted(warrants)}; "
                f"records: {[(r.domain, r.local_id, r.resource) for r in group]}"
            )

    if unattributable:
        raise CorrelationCollapseError(
            f"{len(unattributable)} record(s) lack causal_root and cannot be "
            f"joined: {[(r.domain, r.local_id) for r in unattributable]}"
        )

    return traces


def mint_causal_root(task_payload: bytes) -> str:
    """Root authority mints a 128-bit causal token; propagated as opaque field."""
    return hashlib.sha256(task_payload).hexdigest()[:32]
