From c5e1f7d2945e98bdbdbe503ee93d29a0b0bc5f38 Mon Sep 17 00:00:00 2001 From: slinkydeveloper Date: Mon, 16 Nov 2026 13:48:23 +0100 Subject: [PATCH 01/11] Sessions: attempts on the explicit recovery VM, without the selector A session object's attempts no longer run on the SDK's journaled context with a selector patched in to fake one await point over do_progress: they run on shared-core's ExplicitRecoveryVM (restatedev/sdk-shared-core#118), which never replays and has no await point at all. - src/explicit_recovery.rs: PyExplicitRecoveryVM. Commands return handles, results come back as notifications; those of the database's own handles go straight to the Rust store. - sessions/_driver.py: one attempt. One input pump, the only reader of the body; a tick after every call into the VM writes the output, settles the futures, and notices the end of the attempt (a shutdown when Restate closes the input, a failure, or the end). Cancellation: the VM's is_cancelled(), checked at every tick. An open annotation sends heartbeats, so a long model request is not shut down for inactivity. - The store over the VM syncs a commit with one acked write of the database's head (KvStore::put_and_sync), instead of an empty run. - Handler.attempt_runner: the server hands a session object's request to it. - The selector and its working run (#312) are gone: nothing suspends on the cancel signal. - shared-core is patched to the PR's branch until it is released. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 +- Cargo.toml | 5 + python/restate/_internal.pyi | 67 ++- python/restate/handler.py | 2 + python/restate/server.py | 12 + python/restate/sessions/_database.py | 25 +- python/restate/sessions/_driver.py | 602 +++++++++++++++++++++++++++ python/restate/sessions/_object.py | 280 +++++-------- python/restate/sessions/_scope.py | 8 +- python/restate/sessions/_selector.py | 412 ------------------ python/restate/sessions/_session.py | 39 +- src/explicit_recovery.rs | 389 +++++++++++++++++ src/lib.rs | 7 + src/sessions.rs | 250 +++++++---- tests/sessions_harness.py | 148 ++++++- tests/sessions_object.py | 70 +++- tests/sessions_selector.py | 492 ---------------------- 17 files changed, 1592 insertions(+), 1219 deletions(-) create mode 100644 python/restate/sessions/_driver.py delete mode 100644 python/restate/sessions/_selector.py create mode 100644 src/explicit_recovery.rs delete mode 100644 tests/sessions_selector.py diff --git a/Cargo.lock b/Cargo.lock index 5b5b59e8..5d7fd38a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2491,8 +2491,7 @@ dependencies = [ [[package]] name = "restate-sdk-shared-core" version = "8.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acfd8eb5d8145db1a2e5480f49a47c0582a34115bdd1e47fcb3af468f5f2654" +source = "git+https://github.com/restatedev/sdk-shared-core?branch=explicit-recovery-vm#3bc25595538fc0a73a57f674408dd25283794c46" dependencies = [ "base64 0.22.1", "bs58", diff --git a/Cargo.toml b/Cargo.toml index ce25a6b3..377cd102 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -45,3 +45,8 @@ tokio-util = { version = "0.7", default-features = false } # Sessions (`src/sessions.rs`): the database's futures, polled on Python's event loop. futures = "0.3" + +# The explicit recovery VM of session objects, until shared-core releases it +# (restatedev/sdk-shared-core#118). +[patch.crates-io] +restate-sdk-shared-core = { git = "https://github.com/restatedev/sdk-shared-core", branch = "explicit-recovery-vm" } diff --git a/python/restate/_internal.pyi b/python/restate/_internal.pyi index 45cfae3f..7c11d65f 100644 --- a/python/restate/_internal.pyi +++ b/python/restate/_internal.pyi @@ -27,6 +27,69 @@ _SqlValue = Union[None, int, float, str, bytes] def __getattr__(name: str) -> Any: ... +class AttemptShutDownException(Exception): + """Restate shut the attempt down: a new attempt will run the handler from the start.""" + +class PyInput: + invocation_id: str + random_seed: int + key: str + headers: list[Any] + input: bytes + scope: str | None + limit_key: str | None + idempotency_key: str | None + +class PyExplicitRecoveryVM: + """The VM of a session object's attempt (``src/explicit_recovery.rs``).""" + + def __init__(self, headers: Sequence[tuple[str, str]], bidirectional: bool) -> None: ... + def set_scheduler(self, scheduler: Callable[[], None]) -> None: ... + def get_response_head(self) -> Any: ... + def notify_input(self, buffer: bytes) -> None: ... + def notify_input_closed(self) -> None: ... + def take_output(self) -> bytes: ... + def is_ready_to_execute(self) -> bool: ... + def input(self) -> PyInput: ... + def take_notification(self) -> tuple[int, Any] | None: ... + def get_state(self, key: str, name: str | None = None) -> int: ... + def get_state_keys(self, name: str | None = None) -> int: ... + def call( + self, + service: str, + handler: str, + buffer: bytes, + key: str | None = None, + idempotency_key: str | None = None, + headers: Sequence[Any] | None = None, + name: str | None = None, + ) -> Any: ... + def attach_invocation(self, invocation_id: str, name: str | None = None) -> int: ... + def set_state(self, key: str, buffer: bytes, name: str | None = None, ack: bool = False) -> int: ... + def clear_state(self, key: str, name: str | None = None, ack: bool = False) -> int: ... + def clear_all_state(self, name: str | None = None, ack: bool = False) -> int: ... + def cancel_invocation(self, invocation_id: str, name: str | None = None, ack: bool = False) -> int: ... + def send( + self, + service: str, + handler: str, + buffer: bytes, + key: str | None = None, + delay: int | None = None, + idempotency_key: str | None = None, + headers: Sequence[Any] | None = None, + name: str | None = None, + ) -> int: ... + def start_trace(self, name: str, parent: int | None = None) -> int: ... + def end_trace_success(self, trace: int, buffer: bytes) -> None: ... + def end_trace_failure(self, trace: int, failure: Any) -> None: ... + def heartbeat(self) -> None: ... + def end_success(self, buffer: bytes) -> None: ... + def end_failure(self, failure: Any) -> None: ... + def notify_error(self, error: str, stacktrace: str | None = None, delay_override_ms: int | None = None) -> None: ... + def is_cancelled(self) -> bool: ... + def state(self) -> str: ... + class PyVM: """The invocation's VM (``restate.vm.VMWrapper`` wraps it).""" @@ -50,7 +113,7 @@ SQL_SET: int SQL_CLEAR: int SQL_SYNC: int SQL_KEYS: int -SQL_WAIT: int +SQL_COMMIT: int class SqlRefusedException(Exception): """A failure of the database that a retry would repeat (shared-core's ``sql::Refused``).""" @@ -79,6 +142,6 @@ def sql_open( dispatch: Callable[[int, Any, bytes | None, SqlReply | None], None], lists_keys: bool = False, reader: bool = False, - vm: PyVM | None = None, + vm: PyExplicitRecoveryVM | None = None, name: str | None = None, ) -> _Answer[PySqlDatabase]: ... diff --git a/python/restate/handler.py b/python/restate/handler.py index a2fe6772..c4d69c7a 100644 --- a/python/restate/handler.py +++ b/python/restate/handler.py @@ -283,6 +283,8 @@ class Handler(Generic[I, O]): context_managers: Optional[List[Callable[[], AsyncContextManager[None]]]] = None explicit_recovery: bool = False explicit_cancellation: bool = False + attempt_runner: Optional[Callable[..., Awaitable[None]]] = None + """What runs an attempt instead of the SDK's context, on a VM of its own (a session object's).""" # disable too many arguments warning diff --git a/python/restate/server.py b/python/restate/server.py index a1fabb79..ebd39272 100644 --- a/python/restate/server.py +++ b/python/restate/server.py @@ -410,6 +410,18 @@ async def app(scope: Scope, receive: Receive, send: Send): active_channels.add(receive_channel) try: journal_codec = await get_codec() + if handler.attempt_runner is not None: + await handler.attempt_runner( + handler, + request_headers=request_headers, + attempt_headers=dict(request_headers), + receive=receive_channel, + send=send, + bidirectional=scope["http_version"] != "1.1" and endpoint.protocol != "request_response", + server_headers=X_RESTATE_SERVER, + journal_codec=journal_codec, + ) + return await process_invocation_to_completion( VMWrapper( request_headers, diff --git a/python/restate/sessions/_database.py b/python/restate/sessions/_database.py index a1240251..33f16d1b 100644 --- a/python/restate/sessions/_database.py +++ b/python/restate/sessions/_database.py @@ -35,11 +35,11 @@ from restate._internal import ( # pylint: disable=import-error,no-name-in-module SQL_CLEAR, + SQL_COMMIT, SQL_GET, SQL_KEYS, SQL_SET, SQL_SYNC, - SQL_WAIT, PySqlDatabase, SqlRefusedException, SqlReply, @@ -96,11 +96,9 @@ class Store(Protocol): - ``keys()`` returns every key, as ``ctx.state_keys()`` does, or an awaitable of them. With it, a commit that writes a checkpoint deletes the packs no checkpoint needs any more; without it, they are kept. - - ``vm`` is the invocation's VM (``restate._internal.PyVM``), for a store - over a Restate context. The extension then reads and writes the VM - directly instead of calling ``get``, ``set`` and ``clear``, and calls - ``wait(handle)`` (an awaitable that completes once the VM has the read - for ``handle``) only when it must wait for a read. + - ``vm`` is the attempt's VM (``restate._internal.PyExplicitRecoveryVM``), + for a store over Restate. The extension then reads, writes, lists and + syncs with the VM directly, instead of calling the store's methods. - ``database_name`` names a database of the key other than the object's own (see ``_session.database``). """ @@ -159,7 +157,6 @@ def __init__(self, store: Store, loop: asyncio.AbstractEventLoop) -> None: self.loop: asyncio.AbstractEventLoop = loop # The store's optional methods (see `Store`). self._keys: Callable[[], Sequence[str] | Awaitable[Sequence[str]]] | None = getattr(store, "keys", None) - self._wait: Callable[[int], Awaitable[None]] | None = getattr(store, "wait", None) self.lists_keys: bool = callable(self._keys) # The store's first error. self.failed: BaseException | None = None @@ -173,7 +170,7 @@ def _keep(self, error: BaseException) -> None: self.failed = error def dispatch(self, op: int, key: Any, value: bytes | None, reply: SqlReply | None) -> None: - """Handle one request of the extension; ``key`` is a store key, or a VM handle for ``SQL_WAIT``.""" + """Handle one request of the extension; ``key`` is a store key, or empty for a sync or a commit.""" if op in (SQL_SET, SQL_CLEAR): try: if op == SQL_SET: @@ -193,9 +190,13 @@ def dispatch(self, op: int, key: Any, value: bytes | None, reply: SqlReply | Non elif op == SQL_KEYS: assert self._keys is not None result = self._keys() - elif op == SQL_WAIT: - assert self._wait is not None - result = self._wait(key) + elif op == SQL_COMMIT: + # A store over the VM syncs with an acked write of the head: what the transaction + # makes at its commit runs between that write and the wait for its ack. + run, self.with_sync = self.with_sync, None + if run is not None: + run() + result = None elif self._write_failed is not None: reply(None, str(self._write_failed)) return @@ -230,7 +231,7 @@ def done(future: asyncio.Future[object]) -> None: def _reply_value(op: int, result: object) -> object: """Convert a request's result to what the extension expects: a value, a list of keys, or ``None``.""" - if op in (SQL_SYNC, SQL_WAIT): + if op in (SQL_SYNC, SQL_COMMIT): return None if op == SQL_KEYS: return list(typing.cast("Sequence[str]", result)) diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py new file mode 100644 index 00000000..64cbb0e8 --- /dev/null +++ b/python/restate/sessions/_driver.py @@ -0,0 +1,602 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""One attempt of a session object's handler, on the explicit recovery VM (``PyExplicitRecoveryVM``). + +The VM never replays a journal: every attempt runs the handler from the start. +An action returns a handle, and its result comes back as a notification of that +handle, which settles the action's future here. Two things move the attempt +along: + +- **The input pump**, the only reader of the request body: it hands the VM + each chunk, and the end of the body. +- **The tick**, scheduled after every call to the VM (once per turn of the + event loop): it writes the VM's output, settles the futures, and notices the + end of the attempt. + +Restate shuts an attempt down by closing the request body: from then on every +action raises ``SuspendedException``, and the futures still pending fail with +it. A new attempt runs the handler from the start. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +import operator +import traceback +import typing +from collections.abc import Awaitable, Callable, Generator +from datetime import timedelta +from typing import Any + +from restate._internal import ( # pylint: disable=no-name-in-module + AttemptShutDownException, + PyExplicitRecoveryVM, + PyFailure, + PyHeader, + PyInput, + PyStateKeys, + PyVoid, + VMException, +) +from restate.context import AttemptFinishedEvent, RestateDurableCallFuture +from restate.exceptions import ( + RetryableError, + SdkInternalBaseException, + SdkInternalException, + SuspendedException, + TerminalError, +) +from restate.server_types import ReceiveChannel, Send + +logger = logging.getLogger(__name__) + +T = typing.TypeVar("T") + +HEARTBEAT_INTERVAL = timedelta(seconds=20) +"""How often an attempt with an annotation open tells Restate it makes progress. + +Restate shuts down an attempt it heard nothing from for its inactivity timeout +(a minute, by default): an open annotation (a model request, a tool call) +keeps it alive. +""" + +SYNC_KEY = "v22/sync" +"""The state key a sync clears with an ack, under the state format's prefix, which tooling hides.""" + + +def _quiet(future: asyncio.Future[Any]) -> asyncio.Future[Any]: + """Keep asyncio from logging the exception of ``future`` if nothing awaits it.""" + future.add_done_callback(lambda f: f.cancelled() or f.exception()) + return future + + +def _settle(future: asyncio.Future[Any], value: Any) -> None: + """Settle ``future`` with a notification's value.""" + if future.done(): + return + if isinstance(value, PyVoid): + future.set_result(None) + elif isinstance(value, PyFailure): + future.set_exception(TerminalError(value.message, value.code, metadata=dict(value.metadata or []))) + elif isinstance(value, PyStateKeys): + future.set_result(list(value.keys)) + else: + future.set_result(value) + + +class AttemptFinished(AttemptFinishedEvent): + """The attempt's ``Request.attempt_finished_event``: set when the attempt ends.""" + + def __init__(self, event: asyncio.Event) -> None: + super().__init__() + self._event: asyncio.Event = event + + def is_set(self) -> bool: + return self._event.is_set() + + async def wait(self) -> None: + await self._event.wait() + + +class AttemptDriver: + """Drives one attempt over its VM: the input pump, the tick, and the futures of the actions.""" + + def __init__( + self, vm: PyExplicitRecoveryVM, send: Send, receive: ReceiveChannel, explicit_cancellation: bool + ) -> None: + self.vm: PyExplicitRecoveryVM = vm + self._send: Send = send + self._receive: ReceiveChannel = receive + self._explicit_cancellation: bool = explicit_cancellation + self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() + self._futures: dict[int, asyncio.Future[Any]] = {} + # The invocation ids of the calls and sends, which a cancellation leaves to settle. + self._invocation_ids: set[int] = set() + self.calls: list[_CallFuture] = [] + # The cancellation of the calls whose invocation id a cancellation waits for. + self._cancelling: asyncio.Future[Any] | None = None + """The attempt's calls, for ``cancel_calls``.""" + self._queued: bool = False + self._output: asyncio.Queue[bytes | None] = asyncio.Queue() + self._writer: asyncio.Task[None] = asyncio.ensure_future(self._write_output()) + self._pump: asyncio.Task[None] | None = None + self._handler: asyncio.Future[bytes] | None = None + self._open_traces: int = 0 + self._heartbeats: asyncio.Task[None] | None = None + self._end_listeners: list[Callable[[], None]] = [] + self.finished: asyncio.Event = asyncio.Event() + self.ended: BaseException | None = None + """Why the attempt ended, once it did: ``SuspendedException`` for a shutdown or the end of the handler.""" + self.cancellation: asyncio.Future[None] = _quiet(self._loop.create_future()) + """Resolved once Restate cancels the invocation; cancelled if the attempt ends first.""" + vm.set_scheduler(self.schedule) + + # --- Start and end + + async def start(self) -> PyInput | None: + """Read the start of the invocation and start the handler: its request, or ``None`` if it can't start.""" + try: + while not self.vm.is_ready_to_execute(): + message = await self._receive() + if message.get("type") == "http.disconnect": + return None + if message.get("type") == "http.request": + body = message.get("body", b"") + if body: + self.vm.notify_input(typing.cast(bytes, body)) + if not message.get("more_body", False): + self.vm.notify_input_closed() + request = self.vm.input() + except (VMException, AttemptShutDownException): + # The VM wrote why. + self.schedule() + return None + self._pump = asyncio.ensure_future(self._read_input()) + # The failures of the traces earlier attempts left open, and an earlier cancellation. + self.schedule() + return request + + async def run(self, handler: Callable[[], Awaitable[bytes]]) -> None: + """Run the handler, and end the attempt with its output or error. + + If the attempt is shut down or fails first, the handler's task is cancelled: its local work + (a model request, say) stops, since nothing it does would count any more. + """ + self._handler = asyncio.ensure_future(self._cancelled_calls_first(handler)) + try: + output = await self._handler + self._last(lambda vm: vm.end_success(output)) + except TerminalError as t: + failure = _failure_of(t) + self._last(lambda vm: vm.end_failure(failure)) + except RetryableError as r: + self._fail(r.message, r, r.retry_after) + except SdkInternalBaseException: + # The attempt ended: the VM wrote why. + pass + except asyncio.CancelledError: + if self.ended is None or asyncio.current_task().cancelling(): # type: ignore[union-attr] + raise + # The attempt ended, and stopped the handler. + except Exception as e: # pylint: disable=broad-exception-caught + cause: BaseException | None = e + while cause is not None: + if isinstance(cause, TerminalError): + self._last(operator.methodcaller("end_failure", _failure_of(cause))) + return + if isinstance(cause, RetryableError): + self._fail(cause.message, cause, cause.retry_after) + return + if isinstance(cause, SdkInternalBaseException): + return + cause = cause.__cause__ + logger.exception("Exception in Restate handler") + self._fail(repr(e), e, None) + + async def _cancelled_calls_first(self, handler: Callable[[], Awaitable[bytes]]) -> bytes: + """Run the handler; before it ends, the calls a cancellation cancels are.""" + try: + return await handler() + finally: + if self._cancelling is not None: + with contextlib.suppress(BaseException): + await asyncio.shield(self._cancelling) + + def _last(self, f: Callable[[PyExplicitRecoveryVM], None]) -> None: + """End the attempt with ``f``, unless it ended already.""" + with contextlib.suppress(VMException, AttemptShutDownException): + f(self.vm) + self.schedule() + + def _fail(self, message: str, error: BaseException, retry_after: timedelta | None) -> None: + stacktrace = "".join(traceback.format_exception(error)) + delay = int(retry_after.total_seconds() * 1000) if retry_after is not None else None + self._last(lambda vm: vm.notify_error(message, stacktrace, delay)) + + def abandon(self) -> None: + """Stop the attempt's tasks without writing anything more: the server is going away.""" + self._end(SuspendedException()) + self._writer.cancel() + if self._pump is not None: + self._pump.cancel() + + async def leave(self) -> None: + """Write the rest of the output, wait for Restate to close the request, then close the response.""" + self._tick() + self._end(SuspendedException()) + self._output.put_nowait(None) + await self._writer + await self._receive.block_until_http_input_closed() + if self._pump is not None: + self._pump.cancel() + await self._send({"type": "http.response.body", "body": b"", "more_body": False}) + + # --- Input and output + + async def _read_input(self) -> None: + """The input pump: hand the VM the request body, until it ends.""" + while True: + message = await self._receive() + kind = message.get("type") + if kind == "http.disconnect": + self.vm.notify_input_closed() + self.schedule() + return + if kind != "http.request": + continue + body = message.get("body", b"") + if body: + self.vm.notify_input(typing.cast(bytes, body)) + if not message.get("more_body", False): + self.vm.notify_input_closed() + self.schedule() + return + self.schedule() + + async def _write_output(self) -> None: + """Write the output, in order, until ``leave``.""" + while (chunk := await self._output.get()) is not None: + try: + await self._send({"type": "http.response.body", "body": chunk, "more_body": True}) + except Exception: # pylint: disable=broad-exception-caught + logger.debug("Could not write the output: the connection is gone", exc_info=True) + + def schedule(self) -> None: + """Schedule a tick, once per turn of the event loop.""" + if not self._queued: + self._queued = True + self._loop.call_soon(self._tick) + + def _tick(self) -> None: + """Write the VM's output, settle the futures of the completed actions, and notice the end of the attempt.""" + self._queued = False + output = self.vm.take_output() + if output: + self._output.put_nowait(output) + if self.ended is not None: + return + try: + while (notification := self.vm.take_notification()) is not None: + handle, value = notification + self._invocation_ids.discard(handle) + future = self._futures.pop(handle, None) + if future is not None: + _settle(future, value) + except AttemptShutDownException: + self._end(SuspendedException()) + except VMException as error: + logger.debug("The attempt failed: %s", error) + self._end(SdkInternalException()) + else: + # The VM tells whether a cancellation arrived, in this attempt or an earlier one: acted + # on once. + if not self.cancellation.done() and self.vm.is_cancelled(): + self._cancelled() + if self.vm.state() == "closed": + self._end(SuspendedException()) + + def _end(self, reason: BaseException) -> None: + """The attempt ended: fail what still waits, and tell the listeners.""" + if self.ended is not None: + return + self.ended = reason + futures, self._futures = self._futures, {} + for future in futures.values(): + if not future.done(): + future.set_exception(reason) + self.cancellation.cancel() + if self._handler is not None: + self._handler.cancel() + if self._heartbeats is not None: + self._heartbeats.cancel() + self.finished.set() + listeners, self._end_listeners = self._end_listeners, [] + for listener in listeners: + listener() + + def on_end(self, listener: Callable[[], None]) -> Callable[[], None]: + """Call ``listener`` when the attempt ends; return a function that unregisters it.""" + if self.ended is not None: + listener() + return lambda: None + self._end_listeners.append(listener) + + def cancel() -> None: + if listener in self._end_listeners: + self._end_listeners.remove(listener) + + return cancel + + # --- Actions + + def act(self, f: Callable[[PyExplicitRecoveryVM], T]) -> T: + """Call the VM with ``f``, then schedule a tick; the attempt's end raises ``SuspendedException``.""" + if self.ended is not None: + raise self.ended + try: + return f(self.vm) + except AttemptShutDownException: + raise SuspendedException() from None + except VMException as error: + raise SdkInternalException() from error + finally: + self.schedule() + + def future(self, handle: int) -> asyncio.Future[Any]: + """The future the notification of ``handle`` settles.""" + future = _quiet(self._loop.create_future()) + if self.ended is not None: + future.set_exception(self.ended) + else: + self._futures[handle] = future + return future + + def invocation_id_future(self, handle: int) -> asyncio.Future[Any]: + """The future of a call's or send's invocation id, which a cancellation leaves to settle.""" + self._invocation_ids.add(handle) + return self.future(handle) + + def _cancelled(self) -> None: + """Restate cancelled the invocation.""" + if not self.cancellation.done(): + self.cancellation.set_result(None) + if self._explicit_cancellation: + return + # The calls in flight are cancelled (right away those whose invocation id is known, so + # that it happens before the handler ends), and the awaits fail. + for call in list(self.calls): + if not call.done() and call.knows_invocation_id(): + with contextlib.suppress(SdkInternalBaseException): + self.act(operator.methodcaller("cancel_invocation", call.known_invocation_id())) + self._cancelling = _quiet(asyncio.ensure_future(self.cancel_calls())) + cancelled = TerminalError("cancelled", 409) + for handle, future in list(self._futures.items()): + if handle not in self._invocation_ids: + del self._futures[handle] + if not future.done(): + future.set_exception(cancelled) + + async def cancel_calls(self) -> list[str]: + """Cancel the calls of the attempt that have not completed; return their invocation ids.""" + cancelled: list[str] = [] + for call in list(self.calls): + if call.done() or call.cancelled: + continue + try: + invocation_id = await call.invocation_id() + except BaseException: # pylint: disable=broad-exception-caught + continue + if not call.done() and not call.cancelled: + call.cancelled = True + self.act(operator.methodcaller("cancel_invocation", invocation_id)) + cancelled.append(invocation_id) + return cancelled + + def trace_opened(self) -> None: + """An annotation opened: heartbeat while any is.""" + self._open_traces += 1 + if self._heartbeats is None and self.ended is None: + self._heartbeats = asyncio.ensure_future(self._heartbeat()) + + def trace_closed(self) -> None: + self._open_traces -= 1 + if self._open_traces == 0 and self._heartbeats is not None: + self._heartbeats.cancel() + self._heartbeats = None + + async def _heartbeat(self) -> None: + while True: + await asyncio.sleep(HEARTBEAT_INTERVAL.total_seconds()) + try: + self.act(lambda vm: vm.heartbeat()) + except SdkInternalBaseException: + return + + +def _failure_of(error: TerminalError) -> Any: + return PyFailure(error.status_code, error.message, None, list((error.metadata or {}).items()) or None) + + +def _headers_of(headers: dict[str, str] | None) -> list[Any] | None: + return [PyHeader(key, value) for key, value in headers.items()] if headers else None + + +class _CallFuture(RestateDurableCallFuture[bytes]): + """The result of a call, its invocation id, and its cancellation.""" + + def __init__( + self, driver: AttemptDriver, invocation_id: asyncio.Future[str], result: asyncio.Future[bytes] + ) -> None: + super().__init__() + self._driver: AttemptDriver = driver + self._invocation_id: asyncio.Future[str] = invocation_id + self._result: asyncio.Future[bytes] = result + + self.cancelled: bool = False + """Whether the attempt cancelled the call's invocation.""" + + def done(self) -> bool: + return self._result.done() + + def knows_invocation_id(self) -> bool: + return ( + self._invocation_id.done() + and not self._invocation_id.cancelled() + and self._invocation_id.exception() is None + ) + + def known_invocation_id(self) -> str: + self.cancelled = True + return self._invocation_id.result() + + def __await__(self) -> Generator[Any, Any, bytes]: + return self._result.__await__() + + async def invocation_id(self) -> str: + return await asyncio.shield(self._invocation_id) + + async def cancel_invocation(self) -> None: + invocation_id = await self.invocation_id() + self._driver.act(lambda vm: vm.cancel_invocation(invocation_id)) + + +class _SendHandle: + """A send: its invocation id, once Restate stored it, and its cancellation.""" + + def __init__(self, driver: AttemptDriver, invocation_id: asyncio.Future[str]) -> None: + self._driver: AttemptDriver = driver + self._invocation_id: asyncio.Future[str] = invocation_id + + async def invocation_id(self) -> str: + return await asyncio.shield(self._invocation_id) + + async def cancel_invocation(self) -> None: + invocation_id = await self.invocation_id() + self._driver.act(lambda vm: vm.cancel_invocation(invocation_id)) + + +class VmHost: + """The ``SqlHost`` of an attempt on Restate: its actions are the VM's. + + The database reads and writes the VM directly (``vm``), and waits for it in + Rust. With a journal codec, which only Python applies, ``vm`` is ``None`` + and the database goes through ``get``, ``set`` and ``clear``. + """ + + def __init__(self, driver: AttemptDriver, *, service: str, key: str, shared: bool, codec: Any = None) -> None: + self.driver: AttemptDriver = driver + self.service: str = service + self.key: str = key + self.shared: bool = shared + self._codec: Any = codec + + @property + def vm(self) -> PyExplicitRecoveryVM | None: + return self.driver.vm if self._codec is None else None + + def get(self, key: str) -> Awaitable[bytes | None]: + handle = self.driver.act(lambda vm: vm.get_state(key, key)) + read = self.driver.future(handle) + codec = self._codec + if codec is None: + return read + + async def decoded() -> bytes | None: + value = await read + return None if value is None else typing.cast(bytes, await codec.decode(value)) + + return decoded() + + def set(self, key: str, value: bytes) -> None: + if self._codec is not None: + value = self._codec.encode(value) + self.driver.act(lambda vm: vm.set_state(key, value, key)) + + def clear(self, key: str) -> None: + self.driver.act(lambda vm: vm.clear_state(key, key)) + + def state_keys(self) -> Awaitable[list[str]]: + # Named under the state format's prefix, which tooling hides. + handle = self.driver.act(lambda vm: vm.get_state_keys("v22/keys")) + return self.driver.future(handle) + + def sync(self) -> Awaitable[Any]: + """Clear ``SYNC_KEY`` with an ack: once acked, every earlier write is stored too.""" + handle = self.driver.act(lambda vm: vm.clear_state(SYNC_KEY, SYNC_KEY, True)) + return self.driver.future(handle) + + def attempt_end(self) -> BaseException | None: + return self.driver.ended + + def on_attempt_end(self, listener: Callable[[], None]) -> Callable[[], None]: + return self.driver.on_end(listener) + + def cancel_invocation(self, invocation_id: str) -> None: + self.driver.act(lambda vm: vm.cancel_invocation(invocation_id)) + + def generic_call( + self, + service: str, + handler: str, + arg: bytes, + key: str | None = None, + idempotency_key: str | None = None, + headers: dict[str, str] | None = None, + name: str | None = None, + ) -> RestateDurableCallFuture[bytes]: + handle = self.driver.act( + lambda vm: vm.call(service, handler, arg, key, idempotency_key, _headers_of(headers), name) + ) + call = _CallFuture( + self.driver, + self.driver.invocation_id_future(handle.invocation_id_handle), + self.driver.future(handle.result_handle), + ) + self.driver.calls.append(call) + return call + + def generic_send( + self, + service: str, + handler: str, + arg: bytes, + key: str | None = None, + send_delay: timedelta | None = None, + idempotency_key: str | None = None, + headers: dict[str, str] | None = None, + name: str | None = None, + ) -> _SendHandle: + delay = int(send_delay.total_seconds() * 1000) if send_delay is not None else None + handle = self.driver.act( + lambda vm: vm.send(service, handler, arg, key, delay, idempotency_key, _headers_of(headers), name) + ) + return _SendHandle(self.driver, self.driver.invocation_id_future(handle)) + + def attach_invocation(self, invocation_id: str) -> Awaitable[bytes]: + return self.driver.future(self.driver.act(lambda vm: vm.attach_invocation(invocation_id))) + + def open_annotation(self, name: str, parent: int | None = None) -> int | None: + trace = self.driver.act(lambda vm: vm.start_trace(name, parent)) + self.driver.trace_opened() + return trace + + def close_annotation(self, handle: int, value: bytes, failure: str | None) -> None: + self.driver.trace_closed() + try: + if failure is None: + self.driver.act(lambda vm: vm.end_trace_success(handle, value)) + else: + self.driver.act(lambda vm: vm.end_trace_failure(handle, PyFailure(500, failure))) + except SdkInternalBaseException: + # The attempt ended: the next one fails the trace. + pass diff --git a/python/restate/sessions/_object.py b/python/restate/sessions/_object.py index dfa284f0..ea687b13 100644 --- a/python/restate/sessions/_object.py +++ b/python/restate/sessions/_object.py @@ -40,22 +40,21 @@ async def list_notes(ctx: sessions.ViewContext) -> list[str]: from datetime import timedelta from typing import Any -from restate import _preview +from restate._internal import PyExplicitRecoveryVM, PyInput # pylint: disable=no-name-in-module from restate.context import Request -from restate.exceptions import SdkInternalBaseException, SuspendedException, TerminalError +from restate.exceptions import TerminalError from restate.handler import RESTATE_UNIQUE_HANDLER_SYMBOL, Handler, handler_from_callable from restate.object import VirtualObject from restate.retry_policy import InvocationRetryPolicy -from restate.serde import BytesSerde, DefaultSerde, Serde -from restate.server_context import DisconnectedException, ServerInvocationContext +from restate.serde import DefaultSerde, Serde +from restate.server_types import ReceiveChannel, Send, header_to_binary from restate.sessions._api import Database, DatabaseReader, SessionContext, ViewContext from restate.sessions._calls import CallHost, Calls, GenericSend, Sends, send_now, send_to +from restate.sessions._driver import AttemptDriver, AttemptFinished, VmHost from restate.sessions._link import Link from restate.sessions._schema import Migration, Schema, steps_of from restate.sessions._scope import SCOPE, Scope -from restate.sessions._selector import FutureSelector, hook from restate.sessions._session import Attempt, ObjectConfig, SqlHost, reader_of, with_attempt -from restate.vm import SingleUnresolvedFuture F = typing.TypeVar("F", bound=Callable[..., Awaitable[Any]]) @@ -72,8 +71,8 @@ async def list_notes(ctx: sessions.ViewContext) -> list[str]: """Metadata added to every session object. It tells Restate's UI to hide the database from the journal view: its head, -tail, manifests and packs (state keys under ``v22/``), and the ``sync`` run -after its writes. +tail, manifests and packs, and the writes that only ask for an ack (state keys +under ``v22/``), and the ``sync`` runs of earlier versions. """ @@ -115,126 +114,6 @@ def cancel(self, invocation_id: str) -> None: self._cancel(invocation_id) -class _ContextHost: - """A ``SqlHost`` over the SDK's context, for one attempt. - - Its waits go through the selector, and its state commands are named after - their keys, so that tooling can hide the database by name. - """ - - def __init__(self, context: ServerInvocationContext, shared: bool) -> None: - self.context: ServerInvocationContext = context - self.shared: bool = shared - self.service: str = context.handler.service_tag.name - self.key: str = context.key() - self._listeners: list[Callable[[], None]] = [] - self.selector: FutureSelector = hook(context, self._notify_attempt_end) - attempt_finished = context.on_attempt_finished - - def on_attempt_finished() -> None: - self._notify_attempt_end() - attempt_finished() - - context.on_attempt_finished = on_attempt_finished # type: ignore[method-assign] - - @property - def vm(self) -> Any: - """The invocation's VM, which the database reads and writes directly (see ``_database.Store``). - - It is ``None`` when a journal codec is configured, since only the - context's state commands apply the codec. - """ - return None if self.context.journal_codec is not None else self.context.vm.vm - - def wait(self, handle: int) -> Awaitable[None]: - """Wait, through the selector, until the VM has the result of the read ``handle``.""" - return self.selector.wait(SingleUnresolvedFuture(handle)) - - def cancel_invocation(self, invocation_id: str) -> None: - self.context.cancel_invocation(invocation_id) - - def get(self, key: str) -> Awaitable[bytes | None]: - return self.context.get(key, serde=BytesSerde(), entry_name=key) - - def set(self, key: str, value: bytes) -> None: - self.context.set(key, value, serde=BytesSerde(), entry_name=key) - - def clear(self, key: str) -> None: - self.context.clear(key, entry_name=key) - - def state_keys(self) -> Awaitable[list[str]]: - # Named under the state format's prefix, which tooling hides. - return self.context.state_keys(entry_name="v22/keys") - - def sync(self) -> Awaitable[Any]: - return self.context.run_typed("sync", _nothing) - - def open_annotation(self, name: str) -> int | None: - return self.context.open_annotation(name) - - def close_annotation(self, handle: int, value: bytes, failure: str | None) -> None: - self.context.close_annotation(handle, value, failure) - - def generic_call( - self, - service: str, - handler: str, - arg: bytes, - key: str | None = None, - idempotency_key: str | None = None, - headers: dict[str, str] | None = None, - name: str | None = None, - ) -> Any: - return self.context.generic_call(service, handler, arg, key, idempotency_key, headers, entry_name=name) - - def attach_invocation(self, invocation_id: str) -> Awaitable[bytes]: - return self.context.attach_invocation(invocation_id, serde=BytesSerde()) - - def generic_send( - self, - service: str, - handler: str, - arg: bytes, - key: str | None = None, - send_delay: timedelta | None = None, - idempotency_key: str | None = None, - headers: dict[str, str] | None = None, - name: str | None = None, - ) -> Any: - return self.context.generic_send( - service, handler, arg, key, send_delay, idempotency_key, headers, entry_name=name - ) - - def attempt_end(self) -> BaseException | None: - ended = self.selector.ended - if ended is not None: - return ended - if self.context.request_finished_event.is_set(): - return SuspendedException() - return None - - def on_attempt_end(self, listener: Callable[[], None]) -> Callable[[], None]: - if self.attempt_end() is not None: - listener() - return lambda: None - self._listeners.append(listener) - - def cancel() -> None: - if listener in self._listeners: - self._listeners.remove(listener) - - return cancel - - def _notify_attempt_end(self) -> None: - listeners, self._listeners = self._listeners, [] - for listener in listeners: - listener() - - -async def _nothing() -> None: - """Do nothing; the action of an empty run.""" - - def _cancel_of(host: SqlHost) -> Callable[[str], None]: """Return the context's ``cancel``, implemented on ``host``.""" @@ -266,8 +145,8 @@ class _Entry: def _context_of(entry: _Entry, host: SqlHost, request: Request, attempt: Attempt) -> SessionContext | ViewContext: """Create the context for an attempt of ``entry``.""" cancel = _cancel_of(host) - sdk = typing.cast("ServerInvocationContext | None", getattr(host, "context", None)) - scope = Scope(sdk=sdk, explicit_cancellation=entry.explicit_cancellation, definition=entry.definition()) + driver = host.driver if isinstance(host, VmHost) else None + scope = Scope(driver=driver, explicit_cancellation=entry.explicit_cancellation, definition=entry.definition()) if entry.view: view = AttemptViewContext( key=host.key, request=request, db=reader_of(attempt.db), _call_host=host, _cancel=cancel @@ -293,28 +172,99 @@ async def _attempt(entry: _Entry, host: SqlHost, request: Request, args: Sequenc def _sdk_handler(entry: _Entry) -> Callable[..., Awaitable[Any]]: - """Wrap ``entry`` as an SDK handler whose attempts drive their awaits through a selector.""" + """The SDK's handler for ``entry``: it has ``entry``'s signature, for the SDK, but Restate's attempts run ``_runner``'s.""" @functools.wraps(entry.fn) - async def handler(ctx: ServerInvocationContext, *args: Any) -> Any: - host = _ContextHost(ctx, shared=entry.view) - try: - return await _attempt(entry, host, ctx.request(), args) - finally: - # Before the SDK writes the output: the working run ends first, in the journal. - host.selector.close() + async def handler(*_: Any) -> Any: + raise RuntimeError("a session object's attempts run on their own VM (see _runner)") return handler -def _explicit_of(ctx: SessionContext, operation: str) -> ServerInvocationContext: - """Return the SDK's context behind ``ctx``, which must be a handler's with ``explicit_cancellation=True``.""" +async def _invoke( + entry: _Entry, + handler: Handler[Any, Any], + driver: AttemptDriver, + request: PyInput, + attempt_headers: dict[str, str], + codec: Any, +) -> bytes: + """Run the attempt's handler on its input; its output, serialized.""" + body = bytes(request.input) + data = body + if codec is not None: + try: + data = await codec.decode(data) + except Exception as e: + raise TerminalError(message="Failed to decode input using journal value codec", status_code=400) from e + args: tuple[Any, ...] = () + if handler.arity == 2: + try: + args = (handler.handler_io.input_serde.deserialize(data),) + except Exception as e: + raise TerminalError(message=f"Unable to parse an input argument. {e}") from e + host = VmHost(driver, service=handler.service_tag.name, key=request.key, shared=entry.view, codec=codec) + context_request = Request( + id=request.invocation_id, + headers={header.key: header.value for header in request.headers}, + attempt_headers=attempt_headers, + body=body, + attempt_finished_event=AttemptFinished(driver.finished), + scope=request.scope, + limit_key=request.limit_key, + idempotency_key=request.idempotency_key, + ) + output = handler.handler_io.output_serde.serialize(await _attempt(entry, host, context_request, args)) + if codec is not None: + output = codec.encode(bytes(output)) + return bytes(output) + + +def _runner(entry: _Entry) -> Callable[..., Awaitable[None]]: + """Return what runs an attempt of ``entry`` on Restate, on its own VM (see ``_driver``).""" + + async def run( + handler: Handler[Any, Any], + *, + request_headers: list[tuple[str, str]], + attempt_headers: dict[str, str], + receive: ReceiveChannel, + send: Send, + bidirectional: bool, + server_headers: list[tuple[bytes, bytes]], + journal_codec: Any = None, + ) -> None: + vm = PyExplicitRecoveryVM(request_headers, bidirectional) + head = vm.get_response_head() + await send( + { + "type": "http.response.start", + "status": head.status_code, + "headers": [*header_to_binary(head.headers), *server_headers], + "trailers": False, + } + ) + driver = AttemptDriver(vm, send, receive, entry.explicit_cancellation) + try: + request = await driver.start() + if request is not None: + await driver.run(lambda: _invoke(entry, handler, driver, request, attempt_headers, journal_codec)) + except asyncio.CancelledError: + driver.abandon() + raise + await driver.leave() + + return run + + +def _explicit_of(ctx: SessionContext, operation: str) -> AttemptDriver: + """Return the attempt behind ``ctx``, which must be a handler's with ``explicit_cancellation=True``.""" scope = SCOPE.of(ctx) - if scope is None or scope.sdk is None: + if scope is None or scope.driver is None: raise TerminalError(f"{operation} takes a session object's ctx") if not scope.explicit_cancellation: raise TerminalError(f"{operation} takes the ctx of a handler with explicit_cancellation=True") - return scope.sdk + return scope.driver async def cancelled(ctx: SessionContext) -> None: @@ -331,15 +281,10 @@ async def stop_when_cancelled(): asyncio.ensure_future(stop_when_cancelled()) - It watches for the cancellation, and holds nothing: awaited alone, it - neither suspends the invocation nor tells Restate that the handler waits - (the attempt's journal has a run named ``work`` instead, for the - handler's own work; see ``_selector.py``). A cancellation reaches the - handler at once while Restate keeps the invocation's input open. Once - Restate closed it (the handler sent and received nothing for the - inactivity timeout), a cancellation reaches the handler at its next - await of Restate's, which suspends the invocation and resumes it at once - (in the next attempt), or not at all if it awaits nothing more. + It watches for the cancellation, and holds nothing: awaiting it neither + suspends the invocation nor tells Restate that the handler waits. A + cancellation reaches the handler as soon as Restate sends it, or at the + start of the next attempt if an earlier one received it. Args: ctx: The context of a handler with ``explicit_cancellation=True``. @@ -351,10 +296,8 @@ async def stop_when_cancelled(): TerminalError: If ``ctx`` is not the context of a handler with ``explicit_cancellation=True``. """ - try: - await _preview.cancellation(_explicit_of(ctx, "cancelled")) - except (SdkInternalBaseException, DisconnectedException) as ended: - raise asyncio.CancelledError() from ended + # The attempt's end cancels the cancellation's future. + await asyncio.shield(_explicit_of(ctx, "cancelled").cancellation) async def cancel_calls(ctx: SessionContext) -> list[str]: @@ -373,7 +316,7 @@ async def cancel_calls(ctx: SessionContext) -> list[str]: TerminalError: If ``ctx`` is not the context of a handler with ``explicit_cancellation=True``. """ - return await _preview.cancel_previous_calls(_explicit_of(ctx, "cancel_calls")) + return await _explicit_of(ctx, "cancel_calls").cancel_calls() def _host_of(ctx: SessionContext) -> CallHost: @@ -410,9 +353,11 @@ class Annotation: next attempt. """ - def __init__(self, host: _ContextHost | None = None, handle: int | None = None) -> None: - self._host: _ContextHost | None = host + def __init__(self, host: VmHost | None = None, handle: int | None = None) -> None: + self._host: VmHost | None = host self._handle: int | None = handle + # The trace, which stays a parent after it ends. + self._trace: int | None = handle def end(self, summary: Any = None) -> None: """End the work, with ``summary`` (as JSON) as the run's value. It does nothing if it has ended.""" @@ -428,16 +373,18 @@ def _close(self, value: bytes, failure: str | None) -> None: self._host.close_annotation(handle, value, failure) -def annotate(ctx: SessionContext, name: str) -> Annotation: +def annotate(ctx: SessionContext, name: str, *, parent: Annotation | None = None) -> Annotation: """Start timing some work of the handler of ``ctx`` (a model request, say), as a run named ``name``. - End it with ``end`` or ``fail``. Outside a session object's handler on - Restate (with a test's host, say), nothing is timed. + The work is part of ``parent``'s, if given, or else of the attempt's. End + it with ``end`` or ``fail``. Outside a session object's handler on Restate + (with a test's host, say), nothing is timed. """ host = ctx._call_host if isinstance(ctx, AttemptContext) else None # pyright: ignore[reportPrivateUsage] - if not isinstance(host, _ContextHost): + if not isinstance(host, VmHost): return Annotation() - return Annotation(host, host.open_annotation(name)) + parent_trace = parent._trace if parent is not None else None # pyright: ignore[reportPrivateUsage] + return Annotation(host, host.open_annotation(name, parent_trace)) def attach_invocation(ctx: SessionContext, invocation_id: str) -> Awaitable[bytes]: @@ -774,13 +721,14 @@ def register(fn: F) -> F: definition=weakref.ref(self), explicit_cancellation=bool(options.get("explicit_cancellation")), ) - # Attempts are not replayed (explicit_recovery): each runs from the - # start, against the current state, so it may read differently from - # earlier attempts. + # Attempts are not replayed: each runs from the start, on a VM of its + # own (see _driver), against the current state, so it may read + # differently from earlier attempts. registered = VirtualObject.handler( self, name, kind="shared" if view else "exclusive", explicit_recovery=True, **options )(_sdk_handler(entry)) sdk: Handler[Any, Any] = handler_from_callable(registered) + sdk.attempt_runner = _runner(entry) entries = ENTRIES.of(self) assert entries is not None entries[sdk.name] = entry diff --git a/python/restate/sessions/_scope.py b/python/restate/sessions/_scope.py index 58b1cb57..397ecf07 100644 --- a/python/restate/sessions/_scope.py +++ b/python/restate/sessions/_scope.py @@ -23,10 +23,12 @@ from dataclasses import dataclass, field from typing import Any -from restate.server_context import ServerInvocationContext from restate.sessions._api import SessionContext, ViewContext from restate.sessions._link import Link +if typing.TYPE_CHECKING: + from restate.sessions._driver import AttemptDriver + T = typing.TypeVar("T") @@ -34,8 +36,8 @@ class Scope: """The per-attempt data this package attaches to a context (see ``SCOPE``).""" - sdk: ServerInvocationContext | None - """The SDK's context of the attempt, or ``None`` when running on a test's host.""" + driver: AttemptDriver | None + """The attempt on Restate, or ``None`` when running on a test's host.""" explicit_cancellation: bool = False """Whether its handler has ``explicit_cancellation=True``.""" definition: object | None = None diff --git a/python/restate/sessions/_selector.py b/python/restate/sessions/_selector.py deleted file mode 100644 index c11371a6..00000000 --- a/python/restate/sessions/_selector.py +++ /dev/null @@ -1,412 +0,0 @@ -# -# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH -# -# This file is part of the Restate SDK for Python, -# which is released under the MIT license. -# -# You can find a copy of the license in file LICENSE in the root -# directory of this repository or package, or at -# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE -# -"""A single loop that drives every pending wait of an invocation without journal replay. - -Without journal replay, a handler's futures are plain awaitables that user -code awaits and combines however it likes: with ``asyncio.gather``, -``asyncio.wait``, its own tasks, or a library's. The protocol, however, has -one await point per invocation: a suspension, the awaiting-on hint and a -cancellation each take a single unresolved future. So every wait registers -with the selector, which asks the VM for progress on whichever of them -completes first, and which is the only reader of the invocation's input. - -To ask is to say that the handler waits, but a handler that watches for its -cancellation does not wait for it: see ``FutureSelector`` for the working -run that the selector asks for with it. -""" - -from __future__ import annotations - -import asyncio -import contextlib -import logging -from collections.abc import Callable, Mapping -from typing import Any, Protocol - -from restate.exceptions import SdkInternalException, SuspendedException, TerminalError -from restate.server_context import DisconnectedException, ServerInvocationContext -from restate.vm import ( - CANCEL_HANDLE, - DoProgressAnyCompleted, - DoProgressCancelSignalReceived, - DoProgressExecuteRun, - DoProgressWaitExternalProgress, - FirstCompletedUnresolvedFuture, - SingleUnresolvedFuture, - Suspended, - UnresolvedFuture, -) - -logger = logging.getLogger(__name__) - - -class SelectorDriver(Protocol): - """The operations of the invocation that the selector uses.""" - - def do_progress(self, future: UnresolvedFuture) -> Any: - """Return the VM's progress on ``future``: a DoProgress* response, ``Suspended``, or an exception.""" - ... - - def is_completed(self, handle: int) -> bool: - """Return whether the VM has the result of ``handle``.""" - ... - - async def flush_output(self) -> None: - """Write out whatever the VM has buffered.""" - ... - - async def receive(self) -> Mapping[str, Any]: - """Return the next input event: a chunk of the request body, a disconnect, or a ``restate.*`` event.""" - ... - - def wake(self) -> None: - """Make ``receive`` return a ``restate.*`` event.""" - ... - - def execute_run(self, handle: int) -> None: - """Start the run of ``handle``, which signals its completion through ``receive``.""" - ... - - def work(self) -> int: - """Return the handle of the attempt's working run, made at the first call. - - It is a run that the VM hands out like any other (``DoProgressExecuteRun``), - and that does not end while the attempt lasts: it stands for the - handler's work outside Restate. - """ - ... - - def end_work(self) -> None: - """End the working run, if there is one, as the attempt ends.""" - ... - - def notify_input(self, chunk: Mapping[str, Any]) -> None: - """Pass a chunk of the request body to the VM.""" - ... - - def track(self, task: asyncio.Future[Any]) -> None: - """Cancel ``task`` when the attempt ends.""" - ... - - def on_end(self) -> None: - """Handle the end of the attempt, after the selector has failed every wait.""" - ... - - -CANCELLATION: int = CANCEL_HANDLE -"""The handle of the invocation's cancel signal: the VM's, and what ``ctx.cancellation()`` awaits.""" - - -def cancellation_alone(future: UnresolvedFuture) -> bool: - """Return whether ``future`` waits for the invocation's cancellation, and nothing else.""" - if isinstance(future, SingleUnresolvedFuture): - return future.handle == CANCELLATION - return all(cancellation_alone(child) for child in future.children) - - -def is_ready(future: UnresolvedFuture, completed: Callable[[int], bool]) -> bool: - """Return whether ``future`` needs no more progress.""" - if isinstance(future, SingleUnresolvedFuture): - return completed(future.handle) - if isinstance(future, FirstCompletedUnresolvedFuture): - return any(is_ready(child, completed) for child in future.children) - return all(is_ready(child, completed) for child in future.children) - - -class FutureSelector: - """The single loop that drives the waits of an invocation without journal replay. - - A wait stays registered until it is ready. Each pass, the loop resolves - the waits that are ready, then asks the VM for progress on whichever - pending wait completes first. So a suspension waits for any of them, a - pending run starts whichever wait reaches it first, and a cancellation - reaches all of them. Registering a wait while the loop reads input wakes - the loop, so the new wait is included in the next check. The loop runs as - long as something is pending. - - To ask is to say that the handler waits: the VM tells Restate what for, - and suspends the invocation on it once the input closed (Restate's - inactivity timeout). That holds for every wait but one. A handler with - explicit cancellation waits for its cancellation (``cancelled(ctx)``) to - stop work it does outside Restate, a model's request, say: it watches for - it, and does not wait for it. Reported as awaited, the cancel signal - would be all Restate believes the handler waits for; and suspended on it, - the invocation would end its attempt in the middle of that work, with a - cancellation as the only thing to resume it. - - So with only the cancellation pending, the loop asks for it together with - the attempt's working run (``SelectorDriver.work``), which says what is - true: the handler is at work on something of its own, as inside - ``ctx.run``. While a run executes, the VM reports no await, and does not - suspend on a future the run is part of, whether the input is open or - closed; and it still finds the cancel signal when it comes. With anything - else pending, the working run is left out, and the invocation suspends on - what it waits for, the cancellation among it, as before. - """ - - def __init__(self, driver: SelectorDriver, disconnected: Callable[[], BaseException]) -> None: - self._driver: SelectorDriver = driver - self._disconnected: Callable[[], BaseException] = disconnected - self._waits: dict[asyncio.Future[None], UnresolvedFuture] = {} - self._task: asyncio.Task[None] | None = None - # True between the VM's WaitExternalProgress and the next input. - self._waiting: bool = False - # True when a wait was registered after the loop took its snapshot of the pending waits: the loop - # then takes another pass instead of waiting for input, which might never come for that wait. - self._missed: bool = False - # Why the attempt ended, once it has; each later wait raises a fresh instance. - self._end: Callable[[], BaseException] | None = None - - @property - def ended(self) -> BaseException | None: - """Why the attempt ended (a suspension, an error, a disconnect), or ``None`` while it continues.""" - return None if self._end is None else self._end() - - @property - def size(self) -> int: - """The number of waits still pending, for tests.""" - return len(self._waits) - - async def wait(self, future: UnresolvedFuture) -> None: - """Wait until ``future`` is ready; raise if the attempt ends first or is cancelled.""" - if self._end is not None: - raise self._end() - if is_ready(future, self._driver.is_completed): - return - waiter = asyncio.get_running_loop().create_future() - self._waits[waiter] = future - self._start() - try: - await waiter - finally: - self._waits.pop(waiter, None) - - def close(self) -> None: - """End the attempt as the handler returns: fail what still waits, and end the working run.""" - if self._end is None: - self._end = SuspendedException - self._fail_all(self._end) - if self._waiting: - # Its next pass finds nothing pending, and ends the loop. - self._waiting = False - self._driver.wake() - self._driver.end_work() - - def _start(self) -> None: - if self._task is None: - self._task = asyncio.create_task(self._loop()) - self._driver.track(self._task) - elif self._waiting: - # A loop that waits for input needs waking, once. - self._waiting = False - self._driver.wake() - else: - # A loop between passes (flushing output, say) may have taken its snapshot already. - self._missed = True - - def _settle(self) -> None: - for waiter, future in self._waits.items(): - if not waiter.done() and is_ready(future, self._driver.is_completed): - waiter.set_result(None) - - def _fail_all(self, error: Callable[[], BaseException]) -> None: - for waiter in list(self._waits): - if not waiter.done(): - waiter.set_exception(error()) - - def _finish(self, end: Callable[[], BaseException]) -> None: - """End the attempt: every wait, current or future, raises ``end()``.""" - self._end = end - self._fail_all(end) - self._driver.on_end() - - async def _loop(self) -> None: - driver = self._driver - try: - while True: - self._settle() - # Let the code that was just resolved run and register its next - # waits, so that one check covers them. This is only an - # optimization: a later registration wakes the loop anyway. - await asyncio.sleep(0) - self._missed = False - pending = [future for waiter, future in self._waits.items() if not waiter.done()] - if not pending: - return - if all(cancellation_alone(future) for future in pending): - # The handler watches, and waits for nothing: it works (see the class). - pending.append(SingleUnresolvedFuture(driver.work())) - await driver.flush_output() - response = driver.do_progress( - pending[0] if len(pending) == 1 else FirstCompletedUnresolvedFuture(pending) - ) - if isinstance(response, BaseException): - logger.exception("Exception in do_progress", exc_info=response) - self._finish(_internal(response)) - return - if isinstance(response, Suspended): - self._finish(SuspendedException) - return - if isinstance(response, DoProgressAnyCompleted): - continue - if isinstance(response, DoProgressCancelSignalReceived): - # Cancel every pending wait; waits registered afterwards are not cancelled. - self._fail_all(lambda: TerminalError("cancelled", 409)) - continue - if isinstance(response, DoProgressExecuteRun): - driver.execute_run(response.handle) - continue - if isinstance(response, DoProgressWaitExternalProgress): - if self._missed: - continue - self._waiting = True - await driver.flush_output() - chunk = await driver.receive() - self._waiting = False - kind = chunk.get("type") - if kind == "http.disconnect": - self._finish(self._disconnected) - return - if kind == "http.request": - driver.notify_input(chunk) - except asyncio.CancelledError: - # The attempt is over. - self._end = self._end or SuspendedException - self._fail_all(self._end) - raise - except BaseException as error: # pylint: disable=broad-exception-caught - logger.exception("Exception in the invocation's selector") - self._finish(_internal(error)) - finally: - self._task = None - - -def _internal(cause: BaseException) -> Callable[[], BaseException]: - """Return a factory of ``SdkInternalException`` instances caused by ``cause``.""" - - def internal() -> BaseException: - error = SdkInternalException() - error.__cause__ = cause - return error - - return internal - - -# ``hook`` makes the selector take over an SDK invocation: the waits of its -# futures, which the SDK makes through ``create_poll_or_cancel_coroutine``, go -# to the selector, and each future starts as soon as it is created. This -# reaches into ``ServerInvocationContext``, from the same package, whose tests -# cover it. -# TODO: once sessions run on it, the context could drive its waits through -# the selector itself, instead of being hooked. - - -class _ContextDriver: - """A ``SelectorDriver`` over the SDK's invocation context.""" - - def __init__(self, context: ServerInvocationContext, on_end: Callable[[], None]) -> None: - self.context: ServerInvocationContext = context - self.on_end: Callable[[], None] = on_end - # The working run's handle, once made. - self._work: int | None = None - - def do_progress(self, future: UnresolvedFuture) -> Any: - return self.context.vm.do_progress(future) - - def is_completed(self, handle: int) -> bool: - return self.context.vm.is_completed(handle) - - async def flush_output(self) -> None: - await self.context.take_and_send_output() - - async def receive(self) -> Mapping[str, Any]: - return await self.context.receive() - - def wake(self) -> None: - # Any restate.* event will do: the loop treats it as a wake-up. - event = self.context.receive.enqueue_restate_event({"type": "restate.run_completed", "data": None}) - self.track(asyncio.ensure_future(event)) - - def execute_run(self, handle: int) -> None: - if handle == self._work: - # The working run has no action: it executes until the attempt ends. - return - context = self.context - fn = context.run_coros_to_execute.pop(handle) - - async def run() -> None: - try: - await fn() - finally: - await context.receive.enqueue_restate_event({"type": "restate.run_completed", "data": None}) - - self.track(asyncio.create_task(run())) - - def notify_input(self, chunk: Mapping[str, Any]) -> None: - # Skip empty body frames, as the SDK does. - body = chunk.get("body") - if body is not None and len(body) > 0: - self.context.vm.notify_input(body) - if not chunk.get("more_body", False): - self.context.vm.notify_input_closed() - - def work(self) -> int: - if self._work is None: - # Journaled as a run named ``work``, whose action is the handler's own work. - self._work = self.context.vm.sys_run("work").handle - return self._work - - def end_work(self) -> None: - handle, self._work = self._work, None - if handle is None: - return - # The work is over: so is its run, in the journal of an invocation that goes on to answer. A VM that a - # suspension or an error closed refuses: the next attempt, or nothing, ends the run. - with contextlib.suppress(Exception): - self.context.vm.propose_run_completion_success(handle, b"") - - def track(self, task: asyncio.Future[Any]) -> None: - self.context.tasks.add(task) - - -def hook(context: ServerInvocationContext, on_end: Callable[[], None]) -> FutureSelector: - """Route the waits of ``context``, an invocation without journal replay, through one selector. - - Each future starts as soon as it is created, whether or not anything - awaits it. The selector calls ``on_end`` if it has to fail every wait. - The hook lasts as long as ``context``, which is one attempt. - """ - selector = FutureSelector(_ContextDriver(context, on_end), DisconnectedException) - started: set[asyncio.Task[Any]] = set() - - def starting(make: Callable[..., Any]) -> Callable[..., Any]: - def make_started(*args: Any, **kwargs: Any) -> Any: - future = make(*args, **kwargs) - lazy = future.future - if lazy.task is None: - lazy.task = asyncio.create_task(lazy.async_def()) - # If nothing awaits it, its error is dropped. - lazy.task.add_done_callback(_retrieve) - started.add(lazy.task) - lazy.task.add_done_callback(started.discard) - return future - - return make_started - - for name in ("create_future", "create_sleep_future", "create_call_future"): - setattr(context, name, starting(getattr(context, name))) - context.create_poll_or_cancel_coroutine = selector.wait # type: ignore[method-assign,assignment] # pyright: ignore[reportAttributeAccessIssue] - return selector - - -def _retrieve(task: asyncio.Future[Any]) -> None: - if not task.cancelled(): - task.exception() diff --git a/python/restate/sessions/_session.py b/python/restate/sessions/_session.py index 273bdc08..e9abc5d7 100644 --- a/python/restate/sessions/_session.py +++ b/python/restate/sessions/_session.py @@ -34,7 +34,7 @@ from typing import Any, Protocol from urllib.parse import quote -from restate._internal import PyVM # pylint: disable=no-name-in-module +from restate._internal import PyExplicitRecoveryVM # pylint: disable=no-name-in-module from restate.exceptions import SuspendedException, TerminalError from restate.sessions._api import Database, DatabaseReader, Transaction from restate.sessions._calls import CallHost, GenericSend, Sends @@ -94,7 +94,7 @@ def state_keys(self) -> Awaitable[list[str]]: ... def sync(self) -> Awaitable[Any]: - """Make an empty run, which completes once every earlier command is stored.""" + """Complete once every earlier write is stored.""" ... def attempt_end(self) -> BaseException | None: @@ -106,12 +106,8 @@ def on_attempt_end(self, listener: Callable[[], None]) -> Callable[[], None]: ... @property - def vm(self) -> PyVM | None: - """The invocation's VM, which the database reads and writes directly, or ``None`` (as on a test's host).""" - ... - - def wait(self, handle: int) -> Awaitable[None]: - """Wait until the VM has the result of the read ``handle``.""" + def vm(self) -> PyExplicitRecoveryVM | None: + """The attempt's VM, which the database reads and writes directly, or ``None`` (as on a test's host).""" ... def cancel_invocation(self, invocation_id: str) -> None: @@ -158,31 +154,22 @@ class _ObjectStore: """The object's state as a ``Store``. ``get`` reads the state; ``set`` and ``clear`` write it, returning at once, - and Restate stores the writes in order; ``sync`` is an empty run, which - completes once the commands before it are stored. A ``get``, ``wait`` or - ``sync`` still pending when the attempt ends raises, so that the session - ends instead of holding its lock. With the invocation's VM (``vm``), the - extension reads and writes the VM directly, and waits for reads with - ``wait``. + and Restate stores the writes in order; ``sync`` completes once the writes + before it are stored. A ``get`` or ``sync`` still pending when the attempt + ends raises, so that the session ends instead of holding its lock. With + the attempt's VM (``vm``), the extension uses the VM directly instead. """ def __init__(self, host: SqlHost, name: str | None) -> None: self._host: SqlHost = host self._name: str | None = name - self.vm: PyVM | None = host.vm + self.vm: PyExplicitRecoveryVM | None = host.vm self.database_name: str | None = name - def wait(self, handle: int) -> Awaitable[None]: - """Wait until the VM has the result of the read ``handle``.""" - return _until_attempt_end(self._host, self._host.wait(handle)) - def _key(self, key: str) -> str: return key if self._name is None else _beside(self._name, key) def get(self, key: str) -> Awaitable[bytes | None]: - # TODO: use protocol v8's ephemeral get, which stays out of the journal, - # once a Restate release ships v8 and the SDK supports it. Restate 1.8 - # negotiates v7 at most, so this is a journaled get. return _until_attempt_end(self._host, self._host.get(self._key(key))) def set(self, key: str, value: bytes) -> None: @@ -204,7 +191,7 @@ async def own() -> list[str]: return own() def sync(self) -> Awaitable[None]: - """Wait until every earlier write is stored; the run is issued now, in order with the writes.""" + """Wait until every earlier write is stored; the request is issued now, in order with the writes.""" return _until_attempt_end(self._host, self._host.sync()) @@ -214,13 +201,9 @@ class _ReaderStore: def __init__(self, host: SqlHost, name: str | None) -> None: self._host: SqlHost = host self._name: str | None = name - self.vm: PyVM | None = host.vm + self.vm: PyExplicitRecoveryVM | None = host.vm self.database_name: str | None = name - def wait(self, handle: int) -> Awaitable[None]: - """Wait until the VM has the result of the read ``handle``.""" - return _until_attempt_end(self._host, self._host.wait(handle)) - def get(self, key: str) -> Awaitable[bytes | None]: key = key if self._name is None else _beside(self._name, key) return _until_attempt_end(self._host, self._host.get(key)) diff --git a/src/explicit_recovery.rs b/src/explicit_recovery.rs new file mode 100644 index 00000000..15a8e07a --- /dev/null +++ b/src/explicit_recovery.rs @@ -0,0 +1,389 @@ +//! The VM of a session object's attempt: shared-core's [`CoreExplicitRecoveryVM`], which never +//! replays a journal. +//! +//! An action returns a handle, and its result comes back as a notification of that handle +//! (`take_notification`): `restate/sessions/_driver.py` settles its futures with them. The +//! database's store ([`crate::sessions`]) awaits its own handles from Rust: their completions go +//! to it ([`PyExplicitRecoveryVM::wait_in_rust`]), never to Python. +use crate::{ + PyCallHandle, PyFailure, PyHeader, PyInput, PyResponseHead, PyStateKeys, PyVoid, VMException, +}; +use futures::channel::oneshot; +use pyo3::create_exception; +use pyo3::prelude::*; +use pyo3::types::{PyBytes, PyString}; +use restate_sdk_shared_core::explicit_recovery::{ + request_response_unsupported, AttemptState, CoreExplicitRecoveryVM, ExplicitRecoveryVM, + Notification, TraceId, +}; +use restate_sdk_shared_core::{ + AttachInvocationTarget, Error, NonEmptyValue, NotificationHandle, Target, Value, +}; +use std::collections::{HashMap, VecDeque}; +use std::time::{Duration, SystemTime}; + +create_exception!( + restate_sdk_python_core, + AttemptShutDownException, + pyo3::exceptions::PyException, + "Restate shut the attempt down: it is over, and a new attempt will run the handler from the start." +); + +/// A VM error as Python gets it: the attempt's shutdown is an `AttemptShutDownException`. +pub(crate) fn vm_error(error: Error) -> PyErr { + if error.is_suspended_error() { + AttemptShutDownException::new_err(error.to_string()) + } else { + VMException::new_err(error.to_string()) + } +} + +/// Where Rust waits for the notification of a handle. +type RustWaiter = oneshot::Sender>; + +#[pyclass] +pub(crate) struct PyExplicitRecoveryVM { + pub(crate) vm: CoreExplicitRecoveryVM, + /// The handles Rust waits for (the database's reads and acks), with their waiter. + rust_waiters: HashMap, + /// The completions taken from the VM for Python, not yet taken by it. + for_python: VecDeque, + /// What Rust calls after its own calls to the VM: it schedules Python's tick, which writes + /// the output and settles Python's futures. + scheduler: Option>, +} + +impl PyExplicitRecoveryVM { + /// Take the VM's completions, handing Rust's to their waiters. Once the attempt closed with + /// an error, every waiter gets it. + fn route(&mut self) -> Result<(), Error> { + loop { + match self.vm.take_next_notification() { + Ok(Some(notification)) => match self.rust_waiters.remove(¬ification.handle) { + Some(waiter) => { + let _ = waiter.send(Ok(notification.value)); + } + None => self.for_python.push_back(notification), + }, + Ok(None) => return Ok(()), + Err(error) => { + for (_, waiter) in self.rust_waiters.drain() { + let _ = waiter.send(Err(error.clone())); + } + return Err(error); + } + } + } + } + + /// The notification of `handle`, for Rust. A handle already notified is at once. + pub(crate) fn wait_in_rust( + &mut self, + handle: NotificationHandle, + ) -> oneshot::Receiver> { + let (sender, receiver) = oneshot::channel(); + self.rust_waiters.insert(handle, sender); + // The error, if any, reaches the waiter. + let _ = self.route(); + receiver + } + + pub(crate) fn scheduler(&self, py: Python<'_>) -> Option> { + self.scheduler + .as_ref() + .map(|scheduler| scheduler.clone_ref(py)) + } +} + +fn target( + service: String, + handler: String, + key: Option, + idempotency_key: Option, + headers: Option>, +) -> Target { + Target { + service, + handler, + key, + idempotency_key, + scope: None, + limit_key: None, + headers: headers + .unwrap_or_default() + .into_iter() + .map(Into::into) + .collect(), + } +} + +/// A notification's value as Python gets it: `PyVoid`, `bytes`, `PyFailure`, `PyStateKeys`, or the +/// invocation id as `str`. +fn value_to_py(py: Python<'_>, value: Value) -> PyResult> { + Ok(match value { + Value::Void => Py::new(py, PyVoid)?.into_any(), + Value::Success(b) => PyBytes::new(py, &b).into_any().unbind(), + Value::Failure(f) => Py::new(py, PyFailure::from(f))?.into_any(), + Value::StateKeys(keys) => Py::new(py, PyStateKeys { keys })?.into_any(), + Value::InvocationId(id) => PyString::new(py, &id).into_any().unbind(), + }) +} + +#[pymethods] +impl PyExplicitRecoveryVM { + /// Without a `bidirectional` stream (a request/response transport, e.g. AWS Lambda), the VM + /// fails the invocation at once, pausing it: no response could reach the handler. + #[new] + fn new(headers: Vec<(String, String)>, bidirectional: bool) -> PyResult { + let mut vm = CoreExplicitRecoveryVM::new(headers).map_err(vm_error)?; + if !bidirectional { + vm.notify_error(request_response_unsupported()); + } + Ok(Self { + vm, + rust_waiters: Default::default(), + for_python: Default::default(), + scheduler: None, + }) + } + + fn set_scheduler(&mut self, scheduler: Py) { + self.scheduler = Some(scheduler); + } + + fn get_response_head(&self) -> PyResponseHead { + self.vm.get_response_head().into() + } + + fn notify_input(&mut self, buffer: &Bound<'_, PyBytes>) { + self.vm.notify_input(buffer.as_bytes().to_vec().into()); + } + + fn notify_input_closed(&mut self) { + self.vm.notify_input_closed(); + } + + fn take_output<'py>(&mut self, py: Python<'py>) -> Bound<'py, PyBytes> { + PyBytes::new(py, &self.vm.take_output()) + } + + fn is_ready_to_execute(&self) -> PyResult { + self.vm.is_ready_to_execute().map_err(vm_error) + } + + fn input(&mut self) -> PyResult { + self.vm.get_input().map(Into::into).map_err(vm_error) + } + + /// The next completion for Python, `(handle, value)`, or `None`. Raises once the attempt is + /// closed by a shutdown (`AttemptShutDownException`) or a failure (`VMException`). + fn take_notification(&mut self, py: Python<'_>) -> PyResult)>> { + self.route().map_err(vm_error)?; + match self.for_python.pop_front() { + Some(Notification { handle, value }) => { + Ok(Some((u32::from(handle), value_to_py(py, value)?))) + } + None => Ok(None), + } + } + + // --- Request/response actions + + #[pyo3(signature = (key, name=None))] + fn get_state(&mut self, key: String, name: Option) -> PyResult { + self.vm + .cmd_state_get(key, name) + .map(u32::from) + .map_err(vm_error) + } + + #[pyo3(signature = (name=None))] + fn get_state_keys(&mut self, name: Option) -> PyResult { + self.vm + .cmd_state_get_keys(name) + .map(u32::from) + .map_err(vm_error) + } + + #[pyo3(signature = (service, handler, buffer, key=None, idempotency_key=None, headers=None, name=None))] + #[allow(clippy::too_many_arguments)] + fn call( + &mut self, + service: String, + handler: String, + buffer: &Bound<'_, PyBytes>, + key: Option, + idempotency_key: Option, + headers: Option>, + name: Option, + ) -> PyResult { + self.vm + .cmd_call( + target(service, handler, key, idempotency_key, headers), + buffer.as_bytes().to_vec().into(), + name, + ) + .map(|handle| PyCallHandle { + invocation_id_handle: handle.invocation_id_notification_handle.into(), + result_handle: handle.call_notification_handle.into(), + }) + .map_err(vm_error) + } + + #[pyo3(signature = (invocation_id, name=None))] + fn attach_invocation(&mut self, invocation_id: String, name: Option) -> PyResult { + self.vm + .cmd_attach_invocation(AttachInvocationTarget::InvocationId(invocation_id), name) + .map(u32::from) + .map_err(vm_error) + } + + // --- Fire-and-forget actions + + #[pyo3(signature = (key, buffer, name=None, ack=false))] + fn set_state( + &mut self, + key: String, + buffer: &Bound<'_, PyBytes>, + name: Option, + ack: bool, + ) -> PyResult { + self.vm + .cmd_state_set(key, buffer.as_bytes().to_vec().into(), name, ack) + .map(u32::from) + .map_err(vm_error) + } + + #[pyo3(signature = (key, name=None, ack=false))] + fn clear_state(&mut self, key: String, name: Option, ack: bool) -> PyResult { + self.vm + .cmd_state_clear(key, name, ack) + .map(u32::from) + .map_err(vm_error) + } + + #[pyo3(signature = (name=None, ack=false))] + fn clear_all_state(&mut self, name: Option, ack: bool) -> PyResult { + self.vm + .cmd_state_clear_all(name, ack) + .map(u32::from) + .map_err(vm_error) + } + + #[pyo3(signature = (invocation_id, name=None, ack=false))] + fn cancel_invocation( + &mut self, + invocation_id: String, + name: Option, + ack: bool, + ) -> PyResult { + self.vm + .cmd_cancel_invocation(invocation_id, name, ack) + .map(u32::from) + .map_err(vm_error) + } + + /// Returns the handle of the invocation id. `delay` is in milliseconds. + #[pyo3(signature = (service, handler, buffer, key=None, delay=None, idempotency_key=None, headers=None, name=None))] + #[allow(clippy::too_many_arguments)] + fn send( + &mut self, + service: String, + handler: String, + buffer: &Bound<'_, PyBytes>, + key: Option, + delay: Option, + idempotency_key: Option, + headers: Option>, + name: Option, + ) -> PyResult { + let execute_at = delay.map(|millis| { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .expect("Duration since unix epoch cannot fail") + + Duration::from_millis(millis) + }); + self.vm + .cmd_send( + target(service, handler, key, idempotency_key, headers), + buffer.as_bytes().to_vec().into(), + execute_at, + name, + ) + .map(|handle| handle.invocation_id_notification_handle.into()) + .map_err(vm_error) + } + + /// Inside the trace `parent` of this attempt, or else inside the attempt itself. + #[pyo3(signature = (name, parent=None))] + fn start_trace(&mut self, name: String, parent: Option) -> PyResult { + self.vm + .trace_start(name, parent.map(TraceId::from)) + .map(u32::from) + .map_err(vm_error) + } + + fn end_trace_success(&mut self, trace: u32, buffer: &Bound<'_, PyBytes>) -> PyResult<()> { + self.vm + .trace_end( + TraceId::from(trace), + NonEmptyValue::Success(buffer.as_bytes().to_vec().into()), + ) + .map_err(vm_error) + } + + fn end_trace_failure(&mut self, trace: u32, failure: PyFailure) -> PyResult<()> { + self.vm + .trace_end(TraceId::from(trace), NonEmptyValue::Failure(failure.into())) + .map_err(vm_error) + } + + fn heartbeat(&mut self) -> PyResult<()> { + self.vm.heartbeat().map_err(vm_error) + } + + // --- End + + fn end_success(&mut self, buffer: &Bound<'_, PyBytes>) -> PyResult<()> { + self.vm + .end(NonEmptyValue::Success(buffer.as_bytes().to_vec().into())) + .map_err(vm_error) + } + + fn end_failure(&mut self, failure: PyFailure) -> PyResult<()> { + self.vm + .end(NonEmptyValue::Failure(failure.into())) + .map_err(vm_error) + } + + #[pyo3(signature = (error, stacktrace=None, delay_override_ms=None))] + fn notify_error( + &mut self, + error: String, + stacktrace: Option, + delay_override_ms: Option, + ) { + let mut error = Error::new(restate_sdk_shared_core::error::codes::INTERNAL, error); + if let Some(stacktrace) = stacktrace { + error = error.with_stacktrace(stacktrace); + } + if let Some(delay) = delay_override_ms { + error = error.with_next_retry_delay_override(Duration::from_millis(delay)); + } + self.vm.notify_error(error); + } + + /// Whether the invocation was cancelled, in this attempt or an earlier one. + fn is_cancelled(&self) -> bool { + self.vm.is_cancelled() + } + + /// `"starting"`, `"running"` or `"closed"`. + fn state(&self) -> &'static str { + match self.vm.state() { + AttemptState::Starting => "starting", + AttemptState::Running => "running", + AttemptState::Closed => "closed", + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 3edd8f26..07e05dc7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ mod asgi; +mod explicit_recovery; mod tunnel; use pyo3::create_exception; @@ -1067,6 +1068,7 @@ fn _internal(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; @@ -1084,6 +1086,11 @@ fn _internal(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("INGRESS_KEY_URL", tunnel::INGRESS_KEY_HELP_URL)?; m.add("VMException", m.py().get_type::())?; + m.add( + "AttemptShutDownException", + m.py() + .get_type::(), + )?; m.add( "IdentityKeyException", m.py().get_type::(), diff --git a/src/sessions.rs b/src/sessions.rs index efb4884f..6ab20e00 100644 --- a/src/sessions.rs +++ b/src/sessions.rs @@ -25,26 +25,27 @@ //! The state the database is kept in: `set` and `clear` queue a write; `sync` //! completes once every write before it is stored. The object's state keeps //! writes in issue order, so a crash loses only a suffix of them (see -//! [`KvStore`]): a statement that commits queues its writes, then completes at -//! one `sync`. With `keys`, a checkpoint deletes the packs no checkpoint needs; -//! a store without keeps its garbage. +//! [`KvStore`]): a statement that commits queues its writes, then completes +//! once the write of its head is acked. With `keys`, a checkpoint deletes the +//! packs no checkpoint needs; a store without keeps its garbage. //! -//! The store is the invocation's VM, as a handler's context has it -//! ([`VmStore`]): a write goes to it directly, as does a read that it can -//! answer at once (state preloaded, or written by the invocation); waiting -//! for a read, the sync (an empty run) and the listing of the keys go through -//! Python, whose selector drives the invocation's waits. Or, without a VM (in -//! tests, or with a journal codec), a store implemented in Python -//! ([`PyStore`]). Either way, Python's side is one function, -//! `dispatch(op, arg, value, reply)`, called directly, on the loop's thread, -//! in the order of the requests, so that a read sees the writes before it. +//! The store is the attempt's VM (`PyExplicitRecoveryVM`, see +//! [`crate::explicit_recovery`]), which never replays a journal ([`VmStore`]): +//! reads, writes, the listing of the keys and the acks are its actions, and +//! the store awaits their completions itself, in Rust. Only what a commit +//! makes besides (a transaction's outbox sends) goes through Python +//! (`COMMIT`). Or, without a VM (in tests, or with a journal codec), a store +//! implemented in Python ([`PyStore`]). Either way, Python's side is one +//! function, `dispatch(op, arg, value, reply)`, called directly, on the +//! loop's thread, in the order of the requests, so that a read sees the +//! writes before it. //! //! Every database of the process is kept warm in one page cache //! ([`page_cache`]), and keeps the checkpoints it outgrows Restate with in //! the object store `RESTATE_SQL_OBJECT_STORE` names, if any //! ([`object_store`]). That store's requests are reqwest's, which need a //! tokio runtime: they alone are polled inside one ([`InRuntime`]). -use crate::PyVM; +use crate::explicit_recovery::{vm_error, PyExplicitRecoveryVM}; use bytes::Bytes; use futures::channel::oneshot; use futures::future::BoxFuture; @@ -54,18 +55,20 @@ use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::{PyBool, PyByteArray, PyBytes, PyFloat, PyInt, PyList, PyString, PyTuple}; use pyo3::IntoPyObjectExt; +use restate_sdk_shared_core::explicit_recovery::ExplicitRecoveryVM; use restate_sdk_shared_core::sql::{self, Numeric, Value}; use restate_sdk_shared_core::state::{ self, BlobStore, KvStore, ObjectStoreBlobs, ObjectStoreL1, PageCache, PageCacheConfig, }; -use restate_sdk_shared_core::{Value as VmValue, VM}; +use restate_sdk_shared_core::NotificationHandle; +use restate_sdk_shared_core::Value as VmValue; use std::borrow::Cow; use std::collections::HashMap; use std::future::Future; use std::io; use std::ops::Range; use std::pin::Pin; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{mpsc, Arc, Mutex, OnceLock}; use std::task::{Context, Poll, Wake, Waker}; use std::thread::ThreadId; @@ -83,8 +86,9 @@ pub(crate) const SET: u32 = 1; pub(crate) const CLEAR: u32 = 2; pub(crate) const SYNC: u32 = 3; pub(crate) const KEYS: u32 = 4; -/// Wait until the VM completes the handle `arg`, a read's ([`VmStore`]). -pub(crate) const WAIT: u32 = 5; +/// Run what the committing transaction makes at its commit (its outbox's sends): between the +/// commit's acked write of the head and the wait for its ack ([`VmStore`]). +pub(crate) const COMMIT: u32 = 5; // --- Running calls on the loop's thread ------------------------------------------------------------ @@ -320,12 +324,6 @@ fn io_error(error: impl std::fmt::Display) -> io::Error { io::Error::other(error.to_string()) } -/// What a request names: a key of the store, or a handle of the VM. -enum Arg<'a> { - Key(&'a str), - Handle(u32), -} - /// Python's side of a store: `dispatch(op, arg, value, reply)`, called on /// the loop's thread, where every call runs. struct Dispatch(Py); @@ -335,33 +333,30 @@ impl Dispatch { fn call( &self, op: u32, - arg: Arg<'_>, + key: &str, value: Option, reply: Option, ) -> io::Result<()> { Python::attach(|py| { - let arg = match arg { - Arg::Key(key) => PyString::new(py, key).into_any(), - Arg::Handle(handle) => handle.into_bound_py_any(py)?, - }; + let key = PyString::new(py, key); let value = value.map(|value| PyBytes::new(py, &value).into_any().unbind()); let reply = match reply { Some(reply) => Py::new(py, reply)?.into_any(), None => py.None(), }; - self.0.call1(py, (op, arg, value, reply))?; + self.0.call1(py, (op, key, value, reply))?; Ok::<_, PyErr>(()) }) .map_err(io_error) } - /// A request that answers: a read, a wait, a sync, or the keys. - async fn request(&self, op: u32, arg: Arg<'_>) -> io::Result { + /// A request that answers: a read, a sync, the keys, or a commit's sends. + async fn request(&self, op: u32, key: &str) -> io::Result { let (sender, receiver) = oneshot::channel(); let reply = SqlReply { sender: Mutex::new(Some(sender)), }; - self.call(op, arg, None, Some(reply))?; + self.call(op, key, None, Some(reply))?; match receiver.await { Ok(Ok(answer)) => Ok(answer), Ok(Err(error)) => Err(io_error(error)), @@ -370,11 +365,11 @@ impl Dispatch { } async fn sync(&self) -> io::Result<()> { - self.request(SYNC, Arg::Key("")).await.map(drop) + self.request(SYNC, "").await.map(drop) } async fn keys(&self) -> io::Result> { - match self.request(KEYS, Arg::Key("")).await? { + match self.request(KEYS, "").await? { Answer::Keys(keys) => Ok(keys), _ => Err(unexpected("keys")), } @@ -399,7 +394,7 @@ struct PyStore { impl KvStore for PyStore { fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, io::Result>> { Box::pin(async move { - match self.dispatch.request(GET, Arg::Key(key)).await? { + match self.dispatch.request(GET, key).await? { Answer::Nothing => Ok(None), Answer::Value(value) => Ok(Some(value)), Answer::Keys(_) => Err(unexpected("get")), @@ -408,11 +403,11 @@ impl KvStore for PyStore { } fn put(&self, key: &str, value: Bytes) -> io::Result<()> { - self.dispatch.call(SET, Arg::Key(key), Some(value), None) + self.dispatch.call(SET, key, Some(value), None) } fn delete(&self, key: &str) -> io::Result<()> { - self.dispatch.call(CLEAR, Arg::Key(key), None, None) + self.dispatch.call(CLEAR, key, None, None) } fn sync(&self) -> BoxFuture<'_, io::Result<()>> { @@ -431,23 +426,33 @@ impl KvStore for PyStore { // --- The invocation's VM as the store -------------------------------------------------------------- -/// The object's state through the invocation's VM, as a handler's context -/// reaches it, but without Python on the way: a write is a state command of -/// the VM's, a read that the VM can answer at once (state preloaded, or -/// written by this invocation) is answered by it. A read the runtime must -/// answer waits through Python's selector (`WAIT`), as do the sync (`SYNC`, an -/// empty run) and the listing of the keys (`KEYS`): `dispatch`'s. +/// The state key of the store's writes that only ask for an ack ([`VmStore::sync`]): under the +/// state format's prefix, which tooling hides. +const SYNC_KEY: &str = "v22/sync"; + +/// The object's state through the attempt's VM (`PyExplicitRecoveryVM`), without Python on the +/// way: a read, a write and the listing of the keys are the VM's actions, and the store awaits +/// their completions itself ([`PyExplicitRecoveryVM::wait_in_rust`]). /// -/// Each command is named after its key, as the context's are, so that -/// tooling can hide the database by name. With `name`, the database `name` of -/// the key, apart from the object's own: each key under `db//` (see -/// `_beside` in `restate/sessions/_session.py`, which lists its keys). A -/// reader (a view's) writes nothing. +/// The sync is Restate's ack of a write: a flush writes its head with +/// [`KvStore::put_and_sync`], an acked write of the head, and since Restate stores writes in +/// order, the ack means every earlier write is stored too. Between the head and the wait for +/// its ack, Python runs what the committing transaction makes at its commit (`COMMIT`, its +/// outbox's sends). A sync with writes since the last ack (garbage collection, an open) +/// clears [`SYNC_KEY`] with an ack. +/// +/// Each action is named after its key, so that tooling can hide the database by name. With +/// `name`, the database `name` of the key, apart from the object's own: each key under +/// `db//` (see `_beside` in `restate/sessions/_session.py`). A reader (a view's) writes +/// nothing. After each call, the VM's scheduler has Python write the output. struct VmStore { - vm: Py, + vm: Py, dispatch: Dispatch, name: Option, reader: bool, + /// The writes issued, and how many of them an ack covers. + issued: AtomicU64, + synced: AtomicU64, } impl VmStore { @@ -462,83 +467,142 @@ impl VmStore { } } - /// `f` of the VM, borrowed for that long: never across an await. - fn with_vm(&self, f: impl FnOnce(&mut PyVM) -> io::Result) -> io::Result { + /// `f` of the VM, borrowed for that long (never across an await); then the scheduler, so + /// that Python writes what `f` sent. + fn act(&self, f: impl FnOnce(&mut PyExplicitRecoveryVM) -> PyResult) -> io::Result { Python::attach(|py| { - let mut vm = self.vm.bind(py).try_borrow_mut().map_err(io_error)?; - f(&mut vm) + let (result, scheduler) = { + let mut vm = self.vm.bind(py).try_borrow_mut().map_err(io_error)?; + let result = f(&mut vm); + (result, vm.scheduler(py)) + }; + if let Some(scheduler) = scheduler { + scheduler.call0(py).map_err(io_error)?; + } + result.map_err(io_error) }) } - fn refuse_write(&self) -> io::Result<()> { - match self.reader { - true => Err(io_error("a view writes no state")), - false => Ok(()), + /// The notification of `handle`. + async fn wait(&self, handle: u32) -> io::Result { + let notification = self.act(|vm| Ok(vm.wait_in_rust(NotificationHandle::from(handle))))?; + match notification.await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(io_error(vm_error(error))), + Err(_) => Err(io_error("the attempt ended")), } } + + /// Issue a write with `f`: its count, and its handle (notified by the ack, if it asks for one). + fn write( + &self, + f: impl FnOnce( + &mut PyExplicitRecoveryVM, + ) -> Result, + ) -> io::Result<(u64, u32)> { + if self.reader { + return Err(io_error("a view writes no state")); + } + let handle = self.act(|vm| f(vm).map(u32::from).map_err(vm_error))?; + Ok((self.issued.fetch_add(1, Ordering::SeqCst) + 1, handle)) + } + + /// Wait for the ack of the write `issued`, after running the committing transaction's + /// callbacks: every write issued up to it is then stored. + async fn acked(&self, issued: u64, handle: u32) -> io::Result<()> { + self.dispatch.request(COMMIT, "").await?; + self.wait(handle).await?; + self.synced.fetch_max(issued, Ordering::SeqCst); + Ok(()) + } +} + +/// The database `name`'s key of the state key `key`, if it is one of it: `_unbeside` of +/// `restate/sessions/_session.py`. +fn unbeside(name: &str, key: &str) -> Option { + let at = key.find('/')? + 1; + let rest = key[at..].strip_prefix(&format!("db/{name}/"))?; + Some(format!("{}{rest}", &key[..at])) } impl KvStore for VmStore { fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, io::Result>> { Box::pin(async move { let key = self.key(key); - let handle = self.with_vm(|vm| { - (vm.vm - .sys_state_get(key.clone(), Some(key), Default::default())) - .map_err(io_error) + let handle = self.act(|vm| { + vm.vm + .cmd_state_get(key.clone(), Some(key)) + .map(u32::from) + .map_err(vm_error) })?; - let ready = self.with_vm(|vm| Ok(vm.vm.is_completed(handle)))?; - if !ready { - self.dispatch - .request(WAIT, Arg::Handle(u32::from(handle))) - .await?; + match self.wait(handle).await? { + VmValue::Success(value) => Ok(Some(value)), + VmValue::Void => Ok(None), + VmValue::Failure(failure) => Err(io_error(failure.message)), + _ => Err(io_error("the state read completed with no value")), } - self.with_vm(|vm| match vm.vm.take_notification(handle) { - Ok(Some(VmValue::Success(value))) => Ok(Some(value)), - Ok(Some(VmValue::Void)) => Ok(None), - Ok(Some(VmValue::Failure(failure))) => Err(io_error(failure.message)), - Ok(_) => Err(io_error("the state read completed with no value")), - Err(error) => Err(io_error(error)), - }) }) } fn put(&self, key: &str, value: Bytes) -> io::Result<()> { - self.refuse_write()?; let key = self.key(key); - self.with_vm(|vm| { - (vm.vm - .sys_state_set(key.clone(), value, Some(key), Default::default())) - .map_err(io_error) - }) + self.write(|vm| vm.vm.cmd_state_set(key.clone(), value, Some(key), false)) + .map(drop) } fn delete(&self, key: &str) -> io::Result<()> { - self.refuse_write()?; let key = self.key(key); - self.with_vm(|vm| { - vm.vm - .sys_state_clear(key.clone(), Some(key)) - .map_err(io_error) + self.write(|vm| vm.vm.cmd_state_clear(key.clone(), Some(key), false)) + .map(drop) + } + + fn put_and_sync<'a>(&'a self, key: &'a str, value: Bytes) -> BoxFuture<'a, io::Result<()>> { + let key = self.key(key); + // Issued now, as a put is. + let written = self.write(|vm| vm.vm.cmd_state_set(key.clone(), value, Some(key), true)); + Box::pin(async move { + let (issued, handle) = written?; + self.acked(issued, handle).await }) } fn sync(&self) -> BoxFuture<'_, io::Result<()>> { Box::pin(async move { - match self.reader { + if self.reader { // A reader wrote nothing to sync. - true => Ok(()), - false => self.dispatch.sync().await, + return Ok(()); + } + if self.synced.load(Ordering::SeqCst) == self.issued.load(Ordering::SeqCst) { + self.dispatch.request(COMMIT, "").await?; + return Ok(()); } + let key = self.key(SYNC_KEY); + let (issued, handle) = + self.write(|vm| vm.vm.cmd_state_clear(key.clone(), Some(key), true))?; + self.acked(issued, handle).await }) } fn keys(&self) -> BoxFuture<'_, io::Result>> { Box::pin(async move { - match self.reader { - true => Err(no_keys()), - false => self.dispatch.keys().await, + if self.reader { + return Err(no_keys()); } + // Named under the state format's prefix, which tooling hides. + let handle = self.act(|vm| { + vm.vm + .cmd_state_get_keys(Some("v22/keys".to_owned())) + .map(u32::from) + .map_err(vm_error) + })?; + let keys = match self.wait(handle).await? { + VmValue::StateKeys(keys) => keys, + _ => return Err(unexpected("keys")), + }; + Ok(match &self.name { + None => keys, + Some(name) => keys.iter().filter_map(|key| unbeside(name, key)).collect(), + }) }) } } @@ -672,7 +736,7 @@ pub(crate) fn sql_open<'py>( dispatch: Py, lists_keys: bool, reader: bool, - vm: Option>, + vm: Option>, name: Option, ) -> PyResult> { let dispatch = Dispatch(dispatch); @@ -682,6 +746,8 @@ pub(crate) fn sql_open<'py>( dispatch, name, reader, + issued: AtomicU64::new(0), + synced: AtomicU64::new(0), }), None => Arc::new(PyStore { dispatch, @@ -879,6 +945,6 @@ pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("SQL_CLEAR", CLEAR)?; m.add("SQL_SYNC", SYNC)?; m.add("SQL_KEYS", KEYS)?; - m.add("SQL_WAIT", WAIT)?; + m.add("SQL_COMMIT", COMMIT)?; Ok(()) } diff --git a/tests/sessions_harness.py b/tests/sessions_harness.py index 2678f068..46269a70 100644 --- a/tests/sessions_harness.py +++ b/tests/sessions_harness.py @@ -15,6 +15,7 @@ import asyncio import typing import uuid +from typing import Any from datetime import timedelta import httpx2 @@ -24,8 +25,9 @@ import restate from support import RESTATE_IMAGE # pylint: disable=import-error from restate import HarnessEnvironment, sessions +from restate.retry_policy import InvocationRetryPolicy from restate.sessions import internal -from restate.sessions import _object, _session +from restate.sessions import _driver, _session @pytest.fixture(scope="session") @@ -50,7 +52,7 @@ def store(request, monkeypatch): global python_writes # pylint: disable=global-statement python_writes = 0 if request.param == "python": - monkeypatch.setattr(_object._ContextHost, "vm", property(lambda self: None)) + monkeypatch.setattr(_driver.VmHost, "vm", property(lambda self: None)) set_state = _session._ObjectStore.set def counted(self, key: str, value: bytes) -> None: @@ -156,10 +158,84 @@ async def stoppable(ctx: sessions.SessionContext, text: str) -> list[str]: return cancelled +@notes.handler() +async def waits_for_a_nap(ctx: sessions.SessionContext) -> str: + """Waits for a nap, noting its invocation id first; without explicit cancellation.""" + napping = ctx.call(nap) + await ctx.db.execute("INSERT INTO notes (text) VALUES (?)", [await napping.invocation_id()]) + return await napping + + +@notes.handler() +async def nested(ctx: sessions.SessionContext) -> None: + """Times a model request inside a turn.""" + turn = internal.annotate(ctx, "turn") + model = internal.annotate(ctx, "model", parent=turn) + model.end({"tokens": 3}) + turn.end() + await ctx.db.execute("INSERT INTO notes (text) VALUES ('nested')") + + +crawler = restate.Service("crawler") + + +@crawler.handler() +async def crawl(ctx: restate.Context) -> str: + await ctx.sleep(timedelta(seconds=3)) + return "crawled" + + +# Restate shuts down an attempt it heard nothing from for a second; its retries pause it after two +# attempts (a restart after a shutdown is not one). +slowpoke = sessions.SessionObject( + "slowpoke", + inactivity_timeout=timedelta(seconds=1), + invocation_retry_policy=InvocationRetryPolicy(max_attempts=2, on_max_attempts="pause"), +) +attempts: dict[str, int] = {} +"""The attempts of each key's invocation, counted here: the app serves in this process.""" + + +def attempt(ctx: sessions.SessionContext) -> int: + attempts[ctx.key] = attempts.get(ctx.key, 0) + 1 + return attempts[ctx.key] + + +@slowpoke.handler() +async def waits_for_a_crawl(ctx: sessions.SessionContext) -> list[Any]: + """Waits longer than the inactivity timeout for a call, which a retry finds by its idempotency key.""" + attempt(ctx) + crawled = await ctx.call(crawl, idempotency_key=ctx.request.id) + return [crawled, attempts[ctx.key]] + + +@slowpoke.handler() +async def thinks(ctx: sessions.SessionContext) -> int: + """Works locally longer than the inactivity timeout, inside an annotation.""" + n = attempt(ctx) + timed = internal.annotate(ctx, "model: thinking") + await asyncio.sleep(2.5) + timed.end() + return n + + +@slowpoke.handler() +async def daydreams(ctx: sessions.SessionContext) -> int: + """Works locally longer than the inactivity timeout, telling Restate nothing.""" + n = attempt(ctx) + await asyncio.sleep(2.5) + daydreamt[ctx.key] = daydreamt.get(ctx.key, 0) + 1 + return n + + +daydreamt: dict[str, int] = {} +"""The attempts of ``daydreams`` that finished their local work.""" + + @pytest.fixture(scope="session") async def harness(): async with restate.create_test_harness( - restate.app([inbox, pricing, sleeper, notes]), restate_image=RESTATE_IMAGE + restate.app([inbox, pricing, sleeper, crawler, notes, slowpoke]), restate_image=RESTATE_IMAGE ) as harness: yield harness @@ -262,3 +338,69 @@ async def test_a_view_cancels_a_handler_of_its_own_object(harness: HarnessEnviro answer = await attach(harness, sent.invocation_id) assert answer.status_code == 200, answer.text assert await harness.client.object_call(texts, key=key, arg=None) == ["stopped: nap"] + + +async def query(harness: HarnessEnvironment, sql: str) -> list[dict[str, Any]]: + async with httpx2.AsyncClient() as admin: + response = await admin.post( + f"{harness.admin_api_url}/query", json={"query": sql}, headers={"Accept": "application/json"} + ) + response.raise_for_status() + return typing.cast("list[dict[str, Any]]", response.json().get("rows", [])) + + +async def test_the_journal_has_no_sync_run_and_names_trace_parents(harness: HarnessEnvironment): + key = str(uuid.uuid4()) + sent = await harness.client.object_send(nested, key=key, arg=None) + assert (await attach(harness, sent.invocation_id)).status_code == 200 + journal = await query( + harness, f"SELECT index, entry_type, name FROM sys_journal WHERE id = '{sent.invocation_id}' ORDER BY index" + ) + names = [entry.get("name") for entry in journal] + # The commit syncs with the ack of its head, not with a run. + assert "sync" not in names, journal + assert "v22/head" in names, journal + assert "turn" in names, journal + parent = next(n for n in names if n and n.startswith("model")) + assert parent.startswith("model (parent trace "), journal + + +async def test_a_cancellation_fails_the_awaits_and_cancels_the_calls(harness: HarnessEnvironment): + key = str(uuid.uuid4()) + sent = await harness.client.object_send(waits_for_a_nap, key=key, arg=None) + await cancel_when_running(harness, sent.invocation_id) + assert (await attach(harness, sent.invocation_id)).status_code == 409 + [nap_id] = await harness.client.object_call(texts, key=key, arg=None) + assert (await attach(harness, nap_id)).status_code == 409 + + +async def test_a_shut_down_attempt_resumes_when_its_call_completes(harness: HarnessEnvironment): + key = str(uuid.uuid4()) + crawled, n = await harness.client.object_call(waits_for_a_crawl, key=key, arg=None) + assert crawled == "crawled" + # The first attempt was shut down while it waited, and the next one found the call's result. + assert n >= 2 + + +async def test_an_open_annotation_keeps_the_attempt_alive(harness: HarnessEnvironment, monkeypatch): + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.3)) + key = str(uuid.uuid4()) + assert await harness.client.object_call(thinks, key=key, arg=None) == 1 + + +async def test_local_work_without_an_annotation_is_shut_down_and_restarted(harness: HarnessEnvironment): + key = str(uuid.uuid4()) + sent = await harness.client.object_send(daydreams, key=key, arg=None) + # Each attempt is shut down after a second with nothing pending, and restarted right away. + for _ in range(300): + if attempts.get(key, 0) >= 4: + break + await asyncio.sleep(0.1) + # More attempts than the retry policy allows: the restarts don't count against it. + assert attempts.get(key, 0) >= 4 + status = await query(harness, f"SELECT status FROM sys_invocation WHERE id = '{sent.invocation_id}'") + async with httpx2.AsyncClient() as admin: + (await admin.patch(f"{harness.admin_api_url}/invocations/{sent.invocation_id}/kill")).raise_for_status() + assert status and status[0]["status"] != "paused", status + # The shutdown stopped each attempt's local work. + assert daydreamt.get(key, 0) == 0 diff --git a/tests/sessions_object.py b/tests/sessions_object.py index 7b0e4ca6..e4099935 100644 --- a/tests/sessions_object.py +++ b/tests/sessions_object.py @@ -570,15 +570,15 @@ async def explicit(ctx: sessions.SessionContext) -> None: await run(obj, "explicit", Host(Backend(), service="cancelling")) -async def test_cancelled_ends_its_waiter_cancelled_when_the_attempt_ends_first(monkeypatch): - from restate import _preview # pylint: disable=import-outside-toplevel - from restate.exceptions import SuspendedException # pylint: disable=import-outside-toplevel +async def test_cancelled_ends_its_waiter_cancelled_when_the_attempt_ends_first(): from restate.sessions import _object, _scope # pylint: disable=import-outside-toplevel - async def attempt_ended(_sdk: Any) -> None: - raise SuspendedException() + class Attempt: + """The part of the attempt's driver ``cancelled`` reads: the cancellation, which the attempt's end cancels.""" + + def __init__(self) -> None: + self.cancellation: asyncio.Future[None] = asyncio.get_running_loop().create_future() - monkeypatch.setattr(_preview, "cancellation", attempt_ended) host = Host(Backend()) ctx = _object.AttemptContext( key="k", @@ -588,8 +588,11 @@ async def attempt_ended(_sdk: Any) -> None: _send_sink=lambda send: None, _cancel=lambda invocation_id: None, ) - _scope.SCOPE.on(ctx, _scope.Scope(sdk=typing.cast(Any, object()), explicit_cancellation=True)) + attempt = Attempt() + _scope.SCOPE.on(ctx, _scope.Scope(driver=typing.cast(Any, attempt), explicit_cancellation=True)) watcher = asyncio.ensure_future(internal.cancelled(ctx)) + await asyncio.sleep(0) + attempt.cancellation.cancel() await asyncio.wait({watcher}) # Cancelled, not failed: asyncio reports no exception nobody retrieved. assert watcher.cancelled() @@ -724,3 +727,56 @@ async def use(ctx: sessions.SessionContext) -> None: gc.collect() # Nothing of this package's holds an attempt's database (and so the attempt) past it. assert kept[0]() is None + + +async def test_a_request_response_transport_is_refused_before_the_handler_runs(): + from restate.server_types import ReceiveChannel # pylint: disable=import-outside-toplevel + + obj = sessions.SessionObject("transported") + ran = False + + @obj.handler + async def handle(ctx: sessions.SessionContext) -> None: + nonlocal ran + ran = True + + events = iter( + [ + # Restate's whole request, then the end of the body: nothing the VM waits for. + {"type": "http.request", "body": b"", "more_body": False}, + {"type": "http.disconnect"}, + ] + ) + + async def receive() -> Any: + event = next(events, None) + if event is None: + await asyncio.Event().wait() + return event + + sent: list[dict[str, Any]] = [] + + async def send(message: Any) -> None: + sent.append(message) + + handler = obj.handlers["handle"] + assert handler.attempt_runner is not None + channel = ReceiveChannel(receive) + try: + await handler.attempt_runner( + handler, + request_headers=[("content-type", "application/vnd.restate.invocation.v7")], + attempt_headers={}, + receive=channel, + send=send, + bidirectional=False, + server_headers=[], + ) + finally: + await channel.close() + assert not ran + assert sent[0]["type"] == "http.response.start" and sent[0]["status"] == 200 + # The error that pauses the invocation, then the end of the response. + bodies = [message for message in sent[1:] if message["type"] == "http.response.body"] + assert bodies[0]["body"], sent + assert bodies[-1] == {"type": "http.response.body", "body": b"", "more_body": False} diff --git a/tests/sessions_selector.py b/tests/sessions_selector.py deleted file mode 100644 index fd8f411b..00000000 --- a/tests/sessions_selector.py +++ /dev/null @@ -1,492 +0,0 @@ -# -# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH -# -# This file is part of the Restate SDK for Python, -# which is released under the MIT license. -# -# You can find a copy of the license in file LICENSE in the root -# directory of this repository or package, or at -# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE -# -"""The selector of an invocation without journal replay, against a fake VM.""" - -# pylint: disable=missing-function-docstring - -import asyncio -from collections.abc import Mapping -from typing import Any - -import pytest -from restate.exceptions import SdkInternalException, SuspendedException, TerminalError -from restate.vm import ( - CANCEL_HANDLE, - AllCompletedUnresolvedFuture, - DoProgressAnyCompleted, - DoProgressCancelSignalReceived, - DoProgressExecuteRun, - DoProgressWaitExternalProgress, - FirstCompletedUnresolvedFuture, - SingleUnresolvedFuture, - Suspended, - UnresolvedFuture, -) -from restate.sessions._selector import FutureSelector, is_ready - - -@pytest.fixture(scope="session") -def anyio_backend(): - return "asyncio" - - -pytestmark = [pytest.mark.anyio] - - -class Disconnected(Exception): - pass - - -class FakeVm: - """ - A VM with the shared core's rules for ``do_progress``, as far as the - selector sees them (sdk-shared-core, ``src/vm/transitions/async_results.rs``). - - A body chunk b"3" brings in the result of handle 3, which a check takes in - (``completed``) only while its future is not resolved. A check whose - future is resolved returns ``AnyCompleted``; else it hands out a run of the - future that has not started (``ExecuteRun``); else, with the input closed - and no run of the future executing, it suspends the invocation on the - future; else it waits. - """ - - def __init__(self) -> None: - self.completed: set[int] = set() - # What came in and no check took in yet, in order. - self.arrived: list[int] = [] - self.input: asyncio.Queue[dict[str, Any]] = asyncio.Queue() - self.checks: list[UnresolvedFuture] = [] - # The checks of the cancellation alone: each would tell Restate that the handler waits for it, and - # suspend the invocation on it once the input closed. - self.alone: list[UnresolvedFuture] = [] - # Responses that do_progress gives before looking at the handles. - self.script: list[Any] = [] - # Runs not yet handed out, and those executing. - self.to_execute: set[int] = set() - self.executing: set[int] = set() - self.input_closed = False - self.suspended_on: UnresolvedFuture | None = None - self.runs: list[int] = [] - self.work_handle: int | None = None - self.work_ended: list[int] = [] - self.wakes = 0 - self.ended = 0 - self.tasks: list[asyncio.Future] = [] - - def do_progress(self, future: UnresolvedFuture) -> Any: - if self.suspended_on is not None: - return ValueError("closed") - self.checks.append(future) - if all(handle == CANCEL_HANDLE for handle in leaves(future)): - self.alone.append(future) - if self.script: - return self.script.pop(0) - while not is_ready(future, self.is_completed) and self.arrived: - self.completed.add(self.arrived.pop(0)) - if is_ready(future, self.is_completed): - return DoProgressAnyCompleted() - for handle in leaves(future): - if handle in self.to_execute: - self.to_execute.discard(handle) - self.executing.add(handle) - return DoProgressExecuteRun(handle) - if self.input_closed and not any(handle in self.executing for handle in leaves(future)): - self.suspended_on = future - return Suspended() - return DoProgressWaitExternalProgress() - - def is_completed(self, handle: int) -> bool: - return handle in self.completed - - async def flush_output(self) -> None: - pass - - async def receive(self) -> dict[str, Any]: - return await self.input.get() - - def wake(self) -> None: - self.wakes += 1 - self.input.put_nowait({"type": "restate.wake"}) - - def execute_run(self, handle: int) -> None: - self.runs.append(handle) - if handle == self.work_handle: - return - self.executing.discard(handle) - self.completed.add(handle) - self.input.put_nowait({"type": "restate.run_completed"}) - - def work(self) -> int: - if self.work_handle is None: - self.work_handle = WORK - self.to_execute.add(WORK) - return self.work_handle - - def end_work(self) -> None: - if self.work_handle is not None: - self.work_ended.append(self.work_handle) - self.work_handle = None - - def notify_input(self, chunk: Mapping[str, Any]) -> None: - if chunk.get("body"): - self.arrived.append(int(chunk["body"])) - if not chunk.get("more_body", False): - self.input_closed = True - - def track(self, task: asyncio.Future) -> None: - self.tasks.append(task) - - def on_end(self) -> None: - self.ended += 1 - - def complete(self, handle: int) -> None: - self.input.put_nowait({"type": "http.request", "body": str(handle).encode(), "more_body": True}) - - def close_input(self, handle: int | None = None) -> None: - """Close the input, with the result of ``handle`` in its last chunk if given.""" - body = b"" if handle is None else str(handle).encode() - self.input.put_nowait({"type": "http.request", "body": body, "more_body": False}) - - -WORK = 9999 -"""The handle the fake VM gives the working run.""" - - -def leaves(future: UnresolvedFuture) -> list[int]: - if isinstance(future, SingleUnresolvedFuture): - return [future.handle] - return [handle for child in future.children for handle in leaves(child)] - - -def single(handle: int) -> SingleUnresolvedFuture: - return SingleUnresolvedFuture(handle) - - -async def settle() -> None: - for _ in range(5): - await asyncio.sleep(0) - - -async def test_a_ready_future_needs_no_loop(): - vm = FakeVm() - vm.completed.add(11) - selector = FutureSelector(vm, Disconnected) - await selector.wait(single(11)) - assert vm.checks == [] - - -async def test_concurrent_waits_share_one_await_point(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - both = asyncio.ensure_future(asyncio.gather(selector.wait(single(11)), selector.wait(single(12)))) - await settle() - # One check, of the first of both to complete. - assert vm.checks == [FirstCompletedUnresolvedFuture([single(11), single(12)])] - vm.complete(12) - await settle() - assert not both.done() - vm.complete(11) - await both - assert selector.size == 0 - - -async def test_a_wait_made_while_the_loop_waits_for_input_joins_the_next_check(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - first = asyncio.ensure_future(selector.wait(single(11))) - await settle() - assert vm.checks == [single(11)] - second = asyncio.ensure_future(selector.wait(single(12))) - await settle() - assert vm.wakes == 1 - assert vm.checks[-1] == FirstCompletedUnresolvedFuture([single(11), single(12)]) - # A third wait while the loop waits again wakes it once more, not once per wait. - third = asyncio.ensure_future(selector.wait(single(13))) - await settle() - assert vm.wakes == 2 - for handle in (13, 12, 11): - vm.complete(handle) - await asyncio.gather(first, second, third) - - -async def test_a_wait_made_while_the_loop_flushes_is_checked_before_it_waits_for_input(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - late: list[asyncio.Future] = [] - - async def flush_letting_a_wait_register() -> None: - if not late: - late.append(asyncio.ensure_future(selector.wait(single(12)))) - await asyncio.sleep(0) - await asyncio.sleep(0) - - vm.flush_output = flush_letting_a_wait_register # type: ignore[method-assign] - first = asyncio.ensure_future(selector.wait(single(11))) - await settle() - await settle() - # Not left out of the check the loop was making while it registered, nor waiting for input or a wake. - assert vm.checks[-1] == FirstCompletedUnresolvedFuture([single(11), single(12)]) - vm.complete(12) - vm.complete(11) - await asyncio.gather(first, *late) - - -async def test_combinators_wait_for_their_children(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - every = asyncio.ensure_future(selector.wait(AllCompletedUnresolvedFuture([single(11), single(12)]))) - vm.complete(11) - await settle() - assert not every.done() - vm.complete(12) - await every - - -async def test_a_cancellation_reaches_every_pending_wait_and_only_those(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - waits = [asyncio.ensure_future(selector.wait(single(h))) for h in (11, 12)] - await settle() - vm.script.append(DoProgressCancelSignalReceived()) - vm.complete(9) - for wait in waits: - with pytest.raises(TerminalError) as error: - await wait - assert error.value.status_code == 409 - # What waits after it is not cancelled. - later = asyncio.ensure_future(selector.wait(single(13))) - vm.complete(13) - await later - - -async def test_a_suspension_ends_every_wait_now_and_later(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - vm.script.append(Suspended()) - with pytest.raises(SuspendedException): - await selector.wait(single(11)) - assert isinstance(selector.ended, SuspendedException) - assert vm.ended == 1 - with pytest.raises(SuspendedException): - await selector.wait(single(12)) - - -async def test_an_error_of_the_vm_ends_the_attempt(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - vm.script.append(ValueError("journal mismatch")) - with pytest.raises(SdkInternalException) as error: - await selector.wait(single(11)) - assert isinstance(error.value.__cause__, ValueError) - - -async def test_a_disconnect_ends_the_attempt(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - wait = asyncio.ensure_future(selector.wait(single(11))) - await settle() - vm.input.put_nowait({"type": "http.disconnect"}) - with pytest.raises(Disconnected): - await wait - - -async def test_a_run_is_started_and_its_completion_wakes_the_loop(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - vm.script.append(DoProgressExecuteRun(7)) - await selector.wait(single(7)) - assert vm.runs == [7] - - -async def test_the_loop_stops_when_nothing_is_pending_and_starts_again(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - first = asyncio.ensure_future(selector.wait(single(11))) - vm.complete(11) - await first - await settle() - assert all(task.done() for task in vm.tasks) - second = asyncio.ensure_future(selector.wait(single(12))) - vm.complete(12) - await second - assert len(vm.tasks) == 2 - - -# --- The cancellation awaited alone, as a handler that works outside Restate awaits it ------------------------------- - -CANCELLATION = single(CANCEL_HANDLE) -WATCHING = FirstCompletedUnresolvedFuture([CANCELLATION, single(WORK)]) -"""A check of the cancellation alone: with the working run, which stands for the handler's work.""" - - -async def test_the_cancellation_alone_is_asked_for_with_the_working_run_and_settles_when_it_comes(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - # The first check starts the working run, the second waits: never for the cancellation alone. - assert vm.checks == [WATCHING, WATCHING] - assert vm.runs == [WORK] - assert vm.alone == [] - vm.complete(CANCEL_HANDLE) - await cancelled - assert selector.ended is None - - -async def test_the_cancellation_alone_does_not_suspend_once_the_input_closed(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - vm.close_input() - await settle() - assert vm.suspended_on is None - assert selector.ended is None - assert vm.alone == [] - assert not cancelled.done() - - -async def test_the_cancellation_alone_does_not_suspend_if_the_input_closed_before_it_was_awaited(): - vm = FakeVm() - vm.input_closed = True - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - assert vm.suspended_on is None - assert selector.ended is None - assert vm.runs == [WORK] - assert vm.alone == [] - assert not cancelled.done() - - -async def test_what_is_awaited_after_the_input_closed_suspends_with_the_cancellation_without_the_working_run(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - vm.close_input() - await settle() - with pytest.raises(SuspendedException): - await selector.wait(single(20)) - assert vm.suspended_on == FirstCompletedUnresolvedFuture([CANCELLATION, single(20)]) - with pytest.raises(SuspendedException): - await cancelled - - -async def test_a_run_awaited_after_the_input_closed_settles_in_the_same_attempt(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - vm.close_input() - await settle() - vm.to_execute.add(21) - await selector.wait(single(21)) - await settle() - assert vm.runs == [WORK, 21] - assert vm.suspended_on is None - assert selector.ended is None - assert not cancelled.done() - - -async def test_a_cancel_signal_that_came_as_the_input_closed_settles_the_cancellation_at_once(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - vm.close_input(CANCEL_HANDLE) - await cancelled - assert vm.suspended_on is None - assert selector.ended is None - - -async def test_a_combinator_over_the_cancellation_and_something_else_suspends_on_both(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - either = FirstCompletedUnresolvedFuture([CANCELLATION, single(40)]) - wait = asyncio.ensure_future(selector.wait(either)) - await settle() - vm.close_input() - with pytest.raises(SuspendedException): - await wait - assert vm.suspended_on == either - assert vm.work_handle is None - - -async def test_close_fails_the_watch_ends_the_working_run_and_stops_the_loop(): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - cancelled = asyncio.ensure_future(selector.wait(CANCELLATION)) - await settle() - selector.close() - with pytest.raises(SuspendedException): - await cancelled - assert vm.work_ended == [WORK] - await settle() - assert all(task.done() for task in vm.tasks) - # A handler that never watched has no working run to end. - other = FakeVm() - FutureSelector(other, Disconnected).close() - assert other.work_ended == [] - - -async def test_the_cancellation_is_never_asked_for_alone_whatever_else_comes_and_goes(): - seed = 11 - - def random() -> float: - nonlocal seed - seed = (seed * 1103515245 + 12345) % 2**31 - return seed / 2**31 - - suspended = worked = 0 - for round_ in range(150): - vm = FakeVm() - selector = FutureSelector(vm, Disconnected) - waits: dict[int, asyncio.Future] = {} - close_at = int(random() * 60) - watch_at = int(random() * 30) - handle = 100 - for step in range(60): - if vm.suspended_on is not None: - break - if step == watch_at: - waits[CANCEL_HANDLE] = asyncio.ensure_future(selector.wait(CANCELLATION)) - if step == close_at: - vm.close_input() - x = random() - if x < 0.25: - handle += 1 - # Every other round, the handler awaits runs only: with the input closed, anything else suspends it. - if round_ % 2 == 0 or random() < 0.5: - vm.to_execute.add(handle) - waits[handle] = asyncio.ensure_future(selector.wait(single(handle))) - elif x < 0.5: - # Once the input closed, nothing comes in. - open_ = [h for h in waits if h not in (CANCEL_HANDLE,) and h not in vm.to_execute] - if open_ and not vm.input_closed: - vm.complete(open_[int(random() * len(open_))]) - if random() < 0.6: - await asyncio.sleep(0) - for _ in range(20): - await asyncio.sleep(0) - assert vm.alone == [] - on = vm.suspended_on - # It suspends only on something else the handler waits for. - assert on is None or any(h != CANCEL_HANDLE for h in leaves(on)) - if on is not None: - suspended += 1 - elif vm.input_closed: - worked += 1 - selector.close() - await asyncio.gather(*waits.values(), return_exceptions=True) - # Both outcomes came up. - assert suspended > 10 - assert worked > 10 From b8216fbfcec3f923212b6b3814443fcdec1bed00 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:51:45 +0000 Subject: [PATCH 02/11] Sessions: a cancellation reaches the handler once, and a cancelled ctx.db call did nothing On the explicit recovery VM a cancellation failed only the awaits pending in the driver when it came. One that arrived with nothing pending was dropped: a handler working outside Restate, or one whose database call was under way, never saw it, and neither did the attempt that follows a cancelled one. With a journal codec, where the database's store goes through Python, it failed the store's reads and the ack of a commit instead, so a commit could land and report as cancelled. The driver now carries a cancellation that failed nothing the handler awaits to its next await, once: a result of Restate's, or a call of `ctx.db`. An invocation id is never the one it is carried to, as it is not what a cancellation fails. `ctx.db` takes the carry where the handler calls it (`Attempt.asked`): its statements, its `transaction()`, and a schema it ensures, before the call issues anything. What the session does for itself does not pass through there: the open, the object's schema, the sends a crashed attempt left, emptying the outbox after a commit, the save at the end. And the store's reads and acks are left to settle on both stores. So the rule is one rule, the same as @restatedev/sessions: a `ctx.db` call that raises the cancellation did nothing, and one already under way runs to its end. `Database`'s docstring states it. A test's own host needs no change: `take_cancellation` is optional. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- python/restate/sessions/_api.py | 28 ++++++++++ python/restate/sessions/_driver.py | 82 ++++++++++++++++++++++++----- python/restate/sessions/_object.py | 4 +- python/restate/sessions/_session.py | 34 +++++++++++- 4 files changed, 133 insertions(+), 15 deletions(-) diff --git a/python/restate/sessions/_api.py b/python/restate/sessions/_api.py index 488e6d33..8deb48a8 100644 --- a/python/restate/sessions/_api.py +++ b/python/restate/sessions/_api.py @@ -266,6 +266,31 @@ class Database(DatabaseWriter, Protocol): Each statement outside ``transaction()`` is a transaction of its own, durable once its call returns. Calls run one at a time, in call order. + + A cancellation of the invocation reaches the handler once, at an await, + which raises ``TerminalError("cancelled", 409)`` (unless the handler has + ``explicit_cancellation``). The awaits of Restate pending when it comes + fail, a call or an attached invocation, and the calls under way are + cancelled. A call of the database is treated differently, so that its + failure means one thing: a call already under way when the cancellation + comes runs to its end, and the cancellation goes to what the handler + awaits next; a call of the database that raises the cancellation was + refused before it began. So the cancellation from ``ctx.db`` says the call + did nothing: it wrote nothing, and a ``transaction()`` neither committed + nor made its sends. A transaction that returns committed, and its sends + are made, once. + + What the handler awaits after the cancellation works, so it can + compensate, or make the call again:: + + try: + async with ctx.db.transaction() as tx: + ... + except restate.TerminalError as cancelled: + if cancelled.status_code != 409: + raise + await ctx.db.execute("UPDATE orders SET status = 'cancelled' WHERE id = ?", [order]) + raise """ def transaction(self) -> typing.AsyncContextManager[Transaction]: @@ -292,6 +317,9 @@ class SessionContext(Caller, Sender, Protocol): suspension, Restate starts a new attempt, which runs the handler from the start and finds what earlier attempts committed. Its operations may be awaited together, with ``asyncio.gather`` or ``asyncio.wait``. + + A cancellation reaches the handler once (see ``Database``). An attempt + that follows a cancelled one gets it at its first await. """ @property diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py index 64cbb0e8..2db5dc32 100644 --- a/python/restate/sessions/_driver.py +++ b/python/restate/sessions/_driver.py @@ -120,8 +120,14 @@ def __init__( self._explicit_cancellation: bool = explicit_cancellation self._loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() self._futures: dict[int, asyncio.Future[Any]] = {} - # The invocation ids of the calls and sends, which a cancellation leaves to settle. - self._invocation_ids: set[int] = set() + # The handles a cancellation leaves to settle, and is never carried to: the invocation + # ids of the calls and sends, and the reads and acks of the database's store. + self._left_to_settle: set[int] = set() + # A cancellation that failed nothing the handler awaits, carried to the next thing it + # does: a result of Restate's (``future``), or a call of its database + # (``take_carried_cancellation``). A retry of a cancelled invocation knows of it before + # the handler starts, and its first await fails all the same. There is one carry, here. + self._carried_cancellation: bool = False self.calls: list[_CallFuture] = [] # The cancellation of the calls whose invocation id a cancellation waits for. self._cancelling: asyncio.Future[Any] | None = None @@ -288,7 +294,7 @@ def _tick(self) -> None: try: while (notification := self.vm.take_notification()) is not None: handle, value = notification - self._invocation_ids.discard(handle) + self._left_to_settle.discard(handle) future = self._futures.pop(handle, None) if future is not None: _settle(future, value) @@ -353,7 +359,40 @@ def act(self, f: Callable[[PyExplicitRecoveryVM], T]) -> T: self.schedule() def future(self, handle: int) -> asyncio.Future[Any]: - """The future the notification of ``handle`` settles.""" + """The future the notification of ``handle`` settles: a result the handler awaits. + + A carried cancellation fails it, once. + """ + if self.ended is None and self._carried_cancellation: + self._carried_cancellation = False + future = _quiet(self._loop.create_future()) + future.set_exception(_cancelled_error()) + return future + return self._future(handle) + + def invocation_id_future(self, handle: int) -> asyncio.Future[Any]: + """The future of a call's or send's invocation id, which a cancellation leaves to settle. + + Cancelling the call needs it; and a handler rarely awaits it, so a cancellation carried + to it would be lost. + """ + self._left_to_settle.add(handle) + return self._future(handle) + + def store_future(self, handle: int) -> asyncio.Future[Any]: + """The future of a read or an ack of the database's store, which a cancellation leaves to settle. + + Restate answers those promptly, and failing the ack of a commit whose writes are out + would report as cancelled a commit that landed. A call of the database gets a + cancellation only as the handler makes it, before it issues anything (see + ``Attempt.asked``); one under way runs to its end. The store's waits in Rust + (``wait_in_rust``) are left alone in the same way: this is the store of an endpoint + with a journal codec. + """ + self._left_to_settle.add(handle) + return self._future(handle) + + def _future(self, handle: int) -> asyncio.Future[Any]: future = _quiet(self._loop.create_future()) if self.ended is not None: future.set_exception(self.ended) @@ -361,10 +400,14 @@ def future(self, handle: int) -> asyncio.Future[Any]: self._futures[handle] = future return future - def invocation_id_future(self, handle: int) -> asyncio.Future[Any]: - """The future of a call's or send's invocation id, which a cancellation leaves to settle.""" - self._invocation_ids.add(handle) - return self.future(handle) + def take_carried_cancellation(self) -> bool: + """Whether a cancellation is owed to the handler's next await, taking it. + + The caller delivers it: the handler's call of its database, before it issues anything, + so that a call that fails with the cancellation did nothing. + """ + carried, self._carried_cancellation = self._carried_cancellation, False + return carried def _cancelled(self) -> None: """Restate cancelled the invocation.""" @@ -379,12 +422,16 @@ def _cancelled(self) -> None: with contextlib.suppress(SdkInternalBaseException): self.act(operator.methodcaller("cancel_invocation", call.known_invocation_id())) self._cancelling = _quiet(asyncio.ensure_future(self.cancel_calls())) - cancelled = TerminalError("cancelled", 409) + cancelled = _cancelled_error() + failed_a_result = False for handle, future in list(self._futures.items()): - if handle not in self._invocation_ids: + if handle not in self._left_to_settle: del self._futures[handle] if not future.done(): future.set_exception(cancelled) + failed_a_result = True + # Carried only if nothing the handler awaits was failed: it is then still owed its one. + self._carried_cancellation = not failed_a_result async def cancel_calls(self) -> list[str]: """Cancel the calls of the attempt that have not completed; return their invocation ids.""" @@ -423,6 +470,11 @@ async def _heartbeat(self) -> None: return +def _cancelled_error() -> TerminalError: + """What an await fails with when Restate cancelled the invocation, as the SDK's own awaits do.""" + return TerminalError("cancelled", 409) + + def _failure_of(error: TerminalError) -> Any: return PyFailure(error.status_code, error.message, None, list((error.metadata or {}).items()) or None) @@ -506,7 +558,7 @@ def vm(self) -> PyExplicitRecoveryVM | None: def get(self, key: str) -> Awaitable[bytes | None]: handle = self.driver.act(lambda vm: vm.get_state(key, key)) - read = self.driver.future(handle) + read = self.driver.store_future(handle) codec = self._codec if codec is None: return read @@ -528,12 +580,16 @@ def clear(self, key: str) -> None: def state_keys(self) -> Awaitable[list[str]]: # Named under the state format's prefix, which tooling hides. handle = self.driver.act(lambda vm: vm.get_state_keys("v22/keys")) - return self.driver.future(handle) + return self.driver.store_future(handle) def sync(self) -> Awaitable[Any]: """Clear ``SYNC_KEY`` with an ack: once acked, every earlier write is stored too.""" handle = self.driver.act(lambda vm: vm.clear_state(SYNC_KEY, SYNC_KEY, True)) - return self.driver.future(handle) + return self.driver.store_future(handle) + + def take_cancellation(self) -> bool: + """Whether a cancellation is owed to the handler's next await, taking it (see ``Attempt.asked``).""" + return self.driver.take_carried_cancellation() def attempt_end(self) -> BaseException | None: return self.driver.ended diff --git a/python/restate/sessions/_object.py b/python/restate/sessions/_object.py index ea687b13..f40e6484 100644 --- a/python/restate/sessions/_object.py +++ b/python/restate/sessions/_object.py @@ -569,7 +569,9 @@ async def add(ctx: sessions.SessionContext, text: str) -> None: Args: name: The handler's name. Defaults to the function's name. explicit_cancellation: If true, cancelling the invocation neither - fails its awaits nor cancels its calls. The handler learns of + fails its awaits nor cancels its calls (without it, a + cancellation cancels the calls under way and fails one await, + once: see ``Database``). The handler learns of the cancellation with ``internal.cancelled(ctx)`` and decides what to stop, for example its calls with ``internal.cancel_calls(ctx)`` (from diff --git a/python/restate/sessions/_session.py b/python/restate/sessions/_session.py index e9abc5d7..d0c85170 100644 --- a/python/restate/sessions/_session.py +++ b/python/restate/sessions/_session.py @@ -60,6 +60,10 @@ class SqlHost(CallHost, Protocol): """The host that an attempt's database runs on: the handler's context, or a test's fake. Implement it to run handlers without Restate, with ``internal.invoke``. + + A host may also have ``take_cancellation() -> bool``: whether a cancellation + is owed to the handler's next await, taking it (see ``Attempt.asked``). A + host without it never has one. """ @property @@ -380,6 +384,7 @@ def __init__(self, attempt: Attempt) -> None: _ATTEMPT.on(self, attempt) async def query_columns(self, sql: str, params: Sequence[SqlParam] | None = None) -> tuple[list[str], Rows]: + self._attempt.asked() return await self._attempt.call(lambda db: db.query_columns(sql, params)) def transaction(self) -> typing.AsyncContextManager[Transaction]: @@ -559,8 +564,33 @@ def __init__(self, host: SqlHost, config: ObjectConfig | None = None, name: str ensuring(self.db, self._ensure) async def _ensure(self, schemas: Sequence[Schema]) -> None: + self.asked() await self.call(lambda db: self._ensure_schemas(db, schemas)) + def asked(self) -> None: + """The handler asked for a call of its database: fail it if a cancellation is owed to it. + + This is where the database delivers a cancellation, and the only place. + What the handler asks for passes through here: ``ctx.db``'s statements, + its ``transaction()``, and a schema it ensures. What the session does for + itself does not: the open, the object's schema, the sends a crashed + attempt left unmade, emptying the outbox after a commit, and the save at + the handler's end. A cancellation that failed one of those would be + delivered to nobody, or would report a transaction as cancelled after it + committed. + + And it is before the call issues anything. So a call of the database + that fails with the cancellation wrote nothing and sent nothing; a call + already under way when the cancellation arrives runs to its end, and the + cancellation goes to what the handler awaits next. + + Raises: + TerminalError: The cancellation (``"cancelled"``, 409), once. + """ + take = getattr(self._host, "take_cancellation", None) + if take is not None and take(): + raise TerminalError("cancelled", 409) + def database(self, name: str) -> Database: """Return the key's separate database ``name`` for this attempt (see ``database``).""" if self._ended: @@ -620,12 +650,14 @@ async def transaction(self) -> AsyncGenerator[AttemptTransaction, None]: commit, right after its writes and before it waits for anything (see ``with_commit``). Since Restate stores an attempt's commands in order, the sends are stored only if the commit is, and anything that fails the - commit's wait (a cancellation, say) comes after them. A second commit + commit's wait (the attempt's end, say) comes after them. A second commit empties the outbox before the transaction returns. If the sends stayed until the handler's end, an attempt that resumes after a long wait could make them again after the idempotency retention has expired, so that the duplicates would no longer be dropped. """ + # Before the session opens or the transaction begins: see ``asked``. + self.asked() outgoing: Outgoing | None = None session = self._current() try: From 63be86532d509ae44030bf0405a4e825dad83b42 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:51:45 +0000 Subject: [PATCH 03/11] Sessions tests: a handler that cancels itself in its transaction, then compensates Against a real server, on both stores: the handler sees one cancellation, its transaction committed and made its send, and the compensation is stored exactly once, made again where the cancellation reached it. A cancelled call that had landed would show as a second row. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- tests/sessions_harness.py | 67 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/tests/sessions_harness.py b/tests/sessions_harness.py index 46269a70..93a15126 100644 --- a/tests/sessions_harness.py +++ b/tests/sessions_harness.py @@ -166,6 +166,55 @@ async def waits_for_a_nap(ctx: sessions.SessionContext) -> str: return await napping +@sleeper.handler() +async def doze(ctx: restate.Context) -> str: + await asyncio.sleep(0.5) + return "dozed" + + +@notes.handler() +async def cancels_itself(ctx: sessions.SessionContext, text: str) -> int: + """Cancels itself inside its transaction, then compensates in its database. + + The cancellation reaches one await of the handler's, once. A call of the + database that it fails did nothing, and one already under way when it + arrives runs to its end: so the transaction, which issued the cancellation, + committed and its send is made; and the compensation is stored exactly + once, by the call itself or, where the cancellation reached that call, by + making it again. A cancelled call that had landed would show as a second + row. The result: how many awaits failed with the cancellation. + """ + cancellations = 0 + + async def counting(step: typing.Callable[[], typing.Awaitable[Any]]) -> bool: + """Whether ``step`` failed with the cancellation.""" + nonlocal cancellations + try: + await step() + return False + except restate.TerminalError as error: + if error.status_code != 409: + raise + cancellations += 1 + return True + + async def commit() -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO notes (text) VALUES (?)", [text]) + tx.send(deliver, text, key=ctx.key) + ctx.cancel(ctx.request.id) + + async def compensate() -> None: + await ctx.db.execute("INSERT INTO notes (text) VALUES (?)", [f"undone: {text}"]) + + await counting(lambda: ctx.db.get("SELECT count(*) AS n FROM notes")) + await counting(commit) + if await counting(compensate): + await compensate() + await counting(lambda: ctx.call(doze)) # by now, the cancellation came + return cancellations + + @notes.handler() async def nested(ctx: sessions.SessionContext) -> None: """Times a model request inside a turn.""" @@ -374,6 +423,24 @@ async def test_a_cancellation_fails_the_awaits_and_cancels_the_calls(harness: Ha assert (await attach(harness, nap_id)).status_code == 409 +async def test_a_cancellation_fails_one_await_once_and_a_cancelled_call_of_the_database_did_nothing( + harness: HarnessEnvironment, +): + for _ in range(5): + key = str(uuid.uuid4()) + assert await harness.client.object_call(cancels_itself, key=key, arg="x") == 1 + # The transaction, and the compensation, once each. + assert await harness.client.object_call(texts, key=key, arg=None) == ["x", "undone: x"] + # The transaction's send went out, though the invocation was cancelled. + delivered: list[str] = [] + for _ in range(50): + delivered = await harness.client.object_call(messages, key=key, arg=None) + if delivered: + break + await asyncio.sleep(0.1) + assert delivered == ["x"] + + async def test_a_shut_down_attempt_resumes_when_its_call_completes(harness: HarnessEnvironment): key = str(uuid.uuid4()) crawled, n = await harness.client.object_call(waits_for_a_crawl, key=key, arg=None) From 0ad587d05fd1007649959ff1718b7f150f40664b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:56:03 +0000 Subject: [PATCH 04/11] Sessions tests: an attempt driven on the wire, and where a cancellation lands Until now the driver was only tested against a real server, where the moment a cancel signal arrives cannot be chosen. `sessions_wire` plays Restate's side of the service protocol in process: it answers state reads from a dict, stores the writes, acks what asks for an ack, and answers calls. It can send the cancel signal while a commit waits for its ack, with nothing waiting, or as an entry an earlier attempt left. `sessions_driver` runs on both stores: - a commit under way when the signal arrives lands, and says so; - the cancellation then fails the await after it, once; - an attempt that follows a cancelled one fails its first call; - a carried cancellation fails the next call of the database before it writes or sends anything, and a read that asks Restate nothing sees it; - a schema the handler ensures takes it as its statements do; - it fails a call's result, not the invocation id made first, and a send does not swallow it. The two commit-under-way cases run on a key an earlier invocation wrote, and assert the attempt made one commit: on a key never written the first commit is the schema's, made as the session opens, and the signal would land there. Each was seen to fail without what it tests: twelve cases with the carry off, and the two commit-under-way cases on the Python store when a cancellation fails the store's waits. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- tests/sessions_driver.py | 333 ++++++++++++++++++++++++++++++++++ tests/sessions_wire.py | 377 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 710 insertions(+) create mode 100644 tests/sessions_driver.py create mode 100644 tests/sessions_wire.py diff --git a/tests/sessions_driver.py b/tests/sessions_driver.py new file mode 100644 index 00000000..5c5b7245 --- /dev/null +++ b/tests/sessions_driver.py @@ -0,0 +1,333 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A session object's attempt on the explicit recovery VM, with Restate's side played on the wire (``sessions_wire``). + +No server and no endpoint: the attempt runs through the object's runner, and a +real database over the object's state. Above all, where a cancellation lands. +""" + +# pylint: disable=missing-function-docstring + +import asyncio +import math +import typing +from collections.abc import Awaitable, Callable +from typing import Any + +import pytest + +from restate import TerminalError, sessions +from restate.sessions import _driver, internal +from restate.sessions._object import HEAD_KEY +from sessions_wire import REQUESTED_ACK, TYPE, RestateSide, output_of, run # pylint: disable=import-error + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + + +@pytest.fixture(autouse=True, params=["vm", "python"]) +def store(request, monkeypatch): + """Each test runs on both stores: the VM's, which the extension reads and writes directly, and the Python store + over the context's state commands, which an endpoint with a journal codec uses.""" + if request.param == "python": + monkeypatch.setattr(_driver.VmHost, "vm", property(lambda self: None)) + return request.param + + +async def said(step: Callable[[], Awaitable[Any]]) -> str: + """How ``step`` ended: ``ok``, ``cancelled``, or the name of what else it failed with.""" + try: + await step() + return "ok" + except TerminalError as error: + if error.status_code == 409 and error.message == "cancelled": + return "cancelled" + return type(error).__name__ + except Exception as error: # pylint: disable=broad-exception-caught + return type(error).__name__ + + +def call(ctx: sessions.SessionContext) -> Awaitable[Any]: + """A call of Restate, which the harness answers with its input: ``"A"``.""" + return ctx.generic_call("Callee", "echo", "A", key="a") + + +notes = sessions.SessionObject("Notes", migrations=["CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)"]) + + +@notes.handler() +async def add(ctx: sessions.SessionContext, body: str) -> int: + await ctx.db.execute("INSERT INTO notes (body) VALUES (?)", [body]) + row = await ctx.db.get("SELECT count(*) AS n FROM notes") + assert row is not None + return typing.cast(int, row["n"]) + + +@notes.handler() +async def commits(ctx: sessions.SessionContext) -> str: + """Commits, and says what its failure was if it did not.""" + outcome = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["x"])) + return "committed" if outcome == "ok" else outcome + + +@notes.handler() +async def commit_then_reads(ctx: sessions.SessionContext) -> str: + """A commit, work outside Restate long enough for a cancellation to land with nothing waiting, then two reads: + of pages the commit left in the session, so they ask Restate nothing.""" + commit = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["a"])) + await asyncio.sleep(0.3) + + def read() -> Awaitable[Any]: + return ctx.db.get("SELECT count(*) AS n FROM notes") + + return f"{commit},{await said(read)},{await said(read)}" + + +@notes.handler() +async def commit_then_call(ctx: sessions.SessionContext) -> str: + """A commit, then a call: which of the two a cancellation failed.""" + commit = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["x"])) + return f"{commit},{await said(lambda: call(ctx))}" + + +@notes.handler() +async def twice(ctx: sessions.SessionContext) -> str: + """Two commits, each reporting whether it failed and how.""" + + def once() -> Awaitable[str]: + return said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["x"])) + + return f"{await once()},{await once()}" + + +@notes.handler() +async def two_commits(ctx: sessions.SessionContext) -> str: + """A commit, work outside Restate long enough for a cancellation to land with nothing waiting, then a + transaction with a send of its own: sends are made between a commit's head write and the wait for its ack.""" + first = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["a"])) + await asyncio.sleep(0.3) + + async def transaction() -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO notes (body) VALUES (?)", ["b"]) + tx.generic_send("Shipping", "ship", "b", key="b") + + return f"{first},{await said(transaction)}" + + +AUDIT = internal.Schema("audit", ["CREATE TABLE audit (what TEXT NOT NULL)"]) + + +@notes.handler() +async def ensures_twice(ctx: sessions.SessionContext) -> str: + """A library's schema, ensured twice: applying it is a call of the database the handler asked for.""" + + def once() -> Awaitable[str]: + return said(lambda: AUDIT.ensure(ctx.db)) + + return f"{await once()},{await once()}" + + +@notes.handler() +async def call_twice(ctx: sessions.SessionContext) -> str: + """Two calls of Restate: a carried cancellation has to reach the call's result, not its invocation id.""" + # The signal has to land with nothing in flight, or the first call is failed where it waits and the carry is + # never exercised. + await asyncio.sleep(0.05) + + async def once() -> str: + try: + return str(await call(ctx)) + except TerminalError as error: + return "cancelled" if error.status_code == 409 and error.message == "cancelled" else type(error).__name__ + + return f"{await once()},{await once()}" + + +@notes.handler() +async def send_then_call(ctx: sessions.SessionContext) -> str: + """A send first, which makes an invocation id and nothing else: it must not swallow the carried cancellation + that the call after it is owed.""" + await asyncio.sleep(0.05) + ctx.generic_send("Callee", "echo", "S", key="a") + try: + return str(await call(ctx)) + except TerminalError as error: + return "cancelled" if error.status_code == 409 and error.message == "cancelled" else type(error).__name__ + + +class Cancelling: + """Restate cancels the invocation after ``delay`` seconds; ``sent_at_cancel`` is how much the attempt had + written by then.""" + + def __init__(self, side: RestateSide, delay: float) -> None: + self.sent_at_cancel: float = math.inf + self._side = side + self._timer = asyncio.get_running_loop().call_later(delay, self._cancel) + + def _cancel(self) -> None: + self.sent_at_cancel = len(self._side.sent()) + self._side.cancel() + + def stop(self) -> None: + self._timer.cancel() + + +def acked(side: RestateSide) -> int: + """How many of the attempt's commands asked for an ack: a commit each, on either store.""" + return sum(1 for m in side.sent() if 0x0400 <= m.type < 0x8000 and m.flags & REQUESTED_ACK) + + +def describe(side: RestateSide) -> str: + """What the attempt wrote, as message types in order: for a failure's message.""" + return " ".join(f"{m.type:#06x}" for m in side.sent()) + + +async def seeded(key: str) -> dict[str, bytes]: + """The state an earlier invocation of ``key`` left: its schema is applied. + + On a key never written, the first commit of an attempt is the schema's, made as the session opens, and it is + that one ``cancel_on_commit`` would land on. After this, it is the handler's own. + """ + side = RestateSide() + side.start(key, "seed") + await run(notes, "add", side) + assert output_of(side.sent()) == 1, describe(side) + return side.state + + +async def test_runs_a_handler_commits_its_database_and_answers(): + side = RestateSide() + side.start("k1", "first") + await run(notes, "add", side) + assert side.head is not None and side.head["status"] == 200 + assert side.ended + sent = side.sent() + assert output_of(sent) == 1 + assert sent[-1].type == TYPE.end + assert HEAD_KEY in side.state + + +async def test_a_cancellation_that_lands_on_a_commit_in_flight_is_delivered_once_to_the_await_after_it(): + # One signal, and the handler sees one cancellation: the commit under way runs to its end, and the call after + # it fails. + side = RestateSide(await seeded("k6"), cancel_on_commit=True) + side.start("k6", None) + await run(notes, "commit_then_call", side) + assert output_of(side.sent()) == "ok,cancelled", describe(side) + # The premise: the attempt made one commit, the handler's, so that is the one the signal landed on. + assert acked(side) == 1, describe(side) + + +async def test_a_cancellation_does_not_fail_a_commit_already_under_way_its_head_is_out_and_it_lands(): + # The signal arrives while the commit waits for the ack of its head write. The commit runs to its end and says + # so; the cancellation is owed to the handler's next await, and this handler has none. + side = RestateSide(await seeded("k5"), cancel_on_commit=True) + side.start("k5", None) + await run(notes, "commits", side) + assert output_of(side.sent()) == "committed", describe(side) + assert HEAD_KEY in side.state + # The premise: the attempt made one commit, the handler's, so that is the one the signal landed on. + assert acked(side) == 1, describe(side) + # And what it committed is there to read: the seed's row, and this one. + after = RestateSide(side.state) + after.start("k5", "third") + await run(notes, "add", after) + assert output_of(after.sent()) == 3, describe(after) + + +async def test_a_retry_of_a_cancelled_invocation_fails_its_first_call_and_works_after_it(): + # The cancel signal is among the earlier attempts' entries, so the VM knows before the handler starts and + # nothing is in flight to fail: the cancellation is carried to the handler's first call. + side = RestateSide(cancel_at_start=True) + side.start("k7", None) + await run(notes, "twice", side) + assert output_of(side.sent()) == "cancelled,ok", describe(side) + + +async def test_a_schema_the_handler_ensures_takes_a_carried_cancellation_as_its_statements_do(): + side = RestateSide(cancel_at_start=True) + side.start("ke", None) + await run(notes, "ensures_twice", side) + assert output_of(side.sent()) == "cancelled,ok", describe(side) + + +async def test_a_read_that_asks_restate_nothing_sees_a_carried_cancellation_too_once(): + # A read of pages the session holds is answered without a wait on Restate, so a cancellation delivered at the + # store's waits had nothing to land on. It is delivered where the handler calls. + side = RestateSide() + side.start("kr", None) + cancelling = Cancelling(side, 0.15) + await run(notes, "commit_then_reads", side) + cancelling.stop() + sent = side.sent() + assert output_of(sent) == "ok,cancelled,ok", describe(side) + # The premise: the reads after the signal asked Restate for nothing. + assert cancelling.sent_at_cancel < len(sent), "the signal went in before the handler ended" + after = sent[int(cancelling.sent_at_cancel) :] + assert [m.type for m in after] == [TYPE.output, TYPE.end], describe(side) + + +async def test_a_carried_cancellation_fails_the_next_call_of_the_database_before_it_writes_or_sends_anything( + store: str, +): + # A call that fails with the cancellation did nothing: the cancellation is delivered where the handler calls, + # before the call issues a command. + side = RestateSide() + side.start("kc", None) + cancelling = Cancelling(side, 0.15) + await run(notes, "two_commits", side) + cancelling.stop() + sent = side.sent() + assert output_of(sent) == "ok,cancelled", describe(side) + assert cancelling.sent_at_cancel < len(sent), "the signal went in before the handler ended" + # What came after the signal went in: the handler's output, and before it no command at all. + after = [m.type for m in sent[int(cancelling.sent_at_cancel) :] if 0x0400 <= m.type < 0x8000] + assert after == [TYPE.output], f"the cancelled transaction issued commands: {describe(side)}" + # Its sends are made between a commit's head write and the wait for that write's ack, so they are the first + # thing to escape a commit that is failed late. + assert not any(m.type == TYPE.one_way_call for m in sent), "the cancelled transaction's sends went out" + # Every head write is synced: that ack is the commit's sync. The VM's store writes the head *with* its sync, + # asking for the ack on the head write itself; the Python store writes it plain and then clears ``v22/sync`` + # with an ack (``VmHost.sync``). + heads = [i for i, m in enumerate(sent) if m.type == TYPE.set_state and m.bytes_of(1).decode() == HEAD_KEY] + assert heads, describe(side) + if store == "vm": + assert all(sent[i].flags & REQUESTED_ACK for i in heads), describe(side) + else: + synced = [ + sent[i + 1].type == TYPE.clear_state + and sent[i + 1].bytes_of(1).decode() == _driver.SYNC_KEY + and bool(sent[i + 1].flags & REQUESTED_ACK) + for i in heads + ] + assert all(synced), describe(side) + + +async def test_a_retrys_carried_cancellation_fails_the_calls_result_not_the_id_it_makes_first(): + # A call makes the invocation id's future before the result's. Handing the carry to the id let the call run to + # completion and the handler see its result: the cancellation lost. + side = RestateSide(cancel_at_start=True) + side.start("k8", None) + await run(notes, "call_twice", side) + assert output_of(side.sent()) == "cancelled,A", describe(side) + + +async def test_a_send_does_not_swallow_the_cancellation_the_call_after_it_is_owed(): + side = RestateSide(cancel_at_start=True) + side.start("k9", None) + await run(notes, "send_then_call", side) + assert output_of(side.sent()) == "cancelled", describe(side) diff --git a/tests/sessions_wire.py b/tests/sessions_wire.py new file mode 100644 index 00000000..404bce8b --- /dev/null +++ b/tests/sessions_wire.py @@ -0,0 +1,377 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""Restate's side of a session object's attempt, for tests: the service protocol on the wire, by hand. + +The codec (frames, protobuf fields and the message types) and ``RestateSide``, +which plays Restate for one attempt of a session object's handler on the +explicit recovery VM: it holds the object's state, answers the reads, applies +the writes, acks the commands that asked to be acked, and answers calls. No +endpoint and no server: ``run`` drives the attempt through the object's +``_runner``, over an ASGI ``receive``/``send`` pair, as ``server.py`` does. +""" + +# pylint: disable=missing-function-docstring + +from __future__ import annotations + +import asyncio +import json +import struct +import time +from dataclasses import dataclass +from typing import Any, Union + +from restate.server_types import ASGIReceiveEvent, ASGISendEvent, ReceiveChannel +from restate.sessions import SessionObject +from restate.sessions._object import ENTRIES, _runner + +# --- Protocol buffers, as much as the messages here need + + +def _varint(n: int) -> bytes: + out = bytearray() + while n > 127: + out.append((n & 127) | 128) + n >>= 7 + out.append(n) + return bytes(out) + + +def field(number: int, wire: int, payload: bytes) -> bytes: + """A field ``number`` of wire type ``wire`` (0, a varint; 2, length-delimited) with ``payload``.""" + if wire == 0: + return _varint(number * 8) + payload + return _varint(number * 8 + 2) + _varint(len(payload)) + payload + + +def uint(number: int, value: int) -> bytes: + return field(number, 0, _varint(value)) + + +def bytes_(number: int, value: Union[bytes, str]) -> bytes: + return field(number, 2, value.encode() if isinstance(value, str) else value) + + +Fields = dict[int, list[Union[int, bytes]]] +"""A decoded message: its fields' values by number, an int or the bytes of each.""" + + +def decode(buffer: bytes) -> Fields: + fields: Fields = {} + at = 0 + + def read_varint() -> int: + nonlocal at + value = 0 + shift = 0 + while True: + byte = buffer[at] + at += 1 + value |= (byte & 127) << shift + if byte < 128: + return value + shift += 7 + + while at < len(buffer): + tag = read_varint() + number = tag >> 3 + value: Union[int, bytes] + if tag & 7 == 0: + value = read_varint() + elif tag & 7 == 2: + length = read_varint() + value = bytes(buffer[at : at + length]) + at += length + else: + raise ValueError(f"wire type {tag & 7} of field {number}") + fields.setdefault(number, []).append(value) + return fields + + +def value(content: Union[bytes, str]) -> bytes: + """A ``Value`` message: its content is field 1.""" + return bytes_(1, content) + + +# --- Messages + + +class TYPE: # pylint: disable=too-few-public-methods + """The message types these tests send and read.""" + + start = 0x0000 + suspension = 0x0001 + error = 0x0002 + end = 0x0003 + command_ack = 0x0004 + get_state_ephemeral = 0x0200 + get_state_ephemeral_notification = 0x0300 + input = 0x0400 + output = 0x0401 + set_state = 0x0403 + clear_state = 0x0404 + get_state_keys = 0x0406 + call = 0x040D + one_way_call = 0x040E + run = 0x0411 + get_state_keys_completion = 0x8006 + call_completion = 0x800D + call_invocation_id_completion = 0x800E + signal = 0xFBFF + + +V8 = "application/vnd.restate.invocation.v8" + +REQUESTED_ACK = 0x8000 +"""The header bit a command sets to ask Restate to ack it once stored.""" + + +def frame(type_: int, body: bytes) -> bytes: + """A message: its type, 16 bits of flags (none), its length, and its body.""" + return struct.pack(">HHI", type_, 0, len(body)) + body + + +@dataclass(frozen=True) +class Message: + """One message of an output buffer: its type, header flags and decoded fields.""" + + type: int + flags: int + """The header's 16 bits of flags; ``REQUESTED_ACK`` is one of them.""" + fields: Fields + + def bytes_of(self, number: int) -> bytes: + found = self.fields[number][0] + assert isinstance(found, bytes) + return found + + def int_of(self, number: int) -> int: + found = self.fields[number][0] + assert isinstance(found, int) + return found + + +def messages(output: bytes) -> list[Message]: + out: list[Message] = [] + at = 0 + while at < len(output): + type_, flags, length = struct.unpack_from(">HHI", output, at) + out.append(Message(type_, flags, decode(output[at + 8 : at + 8 + length]))) + at += 8 + length + return out + + +def output_of(sent: list[Message]) -> Any: + """The handler's output, deserialized from the attempt's output message.""" + output = next(m for m in sent if m.type == TYPE.output) + answered = decode(output.bytes_of(14)) + content = answered[1][0] + assert isinstance(content, bytes) + return json.loads(content) + + +CANCEL_SIGNAL = frame(TYPE.signal, uint(2, 1) + bytes_(4, b"")) +"""Restate cancelling the invocation: the built-in signal 1, with an empty (void) value.""" + + +# --- Restate's side + + +class RestateSide: + """Restate's side of one attempt: it holds the object's state, answers the reads, applies the writes, and acks. + + Args: + state: The object's state, which the attempt reads and writes. + cancel_on_commit: The first time a command asks for an ack, Restate + sends the cancel signal and, a moment later, the ack: a + cancellation that lands with the database waiting on Restate. + cancel_at_start: A retry of a cancelled invocation: the start counts + two known entries, and the signal follows the input, so the VM + knows of the cancellation before the handler starts. + """ + + def __init__( + self, + state: dict[str, bytes] | None = None, + *, + cancel_on_commit: bool = False, + cancel_at_start: bool = False, + ) -> None: + self.state: dict[str, bytes] = {} if state is None else state + self._cancel_on_commit = cancel_on_commit + self._cancel_at_start = cancel_at_start + self._inbound: asyncio.Queue[ASGIReceiveEvent] = asyncio.Queue() + self._chunks: list[bytes] = [] + self.head: dict[str, Any] | None = None + self.ended = False + # The journal index of the last command seen. Restate numbers *every* command, so an ack + # must count the calls too, not only the writes. The input is the first, at index 0. + self._index = 0 + # How many of the attempt's messages have been answered. + self._answered = 0 + # Whether the one cancel signal has been sent (``cancel_on_commit``). + self._signalled = False + + # --- The ASGI pair the attempt runs over + + async def receive(self) -> ASGIReceiveEvent: + return await self._inbound.get() + + async def send(self, event: ASGISendEvent) -> None: + if event["type"] == "http.response.start": + self.head = dict(event) + elif event["type"] == "http.response.body": + body = event.get("body", b"") + if body: + self._chunks.append(bytes(body)) + if not event.get("more_body", False): + self.ended = True + + def _push(self, chunk: bytes) -> None: + self._inbound.put_nowait({"type": "http.request", "body": chunk, "more_body": True}) + + def _close(self) -> None: + self._inbound.put_nowait({"type": "http.request", "body": b"", "more_body": False}) + # Ends the receive channel's loop, which reads on after the body ends. + self._inbound.put_nowait({"type": "http.disconnect"}) + + # --- What tests call + + def sent(self) -> list[Message]: + """Everything the attempt wrote, as messages.""" + return messages(b"".join(self._chunks)) + + def start(self, key: str, input_: Any) -> None: + """Start the invocation for ``key`` with ``input_``.""" + entries = b"".join(field(4, 2, bytes_(1, k) + bytes_(2, v)) for k, v in self.state.items()) + self._push( + frame( + TYPE.start, + bytes_(1, bytes([1, 2, 3, 4])) + + bytes_(2, "inv_test") + # Known entries: the input, and for a retry of a cancelled invocation the signal the + # earlier attempt got. The VM is not ready to execute until it has them. + + uint(3, 2 if self._cancel_at_start else 1) + + entries + + bytes_(6, key), + ) + ) + self._push(frame(TYPE.input, bytes_(14, value(json.dumps(input_))))) + # A retry of a cancelled invocation: the signal is among the entries of the earlier + # attempts, so the VM knows before the handler starts. + if self._cancel_at_start: + self._push(CANCEL_SIGNAL) + + def cancel(self) -> None: + """Restate cancels the invocation now.""" + self._push(CANCEL_SIGNAL) + + def _over(self, sent: list[Message]) -> bool: + return any(m.type in (TYPE.end, TYPE.error) for m in sent) + + async def settle(self, timeout: float = 20.0) -> None: + """Answer what the attempt asks for until it ends, then close the request body. + + Closing it earlier is what Restate's inactivity timeout does, and would shut the attempt down. + Between rounds the event loop runs: the database's store waits in Rust, and gets its tick + through the VM's scheduler. + """ + deadline = time.monotonic() + timeout + while not self.ended and time.monotonic() < deadline: + await asyncio.sleep(0.001) + sent = self.sent() + for message in sent[self._answered :]: + self._answered += 1 + self._answer(message) + # The attempt is over once it has said so; nothing more will come. + if self._over(sent): + break + if not self.ended and not self._over(self.sent()): + raise AssertionError(f"the attempt did not end within {timeout}s") + self._close() + + def _answer(self, message: Message) -> None: + # Commands are journaled and numbered; ephemeral commands (0x02xx) and notifications + # (0x8xxx) are not. + if 0x0400 <= message.type < 0x8000: + self._index += 1 + # Restate acks a command only if it asked to be acked, and the ack of one covers every + # command before it. + if message.flags & REQUESTED_ACK: + # Restate signals a cancellation once, not on every commit: what follows is acked + # as usual. + ack = frame(TYPE.command_ack, uint(1, self._index)) + if self._cancel_on_commit and not self._signalled: + self._signalled = True + self._push(CANCEL_SIGNAL) + # The ack follows after a moment: together, the attempt would read the ack first + # and the cancellation would find the commit done, with nothing waiting. + asyncio.get_running_loop().call_later(0.02, self._push, ack) + else: + self._push(ack) + if message.type == TYPE.get_state_ephemeral: + key = message.bytes_of(2).decode() + held = self.state.get(key) + self._push( + frame( + TYPE.get_state_ephemeral_notification, + uint(1, message.int_of(1)) + (field(4, 2, b"") if held is None else field(5, 2, value(held))), + ) + ) + elif message.type == TYPE.set_state: + key = message.bytes_of(1).decode() + wrapped = decode(message.bytes_of(3)) + content = wrapped[1][0] if 1 in wrapped else b"" + assert isinstance(content, bytes) + self.state[key] = content + elif message.type == TYPE.clear_state: + self.state.pop(message.bytes_of(1).decode(), None) + elif message.type == TYPE.call: + self._push( + frame(TYPE.call_invocation_id_completion, uint(1, message.int_of(10)) + bytes_(16, "inv_started")) + ) + # A call to key ``k`` is never answered: what a started call, whose result nobody + # holds, looks like to the handler. + if message.fields.get(5) != [b"k"]: + echoed = message.bytes_of(3) + self._push(frame(TYPE.call_completion, uint(1, message.int_of(11)) + field(5, 2, value(echoed)))) + elif message.type == TYPE.get_state_keys: + keys = b"".join(bytes_(1, k) for k in self.state) + self._push(frame(TYPE.get_state_keys_completion, uint(1, message.int_of(11)) + field(5, 2, keys))) + + +async def run(obj: SessionObject, handler_name: str, side: RestateSide) -> None: + """Drive one attempt of ``obj``'s ``handler_name`` through its runner, with ``side`` playing Restate. + + Call ``side.start`` first; this answers the attempt until it ends. + """ + entries = ENTRIES.of(obj) + assert entries is not None + entry = entries[handler_name] + handler = obj.handlers[handler_name] + request_headers = [("content-type", V8)] + serving = asyncio.ensure_future( + _runner(entry)( + handler, + request_headers=request_headers, + attempt_headers=dict(request_headers), + receive=ReceiveChannel(side.receive), + send=side.send, + bidirectional=True, + server_headers=[], + ) + ) + try: + await side.settle() + except BaseException: + serving.cancel() + raise + await asyncio.wait_for(serving, 20) From 030d1728eb63d91b02f735592dce65f442a8d4f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:31:27 +0000 Subject: [PATCH 05/11] Shared core 8.7.0, the release with the explicit recovery VM The extension built against a branch of shared-core until the VM was released (restatedev/sdk-shared-core#118). 8.7.0 has it, and is what @restatedev/sessions builds against: the two SDKs now run the same VM. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- Cargo.lock | 6 ++++-- Cargo.toml | 7 +------ 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d7fd38a..8cb629ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2490,8 +2490,9 @@ dependencies = [ [[package]] name = "restate-sdk-shared-core" -version = "8.6.0" -source = "git+https://github.com/restatedev/sdk-shared-core?branch=explicit-recovery-vm#3bc25595538fc0a73a57f674408dd25283794c46" +version = "8.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f776d05ba074f66611aafd9f1b91373638bd9ed6e867a4b392463f5eb7281b0a" dependencies = [ "base64 0.22.1", "bs58", @@ -2512,6 +2513,7 @@ dependencies = [ "hyper", "hyper-util", "jsonwebtoken", + "mixtrics", "object_store", "parking_lot", "pastey", diff --git a/Cargo.toml b/Cargo.toml index 377cd102..e50c6d9d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] } # checkpoints may outgrow Restate into (RESTATE_SQL_OBJECT_STORE: S3, GCS, Azure, or a # directory); `tunnel` is Restate Cloud's. `aws_lc_rs` is the crypto of all of them (the # tunnel's TLS, request identity's signatures), as the object stores' must be aws-lc. -restate-sdk-shared-core = { version = "8.6.0", features = [ +restate-sdk-shared-core = { version = "8.7.0", features = [ "request_identity", "sha2_random_seed", "aws_lc_rs", @@ -45,8 +45,3 @@ tokio-util = { version = "0.7", default-features = false } # Sessions (`src/sessions.rs`): the database's futures, polled on Python's event loop. futures = "0.3" - -# The explicit recovery VM of session objects, until shared-core releases it -# (restatedev/sdk-shared-core#118). -[patch.crates-io] -restate-sdk-shared-core = { git = "https://github.com/restatedev/sdk-shared-core", branch = "explicit-recovery-vm" } From 56e6cf52ca2a24cee7785b5c077335be0f5305cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:33:45 +0000 Subject: [PATCH 06/11] Sessions: a cancellation cancels a call whose invocation id is yet to come Two places where the driver did not do what @restatedev/sessions does. A cancellation cancels the calls Restate has not answered, waiting for the invocation id of one that has none yet. It skipped those: a call counted as done once its result was settled, and the cancellation itself had just settled it, with its failure. So a call made shortly before the cancellation was reported as cancelled and its callee ran on. A call is now over when Restate answers it. And once the attempt is over, a cancellation still carried made a call of the database raise it, a terminal 409, where the handler's awaits of Restate raise the attempt's end. Whatever cleans up after a shutdown took an attempt that will be retried for an invocation that is over. The docstrings say what a cancellation does rather than that it fails one await: every await pending fails, or else the next one, and a call made while it is carried is made all the same. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- python/restate/sessions/_api.py | 34 ++++++++++++++++------------ python/restate/sessions/_driver.py | 36 +++++++++++++++++++++++------- python/restate/sessions/_object.py | 8 +++---- 3 files changed, 52 insertions(+), 26 deletions(-) diff --git a/python/restate/sessions/_api.py b/python/restate/sessions/_api.py index 8deb48a8..7b8970be 100644 --- a/python/restate/sessions/_api.py +++ b/python/restate/sessions/_api.py @@ -267,18 +267,24 @@ class Database(DatabaseWriter, Protocol): Each statement outside ``transaction()`` is a transaction of its own, durable once its call returns. Calls run one at a time, in call order. - A cancellation of the invocation reaches the handler once, at an await, - which raises ``TerminalError("cancelled", 409)`` (unless the handler has - ``explicit_cancellation``). The awaits of Restate pending when it comes - fail, a call or an attached invocation, and the calls under way are - cancelled. A call of the database is treated differently, so that its - failure means one thing: a call already under way when the cancellation - comes runs to its end, and the cancellation goes to what the handler - awaits next; a call of the database that raises the cancellation was - refused before it began. So the cancellation from ``ctx.db`` says the call - did nothing: it wrote nothing, and a ``transaction()`` neither committed - nor made its sends. A transaction that returns committed, and its sends - are made, once. + A cancellation of the invocation reaches the handler once, as + ``TerminalError("cancelled", 409)`` (unless the handler has + ``explicit_cancellation``). When it comes, the calls Restate has not + answered are cancelled, and every await of Restate then pending fails with + it: a call, an attached invocation. If none was pending, it is carried to + the handler's next such await, or to its next call of the database; a + handler that awaits nothing more does not see it. A call made while it is + carried is made all the same: its result fails, and the callee runs on. + + A call of the database is treated differently from an await of Restate, so + that its failure means one thing. A call already under way when the + cancellation comes runs to its end. A call of the database that the + carried cancellation fails was refused before it began, and did nothing: + it wrote nothing, and a ``transaction()`` neither committed nor made its + sends. A transaction that returns committed, and its sends are made, once. + (A transaction also raises the cancellation when its body awaits a call + that the cancellation fails, unless the body catches it: it rolls back, as + for any error of its body.) What the handler awaits after the cancellation works, so it can compensate, or make the call again:: @@ -286,8 +292,8 @@ class Database(DatabaseWriter, Protocol): try: async with ctx.db.transaction() as tx: ... - except restate.TerminalError as cancelled: - if cancelled.status_code != 409: + except restate.TerminalError as error: + if error.status_code != 409 or error.message != "cancelled": raise await ctx.db.execute("UPDATE orders SET status = 'cancelled' WHERE id = ?", [order]) raise diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py index 2db5dc32..0882742d 100644 --- a/python/restate/sessions/_driver.py +++ b/python/restate/sessions/_driver.py @@ -129,9 +129,11 @@ def __init__( # the handler starts, and its first await fails all the same. There is one carry, here. self._carried_cancellation: bool = False self.calls: list[_CallFuture] = [] + """The attempt's calls, for ``cancel_calls``.""" + # The calls Restate has yet to answer, by the handle of their result. + self._unanswered: dict[int, _CallFuture] = {} # The cancellation of the calls whose invocation id a cancellation waits for. self._cancelling: asyncio.Future[Any] | None = None - """The attempt's calls, for ``cancel_calls``.""" self._queued: bool = False self._output: asyncio.Queue[bytes | None] = asyncio.Queue() self._writer: asyncio.Task[None] = asyncio.ensure_future(self._write_output()) @@ -295,6 +297,9 @@ def _tick(self) -> None: while (notification := self.vm.take_notification()) is not None: handle, value = notification self._left_to_settle.discard(handle) + call = self._unanswered.pop(handle, None) + if call is not None: + call.answered = True future = self._futures.pop(handle, None) if future is not None: _settle(future, value) @@ -406,19 +411,28 @@ def take_carried_cancellation(self) -> bool: The caller delivers it: the handler's call of its database, before it issues anything, so that a call that fails with the cancellation did nothing. """ + if self.ended is not None: + # The attempt is over: what the handler does now fails with that, as its awaits of + # Restate do, and the next attempt gets the cancellation. + return False carried, self._carried_cancellation = self._carried_cancellation, False return carried + def track(self, call: _CallFuture, result_handle: int) -> None: + """A call the attempt made, which a cancellation cancels until Restate answers it.""" + self.calls.append(call) + self._unanswered[result_handle] = call + def _cancelled(self) -> None: """Restate cancelled the invocation.""" if not self.cancellation.done(): self.cancellation.set_result(None) if self._explicit_cancellation: return - # The calls in flight are cancelled (right away those whose invocation id is known, so - # that it happens before the handler ends), and the awaits fail. + # The calls in flight are cancelled (right away those whose invocation id is known, the + # others as it comes: the handler's end waits for them), and the awaits fail. for call in list(self.calls): - if not call.done() and call.knows_invocation_id(): + if not call.answered and call.knows_invocation_id(): with contextlib.suppress(SdkInternalBaseException): self.act(operator.methodcaller("cancel_invocation", call.known_invocation_id())) self._cancelling = _quiet(asyncio.ensure_future(self.cancel_calls())) @@ -434,16 +448,20 @@ def _cancelled(self) -> None: self._carried_cancellation = not failed_a_result async def cancel_calls(self) -> list[str]: - """Cancel the calls of the attempt that have not completed; return their invocation ids.""" + """Cancel the calls of the attempt that Restate has not answered; return their invocation ids. + + Not answered, rather than not done: a cancellation fails the result of a call the handler + awaits, which leaves the callee running, and that is the call to cancel. + """ cancelled: list[str] = [] for call in list(self.calls): - if call.done() or call.cancelled: + if call.answered or call.cancelled: continue try: invocation_id = await call.invocation_id() except BaseException: # pylint: disable=broad-exception-caught continue - if not call.done() and not call.cancelled: + if not call.answered and not call.cancelled: call.cancelled = True self.act(operator.methodcaller("cancel_invocation", invocation_id)) cancelled.append(invocation_id) @@ -496,6 +514,8 @@ def __init__( self.cancelled: bool = False """Whether the attempt cancelled the call's invocation.""" + self.answered: bool = False + """Whether Restate answered the call: its result came, the callee's value or its failure.""" def done(self) -> bool: return self._result.done() @@ -618,7 +638,7 @@ def generic_call( self.driver.invocation_id_future(handle.invocation_id_handle), self.driver.future(handle.result_handle), ) - self.driver.calls.append(call) + self.driver.track(call, handle.result_handle) return call def generic_send( diff --git a/python/restate/sessions/_object.py b/python/restate/sessions/_object.py index f40e6484..e62a0d51 100644 --- a/python/restate/sessions/_object.py +++ b/python/restate/sessions/_object.py @@ -570,10 +570,10 @@ async def add(ctx: sessions.SessionContext, text: str) -> None: name: The handler's name. Defaults to the function's name. explicit_cancellation: If true, cancelling the invocation neither fails its awaits nor cancels its calls (without it, a - cancellation cancels the calls under way and fails one await, - once: see ``Database``). The handler learns of - the cancellation with ``internal.cancelled(ctx)`` and decides - what to stop, for example its calls with + cancellation cancels the calls under way and fails the awaits + pending, or else the next one: see ``Database``). The handler + learns of the cancellation with ``internal.cancelled(ctx)`` + and decides what to stop, for example its calls with ``internal.cancel_calls(ctx)`` (from ``restate.sessions.internal``). From ac2fd9f01f4d153d711c954a0da399a382b17989 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:59:10 +0000 Subject: [PATCH 07/11] Sessions tests: the cancellation rule held against the ways it could be wrong The driver tests passed against several wrong implementations. They now fail against each of these, tried one at a time: - a cancellation carried even though it failed an await (delivered twice); - the outbox emptied after a commit taking the carry, which reports a committed transaction as cancelled; - a carry set for a handler with explicit cancellation; - a cancellation failing the store's reads, its key listing or its acks; - a call left running because its invocation id came after the cancellation; - a carry delivered after the attempt ended. Three things in the harness made that possible. It sent the whole state with the start, so the store never asked Restate for anything: it sends only the database's head, as an invocation does. It gave the ack of a commit twenty milliseconds after the cancel signal, which on a stalled machine reads both at once and proves nothing: it now holds what follows the signal until the attempt has acted on it, with no clock involved. And it always gave a call its invocation id at once. New cases: a call and a commit made at once, a view, the key's other database, a transaction whose cancelled body never ran. No test waits on wall-clock time for what it asserts. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- tests/sessions_driver.py | 420 ++++++++++++++++++++++++++++++++------- tests/sessions_wire.py | 137 ++++++++++--- 2 files changed, 460 insertions(+), 97 deletions(-) diff --git a/tests/sessions_driver.py b/tests/sessions_driver.py index 5c5b7245..2d33f1a1 100644 --- a/tests/sessions_driver.py +++ b/tests/sessions_driver.py @@ -12,14 +12,16 @@ No server and no endpoint: the attempt runs through the object's runner, and a real database over the object's state. Above all, where a cancellation lands. +Every cancel signal goes in at a point the test chooses, and what follows it +only once the attempt has acted on it: no test depends on how long anything takes. """ # pylint: disable=missing-function-docstring import asyncio -import math +import random import typing -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Iterator from typing import Any import pytest @@ -47,6 +49,54 @@ def store(request, monkeypatch): return request.param +class Gate: + """Where a handler waits for the test: ``wait`` tells the test the handler is there, and returns once it opens.""" + + def __init__(self) -> None: + self.reached = asyncio.Event() + self.opened = asyncio.Event() + self.seen: list[str] = [] + """What a handler reports from where it cannot return it: its cleanup, say.""" + + async def wait(self) -> None: + self.reached.set() + await self.opened.wait() + + +_gates: list[Gate] = [] + + +@pytest.fixture +def gate() -> Iterator[Gate]: + """The test's ``Gate``, which its handler reaches with ``gate_of()``.""" + made = Gate() + _gates.append(made) + yield made + _gates.remove(made) + + +def gate_of() -> Gate: + return _gates[-1] + + +async def cancel_at(gate_: Gate, side: RestateSide) -> None: + """Once the handler waits at ``gate_``, Restate cancels the invocation; once the attempt has acted on that, the + handler goes on. Nothing the handler awaits is pending, so the cancellation is carried.""" + await gate_.reached.wait() + await side.cancel() + gate_.opened.set() + + +async def run_cancelling_at(gate_: Gate, handler_name: str, side: RestateSide) -> None: + """``run`` the handler, with Restate cancelling the invocation as the handler reaches ``gate_``.""" + cancelling = asyncio.ensure_future(cancel_at(gate_, side)) + try: + await run(notes, handler_name, side) + finally: + cancelling.cancel() + assert side.signalled_at is not None, "the handler never reached the gate" + + async def said(step: Callable[[], Awaitable[Any]]) -> str: """How ``step`` ended: ``ok``, ``cancelled``, or the name of what else it failed with.""" try: @@ -60,14 +110,27 @@ async def said(step: Callable[[], Awaitable[Any]]) -> str: return type(error).__name__ -def call(ctx: sessions.SessionContext) -> Awaitable[Any]: - """A call of Restate, which the harness answers with its input: ``"A"``.""" - return ctx.generic_call("Callee", "echo", "A", key="a") +async def ended_with(step: Callable[[], Awaitable[Any]]) -> str: + """As ``said``, and the attempt's end too, which is not an ``Exception``.""" + try: + return await said(step) + except BaseException as error: # pylint: disable=broad-exception-caught + return type(error).__name__ + + +def call(ctx: sessions.SessionContext, key: str = "a") -> Awaitable[Any]: + """A call of Restate, which the harness answers with its input, ``"A"``; never, to key ``k``.""" + return ctx.generic_call("Callee", "echo", "A", key=key) notes = sessions.SessionObject("Notes", migrations=["CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT)"]) +def insert(ctx: sessions.SessionContext, body: str = "x") -> Callable[[], Awaitable[Any]]: + """A call of the database: one statement, which commits.""" + return lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", [body]) + + @notes.handler() async def add(ctx: sessions.SessionContext, body: str) -> int: await ctx.db.execute("INSERT INTO notes (body) VALUES (?)", [body]) @@ -79,16 +142,16 @@ async def add(ctx: sessions.SessionContext, body: str) -> int: @notes.handler() async def commits(ctx: sessions.SessionContext) -> str: """Commits, and says what its failure was if it did not.""" - outcome = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["x"])) + outcome = await said(insert(ctx)) return "committed" if outcome == "ok" else outcome @notes.handler() async def commit_then_reads(ctx: sessions.SessionContext) -> str: - """A commit, work outside Restate long enough for a cancellation to land with nothing waiting, then two reads: - of pages the commit left in the session, so they ask Restate nothing.""" - commit = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["a"])) - await asyncio.sleep(0.3) + """A commit, a wait outside Restate where the test cancels the invocation, then two reads: of pages the commit left + in the session, so they ask Restate nothing.""" + commit = await said(insert(ctx, "a")) + await gate_of().wait() def read() -> Awaitable[Any]: return ctx.db.get("SELECT count(*) AS n FROM notes") @@ -99,54 +162,62 @@ def read() -> Awaitable[Any]: @notes.handler() async def commit_then_call(ctx: sessions.SessionContext) -> str: """A commit, then a call: which of the two a cancellation failed.""" - commit = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["x"])) + commit = await said(insert(ctx)) return f"{commit},{await said(lambda: call(ctx))}" @notes.handler() async def twice(ctx: sessions.SessionContext) -> str: """Two commits, each reporting whether it failed and how.""" + return f"{await said(insert(ctx))},{await said(insert(ctx))}" - def once() -> Awaitable[str]: - return said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["x"])) - return f"{await once()},{await once()}" +@notes.handler() +async def three_times(ctx: sessions.SessionContext) -> str: + """Three commits, each reporting whether it failed and how.""" + return f"{await said(insert(ctx))},{await said(insert(ctx))},{await said(insert(ctx))}" @notes.handler() async def two_commits(ctx: sessions.SessionContext) -> str: - """A commit, work outside Restate long enough for a cancellation to land with nothing waiting, then a - transaction with a send of its own: sends are made between a commit's head write and the wait for its ack.""" - first = await said(lambda: ctx.db.execute("INSERT INTO notes (body) VALUES (?)", ["a"])) - await asyncio.sleep(0.3) + """A commit, a wait outside Restate where the test cancels the invocation, then a transaction with a send of its + own: sends are made between a commit's head write and the wait for its ack.""" + first = await said(insert(ctx, "a")) + await gate_of().wait() async def transaction() -> None: async with ctx.db.transaction() as tx: + gate_of().seen.append("body") await tx.execute("INSERT INTO notes (body) VALUES (?)", ["b"]) tx.generic_send("Shipping", "ship", "b", key="b") return f"{first},{await said(transaction)}" +@notes.handler() +async def sending_transaction_then_insert(ctx: sessions.SessionContext) -> str: + """A transaction with a send, whose commit empties the outbox after it, then a commit.""" + + async def transaction() -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO notes (body) VALUES (?)", ["t"]) + tx.generic_send("Shipping", "ship", "t", key="t") + + return f"{await said(transaction)},{await said(insert(ctx))}" + + AUDIT = internal.Schema("audit", ["CREATE TABLE audit (what TEXT NOT NULL)"]) @notes.handler() async def ensures_twice(ctx: sessions.SessionContext) -> str: """A library's schema, ensured twice: applying it is a call of the database the handler asked for.""" - - def once() -> Awaitable[str]: - return said(lambda: AUDIT.ensure(ctx.db)) - - return f"{await once()},{await once()}" + return f"{await said(lambda: AUDIT.ensure(ctx.db))},{await said(lambda: AUDIT.ensure(ctx.db))}" @notes.handler() async def call_twice(ctx: sessions.SessionContext) -> str: """Two calls of Restate: a carried cancellation has to reach the call's result, not its invocation id.""" - # The signal has to land with nothing in flight, or the first call is failed where it waits and the carry is - # never exercised. - await asyncio.sleep(0.05) async def once() -> str: try: @@ -161,7 +232,6 @@ async def once() -> str: async def send_then_call(ctx: sessions.SessionContext) -> str: """A send first, which makes an invocation id and nothing else: it must not swallow the carried cancellation that the call after it is owed.""" - await asyncio.sleep(0.05) ctx.generic_send("Callee", "echo", "S", key="a") try: return str(await call(ctx)) @@ -169,21 +239,90 @@ async def send_then_call(ctx: sessions.SessionContext) -> str: return "cancelled" if error.status_code == 409 and error.message == "cancelled" else type(error).__name__ -class Cancelling: - """Restate cancels the invocation after ``delay`` seconds; ``sent_at_cancel`` is how much the attempt had - written by then.""" +@notes.handler() +async def call_then_twice(ctx: sessions.SessionContext) -> str: + """A call Restate never answers, then two commits.""" + return f"{await said(lambda: call(ctx, 'k'))},{await said(insert(ctx))},{await said(insert(ctx))}" - def __init__(self, side: RestateSide, delay: float) -> None: - self.sent_at_cancel: float = math.inf - self._side = side - self._timer = asyncio.get_running_loop().call_later(delay, self._cancel) - def _cancel(self) -> None: - self.sent_at_cancel = len(self._side.sent()) - self._side.cancel() +@notes.handler() +async def unanswered_call(ctx: sessions.SessionContext) -> str: + """A call Restate never answers.""" + return await said(lambda: call(ctx, "k")) - def stop(self) -> None: - self._timer.cancel() + +@notes.handler(explicit_cancellation=True) +async def explicitly(ctx: sessions.SessionContext) -> str: + """A commit, a call and a commit, in a handler that takes cancellations itself.""" + return f"{await said(insert(ctx))},{await said(lambda: call(ctx))},{await said(insert(ctx))}" + + +@notes.handler() +async def gathers(ctx: sessions.SessionContext) -> str: + """A call and a commit at once, then a commit.""" + both = await asyncio.gather(said(lambda: call(ctx)), said(insert(ctx))) + return f"{','.join(both)},{await said(insert(ctx))}" + + +@notes.view() +async def counts(ctx: sessions.ViewContext) -> str: + """Two reads of a view.""" + + def read() -> Awaitable[Any]: + return ctx.db.get("SELECT count(*) AS n FROM notes") + + return f"{await said(read)},{await said(read)}" + + +@notes.handler() +async def other_database(ctx: sessions.SessionContext) -> str: + """Two calls of another database of the key, then one of the object's own.""" + other = internal.database(ctx.db, "other") + + def create() -> Awaitable[Any]: + return other.execute("CREATE TABLE IF NOT EXISTS t (x)") + + return f"{await said(create)},{await said(create)},{await said(insert(ctx))}" + + +BULK_ROWS = 40 + + +def bulk_rows(seed: int) -> list[str]: + """About 160 KiB of rows that do not compress, the same for each ``seed``: enough to make a commit checkpoint.""" + rows = random.Random(seed) + return [rows.randbytes(2000).hex() for _ in range(BULK_ROWS)] + + +@notes.handler() +async def bulks_then_twice(ctx: sessions.SessionContext) -> str: + """Three bulk commits, then two commits. + + The third bulk commit checkpoints and then lists the state's keys, to delete the packs no checkpoint needs any + more: where that falls follows from the shared core's checkpoint thresholds, which the test checks. + """ + statement = f"INSERT INTO notes (body) VALUES {', '.join(['(?)'] * BULK_ROWS)}" + + def bulk(seed: int) -> Callable[[], Awaitable[Any]]: + return lambda: ctx.db.execute(statement, bulk_rows(seed)) + + bulks = [await said(bulk(1)), await said(bulk(2)), await said(bulk(3))] + return f"{','.join(bulks)},{await said(insert(ctx))},{await said(insert(ctx))}" + + +@notes.handler() +async def cleans_up_after_its_end(ctx: sessions.SessionContext) -> str: + """A commit, then a wait outside Restate that the attempt's end stops; the cleanup calls the database and Restate, + and reports how each ended.""" + await said(insert(ctx, "a")) + seen = gate_of().seen + try: + await gate_of().wait() + except asyncio.CancelledError: + seen.append(await ended_with(insert(ctx, "b"))) + seen.append(await ended_with(lambda: call(ctx))) + raise + return "not ended" def acked(side: RestateSide) -> int: @@ -196,6 +335,18 @@ def describe(side: RestateSide) -> str: return " ".join(f"{m.type:#06x}" for m in side.sent()) +def acked_after_signal(side: RestateSide) -> int: + """How many of the commands the attempt wrote after the cancel signal went in asked for an ack: its commits.""" + assert side.signalled_at is not None, f"no cancel signal went in: {describe(side)}" + return sum(1 for m in side.sent()[side.signalled_at :] if 0x0400 <= m.type < 0x8000 and m.flags & REQUESTED_ACK) + + +def types_after_signal(side: RestateSide) -> list[int]: + """The types of what the attempt wrote after the cancel signal went in.""" + assert side.signalled_at is not None, f"no cancel signal went in: {describe(side)}" + return [m.type for m in side.sent()[side.signalled_at :]] + + async def seeded(key: str) -> dict[str, bytes]: """The state an earlier invocation of ``key`` left: its schema is applied. @@ -221,6 +372,16 @@ async def test_runs_a_handler_commits_its_database_and_answers(): assert HEAD_KEY in side.state +async def test_reads_the_state_beyond_the_head_on_the_wire_and_reads_back_what_it_wrote(store: str): + # Restate preloads the head alone; the rest of the state is read on the wire. A key this process never opened + # has no pages cached, so the read goes to Restate. + side = RestateSide(await seeded(f"kl-seed-{store}")) + side.start(f"kl-{store}", "second") + await run(notes, "add", side) + assert output_of(side.sent()) == 2, describe(side) + assert side.reads > 0, describe(side) + + async def test_a_cancellation_that_lands_on_a_commit_in_flight_is_delivered_once_to_the_await_after_it(): # One signal, and the handler sees one cancellation: the commit under way runs to its end, and the call after # it fails. @@ -249,6 +410,146 @@ async def test_a_cancellation_does_not_fail_a_commit_already_under_way_its_head_ assert output_of(after.sent()) == 3, describe(after) +async def test_the_outbox_emptied_after_a_commit_does_not_take_the_cancellation_that_landed_on_the_commit(): + # The signal lands on the transaction's commit, which made its send. The session then empties the outbox, a + # call of the database of its own: the cancellation is not its, and the transaction reports what it did. + side = RestateSide(await seeded("kb"), cancel_on_commit=True) + side.start("kb", None) + await run(notes, "sending_transaction_then_insert", side) + sent = side.sent() + assert output_of(sent) == "ok,cancelled", describe(side) + # The premise: the signal went in, and the transaction's send went out. + assert side.signalled_at is not None, describe(side) + assert TYPE.one_way_call in [m.type for m in sent], describe(side) + + +async def test_a_cancellation_that_fails_a_call_it_finds_waiting_is_not_carried_as_well(): + # The signal arrives with the call waiting for its result: the call fails, and that was the cancellation. The + # calls of the database after it succeed. + side = RestateSide(cancel_on_call="after_id") + side.start("ka", None) + await run(notes, "call_then_twice", side) + assert output_of(side.sent()) == "cancelled,ok,ok", describe(side) + assert TYPE.cancel_invocation in types_after_signal(side), describe(side) + + +async def test_a_handler_with_explicit_cancellation_gets_no_carried_cancellation(): + side = RestateSide(cancel_at_start=True) + side.start("kx", None) + await run(notes, "explicitly", side) + assert output_of(side.sent()) == "ok,ok,ok", describe(side) + + +async def test_a_cancellation_does_not_fail_the_read_of_the_state_it_finds_waiting(store: str): + # The signal arrives while the session's read of the state waits for Restate (on the VM's store, in Rust): + # the read is the open's, which the handler's first call waits for. The read and the call run to their end; the + # cancellation goes to the next call. + side = RestateSide(await seeded(f"kd-seed-{store}"), cancel_on_read=1) + side.start(f"kd-{store}", None) + await run(notes, "three_times", side) + assert output_of(side.sent()) == "ok,cancelled,ok", describe(side) + assert side.signalled_at is not None, f"no read went to Restate: {describe(side)}" + + +async def test_a_cancellation_does_not_fail_the_listing_of_the_state_keys_it_finds_waiting(store: str): + # The third bulk commit lists the state's keys after it checkpoints. The signal arrives while the listing waits + # for Restate (on the VM's store, in Rust): the call runs to its end, and the next call gets the cancellation. + side = RestateSide(cancel_on_keys=True) + side.start(f"kk-{store}", None) + await run(notes, "bulks_then_twice", side) + # The premise: the keys were listed after the third bulk commit, with the open's commit of the schema, four + # commits in all, before the listing. + assert side.signalled_at is not None, f"the state's keys were never listed: {describe(side)}" + assert acked(side) - acked_after_signal(side) == 4, f"the listing came after another commit: {describe(side)}" + assert output_of(side.sent()) == "ok,ok,ok,cancelled,ok", describe(side) + # The listing ran to its end, and the session went on: after the signal, the one commit is the last call's. + assert acked_after_signal(side) == 1, describe(side) + + +async def test_a_call_whose_invocation_id_comes_after_the_cancellation_is_cancelled_once_it_comes(): + # The signal arrives before the call's invocation id: the call is cancelled as the id comes, before the handler + # ends. The cancel command names the id, so it went out after the id came. + side = RestateSide(cancel_on_call="before_id") + side.start("ki", None) + await run(notes, "unanswered_call", side) + sent = side.sent() + assert output_of(sent) == "cancelled", describe(side) + types = [m.type for m in sent] + assert TYPE.cancel_invocation in types, describe(side) + cancel = types.index(TYPE.cancel_invocation) + assert cancel < types.index(TYPE.output), describe(side) + assert sent[cancel].bytes_of(1) == b"inv_started", describe(side) + + +async def test_a_call_whose_invocation_id_came_before_the_cancellation_is_cancelled(): + side = RestateSide(cancel_on_call="after_id") + side.start("kj", None) + await run(notes, "unanswered_call", side) + sent = side.sent() + assert output_of(sent) == "cancelled", describe(side) + types = [m.type for m in sent] + assert TYPE.cancel_invocation in types, describe(side) + cancel = types.index(TYPE.cancel_invocation) + assert cancel < types.index(TYPE.output), describe(side) + assert sent[cancel].bytes_of(1) == b"inv_started", describe(side) + + +async def test_once_the_attempt_has_ended_a_carried_cancellation_is_not_delivered(): + # The signal arrives during the handler's local work, and Restate shuts the attempt down. The handler's cleanup + # calls its database and Restate: each fails with the attempt's end, as it does without the signal, and not with + # the cancellation, which the next attempt gets. + async def cleanup_saw(cancelled: bool, key: str) -> list[str]: + made = Gate() + _gates.append(made) + try: + side = RestateSide() + side.start(key, None) + + async def end() -> None: + await made.reached.wait() + if cancelled: + await side.cancel() + side.shut_down() + + ending = asyncio.ensure_future(end()) + try: + await run(notes, "cleans_up_after_its_end", side) + finally: + ending.cancel() + assert not cancelled or side.signalled_at is not None, describe(side) + return made.seen + finally: + _gates.remove(made) + + without = await cleanup_saw(False, "kf1") + with_signal = await cleanup_saw(True, "kf2") + assert len(without) == 2 and without[1] == "SuspendedException", without + assert with_signal == without, f"with the signal: {with_signal}; without: {without}" + + +async def test_a_carried_cancellation_goes_to_the_first_of_a_call_and_a_commit_made_at_once(): + # ``gather`` starts its steps in order: the call is made first, and takes the carry as it makes its result's + # future; the commit after it runs. + side = RestateSide(cancel_at_start=True) + side.start("kg", None) + await run(notes, "gathers", side) + assert output_of(side.sent()) == "cancelled,ok,ok", describe(side) + + +async def test_a_view_takes_a_carried_cancellation_at_its_first_read(): + side = RestateSide(await seeded("kv"), cancel_at_start=True) + side.start("kv", None) + await run(notes, "counts", side) + assert output_of(side.sent()) == "cancelled,ok", describe(side) + + +async def test_another_database_of_the_key_takes_a_carried_cancellation_as_the_objects_own_does(): + side = RestateSide(cancel_at_start=True) + side.start("ko", None) + await run(notes, "other_database", side) + assert output_of(side.sent()) == "cancelled,ok,ok", describe(side) + + async def test_a_retry_of_a_cancelled_invocation_fails_its_first_call_and_works_after_it(): # The cancel signal is among the earlier attempts' entries, so the VM knows before the handler starts and # nothing is in flight to fail: the cancellation is carried to the handler's first call. @@ -265,60 +566,39 @@ async def test_a_schema_the_handler_ensures_takes_a_carried_cancellation_as_its_ assert output_of(side.sent()) == "cancelled,ok", describe(side) -async def test_a_read_that_asks_restate_nothing_sees_a_carried_cancellation_too_once(): +async def test_a_read_that_asks_restate_nothing_sees_a_carried_cancellation_too_once(gate: Gate): # A read of pages the session holds is answered without a wait on Restate, so a cancellation delivered at the # store's waits had nothing to land on. It is delivered where the handler calls. side = RestateSide() side.start("kr", None) - cancelling = Cancelling(side, 0.15) - await run(notes, "commit_then_reads", side) - cancelling.stop() - sent = side.sent() - assert output_of(sent) == "ok,cancelled,ok", describe(side) + await run_cancelling_at(gate, "commit_then_reads", side) + assert output_of(side.sent()) == "ok,cancelled,ok", describe(side) # The premise: the reads after the signal asked Restate for nothing. - assert cancelling.sent_at_cancel < len(sent), "the signal went in before the handler ended" - after = sent[int(cancelling.sent_at_cancel) :] - assert [m.type for m in after] == [TYPE.output, TYPE.end], describe(side) + assert types_after_signal(side) == [TYPE.output, TYPE.end], describe(side) async def test_a_carried_cancellation_fails_the_next_call_of_the_database_before_it_writes_or_sends_anything( - store: str, + gate: Gate, ): # A call that fails with the cancellation did nothing: the cancellation is delivered where the handler calls, # before the call issues a command. side = RestateSide() side.start("kc", None) - cancelling = Cancelling(side, 0.15) - await run(notes, "two_commits", side) - cancelling.stop() + await run_cancelling_at(gate, "two_commits", side) sent = side.sent() assert output_of(sent) == "ok,cancelled", describe(side) - assert cancelling.sent_at_cancel < len(sent), "the signal went in before the handler ended" + # The transaction failed before its body ran. + assert not gate.seen, gate.seen # What came after the signal went in: the handler's output, and before it no command at all. - after = [m.type for m in sent[int(cancelling.sent_at_cancel) :] if 0x0400 <= m.type < 0x8000] + after = [t for t in types_after_signal(side) if 0x0400 <= t < 0x8000] assert after == [TYPE.output], f"the cancelled transaction issued commands: {describe(side)}" # Its sends are made between a commit's head write and the wait for that write's ack, so they are the first # thing to escape a commit that is failed late. assert not any(m.type == TYPE.one_way_call for m in sent), "the cancelled transaction's sends went out" - # Every head write is synced: that ack is the commit's sync. The VM's store writes the head *with* its sync, - # asking for the ack on the head write itself; the Python store writes it plain and then clears ``v22/sync`` - # with an ack (``VmHost.sync``). - heads = [i for i, m in enumerate(sent) if m.type == TYPE.set_state and m.bytes_of(1).decode() == HEAD_KEY] - assert heads, describe(side) - if store == "vm": - assert all(sent[i].flags & REQUESTED_ACK for i in heads), describe(side) - else: - synced = [ - sent[i + 1].type == TYPE.clear_state - and sent[i + 1].bytes_of(1).decode() == _driver.SYNC_KEY - and bool(sent[i + 1].flags & REQUESTED_ACK) - for i in heads - ] - assert all(synced), describe(side) async def test_a_retrys_carried_cancellation_fails_the_calls_result_not_the_id_it_makes_first(): - # A call makes the invocation id's future before the result's. Handing the carry to the id let the call run to + # A call makes the invocation id's future before the result's. A carry the id took would let the call run to # completion and the handler see its result: the cancellation lost. side = RestateSide(cancel_at_start=True) side.start("k8", None) diff --git a/tests/sessions_wire.py b/tests/sessions_wire.py index 404bce8b..8319fd96 100644 --- a/tests/sessions_wire.py +++ b/tests/sessions_wire.py @@ -27,11 +27,11 @@ import struct import time from dataclasses import dataclass -from typing import Any, Union +from typing import Any, Literal, Union from restate.server_types import ASGIReceiveEvent, ASGISendEvent, ReceiveChannel from restate.sessions import SessionObject -from restate.sessions._object import ENTRIES, _runner +from restate.sessions._object import ENTRIES, HEAD_KEY, _runner # --- Protocol buffers, as much as the messages here need @@ -108,7 +108,6 @@ class TYPE: # pylint: disable=too-few-public-methods """The message types these tests send and read.""" start = 0x0000 - suspension = 0x0001 error = 0x0002 end = 0x0003 command_ack = 0x0004 @@ -121,7 +120,7 @@ class TYPE: # pylint: disable=too-few-public-methods get_state_keys = 0x0406 call = 0x040D one_way_call = 0x040E - run = 0x0411 + cancel_invocation = 0x0410 get_state_keys_completion = 0x8006 call_completion = 0x800D call_invocation_id_completion = 0x800E @@ -181,6 +180,13 @@ def output_of(sent: list[Message]) -> Any: CANCEL_SIGNAL = frame(TYPE.signal, uint(2, 1) + bytes_(4, b"")) """Restate cancelling the invocation: the built-in signal 1, with an empty (void) value.""" +HAND_OFF_TURNS = 10 +"""Turns of the event loop that a message takes from the request body to the driver's tick, with margin. + +The ``ReceiveChannel``'s loop takes it, the input pump hands it to the VM and +schedules a tick, and the tick acts on it: three turns. +""" + # --- Restate's side @@ -189,13 +195,30 @@ class RestateSide: """Restate's side of one attempt: it holds the object's state, answers the reads, applies the writes, and acks. Args: - state: The object's state, which the attempt reads and writes. + state: The object's state, which the attempt reads and writes. The + start carries the head of the database alone, as Restate preloads + it for a session object, and the attempt reads the rest on the wire. cancel_on_commit: The first time a command asks for an ack, Restate - sends the cancel signal and, a moment later, the ack: a - cancellation that lands with the database waiting on Restate. + sends the cancel signal, and the ack once the attempt has acted + on the signal: a cancellation that lands with the database waiting + on Restate. + cancel_on_read: At the ``n``-th read of the state on the wire, Restate + sends the cancel signal, and the read's value once the attempt has + acted on the signal. + cancel_on_keys: At the first listing of the state's keys, Restate + sends the cancel signal, and the listing once the attempt has + acted on the signal. + cancel_on_call: At the first call, Restate sends the cancel signal + ``"before_id"``, the call's invocation id once the attempt has + acted on it; or ``"after_id"``, the signal once the attempt has + the id. cancel_at_start: A retry of a cancelled invocation: the start counts two known entries, and the signal follows the input, so the VM knows of the cancellation before the handler starts. + + A call to key ``k`` is never answered: what a started call, whose result + nobody holds, looks like to the handler. Every other call is answered with + its input. """ def __init__( @@ -203,22 +226,34 @@ def __init__( state: dict[str, bytes] | None = None, *, cancel_on_commit: bool = False, + cancel_on_read: int | None = None, + cancel_on_keys: bool = False, + cancel_on_call: Literal["before_id", "after_id"] | None = None, cancel_at_start: bool = False, ) -> None: self.state: dict[str, bytes] = {} if state is None else state self._cancel_on_commit = cancel_on_commit + self._cancel_on_read = cancel_on_read + self._cancel_on_keys = cancel_on_keys + self._cancel_on_call = cancel_on_call self._cancel_at_start = cancel_at_start self._inbound: asyncio.Queue[ASGIReceiveEvent] = asyncio.Queue() self._chunks: list[bytes] = [] self.head: dict[str, Any] | None = None self.ended = False + self.reads = 0 + """How many reads of the state the attempt made on the wire.""" + self.signalled_at: int | None = None + """How many messages the attempt had written when the cancel signal went in, if it did.""" # The journal index of the last command seen. Restate numbers *every* command, so an ack # must count the calls too, not only the writes. The input is the first, at index 0. self._index = 0 # How many of the attempt's messages have been answered. self._answered = 0 - # Whether the one cancel signal has been sent (``cancel_on_commit``). - self._signalled = False + # What is pushed after a message that the attempt must act on first (``_push_alone``), + # until it has. + self._held: list[bytes] | None = None + self._releasing: asyncio.Task[None] | None = None # --- The ASGI pair the attempt runs over @@ -236,8 +271,43 @@ async def send(self, event: ASGISendEvent) -> None: self.ended = True def _push(self, chunk: bytes) -> None: + if self._held is not None: + self._held.append(chunk) + return self._inbound.put_nowait({"type": "http.request", "body": chunk, "more_body": True}) + def _push_alone(self, chunk: bytes) -> None: + """Push ``chunk``, and hold back what is pushed after it until the attempt has acted on it.""" + self._push(chunk) + if self._held is None: + self._held = [] + self._releasing = asyncio.ensure_future(self._release()) + + async def _release(self) -> None: + await self.handed_off() + held, self._held = self._held or [], None + for chunk in held: + self._push(chunk) + + async def handed_off(self) -> None: + """Return once the attempt has acted on everything pushed so far. + + The attempt has taken every message once the request body's queue is + empty; ``HAND_OFF_TURNS`` turns of the event loop later, its input pump + has handed them to the VM and its driver has ticked on them. Turns, not + time: on a slow machine the attempt still acts on the message before + anything pushed after this returns can reach it. + """ + while not self._inbound.empty() and not self.ended: + await asyncio.sleep(0) + for _ in range(HAND_OFF_TURNS): + await asyncio.sleep(0) + + def _signal(self) -> None: + """Send the cancel signal, and hold back what follows until the attempt has acted on it.""" + self.signalled_at = len(self.sent()) + self._push_alone(CANCEL_SIGNAL) + def _close(self) -> None: self._inbound.put_nowait({"type": "http.request", "body": b"", "more_body": False}) # Ends the receive channel's loop, which reads on after the body ends. @@ -251,7 +321,8 @@ def sent(self) -> list[Message]: def start(self, key: str, input_: Any) -> None: """Start the invocation for ``key`` with ``input_``.""" - entries = b"".join(field(4, 2, bytes_(1, k) + bytes_(2, v)) for k, v in self.state.items()) + preloaded = {k: v for k, v in self.state.items() if k == HEAD_KEY} + entries = b"".join(field(4, 2, bytes_(1, k) + bytes_(2, v)) for k, v in preloaded.items()) self._push( frame( TYPE.start, @@ -261,6 +332,8 @@ def start(self, key: str, input_: Any) -> None: # earlier attempt got. The VM is not ready to execute until it has them. + uint(3, 2 if self._cancel_at_start else 1) + entries + # Partial state: a key missing from the entries is read from Restate. + + uint(5, 1) + bytes_(6, key), ) ) @@ -270,9 +343,14 @@ def start(self, key: str, input_: Any) -> None: if self._cancel_at_start: self._push(CANCEL_SIGNAL) - def cancel(self) -> None: - """Restate cancels the invocation now.""" - self._push(CANCEL_SIGNAL) + async def cancel(self) -> None: + """Restate cancels the invocation now; return once the attempt has acted on it.""" + self._signal() + await self.handed_off() + + def shut_down(self) -> None: + """Restate closes the request body, as its inactivity timeout does: the attempt is shut down.""" + self._close() def _over(self, sent: list[Message]) -> bool: return any(m.type in (TYPE.end, TYPE.error) for m in sent) @@ -308,16 +386,13 @@ def _answer(self, message: Message) -> None: if message.flags & REQUESTED_ACK: # Restate signals a cancellation once, not on every commit: what follows is acked # as usual. - ack = frame(TYPE.command_ack, uint(1, self._index)) - if self._cancel_on_commit and not self._signalled: - self._signalled = True - self._push(CANCEL_SIGNAL) - # The ack follows after a moment: together, the attempt would read the ack first - # and the cancellation would find the commit done, with nothing waiting. - asyncio.get_running_loop().call_later(0.02, self._push, ack) - else: - self._push(ack) + if self._cancel_on_commit and self.signalled_at is None: + self._signal() + self._push(frame(TYPE.command_ack, uint(1, self._index))) if message.type == TYPE.get_state_ephemeral: + self.reads += 1 + if self.reads == self._cancel_on_read and self.signalled_at is None: + self._signal() key = message.bytes_of(2).decode() held = self.state.get(key) self._push( @@ -335,17 +410,25 @@ def _answer(self, message: Message) -> None: elif message.type == TYPE.clear_state: self.state.pop(message.bytes_of(1).decode(), None) elif message.type == TYPE.call: - self._push( - frame(TYPE.call_invocation_id_completion, uint(1, message.int_of(10)) + bytes_(16, "inv_started")) + invocation_id = frame( + TYPE.call_invocation_id_completion, uint(1, message.int_of(10)) + bytes_(16, "inv_started") ) - # A call to key ``k`` is never answered: what a started call, whose result nobody - # holds, looks like to the handler. + if self._cancel_on_call is not None and self.signalled_at is None: + if self._cancel_on_call == "before_id": + self._signal() + self._push_alone(invocation_id) + if self._cancel_on_call == "after_id": + self._signal() + else: + self._push(invocation_id) if message.fields.get(5) != [b"k"]: echoed = message.bytes_of(3) self._push(frame(TYPE.call_completion, uint(1, message.int_of(11)) + field(5, 2, value(echoed)))) elif message.type == TYPE.get_state_keys: + if self._cancel_on_keys and self.signalled_at is None: + self._signal() keys = b"".join(bytes_(1, k) for k in self.state) - self._push(frame(TYPE.get_state_keys_completion, uint(1, message.int_of(11)) + field(5, 2, keys))) + self._push(frame(TYPE.get_state_keys_completion, uint(1, message.int_of(11)) + field(17, 2, keys))) async def run(obj: SessionObject, handler_name: str, side: RestateSide) -> None: From 14a0604509d647142546457968b4138e010d2bd5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:16:49 +0000 Subject: [PATCH 08/11] Sessions: an attempt heartbeats while its handler works on its own, annotated or not An attempt told Restate that it makes progress only while an annotation was open, and only the OpenAI agents open one. Everything else that works outside Restate for longer than the inactivity timeout (a minute, by default) was shut down and restarted, over and over: a model request of Pydantic AI, ADK or LangGraph, a tool, a summarizer, any handler of a session object. Each attempt made the request again, and none got past it. On main a turn is kept by its working run, which this branch removed with the selector. An agent whose model takes three seconds, with an inactivity timeout of one, answers there after one request; here it asked its model twenty times in twenty seconds and never answered (`tests/agents_long_work_server.py`). The attempt now heartbeats for as long as its handler runs, when either holds: - nothing of Restate's is outstanding for the handler, so it is working on its own. This is the rule of @restatedev/sessions. The reads and acks of the database's store do not count: the database waits for those. - an annotation is open, as before: it says the handler works beside a call it waits for. With an answer of Restate's outstanding and no annotation it stays silent, so that Restate shuts the attempt down and a wait of days holds no process. The test that un-annotated work is shut down and restarted still holds when the heartbeat is slower than the inactivity timeout, and is named for that; beside it, the same work now finishes in its first attempt. The agents' docs said a turn works on after Restate closed its input, and advised raising the inactivity timeout for long steps. Neither is so here. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- docs/agents/turns.md | 19 ++++--- python/restate/agents/_turn.py | 11 ++-- python/restate/sessions/_driver.py | 32 ++++++++--- tests/agents_long_work_server.py | 89 ++++++++++++++++++++++++++++++ tests/sessions_driver.py | 73 ++++++++++++++++++++++++ tests/sessions_harness.py | 18 +++++- tests/sessions_wire.py | 1 + 7 files changed, 218 insertions(+), 25 deletions(-) create mode 100644 tests/agents_long_work_server.py diff --git a/docs/agents/turns.md b/docs/agents/turns.md index 58744781..2224e449 100644 --- a/docs/agents/turns.md +++ b/docs/agents/turns.md @@ -455,14 +455,17 @@ sequenceDiagram does nothing), never the message that started after it. - The turn ends cancelled whenever the cancellation comes, and the next message starts afresh: the cancelled prompt is over. -- The cancellation reaches the turn's work at once while Restate keeps the - turn's input open. Restate closes it once the turn has sent and received - nothing for the inactivity timeout (a minute by default: a long model - request, or a slow tool). The turn works on, as watching for the - cancellation holds nothing, and a cancellation then reaches it at its next - step, when it next commits or calls. For turns whose steps take longer, - raise Restate's inactivity timeout (the server's - `worker.invoker.inactivity-timeout`). +- The cancellation reaches the turn's work at once. Restate shuts down an + attempt it has heard nothing from for the inactivity timeout (a minute by + default), and the next attempt runs the turn from its start. So while the + turn works on its own (a model request, a tool), its attempt tells Restate + every 20 seconds that it makes progress, and Restate keeps it however long + the step takes. While the turn waits for an answer of Restate's instead (a + tool waiting for an approval, a call), it tells Restate nothing: Restate + shuts the attempt down after the timeout, so that a wait of days holds no + process, and the next attempt gets the cancellation as it starts. A + deployment that sets an inactivity timeout under 20 seconds is shut down + between two of those messages. - A cancellation that comes once the turn answered changes nothing: the answer stands. - A tool cut short by the stop raises the stop's reason, so the model never diff --git a/python/restate/agents/_turn.py b/python/restate/agents/_turn.py index f354db21..bcc602b4 100644 --- a/python/restate/agents/_turn.py +++ b/python/restate/agents/_turn.py @@ -371,12 +371,11 @@ async def chat_turn(ctx: AgentContext, text: str, answer: Callable[[AgentContext While it answers, the object's ``status`` reports the turn. Cancelling the invocation stops the turn (through ``stop_signal_of``) whenever it comes, and cancels the calls its tools made; the handler then fails with the - cancellation. The cancellation reaches the turn's work at once while - Restate keeps the turn's input open; once Restate closed it (nothing - sent or received for its inactivity timeout: a long model request, say), - at the turn's next step, when it next commits or calls (see - ``cancelled`` of ``restate.sessions.internal``). Watching for it holds - nothing: the turn works on. If the attempt ends first, the turn stops with + cancellation. The cancellation reaches the turn's work at once (see + ``cancelled`` of ``restate.sessions.internal``): watching for it holds + nothing, and while the turn works on its own (a model request, a tool) + its attempt tells Restate that it makes progress, so Restate keeps it + past its inactivity timeout. If the attempt ends first, the turn stops with ``AttemptEnded`` and the next attempt carries on. The turn publishes when it starts (the companion's ``start`` does), after each write of its steps that commits (a reply with tool calls, the tools' results: ``answer_once`` diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py index 0882742d..798e7580 100644 --- a/python/restate/sessions/_driver.py +++ b/python/restate/sessions/_driver.py @@ -63,11 +63,17 @@ T = typing.TypeVar("T") HEARTBEAT_INTERVAL = timedelta(seconds=20) -"""How often an attempt with an annotation open tells Restate it makes progress. +"""How often an attempt that works outside Restate tells it that it makes progress. Restate shuts down an attempt it heard nothing from for its inactivity timeout -(a minute, by default): an open annotation (a model request, a tool call) -keeps it alive. +(a minute, by default), and the next one runs the handler from the start: a +model request that takes longer would be made again by every attempt, and +never answered. So an attempt heartbeats while its handler has nothing of +Restate's outstanding (it is then working on its own: a model request, a +tool), and while an annotation is open, which says the same of work that goes +on beside a call. With an answer of Restate's outstanding and no annotation, +it does not: Restate shuts the attempt down after the timeout, and starts the +next when the answer comes, so that a wait of days holds no process. """ SYNC_KEY = "v22/sync" @@ -123,6 +129,9 @@ def __init__( # The handles a cancellation leaves to settle, and is never carried to: the invocation # ids of the calls and sends, and the reads and acks of the database's store. self._left_to_settle: set[int] = set() + # The store's among them: the database waits for those, not the handler, and they come + # promptly, so they do not count as an answer of Restate's the handler waits for. + self._store_waits: set[int] = set() # A cancellation that failed nothing the handler awaits, carried to the next thing it # does: a result of Restate's (``future``), or a call of its database # (``take_carried_cancellation``). A retry of a cancelled invocation knows of it before @@ -181,6 +190,7 @@ async def run(self, handler: Callable[[], Awaitable[bytes]]) -> None: (a model request, say) stops, since nothing it does would count any more. """ self._handler = asyncio.ensure_future(self._cancelled_calls_first(handler)) + self._heartbeats = asyncio.ensure_future(self._heartbeat()) try: output = await self._handler self._last(lambda vm: vm.end_success(output)) @@ -297,6 +307,7 @@ def _tick(self) -> None: while (notification := self.vm.take_notification()) is not None: handle, value = notification self._left_to_settle.discard(handle) + self._store_waits.discard(handle) call = self._unanswered.pop(handle, None) if call is not None: call.answered = True @@ -395,6 +406,7 @@ def store_future(self, handle: int) -> asyncio.Future[Any]: with a journal codec. """ self._left_to_settle.add(handle) + self._store_waits.add(handle) return self._future(handle) def _future(self, handle: int) -> asyncio.Future[Any]: @@ -468,20 +480,22 @@ async def cancel_calls(self) -> list[str]: return cancelled def trace_opened(self) -> None: - """An annotation opened: heartbeat while any is.""" + """An annotation opened: the attempt heartbeats while any is, whatever else is outstanding.""" self._open_traces += 1 - if self._heartbeats is None and self.ended is None: - self._heartbeats = asyncio.ensure_future(self._heartbeat()) def trace_closed(self) -> None: self._open_traces -= 1 - if self._open_traces == 0 and self._heartbeats is not None: - self._heartbeats.cancel() - self._heartbeats = None + + def _awaits_restate(self) -> bool: + """Whether an answer of Restate's that the handler made for is outstanding: a result or an invocation id.""" + return any(handle not in self._store_waits for handle in self._futures) async def _heartbeat(self) -> None: + """Tell Restate the attempt makes progress, while it works outside Restate (see ``HEARTBEAT_INTERVAL``).""" while True: await asyncio.sleep(HEARTBEAT_INTERVAL.total_seconds()) + if self._open_traces == 0 and self._awaits_restate(): + continue try: self.act(lambda vm: vm.heartbeat()) except SdkInternalBaseException: diff --git a/tests/agents_long_work_server.py b/tests/agents_long_work_server.py new file mode 100644 index 00000000..b3cae998 --- /dev/null +++ b/tests/agents_long_work_server.py @@ -0,0 +1,89 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""An agent's turn whose model takes longer than Restate's inactivity timeout, against a real server.""" + +# pylint: disable=missing-function-docstring + +import asyncio +import typing +import uuid +from datetime import timedelta + +import httpx2 +import pytest + +import restate +from agents_conversation import ITEMS # pylint: disable=import-error +from restate import HarnessEnvironment, sessions +from restate.agents._conversation import Conversation, answer_once +from restate.agents._object import AgentObject +from restate.sessions import _driver +from support import RESTATE_IMAGE # pylint: disable=import-error + + +@pytest.fixture(scope="session") +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + +requests: dict[str, int] = {} +"""How many times the model was asked, by the conversation's key.""" + + +async def answer(ctx: sessions.SessionContext, text: str) -> str: + """A scripted framework whose model thinks for longer than the inactivity timeout, and says nothing meanwhile. + + It is what a turn of any framework is while its model request runs: local work, with nothing of Restate's + outstanding. + """ + + async def work(conversation: Conversation) -> str: + requests[ctx.key] = requests.get(ctx.key, 0) + 1 + await asyncio.sleep(3) + await conversation.turn.append_reply({"role": "assistant", "text": f"echo: {text}"}) + return f"echo: {text}" + + return await answer_once(ctx, text, ITEMS, work) + + +thinker = AgentObject("thinker", inactivity_timeout=timedelta(seconds=1)) +thinker.chat(answer, items=ITEMS) + + +@pytest.fixture(scope="session") +async def harness(): + async with restate.create_test_harness(restate.app([thinker]), restate_image=RESTATE_IMAGE) as harness: + yield harness + + +async def test_a_model_request_longer_than_the_inactivity_timeout_is_made_once_and_answered( + harness: HarnessEnvironment, monkeypatch +): + # The attempt heartbeats while the model thinks, faster than the agent's inactivity timeout of a second. + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.3)) + key = str(uuid.uuid4()) + async with httpx2.AsyncClient(timeout=30) as ingress: + sent = await ingress.post( + f"{harness.ingress_url}/thinker/{key}/chat/send", content="hello", headers={"content-type": "text/plain"} + ) + invocation_id = typing.cast(str, sent.json()["invocationId"]) + try: + answered = await ingress.get(f"{harness.ingress_url}/restate/invocation/{invocation_id}/attach", timeout=20) + except httpx2.TimeoutException: + answered = None + finally: + async with httpx2.AsyncClient() as admin: + await admin.patch(f"{harness.admin_api_url}/invocations/{invocation_id}/kill") + assert answered is not None, f"the turn did not answer in 20 s; the model was asked {requests.get(key, 0)} times" + assert answered.status_code == 200, answered.text + assert requests.get(key) == 1 diff --git a/tests/sessions_driver.py b/tests/sessions_driver.py index 2d33f1a1..3b6c175c 100644 --- a/tests/sessions_driver.py +++ b/tests/sessions_driver.py @@ -19,6 +19,7 @@ # pylint: disable=missing-function-docstring import asyncio +from datetime import timedelta import random import typing from collections.abc import Awaitable, Callable, Iterator @@ -146,6 +147,25 @@ async def commits(ctx: sessions.SessionContext) -> str: return "committed" if outcome == "ok" else outcome +@notes.handler() +async def works_alone(ctx: sessions.SessionContext) -> str: + """Works outside Restate, with nothing of Restate's outstanding, until the test lets it go on.""" + await gate_of().wait() + return "done" + + +@notes.handler() +async def works_beside_a_call(ctx: sessions.SessionContext, annotated: bool) -> str: + """Waits for a call that is never answered, working meanwhile, inside an annotation or not.""" + pending = asyncio.ensure_future(ctx.generic_call("Callee", "echo", "A", key="k")) + annotation = internal.annotate(ctx, "tool") if annotated else None + await gate_of().wait() + if annotation is not None: + annotation.end() + pending.cancel() + return "done" + + @notes.handler() async def commit_then_reads(ctx: sessions.SessionContext) -> str: """A commit, a wait outside Restate where the test cancels the invocation, then two reads: of pages the commit left @@ -566,6 +586,59 @@ async def test_a_schema_the_handler_ensures_takes_a_carried_cancellation_as_its_ assert output_of(side.sent()) == "cancelled,ok", describe(side) +def heartbeats(side: RestateSide) -> int: + """How many times the attempt told Restate that it makes progress.""" + return sum(1 for m in side.sent() if m.type == TYPE.awaiting_on) + + +async def beats_while_at(gate_: Gate, handler: str, side: RestateSide) -> int: + """Run ``handler`` until it waits at ``gate_``, leave it there for ten heartbeat intervals, then let it end. + + Returns the heartbeats it sent while it waited there. + """ + running = asyncio.ensure_future(run(notes, handler, side)) + await gate_.reached.wait() + before = heartbeats(side) + await asyncio.sleep(10 * _driver.HEARTBEAT_INTERVAL.total_seconds()) + during = heartbeats(side) - before + gate_.opened.set() + await running + return during + + +@pytest.fixture +def quick_heartbeats(monkeypatch) -> None: + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.02)) + + +async def test_an_attempt_heartbeats_while_its_handler_works_with_nothing_of_restates_outstanding( + gate: Gate, quick_heartbeats: None +): + # A model request, say: Restate hears nothing from the attempt meanwhile, and shuts down one it heard nothing + # from for its inactivity timeout. The next attempt would make the request again, and never get past it. + side = RestateSide() + side.start("kh1", None) + assert await beats_while_at(gate, "works_alone", side) >= 3, describe(side) + assert output_of(side.sent()) == "done", describe(side) + + +async def test_an_attempt_does_not_heartbeat_while_an_answer_of_restates_is_outstanding( + gate: Gate, quick_heartbeats: None +): + # A wait of days for an approval holds no process: Restate shuts the attempt down, and starts the next one when + # the answer comes. + side = RestateSide() + side.start("kh2", False) + assert await beats_while_at(gate, "works_beside_a_call", side) == 0, describe(side) + + +async def test_an_open_annotation_heartbeats_beside_an_outstanding_answer(gate: Gate, quick_heartbeats: None): + # The annotation says the handler is working, on a tool beside the call it waits for. + side = RestateSide() + side.start("kh3", True) + assert await beats_while_at(gate, "works_beside_a_call", side) >= 3, describe(side) + + async def test_a_read_that_asks_restate_nothing_sees_a_carried_cancellation_too_once(gate: Gate): # A read of pages the session holds is answered without a wait on Restate, so a cancellation delivered at the # store's waits had nothing to land on. It is delivered where the handler calls. diff --git a/tests/sessions_harness.py b/tests/sessions_harness.py index 93a15126..d525709e 100644 --- a/tests/sessions_harness.py +++ b/tests/sessions_harness.py @@ -455,10 +455,24 @@ async def test_an_open_annotation_keeps_the_attempt_alive(harness: HarnessEnviro assert await harness.client.object_call(thinks, key=key, arg=None) == 1 -async def test_local_work_without_an_annotation_is_shut_down_and_restarted(harness: HarnessEnvironment): +async def test_local_work_keeps_its_attempt_alive_with_nothing_of_restates_outstanding( + harness: HarnessEnvironment, monkeypatch +): + # The attempt heartbeats while its handler works on its own, annotation or not: here faster than the object's + # inactivity timeout of a second, so the work is done in the first attempt. + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.3)) + key = str(uuid.uuid4()) + assert await harness.client.object_call(daydreams, key=key, arg=None) == 1 + assert daydreamt.get(key, 0) == 1 + + +async def test_local_work_is_shut_down_and_restarted_when_the_heartbeat_is_slower_than_the_inactivity_timeout( + harness: HarnessEnvironment, +): key = str(uuid.uuid4()) sent = await harness.client.object_send(daydreams, key=key, arg=None) - # Each attempt is shut down after a second with nothing pending, and restarted right away. + # The heartbeat comes every 20 seconds, and the object's inactivity timeout is a second: each attempt is shut + # down after a second with nothing heard from it, and restarted right away. for _ in range(300): if attempts.get(key, 0) >= 4: break diff --git a/tests/sessions_wire.py b/tests/sessions_wire.py index 8319fd96..7300a6da 100644 --- a/tests/sessions_wire.py +++ b/tests/sessions_wire.py @@ -111,6 +111,7 @@ class TYPE: # pylint: disable=too-few-public-methods error = 0x0002 end = 0x0003 command_ack = 0x0004 + awaiting_on = 0x0006 get_state_ephemeral = 0x0200 get_state_ephemeral_notification = 0x0300 input = 0x0400 From 1cd3919ca8ea8291cfd63091e0479d883abd30ab Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:26:48 +0000 Subject: [PATCH 09/11] Agents: a dead attempt's model request is cancelled with it When Restate shut an attempt down in the middle of a model request, the request ran on to its end in the dead attempt, beside the one the next attempt made, and was paid for twice. The docs say a dead attempt stops, a model's request included. The request runs in a task of `Stop.guard`, which waits for it or for the stop, whichever comes first. The end of an attempt cancels the handler's task, and that cancellation landed on the guard's wait: the guard let go of its watcher and left the request running, with nobody awaiting it. The guard now cancels its work when it is itself cancelled. Nested guards pass it on, down to the request. With a model that outlasts the inactivity timeout twice and then answers: three requests started and all three completed before; now two are cancelled and one completes. On main the guard is the same, but nothing shuts a turn down there, so it does not show. Also a sentence in the heartbeat's docstring: an answer of Restate's counts as outstanding from the call to its answer, awaited or not. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- python/restate/agents/_turn.py | 14 ++- python/restate/sessions/_driver.py | 5 +- tests/agents_dead_attempt_server.py | 132 ++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 tests/agents_dead_attempt_server.py diff --git a/python/restate/agents/_turn.py b/python/restate/agents/_turn.py index bcc602b4..cb692913 100644 --- a/python/restate/agents/_turn.py +++ b/python/restate/agents/_turn.py @@ -112,12 +112,18 @@ async def guard(self, work: Awaitable[T]) -> T: If it stops first, ``work`` is cancelled and the stop reason is raised. Use it for a framework request that stopping the turn must cut - short. + short. Cancelling the task that awaits it (as the end of an attempt + cancels its handler) cancels ``work`` too. """ task = asyncio.ensure_future(work) stopping = asyncio.ensure_future(self._event.wait()) try: await asyncio.wait({task, stopping}, return_when=asyncio.FIRST_COMPLETED) + except BaseException: + # The guard itself is cancelled: so is the work, whose end nobody awaits. + task.cancel() + task.add_done_callback(_retrieve) + raise finally: stopping.cancel() if task.done(): @@ -129,6 +135,12 @@ async def guard(self, work: Awaitable[T]) -> T: raise self.reason +def _retrieve(task: asyncio.Future[typing.Any]) -> None: + """Retrieve the end of a task nobody awaits, so that asyncio logs no "exception was never retrieved".""" + if not task.cancelled(): + task.exception() + + _STOP: ScopeKey[Stop] = ScopeKey("stop_signal_of") diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py index 798e7580..07ce7998 100644 --- a/python/restate/sessions/_driver.py +++ b/python/restate/sessions/_driver.py @@ -73,7 +73,10 @@ tool), and while an annotation is open, which says the same of work that goes on beside a call. With an answer of Restate's outstanding and no annotation, it does not: Restate shuts the attempt down after the timeout, and starts the -next when the answer comes, so that a wait of days holds no process. +next when the answer comes, so that a wait of days holds no process. An +answer is outstanding from the moment the call is made until Restate gives +it, whether or not the handler awaits it: work done after a call whose result +is left aside gets no heartbeat until that call is answered. """ SYNC_KEY = "v22/sync" diff --git a/tests/agents_dead_attempt_server.py b/tests/agents_dead_attempt_server.py new file mode 100644 index 00000000..560fb630 --- /dev/null +++ b/tests/agents_dead_attempt_server.py @@ -0,0 +1,132 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A dead attempt's model request stops: Restate shuts the attempt down mid-request, and the retry asks again.""" + +# pylint: disable=missing-function-docstring + +import asyncio +import typing +import uuid +from collections import Counter +from datetime import timedelta + +import httpx2 +import pytest + +import restate +from agents_conversation import ITEMS # pylint: disable=import-error +from restate import HarnessEnvironment, sessions +from restate.agents._conversation import Conversation, answer_once +from restate.agents._object import AgentObject +from restate.agents._turn import Stop, stop_signal_of +from support import RESTATE_IMAGE # pylint: disable=import-error + + +@pytest.fixture(scope="session") +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + +started: Counter[str] = Counter() +"""How many model requests started, by the conversation's key.""" +cancelled: Counter[str] = Counter() +"""How many model requests were cancelled, by the conversation's key.""" +completed: Counter[str] = Counter() +"""How many model requests ran to their end, by the conversation's key.""" + +SLOW = 4.0 +"""How long a slow model request takes: longer than the inactivity timeout, shorter than a heartbeat (20 s).""" + + +async def model(key: str) -> str: + """A model request: its first two are slow, so that Restate shuts their attempts down; the third is quick.""" + started[key] += 1 + try: + await asyncio.sleep(SLOW if started[key] < 3 else 0.1) + except asyncio.CancelledError: + cancelled[key] += 1 + raise + completed[key] += 1 + return "done" + + +async def answer(ctx: sessions.SessionContext, text: str) -> str: + """A scripted framework whose model request goes through the turn's stop signal, as the frameworks' do.""" + + async def work(conversation: Conversation) -> str: + stop = stop_signal_of(ctx) + assert stop is not None + await stop.guard(model(ctx.key)) + await conversation.turn.append_reply({"role": "assistant", "text": f"echo: {text}"}) + return f"echo: {text}" + + return await answer_once(ctx, text, ITEMS, work) + + +sleeper = AgentObject("sleeper", inactivity_timeout=timedelta(seconds=1)) +sleeper.chat(answer, items=ITEMS) + + +@pytest.fixture(scope="session") +async def harness(): + async with restate.create_test_harness(restate.app([sleeper]), restate_image=RESTATE_IMAGE) as harness: + yield harness + + +async def test_a_dead_attempts_model_request_is_cancelled(harness: HarnessEnvironment): + # The attempt heartbeats every 20 s, by default: past the agent's inactivity timeout of a second, Restate + # shuts each slow attempt down in the middle of its model request, and the next attempt asks again. + key = str(uuid.uuid4()) + async with httpx2.AsyncClient(timeout=60) as ingress: + sent = await ingress.post( + f"{harness.ingress_url}/sleeper/{key}/chat/send", content="hello", headers={"content-type": "text/plain"} + ) + invocation_id = typing.cast(str, sent.json()["invocationId"]) + try: + answered = await ingress.get(f"{harness.ingress_url}/restate/invocation/{invocation_id}/attach", timeout=45) + except httpx2.TimeoutException: + answered = None + finally: + async with httpx2.AsyncClient() as admin: + await admin.patch(f"{harness.admin_api_url}/invocations/{invocation_id}/kill") + # Leave a dead attempt's request the time to end on its own, had it not been cancelled. + await asyncio.sleep(SLOW + 1) + counts = f"started {started[key]}, cancelled {cancelled[key]}, completed {completed[key]}" + assert answered is not None, f"the turn did not answer in 45 s: {counts}" + assert answered.status_code == 200, answered.text + assert started[key] >= 3, counts + assert completed[key] == 1, counts + assert cancelled[key] == started[key] - 1, counts + + +async def test_cancelling_the_task_that_awaits_a_guard_cancels_its_work(): + # As the attempt's end cancels the handler's task, while the guard of its model request awaits. + stop = Stop() + events: list[str] = [] + + async def work() -> None: + events.append("started") + try: + await asyncio.sleep(10) + except asyncio.CancelledError: + events.append("cancelled") + raise + events.append("completed") + + task = asyncio.ensure_future(stop.guard(work())) + await asyncio.sleep(0.01) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.sleep(0.01) + assert events == ["started", "cancelled"] From 2af0fd52d19caa9ca0b428fc8a3846ee2fda9a33 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:44:06 +0000 Subject: [PATCH 10/11] Sessions tests: a saga, and a transaction under a cancellation, as @restatedev/sessions tests them The two things a session object has to hold, driven on the wire on both stores, from the tests of the same name in @restatedev/sessions. A saga (`sessions_saga.py`). A handler has no journal to replay, so the saga keeps its progress in `ctx.db` and resumes from what is stored: cancelled while a step's call is pending, cancelled between two steps, a crash in the middle of the compensation that the next attempt finishes with the same idempotency keys, a step that fails terminally, and a shutdown while a step's call is outstanding, after which the next attempt calls again with the same key and undoes nothing. One case writes down a limit: a call made while a cancellation is carried is still made, and its callee is not cancelled; the saga undoes that step too. A transaction under a cancellation (`sessions_transaction_cancel.py`): it either committed, with each of its sends made once, or did nothing, and it says which. Two sweeps deliver the cancel signal before each thing the attempt asks Restate for, and read the rows back through a second attempt. In the second sweep the transaction is not the handler's first call, so the signal is also carried into it: it is then refused, with no row and no send. Where Python differs from @restatedev/sessions: at a shutdown the handler's task is cancelled, so its await raises asyncio's cancellation where TypeScript's rejects with `AttemptShutDown`. Neither is a terminal error, which is what a saga needs; two tests say so. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- tests/sessions_saga.py | 410 ++++++++++++++++++ tests/sessions_transaction_cancel.py | 603 +++++++++++++++++++++++++++ tests/sessions_wire.py | 182 +++++++- 3 files changed, 1177 insertions(+), 18 deletions(-) create mode 100644 tests/sessions_saga.py create mode 100644 tests/sessions_transaction_cancel.py diff --git a/tests/sessions_saga.py b/tests/sessions_saga.py new file mode 100644 index 00000000..4932d736 --- /dev/null +++ b/tests/sessions_saga.py @@ -0,0 +1,410 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A saga written as a session object, run on the wire (``sessions_wire``). + +Its progress lives in ``ctx.db``, every attempt resumes from what is stored, +and a cancellation or a terminal failure compensates the steps that may have +happened, in reverse, with idempotency keys of their own. +""" + +# pylint: disable=missing-function-docstring + +import asyncio +from collections.abc import Iterator +from typing import Any, Optional + +import pytest + +from restate import TerminalError, sessions +from restate.sessions import _driver +from sessions_wire import TYPE, Made, RestateSide, commits, outcome, run # pylint: disable=import-error + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + + +@pytest.fixture(autouse=True, params=["vm", "python"]) +def store(request, monkeypatch): + """Each test runs on both stores: the VM's, which the extension reads and writes directly, and the Python store + over the context's state commands, which an endpoint with a journal codec uses.""" + if request.param == "python": + monkeypatch.setattr(_driver.VmHost, "vm", property(lambda self: None)) + return request.param + + +UNDO = {"reserve": ("Inventory", "release"), "charge": ("Payments", "refund")} +"""Each step, and the call that undoes it.""" + +HAPPENED = {"started": ["reserve"], "reserved": ["charge", "reserve"], "charged": ["charge", "reserve"]} +"""The steps that may have happened by an order's status, last first.""" + + +def is_cancellation(error: BaseException) -> bool: + return isinstance(error, TerminalError) and error.status_code == 409 and error.message == "cancelled" + + +def name_of(error: BaseException) -> str: + """What ``place`` caught, as a test compares it: ``cancelled``, or the class's qualified name.""" + return "cancelled" if is_cancellation(error) else f"{type(error).__module__}.{type(error).__qualname__}" + + +class Outside: + """Work the handler does outside Restate between its two steps, and what it caught; a test holds it there.""" + + def __init__(self) -> None: + self.reached = asyncio.Event() + self.opened = asyncio.Event() + self.opened.set() + self.caught: list[str] = [] + self.terminal: list[bool] = [] + """Whether each error ``caught`` has is a ``TerminalError``, which the saga compensates on.""" + + def hold(self) -> None: + self.opened.clear() + + async def work(self) -> None: + self.reached.set() + await self.opened.wait() + + +_outside: list[Outside] = [] + + +@pytest.fixture(autouse=True) +def outside() -> Iterator[Outside]: + made = Outside() + _outside.append(made) + yield made + _outside.remove(made) + + +orders = sessions.SessionObject( + "Orders", migrations=["CREATE TABLE orders (id TEXT PRIMARY KEY, status TEXT NOT NULL, undo TEXT)"] +) + + +@orders.handler() +async def place(ctx: sessions.SessionContext, id_: str) -> str: + here = _outside[-1] + + def call(service: str, handler: str, step: str) -> Any: + # The same on every attempt: a repeated call reaches the invocation the first attempt started. + return ctx.generic_call(service, handler, id_, key=id_, idempotency_key=f"{ctx.request.id}/{step}") + + async def read() -> Optional[dict[str, Any]]: + return await ctx.db.get("SELECT status, undo FROM orders WHERE id = ?", [id_]) + + async def record(status: str) -> None: + await ctx.db.execute("UPDATE orders SET status = ? WHERE id = ?", [status, id_]) + + # A step whose call failed terminally did not happen, and has nothing to undo. + did_not_happen: Optional[str] = None + + async def step(name: str, service: str, handler: str) -> None: + nonlocal did_not_happen + try: + await call(service, handler, name) + except TerminalError as error: + if not is_cancellation(error): + did_not_happen = name + raise + + async def compensate() -> None: + # Undo, from what is stored: a retry that finds the saga compensating goes on with the same list, and calls + # again with the same keys. + order = await read() + if order is None or order["status"] == "compensated": + return + undo = order["undo"] or "" + if order["status"] != "compensating": + undo = ",".join(s for s in HAPPENED[order["status"]] if s != did_not_happen) + await ctx.db.execute("UPDATE orders SET status = 'compensating', undo = ? WHERE id = ?", [undo, id_]) + for s in filter(None, undo.split(",")): + service, handler = UNDO[s] + await call(service, handler, f"undo-{s}") + await record("compensated") + + try: + order = await read() + if order is None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO orders (id, status) VALUES (?, 'started')", [id_]) + order = {"status": "started", "undo": None} + if order["status"] in ("compensating", "compensated"): + raise TerminalError(f"order {id_} was cancelled") + if order["status"] == "started": + await step("reserve", "Inventory", "reserve") + await here.work() + await record("reserved") + order["status"] = "reserved" + if order["status"] == "reserved": + await step("charge", "Payments", "charge") + await record("charged") + return "charged" + except BaseException as error: + here.caught.append(name_of(error)) + here.terminal.append(isinstance(error, TerminalError)) + # A cancellation is a TerminalError; the attempt's end (a shutdown) is not, and the next attempt resumes: + # nothing to compensate. + if not isinstance(error, TerminalError): + raise + await compensate() + raise + + +@orders.view() +async def status(ctx: sessions.ViewContext, id_: str) -> Optional[dict[str, Any]]: + return await ctx.db.get("SELECT status, undo FROM orders WHERE id = ?", [id_]) + + +async def stored(state: dict[str, bytes], key: str, id_: str) -> Optional[dict[str, Any]]: + """The stored row of order ``id_``, read by a view on ``state``.""" + side = RestateSide(state) + side.start(key, id_) + await run(orders, "status", side) + ended = outcome(side.sent()) + assert ended is not None and ended[0] == "value", ended + return ended[1] + + +def target(c: Made) -> str: + """A call as a test compares it: its target and idempotency key.""" + return f"{c.target} {c.idempotency_key}" + + +def describe(side: RestateSide) -> str: + """What the attempt wrote, as message types in order: for a failure's message.""" + return " ".join(f"{m.type:#06x}" for m in side.sent()) + + +class Placing: + """An attempt of ``place`` for an order, running while the test plays Restate's side of it.""" + + def __init__(self, state: dict[str, bytes], key: str, id_: str, **options: Any) -> None: + self.side = RestateSide(state, id_per_call=True, **options) + self.side.start(key, id_) + self.done = asyncio.ensure_future(run(orders, "place", self.side)) + + +CANCELLED = ("failure", 409, "cancelled") +"""The invocation's end with the cancellation, as Restate is told it.""" + + +def keyed(name: str, store: str) -> str: + """The test's key on this store: the page cache is the process's, and every test runs on both stores.""" + return f"{name}-{store}" + + +async def test_a_without_a_cancellation_reserves_and_charges_once_each_and_ends_charged(store: str): + state: dict[str, bytes] = {} + key = keyed("sa", store) + p = Placing(state, key, "o1") + await p.done + r = p.side + assert outcome(r.sent()) == ("value", "charged"), describe(r) + assert [target(c) for c in r.calls] == ["Inventory/reserve inv_test/reserve", "Payments/charge inv_test/charge"] + assert r.cancels == [] + assert await stored(state, key, "o1") == {"status": "charged", "undo": None} + + +async def test_b_cancelled_while_reserve_is_pending_it_is_cancelled_released_and_the_invocation_ends_cancelled( + store: str, +): + state: dict[str, bytes] = {} + key = keyed("sb", store) + p = Placing(state, key, "o1", hold=["Inventory/reserve"]) + r = p.side + await r.until(lambda: r.has_called("Inventory/reserve"), "the reserve call") + await r.cancel() + await p.done + assert outcome(r.sent()) == CANCELLED, describe(r) + assert [target(c) for c in r.calls] == [ + "Inventory/reserve inv_test/reserve", + "Inventory/release inv_test/undo-reserve", + ] + # The cancel command names the reserve call's invocation. + assert r.cancels == [r.calls[0].invocation_id], describe(r) + assert await stored(state, key, "o1") == {"status": "compensated", "undo": "reserve"} + + +async def test_c_cancelled_while_charge_is_pending_refunds_then_releases(store: str): + state: dict[str, bytes] = {} + key = keyed("sc", store) + p = Placing(state, key, "o1", hold=["Payments/charge"]) + r = p.side + await r.until(lambda: r.has_called("Payments/charge"), "the charge call") + await r.cancel() + await p.done + assert outcome(r.sent()) == CANCELLED, describe(r) + assert [target(c) for c in r.calls] == [ + "Inventory/reserve inv_test/reserve", + "Payments/charge inv_test/charge", + "Payments/refund inv_test/undo-charge", + "Inventory/release inv_test/undo-reserve", + ] + assert r.cancels == [r.calls[1].invocation_id], describe(r) + assert await stored(state, key, "o1") == {"status": "compensated", "undo": "charge,reserve"} + + +async def test_d_known_limitation_a_signal_on_the_commit_of_reserved_is_carried_to_the_charge_call_which_is_issued_fails_and_is_not_cancelled( # noqa: E501 + store: str, +): + # The commit that records `reserved` is under way when the signal comes: it lands, and the cancellation is + # carried to the next await, the `charge` call. That call is still issued (it is on the wire) and its result + # fails with the cancellation at once, but no cancel command is sent for it, so the charge may run. The saga then + # compensates both steps, so a charge that did run is refunded. + # On a fresh key the attempt's commits are the schema's, `started`'s and `reserved`'s: the signal goes in with + # the third. + state: dict[str, bytes] = {} + key = keyed("sd", store) + p = Placing(state, key, "o1", cancel_on_commit=3) + await p.done + r = p.side + sent = r.sent() + assert outcome(sent) == CANCELLED, describe(r) + # The premise: before the signal, three commits and the reserve call; the first command after it is the charge + # call. + assert r.signalled_at is not None, describe(r) + assert commits(sent[: r.signalled_at]) == 3, describe(r) + after = next((m for m in sent[r.signalled_at :] if 0x0400 <= m.type < 0x8000), None) + assert after is not None and after.type == TYPE.call, describe(r) + assert [target(c) for c in r.calls] == [ + "Inventory/reserve inv_test/reserve", + "Payments/charge inv_test/charge", + "Payments/refund inv_test/undo-charge", + "Inventory/release inv_test/undo-reserve", + ] + # The stray charge: no cancel command for it, nor for anything. + assert r.cancels == [], describe(r) + assert await stored(state, key, "o1") == {"status": "compensated", "undo": "charge,reserve"} + + +async def test_e_cancelled_while_working_outside_restate_the_next_db_call_is_refused_and_it_compensates_from_started( + store: str, outside: Outside +): + state: dict[str, bytes] = {} + key = keyed("se", store) + outside.hold() + p = Placing(state, key, "o1") + r = p.side + await r.until(outside.reached.is_set, "the work between the steps") + # Nothing of Restate's is outstanding, so the cancellation is carried; this returns once the attempt has it. + await r.cancel() + before = len(r.sent()) + outside.opened.set() + await p.done + assert outcome(r.sent()) == CANCELLED, describe(r) + assert outside.caught == ["cancelled"] + # The refused `reserved` wrote nothing: the first command after the signal is the write of `compensating`'s + # commit, whose row says `started` was the last step recorded. + assert [target(c) for c in r.calls] == [ + "Inventory/reserve inv_test/reserve", + "Inventory/release inv_test/undo-reserve", + ] + assert r.cancels == [] + assert before == r.signalled_at, describe(r) + # After the signal, two commits: `compensating`'s and `compensated`'s. + assert commits(r.sent()[before:]) == 2, describe(r) + assert await stored(state, key, "o1") == {"status": "compensated", "undo": "reserve"} + + +async def test_f_a_crash_in_the_middle_of_compensating_the_retry_of_the_cancelled_invocation_finishes_it_with_the_same_keys( # noqa: E501 + store: str, outside: Outside +): + state: dict[str, bytes] = {} + key = keyed("sf", store) + first = Placing(state, key, "o1", hold=["Inventory/reserve", "Inventory/release"]) + r1 = first.side + await r1.until(lambda: r1.has_called("Inventory/reserve"), "the reserve call") + await r1.cancel() + await r1.until(lambda: r1.has_called("Inventory/release"), "the release call") + # `compensating` was committed before `release` was called. + r1.shut_down() + await first.done + assert outcome(r1.sent()) is None, describe(r1) + assert await stored(state, key, "o1") == {"status": "compensating", "undo": "reserve"} + + outside.caught.clear() + second = Placing(state, key, "o1", cancel_at_start=True) + await second.done + r2 = second.side + # Its first await, the read of the stored state, got the cancellation. + assert outside.caught == ["cancelled"] + assert outcome(r2.sent()) == CANCELLED, describe(r2) + assert [target(c) for c in r2.calls] == ["Inventory/release inv_test/undo-reserve"] + assert r2.calls[0].idempotency_key == r1.calls[1].idempotency_key + assert await stored(state, key, "o1") == {"status": "compensated", "undo": "reserve"} + + +async def test_g_a_step_that_fails_terminally_only_the_step_before_it_is_undone_and_the_invocation_ends_with_that_failure( # noqa: E501 + store: str, +): + state: dict[str, bytes] = {} + key = keyed("sg", store) + p = Placing(state, key, "o1", fail={"Payments/charge": (402, "declined")}) + await p.done + r = p.side + assert outcome(r.sent()) == ("failure", 402, "declined"), describe(r) + assert [target(c) for c in r.calls] == [ + "Inventory/reserve inv_test/reserve", + "Payments/charge inv_test/charge", + "Inventory/release inv_test/undo-reserve", + ] + assert r.cancels == [] + assert await stored(state, key, "o1") == {"status": "compensated", "undo": "reserve"} + + +async def shut_down_while_reserve_is_outstanding(state: dict[str, bytes], key: str) -> RestateSide: + """Run ``place`` until its reserve call is outstanding, then shut the attempt down.""" + first = Placing(state, key, "o1", hold=["Inventory/reserve"]) + r1 = first.side + await r1.until(lambda: r1.has_called("Inventory/reserve"), "the reserve call") + r1.shut_down() + await first.done + return r1 + + +async def test_h_shut_down_while_reserve_is_outstanding_no_compensation_and_the_next_attempt_resumes_with_the_same_key( # noqa: E501 + store: str, outside: Outside +): + state: dict[str, bytes] = {} + key = keyed("sh", store) + r1 = await shut_down_while_reserve_is_outstanding(state, key) + # The await failed with the attempt's end, which is no TerminalError. + assert len(outside.caught) == 1 and outside.caught != ["cancelled"], outside.caught + assert outside.terminal == [False], outside.caught + assert outcome(r1.sent()) is None, describe(r1) + assert [target(c) for c in r1.calls] == ["Inventory/reserve inv_test/reserve"] + assert await stored(state, key, "o1") == {"status": "started", "undo": None} + + second = Placing(state, key, "o1") + await second.done + r2 = second.side + assert outcome(r2.sent()) == ("value", "charged"), describe(r2) + assert [target(c) for c in r2.calls] == [ + "Inventory/reserve inv_test/reserve", + "Payments/charge inv_test/charge", + ] + assert r2.calls[0].idempotency_key == r1.calls[0].idempotency_key + assert await stored(state, key, "o1") == {"status": "charged", "undo": None} + + +async def test_h_a_shutdown_cancels_the_handlers_task(store: str, outside: Outside): + # The end of an attempt cancels the handler's task (``AttemptDriver._end``), so what the handler's await raises + # is asyncio's cancellation: not a ``TerminalError``, which is what keeps the saga from undoing anything. This is + # where Python differs from @restatedev/sessions, whose await rejects with ``AttemptShutDown``. + await shut_down_while_reserve_is_outstanding({}, keyed("sh2", store)) + assert outside.caught == ["asyncio.exceptions.CancelledError"] diff --git a/tests/sessions_transaction_cancel.py b/tests/sessions_transaction_cancel.py new file mode 100644 index 00000000..923a0887 --- /dev/null +++ b/tests/sessions_transaction_cancel.py @@ -0,0 +1,603 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A transaction under a cancellation, on the wire (``sessions_wire``). + +Wherever the signal lands, ``transaction()`` either returns, and then its rows +are committed and each of its sends went out once, or raises the cancellation +(``TerminalError("cancelled", 409)``), and then it committed nothing and sent +nothing. And the handler sees one cancellation for the one signal. +""" + +# pylint: disable=missing-function-docstring + +import asyncio +from collections.abc import Awaitable, Callable, Iterator +from dataclasses import dataclass +from typing import Any + +import pytest + +from restate import TerminalError, sessions +from restate.sessions import _driver +from sessions_wire import ( # pylint: disable=import-error + REQUESTED_ACK, + TYPE, + Made, + Message, + RestateSide, + outcome, + run, +) + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + + +@pytest.fixture(autouse=True, params=["vm", "python"]) +def store(request, monkeypatch): + """Each test runs on both stores: the VM's, which the extension reads and writes directly, and the Python store + over the context's state commands, which an endpoint with a journal codec uses.""" + if request.param == "python": + monkeypatch.setattr(_driver.VmHost, "vm", property(lambda self: None)) + return request.param + + +def is_cancellation(error: BaseException) -> bool: + return isinstance(error, TerminalError) and error.status_code == 409 and error.message == "cancelled" + + +async def said(step: Callable[[], Awaitable[Any]]) -> str: + """How ``step`` ended: ``ok``, ``cancelled``, or the name of what else it failed with.""" + try: + await step() + return "ok" + except Exception as error: # pylint: disable=broad-exception-caught + return "cancelled" if is_cancellation(error) else type(error).__name__ + + +class Seen: + """What a handler reports from where it cannot return it, and where it works outside Restate for a test.""" + + def __init__(self) -> None: + self.seen: list[str] = [] + """How each noted step ended, by class name (or ``cancelled``).""" + self.terminal: list[bool] = [] + """Whether each error ``seen`` has is a ``TerminalError``, which a saga compensates on.""" + self.reached = asyncio.Event() + self.opened = asyncio.Event() + self.opened.set() + + def note(self, error: BaseException | None) -> None: + if error is None: + self.seen.append("ok") + return + self.terminal.append(isinstance(error, TerminalError)) + self.seen.append( + "cancelled" if is_cancellation(error) else f"{type(error).__module__}.{type(error).__qualname__}" + ) + + def hold(self) -> None: + self.opened.clear() + + async def work(self) -> None: + """Work outside Restate, until the test lets it go on.""" + self.reached.set() + await self.opened.wait() + + +_seen: list[Seen] = [] + + +@pytest.fixture(autouse=True) +def seen() -> Iterator[Seen]: + made = Seen() + _seen.append(made) + yield made + _seen.remove(made) + + +ledger = sessions.SessionObject("Ledger", migrations=["CREATE TABLE rows (id INTEGER PRIMARY KEY, body TEXT)"]) + + +async def insert_and_send(db: sessions.Database, body: str) -> None: + """One transaction that reads, inserts ``body`` and sends ``body`` to ``Mail/notify``.""" + async with db.transaction() as tx: + await tx.get("SELECT count(*) AS n FROM rows") + await tx.execute("INSERT INTO rows (body) VALUES (?)", [body]) + tx.generic_send("Mail", "notify", body, key=body) + + +def statement(ctx: sessions.SessionContext, body: str) -> Callable[[], Awaitable[Any]]: + return lambda: ctx.db.execute("INSERT INTO rows (body) VALUES (?)", [body]) + + +def echo(ctx: sessions.SessionContext) -> Awaitable[Any]: + """The call each handler makes last: ``Callee/echo``.""" + return ctx.generic_call("Callee", "echo", "A", key="a") + + +@ledger.handler() +async def seed(ctx: sessions.SessionContext) -> str: + """Opens the database, so that the schema's commit is behind the key.""" + return "seeded" + + +@ledger.handler() +async def sweep(ctx: sessions.SessionContext) -> str: + """One transaction, one statement, one call: how each ended.""" + tx = await said(lambda: insert_and_send(ctx.db, "tx")) + after = await said(statement(ctx, "after")) + call = await said(lambda: echo(ctx)) + return f"{tx},{after},{call}" + + +@ledger.handler() +async def sweep_later(ctx: sessions.SessionContext) -> str: + """A statement, then the sweep's: the transaction is not the first call of the database, so a signal that lands + during the statement is carried into it.""" + before = await said(statement(ctx, "before")) + tx = await said(lambda: insert_and_send(ctx.db, "tx")) + after = await said(statement(ctx, "after")) + call = await said(lambda: echo(ctx)) + return f"{before},{tx},{after},{call}" + + +@ledger.handler() +async def body_calls(ctx: sessions.SessionContext, catches: bool) -> str: + """A transaction whose body awaits a call; it catches that call's failure if ``catches``.""" + in_body = "not reached" + + def work() -> Awaitable[Any]: + return ctx.generic_call("Slow", "work", "W", key="a") + + async def transaction() -> None: + nonlocal in_body + async with ctx.db.transaction() as t: + await t.execute("INSERT INTO rows (body) VALUES ('tx')") + called = "ok" + if catches: + called = await said(work) + else: + await work() + in_body = called + t.generic_send("Mail", "notify", "tx", key="tx") + + tx = await said(transaction) + after = await said(statement(ctx, "after")) + return f"{in_body},{tx},{after}" + + +@ledger.handler() +async def two(ctx: sessions.SessionContext) -> str: + """Two transactions, one after the other, then a statement.""" + first = await said(lambda: insert_and_send(ctx.db, "first")) + second = await said(lambda: insert_and_send(ctx.db, "second")) + after = await said(statement(ctx, "after")) + return f"{first},{second},{after}" + + +@ledger.handler() +async def noted(ctx: sessions.SessionContext) -> str: + """The sweep's transaction, noting how it ended where a test can read it.""" + here = _seen[-1] + try: + await insert_and_send(ctx.db, "tx") + except BaseException as error: + here.note(error) + # The attempt's end is not the handler's to swallow. + if not isinstance(error, Exception): + raise + else: + here.note(None) + return "done" + + +@ledger.handler() +async def awaits_a_call(ctx: sessions.SessionContext) -> str: + """A call whose result Restate holds, noting how its await ended where a test can read it.""" + here = _seen[-1] + try: + await ctx.generic_call("Slow", "work", "W", key="a") + except BaseException as error: + here.note(error) + raise + here.note(None) + return "done" + + +@ledger.handler() +async def throws(ctx: sessions.SessionContext) -> str: + """A transaction whose body writes, works outside Restate, and raises.""" + here = _seen[-1] + + async def transaction() -> None: + async with ctx.db.transaction() as t: + await t.execute("INSERT INTO rows (body) VALUES ('tx')") + t.generic_send("Mail", "notify", "tx", key="tx") + await here.work() + await t.get("SELECT count(*) AS n FROM rows") + raise ValueError("the body failed") + + tx = await said(transaction) + after = await said(statement(ctx, "after")) + call = await said(lambda: echo(ctx)) + return f"{tx},{after},{call}" + + +@ledger.view() +async def rows_of(ctx: sessions.ViewContext) -> list[str]: + return [str(row["body"]) for row in await ctx.db.query("SELECT body FROM rows ORDER BY id")] + + +# --- Running attempts + + +def describe(side: RestateSide) -> str: + """What the attempt wrote, as message types in order (``!`` for a command that asks for an ack).""" + return " ".join(f"{m.type:#06x}{'!' if m.flags & REQUESTED_ACK else ''}" for m in side.sent()) + + +async def attempt(handler: str, state: dict[str, bytes], key: str, input_: Any = None, **options: Any) -> RestateSide: + """Run ``handler`` on ``state`` for ``key`` with Restate's side ``options``, answering everything.""" + side = RestateSide(state, id_per_call=True, **options) + side.start(key, input_) + await run(ledger, handler, side) + return side + + +async def seeded(key: str) -> dict[str, bytes]: + """The state an earlier invocation of ``key`` left: its schema is applied, so an attempt's commits are its own.""" + side = await attempt("seed", {}, key) + assert returned(side) == "seeded", describe(side) + return side.state + + +async def stored_rows(state: dict[str, bytes], key: str) -> list[str]: + """The rows stored in ``state``, read by a later attempt.""" + side = RestateSide(state) + side.start(key, None) + await run(ledger, "rows_of", side) + ended = outcome(side.sent()) + assert ended is not None and ended[0] == "value", ended + return list(ended[1]) + + +def returned(side: RestateSide) -> str: + """The handler's output, which these handlers end with.""" + ended = outcome(side.sent()) + assert ended is not None and ended[0] == "value", f"the handler ended with {ended}: {describe(side)}" + return str(ended[1]) + + +def sends_of(side: RestateSide, body: str) -> list[Made]: + """The sends of ``body`` the attempt made.""" + return [s for s in side.sends if s.input == f'"{body}"'] + + +def is_command(m: Message) -> bool: + return 0x0400 <= m.type < 0x8000 + + +def acks_asked(sent: list[Message]) -> list[int]: + """The positions in ``sent`` of the commands that asked for an ack.""" + return [i for i, m in enumerate(sent) if is_command(m) and m.flags & REQUESTED_ACK] + + +def writes_before_send(side: RestateSide) -> list[int]: + """The types of the commands the attempt sent before its first send.""" + sent = side.sent() + first = next(i for i, m in enumerate(sent) if m.type == TYPE.one_way_call) + return [m.type for m in sent[:first] if is_command(m) and m.type != TYPE.input] + + +def send_is_inside_commit(sent: list[Message], store: str, commit: int) -> bool: + """Whether the first send went out between the writes of the ``commit``-th commit that asks for an ack (from 0) + and Restate's ack of it. + + On the VM's store the commit's last write asks for the ack, and the sends follow it; on the Python store the + sends follow the writes, and the sync that asks for the ack follows the sends. + """ + acks = acks_asked(sent) + send = next(i for i, m in enumerate(sent) if m.type == TYPE.one_way_call) + if store == "vm": + return acks[commit] < send < acks[commit + 1] + before = acks[commit - 1] if commit > 0 else 0 + writes = [i for i in range(before + 1, send) if sent[i].type == TYPE.set_state] + return bool(writes) and before < send < acks[commit] and sent[acks[commit]].type == TYPE.clear_state + + +def keyed(name: str, store: str) -> str: + """The test's key on this store: the page cache is the process's, and every test runs on both stores.""" + return f"{name}-{store}" + + +# --- The sweep + + +@dataclass +class Swept: + """One ``n`` of a sweep: what was outstanding when the signal went in, and what the handler saw.""" + + n: int + outstanding: str + outcomes: str + rows: list[str] + sends: int + + +def table_of(swept: list[Swept]) -> str: + lines = [f"{'n':>2} {'outstanding':<58} {'outcomes':<34} {'rows':<20} sends"] + for s in swept: + lines.append(f"{s.n:>2} {s.outstanding:<58} {s.outcomes:<34} {' '.join(s.rows):<20} {s.sends}") + return "\n".join(lines) + + +ACKS = [ + "the transaction's commit (writes out, ack outstanding)", + "the outbox's flush, after the transaction's commit", + "the statement's commit, after the transaction", +] +"""What the sweep's acks are of, in order.""" + +ACKS_LATER = ["the first statement's commit, before the transaction", *ACKS] +"""What ``sweep_later``'s acks are of, in order.""" + + +def phase(side: RestateSide, n: int, acks: list[str]) -> str: + """What was outstanding when the signal went in at the ``n``-th ask of ``side``.""" + ask = side.asks[n - 1] + if ask.startswith("read "): + return "read of the state, by the open the first call waits for" + if ask != "ack": + return ask + ordinal = side.asks[:n].count("ack") + return acks[ordinal - 1] if ordinal <= len(acks) else "ack" + + +async def sweep_over(handler: str, store: str, steps: list[str], acks: list[str], commit: int) -> list[Swept]: + """Run ``handler`` with the signal before each successive answer, checking each run; its table. + + ``steps`` names the handler's outcomes, in order; ``commit`` is the transaction's commit among those that ask + for an ack (from 0). + """ + table: list[Swept] = [] + violations: list[str] = [] + reads = 0 + n = 0 + while True: + n += 1 + assert n <= 200, "the sweep did not end" + key = keyed(f"{handler}{n}", store) + # Seeded under another key, so another namespace of the page cache: the attempt starts cold, and reads its + # pages from Restate. + state = await seeded(f"{key}-seed") + r = await attempt(handler, state, key, cancel_before_answer=n) + # Past the last thing a run asks for, the signal never goes in. + if r.signalled_at is None: + break + sent = r.sent() + reads += sum(1 for a in r.asks if a.startswith("read ")) + outcomes = returned(r) + ended = dict(zip(steps, outcomes.split(","))) + stored = await stored_rows(state, key) + sends = sends_of(r, "tx") + table.append(Swept(n, phase(r, n, acks), outcomes, stored, len(sends))) + + problems: list[str] = [] + if any(m.type == TYPE.one_way_call for m in sent) and not send_is_inside_commit(sent, store, commit): + problems.append("the transaction's send is not inside its commit") + tx = ended["tx"] + if tx == "ok": + if "tx" not in stored: + problems.append("returned, but its row is not stored") + if len(sends) != 1 or len({s.idempotency_key for s in sends}) != 1: + problems.append("returned, but its send did not go out once") + elif tx == "cancelled": + if "tx" in stored: + problems.append("raised the cancellation, but its row is stored") + if sends: + problems.append("raised the cancellation, but its send went out") + else: + problems.append(f"ended with {tx}") + for name in ("before", "after"): + if name in ended and (ended[name] == "ok") != (name in stored): + problems.append(f"the statement {name!r} said one thing, the rows another") + cancelled = sum(1 for o in ended.values() if o == "cancelled") + # The call is the handler's last await: a signal that comes after its answer has nothing left to fail. + last_ask = len(r.asks) - r.asks[::-1].index("call Callee/echo") + owed = 1 if n <= last_ask else 0 + if cancelled != owed: + problems.append(f"{cancelled} cancellations for one signal, {owed} owed") + violations.extend( + f"n={n} ({r.asks[n - 1]}): {what}; {outcomes}, rows {stored}, sends {len(sends)}, wire {describe(r)}" + for what in problems + ) + shown = table_of(table) + print(f"\n{handler} on the {store} store:\n{shown}") + assert not violations, "\n".join(violations) + "\n" + shown + # The premise: the sweep covered reads that reached Restate, acks and the call's answer. + assert reads > 0, f"no read reached Restate: the page cache answered them all\n{shown}" + outstanding = {t.outstanding for t in table} + assert set(acks) | {"call Callee/echo"} <= outstanding, shown + return table + + +async def test_1_a_sweep_of_the_signal_over_every_answer_the_attempt_waits_for(store: str): + await sweep_over("sweep", store, ["tx", "after", "call"], ACKS, 0) + + +async def test_1b_the_sweep_with_a_statement_first_so_the_transaction_can_be_refused_by_a_carried_cancellation( + store: str, +): + table = await sweep_over("sweep_later", store, ["before", "tx", "after", "call"], ACKS_LATER, 1) + # The premise: a signal that lands during the first statement's commit is carried into the transaction. + carried = [t for t in table if t.outstanding == ACKS_LATER[0]] + assert carried and all(t.outcomes == "ok,cancelled,ok,ok" for t in carried), table_of(table) + + +# --- A body that awaits a call + + +async def run_body_calls(store: str, name: str, catches: bool) -> tuple[RestateSide, dict[str, bytes], str]: + key = keyed(name, store) + state = await seeded(key) + r = RestateSide(state, id_per_call=True, hold=["Slow/work"]) + r.start(key, catches) + running = asyncio.ensure_future(run(ledger, "body_calls", r)) + await r.until(lambda: r.has_called("Slow/work"), "the call in the body") + await r.cancel() + await running + return r, state, key + + +async def test_2_the_body_awaits_a_call_when_the_signal_comes_the_call_is_cancelled_and_the_transaction_rolls_back( + store: str, +): + r, state, key = await run_body_calls(store, "body1", False) + # The body did not get past its call; the transaction raised. + assert returned(r) == "not reached,cancelled,ok", describe(r) + assert await stored_rows(state, key) == ["after"] + assert r.sends == [] + assert r.cancels == [r.calls[0].invocation_id], describe(r) + + +async def test_2b_the_body_catches_the_cancellation_and_goes_on_the_transaction_commits_with_its_send(store: str): + r, state, key = await run_body_calls(store, "body2", True) + # The body saw the one cancellation, so the transaction and the statement after it work. + assert returned(r) == "cancelled,ok,ok", describe(r) + assert await stored_rows(state, key) == ["tx", "after"] + assert len(sends_of(r, "tx")) == 1 + assert r.cancels == [r.calls[0].invocation_id], describe(r) + + +# --- A carried cancellation + + +async def test_3_a_carried_cancellation_refuses_the_transaction_before_it_begins_the_next_one_commits(store: str): + key = keyed("carried", store) + state = await seeded(key) + r = await attempt("two", state, key, cancel_at_start=True) + assert returned(r) == "cancelled,ok,ok", describe(r) + assert await stored_rows(state, key) == ["second", "after"] + assert sends_of(r, "first") == [] + assert len(sends_of(r, "second")) == 1 + # The refused one put nothing on the wire: up to the first send, the attempt wrote what one transaction writes, + # as a run without the cancellation does up to its first transaction's send. + control_key = keyed("carried-control", store) + control = await attempt("two", await seeded(control_key), control_key) + assert returned(control) == "ok,ok,ok", describe(control) + assert writes_before_send(r) == writes_before_send(control), f"{describe(r)}\ncontrol: {describe(control)}" + # And that is one commit: its send is inside it. + assert send_is_inside_commit(r.sent(), store, 0), describe(r) + + +# --- A shutdown at the commit's ack + + +async def shut_at_ack(key: str) -> tuple[RestateSide, dict[str, bytes]]: + """Run ``noted`` on a seeded key until its commit asks for its ack, then shut the attempt down.""" + state = await seeded(key) + # Seeded under the same key, the pages are in the session's cache: the attempt asks for nothing before the ack + # of its transaction's commit, the first thing it asks for. + r = RestateSide(state, id_per_call=True, withhold_answer=1) + r.start(key, None) + running = asyncio.ensure_future(run(ledger, "noted", r)) + await r.until(lambda: len(r.asks) >= 1, "the commit asking for its ack") + assert r.asks[0] == "ack", r.asks + r.shut_down() + await running + return r, state + + +async def test_4_shut_down_while_the_commits_ack_is_outstanding_not_the_cancellation_and_the_next_attempt_finds_rows_and_send_agreeing( # noqa: E501 + store: str, seen: Seen +): + key = keyed("shut", store) + r, state = await shut_at_ack(key) + # The attempt's end, which is neither a cancellation nor terminal. + assert len(seen.seen) == 1, seen.seen + assert seen.seen[0] != "cancelled" + assert seen.terminal == [False], seen.seen + assert outcome(r.sent()) is None, describe(r) + + # A plain retry: its open makes what the outbox holds. + again = await attempt("seed", state, key) + assert returned(again) == "seeded", describe(again) + stored = await stored_rows(state, key) + sends = [*sends_of(r, "tx"), *sends_of(again, "tx")] + # A stored row has its send, made by one attempt or both, always with the one key, so Restate makes it once; no + # row, no send at all. + assert len({s.idempotency_key for s in sends}) == (1 if "tx" in stored else 0), (stored, sends) + + +async def test_4b_the_commits_wait_fails_at_a_shutdown_as_a_calls_await_does(store: str, seen: Seen): + # The commit's wait is the store's: at the attempt's end it fails as an await of the driver's does, so a handler + # tells a shutdown from an error of its own. + await shut_at_ack(keyed("shut2", store)) + commit = list(seen.seen) + + seen.seen.clear() + key = keyed("shut2-call", store) + r = RestateSide(await seeded(key), id_per_call=True, hold=["Slow/work"]) + r.start(key, None) + running = asyncio.ensure_future(run(ledger, "awaits_a_call", r)) + await r.until(lambda: r.has_called("Slow/work"), "the call") + r.shut_down() + await running + call = list(seen.seen) + + assert commit == call and len(commit) == 1, f"the commit's wait: {commit}; a call's await: {call}" + + +async def test_4c_a_shutdown_at_the_commits_ack_cancels_the_handlers_task(store: str, seen: Seen): + # As for a call's await (``sessions_saga``, h): the handler's task is cancelled, where @restatedev/sessions + # rejects the commit with ``AttemptShutDown``. + await shut_at_ack(keyed("shut3", store)) + assert seen.seen == ["asyncio.exceptions.CancelledError"] + + +# --- A body that raises + + +async def test_5_a_body_that_raises_with_the_signal_arriving_during_it_no_row_no_send_and_one_cancellation_after_it( + store: str, seen: Seen +): + key = keyed("throws", store) + state = await seeded(key) + seen.hold() + r = RestateSide(state, id_per_call=True) + r.start(key, None) + running = asyncio.ensure_future(run(ledger, "throws", r)) + await r.until(seen.reached.is_set, "the body working outside Restate") + # Nothing of Restate's is outstanding, so the cancellation is carried; this returns once the attempt has it. + await r.cancel() + seen.opened.set() + await running + # The body's own error, then the cancellation at the next call of the database. + assert returned(r) == "ValueError,cancelled,ok", describe(r) + assert await stored_rows(state, key) == [] + assert r.sends == [] + + +async def test_5b_a_body_that_raises_with_the_signal_carried_into_it_refused_before_it_begins_and_nothing_else_fails( + store: str, +): + key = keyed("throws2", store) + state = await seeded(key) + r = await attempt("throws", state, key, cancel_at_start=True) + assert returned(r) == "cancelled,ok,ok", describe(r) + assert await stored_rows(state, key) == ["after"] + assert r.sends == [] diff --git a/tests/sessions_wire.py b/tests/sessions_wire.py index 7300a6da..feafdb61 100644 --- a/tests/sessions_wire.py +++ b/tests/sessions_wire.py @@ -26,8 +26,10 @@ import json import struct import time +import typing +from collections.abc import Callable from dataclasses import dataclass -from typing import Any, Literal, Union +from typing import Any, Literal, Optional, Union from restate.server_types import ASGIReceiveEvent, ASGISendEvent, ReceiveChannel from restate.sessions import SessionObject @@ -169,6 +171,28 @@ def messages(output: bytes) -> list[Message]: return out +def outcome(sent: list[Message]) -> Optional[Union[tuple[Literal["value"], Any], tuple[Literal["failure"], int, str]]]: + """How the invocation ended: ``("value", v)`` with its output deserialized, ``("failure", code, message)``, or + ``None`` if the attempt wrote no output (it was shut down).""" + output = next((m for m in sent if m.type == TYPE.output), None) + if output is None: + return None + if 14 in output.fields: + content = decode(output.bytes_of(14)).get(1, [b""])[0] + assert isinstance(content, bytes) + return ("value", json.loads(content)) + failure = decode(output.bytes_of(15)) + code = failure[1][0] + message = failure.get(2, [b""])[0] + assert isinstance(code, int) and isinstance(message, bytes) + return ("failure", code, message.decode()) + + +def commits(sent: list[Message]) -> int: + """How many of ``sent``'s commands asked for an ack: a commit each, on either store.""" + return sum(1 for m in sent if 0x0400 <= m.type < 0x8000 and m.flags & REQUESTED_ACK) + + def output_of(sent: list[Message]) -> Any: """The handler's output, deserialized from the attempt's output message.""" output = next(m for m in sent if m.type == TYPE.output) @@ -178,6 +202,40 @@ def output_of(sent: list[Message]) -> Any: return json.loads(content) +@dataclass(frozen=True) +class Made: + """A call or a send the attempt made, as it went on the wire.""" + + service: str + handler: str + key: str + idempotency_key: Optional[str] + input: str + """The input, as the text of its bytes.""" + invocation_id: Optional[str] = None + """The invocation id Restate gave a call; a send's is never answered here.""" + + @property + def target(self) -> str: + """``Service/handler``.""" + return f"{self.service}/{self.handler}" + + +def _made(message: Message, key_field: int, idempotency_field: int, invocation_id: Optional[str] = None) -> Made: + def text(number: int) -> Optional[str]: + found = message.fields.get(number) + return None if found is None else typing.cast(bytes, found[0]).decode() + + return Made( + service=text(1) or "", + handler=text(2) or "", + key=text(key_field) or "", + idempotency_key=text(idempotency_field), + input=text(3) or "", + invocation_id=invocation_id, + ) + + CANCEL_SIGNAL = frame(TYPE.signal, uint(2, 1) + bytes_(4, b"")) """Restate cancelling the invocation: the built-in signal 1, with an empty (void) value.""" @@ -199,10 +257,10 @@ class RestateSide: state: The object's state, which the attempt reads and writes. The start carries the head of the database alone, as Restate preloads it for a session object, and the attempt reads the rest on the wire. - cancel_on_commit: The first time a command asks for an ack, Restate - sends the cancel signal, and the ack once the attempt has acted - on the signal: a cancellation that lands with the database waiting - on Restate. + cancel_on_commit: The first time a command asks for an ack (``True``), + or the ``n``-th time (from 1), Restate sends the cancel signal, + and the ack once the attempt has acted on the signal: a + cancellation that lands with the database waiting on Restate. cancel_on_read: At the ``n``-th read of the state on the wire, Restate sends the cancel signal, and the read's value once the attempt has acted on the signal. @@ -216,6 +274,17 @@ class RestateSide: cancel_at_start: A retry of a cancelled invocation: the start counts two known entries, and the signal follows the input, so the VM knows of the cancellation before the handler starts. + cancel_before_answer: Just before Restate answers the ``n``-th thing + the attempt asks for (from 1; see ``asks``), it sends the cancel + signal, and the answer once the attempt has acted on the signal. + withhold_answer: The ``n``-th thing the attempt asks for (from 1) is + never answered: a test shuts the attempt down meanwhile. + hold: Calls to these targets (``Service/handler``) get their + invocation id, and their result only once ``release``d. + fail: Calls to these targets fail with this terminal failure, + ``(code, message)``. + id_per_call: Give each call an invocation id of its own (``inv_``) + rather than ``inv_started`` for all. A call to key ``k`` is never answered: what a started call, whose result nobody holds, looks like to the handler. Every other call is answered with @@ -226,14 +295,37 @@ def __init__( self, state: dict[str, bytes] | None = None, *, - cancel_on_commit: bool = False, + cancel_on_commit: bool | int = False, cancel_on_read: int | None = None, cancel_on_keys: bool = False, cancel_on_call: Literal["before_id", "after_id"] | None = None, cancel_at_start: bool = False, + cancel_before_answer: int | None = None, + withhold_answer: int | None = None, + hold: list[str] | None = None, + fail: dict[str, tuple[int, str]] | None = None, + id_per_call: bool = False, ) -> None: self.state: dict[str, bytes] = {} if state is None else state - self._cancel_on_commit = cancel_on_commit + # The ack (from 1) that the signal goes in with, or 0 for none. + self._cancel_on_commit = int(cancel_on_commit) + self._cancel_before_answer = cancel_before_answer + self._withhold_answer = withhold_answer + self._hold = set(hold or []) + self._fail = dict(fail or {}) + self._id_per_call = id_per_call + # The results withheld, by target, oldest first: (the result's completion id, the input echoed). + self._held_results: dict[str, list[tuple[int, bytes]]] = {} + self._acks = 0 + self.asks: list[str] = [] + """What the attempt asked Restate for, in order, which Restate answers: ``read ``, ``ack``, or ``call + `` (a call that is neither held nor to key ``k``).""" + self.calls: list[Made] = [] + """The calls the attempt made, in order, with the invocation id each got.""" + self.sends: list[Made] = [] + """The sends the attempt made, in order.""" + self.cancels: list[str] = [] + """The invocation ids the attempt sent a cancellation to, in order.""" self._cancel_on_read = cancel_on_read self._cancel_on_keys = cancel_on_keys self._cancel_on_call = cancel_on_call @@ -353,6 +445,38 @@ def shut_down(self) -> None: """Restate closes the request body, as its inactivity timeout does: the attempt is shut down.""" self._close() + def release(self, target: str) -> None: + """Answer the oldest withheld call to ``target`` (``Service/handler``), echoing its input.""" + withheld = self._held_results.get(target) + if not withheld: + raise AssertionError(f"no call to {target} is withheld") + result, echoed = withheld.pop(0) + self._push(frame(TYPE.call_completion, uint(1, result) + field(5, 2, value(echoed)))) + + def has_called(self, target: str) -> bool: + """Whether the attempt has called ``target`` (``Service/handler``), as far as Restate has taken it in.""" + return any(c.target == target for c in self.calls) + + async def until(self, condition: Callable[[], bool], what: str, timeout: float = 20.0) -> None: + """Return once ``condition`` holds, letting the attempt run; fail after ``timeout``, which only a hang reaches.""" + deadline = time.monotonic() + timeout + while not condition(): + if time.monotonic() >= deadline: + raise AssertionError(f"waited {timeout}s for {what}") + await asyncio.sleep(0.001) + + def _asked(self, ask: str) -> bool: + """Before Restate answers ``ask``: the signal, if this ask is the one; whether to answer it. + + The answer pushed after the signal is held until the attempt has acted on the signal (``_signal``). + """ + self.asks.append(ask) + if self._withhold_answer == len(self.asks): + return False + if self._cancel_before_answer == len(self.asks) and self.signalled_at is None: + self._signal() + return True + def _over(self, sent: list[Message]) -> bool: return any(m.type in (TYPE.end, TYPE.error) for m in sent) @@ -385,16 +509,21 @@ def _answer(self, message: Message) -> None: # Restate acks a command only if it asked to be acked, and the ack of one covers every # command before it. if message.flags & REQUESTED_ACK: - # Restate signals a cancellation once, not on every commit: what follows is acked - # as usual. - if self._cancel_on_commit and self.signalled_at is None: - self._signal() - self._push(frame(TYPE.command_ack, uint(1, self._index))) + self._acks += 1 + # A withheld ack still stores the command, below. + if self._asked("ack"): + # Restate signals a cancellation once, not on every commit: what follows is + # acked as usual. + if self._acks == self._cancel_on_commit and self.signalled_at is None: + self._signal() + self._push(frame(TYPE.command_ack, uint(1, self._index))) if message.type == TYPE.get_state_ephemeral: self.reads += 1 if self.reads == self._cancel_on_read and self.signalled_at is None: self._signal() key = message.bytes_of(2).decode() + if not self._asked(f"read {key}"): + return held = self.state.get(key) self._push( frame( @@ -410,10 +539,15 @@ def _answer(self, message: Message) -> None: self.state[key] = content elif message.type == TYPE.clear_state: self.state.pop(message.bytes_of(1).decode(), None) + elif message.type == TYPE.one_way_call: + self.sends.append(_made(message, 6, 7)) + elif message.type == TYPE.cancel_invocation: + self.cancels.append(message.bytes_of(1).decode()) elif message.type == TYPE.call: - invocation_id = frame( - TYPE.call_invocation_id_completion, uint(1, message.int_of(10)) + bytes_(16, "inv_started") - ) + id_ = f"inv_{len(self.calls) + 1}" if self._id_per_call else "inv_started" + made = _made(message, 5, 6, id_) + self.calls.append(made) + invocation_id = frame(TYPE.call_invocation_id_completion, uint(1, message.int_of(10)) + bytes_(16, id_)) if self._cancel_on_call is not None and self.signalled_at is None: if self._cancel_on_call == "before_id": self._signal() @@ -422,9 +556,21 @@ def _answer(self, message: Message) -> None: self._signal() else: self._push(invocation_id) - if message.fields.get(5) != [b"k"]: - echoed = message.bytes_of(3) - self._push(frame(TYPE.call_completion, uint(1, message.int_of(11)) + field(5, 2, value(echoed)))) + result = message.int_of(11) + echoed = typing.cast(bytes, message.fields.get(3, [b""])[0]) + if made.key == "k": + return + if made.target in self._hold: + self._held_results.setdefault(made.target, []).append((result, echoed)) + return + if not self._asked(f"call {made.target}"): + return + failure = self._fail.get(made.target) + if failure is None: + self._push(frame(TYPE.call_completion, uint(1, result) + field(5, 2, value(echoed)))) + else: + code, text = failure + self._push(frame(TYPE.call_completion, uint(1, result) + field(6, 2, uint(1, code) + bytes_(2, text)))) elif message.type == TYPE.get_state_keys: if self._cancel_on_keys and self.signalled_at is None: self._signal() From df889a9df64f2e00b99c0e1906f187ddb511041e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:44:06 +0000 Subject: [PATCH 11/11] Tests: a cancellation does not reach an invocation shut down while it waits for a call Expected failures, until shared-core has the fix. Restate shuts down an attempt that waits for a call, and starts the next when the call answers. On the explicit recovery VM the suspension names the call alone, so cancelling the invocation meanwhile does nothing until the call answers, and nothing at all if it never does. On main the invocation ends at once. For a session object: a cancelled invocation stays suspended, with or without explicit cancellation. For an agent: `stop` does not end a turn that waits for an approval once its attempt was shut down. shared-core's branch `claude/cancel-wakes-a-shut-down-attempt` names the cancellation in the suspension unless the invocation was cancelled already. Built against it, these four pass, with the rest of the suite. A third test checks what kept the cancellation out of the suspension: that a cancelled invocation which goes on waiting is not resumed over and over. The tests are strict expected failures: with the release that has the fix they pass, which fails them, and the marker comes off. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01RePHkSS8KRKmJ93hcd9asV --- tests/agents_suspended_stop_server.py | 121 +++++++++++++++++++ tests/sessions_suspended_server.py | 168 ++++++++++++++++++++++++++ 2 files changed, 289 insertions(+) create mode 100644 tests/agents_suspended_stop_server.py create mode 100644 tests/sessions_suspended_server.py diff --git a/tests/agents_suspended_stop_server.py b/tests/agents_suspended_stop_server.py new file mode 100644 index 00000000..74a415ef --- /dev/null +++ b/tests/agents_suspended_stop_server.py @@ -0,0 +1,121 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""An agent's turn that waits for an approval, which Restate shut down meanwhile, and is then stopped.""" + +# pylint: disable=missing-function-docstring + +import asyncio +import typing +import uuid +from datetime import timedelta +from typing import Any + +import httpx2 +import pydantic +import pytest + +import restate +from agents_conversation import ITEMS # pylint: disable=import-error +from restate import HarnessEnvironment, sessions +from restate.agents._conversation import Conversation, answer_once +from restate.agents._object import AgentObject +from restate.agents._tools import ToolCall, run_tool, wait_for_signal +from support import RESTATE_IMAGE # pylint: disable=import-error + + +@pytest.fixture(scope="session") +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + +NEEDS_SHARED_CORE = pytest.mark.xfail( + strict=True, + reason="shared-core 8.7.0 suspends a shut down attempt on its calls alone, so a cancellation does not resume it; " + "fixed on shared-core's branch claude/cancel-wakes-a-shut-down-attempt, not released yet", +) +"""Remove with the shared-core release that has the fix: these then pass, and a strict xfail that passes fails.""" + + +class Refund(pydantic.BaseModel): + order: str + amount: int + + +approval = wait_for_signal("approval", description="Wait for a manager to approve a refund.", input=Refund) + + +async def answer(ctx: sessions.SessionContext, text: str) -> str: + """A scripted framework whose model asks for an approval, and waits for it.""" + + async def work(conversation: Conversation) -> str: + call_id = "call-1" + args = {"order": "1", "amount": 5} + call = {"id": call_id, "name": approval.name, "input": args} + await conversation.turn.append_reply({"role": "assistant", "text": "", "calls": [call]}) + result = await run_tool(approval, args, ToolCall(ctx, call_id)) + await conversation.turn.append({"result": call_id, "output": result}) + await conversation.turn.append_reply({"role": "assistant", "text": f"refund: {result}"}) + return f"refund: {result}" + + return await answer_once(ctx, text, ITEMS, work) + + +# Restate shuts down an attempt it heard nothing from for a second. +clerk = AgentObject("clerk", inactivity_timeout=timedelta(seconds=1)) +clerk.chat(answer, items=ITEMS) + + +@pytest.fixture(scope="session") +async def harness(): + async with restate.create_test_harness(restate.app([clerk]), restate_image=RESTATE_IMAGE) as harness: + yield harness + + +@NEEDS_SHARED_CORE +async def test_stop_ends_a_turn_that_restate_shut_down_while_it_waited_for_an_approval(harness: HarnessEnvironment): + key = str(uuid.uuid4()) + seen: list[str] = [] + async with httpx2.AsyncClient(timeout=30) as http: + sent = await http.post( + f"{harness.ingress_url}/clerk/{key}/chat/send", content="refund", headers={"content-type": "text/plain"} + ) + invocation_id = typing.cast(str, sent.json()["invocationId"]) + + async def status() -> str | None: + answered = await http.post( + f"{harness.admin_api_url}/query", + json={"query": f"SELECT status FROM sys_invocation WHERE id = '{invocation_id}'"}, + headers={"Accept": "application/json"}, + ) + rows = typing.cast("list[dict[str, Any]]", answered.json().get("rows", [])) + return typing.cast(str, rows[0]["status"]) if rows else None + + for _ in range(100): + now = await status() + if now is not None and (not seen or seen[-1] != now): + seen.append(now) + if now == "suspended": + break + await asyncio.sleep(0.1) + assert seen and seen[-1] == "suspended", seen + stopped = await http.post(f"{harness.ingress_url}/clerk/{key}/stop", json=None) + seen.append(f"stop: {stopped.status_code} {stopped.text[:80]}") + try: + answered = await http.get(f"{harness.ingress_url}/restate/invocation/{invocation_id}/attach", timeout=10) + code: int | None = answered.status_code + except httpx2.TimeoutException: + code = None + seen.append(f"after the stop: {await status()}") + if code is None: + await http.patch(f"{harness.admin_api_url}/invocations/{invocation_id}/kill") + assert code == 409, f"the stopped turn did not end in 10 s: {seen}" diff --git a/tests/sessions_suspended_server.py b/tests/sessions_suspended_server.py new file mode 100644 index 00000000..dafb0692 --- /dev/null +++ b/tests/sessions_suspended_server.py @@ -0,0 +1,168 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A session object's invocation that Restate shut down while it waited for a call, and is then cancelled.""" + +# pylint: disable=missing-function-docstring + +import asyncio +import typing +import uuid +from datetime import timedelta +from typing import Any + +import httpx2 +import pytest + +import restate +from restate import HarnessEnvironment, sessions +from restate.sessions import internal +from support import RESTATE_IMAGE # pylint: disable=import-error + + +@pytest.fixture(scope="session") +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + +NEEDS_SHARED_CORE = pytest.mark.xfail( + strict=True, + reason="shared-core 8.7.0 suspends a shut down attempt on its calls alone, so a cancellation does not resume it; " + "fixed on shared-core's branch claude/cancel-wakes-a-shut-down-attempt, not released yet", +) +"""Remove with the shared-core release that has the fix: these then pass, and a strict xfail that passes fails.""" + +sleeper = restate.Service("sleeper") + + +@sleeper.handler() +async def nap(ctx: restate.Context) -> str: + await ctx.sleep(timedelta(minutes=5)) + return "rested" + + +# Restate shuts down an attempt it heard nothing from for a second. +waiting = sessions.SessionObject( + "waiting", migrations=["CREATE TABLE seen (what TEXT NOT NULL)"], inactivity_timeout=timedelta(seconds=1) +) +attempts: dict[str, int] = {} + + +@waiting.handler() +async def waits(ctx: sessions.SessionContext) -> str: + """Waits for a call that takes minutes, without explicit cancellation.""" + attempts[ctx.key] = attempts.get(ctx.key, 0) + 1 + return await ctx.call(nap, idempotency_key=ctx.request.id) + + +@waiting.handler(explicit_cancellation=True) +async def waits_and_watches(ctx: sessions.SessionContext) -> str: + """Waits for a call that takes minutes, or for its cancellation, which it handles itself.""" + attempts[ctx.key] = attempts.get(ctx.key, 0) + 1 + napping = asyncio.ensure_future(ctx.call(nap, idempotency_key=ctx.request.id)) + stopping = asyncio.ensure_future(internal.cancelled(ctx)) + await asyncio.wait({napping, stopping}, return_when=asyncio.FIRST_COMPLETED) + if not stopping.done(): + return await napping + await internal.cancel_calls(ctx) + await ctx.db.execute("INSERT INTO seen (what) VALUES ('stopped')") + return "stopped" + + +@waiting.handler(explicit_cancellation=True) +async def waits_whatever_comes(ctx: sessions.SessionContext) -> str: + """Waits for a call that takes minutes, and goes on waiting for it once cancelled.""" + attempts[ctx.key] = attempts.get(ctx.key, 0) + 1 + return await ctx.call(nap, idempotency_key=ctx.request.id) + + +@pytest.fixture(scope="session") +async def harness(): + async with restate.create_test_harness(restate.app([sleeper, waiting]), restate_image=RESTATE_IMAGE) as harness: + yield harness + + +async def status(admin: httpx2.AsyncClient, harness: HarnessEnvironment, invocation_id: str) -> str | None: + answered = await admin.post( + f"{harness.admin_api_url}/query", + json={"query": f"SELECT status FROM sys_invocation WHERE id = '{invocation_id}'"}, + headers={"Accept": "application/json"}, + ) + rows = typing.cast("list[dict[str, Any]]", answered.json().get("rows", [])) + return typing.cast(str, rows[0]["status"]) if rows else None + + +async def cancelled_while_suspended(harness: HarnessEnvironment, handler: Any) -> tuple[int | None, list[str]]: + """Start ``handler``, wait until Restate has shut its attempt down, cancel it; its HTTP status, and its statuses.""" + key = str(uuid.uuid4()) + sent = await harness.client.object_send(handler, key=key, arg=None) + seen: list[str] = [] + async with httpx2.AsyncClient(timeout=30) as admin: + for _ in range(100): + now = await status(admin, harness, sent.invocation_id) + if now is not None and (not seen or seen[-1] != now): + seen.append(now) + if now == "suspended": + break + await asyncio.sleep(0.1) + assert seen and seen[-1] == "suspended", seen + (await admin.patch(f"{harness.admin_api_url}/invocations/{sent.invocation_id}/cancel")).raise_for_status() + try: + answered = await admin.get( + f"{harness.ingress_url}/restate/invocation/{sent.invocation_id}/attach", timeout=10 + ) + code: int | None = answered.status_code + except httpx2.TimeoutException: + code = None + seen.append(f"after the cancel: {await status(admin, harness, sent.invocation_id)}") + if code is None: + await admin.patch(f"{harness.admin_api_url}/invocations/{sent.invocation_id}/kill") + return code, seen + + +@NEEDS_SHARED_CORE +async def test_a_cancellation_reaches_an_invocation_that_was_shut_down_while_it_waited_for_a_call( + harness: HarnessEnvironment, +): + code, seen = await cancelled_while_suspended(harness, waits) + assert code == 409, f"the cancelled invocation did not end in 10 s: {seen}" + + +@NEEDS_SHARED_CORE +async def test_a_handler_that_watches_for_its_cancellation_learns_of_it_after_it_was_shut_down( + harness: HarnessEnvironment, +): + code, seen = await cancelled_while_suspended(harness, waits_and_watches) + assert code == 200, f"the cancelled invocation did not end in 10 s: {seen}" + + +@NEEDS_SHARED_CORE +async def test_a_cancelled_invocation_that_goes_on_waiting_is_not_resumed_over_and_over(harness: HarnessEnvironment): + # Waiting on a cancellation that Restate has stored resumes the invocation at once. The attempt that follows + # the cancellation knows of it, and waits for its call alone. + key = str(uuid.uuid4()) + sent = await harness.client.object_send(waits_whatever_comes, key=key, arg=None) + async with httpx2.AsyncClient(timeout=30) as admin: + for _ in range(100): + if await status(admin, harness, sent.invocation_id) == "suspended": + break + await asyncio.sleep(0.1) + before = attempts.get(key, 0) + (await admin.patch(f"{harness.admin_api_url}/invocations/{sent.invocation_id}/cancel")).raise_for_status() + await asyncio.sleep(4) + after_the_cancel = attempts.get(key, 0) + await asyncio.sleep(4) + later = attempts.get(key, 0) + now = await status(admin, harness, sent.invocation_id) + await admin.patch(f"{harness.admin_api_url}/invocations/{sent.invocation_id}/kill") + # The cancellation started one attempt, which was shut down in its turn, and no more came. + assert (after_the_cancel - before, later - after_the_cancel, now) == (1, 0, "suspended")