# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-speculative-branch-execution-when-rollback-reconciliation-cannot-prove-causal-isolation-across-cooperating-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-speculative-branch-execution-when-rollback-reconciliation-cannot-prove-causal-isolation-across-cooperating-agents.warrant.json
# Markdown SHA-256:   7f4aab5d829dcb69239fdbe524e912007dc99f670b3f06fd2e66478cc484d507
# Code AST SHA-256:   e0961d34efd78a01e271a47663e4b0c0e9f1ce30a5bf50aba064e7cc08dd7849
# Verified Classes:   RollbackContaminationError, Version, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class RollbackContaminationError(RuntimeError):
    """Raised when commit would leave a decision dependent on a retracted version."""
    pass


@dataclass(frozen=True)
class Version:
    key: str
    version_id: str
    branch_id: str


@dataclass
class Branch:
    branch_id: str
    writes: List[Version] = field(default_factory=list)
    # decision_set_reads: reads that actually drove committed decisions
    decision_set_reads: List[Version] = field(default_factory=list)
    read_versions_recorded: bool = True


def reconcile_commit(
    winning: Branch,
    rolled_back: List[Branch],
    require_read_lineage: bool = True,
) -> None:
    if require_read_lineage and not winning.read_versions_recorded:
        raise RollbackContaminationError(
            f"branch {winning.branch_id} emitted no read-version lineage; "
            "causal isolation unprovable, commit refused"
        )

    retracted: Set[Tuple[str, str]] = {
        (v.key, v.version_id)
        for b in rolled_back
        for v in b.writes
    }

    poisoned = [
        r for r in winning.decision_set_reads
        if (r.key, r.version_id) in retracted
    ]

    if poisoned:
        detail = ", ".join(f"{p.key}@{p.version_id}(from {p.branch_id})" for p in poisoned)
        raise RollbackContaminationError(
            f"branch {winning.branch_id} decision set consumed retracted versions: {detail}; "
            "halt and serialize re-execution against post-rollback snapshot"
        )


def commit_with_guard(winning: Branch, rolled_back: List[Branch]) -> str:
    reconcile_commit(winning, rolled_back)
    return f"committed {winning.branch_id}"


# Example: disjoint writes, hidden read-dependency -> the boundary must fire.
a = Branch("A", writes=[Version("config.mode", "v7", "A")])
b = Branch(
    "B",
    writes=[Version("cache.policy", "v9", "B")],
    decision_set_reads=[Version("config.mode", "v7", "A")],  # poisoned read
)
try:
    commit_with_guard(b, rolled_back=[a])
except RollbackContaminationError as e:
    print("HALT:", e)
