# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-lose-its-rollback-anchor-when-a-sibling-commits-first.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-lose-its-rollback-anchor-when-a-sibling-commits-first.warrant.json
# Markdown SHA-256:   b9e4d804cad20048f1e42af4b9a47255d8887f7dacdf4ac6b23e185b2f3712e6
# Code AST SHA-256:   c43ee8f8d569ed9fcba8d804e3fd6712023524fadfc700a59514d19806af9136
# Verified Classes:   SpeculativeRollbackFenceError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SpeculativeRollbackFenceError(RuntimeError):
    """Raised when a branch rollback would clobber a sibling's committed state."""
    pass


class Branch:
    def __init__(self, branch_id, write_set, pre_state):
        self.branch_id = branch_id
        self.write_set = set(write_set)      # resource ids this branch mutates
        self.pre_state = dict(pre_state)     # resource -> content at fork (C0)
        self.committed = False


def select_and_rollback(branches, winner_id, substrate):
    """
    substrate: dict-like with .read(resource) and .write(resource, value)
    Enforces the write-set fence: a loser may only roll back a resource
    if the substrate still holds that loser's own write, i.e. no sibling
    has since committed over it.
    """
    winner = next(b for b in branches if b.branch_id == winner_id)
    winner.committed = True

    for loser in branches:
        if loser.branch_id == winner_id:
            continue
        for resource in loser.write_set:
            current = substrate.read(resource)
            # The invariant: we may only undo our own write if it is still
            # the head. If a sibling committed here, current != loser's write
            # and we must not touch it.
            if current != loser.pre_state.get(resource) and _written_by(current, loser):
                substrate.write(resource, loser.pre_state[resource])
            elif _written_by_sibling(current, loser, branches):
                raise SpeculativeRollbackFenceError(
                    f"branch {loser.branch_id} cannot roll back {resource}: "
                    f"sibling already committed over it; unconditional "
                    f"restore would clobber the winner"
                )
    return winner


def _written_by(current, branch):
    # In a real system this is a content hash comparison against the
    # branch's recorded post-write value.
    return getattr(current, "author", None) == branch.branch_id


def _written_by_sibling(current, branch, branches):
    author = getattr(current, "author", None)
    return author is not None and author != branch.branch_id and any(
        b.branch_id == author and b.committed for b in branches
    )
