# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-execution-from-committing-orphaned-side-effects-in-shared-multi-agent-workspaces.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-execution-from-committing-orphaned-side-effects-in-shared-multi-agent-workspaces.warrant.json
# Markdown SHA-256:   b40f8fdde7fae94cdc11baa9c5303ccd968100876771ac099d2c1095cd7d7997
# Code AST SHA-256:   1da1b6cad881993fb3b426cd429ee3e4f786aec07d4ac8b74aa24347cd5f99bc
# Verified Classes:   SpeculationInvariantViolation, ToolNotSpeculatableError, EffectHandle, CommitLog, SpeculationCoordinator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Optional


class SpeculationInvariantViolation(RuntimeError):
    """Raised when a speculative branch's side effect cannot be safely aborted."""
    pass


class ToolNotSpeculatableError(SpeculationInvariantViolation):
    """Raised at tool registration when a tool cannot honor deferral or compensation."""
    pass


@dataclass
class EffectHandle:
    speculation_token: str
    branch_id: str
    tool_name: str
    handle: str            # gateway-issued handle (reservation_id, message_id, ...)
    compensable: bool


@dataclass
class CommitLog:
    """Durable record of (speculation_token -> effect handles). Must survive coordinator crash."""
    entries: Dict[str, List[EffectHandle]] = field(default_factory=dict)
    aborted: set = field(default_factory=set)

    def register(self, eff: EffectHandle) -> None:
        self.entries.setdefault(eff.speculation_token, []).append(eff)


class SpeculationCoordinator:
    def __init__(self, log: CommitLog):
        self.log = log
        self._registered_tools: Dict[str, str] = {}  # tool -> "deferred" | "compensating"

    def register_tool(self, name: str, regime: str) -> None:
        if regime not in ("deferred", "compensating"):
            raise ToolNotSpeculatableError(
                f"tool {name!r} declared regime {regime!r}; must be deferred or compensating"
            )
        self._registered_tools[name] = regime

    def dispatch_speculative(self, token: str, branch: str, tool: str,
                             handle: str, compensable: bool) -> None:
        regime = self._registered_tools.get(tool)
        if regime is None:
            # Unregistered tool: cannot guarantee abort safety -> refuse to speculate.
            raise ToolNotSpeculatableError(
                f"speculative call to unregistered tool {tool!r} on branch {branch}"
            )
        if regime == "compensating" and not compensable:
            # Effect is visible and cannot be undone: this is exactly the OSSE condition.
            raise SpeculationInvariantViolation(
                f"tool {tool!r} materialized non-compensable effect {handle!r} "
                f"under speculation token {token!r}; abort would orphan it"
            )
        self.log.register(EffectHandle(token, branch, tool, handle, compensable))

    def abort(self, token: str) -> List[str]:
        """Idempotent compensating abort. Returns handles compensated (empty if already aborted)."""
        if token in self.log.aborted:
            return []
        effects = self.log.entries.get(token, [])
        uncompensable = [e for e in effects if not e.compensable]
        if uncompensable:
            # Cannot silently proceed: surface the orphan for human/ledger reconciliation.
            raise SpeculationInvariantViolation(
                f"abort({token!r}) blocked: {len(uncompensable)} non-compensable "
                f"effect(s) would be orphaned: {[e.handle for e in uncompensable]}"
            )
        self.log.aborted.add(token)
        return [e.handle for e in effects]


# --- reproduction of the observed failure ---
if __name__ == "__main__":
    coord = SpeculationCoordinator(CommitLog())
    coord.register_tool("reserve_inventory", "compensating")

    # S1 materializes a reservation the gateway cannot reverse -> must fail loudly.
    try:
        coord.dispatch_speculative(
            token="spec-42", branch="S1", tool="reserve_inventory",
            handle="reservation:7f3a", compensable=False,
        )
    except SpeculationInvariantViolation as exc:
        print(f"BLOCKED orphaned side effect: {exc}")

    # Correct path: compensable reservation, then abort releases it.
    coord.dispatch_speculative(
        token="spec-43", branch="S1", tool="reserve_inventory",
        handle="reservation:7f3a", compensable=True,
    )
    released = coord.abort("spec-43")
    print(f"abort(spec-43) compensated: {released}")
    # Idempotent re-abort (coordinator crash recovery path).
    assert coord.abort("spec-43") == []
