# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-speculative-execution-livelock-from-genuine-multi-agent-deadlock-when-federated-schedulers-keep-re-issuing-the-same.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-speculative-execution-livelock-from-genuine-multi-agent-deadlock-when-federated-schedulers-keep-re-issuing-the-same.warrant.json
# Markdown SHA-256:   bba685d629fa4db7f05984f7bef6aa4c199020c2e1324a4a1e8f07271202ccfb
# Code AST SHA-256:   73958b6a6f600522786f7735de7e1300129aec4c7b8165391a16b28f0262bf1c
# Verified Classes:   SchedulerInvariantViolation, Classification, Agent, Slot
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Set


class SchedulerInvariantViolation(RuntimeError):
    """Raised when speculation policy would re-issue a baton that already committed."""
    pass


class Classification(Enum):
    PROGRESS = "progress"
    DEADLOCK = "deadlock"
    LIVELOCK = "livelock"


@dataclass
class Agent:
    agent_id: str
    blocked_on: Optional[str] = None      # resource id if blocked
    lease_expires_epoch: int = 10**9      # unexpired by default


@dataclass
class Slot:
    slot_id: str
    committed_hash_by_epoch: Dict[int, str] = field(default_factory=dict)

    def distinct_values(self) -> Set[str]:
        return set(self.committed_hash_by_epoch.values())


def has_wait_for_cycle(agents: List[Agent], epoch: int) -> bool:
    """Cycle among agents blocked on resources held by other *unexpired-lease* agents."""
    holder: Dict[str, str] = {}
    for a in agents:
        if a.blocked_on is not None and a.lease_expires_epoch > epoch:
            holder[a.agent_id] = a.blocked_on
    # resource -> agent that holds it (blocked_on points at a holder's agent_id)
    graph: Dict[str, str] = {}
    for aid, res in holder.items():
        if res in holder:            # blocked on another live agent
            graph[aid] = res
    seen: Set[str] = set()
    for start in graph:
        cur = start
        path: Set[str] = set()
        while cur in graph and cur not in path:
            path.add(cur)
            cur = graph[cur]
        if cur in path:
            return True
    return False


def classify(
    agents: List[Agent],
    slots: List[Slot],
    epoch: int,
    speculation_factor: int,
) -> Classification:
    if has_wait_for_cycle(agents, epoch):
        return Classification.DEADLOCK
    for slot in slots:
        if len(slot.distinct_values()) > speculation_factor:
            # commit set keeps changing but never converges: speculation churn
            return Classification.LIVELOCK
    return Classification.PROGRESS


def guard_redispatch(
    slot: Slot,
    last_dispatch_epoch: int,
    current_epoch: int,
    speculation_factor: int,
) -> None:
    """Enforce: re-dispatch only if slot hash unchanged since last dispatch.

    If the slot changed AND we already have more distinct values than the
    speculation factor, re-dispatching will deepen the livelock, not fix it.
    """
    changed_since_dispatch = (
        last_dispatch_epoch not in slot.committed_hash_by_epoch
        or slot.committed_hash_by_epoch[last_dispatch_epoch]
        != slot.committed_hash_by_epoch.get(current_epoch)
    )
    if changed_since_dispatch and len(slot.distinct_values()) > speculation_factor:
        raise SchedulerInvariantViolation(
            f"slot {slot.slot_id!r} diverged across "
            f"{len(slot.distinct_values())} values > speculation_factor "
            f"{speculation_factor}; re-dispatch would deepen livelock. "
            f"Collapse to single-writer and freeze slot."
        )
