# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-s-tool-commits-as-durable-before-the-parent-rollout-has-voted-to-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-s-tool-commits-as-durable-before-the-parent-rollout-has-voted-to-commit.warrant.json
# Markdown SHA-256:   72acc0b790c0329da728e711d5f24003198f16d4a924f8b7518154848d7911ab
# Code AST SHA-256:   085e2e6d048788291667e1bc0a9ccba686d47248eb4e023155c84a6973517844
# Verified Classes:   ToolClass, SpeculativeEffectLeak, ToolCall, RolloutJournal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ToolClass(Enum):
    PROVISIONAL_SAFE = "provisional_safe"
    COMPENSABLE = "compensable"
    DURABLE_IRREVERSIBLE = "durable_irreversible"


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a speculative branch reaches a durable tool or when the
    abort path attempts to compensate from branch summary rather than journal."""


@dataclass
class ToolCall:
    rollout_id: str
    branch_id: str
    call_seq: int
    tool_name: str
    tool_class: ToolClass
    idempotency_key: str
    compensated: bool = False


@dataclass
class RolloutJournal:
    calls: list[ToolCall] = field(default_factory=list)

    def record(self, call: ToolCall) -> None:
        for existing in self.calls:
            if (existing.rollout_id, existing.branch_id, existing.call_seq) == (
                call.rollout_id, call.branch_id, call.call_seq
            ):
                raise SpeculativeEffectLeak(
                    f"duplicate call_seq {call.call_seq} for branch {call.branch_id}; "
                    "branch-local retry would overwrite journal entry and corrupt compensation"
                )
        self.calls.append(call)


def admit_branch_call(journal: RolloutJournal, call: ToolCall) -> None:
    if call.tool_class is ToolClass.DURABLE_IRREVERSIBLE:
        raise SpeculativeEffectLeak(
            f"branch {call.branch_id} attempted durable tool {call.tool_name} "
            "before commit vote; serialize this call or exclude it from fan-out"
        )
    journal.record(call)


def execute_abort(journal: RolloutJournal, rollout_id: str, branch_id: str) -> list[ToolCall]:
    branch_calls = [
        c for c in journal.calls
        if c.rollout_id == rollout_id and c.branch_id == branch_id
    ]
    if not branch_calls:
        return []
    uncompensable = [c for c in branch_calls if c.tool_class is ToolClass.DURABLE_IRREVERSIBLE]
    if uncompensable:
        raise SpeculativeEffectLeak(
            f"abort of {branch_id} cannot compensate durable calls: "
            f"{[c.tool_name for c in uncompensable]}; reconciliation obligation outstanding"
        )
    to_compensate = [c for c in reversed(branch_calls) if not c.compensated]
    for call in to_compensate:
        call.compensated = True
    return to_compensate


if __name__ == "__main__":
    journal = RolloutJournal()
    admit_branch_call(journal, ToolCall("r1", "b1", 1, "issue_refund", ToolClass.COMPENSABLE, "r1:b1:1"))
    admit_branch_call(journal, ToolCall("r1", "b1", 2, "issue_refund", ToolClass.COMPENSABLE, "r1:b1:2"))
    # The next call would be rejected: durable tool reached pre-vote.
    try:
        admit_branch_call(journal, ToolCall("r1", "b1", 3, "send_customer_email", ToolClass.DURABLE_IRREVERSIBLE, "r1:b1:3"))
    except SpeculativeEffectLeak as e:
        print("blocked:", e)
    compensated = execute_abort(journal, "r1", "b1")
    assert [c.call_seq for c in compensated] == [2, 1], "compensation must replay journal in reverse"
