diff --git a/docs/reference/mailbox.md b/docs/reference/mailbox.md index 73302f0d..4827e684 100644 --- a/docs/reference/mailbox.md +++ b/docs/reference/mailbox.md @@ -2,7 +2,57 @@ # Mailbox +`MailboxProcessor` provides a FIFO queue with one active receiver and multiple +producers. Create the mailbox and call `receive`, `post_and_async_reply`, and +`wait` on its owning running asyncio event loop. `post` and reply channels may +be used from other threads. + +```python +import asyncio + +from expression import AsyncReplyChannel, MailboxProcessor + + +async def main() -> None: + async def body(inbox: MailboxProcessor[AsyncReplyChannel[None]]) -> None: + channel = await inbox.receive(timeout=1.0) + channel.reply(None) + + agent = MailboxProcessor.start(body) + def request(channel: AsyncReplyChannel[None]) -> AsyncReplyChannel[None]: + return channel + + await agent.post_and_async_reply(request, timeout=1.0) + await agent.wait() + + +asyncio.run(main()) +``` + +Timeouts are optional and measured in **seconds**, following asyncio conventions. +An expired timeout raises `TimeoutError`. Cancelling or timing out a receive +releases the reader without consuming a message. Concurrent receives raise +`RuntimeError`. + +`post_and_async_reply` posts immediately. The first reply wins, including `None`; +duplicate replies and replies arriving after cancellation or timeout are ignored. +Cancelling a reply wait does not retract the request or stop its processing. +Without a timeout, a request that is never answered can wait indefinitely. + +A cancellation token wakes an idle receiver and cancels a started body. An +already-cancelled token prevents the body coroutine from running, while +`CancellationToken.none()` behaves like an omitted token. `wait()` observes body +completion and propagates its exception or `asyncio.CancelledError`. Cancelling +`wait()` itself leaves the body running. A directly constructed mailbox has no +body to wait for. + +Body termination does not close the queue or settle outstanding reply waits. +Use reply timeouts and observe `wait()` when coordinating shutdown. The queue is +unbounded; posting does not provide backpressure. This is a subset of F#'s +MailboxProcessor API: selective scanning and optional-result receive/reply +variants are not provided. + ```{eval-rst} .. automodule:: expression.core.mailbox :members: -``` \ No newline at end of file +``` diff --git a/expression/core/aiotools.py b/expression/core/aiotools.py index 2c157b14..1d0d51cf 100644 --- a/expression/core/aiotools.py +++ b/expression/core/aiotools.py @@ -11,9 +11,10 @@ import asyncio from asyncio import Future, Task from collections.abc import Awaitable, Callable +from inspect import iscoroutine from typing import Any, TypeVar -from expression.system import CancellationToken, OperationCanceledError +from expression.system import CancellationToken, ObjectDisposedException, OperationCanceledError _TSource = TypeVar("_TSource") @@ -68,53 +69,49 @@ def cancel(_: OperationCanceledError) -> None: __running_tasks: set[Task[Any]] = set() -def start(computation: Awaitable[Any], token: CancellationToken | None = None) -> None: - """Start computation. - - Starts the asynchronous computation in the event loop. Do not await - its result. - - If no cancellation token is provided then the default cancellation - token is used. - """ - - async def runner() -> Any: - result = await computation - __running_tasks.remove(task) - return result +def _start_task(computation: Awaitable[_TSource], token: CancellationToken | None = None) -> Task[_TSource]: + async def runner() -> _TSource: + if token is not None and token.is_cancellation_requested: + raise asyncio.CancelledError() + return await computation - task = asyncio.create_task(runner()) + loop = asyncio.get_running_loop() + task = loop.create_task(runner()) __running_tasks.add(task) + registration = None - def cb(): - task.cancel() + def cancel() -> None: + loop.call_soon_threadsafe(task.cancel) - if token: - token.register(cb) - return None + if token is not None: + try: + registration = token.register(cancel) + except ObjectDisposedException: + cancel() + def cleanup(completed: Task[_TSource]) -> None: + __running_tasks.discard(completed) + if registration is not None: + registration.dispose() + # The wrapper may be cancelled before it ever awaits the coroutine. + if iscoroutine(computation): + computation.close() -def start_immediate(computation: Awaitable[Any], token: CancellationToken | None = None) -> None: - """Start computation immediately. + task.add_done_callback(cleanup) + return task - Runs an asynchronous computation, starting immediately on the - current operating system thread. - """ - async def runner() -> Any: - result = await computation - __running_tasks.remove(task) - return result +def start(computation: Awaitable[Any], token: CancellationToken | None = None) -> None: + """Schedule a computation on the running event loop.""" + _start_task(computation, token) - task = asyncio.create_task(runner()) - __running_tasks.add(task) - def cb() -> None: - task.cancel() +def start_immediate(computation: Awaitable[Any], token: CancellationToken | None = None) -> None: + """Schedule a computation on the running event loop. - if token: - token.register(cb) - return None + Execution begins when the event loop next runs the task. + """ + _start_task(computation, token) def run_synchronously(computation: Awaitable[_TSource]) -> _TSource: diff --git a/expression/core/mailbox.py b/expression/core/mailbox.py index 17e05acb..cf774bee 100644 --- a/expression/core/mailbox.py +++ b/expression/core/mailbox.py @@ -13,18 +13,19 @@ from __future__ import annotations import asyncio -from collections.abc import Awaitable, Callable -from queue import SimpleQueue -from threading import RLock -from typing import Any, Generic, TypeVar +from collections.abc import AsyncGenerator, Awaitable, Callable +from contextlib import asynccontextmanager +from queue import Empty, SimpleQueue +from typing import Generic, TypeVar -from expression.system import CancellationToken, OperationCanceledError +from expression.system import CancellationToken, ObjectDisposedException -from .aiotools import Continuation, from_continuations, start_immediate +from .aiotools import _start_task # pyright: ignore[reportPrivateUsage] _Msg = TypeVar("_Msg") _Reply = TypeVar("_Reply") +_StartedMsg = TypeVar("_StartedMsg") class AsyncReplyChannel(Generic[_Reply]): @@ -36,129 +37,122 @@ def reply(self, r: _Reply) -> None: class MailboxProcessor(Generic[_Msg]): - def __init__(self, cancellation_token: CancellationToken | None) -> None: - self.messages: SimpleQueue[_Msg] = SimpleQueue() - self.token = cancellation_token or CancellationToken.none() - self.loop = asyncio.get_event_loop() - self.lock = RLock() + """A FIFO mailbox with one reader and thread-safe posting and replies. - # Holds the continuation i.e the `done` callback of Async.from_continuations - # returned by `receive`. - self.continuation: Continuation[_Msg] | None = None - self.cancel: Continuation[OperationCanceledError] | None = None + Construct and receive on the same running event loop. Timeouts use seconds, + as in asyncio. Cancelling a reply wait does not retract its posted message. + """ - def post(self, msg: _Msg) -> None: - """Post a message synchronously to the mailbox processor. + def __init__(self, cancellation_token: CancellationToken | None = None) -> None: + self.messages: SimpleQueue[_Msg] = SimpleQueue() + self.token = cancellation_token or CancellationToken.none() + self.loop = asyncio.get_running_loop() + # Presence owns the reader slot, even after the signal completes. + self._receive_signal: asyncio.Future[None] | None = None + self._task: asyncio.Task[None] | None = None - This method is not asynchronous since it's very fast to execute. - It simply adds the message to the message queue of the mailbox - processor and returns. + def _check_loop(self) -> None: + if asyncio.get_running_loop() is not self.loop: + raise RuntimeError("Mailbox operations must run on the owning event loop") - Args: - msg: Message to post. + def _wake(self) -> None: + if self._receive_signal is not None and not self._receive_signal.done(): + self._receive_signal.set_result(None) - Returns: - None - """ + def post(self, msg: _Msg) -> None: + """Post a message synchronously, including from another thread.""" + if self.loop.is_closed(): + raise RuntimeError("Mailbox event loop is closed") self.messages.put(msg) - self.loop.call_soon_threadsafe(self.__process_events) - - def post_and_async_reply(self, build_message: Callable[[AsyncReplyChannel[_Reply]], _Msg]) -> Awaitable[_Reply]: - """Post with async reply. + self.loop.call_soon_threadsafe(self._wake) - Post a message asynchronously to the mailbox processor and wait - for the reply. + def post_and_async_reply( + self, build_message: Callable[[AsyncReplyChannel[_Reply]], _Msg], timeout: float | None = None + ) -> Awaitable[_Reply]: + """Post immediately and await a reply, optionally timing out in seconds. - Args: - build_message: A function that takes a reply channel - (`AsyncReplyChannel[Reply]`) and returns a message to send - to the mailbox processor. The message should contain the - reply channel as e.g a tuple. - - Returns: - The reply from mailbox processor. - """ - result: _Reply | None = None - # This is the continuation for the `done` callback of the awaiting poster. - continuation: Continuation[_Reply] | None = None - - def check_completion() -> None: - if result is not None and continuation is not None: - continuation(result) - - def reply_callback(res: _Reply): - nonlocal result - result = res - check_completion() - - reply_channel = AsyncReplyChannel(reply_callback) - self.messages.put(build_message(reply_channel)) - self.__process_events() - - def callback( - done: Continuation[_Reply], - _: Continuation[Exception], - __: Continuation[OperationCanceledError], - ): - nonlocal continuation - continuation = done - check_completion() - - return from_continuations(callback) - - async def receive(self) -> _Msg: - """Receive message from mailbox. - - Returns: - An asynchronous computation which will consume the - first message in arrival order. No thread is blocked while - waiting for further messages. Raises a TimeoutException if - the timeout is exceeded. + The first reply wins, including None. Replies may come from any thread; + late replies after cancellation or timeout are ignored. """ + self._check_loop() + future: asyncio.Future[_Reply] = self.loop.create_future() - def callback( - done: Continuation[_Msg], - error: Continuation[Exception], - cancel: Continuation[OperationCanceledError], - ): - if self.continuation: - raise Exception("Receive can only be called once!") - - self.continuation = done - self.cancel = cancel - - self.__process_events() + def complete(value: _Reply) -> None: + if not future.done(): + future.set_result(value) - return await from_continuations(callback) + def reply(value: _Reply) -> None: + if not self.loop.is_closed(): + self.loop.call_soon_threadsafe(complete, value) - def __process_events(self): - # Cancellation of async workflows is more tricky in Python than - # with F# so we check the cancellation token for each process. - if self.token.is_cancellation_requested: - self.cancel, cancel = None, self.cancel - if cancel is not None: - cancel(OperationCanceledError("Mailbox was cancelled")) - return + self.post(build_message(AsyncReplyChannel(reply))) + if timeout is None: + return future + return asyncio.wait_for(future, timeout) - if self.continuation is None: - return + async def receive(self, timeout: float | None = None) -> _Msg: + """Receive the next message; raise TimeoutError after timeout seconds. - with self.lock: - if self.messages.empty(): - return - msg = self.messages.get() - self.continuation, cont = None, self.continuation - - if cont is not None: # type: ignore - cont(msg) + Only one receive may be active. Cancellation or timeout releases the + reader without consuming a message. Token cancellation raises + asyncio.CancelledError, including when messages are already queued. + """ + async with self._receive_scope(timeout) as signal: + while True: + if self.token.is_cancellation_requested: + raise asyncio.CancelledError() + try: + return self.messages.get_nowait() + except Empty: + await signal + signal = self.loop.create_future() + self._receive_signal = signal + + @asynccontextmanager + async def _receive_scope(self, timeout: float | None) -> AsyncGenerator[asyncio.Future[None], None]: + """Own the single reader and release its resources on every exit path.""" + self._check_loop() + if self._receive_signal is not None: + raise RuntimeError("Only one receive may be active at a time") + signal: asyncio.Future[None] = self.loop.create_future() + self._receive_signal = signal + registration = None + + def wake() -> None: + self.loop.call_soon_threadsafe(self._wake) + + try: + try: + registration = self.token.register(wake) + except ObjectDisposedException: + # Cancellation may win the race with listener registration. + raise asyncio.CancelledError() from None + async with asyncio.timeout(timeout): + yield signal + finally: + self._receive_signal = None + if registration is not None: + registration.dispose() + + async def wait(self) -> None: + """Await body termination and propagate its failure or cancellation. + + Cancelling this wait does not cancel the body. A directly constructed + mailbox has no body and cannot be waited on. + """ + self._check_loop() + if self._task is None: + raise RuntimeError("Mailbox has not been started") + await asyncio.shield(self._task) @staticmethod def start( - body: Callable[[MailboxProcessor[Any]], Awaitable[None]], + body: Callable[[MailboxProcessor[_StartedMsg]], Awaitable[None]], cancellation_token: CancellationToken | None = None, - ) -> MailboxProcessor[Any]: - mbox: MailboxProcessor[Any] = MailboxProcessor(cancellation_token) - start_immediate(body(mbox), cancellation_token) + ) -> MailboxProcessor[_StartedMsg]: + """Start a body whose completion can be observed with wait().""" + mbox: MailboxProcessor[_StartedMsg] = MailboxProcessor(cancellation_token) + mbox._task = _start_task(body(mbox), cancellation_token) return mbox diff --git a/expression/system/cancellation.py b/expression/system/cancellation.py index 0044e34a..b15f2ec9 100644 --- a/expression/system/cancellation.py +++ b/expression/system/cancellation.py @@ -46,6 +46,8 @@ def throw_if_cancellation_requested(self): raise ObjectDisposedException() def register(self, callback: Callable[[], None]) -> Disposable: + if not self.can_be_canceled: + return Disposable.create(lambda: None) return self._source.register_internal(callback) @staticmethod @@ -78,6 +80,7 @@ def dispose(self) -> None: if not self._is_disposed: self._is_disposed = True listeners.extend(self._listeners.values()) + self._listeners.clear() for listener in listeners: try: @@ -86,17 +89,16 @@ def dispose(self) -> None: pass def register_internal(self, callback: Callable[[], None]) -> Disposable: - if self._is_disposed: - raise ObjectDisposedException() - with self._lock: + if self._is_disposed: + raise ObjectDisposedException() current = self._id self._listeners[current] = callback self._id += 1 def dispose(): with self._lock: - del self._listeners[current] + self._listeners.pop(current, None) return Disposable.create(dispose) diff --git a/tests/test_cancellation.py b/tests/test_cancellation.py index 6a040b7c..bf2f73f8 100644 --- a/tests/test_cancellation.py +++ b/tests/test_cancellation.py @@ -93,3 +93,21 @@ def test_token_cancelled_register_throws(): token.register(lambda: called.append(True)) assert not called + + +def test_none_token_registration_is_noop(): + called: list[bool] = [] + registration = CancellationToken.none().register(lambda: called.append(True)) + registration.dispose() + assert not called + + +def test_registration_disposal_after_cancellation(): + source = CancellationTokenSource() + called: list[bool] = [] + registration = source.token.register(lambda: called.append(True)) + source.cancel() + registration.dispose() + registration.dispose() + assert called == [True] + assert not source._listeners # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_mailbox.py b/tests/test_mailbox.py index 74b9f958..93289c8b 100644 --- a/tests/test_mailbox.py +++ b/tests/test_mailbox.py @@ -1,57 +1,248 @@ +# pyright: reportPrivateUsage=false +# Inspect task and listener registries to verify lifecycle cleanup. import asyncio from collections.abc import Callable +from threading import Thread +from typing import assert_type -from hypothesis import given # type: ignore +import pytest +from hypothesis import given from hypothesis import strategies as st from expression import AsyncReplyChannel, MailboxProcessor +from expression.core import aiotools +from expression.system import CancellationToken, CancellationTokenSource -@given(st.lists(st.integers())) # type: ignore -def test_mailbox(xs: list[int]) -> None: - result: list[int] = [] +def int_reply_message(channel: AsyncReplyChannel[int]) -> AsyncReplyChannel[int]: + return channel - async def runner(): - async def process(inbox: MailboxProcessor[int]) -> None: - """The message processing function.""" - async def message_loop() -> None: - msg: int = await inbox.receive() - result.append(msg) +def object_reply_message(channel: AsyncReplyChannel[object]) -> AsyncReplyChannel[object]: + return channel - return await message_loop() - return await message_loop() # start the loop +def run_in_thread(action: Callable[[], None]) -> None: + errors: list[BaseException] = [] - agent = MailboxProcessor.start(process) - for x in xs: - agent.post(x) - await asyncio.sleep(0) - - asyncio.run(runner()) + def run() -> None: + try: + action() + except BaseException as error: + errors.append(error) - assert result == xs + thread = Thread(target=run) + thread.start() + thread.join(timeout=2) + assert not thread.is_alive() + if errors: + raise errors[0] -@given(st.integers()) # type: ignore -def test_mailbox_post_and_async_reply(x: int): +@given(st.lists(st.integers())) +def test_mailbox(xs: list[int]) -> None: async def runner(): - async def process(inbox: MailboxProcessor[tuple[int, AsyncReplyChannel[str]]]) -> None: - """The message processing function.""" + result: list[int] = [] + + async def process(inbox: MailboxProcessor[int]) -> None: + for _ in xs: + result.append(await inbox.receive()) - async def message_loop() -> None: - msg, rc = await inbox.receive() - rc.reply(f"Got {msg}") + agent = MailboxProcessor.start(process) + assert_type(agent, MailboxProcessor[int]) + for x in xs: + agent.post(x) + await agent.wait() + assert result == xs - return await message_loop() + asyncio.run(runner()) - # start the loop - return await message_loop() - agent: MailboxProcessor[tuple[int, AsyncReplyChannel[str]]] = MailboxProcessor.start(process) - build_message: Callable[[AsyncReplyChannel[str]], tuple[int, AsyncReplyChannel[str]]] = lambda r: (x, r) - reply = await agent.post_and_async_reply(build_message) +@pytest.mark.asyncio +@pytest.mark.parametrize("value", [None, False, 0, "", "reply"]) +async def test_reply_values(value: object): + async def process(inbox: MailboxProcessor[AsyncReplyChannel[object]]) -> None: + channel = await inbox.receive() + channel.reply(value) + channel.reply("duplicate") - assert reply == f"Got {x}" + agent = MailboxProcessor.start(process) + assert await agent.post_and_async_reply(object_reply_message, timeout=1) == value + await agent.wait() - asyncio.run(runner()) + +@pytest.mark.asyncio +@pytest.mark.parametrize("wake_before_cancel", [False, True]) +async def test_cancelled_receive_preserves_next_message(wake_before_cancel: bool): + inbox: MailboxProcessor[int] = MailboxProcessor() + pending = asyncio.create_task(inbox.receive()) + await asyncio.sleep(0) + if wake_before_cancel: + inbox.post(42) + await asyncio.sleep(0) + pending.cancel() + if not wake_before_cancel: + inbox.post(42) + with pytest.raises(asyncio.CancelledError): + await pending + assert await inbox.receive() == 42 + + +@pytest.mark.asyncio +async def test_receive_timeout_releases_reader(): + inbox: MailboxProcessor[int] = MailboxProcessor() + with pytest.raises(TimeoutError): + await inbox.receive(timeout=0) + with pytest.raises(TimeoutError): + await asyncio.wait_for(inbox.receive(), 0.001) + inbox.post(42) + assert await inbox.receive() == 42 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("wake_before_second_receive", [False, True]) +async def test_concurrent_receive_rejected_without_disturbing_reader(wake_before_second_receive: bool): + inbox: MailboxProcessor[int] = MailboxProcessor() + first = asyncio.create_task(inbox.receive()) + await asyncio.sleep(0) + if wake_before_second_receive: + inbox.post(42) + await asyncio.sleep(0) + with pytest.raises(RuntimeError, match="Only one receive"): + await inbox.receive() + if not wake_before_second_receive: + inbox.post(42) + assert await first == 42 + + +@pytest.mark.asyncio +async def test_token_cancels_idle_direct_receive_from_thread(): + source = CancellationTokenSource() + inbox: MailboxProcessor[int] = MailboxProcessor(source.token) + pending = asyncio.create_task(inbox.receive()) + await asyncio.sleep(0) + run_in_thread(source.cancel) + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(pending, 1) + inbox.post(42) + with pytest.raises(asyncio.CancelledError): + await inbox.receive() + assert inbox.messages.qsize() == 1 + + +@pytest.mark.asyncio +async def test_post_and_reply_from_threads(): + loop = asyncio.get_running_loop() + previous = loop.get_debug() + loop.set_debug(True) + try: + inbox: MailboxProcessor[AsyncReplyChannel[int]] = MailboxProcessor() + pending = asyncio.create_task(inbox.receive()) + await asyncio.sleep(0) + result = inbox.post_and_async_reply(int_reply_message) + channel = await pending + run_in_thread(lambda: channel.reply(42)) + assert await asyncio.wait_for(result, 1) == 42 + ints: MailboxProcessor[int] = MailboxProcessor() + pending_int = asyncio.create_task(ints.receive()) + await asyncio.sleep(0) + run_in_thread(lambda: ints.post(7)) + assert await asyncio.wait_for(pending_int, 1) == 7 + finally: + loop.set_debug(previous) + + +@pytest.mark.asyncio +async def test_late_reply_after_timeout_or_cancellation_is_ignored(): + inbox: MailboxProcessor[AsyncReplyChannel[int]] = MailboxProcessor() + with pytest.raises(TimeoutError): + await inbox.post_and_async_reply(int_reply_message, timeout=0) + (await inbox.receive()).reply(1) + result = asyncio.ensure_future(inbox.post_and_async_reply(int_reply_message)) + result.cancel() + with pytest.raises(asyncio.CancelledError): + await result + (await inbox.receive()).reply(2) + await asyncio.sleep(0) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_start_token_and_task_cleanup(cancelled: bool): + source = CancellationTokenSource() + entered = False + if cancelled: + source.cancel() + + async def body(inbox: MailboxProcessor[int]) -> None: + nonlocal entered + entered = True + + before = set(aiotools.__running_tasks) + agent = MailboxProcessor.start(body, source.token if cancelled else CancellationToken.none()) + if cancelled: + with pytest.raises(asyncio.CancelledError): + await agent.wait() + assert not entered + else: + await agent.wait() + assert entered + assert set(aiotools.__running_tasks) == before + + +@pytest.mark.asyncio +async def test_failed_body_observable_and_not_retained(): + before = set(aiotools.__running_tasks) + source = CancellationTokenSource() + + async def body(inbox: MailboxProcessor[int]) -> None: + raise ValueError("failure") + + agent = MailboxProcessor.start(body, source.token) + with pytest.raises(ValueError, match="failure"): + await agent.wait() + assert set(aiotools.__running_tasks) == before + assert not source._listeners + + +@pytest.mark.asyncio +async def test_cancel_wait_does_not_cancel_body(): + finish = asyncio.Event() + + async def body(inbox: MailboxProcessor[int]) -> None: + await finish.wait() + + agent = MailboxProcessor.start(body) + waiter = asyncio.create_task(agent.wait()) + await asyncio.sleep(0) + waiter.cancel() + with pytest.raises(asyncio.CancelledError): + await waiter + finish.set() + await agent.wait() + + +@pytest.mark.asyncio +async def test_cancellation_cleans_up_started_body(): + source = CancellationTokenSource() + ready = asyncio.Event() + before = set(aiotools.__running_tasks) + + async def body(inbox: MailboxProcessor[int]) -> None: + ready.set() + await inbox.receive() + + agent = MailboxProcessor.start(body, source.token) + await ready.wait() + run_in_thread(source.cancel) + with pytest.raises(asyncio.CancelledError): + await agent.wait() + assert set(aiotools.__running_tasks) == before + assert not source._listeners + + +@pytest.mark.asyncio +async def test_wait_requires_started_mailbox(): + inbox: MailboxProcessor[int] = MailboxProcessor() + with pytest.raises(RuntimeError, match="not been started"): + await inbox.wait() diff --git a/typing_tests/negative.py b/typing_tests/negative.py index 00faf417..e577ff9d 100644 --- a/typing_tests/negative.py +++ b/typing_tests/negative.py @@ -2,7 +2,7 @@ from typing import Generic, Literal, TypeAlias, TypeVar, final -from expression import Error, Nothing, Option, Result, Some, TaggedUnion, case, tag +from expression import Error, MailboxProcessor, Nothing, Option, Result, Some, TaggedUnion, case, tag def unchecked(value: Option[int]) -> None: @@ -106,3 +106,12 @@ class CustomKeyword: class ExtraNothing(Nothing): # type-error pass + + +async def integer_mailbox_body(inbox: MailboxProcessor[int]) -> None: + await inbox.receive() + + +def invalid_mailbox_message() -> None: + agent = MailboxProcessor.start(integer_mailbox_body) + agent.post("wrong") # type-error