# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-its-speculative-branch-has-been-invalidated-by-a-sibling-s-committed-side-effect-during-parallel-hedging.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-its-speculative-branch-has-been-invalidated-by-a-sibling-s-committed-side-effect-during-parallel-hedging.warrant.json
# Markdown SHA-256:   7068663297213c797923f6b9d32927b08545d8d46b8e6c8ed3a568708f7e68f0
# Code AST SHA-256:   644bf4f18e7e573b0e07e0aafc710121e2156e1309797efa178f9c922be8b8ee
# Verified Classes:   ContaminatedBranchError, BranchLedger, SpeculationOrchestrator
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ContaminatedBranchError(RuntimeError):
    """Raised when a speculative branch consumed a sibling's effect that is being rolled back."""


@dataclass
class BranchLedger:
    branch_id: str
    read_set: Set[str] = field(default_factory=set)
    write_set: Set[str] = field(default_factory=set)


class SpeculationOrchestrator:
    def __init__(self) -> None:
        self.ledgers: Dict[str, BranchLedger] = {}
        self.committed_pre_speculation: Set[str] = set()

    def register(self, branch_id: str) -> BranchLedger:
        led = BranchLedger(branch_id)
        self.ledgers[branch_id] = led
        return led

    def record_read(self, branch_id: str, surface_key: str) -> None:
        self.ledgers[branch_id].read_set.add(surface_key)

    def record_write(self, branch_id: str, surface_key: str) -> None:
        self.ledgers[branch_id].write_set.add(surface_key)

    def check_contamination(self, branch_id: str, rolling_back: Set[str]) -> None:
        """Before consensus, reject any branch that read a rolling-back sibling's writes."""
        led = self.ledgers[branch_id]
        for sibling_id in rolling_back:
            if sibling_id == branch_id:
                continue
            sibling_writes = self.ledgers[sibling_id].write_set
            overlap = led.read_set & sibling_writes
            if overlap:
                raise ContaminatedBranchError(
                    f"branch {branch_id} read {sorted(overlap)} written by "
                    f"rolling-back sibling {sibling_id}; result must be quarantined "
                    f"and re-executed against post-rollback state"
                )

    def promote(self, winner_id: str, all_branches: Set[str]) -> None:
        rolling_back = all_branches - {winner_id}
        for b in all_branches:
            self.check_contamination(b, rolling_back)
        self.committed_pre_speculation |= self.ledgers[winner_id].write_set
