# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-quorum-based-recovery-as-a-deadlock-source-rather-than-a-deadlock-remedy-in-federated-task-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-quorum-based-recovery-as-a-deadlock-source-rather-than-a-deadlock-remedy-in-federated-task-graphs.warrant.json
# Markdown SHA-256:   b55bb7a91e571d79e716f21c19f175df9117f4604b4e2bc7120a926850e637f4
# Code AST SHA-256:   1057ad9e65c5f6c237eaefa989493139180306be4c543d03142bf05929cc3925
# Verified Classes:   QuorumRecoveryMisapplied, Agent, TaskGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Dict, Set, List


class QuorumRecoveryMisapplied(RuntimeError):
    """Raised when a quorum round is opened over a stall whose causal
    closure intersects the voter pool, converting recovery into deadlock."""
    pass


@dataclass
class Agent:
    agent_id: str
    pending_handoffs_out: Set[str] = field(default_factory=set)  # target agent ids
    frozen: bool = False


@dataclass
class TaskGraph:
    agents: Dict[str, Agent]
    # handoff edges: (from_agent, to_agent, task_id)
    handoff_edges: List[tuple] = field(default_factory=list)

    def reverse_reachable_agents(self, stalled_task_owner: str) -> Set[str]:
        """Agents whose outbound handoffs are causally upstream of the stall."""
        upstream: Set[str] = set()
        frontier = {stalled_task_owner}
        while frontier:
            nxt = set()
            for (src, dst, _task) in self.handoff_edges:
                if dst in frontier and src not in upstream:
                    upstream.add(src)
                    nxt.add(src)
            frontier = nxt
        return upstream


def open_quorum_round(
    graph: TaskGraph,
    stall_signals: Set[str],
    quorum_threshold: int,
    drain_timeout_s: float = 5.0,
) -> Dict[str, str]:
    # Phase 1: bounded, NON-FREEZING handoff drain.
    deadline = time.monotonic() + drain_timeout_s
    for agent_id in list(stall_signals):
        agent = graph.agents[agent_id]
        while agent.pending_handoffs_out and time.monotonic() < deadline:
            # re-drive pending handoffs; never freeze the sender
            agent.pending_handoffs_out.pop()
    residual_stalls = {
        a for a in stall_signals
        if graph.agents[a].pending_handoffs_out
    }
    if not residual_stalls:
        return {"status": "healed_by_drain"}

    # Phase 2: causal-closure check against voter pool.
    causal_upstream: Set[str] = set()
    for stalled_owner in residual_stalls:
        causal_upstream |= graph.reverse_reachable_agents(stalled_owner)

    eligible_voters = set(graph.agents) - causal_upstream
    if len(eligible_voters) < quorum_threshold:
        raise QuorumRecoveryMisapplied(
            f"quorum threshold {quorum_threshold} unreachable: "
            f"{len(causal_upstream)} agents are causally upstream of the "
            f"residual stall and must be excluded from the voter pool; "
            f"only {len(eligible_voters)} eligible voters remain. "
            f"Opening the round would freeze the handoffs that heal the stall."
        )

    # Freeze only eligible voters; never freeze causal-upstream agents.
    for agent_id in eligible_voters:
        graph.agents[agent_id].frozen = True

    return {
        "status": "quorum_open",
        "voters": sorted(eligible_voters),
        "excluded_causal": sorted(causal_upstream),
    }
