# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-fence-speculative-tool-calls-before-rollback-reconciliation-and-what-breaks-if-it-doesn-t.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-fence-speculative-tool-calls-before-rollback-reconciliation-and-what-breaks-if-it-doesn-t.warrant.json
# Markdown SHA-256:   29f008dcdd1ed1f665e35d49bf1fcaaa85d653015a657e866d3dd07c735578e2
# Code AST SHA-256:   0dd4efbf33a265748f38cef29167b6cc6b6c0b5664549dc605ad90faf2c273f3
# Verified Classes:   SpeculativeFenceViolation, ToolEffect, FencedToolGateway
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set, Optional
import time


class SpeculativeFenceViolation(RuntimeError):
    """Raised when a tool effect commits for a branch that is no longer live."""
    pass


@dataclass
class ToolEffect:
    branch_id: str
    epoch: int
    request_id: str
    compensation: Optional[str] = None
    committed: bool = False


class FencedToolGateway:
    """
    Enforces the fencing invariant: a tool effect may only commit while its
    issuing branch is in the coordinator's live set. Abandonment is two-phase:
    fence (reject new commits) -> drain -> compensate -> abandon.
    """

    def __init__(self) -> None:
        self._live: Set[str] = set()
        self._fenced: Set[str] = set()
        self._journal: Dict[str, ToolEffect] = {}
        self._inflight: Dict[str, ToolEffect] = {}

    def register_branch(self, branch_id: str, epoch: int) -> None:
        self._live.add(branch_id)

    def dispatch(self, effect: ToolEffect) -> str:
        if effect.branch_id in self._fenced or effect.branch_id not in self._live:
            raise SpeculativeFenceViolation(
                f"dispatch rejected: branch {effect.branch_id} not live"
            )
        self._inflight[effect.request_id] = effect
        return effect.request_id

    def commit(self, request_id: str) -> None:
        effect = self._inflight.get(request_id)
        if effect is None:
            raise SpeculativeFenceViolation(f"unknown request {request_id}")
        # The linearization point. This is where the race is decided.
        if effect.branch_id in self._fenced or effect.branch_id not in self._live:
            del self._inflight[request_id]
            raise SpeculativeFenceViolation(
                f"commit rejected for fenced/abandoned branch {effect.branch_id}; "
                f"effect {request_id} must be compensated, not applied"
            )
        effect.committed = True
        self._journal[request_id] = effect
        del self._inflight[request_id]

    def abandon(self, branch_id: str, drain_timeout_s: float = 2.0) -> None:
        """Two-phase abandonment. Phase 1 fences; phase 2 drains + compensates."""
        self._fenced.add(branch_id)  # phase 1: no new commits accepted
        deadline = time.time() + drain_timeout_s
        while time.time() < deadline:
            pending = [r for r, e in self._inflight.items() if e.branch_id == branch_id]
            if not pending:
                break
            time.sleep(0.01)
        # phase 2: compensate anything that committed before the fence and
        # reject anything still in flight (its commit will fail the fence check).
        for request_id, effect in list(self._journal.items()):
            if effect.branch_id == branch_id and effect.compensation:
                self._apply_compensation(effect)
        for request_id in [r for r, e in self._inflight.items() if e.branch_id == branch_id]:
            del self._inflight[request_id]
        self._live.discard(branch_id)
        self._fenced.discard(branch_id)

    def _apply_compensation(self, effect: ToolEffect) -> None:
        # Idempotent by request_id; safe to call from rollback and reconciliation.
        ...


def reconcile(committed_branch: str, gateway: FencedToolGateway) -> Dict[str, ToolEffect]:
    if committed_branch not in gateway._live:
        raise SpeculativeFenceViolation(
            f"cannot reconcile non-live branch {committed_branch}"
        )
    return {
        rid: eff for rid, eff in gateway._journal.items()
        if eff.branch_id == committed_branch and eff.committed
    }
