# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-rollback-when-subagent-divergence-is-detected-only-after-side-effects-have-already-been-committed-to-a-shared.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-rollback-when-subagent-divergence-is-detected-only-after-side-effects-have-already-been-committed-to-a-shared.warrant.json
# Markdown SHA-256:   e29bb2126a05898344a840f0f8f5e4fe443140443cf5ef0646ca5273b076b5c4
# Code AST SHA-256:   8f7a14e84f51cea44da8584439b0274f20e96579e61b93f8ac3993f79d6d5f34
# Verified Classes:   EffectIrreversibilityError, Phase, EffectProposal, Branch, SpeculativeOrchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectIrreversibilityError(RuntimeError):
    """Raised when a speculative branch attempts to commit an effect
    whose blast radius escapes the checkpointed region before divergence
    has been adjudicated over the full effect log."""
    pass


class Phase(Enum):
    SPECULATIVE = "speculative"
    ADJUDICATED = "adjudicated"
    COMMITTED = "committed"


@dataclass(frozen=True)
class EffectProposal:
    branch_id: str
    resource: str          # e.g. "ledger:acct_42", "memory:auditor"
    op: str                # e.g. "refund", "hold"
    reversible: bool


@dataclass
class Branch:
    branch_id: str
    proposals: List[EffectProposal] = field(default_factory=list)
    answer: str = ""


class SpeculativeOrchestrator:
    def __init__(self, checkpoint_region: Set[str]):
        # The set of resources whose state is captured/restored by rollback.
        self.checkpoint_region = checkpoint_region
        self.phase = Phase.SPECULATIVE
        self.committed_effects: List[EffectProposal] = []

    def propose(self, branch: Branch, proposal: EffectProposal) -> None:
        if self.phase is not Phase.SPECULATIVE:
            raise EffectIrreversibilityError(
                f"branch {branch.branch_id} proposed effect {proposal.op} "
                f"on {proposal.resource} after adjudication phase began"
            )
        branch.proposals.append(proposal)

    def apply_speculatively(self, branch: Branch, proposal: EffectProposal) -> None:
        # The forbidden path: eager commit of an irreversible effect whose
        # blast radius escapes the checkpoint region before divergence is known.
        if not proposal.reversible and proposal.resource not in self.checkpoint_region:
            raise EffectIrreversibilityError(
                f"branch {branch.branch_id} attempted speculative commit of "
                f"irreversible effect {proposal.op} on {proposal.resource}, "
                f"which lies outside checkpoint region {sorted(self.checkpoint_region)}; "
                f"must propose-only until divergence is adjudicated over the effect log"
            )
        self.committed_effects.append(proposal)

    def adjudicate_and_commit(self, branches: List[Branch]) -> List[EffectProposal]:
        self.phase = Phase.ADJUDICATED
        # Divergence must be computed over the effect-proposal multiset,
        # not over answers, to satisfy divergence completeness.
        effect_signatures: Dict[frozenset, List[Branch]] = {}
        for b in branches:
            sig = frozenset((p.resource, p.op) for p in b.proposals)
            effect_signatures.setdefault(sig, []).append(b)
        if len(effect_signatures) > 1:
            # Divergence detected; only the largest effect-equivalent group survives.
            winner_group = max(effect_signatures.values(), key=len)
        else:
            winner_group = branches
        surviving = {b.branch_id for b in winner_group}
        committed = [p for b in winner_group for p in b.proposals]
        # Atomic commit: apply all surviving proposals, broadcast to observers.
        self.committed_effects.extend(committed)
        self.phase = Phase.COMMITTED
        return committed

    def assert_observer_consistency(self, observer_memory: Set[tuple]) -> None:
        committed_set = {(p.resource, p.op) for p in self.committed_effects}
        phantom = observer_memory - committed_set
        if phantom:
            raise EffectIrreversibilityError(
                f"observer memory references effects absent from committed world: "
                f"{sorted(phantom)}; rollback boundary excluded observer state"
            )
