diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bb2487..51c4f94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,13 @@ timeout. The context thread waited for the callback on its pipe while the nested call sat in its queue. It now waits inline and serves the nested call, as worker contexts do since 5.0.1. +- Awaiting a message on a channel could lose it. A message that was `none` + arrived in Python as `None`, was taken for an empty channel and skipped, + on any event loop. On the Erlang event loop, a task cancelled just after a + message woke it dropped that message, on term and byte channels alike. + The message now stays in the channel until a receive returns it. - +## 5.0.1 (2026-09-22) ### Fixed diff --git a/c_src/py_callback.c b/c_src/py_callback.c index 7b0d1bb..5d754db 100644 --- a/c_src/py_callback.c +++ b/c_src/py_callback.c @@ -3000,12 +3000,6 @@ static PyObject *erlang_channel_wait_impl(PyObject *self, PyObject *args) { pthread_mutex_lock(&channel->mutex); - /* Check if closed */ - if (channel->closed) { - pthread_mutex_unlock(&channel->mutex); - return Py_BuildValue("(ss)", "error", "closed"); - } - /* Check if waiter already exists */ if (channel->has_waiter || channel->has_sync_waiter) { pthread_mutex_unlock(&channel->mutex); @@ -3063,6 +3057,11 @@ static PyObject *erlang_channel_wait_impl(PyObject *self, PyObject *args) { } } + if (channel->closed) { + pthread_mutex_unlock(&channel->mutex); + return Py_BuildValue("(ss)", "error", "closed"); + } + /* No data - register waiter */ enif_keep_resource(loop); channel->waiter_loop = loop; @@ -3158,19 +3157,13 @@ static PyObject *erlang_byte_channel_wait_impl(PyObject *self, PyObject *args) { pthread_mutex_lock(&channel->mutex); - /* Check if closed */ - if (channel->closed) { - pthread_mutex_unlock(&channel->mutex); - return Py_BuildValue("(ss)", "error", "closed"); - } - /* Check if waiter already exists */ if (channel->has_waiter || channel->has_sync_waiter) { pthread_mutex_unlock(&channel->mutex); return Py_BuildValue("(ss)", "error", "waiter_exists"); } - /* Check if data available */ + /* Check if data available (drained before reporting a close) */ size_t queue_size = enif_ioq_size(channel->queue); if (queue_size > 0) { SysIOVec *iov; @@ -3191,8 +3184,9 @@ static PyObject *erlang_byte_channel_wait_impl(PyObject *self, PyObject *args) { channel->current_size -= msg_size; pthread_mutex_unlock(&channel->mutex); - /* Return raw bytes (NO term decoding) */ - return Py_BuildValue("(sO)", "ok", bytes); + /* Return raw bytes (NO term decoding); "N" hands the + * reference to the tuple */ + return Py_BuildValue("(sN)", "ok", bytes); } } diff --git a/docs/channel.md b/docs/channel.md index 0a2acd7..9937d55 100644 --- a/docs/channel.md +++ b/docs/channel.md @@ -158,6 +158,10 @@ msg = ch.try_receive() # Returns None if empty **Returns:** Message or `None` if empty. **Raises:** `ChannelClosed` when the channel is closed. +A queued `none` also comes back as `None`, so you cannot tell it from an +empty channel. If Erlang may send `none`, use `receive(0)`, which raises +`TimeoutError` when the channel is empty, or `async_receive()`. + #### `async_receive()` Asyncio-compatible receive. Yields to other coroutines while waiting. @@ -167,10 +171,11 @@ msg = await ch.async_receive() ``` **Behavior:** -- When using `ErlangEventLoop`: Uses event-driven notification (no polling). The channel notifies the event loop via timer dispatch when data arrives. -- When using other asyncio loops: Falls back to polling with 100us sleep intervals. +- If the channel has data, returns it immediately, including a queued `None`. +- When using `ErlangEventLoop`: Uses event-driven notification (no polling). The channel notifies the event loop via timer dispatch when data arrives. A task cancelled while waiting leaves the message in the channel for the next receive. +- When using other asyncio loops: Runs a blocking receive in the loop's default executor, in 100 ms waits. Cancelling the task does not stop a wait already running, so a message that arrives during it is lost. -**Raises:** `ChannelClosed` when the channel is closed. +**Raises:** `ChannelClosed` when the channel is closed and empty. #### `close()` @@ -383,7 +388,7 @@ Python C / Erlang await ch.async_receive() │ - ├── try_receive() ──────────▶ Check queue (fast path) + ├── receive(0) ─────────────▶ Check queue (fast path) │ └── Data? Return immediately │ └── No data: @@ -418,13 +423,20 @@ await future ◀───────────────────── │ Fire handle from _timers │ │ │ ▼ - │ Callback: try_receive() → future.set_result(data) + │ Callback: future.set_result(None) (wake only) │ ▼ +_channel_wait() again ──────────────▶ Dequeue under the channel lock + │ (or register a new waiter) + ▼ Return data ``` This avoids polling overhead - Python only wakes when data actually arrives. +The callback only wakes the task, and the task takes the message itself when +it resumes, so a task cancelled between the two leaves the message queued. +After a close, the task still gets the messages queued before it, then +`ChannelClosed`. ## ByteChannel - Raw Byte Streaming @@ -509,7 +521,7 @@ async def process_bytes_async(channel_ref): process(chunk) ``` -**Event-driven async:** When using `ErlangEventLoop`, `async_receive_bytes()` uses event-driven notification instead of polling. The channel signals the event loop when data arrives, avoiding CPU overhead from sleep loops. +**Event-driven async:** When using `ErlangEventLoop`, `async_receive_bytes()` uses event-driven notification instead of polling. The channel signals the event loop when data arrives, avoiding CPU overhead from sleep loops. As with `Channel`, a task cancelled while waiting on `ErlangEventLoop` leaves the bytes in the channel. ### ByteChannel vs Channel Architecture diff --git a/priv/_erlang_impl/_byte_channel.py b/priv/_erlang_impl/_byte_channel.py index 63979f9..eb76302 100644 --- a/priv/_erlang_impl/_byte_channel.py +++ b/priv/_erlang_impl/_byte_channel.py @@ -187,87 +187,49 @@ async def async_receive_bytes(self) -> bytes: """ import asyncio - # Try non-blocking first (direct NIF - fast path) + # Non-blocking first (direct NIF - fast path). Received bytes are + # never None, so None here always means the channel is empty. result = self.try_receive_bytes() if result is not None: return result - # Check if closed - if self._is_closed(): - raise ByteChannelClosed("Channel has been closed") - - # Get the running event loop loop = asyncio.get_running_loop() - - # Check if this is an ErlangEventLoop with native dispatch support if hasattr(loop, '_loop_capsule') and hasattr(loop, '_timers'): return await self._async_receive_event_driven(loop) - else: - # Fallback for non-Erlang event loops: use polling - return await self._async_receive_polling() + return await self._async_receive_polling() async def _async_receive_event_driven(self, loop) -> bytes: """Event-driven async receive using channel waiter mechanism. Registers with the channel and waits for EVENT_TYPE_TIMER dispatch - when data arrives. No polling required. + when data arrives. The callback only wakes the task, which then + takes the data itself, so a task cancelled after the wake-up leaves + the data in the channel. """ - import asyncio from asyncio import events import erlang - future = loop.create_future() - callback_id = id(future) + while True: + future = loop.create_future() + callback_id = id(future) - # Callback that fires when channel has data - def on_channel_ready(): - if future.done(): - return - try: - data = self.try_receive_bytes() - if data is not None: - future.set_result(data) - elif self._is_closed(): - future.set_exception(ByteChannelClosed("Channel closed")) - else: - # Data consumed by race - set None to signal retry + def on_channel_ready(future=future): + if not future.done(): future.set_result(None) - except Exception as e: - future.set_exception(e) - - # Create handle and register in timer dispatch system - # Only use _timers dict - don't touch _handle_to_callback_id (for timer cancellation only) - handle = events.Handle(on_channel_ready, (), loop) - loop._timers[callback_id] = handle - try: - # Register waiter with channel (direct C call, no Erlang overhead) - result = erlang._byte_channel_wait(self._ref, callback_id, loop._loop_capsule) - - if isinstance(result, tuple): - if result[0] == 'ok': - # Data already available - clean up and return - loop._timers.pop(callback_id, None) - return result[1] - elif result[0] == 'error': - loop._timers.pop(callback_id, None) + loop._timers[callback_id] = events.Handle(on_channel_ready, (), loop) + try: + result = erlang._byte_channel_wait(self._ref, callback_id, loop._loop_capsule) + if isinstance(result, tuple): + if result[0] == 'ok': + return result[1] if result[1] == 'closed': raise ByteChannelClosed("Channel closed") raise RuntimeError(f"Channel wait failed: {result[1]}") - - # Waiter registered - await notification - try: - data = await future - # Handle race condition (data was None) - if data is None: - # Retry with polling fallback for this edge case - return await self._async_receive_polling() - return data - except asyncio.CancelledError: + await future + finally: + loop._timers.pop(callback_id, None) erlang._byte_channel_cancel_wait(self._ref, callback_id) - raise - finally: - loop._timers.pop(callback_id, None) async def _async_receive_polling(self) -> bytes: """Fallback async receive for non-Erlang event loops. diff --git a/priv/_erlang_impl/_channel.py b/priv/_erlang_impl/_channel.py index e0bddba..427c713 100644 --- a/priv/_erlang_impl/_channel.py +++ b/priv/_erlang_impl/_channel.py @@ -164,24 +164,18 @@ async def async_receive(self): """ import asyncio - # Try non-blocking first (direct NIF - fast) - result = self.try_receive() - if result is not None: - return result - - # Check if closed - if self._is_closed(): - raise ChannelClosed("Channel has been closed") + # Non-blocking first. receive(0) raises TimeoutError when the channel + # is empty, so a queued None comes back like any other message, which + # try_receive() cannot tell apart from an empty channel. + try: + return self.receive(0) + except TimeoutError: + pass - # Get the running event loop loop = asyncio.get_running_loop() - - # Check if this is an ErlangEventLoop with native dispatch support if hasattr(loop, '_loop_capsule') and hasattr(loop, '_timers'): return await self._async_receive_event_driven(loop) - else: - # Fallback for non-Erlang event loops: use polling - return await self._async_receive_polling() + return await self._async_receive_polling() async def _async_receive_event_driven(self, loop): """Event-driven async receive using channel waiter mechanism. @@ -189,62 +183,30 @@ async def _async_receive_event_driven(self, loop): Registers with the channel and waits for EVENT_TYPE_TIMER dispatch when data arrives. No polling required. """ - import asyncio from asyncio import events import erlang - future = loop.create_future() - callback_id = id(future) + while True: + future = loop.create_future() + callback_id = id(future) - # Callback that fires when channel has data - def on_channel_ready(): - if future.done(): - return - try: - data = self.try_receive() - if data is not None: - future.set_result(data) - elif self._is_closed(): - future.set_exception(ChannelClosed("Channel closed")) - else: - # Data consumed by race - set None to signal retry + def on_channel_ready(future=future): + if not future.done(): future.set_result(None) - except Exception as e: - future.set_exception(e) - # Create handle and register in timer dispatch system - # Only use _timers dict - don't touch _handle_to_callback_id (for timer cancellation only) - handle = events.Handle(on_channel_ready, (), loop) - loop._timers[callback_id] = handle - - try: - # Register waiter with channel (direct C call, no Erlang overhead) - result = erlang._channel_wait(self._ref, callback_id, loop._loop_capsule) - - if isinstance(result, tuple): - if result[0] == 'ok': - # Data already available - clean up and return - loop._timers.pop(callback_id, None) - return result[1] - elif result[0] == 'error': - loop._timers.pop(callback_id, None) + loop._timers[callback_id] = events.Handle(on_channel_ready, (), loop) + try: + result = erlang._channel_wait(self._ref, callback_id, loop._loop_capsule) + if isinstance(result, tuple): + if result[0] == 'ok': + return result[1] if result[1] == 'closed': raise ChannelClosed("Channel closed") raise RuntimeError(f"Channel wait failed: {result[1]}") - - # Waiter registered - await notification - try: - data = await future - # Handle race condition (data was None) - if data is None: - # Retry with polling fallback for this edge case - return await self._async_receive_polling() - return data - except asyncio.CancelledError: + await future + finally: + loop._timers.pop(callback_id, None) erlang._channel_cancel_wait(self._ref, callback_id) - raise - finally: - loop._timers.pop(callback_id, None) async def _async_receive_polling(self): """Fallback async receive for non-Erlang event loops. diff --git a/test/py_byte_channel_SUITE.erl b/test/py_byte_channel_SUITE.erl index d7b3aa4..787deaa 100644 --- a/test/py_byte_channel_SUITE.erl +++ b/test/py_byte_channel_SUITE.erl @@ -42,7 +42,11 @@ close_drain_bytes_erlang_test/1, close_drain_bytes_python_sync_test/1, close_drain_bytes_python_async_test/1, - close_drain_bytes_create_task_async_test/1 + close_drain_bytes_create_task_async_test/1, + %% Native async receive: cancel after wake-up, send then close + native_cancel_ready_bytes_test/1, + native_send_then_close_bytes_test/1, + native_wait_bytes_no_leak_test/1 ]). all() -> [ @@ -74,7 +78,11 @@ all() -> [ close_drain_bytes_erlang_test, close_drain_bytes_python_sync_test, close_drain_bytes_python_async_test, - close_drain_bytes_create_task_async_test + close_drain_bytes_create_task_async_test, + %% Native async receive: cancel after wake-up, send then close + native_cancel_ready_bytes_test, + native_send_then_close_bytes_test, + native_wait_bytes_no_leak_test ]. init_per_suite(Config) -> @@ -592,3 +600,110 @@ async def drain_task(ch_ref, reply_pid): {error, AwaitErr} -> ct:pal("Await error: ~p", [AwaitErr]) end. + +%% A receiver cancelled after its wake-up ran, before it resumed, leaves +%% the bytes in the channel. +native_cancel_ready_bytes_test(_Config) -> + {ok, Ch} = py_byte_channel:new(), + ok = py:register_function(byte_channel_regression_send, fun([]) -> + py_byte_channel:send(Ch, <<"payload">>) + end), + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import erlang +async def cancel_ready_bytes(ref): + loop = asyncio.get_running_loop() + channel = erlang.ByteChannel(ref) + before = set(loop._timers) + receiver = asyncio.create_task(channel.async_receive_bytes()) + await asyncio.sleep(0) + callbacks = set(loop._timers) - before + assert len(callbacks) == 1 + ready = loop._timers[callbacks.pop()] + erlang.call('byte_channel_regression_send') + ready._run() + receiver.cancel() + try: + await receiver + except asyncio.CancelledError: + pass + return channel.try_receive_bytes() +def run_cancel_ready_bytes(ref): + return erlang.run(cancel_ready_bytes(ref)) +">>), + try + {ok, <<"payload">>} = py:call(Ctx, '__main__', run_cancel_ready_bytes, [Ch]) + after + py:unregister_function(byte_channel_regression_send), + py_byte_channel:close(Ch) + end. + +%% Bytes sent just before a close, while the receiver waits, are delivered: +%% the woken receiver takes them before it sees the close. +native_send_then_close_bytes_test(_Config) -> + {ok, Ch} = py_byte_channel:new(), + ok = py:register_function(byte_channel_regression_send_close, fun([]) -> + ok = py_byte_channel:send(Ch, <<"last">>), + py_byte_channel:close(Ch) + end), + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import erlang +async def send_then_close_bytes(ref): + channel = erlang.ByteChannel(ref) + receiver = asyncio.create_task(channel.async_receive_bytes()) + await asyncio.sleep(0) + erlang.call('byte_channel_regression_send_close') + assert await asyncio.wait_for(receiver, 1) == b'last' + try: + await asyncio.wait_for(channel.async_receive_bytes(), 1) + except erlang.ByteChannelClosed: + return True + return False +def run_send_then_close_bytes(ref): + return erlang.run(send_then_close_bytes(ref)) +">>), + try + {ok, true} = py:call(Ctx, '__main__', run_send_then_close_bytes, [Ch]) + after + py:unregister_function(byte_channel_regression_send_close) + end. + +%% Bytes returned by the native wait when data is already queued are freed +%% once the caller drops them (a woken receiver takes its data this way). +native_wait_bytes_no_leak_test(_Config) -> + {ok, Ch} = py_byte_channel:new(), + Chunk = binary:copy(<<"x">>, 4096), + [ok = py_byte_channel:send(Ch, Chunk) || _ <- lists:seq(1, 1000)], + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import gc +import tracemalloc +import erlang +async def wait_drain_growth(ref, n): + capsule = asyncio.get_running_loop()._loop_capsule + tracemalloc.start() + try: + gc.collect() + before = tracemalloc.get_traced_memory()[0] + for i in range(n): + result = erlang._byte_channel_wait(ref, i + 1, capsule) + assert result[0] == 'ok' and len(result[1]) == 4096 + del result + gc.collect() + return tracemalloc.get_traced_memory()[0] - before + finally: + tracemalloc.stop() +def run_wait_drain_growth(ref, n): + return erlang.run(wait_drain_growth(ref, n)) +">>), + try + {ok, Growth} = py:call(Ctx, '__main__', run_wait_drain_growth, [Ch, 1000]), + ct:pal("traced growth after 1000 x 4 KB waits: ~p bytes", [Growth]), + true = Growth < 1024 * 1024 + after + py_byte_channel:close(Ch) + end. diff --git a/test/py_channel_SUITE.erl b/test/py_channel_SUITE.erl index ae35277..d814fdf 100644 --- a/test/py_channel_SUITE.erl +++ b/test/py_channel_SUITE.erl @@ -27,6 +27,10 @@ python_try_receive_test/1, python_iterate_test/1, async_receive_immediate_test/1, + native_none_payload_test/1, + native_cancel_ready_test/1, + native_send_then_close_test/1, + fallback_none_payload_test/1, async_receive_wait_test/1, async_iteration_test/1, async_closed_channel_test/1, @@ -63,6 +67,10 @@ all() -> [ python_try_receive_test, python_iterate_test, async_receive_immediate_test, + native_none_payload_test, + native_cancel_ready_test, + native_send_then_close_test, + fallback_none_payload_test, async_receive_wait_test, async_iteration_test, async_closed_channel_test, @@ -99,6 +107,129 @@ end_per_suite(_Config) -> init_per_testcase(_TestCase, Config) -> Config. +native_none_payload_test(_Config) -> + {ok, Ch} = py_channel:new(), + ok = py_channel:send(Ch, none), + ok = py:register_function(channel_regression_none, fun([]) -> + py_channel:send(Ch, none) + end), + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import erlang +async def receive_none(ref): + value = await asyncio.wait_for(erlang.Channel(ref).async_receive(), 0.2) + assert value is None + receiver = asyncio.create_task(erlang.Channel(ref).async_receive()) + await asyncio.sleep(0) + erlang.call('channel_regression_none') + assert await asyncio.wait_for(receiver, 0.2) is None + return True +def run_receive_none(ref): + return erlang.run(receive_none(ref)) +">>), + try + {ok, true} = py:call(Ctx, '__main__', run_receive_none, [Ch]) + after + py:unregister_function(channel_regression_none), + py_channel:close(Ch) + end. + +native_cancel_ready_test(_Config) -> + {ok, Ch} = py_channel:new(), + ok = py:register_function(channel_regression_send, fun([]) -> + py_channel:send(Ch, 42) + end), + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import erlang +async def cancel_ready(ref): + loop = asyncio.get_running_loop() + channel = erlang.Channel(ref) + before = set(loop._timers) + receiver = asyncio.create_task(channel.async_receive()) + await asyncio.sleep(0) + callbacks = set(loop._timers) - before + assert len(callbacks) == 1 + ready = loop._timers[callbacks.pop()] + erlang.call('channel_regression_send') + ready._run() + receiver.cancel() + try: + await receiver + except asyncio.CancelledError: + pass + assert channel.try_receive() == 42 + return True +def run_cancel_ready(ref): + return erlang.run(cancel_ready(ref)) +">>), + try + {ok, true} = py:call(Ctx, '__main__', run_cancel_ready, [Ch]) + after + py:unregister_function(channel_regression_send), + py_channel:close(Ch) + end. + +%% A message sent just before a close, while the receiver waits, is +%% delivered: the woken receiver takes it before it sees the close. +native_send_then_close_test(_Config) -> + {ok, Ch} = py_channel:new(), + ok = py:register_function(channel_regression_send_close, fun([]) -> + ok = py_channel:send(Ch, 42), + py_channel:close(Ch) + end), + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import erlang +async def send_then_close(ref): + channel = erlang.Channel(ref) + receiver = asyncio.create_task(channel.async_receive()) + await asyncio.sleep(0) + erlang.call('channel_regression_send_close') + assert await asyncio.wait_for(receiver, 1) == 42 + try: + await asyncio.wait_for(channel.async_receive(), 1) + except erlang.ChannelClosed: + return True + return False +def run_send_then_close(ref): + return erlang.run(send_then_close(ref)) +">>), + try + {ok, true} = py:call(Ctx, '__main__', run_send_then_close, [Ch]) + after + py:unregister_function(channel_regression_send_close) + end. + +%% On a plain asyncio loop a queued none is received as None, not taken +%% for an empty channel. +fallback_none_payload_test(_Config) -> + {ok, Ch} = py_channel:new(), + ok = py_channel:send(Ch, none), + ok = py_channel:send(Ch, second), + Ctx = py:context(1), + ok = py:exec(Ctx, <<" +import asyncio +import erlang +def fallback_receive_two(ref): + channel = erlang.Channel(ref) + loop = asyncio.SelectorEventLoop() + try: + first = loop.run_until_complete(asyncio.wait_for(channel.async_receive(), 1)) + second = loop.run_until_complete(asyncio.wait_for(channel.async_receive(), 1)) + return [first, second] + finally: + loop.close() +">>), + try + {ok, [none, <<"second">>]} = py:call(Ctx, '__main__', fallback_receive_two, [Ch]) + after + py_channel:close(Ch) + end. + end_per_testcase(_TestCase, _Config) -> ok.