# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-fork-agent-branches-and-then-merge-a-rolled-back-sibling-s-side-effects-into-the-surviving-branch-s-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-fork-agent-branches-and-then-merge-a-rolled-back-sibling-s-side-effects-into-the-surviving-branch-s-memory.warrant.json
# Markdown SHA-256:   74a4b16cd18680cf93458ddcdeb479280c0286748d186796a2df93b1a6d9cec4
# Code AST SHA-256:   8d0d152c0c37b23979290b9a74724d604bf7ef1f40a2315c3126732b250c485b
# Verified Classes:   SpeculativeMergeViolation, BranchState, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class SpeculativeMergeViolation(RuntimeError):
    """Raised when a rolled-back branch's effects leak into the merged state."""
    pass


class BranchState(Enum):
    RUNNING = "running"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"
    PROMOTED = "promoted"  # was speculative, emitted an effect, must serialize


@dataclass
class Effect:
    branch_id: str
    tool: str
    payload: dict
    epoch: int
    acknowledged: bool = False


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.RUNNING
    inflight_effects: int = 0
    emitted: list[Effect] = field(default_factory=list)

    def dispatch_mutating(self, tool: str, payload: dict, epoch: int,
                          fenced: bool) -> Effect:
        """Emit a mutating effect. Unfenced speculative effects force promotion."""
        if not fenced:
            # Cannot cancel after emit: promote to a serialized committed branch.
            self.state = BranchState.PROMOTED
        eff = Effect(self.branch_id, tool, payload, epoch)
        self.inflight_effects += 1
        self.emitted.append(eff)
        return eff

    def acknowledge(self, eff: Effect) -> None:
        eff.acknowledged = True
        self.inflight_effects -= 1

    def request_cancel(self) -> bool:
        """Returns True if cancellation is safe now; False if deferred."""
        if self.inflight_effects > 0:
            return False  # cancel-after-emit race: must wait or promote
        if self.state == BranchState.PROMOTED:
            return False  # promoted branches are never rolled back
        self.state = BranchState.ROLLED_BACK
        return True


def merge(winner: Branch, loser: Branch, shared_store: list[Effect],
          commit_epoch: int) -> list[Effect]:
    """Merge winner's context; assert no rolled-back effect is visible."""
    committed = {winner.branch_id}
    if winner.state in (BranchState.COMMITTED, BranchState.PROMOTED):
        committed.add(winner.branch_id)

    # Reap rolled-back effects from the shared store before merge.
    visible = [e for e in shared_store
               if e.branch_id in committed and e.epoch == commit_epoch]

    leaked = [e for e in visible
              if e.branch_id == loser.branch_id
              and loser.state == BranchState.ROLLED_BACK]
    if leaked:
        raise SpeculativeMergeViolation(
            f"branch {loser.branch_id} was rolled back but {len(leaked)} "
            f"effect(s) remain visible: {[e.tool for e in leaked]}"
        )

    # Invariant: visible effects == effects of committed branches only.
    expected = {e for e in winner.emitted if e.acknowledged}
    if set(visible) != expected:
        raise SpeculativeMergeViolation(
            "merge divergence: visible effect set does not match "
            "committed-branch effect log"
        )
    return visible
