# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-roll-back-a-speculative-branch-after-a-sibling-branch-has-already-observed-its-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-roll-back-a-speculative-branch-after-a-sibling-branch-has-already-observed-its-side-effect.warrant.json
# Markdown SHA-256:   94cf243fe1937f10394e37068b39c62f221b2f2c5dc4fb36089d8f869d1d8143
# Code AST SHA-256:   5b9bfea83a870b710016683b499b35f62a0de41da3dd632c26688ce5f9af1819
# Verified Classes:   RollbackUnsafeError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class RollbackUnsafeError(RuntimeError):
    """Raised when a speculative branch's effects have been observed by a
    surviving sibling and therefore cannot be honestly rolled back."""


def rollback_branch(loser, survivors):
    """Attempt to delete a losing speculative branch's effects.

    Invariant: deletion is permitted only if no surviving branch's read-set
    intersects the loser's write-set. Otherwise the effect is a provisional
    commit and must be retained with provenance.
    """
    loser_writes = set(loser.write_set)
    for sibling in survivors:
        overlap = loser_writes & set(sibling.read_set)
        if overlap:
            raise RollbackUnsafeError(
                f"branch {loser.id} wrote {sorted(overlap)} which sibling "
                f"{sibling.id} already observed; rollback would invalidate "
                f"sibling state. Retain with tombstone and re-verify sibling."
            )
    # Safe path: no sibling consumed the loser's effects.
    for effect_id in loser_writes:
        loser.substrate.delete(effect_id)
    return True


def commit_with_barrier(branches, winner_id):
    winner = next(b for b in branches if b.id == winner_id)
    survivors = [b for b in branches if b.id != winner_id]
    for loser in survivors:
        try:
            rollback_branch(loser, [winner])
        except RollbackUnsafeError as exc:
            loser.retain_with_tombstone(reason=str(exc))
            winner.mark_tainted(source=loser.id)
            winner.force_reverify()
    return winner
