# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-unwind-a-poisoned-merge-in-speculative-parallel-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-unwind-a-poisoned-merge-in-speculative-parallel-agent-execution.warrant.json
# Markdown SHA-256:   bc529dd168b6d156c93be18794aee7caec57bb71ad04f85870bdd18601c7c07c
# Code AST SHA-256:   591469a76c420c9e0fd5abee731ebfcafaa4f3693e1c3a9e35b932793e8ef7d2
# Verified Classes:   ContaminatedMergeError, Branch, WriteRecord, MergeGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class ContaminatedMergeError(RuntimeError):
    """Raised when a branch to be committed read state that was later rolled back."""
    pass


@dataclass
class Branch:
    branch_id: str
    read_set: Set[str] = field(default_factory=set)      # write-ids observed
    output_facts: Set[str] = field(default_factory=set)
    verified: bool = False


@dataclass
class WriteRecord:
    write_id: str
    branch_id: str
    generation: int
    rolled_back: bool = False


class MergeGate:
    def __init__(self, checkpoint_generation: int):
        self.generation = checkpoint_generation
        self.writes: Dict[str, WriteRecord] = {}

    def record_write(self, write_id: str, branch_id: str) -> WriteRecord:
        rec = WriteRecord(write_id, branch_id, self.generation)
        self.writes[write_id] = rec
        return rec

    def rollback(self, write_id: str) -> None:
        # Rollback invalidates the write AND bumps generation so no branch
        # that read the old generation can be silently committed.
        self.writes[write_id].rolled_back = True
        self.generation += 1

    def commit(self, branches: list[Branch]) -> Set[str]:
        rolled_back = {w.write_id for w in self.writes.values() if w.rolled_back}
        tainted = [
            b for b in branches
            if b.verified and (b.read_set & rolled_back)
        ]
        if tainted:
            ids = ", ".join(b.branch_id for b in tainted)
            raise ContaminatedMergeError(
                f"branches [{ids}] read rolled-back writes "
                f"{sorted(set().union(*(b.read_set for b in tainted)) & rolled_back)}; "
                f"re-execute from checkpoint generation {self.generation}, "
                f"do not re-verify."
            )
        committed: Set[str] = set()
        for b in branches:
            if b.verified:
                committed |= b.output_facts
        return committed


def run_fanout(gate: MergeGate, branches: list[Branch]) -> Set[str]:
    # Simulated: A writes X then fails; B reads X; C independent.
    a, b, c = branches
    w = gate.record_write("X", a.branch_id)
    a.output_facts.add("X")
    a.verified = False          # A fails its own verification
    b.read_set.add(w.write_id)  # B observed X before rollback
    b.output_facts.add("X")     # X is now inside B's immutable context
    b.verified = True
    c.verified = True
    gate.rollback(w.write_id)   # store restored, generation bumped
    return gate.commit(branches)  # must raise, not return {X, ...}
