# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-branch-divergence-is-irreversible-in-speculative-multi-agent-execution-with-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-branch-divergence-is-irreversible-in-speculative-multi-agent-execution-with-rollback.warrant.json
# Markdown SHA-256:   4889f332ba7495392a246bfe61b61c007f08fa5c18465f2b3376edbc9ab83f25
# Code AST SHA-256:   977ca56c1539d0503e450feef689f80fa37d03c73a4d49ac9e574b3456dd9650
# Verified Classes:   RollbackUnsafeError, EdgeKind, ActionNode, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class RollbackUnsafeError(RuntimeError):
    """Raised when a branch cannot be rolled back because its effects are irreversible."""
    pass


class EdgeKind(Enum):
    LOCAL_MUTATION = "local_mutation"
    EGRESS = "egress"                # leaves orchestrator state domain
    EVENT_EMISSION = "event_emission"
    NOTIFICATION = "notification"


@dataclass(frozen=True)
class ActionNode:
    name: str
    kind: EdgeKind
    compensated_by: str | None = None   # name of compensating action, if any
    compensation_is_inverse: bool = False
    idempotent_compensation: bool = False


@dataclass
class Branch:
    branch_id: str
    executed: list[ActionNode] = field(default_factory=list)
    planned: list[ActionNode] = field(default_factory=list)
    acknowledged_by_external: bool = False


IRREVERSIBLE_KINDS: FrozenSet[EdgeKind] = frozenset({
    EdgeKind.EGRESS,
    EdgeKind.EVENT_EMISSION,
    EdgeKind.NOTIFICATION,
})


def assert_rollback_safe(branch: Branch) -> None:
    """
    Structural pre-check: refuse rollback if the branch's executed or planned
    action graph contains irreversible or asymmetric edges.
    """
    for node in branch.executed + branch.planned:
        if node.kind in IRREVERSIBLE_KINDS:
            raise RollbackUnsafeError(
                f"branch {branch.branch_id}: action '{node.name}' has "
                f"irreversible kind {node.kind.value}; rollback would leak "
                f"an un-observable commitment"
            )
        if node.kind == EdgeKind.LOCAL_MUTATION and not node.compensation_is_inverse:
            raise RollbackUnsafeError(
                f"branch {branch.branch_id}: action '{node.name}' has "
                f"asymmetric compensation '{node.compensated_by}'; "
                f"compensation is a new action, not an inverse"
            )
        if node.compensated_by and not node.idempotent_compensation:
            raise RollbackUnsafeError(
                f"branch {branch.branch_id}: compensation for '{node.name}' "
                f"is non-idempotent; retry would compound divergence"
            )
    if branch.acknowledged_by_external:
        raise RollbackUnsafeError(
            f"branch {branch.branch_id}: effect acknowledged by external "
            f"observer; committed regardless of local state"
        )


def rollback_or_escalate(branch: Branch) -> str:
    try:
        assert_rollback_safe(branch)
    except RollbackUnsafeError as exc:
        return f"ESCALATE_TO_RECONCILIATION: {exc}"
    # safe: perform local rollback
    return "ROLLED_BACK"
