# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-a-trace-segment-rather-than-aggregate-it-cross-org-k-anonymity-collapse-in-federated-agent-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-withhold-a-trace-segment-rather-than-aggregate-it-cross-org-k-anonymity-collapse-in-federated-agent-observability.warrant.json
# Markdown SHA-256:   2ec4bd7226b46921b21fc5a2b4ff56716a4fdfae14e0b52e362655fcaa1885ad
# Code AST SHA-256:   d756fc26a3794cea8ddd2376f9e1c6ec5e684c993dd46bed9230829d60b45897
# Verified Classes:   JointSupportViolation, TraceKey, PublicationState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Dict, Tuple

K_JOINT = 5
K_FAILURE = 10  # higher bar for failure signatures
NOVELTY_WINDOW = 3  # publication buckets a new attribute value must age before eligible


class JointSupportViolation(RuntimeError):
    """Raised when a trace row's published key would disclose a single org."""
    pass


@dataclass(frozen=True)
class TraceKey:
    tool_name: str
    model_id: str
    error_class: str
    time_bucket: int


@dataclass
class PublicationState:
    # key -> set of orgs that contributed
    support: Dict[TraceKey, FrozenSet[str]] = field(default_factory=dict)
    # attribute value -> first bucket it appeared in
    first_seen: Dict[str, int] = field(default_factory=dict)


def check_publishable(
    key: TraceKey,
    contributing_orgs: FrozenSet[str],
    state: PublicationState,
    is_failure: bool,
) -> None:
    """Gate a single row for publication. Raises on any unsafe condition."""
    threshold = K_FAILURE if is_failure else K_JOINT

    # 1. joint support on the full key, counted in distinct orgs
    joint = state.support.get(key, frozenset()) | contributing_orgs
    if len(joint) < threshold:
        raise JointSupportViolation(
            f"joint support {len(joint)} < {threshold} for key {key}; "
            f"withhold to private staging tier"
        )

    # 2. novelty: any attribute value too young to publish
    for attr in (key.tool_name, key.model_id, key.error_class):
        seen_at = state.first_seen.get(attr)
        if seen_at is None:
            raise JointSupportViolation(
                f"attribute {attr!r} has no recorded first-seen; "
                f"cannot certify novelty window"
            )
        if key.time_bucket - seen_at < NOVELTY_WINDOW:
            raise JointSupportViolation(
                f"attribute {attr!r} within novelty window "
                f"(age {key.time_bucket - seen_at} < {NOVELTY_WINDOW}); "
                f"novelty is identifying, withhold"
            )

    # 3. temporal differencing: symmetric difference vs adjacent bucket
    for adj_bucket in (key.time_bucket - 1, key.time_bucket + 1):
        adj_key = TraceKey(key.tool_name, key.model_id, key.error_class, adj_bucket)
        adj_orgs = state.support.get(adj_key)
        if adj_orgs is None:
            continue  # no adjacent publication, no differencing risk
        sym_diff = joint.symmetric_difference(adj_orgs)
        if 0 < len(sym_diff) < threshold:
            raise JointSupportViolation(
                f"differencing leak vs bucket {adj_bucket}: "
                f"symmetric org difference {len(sym_diff)} < {threshold}; "
                f"coarsen time bucket or withhold"
            )

    # safe: record support for future differencing checks
    state.support[key] = joint
    for attr in (key.tool_name, key.model_id, key.error_class):
        state.first_seen.setdefault(attr, key.time_bucket)


def publish_batch(rows, state: PublicationState) -> list:
    published, withheld = [], []
    for key, orgs, is_failure in rows:
        try:
            check_publishable(key, orgs, state, is_failure)
            published.append(key)
        except JointSupportViolation as e:
            withheld.append((key, str(e)))
    return published, withheld
