# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-plan-branch-before-its-compensating-actions-have-quiesced-rollback-ordering-divergence-in-parallel-agent-pla.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-plan-branch-before-its-compensating-actions-have-quiesced-rollback-ordering-divergence-in-parallel-agent-pla.warrant.json
# Markdown SHA-256:   1e12b891961394fdd64cecbdfc3639fe867e7d96315f260cdb604fe0bd047dc9
# Code AST SHA-256:   66ed863ac6fa0f8d75d44d3dd8530037d389bcc56ac1bc7af528431bab375654
# Verified Classes:   QuiescenceViolation, EffectStatus, Effect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class QuiescenceViolation(RuntimeError):
    """Raised when a committed branch would touch state a losing branch still mutates."""
    pass


class EffectStatus(Enum):
    PROPOSED = "proposed"
    DISPATCHED = "dispatched"
    LANDED = "landed"
    COMPENSATED = "compensated"
    COMPENSATION_FAILED = "compensation_failed"


@dataclass
class Effect:
    effect_id: str
    resources: Set[str]
    status: EffectStatus = EffectStatus.PROPOSED


@dataclass
class Branch:
    branch_id: str
    ledger: List[Effect] = field(default_factory=list)

    def footprint(self) -> Set[str]:
        return {r for e in self.ledger for r in e.resources}

    def is_quiescent(self) -> bool:
        for e in self.ledger:
            if e.status in (EffectStatus.DISPATCHED, EffectStatus.PROPOSED):
                return False
            if e.status == EffectStatus.LANDED:
                return False  # landed but not yet compensated
            if e.status == EffectStatus.COMPENSATION_FAILED:
                return False
        return True

    def has_failed_compensation(self) -> bool:
        return any(e.status == EffectStatus.COMPENSATION_FAILED for e in self.ledger)


def await_quiescence(branches: List[Branch], deadline_s: float, poll_s: float = 0.5) -> None:
    start = time.monotonic()
    while time.monotonic() - start < deadline_s:
        if all(b.is_quiescent() for b in branches):
            return
        if any(b.has_failed_compensation() for b in branches):
            bad = [b.branch_id for b in branches if b.has_failed_compensation()]
            raise QuiescenceViolation(
                f"compensation_failed on branches {bad}: live mutation with no reverse; "
                f"committed branch must be held and escalated"
            )
        time.sleep(poll_s)
    pending = [b.branch_id for b in branches if not b.is_quiescent()]
    raise QuiescenceViolation(
        f"branches {pending} did not quiesce within {deadline_s}s; "
        f"proceeding would let committed branch write into a live losing branch"
    )


def commit_with_fencing(
    winner: Branch,
    losers: List[Branch],
    winner_next_resources: Set[str],
    deadline_s: float,
) -> None:
    # Logical abort first (immediate), then physical drain (bounded), then commit.
    for b in losers:
        for e in b.ledger:
            if e.status == EffectStatus.DISPATCHED:
                pass  # abort signal sent; in-flight calls still land

    await_quiescence(losers, deadline_s)

    # Read-set fencing: winner may not touch any loser footprint.
    forbidden: Set[str] = set()
    for b in losers:
        forbidden |= b.footprint()
    collision = winner_next_resources & forbidden
    if collision:
        raise QuiescenceViolation(
            f"winner {winner.branch_id} next step touches {collision}, "
            f"still in losing-branch footprint; fencing violated"
        )
    # Only now is the commit safe.
    return None


def run_forked_plan(winner: Branch, losers: List[Branch], next_resources: Set[str]) -> None:
    try:
        commit_with_fencing(winner, losers, next_resources, deadline_s=120.0)
    except QuiescenceViolation as exc:
        # Escalate; do not proceed into a live losing branch.
        raise QuiescenceViolation(f"commit of {winner.branch_id} blocked: {exc}") from exc
