# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-speculative-branch-contamination-when-rollback-checkpoints-share-mutable-toolside-state-across-pruned-agent-trees.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-speculative-branch-contamination-when-rollback-checkpoints-share-mutable-toolside-state-across-pruned-agent-trees.warrant.json
# Markdown SHA-256:   158b75ef4a65e9d62196fecfa3c396915b4edfd8e6188ea7cb6b64a290e15fce
# Code AST SHA-256:   5d635bb5a2098f09023c1c3aebe4c58997e57fc7c98ad4d63e78de363a9c3ba7
# Verified Classes:   SpeculativeRollbackContamination, EffectHandle, CheckpointedSubstrate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class SpeculativeRollbackContamination(RuntimeError):
    """Raised when a pruned branch would compensate an effect handle
    still owned by a live branch, or when a surviving branch observes
    an effect it did not commit."""
    pass


@dataclass
class EffectHandle:
    handle_id: str
    owners: Set[str] = field(default_factory=set)  # branch_ids that committed/claim it


class CheckpointedSubstrate:
    def __init__(self) -> None:
        self._handles: Dict[str, EffectHandle] = {}
        self._branch_effects: Dict[str, Set[str]] = {}

    def commit_effect(self, branch_id: str, handle_id: str) -> EffectHandle:
        h = self._handles.setdefault(handle_id, EffectHandle(handle_id))
        h.owners.add(branch_id)
        self._branch_effects.setdefault(branch_id, set()).add(handle_id)
        return h

    def rollback_branch(self, branch_id: str, live_branches: Set[str]) -> None:
        """Compensate a pruned branch, refusing to destroy shared handles."""
        for handle_id in self._branch_effects.get(branch_id, set()):
            h = self._handles[handle_id]
            other_owners = (h.owners & live_branches) - {branch_id}
            if other_owners:
                # Survivor still holds this handle: release our claim only.
                h.owners.discard(branch_id)
                continue
            # Sole owner: safe to destroy.
            h.owners.discard(branch_id)
            if not h.owners:
                del self._handles[handle_id]
        self._branch_effects.pop(branch_id, None)

    def assert_owned(self, branch_id: str, handle_id: str) -> None:
        h = self._handles.get(handle_id)
        if h is None:
            raise SpeculativeRollbackContamination(
                f"branch {branch_id} references {handle_id}: handle no longer exists "
                f"(likely destroyed by a sibling's rollback)"
            )
        if branch_id not in h.owners:
            raise SpeculativeRollbackContamination(
                f"branch {branch_id} references {handle_id} it does not own; "
                f"owners={sorted(h.owners)} — inherited contaminated world-state"
            )


def prune_and_verify(substrate: CheckpointedSubstrate,
                     pruned: Set[str],
                     survivors: Set[str],
                     survivor_probe: Dict[str, str]) -> None:
    """Roll back pruned branches, then verify survivors still own their handles."""
    for b in pruned:
        substrate.rollback_branch(b, live_branches=survivors)
    for branch_id, handle_id in survivor_probe.items():
        substrate.assert_owned(branch_id, handle_id)
