# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-speculative-branch-before-rollback-rather-than-merging-it-into-the-verified-timeline.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-speculative-branch-before-rollback-rather-than-merging-it-into-the-verified-timeline.warrant.json
# Markdown SHA-256:   bae18391c64c10b94ee3070688445b6b155acef5b5dfa918a8c982d8db78fb75
# Code AST SHA-256:   797fd97660f692805ccb0b69c4113d8ca41686b86e9ef1dd5e53e247fc44490c
# Verified Classes:   EffectClass, Surface, Effect, Branch, ContaminantBranchError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EffectClass(Enum):
    READ = "read"
    WRITE = "write"


class Surface(Enum):
    PRIVATE = "private"   # branch-local overlay, safe to drop
    SHARED = "shared"     # world-visible, survives branch death


@dataclass
class Effect:
    tool: str
    cls: EffectClass
    surface: Surface
    attributable: bool
    reversed: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)
    invoked_unmanifested_tool: bool = False


class ContaminantBranchError(RuntimeError):
    """Raised when a branch to be discarded has live, unattributed, or
    unreversed shared-surface writes that would survive rollback."""


def assert_discardable(branch: Branch, manifest_tools: set[str]) -> None:
    if branch.invoked_unmanifested_tool:
        raise ContaminantBranchError(
            f"branch {branch.branch_id}: invoked tool outside effect manifest; "
            "effect enumeration incomplete, quarantine required"
        )
    for eff in branch.effects:
        if eff.tool not in manifest_tools:
            raise ContaminantBranchError(
                f"branch {branch.branch_id}: effect on {eff.tool!r} not in manifest"
            )
        if eff.cls is EffectClass.WRITE and eff.surface is Surface.SHARED:
            if not eff.attributable:
                raise ContaminantBranchError(
                    f"branch {branch.branch_id}: shared write via {eff.tool!r} "
                    "is unattributable; cannot selectively revert"
                )
            if not eff.reversed:
                raise ContaminantBranchError(
                    f"branch {branch.branch_id}: shared write via {eff.tool!r} "
                    "not yet compensated; merge blocked"
                )


def rollback(branch: Branch, manifest_tools: set[str]) -> None:
    # Gate every discard behind the contamination check.
    assert_discardable(branch, manifest_tools)
    branch.effects.clear()
