# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-corrupting-the-committed-agent-state-graph.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-corrupting-the-committed-agent-state-graph.warrant.json
# Markdown SHA-256:   a2030591fd644b2c74899f59f85a1987cd500df3cae7ff178760217cb1d5a838
# Code AST SHA-256:   6c692df8a409bf1de4787a666e6562a8a0eda463de8fb24f7992b082ae89fa2c
# Verified Classes:   ProvenanceClosureViolation, Node
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

class ProvenanceClosureViolation(RuntimeError):
    """Raised when a committed node's provenance DAG reaches a rolled-back node."""
    pass

@dataclass
class Node:
    node_id: str
    branch_id: str
    parents: Set[str] = field(default_factory=set)
    external_effect: bool = False
    compensation_token: str | None = None

def reconcile(committed: Dict[str, Node], rolled_back: Set[str]) -> None:
    # Build reverse provenance index over the committed graph only.
    children: Dict[str, Set[str]] = {nid: set() for nid in committed}
    for nid, node in committed.items():
        for p in node.parents:
            if p in children:
                children[p].add(nid)

    # Any committed node whose ancestry touches a rolled-back node is poisoned.
    poisoned: Set[str] = set()
    frontier = [nid for nid in committed if committed[nid].parents & rolled_back]
    while frontier:
        nid = frontier.pop()
        if nid in poisoned:
            continue
        poisoned.add(nid)
        frontier.extend(children.get(nid, ()))

    if poisoned:
        raise ProvenanceClosureViolation(
            f"commit invalid: {len(poisoned)} committed nodes derive from "
            f"rolled-back branches {sorted(rolled_back)}; "
            f"poisoned={sorted(poisoned)}; abort epoch, do not partially reconcile"
        )

    # External effects without compensation tokens cannot be rolled back.
    for nid in rolled_back:
        node = committed.get(nid)
        if node and node.external_effect and not node.compensation_token:
            raise ProvenanceClosureViolation(
                f"rolled-back node {nid} has irreversible external effect; "
                f"epoch must be invalidated, not surgically rolled back"
            )
