# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-reconciliation-becomes-non-deterministic-across-parallel-agent-plans.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-fan-out-before-rollback-reconciliation-becomes-non-deterministic-across-parallel-agent-plans.warrant.json
# Markdown SHA-256:   7a06e580638ca0f94f8cb02ff89d9fc2767d4222299d67d8d29ea0652e1c081c
# Code AST SHA-256:   bb9d000567080bc583f5d3bdf2960fb46b60e347d2b14cd7675ae08853dba0bd
# Verified Classes:   SpeculationBoundaryError, JournalState, EffectJournalEntry, Branch, SpeculationOrchestrator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculationBoundaryError(RuntimeError):
    """Raised when speculative fan-out exceeds compensable-effect capacity
    or when rollback encounters a journal state that cannot be safely resolved."""
    pass


class JournalState(Enum):
    INTENT = "intent"        # effect attempted, receipt not yet recorded
    RECEIPT = "receipt"      # effect confirmed landed
    COMPENSATED = "compensated"


@dataclass
class EffectJournalEntry:
    handle: str
    state: JournalState
    receipt: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    real_effect_authority: bool
    journal: list[EffectJournalEntry] = field(default_factory=list)
    quarantined: bool = False


class SpeculationOrchestrator:
    def __init__(self, compensation_capacity: int):
        if compensation_capacity < 1:
            raise SpeculationBoundaryError(
                f"compensation_capacity must be >= 1, got {compensation_capacity}"
            )
        self.capacity = compensation_capacity
        self.active_real_effect_branches: list[Branch] = []
        self.seen_handles: set[str] = set()

    def launch_branch(self, branch: Branch) -> None:
        if not branch.real_effect_authority:
            return  # shadow mode: unbounded, no effect authority
        if len(self.active_real_effect_branches) >= self.capacity:
            raise SpeculationBoundaryError(
                f"refusing to grant real-effect authority to {branch.branch_id}: "
                f"compensation capacity {self.capacity} exhausted by "
                f"{[b.branch_id for b in self.active_real_effect_branches]}"
            )
        self.active_real_effect_branches.append(branch)

    def record_effect(self, branch: Branch, handle: str) -> None:
        if handle in self.seen_handles:
            raise SpeculationBoundaryError(
                f"duplicate compensation handle {handle!r} from {branch.branch_id}: "
                "handles must be globally unique or compensation will double-release"
            )
        self.seen_handles.add(handle)
        branch.journal.append(EffectJournalEntry(handle=handle, state=JournalState.INTENT))

    def confirm_effect(self, branch: Branch, handle: str, receipt: str) -> None:
        for entry in branch.journal:
            if entry.handle == handle and entry.state is JournalState.INTENT:
                entry.state = JournalState.RECEIPT
                entry.receipt = receipt
                return
        raise SpeculationBoundaryError(
            f"confirm_effect for unknown or non-intent handle {handle!r} on {branch.branch_id}"
        )

    def rollback(self, branch: Branch) -> list[str]:
        """Consume the journal, not the transcript. Refuse on incomplete journals."""
        if not branch.real_effect_authority:
            return []
        for entry in branch.journal:
            if entry.state is JournalState.INTENT:
                # effect may or may not have landed; cannot assume either way
                branch.quarantined = True
                raise SpeculationBoundaryError(
                    f"cannot roll back {branch.branch_id}: handle {entry.handle!r} "
                    "has intent without receipt; quarantine and probe out-of-band"
                )
        compensated = []
        for entry in branch.journal:
            if entry.state is JournalState.RECEIPT:
                entry.state = JournalState.COMPENSATED
                compensated.append(entry.handle)
        if branch in self.active_real_effect_branches:
            self.active_real_effect_branches.remove(branch)
        return compensated
