diff --git a/python/restate/server_context.py b/python/restate/server_context.py index 176b217..c774cbc 100644 --- a/python/restate/server_context.py +++ b/python/restate/server_context.py @@ -511,6 +511,10 @@ async def auto_close_extension_data(data: Dict[str, Any]): class ServerInvocationContext(ObjectContext): """This class implements the context for the restate framework based on the server.""" + _receiving: bool = False + _progress_event: Optional[asyncio.Event] = None + _disconnected: bool = False + def __init__( self, vm: VMWrapper, @@ -541,6 +545,9 @@ def __init__( # Taking the VM's output and sending it is one step, so that output sent from two tasks (an # annotation's flush, beside the awaits') keeps its order. self._output_lock = asyncio.Lock() + self._receiving = False + self._progress_event = None + self._disconnected = False def _encode(self, buffer: bytes) -> bytes: """Apply the journal value codec encode step, if a codec is configured.""" @@ -722,17 +729,37 @@ async def wrapper(f): # Send what do_progress wrote before blocking: the AwaitingOn message, which tells Restate # what this attempt awaits while it waits, so that Restate may suspend it. await self.take_and_send_output() - chunk = await self.receive() - if chunk.get("type") == "restate.run_completed": - continue - if chunk.get("type") == "http.disconnect": - raise DisconnectedException() + await self._wait_for_external_progress() + + async def _wait_for_external_progress(self) -> None: + if self._disconnected: + raise DisconnectedException() + if self._progress_event is None: + self._progress_event = asyncio.Event() + if self._receiving: + event = self._progress_event + await event.wait() + if self._disconnected: + raise DisconnectedException() + return + self._receiving = True + event = self._progress_event + try: + chunk = await self.receive() + if chunk.get("type") == "http.disconnect": + self._disconnected = True + raise DisconnectedException() + if chunk.get("type") != "restate.run_completed": # Skip empty body frames to avoid hot loop (see #175) body: bytes | None = chunk.get("body", None) # type: ignore[assignment] if body is not None and len(body) > 0: self.vm.notify_input(body) if not chunk.get("more_body", False): self.vm.notify_input_closed() + finally: + self._receiving = False + self._progress_event = asyncio.Event() + event.set() def _create_fetch_result_coroutine(self, handle: int, serde: Serde[T] | None = None): """Create a coroutine that fetches a result from a notification handle.""" diff --git a/tests/disconnect_hotloop.py b/tests/disconnect_hotloop.py index 39e6bbf..e670cdc 100644 --- a/tests/disconnect_hotloop.py +++ b/tests/disconnect_hotloop.py @@ -255,3 +255,108 @@ async def waiter(idx: int): assert sorted(results) == [0, 1, 2] finally: await channel.close() + + +async def test_concurrent_poll_wakes_all_waiters_on_shared_receive(): + """When multiple tasks poll concurrently, one receive wakes peer waiters.""" + from restate.server_context import ServerInvocationContext + from restate.vm import DoProgressAnyCompleted, DoProgressWaitExternalProgress, SingleUnresolvedFuture + + completed: set[int] = set() + receive_calls = 0 + + vm = MagicMock() + vm.take_output.return_value = None + + def fake_notify_input(body: bytes): + if body == b"second": + completed.add(2) + elif body == b"first": + completed.add(1) + + def fake_do_progress(unresolved): + if unresolved.handle in completed: + return DoProgressAnyCompleted() + return DoProgressWaitExternalProgress() + + vm.notify_input.side_effect = fake_notify_input + vm.do_progress.side_effect = fake_do_progress + + events = [ + {"type": "http.request", "body": b"second", "more_body": True}, + {"type": "http.request", "body": b"first", "more_body": False}, + ] + event_iter = iter(events) + + async def mock_receive() -> ASGIReceiveEvent: + nonlocal receive_calls + try: + event = next(event_iter) + except StopIteration: + await asyncio.Event().wait() + raise RuntimeError("unreachable") + receive_calls += 1 + if receive_calls == 1: + await asyncio.sleep(0.05) + return cast(ASGIReceiveEvent, event) + + receive_channel = ReceiveChannel(mock_receive) + + ctx = ServerInvocationContext.__new__(ServerInvocationContext) + ctx.vm = vm + ctx.handler = MagicMock() + ctx.invocation = MagicMock() + ctx.send = MagicMock() + ctx.receive = receive_channel + ctx.run_coros_to_execute = {} + ctx.tasks = MagicMock() + ctx._output_lock = asyncio.Lock() # pylint: disable=protected-access + + try: + task1 = asyncio.create_task(ctx.create_poll_or_cancel_coroutine(SingleUnresolvedFuture(1))) + await asyncio.sleep(0) + task2 = asyncio.create_task(ctx.create_poll_or_cancel_coroutine(SingleUnresolvedFuture(2))) + + await asyncio.wait_for(task2, timeout=1.0) + await asyncio.wait_for(task1, timeout=1.0) + finally: + await receive_channel.close() + + +async def test_concurrent_poll_propagates_disconnect_to_all_waiters(): + """A single http.disconnect wakes all concurrent poll waiters with DisconnectedException.""" + from restate.server_context import DisconnectedException, ServerInvocationContext + from restate.vm import DoProgressWaitExternalProgress, SingleUnresolvedFuture + + vm = MagicMock() + vm.take_output.return_value = None + vm.do_progress.return_value = DoProgressWaitExternalProgress() + + async def mock_receive() -> ASGIReceiveEvent: + await asyncio.sleep(0.05) + return cast(ASGIReceiveEvent, {"type": "http.disconnect"}) + + receive_channel = ReceiveChannel(mock_receive) + + ctx = ServerInvocationContext.__new__(ServerInvocationContext) + ctx.vm = vm + ctx.handler = MagicMock() + ctx.invocation = MagicMock() + ctx.send = MagicMock() + ctx.receive = receive_channel + ctx.run_coros_to_execute = {} + ctx.tasks = MagicMock() + ctx._output_lock = asyncio.Lock() # pylint: disable=protected-access + + try: + task1 = asyncio.create_task(ctx.create_poll_or_cancel_coroutine(SingleUnresolvedFuture(1))) + await asyncio.sleep(0) + task2 = asyncio.create_task(ctx.create_poll_or_cancel_coroutine(SingleUnresolvedFuture(2))) + + results = await asyncio.wait_for( + asyncio.gather(task1, task2, return_exceptions=True), + timeout=1.0, + ) + assert all(isinstance(r, DisconnectedException) for r in results) + finally: + await receive_channel.close()