# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-rollback-horizon-when-speculative-branch-and-verify-agents-share-a-mutable-world.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-rollback-horizon-when-speculative-branch-and-verify-agents-share-a-mutable-world.warrant.json
# Markdown SHA-256:   51b2192aa747f62860e9d5003cf5d843a468a0dee3718181cdafb88fb0efa8b5
# Code AST SHA-256:   4d092dd848b8da9eaa3fdc07506caf221dc75d10d95f4677fbb62324b509dc0e
# Verified Classes:   SpeculativeHorizonViolation, ToolRegistry, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SpeculativeHorizonViolation(RuntimeError):
    """Raised when a speculative branch crosses the commit horizon with an
    un-reverted external effect, or when selection races an in-flight
    non-compensable call."""
    pass


PURE = "pure"
COMPENSABLE = "compensable"
GATED = "gated"


class ToolRegistry:
    def __init__(self):
        self._class = {}

    def register(self, name, kind, compensator=None):
        if kind == COMPENSABLE and compensator is None:
            raise SpeculativeHorizonViolation(
                f"tool {name!r} classified compensable but has no compensator"
            )
        self._class[name] = (kind, compensator)

    def kind(self, name):
        return self._class[name][0]


class SpeculativeBranch:
    def __init__(self, branch_id, registry):
        self.branch_id = branch_id
        self.registry = registry
        self.pending_gate = None      # set when suspended at a gated tool
        self.in_flight = False        # a non-compensable call is unresolved
        self.effects = []             # (tool, compensator) for compensable calls

    def call(self, tool, args, invoke):
        kind = self.registry.kind(tool)
        if kind == PURE:
            return invoke(args)
        if kind == COMPENSABLE:
            result = invoke(args)
            _, comp = self.registry._class[tool]
            self.effects.append((tool, comp, args))
            return result
        # GATED: must not execute while speculative
        raise SpeculativeHorizonViolation(
            f"branch {self.branch_id} attempted non-compensable tool {tool!r} "
            f"while speculative; must suspend behind the commit gate"
        )


def select_and_rollback(branches, winner_id, commit):
    # Barrier: refuse to select while any branch has an unresolved
    # non-compensable call in flight. This is the race that manufactures
    # phantoms after the sweep has already passed.
    for b in branches:
        if b.in_flight:
            raise SpeculativeHorizonViolation(
                f"branch {b.branch_id} has in-flight non-compensable effect; "
                f"selection must wait for quiescence"
            )

    winner = next(b for b in branches if b.branch_id == winner_id)
    for b in branches:
        if b.branch_id == winner_id:
            continue
        # Drain compensators BEFORE pruning lineage, atomically.
        for tool, comp, args in reversed(b.effects):
            comp(args)
        b.effects.clear()
    commit(winner)
    return winner
