# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-capability-scoped-sandbox-revocation-against-in-flight-mcp-tool-calls-before-the-next-model-turn.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-capability-scoped-sandbox-revocation-against-in-flight-mcp-tool-calls-before-the-next-model-turn.warrant.json
# Markdown SHA-256:   e370517bab41cc0ae6c3f9d7468430c94a39f57b24ac0bcebaadbaaf039c880f
# Code AST SHA-256:   31cd0b03e7aa55b6578e1f35c7494d8009d6c1ccc54e59ba219f4247cf413495
# Verified Classes:   CapabilityEpochViolation, CapabilityTable, InFlightCall, AdmittedResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CapabilityEpochViolation(RuntimeError):
    """Raised when an in-flight tool result is admitted without epoch reconciliation."""
    pass


@dataclass
class CapabilityTable:
    epoch: int = 0
    held: set = field(default_factory=set)

    def revoke(self, capability: str) -> None:
        if capability not in self.held:
            raise CapabilityEpochViolation(
                f"cannot revoke unheld capability {capability!r} at epoch {self.epoch}"
            )
        self.held.discard(capability)
        self.epoch += 1


@dataclass
class InFlightCall:
    request_id: str
    capability: str
    dispatch_epoch: int
    buffer: bytes = b""


@dataclass
class AdmittedResult:
    request_id: str
    payload: bytes
    stale_capability: Optional[str] = None
    epoch_delta: int = 0


def admit_result(call: InFlightCall, table: CapabilityTable) -> AdmittedResult:
    if call.dispatch_epoch > table.epoch:
        raise CapabilityEpochViolation(
            f"dispatch epoch {call.dispatch_epoch} is ahead of table epoch {table.epoch}"
        )
    if call.capability in table.held and call.dispatch_epoch == table.epoch:
        return AdmittedResult(call.request_id, call.buffer)
    if call.capability not in table.held:
        delta = table.epoch - call.dispatch_epoch
        if delta <= 0:
            raise CapabilityEpochViolation(
                f"capability {call.capability!r} absent but epoch did not advance "
                f"(dispatch {call.dispatch_epoch}, table {table.epoch}); "
                f"table mutation bypassed revoke()"
            )
        return AdmittedResult(
            call.request_id,
            call.buffer,
            stale_capability=call.capability,
            epoch_delta=delta,
        )
    raise CapabilityEpochViolation(
        f"capability {call.capability!r} held but epoch drifted "
        f"(dispatch {call.dispatch_epoch}, table {table.epoch}); "
        f"re-admission requires explicit epoch reconciliation"
    )
