# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-merges-a-speculative-branch-whose-side-effects-were-committed-to-a-shared-store-before-the-merge-decision.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-merges-a-speculative-branch-whose-side-effects-were-committed-to-a-shared-store-before-the-merge-decision.warrant.json
# Markdown SHA-256:   8e91a68b21a9d425de003419b063c05aa96e55df4e9c20dc7b9a3166dd0f7204
# Code AST SHA-256:   38107e5281919389d4a7b86afe72f362c1b83be33883f78ea8d089b44086fb2f
# Verified Classes:   SpeculativeRollbackError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackError(RuntimeError):
    """Raised when a branch is rolled back by discard while it holds
    un-compensated writes to a shared store. Rollback-by-discard is only
    sound when every side effect is versioned or compensated."""


class Branch:
    def __init__(self, branch_id: str):
        self.branch_id = branch_id
        self.trajectory = []
        self.side_effects = []  # (store, key, compensator_or_None)

    def record_write(self, store: str, key: str, compensator=None):
        self.side_effects.append((store, key, compensator))


def rollback_branch(branch: Branch, store_is_shared: bool) -> None:
    """
    Roll back a speculative branch. Sound only if the branch's writes are
    either versioned (compensator present) or the store is not shared.
    """
    leaked = [
        (store, key)
        for (store, key, comp) in branch.side_effects
        if comp is None
    ]

    if store_is_shared and leaked:
        raise SpeculativeRollbackError(
            f"branch {branch.branch_id} has {len(leaked)} un-compensated "
            f"writes to shared store: {leaked}. Discard-only rollback would "
            f"leak these into sibling branches and future runs. Refusing to "
            f"report a clean rollback."
        )

    # Compensate what we can, in reverse order.
    for store, key, comp in reversed(branch.side_effects):
        if comp is not None:
            comp(store, key)

    branch.trajectory.clear()
    branch.side_effects.clear()


def merge_or_rollback(branch: Branch, accepted: bool, store_is_shared: bool) -> None:
    if accepted:
        # Writes become authoritative; no compensation.
        branch.side_effects.clear()
        return
    rollback_branch(branch, store_is_shared=store_is_shared)
