# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-outlived-its-rollback-window-in-multi-agent-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-divergence-has-outlived-its-rollback-window-in-multi-agent-tool-invocation.warrant.json
# Markdown SHA-256:   27e748016f4aab648eca9a9dc326bcf77c37bd39159f1779126b6ff13fbe0048
# Code AST SHA-256:   15d205cf8a61c5f77ac3ec3a0301c13d6c5912d5e4a91363dd50db78ba3128fa
# Verified Classes:   RollbackWindowExceeded, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RollbackWindowExceeded(RuntimeError):
    """Raised when a speculative branch's tool commit frontier has passed
    the verification-close frontier, making rollback unsound."""
    pass


@dataclass
class ToolCall:
    name: str
    declared_commit_latency_s: float
    observed_commit_latency_s: float
    compensable: bool


def admit_speculative_branch(
    branch_id: str,
    tool_calls: list[ToolCall],
    verification_close_s: float,
    now_s: float,
) -> None:
    """Refuse to speculate when any call's commit frontier precedes
    the verification close, or when a call is non-compensable."""
    for call in tool_calls:
        if not call.compensable:
            raise RollbackWindowExceeded(
                f"branch {branch_id}: tool '{call.name}' is non-compensable; "
                f"it cannot be speculated on and must sit behind a commit barrier"
            )
        # Use observed latency, never declared, for the frontier estimate.
        commit_frontier = now_s + call.observed_commit_latency_s
        if commit_frontier <= verification_close_s:
            raise RollbackWindowExceeded(
                f"branch {branch_id}: tool '{call.name}' commits at "
                f"t={commit_frontier:.1f}s but verification closes at "
                f"t={verification_close_s:.1f}s; rollback would be unsound "
                f"(declared latency {call.declared_commit_latency_s:.1f}s "
                f"understates observed {call.observed_commit_latency_s:.1f}s)"
            )


def rollback_branch(branch_id: str, committed_calls: list[ToolCall]) -> None:
    """Rollback is only legal if every committed call has a tested inverse."""
    for call in committed_calls:
        if not call.compensable:
            raise RollbackWindowExceeded(
                f"branch {branch_id}: cannot roll back committed call "
                f"'{call.name}'; no compensating operation is registered"
            )
    # ... issue compensating operations, then mark ledger ROLLED_BACK
