# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-tenant-trace-aggregation-from-silently-collapsing-distinct-causal-chains-into-a-single-phantom-incident.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-tenant-trace-aggregation-from-silently-collapsing-distinct-causal-chains-into-a-single-phantom-incident.warrant.json
# Markdown SHA-256:   e2bc3ff7822f702f77503ce105e3bf01f94fe15690b8595d71be89d60a35ade6
# Code AST SHA-256:   e992c0277c09b911c0c625d24abb5ea9a9b127db64a8ee2d680c03f3b8ccc733
# Verified Classes:   PhantomIncidentError, ReductionContract
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import math
from dataclasses import dataclass


class PhantomIncidentError(RuntimeError):
    """Raised when a federated aggregation promotes a collision-prone count to an incident."""
    pass


@dataclass
class ReductionContract:
    hash_bits: int
    bucket_seconds: int
    per_tenant_salt: bool
    declared_epsilon: float = 0.01

    def expected_collisions(self, n_records: int) -> float:
        # Birthday-bound on truncated hash collisions over n records.
        return (n_records ** 2) / (2 ** (self.hash_bits + 1))

    def aggregation_mode(self, n_records: int) -> str:
        ec = self.expected_collisions(n_records)
        if not self.per_tenant_salt:
            raise PhantomIncidentError(
                "shared salt across tenants: collisions are cross-tenant and "
                "cannot be bounded by any single tenant's cardinality"
            )
        if ec < 0.01:
            return "frequency_ok"
        if ec < 1.0:
            return "detector_only"
        return "rate_only"


def promote_to_incident(
    contract: ReductionContract,
    tenant_records: int,
    observed_count: int,
    locally_corroborated: bool,
) -> int:
    mode = contract.aggregation_mode(tenant_records)
    if mode == "rate_only":
        raise PhantomIncidentError(
            f"reduction has expected collisions {contract.expected_collisions(tenant_records):.3f} "
            f">= 1.0; observed_count={observed_count} is a collision artifact, not a frequency"
        )
    if mode == "detector_only" and not locally_corroborated:
        raise PhantomIncidentError(
            f"detector-only aggregation (collisions={contract.expected_collisions(tenant_records):.3f}) "
            f"requires tenant-local corroboration before incident promotion"
        )
    # Return the corroborated lower bound, never the raw reduced count.
    return 1 if locally_corroborated else observed_count
