# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-branches-from-leaking-uncommitted-side-effects-across-a-rollback-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-agent-branches-from-leaking-uncommitted-side-effects-across-a-rollback-barrier.warrant.json
# Markdown SHA-256:   f92a8ab45755e90d67643764ce11479f90b1942b0561064e4568faae73c8bbc9
# Code AST SHA-256:   3968fe8c20eb5fd7236ba21ed8fdd837ec072fed69bfb8e943843b2ec0a821bb
# Verified Classes:   SpeculativeEffectLeak, BranchScope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeEffectLeak(RuntimeError):
    """Raised when a discarded speculative branch leaves observable effects
    that survive rollback and are not attributable to the committed branch."""
    pass


class BranchScope:
    def __init__(self, branch_id: str, revocable: bool, irreversible: bool):
        self.branch_id = branch_id
        self.revocable = revocable
        self.irreversible = irreversible
        self.deferred_callbacks = []
        self.declared_effects = set()
        self.observed_effects = set()
        self.retired = False


def discard_branch(scope: BranchScope) -> None:
    if scope.irreversible and not scope.retired:
        # You may not silently discard a branch that has committed an
        # irreversible effect; that effect is already in the world.
        raise SpeculativeEffectLeak(
            f"branch {scope.branch_id} holds irreversible effects; "
            f"cannot roll back, must reconcile explicitly"
        )
    if not scope.revocable:
        raise SpeculativeEffectLeak(
            f"branch {scope.branch_id} shares an effect scope with siblings; "
            f"discard would leak its writes"
        )
    # Cancel deferred callbacks synchronously, then retire the session id
    # so a retry cannot alias onto armed hooks.
    for cb in scope.deferred_callbacks:
        cb.cancel()
    scope.deferred_callbacks.clear()
    scope.retired = True


def commit_winner(winner: BranchScope, environment_effects: set) -> None:
    if winner.retired:
        raise SpeculativeEffectLeak(
            f"winner {winner.branch_id} was retired; session-id reuse detected"
        )
    leaked = environment_effects - winner.declared_effects
    if leaked:
        # Observed mutations not declared by the winner are sibling leaks.
        raise SpeculativeEffectLeak(
            f"commit of {winner.branch_id} found undeclared effects {leaked}; "
            f"a discarded sibling leaked across the rollback barrier"
        )
    winner.retired = True
