# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-sibling-commits.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-sibling-commits.warrant.json
# Markdown SHA-256:   903cfb7fc78c43d9e6b25c3b85942f149f6640274c0414e7ccd40cf8007ef904
# Code AST SHA-256:   e77c76e657343c55f7ea19a2c9f3fe9204803727e7fb8e9969dd84a133283d23
# Verified Classes:   CommitHorizonViolation, EffectClass, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class CommitHorizonViolation(RuntimeError):
    """Raised when a speculative branch is aborted after an effect escaped its overlay."""
    pass


class EffectClass(Enum):
    REVERSIBLE = "reversible"      # stays in branch overlay, discardable
    IRREVERSIBLE = "irreversible"  # escapes overlay: external side effect


@dataclass
class Branch:
    name: str
    overlay: dict = field(default_factory=dict)
    escaped_effects: list = field(default_factory=list)
    shared_context_writes: set = field(default_factory=set)

    def emit(self, key: str, value, effect: EffectClass, shared: bool = False) -> None:
        if effect is EffectClass.REVERSIBLE and not shared:
            self.overlay[key] = value
            return
        # Effect escapes the discardable overlay.
        self.escaped_effects.append((key, value, effect, shared))
        if shared:
            self.shared_context_writes.add(key)

    def is_past_horizon(self) -> bool:
        return bool(self.escaped_effects)


def rollback(branch: Branch, siblings: list[Branch]) -> None:
    """Abort a speculative branch. Legal only while it is within its commit horizon."""
    if branch.is_past_horizon():
        raise CommitHorizonViolation(
            f"branch {branch.name!r} cannot be rolled back: "
            f"{len(branch.escaped_effects)} effect(s) escaped the overlay "
            f"({branch.escaped_effects!r}); freeze-and-reconcile required"
        )
    # Contamination check: a sibling that read a value this branch wrote
    # would have its committed output silently conditioned on a discarded branch.
    contaminated = [
        s.name for s in siblings
        if s.shared_context_writes & branch.shared_context_writes
    ]
    if contaminated:
        raise CommitHorizonViolation(
            f"branch {branch.name!r} shares context writes with {contaminated}; "
            f"read-path contamination must be resolved before rollback"
        )
    branch.overlay.clear()


def speculative_merge(draft: Branch, probe: Branch, winner: str) -> Branch:
    loser = probe if winner == draft.name else draft
    rollback(loser, siblings=[draft, probe])
    return draft if winner == draft.name else probe
