diff --git a/.zed/rules b/.zed/rules index 6967e6d81..bbd720618 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1299,21 +1299,26 @@ 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/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 - 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. + 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 7b781c65c..0c6d59591 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1346,21 +1346,26 @@ 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/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 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. + `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 b522c117f..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,10 +29,12 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.core.streams.base import ( ZERO_ROW_INPUT_COLUMNS, + row_built_columns, schema_requires_io, typed_arrow_schemas, typed_zero_row_table, ) +from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( ViewStatus, StreamView, @@ -57,6 +61,9 @@ if TYPE_CHECKING: from orcapod.channels import WritableChannel from orcapod.protocols.core_protocols import StreamProtocol + from orcapod.protocols.core_protocols.streams import ( + RecordBatchInput, + ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol logger = logging.getLogger(__name__) @@ -412,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. @@ -1163,6 +1219,20 @@ 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). + + 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. + """ + return InputChannel(self, _ExecuteOutputFeed(self)) + async def async_iter_data(self): """Asynchronous iterator over (tag, data) pairs. 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..e32ae30df 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -3,13 +3,13 @@ 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 import pyarrow as pa -from orcapod.protocols.core_protocols.record_batch_channels import ( +from orcapod.protocols.core_protocols.streams import ( RecordBatchInput, RecordBatchOutput, ) @@ -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,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()) 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 @@ -1065,6 +1075,67 @@ 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. +""" + + +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 + 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 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 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: + 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, + 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. + """ + 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() + return opened_on + return stream_from_batches(channel.stream, await channel.collect()) + + def stream_from_batches( stream: StreamProtocol, batches: Sequence[pa.RecordBatch] ) -> StreamProtocol: @@ -1072,7 +1143,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 @@ -1091,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/record_batch_channels.py b/src/orcapod/core/record_batch_channels.py index a6f5e57ab..66527f145 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.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 -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,11 +25,8 @@ 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 @@ -38,67 +34,10 @@ 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. -""" - 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 +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. @@ -157,132 +101,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 +349,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..3d941e5cb 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, @@ -21,6 +22,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 +36,7 @@ StreamProtocol, TagProtocol, ) +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 @@ -333,6 +336,54 @@ 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 (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: + """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 channel is opened; + batches with no rows are skipped. + """ + if self._batches is None: + # 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) + 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: + """The complete stream this feed reads.""" + return self._stream + + def typed_arrow_schemas( stream: object, *, own: bool = True ) -> tuple[pa.Schema, pa.Schema]: @@ -1146,6 +1197,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; then the stream is read + once, a fixed snapshot. + + 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..98d23e33b --- /dev/null +++ b/src/orcapod/core/streams/record_batch_input.py @@ -0,0 +1,287 @@ +"""The input channel of Arrow record batches (ITL-1347). + +``InputChannel`` implements ``RecordBatchInput`` +(``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. + +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.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.""" + ... + + @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. + + 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 + ``channel_to_stream`` makes of what it delivered). + + 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 + # 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 + # 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: + """The stream whose rows this channel delivers: the description.""" + return self._stream + + @property + def unread(self) -> bool: + """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 + 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, 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; or + if ``claim`` is not this channel's claim. + ChannelClosed: If it was closed. + """ + if self._closed: + raise self._closed_early() + 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() + 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( + 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. + + 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. A ``ChannelClosed`` raised by the + feed's own read is a read error too: only the feed's end ends it. + 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() # 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 " + + "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 + 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 + + 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: + # 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.""" + 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 close(self) -> None: + """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() + + +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) + return repr(label) if label else repr(stream) 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 010d29232..ec42f4c7e 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -183,6 +183,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 (``channel_to_stream`` makes a stream of + what a channel delivers). + + Returns: + The input channel. + """ + ... + def async_iter_data(self) -> AsyncIterator[tuple[TagProtocol, DataProtocol]]: """ Generates asynchronous iterator over (tag, data) pairs in the stream. @@ -568,3 +581,92 @@ 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.""" + ... + + @property + def unread(self) -> bool: + """Whether no read was called and the channel is not closed. + + A reserved channel (``reserve()``) is not unread, even before its first read. + """ + ... + + @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, claim: object | None = None) -> object: + """Take the channel for one consumer that will read all of it. + + 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 + claim. + ChannelClosed: If it was closed. + """ + ... + + 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 4c03cefd3..95821c2cd 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -2,10 +2,10 @@ 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". +(``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 @@ -21,7 +23,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, ) @@ -30,23 +32,32 @@ 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 ( + ROW_BUILT_OUTPUT, StaticOutputOperatorPod, + channel_to_stream, stream_from_batches, transport_schema, ) 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.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} @@ -97,7 +108,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 +117,688 @@ 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 ``channel_to_stream`` rebuilds what the channel delivered, with + the stream's identity.""" 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) + batches = run(stream.open_channel().collect) + assert same(pa.Table.from_batches(batches), R(stream)) + delivered = run(lambda: channel_to_stream(channel)) 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() + with pytest.raises(ChannelClosed): + _ = 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, 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)) + 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) + channel = slot.open_channel() + with pytest.raises(UnboundSourceError): + _ = 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 _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)) + + +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, + 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 + + +@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_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.""" + 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: + """Record the fetch, then fail it as a source whose own input closed.""" + 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.""" + 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 + 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 + return released_while_open + + 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() + 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 == 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 + 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: @@ -131,7 +810,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 +821,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 +839,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 +847,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() @@ -177,8 +856,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) @@ -189,8 +869,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) @@ -230,7 +910,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) @@ -240,7 +920,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) @@ -253,7 +933,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) @@ -263,7 +943,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) @@ -505,17 +1185,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() @@ -768,13 +1452,18 @@ 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: + """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() + + # 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] @@ -904,24 +1593,30 @@ 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: + """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()) + + 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), ) @@ -996,9 +1691,18 @@ 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()) - whole = asyncio.ensure_future(barrier.to_stream()) + first_read = asyncio.Event() + + async def waiting_consumer() -> Any: + """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() + + 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) output.fail(RuntimeError("a second failure changes nothing")) @@ -1033,7 +1737,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 @@ -1044,7 +1748,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 +1778,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,15 +1838,15 @@ 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))) 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 c47c11a3c..568b44975 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,19 +27,22 @@ 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 ( 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.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 ( @@ -83,11 +86,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 +266,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 @@ -279,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 @@ -321,15 +328,17 @@ 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]) - 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) @@ -386,28 +395,28 @@ def _outcome(make: Callable[[], StreamProtocol]) -> tuple[str, Any]: 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 + ``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() - 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 - 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])) - == 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 +528,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 +558,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,9 +679,10 @@ 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) + async with asyncio.timeout(TIMEOUT): + _ = await results.collect() asyncio.run(go()) @@ -684,7 +694,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") @@ -729,3 +739,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()) + )