# 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-rollback-checkpoints-are-shared-across-a-branch-and-prune-multi-agent-or.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-speculative-branch-contamination-when-rollback-checkpoints-are-shared-across-a-branch-and-prune-multi-agent-or.warrant.json
# Markdown SHA-256:   898508f2088d2ebeba4e05d967e0fc1d47f816cf6c59724e14b0e73dacca212c
# Code AST SHA-256:   54cf58cd76cee65d7d01feb23c5c0b0c052b9aa287e0e301403c75dc5a6e7b58
# Verified Classes:   SinkClass, UnsoundForkError, Checkpoint, Tool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class SinkClass(Enum):
    JOURNALED = "journaled"        # reversible via checkpoint journal
    LEASE_GATED = "lease_gated"    # reversible via revoke-and-drain
    IRREVERSIBLE = "irreversible"  # cannot be rolled back at all


class UnsoundForkError(RuntimeError):
    """Raised when a speculative fork would reach a sink the checkpoint cannot restore."""


@dataclass
class Checkpoint:
    ckpt_id: str
    reversible_sinks: set[str] = field(default_factory=set)
    revocable_leases: set[str] = field(default_factory=set)


@dataclass
class Tool:
    name: str
    sinks: dict[str, SinkClass]
    has_dry_run: bool = False


def assert_fork_is_sound(ckpt: Checkpoint, branch_tools: list[Tool]) -> None:
    """
    Fork-time guardrail: refuse to fork a speculative branch whose toolset
    reaches a sink the checkpoint cannot restore. Rollback soundness is a
    property fixed at fork, not repaired at prune.
    """
    offenders: list[str] = []
    for tool in branch_tools:
        for sink, cls in tool.sinks.items():
            if cls is SinkClass.JOURNALED and sink in ckpt.reversible_sinks:
                continue
            if cls is SinkClass.LEASE_GATED and sink in ckpt.revocable_leases:
                continue
            if cls is SinkClass.IRREVERSIBLE and tool.has_dry_run:
                continue  # substitute dry-run variant at execution time
            offenders.append(f"{tool.name} -> {sink} ({cls.value})")

    if offenders:
        raise UnsoundForkError(
            f"checkpoint {ckpt.ckpt_id} cannot roll back speculative effects: "
            + "; ".join(offenders)
            + ". Serialize these branches or supply dry-run tool variants."
        )


def prune_branch(ckpt: Checkpoint, branch_leases: set[str], inflight_calls: int) -> None:
    """
    Two-phase prune: revoke-and-drain leases BEFORE declaring the checkpoint
    restored. A revoke that races an in-flight write is not a rollback.
    """
    for lease in branch_leases:
        if lease not in ckpt.revocable_leases:
            raise UnsoundForkError(
                f"cannot revoke lease {lease!r}: not covered by {ckpt.ckpt_id}"
            )
    if inflight_calls > 0:
        raise UnsoundForkError(
            f"refusing to declare {ckpt.ckpt_id} restored with "
            f"{inflight_calls} in-flight calls; drain first"
        )
    # drain complete; restore journaled sinks here
