# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-rollback-as-unsafe-once-a-tool-call-has-crossed-the-commit-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-speculative-branch-rollback-as-unsafe-once-a-tool-call-has-crossed-the-commit-horizon.warrant.json
# Markdown SHA-256:   22a62b6d47abeea2234709c4d16ba29e7298e75408be8394c42c412f25441d05
# Code AST SHA-256:   56dd7a0c596516bea3bc9f6dd863f3bbc5a3724531f28d11d05995dd6783a22b
# Verified Classes:   RollbackSafetyError, BranchState, RemoteEffect, ToolCall, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class RollbackSafetyError(RuntimeError):
    """Raised when a branch is rolled back while a dispatched tool call's
    remote commit state is unknown or unverified."""


class BranchState(Enum):
    SPECULATIVE = "speculative"
    COMMITTED = "committed"
    ROLLED_BACK = "rolled_back"
    QUARANTINED = "quarantined"


class RemoteEffect(Enum):
    ABSENT = "absent"
    PRESENT = "present"
    UNKNOWN = "unknown"


@dataclass
class ToolCall:
    call_id: str
    tool: str
    idempotent: bool
    compensator: Optional[str] = None
    remote_effect: RemoteEffect = RemoteEffect.UNKNOWN


@dataclass
class SpeculativeBranch:
    branch_id: str
    state: BranchState = BranchState.SPECULATIVE
    dispatched: list[ToolCall] = field(default_factory=list)


def rollback_branch(
    branch: SpeculativeBranch,
    probe_remote_effect,
    apply_compensator,
    verify_compensation,
) -> BranchState:
    """Roll back a losing speculative branch, enforcing the commit-horizon
    invariant: a branch with any unverified remote effect is quarantined,
    never marked clean."""

    for call in branch.dispatched:
        if call.remote_effect is RemoteEffect.UNKNOWN:
            call.remote_effect = probe_remote_effect(call.call_id)

    unresolved = [
        c for c in branch.dispatched
        if c.remote_effect is RemoteEffect.UNKNOWN
    ]
    if unresolved:
        branch.state = BranchState.QUARANTINED
        raise RollbackSafetyError(
            f"branch {branch.branch_id}: cannot roll back, remote effect "
            f"unknown for calls {[c.call_id for c in unresolved]}"
        )

    present = [c for c in branch.dispatched if c.remote_effect is RemoteEffect.PRESENT]
    for call in present:
        if call.idempotent:
            continue
        if call.compensator is None:
            branch.state = BranchState.QUARANTINED
            raise RollbackSafetyError(
                f"branch {branch.branch_id}: effect durable for non-idempotent "
                f"call {call.call_id} ({call.tool}) with no registered compensator"
            )
        apply_compensator(call.call_id, call.compensator)
        if not verify_compensation(call.call_id):
            branch.state = BranchState.QUARANTINED
            raise RollbackSafetyError(
                f"branch {branch.branch_id}: compensation for {call.call_id} "
                f"not verified against external system; branch remains quarantined"
            )

    branch.state = BranchState.ROLLED_BACK
    return branch.state
