# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-merges-a-speculative-branch-whose-tool-side-effects-were-already-committed-downstream.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-merges-a-speculative-branch-whose-tool-side-effects-were-already-committed-downstream.warrant.json
# Markdown SHA-256:   275468a233fab863ea5b7dd8c9d8a01d540900834084b6b1c6b6c5172c9ceb55
# Code AST SHA-256:   1763aeee58dd2e0c1844428c1277184cfd881bcd8c7832474aec1fbf73c8c5dd
# Verified Classes:   SpeculativeIsolationViolation, Branch, SharedSurface
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class SpeculativeIsolationViolation(RuntimeError):
    """Raised when a branch's tool effect escaped the rollback domain before commit."""


@dataclass
class Branch:
    branch_id: str
    staged_effects: list[str] = field(default_factory=list)
    committed: bool = False

    def stage_effect(self, effect_key: str) -> None:
        self.staged_effects.append(effect_key)


@dataclass
class SharedSurface:
    # Effects that have become visible to non-branch consumers.
    visible: set[str] = field(default_factory=set)

    def observe(self, effect_key: str) -> None:
        self.visible.add(effect_key)


def commit_branch(
    winner: Branch,
    losers: list[Branch],
    surface: SharedSurface,
    non_idempotent_keys: set[str],
) -> None:
    # Pre-commit invariant: no losing branch may have leaked an effect
    # onto a surface observable by non-branch consumers.
    for loser in losers:
        for effect in loser.staged_effects:
            if effect in surface.visible:
                raise SpeculativeIsolationViolation(
                    f"branch {loser.branch_id} effect {effect!r} was observed "
                    f"before commit; rollback cannot un-materialize it"
                )

    # Second invariant: winner must not depend on a non-idempotent effect
    # that any branch (including itself) may have fired more than once.
    fired_counts: dict[str, int] = {}
    for b in [winner, *losers]:
        for effect in b.staged_effects:
            fired_counts[effect] = fired_counts.get(effect, 0) + 1
    for effect, count in fired_counts.items():
        if count > 1 and effect in non_idempotent_keys:
            raise SpeculativeIsolationViolation(
                f"non-idempotent effect {effect!r} fired {count} times across "
                f"speculative branches; merge cannot reconcile"
            )

    # Safe to flush: effects become world-visible only now.
    for effect in winner.staged_effects:
        surface.observe(effect)
    winner.committed = True
