# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-peer-s-context-and-the-merge-rolls-back-a-branch-that-already-emitted-a-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-peer-s-context-and-the-merge-rolls-back-a-branch-that-already-emitted-a-side-effect.warrant.json
# Markdown SHA-256:   b02cb509a2c32b77f43939fa42a133b5a46b5a58a2a8f4472f8df61be8ac8c81
# Code AST SHA-256:   87e9eb4f7f14d9fd4eacb68cdde9f0fe79ecf27adbc469b1745ca121bbc590fa
# Verified Classes:   MergeInvariantError, BranchKind, EffectTombstone, Branch, MergeBarrier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class MergeInvariantError(RuntimeError):
    """Raised when a merge would commit a lineage whose world-model diverges from reality."""


class BranchKind(Enum):
    SPECULATIVE = "speculative"   # no effect tokens; rollback is total
    COMMITTED = "committed"       # holds effect token; guaranteed to survive barrier


@dataclass
class EffectTombstone:
    branch_id: str
    tool: str
    args: dict
    committed: bool  # did the effect actually reach the external world?


@dataclass
class Branch:
    branch_id: str
    kind: BranchKind
    effect_token: Optional[str] = None
    tombstones: list[EffectTombstone] = field(default_factory=list)
    context: list[str] = field(default_factory=list)


@dataclass
class MergeBarrier:
    surviving: Branch
    rolled_back: list[Branch]
    reconciled: bool = False


def request_effect(branch: Branch, tool: str, args: dict) -> EffectTombstone:
    """A branch attempts a side-effecting tool call."""
    if branch.kind is BranchKind.SPECULATIVE:
        # Speculative branches cannot act; the attempt is recorded but fenced.
        tomb = EffectTombstone(branch.branch_id, tool, args, committed=False)
        branch.tombstones.append(tomb)
        raise MergeInvariantError(
            f"speculative branch {branch.branch_id} attempted effect {tool!r}; "
            "effect fenced, tombstone recorded, no external call issued"
        )
    if branch.effect_token is None:
        raise MergeInvariantError(
            f"committed branch {branch.branch_id} has no effect token; "
            "cannot issue effect without structural warrant"
        )
    tomb = EffectTombstone(branch.branch_id, tool, args, committed=True)
    branch.tombstones.append(tomb)
    return tomb


def merge(barrier: MergeBarrier) -> Branch:
    """Reconcile branches at the barrier. Rolls back context, never effects."""
    # Collect every escaped effect from rolled-back branches.
    escaped = [
        t
        for b in barrier.rolled_back
        for t in b.tombstones
        if t.committed
    ]
    if escaped and not barrier.reconciled:
        raise MergeInvariantError(
            f"merge would roll back {len(escaped)} committed effect(s) from "
            f"branches {[t.branch_id for t in escaped]}; "
            "surviving lineage's world-model would diverge from reality. "
            "Run reconciliation against the external world before merging."
        )
    # Rollback is context-only; tombstones are copied into the survivor's ledger.
    for b in barrier.rolled_back:
        barrier.surviving.context.extend(
            f"[tombstone] {t.branch_id}:{t.tool} committed={t.committed}"
            for t in b.tombstones
        )
    return barrier.surviving


# --- Trace of the failure ---
spec = Branch("B", BranchKind.SPECULATIVE)
try:
    request_effect(spec, "deploy_fix", {"service": "staging"})
except MergeInvariantError as e:
    # Correct behavior: effect fenced, tombstone recorded, no external mutation.
    print(f"fenced: {e}")

# If the fence is absent and B is (incorrectly) treated as committed,
# the merge must refuse to proceed until reconciliation runs.
leaked = Branch("B", BranchKind.SPECULATIVE)
leaked.effect_token = "tok-B"  # bug: speculative branch given a token
leaked.kind = BranchKind.COMMITTED  # bug: mislabeled
request_effect(leaked, "deploy_fix", {"service": "staging"})
barrier = MergeBarrier(surviving=Branch("A", BranchKind.COMMITTED), rolled_back=[leaked])
merge(barrier)  # raises: surviving lineage would diverge from reality
