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
5 changes: 4 additions & 1 deletion src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -1099,7 +1099,10 @@ def channel_to_stream(

The channel is reserved when this function is called, before the returned
coroutine is awaited, so nothing can read it in between; the task that runs the
coroutine takes the channel over, and any other task's read is refused.
coroutine takes the channel over, and any other task's read is refused. If the
coroutine never starts (its task is cancelled first, or it is never awaited),
the reservation's claim is freed with it and the channel is closed, so no
producer waits on it.

Args:
channel: The input channel, not read yet.
Expand Down
69 changes: 63 additions & 6 deletions src/orcapod/core/streams/record_batch_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from __future__ import annotations

import asyncio
import weakref
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING, Any, Protocol

Expand Down Expand Up @@ -84,8 +85,12 @@ def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None:
self._reading = False
# The consumer: the asyncio task the channel belongs to, for its whole life,
# and the claim a conversion holds while it moves to the task that runs it.
# The claim is held weakly: a claim freed before a task took it over (its
# conversion cancelled before it started, or never awaited) closes the
# channel, so no producer waits on a reader nobody will read.
self._owner: asyncio.Task[Any] | None = None
self._claim: object | None = None
self._claim: weakref.ref[_Claim] | None = None
self._claim_release: weakref.finalize[Any, Any] | None = None

@property
def stream(self) -> StreamProtocol:
Expand Down Expand Up @@ -132,13 +137,14 @@ def reserve(self, claim: object | None = None) -> object:
if self._closed:
raise self._closed_early()
if claim is not None:
if claim is not self._claim:
held = self._claim() if self._claim is not None else None
if held is None or claim is not held:
raise RuntimeError(
f"The input channel of {_named(self._stream)} is claimed by "
+ "another consumer."
)
self._owner = _current_task()
self._claim = None # redeemed: a later reserve(claim) is refused
self._drop_claim() # redeemed: a later reserve(claim) is refused
return claim
if self._started or self._ended or self._owner is not None:
raise RuntimeError(
Expand All @@ -148,8 +154,35 @@ def reserve(self, claim: object | None = None) -> object:
)
self._started = True
self._owner = None # held for the claim until a task takes it over
self._claim = object()
return self._claim
new_claim = _Claim()
self._claim = weakref.ref(new_claim)
# The release holds the feed (the reader's place in its producer, which never
# refers to the channel), so it is released even if the channel object has
# been freed first.
self._claim_release = weakref.finalize(
new_claim, _release_claim, self._feed, weakref.ref(self)
)
return new_claim

def _drop_claim(self) -> None:
"""Forget the claim: taken over, or the channel closed."""
if self._claim_release is not None:
_ = self._claim_release.detach()
self._claim_release = None
self._claim = None

def _abandon(self) -> None:
"""Mark the channel closed: its claim was freed before any task took it over.

Synchronous (it runs when the claim is freed); its feed is closed by the
claim's release itself (``_release_claim``).
"""
self._claim_release = None
self._claim = None
if not self._ended:
self._closed = True
self._ended = True
self._owner = None

def _belong_to_caller(self) -> None:
"""Bind the channel to the calling task on its first read; refuse any other.
Expand Down Expand Up @@ -269,10 +302,34 @@ async def close(self) -> None:
self._closed = True
self._ended = True
self._owner = None
self._claim = None
self._drop_claim()
self._feed.close()


class _Claim:
"""The claim ``reserve()`` returns; the channel is held for it while it lives.

A plain class, so that the channel can hold it weakly.
"""


def _release_claim(feed: BatchFeed, channel_ref: weakref.ref[InputChannel]) -> None:
"""Release a reader whose claim was freed before any task took it over.

The reader's feed (its place in its producer) is closed in every case, so no
producer waits on it, also when the channel object was freed first; the channel,
if it still exists, is marked closed.

Args:
feed: The reader's feed.
channel_ref: The channel, held weakly.
"""
feed.close()
channel = channel_ref()
if channel is not None:
channel._abandon() # pyright: ignore[reportPrivateUsage] # the claim's release


def _current_task() -> asyncio.Task[Any] | None:
"""The running asyncio task, or ``None`` outside one."""
try:
Expand Down
3 changes: 2 additions & 1 deletion src/orcapod/protocols/core_protocols/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,8 @@ def reserve(self, claim: object | None = None) -> object:
Without ``claim``, the unread channel is held for the returned claim, not for
the calling task: no task, the reserving one included, can read it until a
task takes it over with that claim (``reserve(claim)``), after which only
that task reads it. A claim is taken over once.
that task reads it. A claim is taken over once; a claim freed before it was
taken over closes the channel.

Raises:
RuntimeError: If a read was called on it already, or ``claim`` is not its
Expand Down
53 changes: 53 additions & 0 deletions tests/test_channels/test_record_batch_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,59 @@ async def read() -> None:
assert unheard == []


@pytest.mark.parametrize("never", ["cancelled", "dropped"])
def test_a_conversion_that_never_starts_releases_its_reader(never: str) -> None:
"""``channel_to_stream`` reserves at call time. If its conversion never starts (its
task is cancelled before the first step, or it is dropped unawaited), the
reservation is released: the reader is closed and a bounded producer no longer
waits on it."""
stream = source(4)
batches = batches_of(stream, 1)

async def read() -> None:
output = OutputChannel(stream, retain=False, buffer_size=1)
reader = output.open_reader()
if never == "cancelled":
task = asyncio.ensure_future(channel_to_stream(reader))
_ = task.cancel()
_ = await asyncio.gather(task, return_exceptions=True)
del task
else:
pending = channel_to_stream(reader)
pending.close() # what dropping an unawaited coroutine does
del pending
gc.collect()
for batch in batches: # would wait forever on a held reader of one slot
await asyncio.wait_for(output.send(batch), 1)
await output.close()
with pytest.raises(ChannelClosed):
_ = await reader.receive()

run(read)


def test_a_dropped_reader_whose_claim_is_freed_later_releases_its_producer() -> None:
"""A reader of a bounded output is reserved, then the reader object is dropped
before its claim: when the claim is freed, the reader's place in the output is
released all the same, so sends past its queue complete."""
stream = source(4)
batches = batches_of(stream, 1)

async def read() -> None:
output = OutputChannel(stream, retain=False, buffer_size=1)
reader = output.open_reader()
claim = reader.reserve()
del reader
gc.collect() # the channel is gone; its claim is not
del claim
gc.collect()
for batch in batches: # would wait forever on a reader still registered
await asyncio.wait_for(output.send(batch), 1)
await output.close()

run(read)


def test_a_closed_reader_cannot_be_converted() -> None:
"""A reader closed before any read: ``channel_to_stream`` raises ``ChannelClosed``,
as documented, not the error of a channel already read."""
Expand Down
14 changes: 8 additions & 6 deletions tests/test_core/operators/test_record_batch_execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,16 @@ def _cut(table: pa.Table, sizes: tuple[int, ...] | None) -> list[pa.RecordBatch]
async def _channel(
stream: StreamProtocol, sizes: tuple[int, ...] | None
) -> RecordBatchInput:
"""An input channel delivering ``stream``'s rows in record batches of ``sizes``."""
batches = await stream.open_channel().collect()
if sizes is None or not batches:
"""An input channel delivering ``stream``'s rows in record batches of ``sizes``:
the stream's own channel for ``None``, else one read of it, cut and re-sent
through an output channel (never a second read of the stream)."""
if sizes is None:
return stream.open_channel()
rows = pa.Table.from_batches(batches)
batches = await stream.open_channel().collect()
feed = OutputChannel(stream)
for batch in _cut(rows, sizes):
await feed.send(batch)
if batches:
for batch in _cut(pa.Table.from_batches(batches), sizes):
await feed.send(batch)
await feed.close()
return feed.open_reader()

Expand Down
Loading