# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-rollback-as-unsafe-when-side-effecting-tool-calls-have-already-escaped-the-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-rollback-as-unsafe-when-side-effecting-tool-calls-have-already-escaped-the-sandbox.warrant.json
# Markdown SHA-256:   9432d7924e2368c11fe50e61c47f84d6676390eabe623e81d951dd248d92e3dc
# Code AST SHA-256:   a88372487c07661c477934dc2bfe609ccde932bb57e3b3116b0f2ab04cc87cdc
# Verified Classes:   Reversibility, UnsafeRollbackError, Effect, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum

class Reversibility(Enum):
    PURE = "pure"
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    UNKNOWN_SIDE_EFFECT = "unknown_side_effect"

class UnsafeRollbackError(RuntimeError):
    """Raised when a branch is pruned while carrying an unresolved external effect."""
    pass

@dataclass
class Effect:
    logical_effect_id: str
    reversibility: Reversibility
    ack_observed: bool = False
    compensated: bool = False

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

def effect_ledger_clean(branch: Branch) -> bool:
    for e in branch.effects:
        if e.reversibility is Reversibility.PURE:
            continue
        if e.reversibility is Reversibility.IDEMPOTENT and e.ack_observed:
            continue
        if e.reversibility is Reversibility.COMPENSABLE and e.compensated:
            continue
        return False
    return True

def prune(branch: Branch, resource_locks: set[str]) -> str:
    if not effect_ledger_clean(branch):
        # Do NOT rollback-and-forget. Quarantine and reconcile.
        leaked = [e.logical_effect_id for e in branch.effects
                  if e.reversibility is Reversibility.UNKNOWN_SIDE_EFFECT
                  or (e.reversibility is Reversibility.IDEMPOTENT and not e.ack_observed)]
        if any(e.logical_effect_id in resource_locks for e in branch.effects):
            raise UnsafeRollbackError(
                f"branch {branch.branch_id} carries unresolved effects {leaked} "
                f"on locked resources; rollback forbidden, quarantine required"
            )
        return "QUARANTINED"
    return "PRUNED"
