# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-effects-from-surviving-a-rollback-across-branched-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-effects-from-surviving-a-rollback-across-branched-agents.warrant.json
# Markdown SHA-256:   f8483a631226e780165d85115f8208e8f6a8ea4e4ea60a674e1ed8187f3f729d
# Code AST SHA-256:   20651c777e00e56467e0e9051d04e58a0b1ee0b3e4055e467e522775848a1b56
# Verified Classes:   SpeculationRollbackError, EffectDisposition, SpecEffect, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculationRollbackError(RuntimeError):
    """Raised when a speculative branch is rolled back while it still owns a live effect."""
    pass


class EffectDisposition(Enum):
    STAGED = "staged"            # never escaped; safe to delete
    COMPENSABLE = "compensable"  # escaped but inverse registered and precondition-checkable
    IRREVERSIBLE = "irreversible"  # escaped, no safe inverse
    COMPENSATED = "compensated"  # inverse confirmed; safe to GC marker
    COMMITTED = "committed"      # merged; marker may be released


@dataclass
class SpecEffect:
    spec_id: str
    tool: str
    disposition: EffectDisposition
    inverse_registered: bool
    inverse_confirmed: bool = False


@dataclass
class SpeculativeBranch:
    spec_id: str
    effects: list[SpecEffect] = field(default_factory=list)


def rollback_branch(branch: SpeculativeBranch, quarantine: set[str]) -> None:
    """
    Roll back a discarded branch. Refuses to GC any spec_id that still owns a
    live, uncompensated effect. Quarantines irreversible escapes instead of
    discarding them.
    """
    for eff in branch.effects:
        if eff.disposition == EffectDisposition.STAGED:
            continue  # delete staging row; effect never escaped
        if eff.disposition == EffectDisposition.COMPENSABLE:
            if not eff.inverse_registered:
                raise SpeculationRollbackError(
                    f"spec_id={eff.spec_id} tool={eff.tool} marked compensable "
                    f"but no inverse registered; cannot safely roll back"
                )
            if not eff.inverse_confirmed:
                raise SpeculationRollbackError(
                    f"spec_id={eff.spec_id} tool={eff.tool} inverse not yet confirmed; "
                    f"marker must survive until compensation completes"
                )
            continue
        if eff.disposition == EffectDisposition.IRREVERSIBLE:
            # Do not discard: quarantine the marker so the orphan stays attributable.
            quarantine.add(eff.spec_id)
            raise SpeculationRollbackError(
                f"spec_id={eff.spec_id} tool={eff.tool} is an irreversible escaped "
                f"effect; branch quarantined, merge must halt pending reconciliation"
            )
        if eff.disposition in (EffectDisposition.COMPENSATED, EffectDisposition.COMMITTED):
            continue
    # Only reached if every effect is staged, confirmed-compensated, or committed.
    # Safe to GC branch markers here.
