# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-quorum-shopping-collusion-when-byzantine-agents-forge-independent-attestations-in-a-federated-task-allocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-quorum-shopping-collusion-when-byzantine-agents-forge-independent-attestations-in-a-federated-task-allocation.warrant.json
# Markdown SHA-256:   9971b1213ffffdd77c29d7206f16a64c4af059c5ea0e0cb2514e05aa3d5b942b
# Code AST SHA-256:   d9dab26c7b75916ce3ad5aac863b3e27758d7f9e90624a2362f01c0ce26faf9c
# Verified Classes:   QuorumSoundnessError, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import math
from dataclasses import dataclass
from typing import Sequence


class QuorumSoundnessError(RuntimeError):
    """Raised when a quorum decision is derived from correlated attestations
    without collapsing them to independent sources first."""


@dataclass(frozen=True)
class Attestation:
    agent_id: str
    result_hash: str
    observation_id: str
    arrival_ms: float
    issuance_batch: str  # registrar batch; shared batch => correlated by construction


def estimate_correlation_clusters(
    attestations: Sequence[Attestation],
    latency_cluster_ms: float = 25.0,
) -> list[list[Attestation]]:
    """Collapse attestations into independent-source clusters.

    Two attestations are treated as the same source if they share an issuance
    batch (admission-lineage correlation) OR arrive within latency_cluster_ms
    of each other AND agree on result_hash (shared-trigger correlation).
    This is deliberately conservative: it over-collapses rather than
    under-collapses, because over-counting independence is a silent
    soundness failure while under-counting is a visible liveness cost.
    """
    clusters: list[list[Attestation]] = []
    for att in attestations:
        placed = False
        for cluster in clusters:
            rep = cluster[0]
            same_batch = rep.issuance_batch == att.issuance_batch
            tight_arrival = abs(rep.arrival_ms - att.arrival_ms) <= latency_cluster_ms
            same_result = rep.result_hash == att.result_hash
            if same_batch or (tight_arrival and same_result):
                cluster.append(att)
                placed = True
                break
        if not placed:
            clusters.append([att])
    return clusters


def source_count_quorum(
    attestations: Sequence[Attestation],
    n_total_agents: int,
    latency_cluster_ms: float = 25.0,
) -> tuple[bool, int, int]:
    """Return (quorum_met, independent_sources, required_threshold).

    Quorum is computed against the *source-collapsed* population, never the
    raw message count. If the collapsed population cannot support the
    Byzantine bound, the decision must fail closed.
    """
    if not attestations:
        raise QuorumSoundnessError("no attestations to evaluate")

    clusters = estimate_correlation_clusters(attestations, latency_cluster_ms)
    independent_sources = len(clusters)

    # Effective N collapses colluding clusters to single sources.
    effective_n = n_total_agents - len(attestations) + independent_sources
    if effective_n < 1:
        raise QuorumSoundnessError(
            f"effective population {effective_n} is degenerate; "
            f"cannot bound f for {n_total_agents} agents"
        )

    # f bound is only valid against the effective (collapsed) population.
    f_effective = (effective_n - 1) // 3
    required = effective_n - f_effective  # 2f+1 in collapsed terms

    # The largest agreeing cluster is the only evidence that can satisfy quorum.
    largest_cluster = max(len(c) for c in clusters)
    # Independent support = number of clusters whose representative agrees with
    # the majority result_hash, counted as *sources*, not messages.
    result_hashes = [c[0].result_hash for c in clusters]
    majority_hash = max(set(result_hashes), key=result_hashes.count)
    independent_support = sum(
        1 for c in clusters if c[0].result_hash == majority_hash
    )

    if independent_support < required:
        return False, independent_support, required
    if largest_cluster > f_effective:
        # A single cluster exceeding f means the colluders alone could swing
        # the decision; quorum is unsound even if support nominally clears.
        raise QuorumSoundnessError(
            f"correlation cluster of {largest_cluster} exceeds f_effective="
            f"{f_effective}; quorum derived from a single source"
        )
    return True, independent_support, required


def commit_decision(
    attestations: Sequence[Attestation],
    n_total_agents: int,
) -> str:
    ok, support, required = source_count_quorum(attestations, n_total_agents)
    if not ok:
        # Unresolved, not rejected: honest minority may be the only independent
        # evidence and must be preserved for a fresh-sample audit.
        raise QuorumSoundnessError(
            f"quorum unresolved: {support} independent sources < {required} "
            f"required after correlation collapse; task must re-sample, "
            f"not commit and not discard minority attestations"
        )
    return "committed"
