# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-tool-call-side-effects-become-irreversible.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abort-a-speculative-branch-before-its-tool-call-side-effects-become-irreversible.warrant.json
# Markdown SHA-256:   d3bbe9e1c73441d081e2da275656a9588d52337d25191652157aff740ec5843e
# Code AST SHA-256:   d43347455ddc99d225f8fb9174a3d0208a76f9019aba90818198ae9c0ebfa509
# Verified Classes:   SpeculativeRollbackViolation, ToolEffect
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a speculative branch's pre-executed effect cannot be
    unwound before it becomes externally observable."""
    pass


class ToolEffect:
    def __init__(self, name, reversible, isolated, read_stable, inverse_ttl_s):
        self.name = name
        self.reversible = reversible          # inverse exists and is total
        self.isolated = isolated              # invisible outside branch until commit
        self.read_stable = read_stable        # no sibling can mutate its read-set
        self.inverse_ttl_s = inverse_ttl_s    # None == non-expiring


def assert_pre_executable(tool: ToolEffect, elapsed_since_pre_exec: float) -> None:
    """Gate a single optimistic tool call. Raises if any validity condition fails."""
    if not tool.reversible:
        raise SpeculativeRollbackViolation(
            f"{tool.name}: no total inverse; must defer effect to post-commit"
        )
    if not tool.isolated:
        raise SpeculativeRollbackViolation(
            f"{tool.name}: effect externally observable pre-commit; must defer"
        )
    if not tool.read_stable:
        raise SpeculativeRollbackViolation(
            f"{tool.name}: read-set mutable by sibling branch; serialize or defer"
        )
    if tool.inverse_ttl_s is not None and elapsed_since_pre_exec >= tool.inverse_ttl_s:
        raise SpeculativeRollbackViolation(
            f"{tool.name}: inverse expired at {tool.inverse_ttl_s}s; "
            f"branch can no longer be rolled back"
        )


def pre_execute_branch(branch_tools, elapsed_since_pre_exec):
    for tool in branch_tools:
        assert_pre_executable(tool, elapsed_since_pre_exec)
    return "pre-executed"
