# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciling-rollback-invalidation-against-shared-state-writes-in-speculative-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-reconciling-rollback-invalidation-against-shared-state-writes-in-speculative-multi-agent-execution.warrant.json
# Markdown SHA-256:   6a2a49fdb7cda5d55b0dbd15d2d3f2ab11c629338534a57b4e6565bdb644c05b
# Code AST SHA-256:   2f0e81005e06a6ccab820c7868190d643d2788b82c225e83777e16211ebb0964
# Verified Classes:   RollbackContaminationError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class RollbackContaminationError(RuntimeError):
    """Raised when a committed branch's read-set intersects a rolled-back
    branch's uncovered write-set, making the commit unsound."""


@dataclass
class Branch:
    branch_id: str
    overlay_covers_all_writes: bool
    # resources written through channels the overlay does NOT intercept
    uncovered_writes: set = field(default_factory=set)
    # resources read during execution (post-fork)
    reads: set = field(default_factory=set)
    rolled_back: bool = False


def reconcile(branches: list, epoch_tag: str) -> list:
    """Return the list of branch_ids safe to commit.

    Invariant: a surviving branch may be committed only if its read-set does
    not intersect the uncovered write-set of any rolled-back branch in the
    same epoch. Otherwise the commit is made on a state that never existed
    in a single causal history.
    """
    rolled_back = [b for b in branches if b.rolled_back]
    survivors = [b for b in branches if not b.rolled_back]

    leaked = set()
    for rb in rolled_back:
        if rb.overlay_covers_all_writes:
            continue  # rollback is a pure overlay discard; no leak
        leaked |= rb.uncovered_writes

    contaminated = []
    for s in survivors:
        hit = s.reads & leaked
        if hit:
            contaminated.append((s.branch_id, hit))

    if contaminated:
        detail = "; ".join(f"{bid} read leaked {sorted(h)}" for bid, h in contaminated)
        raise RollbackContaminationError(
            f"commit blocked at epoch {epoch_tag}: rolled-back branch writes "
            f"survived the overlay and were observed by survivors -> {detail}. "
            f"Invalidate leaked resources and re-run affected branches."
        )

    return [s.branch_id for s in survivors]


if __name__ == "__main__":
    b1 = Branch("B1", overlay_covers_all_writes=True, reads={"users.count"})
    b2 = Branch(
        "B2",
        overlay_covers_all_writes=False,
        uncovered_writes={"cache:q_8812"},
        rolled_back=True,
    )
    b3 = Branch("B3", overlay_covers_all_writes=True, reads={"cache:q_8812"})
    # B3 read a cache key that B2 wrote through an uncovered channel and
    # then rolled back -> commit must be refused.
    reconcile([b1, b2, b3], epoch_tag="e-42")
