# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-speculative-subtree-before-committing-its-rollback-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-speculative-subtree-before-committing-its-rollback-boundary.warrant.json
# Markdown SHA-256:   9050e335ca3d0a7b716212e9010f25542ab4f380b6a153cf9a27f957af8ffb63
# Code AST SHA-256:   5312a826b7a00a5c7e4429b36a6956a26a08a3dea5e104c5f46027961ca826ec
# Verified Classes:   ToolClass, RollbackUnsoundError, Effect, Subtree
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class ToolClass(Enum):
    ISOLATED = "isolated"
    KEYED_REVERSIBLE = "keyed_reversible"
    POOLED = "pooled"


class RollbackUnsoundError(RuntimeError):
    """Raised when a rollback boundary is declared over a subtree with unverified pooled effects."""


@dataclass
class Effect:
    tool: str
    tool_class: ToolClass
    key: str
    verified_delta: int | None  # None means the delta could not be read back


@dataclass
class Subtree:
    branch_id: str
    effects: list[Effect]


def assert_rollback_sound(subtree: Subtree) -> None:
    """
    Enforce the rollback invariant: a subtree may be rolled back only if every
    POOLED effect has a verified-zero delta. Transport success is not enough.
    """
    for eff in subtree.effects:
        if eff.tool_class is not ToolClass.POOLED:
            continue
        if eff.verified_delta is None:
            raise RollbackUnsoundError(
                f"branch {subtree.branch_id}: pooled effect {eff.tool} "
                f"(key={eff.key}) has no authoritative read-back; "
                f"rollback would be best-effort, not sound"
            )
        if eff.verified_delta != 0:
            raise RollbackUnsoundError(
                f"branch {subtree.branch_id}: pooled effect {eff.tool} "
                f"(key={eff.key}) leaked delta={eff.verified_delta}; "
                f"must be marked ORPHANED and attributed to lineage, not rolled back"
            )


def rollback(subtree: Subtree) -> str:
    assert_rollback_sound(subtree)
    return f"ROLLED_BACK:{subtree.branch_id}"
