# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-side-effects-when-speculative-agent-branches-roll-back-after-a-shared-resource-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-side-effects-when-speculative-agent-branches-roll-back-after-a-shared-resource-commit.warrant.json
# Markdown SHA-256:   547f23fe607ceaf16fa8455cae1dd8d7ebe279d3975de494ad17c8faa8cb0ac9
# Code AST SHA-256:   5ac2d0de13996ee7066b14292d26b8dbc41cf1b7aeabf238d1ac688c8c4f64a9
# Verified Classes:   OrphanedEffectError, EffectClass, CommitTokenGate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class OrphanedEffectError(RuntimeError):
    """Raised when a speculative branch attempts an irreversible effect
    before global nomination, or when rollback verification finds an
    uncompensated external effect."""
    pass


class EffectClass:
    PURE = "pure"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class CommitTokenGate:
    def __init__(self):
        self._nominated_branch = None
        self._token_consumed = False

    def nominate(self, branch_id):
        if self._nominated_branch is not None:
            raise OrphanedEffectError(
                f"nomination already held by {self._nominated_branch}; "
                f"cannot nominate {branch_id} — commit phase must serialize"
            )
        self._nominated_branch = branch_id
        self._token_consumed = False

    def authorize(self, branch_id, tool_name, effect_class):
        if effect_class == EffectClass.PURE:
            return True
        if effect_class == EffectClass.IRREVERSIBLE:
            if self._nominated_branch != branch_id:
                raise OrphanedEffectError(
                    f"branch {branch_id} attempted irreversible tool "
                    f"'{tool_name}' before nomination (holder="
                    f"{self._nominated_branch}); effect must be deferred to outbox"
                )
            if self._token_consumed:
                raise OrphanedEffectError(
                    f"commit token for {branch_id} already consumed; "
                    f"irreversible tools are single-use per nomination"
                )
            self._token_consumed = True
            return True
        # COMPENSABLE: allowed only if handle is journaled synchronously
        return True


def rollback_branch(branch_id, journal, environment):
    for entry in reversed(journal):
        if entry.effect_class == EffectClass.PURE:
            continue
        if entry.effect_class == EffectClass.IRREVERSIBLE:
            raise OrphanedEffectError(
                f"branch {branch_id} journal contains irreversible effect "
                f"'{entry.tool}' with no compensation contract; "
                f"this branch was not speculable"
            )
        environment.compensate(entry.handle)
    # verify against environment, not the journal
    residual = environment.query_effects_by_token(branch_id)
    if residual:
        raise OrphanedEffectError(
            f"rollback of {branch_id} left {len(residual)} live effect(s) "
            f"in environment: {[r.id for r in residual]}"
        )
