# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculative-rollback-checkpoint-when-a-sibling-branch-has-already-committed-external-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-a-speculative-rollback-checkpoint-when-a-sibling-branch-has-already-committed-external-side-effects.warrant.json
# Markdown SHA-256:   eec84db9daaf53f63298c63bd05d15d7025fa4f67562675d847cb8536c2e9869
# Code AST SHA-256:   5166c024f9843677b533d9389094f6023ce2c40fbf4e017e76ae824838b7ed4a
# Verified Classes:   RollbackUnsafeError, EffectKind, ExternalEffect, Checkpoint
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class RollbackUnsafeError(RuntimeError):
    """Raised when a rollback checkpoint is invalidated by a committed,
    uncompensated external side effect on a discarded sibling branch."""


class EffectKind(Enum):
    IDEMPOTENT = "idempotent"
    NON_IDEMPOTENT = "non_idempotent"


@dataclass(frozen=True)
class ExternalEffect:
    branch_id: str
    tool: str
    idempotency_key: str
    kind: EffectKind
    compensated: bool = False


@dataclass
class Checkpoint:
    checkpoint_id: str
    # Effect ledger lives OUTSIDE the checkpointed agent memory on purpose.
    effects: Dict[str, ExternalEffect] = field(default_factory=dict)

    def record_effect(self, effect: ExternalEffect) -> None:
        self.effects[effect.idempotency_key] = effect

    def compensate(self, idempotency_key: str) -> None:
        eff = self.effects[idempotency_key]
        self.effects[idempotency_key] = ExternalEffect(
            branch_id=eff.branch_id,
            tool=eff.tool,
            idempotency_key=eff.idempotency_key,
            kind=eff.kind,
            compensated=True,
        )


def assert_rollback_safe(checkpoint: Checkpoint, discarded_branches: Set[str]) -> None:
    """Enforce the causal-cut invariant before restoring a checkpoint.

    rollback(cp) is sound iff every committed non-idempotent effect on a
    discarded branch has been compensated. Otherwise the checkpoint is DIRTY
    and must be invalidated rather than restored.
    """
    for eff in checkpoint.effects.values():
        if eff.branch_id not in discarded_branches:
            continue
        if eff.kind is EffectKind.NON_IDEMPOTENT and not eff.compensated:
            raise RollbackUnsafeError(
                f"checkpoint {checkpoint.checkpoint_id} is DIRTY: "
                f"branch {eff.branch_id} committed uncompensated non-idempotent "
                f"effect {eff.tool!r} (key={eff.idempotency_key}). "
                f"Rollback forbidden; escalate to reconciliation."
            )


def rollback(checkpoint: Checkpoint, discarded_branches: Set[str]) -> None:
    # The guard runs BEFORE any state restore. A successful internal restore
    # with a dirty ledger is exactly the phantom-rollback duplication failure.
    assert_rollback_safe(checkpoint, discarded_branches)
    # ... restore internal state to checkpoint here ...
