Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
24 changes: 9 additions & 15 deletions c_src/py_callback.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
}

Expand Down
24 changes: 18 additions & 6 deletions docs/channel.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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()`

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
78 changes: 20 additions & 58 deletions priv/_erlang_impl/_byte_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
82 changes: 22 additions & 60 deletions priv/_erlang_impl/_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,87 +164,49 @@ 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.

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.
Expand Down
Loading
Loading