From d1b997cd045efbfe2daaffb162a905429675953c Mon Sep 17 00:00:00 2001 From: Robert Horvath Date: Mon, 16 Nov 2026 22:38:22 +0000 Subject: [PATCH 1/4] Preserve native channel deliveries across None payloads and cancellation --- CHANGELOG.md | 4 +- c_src/py_callback.c | 11 +++-- docs/code-map.md | 2 +- priv/_erlang_impl/_channel.py | 74 ++++++++------------------------ test/coverage_audit.md | 2 +- test/py_channel_SUITE.erl | 81 +++++++++++++++++++++++++++++++++++ 6 files changed, 110 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bb2487..b19e417 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,10 @@ 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. +- Native `Channel.async_receive()` no longer drops a queued `None` or a + delivery whose receiver is cancelled after notification. - +## 5.0.1 (2026-09-22) ### Fixed diff --git a/c_src/py_callback.c b/c_src/py_callback.c index 7b0d1bb..ccef929 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; diff --git a/docs/code-map.md b/docs/code-map.md index 647994f..b0a6eb0 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -30,7 +30,7 @@ exercised by suites). Guides are in `docs/`, suites in `test/`. Start with | `py_event_worker` | One process per running loop receiving `enif_select` readiness and timers | live | event_loop_architecture | `py_event_loop_SUITE`, `py_fd_ops_SUITE` | | `py_event_worker_sup`, `py_event_worker_registry` | Supervisor and name registry of the event workers | live | event_loop_architecture | `py_event_loop_SUITE` | | `py_reactor_context` | FD-owning context for the protocol-based reactor | live | reactor | `py_reactor_SUITE` | -| `py_channel`, `py_byte_channel` | Term and byte queues between Erlang and Python coroutines (NIF resources) | live | channel | `py_channel_SUITE`, `py_byte_channel_SUITE` | +| `py_channel`, `py_byte_channel` | Term and byte queues between Erlang and Python coroutines (NIF resources); native term receives dequeue in the receiving task, not the readiness callback | live | channel | `py_channel_SUITE`, `py_byte_channel_SUITE` | | `py_buffer` | Native streaming input buffer; shared variant delegates to `py_shm` | live | buffer, isolated | `py_buffer_SUITE`, `py_isolated_buffer_SUITE` | | `py_shm` | Shared memory regions over iommap and the ring behind shared buffers | live | isolated | `py_isolated_shm_SUITE` | | `py_import` | Registry of imports and `sys.path` entries applied to every interpreter | live | imports | `py_import_SUITE` | diff --git a/priv/_erlang_impl/_channel.py b/priv/_erlang_impl/_channel.py index e0bddba..b4cfee4 100644 --- a/priv/_erlang_impl/_channel.py +++ b/priv/_erlang_impl/_channel.py @@ -164,6 +164,10 @@ async def async_receive(self): """ import asyncio + loop = asyncio.get_running_loop() + if hasattr(loop, '_loop_capsule') and hasattr(loop, '_timers'): + return await self._async_receive_event_driven(loop) + # Try non-blocking first (direct NIF - fast) result = self.try_receive() if result is not None: @@ -173,15 +177,7 @@ async def async_receive(self): if self._is_closed(): raise ChannelClosed("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): """Event-driven async receive using channel waiter mechanism. @@ -189,62 +185,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/coverage_audit.md b/test/coverage_audit.md index 5087787..5b9f3e6 100644 --- a/test/coverage_audit.md +++ b/test/coverage_audit.md @@ -102,7 +102,7 @@ suite is visible. `scripts/check_code_map.sh` requires a row per module. | `erlang.spawn_task()` | asyncio.md | `py_async_task_SUITE` | | `erlang.sleep()` | asyncio.md | `py_erlang_sleep_SUITE` | | `erlang.SharedDict` | shared-dict.md | `py_SUITE` (`test_shared_dict_*`) | -| `erlang.Channel`, `erlang.ByteChannel` | channel.md, buffer.md | `py_channel_SUITE`, `py_byte_channel_SUITE` | +| `erlang.Channel`, `erlang.ByteChannel` | channel.md, buffer.md | `py_channel_SUITE` (including native None payloads, readiness cancellation and isolated rejection), `py_byte_channel_SUITE` | | `erlang.reactor.Protocol` and friends | reactor.md | `py_reactor_SUITE` | | `erlang.state_set / state_get / state_delete / state_keys / state_incr / state_decr` (registered callbacks) | README, getting-started.md | `py_SUITE` (`test_shared_state`) | diff --git a/test/py_channel_SUITE.erl b/test/py_channel_SUITE.erl index ae35277..a6ceb74 100644 --- a/test/py_channel_SUITE.erl +++ b/test/py_channel_SUITE.erl @@ -27,6 +27,9 @@ python_try_receive_test/1, python_iterate_test/1, async_receive_immediate_test/1, + native_none_payload_test/1, + native_cancel_ready_test/1, + isolated_channel_rejected_test/1, async_receive_wait_test/1, async_iteration_test/1, async_closed_channel_test/1, @@ -63,6 +66,9 @@ all() -> [ python_try_receive_test, python_iterate_test, async_receive_immediate_test, + native_none_payload_test, + native_cancel_ready_test, + isolated_channel_rejected_test, async_receive_wait_test, async_iteration_test, async_closed_channel_test, @@ -99,6 +105,81 @@ 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. + +isolated_channel_rejected_test(_Config) -> + {ok, Ctx} = py_context:new(#{mode => isolated}), + try + {ok, true} = py_context:eval(Ctx, <<" +exec('import erlang\\ntry:\\n erlang.Channel(None)\\nexcept RuntimeError:\\n rejected = True\\nelse:\\n rejected = False') or rejected +">>) + after + py_context:destroy(Ctx) + end. + end_per_testcase(_TestCase, _Config) -> ok. From 82c3d320616392441204b2f3aa195f879b30e01c Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Thu, 26 Nov 2026 22:36:08 +0100 Subject: [PATCH 2/4] Receive a queued None on any loop before registering a waiter On a plain asyncio loop, async_receive() still began with try_receive(), which takes a queued None and reports the channel as empty, so the message was lost. It now begins with receive(0) on every loop, which raises TimeoutError only when the channel is empty. When data is already queued, the native path no longer builds a future and a handle for it. --- priv/_erlang_impl/_channel.py | 18 +++++----- test/py_channel_SUITE.erl | 62 +++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/priv/_erlang_impl/_channel.py b/priv/_erlang_impl/_channel.py index b4cfee4..427c713 100644 --- a/priv/_erlang_impl/_channel.py +++ b/priv/_erlang_impl/_channel.py @@ -164,19 +164,17 @@ async def async_receive(self): """ import asyncio + # 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 + loop = asyncio.get_running_loop() if hasattr(loop, '_loop_capsule') and hasattr(loop, '_timers'): return await self._async_receive_event_driven(loop) - - # 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") - return await self._async_receive_polling() async def _async_receive_event_driven(self, loop): diff --git a/test/py_channel_SUITE.erl b/test/py_channel_SUITE.erl index a6ceb74..e9cf8b0 100644 --- a/test/py_channel_SUITE.erl +++ b/test/py_channel_SUITE.erl @@ -29,6 +29,8 @@ 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, isolated_channel_rejected_test/1, async_receive_wait_test/1, async_iteration_test/1, @@ -68,6 +70,8 @@ all() -> [ async_receive_immediate_test, native_none_payload_test, native_cancel_ready_test, + native_send_then_close_test, + fallback_none_payload_test, isolated_channel_rejected_test, async_receive_wait_test, async_iteration_test, @@ -170,6 +174,64 @@ def run_cancel_ready(ref): 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. + isolated_channel_rejected_test(_Config) -> {ok, Ctx} = py_context:new(#{mode => isolated}), try From a8c3173277f0b90c61717a5f65c57b1bf46d03f8 Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Thu, 26 Nov 2026 22:38:09 +0100 Subject: [PATCH 3/4] Keep a byte channel delivery when its receiver is cancelled ByteChannel.async_receive_bytes() lost data the same way: its wake-up callback took the bytes, so a task cancelled before it resumed dropped them. It now uses the term channel's loop, where the callback only wakes the task. The byte wait takes queued data before it reports a close, and no longer leaks the bytes it returns, a path every woken receive now takes. --- c_src/py_callback.c | 13 +--- priv/_erlang_impl/_byte_channel.py | 78 +++++-------------- test/py_byte_channel_SUITE.erl | 119 ++++++++++++++++++++++++++++- 3 files changed, 141 insertions(+), 69 deletions(-) diff --git a/c_src/py_callback.c b/c_src/py_callback.c index ccef929..5d754db 100644 --- a/c_src/py_callback.c +++ b/c_src/py_callback.c @@ -3157,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; @@ -3190,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/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/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. From 535046f496221b6217dc34971e124dbbf494030e Mon Sep 17 00:00:00 2001 From: Benoit Chesneau Date: Thu, 26 Nov 2026 22:39:27 +0100 Subject: [PATCH 4/4] Describe the channel receive changes, drop a duplicate test The channel guide still showed the wake-up callback taking the message; it now shows the task taking it after the wake-up, what a cancel or a close means for queued messages, and that try_receive() cannot tell a queued none from an empty channel. The CHANGELOG entry covers both channel types. The isolated rejection test repeated py_isolated_SUITE, and the code map row goes back to what the module is. --- CHANGELOG.md | 7 +++++-- docs/channel.md | 24 ++++++++++++++++++------ docs/code-map.md | 2 +- test/coverage_audit.md | 2 +- test/py_channel_SUITE.erl | 12 ------------ 5 files changed, 25 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b19e417..51c4f94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,11 @@ 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. -- Native `Channel.async_receive()` no longer drops a queued `None` or a - delivery whose receiver is cancelled after notification. +- 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) 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/docs/code-map.md b/docs/code-map.md index b0a6eb0..647994f 100644 --- a/docs/code-map.md +++ b/docs/code-map.md @@ -30,7 +30,7 @@ exercised by suites). Guides are in `docs/`, suites in `test/`. Start with | `py_event_worker` | One process per running loop receiving `enif_select` readiness and timers | live | event_loop_architecture | `py_event_loop_SUITE`, `py_fd_ops_SUITE` | | `py_event_worker_sup`, `py_event_worker_registry` | Supervisor and name registry of the event workers | live | event_loop_architecture | `py_event_loop_SUITE` | | `py_reactor_context` | FD-owning context for the protocol-based reactor | live | reactor | `py_reactor_SUITE` | -| `py_channel`, `py_byte_channel` | Term and byte queues between Erlang and Python coroutines (NIF resources); native term receives dequeue in the receiving task, not the readiness callback | live | channel | `py_channel_SUITE`, `py_byte_channel_SUITE` | +| `py_channel`, `py_byte_channel` | Term and byte queues between Erlang and Python coroutines (NIF resources) | live | channel | `py_channel_SUITE`, `py_byte_channel_SUITE` | | `py_buffer` | Native streaming input buffer; shared variant delegates to `py_shm` | live | buffer, isolated | `py_buffer_SUITE`, `py_isolated_buffer_SUITE` | | `py_shm` | Shared memory regions over iommap and the ring behind shared buffers | live | isolated | `py_isolated_shm_SUITE` | | `py_import` | Registry of imports and `sys.path` entries applied to every interpreter | live | imports | `py_import_SUITE` | diff --git a/test/coverage_audit.md b/test/coverage_audit.md index 5b9f3e6..5087787 100644 --- a/test/coverage_audit.md +++ b/test/coverage_audit.md @@ -102,7 +102,7 @@ suite is visible. `scripts/check_code_map.sh` requires a row per module. | `erlang.spawn_task()` | asyncio.md | `py_async_task_SUITE` | | `erlang.sleep()` | asyncio.md | `py_erlang_sleep_SUITE` | | `erlang.SharedDict` | shared-dict.md | `py_SUITE` (`test_shared_dict_*`) | -| `erlang.Channel`, `erlang.ByteChannel` | channel.md, buffer.md | `py_channel_SUITE` (including native None payloads, readiness cancellation and isolated rejection), `py_byte_channel_SUITE` | +| `erlang.Channel`, `erlang.ByteChannel` | channel.md, buffer.md | `py_channel_SUITE`, `py_byte_channel_SUITE` | | `erlang.reactor.Protocol` and friends | reactor.md | `py_reactor_SUITE` | | `erlang.state_set / state_get / state_delete / state_keys / state_incr / state_decr` (registered callbacks) | README, getting-started.md | `py_SUITE` (`test_shared_state`) | diff --git a/test/py_channel_SUITE.erl b/test/py_channel_SUITE.erl index e9cf8b0..d814fdf 100644 --- a/test/py_channel_SUITE.erl +++ b/test/py_channel_SUITE.erl @@ -31,7 +31,6 @@ native_cancel_ready_test/1, native_send_then_close_test/1, fallback_none_payload_test/1, - isolated_channel_rejected_test/1, async_receive_wait_test/1, async_iteration_test/1, async_closed_channel_test/1, @@ -72,7 +71,6 @@ all() -> [ native_cancel_ready_test, native_send_then_close_test, fallback_none_payload_test, - isolated_channel_rejected_test, async_receive_wait_test, async_iteration_test, async_closed_channel_test, @@ -232,16 +230,6 @@ def fallback_receive_two(ref): py_channel:close(Ch) end. -isolated_channel_rejected_test(_Config) -> - {ok, Ctx} = py_context:new(#{mode => isolated}), - try - {ok, true} = py_context:eval(Ctx, <<" -exec('import erlang\\ntry:\\n erlang.Channel(None)\\nexcept RuntimeError:\\n rejected = True\\nelse:\\n rejected = False') or rejected -">>) - after - py_context:destroy(Ctx) - end. - end_per_testcase(_TestCase, _Config) -> ok.