# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-scheduling-from-committing-unverified-side-effects-when-early-abort-heuristics-fire-mid-fanout.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-scheduling-from-committing-unverified-side-effects-when-early-abort-heuristics-fire-mid-fanout.warrant.json
# Markdown SHA-256:   dfcb8f196dc8ac0ea42aa39d654bdd58b6de980c1f6fb0c4f943d98b670d4449
# Code AST SHA-256:   612319a512c295cb00a69fa1dd88571a87a90bed9f673109d9ad0e8388c1f032
# Verified Classes:   EffectClass, UnreconciledAbortError, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class EffectClass(Enum):
    READ_ONLY = "read_only"
    IDEMPOTENT = "idempotent"
    SHARED_MUTATING = "shared_mutating"


class UnreconciledAbortError(RuntimeError):
    """Raised when an early-abort heuristic fires on a branch whose
    non-idempotent shared-state effects have already committed, without
    routing through a reconciliation handler."""
    pass


@dataclass
class Branch:
    branch_id: str
    effect_class: EffectClass
    committed_effects: list = field(default_factory=list)
    scored: bool = False
    aborted: bool = False


def early_abort(branch: Branch, reconciliation_available: bool) -> None:
    """Attempt to de-schedule a speculative branch under a cost heuristic.

    Invariant enforced: a branch may only transition to aborted without
    reconciliation when its effect frontier is closed (no committed
    non-idempotent shared-state writes).
    """
    frontier_open = (
        branch.effect_class is EffectClass.SHARED_MUTATING
        and len(branch.committed_effects) > 0
        and not branch.scored
    )

    if frontier_open and not reconciliation_available:
        raise UnreconciledAbortError(
            f"branch {branch.branch_id} has {len(branch.committed_effects)} "
            f"committed shared-mutating effect(s) and was never scored; "
            f"aborting would leak unverified writes into shared state. "
            f"Provide a reconciliation handler or keep the branch in the "
            f"scored set."
        )

    if frontier_open and reconciliation_available:
        # Abort is legal only as a reconciliation event, not a deallocation.
        # The handler is responsible for rollback or retroactive scoring.
        branch.aborted = True
        return

    # Closed frontier: safe, cheap deallocation.
    branch.aborted = True


def schedule_speculative(branches: list, abort_triggered: bool,
                         reconciliation_available: bool) -> Optional[Branch]:
    """Select a winner under an early-abort heuristic with commit-barrier checks."""
    if abort_triggered:
        for b in branches:
            if not b.scored:
                early_abort(b, reconciliation_available)

    scored = [b for b in branches if b.scored and not b.aborted]
    if not scored:
        raise UnreconciledAbortError(
            "early-abort fired before any branch was scored; no winner exists "
            "and reconciliation is required for all open frontiers."
        )
    return scored[0]
