# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-abort-a-collusive-auction-coalition-before-it-corrupts-task-allocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-abort-a-collusive-auction-coalition-before-it-corrupts-task-allocation.warrant.json
# Markdown SHA-256:   c02d2afd09a9a7dea4784e02550ae4cd9dfd746ae133c179e0aea7f535ed1569
# Code AST SHA-256:   eb07c03bcec0aca15ca66ce39027f06da27e2bc6f6c8a5088fb807dfc7e2017c
# Verified Classes:   CollusiveCoalitionError, RoundResult, CoalitionMonitor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict


class CollusiveCoalitionError(RuntimeError):
    """Raised when a persistent co-winning agent set diverges from predicted cost."""
    pass


@dataclass
class RoundResult:
    round_id: int
    winning_set: frozenset
    predicted_cost: float
    realized_cost: float


@dataclass
class CoalitionMonitor:
    persistence_rounds: int = 3
    divergence_ratio: float = 1.5
    history: list = field(default_factory=list)

    def record(self, result: RoundResult) -> None:
        self.history.append(result)

    def _consecutive_co_wins(self, agent_set: frozenset) -> int:
        count = 0
        for r in reversed(self.history):
            if r.winning_set == agent_set:
                count += 1
            else:
                break
        return count

    def _mean_divergence(self, agent_set: frozenset) -> float:
        ratios = [
            r.realized_cost / r.predicted_cost
            for r in self.history
            if r.winning_set == agent_set and r.predicted_cost > 0
        ]
        if not ratios:
            return 0.0
        return sum(ratios) / len(ratios)

    def check_boundary(self) -> None:
        if not self.history:
            return
        latest_set = self.history[-1].winning_set
        persistence = self._consecutive_co_wins(latest_set)
        divergence = self._mean_divergence(latest_set)

        # Conjunction: both conditions must hold. Persistence alone is legitimate
        # specialization; divergence alone is a single bad round.
        if persistence >= self.persistence_rounds and divergence > self.divergence_ratio:
            raise CollusiveCoalitionError(
                f"Coalition {sorted(latest_set)} co-won {persistence} consecutive "
                f"rounds with mean realized/predicted ratio {divergence:.2f} "
                f"(threshold {self.divergence_ratio}). Void award; re-auction with "
                f"de-shared bidder contexts."
            )


def dispatch_round(monitor: CoalitionMonitor, result: RoundResult) -> str:
    """Gate between bid close and task dispatch. Void before execution, never after."""
    monitor.record(result)
    try:
        monitor.check_boundary()
    except CollusiveCoalitionError:
        # Do NOT blacklist agents. Void the award and de-share contexts.
        return "VOID_AND_REAUCTION_DESHARED"
    return "DISPATCH"
