# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-exports-a-federated-trace-aggregate-whose-span-level-k-anonymity-is-satisfied-per-organization-but-violated-after-cross.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-exports-a-federated-trace-aggregate-whose-span-level-k-anonymity-is-satisfied-per-organization-but-violated-after-cross.warrant.json
# Markdown SHA-256:   65fa0e87b2fe9e89dad8220e4b09cb0458360e720aa53620d9fe76add397122a
# Code AST SHA-256:   76f5cfc52e518dc09a3e6b9e0da582d27c2be26200d5cb0709b246b88a1888d0
# Verified Classes:   FederatedKAnonymityViolation, OrgExport, MergedBucket
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict
from typing import Dict, Tuple, List

K_MIN = 5


class FederatedKAnonymityViolation(RuntimeError):
    """Raised when a merged federated trace bucket falls below k after union,
    even though every contributing org certified k locally."""
    pass


@dataclass
class OrgExport:
    org_id: str
    # tuple -> true count reported by the org (post-DP in production)
    buckets: Dict[Tuple, int] = field(default_factory=dict)
    # tuple -> locally certified min bucket size (the manifest claim)
    certified_min: int = K_MIN


@dataclass
class MergedBucket:
    quasi_id: Tuple
    total_count: int
    contributing_orgs: List[str]


def merge_and_enforce(
    exports: List[OrgExport],
    auxiliary_join_keys: List[Tuple],
) -> List[MergedBucket]:
    """Merge per-org bucket counts, then enforce k-anonymity on the UNION.

    auxiliary_join_keys are tuples the merger can join against external
    feeds (incident tickets, deployment logs). If any auxiliary key is a
    strict subset of a merged quasi-id, that quasi-id is treated as a
    de-anonymizer and its effective k is 1 regardless of count.
    """
    totals: Dict[Tuple, int] = defaultdict(int)
    orgs: Dict[Tuple, List[str]] = defaultdict(list)

    for exp in exports:
        # Reject orgs that claim a weaker invariant than the federation floor.
        if exp.certified_min < K_MIN:
            raise FederatedKAnonymityViolation(
                f"org {exp.org_id} certifies k={exp.certified_min} < {K_MIN}"
            )
        for qid, count in exp.buckets.items():
            totals[qid] += count
            orgs[qid].append(exp.org_id)

    merged: List[MergedBucket] = []
    for qid, total in totals.items():
        # The actual invariant: cardinality of the MERGED bucket.
        if total < K_MIN:
            raise FederatedKAnonymityViolation(
                f"merged bucket {qid} has k={total} < {K_MIN} "
                f"(contributors: {orgs[qid]}); per-org manifests were "
                f"individually valid but union collapsed the group"
            )
        # The subtle invariant: auxiliary joins on subsets void the count.
        for aux in auxiliary_join_keys:
            if _is_strict_subset(aux, qid):
                raise FederatedKAnonymityViolation(
                    f"merged bucket {qid} is joinable on strict subset {aux}; "
                    f"effective k=1 despite count={total}"
                )
        merged.append(MergedBucket(qid, total, orgs[qid]))

    return merged


def _is_strict_subset(aux: Tuple, qid: Tuple) -> bool:
    """True if every field of aux appears in qid and qid has more fields."""
    if len(aux) >= len(qid):
        return False
    return all(a in qid for a in aux)


# --- Reproduction of the observed failure -------------------------------

def reproduce_incident():
    qid = ("mcp__fs__write", "claude-x", 2, 9)  # tool, model, retry, lat_decile
    exports = [
        OrgExport("A", {qid: 6}),  # passes local k=5
        OrgExport("B", {qid: 5}),  # passes local k=5
        OrgExport("C", {qid: 7}),  # passes local k=5
    ]
    # Incident feed keyed on (tool, model) — a strict subset of qid.
    aux = [("mcp__fs__write", "claude-x")]

    try:
        merge_and_enforce(exports, aux)
    except FederatedKAnonymityViolation as e:
        print(f"BLOCKED: {e}")
        return

    raise FederatedKAnonymityViolation(
        "merger released a joinable bucket; invariant not enforced"
    )


if __name__ == "__main__":
    reproduce_incident()
