# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-rollback-from-silently-committing-divergent-sub-task-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-rollback-from-silently-committing-divergent-sub-task-side-effects.warrant.json
# Markdown SHA-256:   23d166ef5f00343e68ddc6fdb9512235293edc914c6d571bec4d1dc7cc8a007c
# Code AST SHA-256:   69b929f254af0584067a2f3a7f43a6c8db00b4ec17242aa88c2ec167259186e5
# Verified Classes:   EffectClass, DivergentRollbackError, CapabilityEscalationError, Effect, EffectJournal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    BUFFERED = "buffered"            # dropped on rollback via barrier
    COMPENSABLE = "compensable"      # inverse registered in journal
    NON_COMPENSABLE = "non_compensable"  # irreversible -> serialize


class DivergentRollbackError(RuntimeError):
    """Raised when post-rollback world state != W0 + E_winner."""


class CapabilityEscalationError(RuntimeError):
    """Raised when a branch acquires a broader capability than its manifest."""


@dataclass
class Effect:
    branch_id: str
    kind: EffectClass
    payload: dict
    inverse: Callable[[dict], None] | None = None


@dataclass
class EffectJournal:
    """Durable, append-only. Survives branch context teardown."""
    entries: list[Effect] = field(default_factory=list)

    def record(self, e: Effect) -> None:
        self.entries.append(e)

    def effects_of(self, branch_id: str) -> list[Effect]:
        return [e for e in self.entries if e.branch_id == branch_id]


def rollback_branch(
    branch_id: str,
    journal: EffectJournal,
    barrier_drop: Callable[[str], None],
    world_snapshot: Callable[[], dict],
) -> None:
    # INVARIANT 1: enumerate effects BEFORE any teardown.
    effects = journal.effects_of(branch_id)

    for e in effects:
        if e.kind is EffectClass.NON_COMPENSABLE:
            # Should have been serialized; reaching here is a classification breach.
            raise DivergentRollbackError(
                f"branch {branch_id} produced non-compensable effect {e.payload}; "
                f"must be serialized, not speculated"
            )
        if e.kind is EffectClass.COMPENSABLE:
            if e.inverse is None:
                raise DivergentRollbackError(
                    f"compensable effect {e.payload} has no registered inverse"
                )
            e.inverse(e.payload)

    # Only after effects are unwound do we drop the barrier and teardown context.
    barrier_drop(branch_id)


def commit_with_reconciliation(
    winner_id: str,
    journal: EffectJournal,
    pre_state: dict,
    winner_effects: list[Effect],
    world_snapshot: Callable[[], dict],
) -> None:
    # INVARIANT 4: hard gate before commit.
    expected = dict(pre_state)
    for e in winner_effects:
        expected.update(e.payload)
    actual = world_snapshot()
    if actual != expected:
        leaked = {k: actual.get(k) for k in actual if actual.get(k) != expected.get(k)}
        raise DivergentRollbackError(
            f"post-rollback world diverges from W0 + E_{winner_id}: leaked={leaked}. "
            f"Refusing to commit winner; halt for review."
        )


def check_capability(declared: set[str], presented: set[str], branch_id: str) -> None:
    # INVARIANT 3: classification re-checked against actual capability.
    upgrade = presented - declared
    if upgrade:
        raise CapabilityEscalationError(
            f"branch {branch_id} presented capabilities {upgrade} not in manifest; "
            f"abort speculation and re-run serialized"
        )
