# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-tool-invocation-has-crossed-the-point-of-no-return-under-optimistic-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-tool-invocation-has-crossed-the-point-of-no-return-under-optimistic-multi-agent-rollback.warrant.json
# Markdown SHA-256:   b1bd208e47a1423d0a3de6d7e79856e29924e6c14229b6f52a041d63fb8df798
# Code AST SHA-256:   3c84cbc05fb690f20a3a92de8ddaf2cdd726269148c6be11eb321debcdcfa567
# Verified Classes:   SpeculationBoundaryError, BranchState, Receipt, SpeculativeBranch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculationBoundaryError(RuntimeError):
    """Raised when a branch crosses the external-visibility frontier
    without a revocable receipt or a committed arbitration ticket."""


class BranchState(Enum):
    SPECULATING = "speculating"
    RECEIPT_HELD = "receipt_held"      # crossed the boundary, uncommitted
    WINNER = "winner"
    DISCARDABLE = "discardable"
    IRREVERSIBLE = "irreversible"      # crossed boundary, no revoke support


@dataclass
class Receipt:
    tool: str
    external_id: str
    supports_revoke: bool
    supports_compensate: bool
    acquired_at: float = field(default_factory=time.time)


@dataclass
class SpeculativeBranch:
    branch_id: str
    ticket_id: str
    ticket_committed: bool = False
    state: BranchState = BranchState.SPECULATING
    receipts: list = field(default_factory=list)


def record_tool_return(branch: SpeculativeBranch, receipt: Receipt) -> None:
    """Called the instant a side-effecting tool returns. This is the
    only correct place to detect the boundary crossing."""
    branch.receipts.append(receipt)

    if not receipt.supports_revoke and not receipt.supports_compensate:
        # Tool declared no rollback contract: branch is irrevocably speculative.
        branch.state = BranchState.IRREVERSIBLE
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id} invoked {receipt.tool} "
            f"(external_id={receipt.external_id}) with no rollback contract; "
            f"ticket {branch.ticket_id} uncommitted. Serialize this tool "
            f"behind arbitration or provide revoke/compensate."
        )

    if not branch.ticket_committed:
        branch.state = BranchState.RECEIPT_HELD


def mark_discardable(branch: SpeculativeBranch) -> None:
    """The guardrail: refuse to discard a branch that holds an
    un-revoked external receipt. This is the invariant that prevents
    the double-notify / double-charge failure."""
    if branch.state == BranchState.IRREVERSIBLE:
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id} is irreversible; cannot discard. "
            f"Escalate to external reconciliation."
        )
    if branch.receipts and not branch.ticket_committed:
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id} holds {len(branch.receipts)} "
            f"un-revoked receipt(s) while ticket {branch.ticket_id} is "
            f"uncommitted; refusing DISCARDABLE transition."
        )
    branch.state = BranchState.DISCARDABLE


def commit_arbitration(branch: SpeculativeBranch, winner: bool) -> None:
    """Commit the ticket. Losers with receipts must be revoked, not
    compensated-as-new-effect, before discard."""
    branch.ticket_committed = True
    if winner:
        branch.state = BranchState.WINNER
        return
    for r in branch.receipts:
        if not r.supports_revoke:
            raise SpeculationBoundaryError(
                f"losing branch {branch.branch_id} holds receipt "
                f"{r.external_id} on {r.tool} that cannot be revoked "
                f"pre-commit; compensation would emit a new external effect."
            )
        # revoke(r.external_id) would be called here against the external party
    branch.state = BranchState.DISCARDABLE
