From a2c31dd3e06d1352984a2d283a7a68ec210b561e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:05:13 -0800 Subject: [PATCH 1/8] refactor(channels): InputChannel in core/streams/record_batch_input; StreamBase and SourceNodeBase open_channel(); StreamProtocol declares it (ITL-1362) L1 of the approved part 2 layout: the concrete input channel imports no concrete stream, node or operator, and reads through a feed (next, close, to_stream). A stream opens a channel itself (CompleteStreamFeed, in streams/base.py beside F's per-slice step); to_stream() of such a channel is the stream. The output channel's reader feed gives stream_from_batches of what it delivered. channel_from_stream is gone: stream.open_channel(). Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 2 +- CLAUDE.md | 2 +- src/orcapod/core/nodes/source_node.py | 17 ++ src/orcapod/core/record_batch_channels.py | 247 +++--------------- src/orcapod/core/streams/base.py | 75 ++++++ .../core/streams/record_batch_input.py | 194 ++++++++++++++ .../protocols/core_protocols/streams.py | 16 ++ .../test_record_batch_channels.py | 63 +++-- .../operators/test_record_batch_execution.py | 53 ++-- 9 files changed, 403 insertions(+), 266 deletions(-) create mode 100644 src/orcapod/core/streams/record_batch_input.py diff --git a/.zed/rules b/.zed/rules index 6967e6d81..8dafa27eb 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1304,7 +1304,7 @@ data. The rules: RecordBatchOutput of protocols/core_protocols/record_batch_channels.py, which imports no concrete core module (keep modules interacting through protocols: basedpyright counts local and TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel - refers to its stream (channel_from_stream(stream)), an output channel to the stream it + refers to its stream (stream.open_channel()), an output channel to the stream it produces, and OutputChannel.result() closes it into that stream. The conversions are in one place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, _row_built_form); never build a stream from record batches elsewhere. An operator's diff --git a/CLAUDE.md b/CLAUDE.md index 7b781c65c..65376a908 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1351,7 +1351,7 @@ data. The rules: `RecordBatchOutput` of `protocols/core_protocols/record_batch_channels.py`, which imports no concrete core module (keep modules interacting through protocols: basedpyright counts local and `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input - channel refers to its stream (`channel_from_stream(stream)`), an output channel to the + channel refers to its stream (`stream.open_channel()`), an output channel to the stream it produces, and `OutputChannel.result()` closes it into that stream. The conversions are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, `transport_schema`, and F, `_row_built_form`); never build a stream from record batches diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b522c117f..ef3b5c94e 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -27,10 +27,12 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + CompleteStreamFeed, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.record_batch_input import InputChannel from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -57,6 +59,9 @@ if TYPE_CHECKING: from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -1163,6 +1168,18 @@ def run(self) -> StreamView: display_all_rows=False, ) + def open_channel(self) -> RecordBatchInput: + """Open an input channel on this node's rows, for async computation (ITL-1347). + + As ``StreamBase.open_channel()``: the rows as Arrow record batches in the + row-built form, read on the first read; the description is this node, and + ``to_stream()`` is this node. + + Returns: + The input channel. + """ + return InputChannel(self, CompleteStreamFeed(self)) + async def async_iter_data(self): """Asynchronous iterator over (tag, data) pairs. diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index a6f5e57ab..31914ccae 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -1,22 +1,21 @@ -"""Channels of Arrow record batches (ITL-1347). +"""The output channel of Arrow record batches (ITL-1347). -``InputChannel`` and ``OutputChannel`` carry a stream's rows as Arrow record batches; they -implement ``RecordBatchInput`` and ``RecordBatchOutput`` -(``orcapod.protocols.core_protocols.record_batch_channels``). The +``OutputChannel`` implements ``RecordBatchOutput`` +(``orcapod.protocols.core_protocols.record_batch_channels``): the producer side of a +node's async output. Each consumer reads through its own ``InputChannel`` +(``open_reader``, ``orcapod.core.streams.record_batch_input``), which is the fan-out. The stream is primary and owns the description (keys, schemas, data context, pipeline hash); a -channel refers to its stream and restates nothing. An input channel is opened from a -stream (``channel_from_stream``) or from an output channel (``OutputChannel.open_reader``); -an output channel, once closed, gives its rows back as a stream (``OutputChannel.result``). -A stream is made from record batches by one function, ``stream_from_batches`` of -``orcapod.core.operators.static_output_pod``. +channel refers to its stream and restates nothing. Once closed, an output channel gives its +rows back as a stream (``OutputChannel.result``). A stream is made from record batches by +one function, ``stream_from_batches`` of ``orcapod.core.operators.static_output_pod``; a +channel is opened on a complete stream by ``stream.open_channel()``. """ from __future__ import annotations import asyncio from collections import deque -from collections.abc import AsyncIterator -from typing import TYPE_CHECKING, Any, Protocol, cast +from typing import TYPE_CHECKING, Any, cast import pyarrow as pa import pyarrow.compute as pc @@ -26,79 +25,22 @@ stream_from_batches, transport_schema, ) -from orcapod.core.streams.base import ( - ZERO_ROW_INPUT_COLUMNS, - row_built_columns, - row_built_names, -) +from orcapod.core.streams.base import row_built_names +from orcapod.core.streams.record_batch_input import InputChannel from orcapod.errors import UpstreamFailedError from orcapod.system_constants import constants from orcapod.utils import arrow_utils if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol - -SOURCE_BATCH_ROWS = 65_536 -"""The most rows of one Arrow record batch a complete stream is read in. - -Developer decision, November 22, 2026 (ITL-1347, question 6): a source sends record -batches of at most 65,536 rows; an operator sends its result's own record batches. -""" + from orcapod.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + ) BATCH_BUFFER_SIZE = 8 """How many Arrow record batches an input channel queues before its producer waits.""" -class _BatchFeed(Protocol): - """Where an input channel's record batches come from.""" - - async def next(self) -> pa.RecordBatch | None: - """Return the next record batch, or ``None`` at the end.""" - ... - - def close(self) -> None: - """Stop reading: nothing waits for this reader any more.""" - ... - - -class _StreamFeed: - """The record batches of a complete stream, read at this reader's own position.""" - - def __init__(self, stream: StreamProtocol) -> None: - """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. - - Args: - stream: The complete stream to read. - """ - self._stream = stream - self._batches: deque[pa.RecordBatch] | None = None - - async def next(self) -> pa.RecordBatch | None: - """Return the stream's next record batch, or ``None`` at the end. - - The stream's table is read on the first call, not when the feed is made, in - the row-built form (``row_built_columns``) and cut into batches of at most - ``SOURCE_BATCH_ROWS`` rows; batches with no rows are skipped. - """ - if self._batches is None: - # On the first read, not when the channel is opened: opening computes - # nothing. - table = row_built_columns( - self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - self._stream.keys(), - ) - self._batches = deque( - batch - for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) - if batch.num_rows - ) - return self._batches.popleft() if self._batches else None - - def close(self) -> None: - """Stop reading: the batches not read are dropped. No producer waits on it.""" - self._batches = deque() - - class _OutputFeed: """One reader of an output channel, with its own position.""" @@ -142,6 +84,22 @@ async def next(self) -> pa.RecordBatch | None: await output._changed.wait() # pyright: ignore[reportPrivateUsage] return None + async def to_stream(self, channel: RecordBatchInput) -> StreamProtocol: + """Read ``channel`` to its end and return what it delivered, as a stream. + + The record batches in arrival order, with the identity of ``channel.stream`` + (``stream_from_batches``, which settles the provenance fields on the complete + table). + + Args: + channel: The input channel this feed serves, not read yet. + + Raises: + ChannelClosed: If the channel is closed before its producer completed. + UpstreamFailedError: If the output failed. + """ + return stream_from_batches(channel.stream, await channel.collect()) + def close(self) -> None: """Stop reading and unregister from the output. @@ -157,132 +115,6 @@ def close(self) -> None: output._notify() # pyright: ignore[reportPrivateUsage] # the producer stops waiting -class InputChannel: - """A single-pass, back-pressured reader of a stream's Arrow record batches. - - The Arrow-record-batch form of ``ReadableChannel``. The description of what it - delivers is its ``stream``, known before the first batch: the producing node, or - the stream it was opened from. A channel has no identity of its own and is read - once; to read again, go back to a stream (the one it was opened from, or the one - ``to_stream`` gives). - - Made by ``channel_from_stream`` or by ``OutputChannel.open_reader``, never - directly. - """ - - def __init__(self, stream: StreamProtocol, feed: _BatchFeed) -> None: - """Make an input channel; use ``channel_from_stream`` or ``open_reader``. - - Args: - stream: The stream whose rows the channel delivers: its description. - feed: Where the record batches come from. - """ - self._stream = stream - self._feed = feed - self._received = 0 - self._ended = False - # Closed by its consumer before the producer completed. - self._closed = False - - @property - def stream(self) -> StreamProtocol: - """The stream whose rows this channel delivers: the description.""" - return self._stream - - async def receive(self) -> pa.RecordBatch: - """Return the next Arrow record batch. - - A read that is cancelled while it waits closes the channel, as ``close`` does: - a consumer that stops reading never holds its producer. - - Raises: - ChannelClosed: At the end, and after ``close``. After a ``close`` that came - before the producer completed, the error says so, and iteration - (``async for``) raises it instead of ending: no consumer loop takes - part of an input for all of it. - UpstreamFailedError: If the producer failed or was cancelled. - """ - if self._closed: - raise self._closed_early() - if self._ended: - raise ChannelClosed() - try: - batch = await self._feed.next() - except asyncio.CancelledError: - await self.close() - raise - if batch is None: - if self._closed: # woken by its own early close - raise self._closed_early() - self._ended = True - raise ChannelClosed() - self._received += 1 - return batch - - def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: - """Iterate over the remaining record batches, in arrival order.""" - return self - - async def __anext__(self) -> pa.RecordBatch: - """Return the next record batch; end the iteration at the producer's end. - - A channel closed before its producer completed does not end the iteration: - its ``ChannelClosed`` is raised, so a loop never takes part of an input for - all of it. - """ - try: - return await self.receive() - except ChannelClosed: - if self._closed: - raise # closed before its producer completed: not the end - raise StopAsyncIteration - - def _closed_early(self) -> ChannelClosed: - """The error of a read after a close that came before the producer completed.""" - return ChannelClosed( - f"The input channel of {_named(self._stream)} was closed before its " - + "producer completed; it has no complete input to give." - ) - - async def collect(self) -> list[pa.RecordBatch]: - """Read to the end and return every remaining record batch, in arrival order. - - Raises: - ChannelClosed: If the channel was closed before its producer completed: - what was read is part of the input, never returned as all of it. - UpstreamFailedError: If the producer failed or was cancelled. - """ - return [batch async for batch in self] - - async def to_stream(self) -> StreamProtocol: - """Read to the end and return what the channel delivered, as a stream. - - The stream holds the record batches in arrival order, with the identity of - ``stream`` (``stream_from_batches``). It is how an operator that needs all of - an input reads it. Called on a channel not read yet: a stream of part of an - input is never made. - - Raises: - RuntimeError: If a record batch has already been received. - ChannelClosed: If the channel was closed before its producer completed. - UpstreamFailedError: If the producer failed or was cancelled. - """ - if self._received: - raise RuntimeError( - "to_stream() gives everything an input channel delivers, as a stream; " - + f"{self._received} record batch(es) of this one have been received " - + "already." - ) - return stream_from_batches(self._stream, await self.collect()) - - async def close(self) -> None: - """Stop reading. The producer no longer waits for this reader.""" - if not self._ended: - self._closed = True - self._ended = True - self._feed.close() - - class OutputChannel: """The producer side of a node's async output, in Arrow record batches. @@ -531,23 +363,6 @@ def result(self) -> StreamProtocol: return self._result -def channel_from_stream(stream: StreamProtocol) -> InputChannel: - """Open an input channel on a complete stream. - - The channel delivers the stream's rows in the row-built form (``row_built_columns``) as - Arrow record batches of at most ``SOURCE_BATCH_ROWS`` rows. Several channels may be - opened on one stream, each with its own position; nothing is computed until the - first read, and nothing is queued, since the stream is complete. - - Args: - stream: The stream to read; it is the channel's description. - - Returns: - The input channel. - """ - return InputChannel(stream, _StreamFeed(stream)) - - def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any stream or node """How an error names a stream: its label, or what it prints as.""" label = getattr(stream, "label", None) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index f4c28d96a..d0051dca7 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -21,6 +21,7 @@ import pyarrow as pa from orcapod.core.base import TraceableBase +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, ViewStatus, @@ -34,6 +35,7 @@ StreamProtocol, TagProtocol, ) +from orcapod.protocols.core_protocols.record_batch_channels import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils @@ -333,6 +335,64 @@ def row_built_names( return [*tag_keys, *system_tags, *data, *source_info] +class CompleteStreamFeed: + """The record batches of a complete stream, read at one reader's own position. + + The feed of a channel opened on a stream (``StreamBase.open_channel()``). Nothing + is read until the first ``next``; then the stream's table is read once, in the + row-built form (``row_built_columns``), and cut into record batches of at most + ``SOURCE_BATCH_ROWS`` rows. The stream is complete, so nothing is queued and no + producer waits on a reader. + """ + + def __init__(self, stream: StreamProtocol) -> None: + """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. + + Args: + stream: The complete stream to read. + """ + self._stream = stream + self._batches: list[pa.RecordBatch] | None = None + self._position = 0 + + async def next(self) -> pa.RecordBatch | None: + """Return the stream's next record batch, or ``None`` at the end. + + The stream's table is read on the first call, not when the channel is opened; + batches with no rows are skipped. + """ + if self._batches is None: + table = row_built_columns( + self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), + self._stream.keys(), + ) + self._batches = [ + batch + for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) + if batch.num_rows + ] + if self._position >= len(self._batches): + return None + self._position += 1 + return self._batches[self._position - 1] + + def close(self) -> None: + """Stop reading: the batches not read are dropped.""" + self._batches = [] + self._position = 0 + + async def to_stream(self, channel: RecordBatchInput) -> StreamProtocol: + """Return the stream itself: all of the input, read by nobody yet. + + It is exactly what the sync path gives an operator over that stream, identity + and rows; nothing is read or rebuilt. + + Args: + channel: The input channel this feed serves. + """ + return self._stream + + def typed_arrow_schemas( stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: @@ -1146,6 +1206,21 @@ def iter_data( self, ) -> Iterator[tuple[TagProtocol, DataProtocol]]: ... + def open_channel(self) -> RecordBatchInput: + """Open an input channel on this stream, for async computation (ITL-1347). + + The channel delivers this stream's rows as Arrow record batches of at most + ``SOURCE_BATCH_ROWS`` rows, in the row-built form, read once and in order; its + description is this stream (``channel.stream``). Several channels may be + opened on one stream, each with its own position, and the stream stays as it + is. Nothing is read until the channel is first read, and its ``to_stream()`` is + this stream. + + Returns: + The input channel. + """ + return InputChannel(self, CompleteStreamFeed(self)) + async def async_iter_data( self, ) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py new file mode 100644 index 000000000..9161c979e --- /dev/null +++ b/src/orcapod/core/streams/record_batch_input.py @@ -0,0 +1,194 @@ +"""The input channel of Arrow record batches (ITL-1347). + +``InputChannel`` implements ``RecordBatchInput`` +(``orcapod.protocols.core_protocols.record_batch_channels``): a single-pass, +back-pressured reader of a stream's Arrow record batches. The stream is primary and owns +the description (keys, schemas, data context, pipeline hash); a channel refers to its +stream and restates nothing. + +A channel reads through a feed (``BatchFeed``), which says where its record batches come +from: a complete stream (``StreamBase.open_channel()``), or an output channel +(``OutputChannel.open_reader()`` in ``orcapod.core.record_batch_channels``). This module +imports no concrete stream, node or operator, so a stream can open a channel without an +import cycle. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator +from typing import TYPE_CHECKING, Any, Protocol + +from orcapod.channels import ChannelClosed + +if TYPE_CHECKING: + import pyarrow as pa + + from orcapod.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + ) + from orcapod.protocols.core_protocols.streams import StreamProtocol + +SOURCE_BATCH_ROWS = 65_536 +"""The most rows of one Arrow record batch a complete stream is read in. + +Developer decision, November 22, 2026 (ITL-1347, question 6): a source sends record +batches of at most 65,536 rows; an operator sends its result's own record batches. +""" + + +class BatchFeed(Protocol): + """Where an input channel's record batches come from.""" + + async def next(self) -> pa.RecordBatch | None: + """Return the next record batch, or ``None`` at the end.""" + ... + + def close(self) -> None: + """Stop reading: nothing waits for this reader any more.""" + ... + + async def to_stream(self, channel: RecordBatchInput) -> StreamProtocol: + """Return all of ``channel``'s input as a stream; ``channel`` is not read yet. + + Args: + channel: The input channel this feed serves. + """ + ... + + +class InputChannel: + """A single-pass, back-pressured reader of a stream's Arrow record batches. + + The Arrow-record-batch form of ``ReadableChannel``. The description of what it + delivers is its ``stream``, known before the first batch: the producing node, or + the stream it was opened from. A channel has no identity of its own and is read + once; to read again, go back to a stream (the one it was opened from, or the one + ``to_stream`` gives). + + Made by ``stream.open_channel()`` or by ``OutputChannel.open_reader()``, never + directly. + """ + + def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: + """Make an input channel; use ``open_channel`` or ``open_reader``. + + Args: + stream: The stream whose rows the channel delivers: its description. + feed: Where the record batches come from. + """ + self._stream = stream + self._feed = feed + self._received = 0 + self._ended = False + # Closed by its consumer before the producer completed. + self._closed = False + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows this channel delivers: the description.""" + return self._stream + + async def receive(self) -> pa.RecordBatch: + """Return the next Arrow record batch. + + A read that is cancelled while it waits closes the channel, as ``close`` does: + a consumer that stops reading never holds its producer. + + Raises: + ChannelClosed: At the end, and after ``close``. After a ``close`` that came + before the producer completed, the error says so, and iteration + (``async for``) raises it instead of ending: no consumer loop takes + part of an input for all of it. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._closed: + raise self._closed_early() + if self._ended: + raise ChannelClosed() + try: + batch = await self._feed.next() + except asyncio.CancelledError: + await self.close() + raise + if batch is None: + if self._closed: # woken by its own early close + raise self._closed_early() + self._ended = True + raise ChannelClosed() + self._received += 1 + return batch + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches, in arrival order.""" + return self + + async def __anext__(self) -> pa.RecordBatch: + """Return the next record batch; end the iteration at the producer's end. + + A channel closed before its producer completed does not end the iteration: + its ``ChannelClosed`` is raised, so a loop never takes part of an input for + all of it. + """ + try: + return await self.receive() + except ChannelClosed: + if self._closed: + raise # closed before its producer completed: not the end + raise StopAsyncIteration + + def _closed_early(self) -> ChannelClosed: + """The error of a read after a close that came before the producer completed.""" + return ChannelClosed( + f"The input channel of {_named(self._stream)} was closed before its " + + "producer completed; it has no complete input to give." + ) + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order. + + Raises: + ChannelClosed: If the channel was closed before its producer completed: + what was read is part of the input, never returned as all of it. + UpstreamFailedError: If the producer failed or was cancelled. + """ + return [batch async for batch in self] + + async def to_stream(self) -> StreamProtocol: + """Read to the end and return all of the channel's input, as a stream. + + It is how an operator that needs all of an input reads it, and it needs a + channel not read yet: a stream of part of an input is never made. A channel + opened on a complete stream gives that stream; a reader of an output channel + gives the record batches it delivered, in arrival order, with the identity of + ``stream``. + + Raises: + RuntimeError: If a record batch has already been received. + ChannelClosed: If the channel was closed before its producer completed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if self._received: + raise RuntimeError( + "to_stream() gives everything an input channel delivers, as a stream; " + + f"{self._received} record batch(es) of this one have been received " + + "already." + ) + if self._closed: + raise self._closed_early() + stream = await self._feed.to_stream(self) + self._ended = True + return stream + + async def close(self) -> None: + """Stop reading. The producer no longer waits for this reader.""" + if not self._ended: + self._closed = True + self._ended = True + self._feed.close() + + +def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any stream or node + """How an error names a stream: its label, or what it prints as.""" + label = getattr(stream, "label", None) + return repr(label) if label else repr(stream) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 010d29232..19ba70d8e 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -16,6 +16,9 @@ from orcapod.types import ColumnConfig, Schema if TYPE_CHECKING: + from orcapod.protocols.core_protocols.record_batch_channels import ( + RecordBatchInput, + ) import pandas as pd import polars as pl import pyarrow as pa @@ -183,6 +186,19 @@ def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """ ... + def open_channel(self) -> RecordBatchInput: + """Open an input channel on this stream, for async computation (ITL-1347). + + The channel delivers the stream's rows as Arrow record batches, read once and + in order; its description is this stream. Several channels may be opened on + one stream, each with its own position, and ``to_stream()`` of a channel not + read yet is this stream. + + Returns: + The input channel. + """ + ... + def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ Generates asynchronous iterator over (tag, data) pairs in the stream. diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 4c03cefd3..0642f5c3b 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2,7 +2,7 @@ A stream is primary and owns the description; a channel is a separate, single-pass carrier of the stream's rows as Arrow record batches. An input channel is opened from a -complete stream (``channel_from_stream``) or from an output channel +complete stream (``stream.open_channel()``) or from an output channel (``OutputChannel.open_reader``); an output channel, once closed, gives its rows back as an ordinary stream (``result()``), and so does an input channel that is read to its end (``to_stream()``). One test per rule of the design's table "The hard semantics". @@ -38,14 +38,14 @@ ) from orcapod.core.record_batch_channels import ( BATCH_BUFFER_SIZE, - SOURCE_BATCH_ROWS, - InputChannel, OutputChannel, _schema_mismatch, # pyright: ignore[reportPrivateUsage] # the check itself is tested - channel_from_stream, ) +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel +from orcapod.core.nodes.source_node import SourceJobNode, SourceNode from orcapod.core.streams import ArrowTableStream -from orcapod.errors import UpstreamFailedError +from orcapod.errors import UnboundSourceError, UpstreamFailedError +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.sources import ArrowTableSource T = TypeVar("T") @@ -97,7 +97,7 @@ def batches_of(stream: Any, rows: int = SOURCE_BATCH_ROWS) -> list[pa.RecordBatc """``stream``'s record batches, cut every ``rows`` rows.""" async def read() -> list[pa.RecordBatch]: - return await channel_from_stream(stream).collect() + return await stream.open_channel().collect() return pa.Table.from_batches(run(read)).to_batches(max_chunksize=rows) @@ -106,20 +106,39 @@ async def read() -> list[pa.RecordBatch]: def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> None: - """The record batches are the stream's rows; the description is the stream.""" + """The record batches are the stream's rows in the row-built form; the description + is the stream, and ``to_stream()`` is the stream itself (all of the input, nothing + rebuilt).""" stream = source() - channel = channel_from_stream(stream) + channel = stream.open_channel() assert isinstance(channel, InputChannel) assert isinstance(channel, ReadableChannel) as_protocol: RecordBatchInput = channel # what an operator reads (type-checked) assert as_protocol.stream is stream - delivered = run(channel.to_stream) - assert same(delivered.as_table(columns=ALL), R(stream)) - assert delivered.keys() == stream.keys() - assert delivered.output_schema() == stream.output_schema() - assert delivered.data_context_key == stream.data_context_key - assert delivered.pipeline_hash() == stream.pipeline_hash() + batches = run(stream.open_channel().collect) + assert same(pa.Table.from_batches(batches), R(stream)) + assert run(channel.to_stream) is stream + with pytest.raises(ChannelClosed): + _ = run(channel.receive) # read to its end by to_stream() + + +def test_a_source_node_opens_a_channel_on_its_rows() -> None: + """A source node is a stream too. A job's source node delivers its source's rows in + the row-built form, and ``to_stream()`` is the node itself. An unbound slot opens a + channel (opening reads nothing), and its first read raises.""" + stream = source() + node = SourceJobNode.from_stream(stream, name="events") + assert isinstance(node, StreamProtocol) + batches = run(node.open_channel().collect) + assert same(pa.Table.from_batches(batches), R(node)) + assert run(node.open_channel().to_stream) is node + + slot = SourceNode.from_stream(stream, name="events") + assert isinstance(slot, StreamProtocol) + channel = slot.open_channel() + with pytest.raises(UnboundSourceError): + _ = run(channel.receive) def test_opening_a_channel_computes_nothing() -> None: @@ -131,7 +150,7 @@ def test_opening_a_channel_computes_nothing() -> None: autospec=True, side_effect=ArrowTableSource.as_table, ) as read: - channel = channel_from_stream(stream) + channel = stream.open_channel() assert read.call_count == 0 _ = run(channel.receive) assert read.call_count == 1 @@ -142,7 +161,7 @@ def test_two_channels_on_one_stream_have_their_own_positions() -> None: stream = source() async def read() -> tuple[int, int, int]: - first, second = channel_from_stream(stream), channel_from_stream(stream) + first, second = stream.open_channel(), stream.open_channel() one = await first.receive() rest = await second.collect() return one.num_rows, sum(b.num_rows for b in rest), len(await first.collect()) @@ -160,7 +179,7 @@ def test_a_stream_is_read_in_record_batches_of_bounded_size() -> None: tag_only_columns=True, source_id="many", ) - sizes = [batch.num_rows for batch in run(channel_from_stream(stream).collect)] + sizes = [batch.num_rows for batch in run(stream.open_channel().collect)] assert sizes == [SOURCE_BATCH_ROWS, 10] @@ -168,7 +187,7 @@ def test_a_channel_is_read_once_and_the_stream_again() -> None: """A channel is single-pass; to read again, go back to a stream.""" async def read() -> tuple[int, int]: - channel = channel_from_stream(source()) + channel = source().open_channel() first = await channel.collect() with pytest.raises(ChannelClosed): _ = await channel.receive() @@ -1044,7 +1063,7 @@ async def write() -> int: def execute( op: StaticOutputOperatorPod, streams: Sequence[Any], - inputs: Callable[[], Awaitable[list[InputChannel]]], + inputs: Callable[[], Awaitable[list[RecordBatchInput]]], ) -> OutputChannel: """Run ``op`` over input channels; return its output channel.""" @@ -1074,7 +1093,7 @@ def test_an_operator_fails_its_output_when_its_input_failed( batches = batches_of(stream, 2) op = make_op() - async def inputs() -> list[InputChannel]: + async def inputs() -> list[RecordBatchInput]: feed = OutputChannel(stream) await feed.send(batches[0]) feed.fail(OSError("disk gone")) @@ -1134,8 +1153,8 @@ def test_an_operator_reads_its_input_to_the_end_and_closes_its_output() -> None: stream = source() op = SelectDataColumns(["subject", "trial", "note"]) - async def inputs() -> list[InputChannel]: - return [channel_from_stream(stream)] + async def inputs() -> list[RecordBatchInput]: + return [stream.open_channel()] output = execute(op, [stream], inputs) assert same(output.result().as_table(columns=ALL), R(op(stream))) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index c47c11a3c..0d7998f0f 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -33,11 +33,8 @@ StaticOutputOperatorPod, stream_from_batches, ) -from orcapod.core.record_batch_channels import ( - InputChannel, - OutputChannel, - channel_from_stream, -) +from orcapod.core.record_batch_channels import OutputChannel +from orcapod.protocols.core_protocols.record_batch_channels import RecordBatchInput from orcapod.channels import ChannelClosed from orcapod.core.streams import ArrowTableStream from orcapod.errors import UpstreamFailedError @@ -83,11 +80,11 @@ def _cut(table: pa.Table, sizes: tuple[int, ...] | None) -> list[pa.RecordBatch] async def _channel( stream: StreamProtocol, sizes: tuple[int, ...] | None -) -> InputChannel: +) -> RecordBatchInput: """An input channel delivering ``stream``'s rows in record batches of ``sizes``.""" - batches = await channel_from_stream(stream).collect() + batches = await stream.open_channel().collect() if sizes is None or not batches: - return channel_from_stream(stream) + return stream.open_channel() rows = pa.Table.from_batches(batches) feed = OutputChannel(stream) for batch in _cut(rows, sizes): @@ -263,7 +260,7 @@ def test_a_row_by_row_operator_sends_each_batch_as_it_arrives(case: Case) -> Non assert expected is not None async def go() -> list[pa.RecordBatch]: - rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + rows = pa.Table.from_batches(await source.open_channel().collect()) inputs = _cut(rows, (1,)) wanted = [ case.make_op()(stream_from_batches(source, [batch])).as_table().num_rows @@ -321,7 +318,7 @@ async def go() -> tuple[int, int]: output = OutputChannel(op(source)) results = output.open_reader() task = asyncio.ensure_future(op.async_execute_batches([reader], output)) - rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + rows = pa.Table.from_batches(await source.open_channel().collect()) one_row = _cut(rows, (1,)) await feed.send(one_row[0]) await feed.send(one_row[1]) @@ -384,30 +381,34 @@ def _outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @pytest.mark.parametrize("label", list(BARRIER_ORACLE_CASES)) def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None: - """The record-batch form is held to what a job's sync path gives an operator: the - upstream rebuilt from its rows (``_materialize_upstream``: ``null`` as - ``large_string``, the columns in row order), not the raw stream it came from. A - predicate that reads a ``null`` column's type or the column order follows that - form (documented behaviour, e5); in a job neither case reaches an operator: a - source refuses a ``null`` column, and a job refuses an expression that selects - columns by position.""" + """Two oracles, which coincide in a job. A channel opened on a complete stream gives + the operator that stream (``to_stream()`` is the stream itself), so the result is + the sync result over it. Record batches that travelled through an output channel + give the stream rebuilt from them in the row-built form, which is what a job's + sync path gives an operator (``_materialize_upstream``: ``null`` as + ``large_string``, the columns in row order). In a job every node's output stream + is already in that form, so both are the job's; on a raw stream they differ, and + a predicate that reads a ``null`` column's type or the column order follows the + form it is given (documented behaviour, e5). In a job neither case reaches an + operator: a source refuses a ``null`` column, and a job refuses an expression that + selects columns by position.""" make_stream, make_op = BARRIER_ORACLE_CASES[label] stream = make_stream() - oracle = _outcome( + job_sync = _outcome( lambda: make_op()( StaticOutputOperatorPod._materialize_upstream( # pyright: ignore[reportPrivateUsage] # the job's sync input list(stream.iter_data()), stream ) ) ) - assert _outcome(lambda: run_on_channels(make_op(), [stream], None)) == oracle + raw_sync = _outcome(lambda: make_op()(stream)) + assert raw_sync != job_sync # the case tells the two oracles apart + assert _outcome(lambda: run_on_channels(make_op(), [stream], None)) == raw_sync for layout in ("one_row_per_batch", "mixed_sizes"): assert ( _outcome(lambda: run_on_channels(make_op(), [stream], LAYOUTS[layout])) - == oracle + == job_sync ) - # The raw stream gives another outcome: the case tells the two oracles apart. - assert _outcome(lambda: make_op()(stream)) != oracle # --- Arrivals from another producer ------------------------------------------------------- @@ -519,7 +520,7 @@ def test_a_meta_column_does_not_travel() -> None: assert expected is not None async def go() -> tuple[list[str], StreamProtocol]: - batches = await channel_from_stream(raw).collect() + batches = await raw.open_channel().collect() output = OutputChannel(raw) for batch in batches: await output.send(batch) @@ -549,7 +550,7 @@ def test_an_input_closed_early_fails_a_streaming_operator( op = make_op() async def go() -> None: - rows = pa.Table.from_batches(await channel_from_stream(source).collect()) + rows = pa.Table.from_batches(await source.open_channel().collect()) first, second = _cut(rows, (1,))[:2] feed = OutputChannel(source, retain=False, buffer_size=4) reader = feed.open_reader() @@ -670,7 +671,7 @@ async def go() -> None: output = _FailingClose(op(source)) results = output.open_reader() with pytest.raises(OSError, match="flush failed"): - await op.async_execute_batches([channel_from_stream(source)], output) + await op.async_execute_batches([source.open_channel()], output) with pytest.raises(UpstreamFailedError): _ = await asyncio.wait_for(results.collect(), TIMEOUT) @@ -684,7 +685,7 @@ def test_every_input_is_closed_when_one_close_fails() -> None: op = operators.SemiJoin() async def go() -> None: - first, second = channel_from_stream(left), channel_from_stream(right) + first, second = left.open_channel(), right.open_channel() async def failing_close() -> None: raise OSError("cannot close") From 11cbc11fc7d90b46b811921d6945afb6defc3b38 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:07:17 -0800 Subject: [PATCH 2/8] refactor(channels): the record-batch protocols beside StreamProtocol in protocols/core_protocols/streams.py (ITL-1362) StreamProtocol.open_channel returns RecordBatchInput and RecordBatchInput.stream is a StreamProtocol: one module, no import cycle. The separate module is gone; core_protocols exports both protocols. Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 2 +- CLAUDE.md | 2 +- src/orcapod/core/nodes/source_node.py | 2 +- src/orcapod/core/operators/batch.py | 2 +- .../core/operators/static_output_pod.py | 2 +- src/orcapod/core/record_batch_channels.py | 4 +- src/orcapod/core/streams/base.py | 2 +- .../core/streams/record_batch_input.py | 6 +- .../protocols/core_protocols/__init__.py | 9 +- .../core_protocols/record_batch_channels.py | 86 ------------------- .../protocols/core_protocols/streams.py | 77 ++++++++++++++++- .../test_record_batch_channels.py | 2 +- .../operators/test_record_batch_execution.py | 2 +- 13 files changed, 95 insertions(+), 103 deletions(-) delete mode 100644 src/orcapod/protocols/core_protocols/record_batch_channels.py diff --git a/.zed/rules b/.zed/rules index 8dafa27eb..212d3f7f5 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1301,7 +1301,7 @@ data. The rules: - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): orcapod.core.record_batch_channels.InputChannel / OutputChannel carry a stream's rows as Arrow record batches; operators see them only through the protocols RecordBatchInput / - RecordBatchOutput of protocols/core_protocols/record_batch_channels.py, which imports no + RecordBatchOutput of protocols/core_protocols/streams.py (beside StreamProtocol), which imports no concrete core module (keep modules interacting through protocols: basedpyright counts local and TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel refers to its stream (stream.open_channel()), an output channel to the stream it diff --git a/CLAUDE.md b/CLAUDE.md index 65376a908..4b238ec75 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1348,7 +1348,7 @@ data. The rules: - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): `orcapod.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as Arrow record batches; operators see them only through the protocols `RecordBatchInput` / - `RecordBatchOutput` of `protocols/core_protocols/record_batch_channels.py`, which imports no + `RecordBatchOutput` of `protocols/core_protocols/streams.py (beside `StreamProtocol`)`, which imports no concrete core module (keep modules interacting through protocols: basedpyright counts local and `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input channel refers to its stream (`stream.open_channel()`), an output channel to the diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index ef3b5c94e..948c2a819 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -59,7 +59,7 @@ if TYPE_CHECKING: from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol - from orcapod.protocols.core_protocols.record_batch_channels import ( + from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 78af8e8d1..e17e28fd4 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -7,7 +7,7 @@ import pyarrow as pa from orcapod.core.operators.meta_columns import WithoutMetaWriter -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 6cdc6ab7e..f0782bf74 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -9,7 +9,7 @@ import pyarrow as pa -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 31914ccae..a3aedc080 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -1,7 +1,7 @@ """The output channel of Arrow record batches (ITL-1347). ``OutputChannel`` implements ``RecordBatchOutput`` -(``orcapod.protocols.core_protocols.record_batch_channels``): the producer side of a +(``orcapod.protocols.core_protocols.streams``): the producer side of a node's async output. Each consumer reads through its own ``InputChannel`` (``open_reader``, ``orcapod.core.streams.record_batch_input``), which is the fan-out. The stream is primary and owns the description (keys, schemas, data context, pipeline hash); a @@ -33,7 +33,7 @@ if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol - from orcapod.protocols.core_protocols.record_batch_channels import ( + from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, ) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index d0051dca7..ab5f2ecb0 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -35,7 +35,7 @@ StreamProtocol, TagProtocol, ) -from orcapod.protocols.core_protocols.record_batch_channels import RecordBatchInput +from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 9161c979e..4348361c8 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -1,7 +1,7 @@ """The input channel of Arrow record batches (ITL-1347). ``InputChannel`` implements ``RecordBatchInput`` -(``orcapod.protocols.core_protocols.record_batch_channels``): a single-pass, +(``orcapod.protocols.core_protocols.streams``): a single-pass, back-pressured reader of a stream's Arrow record batches. The stream is primary and owns the description (keys, schemas, data context, pipeline hash); a channel refers to its stream and restates nothing. @@ -24,10 +24,10 @@ if TYPE_CHECKING: import pyarrow as pa - from orcapod.protocols.core_protocols.record_batch_channels import ( + from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, + StreamProtocol, ) - from orcapod.protocols.core_protocols.streams import StreamProtocol SOURCE_BATCH_ROWS = 65_536 """The most rows of one Arrow record batch a complete stream is read in. diff --git a/src/orcapod/protocols/core_protocols/__init__.py b/src/orcapod/protocols/core_protocols/__init__.py index caf52a0a9..7ec5f81d9 100644 --- a/src/orcapod/protocols/core_protocols/__init__.py +++ b/src/orcapod/protocols/core_protocols/__init__.py @@ -8,7 +8,12 @@ from .data_function import DataFunctionProtocol from .pod import ArgumentGroup, PodProtocol from .sources import DynamicSourceProtocol, SourceProtocol -from .streams import StreamViewProtocol, StreamProtocol +from .streams import ( + RecordBatchInput, + RecordBatchOutput, + StreamProtocol, + StreamViewProtocol, +) from .side_effect_pod import SideEffectPodProtocol from .trackers import TrackerProtocol, TrackerManagerProtocol @@ -21,6 +26,8 @@ "SourceProtocol", "StreamViewProtocol", "StreamProtocol", + "RecordBatchInput", + "RecordBatchOutput", "PodProtocol", "ArgumentGroup", "PipelineElementProtocol", diff --git a/src/orcapod/protocols/core_protocols/record_batch_channels.py b/src/orcapod/protocols/core_protocols/record_batch_channels.py deleted file mode 100644 index 27f34aa69..000000000 --- a/src/orcapod/protocols/core_protocols/record_batch_channels.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Protocols of the channels of Arrow record batches (ITL-1347). - -``RecordBatchInput`` and ``RecordBatchOutput`` are what an operator's record-batch form -reads and writes. The stream is primary and owns the description (keys, schemas, data -context, pipeline hash); a channel refers to its stream and restates nothing. The -implementations are in ``orcapod.core.record_batch_channels``. -""" - -from __future__ import annotations - -from collections.abc import AsyncIterator -from typing import TYPE_CHECKING, Protocol - -if TYPE_CHECKING: - import pyarrow as pa - - from orcapod.protocols.core_protocols.streams import StreamProtocol - - -class RecordBatchInput(Protocol): - """A single-pass reader of a stream's Arrow record batches. - - The Arrow-record-batch form of ``ReadableChannel`` (``orcapod.channels``); ``InputChannel`` of - ``orcapod.core.record_batch_channels`` is the implementation. Its description is - its ``stream``, known before the first batch. - """ - - @property - def stream(self) -> StreamProtocol: - """The stream whose rows this channel delivers: the description.""" - ... - - async def receive(self) -> pa.RecordBatch: - """Return the next Arrow record batch. - - Raises: - ChannelClosed: At the end, and after ``close``. - UpstreamFailedError: If the producer failed or was cancelled. - """ - ... - - def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: - """Iterate over the remaining record batches, in arrival order.""" - ... - - async def collect(self) -> list[pa.RecordBatch]: - """Read to the end and return every remaining record batch, in arrival order.""" - ... - - async def to_stream(self) -> StreamProtocol: - """Read to the end and return what the channel delivered, as a stream. - - All of the input or nothing: it needs a channel not read yet. ``collect`` - drains the batches that remain; ``to_stream`` never makes a stream of part of - an input. - - Raises: - RuntimeError: If a record batch has already been received. - ChannelClosed: If the channel was closed before its producer completed. - UpstreamFailedError: If the producer failed or was cancelled. - """ - ... - - async def close(self) -> None: - """Stop reading. The producer no longer waits for this reader.""" - ... - - -class RecordBatchOutput(Protocol): - """The producer side of a stream's Arrow record batches. - - The Arrow-record-batch form of ``WritableChannel`` (``orcapod.channels``); ``OutputChannel`` of - ``orcapod.core.record_batch_channels`` is the implementation. - """ - - async def send(self, batch: pa.RecordBatch) -> None: - """Send one Arrow record batch of the stream's transport columns.""" - ... - - async def close(self) -> None: - """Complete the output.""" - ... - - def fail(self, error: BaseException) -> None: - """End the output with the producer's failure or cancellation.""" - ... diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 19ba70d8e..6bf032afe 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -16,9 +16,6 @@ from orcapod.types import ColumnConfig, Schema if TYPE_CHECKING: - from orcapod.protocols.core_protocols.record_batch_channels import ( - RecordBatchInput, - ) import pandas as pd import polars as pl import pyarrow as pa @@ -584,3 +581,77 @@ def batch( Self: New stream containing batched (tag, data) pairs. """ ... + + +# --------------------------------------------------------------------------- +# Channels of Arrow record batches (ITL-1347): the stream is the description +# --------------------------------------------------------------------------- + + +class RecordBatchInput(Protocol): + """A single-pass reader of a stream's Arrow record batches. + + The Arrow-record-batch form of ``ReadableChannel`` (``orcapod.channels``); ``InputChannel`` of + ``orcapod.core.streams.record_batch_input`` is the implementation. Its description is + its ``stream``, known before the first batch. + """ + + @property + def stream(self) -> StreamProtocol: + """The stream whose rows this channel delivers: the description.""" + ... + + async def receive(self) -> pa.RecordBatch: + """Return the next Arrow record batch. + + Raises: + ChannelClosed: At the end, and after ``close``. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + + def __aiter__(self) -> AsyncIterator[pa.RecordBatch]: + """Iterate over the remaining record batches, in arrival order.""" + ... + + async def collect(self) -> list[pa.RecordBatch]: + """Read to the end and return every remaining record batch, in arrival order.""" + ... + + async def to_stream(self) -> StreamProtocol: + """Read to the end and return what the channel delivered, as a stream. + + All of the input or nothing: it needs a channel not read yet. ``collect`` + drains the batches that remain; ``to_stream`` never makes a stream of part of + an input. + + Raises: + RuntimeError: If a record batch has already been received. + ChannelClosed: If the channel was closed before its producer completed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + ... + + async def close(self) -> None: + """Stop reading. The producer no longer waits for this reader.""" + ... + + +class RecordBatchOutput(Protocol): + """The producer side of a stream's Arrow record batches. + + The Arrow-record-batch form of ``WritableChannel`` (``orcapod.channels``); ``OutputChannel`` of + ``orcapod.core.record_batch_channels`` is the implementation. + """ + + async def send(self, batch: pa.RecordBatch) -> None: + """Send one Arrow record batch of the stream's transport columns.""" + ... + + async def close(self) -> None: + """Complete the output.""" + ... + + def fail(self, error: BaseException) -> None: + """End the output with the producer's failure or cancellation.""" + ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 0642f5c3b..97f325cf6 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -21,7 +21,7 @@ import pyarrow as pa import pytest -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 0d7998f0f..10cb854fa 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -34,7 +34,7 @@ stream_from_batches, ) from orcapod.core.record_batch_channels import OutputChannel -from orcapod.protocols.core_protocols.record_batch_channels import RecordBatchInput +from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.channels import ChannelClosed from orcapod.core.streams import ArrowTableStream from orcapod.errors import UpstreamFailedError From 19e9424d5438004b4c893d9ca4db0d914093ec98 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:07:25 -0800 Subject: [PATCH 3/8] docs: name the protocol module correctly in the record-batch channel rule (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4b238ec75..d17a7e6b6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1348,19 +1348,19 @@ data. The rules: - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): `orcapod.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as Arrow record batches; operators see them only through the protocols `RecordBatchInput` / - `RecordBatchOutput` of `protocols/core_protocols/streams.py (beside `StreamProtocol`)`, which imports no - concrete core module (keep modules interacting through protocols: basedpyright counts local - and `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input - channel refers to its stream (`stream.open_channel()`), an output channel to the - stream it produces, and `OutputChannel.result()` closes it into that stream. The conversions - are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, - `transport_schema`, and F, `_row_built_form`); never build a stream from record batches - elsewhere. An operator's record-batch form (`async_execute_batches`, renamed `async_execute` - when wired) applies its one `static_process` body: per record batch when the class declares - `ROW_BY_ROW = True` (each output row comes from one input row), otherwise as a barrier over - the whole input (`to_stream()`); `Batch` with a size has its own form, grouping rows by - arrival. A new operator whose output rows each come from one input row declares - `ROW_BY_ROW`; write no other per-operator batch code. + `RecordBatchOutput` of `protocols/core_protocols/streams.py` (beside `StreamProtocol`), + which imports no concrete core module (keep modules interacting through protocols: + basedpyright counts local and `TYPE_CHECKING` imports as import cycles). A channel owns no + description: an input channel refers to its stream (`stream.open_channel()`), an output + channel to the stream it produces, and `OutputChannel.result()` closes it into that stream. + The conversions are in one place, `core/operators/static_output_pod.py` + (`stream_from_batches`, `transport_schema`, and F, `_row_built_form`); never build a stream + from record batches elsewhere. An operator's record-batch form (`async_execute_batches`, + renamed `async_execute` when wired) applies its one `static_process` body: per record batch + when the class declares `ROW_BY_ROW = True` (each output row comes from one input row), + otherwise as a barrier over the whole input (`to_stream()`); `Batch` with a size has its own + form, grouping rows by arrival. A new operator whose output rows each come from one input + row declares `ROW_BY_ROW`; write no other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). From a85ffb7fef78613cd1651216b48fcb46b9c3b339 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:07:39 -0800 Subject: [PATCH 4/8] docs: the record-batch channel rule names each channel's module (ITL-1362) Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 17 +++++++++-------- CLAUDE.md | 31 ++++++++++++++++--------------- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/.zed/rules b/.zed/rules index 212d3f7f5..d70d98f4b 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1299,14 +1299,15 @@ data. The rules: context from those datagrams (data_context_key). Add new async operators to tests/test_core/operators/test_async_sync_equivalence.py. - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): - orcapod.core.record_batch_channels.InputChannel / OutputChannel carry a stream's rows as - Arrow record batches; operators see them only through the protocols RecordBatchInput / - RecordBatchOutput of protocols/core_protocols/streams.py (beside StreamProtocol), which imports no - concrete core module (keep modules interacting through protocols: basedpyright counts local - and TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel - refers to its stream (stream.open_channel()), an output channel to the stream it - produces, and OutputChannel.result() closes it into that stream. The conversions are in one - place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, + InputChannel (core/streams/record_batch_input.py) and OutputChannel + (core/record_batch_channels.py) carry a stream's rows as Arrow record batches; operators see + them only through the protocols RecordBatchInput / RecordBatchOutput of + protocols/core_protocols/streams.py (beside StreamProtocol), which imports no concrete core + module (keep modules interacting through protocols: basedpyright counts local and + TYPE_CHECKING imports as import cycles). A channel owns no description: an input channel + refers to its stream (stream.open_channel()), an output channel to the stream it produces, + and OutputChannel.result() closes it into that stream. The conversions are in one place, + core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, _row_built_form); never build a stream from record batches elsewhere. An operator's record-batch form (async_execute_batches, renamed async_execute when wired) applies its one static_process body: per record batch when the class declares ROW_BY_ROW = True (each output diff --git a/CLAUDE.md b/CLAUDE.md index d17a7e6b6..571f997e3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1346,21 +1346,22 @@ data. The rules: context from those datagrams (`data_context_key`). Add new async operators to `tests/test_core/operators/test_async_sync_equivalence.py`. - Record-batch channels (ITL-1347, ITL-1362; not wired into nodes or orchestrators yet): - `orcapod.core.record_batch_channels.InputChannel` / `OutputChannel` carry a stream's rows as - Arrow record batches; operators see them only through the protocols `RecordBatchInput` / - `RecordBatchOutput` of `protocols/core_protocols/streams.py` (beside `StreamProtocol`), - which imports no concrete core module (keep modules interacting through protocols: - basedpyright counts local and `TYPE_CHECKING` imports as import cycles). A channel owns no - description: an input channel refers to its stream (`stream.open_channel()`), an output - channel to the stream it produces, and `OutputChannel.result()` closes it into that stream. - The conversions are in one place, `core/operators/static_output_pod.py` - (`stream_from_batches`, `transport_schema`, and F, `_row_built_form`); never build a stream - from record batches elsewhere. An operator's record-batch form (`async_execute_batches`, - renamed `async_execute` when wired) applies its one `static_process` body: per record batch - when the class declares `ROW_BY_ROW = True` (each output row comes from one input row), - otherwise as a barrier over the whole input (`to_stream()`); `Batch` with a size has its own - form, grouping rows by arrival. A new operator whose output rows each come from one input - row declares `ROW_BY_ROW`; write no other per-operator batch code. + `InputChannel` (`core/streams/record_batch_input.py`) and `OutputChannel` + (`core/record_batch_channels.py`) carry a stream's rows as Arrow record batches; operators + see them only through the protocols `RecordBatchInput` / `RecordBatchOutput` of + `protocols/core_protocols/streams.py` (beside `StreamProtocol`), which imports no concrete + core module (keep modules interacting through protocols: basedpyright counts local and + `TYPE_CHECKING` imports as import cycles). A channel owns no description: an input channel + refers to its stream (`stream.open_channel()`), an output channel to the stream it produces, + and `OutputChannel.result()` closes it into that stream. The conversions are in one place, + `core/operators/static_output_pod.py` (`stream_from_batches`, `transport_schema`, and F, + `_row_built_form`); never build a stream from record batches elsewhere. An operator's + record-batch form (`async_execute_batches`, renamed `async_execute` when wired) applies its + one `static_process` body: per record batch when the class declares `ROW_BY_ROW = True` + (each output row comes from one input row), otherwise as a barrier over the whole input + (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new + operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no + other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). From 3424729b38fbff557036c164f3cc76e2c0ac8d8c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 05:56:55 -0800 Subject: [PATCH 5/8] fix(channels): channel_to_stream is the one conversion from an input channel to a stream; a channel is read once, a fixed snapshot (ITL-1362) Codex review of #488. The rule 'to_stream() of a channel on a complete stream is the stream itself' is withdrawn in its general form: - channel_to_stream(channel), beside stream_from_batches, reads the channel to its end (every read error raised before an operator runs) and rebuilds a fixed snapshot through stream_from_batches; only an unread channel whose stream _output_stream built (ROW_BUILT_OUTPUT, set there only) gives that stream - to_stream() is removed from RecordBatchInput, InputChannel and the feeds (a builder sits above core/streams/base.py, so a stream's feed cannot reach one without an import cycle); RecordBatchInput.unread is added - a channel is single pass: after its end it never reads its stream again - a source node's batches follow its bound source's keys (its rows' order) - the feed drops a batch once delivered Co-Authored-By: Claude Opus 5.5 --- .zed/rules | 18 +- CLAUDE.md | 18 +- src/orcapod/core/nodes/source_node.py | 10 +- .../core/operators/static_output_pod.py | 71 +++++- src/orcapod/core/record_batch_channels.py | 19 -- src/orcapod/core/streams/base.py | 54 ++--- .../core/streams/record_batch_input.py | 46 +--- .../protocols/core_protocols/streams.py | 19 +- .../test_record_batch_channels.py | 205 ++++++++++++++++-- .../operators/test_record_batch_execution.py | 90 ++++++-- 10 files changed, 381 insertions(+), 169 deletions(-) diff --git a/.zed/rules b/.zed/rules index d70d98f4b..bbd720618 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1308,13 +1308,17 @@ data. The rules: refers to its stream (stream.open_channel()), an output channel to the stream it produces, and OutputChannel.result() closes it into that stream. The conversions are in one place, core/operators/static_output_pod.py (stream_from_batches, transport_schema, and F, - _row_built_form); never build a stream from record batches elsewhere. An operator's - record-batch form (async_execute_batches, renamed async_execute when wired) applies its one - static_process body: per record batch when the class declares ROW_BY_ROW = True (each output - row comes from one input row), otherwise as a barrier over the whole input (to_stream()); - Batch with a size has its own form, grouping rows by arrival. A new operator whose output - rows each come from one input row declares ROW_BY_ROW; write no other per-operator batch - code. + _row_built_form); never build a stream from record batches elsewhere. + channel_to_stream(channel) is the one conversion from an input channel to a stream: it reads + the channel to its end (one pass, every read error raised before an operator runs) and + rebuilds a fixed snapshot through stream_from_batches; only an unread channel whose stream + _output_stream built (ROW_BUILT_OUTPUT, set there only) gives that stream as it is. An + operator's record-batch form (async_execute_batches, renamed async_execute when wired) + applies its one static_process body: per record batch when the class declares ROW_BY_ROW = + True (each output row comes from one input row), otherwise as a barrier over the whole input + (channel_to_stream); Batch with a size has its own form, grouping rows by arrival. A new + operator whose output rows each come from one input row declares ROW_BY_ROW; write no other + per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so struct and struct are one Python type (a workaround, TODO(ITL-841)). diff --git a/CLAUDE.md b/CLAUDE.md index 571f997e3..0c6d59591 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1355,13 +1355,17 @@ data. The rules: refers to its stream (`stream.open_channel()`), an output channel to the stream it produces, and `OutputChannel.result()` closes it into that stream. The conversions are in one place, `core/operators/static_output_pod.py` (`stream_from_batches`, `transport_schema`, and F, - `_row_built_form`); never build a stream from record batches elsewhere. An operator's - record-batch form (`async_execute_batches`, renamed `async_execute` when wired) applies its - one `static_process` body: per record batch when the class declares `ROW_BY_ROW = True` - (each output row comes from one input row), otherwise as a barrier over the whole input - (`to_stream()`); `Batch` with a size has its own form, grouping rows by arrival. A new - operator whose output rows each come from one input row declares `ROW_BY_ROW`; write no - other per-operator batch code. + `_row_built_form`); never build a stream from record batches elsewhere. + `channel_to_stream(channel)` is the one conversion from an input channel to a stream: it + reads the channel to its end (one pass, every read error raised before an operator runs) and + rebuilds a fixed snapshot through `stream_from_batches`; only an unread channel whose stream + `_output_stream` built (`ROW_BUILT_OUTPUT`, set there only) gives that stream as it is. An + operator's record-batch form (`async_execute_batches`, renamed `async_execute` when wired) + applies its one `static_process` body: per record batch when the class declares `ROW_BY_ROW + = True` (each output row comes from one input row), otherwise as a barrier over the whole + input (`channel_to_stream`); `Batch` with a size has its own form, grouping rows by arrival. + A new operator whose output rows each come from one input row declares `ROW_BY_ROW`; write + no other per-operator batch code. - The type converter keys synthesized struct classes by the large-normalized struct, so `struct` and `struct` are one Python type (a workaround, `TODO(ITL-841)`). diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 948c2a819..923d3f828 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1172,13 +1172,17 @@ def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). As ``StreamBase.open_channel()``: the rows as Arrow record batches in the - row-built form, read on the first read; the description is this node, and - ``to_stream()`` is this node. + row-built form, read once on the first read; the description is this node. + The rows are those of ``execute()``, so their columns follow the bound + source's keys (its tag order), which may differ from this node's keys (the + slot's order). An unbound node's first read raises what reading it raises. Returns: The input channel. """ - return InputChannel(self, CompleteStreamFeed(self)) + bound = self._bound_stream() + keys = bound.keys() if bound is not None else None + return InputChannel(self, CompleteStreamFeed(self, keys)) async def async_iter_data(self): """Asynchronous iterator over (tag, data) pairs. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f0782bf74..c89109680 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -547,14 +547,19 @@ def _output_stream( The output stream, with ``node``'s identity. """ if table.num_rows == 0: - return StaticOutputOperatorPod._materialize_upstream([], node) - tag_keys, data_keys = keys - return StaticOutputOperatorPod._as_upstream_stream( - StaticOutputOperatorPod._row_built_form(table, keys), - tag_keys, - data_tag_names(tag_keys, data_keys), - node, - ) + stream = StaticOutputOperatorPod._materialize_upstream([], node) + else: + tag_keys, data_keys = keys + stream = StaticOutputOperatorPod._as_upstream_stream( + StaticOutputOperatorPod._row_built_form(table, keys), + tag_keys, + data_tag_names(tag_keys, data_keys), + node, + ) + # The one place a stream is marked as a complete, immutable output in the + # row-built form (ITL-1347): ``channel_to_stream`` may give it as it is. + setattr(stream, ROW_BUILT_OUTPUT, True) + return stream @staticmethod def _flag_source_info_nullability(table: pa.Table) -> pa.Table: @@ -900,7 +905,7 @@ async def async_execute_batches( A row-by-row operator (``ROW_BY_ROW``) is applied to each record batch as it arrives and sends that batch's result at once. Every other operator reads - all of its inputs first (``InputChannel.to_stream``) and then runs exactly + all of its inputs first (``channel_to_stream``) and then runs exactly the sync call, so an input with no rows gives the typed zero-row result of the sync path, with no row to send. @@ -1012,7 +1017,7 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol UpstreamFailedError: If an input's producer failed; the other inputs are no longer read. """ - tasks = [asyncio.ensure_future(channel.to_stream()) for channel in inputs] + tasks = [asyncio.ensure_future(channel_to_stream(channel)) for channel in inputs] try: return list(await asyncio.gather(*tasks)) except BaseException: @@ -1065,6 +1070,50 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: return row_built_provenance(zero_rows.select(names)).schema +ROW_BUILT_OUTPUT = "_orcapod_row_built_output" +"""The attribute that marks a stream ``_output_stream`` built (ITL-1347). + +Set in that one place, never inferred from a class: such a stream is a complete, +immutable output already in the row-built form, so a consumer of its record batches +would rebuild exactly it, and ``channel_to_stream`` may give it without reading. +""" + + +async def channel_to_stream(channel: RecordBatchInput) -> StreamProtocol: + """Return what an input channel delivers, as a stream: the one such conversion. + + It reads the channel to its end (one pass; every error of the read, such as an + unbound source's or a failed producer's, is raised here, before any operator runs) + and builds a fixed snapshot of what was delivered through the one settlement path + (``stream_from_batches``). The only shortcut: a channel not read yet whose stream + ``_output_stream`` built (``ROW_BUILT_OUTPUT``) gives that stream, which is exactly + what its batches would rebuild; the channel is then closed. + + Args: + channel: The input channel, not read yet. + + Returns: + A complete, re-readable stream of the channel's input. + + Raises: + RuntimeError: If the channel has already been read (a batch received, or its + end reached): a stream of part of an input is never made, and a channel + is never read again. + ChannelClosed: If the channel was closed before its producer completed. + UpstreamFailedError: If the producer failed or was cancelled. + """ + if not channel.unread: + raise RuntimeError( + "channel_to_stream() gives everything an input channel delivers, as a " + + "stream; this channel has been read already." + ) + stream = channel.stream + if getattr(stream, ROW_BUILT_OUTPUT, False): + await channel.close() + return stream + return stream_from_batches(stream, await channel.collect()) + + def stream_from_batches( stream: StreamProtocol, batches: Sequence[pa.RecordBatch] ) -> StreamProtocol: @@ -1072,7 +1121,7 @@ def stream_from_batches( The one place a stream is made from Arrow record batches: what an output channel gives once closed (``OutputChannel.result``), what an input channel delivered - (``InputChannel.to_stream``), and the record batches a row-by-row operator is + (``channel_to_stream``), and the record batches a row-by-row operator is applied to. The batches are put under one another in the order given, and the table is handed on as a node hands its rows to its successors (``_output_stream``): in the row-built form, each system-tag and source-info field diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index a3aedc080..3dc1b5ad2 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -33,9 +33,6 @@ if TYPE_CHECKING: from orcapod.protocols.core_protocols import StreamProtocol - from orcapod.protocols.core_protocols.streams import ( - RecordBatchInput, - ) BATCH_BUFFER_SIZE = 8 """How many Arrow record batches an input channel queues before its producer waits.""" @@ -84,22 +81,6 @@ async def next(self) -> pa.RecordBatch | None: await output._changed.wait() # pyright: ignore[reportPrivateUsage] return None - async def to_stream(self, channel: RecordBatchInput) -> StreamProtocol: - """Read ``channel`` to its end and return what it delivered, as a stream. - - The record batches in arrival order, with the identity of ``channel.stream`` - (``stream_from_batches``, which settles the provenance fields on the complete - table). - - Args: - channel: The input channel this feed serves, not read yet. - - Raises: - ChannelClosed: If the channel is closed before its producer completed. - UpstreamFailedError: If the output failed. - """ - return stream_from_batches(channel.stream, await channel.collect()) - def close(self) -> None: """Stop reading and unregister from the output. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index ab5f2ecb0..bb5d169cc 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -2,6 +2,7 @@ import logging from abc import abstractmethod +from collections import deque from collections.abc import ( AsyncIterator, Callable, @@ -339,21 +340,29 @@ class CompleteStreamFeed: """The record batches of a complete stream, read at one reader's own position. The feed of a channel opened on a stream (``StreamBase.open_channel()``). Nothing - is read until the first ``next``; then the stream's table is read once, in the - row-built form (``row_built_columns``), and cut into record batches of at most - ``SOURCE_BATCH_ROWS`` rows. The stream is complete, so nothing is queued and no - producer waits on a reader. + is read until the first ``next``; then the stream's table is read once (a fixed + snapshot: a stream that changes later is not read again), in the row-built form + (``row_built_columns``), and cut into record batches of at most + ``SOURCE_BATCH_ROWS`` rows. A batch is dropped by the feed once delivered. The + stream is complete, so nothing is queued and no producer waits on a reader. """ - def __init__(self, stream: StreamProtocol) -> None: + def __init__( + self, + stream: StreamProtocol, + keys: tuple[Sequence[str], Sequence[str]] | None = None, + ) -> None: """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. Args: stream: The complete stream to read. + keys: The tag and data keys of the rows read, when they differ from + ``stream.keys()`` (a source node gives its bound source's rows); + default ``stream.keys()``. """ self._stream = stream - self._batches: list[pa.RecordBatch] | None = None - self._position = 0 + self._keys = keys + self._batches: deque[pa.RecordBatch] | None = None async def next(self) -> pa.RecordBatch | None: """Return the stream's next record batch, or ``None`` at the end. @@ -362,35 +371,20 @@ async def next(self) -> pa.RecordBatch | None: batches with no rows are skipped. """ if self._batches is None: + keys = self._keys if self._keys is not None else self._stream.keys() table = row_built_columns( - self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), - self._stream.keys(), + self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), keys ) - self._batches = [ + self._batches = deque( batch for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) if batch.num_rows - ] - if self._position >= len(self._batches): - return None - self._position += 1 - return self._batches[self._position - 1] + ) + return self._batches.popleft() if self._batches else None def close(self) -> None: """Stop reading: the batches not read are dropped.""" - self._batches = [] - self._position = 0 - - async def to_stream(self, channel: RecordBatchInput) -> StreamProtocol: - """Return the stream itself: all of the input, read by nobody yet. - - It is exactly what the sync path gives an operator over that stream, identity - and rows; nothing is read or rebuilt. - - Args: - channel: The input channel this feed serves. - """ - return self._stream + self._batches = deque() def typed_arrow_schemas( @@ -1213,8 +1207,8 @@ def open_channel(self) -> RecordBatchInput: ``SOURCE_BATCH_ROWS`` rows, in the row-built form, read once and in order; its description is this stream (``channel.stream``). Several channels may be opened on one stream, each with its own position, and the stream stays as it - is. Nothing is read until the channel is first read, and its ``to_stream()`` is - this stream. + is. Nothing is read until the channel is first read; then the stream is read + once, a fixed snapshot. Returns: The input channel. diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 4348361c8..0fcdb7efc 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -24,10 +24,7 @@ if TYPE_CHECKING: import pyarrow as pa - from orcapod.protocols.core_protocols.streams import ( - RecordBatchInput, - StreamProtocol, - ) + from orcapod.protocols.core_protocols.streams import StreamProtocol SOURCE_BATCH_ROWS = 65_536 """The most rows of one Arrow record batch a complete stream is read in. @@ -48,14 +45,6 @@ def close(self) -> None: """Stop reading: nothing waits for this reader any more.""" ... - async def to_stream(self, channel: RecordBatchInput) -> StreamProtocol: - """Return all of ``channel``'s input as a stream; ``channel`` is not read yet. - - Args: - channel: The input channel this feed serves. - """ - ... - class InputChannel: """A single-pass, back-pressured reader of a stream's Arrow record batches. @@ -64,7 +53,7 @@ class InputChannel: delivers is its ``stream``, known before the first batch: the producing node, or the stream it was opened from. A channel has no identity of its own and is read once; to read again, go back to a stream (the one it was opened from, or the one - ``to_stream`` gives). + ``channel_to_stream`` makes of what it delivered). Made by ``stream.open_channel()`` or by ``OutputChannel.open_reader()``, never directly. @@ -89,6 +78,11 @@ def stream(self) -> StreamProtocol: """The stream whose rows this channel delivers: the description.""" return self._stream + @property + def unread(self) -> bool: + """Whether nothing has been read from the channel: no batch, no end, no close.""" + return not self._received and not self._ended + async def receive(self) -> pa.RecordBatch: """Return the next Arrow record batch. @@ -154,32 +148,6 @@ async def collect(self) -> list[pa.RecordBatch]: """ return [batch async for batch in self] - async def to_stream(self) -> StreamProtocol: - """Read to the end and return all of the channel's input, as a stream. - - It is how an operator that needs all of an input reads it, and it needs a - channel not read yet: a stream of part of an input is never made. A channel - opened on a complete stream gives that stream; a reader of an output channel - gives the record batches it delivered, in arrival order, with the identity of - ``stream``. - - Raises: - RuntimeError: If a record batch has already been received. - ChannelClosed: If the channel was closed before its producer completed. - UpstreamFailedError: If the producer failed or was cancelled. - """ - if self._received: - raise RuntimeError( - "to_stream() gives everything an input channel delivers, as a stream; " - + f"{self._received} record batch(es) of this one have been received " - + "already." - ) - if self._closed: - raise self._closed_early() - stream = await self._feed.to_stream(self) - self._ended = True - return stream - async def close(self) -> None: """Stop reading. The producer no longer waits for this reader.""" if not self._ended: diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 6bf032afe..d70f95115 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -188,8 +188,8 @@ def open_channel(self) -> RecordBatchInput: The channel delivers the stream's rows as Arrow record batches, read once and in order; its description is this stream. Several channels may be opened on - one stream, each with its own position, and ``to_stream()`` of a channel not - read yet is this stream. + one stream, each with its own position (``channel_to_stream`` makes a stream of + what a channel delivers). Returns: The input channel. @@ -618,18 +618,9 @@ async def collect(self) -> list[pa.RecordBatch]: """Read to the end and return every remaining record batch, in arrival order.""" ... - async def to_stream(self) -> StreamProtocol: - """Read to the end and return what the channel delivered, as a stream. - - All of the input or nothing: it needs a channel not read yet. ``collect`` - drains the batches that remain; ``to_stream`` never makes a stream of part of - an input. - - Raises: - RuntimeError: If a record batch has already been received. - ChannelClosed: If the channel was closed before its producer completed. - UpstreamFailedError: If the producer failed or was cancelled. - """ + @property + def unread(self) -> bool: + """Whether nothing has been read from the channel: no batch, no end, no close.""" ... async def close(self) -> None: diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 97f325cf6..37e149be0 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -5,7 +5,7 @@ complete stream (``stream.open_channel()``) or from an output channel (``OutputChannel.open_reader``); an output channel, once closed, gives its rows back as an ordinary stream (``result()``), and so does an input channel that is read to its end -(``to_stream()``). One test per rule of the design's table "The hard semantics". +(``channel_to_stream``). One test per rule of the design's table "The hard semantics". The oracle of every table is ``R``: the table today's code builds from a stream's rows (``StaticOutputOperatorPod._rows_to_table``). @@ -14,6 +14,8 @@ from __future__ import annotations import asyncio +import gc +import weakref from collections.abc import Awaitable, Callable, Sequence from typing import Any, TypeVar from unittest import mock @@ -30,9 +32,10 @@ ReadableChannel, WritableChannel, ) -from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns +from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns, SemiJoin from orcapod.core.operators.static_output_pod import ( StaticOutputOperatorPod, + channel_to_stream, stream_from_batches, transport_schema, ) @@ -46,7 +49,14 @@ from orcapod.core.streams import ArrowTableStream from orcapod.errors import UnboundSourceError, UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.core.sources import PollingSource +from orcapod.core.sources.source_proxy import SourceProxy +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import SyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob from orcapod.sources import ArrowTableSource +from orcapod.types import Schema +from tests.test_channels.test_polling_source import FakeDynamicSource, _batch T = TypeVar("T") ALL = {"system_tags": True, "source": True} @@ -107,8 +117,8 @@ async def read() -> list[pa.RecordBatch]: def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> None: """The record batches are the stream's rows in the row-built form; the description - is the stream, and ``to_stream()`` is the stream itself (all of the input, nothing - rebuilt).""" + is the stream, and ``channel_to_stream`` rebuilds what the channel delivered, with + the stream's identity.""" stream = source() channel = stream.open_channel() @@ -118,21 +128,26 @@ def test_a_channel_opened_on_a_stream_delivers_its_rows_and_refers_to_it() -> No assert as_protocol.stream is stream batches = run(stream.open_channel().collect) assert same(pa.Table.from_batches(batches), R(stream)) - assert run(channel.to_stream) is stream + delivered = run(lambda: channel_to_stream(channel)) + assert same(delivered.as_table(columns=ALL), R(stream)) + assert delivered.keys() == stream.keys() + assert delivered.data_context_key == stream.data_context_key + assert delivered.pipeline_hash() == stream.pipeline_hash() with pytest.raises(ChannelClosed): - _ = run(channel.receive) # read to its end by to_stream() + _ = run(channel.receive) # read to its end def test_a_source_node_opens_a_channel_on_its_rows() -> None: """A source node is a stream too. A job's source node delivers its source's rows in - the row-built form, and ``to_stream()`` is the node itself. An unbound slot opens a + the row-built form, which ``channel_to_stream`` rebuilds. An unbound slot opens a channel (opening reads nothing), and its first read raises.""" stream = source() node = SourceJobNode.from_stream(stream, name="events") assert isinstance(node, StreamProtocol) batches = run(node.open_channel().collect) assert same(pa.Table.from_batches(batches), R(node)) - assert run(node.open_channel().to_stream) is node + rebuilt = run(lambda: channel_to_stream(node.open_channel())) + assert same(rebuilt.as_table(columns=ALL), R(node)) slot = SourceNode.from_stream(stream, name="events") assert isinstance(slot, StreamProtocol) @@ -141,6 +156,145 @@ def test_a_source_node_opens_a_channel_on_its_rows() -> None: _ = run(channel.receive) +def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: + """A source whose physical columns are x, j, k, y with tags declared k, j: the + node's batches have the column order of its own rows (``execute()``: k, j, ...), + not the slot's schema order.""" + stream = ArrowTableSource( + pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ), + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="ordered", + ) + node = SourceJobNode.from_stream(stream, name="ordered") + assert node.keys()[0] != stream.keys()[0] # the slot's order is another + rows = node.execute() + expected = StaticOutputOperatorPod._rows_to_table(rows)[0] + batches = run(node.open_channel().collect) + assert pa.Table.from_batches(batches).schema.names == expected.schema.names + assert same(pa.Table.from_batches(batches), expected) + + +def test_a_delivered_batch_is_not_kept_by_the_feed() -> None: + """Once delivered, a batch is not held by the channel: a consumer that drops it + frees it, also while the channel is still open.""" + n = SOURCE_BATCH_ROWS + 3 + stream = ArrowTableSource( + pa.table( + {"k": pa.array(range(n), pa.int64()), "v": pa.array(range(n), pa.int64())} + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="large", + ) + + async def read() -> bool: + channel = stream.open_channel() + first = await channel.receive() + reference = weakref.ref(first) + del first + rest = await channel.collect() + assert sum(batch.num_rows for batch in rest) == 3 + gc.collect() + return reference() is None + + assert run(read) + + +def test_an_unbound_input_fails_a_barrier_before_it_runs() -> None: + """``SemiJoin`` with no shared tag never reads its right input on the sync path, + but ``channel_to_stream`` reads every input first: an unbound right input (a slot, + or a ``SourceProxy``) raises what reading it raises, before the operator runs.""" + left = source() + other = ArrowTableSource( + pa.table({"other": pa.array([1], pa.int64()), "v": pa.array([0.5])}), + tag_columns=["other"], + tag_only_columns=True, + source_id="other", + ) + slot = SourceNode.from_stream(other, name="other") + proxy = SourceProxy( + source_id="other", + expected_class_name="ArrowTableSource", + tag_schema=Schema({"other": int}), + data_schema=Schema({"v": float}), + content_hash_str=other.content_hash().to_string(), + pipeline_hash_str=other.pipeline_hash().to_string(), + ) + for right, raised in ((slot, UnboundSourceError), (proxy, NotImplementedError)): + op = SemiJoin() + + async def go(right: Any = right) -> None: + output = OutputChannel(op(left, right)) + await op.async_execute_batches( + [left.open_channel(), right.open_channel()], output + ) + + with pytest.raises(raised): + run(go) + + +def test_an_exhausted_channel_never_yields_rows_later() -> None: + """A job node's channel read to its end before the node's run delivered nothing; + after the run, the same channel neither gives the run's rows nor reads again.""" + job = PipelineJob(name="exhausted", database=InMemoryArrowDatabase()) + with job: + _ = SelectDataColumns(["subject", "trial", "note"])(source(), label="selected") + node = job.nodes["selected"] + + async def before_run() -> Any: + channel = node.open_channel() + assert await channel.collect() == [] + return channel + + channel = run(before_run) + _ = job.run(orchestrator=SyncPipelineOrchestrator()) + assert node.as_table().num_rows == 7 + + async def after_run() -> None: + assert await channel.collect() == [] # single pass: nothing more + with pytest.raises(RuntimeError, match="read already"): + _ = await channel_to_stream(channel) + + run(after_run) + + +def test_a_polling_source_is_read_once_through_a_channel() -> None: + """A fresh ``PollingSource``: opening a channel fetches nothing; reading it fetches + once and the stream ``channel_to_stream`` gives is a fixed snapshot, read again + with no further fetch, also through ``collect``.""" + fake = FakeDynamicSource(batches=[_batch(i, 10 * i) for i in range(1, 6)]) + polling = PollingSource( + fake, tag_columns="id", record_id_columns="id", source_id="polled" + ) + + async def read() -> None: + channel = polling.open_channel() + assert len(fake.fetch_cursors) == 0 # opening reads nothing + snapshot = await channel_to_stream(channel) + fetched = len(fake.fetch_cursors) + assert fetched > 0 + rows = snapshot.as_table().num_rows + assert snapshot.as_table().num_rows == rows # a fixed snapshot + assert len(fake.fetch_cursors) == fetched # read again: no fetch + second = polling.open_channel() + assert len(fake.fetch_cursors) == fetched + batches = await second.collect() + read_once = len(fake.fetch_cursors) + assert await second.collect() == [] # one pass + assert len(fake.fetch_cursors) == read_once # never read again + assert batches + + run(read) + + def test_opening_a_channel_computes_nothing() -> None: """The stream's table is read at the first ``receive``, not when the channel opens.""" stream = source() @@ -196,8 +350,9 @@ async def read() -> tuple[int, int]: assert run(read) == (1, 0) -def test_to_stream_is_everything_or_nothing() -> None: - """``to_stream()`` on a channel already read is refused: never part of an input.""" +def test_channel_to_stream_is_everything_or_nothing() -> None: + """``channel_to_stream`` on a channel already read is refused: never part of an + input, and a channel is never read again.""" batches = batches_of(source(), 2) @@ -208,8 +363,8 @@ async def read() -> None: await output.close() channel = output.open_reader() _ = await channel.receive() - with pytest.raises(RuntimeError, match="1 record batch"): - _ = await channel.to_stream() + with pytest.raises(RuntimeError, match="read already"): + _ = await channel_to_stream(channel) run(read) @@ -249,7 +404,7 @@ async def write() -> OutputChannel: def test_the_identity_of_a_result_with_and_without_a_producer() -> None: - """``result()`` and ``to_stream()`` take the describing stream's identity: its + """``result()`` and ``channel_to_stream`` take the describing stream's identity: its producer and upstreams when it has a producer, its pipeline hash when it has none.""" root = source() produced = SelectDataColumns(["subject", "trial", "amplitude"])(root) @@ -259,7 +414,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: for batch in batches: await output.send(batch) await output.close() - return output.result(), await output.open_reader().to_stream() + return output.result(), await channel_to_stream(output.open_reader()) for stream in (root, produced): batches = batches_of(stream, 3) @@ -272,7 +427,7 @@ async def both(stream: Any, batches: list[pa.RecordBatch]) -> tuple[Any, Any]: def test_a_close_with_no_batch_is_the_typed_zero_row_stream() -> None: - """Zero rows: ``result()`` and ``to_stream()`` are typed by the description, never + """Zero rows: ``result()`` and ``channel_to_stream`` are typed by the description, never by rows, with the columns of a run with rows.""" stream = SelectDataColumns(["subject", "trial", "amplitude", "trace"])(source()) with_rows = R(stream) @@ -282,7 +437,7 @@ async def empty() -> tuple[Any, Any]: reader = output.open_reader() await output.close() await output.close() # a second close does nothing - return output.result(), await reader.to_stream() + return output.result(), await channel_to_stream(reader) for made in run(empty): table = made.as_table(columns=ALL) @@ -524,17 +679,21 @@ async def write() -> tuple[type[object], list[int]]: assert rows == [1] -def test_to_stream_of_a_channel_closed_before_its_end_raises() -> None: - """A reader closed while ``to_stream()`` (or ``collect()``) reads never makes part +def test_channel_to_stream_of_a_channel_closed_before_its_end_raises() -> None: + """A reader closed while ``channel_to_stream`` (or ``collect()``) reads never makes part of an input into a stream.""" stream = source(2) first, second = batches_of(stream, 1) async def write() -> None: - for read in ("to_stream", "collect"): + for read in ("channel_to_stream", "collect"): output = OutputChannel(stream, retain=False, buffer_size=4) reader = output.open_reader() - reading = asyncio.ensure_future(getattr(reader, read)()) + reading = asyncio.ensure_future( + channel_to_stream(reader) + if read == "channel_to_stream" + else reader.collect() + ) await output.send(first) await asyncio.sleep(0) await reader.close() @@ -1017,7 +1176,7 @@ async def write() -> list[BaseException]: await output.send(batches[0]) _ = await waiting.receive() blocked = asyncio.ensure_future(waiting.receive()) - whole = asyncio.ensure_future(barrier.to_stream()) + whole = asyncio.ensure_future(channel_to_stream(barrier)) await asyncio.sleep(0) output.fail(boom) output.fail(RuntimeError("a second failure changes nothing")) @@ -1052,7 +1211,7 @@ async def write() -> int: await output.send(batch) await output.close() output.fail(OSError("too late")) - return (await output.open_reader().to_stream()).as_table().num_rows + return (await channel_to_stream(output.open_reader())).as_table().num_rows assert run(write) == 7 @@ -1161,7 +1320,7 @@ async def inputs() -> list[RecordBatchInput]: def test_stream_from_batches_is_the_one_conversion() -> None: - """``result()`` and ``to_stream()`` are ``stream_from_batches``: its table equals the + """``result()`` and ``channel_to_stream`` are ``stream_from_batches``: its table equals the rows' table for every way the batches are cut, and no batch gives zero rows.""" stream = source() for rows in (1, 2, 5, 7): diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 10cb854fa..8c1c37e75 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -4,7 +4,7 @@ (``async_execute_batches``) reads input channels opened from streams and writes an output channel, which closes into a stream. An operator whose output rows each come from one input row is applied to every record batch as it arrives; every other -operator reads all of its inputs first (``InputChannel.to_stream``) and then runs the +operator reads all of its inputs first (``channel_to_stream``) and then runs the sync call; ``Batch`` batches consecutive arrivals. For every case of the async/sync matrix (``test_async_sync_equivalence.CASES``) the @@ -27,6 +27,7 @@ import pyarrow as pa import pytest +import orcapod.contexts as contexts import orcapod.core.operators as operators from orcapod.core.operators import AddTags, Batch, PolarsFilter, SelectDataColumns from orcapod.core.operators.static_output_pod import ( @@ -37,6 +38,11 @@ from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.channels import ChannelClosed from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline import SyncPipelineOrchestrator +from orcapod.pipeline.job import PipelineJob +from orcapod.system_constants import constants +from tests.test_core.operators.test_rejoin import other_context # noqa: F401 # the fixture from orcapod.errors import UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol from tests.test_core.operators.test_async_sync_equivalence import ( @@ -381,17 +387,14 @@ def _outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: @pytest.mark.parametrize("label", list(BARRIER_ORACLE_CASES)) def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None: - """Two oracles, which coincide in a job. A channel opened on a complete stream gives - the operator that stream (``to_stream()`` is the stream itself), so the result is - the sync result over it. Record batches that travelled through an output channel - give the stream rebuilt from them in the row-built form, which is what a job's - sync path gives an operator (``_materialize_upstream``: ``null`` as - ``large_string``, the columns in row order). In a job every node's output stream - is already in that form, so both are the job's; on a raw stream they differ, and - a predicate that reads a ``null`` column's type or the column order follows the - form it is given (documented behaviour, e5). In a job neither case reaches an - operator: a source refuses a ``null`` column, and a job refuses an expression that - selects columns by position.""" + """The record-batch form is held to what a job's sync path gives an operator: the + upstream rebuilt from its rows (``_materialize_upstream``: ``null`` as + ``large_string``, the columns in row order), not the raw stream it came from, in + every layout: ``channel_to_stream`` rebuilds what the channel delivered. A + predicate that reads a ``null`` column's type or the column order follows that + form (documented behaviour, e5); in a job neither case reaches an operator: a + source refuses a ``null`` column, and a job refuses an expression that selects + columns by position.""" make_stream, make_op = BARRIER_ORACLE_CASES[label] stream = make_stream() job_sync = _outcome( @@ -401,10 +404,9 @@ def test_a_barrier_operator_sees_its_input_as_a_job_gives_it(label: str) -> None ) ) ) - raw_sync = _outcome(lambda: make_op()(stream)) - assert raw_sync != job_sync # the case tells the two oracles apart - assert _outcome(lambda: run_on_channels(make_op(), [stream], None)) == raw_sync - for layout in ("one_row_per_batch", "mixed_sizes"): + # The raw stream gives another outcome: the case tells the two oracles apart. + assert _outcome(lambda: make_op()(stream)) != job_sync + for layout in LAYOUTS: assert ( _outcome(lambda: run_on_channels(make_op(), [stream], LAYOUTS[layout])) == job_sync @@ -730,3 +732,59 @@ def test_drop_tag_columns_over_three_tags_sends_its_result() -> None: assert expected is not None result = run_on_channels(operators.DropTagColumns(["a"]), [stream], None) assert_same_table(result.as_table(columns=ALL), expected) + + +# --- A barrier over a job's own nodes ------------------------------------------------------ + + +def test_rejoin_over_job_nodes_with_rows_of_two_data_contexts( + other_context: contexts.DataContext, # noqa: F811 # the fixture, by name +) -> None: + """``Rejoin`` of a job's source node with a renaming branch held from the run, rows + in two data contexts: reading the source node's channel rebuilds its rows in the + row-built form (never its raw table with its own context column), so the result + has both rows, as the sync run does.""" + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "x": pa.array([1.0, 2.0], pa.float64()), + "y": pa.array([3, 4], pa.int64()), + "source_id::a": pa.array(["s", "s"], pa.large_string()), + "record_id::a": pa.array(["r0", "r1"], pa.large_string()), + constants.CONTEXT_KEY: pa.array( + [contexts.get_default_context().context_key, other_context.context_key], + pa.large_string(), + ), + } + ) + table = table.cast( + pa.schema( + [ + f.with_nullable(False) if f.name.endswith("::a") else f + for f in table.schema + ] + ) + ) + raw = ArrowTableStream( + table, tag_columns=["k"], system_tag_columns=["source_id::a", "record_id::a"] + ) + job = PipelineJob(name="rejoin-contexts", database=InMemoryArrowDatabase()) + with job: + branch = operators.MapData({"x": "u", "y": "v"})(raw, label="branch") + _ = operators.Rejoin()(raw, branch, label="rejoin") + _ = job.run(orchestrator=SyncPipelineOrchestrator()) + rejoin = job.nodes["rejoin"] + assert rejoin.as_table().num_rows == 2 + upstreams = rejoin.upstreams + + async def go() -> StreamProtocol: + op = operators.Rejoin() + output = OutputChannel(op(*upstreams)) + await op.async_execute_batches([u.open_channel() for u in upstreams], output) + return output.result() + + result = asyncio.run(go()) + assert result.as_table().num_rows == 2 + assert sorted(map(str, result.as_table().to_pylist())) == sorted( + map(str, rejoin.as_table().to_pylist()) + ) From 793337e030c5ff4147c696c749c7969f70af6c30 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 06:28:10 -0800 Subject: [PATCH 6/8] fix(channels): Codex round 2 on #488: the shortcut belongs to the feed, a source node's channel is its execute() output, one consumer per reader, only the feed's end is the end (ITL-1362) - RecordBatchInput.opened_on: only a channel opened on a complete stream may give that stream (when _output_stream built it); a reader of an output channel always collects, whatever its description - a source node's channel carries exactly its execute() output, built at the first read from one binding (_materialize_upstream of its rows; TODO(ITL-1360)) - RecordBatchInput.reserve(): the first read or conversion takes the reader at call time; a second consumer is refused, naming it; a closed reader converts to ChannelClosed - only the feed returning None ends a channel: a ChannelClosed raised by the feed's own read is a read error - the complete-stream feed reads the table before the keys (one fetch) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/source_node.py | 69 ++++- .../core/operators/static_output_pod.py | 31 +-- src/orcapod/core/record_batch_channels.py | 5 + src/orcapod/core/streams/base.py | 23 +- .../core/streams/record_batch_input.py | 62 ++++- .../protocols/core_protocols/streams.py | 17 +- .../test_record_batch_channels.py | 257 +++++++++++++++++- 7 files changed, 417 insertions(+), 47 deletions(-) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 923d3f828..9bb629109 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -7,6 +7,8 @@ from __future__ import annotations +from collections import deque + import contextlib import dataclasses import functools @@ -27,12 +29,12 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, - CompleteStreamFeed, + row_built_columns, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, ) -from orcapod.core.streams.record_batch_input import InputChannel +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -417,6 +419,55 @@ def _require_stream_arrow_types(stream: Any, slot: str) -> None: raise _no_arrow_type_error(slot, missing) +class _ExecuteOutputFeed: + """The record batches of a source node's own ``execute()`` output. + + Built at the first read from the rows ``execute()`` gives, rebuilt as a job does + (``StaticOutputOperatorPod._materialize_upstream``): slow, and correct by + definition. One binding is read, at that moment. A batch is dropped once + delivered. + """ + + # TODO(ITL-1360): the channel of stage 2's ``execute()`` output stream. + + def __init__(self, node: SourceNodeBase) -> None: + """Make the feed; nothing is read until the first ``next``. + + Args: + node: The source node whose output it delivers. + """ + self._node = node + self._batches: deque[pa.RecordBatch] | None = None + + async def next(self) -> pa.RecordBatch | None: + """Return the next record batch of the node's output, or ``None`` at the end.""" + if self._batches is None: + from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + ) + + rows = self._node.execute() + output = StaticOutputOperatorPod._materialize_upstream(rows, self._node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of a node's rows + table = row_built_columns( + output.as_table(columns=ZERO_ROW_INPUT_COLUMNS), output.keys() + ) + self._batches = deque( + batch + for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) + if batch.num_rows + ) + return self._batches.popleft() if self._batches else None + + def close(self) -> None: + """Stop reading: the batches not read are dropped.""" + self._batches = deque() + + @property + def opened_on(self) -> StreamProtocol | None: + """``None``: the node is not the stream its batches rebuild.""" + return None + + class SourceNodeBase(TraceableBase, ABC): """Abstract base for SourceNode and SourceJobNode. @@ -1171,18 +1222,16 @@ def run(self) -> StreamView: def open_channel(self) -> RecordBatchInput: """Open an input channel on this node's rows, for async computation (ITL-1347). - As ``StreamBase.open_channel()``: the rows as Arrow record batches in the - row-built form, read once on the first read; the description is this node. - The rows are those of ``execute()``, so their columns follow the bound - source's keys (its tag order), which may differ from this node's keys (the - slot's order). An unbound node's first read raises what reading it raises. + The channel carries exactly this node's own ``execute()`` output: its rows, + as the table a job builds from them, in Arrow record batches. Everything + (the binding, the declared form, the column order, the source info) is read + at the first read, from one binding; opening reads nothing. The description + is this node. An unbound node's first read raises what reading it raises. Returns: The input channel. """ - bound = self._bound_stream() - keys = bound.keys() if bound is not None else None - return InputChannel(self, CompleteStreamFeed(self, keys)) + return InputChannel(self, _ExecuteOutputFeed(self)) async def async_iter_data(self): """Asynchronous iterator over (tag, data) pairs. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index c89109680..b4dad654c 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1085,9 +1085,12 @@ async def channel_to_stream(channel: RecordBatchInput) -> StreamProtocol: It reads the channel to its end (one pass; every error of the read, such as an unbound source's or a failed producer's, is raised here, before any operator runs) and builds a fixed snapshot of what was delivered through the one settlement path - (``stream_from_batches``). The only shortcut: a channel not read yet whose stream - ``_output_stream`` built (``ROW_BUILT_OUTPUT``) gives that stream, which is exactly - what its batches would rebuild; the channel is then closed. + (``stream_from_batches``). The only shortcut: a channel opened on a complete + stream that ``_output_stream`` built (``ROW_BUILT_OUTPUT``), not read yet, gives + that stream, which is exactly what its batches would rebuild; the channel is then + closed. A reader of an output channel always collects, whatever its description. + The channel is reserved for this call when it is made: no other consumer may + read it. Args: channel: The input channel, not read yet. @@ -1096,22 +1099,18 @@ async def channel_to_stream(channel: RecordBatchInput) -> StreamProtocol: A complete, re-readable stream of the channel's input. Raises: - RuntimeError: If the channel has already been read (a batch received, or its - end reached): a stream of part of an input is never made, and a channel - is never read again. - ChannelClosed: If the channel was closed before its producer completed. + RuntimeError: If a read of the channel was already called (a batch received, + its end reached, or another consumer still waiting): a stream of part of + an input is never made, and a channel is never read again. + ChannelClosed: If the channel was closed, before or during the read. UpstreamFailedError: If the producer failed or was cancelled. """ - if not channel.unread: - raise RuntimeError( - "channel_to_stream() gives everything an input channel delivers, as a " - + "stream; this channel has been read already." - ) - stream = channel.stream - if getattr(stream, ROW_BUILT_OUTPUT, False): + channel.reserve() # one consumer, from this call on + opened_on = channel.opened_on + if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): await channel.close() - return stream - return stream_from_batches(stream, await channel.collect()) + return opened_on + return stream_from_batches(channel.stream, await channel.collect()) def stream_from_batches( diff --git a/src/orcapod/core/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index 3dc1b5ad2..66527f145 100644 --- a/src/orcapod/core/record_batch_channels.py +++ b/src/orcapod/core/record_batch_channels.py @@ -81,6 +81,11 @@ async def next(self) -> pa.RecordBatch | None: await output._changed.wait() # pyright: ignore[reportPrivateUsage] return None + @property + def opened_on(self) -> StreamProtocol | None: + """``None``: a reader of an output reads what its producer sends.""" + return None + def close(self) -> None: """Stop reading and unregister from the output. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index bb5d169cc..3d941e5cb 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -347,21 +347,13 @@ class CompleteStreamFeed: stream is complete, so nothing is queued and no producer waits on a reader. """ - def __init__( - self, - stream: StreamProtocol, - keys: tuple[Sequence[str], Sequence[str]] | None = None, - ) -> None: + def __init__(self, stream: StreamProtocol) -> None: """Make a feed of ``stream``'s rows; nothing is read until the first ``next``. Args: stream: The complete stream to read. - keys: The tag and data keys of the rows read, when they differ from - ``stream.keys()`` (a source node gives its bound source's rows); - default ``stream.keys()``. """ self._stream = stream - self._keys = keys self._batches: deque[pa.RecordBatch] | None = None async def next(self) -> pa.RecordBatch | None: @@ -371,10 +363,10 @@ async def next(self) -> pa.RecordBatch | None: batches with no rows are skipped. """ if self._batches is None: - keys = self._keys if self._keys is not None else self._stream.keys() - table = row_built_columns( - self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS), keys - ) + # The table first: reading it is the stream's one read (an unpolled + # source polls here), and its keys are then known without another. + table = self._stream.as_table(columns=ZERO_ROW_INPUT_COLUMNS) + table = row_built_columns(table, self._stream.keys()) self._batches = deque( batch for batch in table.to_batches(max_chunksize=SOURCE_BATCH_ROWS) @@ -386,6 +378,11 @@ def close(self) -> None: """Stop reading: the batches not read are dropped.""" self._batches = deque() + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream this feed reads.""" + return self._stream + def typed_arrow_schemas( stream: object, *, own: bool = True diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 0fcdb7efc..2b1212698 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -45,6 +45,11 @@ def close(self) -> None: """Stop reading: nothing waits for this reader any more.""" ... + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream the feed reads, or ``None`` (a reader of an output).""" + ... + class InputChannel: """A single-pass, back-pressured reader of a stream's Arrow record batches. @@ -69,9 +74,14 @@ def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: self._stream = stream self._feed = feed self._received = 0 + # The producer's end was reached (the feed returned ``None``). self._ended = False # Closed by its consumer before the producer completed. self._closed = False + # A read was called: the channel has a consumer (reserved at call time). + self._started = False + # A read is in progress. + self._reading = False @property def stream(self) -> StreamProtocol: @@ -80,8 +90,35 @@ def stream(self) -> StreamProtocol: @property def unread(self) -> bool: - """Whether nothing has been read from the channel: no batch, no end, no close.""" - return not self._received and not self._ended + """Whether no read was called and the channel is not closed.""" + return not self._started and not self._ended and not self._closed + + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream this channel reads, when it was opened on one. + + ``None`` for a reader of an output channel, whatever its description: only a + complete stream's own feed delivers exactly that stream. + """ + return self._feed.opened_on + + def reserve(self) -> None: + """Take the channel for one consumer that will read all of it. + + Raises: + RuntimeError: If a read was called on it already (by any consumer, also + one still waiting), so all of the input can no longer be given. + ChannelClosed: If it was closed. + """ + if self._closed: + raise self._closed_early() + if self._started or self._ended: + raise RuntimeError( + f"The input channel of {_named(self._stream)} has been read already, " + + "or is being read by another consumer; all of its input can no " + + "longer be given." + ) + self._started = True async def receive(self) -> pa.RecordBatch: """Return the next Arrow record batch. @@ -93,18 +130,29 @@ async def receive(self) -> pa.RecordBatch: ChannelClosed: At the end, and after ``close``. After a ``close`` that came before the producer completed, the error says so, and iteration (``async for``) raises it instead of ending: no consumer loop takes - part of an input for all of it. + part of an input for all of it. A ``ChannelClosed`` raised by the + feed's own read is a read error too: only the feed's end ends it. + RuntimeError: If another consumer's read of this channel is in progress. UpstreamFailedError: If the producer failed or was cancelled. """ if self._closed: raise self._closed_early() if self._ended: raise ChannelClosed() + if self._reading: + raise RuntimeError( + f"The input channel of {_named(self._stream)} is being read by another " + + "consumer; a channel has one consumer." + ) + self._started = True + self._reading = True try: batch = await self._feed.next() except asyncio.CancelledError: await self.close() raise + finally: + self._reading = False if batch is None: if self._closed: # woken by its own early close raise self._closed_early() @@ -127,9 +175,11 @@ async def __anext__(self) -> pa.RecordBatch: try: return await self.receive() except ChannelClosed: - if self._closed: - raise # closed before its producer completed: not the end - raise StopAsyncIteration + # Only the producer's end ends the iteration: an early close, or a + # ChannelClosed raised by the feed's own read, is a read error. + if self._ended and not self._closed: + raise StopAsyncIteration + raise def _closed_early(self) -> ChannelClosed: """The error of a read after a close that came before the producer completed.""" diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index d70f95115..e3c467c96 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -620,7 +620,22 @@ async def collect(self) -> list[pa.RecordBatch]: @property def unread(self) -> bool: - """Whether nothing has been read from the channel: no batch, no end, no close.""" + """Whether no read was called and the channel is not closed.""" + ... + + @property + def opened_on(self) -> StreamProtocol | None: + """The complete stream this channel reads, when it was opened on one; else + ``None`` (a reader of an output channel, whatever its description).""" + ... + + def reserve(self) -> None: + """Take the channel for one consumer that will read all of it. + + Raises: + RuntimeError: If a read was called on it already. + ChannelClosed: If it was closed. + """ ... async def close(self) -> None: diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 37e149be0..b05a6aaba 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -34,6 +34,7 @@ ) from orcapod.core.operators import MapData, PolarsFilter, SelectDataColumns, SemiJoin from orcapod.core.operators.static_output_pod import ( + ROW_BUILT_OUTPUT, StaticOutputOperatorPod, channel_to_stream, stream_from_batches, @@ -182,6 +183,256 @@ def test_a_bound_source_node_sends_its_rows_in_their_own_column_order() -> None: assert same(pa.Table.from_batches(batches), expected) +def _keyed_source( + tag_only: tuple[str, ...], *, source_id: str = "keyed", offset: int = 0 +) -> ArrowTableSource: + """Tags ``k, j`` (data-tags unless named in ``tag_only``), data ``x, y``; every + field non-nullable, so a slot may declare ``x: int | None`` (a narrower bind).""" + table = pa.table( + { + "x": pa.array([1 + offset, 2 + offset], pa.int64()), + "k": pa.array([5 + offset, 6 + offset], pa.int64()), + "j": pa.array([3 + offset, 4 + offset], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ) + table = table.cast(pa.schema([f.with_nullable(False) for f in table.schema])) + return ArrowTableSource( + table, tag_columns=["k", "j"], tag_only_columns=tag_only, source_id=source_id + ) + + +def _declared_node(source: ArrowTableSource) -> SourceJobNode: + """A slot that declares tags ``j, k`` and data ``y, x: int | None`` (the source's + data-tags first), bound to ``source``: the declared form.""" + data_tags = [t for t in ("j", "k") if t in source.keys()[1]] + return SourceJobNode( + "keyed", + tag_schema=Schema({"j": int, "k": int}), + data_schema=Schema( + {**{t: int for t in data_tags}, "y": float, "x": int | None} + ), + bound_source=source, + ) + + +@pytest.mark.parametrize( + ("bind", "tag_only"), + [ + ("transparent", ()), + ("transparent", ("j",)), + ("transparent", ("k",)), + # A declared slot with one of two data-tags fails on main already, in its + # own execute() rows (duplicate column); reported separately. + ("declared", ()), + ], + ids=["transparent-both", "transparent-k", "transparent-j", "declared-both"], +) +def test_a_source_nodes_channel_carries_its_execute_output( + bind: str, tag_only: tuple[str, ...] +) -> None: + """A source node's batches, and the stream rebuilt from them, are its own + ``execute()`` output (schema, order, values, content hash), with data-tags in each + tag position (the declared slot orders the tags j, k against the source's k, j); + the node's own output channel takes them.""" + source = _keyed_source(tag_only) + node = ( + SourceJobNode.from_stream(source, name="keyed") + if bind == "transparent" + else _declared_node(source) + ) + expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + wanted = expected.as_table(columns=ALL) + assert any( + name.startswith("_source_") and name.removeprefix("_source_") in ("j", "k") + for name in wanted.column_names + ) # data-tag tokens are there + + async def read() -> tuple[list[pa.RecordBatch], Any]: + batches = await node.open_channel().collect() + output = OutputChannel(node) + for batch in batches: + await output.send(batch) # the node's description takes them + await output.close() + return batches, await channel_to_stream(node.open_channel()) + + batches, rebuilt = run(read) + assert same(pa.Table.from_batches(batches), R(expected)) + assert same(rebuilt.as_table(columns=ALL), wanted) + assert rebuilt.content_hash() == expected.content_hash() + + +def test_a_rebind_before_the_first_read_is_read_whole() -> None: + """A channel opened on a source node, then the node rebound: the first read reads + the new binding only (rows, order and source info from one binding).""" + node = SourceJobNode.from_stream(_keyed_source(()), name="keyed") + channel = node.open_channel() + node.bound_source = _keyed_source((), source_id="other", offset=10) + expected = StaticOutputOperatorPod._materialize_upstream(node.execute(), node) # pyright: ignore[reportPrivateUsage] # the job's rebuild of the rows + batches = run(channel.collect) + assert same(pa.Table.from_batches(batches), R(expected)) + + +@pytest.mark.xfail( + strict=True, + raises=ValueError, + reason="ITL-1365: a source node whose plain tags are declared in another order " + "than their columns (x, j, k, y with tags k, j) describes itself in the slot's " + "order (keys() j, k; its zero-row input too, as on main), while its rows are in " + "the bound source's order, so its own description refuses its batches", +) +def test_a_source_nodes_description_takes_its_rows_in_their_own_order() -> None: + """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the node's + own output channel takes the batches its channel delivers.""" + stream = ArrowTableSource( + pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ), + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="ordered", + ) + node = SourceJobNode.from_stream(stream, name="ordered") + + async def read() -> None: + output = OutputChannel(node) + for batch in await node.open_channel().collect(): + await output.send(batch) + + run(read) + + +def test_a_flagged_stream_is_given_as_it_is_only_by_its_own_channel() -> None: + """The shortcut belongs to a channel opened on a stream ``_output_stream`` built: + such a channel gives that stream. A reader of an output channel whose description + is that same stream reads its producer: other rows, or its failure.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def flagged_stream() -> Any: + output = OutputChannel(stream) + for batch in batches: + await output.send(batch) + await output.close() + return await channel_to_stream(output.open_reader()) + + flagged = run(flagged_stream) + assert getattr(flagged, ROW_BUILT_OUTPUT, False) + + async def read() -> None: + direct = flagged.open_channel() + assert await channel_to_stream(direct) is flagged + other = OutputChannel(flagged) + reader = other.open_reader() + await other.send(batches[0]) + await other.close() + rebuilt = await channel_to_stream(reader) + assert rebuilt is not flagged + assert rebuilt.as_table().num_rows == 1 + failed = OutputChannel(flagged) + failing = failed.open_reader() + failed.fail(OSError("disk gone")) + with pytest.raises(UpstreamFailedError): + _ = await channel_to_stream(failing) + op = SemiJoin() + semi_output = OutputChannel(op(stream, flagged)) + broken = OutputChannel(flagged) + broken_reader = broken.open_reader() + broken.fail(OSError("disk gone")) + with pytest.raises(UpstreamFailedError): + await op.async_execute_batches( + [stream.open_channel(), broken_reader], semi_output + ) + + run(read) + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_reader_has_one_consumer(retain: bool) -> None: + """A receive waiting on a reader holds it: a second consumer of the same reader + (a conversion, or another receive) is refused, naming it, and the waiting + receive gets the batch.""" + stream = source(1) + (batch,) = batches_of(stream) + + async def read() -> int: + output = OutputChannel(stream, retain=retain) + reader = output.open_reader() + waiting = asyncio.ensure_future(reader.receive()) + await asyncio.sleep(0) + assert not reader.unread + with pytest.raises(RuntimeError, match="read already|another consumer"): + _ = await channel_to_stream(reader) + with pytest.raises(RuntimeError, match="another consumer"): + _ = await reader.receive() + await output.send(batch) + await output.close() + return (await waiting).num_rows + + assert run(read) == 1 + + +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.""" + stream = source(1) + + async def read() -> None: + reader = OutputChannel(stream).open_reader() + await reader.close() + with pytest.raises(ChannelClosed, match="closed before its producer"): + _ = await channel_to_stream(reader) + + run(read) + + +class _ClosingFetch(FakeDynamicSource): + """A dynamic source whose fetch raises ``ChannelClosed`` (its own input closed + early); its schema is declared, so nothing before the read fetches.""" + + async def fetch(self, cursor: Any = None) -> Any: + self.fetch_cursors.append(cursor) + raise ChannelClosed("underlying input closed early") + + +def test_a_channel_closed_inside_the_read_is_a_read_error() -> None: + """A ``ChannelClosed`` raised by the feed's own read (the source's) is not the end + of the input: iteration, ``collect`` and ``channel_to_stream`` raise it, and a + barrier fails before its body.""" + declared = Schema({"id": int, "val": int}) + + def polling() -> PollingSource[Any]: + fake = _ClosingFetch( + batches=[_batch(1, 10), _batch(2, 20)], schema_override=declared + ) + return PollingSource( + fake, tag_columns="id", record_id_columns="id", source_id="closing" + ) + + async def read() -> None: + with pytest.raises(ChannelClosed, match="underlying input"): + _ = await polling().open_channel().collect() + channel = polling().open_channel() + with pytest.raises(ChannelClosed, match="underlying input"): + _ = await channel_to_stream(channel) + assert not channel.unread + left = source() + right = polling() + op = SemiJoin() + output = OutputChannel(op(left, right)) + with pytest.raises(ChannelClosed, match="underlying input"): + await op.async_execute_batches( + [left.open_channel(), right.open_channel()], output + ) + + run(read) + + def test_a_delivered_batch_is_not_kept_by_the_feed() -> None: """Once delivered, a batch is not held by the channel: a consumer that drops it frees it, also while the channel is still open.""" @@ -277,10 +528,14 @@ def test_a_polling_source_is_read_once_through_a_channel() -> None: async def read() -> None: channel = polling.open_channel() + other = polling.open_channel() assert len(fake.fetch_cursors) == 0 # opening reads nothing snapshot = await channel_to_stream(channel) fetched = len(fake.fetch_cursors) - assert fetched > 0 + assert fetched == 1 # exactly one fetch for the channel's first read + assert len(await other.collect()) >= 1 + assert len(fake.fetch_cursors) == 2 # and one for the other channel's + fetched = len(fake.fetch_cursors) rows = snapshot.as_table().num_rows assert snapshot.as_table().num_rows == rows # a fixed snapshot assert len(fake.fetch_cursors) == fetched # read again: no fetch From 81c09f2fc19e1e65254eb5d34bb015ab8ad931af Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:03:41 -0800 Subject: [PATCH 7/8] fix(channels): a reader belongs to one consumer for its whole life; channel_to_stream reserves at call time (ITL-1362) Codex round 3 on #488: the first read binds a reader to the calling asyncio task, and a read from another task is refused, between batches as well as while one is pending; after the end a reader answers ChannelClosed to anyone (nothing to take); close() stays callable from anywhere. reserve() holds an unread reader for a claim, and no read is taken until a task takes it over with the claim: channel_to_stream is a plain function that reserves synchronously and returns the conversion, which adopts the claim in the task that runs it. Tests whose readers had two consuming tasks now give each reader one. Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 30 +++- .../core/streams/record_batch_input.py | 67 +++++++- .../protocols/core_protocols/streams.py | 8 +- .../test_record_batch_channels.py | 153 +++++++++++++++--- 4 files changed, 224 insertions(+), 34 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index b4dad654c..37dcc42ac 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,7 +3,7 @@ import asyncio import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Sequence +from collections.abc import Collection, Coroutine, Iterator, Sequence from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, ClassVar, cast @@ -1079,7 +1079,9 @@ def transport_schema(stream: StreamProtocol) -> pa.Schema | None: """ -async def channel_to_stream(channel: RecordBatchInput) -> StreamProtocol: +def channel_to_stream( + channel: RecordBatchInput, +) -> Coroutine[Any, Any, StreamProtocol]: """Return what an input channel delivers, as a stream: the one such conversion. It reads the channel to its end (one pass; every error of the read, such as an @@ -1089,14 +1091,17 @@ async def channel_to_stream(channel: RecordBatchInput) -> StreamProtocol: stream that ``_output_stream`` built (``ROW_BUILT_OUTPUT``), not read yet, gives that stream, which is exactly what its batches would rebuild; the channel is then closed. A reader of an output channel always collects, whatever its description. - The channel is reserved for this call when it is made: no other consumer may - read it. + + 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. Args: channel: The input channel, not read yet. Returns: - A complete, re-readable stream of the channel's input. + The conversion to await: a complete, re-readable stream of the channel's + input. Raises: RuntimeError: If a read of the channel was already called (a batch received, @@ -1105,7 +1110,20 @@ async def channel_to_stream(channel: RecordBatchInput) -> StreamProtocol: ChannelClosed: If the channel was closed, before or during the read. UpstreamFailedError: If the producer failed or was cancelled. """ - channel.reserve() # one consumer, from this call on + claim = channel.reserve() # at call time: nothing can read it before the await + return _channel_to_stream(channel, claim) + + +async def _channel_to_stream( + channel: RecordBatchInput, claim: object +) -> StreamProtocol: + """Read a reserved channel and return its input as a stream (``channel_to_stream``). + + Args: + channel: The channel ``channel_to_stream`` reserved. + claim: Its claim, which the task running this conversion takes over. + """ + channel.reserve(claim) opened_on = channel.opened_on if opened_on is not None and getattr(opened_on, ROW_BUILT_OUTPUT, False): await channel.close() diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 2b1212698..10040ef5a 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -82,6 +82,10 @@ def __init__(self, stream: StreamProtocol, feed: BatchFeed) -> None: self._started = False # A read is in progress. 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. + self._owner: asyncio.Task[Any] | None = None + self._claim: object | None = None @property def stream(self) -> StreamProtocol: @@ -102,23 +106,66 @@ def opened_on(self) -> StreamProtocol | None: """ return self._feed.opened_on - def reserve(self) -> None: + def reserve(self, claim: object | None = None) -> object: """Take the channel for one consumer that will read all of it. + Without ``claim``: the channel, not read yet, is held for the returned claim: + no read is taken, from any task, until a task takes it over with the claim + (the task that runs a conversion). With the claim it returned: the calling + task takes the channel over, and any other task's read is then refused. + + Args: + claim: The claim an earlier ``reserve()`` returned, to take it over. + + Returns: + The claim. + Raises: RuntimeError: If a read was called on it already (by any consumer, also - one still waiting), so all of the input can no longer be given. + one still waiting), so all of the input can no longer be given; or + if ``claim`` is not this channel's claim. ChannelClosed: If it was closed. """ if self._closed: raise self._closed_early() - if self._started or self._ended: + if claim is not None: + if claim is not self._claim: + raise RuntimeError( + f"The input channel of {_named(self._stream)} is claimed by " + + "another consumer." + ) + self._owner = _current_task() + return claim + if self._started or self._ended or self._owner is not None: raise RuntimeError( f"The input channel of {_named(self._stream)} has been read already, " + "or is being read by another consumer; all of its input can no " + "longer be given." ) self._started = True + self._owner = None # held for the claim until a task takes it over + self._claim = object() + return self._claim + + def _belong_to_caller(self) -> None: + """Bind the channel to the calling task on its first read; refuse any other. + + A channel has one consumer for its whole life: between batches as well as + while a read is pending, a read from another task is refused. + """ + task = _current_task() + if self._owner is None and self._claim is not None: + raise RuntimeError( + f"The input channel of {_named(self._stream)} is held for a " + + "conversion that has not started; no other read is taken." + ) + if self._owner is None: + self._owner = task + elif self._owner is not task: + raise RuntimeError( + f"The input channel of {_named(self._stream)} belongs to another " + + "consumer (another task); a channel has one consumer." + ) async def receive(self) -> pa.RecordBatch: """Return the next Arrow record batch. @@ -132,13 +179,15 @@ async def receive(self) -> pa.RecordBatch: (``async for``) raises it instead of ending: no consumer loop takes part of an input for all of it. A ``ChannelClosed`` raised by the feed's own read is a read error too: only the feed's end ends it. - RuntimeError: If another consumer's read of this channel is in progress. + RuntimeError: If the channel belongs to another consumer (another task; + the first read binds it), or a read of it is in progress. UpstreamFailedError: If the producer failed or was cancelled. """ if self._closed: raise self._closed_early() if self._ended: - raise ChannelClosed() + raise ChannelClosed() # after the end there is nothing to take, for anyone + self._belong_to_caller() if self._reading: raise RuntimeError( f"The input channel of {_named(self._stream)} is being read by another " @@ -206,6 +255,14 @@ async def close(self) -> None: self._feed.close() +def _current_task() -> asyncio.Task[Any] | None: + """The running asyncio task, or ``None`` outside one.""" + try: + return asyncio.current_task() + except RuntimeError: # no running event loop + return None + + def _named(stream: Any) -> str: # pyright: ignore[reportExplicitAny] # any stream or node """How an error names a stream: its label, or what it prints as.""" label = getattr(stream, "label", None) diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index e3c467c96..4027893f2 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -629,11 +629,15 @@ def opened_on(self) -> StreamProtocol | None: ``None`` (a reader of an output channel, whatever its description).""" ... - def reserve(self) -> None: + def reserve(self, claim: object | None = None) -> object: """Take the channel for one consumer that will read all of it. + Without ``claim``, the calling task takes the unread channel and gets a claim; + with that claim, another task (the one that will read it) takes it over. + Raises: - RuntimeError: If a read was called on it already. + RuntimeError: If a read was called on it already, or ``claim`` is not its + claim. ChannelClosed: If it was closed. """ ... diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index b05a6aaba..7d47278e4 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -377,6 +377,102 @@ async def read() -> int: assert run(read) == 1 +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_reader_belongs_to_its_first_consumer_between_batches(retain: bool) -> None: + """Task A iterates a reader and pauses after its first batch; task B's read of the + same reader, between A's batches, is refused, and A reads all three batches.""" + stream = source(3) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + paused, resume = asyncio.Event(), asyncio.Event() + + async def consumer_a() -> int: + seen = 0 + async for _ in reader: + seen += 1 + if seen == 1: + paused.set() + await resume.wait() + return seen + + async def consumer_b() -> None: + _ = await reader.receive() + + a = asyncio.ensure_future(consumer_a()) + await paused.wait() + with pytest.raises(RuntimeError, match="belongs to another consumer"): + await asyncio.ensure_future(consumer_b()) + resume.set() + return await a + + assert run(read) == 3 + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_reserved_reader_is_read_only_through_its_claim(retain: bool) -> None: + """``reserve()`` holds the reader for its claim: no read is taken (from another + task, nor from the reserving task) until a task takes it over with the claim; + then only that task reads.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + claim = reader.reserve() + with pytest.raises(RuntimeError, match="held for a conversion"): + _ = await reader.receive() + + async def other() -> None: + _ = await reader.receive() + + with pytest.raises(RuntimeError, match="held for a conversion"): + await asyncio.ensure_future(other()) + with pytest.raises(RuntimeError, match="claimed by another consumer"): + _ = reader.reserve(object()) + + async def owner() -> int: + _ = reader.reserve(claim) + return len(await reader.collect()) + + taken = await asyncio.ensure_future(owner()) + with pytest.raises(ChannelClosed): + _ = await reader.receive() # read to its end: nothing left, for anyone + return taken + + assert run(read) == 2 + + +@pytest.mark.parametrize("retain", [True, False], ids=["retained", "bounded"]) +def test_a_conversion_reserves_the_reader_when_it_is_created(retain: bool) -> None: + """``pending = channel_to_stream(reader)`` reserves at once: a receive before + ``await pending`` is refused, and the conversion gets every batch.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream, retain=retain, buffer_size=4) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + pending = channel_to_stream(reader) + with pytest.raises(RuntimeError, match="held for a conversion"): + _ = await reader.receive() + return (await pending).as_table().num_rows + + assert run(read) == 2 + + 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.""" @@ -1201,13 +1297,16 @@ async def trials(reader: InputChannel, start: list[Any]) -> list[Any]: got.extend(batch.column("trial").to_pylist()) return got - readers = asyncio.ensure_future( - asyncio.gather(trials(fast, [0]), trials(slow, [])) - ) - _ = await asyncio.gather(*sending) - await output.close() - fast_order, slow_order = await readers - return fast_order, slow_order + async def close_after_sends() -> None: + _ = await asyncio.gather(*sending) + await output.close() + + # Each reader has one consumer: this task keeps reading the fast one. + slow_order = asyncio.ensure_future(trials(slow, [])) + closing = asyncio.ensure_future(close_after_sends()) + fast_order = await trials(fast, [0]) + await closing + return fast_order, await slow_order fast_order, slow_order = run(write) assert fast_order == slow_order == [0, 1, 2] @@ -1337,24 +1436,28 @@ async def produce() -> None: await output.close() producer = asyncio.ensure_future(produce()) - # Two batches fit each queue. The fast reader makes room for a third, which - # then waits for the slow reader: that send does not return. - got_fast = [await fast.receive() for _ in range(3)] + # Two batches fit each queue. The fast reader (one consumer, its own task) + # makes room for a third, which then waits for the slow reader: that send + # does not return, and the fast reader waits for its fourth batch. + three_read = asyncio.Event() + + async def fast_consumer() -> int: + got = [await fast.receive() for _ in range(3)] + three_read.set() + return len(got) + len(await fast.collect()) + + fast_reading = asyncio.ensure_future(fast_consumer()) + await three_read.wait() await asyncio.sleep(0.01) sent_while_slow_is_full = len(sent) - starved = asyncio.ensure_future(fast.receive()) - await asyncio.sleep(0.01) - fast_waits_for_the_slow_reader = not starved.done() - - async def rest_of_fast() -> int: - return 1 + len(await fast.collect()) if await starved else 0 - - rest, slow_batches = await asyncio.gather(rest_of_fast(), slow.collect()) + fast_waits_for_the_slow_reader = not fast_reading.done() + slow_batches = await slow.collect() + fast_total = await fast_reading await producer return ( sent_while_slow_is_full, fast_waits_for_the_slow_reader, - len(got_fast) + rest, + fast_total, len(slow_batches), ) @@ -1429,8 +1532,16 @@ async def write() -> list[BaseException]: output = OutputChannel(stream, retain=retain) unread, waiting, barrier = (output.open_reader() for _ in range(3)) await output.send(batches[0]) - _ = await waiting.receive() - blocked = asyncio.ensure_future(waiting.receive()) + first_read = asyncio.Event() + + async def waiting_consumer() -> Any: + # One consumer for the reader: it reads a batch, then waits for the next. + _ = await waiting.receive() + first_read.set() + return await waiting.receive() + + blocked = asyncio.ensure_future(waiting_consumer()) + await first_read.wait() whole = asyncio.ensure_future(channel_to_stream(barrier)) await asyncio.sleep(0) output.fail(boom) From 03918d5738f93ecc2e87fab62cafc2d2679246c4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 07:29:47 -0800 Subject: [PATCH 8/8] fix(channels): CodeRabbit on #488: cleanup on failure leaves nothing behind, a claim is taken over once, the consumer task is released, the delivered column order is kept (ITL-1362) - a barrier's input conversions are started inside the protected block, and on any failure every started conversion is cancelled and awaited - a reader releases its consumer task at its end and on close; a redeemed claim is cleared; a feed raising StopAsyncIteration is a read error (only None ends) - stream_from_batches keeps the delivered column order, with the roles from the description (a source node whose plain tags the slot orders otherwise, ITL-1365) - reserve()/unread document the claim-held state - tests read with asyncio.timeout, not wait_for (Python 3.11 runs wait_for's argument in another task); helper docstrings; the batch-release check runs before the channel is drained Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 41 ++++- .../core/streams/record_batch_input.py | 22 ++- .../protocols/core_protocols/streams.py | 11 +- .../test_record_batch_channels.py | 166 +++++++++++++++++- .../operators/test_record_batch_execution.py | 17 +- 5 files changed, 242 insertions(+), 15 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 37dcc42ac..e32ae30df 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1017,12 +1017,17 @@ async def _streams_of(inputs: Sequence[RecordBatchInput]) -> list[StreamProtocol UpstreamFailedError: If an input's producer failed; the other inputs are no longer read. """ - tasks = [asyncio.ensure_future(channel_to_stream(channel)) for channel in inputs] + tasks: list[asyncio.Future[StreamProtocol]] = [] try: + for channel in inputs: + tasks.append(asyncio.ensure_future(channel_to_stream(channel))) return list(await asyncio.gather(*tasks)) except BaseException: + # Every conversion already started is cancelled and awaited: none is left + # running, or raising with nobody to hear it. for task in tasks: _ = task.cancel() + _ = await asyncio.gather(*tasks, return_exceptions=True) raise @@ -1157,7 +1162,39 @@ def stream_from_batches( if not batches: return StaticOutputOperatorPod._materialize_upstream([], stream) # pyright: ignore[reportPrivateUsage] # the zero-row input of an operator table = pa.Table.from_batches([with_open_provenance_flags(b) for b in batches]) - return StaticOutputOperatorPod._output_stream(table, stream.keys(), stream) # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's + return StaticOutputOperatorPod._output_stream( # pyright: ignore[reportPrivateUsage] # F and the identity, stage 2's + table, _keys_in_delivered_order(stream.keys(), table.column_names), stream + ) + + +def _keys_in_delivered_order( + keys: tuple[Sequence[str], Sequence[str]], names: Sequence[str] +) -> tuple[list[str], list[str]]: + """The description's tag and data keys, in the order the delivered rows have them. + + The roles come from the description; the order from the batches, so a stream + made from them keeps the columns as they were delivered. They agree for every + stream whose description follows its rows (an operator's or a function's); + a source node whose plain tags are declared in another order than its columns + describes itself in the slot's order (ITL-1365) while its rows are not. + + Args: + keys: The describing stream's tag keys and data keys. + names: The delivered table's column names. + + Returns: + The tag keys and the data keys, data-tags first in tag order. + """ + tag_keys, data_keys = keys + tags, data = set(tag_keys), set(data_keys) + position = {name: i for i, name in enumerate(names)} + ordered_tags = sorted(tag_keys, key=lambda n: position.get(n, len(names))) + data_tags = [n for n in ordered_tags if n in data] + plain = sorted( + (n for n in data_keys if n not in tags), + key=lambda n: position.get(n, len(names)), + ) + return ordered_tags, data_tags + plain def with_open_provenance_flags(batch: pa.RecordBatch) -> pa.RecordBatch: diff --git a/src/orcapod/core/streams/record_batch_input.py b/src/orcapod/core/streams/record_batch_input.py index 10040ef5a..98d23e33b 100644 --- a/src/orcapod/core/streams/record_batch_input.py +++ b/src/orcapod/core/streams/record_batch_input.py @@ -94,7 +94,10 @@ def stream(self) -> StreamProtocol: @property def unread(self) -> bool: - """Whether no read was called and the channel is not closed.""" + """Whether no read was called and the channel is not closed. + + A reserved channel (``reserve()``) is not unread, even before its first read. + """ return not self._started and not self._ended and not self._closed @property @@ -135,6 +138,7 @@ def reserve(self, claim: object | None = None) -> object: + "another consumer." ) self._owner = _current_task() + self._claim = None # redeemed: a later reserve(claim) is refused return claim if self._started or self._ended or self._owner is not None: raise RuntimeError( @@ -200,12 +204,20 @@ async def receive(self) -> pa.RecordBatch: except asyncio.CancelledError: await self.close() raise + except StopAsyncIteration as error: + # Only ``None`` is the feed's end: a raised StopAsyncIteration would end + # an ``async for`` over part of the input. + raise RuntimeError( + f"The read of the input channel of {_named(self._stream)} raised " + + "StopAsyncIteration; a feed ends by returning None." + ) from error finally: self._reading = False if batch is None: if self._closed: # woken by its own early close raise self._closed_early() self._ended = True + self._owner = None # nothing left to read: the consumer is released raise ChannelClosed() self._received += 1 return batch @@ -248,10 +260,16 @@ async def collect(self) -> list[pa.RecordBatch]: return [batch async for batch in self] async def close(self) -> None: - """Stop reading. The producer no longer waits for this reader.""" + """Stop reading. The producer no longer waits for this reader. + + Callable from any task. The consumer task is released: no read is taken + after a close, from any task. + """ if not self._ended: self._closed = True self._ended = True + self._owner = None + self._claim = None self._feed.close() diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 4027893f2..ec42f4c7e 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -620,7 +620,10 @@ async def collect(self) -> list[pa.RecordBatch]: @property def unread(self) -> bool: - """Whether no read was called and the channel is not closed.""" + """Whether no read was called and the channel is not closed. + + A reserved channel (``reserve()``) is not unread, even before its first read. + """ ... @property @@ -632,8 +635,10 @@ def opened_on(self) -> StreamProtocol | None: def reserve(self, claim: object | None = None) -> object: """Take the channel for one consumer that will read all of it. - Without ``claim``, the calling task takes the unread channel and gets a claim; - with that claim, another task (the one that will read it) takes it over. + 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. Raises: RuntimeError: If a read was called on it already, or ``claim`` is not its diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index 7d47278e4..95821c2cd 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -273,6 +273,36 @@ def test_a_rebind_before_the_first_read_is_read_whole() -> None: assert same(pa.Table.from_batches(batches), R(expected)) +def test_a_source_nodes_conversion_keeps_the_delivered_column_order() -> None: + """Plain tags declared ``k, j`` over physical columns ``x, j, k, y``: the stream + ``channel_to_stream`` makes keeps the columns in the order they were delivered + (the node's rows), though the node describes itself in the slot's order.""" + stream = ArrowTableSource( + pa.table( + { + "x": pa.array([1, 2], pa.int64()), + "j": pa.array([3, 4], pa.int64()), + "k": pa.array([5, 6], pa.int64()), + "y": pa.array([7.5, 8.5], pa.float64()), + } + ), + tag_columns=["k", "j"], + tag_only_columns=True, + source_id="ordered", + ) + node = SourceJobNode.from_stream(stream, name="ordered") + assert node.keys()[0] == ("j", "k") # the slot's order + + async def read() -> tuple[list[str], list[str]]: + batches = await node.open_channel().collect() + rebuilt = await channel_to_stream(node.open_channel()) + return batches[0].schema.names, rebuilt.as_table(columns=ALL).column_names + + delivered, rebuilt = run(read) + assert delivered[:2] == ["k", "j"] + assert rebuilt == delivered + + @pytest.mark.xfail( strict=True, raises=ValueError, @@ -473,6 +503,129 @@ async def read() -> int: assert run(read) == 2 +def test_a_claim_is_taken_over_once() -> None: + """A redeemed claim cannot be redeemed again: the channel stays with the task that + took it over.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> int: + output = OutputChannel(stream) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + claim = reader.reserve() + _ = reader.reserve(claim) + + async def thief() -> None: + _ = reader.reserve(claim) + + with pytest.raises(RuntimeError, match="claimed by another consumer"): + await asyncio.ensure_future(thief()) + return len(await reader.collect()) + + assert run(read) == 2 + + +def test_a_reader_releases_its_consumer_task_at_its_end_and_on_close() -> None: + """The consumer task is not kept by the reader once it has nothing left to read: + after the end, or after ``close()``.""" + stream = source(2) + batches = batches_of(stream, 1) + + async def read() -> tuple[bool, bool]: + released: list[bool] = [] + for ending in ("end", "close"): + output = OutputChannel(stream) + reader = output.open_reader() + for batch in batches: + await output.send(batch) + await output.close() + + async def consume() -> None: + if ending == "end": + _ = await reader.collect() + else: + _ = await reader.receive() + await reader.close() + + task = asyncio.ensure_future(consume()) + await task + reference = weakref.ref(task) + del task + await asyncio.sleep(0) # the loop drops its own references to the task + gc.collect() + released.append(reference() is None) + return released[0], released[1] + + assert run(read) == (True, True) + + +class _StoppingFeed: + """A feed whose second read raises ``StopAsyncIteration`` instead of returning + ``None``: a broken feed, not the end of its input.""" + + def __init__(self, batch: pa.RecordBatch) -> None: + self._batch: pa.RecordBatch | None = batch + + async def next(self) -> pa.RecordBatch | None: + """Return the one batch, then raise ``StopAsyncIteration``.""" + if self._batch is None: + raise StopAsyncIteration + batch, self._batch = self._batch, None + return batch + + def close(self) -> None: + """Nothing to release.""" + + @property + def opened_on(self) -> None: + """Not a complete stream's feed.""" + return None + + +def test_a_feed_raising_stop_async_iteration_is_a_read_error() -> None: + """Only a feed returning ``None`` ends a channel: a raised ``StopAsyncIteration`` + is a read error, so ``collect()`` and a barrier never take one batch for all.""" + stream = source(2) + (first, _) = batches_of(stream, 1) + + async def read() -> None: + with pytest.raises(RuntimeError, match="StopAsyncIteration"): + _ = await InputChannel(stream, _StoppingFeed(first)).collect() + with pytest.raises(RuntimeError, match="StopAsyncIteration"): + _ = await channel_to_stream(InputChannel(stream, _StoppingFeed(first))) + + run(read) + + +def test_a_barrier_leaves_no_conversion_behind_when_an_input_was_read() -> None: + """A barrier whose second input was read already: its setup fails, and the first + input's conversion, already started, is cancelled and awaited, so no task fails + later with nobody to hear it.""" + left = source(2) + right = source(2, source_id="other") + unheard: list[Any] = [] + + async def read() -> None: + asyncio.get_running_loop().set_exception_handler( + lambda _loop, context: unheard.append(context) + ) + first, second = left.open_channel(), right.open_channel() + _ = await second.receive() + op = SemiJoin() + output = OutputChannel(op(left, right)) + with pytest.raises(RuntimeError, match="read already"): + await op.async_execute_batches([first, second], output) + gc.collect() + await asyncio.sleep(0.01) + + run(read) + gc.collect() + assert unheard == [] + + 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.""" @@ -492,6 +645,7 @@ class _ClosingFetch(FakeDynamicSource): early); its schema is declared, so nothing before the read fetches.""" async def fetch(self, cursor: Any = None) -> Any: + """Record the fetch, then fail it as a source whose own input closed.""" self.fetch_cursors.append(cursor) raise ChannelClosed("underlying input closed early") @@ -547,10 +701,11 @@ async def read() -> bool: first = await channel.receive() reference = weakref.ref(first) del first + gc.collect() + released_while_open = reference() is None # before the channel is drained rest = await channel.collect() assert sum(batch.num_rows for batch in rest) == 3 - gc.collect() - return reference() is None + return released_while_open assert run(read) @@ -1298,6 +1453,8 @@ async def trials(reader: InputChannel, start: list[Any]) -> list[Any]: return got async def close_after_sends() -> None: + """Close the output once both sends are done (they wait for the slow + reader's room, which its own consumer task frees).""" _ = await asyncio.gather(*sending) await output.close() @@ -1442,6 +1599,8 @@ async def produce() -> None: three_read = asyncio.Event() async def fast_consumer() -> int: + """The fast reader's one consumer: read three batches, signal, then wait + for the rest, which come only as the slow reader makes room.""" got = [await fast.receive() for _ in range(3)] three_read.set() return len(got) + len(await fast.collect()) @@ -1535,7 +1694,8 @@ async def write() -> list[BaseException]: first_read = asyncio.Event() async def waiting_consumer() -> Any: - # One consumer for the reader: it reads a batch, then waits for the next. + """The reader's one consumer: read a batch, signal, then wait for the next, + which the producer's failure ends.""" _ = await waiting.receive() first_read.set() return await waiting.receive() diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index 8c1c37e75..568b44975 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -282,11 +282,15 @@ async def go() -> list[pa.RecordBatch]: await asyncio.wait_for(feed.send(batch), TIMEOUT) if rows_wanted: # This row's result arrives before the next row is sent. - result = await asyncio.wait_for(results.receive(), TIMEOUT) + # asyncio.timeout, not wait_for: on Python 3.11 wait_for reads in + # another task, and a reader has one consumer. + async with asyncio.timeout(TIMEOUT): + result = await results.receive() assert result.num_rows == rows_wanted received.append(result) await feed.close() - assert await asyncio.wait_for(results.collect(), TIMEOUT) == [] + async with asyncio.timeout(TIMEOUT): + assert await results.collect() == [] await asyncio.wait_for(task, TIMEOUT) return received @@ -328,11 +332,13 @@ async def go() -> tuple[int, int]: one_row = _cut(rows, (1,)) await feed.send(one_row[0]) await feed.send(one_row[1]) - first = await asyncio.wait_for(results.receive(), TIMEOUT) + async with asyncio.timeout(TIMEOUT): + first = await results.receive() assert not task.done() await feed.send(one_row[2]) await feed.close() - rest = await asyncio.wait_for(results.collect(), TIMEOUT) + async with asyncio.timeout(TIMEOUT): + rest = await results.collect() await task return first.num_rows, sum(batch.num_rows for batch in rest) @@ -675,7 +681,8 @@ async def go() -> None: with pytest.raises(OSError, match="flush failed"): await op.async_execute_batches([source.open_channel()], output) with pytest.raises(UpstreamFailedError): - _ = await asyncio.wait_for(results.collect(), TIMEOUT) + async with asyncio.timeout(TIMEOUT): + _ = await results.collect() asyncio.run(go())