# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-divergent-speculative-branches-from-corrupting-the-shared-checkpoint-graph-during-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-divergent-speculative-branches-from-corrupting-the-shared-checkpoint-graph-during-multi-agent-rollback.warrant.json
# Markdown SHA-256:   d619b806b5d3ee5765a2dd6deeb773dbdf7dbff8bb63da90bed513fc4529f499
# Code AST SHA-256:   0afa5960526be9f40b2bab320921d42dfc25344f45bd286ea0e6c960349de1d6
# Verified Classes:   UnscopedRollbackError, Checkpoint, SpeculativeStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnscopedRollbackError(RuntimeError):
    """Raised when a rollback would tombstone checkpoints outside the initiating branch."""
    pass


class Checkpoint:
    __slots__ = ("coord", "parent", "branch_id", "content_hash", "superseded")

    def __init__(self, coord, parent, branch_id, content_hash):
        self.coord = coord
        self.parent = parent
        self.branch_id = branch_id
        self.content_hash = content_hash
        self.superseded = False


class SpeculativeStore:
    def __init__(self):
        self._nodes = {}  # coord -> Checkpoint
        self._head = None

    def fork(self, parent_coord, branch_id, content_hash):
        coord = f"{parent_coord}/{branch_id}"
        node = Checkpoint(coord, parent_coord, branch_id, content_hash)
        self._nodes[coord] = node
        self._head = coord
        return coord

    def _ancestry(self, coord):
        path = []
        cur = coord
        while cur is not None:
            path.append(cur)
            cur = self._nodes[cur].parent
        return path

    def revert_to(self, target_coord, initiating_branch):
        if target_coord not in self._nodes:
            raise UnscopedRollbackError(f"unknown checkpoint {target_coord}")
        # Collect descendants of target that are NOT on the initiating branch's path.
        tombstone = []
        for coord, node in self._nodes.items():
            if node.superseded:
                continue
            path = self._ancestry(coord)
            if target_coord not in path:
                continue
            # Walk from coord down to target; every node on that segment must belong
            # to the initiating branch, else rollback would clobber a sibling.
            seg = path[: path.index(target_coord)]
            if any(self._nodes[c].branch_id != initiating_branch for c in seg):
                raise UnscopedRollbackError(
                    f"rollback from {initiating_branch} at {target_coord} would "
                    f"tombstone sibling checkpoints {seg}; refusing global rewind"
                )
            tombstone.append(coord)
        for coord in tombstone:
            self._nodes[coord].superseded = True
        self._head = target_coord

    def reconcile(self, live_coords):
        seen = {}
        for coord in live_coords:
            node = self._nodes[coord]
            if node.superseded:
                continue
            if node.content_hash in seen:
                continue  # content-hash dedup, not coordinate dedup
            seen[node.content_hash] = coord
        return list(seen.values())


def safe_revert(store, target_coord, initiating_branch):
    try:
        store.revert_to(target_coord, initiating_branch)
    except UnscopedRollbackError as e:
        # Downgrade to serialized execution: do not fork again until siblings drain.
        raise UnscopedRollbackError(
            f"speculative fork unsound on this store; serialize workers: {e}"
        ) from e
    return store.reconcile([n for n, c in store._nodes.items() if not c.superseded])
