# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-one-branch-of-a-parallel-plan-and-then-discover-its-rollback-is-unsound.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-one-branch-of-a-parallel-plan-and-then-discover-its-rollback-is-unsound.warrant.json
# Markdown SHA-256:   0d2dc56a6764afd4de5b508555758c5cc25b4a28d0d08da546cc7112c18139ea
# Code AST SHA-256:   772456421047989165fe53b8354bc0644a4faef30f8777f2bc25679bc553b80a
# Verified Classes:   RollbackUnsoundError, CompensationStatus
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class RollbackUnsoundError(RuntimeError):
    """Raised when a speculative branch's effects cannot be terminally reverted."""
    pass


class CompensationStatus:
    SUCCESS = "success"
    TERMINAL_FAILURE = "terminal_failure"   # effect is permanent; rollback impossible
    NON_TERMINAL = "non_terminal"           # pending / conflict / timeout; ambiguous


def rollback_branch(branch, compensator, max_retries=2):
    """
    Attempt to revert a speculative branch's effects.
    Returns only on terminal success. Raises on any non-terminal or
    terminal-failure outcome, because the branch cannot be marked
    rolled_back unless the world agrees.
    """
    for attempt in range(max_retries + 1):
        status, detail = compensator(branch)
        if status == CompensationStatus.SUCCESS:
            branch.mark_rolled_back()
            return
        if status == CompensationStatus.TERMINAL_FAILURE:
            # e.g. refund already settled; 409 Conflict is terminal, not transient.
            raise RollbackUnsoundError(
                f"branch {branch.id} effect is permanent: {detail}"
            )
        # NON_TERMINAL: retry, but never swallow.
        if attempt == max_retries:
            raise RollbackUnsoundError(
                f"branch {branch.id} compensation non-terminal after "
                f"{max_retries + 1} attempts: {detail}"
            )


def commit_plan(plan, winning_branch):
    """
    Commit the winning branch, then terminally roll back the losers.
    If any loser cannot be terminally reverted, the plan is marked
    diverged and the answer must not claim a clean outcome.
    """
    winning_branch.mark_committed()
    for branch in plan.speculative_branches:
        if branch is winning_branch:
            continue
        try:
            rollback_branch(branch, branch.compensator)
        except RollbackUnsoundError as e:
            plan.state = "diverged"
            plan.divergence_log.append(str(e))
            # Do not raise past the plan boundary; surface the divergence
            # in the committed answer so downstream agents see it.
            raise RollbackUnsoundError(
                f"plan {plan.id} diverged: {e}"
            ) from e
    plan.state = "committed"
