# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-poisoning-when-optimistic-tool-call-preemption-commits-side-effects-before-the-rollback-frontier-is-val.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-branch-poisoning-when-optimistic-tool-call-preemption-commits-side-effects-before-the-rollback-frontier-is-val.warrant.json
# Markdown SHA-256:   e212098b63dbb74724424fea5d1802ce0695b2169148b9e31bd48b2d114176c7
# Code AST SHA-256:   e88b95205f801cd50fcfe04a4cd343b5bde1ebe4e2d2f7dfb2b395af7d73ee64
# Verified Classes:   SpeculativePoisonError, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class SpeculativePoisonError(RuntimeError):
    """Raised when a rolled-back branch's preempted side effect poisoned a sibling."""
    pass


@dataclass
class Branch:
    name: str
    preempted_effects: Set[str] = field(default_factory=set)
    reads: Set[str] = field(default_factory=set)
    rolled_back: bool = False


def detect_poisoning(branches: Dict[str, Branch], committed_effects: Set[str]) -> None:
    # Effects that left the process and are observable to siblings.
    observable = committed_effects
    poisoned: Set[str] = set()

    for b in branches.values():
        # A branch is poisoned if it read an effect that a *different*
        # branch preempted and that has not been compensated.
        for effect in b.reads & observable:
            for other in branches.values():
                if other.name != b.name and effect in other.preempted_effects:
                    poisoned.add(b.name)

    if poisoned:
        raise SpeculativePoisonError(
            f"sibling branches poisoned by preempted effects: {sorted(poisoned)}; "
            f"rollback of local state is insufficient — re-derive from last "
            f"consistent ledger snapshot"
        )


def resolve_selector(selected: Branch, branches: Dict[str, Branch],
                     committed_effects: Set[str]) -> None:
    for b in branches.values():
        if b.name != selected.name:
            b.rolled_back = True
    detect_poisoning(branches, committed_effects)
