# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-speculative-branch-contamination-when-a-rollback-checkpoint-restores-tool-side-effects-that-the-branch-predict.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-speculative-branch-contamination-when-a-rollback-checkpoint-restores-tool-side-effects-that-the-branch-predict.warrant.json
# Markdown SHA-256:   8d1a40317ae2be32a32364edf9f2e34cee7592d1607404dea12181a19eacb18a
# Code AST SHA-256:   4c6b71fa5881a164fbe7e354609a00f3ee56ed450a1b0077572bd927b79bf744
# Verified Classes:   EffectClass, BranchContaminationError, ToolSpec
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class EffectClass(Enum):
    ISOLATED = "isolated"
    COMPENSABLE = "compensable"
    IDEMPOTENT = "idempotent"
    UNISOLATABLE = "unisolatable"


class BranchContaminationError(RuntimeError):
    """Raised when a speculative branch would (or did) mutate shared state
    that rollback cannot retract, invalidating the speculation's premise."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    effect_class: EffectClass
    compensation_rpc: str | None = None


def pre_fork_effect_audit(
    branch_id: str,
    reachable_tools: list[ToolSpec],
    barrier_active: bool,
    overlay_active: bool,
) -> None:
    """Static reachability check over a speculative branch's plan DAG.

    Must run before the branch executes and again on every re-plan, because a
    branch can discover a new tool mid-execution that was absent from the
    step-1 manifest.
    """
    for tool in reachable_tools:
        if tool.effect_class is EffectClass.UNISOLATABLE:
            if barrier_active or overlay_active:
                # Writes are deferred or namespaced; effect cannot leak.
                continue
            raise BranchContaminationError(
                f"branch {branch_id!r} reaches unisolatable tool "
                f"{tool.name!r} with no barrier or overlay active; "
                f"rollback cannot retract its effect and the verifier "
                f"would score against a mutated world"
            )
        if tool.effect_class is EffectClass.COMPENSABLE and not tool.compensation_rpc:
            raise BranchContaminationError(
                f"branch {branch_id!r} reaches compensable tool "
                f"{tool.name!r} with no compensation RPC declared; "
                f"a failed rollback leaves a live hold"
            )


def rollback_branch(
    branch_id: str,
    executed_tools: list[ToolSpec],
    invoke_compensation,
    compensation_succeeded: dict[str, bool],
) -> None:
    """Rollback must escalate to abort if any compensation failed.

    A partially-compensated branch is a contamination vector that has
    already fired; continuing the speculation round would let the winner
    reason over the loser's orphaned effect.
    """
    for tool in reversed(executed_tools):
        if tool.effect_class is EffectClass.COMPENSABLE:
            if not compensation_succeeded.get(tool.name, False):
                raise BranchContaminationError(
                    f"compensation for {tool.name!r} on branch "
                    f"{branch_id!r} failed; aborting speculation round "
                    f"rather than committing a branch against a mutated "
                    f"environment"
                )
            invoke_compensation(tool.compensation_rpc)
