# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-s-tool-side-effects-before-the-merge-barrier-resolves.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-s-tool-side-effects-before-the-merge-barrier-resolves.warrant.json
# Markdown SHA-256:   0d907d25d3760c4651040e54911fa7d5a9cd7bd6cbc29eef35d9d507f2303dc9
# Code AST SHA-256:   483f123d7ef4db2de711aedb88ff3e38048f2e3f851abf6137438c9e7615ea9d
# Verified Classes:   SpeculativeEffectLeak, StagedEffect, Branch, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a branch's mutating tool effect reaches shared state before the merge barrier commits it."""
    pass


@dataclass
class StagedEffect:
    branch_id: str
    effect_seq: int
    tool: str
    key: str
    payload: Any


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


class SpeculativeOrchestrator:
    def __init__(self) -> None:
        self._staging: dict[str, list[StagedEffect]] = {}
        self._shared_world: dict[str, Any] = {}
        self._barrier_resolved = False

    def dispatch_tool(self, branch: Branch, tool: str, key: str, payload: Any) -> None:
        # Mutating tools MUST stage; a direct write before the barrier is the leak.
        if self._barrier_resolved is False and tool in {"records.upsert", "records.delete", "records.create"}:
            seq = len(self._staging.setdefault(branch.branch_id, []))
            self._staging[branch.branch_id].append(
                StagedEffect(branch.branch_id, seq, tool, key, payload)
            )
            return
        # Non-mutating or post-barrier path writes through.
        self._shared_world[key] = payload

    def resolve_barrier(self, branches: list[Branch], winner_id: str) -> None:
        winners = [b for b in branches if b.branch_id == winner_id]
        if len(winners) != 1:
            raise SpeculativeEffectLeak(
                f"merge selected {winner_id!r} but {len(winners)} matching branches exist; "
                "selection is ambiguous and staged effects cannot be attributed"
            )
        winner = winners[0]

        # Conflict detection: two committed effects on the same key is a write-write hazard.
        seen: dict[str, str] = {}
        for eff in self._staging.get(winner.branch_id, []):
            if eff.key in seen:
                raise SpeculativeEffectLeak(
                    f"branch {winner.branch_id} staged two effects on key {eff.key!r} "
                    f"(seq {seen[eff.key]} and {eff.effect_seq}); merge cannot order them"
                )
            seen[eff.key] = eff.effect_seq

        # Commit only the winner's staged effects, in seq order.
        for eff in sorted(self._staging.get(winner.branch_id, []), key=lambda e: e.effect_seq):
            self._apply(eff)
        winner.committed = True

        # Discard all other branches' staging unread — this is the whole point.
        for b in branches:
            if b.branch_id != winner_id:
                self._staging.pop(b.branch_id, None)
        self._barrier_resolved = True

    def _apply(self, eff: StagedEffect) -> None:
        if eff.tool == "records.delete":
            self._shared_world.pop(eff.key, None)
        else:
            self._shared_world[eff.key] = eff.payload
