# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-parallel-agent-plans-and-the-merge-commits-a-branch-whose-tool-side-effects-were-only-partially-roll.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-parallel-agent-plans-and-the-merge-commits-a-branch-whose-tool-side-effects-were-only-partially-roll.warrant.json
# Markdown SHA-256:   681d2f49d1badacb13b7c7d5316065b977df9eeb469962f621cedb550060dae3
# Code AST SHA-256:   1f964575bc5f0f295d6a4d5723d51c0ec5da02d98316d6389c1056e83066b410
# Verified Classes:   SpeculationBoundaryError, Reversibility, Effect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative round would commit effects it cannot safely un-run."""
    pass


class Reversibility(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"   # un-run via compare-and-revert, keyed to effect_id
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class Effect:
    branch_id: str
    effect_id: str
    resource: str
    written_value: str
    reversibility: Reversibility


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)


def assert_round_is_speculatable(branches: list[Branch]) -> None:
    # 1. Irreversible effects may not be forked speculatively; they must be merge-gated.
    for b in branches:
        for e in b.effects:
            if e.reversibility is Reversibility.IRREVERSIBLE:
                raise SpeculationBoundaryError(
                    f"branch {b.branch_id} carries irreversible effect {e.effect_id} "
                    f"on {e.resource}; defer behind merge gate, do not fork"
                )

    # 2. Non-commutative aliasing: two branches writing the same resource is a conflict,
    #    not a race to be resolved by plan scoring.
    by_resource: dict[str, set[str]] = {}
    for b in branches:
        for e in b.effects:
            by_resource.setdefault(e.resource, set()).add(b.branch_id)
    for resource, writers in by_resource.items():
        if len(writers) > 1:
            raise SpeculationBoundaryError(
                f"resource {resource} mutated by multiple branches {sorted(writers)}; "
                f"compensation keyed on resource-prior would clobber the winner"
            )


def compensate_loser(branch: Branch, world: dict[str, str]) -> None:
    # Compare-and-revert: only undo if the world still holds what this effect wrote.
    for e in branch.effects:
        if e.reversibility is Reversibility.IRREVERSIBLE:
            raise SpeculationBoundaryError(
                f"cannot compensate irreversible effect {e.effect_id}; round was not speculatable"
            )
        if world.get(e.resource) != e.written_value:
            raise SpeculationBoundaryError(
                f"effect {e.effect_id} on {e.resource} was overwritten by a sibling; "
                f"blind revert would corrupt committed state"
            )
        world[e.resource] = "<prior>"
