# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-contain-speculative-writes-when-a-speculative-tool-call-commits-a-non-idempotent-external-effect-before-the-branch-is-discarded.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-contain-speculative-writes-when-a-speculative-tool-call-commits-a-non-idempotent-external-effect-before-the-branch-is-discarded.warrant.json
# Markdown SHA-256:   9390796e48cb4ebf2ed6cee14c6b1a2f67d69c8ea49bb870001472091a36f2a4
# Code AST SHA-256:   cc11a5b2201c3ec0aee0fe5a4407ac76a929511fc99c69e9b21d9e1a28b48b4d
# Verified Classes:   EffectClass, SpeculativeContainmentError, CommittedCall, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    READ = "read"
    IDEMPOTENT_WRITE = "idempotent_write"
    NON_IDEMPOTENT_WRITE = "non_idempotent_write"
    IRREVERSIBLE = "irreversible"


class SpeculativeContainmentError(RuntimeError):
    """Raised when a speculative branch holds an un-compensable committed effect."""


@dataclass
class CommittedCall:
    tool: str
    effect_class: EffectClass
    commit_token: Optional[str]
    compensation_token: Optional[str]


@dataclass
class Branch:
    branch_id: str
    committed_calls: list[CommittedCall] = field(default_factory=list)


def assert_speculative_call_allowed(
    tool: str,
    effect_class: EffectClass,
    transport_enforces_speculative_mode: bool,
    response_has_commit_token: bool,
) -> None:
    """Gate before emitting any tool call from a speculative branch."""
    if effect_class in (EffectClass.NON_IDEMPOTENT_WRITE, EffectClass.IRREVERSIBLE):
        if not transport_enforces_speculative_mode:
            raise SpeculativeContainmentError(
                f"tool {tool!r} has effect_class={effect_class.value} but speculative "
                f"mode is not transport-enforced; refusing to emit call"
            )
        if not response_has_commit_token:
            raise SpeculativeContainmentError(
                f"tool {tool!r} does not return a commit token; "
                f"branch would be un-discardable after commit"
            )


def assert_branch_discardable(branch: Branch) -> None:
    """Gate before transitioning a branch to discarded."""
    un_compensable = [
        c for c in branch.committed_calls
        if c.effect_class is not EffectClass.READ
        and c.compensation_token is None
    ]
    if un_compensable:
        raise SpeculativeContainmentError(
            f"branch {branch.branch_id!r} holds {len(un_compensable)} committed "
            f"effect(s) with no compensation token: "
            f"{[c.tool for c in un_compensable]}; halting discard"
        )
